Datasets:
AI4M
/

text
stringlengths
0
3.34M
proposition contour_integral_uniform_limit: assumes ev_fint: "eventually (\<lambda>n::'a. (f n) contour_integrable_on \<gamma>) F" and ul_f: "uniform_limit (path_image \<gamma>) f l F" and noleB: "\<And>t. t \<in> {0..1} \<Longrightarrow> norm (vector_derivative \<gamma> (at t)) \<le> B" and \<gamma>: "valid_path \<gamma>" and [simp]: "\<not> trivial_limit F" shows "l contour_integrable_on \<gamma>" "((\<lambda>n. contour_integral \<gamma> (f n)) \<longlongrightarrow> contour_integral \<gamma> l) F"
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import order.conditionally_complete_lattice import algebra.big_operators.basic import algebra.group.prod import algebra.group.pi import algebra.module.pi /-! # Support of a function In this file we define `function.support f = {x | f x ≠ 0}` and prove its basic properties. We also define `function.mul_support f = {x | f x ≠ 1}`. -/ open set open_locale big_operators namespace function variables {α β A B M N P R S G M₀ G₀ : Type*} {ι : Sort*} section has_one variables [has_one M] [has_one N] [has_one P] /-- `support` of a function is the set of points `x` such that `f x ≠ 0`. -/ def support [has_zero A] (f : α → A) : set α := {x | f x ≠ 0} /-- `mul_support` of a function is the set of points `x` such that `f x ≠ 1`. -/ @[to_additive] def mul_support (f : α → M) : set α := {x | f x ≠ 1} @[to_additive] lemma mul_support_eq_preimage (f : α → M) : mul_support f = f ⁻¹' {1}ᶜ := rfl @[to_additive] lemma nmem_mul_support {f : α → M} {x : α} : x ∉ mul_support f ↔ f x = 1 := not_not @[to_additive] lemma compl_mul_support {f : α → M} : (mul_support f)ᶜ = {x | f x = 1} := ext $ λ x, nmem_mul_support @[simp, to_additive] lemma mem_mul_support {f : α → M} {x : α} : x ∈ mul_support f ↔ f x ≠ 1 := iff.rfl @[simp, to_additive] lemma mul_support_subset_iff {f : α → M} {s : set α} : mul_support f ⊆ s ↔ ∀ x, f x ≠ 1 → x ∈ s := iff.rfl @[to_additive] lemma mul_support_subset_iff' {f : α → M} {s : set α} : mul_support f ⊆ s ↔ ∀ x ∉ s, f x = 1 := forall_congr $ λ x, not_imp_comm @[to_additive] lemma mul_support_disjoint_iff {f : α → M} {s : set α} : disjoint (mul_support f) s ↔ eq_on f 1 s := by simp_rw [disjoint_iff_subset_compl_right, mul_support_subset_iff', not_mem_compl_iff, eq_on, pi.one_apply] @[to_additive] lemma disjoint_mul_support_iff {f : α → M} {s : set α} : disjoint s (mul_support f) ↔ eq_on f 1 s := by rw [disjoint.comm, mul_support_disjoint_iff] @[simp, to_additive] lemma mul_support_eq_empty_iff {f : α → M} : mul_support f = ∅ ↔ f = 1 := by { simp_rw [← subset_empty_iff, mul_support_subset_iff', funext_iff], simp } @[simp, to_additive] lemma mul_support_nonempty_iff {f : α → M} : (mul_support f).nonempty ↔ f ≠ 1 := by rw [← ne_empty_iff_nonempty, ne.def, mul_support_eq_empty_iff] @[simp, to_additive] lemma mul_support_one' : mul_support (1 : α → M) = ∅ := mul_support_eq_empty_iff.2 rfl @[simp, to_additive] lemma mul_support_one : mul_support (λ x : α, (1 : M)) = ∅ := mul_support_one' @[to_additive] @[to_additive] lemma mul_support_binop_subset (op : M → N → P) (op1 : op 1 1 = 1) (f : α → M) (g : α → N) : mul_support (λ x, op (f x) (g x)) ⊆ mul_support f ∪ mul_support g := λ x hx, classical.by_cases (λ hf : f x = 1, or.inr $ λ hg, hx $ by simp only [hf, hg, op1]) or.inl @[to_additive] lemma mul_support_sup [semilattice_sup M] (f g : α → M) : mul_support (λ x, f x ⊔ g x) ⊆ mul_support f ∪ mul_support g := mul_support_binop_subset (⊔) sup_idem f g @[to_additive] lemma mul_support_inf [semilattice_inf M] (f g : α → M) : mul_support (λ x, f x ⊓ g x) ⊆ mul_support f ∪ mul_support g := mul_support_binop_subset (⊓) inf_idem f g @[to_additive] lemma mul_support_max [linear_order M] (f g : α → M) : mul_support (λ x, max (f x) (g x)) ⊆ mul_support f ∪ mul_support g := mul_support_sup f g @[to_additive] lemma mul_support_min [linear_order M] (f g : α → M) : mul_support (λ x, min (f x) (g x)) ⊆ mul_support f ∪ mul_support g := mul_support_inf f g @[to_additive] lemma mul_support_supr [conditionally_complete_lattice M] [nonempty ι] (f : ι → α → M) : mul_support (λ x, ⨆ i, f i x) ⊆ ⋃ i, mul_support (f i) := begin rw mul_support_subset_iff', simp only [mem_Union, not_exists, nmem_mul_support], intros x hx, simp only [hx, csupr_const] end @[to_additive] lemma mul_support_infi [conditionally_complete_lattice M] [nonempty ι] (f : ι → α → M) : mul_support (λ x, ⨅ i, f i x) ⊆ ⋃ i, mul_support (f i) := @mul_support_supr _ (order_dual M) ι ⟨(1:M)⟩ _ _ f @[to_additive] lemma mul_support_comp_subset {g : M → N} (hg : g 1 = 1) (f : α → M) : mul_support (g ∘ f) ⊆ mul_support f := λ x, mt $ λ h, by simp only [(∘), *] @[to_additive] lemma mul_support_subset_comp {g : M → N} (hg : ∀ {x}, g x = 1 → x = 1) (f : α → M) : mul_support f ⊆ mul_support (g ∘ f) := λ x, mt hg @[to_additive] lemma mul_support_comp_eq (g : M → N) (hg : ∀ {x}, g x = 1 ↔ x = 1) (f : α → M) : mul_support (g ∘ f) = mul_support f := set.ext $ λ x, not_congr hg @[to_additive] lemma mul_support_comp_eq_preimage (g : β → M) (f : α → β) : mul_support (g ∘ f) = f ⁻¹' mul_support g := rfl @[to_additive support_prod_mk] lemma mul_support_prod_mk (f : α → M) (g : α → N) : mul_support (λ x, (f x, g x)) = mul_support f ∪ mul_support g := set.ext $ λ x, by simp only [mul_support, not_and_distrib, mem_union_eq, mem_set_of_eq, prod.mk_eq_one, ne.def] @[to_additive support_prod_mk'] lemma mul_support_prod_mk' (f : α → M × N) : mul_support f = mul_support (λ x, (f x).1) ∪ mul_support (λ x, (f x).2) := by simp only [← mul_support_prod_mk, prod.mk.eta] @[to_additive] lemma mul_support_along_fiber_subset (f : α × β → M) (a : α) : mul_support (λ b, f (a, b)) ⊆ (mul_support f).image prod.snd := by tidy @[simp, to_additive] lemma mul_support_along_fiber_finite_of_finite (f : α × β → M) (a : α) (h : (mul_support f).finite) : (mul_support (λ b, f (a, b))).finite := (h.image prod.snd).subset (mul_support_along_fiber_subset f a) end has_one @[to_additive] lemma mul_support_mul [mul_one_class M] (f g : α → M) : mul_support (λ x, f x * g x) ⊆ mul_support f ∪ mul_support g := mul_support_binop_subset (*) (one_mul _) f g @[to_additive] lemma mul_support_pow [monoid M] (f : α → M) (n : ℕ) : mul_support (λ x, f x ^ n) ⊆ mul_support f := begin induction n with n hfn, { simpa only [pow_zero, mul_support_one] using empty_subset _ }, { simpa only [pow_succ] using subset_trans (mul_support_mul f _) (union_subset (subset.refl _) hfn) } end @[simp, to_additive] lemma mul_support_inv [group G] (f : α → G) : mul_support (λ x, (f x)⁻¹) = mul_support f := set.ext $ λ x, not_congr inv_eq_one @[simp, to_additive] lemma mul_support_inv' [group G] (f : α → G) : mul_support (f⁻¹) = mul_support f := mul_support_inv f @[simp] lemma mul_support_inv₀ [group_with_zero G₀] (f : α → G₀) : mul_support (λ x, (f x)⁻¹) = mul_support f := set.ext $ λ x, not_congr inv_eq_one₀ @[to_additive] lemma mul_support_mul_inv [group G] (f g : α → G) : mul_support (λ x, f x * (g x)⁻¹) ⊆ mul_support f ∪ mul_support g := mul_support_binop_subset (λ a b, a * b⁻¹) (by simp) f g @[to_additive support_sub] lemma mul_support_group_div [group G] (f g : α → G) : mul_support (λ x, f x / g x) ⊆ mul_support f ∪ mul_support g := mul_support_binop_subset (/) (by simp only [one_div, one_inv]) f g lemma mul_support_div [group_with_zero G₀] (f g : α → G₀) : mul_support (λ x, f x / g x) ⊆ mul_support f ∪ mul_support g := mul_support_binop_subset (/) (by simp only [div_one]) f g @[simp] lemma support_mul [mul_zero_class R] [no_zero_divisors R] (f g : α → R) : support (λ x, f x * g x) = support f ∩ support g := set.ext $ λ x, by simp only [mem_support, mul_ne_zero_iff, mem_inter_eq, not_or_distrib] @[simp] lemma support_mul_subset_left [mul_zero_class R] (f g : α → R) : support (λ x, f x * g x) ⊆ support f := λ x hfg hf, hfg $ by simp only [hf, zero_mul] @[simp] lemma support_mul_subset_right [mul_zero_class R] (f g : α → R) : support (λ x, f x * g x) ⊆ support g := λ x hfg hg, hfg $ by simp only [hg, mul_zero] lemma support_smul_subset_right [add_monoid A] [monoid B] [distrib_mul_action B A] (b : B) (f : α → A) : support (b • f) ⊆ support f := λ x hbf hf, hbf $ by rw [pi.smul_apply, hf, smul_zero] lemma support_smul_subset_left [semiring R] [add_comm_monoid M] [module R M] (f : α → R) (g : α → M) : support (f • g) ⊆ support f := λ x hfg hf, hfg $ by rw [pi.smul_apply', hf, zero_smul] lemma support_smul [semiring R] [add_comm_monoid M] [module R M] [no_zero_smul_divisors R M] (f : α → R) (g : α → M) : support (f • g) = support f ∩ support g := ext $ λ x, smul_ne_zero lemma support_const_smul_of_ne_zero [semiring R] [add_comm_monoid M] [module R M] [no_zero_smul_divisors R M] (c : R) (g : α → M) (hc : c ≠ 0) : support (c • g) = support g := ext $ λ x, by simp only [hc, mem_support, pi.smul_apply, ne.def, smul_eq_zero, false_or] @[simp] lemma support_inv [group_with_zero G₀] (f : α → G₀) : support (λ x, (f x)⁻¹) = support f := set.ext $ λ x, not_congr inv_eq_zero @[simp] lemma support_div [group_with_zero G₀] (f g : α → G₀) : support (λ x, f x / g x) = support f ∩ support g := by simp [div_eq_mul_inv] @[to_additive] lemma mul_support_prod [comm_monoid M] (s : finset α) (f : α → β → M) : mul_support (λ x, ∏ i in s, f i x) ⊆ ⋃ i ∈ s, mul_support (f i) := begin rw mul_support_subset_iff', simp only [mem_Union, not_exists, nmem_mul_support], exact λ x, finset.prod_eq_one end lemma support_prod_subset [comm_monoid_with_zero A] (s : finset α) (f : α → β → A) : support (λ x, ∏ i in s, f i x) ⊆ ⋂ i ∈ s, support (f i) := λ x hx, mem_Inter₂.2 $ λ i hi H, hx $ finset.prod_eq_zero hi H lemma support_prod [comm_monoid_with_zero A] [no_zero_divisors A] [nontrivial A] (s : finset α) (f : α → β → A) : support (λ x, ∏ i in s, f i x) = ⋂ i ∈ s, support (f i) := set.ext $ λ x, by simp only [support, ne.def, finset.prod_eq_zero_iff, mem_set_of_eq, set.mem_Inter, not_exists] lemma mul_support_one_add [has_one R] [add_left_cancel_monoid R] (f : α → R) : mul_support (λ x, 1 + f x) = support f := set.ext $ λ x, not_congr add_right_eq_self lemma mul_support_one_add' [has_one R] [add_left_cancel_monoid R] (f : α → R) : mul_support (1 + f) = support f := mul_support_one_add f lemma mul_support_add_one [has_one R] [add_right_cancel_monoid R] (f : α → R) : mul_support (λ x, f x + 1) = support f := set.ext $ λ x, not_congr add_left_eq_self lemma mul_support_add_one' [has_one R] [add_right_cancel_monoid R] (f : α → R) : mul_support (f + 1) = support f := mul_support_add_one f lemma mul_support_one_sub' [has_one R] [add_group R] (f : α → R) : mul_support (1 - f) = support f := by rw [sub_eq_add_neg, mul_support_one_add', support_neg'] lemma mul_support_one_sub [has_one R] [add_group R] (f : α → R) : mul_support (λ x, 1 - f x) = support f := mul_support_one_sub' f end function namespace set open function variables {α β M : Type*} [has_one M] {f : α → M} @[to_additive] lemma image_inter_mul_support_eq {s : set β} {g : β → α} : (g '' s ∩ mul_support f) = g '' (s ∩ mul_support (f ∘ g)) := by rw [mul_support_comp_eq_preimage f g, image_inter_preimage] end set namespace pi variables {A : Type*} {B : Type*} [decidable_eq A] [has_zero B] {a : A} {b : B} lemma support_single_zero : function.support (pi.single a (0 : B)) = ∅ := by simp @[simp] lemma support_single_of_ne (h : b ≠ 0) : function.support (pi.single a b) = {a} := begin ext, simp only [mem_singleton_iff, ne.def, function.mem_support], split, { contrapose!, exact λ h', single_eq_of_ne h' b }, { rintro rfl, rw single_eq_same, exact h } end lemma support_single [decidable_eq B] : function.support (pi.single a b) = if b = 0 then ∅ else {a} := by { split_ifs with h; simp [h] } lemma support_single_subset : function.support (pi.single a b) ⊆ {a} := begin classical, rw support_single, split_ifs; simp end lemma support_single_disjoint {b' : B} (hb : b ≠ 0) (hb' : b' ≠ 0) {i j : A} : disjoint (function.support (single i b)) (function.support (single j b')) ↔ i ≠ j := by rw [support_single_of_ne hb, support_single_of_ne hb', disjoint_singleton] end pi
[GOAL] 𝕜 : Type u_1 inst✝⁷ : NontriviallyNormedField 𝕜 H : Type u_2 inst✝⁶ : TopologicalSpace H E : Type u_3 inst✝⁵ : NormedAddCommGroup E inst✝⁴ : NormedSpace 𝕜 E I : ModelWithCorners 𝕜 E H R : Type u_4 inst✝³ : Ring R inst✝² : TopologicalSpace R inst✝¹ : ChartedSpace H R inst✝ : SmoothRing I R ⊢ Smooth I I fun a => -a [PROOFSTEP] simpa only [neg_one_mul] using @smooth_mul_left 𝕜 _ H _ E _ _ I R _ _ _ _ (-1) [GOAL] 𝕜 : Type u_1 inst✝ : NontriviallyNormedField 𝕜 src✝ : LieAddGroup 𝓘(𝕜, 𝕜) 𝕜 := normedSpaceLieAddGroup ⊢ Smooth (ModelWithCorners.prod 𝓘(𝕜, 𝕜) 𝓘(𝕜, 𝕜)) 𝓘(𝕜, 𝕜) fun p => p.fst * p.snd [PROOFSTEP] rw [smooth_iff] [GOAL] 𝕜 : Type u_1 inst✝ : NontriviallyNormedField 𝕜 src✝ : LieAddGroup 𝓘(𝕜, 𝕜) 𝕜 := normedSpaceLieAddGroup ⊢ (Continuous fun p => p.fst * p.snd) ∧ ∀ (x : 𝕜 × 𝕜) (y : 𝕜), ContDiffOn 𝕜 ⊤ (↑(extChartAt 𝓘(𝕜, 𝕜) y) ∘ (fun p => p.fst * p.snd) ∘ ↑(LocalEquiv.symm (extChartAt (ModelWithCorners.prod 𝓘(𝕜, 𝕜) 𝓘(𝕜, 𝕜)) x))) ((extChartAt (ModelWithCorners.prod 𝓘(𝕜, 𝕜) 𝓘(𝕜, 𝕜)) x).target ∩ ↑(LocalEquiv.symm (extChartAt (ModelWithCorners.prod 𝓘(𝕜, 𝕜) 𝓘(𝕜, 𝕜)) x)) ⁻¹' ((fun p => p.fst * p.snd) ⁻¹' (extChartAt 𝓘(𝕜, 𝕜) y).source)) [PROOFSTEP] refine' ⟨continuous_mul, fun x y => _⟩ [GOAL] 𝕜 : Type u_1 inst✝ : NontriviallyNormedField 𝕜 src✝ : LieAddGroup 𝓘(𝕜, 𝕜) 𝕜 := normedSpaceLieAddGroup x : 𝕜 × 𝕜 y : 𝕜 ⊢ ContDiffOn 𝕜 ⊤ (↑(extChartAt 𝓘(𝕜, 𝕜) y) ∘ (fun p => p.fst * p.snd) ∘ ↑(LocalEquiv.symm (extChartAt (ModelWithCorners.prod 𝓘(𝕜, 𝕜) 𝓘(𝕜, 𝕜)) x))) ((extChartAt (ModelWithCorners.prod 𝓘(𝕜, 𝕜) 𝓘(𝕜, 𝕜)) x).target ∩ ↑(LocalEquiv.symm (extChartAt (ModelWithCorners.prod 𝓘(𝕜, 𝕜) 𝓘(𝕜, 𝕜)) x)) ⁻¹' ((fun p => p.fst * p.snd) ⁻¹' (extChartAt 𝓘(𝕜, 𝕜) y).source)) [PROOFSTEP] simp only [Prod.mk.eta, mfld_simps] [GOAL] 𝕜 : Type u_1 inst✝ : NontriviallyNormedField 𝕜 src✝ : LieAddGroup 𝓘(𝕜, 𝕜) 𝕜 := normedSpaceLieAddGroup x : 𝕜 × 𝕜 y : 𝕜 ⊢ ContDiffOn 𝕜 ⊤ (fun p => p.fst * p.snd) Set.univ [PROOFSTEP] rw [contDiffOn_univ] [GOAL] 𝕜 : Type u_1 inst✝ : NontriviallyNormedField 𝕜 src✝ : LieAddGroup 𝓘(𝕜, 𝕜) 𝕜 := normedSpaceLieAddGroup x : 𝕜 × 𝕜 y : 𝕜 ⊢ ContDiff 𝕜 ⊤ fun p => p.fst * p.snd [PROOFSTEP] exact contDiff_mul
------------------------------------------------------------------------ -- The Agda standard library -- -- A universe which includes several kinds of "relatedness" for sets, -- such as equivalences, surjections and bijections ------------------------------------------------------------------------ module Function.Related where open import Level open import Function open import Function.Equality using (_⟨$⟩_) open import Function.Equivalence as Eq using (Equivalence) open import Function.Injection as Inj using (Injection; _↣_) open import Function.Inverse as Inv using (Inverse; _↔_) open import Function.LeftInverse as LeftInv using (LeftInverse) open import Function.Surjection as Surj using (Surjection) open import Relation.Binary open import Relation.Binary.PropositionalEquality as P using (_≡_) ------------------------------------------------------------------------ -- Wrapper types -- Synonyms which are used to make _∼[_]_ below "constructor-headed" -- (which implies that Agda can deduce the universe code from an -- expression matching any of the right-hand sides). record _←_ {a b} (A : Set a) (B : Set b) : Set (a ⊔ b) where constructor lam field app-← : B → A open _←_ public record _↢_ {a b} (A : Set a) (B : Set b) : Set (a ⊔ b) where constructor lam field app-↢ : B ↣ A open _↢_ public ------------------------------------------------------------------------ -- Relatedness -- There are several kinds of "relatedness". -- The idea to include kinds other than equivalence and bijection came -- from Simon Thompson and Bengt Nordström. /NAD data Kind : Set where implication reverse-implication equivalence injection reverse-injection left-inverse surjection bijection : Kind -- Interpretation of the codes above. The code "bijection" is -- interpreted as Inverse rather than Bijection; the two types are -- equivalent. infix 4 _∼[_]_ _∼[_]_ : ∀ {ℓ₁ ℓ₂} → Set ℓ₁ → Kind → Set ℓ₂ → Set _ A ∼[ implication ] B = A → B A ∼[ reverse-implication ] B = A ← B A ∼[ equivalence ] B = Equivalence (P.setoid A) (P.setoid B) A ∼[ injection ] B = Injection (P.setoid A) (P.setoid B) A ∼[ reverse-injection ] B = A ↢ B A ∼[ left-inverse ] B = LeftInverse (P.setoid A) (P.setoid B) A ∼[ surjection ] B = Surjection (P.setoid A) (P.setoid B) A ∼[ bijection ] B = Inverse (P.setoid A) (P.setoid B) -- A non-infix synonym. Related : Kind → ∀ {ℓ₁ ℓ₂} → Set ℓ₁ → Set ℓ₂ → Set _ Related k A B = A ∼[ k ] B -- The bijective equality implies any kind of relatedness. ↔⇒ : ∀ {k x y} {X : Set x} {Y : Set y} → X ∼[ bijection ] Y → X ∼[ k ] Y ↔⇒ {implication} = _⟨$⟩_ ∘ Inverse.to ↔⇒ {reverse-implication} = lam ∘′ _⟨$⟩_ ∘ Inverse.from ↔⇒ {equivalence} = Inverse.equivalence ↔⇒ {injection} = Inverse.injection ↔⇒ {reverse-injection} = lam ∘′ Inverse.injection ∘ Inv.sym ↔⇒ {left-inverse} = Inverse.left-inverse ↔⇒ {surjection} = Inverse.surjection ↔⇒ {bijection} = id -- Actual equality also implies any kind of relatedness. ≡⇒ : ∀ {k ℓ} {X Y : Set ℓ} → X ≡ Y → X ∼[ k ] Y ≡⇒ P.refl = ↔⇒ Inv.id ------------------------------------------------------------------------ -- Special kinds of kinds -- Kinds whose interpretation is symmetric. data Symmetric-kind : Set where equivalence bijection : Symmetric-kind -- Forgetful map. ⌊_⌋ : Symmetric-kind → Kind ⌊ equivalence ⌋ = equivalence ⌊ bijection ⌋ = bijection -- The proof of symmetry can be found below. -- Kinds whose interpretation include a function which "goes in the -- forward direction". data Forward-kind : Set where implication equivalence injection left-inverse surjection bijection : Forward-kind -- Forgetful map. ⌊_⌋→ : Forward-kind → Kind ⌊ implication ⌋→ = implication ⌊ equivalence ⌋→ = equivalence ⌊ injection ⌋→ = injection ⌊ left-inverse ⌋→ = left-inverse ⌊ surjection ⌋→ = surjection ⌊ bijection ⌋→ = bijection -- The function. ⇒→ : ∀ {k x y} {X : Set x} {Y : Set y} → X ∼[ ⌊ k ⌋→ ] Y → X → Y ⇒→ {implication} = id ⇒→ {equivalence} = _⟨$⟩_ ∘ Equivalence.to ⇒→ {injection} = _⟨$⟩_ ∘ Injection.to ⇒→ {left-inverse} = _⟨$⟩_ ∘ LeftInverse.to ⇒→ {surjection} = _⟨$⟩_ ∘ Surjection.to ⇒→ {bijection} = _⟨$⟩_ ∘ Inverse.to -- Kinds whose interpretation include a function which "goes backwards". data Backward-kind : Set where reverse-implication equivalence reverse-injection left-inverse surjection bijection : Backward-kind -- Forgetful map. ⌊_⌋← : Backward-kind → Kind ⌊ reverse-implication ⌋← = reverse-implication ⌊ equivalence ⌋← = equivalence ⌊ reverse-injection ⌋← = reverse-injection ⌊ left-inverse ⌋← = left-inverse ⌊ surjection ⌋← = surjection ⌊ bijection ⌋← = bijection -- The function. ⇒← : ∀ {k x y} {X : Set x} {Y : Set y} → X ∼[ ⌊ k ⌋← ] Y → Y → X ⇒← {reverse-implication} = app-← ⇒← {equivalence} = _⟨$⟩_ ∘ Equivalence.from ⇒← {reverse-injection} = _⟨$⟩_ ∘ Injection.to ∘ app-↢ ⇒← {left-inverse} = _⟨$⟩_ ∘ LeftInverse.from ⇒← {surjection} = _⟨$⟩_ ∘ Surjection.from ⇒← {bijection} = _⟨$⟩_ ∘ Inverse.from -- Kinds whose interpretation include functions going in both -- directions. data Equivalence-kind : Set where equivalence left-inverse surjection bijection : Equivalence-kind -- Forgetful map. ⌊_⌋⇔ : Equivalence-kind → Kind ⌊ equivalence ⌋⇔ = equivalence ⌊ left-inverse ⌋⇔ = left-inverse ⌊ surjection ⌋⇔ = surjection ⌊ bijection ⌋⇔ = bijection -- The functions. ⇒⇔ : ∀ {k x y} {X : Set x} {Y : Set y} → X ∼[ ⌊ k ⌋⇔ ] Y → X ∼[ equivalence ] Y ⇒⇔ {equivalence} = id ⇒⇔ {left-inverse} = LeftInverse.equivalence ⇒⇔ {surjection} = Surjection.equivalence ⇒⇔ {bijection} = Inverse.equivalence -- Conversions between special kinds. ⇔⌊_⌋ : Symmetric-kind → Equivalence-kind ⇔⌊ equivalence ⌋ = equivalence ⇔⌊ bijection ⌋ = bijection →⌊_⌋ : Equivalence-kind → Forward-kind →⌊ equivalence ⌋ = equivalence →⌊ left-inverse ⌋ = left-inverse →⌊ surjection ⌋ = surjection →⌊ bijection ⌋ = bijection ←⌊_⌋ : Equivalence-kind → Backward-kind ←⌊ equivalence ⌋ = equivalence ←⌊ left-inverse ⌋ = left-inverse ←⌊ surjection ⌋ = surjection ←⌊ bijection ⌋ = bijection ------------------------------------------------------------------------ -- Opposites -- For every kind there is an opposite kind. _op : Kind → Kind implication op = reverse-implication reverse-implication op = implication equivalence op = equivalence injection op = reverse-injection reverse-injection op = injection left-inverse op = surjection surjection op = left-inverse bijection op = bijection -- For every morphism there is a corresponding reverse morphism of the -- opposite kind. reverse : ∀ {k a b} {A : Set a} {B : Set b} → A ∼[ k ] B → B ∼[ k op ] A reverse {implication} = lam reverse {reverse-implication} = app-← reverse {equivalence} = Eq.sym reverse {injection} = lam reverse {reverse-injection} = app-↢ reverse {left-inverse} = Surj.fromRightInverse reverse {surjection} = Surjection.right-inverse reverse {bijection} = Inv.sym ------------------------------------------------------------------------ -- Equational reasoning -- Equational reasoning for related things. module EquationalReasoning where private refl : ∀ {k ℓ} → Reflexive (Related k {ℓ}) refl {implication} = id refl {reverse-implication} = lam id refl {equivalence} = Eq.id refl {injection} = Inj.id refl {reverse-injection} = lam Inj.id refl {left-inverse} = LeftInv.id refl {surjection} = Surj.id refl {bijection} = Inv.id trans : ∀ {k ℓ₁ ℓ₂ ℓ₃} → Trans (Related k {ℓ₁} {ℓ₂}) (Related k {ℓ₂} {ℓ₃}) (Related k {ℓ₁} {ℓ₃}) trans {implication} = flip _∘′_ trans {reverse-implication} = λ f g → lam (app-← f ∘ app-← g) trans {equivalence} = flip Eq._∘_ trans {injection} = flip Inj._∘_ trans {reverse-injection} = λ f g → lam (Inj._∘_ (app-↢ f) (app-↢ g)) trans {left-inverse} = flip LeftInv._∘_ trans {surjection} = flip Surj._∘_ trans {bijection} = flip Inv._∘_ sym : ∀ {k ℓ₁ ℓ₂} → Sym (Related ⌊ k ⌋ {ℓ₁} {ℓ₂}) (Related ⌊ k ⌋ {ℓ₂} {ℓ₁}) sym {equivalence} = Eq.sym sym {bijection} = Inv.sym infix 2 _∎ infixr 2 _∼⟨_⟩_ _↔⟨_⟩_ _↔⟨⟩_ _≡⟨_⟩_ _∼⟨_⟩_ : ∀ {k x y z} (X : Set x) {Y : Set y} {Z : Set z} → X ∼[ k ] Y → Y ∼[ k ] Z → X ∼[ k ] Z _ ∼⟨ X↝Y ⟩ Y↝Z = trans X↝Y Y↝Z -- Isomorphisms can be combined with any other kind of relatedness. _↔⟨_⟩_ : ∀ {k x y z} (X : Set x) {Y : Set y} {Z : Set z} → X ↔ Y → Y ∼[ k ] Z → X ∼[ k ] Z X ↔⟨ X↔Y ⟩ Y⇔Z = X ∼⟨ ↔⇒ X↔Y ⟩ Y⇔Z _↔⟨⟩_ : ∀ {k x y} (X : Set x) {Y : Set y} → X ∼[ k ] Y → X ∼[ k ] Y X ↔⟨⟩ X⇔Y = X⇔Y _≡⟨_⟩_ : ∀ {k ℓ z} (X : Set ℓ) {Y : Set ℓ} {Z : Set z} → X ≡ Y → Y ∼[ k ] Z → X ∼[ k ] Z X ≡⟨ X≡Y ⟩ Y⇔Z = X ∼⟨ ≡⇒ X≡Y ⟩ Y⇔Z _∎ : ∀ {k x} (X : Set x) → X ∼[ k ] X X ∎ = refl -- For a symmetric kind and a fixed universe level we can construct a -- setoid. setoid : Symmetric-kind → (ℓ : Level) → Setoid _ _ setoid k ℓ = record { Carrier = Set ℓ ; _≈_ = Related ⌊ k ⌋ ; isEquivalence = record {refl = _ ∎; sym = sym; trans = _∼⟨_⟩_ _} } where open EquationalReasoning -- For an arbitrary kind and a fixed universe level we can construct a -- preorder. preorder : Kind → (ℓ : Level) → Preorder _ _ _ preorder k ℓ = record { Carrier = Set ℓ ; _≈_ = _↔_ ; _∼_ = Related k ; isPreorder = record { isEquivalence = Setoid.isEquivalence (setoid bijection ℓ) ; reflexive = ↔⇒ ; trans = _∼⟨_⟩_ _ } } where open EquationalReasoning ------------------------------------------------------------------------ -- Some induced relations -- Every unary relation induces a preorder and, for symmetric kinds, -- an equivalence. (No claim is made that these relations are unique.) InducedRelation₁ : Kind → ∀ {a s} {A : Set a} → (A → Set s) → A → A → Set _ InducedRelation₁ k S = λ x y → S x ∼[ k ] S y InducedPreorder₁ : Kind → ∀ {a s} {A : Set a} → (A → Set s) → Preorder _ _ _ InducedPreorder₁ k S = record { _≈_ = P._≡_ ; _∼_ = InducedRelation₁ k S ; isPreorder = record { isEquivalence = P.isEquivalence ; reflexive = reflexive ∘ Setoid.reflexive (setoid bijection _) ∘ P.cong S ; trans = trans } } where open Preorder (preorder _ _) InducedEquivalence₁ : Symmetric-kind → ∀ {a s} {A : Set a} → (A → Set s) → Setoid _ _ InducedEquivalence₁ k S = record { _≈_ = InducedRelation₁ ⌊ k ⌋ S ; isEquivalence = record {refl = refl; sym = sym; trans = trans} } where open Setoid (setoid _ _) -- Every binary relation induces a preorder and, for symmetric kinds, -- an equivalence. (No claim is made that these relations are unique.) InducedRelation₂ : Kind → ∀ {a b s} {A : Set a} {B : Set b} → (A → B → Set s) → B → B → Set _ InducedRelation₂ k _S_ = λ x y → ∀ {z} → (z S x) ∼[ k ] (z S y) InducedPreorder₂ : Kind → ∀ {a b s} {A : Set a} {B : Set b} → (A → B → Set s) → Preorder _ _ _ InducedPreorder₂ k _S_ = record { _≈_ = P._≡_ ; _∼_ = InducedRelation₂ k _S_ ; isPreorder = record { isEquivalence = P.isEquivalence ; reflexive = λ x≡y {z} → reflexive $ Setoid.reflexive (setoid bijection _) $ P.cong (_S_ z) x≡y ; trans = λ i↝j j↝k → trans i↝j j↝k } } where open Preorder (preorder _ _) InducedEquivalence₂ : Symmetric-kind → ∀ {a b s} {A : Set a} {B : Set b} → (A → B → Set s) → Setoid _ _ InducedEquivalence₂ k _S_ = record { _≈_ = InducedRelation₂ ⌊ k ⌋ _S_ ; isEquivalence = record { refl = refl ; sym = λ i↝j → sym i↝j ; trans = λ i↝j j↝k → trans i↝j j↝k } } where open Setoid (setoid _ _)
function pathStr = dataDir(vw, ~) % Directory containing data for a given dataTYPE % % pathStr = dataDir(view) % % If you're nice and neat e.g., if you're in an inplane view and looking at % average tSeries, the dataDir would be HOMEDIR/Inplane/Averages/ % % If this directory doesn't exist, make it! % % djh, 2/2001 global HOMEDIR if isempty(HOMEDIR), HOMEDIR = pwd; end dir = viewGet(vw,'subdir'); dt = viewGet(vw,'dtStruct'); subDir = dtGet(dt,'Name'); pathStr = fullfile(HOMEDIR,dir,subDir); if ~exist(pathStr,'dir') pathStr; subDir; mkdir(dir,subDir); end return;
##hp ##05.31.2016 setwd('B:/') source('fcns/config.r') source('fcns/my_heat_pwys.r') setwd('kahn/emrah/emrah_stoolProteomics/host') source('../../my_barplot.r') library('plyr') ##Parse data dat <- read.csv('150427KEASAM00828_MUSTMT10PLX-FTK2_UNiprotMouse_Annotation_128Cnormaliza....csv') dat <- dat[dat$Protein.FDR.Confidence %in% c('High', 'Medium', 'Low') & dat$Contaminant == FALSE, ] rownames(dat) <- dat$Accession rownames(dat) <- gsub('-.*', '', rownames(dat)) pheno <- data.frame(Group = c(rep('Chow', 3), rep('HFD', 3), rep('Vanc', 2), rep('Metr', 2)), Replicate = c(1:3, 1:3, 1:2, 1:2), Label = c('126', '127C', '127N', '128N', '129C', '128C', '129N', '130C', '130N', '131')) rownames(pheno) <- paste(pheno$Group, pheno$Replicate, sep = '.') annot <- dat[, c('Accession', 'Gene.ID', 'Description')] annot$Gene.ID[annot$Gene.ID == ''] <- annot$Accession[annot$Gene.ID == ''] dat.tissue <- read.csv("B:/Annotations/encode_mouse_19_tissues_expr/mouse_tissue_expr.csv", row.names = 1) annot <- cbind(annot, dat.tissue[match(annot$Gene.ID, dat.tissue$Symbol), paste0("Tissue.", 1:3)]) mf <- read.csv("B:/Annotations/msigdb/msigdb_mf_table.csv", row.names = 1) annot$Molecular.Function <- mf[toupper(annot$Gene.ID), ] signalIP <- read.delim("B:/Annotations/protein_secretion/hpa_protein-class_SignalPPredictedSecreted.tab") signalIP <- signalIP[grep('Predicted secreted proteins', signalIP$Protein.class), ] annot$SignalPPredictedSecreted <- toupper(annot$Gene.ID) %in% signalIP$Gene annot$SignalPPredictedSecreted[grep(';', annot$Gene.ID)] <- NA mat <- data.matrix(dat[, grep('Abundance..F1', colnames(dat))]) colnames(mat) <- gsub('.*F1\\.\\.|\\.\\.(Sam|Con).*', '', colnames(mat)) mat <- mat[, match(pheno$Label, colnames(mat))] colnames(mat) <- rownames(pheno) # filter NAs hist(rowMeans(is.na(mat))) mat <- mat[rowMeans(is.na(mat)) < 0.8, ] sum(is.na(mat)) # normalize to column sum and log transform mat <- log2(apply(mat, 2, function(v) v*max(colSums(mat))/sum(v))) boxplot(mat, las=2) ##Qc multi.pca(mat, pheno, color = 'Group', name = 'stoolproteomics_pca') # see trend, flat voom(2^mat, plot = TRUE) ##Stats contr.v = c(HFDvsChow = 'HFD - Chow', VancvsHFD = 'Vanc - HFD', MetrvsHFD = 'Metr - HFD', MetrvsVanc='Metr - Vanc') mtt <- limma.contrasts(mat, pheno$Group, contr.v) mtt.df <- data.frame(signif(mtt, 3), annot[rownames(mtt), ]) sig.hist(mtt, name = 'stoolproteomics_sig_hist') write.csv(mtt.df, 'stoolproteomics_protein_stats.csv', na = '') ##Plots # volcanoe plots mtt.df.vol <- mtt.df mtt.df.vol$Gene.ID <- gsub(';.*', '', mtt.df.vol$Gene.ID) pdf('stoolproteomics_volcanoes.pdf', 4, 4) multi.volcano(mtt.df.vol, sym.col = 'Gene.ID', n.top = 5, name = NA) dev.off() # heat maps topp1 <- rownames(mtt)[1:50] my.heat(mat[topp1, ], symbols = annot[topp1, 'Gene.ID'], name = 'stoolproteomics_all_group', Colv = FALSE, margins = c(7, 10), labCol = pheno$Group) topp2 <- rownames(mtt)[order(combine.pvalues(mtt[, -grep('Chow', colnames(mtt))]))][1:50] my.heat(mat[topp2, pheno$Group != 'Chow'], symbols = annot[topp2, 'Gene.ID'], name = 'stoolproteomics_no_chow', Colv = FALSE, margins = c(7, 10), labCol = pheno$Group[pheno$Group != 'Chow']) topp3 <- rownames(mtt)[order(combine.pvalues(mtt[, -grep('Vanc|Metr', colnames(mtt))]))][1:50] my.heat(mat[topp3, !pheno$Group %in% c('Vanc', 'Metr')], symbols = annot[topp3, 'Gene.ID'], name = 'stoolproteomics_no_antibiotics', Colv = FALSE, margins = c(7, 10), labCol = pheno$Group[!pheno$Group %in% c('Vanc', 'Metr')]) top4 <- rownames(mtt)[order(mtt$HFDvsChow.p)][1:50] top5 <- rownames(mtt)[order(mtt$VancvsHFD.p)][1:10] top6 <- rownames(mtt)[order(mtt$MetrvsHFD.p)][1:10] topp <- unique(c(top4, top5, top6)) my.heat2(mat[topp, ], symbols = mtt.df.vol[topp, 'Gene.ID'], name = 'stoolproteomics_all_groups_2', Colv = FALSE, labCol = pheno$Group, sc = 'z') # bar plots pdf('stoolproteomics_topprotein_barplots.pdf') for(p in topp1) { dat2p <- data.frame(Protein = 2^(mat[p, ])/mean(2^mat[p, 4:6]), Group = pheno$Group) dat2p <- ddply(dat2p, .(Group), summarise, N = length(Protein), Mean = mean(Protein), SE = sd(Protein)/sqrt(N)) g <- ggplot(dat2p, aes(Group, Mean, fill = Group)) g <- g + geom_bar(stat = 'identity', width = 0.7) + guides(fill=FALSE) g <- g + theme_bw() + geom_errorbar(aes(ymax = Mean + SE, ymin = Mean - SE, width = 0.35)) g <- g + labs(y = 'Relative abundance', title = paste(annot[p, 'Gene.ID'], p, sep = '/')) plot(g) } dev.off() grp <- factor(pheno$Group) levels(grp) <- list(C = "Chow", H = "HFD", M = "Metr", V = "Vanc") pdf("stoolproteomics_topprotein_barplots_2.pdf", 2.5, 3) my.barplot(2^mat/rowMeans(2^mat[, 4:6]), grp, main.v = annot[rownames(mat), "Gene.ID"], fill = c("#CCCCCC","#FF6666", "#6699FF","#66CC66"), xlab = "", ylab="Relative Abundance") dev.off() ##Pwys # pdb.files <- c(c2.kegg = 'c2.cp.kegg.v4.0', c2.reactome = 'c2.cp.reactome.v4.0', c5.cc = 'c5.cc.v5.1') # for (pdb.ind in seq_along(pdb.files)){ # G <- gmtToG(paste0('B:/Annotations/gene_sets/', pdb.files[pdb.ind], '.symbols.gmt')) # G <- processG(G) # G <- my.chip2chip(G = G, annot = annot, split='; ', symbol.col = 'Gene.ID') # sp <- sigpwy.contrasts(G=G, tab=mat, grp=pheno$Group, contrasts.v=contr.v, minNPS=2, # annot=annot[rownames(mat), ], prefix = names(pdb.files)[pdb.ind], # add.comb=FALSE) # write.csv(sp, paste0(names(pdb.files)[pdb.ind], '_pwys.csv'), row.names=FALSE) # } # fry pdb.files <- c(cp = 'c2.cp.v6.0', go = 'c5.all.v6.0') for (i in seq_along(pdb.files)){ G <- gmtToG(paste0('B:/Annotations/gene_sets/', pdb.files[i], '.symbols.gmt')) G <- processG(G) G <- my.chip2chip(G = G, annot = annot, split='; ', symbol.col = 'Gene.ID') pwys <- fry.contrasts(dat=mat, G=G, stats=mtt.df, name=names(pdb.files)[i], grp=pheno$Group, contrasts.v=contr.v, min.ngenes=2) my.heat.pwys(dat=pwys[1:min(50, nrow(pwys)), ], contrast.v=contr.v, p.cutoff=0.05, name=paste0(names(pdb.files)[i], '_pwys'), Colv=FALSE) } ##Check all(rownames(mat)%in% rownames(annot)) all(colnames(mat) == rownames(pheno)) mtt.df[1, 'Accession'] == 'Q7TSG5-2' mtt.df[1, 'HFDvsChow.FC'] < -2.5 mtt.df[which(mtt.df$Gene.ID == 'Scgb1b2'), 'VancvsHFD.logFC'] > 0.5 tapply(mat['Q6DYE8', ], pheno$Group, mean)[c('Chow', 'HFD')] #17.9, 16.9
-- --------------------------------------------------------------- [ Utils.idr ] -- Module : Utils.idr -- Copyright : (c) Jan de Muijnck-Hughes -- License : see LICENSE -- --------------------------------------------------------------------- [ EOH ] module GRL.Lang.Common.Utils import GRL.Common import GRL.Model %access export prettyResult : GoalNode -> String prettyResult g = unwords [ "Result:" , show (fromMaybe NONE (getSValue g)) , "\t<==" , getNodeTitle g] -- --------------------------------------------------------------------- [ EOF ]
flavor 1 srclang 3 id 65535 numfuncs 7 import "InterfaceTest.mplt" import "/home/bravewtz/Desktop/openarkcompiler/libjava-core/libjava-core.mplt" entryfunc &LInterfaceTest_3B_7Cmain_7C_28ALjava_2Flang_2FString_3B_29V fileinfo { @INFO_filename "InterfaceTest.jar"} srcfileinfo { 1 "InterfaceTest.java"} type $__class_meta__ <struct { @shadow <* void> final, @monitor i32 final, @classloader u16 final, @objsize u16 final, @itab <* void> final, @vtab <* void> final, @gctib <* void> final, @classinforo <* void> final, @clinitbridge <* void> final}> type $__class_meta_ro__ <struct { @classname <* void> final, @ifields <* void> final, @methods <* void> final, @superclass_or_componentclass <* void> final, @numoffields u16 final, @numofmethods u16 final, @flag u16 final, @numofsuperclasses u16 final, @padding u32 final, @mod i32 final, @annotation i32 final, @clinitAddr i32 final}> type $__method_info__ <struct { @method_in_vtab_index i64 final, @declaringclass i64 final, @addr i64 final, @mod i32 final, @methodname i32 final, @signaturename i32 final, @annotationvalue i32 final, @flag u16 final, @argsize u16 final, @padding u32 final}> type $__method_info_compact__ <struct { @method_in_vtab_index i32 final, @addr i32 final, @lebPadding0 u8 final}> type $__field_info__ <struct { @offset u64 final, @mod u32 final, @flag u16 final, @index u16 final, @typeName i64 final, @fieldname u32 final, @annotation u32 final, @declaringclass <* void> final}> type $__field_info_compact__ <struct { @offset u32 final, @lebPadding0 u8 final}> type $__superclass_meta__ <struct { @superclassinfo <* void> final}> type $MUIDFuncDefTabEntry <struct { @funcUnifiedAddr u64}> type $MUIDFuncInfTabEntry <struct { @funcSize u32, @funcName u32}> type $MUIDFuncDefMuidTabEntry <struct { @muidLow u64, @muidHigh u64}> type $MUIDDataDefTabEntry <struct { @dataUnifiedAddr u64}> type $MUIDDataDefMuidTabEntry <struct { @muidLow u64, @muidHigh u64}> type $MUIDUnifiedUndefTabEntry <struct { @globalAddress u64}> type $MUIDUnifiedUndefMuidTabEntry <struct { @muidLow u64, @muidHigh u64}> type $MUIDRangeTabEntry <struct { @tabBegin <* void>, @tabEnd <* void>}> javaclass $LBase_3B <$LBase_3B> javaclass $LDerived_3B <$LDerived_3B> javainterface $LInter_3B <$LInter_3B> abstract javaclass $LInterfaceTest_3B <$LInterfaceTest_3B> public var $_C_STR_477e2dc723978d7245344fc51fc13e2b fstatic <[4] u64> readonly = [0, 0x1500000000, 0x65736142062a270a, 0x29286f6f662e] var $_C_STR_d820ddedd204b763a52374e860ce318e fstatic <[5] u64> readonly = [0, 0x1b00000000, 0x69726544357c6116, 0x286f6f662e646576, 41] var $_C_STR_a3cc511f7ef4b5079c824f99850ea7ef fstatic <[4] u64> readonly = [0, 0x1700000000, 0x65746e497a755c95, 0x29286f6f662e72] var $Ljava_2Flang_2FSystem_3B_7Cout extern <* <$Ljava_2Fio_2FPrintStream_3B>> final public static var $__cinf_Ljava_2Flang_2FString_3B <$__class_meta__> func &MCC_GetOrInsertLiteral () <* <$Ljava_2Flang_2FString_3B>> var $__vtb_LBase_3B fstatic <[12] <* void>> = [16, 24, 32, 36, 8, 4, 48, 12, 20, 44, 28, 10] var $__itb_LBase_3B fstatic <[16] <* void>> = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10] var $__vtb_LInterfaceTest_3B fstatic <[11] <* void>> = [16, 24, 32, 36, 8, 4, 48, 12, 20, 44, 28] var $__vtb_LDerived_3B fstatic <[12] <* void>> = [16, 24, 32, 36, 8, 4, 48, 12, 20, 44, 28, 18] var $__itb_LDerived_3B fstatic <[16] <* void>> = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18] var $__cinf_LInter_3B <$__class_meta__> public var $__methods_info__LInter_3B fstatic <[1] <$__method_info__>> public = [[1= 0, 2= addrof ptr $__cinf_LInter_3B, 3= addroffunc ptr &LInter_3B_7Cfoo_7C_28_29V, 4= 0x400001, 5= 36, 6= 52, 7= 68, 8= 0x2e00, 9= 1, 10= 0]] var $__classinforo__LInter_3B fstatic <$__class_meta_ro__> public = [1= 4, 2= 0, 3= addrof ptr $__methods_info__LInter_3B, 4= 0, 5= 0, 6= 1, 7= 0, 8= 0, 9= 0, 10= 0x600, 11= 68, 12= 0] var $MCC_GCTIB__LInter_3B fstatic <* void> public var $classStateInitialized u64 var $__cinf_LInter_3B <$__class_meta__> public = [1= 0x17efaac0f65c2f, 2= 0, 3= 0xffff, 4= 0, 5= 0, 6= 0, 7= addrof ptr $MCC_GCTIB__LInter_3B, 8= addrof ptr $__classinforo__LInter_3B, 9= addrof ptr $classStateInitialized] var $__cinf_LBase_3B <$__class_meta__> public var $__methods_info__LBase_3B fstatic <[2] <$__method_info__>> public = [[1= 11, 2= addrof ptr $__cinf_LBase_3B, 3= addroffunc ptr &LBase_3B_7Cfoo_7C_28_29V, 4= 1, 5= 36, 6= 52, 7= 68, 8= 0x2e00, 9= 1, 10= 0], [1= 0xfff6, 2= addrof ptr $__cinf_LBase_3B, 3= addroffunc ptr &LBase_3B_7C_3Cinit_3E_7C_28_29V, 4= 0x10000, 5= 112, 6= 52, 7= 68, 8= 0xad81, 9= 1, 10= 0]] var $__cinf_Ljava_2Flang_2FObject_3B extern <$__class_meta__> public var $__superclasses__LBase_3B fstatic <[2] <$__superclass_meta__>> public = [[1= 0x4000000000000000], [1= 0x2000000000000003]] var $__classinforo__LBase_3B fstatic <$__class_meta_ro__> public = [1= 84, 2= 0, 3= addrof ptr $__methods_info__LBase_3B, 4= addrof ptr $__superclasses__LBase_3B, 5= 0, 6= 2, 7= 0, 8= 2, 9= 0, 10= 32, 11= 68, 12= 0] var $MCC_GCTIB__LBase_3B fstatic <* void> public var $__cinf_LBase_3B <$__class_meta__> public = [1= 0x1d0741a94f96, 2= 0, 3= 0xffff, 4= 0, 5= addrof ptr $__itb_LBase_3B, 6= addrof ptr $__vtb_LBase_3B, 7= addrof ptr $MCC_GCTIB__LBase_3B, 8= addrof ptr $__classinforo__LBase_3B, 9= addrof ptr $classStateInitialized] var $__cinf_LInterfaceTest_3B <$__class_meta__> public var $__methods_info__LInterfaceTest_3B fstatic <[2] <$__method_info__>> public = [[1= 0xfff6, 2= addrof ptr $__cinf_LInterfaceTest_3B, 3= addroffunc ptr &LInterfaceTest_3B_7Cmain_7C_28ALjava_2Flang_2FString_3B_29V, 4= 9, 5= 204, 6= 224, 7= 68, 8= 0xa201, 9= 1, 10= 0], [1= 0xfff6, 2= addrof ptr $__cinf_LInterfaceTest_3B, 3= addroffunc ptr &LInterfaceTest_3B_7C_3Cinit_3E_7C_28_29V, 4= 0x10001, 5= 112, 6= 52, 7= 68, 8= 0xad81, 9= 1, 10= 0]] var $__superclasses__LInterfaceTest_3B fstatic <[1] <$__superclass_meta__>> public = [[1= 0x4000000000000000]] var $__classinforo__LInterfaceTest_3B fstatic <$__class_meta_ro__> public = [1= 140, 2= 0, 3= addrof ptr $__methods_info__LInterfaceTest_3B, 4= addrof ptr $__superclasses__LInterfaceTest_3B, 5= 0, 6= 2, 7= 0, 8= 1, 9= 0, 10= 33, 11= 68, 12= 0] var $MCC_GCTIB__LInterfaceTest_3B fstatic <* void> public var $__cinf_LInterfaceTest_3B <$__class_meta__> public = [1= 0x31d3c74ca034cbdc, 2= 0, 3= 0xffff, 4= 0, 5= 0, 6= addrof ptr $__vtb_LInterfaceTest_3B, 7= addrof ptr $MCC_GCTIB__LInterfaceTest_3B, 8= addrof ptr $__classinforo__LInterfaceTest_3B, 9= addrof ptr $classStateInitialized] var $__cinf_LDerived_3B <$__class_meta__> public var $__methods_info__LDerived_3B fstatic <[2] <$__method_info__>> public = [[1= 11, 2= addrof ptr $__cinf_LDerived_3B, 3= addroffunc ptr &LDerived_3B_7Cfoo_7C_28_29V, 4= 1, 5= 36, 6= 52, 7= 68, 8= 0x2e00, 9= 1, 10= 0], [1= 0xfff6, 2= addrof ptr $__cinf_LDerived_3B, 3= addroffunc ptr &LDerived_3B_7C_3Cinit_3E_7C_28_29V, 4= 0x10000, 5= 112, 6= 52, 7= 68, 8= 0xad81, 9= 1, 10= 0]] var $__superclasses__LDerived_3B fstatic <[1] <$__superclass_meta__>> public = [[1= 0x2000000000000002]] var $__classinforo__LDerived_3B fstatic <$__class_meta_ro__> public = [1= 316, 2= 0, 3= addrof ptr $__methods_info__LDerived_3B, 4= addrof ptr $__superclasses__LDerived_3B, 5= 0, 6= 2, 7= 0, 8= 1, 9= 0, 10= 32, 11= 68, 12= 0] var $MCC_GCTIB__LDerived_3B fstatic <* void> public var $__cinf_LDerived_3B <$__class_meta__> public = [1= 0x4171f2415194822a, 2= 0, 3= 0xffff, 4= 0, 5= addrof ptr $__itb_LDerived_3B, 6= addrof ptr $__vtb_LDerived_3B, 7= addrof ptr $MCC_GCTIB__LDerived_3B, 8= addrof ptr $__classinforo__LDerived_3B, 9= addrof ptr $classStateInitialized] var $__muid_classmetadata_bucket$$InterfaceTest_jar <[4] <* void>> public = [addrof ptr $__cinf_LInter_3B, addrof ptr $__cinf_LBase_3B, addrof ptr $__cinf_LInterfaceTest_3B, addrof ptr $__cinf_LDerived_3B] func &MCC_Reflect_ThrowCastException nosideeffect () void func &MCC_Reflect_Check_Casting_NoArray nosideeffect () void func &MCC_Reflect_Check_Casting_Array nosideeffect () void func &MCC_CheckThrowPendingException nosideeffect () void func &MCC_PreNativeCall (var %caller ref) <* void> func &MCC_PostNativeCall (var %env <* void>) void func &MCC_DecodeReference nosideeffect (var %obj ref) ref func &MCC_CallFastNative (var %func <* void>) <* void> func &MCC_CallSlowNative0 (var %func <* void>) <* void> func &MCC_CallSlowNative1 (var %func <* void>) <* void> func &MCC_CallSlowNative2 (var %func <* void>) <* void> func &MCC_CallSlowNative3 (var %func <* void>) <* void> func &MCC_CallSlowNative4 (var %func <* void>) <* void> func &MCC_CallSlowNative5 (var %func <* void>) <* void> func &MCC_CallSlowNative6 (var %func <* void>) <* void> func &MCC_CallSlowNative7 (var %func <* void>) <* void> func &MCC_CallSlowNative8 (var %func <* void>) <* void> func &MCC_CallFastNativeExt (var %func <* void>) <* void> func &MCC_CallSlowNativeExt (var %func <* void>) <* void> func &MCC_SetReliableUnwindContext nosideeffect () void var $__reg_jni_func_tab$$InterfaceTest_jar <[0] <* void>> var $__cinf_Ljava_2Flang_2FSystem_3B extern <$__class_meta__> func &MCC_getFuncPtrFromItabSecondHash64 nosideeffect () ptr var $__muid_func_def_tab$$InterfaceTest_jar fstatic <[7] <$MUIDFuncDefTabEntry>> = [[1= addroffunc ptr &LBase_3B_7C_3Cinit_3E_7C_28_29V], [1= addroffunc ptr &LBase_3B_7Cfoo_7C_28_29V], [1= addroffunc ptr &LDerived_3B_7C_3Cinit_3E_7C_28_29V], [1= addroffunc ptr &LDerived_3B_7Cfoo_7C_28_29V], [1= addroffunc ptr &LInter_3B_7Cfoo_7C_28_29V], [1= addroffunc ptr &LInterfaceTest_3B_7C_3Cinit_3E_7C_28_29V], [1= addroffunc ptr &LInterfaceTest_3B_7Cmain_7C_28ALjava_2Flang_2FString_3B_29V]] var $__muid_func_inf_tab$$InterfaceTest_jar fstatic <[7] <$MUIDFuncInfTabEntry>> = [[1= addroffunc ptr &LBase_3B_7C_3Cinit_3E_7C_28_29V, 2= addroffunc ptr &LBase_3B_7C_3Cinit_3E_7C_28_29V], [1= addroffunc ptr &LBase_3B_7Cfoo_7C_28_29V, 2= addroffunc ptr &LBase_3B_7Cfoo_7C_28_29V], [1= addroffunc ptr &LDerived_3B_7C_3Cinit_3E_7C_28_29V, 2= addroffunc ptr &LDerived_3B_7C_3Cinit_3E_7C_28_29V], [1= addroffunc ptr &LDerived_3B_7Cfoo_7C_28_29V, 2= addroffunc ptr &LDerived_3B_7Cfoo_7C_28_29V], [1= addroffunc ptr &LInter_3B_7Cfoo_7C_28_29V, 2= addroffunc ptr &LInter_3B_7Cfoo_7C_28_29V], [1= addroffunc ptr &LInterfaceTest_3B_7C_3Cinit_3E_7C_28_29V, 2= addroffunc ptr &LInterfaceTest_3B_7C_3Cinit_3E_7C_28_29V], [1= addroffunc ptr &LInterfaceTest_3B_7Cmain_7C_28ALjava_2Flang_2FString_3B_29V, 2= addroffunc ptr &LInterfaceTest_3B_7Cmain_7C_28ALjava_2Flang_2FString_3B_29V]] var $__muid_func_def_muid_tab$$InterfaceTest_jar fstatic <[7] <$MUIDFuncDefMuidTabEntry>> = [[1= 0x178109574fbab3d6, 2= -1724730257836805130], [1= 0x368e6237953a2580, 2= -504698780890953708], [1= 0xb7b286ddee8eafe, 2= -2169785298905445890], [1= 0x63bbf9d1c3499099, 2= -1943522023966098161], [1= -1675590344887417795, 2= -2230789790025730929], [1= 0x5100e9678d558128, 2= -3593795459477186102], [1= -2829949660543074558, 2= -1685351998939611686]] var $__muid_func_muid_idx_tab$$InterfaceTest_jar fstatic <[7] u32> = [5, 4, 2, 3, 0, 6, 1] var $__muid_data_def_tab$$InterfaceTest_jar fstatic <[4] <$MUIDDataDefTabEntry>> = [[1= addrof ptr $__cinf_LDerived_3B], [1= addrof ptr $__cinf_LInterfaceTest_3B], [1= addrof ptr $__cinf_LBase_3B], [1= addrof ptr $__cinf_LInter_3B]] var $__muid_data_def_muid_tab$$InterfaceTest_jar fstatic <[4] <$MUIDDataDefMuidTabEntry>> = [[1= 0x7eb6c0f619e83624, 2= -3145394803863882273], [1= -5523991683343173598, 2= -1468839900656767610], [1= -8809292195587745449, 2= -1374821749885213916], [1= 0x77baadcefdd399cb, 2= -745242518540589114]] var $__muid_func_undef_tab$$InterfaceTest_jar fstatic <[12] <$MUIDUnifiedUndefTabEntry>> = [[1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0]] var $__muid_func_undef_muid_tab$$InterfaceTest_jar fstatic <[12] <$MUIDUnifiedUndefMuidTabEntry>> = [[1= 0x3e32352aee789835, 2= -3887705395317205813], [1= -4187412136968710015, 2= -3800091941095621250], [1= 0x6742c234127e0a27, 2= -3762262047879347071], [1= 0x7230554331c55d92, 2= -3676689525926909155], [1= -715372855679083712, 2= -2647497990906227723], [1= -7464356948810446352, 2= -2259485500590180091], [1= 0x783627f2afd1cbde, 2= -2046851302095768916], [1= -2701934576591406938, 2= -1693831364093527548], [1= 0x126777a7fe39e1fb, 2= -1314856249532362766], [1= 0xbf40578f3343f7a, 2= -1198421541845410999], [1= 0x7ca2bdf69a6c7c94, 2= -801329978528900548], [1= 0x477aafa4d7dd102b, 2= -442561182569419835]] var $__muid_data_undef_tab$$InterfaceTest_jar fstatic <[3] <$MUIDUnifiedUndefTabEntry>> = [[1= addrof ptr $__cinf_Ljava_2Flang_2FObject_3B], [1= addrof ptr $Ljava_2Flang_2FSystem_3B_7Cout], [1= addrof ptr $__cinf_Ljava_2Flang_2FSystem_3B]] var $__muid_data_undef_muid_tab$$InterfaceTest_jar fstatic <[3] <$MUIDUnifiedUndefMuidTabEntry>> = [[1= -567417612161374449, 2= -3298852447504547670], [1= 0x191283ac418c4bb9, 2= -1676204161023949463], [1= -5921653145571052587, 2= -171150348656858163]] var $__muid_range_tab$$InterfaceTest_jar fstatic <[29] <$MUIDRangeTabEntry>> = [[1= -4105516598114278518, 2= -3041593165803565154], [1= -906916996929164970, 2= -2307534257755856003], [1= 2, 2= 2], [1= 3, 2= 3], [1= 4, 2= 4], [1= 5, 2= 5], [1= 6, 2= 6], [1= 7, 2= 7], [1= 8, 2= 8], [1= 9, 2= 9], [1= 0, 2= 0], [1= 11, 2= 11], [1= 12, 2= 12], [1= 13, 2= 13], [1= 14, 2= 14], [1= 15, 2= 15], [1= addrof ptr $__muid_func_def_tab$$InterfaceTest_jar, 2= addrof ptr $__muid_func_def_tab$$InterfaceTest_jar], [1= 0, 2= 0], [1= addrof ptr $__muid_func_inf_tab$$InterfaceTest_jar, 2= addrof ptr $__muid_func_inf_tab$$InterfaceTest_jar], [1= addrof ptr $__muid_func_undef_tab$$InterfaceTest_jar, 2= addrof ptr $__muid_func_undef_tab$$InterfaceTest_jar], [1= addrof ptr $__muid_data_def_tab$$InterfaceTest_jar, 2= addrof ptr $__muid_data_def_tab$$InterfaceTest_jar], [1= 0, 2= 0], [1= addrof ptr $__muid_data_undef_tab$$InterfaceTest_jar, 2= addrof ptr $__muid_data_undef_tab$$InterfaceTest_jar], [1= addrof ptr $__muid_func_def_muid_tab$$InterfaceTest_jar, 2= addrof ptr $__muid_func_def_muid_tab$$InterfaceTest_jar], [1= addrof ptr $__muid_func_undef_muid_tab$$InterfaceTest_jar, 2= addrof ptr $__muid_func_undef_muid_tab$$InterfaceTest_jar], [1= addrof ptr $__muid_data_def_muid_tab$$InterfaceTest_jar, 2= addrof ptr $__muid_data_def_muid_tab$$InterfaceTest_jar], [1= addrof ptr $__muid_data_undef_muid_tab$$InterfaceTest_jar, 2= addrof ptr $__muid_data_undef_muid_tab$$InterfaceTest_jar], [1= addrof ptr $__muid_func_muid_idx_tab$$InterfaceTest_jar, 2= addrof ptr $__muid_func_muid_idx_tab$$InterfaceTest_jar], [1= 0, 2= 0]] var $__reflection_strtab$$InterfaceTest_jar fstatic <[89] u8> = [0, 76, 73, 110, 116, 101, 114, 59, 0, 102, 111, 111, 0, 40, 41, 86, 0, 48, 33, 48, 0, 76, 66, 97, 115, 101, 59, 0, 60, 105, 110, 105, 116, 62, 0, 76, 73, 110, 116, 101, 114, 102, 97, 99, 101, 84, 101, 115, 116, 59, 0, 109, 97, 105, 110, 0, 40, 91, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 41, 86, 0, 76, 68, 101, 114, 105, 118, 101, 100, 59, 0] var $__compilerVersionNum$$InterfaceTest_jar <[0] <* void>> = [1, 0] func &LBase_3B_7C_3Cinit_3E_7C_28_29V constructor (var %_this <* <$LBase_3B>>) void { funcid 48153 var %Reg1_R43697 <* <$LBase_3B>> localrefvar var %Reg1_R57 <* <$Ljava_2Flang_2FObject_3B>> localrefvar var %__muid_symptr <* void> intrinsiccall MCCIncRef (dread ref %_this) intrinsiccall MCCDecRef (dread ref %Reg1_R43697) dassign %Reg1_R43697 0 (dread ref %_this) #INSTIDX : 0||0000: aload_0 #INSTIDX : 1||0001: invokespecial regassign ptr %1 (dread ref %Reg1_R57) dassign %Reg1_R57 0 (retype ref <* <$Ljava_2Flang_2FObject_3B>> (dread ref %Reg1_R43697)) intrinsiccall MCCIncRef (dread ref %Reg1_R57) intrinsiccall MCCDecRef (regread ptr %1) #Call function:Ljava_2Flang_2FObject_3B_7C_3Cinit_3E_7C_28_29V dassign %__muid_symptr 0 (iread ptr <* <$MUIDUnifiedUndefTabEntry>> 1 (array 0 ptr <* <[12] <$MUIDUnifiedUndefTabEntry>>> (addrof ptr $__muid_func_undef_tab$$InterfaceTest_jar, constval i64 9))) icallassigned (dread ptr %__muid_symptr, dread ref %Reg1_R57) {} #INSTIDX : 4||0004: return intrinsiccall MPL_CLEANUP_LOCALREFVARS (dread ref %Reg1_R43697, dread ref %Reg1_R57) return () } func &LBase_3B_7Cfoo_7C_28_29V public virtual (var %_this <* <$LBase_3B>>) void { funcid 48154 var %Reg2_R43697 <* <$LBase_3B>> localrefvar var %Reg0_R562 <* <$Ljava_2Fio_2FPrintStream_3B>> localrefvar var %Reg1_R43 <* <$Ljava_2Flang_2FString_3B>> localrefvar var %L_STR_161333 <* <$Ljava_2Flang_2FString_3B>> intrinsiccall MCCIncRef (dread ref %_this) intrinsiccall MCCDecRef (dread ref %Reg2_R43697) dassign %Reg2_R43697 0 (dread ref %_this) #INSTIDX : 0||0000: getstatic intrinsiccall MPL_CLINIT_CHECK (addrof ptr $__cinf_Ljava_2Flang_2FSystem_3B) regassign ptr %1 (dread ref %Reg0_R562) #Read from: Ljava_2Flang_2FSystem_3B_7Cout dassign %Reg0_R562 0 (iread ref <* <* <$Ljava_2Fio_2FPrintStream_3B>>> 0 (iread ptr <* <$MUIDUnifiedUndefTabEntry>> 1 (array 0 ptr <* <[3] <$MUIDUnifiedUndefTabEntry>>> (addrof ptr $__muid_data_undef_tab$$InterfaceTest_jar, constval i64 1)))) intrinsiccall MCCIncRef (dread ref %Reg0_R562) intrinsiccall MCCDecRef (regread ptr %1) #INSTIDX : 3||0003: ldc callassigned &MCC_GetOrInsertLiteral (addrof ptr $_C_STR_477e2dc723978d7245344fc51fc13e2b) { dassign %L_STR_161333 0 } intrinsiccall MCCIncRef (dread ptr %L_STR_161333) intrinsiccall MCCDecRef (dread ref %Reg1_R43) dassign %Reg1_R43 0 (dread ptr %L_STR_161333) #INSTIDX : 5||0005: invokevirtual icallassigned ( iread u64 <* u64> 0 (add ptr ( iread ptr <* <$__class_meta__>> 6 (iread ref <* <$Ljava_2Flang_2FObject_3B>> 1 (dread ref %Reg0_R562)), constval u32 312)), dread ref %Reg0_R562, dread ref %Reg1_R43) {} #INSTIDX : 8||0008: return intrinsiccall MPL_CLEANUP_LOCALREFVARS (dread ref %Reg2_R43697, dread ref %Reg0_R562, dread ref %Reg1_R43) return () } func &LDerived_3B_7C_3Cinit_3E_7C_28_29V constructor (var %_this <* <$LDerived_3B>>) void { funcid 48155 var %Reg1_R43699 <* <$LDerived_3B>> localrefvar var %Reg1_R43697 <* <$LBase_3B>> localrefvar var %__muid_symptr <* void> intrinsiccall MCCIncRef (dread ref %_this) intrinsiccall MCCDecRef (dread ref %Reg1_R43699) dassign %Reg1_R43699 0 (dread ref %_this) #INSTIDX : 0||0000: aload_0 #INSTIDX : 1||0001: invokespecial regassign ptr %1 (dread ref %Reg1_R43697) dassign %Reg1_R43697 0 (retype ref <* <$LBase_3B>> (dread ref %Reg1_R43699)) intrinsiccall MCCIncRef (dread ref %Reg1_R43697) intrinsiccall MCCDecRef (regread ptr %1) #Call function:LBase_3B_7C_3Cinit_3E_7C_28_29V dassign %__muid_symptr 0 (iread ptr <* <$MUIDFuncDefTabEntry>> 1 (array 0 ptr <* <[7] <$MUIDFuncDefTabEntry>>> (addrof ptr $__muid_func_def_tab$$InterfaceTest_jar, constval i64 0))) icallassigned (dread ptr %__muid_symptr, dread ref %Reg1_R43697) {} #INSTIDX : 4||0004: return intrinsiccall MPL_CLEANUP_LOCALREFVARS (dread ref %Reg1_R43699, dread ref %Reg1_R43697) return () } func &LDerived_3B_7Cfoo_7C_28_29V public virtual (var %_this <* <$LDerived_3B>>) void { funcid 48156 var %Reg2_R43699 <* <$LDerived_3B>> localrefvar var %Reg0_R562 <* <$Ljava_2Fio_2FPrintStream_3B>> localrefvar var %Reg1_R43 <* <$Ljava_2Flang_2FString_3B>> localrefvar var %L_STR_161344 <* <$Ljava_2Flang_2FString_3B>> intrinsiccall MCCIncRef (dread ref %_this) intrinsiccall MCCDecRef (dread ref %Reg2_R43699) dassign %Reg2_R43699 0 (dread ref %_this) #INSTIDX : 0||0000: getstatic intrinsiccall MPL_CLINIT_CHECK (addrof ptr $__cinf_Ljava_2Flang_2FSystem_3B) regassign ptr %1 (dread ref %Reg0_R562) #Read from: Ljava_2Flang_2FSystem_3B_7Cout dassign %Reg0_R562 0 (iread ref <* <* <$Ljava_2Fio_2FPrintStream_3B>>> 0 (iread ptr <* <$MUIDUnifiedUndefTabEntry>> 1 (array 0 ptr <* <[3] <$MUIDUnifiedUndefTabEntry>>> (addrof ptr $__muid_data_undef_tab$$InterfaceTest_jar, constval i64 1)))) intrinsiccall MCCIncRef (dread ref %Reg0_R562) intrinsiccall MCCDecRef (regread ptr %1) #INSTIDX : 3||0003: ldc callassigned &MCC_GetOrInsertLiteral (addrof ptr $_C_STR_d820ddedd204b763a52374e860ce318e) { dassign %L_STR_161344 0 } intrinsiccall MCCIncRef (dread ptr %L_STR_161344) intrinsiccall MCCDecRef (dread ref %Reg1_R43) dassign %Reg1_R43 0 (dread ptr %L_STR_161344) #INSTIDX : 5||0005: invokevirtual icallassigned ( iread u64 <* u64> 0 (add ptr ( iread ptr <* <$__class_meta__>> 6 (iread ref <* <$Ljava_2Flang_2FObject_3B>> 1 (dread ref %Reg0_R562)), constval u32 312)), dread ref %Reg0_R562, dread ref %Reg1_R43) {} #INSTIDX : 8||0008: return intrinsiccall MPL_CLEANUP_LOCALREFVARS (dread ref %Reg2_R43699, dread ref %Reg0_R562, dread ref %Reg1_R43) return () } func &LInter_3B_7Cfoo_7C_28_29V public virtual (var %_this <* <$LInter_3B>>) void { funcid 48157 var %Reg2_R43701 <* <$LInter_3B>> localrefvar var %Reg0_R562 <* <$Ljava_2Fio_2FPrintStream_3B>> localrefvar var %Reg1_R43 <* <$Ljava_2Flang_2FString_3B>> localrefvar var %L_STR_161347 <* <$Ljava_2Flang_2FString_3B>> intrinsiccall MCCIncRef (dread ref %_this) intrinsiccall MCCDecRef (dread ref %Reg2_R43701) dassign %Reg2_R43701 0 (dread ref %_this) #INSTIDX : 0||0000: getstatic intrinsiccall MPL_CLINIT_CHECK (addrof ptr $__cinf_Ljava_2Flang_2FSystem_3B) regassign ptr %1 (dread ref %Reg0_R562) #Read from: Ljava_2Flang_2FSystem_3B_7Cout dassign %Reg0_R562 0 (iread ref <* <* <$Ljava_2Fio_2FPrintStream_3B>>> 0 (iread ptr <* <$MUIDUnifiedUndefTabEntry>> 1 (array 0 ptr <* <[3] <$MUIDUnifiedUndefTabEntry>>> (addrof ptr $__muid_data_undef_tab$$InterfaceTest_jar, constval i64 1)))) intrinsiccall MCCIncRef (dread ref %Reg0_R562) intrinsiccall MCCDecRef (regread ptr %1) #INSTIDX : 3||0003: ldc callassigned &MCC_GetOrInsertLiteral (addrof ptr $_C_STR_a3cc511f7ef4b5079c824f99850ea7ef) { dassign %L_STR_161347 0 } intrinsiccall MCCIncRef (dread ptr %L_STR_161347) intrinsiccall MCCDecRef (dread ref %Reg1_R43) dassign %Reg1_R43 0 (dread ptr %L_STR_161347) #INSTIDX : 5||0005: invokevirtual icallassigned ( iread u64 <* u64> 0 (add ptr ( iread ptr <* <$__class_meta__>> 6 (iread ref <* <$Ljava_2Flang_2FObject_3B>> 1 (dread ref %Reg0_R562)), constval u32 312)), dread ref %Reg0_R562, dread ref %Reg1_R43) {} #INSTIDX : 8||0008: return intrinsiccall MPL_CLEANUP_LOCALREFVARS (dread ref %Reg2_R43701, dread ref %Reg0_R562, dread ref %Reg1_R43) return () } func &LInterfaceTest_3B_7C_3Cinit_3E_7C_28_29V public constructor (var %_this <* <$LInterfaceTest_3B>>) void { funcid 48158 var %Reg1_R43703 <* <$LInterfaceTest_3B>> localrefvar var %Reg1_R57 <* <$Ljava_2Flang_2FObject_3B>> localrefvar var %__muid_symptr <* void> intrinsiccall MCCIncRef (dread ref %_this) intrinsiccall MCCDecRef (dread ref %Reg1_R43703) dassign %Reg1_R43703 0 (dread ref %_this) #INSTIDX : 0||0000: aload_0 #INSTIDX : 1||0001: invokespecial regassign ptr %1 (dread ref %Reg1_R57) dassign %Reg1_R57 0 (retype ref <* <$Ljava_2Flang_2FObject_3B>> (dread ref %Reg1_R43703)) intrinsiccall MCCIncRef (dread ref %Reg1_R57) intrinsiccall MCCDecRef (regread ptr %1) #Call function:Ljava_2Flang_2FObject_3B_7C_3Cinit_3E_7C_28_29V dassign %__muid_symptr 0 (iread ptr <* <$MUIDUnifiedUndefTabEntry>> 1 (array 0 ptr <* <[12] <$MUIDUnifiedUndefTabEntry>>> (addrof ptr $__muid_func_undef_tab$$InterfaceTest_jar, constval i64 9))) icallassigned (dread ptr %__muid_symptr, dread ref %Reg1_R57) {} #INSTIDX : 4||0004: return intrinsiccall MPL_CLEANUP_LOCALREFVARS (dread ref %Reg1_R43703, dread ref %Reg1_R57) return () } func &LInterfaceTest_3B_7Cmain_7C_28ALjava_2Flang_2FString_3B_29V public static (var %Reg5_R743 <* <[] <* <$Ljava_2Flang_2FString_3B>>>>) void { funcid 48159 var %Reg0_R43699 <* <$LDerived_3B>> localrefvar var %Reg2_R43699 <* <$LDerived_3B>> localrefvar var %Reg3_R43699 <* <$LDerived_3B>> localrefvar var %Reg3_R43697 <* <$LBase_3B>> localrefvar var %Reg4_R43699 <* <$LDerived_3B>> localrefvar var %Reg4_R43701 <* <$LInter_3B>> localrefvar var %__muid_symptr <* void> #INSTIDX : 0||0000: new regassign ptr %1 (dread ref %Reg0_R43699) dassign %Reg0_R43699 0 (gcmalloc ref <$LDerived_3B>) intrinsiccall MCCDecRef (regread ptr %1) #INSTIDX : 3||0003: dup #INSTIDX : 4||0004: invokespecial #Call function:LDerived_3B_7C_3Cinit_3E_7C_28_29V dassign %__muid_symptr 0 (iread ptr <* <$MUIDFuncDefTabEntry>> 1 (array 0 ptr <* <[7] <$MUIDFuncDefTabEntry>>> (addrof ptr $__muid_func_def_tab$$InterfaceTest_jar, constval i64 2))) icallassigned (dread ptr %__muid_symptr, dread ref %Reg0_R43699) {} #INSTIDX : 7||0007: astore_1 intrinsiccall MCCIncRef (dread ref %Reg0_R43699) intrinsiccall MCCDecRef (dread ref %Reg2_R43699) dassign %Reg2_R43699 0 (dread ref %Reg0_R43699) #INSTIDX : 8||0008: aload_1 #INSTIDX : 9||0009: invokevirtual icallassigned ( iread u64 <* u64> 0 (add ptr ( iread ptr <* <$__class_meta__>> 6 (iread ref <* <$Ljava_2Flang_2FObject_3B>> 1 (dread ref %Reg2_R43699)), constval u32 88)), dread ref %Reg2_R43699) {} #INSTIDX : 12||000c: new regassign ptr %2 (dread ref %Reg0_R43699) dassign %Reg0_R43699 0 (gcmalloc ref <$LDerived_3B>) intrinsiccall MCCDecRef (regread ptr %2) #INSTIDX : 15||000f: dup #INSTIDX : 16||0010: invokespecial #Call function:LDerived_3B_7C_3Cinit_3E_7C_28_29V dassign %__muid_symptr 0 (iread ptr <* <$MUIDFuncDefTabEntry>> 1 (array 0 ptr <* <[7] <$MUIDFuncDefTabEntry>>> (addrof ptr $__muid_func_def_tab$$InterfaceTest_jar, constval i64 2))) icallassigned (dread ptr %__muid_symptr, dread ref %Reg0_R43699) {} #INSTIDX : 19||0013: astore_2 intrinsiccall MCCIncRef (dread ref %Reg0_R43699) intrinsiccall MCCDecRef (dread ref %Reg3_R43699) dassign %Reg3_R43699 0 (dread ref %Reg0_R43699) #INSTIDX : 20||0014: aload_2 #INSTIDX : 21||0015: invokevirtual regassign ptr %3 (dread ref %Reg3_R43697) dassign %Reg3_R43697 0 (retype ref <* <$LBase_3B>> (dread ref %Reg3_R43699)) intrinsiccall MCCIncRef (dread ref %Reg3_R43697) intrinsiccall MCCDecRef (regread ptr %3) icallassigned ( iread u64 <* u64> 0 (add ptr ( iread ptr <* <$__class_meta__>> 6 (iread ref <* <$Ljava_2Flang_2FObject_3B>> 1 (dread ref %Reg3_R43697)), constval u32 88)), dread ref %Reg3_R43697) {} #INSTIDX : 24||0018: new regassign ptr %4 (dread ref %Reg0_R43699) dassign %Reg0_R43699 0 (gcmalloc ref <$LDerived_3B>) intrinsiccall MCCDecRef (regread ptr %4) #INSTIDX : 27||001b: dup #INSTIDX : 28||001c: invokespecial #Call function:LDerived_3B_7C_3Cinit_3E_7C_28_29V dassign %__muid_symptr 0 (iread ptr <* <$MUIDFuncDefTabEntry>> 1 (array 0 ptr <* <[7] <$MUIDFuncDefTabEntry>>> (addrof ptr $__muid_func_def_tab$$InterfaceTest_jar, constval i64 2))) icallassigned (dread ptr %__muid_symptr, dread ref %Reg0_R43699) {} #INSTIDX : 31||001f: astore_3 intrinsiccall MCCIncRef (dread ref %Reg0_R43699) intrinsiccall MCCDecRef (dread ref %Reg4_R43699) dassign %Reg4_R43699 0 (dread ref %Reg0_R43699) #INSTIDX : 32||0020: aload_3 #INSTIDX : 33||0021: invokeinterface regassign ptr %5 (dread ref %Reg4_R43701) dassign %Reg4_R43701 0 (retype ref <* <$LInter_3B>> (dread ref %Reg4_R43699)) intrinsiccall MCCIncRef (dread ref %Reg4_R43701) intrinsiccall MCCDecRef (regread ptr %5) regassign ptr %6 (iread ptr <* <$__class_meta__>> 5 (iread ref <* <$Ljava_2Flang_2FObject_3B>> 1 (dread ref %Reg4_R43701))) regassign u64 %7 (iread u64 <* u64> 0 (add ptr (regread ptr %6, constval u32 120))) if (eq u1 u64 (regread u64 %7, constval u64 0)) { callassigned &MCC_getFuncPtrFromItabSecondHash64 (regread ptr %6, constval u64 0x12c8, conststr ptr "foo|()V") { regassign u64 %7} } icallassigned (regread u64 %7, dread ref %Reg4_R43701) {} #INSTIDX : 38||0026: return intrinsiccall MPL_CLEANUP_LOCALREFVARS (dread ref %Reg0_R43699, dread ref %Reg2_R43699, dread ref %Reg3_R43699, dread ref %Reg3_R43697, dread ref %Reg4_R43699, dread ref %Reg4_R43701) return () }
[STATEMENT] lemma (in fin_digraph) subgraph_in_degree: assumes "subgraph H G" shows "in_degree H v \<le> in_degree G v" [PROOF STATE] proof (prove) goal (1 subgoal): 1. in_degree H v \<le> in_degree G v [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. in_degree H v \<le> in_degree G v [PROOF STEP] have "finite (in_arcs G v)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. finite (in_arcs G v) [PROOF STEP] by auto [PROOF STATE] proof (state) this: finite (in_arcs G v) goal (1 subgoal): 1. in_degree H v \<le> in_degree G v [PROOF STEP] moreover [PROOF STATE] proof (state) this: finite (in_arcs G v) goal (1 subgoal): 1. in_degree H v \<le> in_degree G v [PROOF STEP] have "in_arcs H v \<subseteq> in_arcs G v" [PROOF STATE] proof (prove) goal (1 subgoal): 1. in_arcs H v \<subseteq> in_arcs G v [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: subgraph H G goal (1 subgoal): 1. in_arcs H v \<subseteq> in_arcs G v [PROOF STEP] by (auto simp: subgraph_def in_arcs_def compatible_head compatible_tail) [PROOF STATE] proof (state) this: in_arcs H v \<subseteq> in_arcs G v goal (1 subgoal): 1. in_degree H v \<le> in_degree G v [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: finite (in_arcs G v) in_arcs H v \<subseteq> in_arcs G v [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: finite (in_arcs G v) in_arcs H v \<subseteq> in_arcs G v goal (1 subgoal): 1. in_degree H v \<le> in_degree G v [PROOF STEP] unfolding in_degree_def [PROOF STATE] proof (prove) using this: finite (in_arcs G v) in_arcs H v \<subseteq> in_arcs G v goal (1 subgoal): 1. card (in_arcs H v) \<le> card (in_arcs G v) [PROOF STEP] by (rule card_mono) [PROOF STATE] proof (state) this: in_degree H v \<le> in_degree G v goal: No subgoals! [PROOF STEP] qed
Require Import Utf8. Require Import Cpdt.CpdtTactics. Module Type STLCArrow. Parameter Inc : Set -> Set. Parameter Exp : Set -> Set. Parameter Choose : Set -> Set. Parameter Empty_inj : Set -> Set. (* Specification is below *) Axiom empty_inj_empty : forall (V : Set), Choose (Empty_inj V) = Empty_set. (* Interestingly, we can still use the same signature to make Exp track of both term variables and type variables. For example, Exp (V * W) where term variables in V, type variables in W Choose := fst Inc := fun (x,y) => (inc x, y) (Leave type variable unchanged) Then we can track multiple groups of variables by Choose *) Parameter ty : Set -> Set. Parameter exp_var : forall {V : Set}, Choose V -> Exp V. Parameter exp_abs : forall {V : Set}, ty V -> Exp (Inc V) -> Exp V. Parameter exp_app : forall {V : Set}, Exp V -> Exp V -> Exp V. Parameter exp_tt : forall {V : Set}, Exp V. Parameter exp_ff : forall {V : Set}, Exp V. Parameter exp_if : forall {V : Set}, Exp V -> Exp V -> Exp V -> Exp V. Parameter val : forall {V : Set}, Exp V -> Prop. Definition Val (V : Set) := {x : Exp V | val x}. Parameter step : forall {V : Set}, Exp V -> Exp V -> Prop. Notation "∅" := (Empty_set). Notation Exp0 := (Exp (Empty_inj Empty_set)). Notation Val0 := (Val (Empty_inj Empty_set)). Parameter subst_one : forall {V : Set}, Val0 -> Exp (Inc V) -> Exp V. Parameter subst_all : forall {V : Set} (f : V -> Val0), Exp V -> Exp0. Axiom subst_one_equations: forall {V: Set} {cond a b : Exp (Inc V)}, (* conditional *) (subst_one (exp_if cond a b) = (exp_if (subst_one cond) (subst_one a) (subst_one b))) /\ (subst_one (V:=V) (exp_tt) = exp_tt) /\ (subst_one (V:=V) (exp_ff) = exp_ff) (* app abs var *) /\ (subst_one (exp_abs T body) = exp_abs) /\ (subst_one (exp_var )) /\ (subst_one (exp_app a b) = (exp_app (subst_one a) (subst_one b))). (* Several design point: 1. In the signature, we will only store the operational semantic, substitution lemmas, like dynmaic typed lambda calculus 2. In the module functor, we will store the proof of semantic typing, where the relation will be in a parameterized way For example, we will have the following two Definition compat_app {V} (R: Ctx V -> Exp V -> ty V -> Prop) := R Γ x (ty_arrow T1 T2) -> R Γ y T1 -> R Γ (exp_app x y) T2. And give Definition type_safe_app : compat_app TypeSafe. 3. In the signature, we will also keep mixing-in the new expression, new terms *) Axiom val_tt : forall {V : Set}, val (V := V) (exp_tt). Axiom val_ff : forall {V : Set}, val (V := V) (exp_ff). Axiom val_abs : forall {V : Set} T body, val (V := V) (exp_abs T body). Axiom val_var : forall {V: Set} v, val (V := V) (exp_var v). (* Eval Context *) Parameter E : Set. Parameter hole : E. Parameter plugE : E -> exp0 -> exp0. (* Inherited Stepping *) Axiom step_respect_E: forall E x y, step x y -> step (plugE E x) (plugE E y). Axiom step_determinstic : forall {V : Set} (x y z : Exp V), step x y -> step x z -> y = z. (* Customized Evaluation Point *) Axiom step_if0: forall {V : Set} {a b : Exp V}, step (exp_if (exp_tt) a b) a. Axiom step_if1: forall {V : Set} {a b : Exp V}, step (exp_if (exp_ff) a b) b. Axiom step_app0: forall {V : Set} {a b : Exp V}, step (exp_app (exp_abs ) a b) b. End STLCArrow. Module Type STLCbic <: STLCArrow. Include STLCArrow. Parameter exp_prod : forall {V : Set}, Exp V -> Exp V -> Exp V. End STLCbic. Print STLCbic. Inductive Exp (U : Type)
A total of twelve hemmemas were built , six of them for the Swedish archipelago fleet and six for the Russian Navy . Details of individual vessels are listed below . The Swedish hemmemas were all built to the same specifications , except for the early design Oden , and Birger Jarl and Erik Segersäll carried heavier armament than the others . <unk> and Sozaev list Oden as a turuma rebuilt as a hemmema in 1784 , though Oscar <unk> and Lars @-@ Otto Berg do not . The Russian vessels were built between 1808 and 1823 and have been described by <unk> and Sozaev as <unk> @-@ class " rowing frigates " .
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} ----------------------------------------------------------------------------- {- | Module : Numeric.LinearAlgebra.Tests.Instances Copyright : (c) Alberto Ruiz 2008 License : BSD3 Maintainer : Alberto Ruiz Stability : provisional Arbitrary instances for vectors, matrices. -} module Test.Numeric.LinearAlgebra.Tests.Instances( Sq(..), rSq,cSq, Sq2WC(..), rSq2WC,cSq2WC, Rot(..), rRot,cRot, rHer,cHer, WC(..), rWC,cWC, SqWC(..), rSqWC, cSqWC, rSymWC, cSymWC, PosDef(..), rPosDef, cPosDef, Consistent(..), rConsist, cConsist, RM,CM, rM,cM, FM,ZM, fM,zM ) where import System.Random import Control.Monad (replicateM) import Numeric.LinearAlgebra.HMatrix hiding (vector) import Test.QuickCheck (Arbitrary, arbitrary, choose, shrink, sized, vector) import Data.Proxy (Proxy (..)) import GHC.TypeLits import qualified Numeric.LinearAlgebra.Static as Static #if MIN_VERSION_base(4,11,0) import Prelude hiding ((<>)) #endif shrinkListElementwise :: (Arbitrary a) => [a] -> [[a]] shrinkListElementwise [] = [] shrinkListElementwise (x:xs) = [ y:xs | y <- shrink x ] ++ [ x:ys | ys <- shrinkListElementwise xs ] shrinkPair :: (Arbitrary a, Arbitrary b) => (a,b) -> [(a,b)] shrinkPair (a,b) = [ (a,x) | x <- shrink b ] ++ [ (x,b) | x <- shrink a ] chooseDim = sized $ \m -> choose (1,max 1 m) instance (Field a, Arbitrary a) => Arbitrary (Vector a) where arbitrary = do m <- chooseDim l <- vector m return $ fromList l -- shrink any one of the components shrink = map fromList . shrinkListElementwise . toList instance KnownNat n => Arbitrary (Static.R n) where arbitrary = do l <- vector n return (Static.fromList l) where n :: Int n = fromIntegral (natVal (Proxy :: Proxy n)) shrink _v = [] instance (Element a, Arbitrary a) => Arbitrary (Matrix a) where arbitrary = do m <- chooseDim n <- chooseDim l <- vector (m*n) return $ (m><n) l -- shrink any one of the components shrink a = map (rows a >< cols a) . shrinkListElementwise . concat . toLists $ a instance (KnownNat n, KnownNat m) => Arbitrary (Static.L m n) where arbitrary = do l <- vector (m * n) return (Static.fromList l) where m :: Int m = fromIntegral (natVal (Proxy :: Proxy m)) n :: Int n = fromIntegral (natVal (Proxy :: Proxy n)) shrink _mat = [] -- a square matrix newtype (Sq a) = Sq (Matrix a) deriving Show instance (Element a, Arbitrary a) => Arbitrary (Sq a) where arbitrary = do n <- chooseDim l <- vector (n*n) return $ Sq $ (n><n) l shrink (Sq a) = [ Sq b | b <- shrink a ] -- a pair of square matrices newtype (Sq2WC a) = Sq2WC (Matrix a, Matrix a) deriving Show instance (ArbitraryField a, Numeric a) => Arbitrary (Sq2WC a) where arbitrary = do n <- chooseDim l <- vector (n*n) r <- vector (n*n) l' <- makeWC $ (n><n) l r' <- makeWC $ (n><n) r return $ Sq2WC (l', r') where makeWC m = do let (u,_,v) = svd m n = rows m sv' <- replicateM n (choose (1,100)) let s = diag (fromList sv') return $ u <> real s <> tr v -- a unitary matrix newtype (Rot a) = Rot (Matrix a) deriving Show instance (Field a, Arbitrary a) => Arbitrary (Rot a) where arbitrary = do Sq m <- arbitrary let (q,_) = qr m return (Rot q) -- a complex hermitian or real symmetric matrix instance (Field a, Arbitrary a, Num (Vector a)) => Arbitrary (Herm a) where arbitrary = do Sq m <- arbitrary let m' = m/2 return $ sym m' class (Field a, Arbitrary a, Element (RealOf a), Random (RealOf a)) => ArbitraryField a instance ArbitraryField Float instance ArbitraryField (Complex Float) -- a well-conditioned general matrix (the singular values are between 1 and 100) newtype (WC a) = WC (Matrix a) deriving Show instance (Numeric a, ArbitraryField a) => Arbitrary (WC a) where arbitrary = do m <- arbitrary let (u,_,v) = svd m r = rows m c = cols m n = min r c sv' <- replicateM n (choose (1,100)) let s = diagRect 0 (fromList sv') r c return $ WC (u <> real s <> tr v) -- a well-conditioned square matrix (the singular values are between 1 and 100) newtype (SqWC a) = SqWC (Matrix a) deriving Show instance (ArbitraryField a, Numeric a) => Arbitrary (SqWC a) where arbitrary = do Sq m <- arbitrary let (u,_,v) = svd m n = rows m sv' <- replicateM n (choose (1,100)) let s = diag (fromList sv') return $ SqWC (u <> real s <> tr v) -- a positive definite square matrix (the eigenvalues are between 0 and 100) newtype (PosDef a) = PosDef (Matrix a) deriving Show instance (Numeric a, ArbitraryField a, Num (Vector a)) => Arbitrary (PosDef a) where arbitrary = do m <- arbitrary let (_,v) = eigSH m n = rows (unSym m) l <- replicateM n (choose (0,100)) let s = diag (fromList l) p = v <> real s <> tr v return $ PosDef (0.5 * p + 0.5 * tr p) -- a pair of matrices that can be multiplied newtype (Consistent a) = Consistent (Matrix a, Matrix a) deriving Show instance (Field a, Arbitrary a) => Arbitrary (Consistent a) where arbitrary = do n <- chooseDim k <- chooseDim m <- chooseDim la <- vector (n*k) lb <- vector (k*m) return $ Consistent ((n><k) la, (k><m) lb) shrink (Consistent (x,y)) = [ Consistent (u,v) | (u,v) <- shrinkPair (x,y) ] type RM = Matrix Float type CM = Matrix (Complex Float) type FM = Matrix Float type ZM = Matrix (Complex Float) rM m = m :: RM cM m = m :: CM fM m = m :: FM zM m = m :: ZM rHer m = unSym m :: RM cHer m = unSym m :: CM rRot (Rot m) = m :: RM cRot (Rot m) = m :: CM rSq (Sq m) = m :: RM cSq (Sq m) = m :: CM rSq2WC (Sq2WC (a, b)) = (a, b) :: (RM, RM) cSq2WC (Sq2WC (a, b)) = (a, b) :: (CM, CM) rWC (WC m) = m :: RM cWC (WC m) = m :: CM rSqWC (SqWC m) = m :: RM cSqWC (SqWC m) = m :: CM rSymWC (SqWC m) = sym m :: Herm R cSymWC (SqWC m) = sym m :: Herm C rPosDef (PosDef m) = m :: RM cPosDef (PosDef m) = m :: CM rConsist (Consistent (a,b)) = (a,b::RM) cConsist (Consistent (a,b)) = (a,b::CM)
```python from sympy import * init_printing() # For Sympy from IPython.display import display ``` ## Simple Pade form for the Jastrow factor. The value of $A$ is fixed by the cusp condition at $r=0$. ```python A, B, r = symbols('A B r') u = A*r/(1.0 + B*r) - A/B sym_u = Symbol('u') display(Eq(sym_u,u)) ``` ```python # Symbolic derivatives du = diff(u, r) du = simplify(du) sym_du = Symbol('du')/Symbol('dr') display(Eq(sym_du, du)) ddu = simplify(diff(u, r, 2)) sym_ddu = Symbol('d^2')*Symbol('u')/Symbol('dr^2') display(Eq(sym_ddu, ddu)) ``` ```python # Substitute concrete values to evaluate vals = {A:-0.25, B: 0.1, r:1.0} display(Eq(sym_u, u.subs(vals))) display(Eq(sym_du, du.subs(vals))) display(Eq(sym_ddu, ddu.subs(vals))) ``` ```python ```
Require Import Crypto.Specific.Framework.RawCurveParameters. Require Import Crypto.Util.LetIn. (*** Modulus : 2^291 - 19 Base: 24.25 ***) Definition curve : CurveParameters := {| sz := 12%nat; base := 24 + 1/4; bitwidth := 32; s := 2^291; c := [(1, 19)]; carry_chains := Some [seq 0 (pred 12); [0; 1]]%nat; a24 := None; coef_div_modulus := Some 2%nat; goldilocks := None; karatsuba := None; montgomery := false; freeze := Some true; ladderstep := false; mul_code := None; square_code := None; upper_bound_of_exponent_loose := None; upper_bound_of_exponent_tight := None; allowable_bit_widths := None; freeze_extra_allowable_bit_widths := None; modinv_fuel := None |}. Ltac extra_prove_mul_eq _ := idtac. Ltac extra_prove_square_eq _ := idtac.
{-# OPTIONS --safe --experimental-lossy-unification #-} module Cubical.Algebra.ZariskiLattice.BasicOpens where open import Cubical.Foundations.Prelude open import Cubical.Foundations.Function open import Cubical.Foundations.Equiv open import Cubical.Foundations.Isomorphism open import Cubical.Foundations.Univalence open import Cubical.Foundations.HLevels open import Cubical.Foundations.Powerset open import Cubical.Foundations.Transport open import Cubical.Foundations.Structure open import Cubical.Functions.FunExtEquiv import Cubical.Data.Empty as ⊥ open import Cubical.Data.Bool open import Cubical.Data.Nat renaming ( _+_ to _+ℕ_ ; _·_ to _·ℕ_ ; +-comm to +ℕ-comm ; +-assoc to +ℕ-assoc ; ·-assoc to ·ℕ-assoc ; ·-comm to ·ℕ-comm) open import Cubical.Data.Sigma.Base open import Cubical.Data.Sigma.Properties open import Cubical.Data.FinData open import Cubical.Relation.Nullary open import Cubical.Relation.Binary open import Cubical.Relation.Binary.Poset open import Cubical.Algebra.Ring open import Cubical.Algebra.Algebra open import Cubical.Algebra.CommRing open import Cubical.Algebra.CommRing.Localisation.Base open import Cubical.Algebra.CommRing.Localisation.UniversalProperty open import Cubical.Algebra.CommRing.Localisation.InvertingElements open import Cubical.Algebra.CommAlgebra.Base open import Cubical.Algebra.CommAlgebra.Properties open import Cubical.Algebra.CommAlgebra.Localisation open import Cubical.Algebra.RingSolver.ReflectionSolving open import Cubical.Algebra.Semilattice open import Cubical.HITs.SetQuotients as SQ open import Cubical.HITs.PropositionalTruncation as PT open Iso open BinaryRelation open isEquivRel private variable ℓ ℓ' : Level module Presheaf (A' : CommRing ℓ) where open CommRingStr (snd A') renaming (_·_ to _·r_ ; ·-comm to ·r-comm ; ·Assoc to ·rAssoc ; ·Lid to ·rLid ; ·Rid to ·rRid) open Exponentiation A' open CommRingTheory A' open isMultClosedSubset open CommAlgebraStr ⦃...⦄ private A = fst A' A[1/_] : A → CommAlgebra A' ℓ A[1/ x ] = AlgLoc.S⁻¹RAsCommAlg A' ([_ⁿ|n≥0] A' x) (powersFormMultClosedSubset _ _) A[1/_]ˣ : (x : A) → ℙ (fst A[1/ x ]) A[1/ x ]ˣ = (CommAlgebra→CommRing A[1/ x ]) ˣ _≼_ : A → A → Type ℓ x ≼ y = ∃[ n ∈ ℕ ] Σ[ z ∈ A ] x ^ n ≡ z ·r y -- rad(x) ⊆ rad(y) -- ≼ is a pre-order: Refl≼ : isRefl _≼_ Refl≼ x = PT.∣ 1 , 1r , ·r-comm _ _ ∣ Trans≼ : isTrans _≼_ Trans≼ x y z = map2 Trans≼Σ where Trans≼Σ : Σ[ n ∈ ℕ ] Σ[ a ∈ A ] x ^ n ≡ a ·r y → Σ[ n ∈ ℕ ] Σ[ a ∈ A ] y ^ n ≡ a ·r z → Σ[ n ∈ ℕ ] Σ[ a ∈ A ] x ^ n ≡ a ·r z Trans≼Σ (n , a , p) (m , b , q) = n ·ℕ m , (a ^ m ·r b) , path where path : x ^ (n ·ℕ m) ≡ a ^ m ·r b ·r z path = x ^ (n ·ℕ m) ≡⟨ ^-rdist-·ℕ x n m ⟩ (x ^ n) ^ m ≡⟨ cong (_^ m) p ⟩ (a ·r y) ^ m ≡⟨ ^-ldist-· a y m ⟩ a ^ m ·r y ^ m ≡⟨ cong (a ^ m ·r_) q ⟩ a ^ m ·r (b ·r z) ≡⟨ ·rAssoc _ _ _ ⟩ a ^ m ·r b ·r z ∎ R : A → A → Type ℓ R x y = x ≼ y × y ≼ x -- rad(x) ≡ rad(y) RequivRel : isEquivRel R RequivRel .reflexive x = Refl≼ x , Refl≼ x RequivRel .symmetric _ _ Rxy = (Rxy .snd) , (Rxy .fst) RequivRel .transitive _ _ _ Rxy Ryz = Trans≼ _ _ _ (Rxy .fst) (Ryz .fst) , Trans≼ _ _ _ (Ryz .snd) (Rxy .snd) RpropValued : isPropValued R RpropValued x y = isProp× isPropPropTrunc isPropPropTrunc powerIs≽ : (x a : A) → x ∈ ([_ⁿ|n≥0] A' a) → a ≼ x powerIs≽ x a = map powerIs≽Σ where powerIs≽Σ : Σ[ n ∈ ℕ ] (x ≡ a ^ n) → Σ[ n ∈ ℕ ] Σ[ z ∈ A ] (a ^ n ≡ z ·r x) powerIs≽Σ (n , p) = n , 1r , sym p ∙ sym (·rLid _) module ≼ToLoc (x y : A) where private instance _ = snd A[1/ x ] lemma : x ≼ y → y ⋆ 1a ∈ A[1/ x ]ˣ -- y/1 ∈ A[1/x]ˣ lemma = PT.rec (A[1/ x ]ˣ (y ⋆ 1a) .snd) lemmaΣ where path1 : (y z : A) → 1r ·r (y ·r 1r ·r z) ·r 1r ≡ z ·r y path1 = solve A' path2 : (xn : A) → xn ≡ 1r ·r 1r ·r (1r ·r 1r ·r xn) path2 = solve A' lemmaΣ : Σ[ n ∈ ℕ ] Σ[ a ∈ A ] x ^ n ≡ a ·r y → y ⋆ 1a ∈ A[1/ x ]ˣ lemmaΣ (n , z , p) = [ z , (x ^ n) , PT.∣ n , refl ∣ ] -- xⁿ≡zy → y⁻¹ ≡ z/xⁿ , eq/ _ _ ((1r , powersFormMultClosedSubset _ _ .containsOne) , (path1 _ _ ∙∙ sym p ∙∙ path2 _)) module ≼PowerToLoc (x y : A) (x≼y : x ≼ y) where private [yⁿ|n≥0] = [_ⁿ|n≥0] A' y instance _ = snd A[1/ x ] lemma : ∀ (s : A) → s ∈ [yⁿ|n≥0] → s ⋆ 1a ∈ A[1/ x ]ˣ lemma _ s∈[yⁿ|n≥0] = ≼ToLoc.lemma _ _ (Trans≼ _ y _ x≼y (powerIs≽ _ _ s∈[yⁿ|n≥0])) 𝓞ᴰ : A / R → CommAlgebra A' ℓ 𝓞ᴰ = rec→Gpd.fun isGroupoidCommAlgebra (λ a → A[1/ a ]) RCoh LocPathProp where RCoh : ∀ a b → R a b → A[1/ a ] ≡ A[1/ b ] RCoh a b (a≼b , b≼a) = fst (isContrS₁⁻¹R≡S₂⁻¹R (≼PowerToLoc.lemma _ _ b≼a) (≼PowerToLoc.lemma _ _ a≼b)) where open AlgLocTwoSubsets A' ([_ⁿ|n≥0] A' a) (powersFormMultClosedSubset _ _) ([_ⁿ|n≥0] A' b) (powersFormMultClosedSubset _ _) LocPathProp : ∀ a b → isProp (A[1/ a ] ≡ A[1/ b ]) LocPathProp a b = isPropS₁⁻¹R≡S₂⁻¹R where open AlgLocTwoSubsets A' ([_ⁿ|n≥0] A' a) (powersFormMultClosedSubset _ _) ([_ⁿ|n≥0] A' b) (powersFormMultClosedSubset _ _) -- The quotient A/R corresponds to the basic opens of the Zariski topology. -- Multiplication lifts to the quotient and corresponds to intersection -- of basic opens, i.e. we get a meet-semilattice with: _∧/_ : A / R → A / R → A / R _∧/_ = setQuotSymmBinOp (RequivRel .reflexive) (RequivRel .transitive) _·r_ (λ a b → subst (λ x → R (a ·r b) x) (·r-comm a b) (RequivRel .reflexive (a ·r b))) ·r-lcoh where ·r-lcoh-≼ : (x y z : A) → x ≼ y → (x ·r z) ≼ (y ·r z) ·r-lcoh-≼ x y z = map ·r-lcoh-≼Σ where path : (x z a y zn : A) → x ·r z ·r (a ·r y ·r zn) ≡ x ·r zn ·r a ·r (y ·r z) path = solve A' ·r-lcoh-≼Σ : Σ[ n ∈ ℕ ] Σ[ a ∈ A ] x ^ n ≡ a ·r y → Σ[ n ∈ ℕ ] Σ[ a ∈ A ] (x ·r z) ^ n ≡ a ·r (y ·r z) ·r-lcoh-≼Σ (n , a , p) = suc n , (x ·r z ^ n ·r a) , (cong (x ·r z ·r_) (^-ldist-· _ _ _) ∙∙ cong (λ v → x ·r z ·r (v ·r z ^ n)) p ∙∙ path _ _ _ _ _) ·r-lcoh : (x y z : A) → R x y → R (x ·r z) (y ·r z) ·r-lcoh x y z Rxy = ·r-lcoh-≼ x y z (Rxy .fst) , ·r-lcoh-≼ y x z (Rxy .snd) BasicOpens : Semilattice ℓ BasicOpens = makeSemilattice [ 1r ] _∧/_ squash/ (elimProp3 (λ _ _ _ → squash/ _ _) λ _ _ _ → cong [_] (·rAssoc _ _ _)) (elimProp (λ _ → squash/ _ _) λ _ → cong [_] (·rRid _)) (elimProp (λ _ → squash/ _ _) λ _ → cong [_] (·rLid _)) (elimProp2 (λ _ _ → squash/ _ _) λ _ _ → cong [_] (·r-comm _ _)) (elimProp (λ _ → squash/ _ _) λ a → eq/ _ _ -- R a a² (∣ 1 , a , ·rRid _ ∣ , ∣ 2 , 1r , cong (a ·r_) (·rRid a) ∙ sym (·rLid _) ∣)) -- The induced partial order open MeetSemilattice BasicOpens renaming (_≤_ to _≼/_ ; IndPoset to BasicOpensAsPoset) -- coincides with our ≼ ≼/CoincidesWith≼ : ∀ (x y : A) → ([ x ] ≼/ [ y ]) ≡ (x ≼ y) ≼/CoincidesWith≼ x y = [ x ] ≼/ [ y ] -- ≡⟨ refl ⟩ [ x ·r y ] ≡ [ x ] ≡⟨ isoToPath (isEquivRel→effectiveIso RpropValued RequivRel _ _) ⟩ R (x ·r y) x ≡⟨ isoToPath Σ-swap-Iso ⟩ R x (x ·r y) ≡⟨ hPropExt (RpropValued _ _) isPropPropTrunc ·To≼ ≼To· ⟩ x ≼ y ∎ where x≼xy→x≼yΣ : Σ[ n ∈ ℕ ] Σ[ z ∈ A ] x ^ n ≡ z ·r (x ·r y) → Σ[ n ∈ ℕ ] Σ[ z ∈ A ] x ^ n ≡ z ·r y x≼xy→x≼yΣ (n , z , p) = n , (z ·r x) , p ∙ ·rAssoc _ _ _ ·To≼ : R x (x ·r y) → x ≼ y ·To≼ (x≼xy , _) = PT.map x≼xy→x≼yΣ x≼xy x≼y→x≼xyΣ : Σ[ n ∈ ℕ ] Σ[ z ∈ A ] x ^ n ≡ z ·r y → Σ[ n ∈ ℕ ] Σ[ z ∈ A ] x ^ n ≡ z ·r (x ·r y) x≼y→x≼xyΣ (n , z , p) = suc n , z , cong (x ·r_) p ∙ ·-commAssocl _ _ _ ≼To· : x ≼ y → R x ( x ·r y) ≼To· x≼y = PT.map x≼y→x≼xyΣ x≼y , PT.∣ 1 , y , ·rRid _ ∙ ·r-comm _ _ ∣ open IsPoset open PosetStr Refl≼/ : isRefl _≼/_ Refl≼/ = BasicOpensAsPoset .snd .isPoset .is-refl Trans≼/ : isTrans _≼/_ Trans≼/ = BasicOpensAsPoset .snd .isPoset .is-trans -- The restrictions: ρᴰᴬ : (a b : A) → a ≼ b → isContr (CommAlgebraHom A[1/ b ] A[1/ a ]) ρᴰᴬ _ b a≼b = A[1/b]HasUniversalProp _ (≼PowerToLoc.lemma _ _ a≼b) where open AlgLoc A' ([_ⁿ|n≥0] A' b) (powersFormMultClosedSubset _ _) renaming (S⁻¹RHasAlgUniversalProp to A[1/b]HasUniversalProp) ρᴰᴬId : ∀ (a : A) (r : a ≼ a) → ρᴰᴬ a a r .fst ≡ idAlgHom ρᴰᴬId a r = ρᴰᴬ a a r .snd _ ρᴰᴬComp : ∀ (a b c : A) (l : a ≼ b) (m : b ≼ c) → ρᴰᴬ a c (Trans≼ _ _ _ l m) .fst ≡ ρᴰᴬ a b l .fst ∘a ρᴰᴬ b c m .fst ρᴰᴬComp a _ c l m = ρᴰᴬ a c (Trans≼ _ _ _ l m) .snd _ ρᴰ : (x y : A / R) → x ≼/ y → CommAlgebraHom (𝓞ᴰ y) (𝓞ᴰ x) ρᴰ = elimContr2 λ _ _ → isContrΠ λ [a]≼/[b] → ρᴰᴬ _ _ (transport (≼/CoincidesWith≼ _ _) [a]≼/[b]) ρᴰId : ∀ (x : A / R) (r : x ≼/ x) → ρᴰ x x r ≡ idAlgHom ρᴰId = SQ.elimProp (λ _ → isPropΠ (λ _ → isSetAlgebraHom _ _ _ _)) λ a r → ρᴰᴬId a (transport (≼/CoincidesWith≼ _ _) r) ρᴰComp : ∀ (x y z : A / R) (l : x ≼/ y) (m : y ≼/ z) → ρᴰ x z (Trans≼/ _ _ _ l m) ≡ ρᴰ x y l ∘a ρᴰ y z m ρᴰComp = SQ.elimProp3 (λ _ _ _ → isPropΠ2 (λ _ _ → isSetAlgebraHom _ _ _ _)) λ a b c _ _ → sym (ρᴰᴬ a c _ .snd _) ∙ ρᴰᴬComp a b c _ _
lemma arg_bounded: "- pi < arg z \<and> arg z \<le> pi"
[STATEMENT] lemma mult_isor: "x \<le> y \<Longrightarrow> x \<cdot> z \<le> y \<cdot> z" [PROOF STATE] proof (prove) goal (1 subgoal): 1. x \<le> y \<Longrightarrow> x \<cdot> z \<le> y \<cdot> z [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. x \<le> y \<Longrightarrow> x \<cdot> z \<le> y \<cdot> z [PROOF STEP] assume "x \<le> y" [PROOF STATE] proof (state) this: x \<le> y goal (1 subgoal): 1. x \<le> y \<Longrightarrow> x \<cdot> z \<le> y \<cdot> z [PROOF STEP] hence "x + y = y" [PROOF STATE] proof (prove) using this: x \<le> y goal (1 subgoal): 1. x + y = y [PROOF STEP] by (simp add: less_eq_def) [PROOF STATE] proof (state) this: x + y = y goal (1 subgoal): 1. x \<le> y \<Longrightarrow> x \<cdot> z \<le> y \<cdot> z [PROOF STEP] hence "(x + y) \<cdot> z = y \<cdot> z" [PROOF STATE] proof (prove) using this: x + y = y goal (1 subgoal): 1. (x + y) \<cdot> z = y \<cdot> z [PROOF STEP] by simp [PROOF STATE] proof (state) this: (x + y) \<cdot> z = y \<cdot> z goal (1 subgoal): 1. x \<le> y \<Longrightarrow> x \<cdot> z \<le> y \<cdot> z [PROOF STEP] thus "x \<cdot> z \<le> y \<cdot> z" [PROOF STATE] proof (prove) using this: (x + y) \<cdot> z = y \<cdot> z goal (1 subgoal): 1. x \<cdot> z \<le> y \<cdot> z [PROOF STEP] by (simp add: less_eq_def) [PROOF STATE] proof (state) this: x \<cdot> z \<le> y \<cdot> z goal: No subgoals! [PROOF STEP] qed
[STATEMENT] lemma prime_multiplicity_gt_zero_iff: "prime_elem p \<Longrightarrow> x \<noteq> 0 \<Longrightarrow> multiplicity p x > 0 \<longleftrightarrow> p dvd x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>prime_elem p; x \<noteq> (0::'a)\<rbrakk> \<Longrightarrow> (0 < multiplicity p x) = (p dvd x) [PROOF STEP] by (rule multiplicity_gt_zero_iff) simp_all
function val=calcGAE(xTrue,xEst,is3D) %%CALCGAE Compute the scalar geometric average error (GAE). Unlike the % RMSE, it is not dominated by large individual terms. % %INPUTS: xTrue The truth data. This is either an xDimXNumSamples matrix or % an xDimXNXnumSamples matrix. The latter formulation is % useful when the MSE over multiple Monte Carlo runs of an % entire length-N track is desired. In the first formulation, % we take N=1. Alternatively, if the same true value is used % for all numSamples, then xTrue can just be an xDimXN matrix. % Alternatively, if xTrue is the same for all numSamples and % all N, then just an xDimX1 matrix can be passed. N and % numSamples are inferred from xEst. % xEst An xDimXnumSamples set of estimates or an xDimXNXnumSamples % set of estimates (if values at N times are desired). % is3D An optional indicating that xEst is 3D. This is only used if % xEst is a matrix. In such an instance, there is an ambiguity % whether xEst is truly 2D, so N=1, or whether numSamples=1 % and xEst is 3D with the third dimension being 1. If this % parameter is omitted or an empty matrix is passed, it is % assumed that N=1. % %OUTPUTS: val The 1XN set of scalar GAE values. % %The GAE is given in Equation 3 in [1]. % %EXAMPLE: %For a Gaussian random vector, the root-trace of the covariance matrix is %the RMSE. The RMSE is larger than the average Euclidean error, which is %also larger than the geometric average error % R=[28, 4, 10; % 4, 22, 16; % 10, 16, 16];%The covariance matrix. % xTrue=[10;-20;30]; % numRuns=100000; % xEst=GaussianD.rand(numRuns,xTrue,R); % valRMSE=rootTrace=sqrt(trace(R)) % valAEE=calcAEE(xTrue,xEst) % valGAE=calcGAE(xTrue,xEst) % %REFERENCES: %[1] X. R. Li and Z. Zhao, "Measures of performance for evaluation of % estimators and filters," in Proceedings of SPIE: Conference on Signal % and Data processing of Small Targets, vol. 4473, San Diego, CA, 29 % Jul. 2001, pp. 530-541. % %February 2017 David F. Crouse, Naval Research Laboratory, Washington D.C. %(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release. if(nargin<3||isempty(is3D)) is3D=false; end xDim=size(xEst,1); if(ismatrix(xEst)&&is3D==false) N=1; numSamples=size(xEst,2); xEst=reshape(xEst,[xDim,1,numSamples]); if(size(xTrue,2)==1) %If the true values are the same for all samples. xTrue=repmat(xTrue,[1,1,numSamples]); else xTrue=reshape(xTrue,[xDim,1,numSamples]); end else N=size(xEst,2); numSamples=size(xEst,3); if(ismatrix(xTrue)) if(size(xTrue,2)==1) %If the true values are the same for all samples and for all N. xTrue=repmat(xTrue,[1,N,numSamples]); else %If the true values are the same for all samples. xTrue=repmat(xTrue,[1,1,numSamples]); end end end val=zeros(1,N); for k=1:N val(k)=exp((1/(2*numSamples))*sum(log(sum((xEst(:,k,:)-xTrue(:,k,:)).^2,1)))); end end %LICENSE: % %The source code is in the public domain and not licensed or under %copyright. The information and software may be used freely by the public. %As required by 17 U.S.C. 403, third parties producing copyrighted works %consisting predominantly of the material produced by U.S. government %agencies must provide notice with such work(s) identifying the U.S. %Government material incorporated and stating that such material is not %subject to copyright protection. % %Derived works shall not identify themselves in a manner that implies an %endorsement by or an affiliation with the Naval Research Laboratory. % %RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE %SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL %RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS %OF RECIPIENT IN THE USE OF THE SOFTWARE.
#!/usr/bin/env Rscript ######################################### # dada2_errmodels_pacbio # # DADA2 sequence error estimation based on files in a given folder # Assumes PacBio reads, i.e. uses errorEstimationFunction = PacBioErrfun # # Author: Jeanette Tångrot ([email protected]), Daniel Lundin suppressPackageStartupMessages(library(optparse)) VERSION = 1.0 # Get arguments option_list = list( make_option( c('--filterDir'), type='character', default='dada2_filtered', help='Directory containing quality filtered reads to estimate sequence errors from, default "dada2_filtered".' ), make_option( c('--prefix'), type='character', default='./', help='Prefix for name of rds file with DADA2 error model. Can include a path to another folder. Default: "./"' ), make_option( c('--nbases'), type='character', default=1e8, help='Minimum number of total bases to use for error estimation, please see DADA2 documentation for details. Default: 1e8' ), make_option( c("-v", "--verbose"), action="store_true", default=FALSE, help="Print progress messages." ), make_option( c("--version"), action="store_true", default=FALSE, help="Print version of script and DADA2 library." ) ) opt = parse_args(OptionParser(option_list=option_list)) if ( opt$version ) { write(sprintf("dada2_errmodels_pacbio.r version %s, DADA2 version %s", VERSION, packageVersion('dada2')), stderr()) q('no', 0) } # Check options if ( ! file_test("-d", opt$filterDir) ) { stop( sprintf("Cannot find folder with filtered files: %s. See help (-h)\n",opt$filterDir) ) } # Function for log messages logmsg = function(msg, llevel='INFO') { if ( opt$verbose ) { write( sprintf("%s: %s: %s", llevel, format(Sys.time(), "%Y-%m-%d %H:%M:%S"), msg), stderr() ) } } logmsg( sprintf( "Sequence error estimation with DADA2 learnErrors and PacBioErrFun." ) ) # Load DADA2 library here, to avoid --help and --version taking so long suppressPackageStartupMessages(library(dada2)) suppressPackageStartupMessages(library(ShortRead)) # Do the error estimation, save rds for error profile files=list.files(opt$filterDir,full.names=T) logmsg( sprintf("Using files: %s", files)) err <- learnErrors(files, errorEstimationFunction=PacBioErrfun, multithread=TRUE, randomize=FALSE, verbose=opt$verbose, nbases=as.double(opt$nbases)) saveRDS(err,sprintf('%serr.rds', opt$prefix)) logmsg(sprintf("Finished error estimation"))
Require Import Crypto.Arithmetic.PrimeFieldTheorems. Require Import Crypto.Specific.solinas32_2e322m2e161m1_12limbs.Synthesis. (* TODO : change this to field once field isomorphism happens *) Definition freeze : { freeze : feBW_tight -> feBW_limbwidths | forall a, phiBW_limbwidths (freeze a) = phiBW_tight a }. Proof. Set Ltac Profiling. Time synthesize_freeze (). Show Ltac Profile. Time Defined. Print Assumptions freeze.
#!/usr/bin/env Rscript #CALL: Rscript rapidNorm.R <configFile> <AnnotationFile> <OutputFolder> <LengthRestrictionIfAny> #load libraries library("scales") ####FUNCTIONS#### readStatistics <- function(path){ full=paste(path,"/Statistics.dat",sep="") stats=read.table(full,header=T,sep=" ",stringsAsFactors=FALSE) return(stats) } readTotal <- function(path){ full=paste(path,"/TotalReads.dat",sep="") total=read.table(full,header=F,sep=" ") return(total$V1) } #This function compute the region lengths from the Annotation file given #to the RAPID pipeline and used for intersection computeRegionLengths <- function(data){ #process names(data)=c("chr","start","end","label","type","strand") #compute lengths singleLengths=apply(data,1,function(x){return(as.numeric(x[3])-as.numeric(x[2])+1)}) dummyDF=data.frame(label=data$label,lens=singleLengths) res=by(dummyDF,dummyDF$label,function(x){sum(x$lens)}) return(data.frame(region=as.character(names(res)),lens=as.numeric(res))) } addLengthColumnToStats <- function(Stats,lens){ Lengths=computeRegionLengths(lens) for(i in 1:length(Stats)){ df=Stats[[i]] Stats[[i]] = merge(df,Lengths,by="region") } return(Stats) } getMax <- function(Total){ return(max(unlist(Total))) } normalizeEntries <- function(Stats,oldTotal,adjustForBackground=TRUE,normalizeByLength=TRUE, normalizeByDESeq=FALSE){ #the default is to adjust the counts for any small RNA background counts obtained and for region length #Note: that if the 3rd column of the config file has the entry none, then no count is substracted Total=oldTotal if(adjustForBackground){ for (i in 1:length(Stats)){ Total[i]=Total[[i]]-countBackgroundReads(Stats[[i]],conf$background[i]) } } if(normalizeByDESeq){ library("DESeq2") newList=Stats readData=as.data.frame(Stats[[1]]$region) for(i in 1:length(Stats)){ readData=cbind(readData,Stats[[i]]$reads) } colnames(readData)=c("Regions",c(1:length(Stats))) readData$Regions=NULL sizes=estimateSizeFactorsForMatrix(readData) for (i in 1:length(Stats)){ newList[[i]]$reads_norm=round(newList[[i]]$reads/sizes[i],digits = 0) newList[[i]]$asreads_norm=round(newList[[i]]$antisenseReads/sizes[i],digits = 0) newList[[i]]$asratio_norm=round(newList[[i]]$asreads_norm/newList[[i]]$reads_norm,digits=2) newList[[i]]$asratio_norm[is.na(newList[[i]]$asratio_norm)]=0 newList[[i]]$asratio_norm[is.infinite(newList[[i]]$asratio_norm)]=0 if(normalizeByLength){ newList[[i]]$reads_avg=round( (newList[[i]]$reads_norm/newList[[i]]$lens),digits=3) } newList[[i]]$RPK=(newList[[i]]$reads_norm/newList[[i]]$lens)*1000 newList[[i]]$TPM=round(newList[[i]]$RPK/(sum(newList[[i]]$RPK)/1e+06), digits = 3) newList[[i]]$RPK=NULL } } else { Max=getMax(Total) newList=Stats for (i in 1:length(Stats)){ newList[[i]]$reads_norm=round(newList[[i]]$reads*(Max/Total[[i]]),digits=0) newList[[i]]$asreads_norm=round(newList[[i]]$antisenseReads*(Max/Total[[i]]),digits=0) newList[[i]]$asratio_norm=round(newList[[i]]$asreads_norm/newList[[i]]$reads_norm,digits=2) newList[[i]]$asratio_norm[is.na(newList[[i]]$asratio_norm)]=0 newList[[i]]$asratio_norm[is.infinite(newList[[i]]$asratio_norm)]=0 if(normalizeByLength){ newList[[i]]$reads_avg=round( (newList[[i]]$reads_norm/newList[[i]]$lens),digits=3) } newList[[i]]$RPK=(newList[[i]]$reads_norm/newList[[i]]$lens)*1000 newList[[i]]$TPM=round(newList[[i]]$RPK/(sum(newList[[i]]$RPK)/1e+06),digits = 3) newList[[i]]$RPK=NULL } } return(newList) } #this function gets as input a string with region names. The total read count of these regions #will be returned. countBackgroundReads <- function(Stats,string){ if(string=="none"){ return(c(0)) } else{ entries=unlist(strsplit(string, ",")) return(sum(subset(Stats,region %in% entries)$reads)) } } createPlottingData <- function(Stats,conf){ rows=nrow(Stats[[1]]) numDatasets=length(Stats) readCounts=rep(Stats[[1]]$reads,numDatasets) readCountsNormTPM=rep(Stats[[1]]$TPM,numDatasets) readCountsNorm=rep(Stats[[1]]$reads_norm,numDatasets) ASreadCountsNorm=rep(Stats[[1]]$asreads_norm,numDatasets) readCountsAvg=rep(Stats[[1]]$reads_avg,numDatasets) #ASratio=rep(Stats[[1]]$ASratio,numDatasets) ASratioNorm=rep(Stats[[1]]$asratio_norm,numDatasets) names=rep(conf$name[1],numDatasets*rows) for(i in 1:(numDatasets-1)){ readCounts[(i*rows+1):((i+1)*rows)] = Stats[[i+1]]$reads readCountsNormTPM[(i*rows+1):((i+1)*rows)] = Stats[[i+1]]$TPM readCountsNorm[(i*rows+1):((i+1)*rows)] = Stats[[i+1]]$reads_norm ASreadCountsNorm[(i*rows+1):((i+1)*rows)] = Stats[[i+1]]$asreads_norm readCountsAvg[(i*rows+1):((i+1)*rows)] = Stats[[i+1]]$reads_avg #ASratio[(i*rows+1):((i+1)*rows)] = Stats[[i+1]]$ASratio ASratioNorm[(i*rows+1):((i+1)*rows)] = Stats[[i+1]]$asratio_norm names[(i*rows+1):((i+1)*rows)] = rep(conf$name[i+1],rows) } df=data.frame(region = rep(Stats[[1]]$region,numDatasets), readCounts=readCounts, readCountsNormTPM=readCountsNormTPM, readCountsNorm=readCountsNorm, readCountsAvg=readCountsAvg, ASreadCountsNorm=ASreadCountsNorm, ASratioNorm=ASratioNorm, samples=names) return(df) } ####DONE FUNCTIONS#### args <- commandArgs(trailingOnly = TRUE) config=args[1] annot=args[2] out=args[3] useDEseq=args[4] restrictLength=args[5] #load datasets conf=read.table(config,header=T,sep="\t",stringsAsFactors=FALSE) lens=read.table(annot,header=F,stringsAsFactors=FALSE) names(lens)=c("chr","start","end","region","type","strand") Stats=lapply(conf$location,readStatistics) Total=lapply(conf$location,readTotal) #check if variable is defined then updated Stats values if(!is.na(restrictLength)){ # update reads column in each Stats entry to the sum of the counts # in the columns of given read counts restrictPattern=gsub(',','|',restrictLength) #show(paste(restrictPattern)) for (i in 1:length(Stats)){ indices=grep(restrictPattern,names(Stats[[i]])) negindices=indices[-c(1:(length(indices)/2))] #show(paste(indices)) if(length(indices) > 0){ Stats[[i]]$reads=apply(Stats[[i]][,indices],1,sum) if(length(negindices)>1){ Stats[[i]]$antisenseReads=apply(Stats[[i]][,negindices],1,sum) } else { Stats[[i]]$antisenseReads=Stats[[i]][,negindices] } } } } #add length column Stats=addLengthColumnToStats(Stats,lens) #normalize read counts if(useDEseq){ normalized=normalizeEntries(Stats,Total,normalizeByDESeq=TRUE) } else { normalized=normalizeEntries(Stats,Total,normalizeByDESeq=FALSE) } allowed= unique(subset(lens,type == "region")$region) #Filter only the non-background regions. Also enables to use different bed files while using rapidStats, although it is not advised. normalizedSub = normalized for(i in 1:length(normalized)){ normalizedSub[[i]]=subset(normalized[[i]], region %in% allowed) } df=createPlottingData(normalizedSub,conf) #save data.frame in output folder write.table(subset(df,region %in% allowed),paste(out,"NormalizedValues.dat",sep=""),quote=F,row.names=F,sep="\t")
Spermonde Archipelago is group of islands spread out along Makassar, South Sulawesi, Indonesia. These islands are rich of biodiversity, such as Clown fish (Nemo), anemones, nudibrach, sharks, dolphins, and colourful reefs. Most of all islands are atol. Some of those islands are; Samalona Island, Kodingareng Keke Island, Kapoposang Island, Lanyukan Island, Kodingareng Lompo Island, Barang Lompo Island, Barang Caddi Island, Kayangan Island, Lae-lae Island, Badi Island, and many more. The nearest beautiful island from the city of Makassar is Samalona Island. It only needs 15 minutes trip from Makassar to Samalona Island.
Formal statement is: lemma (in perfect_space) UNIV_not_singleton: "UNIV \<noteq> {x}" for x::'a Informal statement is: In a perfect space, the whole space is not a singleton.
function _default_tween_creator() # println("Pool: used default tween creator") Tween() end mutable struct TweenPool tweens::Array{AbstractTween,1} creator::Function # f() -> AbstractTween function TweenPool(creator::Function = _default_tween_creator) o = new() o.tweens = Array{AbstractTween,1}() o.creator = creator o end end function count(pool::TweenPool) length(pool.tweens) end function get_from!(pool::TweenPool) tween = if count(pool) == 0 pool.creator() else pop!(pool.tweens) end reset!(tween) tween end function put_to!(pool::TweenPool, tween::AbstractTween) push!(pool.tweens, tween) end
When you smell Cows cow dung, think Essence of Davis. Not currently available in stores. An odors odor naturally occurring in the vicinity of Tercero, but on a hot summer night anywhere in town is fair game. West Davis is hit particularly bad, where people have been known to quit smoking rather than brave the outside stench. For a second opinion on the matter: I live in West Davis, and all I ever smell is flowers and trees. Quitting smoking rather than braving the outside stench is totally ridiculous. There are towns that smell like sh.., but Davis is NOT one of them! Users/SteveDavison Excrement is not the only Essence of Davis there is, or ever has been. Current UCD students are clueless about this, but anyone who grew up in or has lived in Davis for more than a few years remembers the smell of tomatoes in the air in the fall, especially when the Hunt Wesson Plant Hunt Cannery was open for business. The Davis Enterprise Enterprise columnist Bob Dunning tries to wax poetic about the smell of tomato soup each September in one of his columns. Folks who live around Sudwerk will recognize the distinct smell of brewing beer. Some find it pleasant, others not so much. Before I moved here I was under the impression that this whole town reeked of shit, but with the exception of the Tercero area that has turned out not to be the case at all. Users/DanMasiel 20041212 14:27:36 nbsp I remember those tomato soup days. I spent most of the summer with a craving for tomato soup. I havent decided if I miss the big tomato spills that happened several times each summer when the huge tomato trucks would take turns too sharply. Users/BevSykes 20050202 14:02:47 nbsp When I lived in Healdsburg, a little town by Santa Rosa in Sonoma County, we called it Sonoma Aroma. Users/SummerSong 20050226 10:06:59 nbsp Dairy to be relocated to new equestrian center location. Anyone know when this is supposed to happen? Users/JaimeRaba 20050408 23:58:59 nbsp the dairy is going to be relocated? lol, and this will happen AFTER i move out of tercero this year Users/PatrickSing 20051206 11:31:07 nbsp The Equestrian Center is not moving, unfortunately. It WAS going to move out past Russell Ranch Wildlife Area Russell Ranch (on Russell Russell Blvd.) to a huge 75 or so acre lot... Users/StaceyGalbreath 20060404 21:38:23 nbsp Occasionally I detect it in front of the ARC, if the wind is blowing just right. Not strong enough to be really unpleasant, though. Users/NicholasCorwin 20060505 22:10:45 nbsp I dunno, theres something kinda comforting about having your windows down when you come back into Davis from being elsewhere. Usually my reaction, is sniff smells like home. Haha. Users/JulieEickhof 20070608 12:49:44 nbsp The cows just arent that bad. When the pig barn was located right next to EUII (now Kemper Hall)... now THAT was some smelly shit. I got used to the cow smell pretty quickly, but I never did get used to the pig smell. Yuk. Users/NicoleTheWonderNerd 20070608 15:51:01 nbsp I dont think its too bad either...I might be saying that though because I have lived in Davis all my life and am used to it. Nothing says summer like having the Delta Breeze with the essance of herbivore. Users/MyaBrn 20090924 15:17:40 nbsp definitely detectable on the way into Aggie Stadium. Consider it a Home Field Advantage. Users/LaFrance 20120416 09:52:39 nbsp chose davis. people in high school calc class kept saying, why davis? what, you like cows? you like the smell? for months x__x came to davis. did not see any cows on my informal tour or during orientation. did not see any cows until october, actually. i live in segundo i dont smell any cows unless i visit my friends in tercero. and even tercero isnt THAT bad... its madness that davis has a reputation for smelling like cows... because, honestly, i see infinitely more cows on that lovely 5 north on the way up to davis... i get anywhere near davis and it stops. Users/MacMoore
[GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 a : ℤ b : ℕ hb : b ≠ 0 ⊢ toNat a < b ↔ a < ↑b [PROOFSTEP] rw [← toNat_lt_toNat, toNat_coe_nat] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 a : ℤ b : ℕ hb : b ≠ 0 ⊢ 0 < ↑b [PROOFSTEP] exact coe_nat_pos.2 hb.bot_lt [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : NonAssocRing α m : ℤ ⊢ ∀ (n : ℤ), ↑(0 * n) = ↑0 * ↑n [PROOFSTEP] simp [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : NonAssocRing α m k : ℤ x✝ : 0 ≤ k ih : ∀ (n : ℤ), ↑(k * n) = ↑k * ↑n n : ℤ ⊢ ↑((k + 1) * n) = ↑(k + 1) * ↑n [PROOFSTEP] simp [add_mul, ih] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : NonAssocRing α m k : ℤ x✝ : k ≤ 0 ih : ∀ (n : ℤ), ↑(k * n) = ↑k * ↑n n : ℤ ⊢ ↑((k - 1) * n) = ↑(k - 1) * ↑n [PROOFSTEP] simp [sub_mul, ih] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : NonAssocRing α n : ℕ x : α ⊢ Commute (↑↑n) x [PROOFSTEP] simpa using n.cast_commute x [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : NonAssocRing α n : ℕ x : α ⊢ Commute (↑-[n+1]) x [PROOFSTEP] simpa only [cast_negSucc, Commute.neg_left_iff, Commute.neg_right_iff] using (n + 1).cast_commute (-x) [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : OrderedRing α ⊢ Monotone fun x => ↑x [PROOFSTEP] intro m n h [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : OrderedRing α m n : ℤ h : m ≤ n ⊢ (fun x => ↑x) m ≤ (fun x => ↑x) n [PROOFSTEP] rw [← sub_nonneg] at h [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : OrderedRing α m n : ℤ h✝ : m ≤ n h : 0 ≤ n - m ⊢ (fun x => ↑x) m ≤ (fun x => ↑x) n [PROOFSTEP] lift n - m to ℕ using h with k hk [GOAL] case intro F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : OrderedRing α m n : ℤ h : m ≤ n k : ℕ hk : ↑k = n - m ⊢ ↑m ≤ ↑n [PROOFSTEP] rw [← sub_nonneg, ← cast_sub, ← hk, cast_ofNat] [GOAL] case intro F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : OrderedRing α m n : ℤ h : m ≤ n k : ℕ hk : ↑k = n - m ⊢ 0 ≤ ↑k [PROOFSTEP] exact k.cast_nonneg [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : OrderedRing α inst✝ : Nontrivial α n : ℕ ⊢ 0 ≤ ↑↑n ↔ 0 ≤ ↑n [PROOFSTEP] simp [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : OrderedRing α inst✝ : Nontrivial α n : ℕ ⊢ 0 ≤ ↑-[n+1] ↔ 0 ≤ -[n+1] [PROOFSTEP] have : -(n : α) < 1 := lt_of_le_of_lt (by simp) zero_lt_one [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : OrderedRing α inst✝ : Nontrivial α n : ℕ ⊢ -↑n ≤ 0 [PROOFSTEP] simp [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : OrderedRing α inst✝ : Nontrivial α n : ℕ this : -↑n < 1 ⊢ 0 ≤ ↑-[n+1] ↔ 0 ≤ -[n+1] [PROOFSTEP] simpa [(negSucc_lt_zero n).not_le, ← sub_eq_add_neg, le_neg] using this.not_le [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : OrderedRing α inst✝ : Nontrivial α m n : ℤ ⊢ ↑m ≤ ↑n ↔ m ≤ n [PROOFSTEP] rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : OrderedRing α inst✝ : Nontrivial α n : ℤ ⊢ ↑n ≤ 0 ↔ n ≤ 0 [PROOFSTEP] rw [← cast_zero, cast_le] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : OrderedRing α inst✝ : Nontrivial α n : ℤ ⊢ 0 < ↑n ↔ 0 < n [PROOFSTEP] rw [← cast_zero, cast_lt] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : OrderedRing α inst✝ : Nontrivial α n : ℤ ⊢ ↑n < 0 ↔ n < 0 [PROOFSTEP] rw [← cast_zero, cast_lt] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b n : ℤ ⊢ ↑|a| = |↑a| [PROOFSTEP] simp [abs_eq_max_neg] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b n : ℤ h : 0 < a ⊢ 1 ≤ ↑a [PROOFSTEP] exact_mod_cast Int.add_one_le_of_lt h [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b n : ℤ h : a < 0 ⊢ ↑a ≤ -1 [PROOFSTEP] rw [← Int.cast_one, ← Int.cast_neg, cast_le] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b n : ℤ h : a < 0 ⊢ a ≤ -1 [PROOFSTEP] exact Int.le_sub_one_of_lt h [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b n : ℤ x : α hx : |x| ≤ 1 ⊢ 0 ≤ ↑n * x + ↑n * ↑n [PROOFSTEP] have hnx : 0 < n → 0 ≤ x + n := fun hn => by have := _root_.add_le_add (neg_le_of_abs_le hx) (cast_one_le_of_pos hn) rwa [add_left_neg] at this [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b n : ℤ x : α hx : |x| ≤ 1 hn : 0 < n ⊢ 0 ≤ x + ↑n [PROOFSTEP] have := _root_.add_le_add (neg_le_of_abs_le hx) (cast_one_le_of_pos hn) [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b n : ℤ x : α hx : |x| ≤ 1 hn : 0 < n this : -1 + 1 ≤ x + ↑n ⊢ 0 ≤ x + ↑n [PROOFSTEP] rwa [add_left_neg] at this [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b n : ℤ x : α hx : |x| ≤ 1 hnx : 0 < n → 0 ≤ x + ↑n ⊢ 0 ≤ ↑n * x + ↑n * ↑n [PROOFSTEP] have hnx' : n < 0 → x + n ≤ 0 := fun hn => by have := _root_.add_le_add (le_of_abs_le hx) (cast_le_neg_one_of_neg hn) rwa [add_right_neg] at this [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b n : ℤ x : α hx : |x| ≤ 1 hnx : 0 < n → 0 ≤ x + ↑n hn : n < 0 ⊢ x + ↑n ≤ 0 [PROOFSTEP] have := _root_.add_le_add (le_of_abs_le hx) (cast_le_neg_one_of_neg hn) [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b n : ℤ x : α hx : |x| ≤ 1 hnx : 0 < n → 0 ≤ x + ↑n hn : n < 0 this : x + ↑n ≤ 1 + -1 ⊢ x + ↑n ≤ 0 [PROOFSTEP] rwa [add_right_neg] at this [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b n : ℤ x : α hx : |x| ≤ 1 hnx : 0 < n → 0 ≤ x + ↑n hnx' : n < 0 → x + ↑n ≤ 0 ⊢ 0 ≤ ↑n * x + ↑n * ↑n [PROOFSTEP] rw [← mul_add, mul_nonneg_iff] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b n : ℤ x : α hx : |x| ≤ 1 hnx : 0 < n → 0 ≤ x + ↑n hnx' : n < 0 → x + ↑n ≤ 0 ⊢ 0 ≤ ↑n ∧ 0 ≤ x + ↑n ∨ ↑n ≤ 0 ∧ x + ↑n ≤ 0 [PROOFSTEP] rcases lt_trichotomy n 0 with (h | rfl | h) [GOAL] case inl F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b n : ℤ x : α hx : |x| ≤ 1 hnx : 0 < n → 0 ≤ x + ↑n hnx' : n < 0 → x + ↑n ≤ 0 h : n < 0 ⊢ 0 ≤ ↑n ∧ 0 ≤ x + ↑n ∨ ↑n ≤ 0 ∧ x + ↑n ≤ 0 [PROOFSTEP] exact Or.inr ⟨by exact_mod_cast h.le, hnx' h⟩ [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b n : ℤ x : α hx : |x| ≤ 1 hnx : 0 < n → 0 ≤ x + ↑n hnx' : n < 0 → x + ↑n ≤ 0 h : n < 0 ⊢ ↑n ≤ 0 [PROOFSTEP] exact_mod_cast h.le [GOAL] case inr.inl F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b : ℤ x : α hx : |x| ≤ 1 hnx : 0 < 0 → 0 ≤ x + ↑0 hnx' : 0 < 0 → x + ↑0 ≤ 0 ⊢ 0 ≤ ↑0 ∧ 0 ≤ x + ↑0 ∨ ↑0 ≤ 0 ∧ x + ↑0 ≤ 0 [PROOFSTEP] simp [le_total 0 x] [GOAL] case inr.inr F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b n : ℤ x : α hx : |x| ≤ 1 hnx : 0 < n → 0 ≤ x + ↑n hnx' : n < 0 → x + ↑n ≤ 0 h : 0 < n ⊢ 0 ≤ ↑n ∧ 0 ≤ x + ↑n ∨ ↑n ≤ 0 ∧ x + ↑n ≤ 0 [PROOFSTEP] exact Or.inl ⟨by exact_mod_cast h.le, hnx h⟩ [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b n : ℤ x : α hx : |x| ≤ 1 hnx : 0 < n → 0 ≤ x + ↑n hnx' : n < 0 → x + ↑n ≤ 0 h : 0 < n ⊢ 0 ≤ ↑n [PROOFSTEP] exact_mod_cast h.le [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b n : ℤ ⊢ ↑(natAbs n) = ↑|n| [PROOFSTEP] cases n [GOAL] case ofNat F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b : ℤ a✝ : ℕ ⊢ ↑(natAbs (ofNat a✝)) = ↑|ofNat a✝| [PROOFSTEP] simp [GOAL] case negSucc F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : LinearOrderedRing α a b : ℤ a✝ : ℕ ⊢ ↑(natAbs -[a✝+1]) = ↑|-[a✝+1]| [PROOFSTEP] rw [abs_eq_natAbs, natAbs_negSucc, cast_succ, cast_ofNat, cast_succ] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 A : Type u_5 inst✝ : AddGroupWithOne A f : ℤ →+ A h1 : ↑f 1 = 1 ⊢ ↑f 1 = ↑(castAddHom A) 1 [PROOFSTEP] simp [h1] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 M : Type u_5 inst✝ : Monoid M f g : ℤ →* M h_neg_one : ↑f (-1) = ↑g (-1) h_nat : comp f ↑ofNatHom = comp g ↑ofNatHom ⊢ f = g [PROOFSTEP] ext (x | x) [GOAL] case h.ofNat F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 M : Type u_5 inst✝ : Monoid M f g : ℤ →* M h_neg_one : ↑f (-1) = ↑g (-1) h_nat : comp f ↑ofNatHom = comp g ↑ofNatHom x : ℕ ⊢ ↑f (ofNat x) = ↑g (ofNat x) [PROOFSTEP] exact (FunLike.congr_fun h_nat x : _) [GOAL] case h.negSucc F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 M : Type u_5 inst✝ : Monoid M f g : ℤ →* M h_neg_one : ↑f (-1) = ↑g (-1) h_nat : comp f ↑ofNatHom = comp g ↑ofNatHom x : ℕ ⊢ ↑f -[x+1] = ↑g -[x+1] [PROOFSTEP] rw [Int.negSucc_eq, ← neg_one_mul, f.map_mul, g.map_mul] [GOAL] case h.negSucc F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 M : Type u_5 inst✝ : Monoid M f g : ℤ →* M h_neg_one : ↑f (-1) = ↑g (-1) h_nat : comp f ↑ofNatHom = comp g ↑ofNatHom x : ℕ ⊢ ↑f (-1) * ↑f (↑x + 1) = ↑g (-1) * ↑g (↑x + 1) [PROOFSTEP] congr 1 [GOAL] case h.negSucc.e_a F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 M : Type u_5 inst✝ : Monoid M f g : ℤ →* M h_neg_one : ↑f (-1) = ↑g (-1) h_nat : comp f ↑ofNatHom = comp g ↑ofNatHom x : ℕ ⊢ ↑f (↑x + 1) = ↑g (↑x + 1) [PROOFSTEP] exact_mod_cast (FunLike.congr_fun h_nat (x + 1) : _)
{- This second-order signature was created from the following second-order syntax description: syntax Lens | L type S : 0-ary A : 0-ary term get : S -> A put : S A -> S theory (PG) s : S a : A |> get (put (s, a)) = a (GP) s : S |> put (s, get(s)) = s (PP) s : S a b : A |> put (put(s, a), b) = put (s, a) -} module Lens.Signature where open import SOAS.Context -- Type declaration data LT : Set where S : LT A : LT open import SOAS.Syntax.Signature LT public open import SOAS.Syntax.Build LT public -- Operator symbols data Lₒ : Set where getₒ putₒ : Lₒ -- Term signature L:Sig : Signature Lₒ L:Sig = sig λ { getₒ → (⊢₀ S) ⟼₁ A ; putₒ → (⊢₀ S) , (⊢₀ A) ⟼₂ S } open Signature L:Sig public
Formal statement is: lemma open_imp_locally_connected: fixes S :: "'a :: real_normed_vector set" shows "open S \<Longrightarrow> locally connected S" Informal statement is: Any open set is locally connected.
## $ \nabla f \iff \text{ 공간 미분}$ ## $ \overset{\cdot}{x} \iff \text{ 시간 미분}$ ## $ # Total Derivative > ### $$ df \begin{cases} \lim\limits_{\Delta x \to 0\\\Delta y \to 0} \Delta f \\ \lim\limits_{\Delta x \to 0\\\Delta y \to 0} f(x+\Delta x , y+\Delta y) - f(x,y) \\ \lim\limits_{\Delta x \to 0\\\Delta y \to 0} f(x+\Delta x , y+\Delta y) - \big( - f(x, y + \Delta y) + f(x+\Delta y, y)\big) - f(x,y,z) \\ \lim\limits_{\Delta x \to 0\\\Delta y \to 0} f(x+\Delta x , y+\Delta y) - f(x, y + \Delta y) + f(x+\Delta y, y)\big) - f(x,y,z) \\ \lim\limits_{\Delta x \to 0\\\Delta y \to 0} \frac{f(x+\Delta x , y+\Delta y) - f(x, y + \Delta y)}{\Delta x}\Delta x + \frac{f(x+\Delta y, y)\big) - f(x,y,z)}{\Delta y}\Delta y \\ \therefore f_x(x,y)dx + f_y(x,y)dy\\ \therefore \frac{df(x,y)}{dx}dx + \frac{df(x,y)}{dy}dy \\ \therefore \frac{d}{dx}f(x,y)dx + \frac{d}{dy}f(x,y)dy \\ \therefore \;<\frac{d}{dx}f(x,y), \frac{d}{dy}f(x,y)> \;\cdot < dx, dy > \\ \therefore \;<\frac{d}{dx}, \frac{d}{dy}>f(x,y) \;\cdot < dx, dy > \\ \end{cases}$$ > ### Del , nabla >> ### $ \nabla = \begin {bmatrix} \frac{\partial}{\partial x_0},& \frac{\partial}{\partial x_1},& \frac{\partial}{\partial x_2},&... \end{bmatrix}$ >>> ### $ \nabla \; f \cdot (dx_0, dx_1, dx_2 ..)$ >>> ### $ \nabla \; f \cdot d\vec{r}$ > ### Gradient >> ### $ \nabla \; f $ >> ### $ f$ is scalar function > ### Total derivative >> ### $df =:\begin{cases} \nabla \; f \cdot (dx,dy,dz)\\ \nabla \; f \cdot d\vec{r}\\ \text{f is scalar function} \end{cases}$ ```python # find the total dervative dz/dy of z = 5x+xy+y^2, where x=3y^2 # dz = f_x(z) * dx/dy + f_y(x) import sympy as sm import sympy.vector N = sm.vector.CoordSys3D('') A = sm.Matrix([N.x, N.y, N.z]) v = sm.vector.matrix_to_vector(A,N) z = 5*N.x + N.x*N.y+N.y**2 g = 3*N.y**2 sm.diff(z,N.x)*sm.diff(g,N.y) + sm.diff(z,N.y).subs({N.x:3*N.y**2}) ``` $\displaystyle 3 \mathbf{{y}_{}}^{2} + 6 \mathbf{{y}_{}} \left(\mathbf{{y}_{}} + 5\right) + 2 \mathbf{{y}_{}}$ ```python # find the total derivative dz/dt of z=x^2-8xy-y^3, where x=3t and y=1-t z = N.x**2 - 8*N.x*N.y - N.y**3 t = sm.symbols('t') x = 3*t y = 1-t # dz = z_x*dx/dt + z_y*dy/dt (sm.diff(z,N.x)*sm.diff(x,t) + sm.diff(z,N.y)*sm.diff(y,t)).subs({N.x:3*t,N.y:1-t}).simplify() ``` $\displaystyle 3 t^{2} + 60 t - 21$ ```python # find the total derivative dz/dt of z = 7*u+v*t, where u=2t^2 and v=t+1 # u(t) u = 2*t**2 # v(t) v = t+1 # z(u,v,t) z = 7*u+v*t sm.diff(z,t) ``` $\displaystyle 30 t + 1$ ```python # https://www.youtube.com/watch?v=j91ijDR-YIc # T(x,y) = 20 - 4x^2 - y^2 T = 20 - 4*N.x**2 - N.y**2 # sm.Matrix mTg = sm.Matrix([sm.diff(T,N.x), sm.diff(T,N.y)]) # matrix_to_vector ~ to_matrix vTg = sm.vector.matrix_to_vector(mTg, N) mTg = mTg.subs({N.x:2,N.y:-3}) # Matrix norm() mTg.norm() sm.N(sm.atan(mTg.norm())) ``` $\displaystyle 1.51234242057036$ ```python ```
Formal statement is: lemma approx_from_below_dense_linorder: fixes x::"'a::{dense_linorder, linorder_topology, first_countable_topology}" assumes "x > y" shows "\<exists>u. (\<forall>n. u n < x) \<and> (u \<longlonglongrightarrow> x)" Informal statement is: If $x$ is greater than $y$ in a dense linear order, then there exists a sequence $u$ such that $u_n < x$ for all $n$ and $u$ converges to $x$.
{-# OPTIONS --cubical --safe #-} module Cubical.Data.Universe where open import Cubical.Data.Universe.Base public open import Cubical.Data.Universe.Properties public
using Mocking apply_security_groups_to_load_balancer_1_patch = @patch function apply_security_groups_to_load_balancer(a...; b...) return Dict{String, Any}("SecurityGroups" => Any["sg-fc448899"]) end attach_load_balancer_to_subnets_1_patch = @patch function attach_load_balancer_to_subnets(a...; b...) return Dict{String, Any}("Subnets" => Any["subnet-15aaab61", "subnet-0ecac448"]) end configure_health_check_1_patch = @patch function configure_health_check(a...; b...) return Dict{String, Any}("HealthCheck" => Dict{String, Any}("Interval" => 30, "UnhealthyThreshold" => 2, "Timeout" => 3, "HealthyThreshold" => 2, "Target" => "HTTP:80/png")) end create_load_balancer_1_patch = @patch function create_load_balancer(a...; b...) return Dict{String, Any}("DNSName" => "my-load-balancer-1234567890.us-west-2.elb.amazonaws.com") end create_load_balancer_2_patch = @patch function create_load_balancer(a...; b...) return Dict{String, Any}("DNSName" => "my-load-balancer-123456789.us-west-2.elb.amazonaws.com") end create_load_balancer_3_patch = @patch function create_load_balancer(a...; b...) return Dict{String, Any}("DNSName" => "my-load-balancer-1234567890.us-west-2.elb.amazonaws.com") end create_load_balancer_4_patch = @patch function create_load_balancer(a...; b...) return Dict{String, Any}("DNSName" => "my-load-balancer-123456789.us-west-2.elb.amazonaws.com") end create_load_balancer_5_patch = @patch function create_load_balancer(a...; b...) return Dict{String, Any}("DNSName" => "internal-my-load-balancer-123456789.us-west-2.elb.amazonaws.com") end deregister_instances_from_load_balancer_1_patch = @patch function deregister_instances_from_load_balancer(a...; b...) return Dict{String, Any}("Instances" => Any[Dict{String, Any}("InstanceId" => "i-207d9717"), Dict{String, Any}("InstanceId" => "i-afefb49b")]) end describe_instance_health_1_patch = @patch function describe_instance_health(a...; b...) return Dict{String, Any}("InstanceStates" => Any[Dict{String, Any}("Description" => "N/A", "InstanceId" => "i-207d9717", "State" => "InService", "ReasonCode" => "N/A"), Dict{String, Any}("Description" => "N/A", "InstanceId" => "i-afefb49b", "State" => "InService", "ReasonCode" => "N/A")]) end describe_load_balancer_attributes_1_patch = @patch function describe_load_balancer_attributes(a...; b...) return Dict{String, Any}("LoadBalancerAttributes" => Dict{String, Any}("ConnectionSettings" => Dict{String, Any}("IdleTimeout" => 60), "CrossZoneLoadBalancing" => Dict{String, Any}("Enabled" => false), "ConnectionDraining" => Dict{String, Any}("Timeout" => 300, "Enabled" => false), "AccessLog" => Dict{String, Any}("Enabled" => false))) end describe_load_balancer_policies_1_patch = @patch function describe_load_balancer_policies(a...; b...) return Dict{String, Any}("PolicyDescriptions" => Any[Dict{String, Any}("PolicyName" => "my-authentication-policy", "PolicyAttributeDescriptions" => Any[Dict{String, Any}("AttributeName" => "PublicKeyPolicyName", "AttributeValue" => "my-PublicKey-policy")], "PolicyTypeName" => "BackendServerAuthenticationPolicyType")]) end describe_load_balancer_policy_types_1_patch = @patch function describe_load_balancer_policy_types(a...; b...) return Dict{String, Any}("PolicyTypeDescriptions" => Any[Dict{String, Any}("Description" => "Policy that controls whether to include the IP address and port of the originating request for TCP messages. This policy operates on TCP listeners only.", "PolicyTypeName" => "ProxyProtocolPolicyType", "PolicyAttributeTypeDescriptions" => Any[Dict{String, Any}("Cardinality" => "ONE", "AttributeName" => "ProxyProtocol", "AttributeType" => "Boolean")])]) end describe_load_balancers_1_patch = @patch function describe_load_balancers(a...; b...) return Dict{String, Any}("LoadBalancerDescriptions" => Any[Dict{String, Any}("CanonicalHostedZoneNameID" => "Z3DZXE0EXAMPLE", "Subnets" => Any["subnet-15aaab61"], "AvailabilityZones" => Any["us-west-2a"], "CreatedTime" => "2015-03-19T03:24:02.650Z", "SecurityGroups" => Any["sg-a61988c3"], "CanonicalHostedZoneName" => "my-load-balancer-1234567890.us-west-2.elb.amazonaws.com", "HealthCheck" => Dict{String, Any}("Interval" => 30, "UnhealthyThreshold" => 2, "Timeout" => 3, "HealthyThreshold" => 2, "Target" => "HTTP:80/png"), "Scheme" => "internet-facing", "ListenerDescriptions" => Any[Dict{String, Any}("PolicyNames" => Any[], "Listener" => Dict{String, Any}("LoadBalancerPort" => 80, "InstancePort" => 80, "Protocol" => "HTTP", "InstanceProtocol" => "HTTP")), Dict{String, Any}("PolicyNames" => Any["ELBSecurityPolicy-2015-03"], "Listener" => Dict{String, Any}("LoadBalancerPort" => 443, "InstancePort" => 443, "SSLCertificateId" => "arn:aws:iam::123456789012:server-certificate/my-server-cert", "Protocol" => "HTTPS", "InstanceProtocol" => "HTTPS"))], "SourceSecurityGroup" => Dict{String, Any}("GroupName" => "my-elb-sg", "OwnerAlias" => "123456789012"), "VPCId" => "vpc-a01106c2", "Policies" => Dict{String, Any}("OtherPolicies" => Any["my-PublicKey-policy", "my-authentication-policy", "my-SSLNegotiation-policy", "my-ProxyProtocol-policy", "ELBSecurityPolicy-2015-03"], "AppCookieStickinessPolicies" => Any[], "LBCookieStickinessPolicies" => Any[Dict{String, Any}("PolicyName" => "my-duration-cookie-policy", "CookieExpirationPeriod" => 60)]), "BackendServerDescriptions" => Any[Dict{String, Any}("PolicyNames" => Any["my-ProxyProtocol-policy"], "InstancePort" => 80)], "DNSName" => "my-load-balancer-1234567890.us-west-2.elb.amazonaws.com", "Instances" => Any[Dict{String, Any}("InstanceId" => "i-207d9717"), Dict{String, Any}("InstanceId" => "i-afefb49b")], "LoadBalancerName" => "my-load-balancer")]) end describe_tags_1_patch = @patch function describe_tags(a...; b...) return Dict{String, Any}("TagDescriptions" => Any[Dict{String, Any}("LoadBalancerName" => "my-load-balancer", "Tags" => Any[Dict{String, Any}("Value" => "lima", "Key" => "project"), Dict{String, Any}("Value" => "digital-media", "Key" => "department")])]) end detach_load_balancer_from_subnets_1_patch = @patch function detach_load_balancer_from_subnets(a...; b...) return Dict{String, Any}("Subnets" => Any["subnet-15aaab61"]) end disable_availability_zones_for_load_balancer_1_patch = @patch function disable_availability_zones_for_load_balancer(a...; b...) return Dict{String, Any}("AvailabilityZones" => Any["us-west-2b"]) end enable_availability_zones_for_load_balancer_1_patch = @patch function enable_availability_zones_for_load_balancer(a...; b...) return Dict{String, Any}("AvailabilityZones" => Any["us-west-2a", "us-west-2b"]) end modify_load_balancer_attributes_1_patch = @patch function modify_load_balancer_attributes(a...; b...) return Dict{String, Any}("LoadBalancerAttributes" => Dict{String, Any}("CrossZoneLoadBalancing" => Dict{String, Any}("Enabled" => true)), "LoadBalancerName" => "my-load-balancer") end modify_load_balancer_attributes_2_patch = @patch function modify_load_balancer_attributes(a...; b...) return Dict{String, Any}("LoadBalancerAttributes" => Dict{String, Any}("ConnectionDraining" => Dict{String, Any}("Timeout" => 300, "Enabled" => true)), "LoadBalancerName" => "my-load-balancer") end register_instances_with_load_balancer_1_patch = @patch function register_instances_with_load_balancer(a...; b...) return Dict{String, Any}("Instances" => Any[Dict{String, Any}("InstanceId" => "i-d6f6fae3"), Dict{String, Any}("InstanceId" => "i-207d9717"), Dict{String, Any}("InstanceId" => "i-afefb49b")]) end
As a self @-@ proclaimed " fan of multitracking " , Townsend has developed a trademark production style featuring an atmospheric , layered " wall of sound " . Townsend has drawn critical praise for his productions , which " are always marked by a sense of adventure , intrigue , chaotic atmospherics and overall aural pyrotechnics " , according to Mike G. of Metal Maniacs . Townsend mainly uses Pro Tools to produce his music , alongside other software suites such as Steinberg Cubase , Ableton Live , and Logic Pro . Townsend 's musical ideas and production style have drawn comparisons to Phil Spector and Frank Zappa . Townsend has carried out the mixing and mastering for most of his solo work himself . He has also mixed and remixed work for other artists such as Rammstein , August Burns Red and Misery Signals .
= = Biology and ecology = =
-- Andreas, 2015-05-02, issue reported by Gabe Dijkstra open import Common.Prelude open import Common.Equality data T : Set where c0 : ⊥ → T c1 : ⊥ → T -- The following should not pass, as c0 and c1 are not fully applied. c0≠c1 : c0 ≡ c1 → ⊥ c0≠c1 () -- The latter conflicts with function extensionality. postulate fun-ext : {A B : Set} → (f g : A → B) → ((x : A) → f x ≡ g x) → f ≡ g c0=c1 : c0 ≡ c1 c0=c1 = fun-ext c0 c1 (λ ()) wrong : ⊥ wrong = c0≠c1 c0=c1
#' @export bib_mmprod = function(x, y) { storage.mode(x) = "double" storage.mode(y) = "double" .Call("bib_mmprod_", x, y) }
[STATEMENT] lemma \<phi>_in_terms_of_\<eta>: assumes "D.ide y" and "\<guillemotleft>f : F y \<rightarrow>\<^sub>C x\<guillemotright>" shows "\<phi> y f = G f \<cdot>\<^sub>D \<eta> y" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<phi> y f = G f \<cdot>\<^sub>D \<eta> y [PROOF STEP] using assms \<eta>_def [PROOF STATE] proof (prove) using this: D.ide y \<guillemotleft>f : F y \<rightarrow>\<^sub>C x\<guillemotright> \<eta> \<equiv> \<eta>.map goal (1 subgoal): 1. \<phi> y f = G f \<cdot>\<^sub>D \<eta> y [PROOF STEP] by (simp add: \<phi>_in_terms_of_\<eta>o)
export howell_form2 # we assume that B has at least as many rows as columns function howell_form2(A::nmod_mat) #A = deepcopy(B) n = A.r m = A.c if n < m A = vcat(A, zero_matrix(base_ring(A), m-n, m)) end for j in 1:m for i in j+1:n #print("Computing xgcd of $(_raw_getindex(A,j,j)), $(_raw_getindex(A,i,j))\n") g,s,t,u,v = _xxgcd(_raw_getindex(A,j,j),_raw_getindex(A,i,j),A._n) #println("$g $s $t $u $v ") for k in 1:m t1 = s*_raw_getindex(A,j,k) + t*_raw_getindex(A, i, k) t2 = u*_raw_getindex(A,j,k) + v*_raw_getindex(A, i, k) t1 = ccall((:n_mod2_preinv, :libflint), Int, (Int, Int, UInt), t1, A._n, A._ninv) t2 = ccall((:n_mod2_preinv, :libflint), Int, (Int, Int, UInt), t2, A._n, A._ninv) ccall((:nmod_mat_set_entry, :libflint), Void, (Ptr{nmod_mat}, Int, Int, UInt), &A, j - 1, k - 1, t1) ccall((:nmod_mat_set_entry, :libflint), Void, (Ptr{nmod_mat}, Int, Int, UInt), &A, i - 1, k - 1, t2) end end #println(A) end #println("I have a triangular matrix:") #println(A) T = zero_matrix(base_ring(A), 1, A.c) for j in 1:m if _raw_getindex(A,j,j) != 0 #println("nonzero case") u = _unit(_raw_getindex(A,j,j), A._n) for k in 1:m t1 = mod(u*_raw_getindex(A,j,k), A._n) ccall((:nmod_mat_set_entry, :libflint), Void, (Ptr{nmod_mat}, Int, Int, UInt), &A, j - 1, k - 1, t1) end #println("Multiplied row $j with $u and obtained \n$A\n") for i in 1:j-1 #println("ich nehme zeile $j und reduziere damit zeile $i") #println("zeile $i: $(window(A, i:i, 1:m))") #println("zeile $j: $(window(A, j:j, 1:m))") #println("A[$i,$j]: $(_raw_getindex(A,i,j)) A[$j,$j]: $(_raw_getindex(A,j,j))") #println("A[$i,$j]: $(A[i,j]) A[$j,$j]: $(A[j,j])") q = UInt(prem(- Int(div(_raw_getindex(A, i, j), _raw_getindex(A, j, j))), Int(A._n))) #println("quotient ist $q") for k in j:m #println("adjusting row $i, divinding by $(_raw_getindex(A, j, j))") #println("I am replacing A[$i,$k] with") #println("A[$i,$j]: $(_raw_getindex(A,i,j)) A[$j,$j]: $(_raw_getindex(A,j,j))") #println("quotient is $(UInt(prem(- Int(div(_raw_getindex(A, i, j), _raw_getindex(A, j, j))), Int(A._n))))") #print(_raw_getindex(A, i, k) + UInt(prem(- Int(div(_raw_getindex(A, i, j), _raw_getindex(A, j, j))), Int(A._n))) *_raw_getindex(A, j, k)) #println() _raw_setindex(A, i, k, mod(_raw_getindex(A, i, k) + q *_raw_getindex(A, j, k), A._n)) end end #print("computing the annihilator for $j ... ") l = mod(div(A._n,gcd(_raw_getindex(A,j,j),A._n)),A._n) #println("annihilator is $l") if l == 0 continue end for k in 1:m _raw_setindex(T, 1, k, mod(l*_raw_getindex(A,j,k), A._n)) end else for k in 1:m _raw_setindex(T, 1, k, _raw_getindex(A,j,k)) end end #println("T looks like: $T") #println("Augmented matrix looks like \n$A\n$T\n") for i in j+1:m g,s,t,u,v = _xxgcd(_raw_getindex(A,i,i),_raw_getindex(T,1,i),A._n) for k in 1:m t1 = s*_raw_getindex(A,i,k) + t*_raw_getindex(T, 1, k) t2 = u*_raw_getindex(A,i,k) + v*_raw_getindex(T, 1, k) t1 = ccall((:n_mod2_preinv, :libflint), Int, (Int, Int, UInt), t1, A._n, A._ninv) t2 = ccall((:n_mod2_preinv, :libflint), Int, (Int, Int, UInt), t2, A._n, A._ninv) ccall((:nmod_mat_set_entry, :libflint), Void, (Ptr{nmod_mat}, Int, Int, UInt), &A, i - 1, k - 1, t1) ccall((:nmod_mat_set_entry, :libflint), Void, (Ptr{nmod_mat}, Int, Int, UInt), &T, 0, k - 1, t2) end end #println("After reducing with T the augmented matrix looks like \n$A\n$T\n") end #return A end function _raw_setindex(A::nmod_mat, i::Int, j::Int, x::UInt) ccall((:nmod_mat_set_entry, :libflint), Void, (Ptr{nmod_mat}, Int, Int, UInt), &A, i - 1, j - 1, x) end function _stab(a::UInt, b::UInt, N::UInt) g = gcd(a,b,N) _, c = ppio(div(N,g),div(a,g)) #c = prem(c,N) return c end function _unit(a::UInt, N::UInt) g,s,_ = gcdx(a,N) if g == 1 return rem(s,N) else l = div(N,g) d = _stab(s,l,N) return rem(s + d*l,N) end end function _xxgcd(a::UInt, b::UInt, N::UInt) g,s,t = gcdx(Int(a),Int(b)) if g == 0 return (UInt(0), UInt(1), UInt(0), UInt(0), UInt(1)) end u = UInt(prem(-div(Int(b),g),Int(N))) g = UInt(g) v = div(a,g) return (g,UInt(prem(s,Int(N))),UInt(prem(t,Int(N))),u,v) end ################################################################################ # # positive remainder # ################################################################################ function prem(a::Integer, m::T) where T<:Integer b = a % m if b < 0 return m+b else return b end end function prem(a::fmpz, m::T) where T return prem(BigInt(a), m) end ############################################################################### # # Howell form for Generic.Mat{fmpz} # ############################################################################### function _xxgcd(a::fmpz, b::fmpz, N::fmpz) g,s,t = gcdx(a,b) if g == 0 return (fmpz(0), fmpz(1), fmpz(0), fmpz(0), fmpz(1)) end u = mod(-div(b,g),N) v = div(a,g) return (g,mod(s,N),mod(t,N),u,v) end function _unit(a::fmpz, N::fmpz) g,s,_ = gcdx(a,N) if g == 1 return mod(s,N) else l = div(N,g) d = _stab(s,l,N) return mod(s + d*l,N) end end function _stab(a::fmpz, b::fmpz, N::fmpz) g = gcd(gcd(a,b),N) _, c = ppio(div(N,g),div(a,g)) return c end function howell_form(A::Generic.Mat{Nemo.Generic.Res{Nemo.fmpz}}) B=deepcopy(A) if rows(B)<cols(B) B=vcat(B, zero_matrix(base_ring(B), cols(B)-rows(B), cols(B))) end howell_form!(B) return B end # # for the in-place function, the number of rows must be at least equal to the number of columns # function howell_form!(A::Generic.Mat{Nemo.Generic.Res{Nemo.fmpz}}) R=base_ring(A) A1=lift(A) ccall((:fmpz_mat_howell_form_mod, :libflint), Void, (Ref{fmpz_mat}, Ref{fmpz}), A1, modulus(R)) A=MatrixSpace(R, rows(A), cols(A))(A1) return A R=base_ring(A) n=R.modulus # # Get an upper triangular matrix # for j=1:cols(A) for i=j+1:cols(A) g,s,t,u,v = _xxgcd(A[j,j].data,A[i,j].data,n) for k in 1:cols(A) t1 = s* A[j,k] + t* A[i,k] t2 = u* A[j,k] + v* A[i,k] A[j,k] = t1 A[i,k] = t2 end end end # # Multiply the rows by annihlator of the pivot element and reduce # T = zero_matrix(R, 1, cols(A)) for j in 1:cols(A) if A[j,j] != 0 u = _unit(A[j,j].data, n) for k in 1:cols(A) A[j,k]=u*A[j,k] end for i in 1:j-1 q = div(A[i,j].data, A[j,j].data) for k in j:cols(A) A[i,k]-= q*A[j,k] end end l = div(n,gcd(A[j,j].data,n)) if l == 0 continue end for k in j:cols(A) T[1,k]=l*A[j,k] end else for k in j:cols(A) T[1, k]= A[j,k] end end for i in j:cols(A) g,s,t,u,v = _xxgcd(A[i,i].data, T[1,i].data,n) for k in 1:cols(A) t1 = s*A[i,k] + t*T[1,k] t2 = u*A[i,k] + v*T[1,k] A[i,k]= t1 T[1,k]=t2 end end end if iszero_row(A,rows(A)) for i=1:cols(A) A[rows(A),i]=T[1,i] end end end function triangularize!(A::Generic.Mat{Nemo.Generic.Res{Nemo.fmpz}}) R=base_ring(A) n=R.modulus # # Get an upper triangular matrix # for j=1:cols(A) for i=j+1:cols(A) g,s,t,u,v = _xxgcd(A[j,j].data,A[i,j].data,n) for k in 1:cols(A) t1 = s* A[j,k] + t* A[i,k] t2 = u* A[j,k] + v* A[i,k] A[j,k] = t1 A[i,k] = t2 end end end end function triangularize(A::Generic.Mat{Nemo.Generic.Res{Nemo.fmpz}}) B= triangularize!(deepcopy(A)) return B end function Base.nullspace(M::Generic.Mat{Nemo.Generic.Res{Nemo.fmpz}}) R = base_ring(M) # # If the modulus is prime, the second part of the Howell form computation is useless and I can directly call the rref # but I have to test if the modulus is prime. What is better? # N = zero_matrix(R, rows(M)+cols(M), rows(M)+cols(M)) for i=1:rows(M) for j=1:cols(M) N[j,i]=M[i,j] end end for i=1:cols(M) N[i, i+rows(M)]=1 end N=howell_form!(N) if gcd(prod([N[i,i] for i=1:rows(N)]).data,R.modulus)==1 return MatrixSpace(R,cols(M),0, false)(), 0 end nr = 1 while nr <= rows(N) && !iszero_row(N, nr) nr += 1 end nr -= 1 h = sub(N, 1:nr, 1:rows(M)) for i=1:rows(h) if iszero_row(h, i) k = sub(N, i:rows(h), rows(M)+1:cols(N)) return k', rows(k) end end return MatrixSpace(R,cols(M),0, false)(0), 0 end
Formal statement is: lemma locally_compact_alt: fixes S :: "'a :: heine_borel set" shows "locally compact S \<longleftrightarrow> (\<forall>x \<in> S. \<exists>U. x \<in> U \<and> openin (top_of_set S) U \<and> compact(closure U) \<and> closure U \<subseteq> S)" (is "?lhs = ?rhs") Informal statement is: A topological space $S$ is locally compact if and only if for every $x \in S$, there exists an open set $U$ containing $x$ such that $U$ is compact and contained in $S$.
{-# OPTIONS --cubical --no-import-sorts --safe #-} module Cubical.Algebra.RingSolver.CommRingExamples where open import Cubical.Foundations.Prelude open import Cubical.Data.FinData open import Cubical.Data.Nat using (ℕ) open import Cubical.Data.Vec.Base open import Cubical.Algebra.CommRing open import Cubical.Algebra.RingSolver.NatAsAlmostRing open import Cubical.Algebra.RingSolver.RawAlgebra renaming (⟨_⟩ to ⟨_⟩ᵣ) open import Cubical.Algebra.RingSolver.CommRingSolver -- In scope for debugging: open import Cubical.Algebra.RingSolver.CommRingHornerForms private variable ℓ : Level module MultivariateSolving (R : CommRing {ℓ}) where -- In scope for debuggin: -- In scope for solver use: open CommRingStr (snd R) AsAlgebra = CommRing→RawℤAlgebra R X : ℤExpr R 3 X = ∣ Fin.zero Y : ℤExpr R 3 Y = ∣ (suc Fin.zero) Z : ℤExpr R 3 Z = ∣ (suc (suc Fin.zero)) _ : (x y z : (fst R)) → x · y · z ≡ z · y · x _ = λ x y z → let lhs = X ·' Y ·' Z rhs = Z ·' Y ·' X in solve R lhs rhs (x ∷ y ∷ z ∷ []) refl _ : (x y z : (fst R)) → x · (y + z) ≡ z · x + y · x _ = λ x y z → let lhs = X ·' (Y +' Z) rhs = Z ·' X +' Y ·' X in solve R lhs rhs (x ∷ y ∷ z ∷ []) refl _ : (x y z : (fst R)) → x · (y - z) ≡ (- z) · x + y · x _ = λ x y z → let lhs = X ·' (Y +' (-' Z)) rhs = (-' Z) ·' X +' (Y ·' X) in solve R lhs rhs (x ∷ y ∷ z ∷ []) refl {- A bigger example, copied from 'Example.agda' -} _ : (x y z : (fst R)) → (x + y) · (x + y) · (x + y) · (x + y) ≡ x · x · x · x + (scalar R 4) · x · x · x · y + (scalar R 6) · x · x · y · y + (scalar R 4) · x · y · y · y + y · y · y · y _ = λ x y z → let lhs = (X +' Y) ·' (X +' Y) ·' (X +' Y) ·' (X +' Y) rhs = X ·' X ·' X ·' X +' (K 4) ·' X ·' X ·' X ·' Y +' (K 6) ·' X ·' X ·' Y ·' Y +' (K 4) ·' X ·' Y ·' Y ·' Y +' Y ·' Y ·' Y ·' Y in solve R lhs rhs (x ∷ y ∷ z ∷ []) refl _ : (x y z : (fst R)) → (x + y) · (x - y) ≡ (x · x - y · y) _ = λ x y z → let lhs = (X +' Y) ·' (X +' (-' Y)) rhs = (X ·' X) +' (-' (Y ·' Y)) in solve R lhs rhs (x ∷ y ∷ z ∷ []) refl
// // ePDF // #pragma once #include <gsl/gsl_integration.h> namespace ePDF { struct int_params { double z; int nl; }; /** * @brief The "NumericIntegrals" class */ class NumericIntegrals { public: /** * @brief The "NumericIntegrals" constructor. * @param flv: 0 = singlet, 1 = photon, 2 = nonsinglet * @param nl: number of leptons (needed for singlet) */ NumericIntegrals(int const& iflv, int const& nl); /** * @brief The "NumericIntegrals" destructor. */ ~NumericIntegrals(); /** * @brief Perform the integration * @param z: momentum fraction */ double integrate(double const& z) const; private: int const _iflv; int const _nl; double const _epsabs; double const _epsrel; gsl_integration_workspace *_w; }; }
/************************************************************************ MIT License Copyright (c) 2021 Deqi Tang Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ************************************************************************/ /// @file src/atomsciflow/vasp/vasp.cpp /// @author DeqiTang /// Mail: [email protected] /// Created Time: Fri 04 Mar 2022 04:08:27 PM CST #include "atomsciflow/vasp/vasp.h" #include <fstream> #include <boost/format.hpp> #include <boost/lexical_cast.hpp> #include <boost/filesystem.hpp> #include "atomsciflow/server/submit_script.h" #include "atomsciflow/remote/server.h" namespace atomsciflow { namespace fs = boost::filesystem; Vasp::Vasp() { incar = std::make_shared<VaspIncar>(); poscar = std::make_shared<VaspPoscar>(); kpoints = std::make_shared<VaspKpoints>(); incar->set_runtype("static"); incar->basic_setting(); job.set_run_default("bash"); job.set_run_default("yh"); job.set_run_default("llhpc"); job.set_run_default("pbs"); job.set_run_default("lsf_sz"); job.set_run_default("lsf_sustc"); job.set_run_default("cdcloud"); job.set_run("cmd", "$ASF_CMD_VASP_STD"); job.set_run("script_name_head", "vasp-run"); } Vasp::~Vasp() { } void Vasp::get_xyz(const std::string& xyzfile) { this->poscar->get_xyz(xyzfile); job.set_run("xyz_file", fs::absolute(xyzfile).string()); } template <typename T> void Vasp::set_param(std::string key, T value) { this->incar->set_param(key, value); } void Vasp::py_set_param(std::string key, int value) { this->set_param(key, value); } void Vasp::py_set_param(std::string key, double value) { this->set_param(key, value); } void Vasp::py_set_param(std::string key, std::string value) { this->set_param(key, value); } void Vasp::py_set_param(std::string key, std::vector<int> value) { this->set_param(key, value); } void Vasp::py_set_param(std::string key, std::vector<double> value) { this->set_param(key, value); } void Vasp::py_set_param(std::string key, std::vector<std::string> value) { this->set_param(key, value); } void Vasp::py_set_param(std::string key, std::vector<std::vector<int>> value) { this->set_param(key, value); } void Vasp::py_set_param(std::string key, std::vector<std::vector<double>> value) { this->set_param(key, value); } void Vasp::py_set_param(std::string key, std::vector<std::vector<std::string>> value) { this->set_param(key, value); } /// \brief Vasp::set_params /// \param params /// \param runtype the type of calculation /// candidates; /// 'static' | 'opt' | 'phonopy' | 'phonon | 'neb' | /// 'md' | 'custom' | void Vasp::set_params(const std::map<std::string, std::string>& params, const std::string& runtype) { if ("static" == runtype) { for (const auto& item : params) { if (limit.static_allowed.find(item.first) != limit.static_allowed.end()) { this->incar->set_param(item.first, item.second); } } } else if ("opt" == runtype) { for (const auto& item : params) { if (limit.opt_allowed.find(item.first) != limit.opt_allowed.end()) { this->incar->set_param(item.first, item.second); } } } else if ("phonopy" == runtype) { for (const auto& item : params) { if (limit.phonopy_allowed.find(item.first) != limit.phonopy_allowed.end()) { this->incar->set_param(item.first, item.second); } } } else if ("phonon" == runtype) { for (const auto& item : params) { if (limit.phonon_allowed.find(item.first) != limit.phonon_allowed.end()) { this->incar->set_param(item.first, item.second); } } } else if ("neb" == runtype) { for (const auto& item : params) { if (limit.neb_allowed.find(item.first) != limit.neb_allowed.end()) { this->incar->set_param(item.first, item.second); } } } else if ("md" == runtype) { for (const auto& item : params) { if (limit.md_allowed.find(item.first) != limit.md_allowed.end()) { this->incar->set_param(item.first, item.second); } } } else if ("custom" == runtype) { for (const auto& item : params) { this->incar->set_param(item.first, item.second); } } else { // } return; } void Vasp::set_kpoints(const std::vector<int>& kpoints_mp = {1, 1, 1, 0, 0, 0}, const std::string& option="automatic", Kpath* kpath=nullptr) { this->kpoints->set_kpoints(kpoints_mp, option, kpath); } void Vasp::run(const std::string& directory) { job.steps.clear(); std::ostringstream step; step << "cd ${ABSOLUTE_WORK_DIR}" << "\n"; step << "cat >INCAR<<EOF\n"; step << this->incar->to_string(); step << "EOF\n"; step << "cat >KPOINTS<<EOF\n"; step << this->kpoints->to_string(); step << "EOF\n"; step << "cat >POSCAR<<EOF\n"; step << this->poscar->to_string("cartesian"); step << "EOF\n"; step << "cat"; for (const auto& item : this->poscar->elem_natom_in_number_order) { step << " " << (fs::path(this->config.get_pseudo_pot_dir()["vasp"]) / "PAW_PBE" / item.first / "POTCAR").string(); } step << " >POTCAR\n"; step << "$CMD_HEAD " << job.run_params["cmd"] << "\n"; job.steps.push_back(step.str()); step.clear(); job.run(directory); } // explicit template instantiation template void Vasp::set_param<int>(std::string, int); template void Vasp::set_param<double>(std::string, double); template void Vasp::set_param<std::string>(std::string, std::string); template void Vasp::set_param<std::vector<int>>(std::string, std::vector<int>); template void Vasp::set_param<std::vector<double>>(std::string, std::vector<double>); template void Vasp::set_param<std::vector<std::string>>(std::string, std::vector<std::string>); template void Vasp::set_param<std::vector<std::vector<int>>>(std::string, std::vector<std::vector<int>>); template void Vasp::set_param<std::vector<std::vector<double>>>(std::string, std::vector<std::vector<double>>); template void Vasp::set_param<std::vector<std::vector<std::string>>>(std::string, std::vector<std::vector<std::string>>); } // namespace atomsciflow
{-| Module: MachineLearning.Optimization Description: Optimization Copyright: (c) Alexander Ignatyev, 2016 License: BSD-3 Stability: experimental Portability: POSIX Optimization module. -} module MachineLearning.Optimization ( MinimizeMethod(..) , minimize , checkGradient ) where import MachineLearning.Types (R, Vector, Matrix) import MachineLearning.Model as Model import MachineLearning.Regularization (Regularization) import qualified MachineLearning.Optimization.GradientDescent as GD import qualified MachineLearning.Optimization.MinibatchGradientDescent as MGD import qualified Data.Vector.Storable as V import qualified Numeric.LinearAlgebra as LA import qualified Numeric.GSL.Minimization as Min data MinimizeMethod = GradientDescent R -- ^ Gradient descent, takes alpha. Requires feature normalization. | MinibatchGradientDescent Int Int R -- ^ Minibacth Gradietn Descent, takes seed, batch size and alpha | ConjugateGradientFR R R -- ^ Fletcher-Reeves conjugate gradient algorithm, -- takes size of first trial step (0.1 is fine) and tol (0.1 is fine). | ConjugateGradientPR R R -- ^ Polak-Ribiere conjugate gradient algorithm. -- takes size of first trial step (0.1 is fine) and tol (0.1 is fine). | BFGS2 R R -- ^ Broyden-Fletcher-Goldfarb-Shanno (BFGS) algorithm, -- takes size of first trial step (0.1 is fine) and tol (0.1 is fine). -- | Returns solution vector (theta) and optimization path. -- Optimization path's row format: -- [iter number, cost function value, theta values...] minimize :: Model.Model a => MinimizeMethod -> a -- ^ model (Least Squares, Logistic Regression etc) -> R -- ^ epsilon, desired precision of the solution -> Int -- ^ maximum number of iterations allowed -> Regularization -- ^ regularization parameter -> Matrix -- ^ X -> Vector -- ^ y -> Vector -- ^ initial solution, theta -> (Vector, Matrix) -- ^ solution vector and optimization path minimize (BFGS2 firstStepSize tol) = minimizeVD Min.VectorBFGS2 firstStepSize tol minimize (ConjugateGradientFR firstStepSize tol) = minimizeVD Min.ConjugateFR firstStepSize tol minimize (ConjugateGradientPR firstStepSize tol) = minimizeVD Min.ConjugatePR firstStepSize tol minimize (GradientDescent alpha) = GD.gradientDescent alpha minimize (MinibatchGradientDescent seed batchSize alpha) = MGD.minibatchGradientDescent seed batchSize alpha minimizeVD method firstStepSize tol model epsilon niters reg x y initialTheta = Min.minimizeVD method epsilon niters firstStepSize tol costf gradientf initialTheta where costf = Model.cost model reg x y gradientf = Model.gradient model reg x y -- | Gradient checking function. -- Approximates the derivates of the Model's cost function -- and calculates derivatives using the Model's gradient functions. -- Returns norn_2 between 2 derivatives. -- Takes model, regularization, X, y, theta and epsilon (used to approximate derivatives, 1e-4 is a good value). checkGradient :: Model a => a -> Regularization -> Matrix -> Vector -> Vector -> R -> R checkGradient model reg x y theta eps = LA.norm_2 $ grad1 - grad2 where theta_m = LA.asColumn theta eps_v = V.replicate (V.length theta) eps eps_m = LA.diag eps_v -- +/- eps_m in case of zero theta theta_m1 = theta_m * (1 + eps_m) + eps_m theta_m2 = theta_m * (1 - eps_m) - eps_m cost1 = LA.vector $ map (cost model reg x y) $ LA.toColumns theta_m1 cost2 = LA.vector $ map (cost model reg x y) $ LA.toColumns theta_m2 eps_v1 = LA.takeDiag $ theta_m1 - theta_m eps_v2 = LA.takeDiag $ theta_m - theta_m2 grad1 = (cost1 - cost2) / (eps_v1 + eps_v2) grad2 = gradient model reg x y theta
module Idris.Pretty import Data.List import Data.Strings import Control.ANSI.SGR import public Text.PrettyPrint.Prettyprinter import public Text.PrettyPrint.Prettyprinter.Render.Terminal import public Text.PrettyPrint.Prettyprinter.Util import Algebra import Idris.REPLOpts import Idris.Syntax import Utils.Term %default covering public export data IdrisAnn = Warning | Error | ErrorDesc | FileCtxt | Code | Meta | Keyword | Pragma export colorAnn : IdrisAnn -> AnsiStyle colorAnn Warning = color Yellow <+> bold colorAnn Error = color BrightRed <+> bold colorAnn ErrorDesc = bold colorAnn FileCtxt = color BrightBlue colorAnn Code = color Magenta colorAnn Keyword = color Red colorAnn Pragma = color BrightMagenta colorAnn Meta = color Green export error : Doc IdrisAnn -> Doc IdrisAnn error = annotate Error export errorDesc : Doc IdrisAnn -> Doc IdrisAnn errorDesc = annotate ErrorDesc export fileCtxt : Doc IdrisAnn -> Doc IdrisAnn fileCtxt = annotate FileCtxt export keyword : Doc IdrisAnn -> Doc IdrisAnn keyword = annotate Keyword export meta : Doc IdrisAnn -> Doc IdrisAnn meta = annotate Meta export code : Doc IdrisAnn -> Doc IdrisAnn code = annotate Code let_ : Doc IdrisAnn let_ = keyword (pretty "let") in_ : Doc IdrisAnn in_ = keyword (pretty "in") case_ : Doc IdrisAnn case_ = keyword (pretty "case") of_ : Doc IdrisAnn of_ = keyword (pretty "of") do_ : Doc IdrisAnn do_ = keyword (pretty "do") with_ : Doc IdrisAnn with_ = keyword (pretty "with") record_ : Doc IdrisAnn record_ = keyword (pretty "record") impossible_ : Doc IdrisAnn impossible_ = keyword (pretty "impossible") auto_ : Doc IdrisAnn auto_ = keyword (pretty "auto") default_ : Doc IdrisAnn default_ = keyword (pretty "default") rewrite_ : Doc IdrisAnn rewrite_ = keyword (pretty "rewrite") export pragma : Doc IdrisAnn -> Doc IdrisAnn pragma = annotate Pragma export prettyRig : RigCount -> Doc ann prettyRig = elimSemi (pretty '0' <+> space) (pretty '1' <+> space) (const emptyDoc) mutual prettyAlt : PClause -> Doc IdrisAnn prettyAlt (MkPatClause _ lhs rhs _) = space <+> pipe <++> prettyTerm lhs <++> pretty "=>" <++> prettyTerm rhs <+> semi prettyAlt (MkWithClause _ lhs wval flags cs) = space <+> pipe <++> angles (angles (reflow "with alts not possible")) <+> semi prettyAlt (MkImpossible _ lhs) = space <+> pipe <++> prettyTerm lhs <++> impossible_ <+> semi prettyCase : PClause -> Doc IdrisAnn prettyCase (MkPatClause _ lhs rhs _) = prettyTerm lhs <++> pretty "=>" <++> prettyTerm rhs prettyCase (MkWithClause _ lhs rhs flags _) = space <+> pipe <++> angles (angles (reflow "with alts not possible")) prettyCase (MkImpossible _ lhs) = prettyTerm lhs <++> impossible_ prettyDo : PDo -> Doc IdrisAnn prettyDo (DoExp _ tm) = prettyTerm tm prettyDo (DoBind _ n tm) = pretty n <++> pretty "<-" <++> prettyTerm tm prettyDo (DoBindPat _ l tm alts) = prettyTerm l <++> pretty "<-" <++> prettyTerm tm <+> hang 4 (fillSep $ prettyAlt <$> alts) prettyDo (DoLet _ l rig _ tm) = let_ <++> prettyRig rig <+> pretty l <++> equals <++> prettyTerm tm prettyDo (DoLetPat _ l _ tm alts) = let_ <++> prettyTerm l <++> equals <++> prettyTerm tm <+> hang 4 (fillSep $ prettyAlt <$> alts) prettyDo (DoLetLocal _ ds) = let_ <++> braces (angles (angles (pretty "definitions"))) prettyDo (DoRewrite _ rule) = rewrite_ <+> prettyTerm rule prettyUpdate : PFieldUpdate -> Doc IdrisAnn prettyUpdate (PSetField path v) = concatWith (surround dot) (pretty <$> path) <++> equals <++> prettyTerm v prettyUpdate (PSetFieldApp path v) = concatWith (surround dot) (pretty <$> path) <++> pretty '$' <+> equals <++> prettyTerm v export prettyTerm : PTerm -> Doc IdrisAnn prettyTerm = go Open where startPrec : Prec startPrec = User 0 appPrec : Prec appPrec = User 10 leftAppPrec : Prec leftAppPrec = User 9 parenthesise : Bool -> Doc IdrisAnn -> Doc IdrisAnn parenthesise b = if b then parens else id go : Prec -> PTerm -> Doc IdrisAnn go d (PRef _ n) = pretty n go d (PPi _ rig Explicit Nothing arg ret) = parenthesise (d > startPrec) $ group $ branchVal (go startPrec arg <++> "->" <++> go startPrec ret) (parens (prettyRig rig <+> "_" <++> colon <++> go startPrec arg) <++> "->" <+> line <+> go startPrec ret) rig go d (PPi _ rig Explicit (Just n) arg ret) = parenthesise (d > startPrec) $ group $ parens (prettyRig rig <+> pretty n <++> colon <++> go startPrec arg) <++> "->" <+> line <+> go startPrec ret go d (PPi _ rig Implicit Nothing arg ret) = parenthesise (d > startPrec) $ group $ braces (prettyRig rig <+> pretty '_' <++> colon <++> go startPrec arg) <++> "->" <+> line <+> go startPrec ret go d (PPi _ rig Implicit (Just n) arg ret) = parenthesise (d > startPrec) $ group $ braces (prettyRig rig <+> pretty n <++> colon <++> go startPrec arg) <++> "->" <+> line <+> go startPrec ret go d (PPi _ rig AutoImplicit Nothing arg ret) = parenthesise (d > startPrec) $ group $ branchVal (go startPrec arg <++> "=>" <+> line <+> go startPrec ret) (braces (auto_ <++> prettyRig rig <+> "_" <++> colon <++> go startPrec arg) <++> "->" <+> line <+> go startPrec ret) rig go d (PPi _ rig AutoImplicit (Just n) arg ret) = parenthesise (d > startPrec) $ group $ braces (auto_ <++> prettyRig rig <+> pretty n <++> colon <++> go startPrec arg) <++> "->" <+> line <+> go startPrec ret go d (PPi _ rig (DefImplicit t) Nothing arg ret) = parenthesise (d > startPrec) $ group $ braces (default_ <++> go appPrec t <++> prettyRig rig <+> "_" <++> colon <++> go startPrec arg) <++> "->" <+> line <+> go startPrec ret go d (PPi _ rig (DefImplicit t) (Just n) arg ret) = parenthesise (d > startPrec) $ group $ braces (default_ <++> go appPrec t <++> prettyRig rig <+> pretty n <++> colon <++> go startPrec arg) <++> "->" <+> line <+> go startPrec ret go d (PLam _ rig _ n ty sc) = let (ns, sc) = getLamNames [(rig, n, ty)] sc in parenthesise (d > startPrec) $ group $ align $ hang 2 $ backslash <+> prettyBindings ns <++> "=>" <+> line <+> go startPrec sc where getLamNames : List (RigCount, PTerm, PTerm) -> PTerm -> (List (RigCount, PTerm, PTerm), PTerm) getLamNames acc (PLam _ rig _ n ty sc) = getLamNames ((rig, n, ty) :: acc) sc getLamNames acc sc = (reverse acc, sc) prettyBindings : List (RigCount, PTerm, PTerm) -> Doc IdrisAnn prettyBindings [] = neutral prettyBindings [(rig, n, (PImplicit _))] = prettyRig rig <+> go startPrec n prettyBindings [(rig, n, ty)] = prettyRig rig <+> go startPrec n <++> colon <++> go startPrec ty prettyBindings ((rig, n, (PImplicit _)) :: ns) = prettyRig rig <+> go startPrec n <+> comma <+> line <+> prettyBindings ns prettyBindings ((rig, n, ty) :: ns) = prettyRig rig <+> go startPrec n <++> colon <++> go startPrec ty <+> comma <+> line <+> prettyBindings ns go d (PLet _ rig n (PImplicit _) val sc alts) = parenthesise (d > startPrec) $ group $ align $ let_ <++> (group $ align $ hang 2 $ prettyRig rig <+> go startPrec n <++> equals <+> line <+> go startPrec val) <+> line <+> in_ <++> (group $ align $ hang 2 $ go startPrec sc) go d (PLet _ rig n ty val sc alts) = parenthesise (d > startPrec) $ group $ align $ let_ <++> (group $ align $ hang 2 $ prettyRig rig <+> go startPrec n <++> colon <++> go startPrec ty <++> equals <+> line <+> go startPrec val) <+> hardline <+> hang 4 (fillSep (prettyAlt <$> alts)) <+> line <+> in_ <++> (group $ align $ hang 2 $ go startPrec sc) go d (PCase _ tm cs) = parenthesise (d > appPrec) $ align $ case_ <++> go startPrec tm <++> of_ <+> line <+> braces (vsep $ punctuate semi (prettyCase <$> cs)) go d (PLocal _ ds sc) = parenthesise (d > startPrec) $ group $ align $ let_ <++> braces (angles (angles "definitions")) <+> line <+> in_ <++> go startPrec sc go d (PUpdate _ fs) = parenthesise (d > appPrec) $ group $ record_ <++> braces (vsep $ punctuate comma (prettyUpdate <$> fs)) go d (PApp _ f a) = parenthesise (d > appPrec) $ group $ go leftAppPrec f <++> go appPrec a go d (PWithApp _ f a) = go d f <++> pipe <++> go d a go d (PDelayed _ LInf ty) = parenthesise (d > appPrec) $ "Inf" <++> go appPrec ty go d (PDelayed _ _ ty) = parenthesise (d > appPrec) $ "Lazy" <++> go appPrec ty go d (PDelay _ tm) = parenthesise (d > appPrec) $ "Delay" <++> go appPrec tm go d (PForce _ tm) = parenthesise (d > appPrec) $ "Force" <++> go appPrec tm go d (PImplicitApp _ f Nothing a) = parenthesise (d > appPrec) $ group $ go leftAppPrec f <++> "@" <+> braces (go startPrec a) go d (PImplicitApp _ f (Just n) (PRef _ a)) = parenthesise (d > appPrec) $ group $ if n == a then go leftAppPrec f <++> braces (pretty n) else go leftAppPrec f <++> braces (pretty n <++> equals <++> pretty a) go d (PImplicitApp _ f (Just n) a) = parenthesise (d > appPrec) $ group $ go leftAppPrec f <++> braces (pretty n <++> equals <++> go d a) go d (PSearch _ _) = pragma "%search" go d (PQuote _ tm) = parenthesise (d > appPrec) $ "`" <+> parens (go startPrec tm) go d (PQuoteName _ n) = parenthesise (d > appPrec) $ "`" <+> braces (braces (pretty n)) go d (PQuoteDecl _ tm) = parenthesise (d > appPrec) $ "`" <+> brackets (angles (angles (pretty "declaration"))) go d (PUnquote _ tm) = parenthesise (d > appPrec) $ "~" <+> parens (go startPrec tm) go d (PRunElab _ tm) = parenthesise (d > appPrec) $ pragma "%runElab" <++> go startPrec tm go d (PPrimVal _ c) = pretty c go d (PHole _ _ n) = meta (pretty (strCons '?' n)) go d (PType _) = pretty "Type" go d (PAs _ n p) = pretty n <+> "@" <+> go d p go d (PDotted _ p) = dot <+> go d p go d (PImplicit _) = "_" go d (PInfer _) = "?" go d (POp _ op x y) = parenthesise (d > appPrec) $ group $ go startPrec x <++> pretty op <++> go startPrec y go d (PPrefixOp _ op x) = parenthesise (d > appPrec) $ pretty op <+> go startPrec x go d (PSectionL _ op x) = parens (pretty op <++> go startPrec x) go d (PSectionR _ x op) = parens (go startPrec x <++> pretty op) go d (PEq fc l r) = parenthesise (d > appPrec) $ go startPrec l <++> equals <++> go startPrec r go d (PBracketed _ tm) = parens (go startPrec tm) go d (PDoBlock _ ns ds) = parenthesise (d > appPrec) $ group $ align $ hang 2 $ do_ <++> (vsep $ punctuate semi (prettyDo <$> ds)) go d (PBang _ tm) = "!" <+> go d tm go d (PIdiom _ tm) = enclose (pretty "[|") (pretty "|]") (go startPrec tm) go d (PList _ xs) = brackets (group $ align $ vsep $ punctuate comma (go startPrec <$> xs)) go d (PPair _ l r) = group $ parens (go startPrec l <+> comma <+> line <+> go startPrec r) go d (PDPair _ l (PImplicit _) r) = group $ parens (go startPrec l <++> pretty "**" <+> line <+> go startPrec r) go d (PDPair _ l ty r) = group $ parens (go startPrec l <++> colon <++> go startPrec ty <++> pretty "**" <+> line <+> go startPrec r) go d (PUnit _) = "()" go d (PIfThenElse _ x t e) = parenthesise (d > appPrec) $ group $ align $ hang 2 $ vsep [keyword "if" <++> go startPrec x, keyword "then" <++> go startPrec t, keyword "else" <++> go startPrec e] go d (PComprehension _ ret es) = group $ brackets (go startPrec (dePure ret) <++> pipe <++> vsep (punctuate comma (prettyDo . deGuard <$> es))) where dePure : PTerm -> PTerm dePure tm@(PApp _ (PRef _ n) arg) = if dropNS n == UN "pure" then arg else tm dePure tm = tm deGuard : PDo -> PDo deGuard tm@(DoExp fc (PApp _ (PRef _ n) arg)) = if dropNS n == UN "guard" then DoExp fc arg else tm deGuard tm = tm go d (PRewrite _ rule tm) = parenthesise (d > appPrec) $ group $ rewrite_ <++> go startPrec rule <+> line <+> in_ <++> go startPrec tm go d (PRange _ start Nothing end) = brackets (go startPrec start <++> pretty ".." <++> go startPrec end) go d (PRange _ start (Just next) end) = brackets (go startPrec start <+> comma <++> go startPrec next <++> pretty ".." <++> go startPrec end) go d (PRangeStream _ start Nothing) = brackets (go startPrec start <++> pretty "..") go d (PRangeStream _ start (Just next)) = brackets (go startPrec start <+> comma <++> go startPrec next <++> pretty "..") go d (PUnifyLog _ lvl tm) = go d tm go d (PPostfixProjs fc rec fields) = parenthesise (d > appPrec) $ go startPrec rec <++> dot <+> concatWith (surround dot) (go startPrec <$> fields) go d (PPostfixProjsSection fc fields args) = parens (dot <+> concatWith (surround dot) (go startPrec <$> fields) <+> fillSep (go appPrec <$> args)) go d (PWithUnambigNames fc ns rhs) = parenthesise (d > appPrec) $ group $ with_ <++> pretty ns <+> line <+> go startPrec rhs export render : {auto o : Ref ROpts REPLOpts} -> Doc IdrisAnn -> Core String render doc = do consoleWidth <- getConsoleWidth color <- getColor opts <- case consoleWidth of Nothing => do cols <- coreLift getTermCols pure $ MkLayoutOptions (AvailablePerLine cols 1) Just 0 => pure $ MkLayoutOptions Unbounded Just cw => pure $ MkLayoutOptions (AvailablePerLine (cast cw) 1) let layout = layoutPretty opts doc pure $ renderString $ if color then reAnnotateS colorAnn layout else unAnnotateS layout export renderWithoutColor : {auto o : Ref ROpts REPLOpts} -> Doc IdrisAnn -> Core String renderWithoutColor doc = do consoleWidth <- getConsoleWidth opts <- case consoleWidth of Nothing => do cols <- coreLift getTermCols pure $ MkLayoutOptions (AvailablePerLine cols 1) Just 0 => pure $ MkLayoutOptions Unbounded Just cw => pure $ MkLayoutOptions (AvailablePerLine (cast cw) 1) let layout = layoutPretty opts doc pure $ renderString $ unAnnotateS layout
import numpy as np def move_rows_around(mat, row_seq): res = [mat[row] for row in row_seq] return np.array(res) def make_mask_from_indices(total_len, indices): mask = np.zeros(total_len, dtype=bool) for i in indices: mask[i] = True return mask def make_opposite_masks_from_indices(total_len, indices): mask = make_mask_from_indices(total_len, indices) mask_not = ~mask return mask, mask_not
lemma islimpt_finite: fixes x :: "'a::t1_space" shows "finite s \<Longrightarrow> \<not> x islimpt s"
FrameFun=function() { vec=c(1,2,3,NA,NA,5) vecDF=data.frame(vec) length(vec) for(i in 1:6) { vec2DF=na.omit(vecDF) if(is.na(vecDF[i,1])) { print("Enter value to replace") v=as.integer(readline()) vecDF[i,1]=v } } vec2DF vecDF } FrameFun()
using ChaosTools using DynamicalSystemsBase using Test using OrdinaryDiffEq @testset "Uncertainty exponent / fractal boundaries" begin @testset "Test uncertainty orginal paper" begin ds = Systems.grebogi_map(rand(2)) θg = range(0, 2π, length = 251) xg = range(-0.5, 0.5, length = 251) bsn, att = basins_of_attraction((θg, xg), ds; show_progress = false) e, f, α = uncertainty_exponent(bsn; range_ε = 3:15) # In the paper the value is roughly 0.2 @test (0.2 ≤ α ≤ 0.3) end @testset "Test uncertainty Newton map" begin function newton_map(dz,z, p, n) f(x) = x^p[1]-1 df(x)= p[1]*x^(p[1]-1) z1 = z[1] + im*z[2] dz1 = f(z1)/df(z1) z1 = z1 - dz1 dz[1]=real(z1) dz[2]=imag(z1) return end # dummy function to keep the initializator happy function newton_map_J(J,z0, p, n) return end ds = DiscreteDynamicalSystem(newton_map,[0.1, 0.2], [3] , newton_map_J) xg = yg = range(-1.,1.,length=300) bsn,att = basins_of_attraction((xg, yg), ds; show_progress = false) e,f,α = uncertainty_exponent(bsn; range_ε = 5:30) # Value (published) from the box-counting dimension is 1.42. α ≃ 0.6 @test (0.55 ≤ α ≤ 0.65) end @testset "Basin entropy and Fractal test" begin ds = Systems.grebogi_map() θg=range(0,2π,length = 300) xg=range(-0.5,0.5,length = 300) basin, attractors = basins_of_attraction((θg,xg), ds; show_progress = false) Sb, Sbb = basin_entropy(basin, 6) @test 0.4 ≤ Sb ≤ 0.42 @test 0.6 ≤ Sbb ≤ 0.61 test_res, Sbb = basins_fractal_test(basin; ε = 5) @test test_res == :fractal ds = Systems.henon(zeros(2); a = 1.4, b = 0.3) xg = yg = range(-2.,2.,length = 300) basin, attractors = basins_of_attraction((xg,yg), ds; show_progress = false) test_res, Sbb = basins_fractal_test(basin; ε = 5) @test test_res == :smooth end end
#ifndef MONOTONE_DECOMPOSITION_HPP #define MONOTONE_DECOMPOSITION_HPP #include "point.hpp" #include "poly_line.hpp" #include "geometry.hpp" #include <boost/assert.hpp> #include <vector> class monotone_decomposition { public: struct monotone_subpath { poly_line line; unsigned begin_idx; unsigned end_idx; geometry::monoticity mono; }; std::vector<monotone_subpath> operator()(const poly_line& line) { auto subpaths = get_monotone_subpaths(line); for (auto& s : subpaths) { geometry::make_x_monotone_increasing(s.mono, s.line.coordinates); } return subpaths; } private: std::vector<monotone_subpath> get_monotone_subpaths(const poly_line& line) const; }; #endif
%STATSDTC Stats Decision tree Classifier (Matlab Stats Toolbox) % % W = STATSDTC(A,'PARAM1',val1,'PARAM2',val2,...) % W = A*STATSDTC([],'PARAM1',val1,'PARAM2',val2,...) % D = B*W % % INPUT % A Dataset used for training % PARAM1 Optional parameter, see CLASSIFICATIONTREE.FIT % B Dataset used for evaluation % % OUTPUT % W Decision tree classifier % D Classification matrix, dataset with posteriors % % DESCRIPTION % This is the PRTools interface to the CLASSIFICATIONTREE of the Matlab % Stats toolbox. See there for more information. It is assumed that objects % labels, feature labels and class priors are included in the dataset A. % % The decision tree is stored in W and can be retrieved by T = +W or by % T = getdata(W). The Stats toolbox command VIEW can be used to visualize % it, either in the command window (default) or graphically setting the % 'mode' options to 'graph'. % % SEE ALSO (<a href="http://37steps.com/prtools">PRTools Guide</a>) % DATASETS, MAPPINGS, DTC, TREEC, CLASSIFICATIONTREE, VIEW % Copyright: R.P.W. Duin, [email protected] function W = statsdtc(varargin) name = 'Stats DecTree'; if mapping_task(varargin,'definition') W = define_mapping(varargin,[],name); elseif mapping_task(varargin,'training') A = varargin{1}; data = +A; labels = getlabels(A); prior = getprior(A); featlab = getfeatlab(A); if ischar(featlab) featlab = cellstr(featlab); end tree = ClassificationTree.fit(data,labels,'prior',prior, ... 'PredictorNames',featlab,varargin{2:end}); W = trained_mapping(A,tree); else % evaluation [A,W] = deal(varargin{:}); tree = getdata(W); [dummy,post] = predict(tree,+A); W = setdat(A,post,W); end return
For 12-cup decanter brewers. Special paper grade assures optimum extraction of coffee’s taste. Perfect for coffees requiring exact brewing, like decaf and flavored coffees. Superior stay-in-place design prevents coffee grounds overflow. Paper stock used in the manufacturing of coffee filters is produced using an elemental chlorine-free (ECF) bleaching method.
module MARY_fRG include("basics/basics.jl") include("helpers/drawers.jl") include("helpers/triangulated.jl") include("helpers/refine.jl") include("helpers/interactions.jl") include("fermi/fermi.jl") include("flowequ/flow_equation.jl") end # module
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.sheaves.local_predicate import Mathlib.topology.sheaves.stalks import Mathlib.PostPort universes v namespace Mathlib /-! # Sheafification of `Type` valued presheaves We construct the sheafification of a `Type` valued presheaf, as the subsheaf of dependent functions into the stalks consisting of functions which are locally germs. We show that the stalks of the sheafification are isomorphic to the original stalks, via `stalk_to_fiber` which evaluates a germ of a dependent function at a point. We construct a morphism `to_sheafify` from a presheaf to (the underlying presheaf of) its sheafification, given by sending a section to its collection of germs. ## Future work Show that the map induced on stalks by `to_sheafify` is the inverse of `stalk_to_fiber`. Show sheafification is a functor from presheaves to sheaves, and that it is the left adjoint of the forgetful functor, following https://stacks.math.columbia.edu/tag/007X. -/ namespace Top.presheaf namespace sheafify /-- The prelocal predicate on functions into the stalks, asserting that the function is equal to a germ. -/ def is_germ {X : Top} (F : presheaf (Type v) X) : prelocal_predicate fun (x : ↥X) => stalk F x := prelocal_predicate.mk (fun (U : topological_space.opens ↥X) (f : (x : ↥U) → stalk F ↑x) => ∃ (g : category_theory.functor.obj F (opposite.op U)), ∀ (x : ↥U), f x = germ F x g) sorry /-- The local predicate on functions into the stalks, asserting that the function is locally equal to a germ. -/ def is_locally_germ {X : Top} (F : presheaf (Type v) X) : local_predicate fun (x : ↥X) => stalk F x := prelocal_predicate.sheafify (is_germ F) end sheafify /-- The sheafification of a `Type` valued presheaf, defined as the functions into the stalks which are locally equal to germs. -/ def sheafify {X : Top} (F : presheaf (Type v) X) : sheaf (Type v) X := subsheaf_to_Types sorry /-- The morphism from a presheaf to its sheafification, sending each section to its germs. (This forms the unit of the adjunction.) -/ def to_sheafify {X : Top} (F : presheaf (Type v) X) : F ⟶ sheaf.presheaf (sheafify F) := category_theory.nat_trans.mk fun (U : topological_space.opens ↥Xᵒᵖ) (f : category_theory.functor.obj F U) => { val := fun (x : ↥(opposite.unop U)) => germ F x f, property := sorry } /-- The natural morphism from the stalk of the sheafification to the original stalk. In `sheafify_stalk_iso` we show this is an isomorphism. -/ def stalk_to_fiber {X : Top} (F : presheaf (Type v) X) (x : ↥X) : stalk (sheaf.presheaf (sheafify F)) x ⟶ stalk F x := stalk_to_fiber (sheafify.is_locally_germ F) x theorem stalk_to_fiber_surjective {X : Top} (F : presheaf (Type v) X) (x : ↥X) : function.surjective (stalk_to_fiber F x) := sorry theorem stalk_to_fiber_injective {X : Top} (F : presheaf (Type v) X) (x : ↥X) : function.injective (stalk_to_fiber F x) := sorry /-- The isomorphism betweeen a stalk of the sheafification and the original stalk. -/ def sheafify_stalk_iso {X : Top} (F : presheaf (Type v) X) (x : ↥X) : stalk (sheaf.presheaf (sheafify F)) x ≅ stalk F x := equiv.to_iso (equiv.of_bijective (stalk_to_fiber F x) sorry)
State Before: F : Type ?u.8146 α : Type u_1 β : Type ?u.8152 R : Type ?u.8155 inst✝ : Monoid α n✝ : ℕ a : α n : ℕ ⊢ IsSquare a → IsSquare (a ^ n) State After: case intro F : Type ?u.8146 α : Type u_1 β : Type ?u.8152 R : Type ?u.8155 inst✝ : Monoid α n✝ n : ℕ a : α ⊢ IsSquare ((a * a) ^ n) Tactic: rintro ⟨a, rfl⟩ State Before: case intro F : Type ?u.8146 α : Type u_1 β : Type ?u.8152 R : Type ?u.8155 inst✝ : Monoid α n✝ n : ℕ a : α ⊢ IsSquare ((a * a) ^ n) State After: no goals Tactic: exact ⟨a ^ n, (Commute.refl _).mul_pow _⟩
function G = divgrad(M,options) % divgrad - compute either gradient or divergence. % % G = divgrad(M); % % if M is a 2D array, compute gradient, % if M is a 3D array, compute divergence. % Use centered finite differences. % % Copyright (c) 2007 Gabriel Peyre options.null = 0; if size(M,3)==2 G = mydiv(M,options); else G = mygrad(M,options); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function d = mydiv(g,options) bound = getoptions(options, 'bound', 'sym'); n = size(g,1); d = zeros(n); if strcmp(bound,'sym') d(2:end-1,:) = d(2:end-1,:) + ( g(3:end,:,1)-g(1:end-2,:,1) )/2; d(1,:) = d(1,:) + g(2,:,1)-g(1,:,1); d(end,:) = d(end,:) + g(end,:,1)-g(end-1,:,1); d(:,2:end-1) = d(:,2:end-1) + ( g(:,3:end,2)-g(:,1:end-2,2) )/2; d(:,1) = d(:,1) + g(:,2,2)-g(:,1,2); d(:,end) = d(:,end) + g(:,end,2)-g(:,end-1,2); else sel1 = [2:n 1]; sel2 = [n 1:n-1]; d = g(sel1,:,1)-g(sel2,:,1) + g(:,sel1,2)-g(:,sel2,2); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function g = mygrad(M,options) bound = getoptions(options, 'bound', 'sym'); n = size(M,1); g = zeros(n,n,2); if strcmp(bound,'sym') % on x g(2:end-1,:,1) = ( M(3:end,:)-M(1:end-2,:) )/2; g(1,:,1) = M(2,:)-M(1,:); g(end,:,1) = M(end,:)-M(end-1,:); % on y g(:,2:end-1,2) = ( M(:,3:end)-M(:,1:end-2,:) )/2; g(:,1,1) = M(2,:)-M(1,:); g(:,end,1) = M(:,end)-M(:,end-1); else sel1 = [2:n 1]; sel2 = [n 1:n-1]; g = cat( 3, M(sel1,:)-M(sel2,:), M(:,sel1)-M(:,sel2) )/2; end
function result = getMotionObject() objectname = findobj('name','Stepper Motor Simulator'); result =get(objectname,'UserData'); end
module Induction %default total plusZeroReduces : (n : Nat) -> n + 0 = n plusZeroReduces Z = refl plusZeroReduces (S k) = let ind = plusZeroReduces k in ?plusZeroSucc Induction.plusZeroSucc = proof intros rewrite ind trivial minusDiag : (n : Nat) -> minus n n = Z minusDiag Z = refl minusDiag (S k) = let ih = minusDiag k in ?minusDiagNeutral Induction.minusDiagNeutral = proof intros rewrite ih trivial multZeroIsZero : (n : Nat) -> mult n Z = Z multZeroIsZero Z = refl multZeroIsZero (S k) = let ih = multZeroIsZero k in ?multSuccByZeroIsZero Induction.multSuccByZeroIsZero = proof intros rewrite ih trivial plusNSuccMRefl : (left : Nat) -> (right : Nat) -> S (left + right) = left + (S right) plusNSuccMRefl Z right = refl plusNSuccMRefl (S k) right = let ih = plusNSuccMRefl k right in ?plusSuccRefl Induction.plusSuccRefl = proof intros rewrite ih trivial plusCommutes : (left : Nat) -> (right : Nat) -> left + right = right + left plusCommutes Z right = ?plusCommutesBaseCase plusCommutes (S left) right = let ih = plusCommutes left right in ?plusCommutesSuccCase Induction.plusCommutesBaseCase = proof intro rewrite sym (plusZeroReduces right) trivial Induction.plusCommutesSuccCase = proof intros rewrite (plusNSuccMRefl right left) rewrite ih trivial plusAssoc : (a : Nat) -> (b : Nat) -> (c : Nat) -> a + (b + c) = (a + b) + c plusAssoc Z b c = ?plusAssocBaseCase plusAssoc (S a) b c = let ih = plusAssoc a b c in ?plusAssocStepCase Induction.plusAssocBaseCase = proof intros trivial Induction.plusAssocStepCase = proof intros rewrite ih trivial double : Nat -> Nat double Z = Z double (S k) = (S (S (double k))) doublePlusRefl : (n : Nat) -> double n = n + n doublePlusRefl Z = refl doublePlusRefl (S n) = let ih = doublePlusRefl n in ?doublePlusStepCase Induction.doublePlusStepCase = proof intros rewrite sym ih rewrite (plusNSuccMRefl n n) trivial plusRearrange : (a:Nat) -> (b:Nat) -> (c:Nat) -> (d:Nat) -> (a + b) + (c + d) = (b + a) + (c + d) plusRearrange a b c d = ?plusRearrangeBase Induction.plusRearrangeBase = proof intros rewrite (plusCommutes a b) trivial plusSwap : (a:Nat) -> (b:Nat) -> (c:Nat) -> a + (b + c) = b + (a + c) plusSwap = ?plusSwapProof Induction.plusSwapProof = proof intros rewrite sym (plusAssoc b a c) rewrite (plusCommutes b a) rewrite (plusCommutes a b) rewrite(plusAssoc a b c) trivial
Fiderio & Sons has been successfully installing roofs in Connecticut homes since 1984. As professional roof installers, our top-notch services have earned us accreditation with the Better Business Bureau, in addition to awards from Houzz, Angie’s List, Remodeling Magazine and many others. For a job as important as installing your roof, you can trust the qualified experts of Fiderio & Sons! We know that it requires more than superior materials to resist to the intense winds, precipitation and temperature variation that is common in Connecticut – it takes expertise in roof installation. Our Connecticut roofing experts design and build residential roofing systems strong enough to deliver many years of reliable protection. Our roofing installers offer years of experience assessing your existing roof and selecting the right materials for your needs – not to mention the thousands of roof installation projects completed. Our roofs are built to last, provide a long service life and deliver exceptional value. Whether you are installing a new roof on your home addition or roof replacement on your home, we provide the quality materials and service you can count on. There are many types of roofing systems out there, and the right one for your home depends on the size and architectural style of your home, where it is located, and your own sense of style. At Fiderio & Sons, we leverage our expertise to assist with selection, and then we install roofing systems based on all three factors. Our experts work with each customer to ensure that they receive the right roofing materials and rain guttersystems, if needed, for their home. Thanks to our status as a CertainTeed 5-Star Contractor, we are able to offer a wide range of superior quality roofing for Connecticut homeowners. Asphalt Shingle Roofing: A traditional roofing choice for hundreds of years, asphalt roofing is durable, versatile and can be fit to nearly any home. There is a vast array of selection for asphalt shingles, with color, style and durability options for any style and budget. Fiderio & Sons is the roofing company Connecticut homeowners count on for superior quality roofing installation. Metal Roofing: Designed to outlast the majority of available roofing systems, metal roofing is the most durable option for roofing. Commonly used in commercial roofing projects, metal roofing is now a viable option for residential properties. Water tight and fire resistant, metal roofing from Fiderio and CertainTeed will keep your family safe and secure for years to come. To learn more about all of our roof installations or any of our other home remodeling services, call Fiderio & Sons today! You can speak to one of our friendly representatives to schedule your roofing consultation with our certified experts.
/- Copyright (c) 2022 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Kevin Buzzard -/ import tactic -- imports all the Lean tactics import group_theory.subgroup.basic -- import Lean's subgroups /- # Group homomorphisms mathlib has group homomorphisms. The type of group homomorphisms from `G` to `H` is called `monoid_hom G H`, but we hardly ever use that name; instead we use the notation, which is `G →* H`, i.e. "`*`-preserving map between groups". Note in particular that we do *not* write `f : G → H` for a group homomorphism and then have some function `is_group_hom : (G → H) → Prop` saying that it's a group homomorphism, we just have a completely new type, whose terms are pairs consisting of the function and the axiom that `f(g₁g₂)=f(g₁)f(g₂)` for all g₁ and g₂. -/ -- Let `G` and `H` be groups. variables {G H : Type} [group G] [group H] -- let `φ : G → H` be a group homomorphism variable (φ : G →* H) -- Even though `φ` is not technically a function (it's a pair consisting of a function and -- a proof), we can still evaluate `φ` at a term of type `G` and get a term of type `H`. -- let `a` be an element of G variable (a : G) -- let's make the element `φ(a)` of `H` example : H := φ a -- If you use this in a proof, you'll see that actually this is denoted `⇑φ g`; what this -- means is that `φ` is not itself a function, but there is a coercion from `G →* H` -- to `G → H` sending `φ` to the underlying function from `G` to `H` (so, it forgets the -- fact that φ is a group homomorphism and just remembers the function bit. -- Here's the basic API for group homomorphisms example (a b : G) : φ (a * b) = φ a * φ b := φ.map_mul a b example : φ 1 = 1 := φ.map_one example (a : G) : φ (a⁻¹) = (φ a)⁻¹ := φ.map_inv a -- The identity group homomorphism from `G` to `G` is called `monoid_hom.id G` example : monoid_hom.id G a = a := begin refl, -- true by definition end -- Let K be a third group. variables (K : Type) [group K] -- Let `ψ : H →* K` be another group homomorphism variable (ψ : H →* K) -- The composite of ψ and φ can't be written `ψ ∘ φ` in Lean, because `∘` is notation -- for function composition, and `φ` and `ψ` aren't functions, they're collections of -- data containing a function and some other things. So we use `monoid_hom.comp` to -- compose functions. We can use dot notation for this. example : G →* K := ψ.comp φ -- When are two group homomorphisms equal? When they agree on all inputs. The `ext` tactic -- knows this. -- The next three lemmas are pretty standard, but they are also in fact -- the axioms that show that groups form a category. lemma comp_id : φ.comp (monoid_hom.id G) = φ := begin ext x, refl, end lemma id_comp : (monoid_hom.id H).comp φ = φ := begin ext x, refl, end lemma comp_assoc {L : Type} [group L] (ρ : K →* L) : (ρ.comp ψ).comp φ = ρ.comp (ψ.comp φ) := begin refl, end -- The kernel of a group homomorphism `φ` is a subgroup of the source group. -- The elements of the kernel are *defined* to be `{x | φ x = 1}`. -- Note the use of dot notation to save us having to write `monoid_hom.ker`. -- `φ.ker` *means* `monoid_hom.ker φ` because `φ` has type `monoid_hom [something]` example (φ : G →* H) : subgroup G := φ.ker -- or `monoid_hom.ker φ` example (φ : G →* H) (x : G) : x ∈ φ.ker ↔ φ x = 1 := begin refl -- true by definition end -- Similarly the image is defined in the obvious way, with `monoid_hom.range` example (φ : G →* H) : subgroup H := φ.range example (φ : G →* H) (y : H) : y ∈ φ.range ↔ ∃ x : G, φ x = y := begin refl -- true by definition end -- `subgroup.map` is used for the image of a subgroup under a group hom example (φ : G →* H) (S : subgroup G) : subgroup H := S.map φ example (φ : G →* H) (S : subgroup G) (y : H) : y ∈ S.map φ ↔ ∃ x, x ∈ S ∧ φ x = y := begin refl, end -- and `subgroup.comap` is used for the preimage of a subgroup under a group hom. example (φ : G →* H) (S : subgroup H) : subgroup G := S.comap φ example (φ : G →* H) (T : subgroup H) (x : G) : x ∈ T.comap φ ↔ φ x ∈ T := begin refl, end -- Here are some basic facts about these constructions. -- Preimage of a subgroup along the identity map is the same subgroup example (S : subgroup G) : S.comap (monoid_hom.id G) = S := begin ext x, refl, end -- Image of a subgroup along the identity map is the same subgroup example (S : subgroup G) : S.map (monoid_hom.id G) = S := begin ext x, split, { rintro ⟨y, hy, rfl⟩, exact hy, }, { intro hx, exact ⟨x, hx, rfl⟩, }, end -- preimage preserves `≤` (i.e. if `S ≤ T` are subgroups of `H` then `φ⁻¹(S) ≤ φ⁻¹(T)`) example (φ : G →* H) (S T : subgroup H) (hST : S ≤ T) : S.comap φ ≤ T.comap φ := begin intros g hg, apply hST, exact hg, end -- image preserves `≤` (i.e. if `S ≤ T` are subgroups of `G` then `φ(S) ≤ φ(T)`) example (φ : G →* H) (S T : subgroup G) (hST : S ≤ T) : S.map φ ≤ T.map φ := begin rintros h ⟨g, hg, rfl⟩, refine ⟨g, _, rfl⟩, exact hST hg, end -- Pulling a subgroup back along one homomorphism and then another, is equal -- to pulling it back along the composite of the homomorphisms. example (φ : G →* H) (ψ : H →* K) (U : subgroup K) : U.comap (ψ.comp φ) = (U.comap ψ).comap φ := begin refl, end -- Pushing a subgroup along one homomorphism and then another is equal to -- pushing it forward along the composite of the homomorphisms. example (φ : G →* H) (ψ : H →* K) (S : subgroup G) : S.map (ψ.comp φ) = (S.map φ).map ψ := begin ext c, split, { rintro ⟨a, ha, rfl⟩, refine ⟨φ a, _, rfl⟩, exact ⟨a, ha, rfl⟩, }, { rintro ⟨b, ⟨a, ha, rfl⟩, rfl⟩, exact ⟨a, ha, rfl⟩, }, end
import subgroup_world.subgroup_one -- hide variables {G : Type} [group G] {H : set G} -- hide /- ## The inverse of an element is in the group In this easy lemma you have to prove that the inverse of an element in a subgroup is in the subgroup as well. -/ /- Lemma: If $H\leq G$, and $x \in H$, then $x^{-1} \in H$. -/ lemma subgroup.inv_mem' [h : subgroup H] {x : G} (hx : x ∈ H) : x⁻¹ ∈ H := begin have h2 := h.2 (1 : G) x subgroup.one_mem hx, rw show (x⁻¹ = 1 * x⁻¹), by group, assumption, end
%!TEX root = ../main.tex %------------------------------------------------------------------------------- \section{Setup} %------------------------------------------------------------------------------- We now present the basic setup of the EKW models. We first describe the economic framework, then turn to its mathematical formulation, and finally outline the calibration procedure. \input{sections/s-setup-economics} \input{sections/s-setup-mathematics} \input{sections/s-setup-calibration}
open import lib open import sum module grammar (form : Set)(_eq_ : form → form → 𝔹)(drop-form : (x y : form) → x ≡ y → x eq y ≡ tt)(rise-form : (x y : form) → x eq y ≡ tt → x ≡ y) where infix 7 _⇒_ data production : Set where _⇒_ : form → 𝕃 (form ⊎ char) → production record grammar {numprods : ℕ} : Set where constructor _,_ field start : form prods : 𝕍 production numprods open grammar splice : ℕ → 𝕃 (form ⊎ char) → form → 𝕃 (form ⊎ char) → 𝕃 (form ⊎ char) splice x [] _ _ = [] splice 0 ((inj₁ s) :: ss) s' ss' with s eq s' ... | tt = ss' ++ ss ... | ff = (inj₁ s) :: ss splice 0 (x :: ss) s' ss' = x :: ss splice (suc n) (s :: ss) s' ss' = s :: splice n ss s' ss' 𝕃inj₂ : ∀{ℓ ℓ'}{B : Set ℓ}{A : Set ℓ'} → 𝕃 A → 𝕃 (B ⊎ A) 𝕃inj₂ (x :: xs) = (inj₂ x) :: 𝕃inj₂ xs 𝕃inj₂ [] = [] 𝕃inj₁ : ∀{ℓ ℓ'}{B : Set ℓ}{A : Set ℓ'} → 𝕃 A → 𝕃 (A ⊎ B) 𝕃inj₁ (x :: xs) = (inj₁ x) :: 𝕃inj₁ xs 𝕃inj₁ [] = [] data derivation{numprods : ℕ} {g : grammar{numprods}} : 𝕃 (form ⊎ char) → 𝕃 char → Set where end : {ss : 𝕃 char} → derivation (𝕃inj₂ ss) ss step : ∀ {ss1 ss1' : 𝕃 (form ⊎ char)}{ss2 : 𝕃 char}{s : form}{ss : 𝕃 (form ⊎ char)} → (m n : ℕ) → (p : n < numprods ≡ tt) → nth𝕍 n p (prods g) ≡ (s ⇒ ss) → m < length ss1 ≡ tt → splice m ss1 s ss ≡ ss1' → derivation {g = g} ss1' ss2 → derivation ss1 ss2 splice-concat : ∀{l1 l2 target final : 𝕃 (form ⊎ char)}{n : ℕ}{slice : form} → splice n l1 slice target ≡ final → splice (n + (length l2)) (l2 ++ l1) slice target ≡ l2 ++ final splice-concat{l2 = []}{n = n} pr rewrite +0 n = pr splice-concat{l1}{x :: xs}{n = n} pr rewrite +suc n (length xs) | splice-concat{l1}{l2 = xs} pr = refl _=form⊎char_ : (x y : form ⊎ char) → 𝔹 _=form⊎char_ = =⊎ _eq_ _=char_ form⊎char-drop : (x y : form ⊎ char) → x ≡ y → x =form⊎char y ≡ tt form⊎char-drop = ≡⊎-to-= _eq_ _=char_ drop-form ≡char-to-= form⊎char-rise : (x y : form ⊎ char) → x =form⊎char y ≡ tt → x ≡ y form⊎char-rise = =⊎-to-≡ _eq_ _=char_ rise-form =char-to-≡ splice-concat2 : ∀{l1 l2 target final : 𝕃 (form ⊎ char)}{n : ℕ}{slice : form} → splice n l1 slice target ≡ final → n < length l1 ≡ tt → splice n (l1 ++ l2) slice target ≡ final ++ l2 splice-concat2{[]}{n = n} pr1 pr2 rewrite <-0 n = 𝔹-contra pr2 splice-concat2{inj₁ x :: xs}{l2}{target}{n = 0}{slice} pr1 pr2 with x eq slice ...| tt rewrite (sym pr1) | ++[] target | ++-assoc target xs l2 = refl ...| ff rewrite (sym pr1) = refl splice-concat2{inj₂ x :: xs}{l2}{target}{n = 0}{slice} pr1 pr2 rewrite (sym pr1) = refl splice-concat2{x :: xs}{l2}{target}{[]}{suc n} pr1 pr2 with pr1 ...| () splice-concat2{x :: xs}{l2}{target}{f :: fs}{suc n}{slice} pr1 pr2 with =𝕃-from-≡ _=form⊎char_ form⊎char-drop pr1 ...| s1 rewrite splice-concat2{xs}{l2}{target}{fs}{n}{slice} (≡𝕃-from-={l1 = splice n xs slice target}{fs} _=form⊎char_ form⊎char-rise (&&-snd{x =form⊎char f} s1)) pr2 | form⊎char-rise x f (&&-fst{x =form⊎char f} s1) = refl length+ : ∀{ℓ}{A : Set ℓ}(l1 l2 : 𝕃 A) → length (l1 ++ l2) ≡ length l1 + length l2 length+ [] l2 = refl length+ (x :: xs) l2 rewrite length+ xs l2 = refl <-h1 : ∀{x y a : ℕ} → x < y ≡ tt → x + a < y + a ≡ tt <-h1{x}{y}{0} p rewrite +0 x | +0 y = p <-h1{x}{y}{suc n} p rewrite +suc y n | +suc x n = <-h1{x}{y}{n} p <-h2 : ∀{a x y : ℕ} → a < x ≡ tt → a < x + y ≡ tt <-h2{a}{x}{0} p rewrite +0 x = p <-h2{a}{x}{suc y} p rewrite +suc x y with <-h2{a}{x}{y} p | <-suc (x + y) ...| pr1 | pr2 = <-trans{a}{x + y}{suc (x + y)} pr1 pr2 length𝕃inj₂ : ∀{ℓ ℓ'}{A : Set ℓ}{B : Set ℓ'} → (l : 𝕃 A) → length (𝕃inj₂{B = B} l) ≡ length l length𝕃inj₂{B = B} (x :: xs) rewrite length𝕃inj₂{B = B} xs = refl length𝕃inj₂ [] = refl 𝕃inj₂++ : ∀{ℓ ℓ'}{A : Set ℓ}{B : Set ℓ'} → (l1 l2 : 𝕃 A) → 𝕃inj₂{B = B} (l1 ++ l2) ≡ 𝕃inj₂ l1 ++ 𝕃inj₂ l2 𝕃inj₂++ [] l2 = refl 𝕃inj₂++{B = B} (x :: xs) l2 rewrite 𝕃inj₂++{B = B} xs l2 = refl infixr 10 _deriv++_ _deriv++_ : {l2 l4 : 𝕃 char}{l1 l3 : 𝕃 (form ⊎ char)}{n : ℕ}{gr : grammar{n}} → derivation{g = gr} l1 l2 → derivation{g = gr} l3 l4 → derivation{g = gr} (l1 ++ l3) (l2 ++ l4) _deriv++_{l2}{l4} end end rewrite sym (𝕃inj₂++{B = form} l2 l4) = end _deriv++_{l2}{l4}{l1}{l3} f (step{ss1' = ss1'}{s = s}{ss} a b pr1 pr2 pr3 pr4 next) with <-h1{a}{length l3}{length l1} pr3 ...| pr5 rewrite +comm (length l3) (length l1) | (sym (length+ l1 l3)) = step{ss1 = l1 ++ l3}{l1 ++ ss1'}{l2 ++ l4} (a + (length l1)) b pr1 pr2 pr5 (splice-concat{l3}{l1} pr4) (_deriv++_ f next) _deriv++_{l2}{l4}{l1} (step{ss1' = ss1'}{s = s}{ss} a b pr1 pr2 pr3 pr4 next) end with <-h2{a}{length l1}{length (𝕃inj₂{B = form} l4)} pr3 ...| pr5 rewrite sym (length+ l1 (𝕃inj₂ l4)) = step{ss1 = l1 ++ 𝕃inj₂ l4}{ss1' ++ 𝕃inj₂ l4}{l2 ++ l4} a b pr1 pr2 pr5 (splice-concat2{l1}{𝕃inj₂ l4} pr4 pr3) (_deriv++_ next end)
import data.real.basic variables a b c : ℝ #check le_antisymm #check le_min #check le_trans #check min_le_right a b #check min_le_left b c -- BEGIN example : min (min a b) c = min a (min b c) := begin apply le_antisymm, { apply le_min, exact le_trans (min_le_left (min a b) c) (min_le_left a b), apply le_min, exact le_trans (min_le_left (min a b) c) (min_le_right a b), exact min_le_right (min a b) c, }, { apply le_min, apply le_min, exact min_le_left a (min b c), exact le_trans (min_le_right a (min b c)) (min_le_left b c), exact le_trans (min_le_right a (min b c)) (min_le_right b c), }, end -- END
# I'll be using dplyr to handle dataframes library(dplyr) # For codebook require(knitr) require(markdown) # Set some vars setwd("~/development/GettingAndCleaningData/") data_path <- paste(getwd(), "/UCI\ HAR\ Dataset", sep="") test_path <- paste(data_path, "/test", sep="") train_path <- paste(data_path, "/train", sep="") # 1. Merges the training and the test sets to create one data set. # 2. Extracts only the measurements on the mean and standard deviation for each measurement. # 3. Uses descriptive activity names to name the activities in the data set # 4. Appropriately labels the data set with descriptive variable names. # 5. From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject. # Step 1. Merges the training and the test sets to create one data set. # Download the data and unzip url <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip" dataset_file <- "dataset.zip" if (!file.exists(file.path(getwd(), dataset_file))) { download.file(url, dataset_file, method="curl") } unzip(file.path(dataset_file), list = FALSE, overwrite = TRUE, unzip = "internal", setTimes = FALSE) # Slurp in all the data for test and training data_Y_test <- read.table(file.path(test_path, "y_test.txt"), header = FALSE) data_X_test <- read.table(file.path(test_path, "X_test.txt"), header = FALSE) data_subject_test <- read.table(file.path(test_path, "subject_test.txt"), header = FALSE) data_Y_train <- read.table(file.path(train_path, "y_train.txt" ), header = FALSE) data_X_train <- read.table(file.path(train_path, "X_train.txt" ), header = FALSE) data_subject_train <- read.table(file.path(train_path, "subject_train.txt" ), header = FALSE) # I'm using dplyr rbind_list to put the dataset rows together # dplyr's data frames are easier to deal with # The features are from the X_test and X_train data data_features <- rbind_list(data_X_test, data_X_train) # The subject data are from the subject_test and subject_train data data_subject <- rbind_list(data_subject_test, data_subject_train) # The activity data are from the Y_test and Y_train data data_activity <- rbind_list(data_Y_test, data_Y_train) # Rename labels # Easy ones first data_subject <- rename(data_subject, subject=V1) data_activity <- rename(data_activity, activity=V1) # Rename the features # Get the feature names feature_names <- tbl_df(read.table(file.path(data_path, "features.txt"), head=FALSE)) # Using that df, rename the columns in data_features names(data_features)<- feature_names$V2 # Finally, merge everything together final_data <- bind_cols(data_subject, data_activity, data_features) # Step 2. Extracts only the measurements on the mean and standard deviation for each measurement. # Clean up the column names valid_column_names <- make.names(names=names(final_data), unique=TRUE, allow_ = TRUE) names(final_data) <- valid_column_names # Get the subset, the escaped \\. is due to the make.names function stripping out the () extracted_data <- select(final_data, subject, activity, matches("mean\\.", ignore.case = FALSE), contains("std")) # Step 3. Uses descriptive activity names to name the activities in the data set # The activities in the dataset are referenced by a number # There are six possible activities defined in the file # Read the acivity labels file activity_labels <- read.table(file.path(data_path, "activity_labels.txt"), header = FALSE) # Convert into a factor and replace those ids in the dataset, use the second column from the file for the description extracted_data$activity <- factor(extracted_data$activity, levels=activity_labels$V1, labels=activity_labels$V2) # Step 4. Appropriately labels the data set with descriptive variable names. # I couldn't figure out how to do this in dplyr, so I went with a gsub solution # The labels are a little cryptic, I'm going to clean them up a little # 'std' = Standard.deviation # 'mean' = Mean # 't' = Time # 'f' = FFT # 'Acc' = Accelerometer # 'Gyro' = Gyroscope # 'Mag' = Magnitude # 'BodyBody' = Body # '...' = . # Cleans up the stuff from make.names # '..$' = . # Cleans up the stuff I made names(extracted_data) <- gsub("std", "Standard.deviation", names(extracted_data)) names(extracted_data) <- gsub("mean", "Mean", names(extracted_data)) names(extracted_data) <- gsub("^t", "Time", names(extracted_data)) names(extracted_data) <- gsub("^f", "FFT", names(extracted_data)) names(extracted_data) <- gsub("Acc", "Accelerometer", names(extracted_data)) names(extracted_data) <- gsub("Gyro", "Gyroscope", names(extracted_data)) names(extracted_data) <- gsub("Mag", "Magnitude", names(extracted_data)) names(extracted_data) <- gsub("BodyBody", "Body", names(extracted_data)) names(extracted_data) <- gsub("\\.\\.\\.", ".", names(extracted_data)) names(extracted_data) <- gsub("\\.\\.$", "", names(extracted_data)) # Step 5. From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject. # I tried chaining here tidy_data <- extracted_data %>% group_by(subject, activity) %>% summarise_each(funs(mean)) # Save the tidy_data to a text file in the working directory write.table(tidy_data, file = "tidy_data.txt", row.names = FALSE) # Make codebook knit("makeCodebook.Rmd", output = "codebook.md", encoding = "ISO8859-1", quiet = TRUE)
Formal statement is: lemma tendsto_add_filterlim_at_infinity: fixes c :: "'b::real_normed_vector" and F :: "'a filter" assumes "(f \<longlongrightarrow> c) F" and "filterlim g at_infinity F" shows "filterlim (\<lambda>x. f x + g x) at_infinity F" Informal statement is: If $f$ converges to $c$ and $g$ tends to infinity, then $f + g$ tends to infinity.
import numpy as np import tensorflow as tf def evaluate_mAP(result): mAP = 0. for _, (query, ranklist) in result: query_class = query.split("@")[0] correct_count = 0. pk_sum = 0. for i, item in enumerate(ranklist): item_class= item.split("@")[0] if query_class == item_class: correct_count += 1. pk_sum += correct_count/(i+1.) if correct_count == 0: continue mAP += pk_sum / correct_count return mAP / len(result) def evaluate_rank(result): mAP = 0. min_first_1_at_K = 0. mean_recall_at_K = [0 for i in range(len(result[0][1][1]))] for _, (query, ranklist) in result: query_class = query.split("@")[0] correct_count = 0 pk_sum = 0. for i, item in enumerate(ranklist): item_class= item.split("@")[0] if query_class == item_class: correct_count += 1. pk_sum += correct_count/(i+1.) if not correct_count: correct_count = 1 recall_count = 0. min_counted = False for k, item in enumerate(ranklist): item_class = item.split("@")[0] if query_class == item_class: recall_count += 1. mean_recall_at_K[k] += recall_count/(correct_count) if recall_count == correct_count and not min_counted: min_first_1_at_K += (k+1) min_counted = True mAP += pk_sum / correct_count min_first_1_at_K = min_first_1_at_K / len(result) mean_recall_at_K = [recall/len(result) for recall in mean_recall_at_K] return mAP / len(result), mean_recall_at_K, min_first_1_at_K
(* * Copyright 2022, Proofcraft Pty Ltd * Copyright 2014, General Dynamics C4 Systems * * SPDX-License-Identifier: GPL-2.0-only *) (* Contains proofs that fastpath + callKernel is semantically identical to callKernel. *) theory Fastpath_Equiv imports Fastpath_Defs IsolatedThreadAction Refine.RAB_FN begin lemma setCTE_obj_at'_queued: "\<lbrace>obj_at' (\<lambda>tcb. P (tcbQueued tcb)) t\<rbrace> setCTE p v \<lbrace>\<lambda>rv. obj_at' (\<lambda>tcb. P (tcbQueued tcb)) t\<rbrace>" unfolding setCTE_def by (rule setObject_cte_obj_at_tcb', simp+) crunch obj_at'_queued: cteInsert "obj_at' (\<lambda>tcb. P (tcbQueued tcb)) t" (wp: setCTE_obj_at'_queued crunch_wps) crunch obj_at'_not_queued: emptySlot "obj_at' (\<lambda>a. \<not> tcbQueued a) p" (wp: setCTE_obj_at'_queued) lemma getEndpoint_obj_at': "\<lbrace>obj_at' P ptr\<rbrace> getEndpoint ptr \<lbrace>\<lambda>rv s. P rv\<rbrace>" apply (wp getEndpoint_wp) apply (clarsimp simp: obj_at'_def projectKOs) done lemmas setEndpoint_obj_at_tcb' = setEndpoint_obj_at'_tcb lemma tcbSchedEnqueue_tcbContext[wp]: "\<lbrace>obj_at' (\<lambda>tcb. P ((atcbContextGet o tcbArch) tcb)) t\<rbrace> tcbSchedEnqueue t' \<lbrace>\<lambda>rv. obj_at' (\<lambda>tcb. P ((atcbContextGet o tcbArch) tcb)) t\<rbrace>" apply (rule tcbSchedEnqueue_obj_at_unchangedT[OF all_tcbI]) apply simp done lemma setCTE_tcbContext: "\<lbrace>obj_at' (\<lambda>tcb. P ((atcbContextGet o tcbArch) tcb)) t\<rbrace> setCTE slot cte \<lbrace>\<lambda>rv. obj_at' (\<lambda>tcb. P ((atcbContextGet o tcbArch) tcb)) t\<rbrace>" apply (simp add: setCTE_def) apply (rule setObject_cte_obj_at_tcb', simp_all) done context begin interpretation Arch . (*FIXME: arch_split*) lemma seThreadState_tcbContext: "\<lbrace>obj_at' (\<lambda>tcb. P ((atcbContextGet o tcbArch) tcb)) t\<rbrace> setThreadState a b \<lbrace>\<lambda>_. obj_at' (\<lambda>tcb. P ((atcbContextGet o tcbArch) tcb)) t\<rbrace>" apply (rule setThreadState_obj_at_unchanged) apply (clarsimp simp: atcbContext_def)+ done lemma setBoundNotification_tcbContext: "\<lbrace>obj_at' (\<lambda>tcb. P ((atcbContextGet o tcbArch) tcb)) t\<rbrace> setBoundNotification a b \<lbrace>\<lambda>_. obj_at' (\<lambda>tcb. P ((atcbContextGet o tcbArch) tcb)) t\<rbrace>" apply (rule setBoundNotification_obj_at_unchanged) apply (clarsimp simp: atcbContext_def)+ done declare comp_apply [simp del] crunch tcbContext[wp]: deleteCallerCap "obj_at' (\<lambda>tcb. P ((atcbContextGet o tcbArch) tcb)) t" (wp: setEndpoint_obj_at_tcb' setBoundNotification_tcbContext setNotification_tcb crunch_wps seThreadState_tcbContext simp: crunch_simps unless_def) declare comp_apply [simp] crunch ksArch[wp]: asUser "\<lambda>s. P (ksArchState s)" (wp: crunch_wps) definition tcbs_of :: "kernel_state => word32 => tcb option" where "tcbs_of s = (%x. if tcb_at' x s then projectKO_opt (the (ksPSpace s x)) else None)" lemma obj_at_tcbs_of: "obj_at' P t s = (EX tcb. tcbs_of s t = Some tcb & P tcb)" apply (simp add: tcbs_of_def split: if_split) apply (intro conjI impI) apply (clarsimp simp: obj_at'_def projectKOs) apply (clarsimp simp: obj_at'_weakenE[OF _ TrueI]) done lemma st_tcb_at_tcbs_of: "st_tcb_at' P t s = (EX tcb. tcbs_of s t = Some tcb & P (tcbState tcb))" by (simp add: st_tcb_at'_def obj_at_tcbs_of) lemma tcbs_of_ko_at': "\<lbrakk> tcbs_of s p = Some tcb \<rbrakk> \<Longrightarrow> ko_at' tcb p s" by (simp add: obj_at_tcbs_of) lemma tcbs_of_valid_tcb': "\<lbrakk> valid_objs' s; tcbs_of s p = Some tcb \<rbrakk> \<Longrightarrow> valid_tcb' tcb s" by (frule tcbs_of_ko_at') (drule (1) ko_at_valid_objs', auto simp: projectKOs valid_obj'_def) lemma acc_CNodeCap_repr: "isCNodeCap cap \<Longrightarrow> cap = CNodeCap (capCNodePtr cap) (capCNodeBits cap) (capCNodeGuard cap) (capCNodeGuardSize cap)" by (clarsimp simp: isCap_simps) lemma valid_cnode_cap_cte_at': "\<lbrakk> s \<turnstile>' c; isCNodeCap c; ptr = capCNodePtr c; v < 2 ^ capCNodeBits c \<rbrakk> \<Longrightarrow> cte_at' (ptr + v * 2^cteSizeBits) s" apply (drule less_mask_eq) apply (drule(1) valid_cap_cte_at'[where addr=v]) apply (simp add: mult.commute mult.left_commute) done lemmas valid_cnode_cap_cte_at'' = valid_cnode_cap_cte_at'[simplified objBits_defs, simplified] declare of_int_sint_scast[simp] lemma of_bl_from_bool: "of_bl [x] = from_bool x" by (cases x, simp_all add: from_bool_def) lemma dmo_clearExMonitor_setCurThread_swap: "(do _ \<leftarrow> doMachineOp ARM_HYP.clearExMonitor; setCurThread thread od) = (do _ \<leftarrow> setCurThread thread; doMachineOp ARM_HYP.clearExMonitor od)" apply (simp add: setCurThread_def doMachineOp_def split_def) apply (rule oblivious_modify_swap[symmetric]) apply (intro oblivious_bind, simp_all) done lemma pd_at_asid_inj': "pd_at_asid' pd asid s \<Longrightarrow> pd_at_asid' pd' asid s \<Longrightarrow> pd' = pd" by (clarsimp simp: pd_at_asid'_def obj_at'_def) lemma bind_case_sum_rethrow: "rethrowFailure fl f >>= case_sum e g = f >>= case_sum (e \<circ> fl) g" apply (simp add: rethrowFailure_def handleE'_def bind_assoc) apply (rule bind_cong[OF refl]) apply (simp add: throwError_bind split: sum.split) done declare empty_fail_assertE[iff] declare empty_fail_resolveAddressBits[iff] lemma lookupExtraCaps_null: "msgExtraCaps info = 0 \<Longrightarrow> lookupExtraCaps thread buffer info = returnOk []" by (clarsimp simp: lookupExtraCaps_def getExtraCPtrs_def liftE_bindE upto_enum_step_def mapM_Nil split: Types_H.message_info.split option.split) lemma isRecvEP_endpoint_case: "isRecvEP ep \<Longrightarrow> case_endpoint f g h ep = f (epQueue ep)" by (clarsimp simp: isRecvEP_def split: endpoint.split_asm) lemma unifyFailure_catch_If: "catch (unifyFailure f >>=E g) h = f >>= (\<lambda>rv. if isRight rv then catch (g (theRight rv)) h else h ())" apply (simp add: unifyFailure_def rethrowFailure_def handleE'_def catch_def bind_assoc bind_bindE_assoc cong: if_cong) apply (rule bind_cong[OF refl]) apply (simp add: throwError_bind isRight_def return_returnOk split: sum.split) done lemma st_tcb_at_not_in_ep_queue: "\<lbrakk> st_tcb_at' P t s; ko_at' ep epptr s; sym_refs (state_refs_of' s); ep \<noteq> IdleEP; \<And>ts. P ts \<Longrightarrow> tcb_st_refs_of' ts = {} \<rbrakk> \<Longrightarrow> t \<notin> set (epQueue ep)" apply clarsimp apply (drule(1) sym_refs_ko_atD') apply (cases ep, simp_all add: st_tcb_at_refs_of_rev') apply (fastforce simp: st_tcb_at'_def obj_at'_def projectKOs)+ done lemma st_tcb_at_not_in_ntfn_queue: "\<lbrakk> st_tcb_at' P t s; ko_at' ntfn ntfnptr s; sym_refs (state_refs_of' s); ntfnObj ntfn = WaitingNtfn xs; \<And>ts. P ts \<Longrightarrow> (ntfnptr, TCBSignal) \<notin> tcb_st_refs_of' ts \<rbrakk> \<Longrightarrow> t \<notin> set xs" apply (drule(1) sym_refs_ko_atD') apply (clarsimp simp: st_tcb_at_refs_of_rev') apply (drule_tac x="(t, NTFNSignal)" in bspec, simp) apply (fastforce simp: st_tcb_at'_def obj_at'_def projectKOs ko_wp_at'_def tcb_bound_refs'_def) done lemma sym_refs_upd_sD: "\<lbrakk> sym_refs ((state_refs_of' s) (p := S)); valid_pspace' s; ko_at' ko p s; refs_of' (injectKO koEx) = S; objBits koEx = objBits ko \<rbrakk> \<Longrightarrow> \<exists>s'. sym_refs (state_refs_of' s') \<and> (\<forall>p' (ko' :: endpoint). ko_at' ko' p' s \<and> injectKO ko' \<noteq> injectKO ko \<longrightarrow> ko_at' ko' p' s') \<and> (\<forall>p' (ko' :: Structures_H.notification). ko_at' ko' p' s \<and> injectKO ko' \<noteq> injectKO ko \<longrightarrow> ko_at' ko' p' s') \<and> (ko_at' koEx p s')" apply (rule exI, rule conjI) apply (rule state_refs_of'_upd[where ko'="injectKO koEx" and ptr=p and s=s, THEN ssubst[where P=sym_refs], rotated 2]) apply simp+ apply (clarsimp simp: obj_at'_def ko_wp_at'_def projectKOs) apply (clarsimp simp: project_inject objBits_def) apply (clarsimp simp: obj_at'_def ps_clear_upd projectKOs split: if_split) apply (clarsimp simp: project_inject objBits_def) apply auto done lemma sym_refs_upd_tcb_sD: "\<lbrakk> sym_refs ((state_refs_of' s) (p := {r \<in> state_refs_of' s p. snd r = TCBBound})); valid_pspace' s; ko_at' (tcb :: tcb) p s \<rbrakk> \<Longrightarrow> \<exists>s'. sym_refs (state_refs_of' s') \<and> (\<forall>p' (ko' :: endpoint). ko_at' ko' p' s \<longrightarrow> ko_at' ko' p' s') \<and> (\<forall>p' (ko' :: Structures_H.notification). ko_at' ko' p' s \<longrightarrow> ko_at' ko' p' s') \<and> (st_tcb_at' ((=) Running) p s')" apply (drule(2) sym_refs_upd_sD[where koEx="makeObject\<lparr>tcbState := Running, tcbBoundNotification := tcbBoundNotification tcb\<rparr>"]) apply (clarsimp dest!: ko_at_state_refs_ofD') apply (simp add: objBits_simps) apply (erule exEI) apply clarsimp apply (auto simp: st_tcb_at'_def elim!: obj_at'_weakenE) done lemma updateCap_cte_wp_at_cteMDBNode: "\<lbrace>cte_wp_at' (\<lambda>cte. P (cteMDBNode cte)) p\<rbrace> updateCap ptr cap \<lbrace>\<lambda>rv. cte_wp_at' (\<lambda>cte. P (cteMDBNode cte)) p\<rbrace>" apply (wp updateCap_cte_wp_at_cases) apply (simp add: o_def) done lemma ctes_of_Some_cte_wp_at: "ctes_of s p = Some cte \<Longrightarrow> cte_wp_at' P p s = P cte" by (clarsimp simp: cte_wp_at_ctes_of) lemma user_getreg_wp: "\<lbrace>\<lambda>s. tcb_at' t s \<and> (\<forall>rv. obj_at' (\<lambda>tcb. (atcbContextGet o tcbArch) tcb r = rv) t s \<longrightarrow> Q rv s)\<rbrace> asUser t (getRegister r) \<lbrace>Q\<rbrace>" apply (rule_tac Q="\<lambda>rv s. \<exists>rv'. rv' = rv \<and> Q rv' s" in hoare_post_imp) apply simp apply (rule hoare_pre, wp hoare_vcg_ex_lift user_getreg_rv) apply (clarsimp simp: obj_at'_def) done lemma setUntypedCapAsFull_replyCap[simp]: "setUntypedCapAsFull cap (ReplyCap curThread False cg) slot = return ()" by (clarsimp simp:setUntypedCapAsFull_def isCap_simps) lemma option_case_liftM_getNotification_wp: "\<lbrace>\<lambda>s. \<forall>rv. (case x of None \<Rightarrow> rv = v | Some p \<Rightarrow> obj_at' (\<lambda>ntfn. f ntfn = rv) p s) \<longrightarrow> Q rv s\<rbrace> case x of None \<Rightarrow> return v | Some ptr \<Rightarrow> liftM f $ getNotification ptr \<lbrace> Q \<rbrace>" apply (rule hoare_pre, (wpc; wp getNotification_wp)) apply (auto simp: obj_at'_def) done lemma threadSet_st_tcb_at_state: "\<lbrace>\<lambda>s. tcb_at' t s \<longrightarrow> (if p = t then obj_at' (\<lambda>tcb. P (tcbState (f tcb))) t s else st_tcb_at' P p s)\<rbrace> threadSet f t \<lbrace>\<lambda>_. st_tcb_at' P p\<rbrace>" apply (rule hoare_chain) apply (rule threadSet_obj_at'_really_strongest) prefer 2 apply (simp add: st_tcb_at'_def) apply (clarsimp split: if_splits simp: st_tcb_at'_def o_def) done lemma recv_ep_queued_st_tcb_at': "\<lbrakk> ko_at' (Structures_H.endpoint.RecvEP ts) epptr s ; t \<in> set ts; sym_refs (state_refs_of' s) \<rbrakk> \<Longrightarrow> st_tcb_at' isBlockedOnReceive t s" apply (drule obj_at_ko_at') apply clarsimp apply (drule (1) sym_refs_ko_atD') apply (clarsimp simp: pred_tcb_at'_def obj_at'_real_def refs_of_rev') apply (erule_tac x=t in ballE; clarsimp?) apply (erule ko_wp_at'_weakenE) apply (clarsimp simp: isBlockedOnReceive_def projectKOs) done lemma valid_ep_typ_at_lift': "\<lbrakk> \<And>p. \<lbrace>typ_at' TCBT p\<rbrace> f \<lbrace>\<lambda>rv. typ_at' TCBT p\<rbrace> \<rbrakk> \<Longrightarrow> \<lbrace>\<lambda>s. valid_ep' ep s\<rbrace> f \<lbrace>\<lambda>rv s. valid_ep' ep s\<rbrace>" apply (cases ep, simp_all add: valid_ep'_def) apply (wp hoare_vcg_const_Ball_lift typ_at_lifts | assumption)+ done lemma threadSet_tcbState_valid_objs: "\<lbrace>valid_tcb_state' st and valid_objs'\<rbrace> threadSet (tcbState_update (\<lambda>_. st)) t \<lbrace>\<lambda>rv. valid_objs'\<rbrace>" apply (wp threadSet_valid_objs') apply (clarsimp simp: valid_tcb'_def tcb_cte_cases_def) done lemma possibleSwitchTo_rewrite: "monadic_rewrite True True (\<lambda>s. obj_at' (\<lambda>tcb. tcbPriority tcb = destPrio \<and> tcbDomain tcb = destDom) t s \<and> ksSchedulerAction s = ResumeCurrentThread \<and> ksCurThread s = thread \<and> ksCurDomain s = curDom \<and> destDom = curDom) (possibleSwitchTo t) (setSchedulerAction (SwitchToThread t))" supply if_split[split del] apply (simp add: possibleSwitchTo_def) (* under current preconditions both branch conditions are false *) apply (monadic_rewrite_l monadic_rewrite_if_l_False \<open>wpsimp wp: threadGet_wp cd_wp\<close>) apply (monadic_rewrite_l monadic_rewrite_if_l_False \<open>wpsimp wp: threadGet_wp cd_wp\<close>) (* discard unused getters before setSchedulerAction *) apply (simp add: getCurThread_def curDomain_def gets_bind_ign getSchedulerAction_def) apply (monadic_rewrite_symb_exec_l_drop, rule monadic_rewrite_refl) apply (auto simp: obj_at'_def) done lemma scheduleSwitchThreadFastfail_False_wp: "\<lbrace>\<lambda>s. ct \<noteq> it \<and> cprio \<le> tprio \<rbrace> scheduleSwitchThreadFastfail ct it cprio tprio \<lbrace>\<lambda>rv s. \<not> rv \<rbrace>" unfolding scheduleSwitchThreadFastfail_def by (wp threadGet_wp) (auto dest!: obj_at_ko_at' simp: le_def obj_at'_def) lemma lookupBitmapPriority_lift: assumes prqL1: "\<And>P. \<lbrace>\<lambda>s. P (ksReadyQueuesL1Bitmap s)\<rbrace> f \<lbrace>\<lambda>_ s. P (ksReadyQueuesL1Bitmap s)\<rbrace>" and prqL2: "\<And>P. \<lbrace>\<lambda>s. P (ksReadyQueuesL2Bitmap s)\<rbrace> f \<lbrace>\<lambda>_ s. P (ksReadyQueuesL2Bitmap s)\<rbrace>" shows "\<lbrace>\<lambda>s. P (lookupBitmapPriority d s) \<rbrace> f \<lbrace>\<lambda>_ s. P (lookupBitmapPriority d s) \<rbrace>" unfolding lookupBitmapPriority_def apply (rule hoare_pre) apply (wps prqL1 prqL2) apply wpsimp+ done (* slow path additionally requires current thread not idle *) definition "fastpathBestSwitchCandidate t \<equiv> \<lambda>s. ksReadyQueuesL1Bitmap s (ksCurDomain s) = 0 \<or> (\<forall>tprio. obj_at' (\<lambda>tcb. tcbPriority tcb = tprio) t s \<longrightarrow> (obj_at' (\<lambda>tcb. tcbPriority tcb \<le> tprio) (ksCurThread s) s \<or> lookupBitmapPriority (ksCurDomain s) s \<le> tprio))" lemma fastpathBestSwitchCandidateI: "\<lbrakk> ksReadyQueuesL1Bitmap s (ksCurDomain s) = 0 \<or> tcbPriority ctcb \<le> tcbPriority ttcb \<or> lookupBitmapPriority (ksCurDomain s) s \<le> tcbPriority ttcb; ko_at' ttcb t s; ko_at' ctcb (ksCurThread s) s\<rbrakk> \<Longrightarrow> fastpathBestSwitchCandidate t s" unfolding fastpathBestSwitchCandidate_def by normalise_obj_at' lemma fastpathBestSwitchCandidate_lift: assumes ct[wp]: "\<And>P. \<lbrace>\<lambda>s. P (ksCurThread s) \<rbrace> f \<lbrace> \<lambda>_ s. P (ksCurThread s) \<rbrace>" assumes cd[wp]: "\<And>P. \<lbrace>\<lambda>s. P (ksCurDomain s) \<rbrace> f \<lbrace> \<lambda>_ s. P (ksCurDomain s) \<rbrace>" assumes l1[wp]: "\<And>P. \<lbrace>\<lambda>s. P (ksReadyQueuesL1Bitmap s) \<rbrace> f \<lbrace> \<lambda>_ s. P (ksReadyQueuesL1Bitmap s) \<rbrace>" assumes l2[wp]: "\<And>P. \<lbrace>\<lambda>s. P (ksReadyQueuesL2Bitmap s) \<rbrace> f \<lbrace> \<lambda>_ s. P (ksReadyQueuesL2Bitmap s) \<rbrace>" assumes p[wp]: "\<And>P t. \<lbrace> obj_at' (\<lambda>tcb. P (tcbPriority tcb)) t \<rbrace> f \<lbrace> \<lambda>_. obj_at' (\<lambda>tcb. P (tcbPriority tcb)) t \<rbrace>" shows "\<lbrace> tcb_at' t and fastpathBestSwitchCandidate t \<rbrace> f \<lbrace>\<lambda>rv. fastpathBestSwitchCandidate t \<rbrace>" unfolding fastpathBestSwitchCandidate_def lookupBitmapPriority_def l1IndexToPrio_def apply (rule hoare_pre) apply (rule hoare_lift_Pf2[where f=ksCurDomain]) apply (wp hoare_vcg_disj_lift hoare_vcg_all_lift) apply (rule hoare_lift_Pf2[where f=ksCurThread]) apply (rule hoare_lift_Pf2[where f=ksReadyQueuesL1Bitmap]) apply (rule hoare_lift_Pf2[where f=ksReadyQueuesL2Bitmap]) apply (wp hoare_vcg_imp_lift') apply (strengthen not_obj_at'_strengthen) apply (wpsimp simp: comp_def wp: l1 l2 hoare_vcg_disj_lift)+ apply (drule (1) tcb_at_not_obj_at_elim'[rotated]) apply (rename_tac tprio, erule_tac x=tprio in allE) apply clarsimp apply (drule (1) tcb_at_not_obj_at_elim'[rotated]) apply (clarsimp simp: obj_at'_def) done lemma fastpathBestSwitchCandidate_ksSchedulerAction_simp[simp]: "fastpathBestSwitchCandidate t (s\<lparr>ksSchedulerAction := a\<rparr>) = fastpathBestSwitchCandidate t s" unfolding fastpathBestSwitchCandidate_def lookupBitmapPriority_def by simp lemma sched_act_SwitchToThread_rewrite: "\<lbrakk> sa = SwitchToThread t \<Longrightarrow> monadic_rewrite F E Q (m_sw t) f \<rbrakk> \<Longrightarrow> monadic_rewrite F E ((\<lambda>_. sa = SwitchToThread t) and Q) (case_scheduler_action m_res m_ch (\<lambda>t. m_sw t) sa) f" apply (cases sa; simp add: monadic_rewrite_impossible) apply (rename_tac t') apply (case_tac "t' = t"; simp add: monadic_rewrite_impossible) done lemma schedule_rewrite_ct_not_runnable': "monadic_rewrite True True (\<lambda>s. ksSchedulerAction s = SwitchToThread t \<and> ct_in_state' (Not \<circ> runnable') s \<and> (ksCurThread s \<noteq> ksIdleThread s) \<and> fastpathBestSwitchCandidate t s) (schedule) (do setSchedulerAction ResumeCurrentThread; switchToThread t od)" supply subst_all [simp del] apply (simp add: schedule_def) (* switching to t *) apply (monadic_rewrite_l sched_act_SwitchToThread_rewrite[where t=t]) (* not wasRunnable, skip enqueue *) apply (simp add: when_def) apply (monadic_rewrite_l monadic_rewrite_if_l_False) (* fastpath: \<not> (fastfail \<and> \<not> highest) *) apply (monadic_rewrite_l monadic_rewrite_if_l_False \<open>wpsimp simp: isHighestPrio_def' wp: hoare_vcg_imp_lift hoare_vcg_disj_lift threadGet_wp'' scheduleSwitchThreadFastfail_False_wp\<close>) (* fastpath: no scheduleChooseNewThread *) apply (monadic_rewrite_l monadic_rewrite_if_l_False \<open>wpsimp simp: isHighestPrio_def' wp: hoare_vcg_imp_lift hoare_vcg_disj_lift threadGet_wp'' scheduleSwitchThreadFastfail_False_wp\<close>) (* remove no-ops *) apply (repeat 10 monadic_rewrite_symb_exec_l) (* until switchToThread *) apply (simp add: setSchedulerAction_def) apply (subst oblivious_modify_swap[symmetric], rule oblivious_switchToThread_schact) apply (rule monadic_rewrite_refl) apply (wpsimp wp: empty_fail_isRunnable simp: isHighestPrio_def')+ apply (clarsimp simp: ct_in_state'_def not_pred_tcb_at'_strengthen fastpathBestSwitchCandidate_def) apply normalise_obj_at' done lemma resolveAddressBits_points_somewhere: "\<lbrace>\<lambda>s. \<forall>slot. Q slot s\<rbrace> resolveAddressBits cp cptr bits \<lbrace>Q\<rbrace>,-" apply (rule_tac Q'="\<lambda>rv s. \<forall>rv. Q rv s" in hoare_post_imp_R) apply wp apply clarsimp done lemma foldr_copy_register_tsrs: "foldr (\<lambda>r . copy_register_tsrs x y r r (\<lambda>x. x)) rs s = (s (y := TCBStateRegs (tsrState (s y)) (\<lambda>r. if r \<in> set rs then tsrContext (s x) r else tsrContext (s y) r)))" apply (induct rs) apply simp apply (simp add: copy_register_tsrs_def fun_eq_iff split: if_split) done lemmas cteInsert_obj_at'_not_queued = cteInsert_obj_at'_queued[of "\<lambda>a. \<not> a"] lemma monadic_rewrite_threadGet: "monadic_rewrite E F (obj_at' (\<lambda>tcb. f tcb = v) t) (threadGet f t) (return v)" unfolding getThreadState_def threadGet_def apply (simp add: liftM_def) apply monadic_rewrite_symb_exec_l apply (rule_tac P="\<lambda>_. f x = v" in monadic_rewrite_pre_imp_eq) apply blast apply (wpsimp wp: OMG_getObject_tcb simp: obj_tcb_at')+ done lemma monadic_rewrite_getThreadState: "monadic_rewrite E F (obj_at' (\<lambda>tcb. tcbState tcb = v) t) (getThreadState t) (return v)" unfolding getThreadState_def by (rule monadic_rewrite_threadGet) lemma setCTE_obj_at'_tcbIPCBuffer: "\<lbrace>obj_at' (\<lambda>tcb. P (tcbIPCBuffer tcb)) t\<rbrace> setCTE p v \<lbrace>\<lambda>rv. obj_at' (\<lambda>tcb. P (tcbIPCBuffer tcb)) t\<rbrace>" unfolding setCTE_def by (rule setObject_cte_obj_at_tcb', simp+) context notes if_cong[cong] begin crunches cteInsert, asUser for obj_at'_tcbIPCBuffer[wp]: "obj_at' (\<lambda>tcb. P (tcbIPCBuffer tcb)) t" (wp: setCTE_obj_at'_queued crunch_wps threadSet_obj_at'_really_strongest) end crunches cteInsert, threadSet, asUser, emptySlot for ksReadyQueuesL1Bitmap_inv[wp]: "\<lambda>s. P (ksReadyQueuesL1Bitmap s)" and ksReadyQueuesL2Bitmap_inv[wp]: "\<lambda>s. P (ksReadyQueuesL2Bitmap s)" (wp: hoare_drop_imps) crunch ksReadyQueuesL1Bitmap_inv[wp]: setEndpoint "\<lambda>s. P (ksReadyQueuesL1Bitmap s)" (wp: setObject_ksPSpace_only updateObject_default_inv) crunch ksReadyQueuesL2Bitmap_inv[wp]: setEndpoint "\<lambda>s. P (ksReadyQueuesL2Bitmap s)" (wp: setObject_ksPSpace_only updateObject_default_inv) lemma setThreadState_runnable_bitmap_inv: "runnable' ts \<Longrightarrow> \<lbrace> \<lambda>s. P (ksReadyQueuesL1Bitmap s) \<rbrace> setThreadState ts t \<lbrace>\<lambda>rv s. P (ksReadyQueuesL1Bitmap s) \<rbrace>" "runnable' ts \<Longrightarrow> \<lbrace> \<lambda>s. Q (ksReadyQueuesL2Bitmap s) \<rbrace> setThreadState ts t \<lbrace>\<lambda>rv s. Q (ksReadyQueuesL2Bitmap s) \<rbrace>" by (simp_all add: setThreadState_runnable_simp, wp+) (* FIXME move *) crunches curDomain for (no_fail) no_fail[intro!, wp, simp] lemma fastpath_callKernel_SysCall_corres: "monadic_rewrite True False (invs' and ct_in_state' ((=) Running) and (\<lambda>s. ksSchedulerAction s = ResumeCurrentThread) and (\<lambda>s. ksDomainTime s \<noteq> 0)) (callKernel (SyscallEvent SysCall)) (fastpaths SysCall)" supply if_cong[cong] option.case_cong[cong] if_split[split del] supply empty_fail_getMRs[wp] (* FIXME *) supply empty_fail_getEndpoint[wp] (* FIXME *) apply (rule monadic_rewrite_introduce_alternative[OF callKernel_def[simplified atomize_eq]]) apply (rule monadic_rewrite_guard_imp) apply (simp add: handleEvent_def handleCall_def handleInvocation_def liftE_bindE_handle bind_assoc getMessageInfo_def) apply (simp add: catch_liftE_bindE unlessE_throw_catch_If unifyFailure_catch_If catch_liftE getMessageInfo_def alternative_bind fastpaths_def cong: if_cong) apply (rule monadic_rewrite_bind_alternative_l, wp) apply (rule monadic_rewrite_bind_tail) apply (rule monadic_rewrite_bind_alternative_l, wp) apply (rule monadic_rewrite_bind_tail) apply (rename_tac msgInfo) apply (rule monadic_rewrite_bind_alternative_l, wp) apply (rule monadic_rewrite_bind_tail) apply monadic_rewrite_symb_exec_r apply (rename_tac tcbFault) apply (rule monadic_rewrite_alternative_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply (rule monadic_rewrite_if_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply (simp add: split_def Syscall_H.syscall_def liftE_bindE_handle bind_assoc capFaultOnFailure_def) apply (simp only: bindE_bind_linearise[where f="rethrowFailure fn f'" for fn f'] bind_case_sum_rethrow) apply (simp add: lookupCapAndSlot_def lookupSlotForThread_def bindE_assoc liftE_bind_return_bindE_returnOk split_def getThreadCSpaceRoot_def locateSlot_conv returnOk_liftE[symmetric] const_def getSlotCap_def) apply (simp only: liftE_bindE_assoc) apply (rule monadic_rewrite_bind_alternative_l, wp) apply (rule monadic_rewrite_bind_tail) apply (rule monadic_rewrite_bind_alternative_l) apply (wp | simp)+ apply (rule_tac fn="case_sum Inl (Inr \<circ> fst)" in monadic_rewrite_split_fn) apply (simp add: liftME_liftM[symmetric] liftME_def bindE_assoc) apply (rule monadic_rewrite_refl) apply (rule monadic_rewrite_if_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply (simp add: isRight_right_map isRight_case_sum) apply (rule monadic_rewrite_if_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply (rule monadic_rewrite_bind_alternative_l[OF lookupIPC_inv]) apply monadic_rewrite_symb_exec_l apply (simp add: lookupExtraCaps_null returnOk_bind liftE_bindE_handle bind_assoc liftE_bindE_assoc decodeInvocation_def Let_def from_bool_0 performInvocation_def liftE_handle liftE_bind) apply monadic_rewrite_symb_exec_r apply (rename_tac "send_ep") apply (rule monadic_rewrite_if_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply (simp add: getThreadVSpaceRoot_def locateSlot_conv) apply monadic_rewrite_symb_exec_r apply (rename_tac "pdCapCTE") apply (rule monadic_rewrite_if_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply monadic_rewrite_symb_exec_r apply monadic_rewrite_symb_exec_r apply monadic_rewrite_symb_exec_r apply (simp add: isHighestPrio_def') apply monadic_rewrite_symb_exec_r apply (rule monadic_rewrite_if_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply (rule monadic_rewrite_if_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply monadic_rewrite_symb_exec_r apply (rule monadic_rewrite_if_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply monadic_rewrite_symb_exec_r apply (rule monadic_rewrite_if_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply (rule monadic_rewrite_trans, rule monadic_rewrite_pick_alternative_1) apply monadic_rewrite_symb_exec_l (* now committed to fastpath *) apply (rule monadic_rewrite_trans) apply (rule_tac F=True and E=True in monadic_rewrite_weaken_flags) apply simp apply (rule monadic_rewrite_bind_tail) apply (monadic_rewrite_symb_exec_l_known thread) apply (simp add: sendIPC_def bind_assoc) apply (monadic_rewrite_symb_exec_l_known send_ep) apply (rule_tac P="epQueue send_ep \<noteq> []" in monadic_rewrite_gen_asm) apply (simp add: isRecvEP_endpoint_case list_case_helper bind_assoc) apply (rule monadic_rewrite_bind_tail) apply (elim conjE) apply (rule monadic_rewrite_bind_tail, rename_tac dest_st) apply (rule_tac P="\<exists>gr. dest_st = BlockedOnReceive (capEPPtr (fst (theRight rv))) gr" in monadic_rewrite_gen_asm) apply monadic_rewrite_symb_exec_l_drop apply (rule monadic_rewrite_bind) apply clarsimp apply (rule_tac msgInfo=msgInfo in doIPCTransfer_simple_rewrite) apply (rule monadic_rewrite_bind_tail) apply (rule monadic_rewrite_bind) apply (rule_tac destPrio=destPrio and curDom=curDom and destDom=destDom and thread=thread in possibleSwitchTo_rewrite) apply (rule monadic_rewrite_bind) apply (rule monadic_rewrite_trans) apply (rule setupCallerCap_rewrite) apply (rule monadic_rewrite_bind_head) apply (rule setThreadState_rewrite_simple, simp) apply (rule monadic_rewrite_trans) apply (monadic_rewrite_symb_exec_l_known BlockedOnReply) apply simp apply (rule monadic_rewrite_refl) apply wpsimp apply (rule monadic_rewrite_trans) apply (rule monadic_rewrite_bind_head) apply (rule_tac t="hd (epQueue send_ep)" in schedule_rewrite_ct_not_runnable') apply (simp add: bind_assoc) apply (rule monadic_rewrite_bind_tail) apply (rule monadic_rewrite_bind) apply (rule switchToThread_rewrite) apply (rule monadic_rewrite_bind) apply (rule activateThread_simple_rewrite) apply (rule monadic_rewrite_refl) apply wp apply (wp setCurThread_ct_in_state) apply (simp only: st_tcb_at'_def[symmetric]) apply (wp, clarsimp simp: cur_tcb'_def ct_in_state'_def) apply (simp add: getThreadCallerSlot_def getThreadReplySlot_def locateSlot_conv ct_in_state'_def cur_tcb'_def) apply ((wp assert_inv threadSet_pred_tcb_at_state cteInsert_obj_at'_not_queued | wps)+)[1] apply (wp fastpathBestSwitchCandidate_lift[where f="cteInsert c w w'" for c w w']) apply ((wp assert_inv threadSet_pred_tcb_at_state cteInsert_obj_at'_not_queued | wps)+)[1] apply ((wp assert_inv threadSet_pred_tcb_at_state cteInsert_obj_at'_not_queued | wps)+)[1] apply ((wp assert_inv threadSet_pred_tcb_at_state cteInsert_obj_at'_not_queued | wps)+)[1] apply ((wp assert_inv threadSet_pred_tcb_at_state cteInsert_obj_at'_not_queued | wps)+)[1] apply (wp fastpathBestSwitchCandidate_lift[where f="threadSet f t" for f t]) apply simp apply ((wp assert_inv threadSet_pred_tcb_at_state cteInsert_obj_at'_not_queued | wps)+)[1] apply (simp add: setSchedulerAction_def) apply wp[1] apply (simp cong: if_cong HOL.conj_cong add: if_bool_simps) apply (simp_all only:)[5] apply ((wp setThreadState_oa_queued[of _ "\<lambda>a _ _. \<not> a"] setThreadState_obj_at_unchanged asUser_obj_at_unchanged mapM_x_wp' sts_st_tcb_at'_cases setThreadState_no_sch_change setEndpoint_obj_at_tcb' fastpathBestSwitchCandidate_lift[where f="setThreadState f t" for f t] setThreadState_oa_queued fastpathBestSwitchCandidate_lift[where f="asUser t f" for f t] fastpathBestSwitchCandidate_lift[where f="setEndpoint a b" for a b] lookupBitmapPriority_lift setThreadState_runnable_bitmap_inv getEndpoint_obj_at' | simp add: setMessageInfo_def | wp (once) hoare_vcg_disj_lift)+) apply (simp add: setThreadState_runnable_simp getThreadCallerSlot_def getThreadReplySlot_def locateSlot_conv bind_assoc) apply (rule_tac P="\<lambda>v. obj_at' (%tcb. tcbIPCBuffer tcb = v) (hd (epQueue send_ep))" in monadic_rewrite_exists_v) apply (rename_tac ipcBuffer) apply (rule_tac P="\<lambda>v. obj_at' (\<lambda>tcb. tcbState tcb = v) (hd (epQueue send_ep))" in monadic_rewrite_exists_v) apply (rename_tac destState) apply (simp add: ARM_HYP_H.switchToThread_def getTCB_threadGet bind_assoc) (* retrieving state or thread registers is not thread_action_isolatable, translate into return with suitable precondition *) apply (rule monadic_rewrite_trans[OF _ monadic_rewrite_transverse]) apply (rule_tac v=destState in monadic_rewrite_getThreadState | rule monadic_rewrite_bind monadic_rewrite_refl)+ apply (wp mapM_x_wp' getObject_inv | wpc | simp | wp (once) hoare_drop_imps)+ apply (rule_tac v=destState in monadic_rewrite_getThreadState | rule monadic_rewrite_bind monadic_rewrite_refl)+ apply (wp mapM_x_wp' getObject_inv | wpc | simp | wp (once) hoare_drop_imps)+ apply (rule_tac P="inj (case_bool thread (hd (epQueue send_ep)))" in monadic_rewrite_gen_asm) apply (rule monadic_rewrite_trans[OF _ monadic_rewrite_transverse]) apply (rule monadic_rewrite_weaken_flags[where F=False and E=True], simp) apply (rule isolate_thread_actions_rewrite_bind fastpath_isolate_rewrites fastpath_isolatables bool.simps setRegister_simple threadGet_vcpu_isolatable[THEN thread_actions_isolatableD, simplified o_def] threadGet_vcpu_isolatable[simplified o_def] vcpuSwitch_isolatable[THEN thread_actions_isolatableD] vcpuSwitch_isolatable setVMRoot_isolatable[THEN thread_actions_isolatableD] setVMRoot_isolatable doMachineOp_isolatable[THEN thread_actions_isolatableD] doMachineOp_isolatable kernelExitAssertions_isolatable[THEN thread_actions_isolatableD] kernelExitAssertions_isolatable zipWithM_setRegister_simple thread_actions_isolatable_bind | assumption | wp assert_inv)+ apply (rule_tac P="\<lambda>s. ksSchedulerAction s = ResumeCurrentThread \<and> tcb_at' thread s" and F=True and E=False in monadic_rewrite_weaken_flags) apply simp apply (rule monadic_rewrite_isolate_final) apply (simp add: isRight_case_sum cong: list.case_cong) apply (clarsimp simp: fun_eq_iff if_flip cong: if_cong) apply (drule obj_at_ko_at', clarsimp) apply (frule get_tcb_state_regs_ko_at') apply (clarsimp simp: zip_map2 zip_same_conv_map foldl_map foldl_fun_upd foldr_copy_register_tsrs isRight_case_sum cong: if_cong) apply (simp add: upto_enum_def fromEnum_def enum_register toEnum_def msgRegisters_unfold cong: if_cong) apply (clarsimp split: if_split) apply (rule ext) apply (simp add: badgeRegister_def msgInfoRegister_def ARM_HYP.badgeRegister_def ARM_HYP.msgInfoRegister_def split: if_split) apply simp apply (wp | simp cong: if_cong bool.case_cong | rule getCTE_wp' gts_wp' threadGet_wp getEndpoint_wp)+ apply (rule validE_cases_valid) apply (simp add: isRight_def getSlotCap_def) apply (wp getCTE_wp') apply (rule resolveAddressBits_points_somewhere) apply (simp cong: if_cong bool.case_cong) apply wp apply simp apply (wp user_getreg_wp threadGet_wp)+ apply clarsimp apply (subgoal_tac "ksCurThread s \<noteq> ksIdleThread s") prefer 2 apply (fastforce simp: ct_in_state'_def dest: ct_running_not_idle' elim: pred_tcb'_weakenE) apply (clarsimp simp: ct_in_state'_def pred_tcb_at') apply (frule cte_wp_at_valid_objs_valid_cap', clarsimp+) apply (clarsimp simp: isCap_simps valid_cap'_def maskCapRights_def) apply (frule ko_at_valid_ep', clarsimp) apply (frule sym_refs_ko_atD'[where 'a=endpoint], clarsimp) apply (clarsimp simp: valid_ep'_def isRecvEP_endpoint_case neq_Nil_conv tcbVTableSlot_def cte_level_bits_def cte_at_tcb_at_16' length_msgRegisters size_msgRegisters_def order_less_imp_le ep_q_refs_of'_def st_tcb_at_refs_of_rev' cong: if_cong) apply (rename_tac blockedThread ys tcba tcbb) apply (frule invs_mdb') apply (thin_tac "Ball S P" for S P)+ supply imp_disjL[simp del] apply (subst imp_disjL[symmetric]) (* clean up broken up disj implication and excessive references to same tcbs *) apply normalise_obj_at' apply (clarsimp simp: invs'_def valid_state'_def) apply (fold imp_disjL, intro allI impI) apply (subgoal_tac "ksCurThread s \<noteq> blockedThread") prefer 2 apply normalise_obj_at' apply clarsimp apply (frule_tac t="blockedThread" in valid_queues_not_runnable_not_queued, assumption) subgoal by (fastforce simp: st_tcb_at'_def elim: obj_at'_weakenE) apply (subgoal_tac "fastpathBestSwitchCandidate blockedThread s") prefer 2 apply (rule_tac ttcb=tcbb and ctcb=tcb in fastpathBestSwitchCandidateI) apply (solves \<open>simp only: disj_ac\<close>) apply simp+ apply (clarsimp simp: st_tcb_at'_def obj_at'_def objBits_simps projectKOs valid_mdb'_def valid_mdb_ctes_def inj_case_bool split: bool.split)+ done lemma capability_case_Null_ReplyCap: "(case cap of NullCap \<Rightarrow> f | ReplyCap t b cg \<Rightarrow> g t b cg | _ \<Rightarrow> h) = (if isReplyCap cap then g (capTCBPtr cap) (capReplyMaster cap) (capReplyCanGrant cap) else if isNullCap cap then f else h)" by (simp add: isCap_simps split: capability.split split del: if_split) lemma injection_handler_catch: "catch (injection_handler f x) y = catch x (y o f)" apply (simp add: injection_handler_def catch_def handleE'_def bind_assoc) apply (rule bind_cong[OF refl]) apply (simp add: throwError_bind split: sum.split) done lemma doReplyTransfer_simple: "monadic_rewrite True False (obj_at' (\<lambda>tcb. tcbFault tcb = None) receiver) (doReplyTransfer sender receiver slot grant) (do state \<leftarrow> getThreadState receiver; assert (isReply state); cte \<leftarrow> getCTE slot; mdbnode \<leftarrow> return $ cteMDBNode cte; assert (mdbPrev mdbnode \<noteq> 0 \<and> mdbNext mdbnode = 0); parentCTE \<leftarrow> getCTE (mdbPrev mdbnode); assert (isReplyCap (cteCap parentCTE) \<and> capReplyMaster (cteCap parentCTE)); doIPCTransfer sender Nothing 0 grant receiver; cteDeleteOne slot; setThreadState Running receiver; possibleSwitchTo receiver od)" apply (simp add: doReplyTransfer_def liftM_def nullPointer_def getSlotCap_def) apply (rule monadic_rewrite_bind_tail)+ apply (monadic_rewrite_symb_exec_l_known None, simp) apply (rule monadic_rewrite_refl) apply (wpsimp wp: threadGet_const gts_wp' getCTE_wp' simp: o_def)+ done lemma receiveIPC_simple_rewrite: "monadic_rewrite True False ((\<lambda>_. isEndpointCap ep_cap \<and> \<not> isSendEP ep) and (ko_at' ep (capEPPtr ep_cap) and (\<lambda>s. \<forall>ntfnptr. bound_tcb_at' ((=) (Some ntfnptr)) thread s \<longrightarrow> obj_at' (Not \<circ> isActive) ntfnptr s))) (receiveIPC thread ep_cap True) (do setThreadState (BlockedOnReceive (capEPPtr ep_cap) (capEPCanGrant ep_cap)) thread; setEndpoint (capEPPtr ep_cap) (RecvEP (case ep of RecvEP q \<Rightarrow> (q @ [thread]) | _ \<Rightarrow> [thread])) od)" supply empty_fail_getEndpoint[wp] apply (rule monadic_rewrite_gen_asm) apply (simp add: receiveIPC_def) apply (monadic_rewrite_symb_exec_l_known ep) apply monadic_rewrite_symb_exec_l+ apply (monadic_rewrite_l monadic_rewrite_if_l_False) apply (rule monadic_rewrite_is_refl) apply (cases ep; simp add: isSendEP_def) apply (wpsimp wp: getNotification_wp gbn_wp' getEndpoint_wp simp: getBoundNotification_def)+ apply (clarsimp simp: obj_at'_def projectKOs pred_tcb_at'_def) done lemma empty_fail_isFinalCapability: "empty_fail (isFinalCapability cte)" by (simp add: isFinalCapability_def Let_def empty_fail_cond split: if_split) lemma cteDeleteOne_replycap_rewrite: "monadic_rewrite True False (cte_wp_at' (\<lambda>cte. isReplyCap (cteCap cte)) slot) (cteDeleteOne slot) (emptySlot slot NullCap)" supply isFinalCapability_inv[wp] empty_fail_isFinalCapability[wp] (* FIXME *) apply (simp add: cteDeleteOne_def) apply (rule monadic_rewrite_symb_exec_l) apply (rule_tac P="cteCap cte \<noteq> NullCap \<and> isReplyCap (cteCap cte) \<and> \<not> isEndpointCap (cteCap cte) \<and> \<not> isNotificationCap (cteCap cte)" in monadic_rewrite_gen_asm) apply (simp add: finaliseCapTrue_standin_def capRemovable_def) apply monadic_rewrite_symb_exec_l apply (rule monadic_rewrite_refl) apply (wpsimp wp: getCTE_wp')+ apply (clarsimp simp: cte_wp_at_ctes_of isCap_simps) done lemma cteDeleteOne_nullcap_rewrite: "monadic_rewrite True False (cte_wp_at' (\<lambda>cte. cteCap cte = NullCap) slot) (cteDeleteOne slot) (return ())" apply (simp add: cteDeleteOne_def unless_def when_def) apply (monadic_rewrite_l monadic_rewrite_if_l_False \<open>wpsimp wp: getCTE_wp'\<close>) apply (monadic_rewrite_symb_exec_l, rule monadic_rewrite_refl) apply (wpsimp wp: getCTE_wp' simp: cte_wp_at_ctes_of)+ done lemma deleteCallerCap_nullcap_rewrite: "monadic_rewrite True False (cte_wp_at' (\<lambda>cte. cteCap cte = NullCap) (thread + 2 ^ cte_level_bits * tcbCallerSlot)) (deleteCallerCap thread) (return ())" apply (simp add: deleteCallerCap_def getThreadCallerSlot_def locateSlot_conv getSlotCap_def) apply (monadic_rewrite_l cteDeleteOne_nullcap_rewrite \<open>wpsimp wp: getCTE_wp\<close>) apply (monadic_rewrite_symb_exec_l+, rule monadic_rewrite_refl) apply (wpsimp simp: cte_wp_at_ctes_of)+ done lemma emptySlot_cnode_caps: "\<lbrace>\<lambda>s. P (only_cnode_caps (ctes_of s)) \<and> cte_wp_at' (\<lambda>cte. \<not> isCNodeCap (cteCap cte)) slot s\<rbrace> emptySlot slot NullCap \<lbrace>\<lambda>rv s. P (only_cnode_caps (ctes_of s))\<rbrace>" apply (simp add: only_cnode_caps_def map_option_comp2 o_assoc[symmetric] cteCaps_of_def[symmetric]) apply (wp emptySlot_cteCaps_of) apply (clarsimp simp: cteCaps_of_def cte_wp_at_ctes_of elim!: rsubst[where P=P] del: ext intro!: ext split: if_split) done lemma asUser_obj_at_ep[wp]: "\<lbrace>obj_at' P p\<rbrace> asUser t m \<lbrace>\<lambda>rv. obj_at' (P :: endpoint \<Rightarrow> bool) p\<rbrace>" apply (simp add: asUser_def split_def) apply (wp hoare_drop_imps | simp)+ done lemma setCTE_obj_at_ep[wp]: "\<lbrace>obj_at' (P :: endpoint \<Rightarrow> bool) p\<rbrace> setCTE ptr cte \<lbrace>\<lambda>rv. obj_at' P p\<rbrace>" unfolding setCTE_def apply (rule obj_at_setObject2) apply (clarsimp simp: updateObject_cte typeError_def in_monad split: Structures_H.kernel_object.split_asm if_split_asm) done lemma setCTE_obj_at_ntfn[wp]: "\<lbrace>obj_at' (P :: Structures_H.notification \<Rightarrow> bool) p\<rbrace> setCTE ptr cte \<lbrace>\<lambda>rv. obj_at' P p\<rbrace>" unfolding setCTE_def apply (rule obj_at_setObject2) apply (clarsimp simp: updateObject_cte typeError_def in_monad split: Structures_H.kernel_object.split_asm if_split_asm) done crunch obj_at_ep[wp]: emptySlot "obj_at' (P :: endpoint \<Rightarrow> bool) p" crunches emptySlot, asUser for gsCNodes[wp]: "\<lambda>s. P (gsCNodes s)" (wp: crunch_wps) crunch tcbContext[wp]: possibleSwitchTo "obj_at' (\<lambda>tcb. P ( (atcbContextGet o tcbArch) tcb)) t" (wp: crunch_wps simp_del: comp_apply) crunch only_cnode_caps[wp]: doFaultTransfer "\<lambda>s. P (only_cnode_caps (ctes_of s))" (wp: crunch_wps simp: crunch_simps) lemma tcbSchedDequeue_rewrite_not_queued: "monadic_rewrite True False (tcb_at' t and obj_at' (Not \<circ> tcbQueued) t) (tcbSchedDequeue t) (return ())" apply (simp add: tcbSchedDequeue_def when_def) apply (monadic_rewrite_l monadic_rewrite_if_l_False \<open>wp threadGet_const\<close>) apply (monadic_rewrite_symb_exec_l, rule monadic_rewrite_refl) apply wp+ apply (clarsimp simp: o_def obj_at'_def) done lemma schedule_known_rewrite: "monadic_rewrite True False (\<lambda>s. ksSchedulerAction s = SwitchToThread t \<and> tcb_at' t s \<and> obj_at' (Not \<circ> tcbQueued) t s \<and> ksCurThread s = t' \<and> st_tcb_at' (Not \<circ> runnable') t' s \<and> (ksCurThread s \<noteq> ksIdleThread s) \<and> fastpathBestSwitchCandidate t s) (schedule) (do Arch.switchToThread t; setCurThread t; setSchedulerAction ResumeCurrentThread od)" supply subst_all[simp del] if_split[split del] apply (simp add: schedule_def) apply (simp only: Thread_H.switchToThread_def) (* switching to t *) apply (monadic_rewrite_l sched_act_SwitchToThread_rewrite[where t=t]) (* not wasRunnable, skip enqueue *) apply (simp add: when_def) apply (monadic_rewrite_l monadic_rewrite_if_l_False) (* fastpath: \<not> (fastfail \<and> \<not> highest) *) apply (monadic_rewrite_l monadic_rewrite_if_l_False \<open>wpsimp simp: isHighestPrio_def' wp: hoare_vcg_imp_lift hoare_vcg_disj_lift threadGet_wp'' scheduleSwitchThreadFastfail_False_wp\<close>) (* fastpath: no scheduleChooseNewThread *) apply (monadic_rewrite_l monadic_rewrite_if_l_False \<open>wpsimp simp: isHighestPrio_def' wp: hoare_vcg_imp_lift hoare_vcg_disj_lift threadGet_wp'' scheduleSwitchThreadFastfail_False_wp\<close>) apply (simp add: bind_assoc) apply (monadic_rewrite_l tcbSchedDequeue_rewrite_not_queued \<open>wpsimp wp: Arch_switchToThread_obj_at_pre\<close>) (* remove no-ops *) apply simp apply (repeat 9 \<open>rule monadic_rewrite_symb_exec_l\<close>) (* until switchToThread *) apply (rule monadic_rewrite_refl) apply (wpsimp simp: isHighestPrio_def')+ apply (clarsimp simp: ct_in_state'_def not_pred_tcb_at'_strengthen fastpathBestSwitchCandidate_def) apply normalise_obj_at' done lemma tcb_at_cte_at_offset: "\<lbrakk> tcb_at' t s; 2 ^ cte_level_bits * off \<in> dom tcb_cte_cases \<rbrakk> \<Longrightarrow> cte_at' (t + 2 ^ cte_level_bits * off) s" apply (clarsimp simp: obj_at'_def projectKOs objBits_simps) apply (erule(2) cte_wp_at_tcbI') apply fastforce apply simp done lemma emptySlot_cte_wp_at_cteCap: "\<lbrace>\<lambda>s. (p = p' \<longrightarrow> P NullCap) \<and> (p \<noteq> p' \<longrightarrow> cte_wp_at' (\<lambda>cte. P (cteCap cte)) p s)\<rbrace> emptySlot p' irqopt \<lbrace>\<lambda>rv s. cte_wp_at' (\<lambda>cte. P (cteCap cte)) p s\<rbrace>" apply (simp add: tree_cte_cteCap_eq[unfolded o_def]) apply (wp emptySlot_cteCaps_of) apply (clarsimp split: if_split) done lemma setEndpoint_getCTE_pivot[unfolded K_bind_def]: "do setEndpoint p val; v <- getCTE slot; f v od = do v <- getCTE slot; setEndpoint p val; f v od" apply (simp add: getCTE_assert_opt setEndpoint_def setObject_modify_assert fun_eq_iff bind_assoc) apply (simp add: exec_gets assert_def assert_opt_def exec_modify update_ep_map_to_ctes split: if_split option.split) done lemma setEndpoint_setCTE_pivot[unfolded K_bind_def]: "do setEndpoint p val; setCTE slot cte; f od = do setCTE slot cte; setEndpoint p val; f od" supply if_split[split del] apply (rule monadic_rewrite_to_eq) apply simp apply (rule monadic_rewrite_guard_imp) apply (rule monadic_rewrite_trans, rule_tac f="ep_at' p" in monadic_rewrite_add_gets) apply (rule monadic_rewrite_transverse, rule monadic_rewrite_add_gets, rule monadic_rewrite_bind_tail) apply (rename_tac epat) apply (rule monadic_rewrite_transverse) apply (rule monadic_rewrite_bind_tail) apply (simp add: setEndpoint_def setObject_modify_assert bind_assoc) apply (rule_tac rv=epat in monadic_rewrite_gets_known) apply (wp setCTE_typ_at'[where T="koType TYPE(endpoint)", unfolded typ_at_to_obj_at'] | simp)+ apply (simp add: setCTE_assert_modify bind_assoc) apply (rule monadic_rewrite_trans, rule monadic_rewrite_add_gets, rule monadic_rewrite_bind_tail)+ apply (rename_tac cteat tcbat) apply (rule monadic_rewrite_trans, rule monadic_rewrite_bind_tail) apply (rule monadic_rewrite_trans) apply (rule_tac rv=cteat in monadic_rewrite_gets_known) apply (rule_tac rv=tcbat in monadic_rewrite_gets_known) apply (wp setEndpoint_typ_at'[where T="koType TYPE(tcb)", unfolded typ_at_to_obj_at'] setEndpoint_typ_at'[where T="koType TYPE(cte)", unfolded typ_at_to_obj_at'] | simp)+ apply (rule_tac P="\<lambda>s. epat = ep_at' p s \<and> cteat = real_cte_at' slot s \<and> tcbat = (tcb_at' (slot && ~~ mask 9) and (%y. slot && mask 9 : dom tcb_cte_cases)) s" in monadic_rewrite_pre_imp_eq) apply (simp add: setEndpoint_def setObject_modify_assert bind_assoc exec_gets assert_def exec_modify split: if_split) apply (auto split: if_split simp: obj_at'_def projectKOs objBits_defs del: ext intro!: arg_cong[where f=f] ext kernel_state.fold_congs)[1] apply wp+ apply (simp add: objBits_defs) done lemma setEndpoint_updateMDB_pivot[unfolded K_bind_def]: "do setEndpoint p val; updateMDB slot mf; f od = do updateMDB slot mf; setEndpoint p val; f od" by (clarsimp simp: updateMDB_def bind_assoc setEndpoint_getCTE_pivot setEndpoint_setCTE_pivot split: if_split) lemma setEndpoint_updateCap_pivot[unfolded K_bind_def]: "do setEndpoint p val; updateCap slot mf; f od = do updateCap slot mf; setEndpoint p val; f od" by (clarsimp simp: updateCap_def bind_assoc setEndpoint_getCTE_pivot setEndpoint_setCTE_pivot) lemma modify_setEndpoint_pivot[unfolded K_bind_def]: "\<lbrakk> \<And>ksf s. ksPSpace_update ksf (sf s) = sf (ksPSpace_update ksf s) \<rbrakk> \<Longrightarrow> (do modify sf; setEndpoint p val; f od) = (do setEndpoint p val; modify sf; f od)" apply (subgoal_tac "\<forall>s. ep_at' p (sf s) = ep_at' p s") apply (simp add: setEndpoint_def setObject_modify_assert bind_assoc fun_eq_iff exec_gets exec_modify assert_def split: if_split) apply atomize apply clarsimp apply (drule_tac x="\<lambda>_. ksPSpace s" in spec) apply (drule_tac x="s" in spec) apply (drule_tac f="ksPSpace" in arg_cong) apply simp apply (metis obj_at'_pspaceI) done lemma setEndpoint_clearUntypedFreeIndex_pivot[unfolded K_bind_def]: "do setEndpoint p val; v <- clearUntypedFreeIndex slot; f od = do v <- clearUntypedFreeIndex slot; setEndpoint p val; f od" supply option.case_cong_weak[cong del] by (simp add: clearUntypedFreeIndex_def bind_assoc getSlotCap_def setEndpoint_getCTE_pivot updateTrackedFreeIndex_def modify_setEndpoint_pivot split: capability.split | rule bind_cong[OF refl] allI impI bind_apply_cong[OF refl])+ lemma emptySlot_setEndpoint_pivot[unfolded K_bind_def]: "(do emptySlot slot NullCap; setEndpoint p val; f od) = (do setEndpoint p val; emptySlot slot NullCap; f od)" apply (rule ext) apply (simp add: emptySlot_def bind_assoc setEndpoint_getCTE_pivot setEndpoint_updateCap_pivot setEndpoint_updateMDB_pivot case_Null_If Retype_H.postCapDeletion_def setEndpoint_clearUntypedFreeIndex_pivot split: if_split | rule bind_apply_cong[OF refl])+ done lemma set_getCTE[unfolded K_bind_def]: "do setCTE p cte; v <- getCTE p; f v od = do setCTE p cte; f cte od" apply (simp add: getCTE_assert_opt bind_assoc) apply (rule monadic_rewrite_to_eq) apply (rule monadic_rewrite_bind_tail) apply (monadic_rewrite_symb_exec_l) apply (monadic_rewrite_symb_exec_l_known cte, rule monadic_rewrite_refl) apply (wpsimp simp: assert_opt_def wp: gets_wp)+ done lemma set_setCTE[unfolded K_bind_def]: "do setCTE p val; setCTE p val' od = setCTE p val'" supply if_split[split del] apply simp apply (rule monadic_rewrite_to_eq) apply (rule monadic_rewrite_guard_imp) apply (rule monadic_rewrite_trans, rule_tac f="real_cte_at' p" in monadic_rewrite_add_gets) apply (rule monadic_rewrite_transverse, rule monadic_rewrite_add_gets, rule monadic_rewrite_bind_tail) apply (rule monadic_rewrite_trans, rule_tac f="tcb_at' (p && ~~ mask 9) and K (p && mask 9 \<in> dom tcb_cte_cases)" in monadic_rewrite_add_gets) apply (rule monadic_rewrite_transverse, rule monadic_rewrite_add_gets, rule monadic_rewrite_bind_tail) apply (rename_tac cteat tcbat) apply (rule monadic_rewrite_trans) apply (rule monadic_rewrite_bind_tail) apply (simp add: setCTE_assert_modify) apply (rule monadic_rewrite_trans, rule_tac rv=cteat in monadic_rewrite_gets_known) apply (rule_tac rv=tcbat in monadic_rewrite_gets_known) apply (wp setCTE_typ_at'[where T="koType TYPE(tcb)", unfolded typ_at_to_obj_at'] setCTE_typ_at'[where T="koType TYPE(cte)", unfolded typ_at_to_obj_at'] | simp)+ apply (simp add: setCTE_assert_modify bind_assoc) apply (rule monadic_rewrite_bind_tail)+ apply (rule_tac P="c = cteat \<and> t = tcbat \<and> (tcbat \<longrightarrow> (\<exists> getF setF. tcb_cte_cases (p && mask 9) = Some (getF, setF) \<and> (\<forall> f g tcb. setF f (setF g tcb) = setF (f o g) tcb)))" in monadic_rewrite_gen_asm) apply (rule monadic_rewrite_is_refl[OF ext]) apply (simp add: exec_modify split: if_split) apply (auto simp: simpler_modify_def projectKO_opt_tcb objBits_defs del: ext intro!: kernel_state.fold_congs ext split: if_split)[1] apply wp+ apply (clarsimp simp: objBits_defs intro!: all_tcbI) apply (auto simp: tcb_cte_cases_def split: if_split_asm) done lemma setCTE_updateCapMDB: "p \<noteq> 0 \<Longrightarrow> setCTE p cte = do updateCap p (cteCap cte); updateMDB p (const (cteMDBNode cte)) od" supply if_split[split del] apply (simp add: updateCap_def updateMDB_def bind_assoc set_getCTE cte_overwrite set_setCTE) apply (simp add: getCTE_assert_opt setCTE_assert_modify bind_assoc) apply (rule ext, simp add: exec_gets assert_opt_def exec_modify split: if_split option.split) apply (cut_tac P=\<top> and p=p and s=x in cte_wp_at_ctes_of) apply (cases cte) apply (simp add: cte_wp_at_obj_cases') apply (auto simp: mask_out_sub_mask) done lemma clearUntypedFreeIndex_simple_rewrite: "monadic_rewrite True False (cte_wp_at' (Not o isUntypedCap o cteCap) slot) (clearUntypedFreeIndex slot) (return ())" apply (simp add: clearUntypedFreeIndex_def getSlotCap_def) apply (rule monadic_rewrite_name_pre) apply (clarsimp simp: cte_wp_at_ctes_of) apply (monadic_rewrite_symb_exec_l_known cte) apply (simp split: capability.split, strengthen monadic_rewrite_refl) apply (wpsimp wp: getCTE_wp' simp: cte_wp_at_ctes_of)+ done lemma emptySlot_replymaster_rewrite[OF refl]: "mdbn = cteMDBNode cte \<Longrightarrow> monadic_rewrite True False ((\<lambda>_. mdbNext mdbn = 0 \<and> mdbPrev mdbn \<noteq> 0) and ((\<lambda>_. cteCap cte \<noteq> NullCap) and (cte_wp_at' ((=) cte) slot and cte_wp_at' (\<lambda>cte. isReplyCap (cteCap cte)) slot and cte_wp_at' (\<lambda>cte. isReplyCap (cteCap cte) \<and> capReplyMaster (cteCap cte)) (mdbPrev mdbn) and (\<lambda>s. reply_masters_rvk_fb (ctes_of s)) and (\<lambda>s. no_0 (ctes_of s))))) (emptySlot slot NullCap) (do updateMDB (mdbPrev mdbn) (mdbNext_update (K 0) o mdbFirstBadged_update (K True) o mdbRevocable_update (K True)); setCTE slot makeObject od)" supply if_split[split del] apply (rule monadic_rewrite_gen_asm)+ apply (rule monadic_rewrite_guard_imp) apply (rule_tac P="slot \<noteq> 0" in monadic_rewrite_gen_asm) apply (clarsimp simp: emptySlot_def setCTE_updateCapMDB) apply (monadic_rewrite_l clearUntypedFreeIndex_simple_rewrite, simp) apply (monadic_rewrite_symb_exec_l_known cte) apply (simp add: updateMDB_def Let_def bind_assoc makeObject_cte case_Null_If) apply (rule monadic_rewrite_bind_tail) apply (rule monadic_rewrite_bind) apply (rule_tac P="mdbFirstBadged (cteMDBNode ctea) \<and> mdbRevocable (cteMDBNode ctea)" in monadic_rewrite_gen_asm) apply (rule monadic_rewrite_is_refl) apply (case_tac ctea, rename_tac mdbnode, case_tac mdbnode) apply simp apply (simp add: Retype_H.postCapDeletion_def) apply (rule monadic_rewrite_refl) apply (solves wp | wp getCTE_wp')+ apply (clarsimp simp: cte_wp_at_ctes_of reply_masters_rvk_fb_def) apply (fastforce simp: isCap_simps) done lemma all_prio_not_inQ_not_tcbQueued: "\<lbrakk> obj_at' (\<lambda>a. (\<forall>d p. \<not> inQ d p a)) t s \<rbrakk> \<Longrightarrow> obj_at' (\<lambda>a. \<not> tcbQueued a) t s" apply (clarsimp simp: obj_at'_def inQ_def) done crunches setThreadState, emptySlot, asUser for ntfn_obj_at[wp]: "obj_at' (P::(Structures_H.notification \<Rightarrow> bool)) ntfnptr" (wp: obj_at_setObject2 crunch_wps simp: crunch_simps updateObject_default_def in_monad) lemma st_tcb_at_is_Reply_imp_not_tcbQueued: "\<And>s t.\<lbrakk> invs' s; st_tcb_at' isReply t s\<rbrakk> \<Longrightarrow> obj_at' (\<lambda>a. \<not> tcbQueued a) t s" apply (clarsimp simp: invs'_def valid_state'_def valid_queues_def st_tcb_at'_def valid_queues_no_bitmap_def) apply (rule all_prio_not_inQ_not_tcbQueued) apply (clarsimp simp: obj_at'_def) apply (erule_tac x="d" in allE) apply (erule_tac x="p" in allE) apply (erule conjE) apply (erule_tac x="t" in ballE) apply (clarsimp simp: obj_at'_def runnable'_def isReply_def) apply (case_tac "tcbState obj") apply ((clarsimp simp: inQ_def)+)[8] apply (clarsimp simp: valid_queues'_def obj_at'_def) done lemma valid_objs_ntfn_at_tcbBoundNotification: "ko_at' tcb t s \<Longrightarrow> valid_objs' s \<Longrightarrow> tcbBoundNotification tcb \<noteq> None \<Longrightarrow> ntfn_at' (the (tcbBoundNotification tcb)) s" apply (drule(1) ko_at_valid_objs', simp add: projectKOs) apply (simp add: valid_obj'_def valid_tcb'_def valid_bound_ntfn'_def) apply clarsimp done crunch bound_tcb_at'_Q[wp]: setThreadState "\<lambda>s. Q (bound_tcb_at' P t s)" (wp: threadSet_pred_tcb_no_state crunch_wps simp: unless_def) lemmas emptySlot_pred_tcb_at'_Q[wp] = lift_neg_pred_tcb_at'[OF emptySlot_typ_at' emptySlot_pred_tcb_at'] lemma emptySlot_tcb_at'[wp]: "\<lbrace>\<lambda>s. Q (tcb_at' t s)\<rbrace> emptySlot a b \<lbrace>\<lambda>_ s. Q (tcb_at' t s)\<rbrace>" by (simp add: tcb_at_typ_at', wp) lemmas cnode_caps_gsCNodes_lift = hoare_lift_Pf2[where P="\<lambda>gs s. cnode_caps_gsCNodes (f s) gs" and f=gsCNodes for f] hoare_lift_Pf2[where P="\<lambda>gs s. Q s \<longrightarrow> cnode_caps_gsCNodes (f s) gs" and f=gsCNodes for f Q] lemma resolveAddressBitsFn_eq_name_slot: "monadic_rewrite F E (\<lambda>s. (isCNodeCap cap \<longrightarrow> cte_wp_at' (\<lambda>cte. cteCap cte = cap) (slot s) s) \<and> valid_objs' s \<and> cnode_caps_gsCNodes' s) (resolveAddressBits cap capptr bits) (gets (resolveAddressBitsFn cap capptr bits o only_cnode_caps o ctes_of))" apply (rule monadic_rewrite_guard_imp, rule resolveAddressBitsFn_eq) apply auto done crunch bound_tcb_at'_Q[wp]: asUser "\<lambda>s. Q (bound_tcb_at' P t s)" (simp: crunch_simps wp: threadSet_pred_tcb_no_state crunch_wps) lemma asUser_tcb_at'_Q[wp]: "\<lbrace>\<lambda>s. Q (tcb_at' t s)\<rbrace> asUser a b \<lbrace>\<lambda>_ s. Q (tcb_at' t s)\<rbrace>" by (simp add: tcb_at_typ_at', wp) lemma active_ntfn_check_wp: "\<lbrace>\<lambda>s. Q (\<exists>ntfnptr. bound_tcb_at' ((=) (Some ntfnptr)) thread s \<and> \<not> obj_at' (Not o isActive) ntfnptr s) s \<rbrace> do bound_ntfn \<leftarrow> getBoundNotification thread; case bound_ntfn of None \<Rightarrow> return False | Some ntfnptr \<Rightarrow> liftM EndpointDecls_H.isActive $ getNotification ntfnptr od \<lbrace>Q\<rbrace>" apply (rule hoare_pre) apply (wp getNotification_wp gbn_wp' | wpc)+ apply (auto simp: pred_tcb_at'_def obj_at'_def projectKOs) done lemma tcbSchedEnqueue_tcbIPCBuffer: "\<lbrace>obj_at' (\<lambda>tcb. P (tcbIPCBuffer tcb)) t\<rbrace> tcbSchedEnqueue t' \<lbrace>\<lambda>_. obj_at' (\<lambda>tcb. P (tcbIPCBuffer tcb)) t\<rbrace>" apply (simp add: tcbSchedEnqueue_def unless_when) apply (wp threadSet_obj_at' hoare_drop_imps threadGet_wp |simp split: if_split)+ done crunch obj_at'_tcbIPCBuffer[wp]: rescheduleRequired "obj_at' (\<lambda>tcb. P (tcbIPCBuffer tcb)) t" (wp: crunch_wps tcbSchedEnqueue_tcbIPCBuffer simp: rescheduleRequired_def) context notes if_cong[cong] begin crunch obj_at'_tcbIPCBuffer[wp]: setThreadState "obj_at' (\<lambda>tcb. P (tcbIPCBuffer tcb)) t" (wp: crunch_wps threadSet_obj_at'_really_strongest) crunch obj_at'_tcbIPCBuffer[wp]: handleFault "obj_at' (\<lambda>tcb. P (tcbIPCBuffer tcb)) t" (wp: crunch_wps constOnFailure_wp tcbSchedEnqueue_tcbIPCBuffer threadSet_obj_at'_really_strongest simp: zipWithM_x_mapM) end crunch obj_at'_tcbIPCBuffer[wp]: emptySlot "obj_at' (\<lambda>tcb. P (tcbIPCBuffer tcb)) t" (wp: crunch_wps) (* FIXME move *) crunches getBoundNotification for (no_fail) no_fail[intro!, wp, simp] lemma fastpath_callKernel_SysReplyRecv_corres: "monadic_rewrite True False (invs' and ct_in_state' ((=) Running) and (\<lambda>s. ksSchedulerAction s = ResumeCurrentThread) and cnode_caps_gsCNodes') (callKernel (SyscallEvent SysReplyRecv)) (fastpaths SysReplyRecv)" including no_pre supply if_cong[cong] option.case_cong[cong] supply if_split[split del] supply user_getreg_inv[wp] (* FIXME *) apply (rule monadic_rewrite_introduce_alternative[OF callKernel_def[simplified atomize_eq]]) apply (rule monadic_rewrite_guard_imp) apply (simp add: handleEvent_def handleReply_def handleRecv_def liftE_bindE_handle liftE_handle bind_assoc getMessageInfo_def liftE_bind) apply (simp add: catch_liftE_bindE unlessE_throw_catch_If unifyFailure_catch_If catch_liftE getMessageInfo_def alternative_bind fastpaths_def getThreadCallerSlot_def locateSlot_conv capability_case_Null_ReplyCap getThreadCSpaceRoot_def cong: if_cong) apply (rule monadic_rewrite_bind_alternative_l, wp) apply (rule monadic_rewrite_bind_tail) apply monadic_rewrite_symb_exec_r apply (rename_tac msgInfo) apply monadic_rewrite_symb_exec_r apply monadic_rewrite_symb_exec_r apply (rename_tac tcbFault) apply (rule monadic_rewrite_alternative_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply (rule monadic_rewrite_if_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply (simp add: lookupCap_def liftME_def lookupCapAndSlot_def lookupSlotForThread_def bindE_assoc split_def getThreadCSpaceRoot_def locateSlot_conv liftE_bindE bindE_bind_linearise capFaultOnFailure_def rethrowFailure_injection injection_handler_catch bind_bindE_assoc getThreadCallerSlot_def bind_assoc getSlotCap_def case_bool_If o_def isRight_def[where x="Inr v" for v] isRight_def[where x="Inl v" for v] cong: if_cong) apply monadic_rewrite_symb_exec_r apply (rename_tac "cTableCTE") apply (rule monadic_rewrite_transverse, monadic_rewrite_l resolveAddressBitsFn_eq wpsimp, rule monadic_rewrite_refl) apply monadic_rewrite_symb_exec_r apply (rename_tac "rab_ret") apply (rule_tac P="isRight rab_ret" in monadic_rewrite_cases[rotated]) apply (case_tac rab_ret, simp_all add: isRight_def)[1] apply (rule monadic_rewrite_alternative_l) apply clarsimp apply (simp add: isRight_case_sum liftE_bind isRight_def[where x="Inr v" for v]) apply monadic_rewrite_symb_exec_r apply (rename_tac ep_cap) apply (rule monadic_rewrite_if_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply (monadic_rewrite_symb_exec \<open>rule monadic_rewrite_symb_exec_r_nE[OF _ _ _ active_ntfn_check_wp, unfolded bind_assoc fun_app_def]\<close> \<open>wpsimp simp: getBoundNotification_def wp: threadGet_wp\<close>) apply (rename_tac ep) apply (rule monadic_rewrite_if_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply monadic_rewrite_symb_exec_r apply (rename_tac ep) apply (rule monadic_rewrite_if_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply (rule monadic_rewrite_bind_alternative_l, wp) apply (rule monadic_rewrite_bind_tail) apply (rename_tac replyCTE) apply (rule monadic_rewrite_if_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply (simp add: bind_assoc) apply (rule monadic_rewrite_bind_alternative_l, wp assert_inv) apply (rule monadic_rewrite_assert) apply monadic_rewrite_symb_exec_r apply (rule monadic_rewrite_if_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply (simp add: getThreadVSpaceRoot_def locateSlot_conv) apply monadic_rewrite_symb_exec_r apply (rename_tac vTableCTE) apply (rule monadic_rewrite_if_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply monadic_rewrite_symb_exec_r apply monadic_rewrite_symb_exec_r apply (simp add: isHighestPrio_def') apply monadic_rewrite_symb_exec_r apply (rule monadic_rewrite_if_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply monadic_rewrite_symb_exec_r apply (rule monadic_rewrite_if_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply monadic_rewrite_symb_exec_r apply (rule monadic_rewrite_if_r[rotated]) apply (rule monadic_rewrite_alternative_l) apply (rule monadic_rewrite_trans, rule monadic_rewrite_pick_alternative_1) (* now committed to fastpath *) apply (rule_tac P="\<lambda>v. obj_at' (%tcb. tcbIPCBuffer tcb = v) (capTCBPtr (cteCap replyCTE))" in monadic_rewrite_exists_v) apply (rename_tac ipcBuffer) apply (simp add: ARM_HYP_H.switchToThread_def bind_assoc) apply (rule monadic_rewrite_trans[OF _ monadic_rewrite_transverse]) apply (rule monadic_rewrite_bind monadic_rewrite_refl)+ apply (wp mapM_x_wp' getObject_inv | wpc | simp add: | wp (once) hoare_drop_imps )+ apply (rule monadic_rewrite_bind monadic_rewrite_refl)+ apply (wp setCTE_obj_at'_tcbIPCBuffer assert_inv mapM_x_wp' getObject_inv | wpc | simp | wp (once) hoare_drop_imps )+ apply (rule monadic_rewrite_trans) apply (rule monadic_rewrite_trans) apply (rule monadic_rewrite_bind_head) apply (rule monadic_rewrite_trans) apply (rule doReplyTransfer_simple) apply simp apply (((rule monadic_rewrite_weaken_flags', (rule_tac msgInfo=msgInfo in doIPCTransfer_simple_rewrite | rule_tac destPrio=callerPrio and curDom=curDom and destDom=callerDom and thread=thread in possibleSwitchTo_rewrite)) | rule cteDeleteOne_replycap_rewrite | rule monadic_rewrite_bind monadic_rewrite_refl | wp assert_inv mapM_x_wp' setThreadState_obj_at_unchanged asUser_obj_at_unchanged hoare_strengthen_post[OF _ obj_at_conj'[simplified atomize_conjL], rotated] lookupBitmapPriority_lift setThreadState_runnable_bitmap_inv | simp add: setMessageInfo_def setThreadState_runnable_simp | wp (once) hoare_vcg_disj_lift)+)[1] apply (simp add: setMessageInfo_def) apply (rule monadic_rewrite_bind_tail) apply (rename_tac unblocked) apply (monadic_rewrite_symb_exec_l_known thread) apply (monadic_rewrite_symb_exec_l_known cptr) apply (rule monadic_rewrite_bind) apply (rule monadic_rewrite_catch[OF _ monadic_rewrite_refl True_E_E]) apply monadic_rewrite_symb_exec_l apply (rename_tac cTableCTE2, rule_tac P="cteCap cTableCTE2 = cteCap cTableCTE" in monadic_rewrite_gen_asm) apply simp apply (rule monadic_rewrite_trans, rule monadic_rewrite_bindE[OF _ monadic_rewrite_refl]) apply (rule_tac slot="\<lambda>s. ksCurThread s + 2 ^ cte_level_bits * tcbCTableSlot" in resolveAddressBitsFn_eq_name_slot) apply wp apply (rule monadic_rewrite_trans) apply (rule_tac rv=rab_ret in monadic_rewrite_gets_known[where m="NonDetMonad.lift f" for f, folded bindE_def]) apply (simp add: NonDetMonad.lift_def isRight_case_sum) apply monadic_rewrite_symb_exec_l apply (rename_tac ep_cap2) apply (rule_tac P="cteCap ep_cap2 = cteCap ep_cap" in monadic_rewrite_gen_asm) apply (simp add: cap_case_EndpointCap_NotificationCap) apply (rule monadic_rewrite_liftE) apply (rule monadic_rewrite_trans) apply (rule monadic_rewrite_bind) apply (rule deleteCallerCap_nullcap_rewrite) apply (rule_tac ep=ep in receiveIPC_simple_rewrite) apply (wp, simp) apply (rule monadic_rewrite_bind_head) apply (rule monadic_rewrite_weaken_flags[where E=True and F=True], simp) apply (rule setThreadState_rewrite_simple) apply clarsimp apply (wp getCTE_known_cap)+ apply (rule monadic_rewrite_bind) apply (rule_tac t="capTCBPtr (cteCap replyCTE)" and t'=thread in schedule_known_rewrite) apply (rule monadic_rewrite_weaken_flags[where E=True and F=True], simp) apply (rule monadic_rewrite_bind) apply (rule activateThread_simple_rewrite) apply (rule monadic_rewrite_refl) apply wp apply wp apply (simp add: ct_in_state'_def, simp add: ct_in_state'_def[symmetric]) apply ((wp setCurThread_ct_in_state[folded st_tcb_at'_def] Arch_switchToThread_pred_tcb')+)[2] apply (simp add: catch_liftE) apply ((wpsimp wp: user_getreg_rv setEndpoint_obj_at_tcb' threadSet_pred_tcb_at_state[unfolded if_bool_eq_conj] fastpathBestSwitchCandidate_lift[where f="setEndpoint a b" for a b] fastpathBestSwitchCandidate_lift[where f="threadSet f t" for f t] | wps)+)[3] apply (simp cong: rev_conj_cong) apply (wpsimp wp: seThreadState_tcbContext[simplified comp_apply] setThreadState_oa_queued user_getreg_rv setThreadState_no_sch_change setThreadState_obj_at_unchanged sts_st_tcb_at'_cases sts_bound_tcb_at' fastpathBestSwitchCandidate_lift[where f="setThreadState s t" for s t] static_imp_wp hoare_vcg_all_lift hoare_vcg_imp_lift static_imp_wp cnode_caps_gsCNodes_lift hoare_vcg_ex_lift | wps)+ apply (strengthen imp_consequent[where Q="tcb_at' t s" for t s]) apply ((wp setThreadState_oa_queued user_getreg_rv setThreadState_no_sch_change setThreadState_obj_at_unchanged sts_st_tcb_at'_cases sts_bound_tcb_at' emptySlot_obj_at'_not_queued emptySlot_obj_at_ep emptySlot_tcbContext[simplified comp_apply] emptySlot_cte_wp_at_cteCap emptySlot_cnode_caps user_getreg_inv asUser_typ_ats asUser_obj_at_not_queued asUser_obj_at' mapM_x_wp' static_imp_wp hoare_vcg_all_lift hoare_vcg_imp_lift static_imp_wp cnode_caps_gsCNodes_lift hoare_vcg_ex_lift fastpathBestSwitchCandidate_lift[where f="emptySlot a b" for a b] | simp del: comp_apply | clarsimp simp: obj_at'_weakenE[OF _ TrueI] | wps)+) apply (wpsimp wp: fastpathBestSwitchCandidate_lift[where f="asUser a b" for a b])+ apply (clarsimp cong: conj_cong) apply ((wp user_getreg_inv asUser_typ_ats asUser_obj_at_not_queued asUser_obj_at' mapM_x_wp' static_imp_wp hoare_vcg_all_lift hoare_vcg_imp_lift static_imp_wp cnode_caps_gsCNodes_lift hoare_vcg_ex_lift | clarsimp simp: obj_at'_weakenE[OF _ TrueI] | solves \<open> wp fastpathBestSwitchCandidate_lift[where f="asUser a b" for a b] \<close>)+) apply (clarsimp | wp getCTE_wp' gts_imp')+ apply (simp add: ARM_HYP_H.switchToThread_def getTCB_threadGet bind_assoc) apply (rule monadic_rewrite_trans[OF _ monadic_rewrite_transverse]) apply (rule monadic_rewrite_bind monadic_rewrite_refl)+ apply (wp mapM_x_wp' handleFault_obj_at'_tcbIPCBuffer getObject_inv | wpc | simp | wp (once) hoare_drop_imps )+ apply (rule monadic_rewrite_bind monadic_rewrite_refl)+ apply (wp setCTE_obj_at'_tcbIPCBuffer assert_inv mapM_x_wp' getObject_inv | wpc | simp | wp (once) hoare_drop_imps )+ apply (simp add: bind_assoc catch_liftE receiveIPC_def Let_def liftM_def setThreadState_runnable_simp) apply monadic_rewrite_symb_exec_l apply (rule monadic_rewrite_assert) apply (rule_tac P="inj (case_bool thread (capTCBPtr (cteCap replyCTE)))" in monadic_rewrite_gen_asm) apply (rule monadic_rewrite_trans[OF _ monadic_rewrite_transverse]) apply (rule monadic_rewrite_weaken_flags[where F=False and E=True], simp) apply (rule isolate_thread_actions_rewrite_bind fastpath_isolate_rewrites fastpath_isolatables bool.simps setRegister_simple zipWithM_setRegister_simple thread_actions_isolatable_bind thread_actions_isolatableD[OF setCTE_isolatable] setCTE_isolatable threadGet_vcpu_isolatable[THEN thread_actions_isolatableD, simplified o_def] threadGet_vcpu_isolatable[simplified o_def] vcpuSwitch_isolatable[THEN thread_actions_isolatableD] vcpuSwitch_isolatable setVMRoot_isolatable[THEN thread_actions_isolatableD] setVMRoot_isolatable doMachineOp_isolatable[THEN thread_actions_isolatableD] doMachineOp_isolatable kernelExitAssertions_isolatable[THEN thread_actions_isolatableD] kernelExitAssertions_isolatable | assumption | wp assert_inv)+ apply (simp only: ) apply (rule_tac P="(\<lambda>s. ksSchedulerAction s = ResumeCurrentThread) and tcb_at' thread and (cte_wp_at' (\<lambda>cte. isReplyCap (cteCap cte)) (thread + 2 ^ cte_level_bits * tcbCallerSlot) and (\<lambda>s. \<forall>x. tcb_at' (case_bool thread (capTCBPtr (cteCap replyCTE)) x) s) and valid_mdb')" and F=True and E=False in monadic_rewrite_weaken_flags) apply (rule monadic_rewrite_isolate_final2) apply simp apply monadic_rewrite_symb_exec_l apply (rename_tac callerCTE) apply (rule monadic_rewrite_assert) apply monadic_rewrite_symb_exec_l apply (rule monadic_rewrite_assert) apply (simp add: emptySlot_setEndpoint_pivot) apply (rule monadic_rewrite_bind) apply (rule monadic_rewrite_is_refl) apply (clarsimp simp: isSendEP_def split: Structures_H.endpoint.split) apply (monadic_rewrite_symb_exec_r_known callerCTE) apply (rule monadic_rewrite_trans, rule monadic_rewrite_bind_head, rule_tac cte=callerCTE in emptySlot_replymaster_rewrite) apply (simp add: bind_assoc o_def) apply (rule monadic_rewrite_refl) apply (simp add: cte_wp_at_ctes_of pred_conj_def) apply (clarsimp | wp getCTE_ctes_wp)+ apply (clarsimp simp: zip_map2 zip_same_conv_map foldl_map foldl_fun_upd foldr_copy_register_tsrs isRight_case_sum cong: if_cong) apply (clarsimp simp: fun_eq_iff if_flip cong: if_cong) apply (drule obj_at_ko_at', clarsimp) apply (frule get_tcb_state_regs_ko_at') apply (clarsimp simp: zip_map2 zip_same_conv_map foldl_map foldl_fun_upd foldr_copy_register_tsrs isRight_case_sum cong: if_cong) apply (simp add: upto_enum_def fromEnum_def enum_register toEnum_def msgRegisters_unfold cong: if_cong) apply (clarsimp split: if_split) apply (rule ext) apply (simp add: badgeRegister_def msgInfoRegister_def ARM_HYP.msgInfoRegister_def ARM_HYP.badgeRegister_def cong: if_cong split: if_split) apply simp apply (clarsimp simp: cte_wp_at_ctes_of isCap_simps map_to_ctes_partial_overwrite) apply (simp add: valid_mdb'_def valid_mdb_ctes_def) apply simp apply (simp cong: if_cong bool.case_cong | rule getCTE_wp' gts_wp' threadGet_wp getEndpoint_wp gets_wp user_getreg_wp gets_the_wp gct_wp getNotification_wp return_wp liftM_wp gbn_wp' | (simp only: curDomain_def, wp)[1])+ apply clarsimp apply (subgoal_tac "ksCurThread s \<noteq> ksIdleThread s") prefer 2 apply (fastforce simp: ct_in_state'_def dest: ct_running_not_idle' elim: pred_tcb'_weakenE) apply (clarsimp simp: ct_in_state'_def pred_tcb_at') apply (subst tcb_at_cte_at_offset, erule obj_at'_weakenE[OF _ TrueI], simp add: tcb_cte_cases_def cte_level_bits_def tcbSlots) apply (clarsimp simp: valid_objs_ntfn_at_tcbBoundNotification invs_valid_objs' if_apply_def2) apply (rule conjI[rotated]) apply (fastforce elim: cte_wp_at_weakenE') apply (clarsimp simp: isRight_def) apply (frule cte_wp_at_valid_objs_valid_cap', clarsimp+) apply (frule resolveAddressBitsFn_real_cte_at', (clarsimp | erule cte_wp_at_weakenE')+) apply (frule real_cte_at', clarsimp) apply (frule cte_wp_at_valid_objs_valid_cap', clarsimp, clarsimp simp: isCap_simps, simp add: valid_cap_simps') apply (clarsimp simp: maskCapRights_def isCap_simps) apply (frule_tac p="p' + 2 ^ cte_level_bits * tcbCallerSlot" for p' in cte_wp_at_valid_objs_valid_cap', clarsimp+) apply (clarsimp simp: valid_cap_simps') apply (subst tcb_at_cte_at_offset, assumption, simp add: tcb_cte_cases_def cte_level_bits_def tcbSlots) apply (clarsimp simp: inj_case_bool cte_wp_at_ctes_of length_msgRegisters order_less_imp_le tcb_at_invs' invs_mdb' split: bool.split) apply (subst imp_disjL[symmetric], intro allI impI) apply (clarsimp simp: inj_case_bool cte_wp_at_ctes_of length_msgRegisters size_msgRegisters_def order_less_imp_le tcb_at_invs' invs_mdb' split: bool.split) apply (subgoal_tac "fastpathBestSwitchCandidate v0a s") prefer 2 apply normalise_obj_at' apply (rule_tac ttcb=tcba and ctcb=tcb in fastpathBestSwitchCandidateI) apply (erule disjE, blast, blast) apply simp+ apply (clarsimp simp: obj_at_tcbs_of tcbSlots cte_level_bits_def) apply (frule(1) st_tcb_at_is_Reply_imp_not_tcbQueued) apply (auto simp: obj_at_tcbs_of tcbSlots cte_level_bits_def) done end lemma cnode_caps_gsCNodes_from_sr: "\<lbrakk> valid_objs s; (s, s') \<in> state_relation \<rbrakk> \<Longrightarrow> cnode_caps_gsCNodes' s'" apply (clarsimp simp: cnode_caps_gsCNodes_def only_cnode_caps_def o_def ran_map_option) apply (safe, simp_all) apply (clarsimp elim!: ranE) apply (frule(1) pspace_relation_cte_wp_atI[rotated]) apply clarsimp apply (clarsimp simp: is_cap_simps) apply (frule(1) cte_wp_at_valid_objs_valid_cap) apply (clarsimp simp: valid_cap_simps cap_table_at_gsCNodes_eq) done end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Tufte-Style Book (Minimal Template) % LaTeX Template % Version 1.0 (5/1/13) % % This template has been downloaded from: % http://www.LaTeXTemplates.com % % License: % CC BY-NC-SA 3.0 (http://creativecommons.org/licenses/by-nc-sa/3.0/) % % IMPORTANT NOTE: % In addition to running BibTeX to compile the reference list from the .bib % file, you will need to run MakeIndex to compile the index at the end of the % document. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \input{auxiliary/preamble.tex} %---------------------------------------------------------------------------------------- % INTRODUCTION %---------------------------------------------------------------------------------------- \cleardoublepage \chapter{Introduction: Development Research in Practice} \input{chapters/0-introduction.tex} %---------------------------------------------------------------------------------------- % CHAPTER 1 %---------------------------------------------------------------------------------------- \chapter{Chapter 1: Reproducibility, transparency, and credibility} \label{ch:1} \input{chapters/1-reproducibility.tex} %------------------------------------------------------------------------------- % CHAPTER 2 %------------------------------------------------------------------------------- \chapter{Chapter 2: Setting the stage for collaboration} \label{ch:2} \input{chapters/2-collaboration.tex} %------------------------------------------------------------------------------- % CHAPTER 3 %------------------------------------------------------------------------------- \chapter{Chapter 3: Establishing a measurement framework} \label{ch:3} \input{chapters/3-measurement.tex} %------------------------------------------------------------------------------- % CHAPTER 4 %------------------------------------------------------------------------------- \chapter{Chapter 4: Acquiring development data} \label{ch:4} \input{chapters/4-acquisition.tex} %------------------------------------------------------------------------------- % CHAPTER 5 %------------------------------------------------------------------------------- \chapter{Chapter 5: Cleaning and processing research data} \label{ch:5} \input{chapters/5-processing.tex} %------------------------------------------------------------------------------- % CHAPTER 6 %------------------------------------------------------------------------------- \chapter{Chapter 6: Constructing and analyzing research data} \label{ch:6} \input{chapters/6-analysis.tex} %------------------------------------------------------------------------------- % CHAPTER 7 %------------------------------------------------------------------------------- \chapter{Chapter 7: Publishing research outputs} \label{ch:7} \input{chapters/7-publication.tex} %------------------------------------------------------------------------------- % Conclusion %------------------------------------------------------------------------------- \chapter*{Bringing it all together} % The asterisk leaves out this chapter from the table of contents \input{auxiliary/conclusion.tex} %------------------------------------------------------------------------------- % APPENDIX : Stata Style Guide %------------------------------------------------------------------------------- \chapter{Appendix: The DIME Analytics Coding Guide} \label{ap:1} \input{auxiliary/stata-guide.tex} %------------------------------------------------------------------------------- % APPENDIX : DIME Analytics Resources %------------------------------------------------------------------------------- \chapter{Appendix: DIME Analytics Resource Directory} \label{ap:2} \input{auxiliary/dime-analytics-resources.tex} %------------------------------------------------------------------------------- %---------------------------------------------------------------------------------------- % APPENDIX : Research Design %---------------------------------------------------------------------------------------- \chapter{Appendix: Research design for impact evaluation} \label{ap:3} \input{auxiliary/research-design.tex} %---------------------------------------------------------------------------------------- \backmatter %------------------------------------------------------------------------------- % BIBLIOGRAPHY %------------------------------------------------------------------------------- \bibliography{bibliography} % Use the bibliography.bib file for the bibliography \bibliographystyle{apalike} % Use the plainnat style of referencing %------------------------------------------------------------------------------- \printindex % Print the index at the very end of the document \end{document}
For any two natural numbers $a$ and $b$, there exist two natural numbers $x$ and $y$ such that $a x - b y = \gcd(a, b)$ or $b x - a y = \gcd(a, b)$.
lemma incseq_SucD: "incseq A \<Longrightarrow> A i \<le> A (Suc i)"
module FCTypes %default total StringOrInt : Bool -> Type StringOrInt b = case b of False => String True => Int getStringOrInt : (b : Bool) -> StringOrInt b getStringOrInt b = case b of False => "94" True => 94 valToString : (b : Bool) -> StringOrInt b -> String valToString b val = case b of False => val True => cast val
(** 116297 - Tópicos Avançados em Computadores - 2017/2 **) (** Provas Formais: Uma Introdução à Teoria de Tipos - Turma B **) (** Prof. Flávio L. C. de Moura **) (** Email: [email protected] **) (** Homepage: http://flaviomoura.mat.br **) (** Aluno: Gabriel F P Araujo **) (** Matrícula: 12/0050943 **) (** Atividade: Formalizar um algoritmo ordenação de sua preferência. *) (** Esta atividade pode ser realizada individualmente ou em dupla. *) (** Algumas dicas: 1. Utilize a biblioteca Arith do Coq. Com isto você terá diversas propriedades sobre os números naturais, e listas de números naturais para utilizar. *) (** Bubble Sort **) Require Import Arith. Require Import Nat. Require Import Peano. Require Import Recdef. Require Import Coq.Lists.SetoidList. Require Import Coq.Sorting.Sorting. Require Import Coq.Structures.OrderedType. Print list. Print pair. Function borb(l: list nat) {measure length l}: list nat := match l with | nil => nil | cons h tl => match tl with | nil => cons h nil | cons h' tl' => match (le_lt_dec h h') with | left _ => cons h (borb tl) | right _ => cons h' (borb (cons h tl')) end end end. Proof. - intros; subst. simpl. apply Nat.lt_succ_diag_r. - intros. simpl. auto. Defined. Print le_lt_dec. Function borb_once(n:nat) (l: list nat) {measure length l}: list nat := match l with | nil => (cons n nil) | cons h tl => match (le_lt_dec n h) with | left _ _ => cons n (cons h tl) | right _ _ => cons h (cons n tl) end end. Print borb_F. Print borb_ind. Print borb_rec. Print borb_tcc. Check borb_equation. Fixpoint num_oc (n:nat) (l:list nat) : nat := match l with | nil => 0 | cons h tl => match le_lt_dec n h with | left _ _ => S (num_oc n tl) | right _ _ => num_oc n tl end end. Definition equiv l l' := forall n, num_oc n l = num_oc n l'. Lemma Sorted_sub: forall l n, Sorted le (cons n l) -> Sorted le l. Proof. intros. induction l. - apply Sorted_nil. - inversion H; subst. assumption. Qed. Lemma le_nm_falso: forall n m, (~ (n <= m)) -> (m < n). Proof. induction n. - intros m H. assert (le 0 m). { apply (le_0_n). } apply False_ind. apply H; assumption. - intro m. case m. + intro H. apply le_n_S. apply le_0_n. + intros n' Hfalso. apply lt_n_S. apply IHn. intro Hle. apply Hfalso. apply le_n_S. assumption. Qed. Lemma Sorted_l_once: forall n l, Sorted le (n :: l) -> ((n :: l) = (borb_once n l)). Proof. induction l. - intro H. reflexivity. - intro H. rewrite borb_once_equation. destruct (le_lt_dec n a). + reflexivity. + inversion H; subst. inversion H3; subst. assert ((~ (n <= a))). { apply lt_not_le. assumption. } contradiction. Qed. Lemma Sorted_l: forall l, Sorted le (l) -> (l = (borb l)). Proof. induction l. - intro H. reflexivity. - intro H. rewrite borb_equation. destruct (l). + reflexivity. + destruct (le_lt_dec a n). * rewrite <- IHl. reflexivity. inversion H; subst. assumption. * inversion H; subst. inversion H3; subst. assert ((~ (a <= n))). { apply lt_not_le. assumption. } contradiction. Qed. Lemma Sorted_n_l_once: forall h tl, Sorted le (h :: tl) -> ((h :: tl) = borb_once h tl). Proof. intros. functional induction (borb_once h tl). - reflexivity. - reflexivity. - inversion H; subst. inversion H3; subst. assert ((~ (h <= h0))). { apply lt_not_le. assumption. } contradiction. Qed. Lemma Sorted_n_l: forall h tl, Sorted le (h :: tl) -> ((h :: tl) = borb (h :: tl)). Proof. intros h tl H. functional induction (borb (tl)). - reflexivity. - rewrite borb_equation. destruct (le_lt_dec h h0). + reflexivity. + inversion H; subst. inversion H3; subst. assert ((~ (h <= h0))). { apply lt_not_le. assumption. } contradiction. - rewrite <- Sorted_l. + reflexivity. + assumption. - rewrite <- Sorted_l. + reflexivity. + assumption. Qed. (**deveria ser <->**) (*functional induction (brob l).*) Lemma borb_preserva_ordem : forall l: list nat, Sorted le l -> Sorted le (borb l). Proof. induction l. - intro. rewrite borb_equation. apply Sorted_nil. - intro. rewrite <- Sorted_n_l. + assumption. + assumption. Qed. Lemma num_oc_borb: forall l n, num_oc n (l) = num_oc n (borb (l)). Proof. intros l n. functional induction (borb l). - reflexivity. - reflexivity. - simpl num_oc. case (le_lt_dec n h). + intro nh. case (le_lt_dec n h'). * intro nh'. rewrite <- IHl0. simpl num_oc. destruct (le_lt_dec n h'). **tauto. **assert ((~ (n <= h'))). { apply lt_not_le. assumption. } contradiction. * intro h'n. rewrite <- IHl0. simpl num_oc. destruct (le_lt_dec n h'). **assert ((~ (n <= h'))). { apply lt_not_le. assumption. } contradiction. **auto. + intro. destruct (le_lt_dec n h'). * rewrite <- IHl0. simpl num_oc. destruct (le_lt_dec n h'). **reflexivity. **assert ((~ (n <= h'))). { apply lt_not_le. assumption. } contradiction. * rewrite <- IHl0. simpl num_oc. destruct (le_lt_dec n h'). **assert ((~ (n <= h'))). { apply lt_not_le. assumption. } contradiction. **reflexivity. - simpl num_oc. case (le_lt_dec n h). + intro nh. case (le_lt_dec n h'). * intro nh'. rewrite <- IHl0. simpl num_oc. destruct (le_lt_dec n h). **reflexivity. **assert ((~ (n <= h))). { apply lt_not_le. assumption. } contradiction. * intro h'n. rewrite <- IHl0. simpl num_oc. destruct (le_lt_dec n h). **reflexivity. **assert ((~ (n <= h))). { apply lt_not_le. assumption. } contradiction. + intro hn. case (le_lt_dec n h'). * intro nh'. rewrite <- IHl0. simpl num_oc. destruct (le_lt_dec n h). **assert ((~ (n <= h))). { apply lt_not_le. assumption. } contradiction. **reflexivity. * intro h'n. rewrite <- IHl0. simpl num_oc. destruct (le_lt_dec n h). **assert ((~ (n <= h))). { apply lt_not_le. assumption. } contradiction. **reflexivity. Qed. Lemma num_oc_borb_once_seq: forall l n n', (num_oc n (borb_once n' l)) = (num_oc n (n' :: l)). Proof. induction l. - intros n n'. rewrite borb_once_equation. reflexivity. - intros n n'. rewrite borb_once_equation. case (le_lt_dec n' a). + intro H. reflexivity. + intro H. apply lt_not_le in H. simpl. case (le_lt_dec n a). * intro H'. case (le_lt_dec n n'). ** intro Hle. reflexivity. ** intro Hlt. reflexivity. * intro H'. case (le_lt_dec n n'). ** intro Hle. reflexivity. ** intro Hlt. reflexivity. Qed. Lemma num_oc_borb_seq: forall l n, (num_oc n (borb l)) = (num_oc n l). Proof. induction l. - intros n. rewrite borb_equation. reflexivity. - intros n. rewrite <- num_oc_borb. reflexivity. Qed. Lemma borb_sorts: forall l a, Sorted le (borb l) -> Sorted le (borb (a :: l)). Proof. intros l a. intro H. functional induction (borb (l)). Admitted. (** 2. Utilize a formalização do algoritmo de ordenação por inserção desenvolvida em sala como parâmetro. *) Theorem correcao: forall l, (equiv l (borb l)) /\ Sorted le (borb l). Proof. (* induction l. *) intro l. functional induction (borb l). - split. * unfold equiv. intro n. reflexivity. * apply Sorted_nil. - split. * unfold equiv. intro n. rewrite -> num_oc_borb. reflexivity. * apply Sorted_cons. ** apply Sorted_nil. ** apply HdRel_nil. - unfold equiv in *. remember (h' :: tl') as l eqn: H. split. + intro n. destruct IHl0 as [Hequiv Hord]. simpl num_oc. destruct (le_lt_dec n h). * rewrite <- num_oc_borb. reflexivity. * rewrite <- num_oc_borb. reflexivity. + destruct IHl0 as [Hequiv Hord]. apply Sorted_cons. * assumption. * inversion Hord. ** apply HdRel_nil. ** - split. * unfold equiv. intro n. destruct IHl0 as [Hequiv Hord]. simpl num_oc. destruct (le_lt_dec n h). ** destruct (le_lt_dec n h'). *** rewrite <- num_oc_borb. simpl num_oc. destruct (le_lt_dec n h). **** reflexivity. **** assert ((~ (n <= h))). { apply lt_not_le. assumption. } contradiction. *** rewrite <- num_oc_borb. simpl num_oc. destruct (le_lt_dec n h). **** reflexivity. **** assert ((~ (n <= h))). { apply lt_not_le. assumption. } contradiction. ** destruct (le_lt_dec n h'). *** rewrite <- num_oc_borb. simpl num_oc. destruct (le_lt_dec n h). **** assert ((~ (n <= h))). { apply lt_not_le. assumption. } contradiction. **** reflexivity. *** rewrite <- num_oc_borb. simpl num_oc. destruct (le_lt_dec n h). **** assert ((~ (n <= h))). { apply lt_not_le. assumption. } contradiction. **** reflexivity. * destruct IHl0 as [Hequiv Hord]. inversion Hord; subst. ** apply Sorted_cons. *** apply Sorted_nil. *** apply HdRel_nil. ** apply Sorted_cons. *** auto. *** apply HdRel_cons. admit. Admitted. Theorem correcao_comp: forall (l:list nat), {l' | equiv l l' /\ Sorted le l'}. Proof. intro l. exists (borb l). apply correcao. Qed.
State Before: R : Type u_3 A : Type u_2 T : Type ?u.27671 B : Type u_1 ι : Type ?u.27677 inst✝¹¹ : SemilatticeSup B inst✝¹⁰ : OrderBot B inst✝⁹ : SemilatticeInf T inst✝⁸ : OrderTop T inst✝⁷ : Semiring R inst✝⁶ : AddMonoid A inst✝⁵ : AddMonoid B inst✝⁴ : CovariantClass B B (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝³ : CovariantClass B B (Function.swap fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝² : AddMonoid T inst✝¹ : CovariantClass T T (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝ : CovariantClass T T (Function.swap fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 degb : A → B degt : A → T degb0 : degb 0 ≤ 0 degbm : ∀ (a b : A), degb (a + b) ≤ degb a + degb b ⊢ Finset.sup (List.prod []).support degb ≤ List.sum (List.map (fun f => Finset.sup f.support degb) []) State After: R : Type u_3 A : Type u_2 T : Type ?u.27671 B : Type u_1 ι : Type ?u.27677 inst✝¹¹ : SemilatticeSup B inst✝¹⁰ : OrderBot B inst✝⁹ : SemilatticeInf T inst✝⁸ : OrderTop T inst✝⁷ : Semiring R inst✝⁶ : AddMonoid A inst✝⁵ : AddMonoid B inst✝⁴ : CovariantClass B B (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝³ : CovariantClass B B (Function.swap fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝² : AddMonoid T inst✝¹ : CovariantClass T T (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝ : CovariantClass T T (Function.swap fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 degb : A → B degt : A → T degb0 : degb 0 ≤ 0 degbm : ∀ (a b : A), degb (a + b) ≤ degb a + degb b ⊢ ∀ (b : A), b ∈ 1.support → degb b ≤ 0 Tactic: rw [List.map_nil, Finset.sup_le_iff, List.prod_nil, List.sum_nil] State Before: R : Type u_3 A : Type u_2 T : Type ?u.27671 B : Type u_1 ι : Type ?u.27677 inst✝¹¹ : SemilatticeSup B inst✝¹⁰ : OrderBot B inst✝⁹ : SemilatticeInf T inst✝⁸ : OrderTop T inst✝⁷ : Semiring R inst✝⁶ : AddMonoid A inst✝⁵ : AddMonoid B inst✝⁴ : CovariantClass B B (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝³ : CovariantClass B B (Function.swap fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝² : AddMonoid T inst✝¹ : CovariantClass T T (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝ : CovariantClass T T (Function.swap fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 degb : A → B degt : A → T degb0 : degb 0 ≤ 0 degbm : ∀ (a b : A), degb (a + b) ≤ degb a + degb b ⊢ ∀ (b : A), b ∈ 1.support → degb b ≤ 0 State After: no goals Tactic: exact fun a ha => by rwa [Finset.mem_singleton.mp (Finsupp.support_single_subset ha)] State Before: R : Type u_3 A : Type u_2 T : Type ?u.27671 B : Type u_1 ι : Type ?u.27677 inst✝¹¹ : SemilatticeSup B inst✝¹⁰ : OrderBot B inst✝⁹ : SemilatticeInf T inst✝⁸ : OrderTop T inst✝⁷ : Semiring R inst✝⁶ : AddMonoid A inst✝⁵ : AddMonoid B inst✝⁴ : CovariantClass B B (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝³ : CovariantClass B B (Function.swap fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝² : AddMonoid T inst✝¹ : CovariantClass T T (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝ : CovariantClass T T (Function.swap fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 degb : A → B degt : A → T degb0 : degb 0 ≤ 0 degbm : ∀ (a b : A), degb (a + b) ≤ degb a + degb b a : A ha : a ∈ 1.support ⊢ degb a ≤ 0 State After: no goals Tactic: rwa [Finset.mem_singleton.mp (Finsupp.support_single_subset ha)] State Before: R : Type u_3 A : Type u_2 T : Type ?u.27671 B : Type u_1 ι : Type ?u.27677 inst✝¹¹ : SemilatticeSup B inst✝¹⁰ : OrderBot B inst✝⁹ : SemilatticeInf T inst✝⁸ : OrderTop T inst✝⁷ : Semiring R inst✝⁶ : AddMonoid A inst✝⁵ : AddMonoid B inst✝⁴ : CovariantClass B B (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝³ : CovariantClass B B (Function.swap fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝² : AddMonoid T inst✝¹ : CovariantClass T T (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝ : CovariantClass T T (Function.swap fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 degb : A → B degt : A → T degb0 : degb 0 ≤ 0 degbm : ∀ (a b : A), degb (a + b) ≤ degb a + degb b f : AddMonoidAlgebra R A fs : List (AddMonoidAlgebra R A) ⊢ Finset.sup (List.prod (f :: fs)).support degb ≤ List.sum (List.map (fun f => Finset.sup f.support degb) (f :: fs)) State After: R : Type u_3 A : Type u_2 T : Type ?u.27671 B : Type u_1 ι : Type ?u.27677 inst✝¹¹ : SemilatticeSup B inst✝¹⁰ : OrderBot B inst✝⁹ : SemilatticeInf T inst✝⁸ : OrderTop T inst✝⁷ : Semiring R inst✝⁶ : AddMonoid A inst✝⁵ : AddMonoid B inst✝⁴ : CovariantClass B B (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝³ : CovariantClass B B (Function.swap fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝² : AddMonoid T inst✝¹ : CovariantClass T T (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝ : CovariantClass T T (Function.swap fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 degb : A → B degt : A → T degb0 : degb 0 ≤ 0 degbm : ∀ (a b : A), degb (a + b) ≤ degb a + degb b f : AddMonoidAlgebra R A fs : List (AddMonoidAlgebra R A) ⊢ Finset.sup (f * List.prod fs).support degb ≤ Finset.sup f.support degb + List.sum (List.map (fun f => Finset.sup f.support degb) fs) Tactic: rw [List.prod_cons, List.map_cons, List.sum_cons] State Before: R : Type u_3 A : Type u_2 T : Type ?u.27671 B : Type u_1 ι : Type ?u.27677 inst✝¹¹ : SemilatticeSup B inst✝¹⁰ : OrderBot B inst✝⁹ : SemilatticeInf T inst✝⁸ : OrderTop T inst✝⁷ : Semiring R inst✝⁶ : AddMonoid A inst✝⁵ : AddMonoid B inst✝⁴ : CovariantClass B B (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝³ : CovariantClass B B (Function.swap fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝² : AddMonoid T inst✝¹ : CovariantClass T T (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 inst✝ : CovariantClass T T (Function.swap fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 degb : A → B degt : A → T degb0 : degb 0 ≤ 0 degbm : ∀ (a b : A), degb (a + b) ≤ degb a + degb b f : AddMonoidAlgebra R A fs : List (AddMonoidAlgebra R A) ⊢ Finset.sup (f * List.prod fs).support degb ≤ Finset.sup f.support degb + List.sum (List.map (fun f => Finset.sup f.support degb) fs) State After: no goals Tactic: exact (sup_support_mul_le (@fun a b => degbm a b) _ _).trans (add_le_add_left (sup_support_list_prod_le degb0 degbm fs) _)
(** * Fresh Constants *) Set Implicit Arguments. Require Import Coq.Arith.Max. Require Export sublist. Require Import language_syntax. (** Remember that [constants] play the role of [parameters]. In particular, we will show that fresh constants are as good as fresh parameters. *) (** [new] chooses a fresh one which does not belong to lists. *) Definition new (l:list name) : name := S (fold_right max 0 l). Lemma new_no_zero : forall (l:list name), new l <> 0. Proof. unfold new; intros; auto with arith. Qed. Lemma IN_less : forall (n:name)(l:list name), IN_name n l -> n < new l. Proof. unfold new; induction l; simpl; intro H; [elim H | ]. case_var; auto with arith. apply lt_le_trans with (m:= S (fold_right max 0 l)); eauto 2 with arith. Qed. Lemma new_fresh : forall l : list name, (new l) # l. Proof. intros l H. elim (lt_irrefl (new l)). apply IN_less; exact H. Qed. (** Freshness for a term *) (* Lemma fresh_out_t : forall (t : trm), (new (oc_t t)) # (oc_t t). Proof. intro t. exact (new_fresh (oc_t t)). Qed. (** Freshness for a formula *) Lemma fresh_out_f : forall (A :fml), (new (oc A)) # (oc A). Proof. intros A. exact (new_fresh (oc A)). Qed. (** Choosing a fresh variable for a context *) Definition fresh_out (Ga:list fml) : name := new (oc_c Ga). (** Freshness for a context *) Definition fresh (x:name)(Ga:list fml) : Prop := x # (oc_c Ga). Lemma fresh_out_spec : forall (Ga : list fml), fresh (fresh_out Ga) Ga. Proof. unfold fresh; unfold fresh_out; intros Ga. exact (new_fresh (oc_c Ga)). Qed. Lemma fresh_fml_peel : forall a A Ga, fresh a (A::Ga) -> a # (oc A). Proof. unfold fresh; simpl; intros; auto with datatypes. Qed. Lemma fresh_peel : forall a A Ga, fresh a (A::Ga) -> fresh a Ga. Proof. unfold fresh; simpl; intros; auto with datatypes. Qed. *) (** Two tactics in dealing with [~ In]. *) Ltac destruct_notin := match goal with | H : ~ (IN ?decA ?x (?l ++ ?m)) |- _ => destruct (notIN_app_1 decA x l m H); clear H; destruct_notin | H : ?x = new ?L |- _ => let Hnew := fresh "Hnew" in generalize (new_fresh L); intro Hnew; rewrite <- H in Hnew; clear H; destruct_notin | x := ?l |- _ => assert (x = l); auto; clearbody x; destruct_notin | _ => idtac end. Ltac solve_notin := intros; destruct_notin; repeat first [ apply notIN_app_2 | apply notIN_cons_3 | apply notIN_singleton_1 | apply notIN_empty_1 ]; auto; try tauto; fail "Not solvable by [solve_notin]; try [destruct_notin]".
Just a reminder that the December Visa Rebate Promo started Friday! See attached flyer and rebate form. See below for specifics. † Subject to credit approval. Limit one Visa® prepaid card per account and per household. Mail-in or online offer. Valid at participating locations. Visa is a registered trademark of Visa U.S.A. Inc. Card can be used everywhere Visa debit cards are accepted. Prepaid card is given to you as a reward, refund, rebate or gift and no money has been paid by you for the card. Prepaid card is issued by MetaBank®, Member FDIC, pursuant to a license from Visa U.S.A. Inc. No cash access or recurring payments. Card valid for up to 6 months; unused funds will be forfeited at midnight EST the last day of the month of the valid thru date. Card terms and conditions apply, see MyPrepaidCenter.com/site/visa-promo. Since the 2 tiered Visa promotion was so well received earlier this year, we are bringing it back for an encore! Below is a snapshot of the flyer with the dates the promotion will run. Flyers and web banners for the December dates will be sent out soon, just wanted to get the information out as soon as possible for any planning/advertising you may want to do in leading up to the promotion dates. Take advantage of these special promotions, these promos cover 40 of the 60 remaining days of 2016! If you have any questions, don’t hesitate to give me a call!
library(ieugwasr) context("afl2") snpinfo1 <- afl2_list() snpinfo2 <- afl2_list("hapmap3") test_that("snplist", { expect_true(nrow(snpinfo2) > 1000000) }) test_that("snplist", { expect_true(nrow(snpinfo1) > 10000 & nrow(snpinfo1) < 30000) }) test_that("ancestry", { a <- associations(snpinfo1$rsid, "bbj-a-10", prox=FALSE) res <- infer_ancestry(a, snpinfo1) expect_true(res$pop[1] == "EAS") }) test_that("chrpos", { a <- afl2_chrpos("1:100000-900000") expect_true(nrow(a) > 100) }) test_that("rsid", { a <- afl2_rsid(c("rs234", "rs123")) expect_true(nrow(a) == 2) })
module UnifyTermL (A : Set) where open import Data.Fin using (Fin; suc; zero) open import Data.Nat using (ℕ; suc; zero) open import Relation.Binary.PropositionalEquality using (_≡_; refl; cong₂; cong; sym; trans) open import Function using (_∘_) open import Relation.Nullary using (¬_; Dec; yes; no) open import Data.Product using (∃; _,_; _×_) open import Data.Empty using (⊥-elim) data Term (n : ℕ) : Set where i : (x : Fin n) -> Term n leaf : A → Term n _fork_ : (s t : Term n) -> Term n Term-leaf-inj : ∀ {n l₁ l₂} → leaf {n} l₁ ≡ leaf l₂ → l₁ ≡ l₂ Term-leaf-inj refl = refl _~>_ : (m n : ℕ) -> Set m ~> n = Fin m -> Term n ▹ : ∀ {m n} -> (r : Fin m -> Fin n) -> Fin m -> Term n ▹ r = i ∘ r _◃_ : ∀ {m n} -> (f : m ~> n) -> Term m -> Term n f ◃ i x = f x f ◃ (leaf l) = leaf l f ◃ (s fork t) = (f ◃ s) fork (f ◃ t) _≐_ : {m n : ℕ} -> (Fin m -> Term n) -> (Fin m -> Term n) -> Set f ≐ g = ∀ x -> f x ≡ g x ◃ext : ∀ {m n} {f g : Fin m -> Term n} -> f ≐ g -> ∀ t -> f ◃ t ≡ g ◃ t ◃ext p (i x) = p x ◃ext p (leaf l) = refl ◃ext p (s fork t) = cong₂ _fork_ (◃ext p s) (◃ext p t) _◇_ : ∀ {l m n : ℕ } -> (f : Fin m -> Term n) (g : Fin l -> Term m) -> Fin l -> Term n f ◇ g = (f ◃_) ∘ g ≐-cong : ∀ {m n o} {f : m ~> n} {g} (h : _ ~> o) -> f ≐ g -> (h ◇ f) ≐ (h ◇ g) ≐-cong h f≐g t = cong (h ◃_) (f≐g t) ≐-sym : ∀ {m n} {f : m ~> n} {g} -> f ≐ g -> g ≐ f ≐-sym f≐g = sym ∘ f≐g module Sub where fact1 : ∀ {n} -> (t : Term n) -> i ◃ t ≡ t fact1 (i x) = refl fact1 (leaf l) = refl fact1 (s fork t) = cong₂ _fork_ (fact1 s) (fact1 t) fact2 : ∀ {l m n} -> (f : Fin m -> Term n) (g : _) (t : Term l) -> (f ◇ g) ◃ t ≡ f ◃ (g ◃ t) fact2 f g (i x) = refl fact2 f g (leaf l) = refl fact2 f g (s fork t) = cong₂ _fork_ (fact2 f g s) (fact2 f g t) fact3 : ∀ {l m n} (f : Fin m -> Term n) (r : Fin l -> Fin m) -> (f ◇ (▹ r)) ≡ (f ∘ r) fact3 f r = refl -- ext (λ _ -> refl) ◃ext' : ∀ {m n o} {f : Fin m -> Term n}{g : Fin m -> Term o}{h} -> f ≐ (h ◇ g) -> ∀ t -> f ◃ t ≡ h ◃ (g ◃ t) ◃ext' p t = trans (◃ext p t) (Sub.fact2 _ _ t) open import Data.Maybe open import Category.Functor open import Category.Monad import Level open RawMonad (Data.Maybe.monad {Level.zero}) open import UnifyFin check : ∀{n} (x : Fin (suc n)) (t : Term (suc n)) -> Maybe (Term n) check x (i y) = i <$> thick x y check x (leaf l) = just (leaf l) check x (s fork t) = _fork_ <$> check x s ⊛ check x t _for_ : ∀ {n} (t' : Term n) (x : Fin (suc n)) -> Fin (suc n) -> Term n (t' for x) y = maybe′ i t' (thick x y) data AList : ℕ -> ℕ -> Set where anil : ∀ {n} -> AList n n _asnoc_/_ : ∀ {m n} (σ : AList m n) (t' : Term m) (x : Fin (suc m)) -> AList (suc m) n sub : ∀ {m n} (σ : AList m n) -> Fin m -> Term n sub anil = i sub (σ asnoc t' / x) = sub σ ◇ (t' for x) _++_ : ∀ {l m n} (ρ : AList m n) (σ : AList l m) -> AList l n ρ ++ anil = ρ ρ ++ (σ asnoc t' / x) = (ρ ++ σ) asnoc t' / x ++-assoc : ∀ {l m n o} (ρ : AList l m) (σ : AList n _) (τ : AList o _) -> ρ ++ (σ ++ τ) ≡ (ρ ++ σ) ++ τ ++-assoc ρ σ anil = refl ++-assoc ρ σ (τ asnoc t / x) = cong (λ s -> s asnoc t / x) (++-assoc ρ σ τ) module SubList where anil-id-l : ∀ {m n} (σ : AList m n) -> anil ++ σ ≡ σ anil-id-l anil = refl anil-id-l (σ asnoc t' / x) = cong (λ σ -> σ asnoc t' / x) (anil-id-l σ) fact1 : ∀ {l m n} (ρ : AList m n) (σ : AList l m) -> sub (ρ ++ σ) ≐ (sub ρ ◇ sub σ) fact1 ρ anil v = refl fact1 {suc l} {m} {n} r (s asnoc t' / x) v = trans hyp-on-terms ◃-assoc where t = (t' for x) v hyp-on-terms = ◃ext (fact1 r s) t ◃-assoc = Sub.fact2 (sub r) (sub s) t _∃asnoc_/_ : ∀ {m} (a : ∃ (AList m)) (t' : Term m) (x : Fin (suc m)) -> ∃ (AList (suc m)) (n , σ) ∃asnoc t' / x = n , σ asnoc t' / x flexFlex : ∀ {m} (x y : Fin m) -> ∃ (AList m) flexFlex {suc m} x y with thick x y ... | just y' = m , anil asnoc i y' / x ... | nothing = suc m , anil flexFlex {zero} () _ flexRigid : ∀ {m} (x : Fin m) (t : Term m) -> Maybe (∃(AList m)) flexRigid {suc m} x t with check x t ... | just t' = just (m , anil asnoc t' / x) ... | nothing = nothing flexRigid {zero} () _
The imaginary part of a complex number is a bounded linear function.
The imaginary part of a complex number is a bounded linear function.
The imaginary part of a complex number is a bounded linear function.
Formal statement is: lemma sums_cnj: "((\<lambda>x. cnj(f x)) sums cnj l) \<longleftrightarrow> (f sums l)" Informal statement is: If the complex conjugate of a series converges, then the series itself converges.
import Data.Vect Matrix : Nat -> Nat -> Type Matrix n m = Vect n (Vect m Double) TupleVect : (n : Nat) -> (ty : Type) -> Type TupleVect Z ty = () TupleVect (S k) ty = (ty, TupleVect k ty) test : TupleVect 4 Nat test = (1, 2, 3, 4, ())
[STATEMENT] lemma all_proto_hlp2: "ProtoAny \<in> a \<or> (\<forall>p \<in> {0..- 1}. Proto p \<in> a) \<longleftrightarrow> ProtoAny \<in> a \<or> a = {p. p \<noteq> ProtoAny}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (ProtoAny \<in> a \<or> (\<forall>p\<in>{0..- 1}. Proto p \<in> a)) = (ProtoAny \<in> a \<or> a = {p. p \<noteq> ProtoAny}) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. (ProtoAny \<in> a \<or> (\<forall>p\<in>{0..- 1}. Proto p \<in> a)) = (ProtoAny \<in> a \<or> a = {p. p \<noteq> ProtoAny}) [PROOF STEP] have all_proto_hlp: "ProtoAny \<notin> a \<Longrightarrow> (\<forall>p \<in> {0..- 1}. Proto p \<in> a) \<longleftrightarrow> a = {p. p \<noteq> ProtoAny}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ProtoAny \<notin> a \<Longrightarrow> (\<forall>p\<in>{0..- 1}. Proto p \<in> a) = (a = {p. p \<noteq> ProtoAny}) [PROOF STEP] by(auto intro: protocol.exhaust) [PROOF STATE] proof (state) this: ProtoAny \<notin> a \<Longrightarrow> (\<forall>p\<in>{0..- 1}. Proto p \<in> a) = (a = {p. p \<noteq> ProtoAny}) goal (1 subgoal): 1. (ProtoAny \<in> a \<or> (\<forall>p\<in>{0..- 1}. Proto p \<in> a)) = (ProtoAny \<in> a \<or> a = {p. p \<noteq> ProtoAny}) [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: ProtoAny \<notin> a \<Longrightarrow> (\<forall>p\<in>{0..- 1}. Proto p \<in> a) = (a = {p. p \<noteq> ProtoAny}) goal (1 subgoal): 1. (ProtoAny \<in> a \<or> (\<forall>p\<in>{0..- 1}. Proto p \<in> a)) = (ProtoAny \<in> a \<or> a = {p. p \<noteq> ProtoAny}) [PROOF STEP] by blast [PROOF STATE] proof (state) this: (ProtoAny \<in> a \<or> (\<forall>p\<in>{0..- 1}. Proto p \<in> a)) = (ProtoAny \<in> a \<or> a = {p. p \<noteq> ProtoAny}) goal: No subgoals! [PROOF STEP] qed
\chapter{$k$-nearest Neighbor} \input{6DL/KNN} \chapter{$k$-Means Clustering Problem and Algorithm} \input{6DL/Kmeans}
State Before: α : Type u_1 inst✝ : NonUnitalNonAssocRing α k : α h : ∀ (x : α), k * x = 0 → x = 0 ⊢ IsLeftRegular k State After: α : Type u_1 inst✝ : NonUnitalNonAssocRing α k : α h : ∀ (x : α), k * x = 0 → x = 0 x y : α h' : k * x = k * y ⊢ k * (x - y) = 0 Tactic: refine' fun x y (h' : k * x = k * y) => sub_eq_zero.mp (h _ _) State Before: α : Type u_1 inst✝ : NonUnitalNonAssocRing α k : α h : ∀ (x : α), k * x = 0 → x = 0 x y : α h' : k * x = k * y ⊢ k * (x - y) = 0 State After: no goals Tactic: rw [mul_sub, sub_eq_zero, h']
-- -------------------------------------------------------------- [ Lens.idr ] -- Description : Idris port of Control.Applicative -- Copyright : (c) Huw Campbell -- --------------------------------------------------------------------- [ EOH ] module Control.Lens.Prism import Control.Lens.Types import Control.Monad.Identity import Data.Profunctor %default total %access public export ||| Create a `Prism` prism : (b -> t) -> (s -> Either t a) -> Prism s t a b prism bt seta = dimap seta (either pure (map bt)) . right' prism' : (b -> s) -> (s -> Maybe a) -> Prism s s a b prism' bs sma = prism bs (\s => maybe (Left s) Right (sma s)) _Left : Prism (Either a c) (Either b c) a b _Left = prism Left $ either Right (Left . Right) _Right : Prism (Either c a) (Either c b) a b _Right = prism Right $ either (Left . Left) Right _Just : Prism (Maybe a) (Maybe b) a b _Just = prism Just $ maybe (Left Nothing) Right _Nothing : Prism' (Maybe a) () _Nothing = prism' (const Nothing) $ maybe (Just ()) (const Nothing) -- --------------------------------------------------------------------- [ EOF ]
[STATEMENT] lemma qfree_plus_inf: "nqfree \<phi> \<Longrightarrow> qfree(inf\<^sub>+ \<phi>)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. nqfree \<phi> \<Longrightarrow> qfree (inf\<^sub>+ \<phi>) [PROOF STEP] by(induct \<phi>)(simp_all add:qfree_aplus_inf)
#!/bin/env python # -*- coding: utf-8 -*- import numpy as np import pandas as pd from astropy.coordinates import SkyCoord import astropy.units as units from dustmaps.bayestar import BayestarWebQuery import sys from .literature_values import * class spyglass: ''' An object class that stores and calls all astrophysical components necessary for finding a targets absolute magnitude in a given band. Input: _ID: List of star IDs for identification Returns: M (pandas dataframe): Absolute magnitude of a target M_err (pandas dataframe): Error on above .. codeauthor:: Oliver James Hall ''' def __init__(self): self.oo = 0. self.r = None self.m = 0. self.ra = 9999. self.dec = 9999. self.band = None self.frame = None self.bailerjones = False def check_contents(self): kill = False try: if self.ra == 9999.: print('Please pass a RA (or appropriate longitude) in degrees.') kill = True if self.dec == 9999.: print('Please pass a Dec (or appropriate latitude) in degrees.') kill = True except ValueError: pass if self.band == None: print('You did not pass a band string when passing magnitude.\nThe band has been set to Ks.') if self.frame == None: print('You did not pass a frame string when passing position.\nThe frame has been set to ICRS.') return kill def pass_parallax(self, par, err=None): '''Feed in a value of parallax (in mas) and an optional error on parallax (in mas). ''' #Give a sanity check that we're dealing with mas if any(par < 0.01) or any(par > 5.): print(r'Are you 100% certain that (all) parallax(es) is/are in units of milliarcsec?') self.oo = par #in mas self.oo_err = err #in mas if type(self.r) != type(None): print('Youve already passed in a value of distance.') print('Be mindful that these parallaxes will overwrite this as 1000./parallax, which is technically incorrect.') self.r = 1000./self.oo self.r_err = None if type(self.oo_err) != type(None): self.r_err = np.sqrt((-1000./self.oo)**2*self.oo_err**2) def pass_distance(self, dist, err=None): '''Feed in a properly treated value of distance (in pc) and an optional error on distance (in pc). ''' self.r = dist #in pc self.r_err = err #in pc self.bailerjones = True #Using proper distances def pass_position(self, ra, dec, frame='icrs'): '''Feed in the position and the reference frame. Input: ra: the longitutde value (can be GLON for frame='galactic', for example) dec: the latitude value (can be GLAT for frame='galactic', for example) ''' self.ra = ra self.dec = dec self.frame = frame def pass_magnitude(self, mag, err=None, band='Ks'): '''Pass in the apparent magnitues of a target in a given band. ''' self.m = mag self.m_err = err self.band = band def get_mu0(self): '''Calculate the distance modulus from the parallax. ''' return 5*np.log10(self.r) - 5 def get_b17_ebv(self): '''Send a request to the online Bayestar catalogue for the extinction coefficients of all the targets. ''' #Call the Bayestar catalogue bayestar = BayestarWebQuery(version='bayestar2017') coords = SkyCoord(self.ra.values*units.deg, self.dec.values*units.deg, distance=(self.r.values)*units.pc,frame=self.frame) #Find the extinction coefficient try: b17 = bayestar(coords, mode='median') except: print('The Av values cant be downloaded for some reason.') print('No Av values for this star. Set Av to 0. for now.') b17 = np.ones(self.ra.shape) '''Convert the Bayestar 17 values to E(B-V) values using the Green et al. 2018 conversion''' ebv = 0.88 * b17 return b17, ebv def get_Aband(self): '''Calculates the extinction coefficient in the chosen band by using the values from Green et al. 2018. ''' #Check we have the conversion for this band of magnitudes if not any(self.band in head for head in list(Av_coeffs)): print('The class cant handle this specific band yet.') print('Please double check youve input the string correctly. The list of possible bands is:') print(list(coeffs)) print('And you passed in: '+self.band) sys.exit() return self.get_b17_ebv()[0] * Av_coeffs[self.band].values def get_error(self): '''Calculate the error on the absolute magnitude, given possible errors in apparent magnitude and parallax. ''' #Case 0: No errors try: if (self.m_err is None) & (self.r_err is None): print('No errors given, error on M set to 0.') M_err = 0. except ValueError: pass #Case 1: Distance error only if self.m_err is None: M_err = np.sqrt((5/(self.r*np.log(10)))**2 * self.r_err**2) #Case 2: Magnitude error only elif self.oo_err is None: M_err = self.m_err #Case 3: Errors on both values else: M_err = np.sqrt(self.m_err**2 + (5/(self.r*np.log(10)))**2 * self.r_err**2) #Add the assumed error on Av return np.sqrt(M_err**2 + err_av**2) def get_M(self): '''Calculate the absolute magnitude given apparent magnitude, parallax and the Bayestar extiction coefficients. ''' if self.check_contents(): print('Im going to kill the run so you can pass the values correctly.') sys.exit() return None m = self.m #Call in the magnitude mu0 = self.get_mu0() #Call in the distance modulus Aband = self.get_Aband() #Call in the appropriate extinction coeff M_err = self.get_error() #Propagate the error through return m - mu0 - Aband, M_err
f = @(x) objfun(x); A = [-2 1;-1 -1;1 0;0 1]; b = [-1;-2;0;0]; E = []; e = []; [xstar,ystar] = zoutendijk(f,A,b,E,e)
[STATEMENT] lemma Limit_insert_in_VsetI: assumes [intro]: "Limit \<alpha>" and [simp]: "small x" and "set x \<in>\<^sub>\<circ> Vset \<alpha>" and [intro]: "a \<in>\<^sub>\<circ> Vset \<alpha>" shows "set (insert a x) \<in>\<^sub>\<circ> Vset \<alpha>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. set (insert a x) \<in>\<^sub>\<circ> Vset \<alpha> [PROOF STEP] proof- [PROOF STATE] proof (state) goal (1 subgoal): 1. set (insert a x) \<in>\<^sub>\<circ> Vset \<alpha> [PROOF STEP] have ax: "set (insert a x) = vinsert a (set x)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. set (insert a x) = vinsert a (set x) [PROOF STEP] by auto [PROOF STATE] proof (state) this: set (insert a x) = vinsert a (set x) goal (1 subgoal): 1. set (insert a x) \<in>\<^sub>\<circ> Vset \<alpha> [PROOF STEP] from assms [PROOF STATE] proof (chain) picking this: Limit \<alpha> small x set x \<in>\<^sub>\<circ> Vset \<alpha> a \<in>\<^sub>\<circ> Vset \<alpha> [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: Limit \<alpha> small x set x \<in>\<^sub>\<circ> Vset \<alpha> a \<in>\<^sub>\<circ> Vset \<alpha> goal (1 subgoal): 1. set (insert a x) \<in>\<^sub>\<circ> Vset \<alpha> [PROOF STEP] unfolding ax [PROOF STATE] proof (prove) using this: Limit \<alpha> small x set x \<in>\<^sub>\<circ> Vset \<alpha> a \<in>\<^sub>\<circ> Vset \<alpha> goal (1 subgoal): 1. vinsert a (set x) \<in>\<^sub>\<circ> Vset \<alpha> [PROOF STEP] by auto [PROOF STATE] proof (state) this: set (insert a x) \<in>\<^sub>\<circ> Vset \<alpha> goal: No subgoals! [PROOF STEP] qed
[GOAL] R : Type u_1 inst✝² : CommRing R K : Type u_2 inst✝¹ : Field K inst✝ : Algebra R K f : R[X] hf : Monic f g : K[X] hg : Monic g hd : g ∣ map (algebraMap R K) f ⊢ g ∈ lifts (algebraMap { x // x ∈ integralClosure R K } K) [PROOFSTEP] have := mem_lift_of_splits_of_roots_mem_range (integralClosure R g.SplittingField) ((splits_id_iff_splits _).2 <| SplittingField.splits g) (hg.map _) fun a ha => (SetLike.ext_iff.mp (integralClosure R g.SplittingField).range_algebraMap _).mpr <| roots_mem_integralClosure hf ?_ [GOAL] case refine_2 R : Type u_1 inst✝² : CommRing R K : Type u_2 inst✝¹ : Field K inst✝ : Algebra R K f : R[X] hf : Monic f g : K[X] hg : Monic g hd : g ∣ map (algebraMap R K) f this : map (algebraMap K (SplittingField g)) g ∈ lifts (algebraMap { x // x ∈ integralClosure R (SplittingField g) } (SplittingField g)) ⊢ g ∈ lifts (algebraMap { x // x ∈ integralClosure R K } K) [PROOFSTEP] rw [lifts_iff_coeff_lifts, ← RingHom.coe_range, Subalgebra.range_algebraMap] at this [GOAL] case refine_2 R : Type u_1 inst✝² : CommRing R K : Type u_2 inst✝¹ : Field K inst✝ : Algebra R K f : R[X] hf : Monic f g : K[X] hg : Monic g hd : g ∣ map (algebraMap R K) f this : ∀ (n : ℕ), coeff (map (algebraMap K (SplittingField g)) g) n ∈ ↑(Subalgebra.toSubring (integralClosure R (SplittingField g))) ⊢ g ∈ lifts (algebraMap { x // x ∈ integralClosure R K } K) [PROOFSTEP] refine' (lifts_iff_coeff_lifts _).2 fun n => _ [GOAL] case refine_2 R : Type u_1 inst✝² : CommRing R K : Type u_2 inst✝¹ : Field K inst✝ : Algebra R K f : R[X] hf : Monic f g : K[X] hg : Monic g hd : g ∣ map (algebraMap R K) f this : ∀ (n : ℕ), coeff (map (algebraMap K (SplittingField g)) g) n ∈ ↑(Subalgebra.toSubring (integralClosure R (SplittingField g))) n : ℕ ⊢ coeff g n ∈ Set.range ↑(algebraMap { x // x ∈ integralClosure R K } K) [PROOFSTEP] rw [← RingHom.coe_range, Subalgebra.range_algebraMap] [GOAL] case refine_2 R : Type u_1 inst✝² : CommRing R K : Type u_2 inst✝¹ : Field K inst✝ : Algebra R K f : R[X] hf : Monic f g : K[X] hg : Monic g hd : g ∣ map (algebraMap R K) f this : ∀ (n : ℕ), coeff (map (algebraMap K (SplittingField g)) g) n ∈ ↑(Subalgebra.toSubring (integralClosure R (SplittingField g))) n : ℕ ⊢ coeff g n ∈ ↑(Subalgebra.toSubring (integralClosure R K)) [PROOFSTEP] obtain ⟨p, hp, he⟩ := SetLike.mem_coe.mp (this n) [GOAL] case refine_2.intro.intro R : Type u_1 inst✝² : CommRing R K : Type u_2 inst✝¹ : Field K inst✝ : Algebra R K f : R[X] hf : Monic f g : K[X] hg : Monic g hd : g ∣ map (algebraMap R K) f this : ∀ (n : ℕ), coeff (map (algebraMap K (SplittingField g)) g) n ∈ ↑(Subalgebra.toSubring (integralClosure R (SplittingField g))) n : ℕ p : R[X] hp : Monic p he : eval₂ (algebraMap R (SplittingField g)) (coeff (map (algebraMap K (SplittingField g)) g) n) p = 0 ⊢ coeff g n ∈ ↑(Subalgebra.toSubring (integralClosure R K)) [PROOFSTEP] use p, hp [GOAL] case right R : Type u_1 inst✝² : CommRing R K : Type u_2 inst✝¹ : Field K inst✝ : Algebra R K f : R[X] hf : Monic f g : K[X] hg : Monic g hd : g ∣ map (algebraMap R K) f this : ∀ (n : ℕ), coeff (map (algebraMap K (SplittingField g)) g) n ∈ ↑(Subalgebra.toSubring (integralClosure R (SplittingField g))) n : ℕ p : R[X] hp : Monic p he : eval₂ (algebraMap R (SplittingField g)) (coeff (map (algebraMap K (SplittingField g)) g) n) p = 0 ⊢ eval₂ (algebraMap R K) (coeff g n) p = 0 [PROOFSTEP] rw [IsScalarTower.algebraMap_eq R K, coeff_map, ← eval₂_map, eval₂_at_apply] at he [GOAL] case right R : Type u_1 inst✝² : CommRing R K : Type u_2 inst✝¹ : Field K inst✝ : Algebra R K f : R[X] hf : Monic f g : K[X] hg : Monic g hd : g ∣ map (algebraMap R K) f this : ∀ (n : ℕ), coeff (map (algebraMap K (SplittingField g)) g) n ∈ ↑(Subalgebra.toSubring (integralClosure R (SplittingField g))) n : ℕ p : R[X] hp : Monic p he : ↑(algebraMap K (SplittingField g)) (eval (coeff g n) (map (algebraMap R K) p)) = 0 ⊢ eval₂ (algebraMap R K) (coeff g n) p = 0 [PROOFSTEP] rw [eval₂_eq_eval_map] [GOAL] case right R : Type u_1 inst✝² : CommRing R K : Type u_2 inst✝¹ : Field K inst✝ : Algebra R K f : R[X] hf : Monic f g : K[X] hg : Monic g hd : g ∣ map (algebraMap R K) f this : ∀ (n : ℕ), coeff (map (algebraMap K (SplittingField g)) g) n ∈ ↑(Subalgebra.toSubring (integralClosure R (SplittingField g))) n : ℕ p : R[X] hp : Monic p he : ↑(algebraMap K (SplittingField g)) (eval (coeff g n) (map (algebraMap R K) p)) = 0 ⊢ eval (coeff g n) (map (algebraMap R K) p) = 0 [PROOFSTEP] apply (injective_iff_map_eq_zero _).1 _ _ he [GOAL] R : Type u_1 inst✝² : CommRing R K : Type u_2 inst✝¹ : Field K inst✝ : Algebra R K f : R[X] hf : Monic f g : K[X] hg : Monic g hd : g ∣ map (algebraMap R K) f this : ∀ (n : ℕ), coeff (map (algebraMap K (SplittingField g)) g) n ∈ ↑(Subalgebra.toSubring (integralClosure R (SplittingField g))) n : ℕ p : R[X] hp : Monic p he : ↑(algebraMap K (SplittingField g)) (eval (coeff g n) (map (algebraMap R K) p)) = 0 ⊢ Function.Injective ↑(algebraMap K (SplittingField g)) [PROOFSTEP] apply RingHom.injective [GOAL] case refine_1 R : Type u_1 inst✝² : CommRing R K : Type u_2 inst✝¹ : Field K inst✝ : Algebra R K f : R[X] hf : Monic f g : K[X] hg : Monic g hd : g ∣ map (algebraMap R K) f a : SplittingField g ha : a ∈ roots (map (algebraMap K (SplittingField g)) g) ⊢ a ∈ roots (map (algebraMap R (SplittingField g)) f) [PROOFSTEP] rw [IsScalarTower.algebraMap_eq R K _, ← map_map] [GOAL] case refine_1 R : Type u_1 inst✝² : CommRing R K : Type u_2 inst✝¹ : Field K inst✝ : Algebra R K f : R[X] hf : Monic f g : K[X] hg : Monic g hd : g ∣ map (algebraMap R K) f a : SplittingField g ha : a ∈ roots (map (algebraMap K (SplittingField g)) g) ⊢ a ∈ roots (map (algebraMap K (SplittingField g)) (map (algebraMap R K) f)) [PROOFSTEP] refine' Multiset.mem_of_le (roots.le_of_dvd ((hf.map _).map _).ne_zero _) ha [GOAL] case refine_1 R : Type u_1 inst✝² : CommRing R K : Type u_2 inst✝¹ : Field K inst✝ : Algebra R K f : R[X] hf : Monic f g : K[X] hg : Monic g hd : g ∣ map (algebraMap R K) f a : SplittingField g ha : a ∈ roots (map (algebraMap K (SplittingField g)) g) ⊢ map (algebraMap K (SplittingField g)) g ∣ map (algebraMap K (SplittingField g)) (map (algebraMap R K) f) [PROOFSTEP] exact map_dvd (algebraMap K g.SplittingField) hd [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f ⊢ ∃ g', map (algebraMap R K) g' * ↑C (leadingCoeff g) = g [PROOFSTEP] have g_ne_0 : g ≠ 0 := ne_zero_of_dvd_ne_zero (Monic.ne_zero <| hf.map (algebraMap R K)) hg [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 ⊢ ∃ g', map (algebraMap R K) g' * ↑C (leadingCoeff g) = g [PROOFSTEP] suffices lem : ∃ g' : R[X], g'.map (algebraMap R K) = g * C g.leadingCoeff⁻¹ [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 lem : ∃ g', map (algebraMap R K) g' = g * ↑C (leadingCoeff g)⁻¹ ⊢ ∃ g', map (algebraMap R K) g' * ↑C (leadingCoeff g) = g [PROOFSTEP] obtain ⟨g', hg'⟩ := lem [GOAL] case intro R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 g' : R[X] hg' : map (algebraMap R K) g' = g * ↑C (leadingCoeff g)⁻¹ ⊢ ∃ g', map (algebraMap R K) g' * ↑C (leadingCoeff g) = g [PROOFSTEP] use g' [GOAL] case h R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 g' : R[X] hg' : map (algebraMap R K) g' = g * ↑C (leadingCoeff g)⁻¹ ⊢ map (algebraMap R K) g' * ↑C (leadingCoeff g) = g [PROOFSTEP] rw [hg', mul_assoc, ← C_mul, inv_mul_cancel (leadingCoeff_ne_zero.mpr g_ne_0), C_1, mul_one] [GOAL] case lem R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 ⊢ ∃ g', map (algebraMap R K) g' = g * ↑C (leadingCoeff g)⁻¹ [PROOFSTEP] have g_mul_dvd : g * C g.leadingCoeff⁻¹ ∣ f.map (algebraMap R K) := by rwa [Associated.dvd_iff_dvd_left (show Associated (g * C g.leadingCoeff⁻¹) g from _)] rw [associated_mul_isUnit_left_iff] exact isUnit_C.mpr (inv_ne_zero <| leadingCoeff_ne_zero.mpr g_ne_0).isUnit [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 ⊢ g * ↑C (leadingCoeff g)⁻¹ ∣ map (algebraMap R K) f [PROOFSTEP] rwa [Associated.dvd_iff_dvd_left (show Associated (g * C g.leadingCoeff⁻¹) g from _)] [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 ⊢ Associated (g * ↑C (leadingCoeff g)⁻¹) g [PROOFSTEP] rw [associated_mul_isUnit_left_iff] [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 ⊢ IsUnit (↑C (leadingCoeff g)⁻¹) [PROOFSTEP] exact isUnit_C.mpr (inv_ne_zero <| leadingCoeff_ne_zero.mpr g_ne_0).isUnit [GOAL] case lem R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 g_mul_dvd : g * ↑C (leadingCoeff g)⁻¹ ∣ map (algebraMap R K) f ⊢ ∃ g', map (algebraMap R K) g' = g * ↑C (leadingCoeff g)⁻¹ [PROOFSTEP] let algeq := (Subalgebra.equivOfEq _ _ <| integralClosure_eq_bot R _).trans (Algebra.botEquivOfInjective <| IsFractionRing.injective R <| K) [GOAL] case lem R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 g_mul_dvd : g * ↑C (leadingCoeff g)⁻¹ ∣ map (algebraMap R K) f algeq : { x // x ∈ integralClosure R K } ≃ₐ[R] R := AlgEquiv.trans (Subalgebra.equivOfEq (integralClosure R K) ⊥ (_ : integralClosure R K = ⊥)) (Algebra.botEquivOfInjective (_ : Function.Injective ↑(algebraMap R K))) ⊢ ∃ g', map (algebraMap R K) g' = g * ↑C (leadingCoeff g)⁻¹ [PROOFSTEP] have : (algebraMap R _).comp algeq.toAlgHom.toRingHom = (integralClosure R _).toSubring.subtype := by ext x; conv_rhs => rw [← algeq.symm_apply_apply x]; rfl [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 g_mul_dvd : g * ↑C (leadingCoeff g)⁻¹ ∣ map (algebraMap R K) f algeq : { x // x ∈ integralClosure R K } ≃ₐ[R] R := AlgEquiv.trans (Subalgebra.equivOfEq (integralClosure R K) ⊥ (_ : integralClosure R K = ⊥)) (Algebra.botEquivOfInjective (_ : Function.Injective ↑(algebraMap R K))) ⊢ RingHom.comp (algebraMap R K) ↑↑algeq = Subring.subtype (Subalgebra.toSubring (integralClosure R K)) [PROOFSTEP] ext x [GOAL] case a R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 g_mul_dvd : g * ↑C (leadingCoeff g)⁻¹ ∣ map (algebraMap R K) f algeq : { x // x ∈ integralClosure R K } ≃ₐ[R] R := AlgEquiv.trans (Subalgebra.equivOfEq (integralClosure R K) ⊥ (_ : integralClosure R K = ⊥)) (Algebra.botEquivOfInjective (_ : Function.Injective ↑(algebraMap R K))) x : { x // x ∈ integralClosure R K } ⊢ ↑(RingHom.comp (algebraMap R K) ↑↑algeq) x = ↑(Subring.subtype (Subalgebra.toSubring (integralClosure R K))) x [PROOFSTEP] conv_rhs => rw [← algeq.symm_apply_apply x]; rfl [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 g_mul_dvd : g * ↑C (leadingCoeff g)⁻¹ ∣ map (algebraMap R K) f algeq : { x // x ∈ integralClosure R K } ≃ₐ[R] R := AlgEquiv.trans (Subalgebra.equivOfEq (integralClosure R K) ⊥ (_ : integralClosure R K = ⊥)) (Algebra.botEquivOfInjective (_ : Function.Injective ↑(algebraMap R K))) x : { x // x ∈ integralClosure R K } | ↑(Subring.subtype (Subalgebra.toSubring (integralClosure R K))) x [PROOFSTEP] rw [← algeq.symm_apply_apply x]; rfl [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 g_mul_dvd : g * ↑C (leadingCoeff g)⁻¹ ∣ map (algebraMap R K) f algeq : { x // x ∈ integralClosure R K } ≃ₐ[R] R := AlgEquiv.trans (Subalgebra.equivOfEq (integralClosure R K) ⊥ (_ : integralClosure R K = ⊥)) (Algebra.botEquivOfInjective (_ : Function.Injective ↑(algebraMap R K))) x : { x // x ∈ integralClosure R K } | ↑(Subring.subtype (Subalgebra.toSubring (integralClosure R K))) x [PROOFSTEP] rw [← algeq.symm_apply_apply x]; rfl [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 g_mul_dvd : g * ↑C (leadingCoeff g)⁻¹ ∣ map (algebraMap R K) f algeq : { x // x ∈ integralClosure R K } ≃ₐ[R] R := AlgEquiv.trans (Subalgebra.equivOfEq (integralClosure R K) ⊥ (_ : integralClosure R K = ⊥)) (Algebra.botEquivOfInjective (_ : Function.Injective ↑(algebraMap R K))) x : { x // x ∈ integralClosure R K } | ↑(Subring.subtype (Subalgebra.toSubring (integralClosure R K))) x [PROOFSTEP] rw [← algeq.symm_apply_apply x] [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 g_mul_dvd : g * ↑C (leadingCoeff g)⁻¹ ∣ map (algebraMap R K) f algeq : { x // x ∈ integralClosure R K } ≃ₐ[R] R := AlgEquiv.trans (Subalgebra.equivOfEq (integralClosure R K) ⊥ (_ : integralClosure R K = ⊥)) (Algebra.botEquivOfInjective (_ : Function.Injective ↑(algebraMap R K))) x : { x // x ∈ integralClosure R K } | ↑(Subring.subtype (Subalgebra.toSubring (integralClosure R K))) (↑(AlgEquiv.symm algeq) (↑algeq x)) [PROOFSTEP] rfl [GOAL] case lem R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 g_mul_dvd : g * ↑C (leadingCoeff g)⁻¹ ∣ map (algebraMap R K) f algeq : { x // x ∈ integralClosure R K } ≃ₐ[R] R := AlgEquiv.trans (Subalgebra.equivOfEq (integralClosure R K) ⊥ (_ : integralClosure R K = ⊥)) (Algebra.botEquivOfInjective (_ : Function.Injective ↑(algebraMap R K))) this : RingHom.comp (algebraMap R K) ↑↑algeq = Subring.subtype (Subalgebra.toSubring (integralClosure R K)) ⊢ ∃ g', map (algebraMap R K) g' = g * ↑C (leadingCoeff g)⁻¹ [PROOFSTEP] have H := (mem_lifts _).1 (integralClosure.mem_lifts_of_monic_of_dvd_map K hf (monic_mul_leadingCoeff_inv g_ne_0) g_mul_dvd) [GOAL] case lem R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 g_mul_dvd : g * ↑C (leadingCoeff g)⁻¹ ∣ map (algebraMap R K) f algeq : { x // x ∈ integralClosure R K } ≃ₐ[R] R := AlgEquiv.trans (Subalgebra.equivOfEq (integralClosure R K) ⊥ (_ : integralClosure R K = ⊥)) (Algebra.botEquivOfInjective (_ : Function.Injective ↑(algebraMap R K))) this : RingHom.comp (algebraMap R K) ↑↑algeq = Subring.subtype (Subalgebra.toSubring (integralClosure R K)) H : ∃ q, map (algebraMap { x // x ∈ integralClosure R K } K) q = g * ↑C (leadingCoeff g)⁻¹ ⊢ ∃ g', map (algebraMap R K) g' = g * ↑C (leadingCoeff g)⁻¹ [PROOFSTEP] refine' ⟨map algeq.toAlgHom.toRingHom _, _⟩ [GOAL] case lem.refine'_1 R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 g_mul_dvd : g * ↑C (leadingCoeff g)⁻¹ ∣ map (algebraMap R K) f algeq : { x // x ∈ integralClosure R K } ≃ₐ[R] R := AlgEquiv.trans (Subalgebra.equivOfEq (integralClosure R K) ⊥ (_ : integralClosure R K = ⊥)) (Algebra.botEquivOfInjective (_ : Function.Injective ↑(algebraMap R K))) this : RingHom.comp (algebraMap R K) ↑↑algeq = Subring.subtype (Subalgebra.toSubring (integralClosure R K)) H : ∃ q, map (algebraMap { x // x ∈ integralClosure R K } K) q = g * ↑C (leadingCoeff g)⁻¹ ⊢ { x // x ∈ integralClosure R K }[X] [PROOFSTEP] use! Classical.choose H [GOAL] case lem.refine'_2 R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 g_mul_dvd : g * ↑C (leadingCoeff g)⁻¹ ∣ map (algebraMap R K) f algeq : { x // x ∈ integralClosure R K } ≃ₐ[R] R := AlgEquiv.trans (Subalgebra.equivOfEq (integralClosure R K) ⊥ (_ : integralClosure R K = ⊥)) (Algebra.botEquivOfInjective (_ : Function.Injective ↑(algebraMap R K))) this : RingHom.comp (algebraMap R K) ↑↑algeq = Subring.subtype (Subalgebra.toSubring (integralClosure R K)) H : ∃ q, map (algebraMap { x // x ∈ integralClosure R K } K) q = g * ↑C (leadingCoeff g)⁻¹ ⊢ map (algebraMap R K) (map (↑↑algeq) (Classical.choose H)) = g * ↑C (leadingCoeff g)⁻¹ [PROOFSTEP] rw [map_map, this] [GOAL] case lem.refine'_2 R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsDomain R inst✝¹ : IsFractionRing R K inst✝ : IsIntegrallyClosed R f : R[X] hf : Monic f g : K[X] hg : g ∣ map (algebraMap R K) f g_ne_0 : g ≠ 0 g_mul_dvd : g * ↑C (leadingCoeff g)⁻¹ ∣ map (algebraMap R K) f algeq : { x // x ∈ integralClosure R K } ≃ₐ[R] R := AlgEquiv.trans (Subalgebra.equivOfEq (integralClosure R K) ⊥ (_ : integralClosure R K = ⊥)) (Algebra.botEquivOfInjective (_ : Function.Injective ↑(algebraMap R K))) this : RingHom.comp (algebraMap R K) ↑↑algeq = Subring.subtype (Subalgebra.toSubring (integralClosure R K)) H : ∃ q, map (algebraMap { x // x ∈ integralClosure R K } K) q = g * ↑C (leadingCoeff g)⁻¹ ⊢ map (Subring.subtype (Subalgebra.toSubring (integralClosure R K))) (Classical.choose H) = g * ↑C (leadingCoeff g)⁻¹ [PROOFSTEP] exact Classical.choose_spec H [GOAL] R : Type u_1 inst✝² : CommRing R S : Type u_2 inst✝¹ : CommRing S inst✝ : IsDomain S φ : R →+* S hinj : Function.Injective ↑φ f : R[X] hf : IsPrimitive f ⊢ IsUnit f ↔ IsUnit (map φ f) [PROOFSTEP] refine' ⟨(mapRingHom φ).isUnit_map, fun h => _⟩ [GOAL] R : Type u_1 inst✝² : CommRing R S : Type u_2 inst✝¹ : CommRing S inst✝ : IsDomain S φ : R →+* S hinj : Function.Injective ↑φ f : R[X] hf : IsPrimitive f h : IsUnit (map φ f) ⊢ IsUnit f [PROOFSTEP] rcases isUnit_iff.1 h with ⟨_, ⟨u, rfl⟩, hu⟩ [GOAL] case intro.intro.intro R : Type u_1 inst✝² : CommRing R S : Type u_2 inst✝¹ : CommRing S inst✝ : IsDomain S φ : R →+* S hinj : Function.Injective ↑φ f : R[X] hf : IsPrimitive f h : IsUnit (map φ f) u : Sˣ hu : ↑C ↑u = map φ f ⊢ IsUnit f [PROOFSTEP] have hdeg := degree_C u.ne_zero [GOAL] case intro.intro.intro R : Type u_1 inst✝² : CommRing R S : Type u_2 inst✝¹ : CommRing S inst✝ : IsDomain S φ : R →+* S hinj : Function.Injective ↑φ f : R[X] hf : IsPrimitive f h : IsUnit (map φ f) u : Sˣ hu : ↑C ↑u = map φ f hdeg : degree (↑C ↑u) = 0 ⊢ IsUnit f [PROOFSTEP] rw [hu, degree_map_eq_of_injective hinj] at hdeg [GOAL] case intro.intro.intro R : Type u_1 inst✝² : CommRing R S : Type u_2 inst✝¹ : CommRing S inst✝ : IsDomain S φ : R →+* S hinj : Function.Injective ↑φ f : R[X] hf : IsPrimitive f h : IsUnit (map φ f) u : Sˣ hu : ↑C ↑u = map φ f hdeg : degree f = 0 ⊢ IsUnit f [PROOFSTEP] rw [eq_C_of_degree_eq_zero hdeg] at hf ⊢ [GOAL] case intro.intro.intro R : Type u_1 inst✝² : CommRing R S : Type u_2 inst✝¹ : CommRing S inst✝ : IsDomain S φ : R →+* S hinj : Function.Injective ↑φ f : R[X] hf : IsPrimitive (↑C (coeff f 0)) h : IsUnit (map φ f) u : Sˣ hu : ↑C ↑u = map φ f hdeg : degree f = 0 ⊢ IsUnit (↑C (coeff f 0)) [PROOFSTEP] exact isUnit_C.mpr (isPrimitive_iff_isUnit_of_C_dvd.mp hf (f.coeff 0) dvd_rfl) [GOAL] R : Type u_1 inst✝² : CommRing R S : Type u_2 inst✝¹ : CommRing S inst✝ : IsDomain S φ : R →+* S hinj : Function.Injective ↑φ f : R[X] hf : IsPrimitive f h_irr : Irreducible (map φ f) ⊢ Irreducible f [PROOFSTEP] refine' ⟨fun h => h_irr.not_unit (IsUnit.map (mapRingHom φ) h), fun a b h => (h_irr.isUnit_or_isUnit <| by rw [h, Polynomial.map_mul]).imp _ _⟩ [GOAL] R : Type u_1 inst✝² : CommRing R S : Type u_2 inst✝¹ : CommRing S inst✝ : IsDomain S φ : R →+* S hinj : Function.Injective ↑φ f : R[X] hf : IsPrimitive f h_irr : Irreducible (map φ f) a b : R[X] h : f = a * b ⊢ map φ f = ?m.200623 a b h * ?m.200624 a b h [PROOFSTEP] rw [h, Polynomial.map_mul] [GOAL] case refine'_1 R : Type u_1 inst✝² : CommRing R S : Type u_2 inst✝¹ : CommRing S inst✝ : IsDomain S φ : R →+* S hinj : Function.Injective ↑φ f : R[X] hf : IsPrimitive f h_irr : Irreducible (map φ f) a b : R[X] h : f = a * b ⊢ IsUnit (map φ a) → IsUnit a case refine'_2 R : Type u_1 inst✝² : CommRing R S : Type u_2 inst✝¹ : CommRing S inst✝ : IsDomain S φ : R →+* S hinj : Function.Injective ↑φ f : R[X] hf : IsPrimitive f h_irr : Irreducible (map φ f) a b : R[X] h : f = a * b ⊢ IsUnit (map φ b) → IsUnit b [PROOFSTEP] all_goals apply ((isPrimitive_of_dvd hf _).isUnit_iff_isUnit_map_of_injective hinj).mpr [GOAL] case refine'_1 R : Type u_1 inst✝² : CommRing R S : Type u_2 inst✝¹ : CommRing S inst✝ : IsDomain S φ : R →+* S hinj : Function.Injective ↑φ f : R[X] hf : IsPrimitive f h_irr : Irreducible (map φ f) a b : R[X] h : f = a * b ⊢ IsUnit (map φ a) → IsUnit a [PROOFSTEP] apply ((isPrimitive_of_dvd hf _).isUnit_iff_isUnit_map_of_injective hinj).mpr [GOAL] case refine'_2 R : Type u_1 inst✝² : CommRing R S : Type u_2 inst✝¹ : CommRing S inst✝ : IsDomain S φ : R →+* S hinj : Function.Injective ↑φ f : R[X] hf : IsPrimitive f h_irr : Irreducible (map φ f) a b : R[X] h : f = a * b ⊢ IsUnit (map φ b) → IsUnit b [PROOFSTEP] apply ((isPrimitive_of_dvd hf _).isUnit_iff_isUnit_map_of_injective hinj).mpr [GOAL] R : Type u_1 inst✝² : CommRing R S : Type u_2 inst✝¹ : CommRing S inst✝ : IsDomain S φ : R →+* S hinj : Function.Injective ↑φ f : R[X] hf : IsPrimitive f h_irr : Irreducible (map φ f) a b : R[X] h : f = a * b ⊢ a ∣ f R : Type u_1 inst✝² : CommRing R S : Type u_2 inst✝¹ : CommRing S inst✝ : IsDomain S φ : R →+* S hinj : Function.Injective ↑φ f : R[X] hf : IsPrimitive f h_irr : Irreducible (map φ f) a b : R[X] h : f = a * b ⊢ b ∣ f [PROOFSTEP] exacts [Dvd.intro _ h.symm, Dvd.intro_left _ h.symm] [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p : R[X] h : Monic p ⊢ Irreducible p ↔ Irreducible (Polynomial.map (algebraMap R K) p) [PROOFSTEP] refine' ⟨fun hp => irreducible_iff.mpr ⟨hp.not_unit.imp h.isPrimitive.isUnit_iff_isUnit_map.mpr, fun a b H => or_iff_not_imp_left.mpr fun hₐ => _⟩, fun hp => h.isPrimitive.irreducible_of_irreducible_map_of_injective (IsFractionRing.injective R K) hp⟩ [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p : R[X] h : Monic p hp : Irreducible p a b : K[X] H : Polynomial.map (algebraMap R K) p = a * b hₐ : ¬IsUnit a ⊢ IsUnit b [PROOFSTEP] obtain ⟨a', ha⟩ := eq_map_mul_C_of_dvd K h (dvd_of_mul_right_eq b H.symm) [GOAL] case intro R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p : R[X] h : Monic p hp : Irreducible p a b : K[X] H : Polynomial.map (algebraMap R K) p = a * b hₐ : ¬IsUnit a a' : R[X] ha : Polynomial.map (algebraMap R K) a' * ↑C (Polynomial.leadingCoeff a) = a ⊢ IsUnit b [PROOFSTEP] obtain ⟨b', hb⟩ := eq_map_mul_C_of_dvd K h (dvd_of_mul_left_eq a H.symm) [GOAL] case intro.intro R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p : R[X] h : Monic p hp : Irreducible p a b : K[X] H : Polynomial.map (algebraMap R K) p = a * b hₐ : ¬IsUnit a a' : R[X] ha : Polynomial.map (algebraMap R K) a' * ↑C (Polynomial.leadingCoeff a) = a b' : R[X] hb : Polynomial.map (algebraMap R K) b' * ↑C (Polynomial.leadingCoeff b) = b ⊢ IsUnit b [PROOFSTEP] have : a.leadingCoeff * b.leadingCoeff = 1 := by rw [← leadingCoeff_mul, ← H, Monic.leadingCoeff (h.map <| algebraMap R K)] [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p : R[X] h : Monic p hp : Irreducible p a b : K[X] H : Polynomial.map (algebraMap R K) p = a * b hₐ : ¬IsUnit a a' : R[X] ha : Polynomial.map (algebraMap R K) a' * ↑C (Polynomial.leadingCoeff a) = a b' : R[X] hb : Polynomial.map (algebraMap R K) b' * ↑C (Polynomial.leadingCoeff b) = b ⊢ Polynomial.leadingCoeff a * Polynomial.leadingCoeff b = 1 [PROOFSTEP] rw [← leadingCoeff_mul, ← H, Monic.leadingCoeff (h.map <| algebraMap R K)] [GOAL] case intro.intro R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p : R[X] h : Monic p hp : Irreducible p a b : K[X] H : Polynomial.map (algebraMap R K) p = a * b hₐ : ¬IsUnit a a' : R[X] ha : Polynomial.map (algebraMap R K) a' * ↑C (Polynomial.leadingCoeff a) = a b' : R[X] hb : Polynomial.map (algebraMap R K) b' * ↑C (Polynomial.leadingCoeff b) = b this : Polynomial.leadingCoeff a * Polynomial.leadingCoeff b = 1 ⊢ IsUnit b [PROOFSTEP] rw [← ha, ← hb, mul_comm _ (C b.leadingCoeff), mul_assoc, ← mul_assoc (C a.leadingCoeff), ← C_mul, this, C_1, one_mul, ← Polynomial.map_mul] at H [GOAL] case intro.intro R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p : R[X] h : Monic p hp : Irreducible p a b : K[X] hₐ : ¬IsUnit a a' : R[X] ha : Polynomial.map (algebraMap R K) a' * ↑C (Polynomial.leadingCoeff a) = a b' : R[X] H : Polynomial.map (algebraMap R K) p = Polynomial.map (algebraMap R K) (a' * b') hb : Polynomial.map (algebraMap R K) b' * ↑C (Polynomial.leadingCoeff b) = b this : Polynomial.leadingCoeff a * Polynomial.leadingCoeff b = 1 ⊢ IsUnit b [PROOFSTEP] rw [← hb, ← Polynomial.coe_mapRingHom] [GOAL] case intro.intro R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p : R[X] h : Monic p hp : Irreducible p a b : K[X] hₐ : ¬IsUnit a a' : R[X] ha : Polynomial.map (algebraMap R K) a' * ↑C (Polynomial.leadingCoeff a) = a b' : R[X] H : Polynomial.map (algebraMap R K) p = Polynomial.map (algebraMap R K) (a' * b') hb : Polynomial.map (algebraMap R K) b' * ↑C (Polynomial.leadingCoeff b) = b this : Polynomial.leadingCoeff a * Polynomial.leadingCoeff b = 1 ⊢ IsUnit (↑(mapRingHom (algebraMap R K)) b' * ↑C (Polynomial.leadingCoeff b)) [PROOFSTEP] refine' IsUnit.mul (IsUnit.map _ (Or.resolve_left (hp.isUnit_or_isUnit _) (show ¬IsUnit a' from _))) (isUnit_iff_exists_inv'.mpr (Exists.intro (C a.leadingCoeff) <| by rw [← C_mul, this, C_1])) [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p : R[X] h : Monic p hp : Irreducible p a b : K[X] hₐ : ¬IsUnit a a' : R[X] ha : Polynomial.map (algebraMap R K) a' * ↑C (Polynomial.leadingCoeff a) = a b' : R[X] H : Polynomial.map (algebraMap R K) p = Polynomial.map (algebraMap R K) (a' * b') hb : Polynomial.map (algebraMap R K) b' * ↑C (Polynomial.leadingCoeff b) = b this : Polynomial.leadingCoeff a * Polynomial.leadingCoeff b = 1 ⊢ ↑C (Polynomial.leadingCoeff a) * ↑C (Polynomial.leadingCoeff b) = 1 [PROOFSTEP] rw [← C_mul, this, C_1] [GOAL] case intro.intro.refine'_1 R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p : R[X] h : Monic p hp : Irreducible p a b : K[X] hₐ : ¬IsUnit a a' : R[X] ha : Polynomial.map (algebraMap R K) a' * ↑C (Polynomial.leadingCoeff a) = a b' : R[X] H : Polynomial.map (algebraMap R K) p = Polynomial.map (algebraMap R K) (a' * b') hb : Polynomial.map (algebraMap R K) b' * ↑C (Polynomial.leadingCoeff b) = b this : Polynomial.leadingCoeff a * Polynomial.leadingCoeff b = 1 ⊢ p = a' * b' [PROOFSTEP] exact Polynomial.map_injective _ (IsFractionRing.injective R K) H [GOAL] case intro.intro.refine'_2 R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p : R[X] h : Monic p hp : Irreducible p a b : K[X] hₐ : ¬IsUnit a a' : R[X] ha : Polynomial.map (algebraMap R K) a' * ↑C (Polynomial.leadingCoeff a) = a b' : R[X] H : Polynomial.map (algebraMap R K) p = Polynomial.map (algebraMap R K) (a' * b') hb : Polynomial.map (algebraMap R K) b' * ↑C (Polynomial.leadingCoeff b) = b this : Polynomial.leadingCoeff a * Polynomial.leadingCoeff b = 1 ⊢ ¬IsUnit a' [PROOFSTEP] by_contra h_contra [GOAL] case intro.intro.refine'_2 R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p : R[X] h : Monic p hp : Irreducible p a b : K[X] hₐ : ¬IsUnit a a' : R[X] ha : Polynomial.map (algebraMap R K) a' * ↑C (Polynomial.leadingCoeff a) = a b' : R[X] H : Polynomial.map (algebraMap R K) p = Polynomial.map (algebraMap R K) (a' * b') hb : Polynomial.map (algebraMap R K) b' * ↑C (Polynomial.leadingCoeff b) = b this : Polynomial.leadingCoeff a * Polynomial.leadingCoeff b = 1 h_contra : IsUnit a' ⊢ False [PROOFSTEP] refine' hₐ _ [GOAL] case intro.intro.refine'_2 R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p : R[X] h : Monic p hp : Irreducible p a b : K[X] hₐ : ¬IsUnit a a' : R[X] ha : Polynomial.map (algebraMap R K) a' * ↑C (Polynomial.leadingCoeff a) = a b' : R[X] H : Polynomial.map (algebraMap R K) p = Polynomial.map (algebraMap R K) (a' * b') hb : Polynomial.map (algebraMap R K) b' * ↑C (Polynomial.leadingCoeff b) = b this : Polynomial.leadingCoeff a * Polynomial.leadingCoeff b = 1 h_contra : IsUnit a' ⊢ IsUnit a [PROOFSTEP] rw [← ha, ← Polynomial.coe_mapRingHom] [GOAL] case intro.intro.refine'_2 R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p : R[X] h : Monic p hp : Irreducible p a b : K[X] hₐ : ¬IsUnit a a' : R[X] ha : Polynomial.map (algebraMap R K) a' * ↑C (Polynomial.leadingCoeff a) = a b' : R[X] H : Polynomial.map (algebraMap R K) p = Polynomial.map (algebraMap R K) (a' * b') hb : Polynomial.map (algebraMap R K) b' * ↑C (Polynomial.leadingCoeff b) = b this : Polynomial.leadingCoeff a * Polynomial.leadingCoeff b = 1 h_contra : IsUnit a' ⊢ IsUnit (↑(mapRingHom (algebraMap R K)) a' * ↑C (Polynomial.leadingCoeff a)) [PROOFSTEP] exact IsUnit.mul (IsUnit.map _ h_contra) (isUnit_iff_exists_inv.mpr (Exists.intro (C b.leadingCoeff) <| by rw [← C_mul, this, C_1])) [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p : R[X] h : Monic p hp : Irreducible p a b : K[X] hₐ : ¬IsUnit a a' : R[X] ha : Polynomial.map (algebraMap R K) a' * ↑C (Polynomial.leadingCoeff a) = a b' : R[X] H : Polynomial.map (algebraMap R K) p = Polynomial.map (algebraMap R K) (a' * b') hb : Polynomial.map (algebraMap R K) b' * ↑C (Polynomial.leadingCoeff b) = b this : Polynomial.leadingCoeff a * Polynomial.leadingCoeff b = 1 h_contra : IsUnit a' ⊢ ↑C (Polynomial.leadingCoeff a) * ↑C (Polynomial.leadingCoeff b) = 1 [PROOFSTEP] rw [← C_mul, this, C_1] [GOAL] R : Type u_1 inst✝⁴ : CommRing R K : Type u_2 inst✝³ : Field K inst✝² : Algebra R K inst✝¹ : IsFractionRing R K inst✝ : IsDomain R ⊢ IsIntegrallyClosed R ↔ ∀ (p : R[X]), Monic p → (Irreducible p ↔ Irreducible (map (algebraMap R K) p)) [PROOFSTEP] constructor [GOAL] case mp R : Type u_1 inst✝⁴ : CommRing R K : Type u_2 inst✝³ : Field K inst✝² : Algebra R K inst✝¹ : IsFractionRing R K inst✝ : IsDomain R ⊢ IsIntegrallyClosed R → ∀ (p : R[X]), Monic p → (Irreducible p ↔ Irreducible (map (algebraMap R K) p)) [PROOFSTEP] intro hR p hp [GOAL] case mp R : Type u_1 inst✝⁴ : CommRing R K : Type u_2 inst✝³ : Field K inst✝² : Algebra R K inst✝¹ : IsFractionRing R K inst✝ : IsDomain R hR : IsIntegrallyClosed R p : R[X] hp : Monic p ⊢ Irreducible p ↔ Irreducible (map (algebraMap R K) p) [PROOFSTEP] exact Monic.irreducible_iff_irreducible_map_fraction_map hp [GOAL] case mpr R : Type u_1 inst✝⁴ : CommRing R K : Type u_2 inst✝³ : Field K inst✝² : Algebra R K inst✝¹ : IsFractionRing R K inst✝ : IsDomain R ⊢ (∀ (p : R[X]), Monic p → (Irreducible p ↔ Irreducible (map (algebraMap R K) p))) → IsIntegrallyClosed R [PROOFSTEP] intro H [GOAL] case mpr R : Type u_1 inst✝⁴ : CommRing R K : Type u_2 inst✝³ : Field K inst✝² : Algebra R K inst✝¹ : IsFractionRing R K inst✝ : IsDomain R H : ∀ (p : R[X]), Monic p → (Irreducible p ↔ Irreducible (map (algebraMap R K) p)) ⊢ IsIntegrallyClosed R [PROOFSTEP] refine' (isIntegrallyClosed_iff K).mpr fun {x} hx => RingHom.mem_range.mp <| minpoly.mem_range_of_degree_eq_one R x _ [GOAL] case mpr R : Type u_1 inst✝⁴ : CommRing R K : Type u_2 inst✝³ : Field K inst✝² : Algebra R K inst✝¹ : IsFractionRing R K inst✝ : IsDomain R H : ∀ (p : R[X]), Monic p → (Irreducible p ↔ Irreducible (map (algebraMap R K) p)) x : K hx : IsIntegral R x ⊢ degree (minpoly R x) = 1 [PROOFSTEP] rw [← Monic.degree_map (minpoly.monic hx) (algebraMap R K)] [GOAL] case mpr R : Type u_1 inst✝⁴ : CommRing R K : Type u_2 inst✝³ : Field K inst✝² : Algebra R K inst✝¹ : IsFractionRing R K inst✝ : IsDomain R H : ∀ (p : R[X]), Monic p → (Irreducible p ↔ Irreducible (map (algebraMap R K) p)) x : K hx : IsIntegral R x ⊢ degree (map (algebraMap R K) (minpoly R x)) = 1 [PROOFSTEP] apply degree_eq_one_of_irreducible_of_root ((H _ <| minpoly.monic hx).mp (minpoly.irreducible hx)) [GOAL] case mpr R : Type u_1 inst✝⁴ : CommRing R K : Type u_2 inst✝³ : Field K inst✝² : Algebra R K inst✝¹ : IsFractionRing R K inst✝ : IsDomain R H : ∀ (p : R[X]), Monic p → (Irreducible p ↔ Irreducible (map (algebraMap R K) p)) x : K hx : IsIntegral R x ⊢ IsRoot (map (algebraMap R K) (minpoly R x)) ?m.306193 R : Type u_1 inst✝⁴ : CommRing R K : Type u_2 inst✝³ : Field K inst✝² : Algebra R K inst✝¹ : IsFractionRing R K inst✝ : IsDomain R H : ∀ (p : R[X]), Monic p → (Irreducible p ↔ Irreducible (map (algebraMap R K) p)) x : K hx : IsIntegral R x ⊢ K [PROOFSTEP] rw [IsRoot, eval_map, ← aeval_def, minpoly.aeval R x] [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p q : R[X] hp : Monic p hq : Monic q h : Polynomial.map (algebraMap R K) q ∣ Polynomial.map (algebraMap R K) p ⊢ q ∣ p [PROOFSTEP] obtain ⟨r, hr⟩ := h [GOAL] case intro R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p q : R[X] hp : Monic p hq : Monic q r : K[X] hr : Polynomial.map (algebraMap R K) p = Polynomial.map (algebraMap R K) q * r ⊢ q ∣ p [PROOFSTEP] obtain ⟨d', hr'⟩ := IsIntegrallyClosed.eq_map_mul_C_of_dvd K hp (dvd_of_mul_left_eq _ hr.symm) [GOAL] case intro.intro R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p q : R[X] hp : Monic p hq : Monic q r : K[X] hr : Polynomial.map (algebraMap R K) p = Polynomial.map (algebraMap R K) q * r d' : R[X] hr' : Polynomial.map (algebraMap R K) d' * ↑C (Polynomial.leadingCoeff r) = r ⊢ q ∣ p [PROOFSTEP] rw [Monic.leadingCoeff, C_1, mul_one] at hr' [GOAL] case intro.intro R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p q : R[X] hp : Monic p hq : Monic q r : K[X] hr : Polynomial.map (algebraMap R K) p = Polynomial.map (algebraMap R K) q * r d' : R[X] hr' : Polynomial.map (algebraMap R K) d' = r ⊢ q ∣ p case intro.intro R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p q : R[X] hp : Monic p hq : Monic q r : K[X] hr : Polynomial.map (algebraMap R K) p = Polynomial.map (algebraMap R K) q * r d' : R[X] hr' : Polynomial.map (algebraMap R K) d' * ↑C (Polynomial.leadingCoeff r) = r ⊢ Monic r [PROOFSTEP] rw [← hr', ← Polynomial.map_mul] at hr [GOAL] case intro.intro R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p q : R[X] hp : Monic p hq : Monic q r : K[X] d' : R[X] hr : Polynomial.map (algebraMap R K) p = Polynomial.map (algebraMap R K) (q * d') hr' : Polynomial.map (algebraMap R K) d' = r ⊢ q ∣ p case intro.intro R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p q : R[X] hp : Monic p hq : Monic q r : K[X] hr : Polynomial.map (algebraMap R K) p = Polynomial.map (algebraMap R K) q * r d' : R[X] hr' : Polynomial.map (algebraMap R K) d' * ↑C (Polynomial.leadingCoeff r) = r ⊢ Monic r [PROOFSTEP] exact dvd_of_mul_right_eq _ (Polynomial.map_injective _ (IsFractionRing.injective R K) hr.symm) [GOAL] case intro.intro R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p q : R[X] hp : Monic p hq : Monic q r : K[X] hr : Polynomial.map (algebraMap R K) p = Polynomial.map (algebraMap R K) q * r d' : R[X] hr' : Polynomial.map (algebraMap R K) d' * ↑C (Polynomial.leadingCoeff r) = r ⊢ Monic r [PROOFSTEP] exact Monic.of_mul_monic_left (hq.map (algebraMap R K)) (by simpa [← hr] using hp.map _) [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : IsIntegrallyClosed R p q : R[X] hp : Monic p hq : Monic q r : K[X] hr : Polynomial.map (algebraMap R K) p = Polynomial.map (algebraMap R K) q * r d' : R[X] hr' : Polynomial.map (algebraMap R K) d' * ↑C (Polynomial.leadingCoeff r) = r ⊢ Monic (Polynomial.map (algebraMap R K) q * r) [PROOFSTEP] simpa [← hr] using hp.map _ [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : K[X] h0 : p ≠ 0 h : IsUnit (primPart (integerNormalization R⁰ p)) ⊢ IsUnit p [PROOFSTEP] rcases isUnit_iff.1 h with ⟨_, ⟨u, rfl⟩, hu⟩ [GOAL] case intro.intro.intro R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : K[X] h0 : p ≠ 0 h : IsUnit (primPart (integerNormalization R⁰ p)) u : Rˣ hu : ↑C ↑u = primPart (integerNormalization R⁰ p) ⊢ IsUnit p [PROOFSTEP] obtain ⟨⟨c, c0⟩, hc⟩ := integerNormalization_map_to_map R⁰ p [GOAL] case intro.intro.intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : K[X] h0 : p ≠ 0 h : IsUnit (primPart (integerNormalization R⁰ p)) u : Rˣ hu : ↑C ↑u = primPart (integerNormalization R⁰ p) c : R c0 : c ∈ R⁰ hc : map (algebraMap R K) (integerNormalization R⁰ p) = ↑{ val := c, property := c0 } • p ⊢ IsUnit p [PROOFSTEP] rw [Subtype.coe_mk, Algebra.smul_def, algebraMap_apply] at hc [GOAL] case intro.intro.intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : K[X] h0 : p ≠ 0 h : IsUnit (primPart (integerNormalization R⁰ p)) u : Rˣ hu : ↑C ↑u = primPart (integerNormalization R⁰ p) c : R c0 : c ∈ R⁰ hc : map (algebraMap R K) (integerNormalization R⁰ p) = ↑C (↑(algebraMap R K) c) * p ⊢ IsUnit p [PROOFSTEP] apply isUnit_of_mul_isUnit_right [GOAL] case intro.intro.intro.intro.mk.hu R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : K[X] h0 : p ≠ 0 h : IsUnit (primPart (integerNormalization R⁰ p)) u : Rˣ hu : ↑C ↑u = primPart (integerNormalization R⁰ p) c : R c0 : c ∈ R⁰ hc : map (algebraMap R K) (integerNormalization R⁰ p) = ↑C (↑(algebraMap R K) c) * p ⊢ IsUnit (?intro.intro.intro.intro.mk.x * p) case intro.intro.intro.intro.mk.x R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : K[X] h0 : p ≠ 0 h : IsUnit (primPart (integerNormalization R⁰ p)) u : Rˣ hu : ↑C ↑u = primPart (integerNormalization R⁰ p) c : R c0 : c ∈ R⁰ hc : map (algebraMap R K) (integerNormalization R⁰ p) = ↑C (↑(algebraMap R K) c) * p ⊢ K[X] [PROOFSTEP] rw [← hc, (integerNormalization R⁰ p).eq_C_content_mul_primPart, ← hu, ← RingHom.map_mul, isUnit_iff] [GOAL] case intro.intro.intro.intro.mk.hu R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : K[X] h0 : p ≠ 0 h : IsUnit (primPart (integerNormalization R⁰ p)) u : Rˣ hu : ↑C ↑u = primPart (integerNormalization R⁰ p) c : R c0 : c ∈ R⁰ hc : map (algebraMap R K) (integerNormalization R⁰ p) = ↑C (↑(algebraMap R K) c) * p ⊢ ∃ r, IsUnit r ∧ ↑C r = map (algebraMap R K) (↑C (content (integerNormalization R⁰ p) * ↑u)) [PROOFSTEP] refine' ⟨algebraMap R K ((integerNormalization R⁰ p).content * ↑u), isUnit_iff_ne_zero.2 fun con => _, by simp⟩ [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : K[X] h0 : p ≠ 0 h : IsUnit (primPart (integerNormalization R⁰ p)) u : Rˣ hu : ↑C ↑u = primPart (integerNormalization R⁰ p) c : R c0 : c ∈ R⁰ hc : map (algebraMap R K) (integerNormalization R⁰ p) = ↑C (↑(algebraMap R K) c) * p ⊢ ↑C (↑(algebraMap R K) (content (integerNormalization R⁰ p) * ↑u)) = map (algebraMap R K) (↑C (content (integerNormalization R⁰ p) * ↑u)) [PROOFSTEP] simp [GOAL] case intro.intro.intro.intro.mk.hu R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : K[X] h0 : p ≠ 0 h : IsUnit (primPart (integerNormalization R⁰ p)) u : Rˣ hu : ↑C ↑u = primPart (integerNormalization R⁰ p) c : R c0 : c ∈ R⁰ hc : map (algebraMap R K) (integerNormalization R⁰ p) = ↑C (↑(algebraMap R K) c) * p con : ↑(algebraMap R K) (content (integerNormalization R⁰ p) * ↑u) = 0 ⊢ False [PROOFSTEP] replace con := (injective_iff_map_eq_zero (algebraMap R K)).1 (IsFractionRing.injective _ _) _ con [GOAL] case intro.intro.intro.intro.mk.hu R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : K[X] h0 : p ≠ 0 h : IsUnit (primPart (integerNormalization R⁰ p)) u : Rˣ hu : ↑C ↑u = primPart (integerNormalization R⁰ p) c : R c0 : c ∈ R⁰ hc : map (algebraMap R K) (integerNormalization R⁰ p) = ↑C (↑(algebraMap R K) c) * p con : content (integerNormalization R⁰ p) * ↑u = 0 ⊢ False [PROOFSTEP] rw [mul_eq_zero, content_eq_zero_iff, IsFractionRing.integerNormalization_eq_zero_iff] at con [GOAL] case intro.intro.intro.intro.mk.hu R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : K[X] h0 : p ≠ 0 h : IsUnit (primPart (integerNormalization R⁰ p)) u : Rˣ hu : ↑C ↑u = primPart (integerNormalization R⁰ p) c : R c0 : c ∈ R⁰ hc : map (algebraMap R K) (integerNormalization R⁰ p) = ↑C (↑(algebraMap R K) c) * p con : p = 0 ∨ ↑u = 0 ⊢ False [PROOFSTEP] rcases con with (con | con) [GOAL] case intro.intro.intro.intro.mk.hu.inl R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : K[X] h0 : p ≠ 0 h : IsUnit (primPart (integerNormalization R⁰ p)) u : Rˣ hu : ↑C ↑u = primPart (integerNormalization R⁰ p) c : R c0 : c ∈ R⁰ hc : map (algebraMap R K) (integerNormalization R⁰ p) = ↑C (↑(algebraMap R K) c) * p con : p = 0 ⊢ False [PROOFSTEP] apply h0 con [GOAL] case intro.intro.intro.intro.mk.hu.inr R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : K[X] h0 : p ≠ 0 h : IsUnit (primPart (integerNormalization R⁰ p)) u : Rˣ hu : ↑C ↑u = primPart (integerNormalization R⁰ p) c : R c0 : c ∈ R⁰ hc : map (algebraMap R K) (integerNormalization R⁰ p) = ↑C (↑(algebraMap R K) c) * p con : ↑u = 0 ⊢ False [PROOFSTEP] apply Units.ne_zero _ con [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p ⊢ Irreducible p ↔ Irreducible (map (algebraMap R K) p) [PROOFSTEP] refine' ⟨fun hi => ⟨fun h => hi.not_unit (hp.isUnit_iff_isUnit_map.2 h), fun a b hab => _⟩, hp.irreducible_of_irreducible_map_of_injective (IsFractionRing.injective R K)⟩ [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b ⊢ IsUnit a ∨ IsUnit b [PROOFSTEP] obtain ⟨⟨c, c0⟩, hc⟩ := integerNormalization_map_to_map R⁰ a [GOAL] case intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ∈ R⁰ hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑{ val := c, property := c0 } • a ⊢ IsUnit a ∨ IsUnit b [PROOFSTEP] obtain ⟨⟨d, d0⟩, hd⟩ := integerNormalization_map_to_map R⁰ b [GOAL] case intro.mk.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ∈ R⁰ hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑{ val := c, property := c0 } • a d : R d0 : d ∈ R⁰ hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑{ val := d, property := d0 } • b ⊢ IsUnit a ∨ IsUnit b [PROOFSTEP] rw [Algebra.smul_def, algebraMap_apply, Subtype.coe_mk] at hc hd [GOAL] case intro.mk.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ∈ R⁰ hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ∈ R⁰ hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b ⊢ IsUnit a ∨ IsUnit b [PROOFSTEP] rw [mem_nonZeroDivisors_iff_ne_zero] at c0 d0 [GOAL] case intro.mk.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b ⊢ IsUnit a ∨ IsUnit b [PROOFSTEP] have hcd0 : c * d ≠ 0 := mul_ne_zero c0 d0 [GOAL] case intro.mk.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b hcd0 : c * d ≠ 0 ⊢ IsUnit a ∨ IsUnit b [PROOFSTEP] rw [Ne.def, ← C_eq_zero] at hcd0 [GOAL] case intro.mk.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b hcd0 : ¬↑C (c * d) = 0 ⊢ IsUnit a ∨ IsUnit b [PROOFSTEP] have h1 : C c * C d * p = integerNormalization R⁰ a * integerNormalization R⁰ b := by apply map_injective (algebraMap R K) (IsFractionRing.injective _ _) _ rw [Polynomial.map_mul, Polynomial.map_mul, Polynomial.map_mul, hc, hd, map_C, map_C, hab] ring [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b hcd0 : ¬↑C (c * d) = 0 ⊢ ↑C c * ↑C d * p = integerNormalization R⁰ a * integerNormalization R⁰ b [PROOFSTEP] apply map_injective (algebraMap R K) (IsFractionRing.injective _ _) _ [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b hcd0 : ¬↑C (c * d) = 0 ⊢ map (algebraMap R K) (↑C c * ↑C d * p) = map (algebraMap R K) (integerNormalization R⁰ a * integerNormalization R⁰ b) [PROOFSTEP] rw [Polynomial.map_mul, Polynomial.map_mul, Polynomial.map_mul, hc, hd, map_C, map_C, hab] [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b hcd0 : ¬↑C (c * d) = 0 ⊢ ↑C (↑(algebraMap R K) c) * ↑C (↑(algebraMap R K) d) * (a * b) = ↑C (↑(algebraMap R K) c) * a * (↑C (↑(algebraMap R K) d) * b) [PROOFSTEP] ring [GOAL] case intro.mk.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b hcd0 : ¬↑C (c * d) = 0 h1 : ↑C c * ↑C d * p = integerNormalization R⁰ a * integerNormalization R⁰ b ⊢ IsUnit a ∨ IsUnit b [PROOFSTEP] obtain ⟨u, hu⟩ : Associated (c * d) (content (integerNormalization R⁰ a) * content (integerNormalization R⁰ b)) := by rw [← dvd_dvd_iff_associated, ← normalize_eq_normalize_iff, normalize.map_mul, normalize.map_mul, normalize_content, normalize_content, ← mul_one (normalize c * normalize d), ← hp.content_eq_one, ← content_C, ← content_C, ← content_mul, ← content_mul, ← content_mul, h1] [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b hcd0 : ¬↑C (c * d) = 0 h1 : ↑C c * ↑C d * p = integerNormalization R⁰ a * integerNormalization R⁰ b ⊢ Associated (c * d) (content (integerNormalization R⁰ a) * content (integerNormalization R⁰ b)) [PROOFSTEP] rw [← dvd_dvd_iff_associated, ← normalize_eq_normalize_iff, normalize.map_mul, normalize.map_mul, normalize_content, normalize_content, ← mul_one (normalize c * normalize d), ← hp.content_eq_one, ← content_C, ← content_C, ← content_mul, ← content_mul, ← content_mul, h1] [GOAL] case intro.mk.intro.mk.intro R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b hcd0 : ¬↑C (c * d) = 0 h1 : ↑C c * ↑C d * p = integerNormalization R⁰ a * integerNormalization R⁰ b u : Rˣ hu : c * d * ↑u = content (integerNormalization R⁰ a) * content (integerNormalization R⁰ b) ⊢ IsUnit a ∨ IsUnit b [PROOFSTEP] rw [← RingHom.map_mul, eq_comm, (integerNormalization R⁰ a).eq_C_content_mul_primPart, (integerNormalization R⁰ b).eq_C_content_mul_primPart, mul_assoc, mul_comm _ (C _ * _), ← mul_assoc, ← mul_assoc, ← RingHom.map_mul, ← hu, RingHom.map_mul, mul_assoc, mul_assoc, ← mul_assoc (C (u : R))] at h1 [GOAL] case intro.mk.intro.mk.intro R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b hcd0 : ¬↑C (c * d) = 0 u : Rˣ h1 : ↑C (c * d) * (↑C ↑u * primPart (integerNormalization R⁰ b) * primPart (integerNormalization R⁰ a)) = ↑C (c * d) * p hu : c * d * ↑u = content (integerNormalization R⁰ a) * content (integerNormalization R⁰ b) ⊢ IsUnit a ∨ IsUnit b [PROOFSTEP] have h0 : a ≠ 0 ∧ b ≠ 0 := by classical rw [Ne.def, Ne.def, ← not_or, ← mul_eq_zero, ← hab] intro con apply hp.ne_zero (map_injective (algebraMap R K) (IsFractionRing.injective _ _) _) simp [con] [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b hcd0 : ¬↑C (c * d) = 0 u : Rˣ h1 : ↑C (c * d) * (↑C ↑u * primPart (integerNormalization R⁰ b) * primPart (integerNormalization R⁰ a)) = ↑C (c * d) * p hu : c * d * ↑u = content (integerNormalization R⁰ a) * content (integerNormalization R⁰ b) ⊢ a ≠ 0 ∧ b ≠ 0 [PROOFSTEP] classical rw [Ne.def, Ne.def, ← not_or, ← mul_eq_zero, ← hab] intro con apply hp.ne_zero (map_injective (algebraMap R K) (IsFractionRing.injective _ _) _) simp [con] [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b hcd0 : ¬↑C (c * d) = 0 u : Rˣ h1 : ↑C (c * d) * (↑C ↑u * primPart (integerNormalization R⁰ b) * primPart (integerNormalization R⁰ a)) = ↑C (c * d) * p hu : c * d * ↑u = content (integerNormalization R⁰ a) * content (integerNormalization R⁰ b) ⊢ a ≠ 0 ∧ b ≠ 0 [PROOFSTEP] rw [Ne.def, Ne.def, ← not_or, ← mul_eq_zero, ← hab] [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b hcd0 : ¬↑C (c * d) = 0 u : Rˣ h1 : ↑C (c * d) * (↑C ↑u * primPart (integerNormalization R⁰ b) * primPart (integerNormalization R⁰ a)) = ↑C (c * d) * p hu : c * d * ↑u = content (integerNormalization R⁰ a) * content (integerNormalization R⁰ b) ⊢ ¬map (algebraMap R K) p = 0 [PROOFSTEP] intro con [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b hcd0 : ¬↑C (c * d) = 0 u : Rˣ h1 : ↑C (c * d) * (↑C ↑u * primPart (integerNormalization R⁰ b) * primPart (integerNormalization R⁰ a)) = ↑C (c * d) * p hu : c * d * ↑u = content (integerNormalization R⁰ a) * content (integerNormalization R⁰ b) con : map (algebraMap R K) p = 0 ⊢ False [PROOFSTEP] apply hp.ne_zero (map_injective (algebraMap R K) (IsFractionRing.injective _ _) _) [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b hcd0 : ¬↑C (c * d) = 0 u : Rˣ h1 : ↑C (c * d) * (↑C ↑u * primPart (integerNormalization R⁰ b) * primPart (integerNormalization R⁰ a)) = ↑C (c * d) * p hu : c * d * ↑u = content (integerNormalization R⁰ a) * content (integerNormalization R⁰ b) con : map (algebraMap R K) p = 0 ⊢ map (algebraMap R K) p = map (algebraMap R K) 0 [PROOFSTEP] simp [con] [GOAL] case intro.mk.intro.mk.intro R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b hcd0 : ¬↑C (c * d) = 0 u : Rˣ h1 : ↑C (c * d) * (↑C ↑u * primPart (integerNormalization R⁰ b) * primPart (integerNormalization R⁰ a)) = ↑C (c * d) * p hu : c * d * ↑u = content (integerNormalization R⁰ a) * content (integerNormalization R⁰ b) h0 : a ≠ 0 ∧ b ≠ 0 ⊢ IsUnit a ∨ IsUnit b [PROOFSTEP] rcases hi.isUnit_or_isUnit (mul_left_cancel₀ hcd0 h1).symm with (h | h) [GOAL] case intro.mk.intro.mk.intro.inl R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b hcd0 : ¬↑C (c * d) = 0 u : Rˣ h1 : ↑C (c * d) * (↑C ↑u * primPart (integerNormalization R⁰ b) * primPart (integerNormalization R⁰ a)) = ↑C (c * d) * p hu : c * d * ↑u = content (integerNormalization R⁰ a) * content (integerNormalization R⁰ b) h0 : a ≠ 0 ∧ b ≠ 0 h : IsUnit (↑C ↑u * primPart (integerNormalization R⁰ b)) ⊢ IsUnit a ∨ IsUnit b [PROOFSTEP] right [GOAL] case intro.mk.intro.mk.intro.inl.h R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b hcd0 : ¬↑C (c * d) = 0 u : Rˣ h1 : ↑C (c * d) * (↑C ↑u * primPart (integerNormalization R⁰ b) * primPart (integerNormalization R⁰ a)) = ↑C (c * d) * p hu : c * d * ↑u = content (integerNormalization R⁰ a) * content (integerNormalization R⁰ b) h0 : a ≠ 0 ∧ b ≠ 0 h : IsUnit (↑C ↑u * primPart (integerNormalization R⁰ b)) ⊢ IsUnit b [PROOFSTEP] apply isUnit_or_eq_zero_of_isUnit_integerNormalization_primPart h0.2 (isUnit_of_mul_isUnit_right h) [GOAL] case intro.mk.intro.mk.intro.inr R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b hcd0 : ¬↑C (c * d) = 0 u : Rˣ h1 : ↑C (c * d) * (↑C ↑u * primPart (integerNormalization R⁰ b) * primPart (integerNormalization R⁰ a)) = ↑C (c * d) * p hu : c * d * ↑u = content (integerNormalization R⁰ a) * content (integerNormalization R⁰ b) h0 : a ≠ 0 ∧ b ≠ 0 h : IsUnit (primPart (integerNormalization R⁰ a)) ⊢ IsUnit a ∨ IsUnit b [PROOFSTEP] left [GOAL] case intro.mk.intro.mk.intro.inr.h R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p : R[X] hp : IsPrimitive p hi : Irreducible p a b : K[X] hab : map (algebraMap R K) p = a * b c : R c0 : c ≠ 0 hc : map (algebraMap R K) (integerNormalization R⁰ a) = ↑C (↑(algebraMap R K) c) * a d : R d0 : d ≠ 0 hd : map (algebraMap R K) (integerNormalization R⁰ b) = ↑C (↑(algebraMap R K) d) * b hcd0 : ¬↑C (c * d) = 0 u : Rˣ h1 : ↑C (c * d) * (↑C ↑u * primPart (integerNormalization R⁰ b) * primPart (integerNormalization R⁰ a)) = ↑C (c * d) * p hu : c * d * ↑u = content (integerNormalization R⁰ a) * content (integerNormalization R⁰ b) h0 : a ≠ 0 ∧ b ≠ 0 h : IsUnit (primPart (integerNormalization R⁰ a)) ⊢ IsUnit a [PROOFSTEP] apply isUnit_or_eq_zero_of_isUnit_integerNormalization_primPart h0.1 h [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q h_dvd : map (algebraMap R K) p ∣ map (algebraMap R K) q ⊢ p ∣ q [PROOFSTEP] rcases h_dvd with ⟨r, hr⟩ [GOAL] case intro R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r ⊢ p ∣ q [PROOFSTEP] obtain ⟨⟨s, s0⟩, hs⟩ := integerNormalization_map_to_map R⁰ r [GOAL] case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑{ val := s, property := s0 } • r ⊢ p ∣ q [PROOFSTEP] rw [Subtype.coe_mk, Algebra.smul_def, algebraMap_apply] at hs [GOAL] case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r ⊢ p ∣ q [PROOFSTEP] have h : p ∣ q * C s := by use integerNormalization R⁰ r apply map_injective (algebraMap R K) (IsFractionRing.injective _ _) rw [Polynomial.map_mul, Polynomial.map_mul, hs, hr, mul_assoc, mul_comm r] simp [GOAL] R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r ⊢ p ∣ q * ↑C s [PROOFSTEP] use integerNormalization R⁰ r [GOAL] case h R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r ⊢ q * ↑C s = p * integerNormalization R⁰ r [PROOFSTEP] apply map_injective (algebraMap R K) (IsFractionRing.injective _ _) [GOAL] case h.a R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r ⊢ map (algebraMap R K) (q * ↑C s) = map (algebraMap R K) (p * integerNormalization R⁰ r) [PROOFSTEP] rw [Polynomial.map_mul, Polynomial.map_mul, hs, hr, mul_assoc, mul_comm r] [GOAL] case h.a R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r ⊢ map (algebraMap R K) p * (map (algebraMap R K) (↑C s) * r) = map (algebraMap R K) p * (↑C (↑(algebraMap R K) s) * r) [PROOFSTEP] simp [GOAL] case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h : p ∣ q * ↑C s ⊢ p ∣ q [PROOFSTEP] rw [← hp.dvd_primPart_iff_dvd, primPart_mul, hq.primPart_eq, Associated.dvd_iff_dvd_right] at h [GOAL] case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h✝ : p ∣ q * primPart (↑C s) h : p ∣ ?m.732534 ⊢ p ∣ q [PROOFSTEP] exact h [GOAL] case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h : p ∣ q * primPart (↑C s) ⊢ Associated (q * primPart (↑C s)) q [PROOFSTEP] symm [GOAL] case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h : p ∣ q * primPart (↑C s) ⊢ Associated q (q * primPart (↑C s)) [PROOFSTEP] rcases isUnit_primPart_C s with ⟨u, hu⟩ [GOAL] case intro.intro.mk.intro R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h : p ∣ q * primPart (↑C s) u : R[X]ˣ hu : ↑u = primPart (↑C s) ⊢ Associated q (q * primPart (↑C s)) [PROOFSTEP] use u [GOAL] case h R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h : p ∣ q * primPart (↑C s) u : R[X]ˣ hu : ↑u = primPart (↑C s) ⊢ q * ↑u = q * primPart (↑C s) [PROOFSTEP] rw [hu] [GOAL] case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h : p ∣ primPart (q * ↑C s) ⊢ q * ↑C s ≠ 0 case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h : p ∣ q * ↑C s ⊢ q * ↑C s ≠ 0 [PROOFSTEP] iterate 2 apply mul_ne_zero hq.ne_zero rw [Ne.def, C_eq_zero] contrapose! s0 simp [s0, mem_nonZeroDivisors_iff_ne_zero] [GOAL] case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h : p ∣ primPart (q * ↑C s) ⊢ q * ↑C s ≠ 0 case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h : p ∣ q * ↑C s ⊢ q * ↑C s ≠ 0 [PROOFSTEP] apply mul_ne_zero hq.ne_zero [GOAL] case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h : p ∣ primPart (q * ↑C s) ⊢ ↑C s ≠ 0 case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h : p ∣ q * ↑C s ⊢ q * ↑C s ≠ 0 [PROOFSTEP] rw [Ne.def, C_eq_zero] [GOAL] case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h : p ∣ primPart (q * ↑C s) ⊢ ¬s = 0 case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h : p ∣ q * ↑C s ⊢ q * ↑C s ≠ 0 [PROOFSTEP] contrapose! s0 [GOAL] case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h : p ∣ primPart (q * ↑C s) s0 : s = 0 ⊢ ¬s ∈ R⁰ case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h : p ∣ q * ↑C s ⊢ q * ↑C s ≠ 0 [PROOFSTEP] simp [s0, mem_nonZeroDivisors_iff_ne_zero] [GOAL] case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h : p ∣ q * ↑C s ⊢ q * ↑C s ≠ 0 [PROOFSTEP] apply mul_ne_zero hq.ne_zero [GOAL] case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h : p ∣ q * ↑C s ⊢ ↑C s ≠ 0 [PROOFSTEP] rw [Ne.def, C_eq_zero] [GOAL] case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R s0 : s ∈ R⁰ hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h : p ∣ q * ↑C s ⊢ ¬s = 0 [PROOFSTEP] contrapose! s0 [GOAL] case intro.intro.mk R : Type u_1 inst✝⁵ : CommRing R K : Type u_2 inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : IsFractionRing R K inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R p q : R[X] hp : IsPrimitive p hq : IsPrimitive q r : K[X] hr : map (algebraMap R K) q = map (algebraMap R K) p * r s : R hs : map (algebraMap R K) (integerNormalization R⁰ r) = ↑C (↑(algebraMap R K) s) * r h : p ∣ q * ↑C s s0 : s = 0 ⊢ ¬s ∈ R⁰ [PROOFSTEP] simp [s0, mem_nonZeroDivisors_iff_ne_zero]
Set Warnings "-notation-overridden". Generalizable All Variables. Set Primitive Projections. Set Universe Polymorphism. Set Transparent Obligations. (* Copyright (c) 2014, John Wiegley * * This work is licensed under a * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 * Unported License. * The license text is available at: * http://creativecommons.org/licenses/by-nc-nd/3.0/ *) (** %\chapter{Category}% *) Require Import Hask.Prelude. Require Import Hask.Crush. Require Import Coq.Unicode.Utf8. Require Import FunctionalExtensionality. Axiom propositional_extensionality : forall P : Prop, P -> P = True. Axiom proof_irrelevance : forall (P : Prop) (u v : P), u = v. Generalizable All Variables. Set Primitive Projections. Set Universe Polymorphism. (* Unset Transparent Obligations. *) (** * Category *) (** Category theory is a language for reasoning about abstractions. Awodey%\cite{Awodey}% calls it, "the algebra of abstract functions." Its power lies in relating ideas from differing disciplines, and unifying them under a common framework. At its heart we have the [Category]. Every category is characterized by its objects, and the morphisms (also called arrows) between those objects. *) (* begin hide *) Reserved Notation "a ~> b" (at level 70, right associativity). Reserved Notation "f ∘ g" (at level 40, left associativity). Reserved Notation "C ^op" (at level 90). (* end hide *) Class Category := { ob : Type; (* These require Coq 8.5 and universe polymorphism. *) (* uhom := Type : Type; *) (* hom : ob → ob → uhom where "a ~> b" := (hom a b); *) hom : ob → ob → Type where "a ~> b" := (hom a b); (** It is important to note that objects and arrows have no inherent meaning: The notion of a category requires only that they exist, and that they be well-behaved. Since all we can know about objects is that they exist, they serve only to differentiate morphisms. Conversely, morphisms are how we characterize objects. *) (** * Morphisms In this formalization, as in many textbooks, morphisms are called [hom], for "homomorphism" (algebraic structure-preserving maps). Each morphism represents the set of all morphism having that type, so they are also called "hom-sets". Since categories may have other categories as objects, we require that the type of [hom] be larger than the type of its arguments. This is the purpose of the [uhom] type, allowing us to make use of Coq's support for universe polymorphism. *) c_id : ∀ {A}, A ~> A; c_comp : ∀ {A B C}, (B ~> C) → (A ~> B) → (A ~> C) where "f ∘ g" := (c_comp f g); (** If [ob] and [hom] are the nouns of category theory, [id] and [compose] are its fundamental verbs. Using only these notions we can reason about concepts such as _idempotency_, _involution_, _section_ and _retraction_, _equalizers_ and _co-equalizers_, and more. Before we may do so, however, we must constrain identity and composition under three laws: *) c_right_id : ∀ A B (f : A ~> B), f ∘ c_id = f; c_left_id : ∀ A B (f : A ~> B), c_id ∘ f = f; c_comp_assoc : ∀ A B C D (f : C ~> D) (g : B ~> C) (h : A ~> B), f ∘ (g ∘ h) = (f ∘ g) ∘ h }. (** Note the difference between the arrow used for function types in Coq, such as [A → B], and for morphisms in a category [A ~> B]. If the category must be indicated, it is stated in the arrow: [A ~{C}~> B]. *) (* begin hide *) (* Using a [Category] in a context requiring a [Type] will do what is expected using this coercion. *) Coercion ob : Category >-> Sortclass. (* Coercion hom : Category >-> Funclass. *) Declare Scope category_scope. Infix "~>" := hom : category_scope. Infix "~{ C }~>" := (@hom C) (at level 100) : category_scope. Infix "∘" := c_comp (at level 40, left associativity) : category_scope. Notation "ob/ C" := (@ob C) (at level 1) : category_scope. Notation "id/ X" := (@c_id _ X) (at level 1) : category_scope. Open Scope category_scope. Lemma cat_irrelevance `(C : Category) `(D : Category) : ∀ (m n : ∀ {A}, A ~> A) (p q : ∀ {A B C}, (B ~> C) → (A ~> B) → (A ~> C)) l l' r r' c c', @m = @n → @p = @q → {| ob := C ; hom := @hom C ; c_id := @m ; c_comp := @p ; c_left_id := l ; c_right_id := r ; c_comp_assoc := c |} = {| ob := C ; hom := @hom C ; c_id := @n ; c_comp := @q ; c_left_id := l' ; c_right_id := r' ; c_comp_assoc := c' |}. Proof. intros. subst. f_equal. apply proof_irrelevance. apply proof_irrelevance. apply proof_irrelevance. Qed. #[export] Hint Extern 1 => apply c_left_id : core. #[export] Hint Extern 1 => apply c_right_id : core. #[export] Hint Extern 4 (?A = ?A) => reflexivity : core. #[export] Hint Extern 7 (?X = ?Z) => match goal with [H : ?X = ?Y, H' : ?Y = ?Z |- ?X = ?Z] => transitivity Y end : core. (* end hide *) (** We may now extend our discourse about functions, using only the few terms we've defined so far: *) (* begin hide *) Section Morphisms. Context `{C : Category}. (* end hide *) Definition Idempotent `(f : X ~> X) := f ∘ f = f. Definition Involutive `(f : X ~> X) := f ∘ f = c_id. (** We can also define relationships between two functions: *) Definition Section' `(f : X ~> Y) := { g : Y ~> X & g ∘ f = c_id }. Definition Retraction `(f : X ~> Y) := { g : Y ~> X & f ∘ g = c_id }. Class SplitIdempotent {X Y : C} := { split_idem_retract := Y; split_idem : X ~> X; split_idem_r : X ~> split_idem_retract; split_idem_s : split_idem_retract ~> X; split_idem_law_1 : split_idem_s ∘ split_idem_r = split_idem; split_idem_law_2 : split_idem_r ∘ split_idem_s = id/Y }. (** A Σ-type (sigma type) is used to convey [Section'] and [Retraction] to make the witness available to proofs. The definition could be expressed with an existential quantifier (∃), but it would not convey which [g] was chosen. *) Definition Epic `(f : X ~> Y) := ∀ Z (g1 g2 : Y ~> Z), g1 ∘ f = g2 ∘ f → g1 = g2. Definition Monic `(f : X ~> Y) := ∀ Z (g1 g2 : Z ~> X), f ∘ g1 = f ∘ g2 → g1 = g2. Definition Bimorphic `(f : X ~> Y) := Epic f ∧ Monic f. Definition SplitEpi `(f : X ~> Y) := Retraction f. Definition SplitMono `(f : X ~> Y) := Section' f. (** The only morphism we've seen so far is [id], but we can trivially prove it is both _idempotent_ and _involutive_. *) (* begin hide *) Hint Unfold Idempotent : core. Hint Unfold Involutive : core. Hint Unfold Section' : core. Hint Unfold Retraction : core. Hint Unfold Epic : core. Hint Unfold Monic : core. Hint Unfold Bimorphic : core. Hint Unfold SplitEpi : core. Hint Unfold SplitMono : core. (* end hide *) Lemma id_idempotent : ∀ X, Idempotent (c_id (A := X)). Proof. auto. Qed. Lemma id_involutive : ∀ X, Involutive (c_id (A := X)). Proof. auto. Qed. (** We can also prove some relationships among these definitions. *) (* begin hide *) Section Lemmas. Variables X Y : C. Variable f : X ~> Y. (* end hide *) Lemma retractions_are_epic : Retraction f → Epic f. Proof. autounfold. intros. destruct X0. rewrite <- c_right_id. symmetry. rewrite <- c_right_id. rewrite <- e. repeat (rewrite c_comp_assoc); try f_equal; auto. Qed. Lemma sections_are_monic : Section' f → Monic f. Proof. autounfold. intros. destruct X0. rewrite <- c_left_id. symmetry. rewrite <- c_left_id. rewrite <- e. repeat (rewrite <- c_comp_assoc); try f_equal; auto. Qed. (* begin hide *) End Lemmas. End Morphisms. (* end hide *) Definition epi_compose `{C : Category} {X Y Z : C} `(ef : @Epic C Y Z f) `(eg : @Epic C X Y g) : Epic (f ∘ g). Proof. unfold Epic in *. intros. apply ef. apply eg. repeat (rewrite <- c_comp_assoc); auto. Qed. Definition monic_compose `{C : Category} {X Y Z : C} `(ef : @Monic C Y Z f) `(eg : @Monic C X Y g) : Monic (f ∘ g). Proof. unfold Monic in *. intros. apply eg. apply ef. repeat (rewrite c_comp_assoc); auto. Qed. (** * Isomorphism An isomorphism is a pair of mappings that establish an equivalence between objects. Using the language above, it is a pair of functions which are both sections and retractions of one another. That is, they compose to identity in both directions: *) Class Isomorphism `{C : Category} (X Y : C) := { to : X ~> Y; from : Y ~> X; iso_to : to ∘ from = id/Y; iso_from : from ∘ to = id/X }. (* begin hide *) Lemma iso_irrelevance `(C : Category) {X Y : C} : ∀ (f g : X ~> Y) (k h : Y ~> X) tl tl' fl fl', @f = @g → @k = @h → {| to := f ; from := k ; iso_to := tl ; iso_from := fl |} = {| to := g ; from := h ; iso_to := tl' ; iso_from := fl' |}. Proof. intros. subst. f_equal. apply proof_irrelevance. apply proof_irrelevance. Qed. (* end hide *) (** Typically isomorphisms are characterized by this pair of functions, but they can also be expressed as an equivalence between objects using the notation [A ≅ B]. A double-tilde is used to express the same notion of equivalence between value terms [a = b]. *) Notation "X {≅} Y" := (Isomorphism X Y) (at level 70, right associativity) : category_scope. Notation "x {≡} y" := (to x = y ∧ from y = x) (at level 70, right associativity). (** [id] witnesses the isomorphism between any object and itself. Isomorphisms are likewise symmetric and transitivity, making them parametric relations. This will allows us to use them in proof rewriting as though they were equalities. *) Program Definition iso_identity `{C : Category} (X : C) : X {≅} X := {| to := id/X; from := id/X |}. Program Definition iso_symmetry `{C : Category} `(iso : X {≅} Y) : Y {≅} X := {| to := @from C X Y iso; from := @to C X Y iso |}. (* begin hide *) Obligation 1. apply iso_from. Qed. Obligation 2. apply iso_to. Qed. (* end hide *) Program Definition iso_compose `{C : Category} {X Y Z : C} (iso_a : Y {≅} Z) (iso_b : X {≅} Y) : X {≅} Z := {| to := (@to C Y Z iso_a) ∘ (@to C X Y iso_b); from := (@from C X Y iso_b) ∘ (@from C Y Z iso_a) |}. (* begin hide *) Obligation 1. destruct iso_a. destruct iso_b. simpl. rewrite <- c_comp_assoc. rewrite (c_comp_assoc _ _ _ _ to1). rewrite iso_to1. rewrite c_left_id. assumption. Qed. Obligation 2. destruct iso_a. destruct iso_b. simpl. rewrite <- c_comp_assoc. rewrite (c_comp_assoc _ _ _ _ from0). rewrite iso_from0. rewrite c_left_id. assumption. Qed. (* end hide *) (* Definition iso_equiv `{C : Category} {a b : C} (x y : a ≅ b) : Prop := match x with | Build_Isomorphism to0 from0 _ _ => match y with | Build_Isomorphism to1 from1 _ _ => to0 = to1 ∧ from0 = from1 end end. Program Definition iso_equivalence `{C : Category} (a b : C) : Equivalence (@iso_equiv C a b). Obligation 1. unfold Reflexive, iso_equiv. intros. destruct x. auto. Defined. Obligation 2. unfold Symmetric, iso_equiv. intros. destruct x. destruct y. inversion H. split; symmetry; assumption. Defined. Obligation 3. unfold Transitive, iso_equiv. intros. destruct x. destruct y. destruct z. inversion H. inversion H0. split. transitivity to1; auto. transitivity from1; auto. Defined. Add Parametric Relation `(C : Category) (a b : C) : (a ≅ b) (@iso_equiv C a b) reflexivity proved by (@Equivalence_Reflexive _ _ (iso_equivalence a b)) symmetry proved by (@Equivalence_Symmetric _ _ (iso_equivalence a b)) transitivity proved by (@Equivalence_Transitive _ _ (iso_equivalence a b)) as parametric_relation_iso_eqv. Add Parametric Morphism `(C : Category) (a b c : C) : (@iso_compose C a b c) with signature (iso_equiv ==> iso_equiv ==> iso_equiv) as parametric_morphism_iso_comp. intros. unfold iso_equiv, iso_compose. destruct x. destruct y. destruct x0. destruct y0. simpl in *. inversion H. inversion H0. split; crush. Defined. *) (** A [Groupoid] is a [Category] where every morphism has an inverse, and is therefore an isomorphism. *) Program Definition Groupoid `(C : Category) : Category := {| ob := @ob C; hom := @Isomorphism C; c_id := @iso_identity C |}. (* begin hide *) Next Obligation. unfold iso_compose, iso_identity. eapply iso_compose; eauto. Defined. Next Obligation. unfold Groupoid_obligation_1. unfold iso_compose, iso_identity. destruct f. simpl in *. apply iso_irrelevance. apply c_right_id. apply c_left_id. Qed. Next Obligation. unfold Groupoid_obligation_1. unfold iso_compose, iso_identity. destruct f. simpl in *. apply iso_irrelevance. apply c_left_id. apply c_right_id. Qed. Next Obligation. unfold Groupoid_obligation_1. unfold iso_compose. destruct f. destruct g. destruct h. simpl; apply iso_irrelevance; rewrite c_comp_assoc; reflexivity. Qed. (* end hide *) (** A function which is both a retraction and monic, or a section and epic, bears an isomorphism with its respective witness. *) Program Definition Monic_Retraction_Iso `{C : Category} `(f : X ~{C}~> Y) (r : Retraction f) (m : Monic f) : X {≅} Y := {| to := f; from := projT1 r |}. (* begin hide *) Obligation 1. autounfold in *. destruct r. auto. Qed. Obligation 2. autounfold in *. destruct r. simpl. specialize (m X (x ∘ f) c_id). apply m. rewrite c_comp_assoc. rewrite e. auto. rewrite c_left_id. rewrite c_right_id. reflexivity. Qed. (* end hide *) Program Definition Epic_Section_Iso `{C : Category} {X Y} `(s : Section' f) `(e : Epic f) : X {≅} Y := {| to := f; from := projT1 s |}. (* begin hide *) Obligation 1. autounfold in *. destruct s. simpl. specialize (e Y (f ∘ x) c_id). apply e. rewrite <- c_comp_assoc. rewrite e0. rewrite c_left_id. rewrite c_right_id. reflexivity. Qed. Obligation 2. autounfold in *. destruct s. specialize (e Y (f ∘ x) c_id). auto. Qed. #[export] Hint Unfold Idempotent : core. #[export] Hint Unfold Involutive : core. #[export] Hint Unfold Section' : core. #[export] Hint Unfold Retraction : core. #[export] Hint Unfold Epic : core. #[export] Hint Unfold Monic : core. #[export] Hint Unfold Bimorphic : core. #[export] Hint Unfold SplitEpi : core. #[export] Hint Unfold SplitMono : core. (* end hide *) (** A section may be flipped using its witness to provide a retraction, and vice-versa. *) Definition flip_section `{Category} `(f : X ~> Y) (s : @Section' _ X Y f) : @Retraction _ Y X (projT1 s). Proof. autounfold. destruct s. exists f. crush. Qed. Definition flip_retraction `{Category} `(f : X ~> Y) (s : @Retraction _ X Y f) : @Section' _ Y X (projT1 s). Proof. autounfold. destruct s. exists f. crush. Qed. (** * Sets [Sets] is our first real category: the category of Coq types and functions. The objects of this category are all the Coq types (including [Set], [Prop] and [Type]), and its morphisms are functions from [Type] to [Type]. [id] simply returns whatever object is passed, and [compose] is regular composition between functions. Proving it is a category in Coq is automatic. Note that in many textbooks this category (or one similar to it) is called just [Set], but since that name conflicts with types of the same name in Coq, the plural is used instead. *) Program Definition Sets : Category := {| ob := Type; hom := fun X Y => X → Y; c_id := fun _ x => x; c_comp := fun _ _ _ f g x => f (g x) |}. (** Within the category of [Sets] we can prove that monic functions are injective, and epic functions are surjective. This is not necessarily true in other categories. *) Notation "X ≅Sets Y" := (@Isomorphism Sets X Y) (at level 70, right associativity) : category_scope. Definition Injective `(f : X → Y) := ∀ x y, f x = f y → x = y. Lemma injectivity_is_monic `(f : X → Y) : Injective f ↔ @Monic Sets _ _ f. Proof. unfold Monic, Injective. split; intros; simpl in *. - extensionality z. apply H. apply (equal_f H0). - pose (fun (_ : unit) => x) as const_x. pose (fun (_ : unit) => y) as const_y. specialize (H unit const_x const_y). unfold const_x in H. unfold const_y in H. apply equal_f in H. + assumption. + extensionality tt. assumption. + constructor. Qed. Definition Surjective `(f : X → Y) := ∀ y, ∃ x, f x = y. Lemma surjectivity_is_epic `(f : X → Y) : Surjective f ↔ @Epic Sets _ _ f. Proof. unfold Epic, Surjective. split; intros; simpl in *. - extensionality y. specialize (H y). destruct H. rewrite <- H. apply (equal_f H0). - specialize H with (Z := Prop). specialize H with (g1 := fun y0 => ∃ x0, f x0 = y0). specialize H with (g2 := fun y => True). eapply equal_f in H. erewrite H. constructor. extensionality x. apply propositional_extensionality. exists x. reflexivity. Qed. (** * Dual Category The opposite, or dual, of a category is expressed [C^op]. It has the same objects as its parent, but the direction of all morphisms is flipped. Doing this twice should result in the same category, making it an involutive operation. *) Program Definition Opposite `(C : Category) : Category := {| ob := @ob C; hom := fun x y => @hom C y x; c_id := @c_id C; c_comp := fun _ _ _ f g => g ∘ f |}. Obligation 3. rewrite c_comp_assoc. auto. Defined. (* begin hide *) Notation "C ^op" := (Opposite C) (at level 90) : category_scope. (* end hide *) Lemma op_involutive (C : Category) : (C^op)^op = C. Proof. unfold Opposite. unfold Opposite_obligation_1. unfold Opposite_obligation_2. unfold Opposite_obligation_3. simpl. destruct C. simpl. apply f_equal3; repeat (extensionality e; simpl; crush). extensionality b. extensionality c. extensionality d. extensionality f. extensionality g. extensionality h. crush. Qed. (** Using the functions [op] and [unop], we can "flip" a particular morphism by mapping to its corresponding morphism in the dual category. *) Definition op `{C : Category} : ∀ {X Y}, (X ~{C^op}~> Y) → (Y ~{C}~> X). Proof. auto. Defined. Definition unop `{C : Category} : ∀ {X Y}, (Y ~{C}~> X) → (X ~{C^op}~> Y). Proof. auto. Defined.
module Control.Monad.Free %access public export %default total data Free : (f : Type -> Type) -> (a : Type) -> Type where Pure : a -> Free f a Bind : f (Free f a) -> Free f a Functor f => Functor (Free f) where map f m = assert_total $ case m of Pure x => Pure (f x) Bind x => Bind (map (map f) x) Functor f => Applicative (Free f) where pure = Pure m <*> x = assert_total $ case m of Pure f => map f x Bind f => Bind (map (<*> x) f) Functor f => Monad (Free f) where m >>= f = assert_total $ case m of Pure x => f x Bind x => Bind (map (>>= f) x) liftFree : Functor f => f a -> Free f a liftFree = assert_total $ Bind . map Pure lowerFree : Monad f => Free f a -> f a lowerFree m = assert_total $ case m of Pure x => pure x Bind f => join (map lowerFree f) iterM : (Monad m, Functor f) => (f (m a) -> m a) -> Free f a -> m a iterM f m = assert_total $ case m of Pure x => pure x Bind x => f (map (iterM f) x) hoistFree : Functor g => ({ a : Type } -> f a -> g a) -> Free f b -> Free g b hoistFree f m = assert_total $ case m of Pure x => Pure x Bind x => Bind (hoistFree f <$> f x) foldFree : (Monad m, Functor f) => ({ a : Type } -> f a -> m a) -> Free f b -> m b foldFree f m = assert_total $ case m of Pure x => pure x Bind x => f x >>= foldFree f interface MonadFree (m : Type -> Type) (f : Type -> Type) | m where wrap : f (m a) -> m a MonadFree (Free f) f where wrap = assert_total Bind
#!/usr/bin/env python import os,sys, DLFCN, time, datetime import matplotlib import numpy import pylab import math import cherrypy from pylab import figure, show matplotlib.use('Agg') sys.setdlopenflags(DLFCN.RTLD_GLOBAL+DLFCN.RTLD_LAZY) from pluginCondDBPyInterface import * a = FWIncantation() rdbms = RDBMS() dbName = "sqlite_file:dati.db" rdbms = RDBMS("/afs/cern.ch/cms/DB/conddb/") dbName = "oracle://cms_orcoff_prep/CMS_COND_30X_RPC" tagPVSS = 'test1' from CondCore.Utilities import iovInspector as inspect db = rdbms.getDB(dbName) tags = db.allTags() ##----------------------- Create assosiacion map for detectors ----------------- ##tagPVSS = 'PVSS_v3' try: iov = inspect.Iov(db,tagPVSS) iovlist=iov.list() print iovlist detMapName = {} for p in iovlist: payload=inspect.PayLoad(db,p[0]) info = payload.summary().split(" ") i = 0 for e in info: try: if int(info[i+1]) == 0: detName = "W"+str(info[i+2])+"_S"+str(info[i+3])+"_RB"+str(info[i+4])+"_Layer"+str(info[i+5])+"_SubS"+str(info[i+6]) else: detName = "D"+str(info[i+2])+"_S"+str(info[i+3])+"_RB"+str(info[i+4])+"_Layer"+str(info[i+5])+"_SubS"+str(info[i+6]) detMapName[info[i]] = detName i += 7 except: pass for (k,v) in detMapName.items(): print k,v except Exception as er : print er ##--------------------- Current reading ----------------------------------------- ##tag = 'Imon_v3' ####tag = 'Test_70195' ##timeStart = time.mktime((2008, 11, 9, 4, 10, 0,0,0,0)) ##timeEnd = time.mktime((2008, 11, 10, 5, 10, 0,0,0,0)) ####print timeStart,timeEnd, time.ctime(timeStart),time.ctime(timeEnd) ##try: ## iov1 = inspect.Iov(db,tag) ## iovlist1=iov1.list() ## detMap = {} ## for p1 in iovlist1: ## payload1=inspect.PayLoad(db,p1[0]) ## info = payload1.summary().split(" ") ## i = 0 ## for e in info: ## if i+2 < len(info): ## timein = int(info[i+2])+(p1[1] >> 32) ## if timein < int(timeEnd): ## if detMap.has_key(info[i]): ## detMap[info[i]][0].append(timein) ## detMap[info[i]][1].append(float(info[i+1])) ## else: ## detMap[info[i]] = [[timein],[float(info[i+1])]] #### if detMap.has_key((detMapName[info[i]])): #### print "Exist the key!" #### print "Current vaues: ", detMap[(detMapName[info[i]])][0], detMap[(detMapName[info[i]])][1] #### print "value is: ", timein, float(info[i+1]) #### print "The det name is: ", (detMapName[info[i]]) #### #### detMap[(detMapName[info[i]])][0].append(timein) #### detMap[(detMapName[info[i]])][1].append(float(info[i+1])) #### else: #### print "Not Exist the key!" #### print "Value is: ", timein, float(info[i+1]) #### print "Det id: ", info[i] #### print "The det name is: ", (detMapName[info[i]]) #### #### detMap[(detMapName[info[i]])] = [[timein],[float(info[i+1])]] ## i += 3 ## for (k,v) in detMap.items(): ## f=pylab.figure() ## ax = f.add_subplot(111) ## ax.set_xlabel('Time (s)') ## ax.set_ylabel('Current (uA)') ## ax.set_title(str(k)) ## ax.plot(v[0],v[1],'rs-',linewidth=2) ## f.canvas.draw() ## f.savefig('/tmp/trentad/'+str(k),format='png') ## average = pylab.polyfit(v[0],v[1],0) ## sigma = 0 ## highCurrent = False ## for c in v[1]: ## sigma += math.pow((average[0]-c), 2) ## if math.fabs(average[0]-c) > 1: highCurrent = True ## sigma = math.sqrt(sigma/len(v[1])) ## if highCurrent: ## print "Num points: ",len(v[0])," Fit coeff: ",pylab.polyfit(v[0],v[1],0), " Sigma: ",sigma, " HighCurrrent: ", highCurrent ##except Exception, er : ## print er
theory Isar imports Main begin lemma fixes f :: "'a \<Rightarrow> 'a set" assumes s: "surj f" shows "False" proof - have "\<exists> a. {x. x \<notin> f x} = f a" using s by (auto simp: surj_def) thus "False" by blast qed lemma fixes a b :: int assumes "b dvd (a+b)" shows "b dvd a" proof - have "\<exists> k'. a = b * k'" if asm: "a+b = b*k" for k proof show "a = b*(k-1)" using asm by (simp add: algebra_simps) qed then show ?thesis using assms by (auto simp add: dvd_def) qed (* A typical proof by case analysis on the form of xs: *) lemma "length (tl xs) = length xs - 1" proof (cases xs) assume "xs = []" thus ?thesis by simp next fix y ys assume "xs = y # ys" thus ?thesis by simp qed (* Alternative: *) lemma "length (tl xs) = length xs - 1" proof (cases xs) case Nil thus ?thesis by simp next case (Cons y ys) thus ?thesis by simp qed lemma "\<Sigma> {0..n :: nat} = n * (n+1) div 2" proof (induction n) case 0 show ?case by simp next case (Suc n) thus ?case by simp qed end
{-# OPTIONS --without-K --safe #-} -- This module packages up all the stuff that's passed to the other -- modules in a convenient form. module Polynomial.Parameters where open import Function open import Algebra open import Relation.Unary open import Level open import Algebra.Solver.Ring.AlmostCommutativeRing open import Data.Bool using (Bool; T) -- This record stores all the stuff we need for the coefficients: -- -- * A raw ring -- * A (decidable) predicate on "zeroeness" -- -- It's used for defining the operations on the horner normal form. record RawCoeff c ℓ : Set (suc (c ⊔ ℓ)) where field coeffs : RawRing c ℓ Zero-C : RawRing.Carrier coeffs → Bool open RawRing coeffs public -- This record stores the full information we need for converting -- to the final ring. record Homomorphism c ℓ₁ ℓ₂ ℓ₃ : Set (suc (c ⊔ ℓ₁ ⊔ ℓ₂ ⊔ ℓ₃)) where field coeffs : RawCoeff c ℓ₁ module Raw = RawCoeff coeffs field ring : AlmostCommutativeRing ℓ₂ ℓ₃ morphism : Raw.coeffs -Raw-AlmostCommutative⟶ ring open _-Raw-AlmostCommutative⟶_ morphism renaming (⟦_⟧ to ⟦_⟧ᵣ) public open AlmostCommutativeRing ring public field Zero-C⟶Zero-R : ∀ x → T (Raw.Zero-C x) → 0# ≈ ⟦ x ⟧ᵣ
\documentclass{article} \usepackage{amsmath} \usepackage[margin=1.0in]{geometry} \usepackage{xcolor} \begin{document} \noindent Does $\displaystyle \sum_{n=1}^\infty \frac{\cos \pi n}{n}$ diverge, converge absolutely, or converge conditionally? \subsection*{Solution} The series $\displaystyle \sum_{n=1}^\infty \frac{\cos \pi n}{n}$ is an alternating series. Note $b_n = |a_n| = \frac1n$. Since the sequence $b_n$ is decreasing and $b_n \to 0$, by the Alternating Series Test, $\displaystyle \sum_{n=1}^\infty \frac{\cos \pi n}{n}$ converges. To figure out whether $\displaystyle \sum_{n=1}^\infty \frac{\cos \pi n}{n}$ converges absolutely or conditionally, we consider the series \[ \sum_{n=1}^\infty \left|\frac{\cos \pi n}{n}\right| = \sum_{n=1}^\infty \frac{1}{n} \] which diverges by the $p$-test, so the series $\displaystyle \sum_{n=1}^\infty \frac{\cos \pi n}{n}$ converges conditionally. \end{document}%%%%%%%%%%%%%%%%% \begin{align*} L&=\lim_{n \to \infty} \sqrt[n]{|a_n|}\\ &= \lim_{n \to \infty} \sqrt[n]{\left| \right|}\\ \end{align*} Since $\sum |a_n| = \sum a_n$, the series $\displaystyle \sum_{n=1}^\infty AAAAAAAAAAAAAA$ converges absolutely. Since $|r| < 1$, the series ... converges by the Geometric Series Test. Since $|r| \geq 1$, the series ... diverges by the Geometric Series Test. The function $f(x)=\frac{}{}$ is continuous, positive, and decreasing on $[1,\infty)$. \subsection*{Solution}
(* Author: Tobias Nipkow *) section "Join-Based Implementation of Sets via RBTs" theory Set2_Join_RBT imports Set2_Join RBT_Set begin subsection "Code" text \<open> Function \<open>joinL\<close> joins two trees (and an element). Precondition: \<^prop>\<open>bheight l \<le> bheight r\<close>. Method: Descend along the left spine of \<open>r\<close> until you find a subtree with the same \<open>bheight\<close> as \<open>l\<close>, then combine them into a new red node. \<close> fun joinL :: "'a rbt \<Rightarrow> 'a \<Rightarrow> 'a rbt \<Rightarrow> 'a rbt" where "joinL l x r = (if bheight l \<ge> bheight r then R l x r else case r of B l' x' r' \<Rightarrow> baliL (joinL l x l') x' r' | R l' x' r' \<Rightarrow> R (joinL l x l') x' r')" fun joinR :: "'a rbt \<Rightarrow> 'a \<Rightarrow> 'a rbt \<Rightarrow> 'a rbt" where "joinR l x r = (if bheight l \<le> bheight r then R l x r else case l of B l' x' r' \<Rightarrow> baliR l' x' (joinR r' x r) | R l' x' r' \<Rightarrow> R l' x' (joinR r' x r))" definition join :: "'a rbt \<Rightarrow> 'a \<Rightarrow> 'a rbt \<Rightarrow> 'a rbt" where "join l x r = (if bheight l > bheight r then paint Black (joinR l x r) else if bheight l < bheight r then paint Black (joinL l x r) else B l x r)" declare joinL.simps[simp del] declare joinR.simps[simp del] subsection "Properties" subsubsection "Color and height invariants" lemma invc2_joinL: "\<lbrakk> invc l; invc r; bheight l \<le> bheight r \<rbrakk> \<Longrightarrow> invc2 (joinL l x r) \<and> (bheight l \<noteq> bheight r \<and> color r = Black \<longrightarrow> invc(joinL l x r))" proof (induct l x r rule: joinL.induct) case (1 l x r) thus ?case by(auto simp: invc_baliL invc2I joinL.simps[of l x r] split!: tree.splits if_splits) qed lemma invc2_joinR: "\<lbrakk> invc l; invh l; invc r; invh r; bheight l \<ge> bheight r \<rbrakk> \<Longrightarrow> invc2 (joinR l x r) \<and> (bheight l \<noteq> bheight r \<and> color l = Black \<longrightarrow> invc(joinR l x r))" proof (induct l x r rule: joinR.induct) case (1 l x r) thus ?case by(fastforce simp: invc_baliR invc2I joinR.simps[of l x r] split!: tree.splits if_splits) qed lemma bheight_joinL: "\<lbrakk> invh l; invh r; bheight l \<le> bheight r \<rbrakk> \<Longrightarrow> bheight (joinL l x r) = bheight r" proof (induct l x r rule: joinL.induct) case (1 l x r) thus ?case by(auto simp: bheight_baliL joinL.simps[of l x r] split!: tree.split) qed lemma invh_joinL: "\<lbrakk> invh l; invh r; bheight l \<le> bheight r \<rbrakk> \<Longrightarrow> invh (joinL l x r)" proof (induct l x r rule: joinL.induct) case (1 l x r) thus ?case by(auto simp: invh_baliL bheight_joinL joinL.simps[of l x r] split!: tree.split color.split) qed lemma bheight_joinR: "\<lbrakk> invh l; invh r; bheight l \<ge> bheight r \<rbrakk> \<Longrightarrow> bheight (joinR l x r) = bheight l" proof (induct l x r rule: joinR.induct) case (1 l x r) thus ?case by(fastforce simp: bheight_baliR joinR.simps[of l x r] split!: tree.split) qed lemma invh_joinR: "\<lbrakk> invh l; invh r; bheight l \<ge> bheight r \<rbrakk> \<Longrightarrow> invh (joinR l x r)" proof (induct l x r rule: joinR.induct) case (1 l x r) thus ?case by(fastforce simp: invh_baliR bheight_joinR joinR.simps[of l x r] split!: tree.split color.split) qed text \<open>All invariants in one:\<close> lemma inv_joinL: "\<lbrakk> invc l; invc r; invh l; invh r; bheight l \<le> bheight r \<rbrakk> \<Longrightarrow> invc2 (joinL l x r) \<and> (bheight l \<noteq> bheight r \<and> color r = Black \<longrightarrow> invc (joinL l x r)) \<and> invh (joinL l x r) \<and> bheight (joinL l x r) = bheight r" proof (induct l x r rule: joinL.induct) case (1 l x r) thus ?case by(auto simp: inv_baliL invc2I joinL.simps[of l x r] split!: tree.splits if_splits) qed lemma inv_joinR: "\<lbrakk> invc l; invc r; invh l; invh r; bheight l \<ge> bheight r \<rbrakk> \<Longrightarrow> invc2 (joinR l x r) \<and> (bheight l \<noteq> bheight r \<and> color l = Black \<longrightarrow> invc (joinR l x r)) \<and> invh (joinR l x r) \<and> bheight (joinR l x r) = bheight l" proof (induct l x r rule: joinR.induct) case (1 l x r) thus ?case by(auto simp: inv_baliR invc2I joinR.simps[of l x r] split!: tree.splits if_splits) qed (* unused *) lemma rbt_join: "\<lbrakk> invc l; invh l; invc r; invh r \<rbrakk> \<Longrightarrow> rbt(join l x r)" by(simp add: inv_joinL inv_joinR invh_paint rbt_def color_paint_Black join_def) text \<open>To make sure the the black height is not increased unnecessarily:\<close> lemma bheight_paint_Black: "bheight(paint Black t) \<le> bheight t + 1" by(cases t) auto lemma "\<lbrakk> rbt l; rbt r \<rbrakk> \<Longrightarrow> bheight(join l x r) \<le> max (bheight l) (bheight r) + 1" using bheight_paint_Black[of "joinL l x r"] bheight_paint_Black[of "joinR l x r"] bheight_joinL[of l r x] bheight_joinR[of l r x] by(auto simp: max_def rbt_def join_def) subsubsection "Inorder properties" text "Currently unused. Instead \<^const>\<open>set_tree\<close> and \<^const>\<open>bst\<close> properties are proved directly." lemma inorder_joinL: "bheight l \<le> bheight r \<Longrightarrow> inorder(joinL l x r) = inorder l @ x # inorder r" proof(induction l x r rule: joinL.induct) case (1 l x r) thus ?case by(auto simp: inorder_baliL joinL.simps[of l x r] split!: tree.splits color.splits) qed lemma inorder_joinR: "inorder(joinR l x r) = inorder l @ x # inorder r" proof(induction l x r rule: joinR.induct) case (1 l x r) thus ?case by (force simp: inorder_baliR joinR.simps[of l x r] split!: tree.splits color.splits) qed lemma "inorder(join l x r) = inorder l @ x # inorder r" by(auto simp: inorder_joinL inorder_joinR inorder_paint join_def split!: tree.splits color.splits if_splits dest!: arg_cong[where f = inorder]) subsubsection "Set and bst properties" lemma set_baliL: "set_tree(baliL l a r) = set_tree l \<union> {a} \<union> set_tree r" by(cases "(l,a,r)" rule: baliL.cases) (auto) lemma set_joinL: "bheight l \<le> bheight r \<Longrightarrow> set_tree (joinL l x r) = set_tree l \<union> {x} \<union> set_tree r" proof(induction l x r rule: joinL.induct) case (1 l x r) thus ?case by(auto simp: set_baliL joinL.simps[of l x r] split!: tree.splits color.splits) qed lemma set_baliR: "set_tree(baliR l a r) = set_tree l \<union> {a} \<union> set_tree r" by(cases "(l,a,r)" rule: baliR.cases) (auto) lemma set_joinR: "set_tree (joinR l x r) = set_tree l \<union> {x} \<union> set_tree r" proof(induction l x r rule: joinR.induct) case (1 l x r) thus ?case by(force simp: set_baliR joinR.simps[of l x r] split!: tree.splits color.splits) qed lemma set_paint: "set_tree (paint c t) = set_tree t" by (cases t) auto lemma set_join: "set_tree (join l x r) = set_tree l \<union> {x} \<union> set_tree r" by(simp add: set_joinL set_joinR set_paint join_def) lemma bst_baliL: "\<lbrakk>bst l; bst r; \<forall>x\<in>set_tree l. x < a; \<forall>x\<in>set_tree r. a < x\<rbrakk> \<Longrightarrow> bst (baliL l a r)" by(cases "(l,a,r)" rule: baliL.cases) (auto simp: ball_Un) lemma bst_baliR: "\<lbrakk>bst l; bst r; \<forall>x\<in>set_tree l. x < a; \<forall>x\<in>set_tree r. a < x\<rbrakk> \<Longrightarrow> bst (baliR l a r)" by(cases "(l,a,r)" rule: baliR.cases) (auto simp: ball_Un) lemma bst_joinL: "\<lbrakk>bst (Node l (a, n) r); bheight l \<le> bheight r\<rbrakk> \<Longrightarrow> bst (joinL l a r)" proof(induction l a r rule: joinL.induct) case (1 l a r) thus ?case by(auto simp: set_baliL joinL.simps[of l a r] set_joinL ball_Un intro!: bst_baliL split!: tree.splits color.splits) qed lemma bst_joinR: "\<lbrakk>bst l; bst r; \<forall>x\<in>set_tree l. x < a; \<forall>y\<in>set_tree r. a < y \<rbrakk> \<Longrightarrow> bst (joinR l a r)" proof(induction l a r rule: joinR.induct) case (1 l a r) thus ?case by(auto simp: set_baliR joinR.simps[of l a r] set_joinR ball_Un intro!: bst_baliR split!: tree.splits color.splits) qed lemma bst_paint: "bst (paint c t) = bst t" by(cases t) auto lemma bst_join: "bst (Node l (a, n) r) \<Longrightarrow> bst (join l a r)" by(auto simp: bst_paint bst_joinL bst_joinR join_def) lemma inv_join: "\<lbrakk> invc l; invh l; invc r; invh r \<rbrakk> \<Longrightarrow> invc(join l x r) \<and> invh(join l x r)" by (simp add: inv_joinL inv_joinR invh_paint join_def) subsubsection "Interpretation of \<^locale>\<open>Set2_Join\<close> with Red-Black Tree" global_interpretation RBT: Set2_Join where join = join and inv = "\<lambda>t. invc t \<and> invh t" defines insert_rbt = RBT.insert and delete_rbt = RBT.delete and split_rbt = RBT.split and join2_rbt = RBT.join2 and split_min_rbt = RBT.split_min proof (standard, goal_cases) case 1 show ?case by (rule set_join) next case 2 thus ?case by (simp add: bst_join) next case 3 show ?case by simp next case 4 thus ?case by (simp add: inv_join) next case 5 thus ?case by simp qed text \<open>The invariant does not guarantee that the root node is black. This is not required to guarantee that the height is logarithmic in the size --- Exercise.\<close> end
import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('Ads_CTR_Optimisation.csv') import math N = 10000 d = 10 ads_selected = [] numbers_of_selections = [0] * d sums_of_rewards = [0] * d total_reward = 0 for n in range(0, N): ad = 0 max_upper_bound = 0 for i in range(0, d): if (numbers_of_selections[i] > 0): average_reward = sums_of_rewards[i] / numbers_of_selections[i] delta_i = math.sqrt(3/2 * math.log(n + 1) / numbers_of_selections[i]) upper_bound = average_reward + delta_i else: upper_bound = 1e400 if (upper_bound > max_upper_bound): max_upper_bound = upper_bound ad = i ads_selected.append(ad) numbers_of_selections[ad] = numbers_of_selections[ad] + 1 reward = dataset.values[n, ad] sums_of_rewards[ad] = sums_of_rewards[ad] + reward total_reward = total_reward + reward plt.hist(ads_selected) plt.title('Histogram of ads selections') plt.xlabel('Ads') plt.ylabel('Number of times each ad was selected') plt.show()