Datasets:
AI4M
/

text
stringlengths
0
3.34M
From Coq Require Import PeanoNat. From DEZ Require Export Init. From DEZ.Is Require Import TotalOrder Semiring MonoidHomomorphism. Module Equivalence. Instance nat_has_eqv : HasEqv nat := Nat.eq. Instance nat_is_reflexive : IsReflexive Nat.eq := {}. Proof. intros x. reflexivity. Qed. Instance nat_is_symmetric : IsSymmetric Nat.eq := {}. Proof. intros x y p. symmetry; auto. Qed. Instance nat_is_transitive : IsTransitive Nat.eq := {}. Proof. intros x y z p q. transitivity y; auto. Qed. Instance nat_is_setoid : IsSetoid Nat.eq := {}. End Equivalence. Module Order. Instance nat_has_ord : HasOrd nat := Nat.le. Instance nat_is_antisymmetric : IsAntisymmetric Nat.le := {}. Proof. intros x y p q. apply Nat.le_antisymm; auto. Qed. Instance nat_is_transitive : IsTransitive Nat.le := {}. Proof. intros x y z p q. transitivity y; auto. Qed. Instance nat_is_connex : IsConnex Nat.le := {}. Proof. intros x y. apply Nat.le_ge_cases. Qed. Instance nat_is_total_order : IsTotalOrder Nat.le := {}. Proof. cbv -[Nat.le]. apply Nat.le_wd. Qed. End Order. Module Additive. Instance nat_has_opr : HasOpr nat := Nat.add. Instance nat_is_associative : IsAssociative Nat.add := {}. Proof. intros x y z. apply Nat.add_assoc. Qed. Instance nat_is_semigroup : IsSemigroup Nat.add := {}. Proof. cbv -[Nat.add]. apply Nat.add_wd. Qed. Instance nat_has_idn : HasIdn nat := Nat.zero. Instance nat_is_left_identifiable : IsLeftIdentifiable Nat.add Nat.zero := {}. Proof. intros x. apply Nat.add_0_l. Qed. Instance nat_is_right_identifiable : IsRightIdentifiable Nat.add Nat.zero := {}. Proof. intros x. apply Nat.add_0_r. Qed. Instance nat_is_identifiable : IsBiidentifiable Nat.add Nat.zero := {}. Instance nat_is_monoid : IsMonoid Nat.add Nat.zero := {}. Instance nat_is_commutative : IsCommutative Nat.add := {}. Proof. intros x y. apply Nat.add_comm. Qed. Instance nat_is_commutative_monoid : IsCommutativeMonoid Nat.add Nat.zero := {}. End Additive. Module Multiplicative. Instance nat_has_opr : HasOpr nat := Nat.mul. Instance nat_is_associative : IsAssociative Nat.mul := {}. Proof. intros x y z. apply Nat.mul_assoc. Qed. Instance nat_is_semigroup : IsSemigroup Nat.mul := {}. Proof. cbv -[Nat.mul]. apply Nat.mul_wd. Qed. Instance nat_has_idn : HasIdn nat := Nat.one. Instance nat_is_left_identifiable : IsLeftIdentifiable Nat.mul Nat.one := {}. Proof. intros x. apply Nat.mul_1_l. Qed. Instance nat_is_right_identifiable : IsRightIdentifiable Nat.mul Nat.one := {}. Proof. intros x. apply Nat.mul_1_r. Qed. Instance nat_is_identifiable : IsBiidentifiable Nat.mul Nat.one := {}. Instance nat_is_monoid : IsMonoid Nat.mul Nat.one := {}. Instance nat_is_commutative : IsCommutative Nat.mul := {}. Proof. intros x y. apply Nat.mul_comm. Qed. Instance nat_is_commutative_monoid : IsCommutativeMonoid Nat.mul Nat.one := {}. End Multiplicative. Instance nat_has_add : HasAdd nat := Nat.add. Instance nat_has_mul : HasMul nat := Nat.mul. Instance nat_has_zero : HasZero nat := Nat.zero. Instance nat_has_one : HasOne nat := Nat.one. Instance nat_is_left_distributive : IsLeftDistributive Nat.add Nat.mul := {}. Proof. intros x y z. apply Nat.mul_add_distr_l. Qed. Instance nat_is_right_distributive : IsRightDistributive Nat.add Nat.mul := {}. Proof. intros x y z. apply Nat.mul_add_distr_r. Qed. Instance nat_is_distributive : IsBidistributive Nat.add Nat.mul := {}. Instance nat_is_semiring : IsSemiring Nat.add Nat.zero Nat.mul Nat.one := {}. Definition natexp (x : nat) : nat := 2 ^ x. Instance nat_has_hom : HasHom nat nat := natexp. Instance nat_is_setoid_homomorphism : IsSetoidHomomorphism natexp := {}. Proof. cbv -[Nat.pow]. apply Nat.pow_wd. reflexivity. Qed. Instance nat_is_semigroup_homomorphism : IsSemigroupHomomorphism Nat.add Nat.mul natexp := {}. Proof. intros x y. apply Nat.pow_add_r. Qed. Instance nat_is_monoid_homomorphism : IsMonoidHomomorphism Nat.add Nat.zero Nat.mul Nat.one natexp := {}. Proof. reflexivity. Qed.
# ------------------------------------------------------------------ # Licensed under the ISC License. See LICENSE in the project root. # ------------------------------------------------------------------ module KrigingEstimators using GeoStatsBase using Variography using LinearAlgebra: Factorization, lu, cholesky, issuccess, ⋅ using Distances: Euclidean using Distributions: Normal using Combinatorics: multiexponents using StaticArrays: MVector import GeoStatsBase: fit, predict, status import GeoStatsBase: preprocess, solve, solve_single include("estimators.jl") include("solvers/kriging.jl") include("solvers/sgsim.jl") export # estimators KrigingEstimator, SimpleKriging, OrdinaryKriging, UniversalKriging, ExternalDriftKriging, fit, predict, status, weights, # solvers Kriging, KrigingParam, SeqGaussSim, SeqGaussSimParam end
import phase2.weak_approx open cardinal quiver set sum with_bot open_locale cardinal classical pointwise universe u namespace con_nf variables [params.{u}] /-! # Filling in orbits of atoms -/ namespace weak_near_litter_approx variables (w : weak_near_litter_approx) def need_forward_images : set atom := w.atom_map.ran \ w.atom_map.dom def need_backward_images : set atom := w.atom_map.dom \ w.atom_map.ran lemma atom_map_ran_small : small w.atom_map.ran := begin have : small (w.atom_map_or_else '' w.atom_map.dom) := small.image w.atom_map_dom_small, refine small.mono _ this, rintros _ ⟨a, ha, rfl⟩, refine ⟨a, ha, _⟩, rw atom_map_or_else_of_dom, end lemma need_forward_images_small : small w.need_forward_images := small.mono (diff_subset _ _) w.atom_map_ran_small lemma need_backward_images_small : small w.need_backward_images := small.mono (diff_subset _ _) w.atom_map_dom_small lemma mk_diff_dom_ran (L : litter) : #(litter_set L \ (w.atom_map.dom ∪ w.atom_map.ran) : set atom) = #κ := begin refine le_antisymm _ _, { refine ⟨⟨λ a, a.1.2, _⟩⟩, intros a b h, refine subtype.coe_injective (prod.ext (a.prop.1.trans b.prop.1.symm) _), simp only [subtype.val_eq_coe] at h, exact h, }, { by_contra' h, have := add_lt_of_lt κ_regular.aleph_0_le h (small.union w.atom_map_dom_small w.atom_map_ran_small), have := (le_mk_diff_add_mk (litter_set L) _).trans_lt this, simp only [mk_litter_set, lt_self_iff_false] at this, exact this, }, end lemma need_images_small (L : litter) : #(ℕ × w.need_backward_images ⊕ ℕ × w.need_forward_images) < #κ := begin simp only [mk_prod, mk_denumerable, lift_aleph_0, lift_uzero, mk_diff_dom_ran, mk_sum, lift_id], rw ← mul_add, refine lt_of_le_of_lt (mul_le_max _ _) (max_lt (max_lt _ _) _), exact Λ_limit.aleph_0_le.trans_lt Λ_lt_κ, exact add_lt_of_lt κ_regular.aleph_0_le w.need_backward_images_small w.need_forward_images_small, exact Λ_limit.aleph_0_le.trans_lt Λ_lt_κ, end lemma le_mk_diff_dom_ran (L : litter) : #(ℕ × w.need_backward_images ⊕ ℕ × w.need_forward_images) ≤ #(litter_set L \ (w.atom_map.dom ∪ w.atom_map.ran) : set atom) := begin rw [mk_diff_dom_ran], exact (w.need_images_small L).le, end def orbit_set (L : litter) : set atom := (le_mk_iff_exists_subset.mp (w.le_mk_diff_dom_ran L)).some lemma orbit_set_subset (L : litter) : w.orbit_set L ⊆ litter_set L \ (w.atom_map.dom ∪ w.atom_map.ran) := (le_mk_iff_exists_subset.mp (w.le_mk_diff_dom_ran L)).some_spec.1 lemma not_mem_need_forward_images_of_mem_orbit_set {a : atom} {L : litter} (h : a ∈ w.orbit_set L) : a ∉ w.need_forward_images := λ ha, (w.orbit_set_subset L h).2 (or.inr ha.1) lemma not_mem_need_backward_images_of_mem_orbit_set {a : atom} {L : litter} (h : a ∈ w.orbit_set L) : a ∉ w.need_backward_images := λ ha, (w.orbit_set_subset L h).2 (or.inl ha.1) lemma mk_orbit_set (L : litter) : #(w.orbit_set L) = #(ℕ × w.need_backward_images ⊕ ℕ × w.need_forward_images) := (le_mk_iff_exists_subset.mp (w.le_mk_diff_dom_ran L)).some_spec.2 @[irreducible] noncomputable def orbit_set_equiv (L : litter) : w.orbit_set L ≃ ℕ × w.need_backward_images ⊕ ℕ × w.need_forward_images := (cardinal.eq.mp (w.mk_orbit_set L)).some lemma orbit_set_equiv_injective {a₁ a₂ : ℕ × w.need_backward_images ⊕ ℕ × w.need_forward_images} {L₁ L₂ : litter} (h : ((w.orbit_set_equiv L₁).symm a₁ : atom) = (w.orbit_set_equiv L₂).symm a₂) : L₁ = L₂ ∧ a₁ = a₂ := begin have h₁ := w.orbit_set_subset L₁ ((w.orbit_set_equiv L₁).symm a₁).prop, have h₂ := w.orbit_set_subset L₂ ((w.orbit_set_equiv L₂).symm a₂).prop, rw h at h₁, cases eq_of_mem_litter_set_of_mem_litter_set h₁.1 h₂.1, simp only [subtype.coe_inj, embedding_like.apply_eq_iff_eq] at h, exact ⟨rfl, h⟩, end lemma orbit_set_equiv_congr {L L' : litter} {a : atom} (ha : a ∈ w.orbit_set L) (h : L = L') : w.orbit_set_equiv L ⟨a, ha⟩ = w.orbit_set_equiv L' ⟨a, h ▸ ha⟩ := by cases h; refl lemma orbit_set_equiv_symm_congr {L L' : litter} {a : ℕ × ↥(w.need_backward_images) ⊕ ℕ × ↥(w.need_forward_images)} (h : L = L') : ((w.orbit_set_equiv L).symm a : atom) = (w.orbit_set_equiv L').symm a := by cases h; refl lemma orbit_set_small (L : litter) : small (w.orbit_set L) := begin rw [small, mk_orbit_set], exact w.need_images_small L, end noncomputable def next_forward_image (L : litter) (a : ℕ × w.need_forward_images) : atom := (w.orbit_set_equiv (w.litter_perm L)).symm (inr (a.1 + 1, a.2)) noncomputable def next_backward_image (L : litter) : ℕ × w.need_backward_images → atom | (0, a) := a | (n + 1, a) := (w.orbit_set_equiv (w.litter_perm L)).symm (inl (n, a)) def next_forward_image_domain (L : litter) : set (ℕ × w.need_forward_images) := {a | (a.2 : atom).1 ∈ w.litter_perm.domain ∧ (w.litter_perm^[a.1 + 1] (a.2 : atom).1 = L)} def next_backward_image_domain (L : litter) : set (ℕ × w.need_backward_images) := {a | (a.2 : atom).1 ∈ w.litter_perm.domain ∧ (w.litter_perm.symm^[a.1 + 1] (a.2 : atom).1 = L)} lemma mk_mem_next_forward_image_domain (L : litter) (n : ℕ) (a : w.need_forward_images) : (n, a) ∈ w.next_forward_image_domain L ↔ (a : atom).1 ∈ w.litter_perm.domain ∧ (w.litter_perm^[n + 1] (a : atom).1 = L) := iff.rfl lemma mk_mem_next_backward_image_domain (L : litter) (n : ℕ) (a : w.need_backward_images) : (n, a) ∈ w.next_backward_image_domain L ↔ (a : atom).1 ∈ w.litter_perm.domain ∧ (w.litter_perm.symm^[n + 1] (a : atom).1 = L) := iff.rfl lemma next_forward_image_eq {L₁ L₂ : litter} {a b : ℕ × w.need_forward_images} (hL₁ : L₁ ∈ w.litter_perm.domain) (hL₂ : L₂ ∈ w.litter_perm.domain) (h : w.next_forward_image L₁ a = w.next_forward_image L₂ b) : L₁ = L₂ := begin rw [next_forward_image, next_forward_image] at h, have ha := w.orbit_set_subset _ ((w.orbit_set_equiv (w.litter_perm L₁)).symm (inr (a.1 + 1, a.2))).prop, have hb := w.orbit_set_subset _ ((w.orbit_set_equiv (w.litter_perm L₂)).symm (inr (b.1 + 1, b.2))).prop, rw h at ha, refine w.litter_perm.inj_on hL₁ hL₂ _, exact eq_of_mem_litter_set_of_mem_litter_set ha.1 hb.1, end lemma next_backward_image_eq {L₁ L₂ : litter} {a b : ℕ × w.need_backward_images} (ha : a ∈ w.next_backward_image_domain L₁) (hb : b ∈ w.next_backward_image_domain L₂) (hL₁ : L₁ ∈ w.litter_perm.domain) (hL₂ : L₂ ∈ w.litter_perm.domain) (h : w.next_backward_image L₁ a = w.next_backward_image L₂ b) : L₁ = L₂ := begin obtain ⟨m, a⟩ := a, obtain ⟨n, b⟩ := b, cases m; cases n; rw [next_backward_image, next_backward_image] at h, { simp only [next_backward_image_domain, function.iterate_succ, function.comp_app, mem_set_of_eq, function.iterate_zero, id.def] at ha hb, rw [← h, ha.2] at hb, exact hb.2, }, { rw subtype.coe_eq_iff at h, obtain ⟨h₁, h₂⟩ := h, cases w.not_mem_need_backward_images_of_mem_orbit_set ((w.orbit_set_equiv _).symm _).prop h₁, }, { symmetry' at h, rw subtype.coe_eq_iff at h, obtain ⟨h₁, h₂⟩ := h, cases w.not_mem_need_backward_images_of_mem_orbit_set ((w.orbit_set_equiv _).symm _).prop h₁, }, { have ha := w.orbit_set_subset _ ((w.orbit_set_equiv (w.litter_perm L₁)).symm (inl (m, a))).prop, have hb := w.orbit_set_subset _ ((w.orbit_set_equiv (w.litter_perm L₂)).symm (inl (n, b))).prop, rw h at ha, refine w.litter_perm.inj_on hL₁ hL₂ _, exact eq_of_mem_litter_set_of_mem_litter_set ha.1 hb.1, }, end lemma next_forward_image_injective {L : litter} {a b : ℕ × w.need_forward_images} (h : w.next_forward_image L a = w.next_forward_image L b) : a = b := begin simp only [next_forward_image, subtype.coe_inj, embedding_like.apply_eq_iff_eq, prod.mk.inj_iff, add_left_inj] at h, exact prod.ext h.1 h.2, end lemma next_backward_image_injective {L : litter} {a b : ℕ × w.need_backward_images} (ha : a ∈ w.next_backward_image_domain L) (hb : b ∈ w.next_backward_image_domain L) (h : w.next_backward_image L a = w.next_backward_image L b) : a = b := begin obtain ⟨m, a⟩ := a, obtain ⟨n, b⟩ := b, cases m; cases n; simp only [prod.mk.inj_iff, subtype.coe_inj, embedding_like.apply_eq_iff_eq, prod.mk.inj_iff, false_and, nat.nat_zero_eq_zero, prod.mk.inj_iff, next_backward_image, prod.mk.inj_iff, eq_self_iff_true, true_and, subtype.coe_inj] at h ⊢, { exact h, }, { rw subtype.coe_eq_iff at h, obtain ⟨h₁, h₂⟩ := h, cases w.not_mem_need_backward_images_of_mem_orbit_set ((w.orbit_set_equiv _).symm _).prop h₁, }, { symmetry' at h, rw subtype.coe_eq_iff at h, obtain ⟨h₁, h₂⟩ := h, cases w.not_mem_need_backward_images_of_mem_orbit_set ((w.orbit_set_equiv _).symm _).prop h₁, }, { exact h, }, end lemma next_forward_image_injective' {L₁ L₂ : litter} {a b : ℕ × w.need_forward_images} (hL₁ : L₁ ∈ w.litter_perm.domain) (hL₂ : L₂ ∈ w.litter_perm.domain) (h : w.next_forward_image L₁ a = w.next_forward_image L₂ b) : a = b := begin cases w.next_forward_image_eq hL₁ hL₂ h, exact w.next_forward_image_injective h, end lemma next_backward_image_injective' {L₁ L₂ : litter} {a b : ℕ × w.need_backward_images} (ha : a ∈ w.next_backward_image_domain L₁) (hb : b ∈ w.next_backward_image_domain L₂) (hL₁ : L₁ ∈ w.litter_perm.domain) (hL₂ : L₂ ∈ w.litter_perm.domain) (h : w.next_backward_image L₁ a = w.next_backward_image L₂ b) : a = b := begin cases w.next_backward_image_eq ha hb hL₁ hL₂ h, exact w.next_backward_image_injective ha hb h, end lemma next_forward_image_ne_next_backward_image {L₁ L₂ : litter} {a : ℕ × w.need_forward_images} {b : ℕ × w.need_backward_images} : w.next_forward_image L₁ a ≠ w.next_backward_image L₂ b := begin obtain ⟨n, b⟩ := b, cases n, { rw [next_forward_image, next_backward_image], refine (ne_of_mem_of_not_mem _ (w.orbit_set_subset _ ((w.orbit_set_equiv _).symm _).prop).2).symm, exact or.inl b.prop.1, }, { rw [next_forward_image, next_backward_image], intro h, cases (w.orbit_set_equiv_injective h).2, }, end noncomputable def next_image_core (a : atom) (L : litter) (ha : a ∈ w.orbit_set L) : atom := (w.orbit_set_equiv L ⟨a, ha⟩).elim (w.next_backward_image L) (w.next_forward_image L) def next_image_core_domain : set atom := ⋃ L ∈ w.litter_perm.domain, coe '' {a : w.orbit_set L | (w.orbit_set_equiv L a).elim (λ b, b ∈ w.next_backward_image_domain L) (λ b, b ∈ w.next_forward_image_domain L)} lemma next_image_core_domain_small : small w.next_image_core_domain := small.bUnion w.litter_perm_domain_small (λ L hL, small.image (lt_of_le_of_lt (cardinal.mk_subtype_le _) (w.orbit_set_small L))) lemma litter_map_dom_of_mem_next_image_core_domain {a : atom} (h : a ∈ w.next_image_core_domain) : a.1 ∈ w.litter_perm.domain := begin rw next_image_core_domain at h, simp only [pfun.mem_dom, Union_exists, mem_Union, mem_image, mem_set_of_eq, set_coe.exists, subtype.coe_mk, exists_and_distrib_right, exists_eq_right, exists_prop] at h, obtain ⟨L, hL, ha, h⟩ := h, have := (w.orbit_set_subset L ha).1, rw mem_litter_set at this, rw this, exact hL, end lemma mem_orbit_set_of_mem_next_image_core_domain {a : atom} (h : a ∈ w.next_image_core_domain) : a ∈ w.orbit_set a.1 := begin rw next_image_core_domain at h, simp only [pfun.mem_dom, Union_exists, mem_Union, mem_image, mem_set_of_eq, set_coe.exists, subtype.coe_mk, exists_and_distrib_right, exists_eq_right, exists_prop] at h, obtain ⟨L, hL, ha, h⟩ := h, have := (w.orbit_set_subset L ha).1, rw mem_litter_set at this, rw this, exact ha, end lemma orbit_set_equiv_elim_of_mem_next_image_core_domain {a : atom} (h : a ∈ w.next_image_core_domain) : (w.orbit_set_equiv a.1 ⟨a, w.mem_orbit_set_of_mem_next_image_core_domain h⟩).elim (λ c, c ∈ w.next_backward_image_domain a.1) (λ c, c ∈ w.next_forward_image_domain a.1) := begin rw next_image_core_domain at h, simp only [pfun.mem_dom, Union_exists, mem_Union, mem_image, mem_set_of_eq, set_coe.exists, subtype.coe_mk, exists_and_distrib_right, exists_eq_right, exists_prop] at h, obtain ⟨L, hL, ha, h⟩ := h, have := (w.orbit_set_subset L ha).1, rw mem_litter_set at this, cases this, exact h, end lemma next_image_core_injective (a b : atom) (ha : a ∈ w.next_image_core_domain) (hb : b ∈ w.next_image_core_domain) (h : w.next_image_core a a.1 (w.mem_orbit_set_of_mem_next_image_core_domain ha) = w.next_image_core b b.1 (w.mem_orbit_set_of_mem_next_image_core_domain hb)) : a = b := begin rw [next_image_core, next_image_core] at h, obtain ⟨a', ha'⟩ := (w.orbit_set_equiv a.fst).symm.surjective ⟨a, w.mem_orbit_set_of_mem_next_image_core_domain ha⟩, obtain ⟨b', hb'⟩ := (w.orbit_set_equiv b.fst).symm.surjective ⟨b, w.mem_orbit_set_of_mem_next_image_core_domain hb⟩, have hae := w.orbit_set_equiv_elim_of_mem_next_image_core_domain ha, have hbe := w.orbit_set_equiv_elim_of_mem_next_image_core_domain hb, simp only [← ha', ← hb', equiv.apply_symm_apply] at h hae hbe, obtain (⟨m, a'⟩ | ⟨m, a'⟩) := a'; obtain (⟨n, b'⟩ | ⟨n, b'⟩) := b'; simp only [elim_inl, elim_inr, mk_mem_next_backward_image_domain, mk_mem_next_forward_image_domain] at h hae hbe, { cases w.next_backward_image_injective' _ _ _ _ h, { rw hae.2 at hbe, rw [subtype.ext_iff, subtype.coe_mk] at ha' hb', rw [← ha', ← hb', hbe.2], }, { exact hae, }, { exact hbe, }, { exact w.litter_map_dom_of_mem_next_image_core_domain ha, }, { exact w.litter_map_dom_of_mem_next_image_core_domain hb, }, }, { cases w.next_forward_image_ne_next_backward_image h.symm, }, { cases w.next_forward_image_ne_next_backward_image h, }, { cases w.next_forward_image_injective' _ _ h, { rw hae.2 at hbe, rw [subtype.ext_iff, subtype.coe_mk] at ha' hb', rw [← ha', ← hb'], exact w.orbit_set_equiv_symm_congr hbe.2, }, { exact w.litter_map_dom_of_mem_next_image_core_domain ha, }, { exact w.litter_map_dom_of_mem_next_image_core_domain hb, }, }, end def next_image_domain : set atom := (w.need_forward_images ∩ {a | a.1 ∈ w.litter_perm.domain}) ∪ w.next_image_core_domain noncomputable def next_image (a : atom) (ha : a ∈ w.next_image_domain) : atom := ha.elim' (λ ha', (w.orbit_set_equiv (w.litter_perm a.1)).symm (inr (0, ⟨a, ha'.1⟩))) (w.next_image_core a a.1 ∘ w.mem_orbit_set_of_mem_next_image_core_domain) lemma next_image_domain_small : small w.next_image_domain := small.union (small.mono (inter_subset_left _ _) w.need_forward_images_small) w.next_image_core_domain_small lemma disjoint_need_forward_images_next_image_core_domain : disjoint w.need_forward_images w.next_image_core_domain := begin rw set.disjoint_iff, rintro a ⟨ha₁, ha₂⟩, exact (w.orbit_set_subset _ (w.mem_orbit_set_of_mem_next_image_core_domain ha₂)).2 (or.inr ha₁.1), end lemma next_image_eq_of_need_forward_images (a : atom) (ha : a ∈ w.need_forward_images ∧ a.1 ∈ w.litter_perm.domain) : w.next_image a (or.inl ha) = (w.orbit_set_equiv (w.litter_perm a.1)).symm (inr (0, ⟨a, ha.1⟩)) := or.elim'_left _ _ _ ha lemma next_image_eq_of_mem_next_image_core_domain (a : atom) (ha : a ∈ w.next_image_core_domain) : w.next_image a (or.inr ha) = w.next_image_core a a.1 (w.mem_orbit_set_of_mem_next_image_core_domain ha) := begin refine or.elim'_right _ _ _ _, exact λ h, set.disjoint_right.mp w.disjoint_need_forward_images_next_image_core_domain ha h.1, end lemma orbit_set_equiv_ne_next_image_core (a b : atom) (ha : a ∈ w.need_forward_images ∧ a.fst ∈ w.litter_perm.domain) (hb : b ∈ w.next_image_core_domain) : (((w.orbit_set_equiv (w.litter_perm a.fst)).symm) (inr (0, ⟨a, ha.1⟩)) : atom) ≠ w.next_image_core b b.fst (w.mem_orbit_set_of_mem_next_image_core_domain hb) := begin obtain ⟨b', hb'⟩ := (w.orbit_set_equiv b.fst).symm.surjective ⟨b, w.mem_orbit_set_of_mem_next_image_core_domain hb⟩, rw equiv.symm_apply_eq at hb', intro h, rw next_image_core at h, rw ← hb' at h, obtain (⟨_ | n, b'⟩ | b') := b'; simp only [elim_inl, elim_inr, next_backward_image, next_forward_image] at h, { have := w.orbit_set_subset _ ((w.orbit_set_equiv _).symm _).prop, rw h at this, exact this.2 (or.inl b'.prop.1), }, { cases (w.orbit_set_equiv_injective h).2, }, { cases (w.orbit_set_equiv_injective h).2, }, end lemma next_image_injective (a b : atom) (ha : a ∈ w.next_image_domain) (hb : b ∈ w.next_image_domain) (h : w.next_image a ha = w.next_image b hb) : a = b := begin cases ha; cases hb; simp only [next_image_eq_of_need_forward_images, next_image_eq_of_mem_next_image_core_domain] at h, { have := w.orbit_set_equiv_injective h, simp only [prod.mk.inj_iff, eq_self_iff_true, subtype.mk_eq_mk, true_and] at this, exact this.2, }, { cases w.orbit_set_equiv_ne_next_image_core _ _ _ _ h, }, { cases w.orbit_set_equiv_ne_next_image_core _ _ _ _ h.symm, }, { refine w.next_image_core_injective a b ha hb h, }, end noncomputable def orbit_atom_map : atom →. atom := λ a, { dom := (w.atom_map a).dom ∨ a ∈ w.next_image_domain, get := λ h, or.elim' h (w.atom_map a).get (w.next_image a) } @[simp] lemma orbit_atom_map_dom_iff (a : atom) : (w.orbit_atom_map a).dom ↔ (w.atom_map a).dom ∨ a ∈ w.next_image_domain := iff.rfl @[simp] lemma orbit_atom_map_dom : w.orbit_atom_map.dom = w.atom_map.dom ∪ w.next_image_domain := rfl lemma disjoint_atom_map_dom_next_image_domain : disjoint w.atom_map.dom w.next_image_domain := begin rw set.disjoint_iff, rintros a ⟨h₁, h₂ | h₂⟩, { exact h₂.1.2 h₁, }, { exact (w.orbit_set_subset _ (w.mem_orbit_set_of_mem_next_image_core_domain h₂)).2 (or.inl h₁), }, end lemma orbit_atom_map_eq_of_mem_dom (a : atom) (ha : (w.atom_map a).dom) : (w.orbit_atom_map a).get (or.inl ha) = (w.atom_map a).get ha := or.elim'_left _ _ _ _ lemma orbit_atom_map_eq_of_mem_next_image_domain (a : atom) (ha : a ∈ w.next_image_domain) : (w.orbit_atom_map a).get (or.inr ha) = w.next_image a ha := or.elim'_right _ _ _ (id set.disjoint_right.mp w.disjoint_atom_map_dom_next_image_domain ha) lemma orbit_atom_map_eq_of_need_forward_images (a : atom) (ha : a ∈ w.need_forward_images ∧ a.fst ∈ w.litter_perm.domain) : (w.orbit_atom_map a).get (or.inr (or.inl ha)) = (w.orbit_set_equiv (w.litter_perm a.1)).symm (inr (0, ⟨a, ha.1⟩)) := begin unfold orbit_atom_map, simp only, rw or.elim'_right, exact w.next_image_eq_of_need_forward_images a ha, exact id set.disjoint_right.mp w.disjoint_atom_map_dom_next_image_domain (or.inl ha), end lemma orbit_atom_map_eq_of_mem_next_image_core_domain (a : atom) (ha : a ∈ w.next_image_core_domain) : (w.orbit_atom_map a).get (or.inr (or.inr ha)) = w.next_image_core a a.1 (w.mem_orbit_set_of_mem_next_image_core_domain ha) := begin unfold orbit_atom_map, simp only, rw or.elim'_right, exact w.next_image_eq_of_mem_next_image_core_domain a ha, exact id set.disjoint_right.mp w.disjoint_atom_map_dom_next_image_domain (or.inr ha), end lemma orbit_atom_map_dom_small : small w.orbit_atom_map.dom := small.union w.atom_map_dom_small w.next_image_domain_small lemma orbit_atom_map_apply_ne_of_need_forward_images ⦃a b : atom⦄ (ha : (w.atom_map a).dom) (hb : b ∈ w.need_forward_images ∧ b.fst ∈ w.litter_perm.domain) : (w.orbit_atom_map a).get (or.inl ha) ≠ (w.orbit_atom_map b).get (or.inr (or.inl hb)) := begin rw [orbit_atom_map_eq_of_mem_dom, orbit_atom_map_eq_of_need_forward_images], intro h, have := w.orbit_set_subset _ ((w.orbit_set_equiv _).symm _).prop, rw ← h at this, exact this.2 (or.inr ⟨a, ha, rfl⟩), end lemma orbit_atom_map_apply_ne_of_mem_next_image_core_domain ⦃a b : atom⦄ (ha : (w.atom_map a).dom) (hb : b ∈ w.next_image_core_domain) : (w.orbit_atom_map a).get (or.inl ha) ≠ (w.orbit_atom_map b).get (or.inr (or.inr hb)) := begin obtain ⟨b', hb'⟩ := (w.orbit_set_equiv b.fst).symm.surjective ⟨b, w.mem_orbit_set_of_mem_next_image_core_domain hb⟩, rw [orbit_atom_map_eq_of_mem_dom, orbit_atom_map_eq_of_mem_next_image_core_domain, next_image_core, ← hb', equiv.apply_symm_apply], obtain (⟨_ | n, b'⟩ | ⟨n, b'⟩) := b'; simp only [elim_inr, elim_inl, nat.nat_zero_eq_zero, next_backward_image, next_forward_image], { intro h, have := b'.prop.2, rw ← h at this, exact this ⟨a, ha, rfl⟩, }, { intro h, have := (w.orbit_set_subset _ ((w.orbit_set_equiv _).symm _).prop).2, rw ← h at this, exact this (or.inr ⟨a, ha, rfl⟩), }, { intro h, have := (w.orbit_set_subset _ ((w.orbit_set_equiv _).symm _).prop).2, rw ← h at this, exact this (or.inr ⟨a, ha, rfl⟩), }, end lemma orbit_atom_map_apply_ne ⦃a b : atom⦄ (ha : (w.atom_map a).dom) (hb : b ∈ w.next_image_domain) : (w.orbit_atom_map a).get (or.inl ha) ≠ (w.orbit_atom_map b).get (or.inr hb) := begin cases hb, exact w.orbit_atom_map_apply_ne_of_need_forward_images ha hb, exact w.orbit_atom_map_apply_ne_of_mem_next_image_core_domain ha hb, end lemma orbit_atom_map_injective ⦃a b : atom⦄ (ha : (w.orbit_atom_map a).dom) (hb : (w.orbit_atom_map b).dom) (h : (w.orbit_atom_map a).get ha = (w.orbit_atom_map b).get hb) : a = b := begin cases ha; cases hb, { rw [orbit_atom_map_eq_of_mem_dom, orbit_atom_map_eq_of_mem_dom] at h, exact w.atom_map_injective ha hb h, }, { cases w.orbit_atom_map_apply_ne ha hb h, }, { cases w.orbit_atom_map_apply_ne hb ha h.symm, }, { rw [orbit_atom_map_eq_of_mem_next_image_domain, orbit_atom_map_eq_of_mem_next_image_domain] at h, exact w.next_image_injective a b ha hb h, }, end lemma next_image_core_atom_mem_litter_map (a : atom) (ha : a ∈ w.next_image_core_domain) : w.next_image_core a a.fst (w.mem_orbit_set_of_mem_next_image_core_domain ha) ∈ litter_set (w.litter_perm a.fst) := begin have hL := w.litter_map_dom_of_mem_next_image_core_domain ha, have := w.mem_orbit_set_of_mem_next_image_core_domain ha, obtain ⟨a', ha'⟩ := (w.orbit_set_equiv a.fst).symm.surjective ⟨a, w.mem_orbit_set_of_mem_next_image_core_domain ha⟩, have := w.orbit_set_equiv_elim_of_mem_next_image_core_domain ha, rw [next_image_core], rw [← ha', equiv.apply_symm_apply] at this ⊢, obtain (⟨_ | n, a'⟩ | ⟨n, a'⟩) := a'; simp only [elim_inr, elim_inl, nat.nat_zero_eq_zero, next_backward_image, next_forward_image, mk_mem_next_backward_image_domain, mk_mem_next_forward_image_domain, function.iterate_one] at this ⊢, { have ha'' := this.2.symm, rw local_perm.eq_symm_apply at ha'', { exact ha''.symm, }, { exact hL, }, { exact this.1, }, }, exact (w.orbit_set_subset _ ((w.orbit_set_equiv _).symm _).prop).1, exact (w.orbit_set_subset _ ((w.orbit_set_equiv _).symm _).prop).1, end lemma next_image_core_not_mem_ran (a : atom) (ha : a ∈ w.next_image_core_domain) : w.next_image_core a a.fst (w.mem_orbit_set_of_mem_next_image_core_domain ha) ∉ w.atom_map.ran := begin rintro ⟨b, hb₁, hb₂⟩, rw next_image_core at hb₂, obtain ⟨a', ha'⟩ := (w.orbit_set_equiv a.fst).symm.surjective ⟨a, w.mem_orbit_set_of_mem_next_image_core_domain ha⟩, rw [← ha', equiv.apply_symm_apply] at hb₂, obtain (⟨_ | n, a'⟩ | ⟨n, a'⟩) := a'; simp only [elim_inr, elim_inl, nat.nat_zero_eq_zero, next_backward_image, next_forward_image, mk_mem_next_backward_image_domain, mk_mem_next_forward_image_domain, function.iterate_one] at hb₂, { exact a'.prop.2 ⟨b, hb₁, hb₂⟩, }, all_goals { have := w.orbit_set_subset _ ((w.orbit_set_equiv _).symm _).prop, rw ← hb₂ at this, exact this.2 (or.inr ⟨b, hb₁, rfl⟩), }, end lemma next_image_core_atom_mem (hdiff : ∀ L hL, ((w.litter_map L).get hL : set atom) ∆ litter_set ((w.litter_map L).get hL).1 ⊆ w.atom_map.ran) (a : atom) (ha : a ∈ w.next_image_core_domain) (L : litter) (hL : (w.litter_map L).dom) : a.fst = L ↔ w.next_image_core a a.fst (w.mem_orbit_set_of_mem_next_image_core_domain ha) ∈ (w.litter_map L).get hL := begin have hamem := w.mem_orbit_set_of_mem_next_image_core_domain ha, have ha' := w.next_image_core_atom_mem_litter_map a ha, rw mem_litter_set at ha', split, { rintro rfl, have := not_mem_subset (hdiff _ hL) (w.next_image_core_not_mem_ran a ha), simp only [mem_symm_diff, set_like.mem_coe, mem_litter_set, not_or_distrib, not_and_distrib, not_not] at this, refine this.2.resolve_left (not_not.mpr _), rw ha', rw w.litter_perm_apply_eq _ hL, rw w.rough_litter_map_or_else_of_dom, }, { intro h, have hL' := w.litter_perm_apply_eq L hL, rw w.rough_litter_map_or_else_of_dom hL at hL', have := not_mem_subset (hdiff _ hL) (w.next_image_core_not_mem_ran a ha), simp only [mem_symm_diff, set_like.mem_coe, mem_litter_set, not_not, h, true_and, not_true, and_false, or_false] at this, rw [ha', ← hL', ← local_perm.eq_symm_apply, local_perm.left_inv] at this, exact this, exact or.inl (or.inl (or.inl hL)), exact w.litter_map_dom_of_mem_next_image_core_domain ha, exact local_perm.map_domain _ (or.inl (or.inl (or.inl hL))), }, end lemma orbit_set_equiv_atom_mem (hdiff : ∀ L hL, ((w.litter_map L).get hL : set atom) ∆ litter_set ((w.litter_map L).get hL).1 ⊆ w.atom_map.ran) (a : atom) (ha : a ∈ w.need_forward_images ∧ a.fst ∈ w.litter_perm.domain) (L : litter) (hL : (w.litter_map L).dom) : a.fst = L ↔ ((w.orbit_set_equiv (w.litter_perm a.fst)).symm (inr (0, ⟨a, ha.1⟩)) : atom) ∈ (w.litter_map L).get hL := begin have ha' : _ ∧ _ := w.orbit_set_subset _ ((w.orbit_set_equiv (w.litter_perm a.fst)).symm (inr (0, ⟨a, ha.1⟩))).prop, rw mem_litter_set at ha', split, { rintro rfl, have := not_mem_subset (hdiff _ hL) _, simp only [mem_symm_diff, set_like.mem_coe, mem_litter_set, not_or_distrib, not_and_distrib, not_not] at this, refine this.2.resolve_left (not_not.mpr _), { rw ha'.1, rw w.litter_perm_apply_eq _ hL, rw w.rough_litter_map_or_else_of_dom, }, { exact ha'.2 ∘ or.inr, }, }, { intro h, have := @not_mem_subset _ ((w.orbit_set_equiv (w.litter_perm a.fst)).symm (inr (0, ⟨a, ha.1⟩)) : atom) _ _ (hdiff L hL) (ha'.2 ∘ or.inr), simp only [mem_symm_diff, h, set_like.mem_coe, mem_litter_set, true_and, not_true, and_false, or_false, not_not] at this, rw [ha'.1, ← rough_litter_map_or_else_of_dom, ← litter_perm_apply_eq, ← local_perm.eq_symm_apply, local_perm.left_inv] at this, exact this, { exact or.inl (or.inl (or.inl hL)), }, { exact ha.2, }, { exact w.litter_perm.map_domain (or.inl (or.inl (or.inl hL))), }, { exact hL, }, }, end lemma orbit_atom_mem (hdiff : ∀ L hL, ((w.litter_map L).get hL : set atom) ∆ litter_set ((w.litter_map L).get hL).1 ⊆ w.atom_map.ran) (a : atom) (ha : (w.orbit_atom_map a).dom) (L : litter) (hL : (w.litter_map L).dom) : a.fst = L ↔ (w.orbit_atom_map a).get ha ∈ (w.litter_map L).get hL := begin obtain ha | ha | ha := ha, { rw orbit_atom_map_eq_of_mem_dom, exact w.atom_mem a ha L hL, }, { rw orbit_atom_map_eq_of_need_forward_images, exact w.orbit_set_equiv_atom_mem hdiff a ha L hL, }, { rw orbit_atom_map_eq_of_mem_next_image_core_domain, rw w.next_image_core_atom_mem hdiff a ha L hL, }, end noncomputable def fill_atom_orbits (hdiff : ∀ L hL, ((w.litter_map L).get hL : set atom) ∆ litter_set ((w.litter_map L).get hL).1 ⊆ w.atom_map.ran) : weak_near_litter_approx := { atom_map := w.orbit_atom_map, litter_map := w.litter_map, atom_map_dom_small := w.orbit_atom_map_dom_small, litter_map_dom_small := w.litter_map_dom_small, atom_map_injective := w.orbit_atom_map_injective, litter_map_injective := w.litter_map_injective, atom_mem := w.orbit_atom_mem hdiff, } variables {w} {hdiff : ∀ L hL, ((w.litter_map L).get hL : set atom) ∆ litter_set ((w.litter_map L).get hL).1 ⊆ w.atom_map.ran} @[simp] lemma fill_atom_orbits_atom_map : (w.fill_atom_orbits hdiff).atom_map = w.orbit_atom_map := rfl @[simp] lemma fill_atom_orbits_litter_map : (w.fill_atom_orbits hdiff).litter_map = w.litter_map := rfl lemma subset_orbit_atom_map_dom : w.atom_map.dom ⊆ w.orbit_atom_map.dom := subset_union_left _ _ lemma subset_orbit_atom_map_ran : w.atom_map.ran ⊆ w.orbit_atom_map.ran := begin rintro _ ⟨a, ha, rfl⟩, exact ⟨a, subset_orbit_atom_map_dom ha, w.orbit_atom_map_eq_of_mem_dom _ _⟩, end lemma fst_mem_litter_perm_domain_of_mem_map ⦃L : litter⦄ (hL : (w.litter_map L).dom) ⦃a : atom⦄ (ha : a ∈ (w.litter_map L).get hL) : a.1 ∈ w.litter_perm.domain := begin by_cases a.1 = ((w.litter_map L).get hL).1, { rw h, refine or.inl (or.inl (or.inr ⟨L, hL, _⟩)), rw rough_litter_map_or_else_of_dom, }, { by_cases h' : a.fst ∈ w.litter_perm'.domain, exact or.inl h', exact or.inr ⟨banned_litter.diff L hL a ⟨ha, h⟩, h'⟩, }, end lemma fst_mem_litter_perm_domain_of_dom ⦃a : atom⦄ (ha : a ∈ w.atom_map.dom) : a.fst ∈ w.litter_perm.domain := begin by_cases h' : a.fst ∈ w.litter_perm'.domain, exact or.inl h', exact or.inr ⟨banned_litter.atom_dom a ha, h'⟩, end lemma fst_mem_litter_perm_domain_of_ran ⦃a : atom⦄ (ha : a ∈ w.atom_map.ran) : a.fst ∈ w.litter_perm.domain := begin by_cases h' : a.fst ∈ w.litter_perm'.domain, exact or.inl h', obtain ⟨b, hb, rfl⟩ := ha, exact or.inr ⟨banned_litter.atom_map b hb, h'⟩, end lemma fill_atom_orbits_precise (hdiff : ∀ L hL, ((w.litter_map L).get hL : set atom) ∆ litter_set ((w.litter_map L).get hL).1 ⊆ w.atom_map.ran) : precise (w.fill_atom_orbits hdiff) := begin intros L hL, constructor, { exact subset_trans (hdiff L hL) subset_orbit_atom_map_ran, }, { intros a ha ha', simp only [fill_atom_orbits_atom_map, fill_atom_orbits_litter_map, mem_litter_set, orbit_atom_map_dom_iff] at *, obtain ha | ha | ha := ha, { have := w.orbit_atom_map_eq_of_mem_dom a ha, generalize_proofs at this ha' ⊢, rw [this, or_iff_not_imp_left], intro hmap, have hfwd : (w.atom_map a).get ha ∈ w.need_forward_images := ⟨⟨a, _, rfl⟩, hmap⟩, refine or.inl ⟨hfwd, or.inl (or.inl _)⟩, refine mem_of_eq_of_mem _ (or.inl hL), rw [← ha', this], }, { refine or.inr (or.inr ⟨_, ⟨L, rfl⟩, _⟩), simp only [pfun.mem_dom, Union_exists, mem_Union, mem_image, mem_set_of_eq, set_coe.exists, subtype.coe_mk, exists_and_distrib_right, exists_eq_right, exists_prop], have haL : L = w.litter_perm a.fst, { have := (congr_arg prod.fst (w.orbit_atom_map_eq_of_need_forward_images a ha)).symm.trans ha', rw ← this, exact (w.orbit_set_subset _ ((w.orbit_set_equiv _).symm _).prop).1, }, refine ⟨or.inl (or.inl (or.inl hL)), _, _⟩, { refine mem_of_eq_of_mem (w.orbit_atom_map_eq_of_need_forward_images a ha) _, rw haL, exact ((w.orbit_set_equiv _).symm _).prop, }, { have := w.orbit_atom_map_eq_of_need_forward_images a ha, obtain ⟨hm₁, hm₂⟩ := subtype.coe_eq_iff.mp this.symm, rw [equiv.symm_apply_eq, w.orbit_set_equiv_congr hm₁ haL.symm] at hm₂, refine mem_of_eq_of_mem hm₂.symm _, change sum.elim (λ b, b ∈ w.next_backward_image_domain L) (λ b, b ∈ w.next_forward_image_domain L) (inr (0, ⟨a, ha.1⟩)), refine ⟨ha.2, _⟩, simp only [subtype.coe_mk, function.iterate_one], exact haL.symm, }, }, { have := w.orbit_atom_map_eq_of_mem_next_image_core_domain a ha, generalize_proofs at this ha' ⊢, rw [this, next_image_core], obtain ⟨_, ⟨L', rfl⟩, _, ⟨hL', rfl⟩, a, hbL, rfl⟩ := ha, set b := w.orbit_set_equiv L' a with hb, clear_value b, simp only [mem_set_of_eq] at hbL, rw ← hb at hbL, have haL' := (w.orbit_set_subset _ a.prop).1, rw mem_litter_set at haL', have := w.orbit_set_equiv_congr (w.mem_orbit_set_of_mem_next_image_core_domain _) (w.orbit_set_subset _ a.prop).1, rw subtype.coe_eta at this, rw [this, ← hb], obtain (⟨_ | n, b⟩ | ⟨n, b⟩) := b; simp only [need_backward_images, need_forward_images, elim_inl, elim_inr, next_backward_image, next_forward_image] at hbL ⊢, { exact or.inl b.prop.1, }, { refine or.inr (or.inr _), have hbL' := hbL.2, symmetry' at hbL', rw [function.iterate_succ_apply', local_perm.eq_symm_apply _ hL' (w.litter_perm.symm.iterate_domain hbL.1)] at hbL', refine ⟨_, ⟨w.litter_perm.symm^[n + 1] (b : atom).1, rfl⟩, _, ⟨_, rfl⟩, ⟨(w.orbit_set_equiv (w.litter_perm (a : atom).1)).symm (inl (n, b)), _⟩, _⟩, { exact w.litter_perm.symm.iterate_domain hbL.1, }, { rw ← hbL', have := (((w.orbit_set_equiv (w.litter_perm (a : atom).1)).symm (inl (n, b)))).prop, rw haL' at this ⊢, exact this, }, { simp only [function.comp_app, mem_set_of_eq, subtype.coe_mk, eq_self_iff_true, and_true], rw [w.orbit_set_equiv_congr _ hbL'.symm, w.orbit_set_equiv_congr _ (congr_arg w.litter_perm haL'.symm)], simp only [subtype.coe_eta, equiv.apply_symm_apply, elim_inl], exact ⟨hbL.1, rfl⟩, }, }, { refine or.inr (or.inr _), refine ⟨_, ⟨w.litter_perm^[n + 2] (b : atom).1, rfl⟩, _, ⟨_, rfl⟩, ⟨(w.orbit_set_equiv (w.litter_perm (a : atom).1)).symm (inr (n + 1, b)), _⟩, _⟩, { exact w.litter_perm.iterate_domain hbL.1, }, { rw [function.iterate_succ_apply', hbL.2, haL'], exact ((w.orbit_set_equiv _).symm _).prop, }, { simp only [function.comp_app, mem_set_of_eq, subtype.coe_mk, eq_self_iff_true, and_true], have := congr_arg w.litter_perm hbL.2, rw ← function.iterate_succ_apply' w.litter_perm (n + 1) at this, rw [w.orbit_set_equiv_congr _ this, w.orbit_set_equiv_congr _ (congr_arg w.litter_perm haL'.symm)], simp only [function.iterate_succ, function.comp_app, subtype.coe_eta, equiv.apply_symm_apply, elim_inr], exact ⟨hbL.1, rfl⟩, }, }, { refine ⟨_, ⟨L', rfl⟩, _, ⟨hL', rfl⟩, a, _, rfl⟩, rw [mem_set_of_eq, ← hb], exact hbL, }, }, }, { rw fill_atom_orbits_litter_map at hL, rintros a ⟨ha₁ | ⟨ha₁, ha₁'⟩ | ha₁, ha₂⟩; simp only [fill_atom_orbits_atom_map, fill_atom_orbits_litter_map, orbit_atom_map_dom, mem_inter_iff, mem_union, set_like.mem_coe] at *, { by_cases ha₃ : a ∈ w.atom_map.ran, { obtain ⟨b, hb₁, hb₂⟩ := ha₃, refine ⟨b, or.inl hb₁, _⟩, rw orbit_atom_map_eq_of_mem_dom, exact hb₂, }, { refine ⟨(w.orbit_set_equiv (w.litter_perm.symm a.1)).symm (inl (0, ⟨a, ha₁, ha₃⟩)), _, _⟩, { refine or.inr (or.inr ⟨_, ⟨w.litter_perm.symm a.1, rfl⟩, _, ⟨_, rfl⟩, _⟩), { exact w.litter_perm.symm.map_domain (fst_mem_litter_perm_domain_of_mem_map hL ha₂), }, refine ⟨_, _, rfl⟩, simp only [mem_set_of_eq, equiv.apply_symm_apply, elim_inl], exact ⟨fst_mem_litter_perm_domain_of_mem_map hL ha₂, rfl⟩, }, { rw [orbit_atom_map_eq_of_mem_next_image_core_domain, next_image_core], have : (((w.orbit_set_equiv (w.litter_perm.symm a.fst)).symm) (inl (0, ⟨a, _⟩)) : atom).fst = w.litter_perm.symm a.fst, { exact (w.orbit_set_subset _ ((w.orbit_set_equiv _).symm _).prop).1, exact ⟨ha₁, ha₃⟩, }, rw w.orbit_set_equiv_congr _ this, simp only [equiv.apply_symm_apply, elim_inl, subtype.coe_eta, next_backward_image, subtype.coe_mk], }, }, }, { obtain ⟨⟨b, hb₁, hb₂⟩, ha₁⟩ := ha₁, rw ← hb₂, refine ⟨b, or.inl hb₁, _⟩, rw orbit_atom_map_eq_of_mem_dom, }, { obtain ⟨a', ha'⟩ := (w.orbit_set_equiv a.fst).symm.surjective ⟨a, w.mem_orbit_set_of_mem_next_image_core_domain ha₁⟩, obtain (⟨n, a'⟩ | ⟨_ | n, a'⟩) := a', { have : ((w.orbit_set_equiv (w.litter_perm.symm^[n + 2] (a' : atom).fst)).symm (inl (n + 1, a')) : atom) ∈ w.next_image_core_domain, { refine ⟨_, ⟨w.litter_perm.symm^[n + 2] (a' : atom).fst, rfl⟩, _, ⟨_, rfl⟩, _⟩, exact w.litter_perm.symm.iterate_domain (fst_mem_litter_perm_domain_of_dom a'.prop.1), refine ⟨_, _, rfl⟩, simp only [mem_set_of_eq, equiv.apply_symm_apply, elim_inl], exact ⟨fst_mem_litter_perm_domain_of_dom a'.prop.1, rfl⟩, }, refine ⟨_, or.inr (or.inr this), _⟩, rw orbit_atom_map_eq_of_mem_next_image_core_domain, rw next_image_core, have : (((w.orbit_set_equiv (w.litter_perm.symm^[n + 2] (a' : atom).fst)).symm) (inl (n + 1, a')) : atom).fst = (w.litter_perm.symm^[n + 2] (a' : atom).fst) := (w.orbit_set_subset _ ((w.orbit_set_equiv _).symm _).prop).1, rw w.orbit_set_equiv_congr _ this, simp only [subtype.coe_eta, equiv.apply_symm_apply, elim_inl, next_backward_image], have := congr_arg subtype.val ha', simp only [subtype.val_eq_coe] at this, rw ← this, refine w.orbit_set_equiv_symm_congr _, have := (w.orbit_set_subset _ ((w.orbit_set_equiv _).symm _).prop).1, rw mem_litter_set at this, rw this, have := w.orbit_set_equiv_elim_of_mem_next_image_core_domain ha₁, rw ← ha' at this, simp only [equiv.apply_symm_apply, elim_inl, next_backward_image_domain, function.comp_app, mem_set_of_eq] at this, rw [← this.2, function.iterate_succ_apply', local_perm.right_inv], exact w.litter_perm.symm.iterate_domain this.1, }, { have := w.orbit_set_equiv_elim_of_mem_next_image_core_domain ha₁, rw ← ha' at this, simp only [equiv.apply_symm_apply, elim_inr, next_forward_image_domain, function.comp_app, mem_set_of_eq, function.iterate_one] at this, refine ⟨a', or.inr (or.inl ⟨a'.prop, this.1⟩), _⟩, rw [orbit_atom_map_eq_of_need_forward_images, w.orbit_set_equiv_symm_congr this.2, subtype.coe_eta, ha'], refl, }, { have : ((w.orbit_set_equiv (w.litter_perm^[n + 1] (a' : atom).fst)).symm (inr (n, a')) : atom) ∈ w.next_image_core_domain, { refine ⟨_, ⟨w.litter_perm^[n + 1] (a' : atom).fst, rfl⟩, _, ⟨_, rfl⟩, _⟩, exact w.litter_perm.iterate_domain (fst_mem_litter_perm_domain_of_ran a'.prop.1), refine ⟨_, _, rfl⟩, simp only [mem_set_of_eq, equiv.apply_symm_apply, elim_inl], exact ⟨fst_mem_litter_perm_domain_of_ran a'.prop.1, rfl⟩, }, refine ⟨_, or.inr (or.inr this), _⟩, rw orbit_atom_map_eq_of_mem_next_image_core_domain, rw next_image_core, have : (((w.orbit_set_equiv (w.litter_perm^[n + 1] (a' : atom).fst)).symm) (inr (n, a')) : atom).fst = (w.litter_perm^[n + 1] (a' : atom).fst) := (w.orbit_set_subset _ ((w.orbit_set_equiv _).symm _).prop).1, rw w.orbit_set_equiv_congr _ this, simp only [subtype.coe_eta, equiv.apply_symm_apply, elim_inl, next_backward_image], have := congr_arg subtype.val ha', simp only [subtype.val_eq_coe] at this, rw ← this, refine w.orbit_set_equiv_symm_congr _, have := (w.orbit_set_subset _ ((w.orbit_set_equiv _).symm _).prop).1, rw mem_litter_set at this, rw this, have := w.orbit_set_equiv_elim_of_mem_next_image_core_domain ha₁, rw ← ha' at this, simp only [equiv.apply_symm_apply, elim_inr, next_forward_image_domain, function.comp_app, mem_set_of_eq] at this, rw [← this.2, function.iterate_succ_apply', function.iterate_succ_apply', function.iterate_succ_apply'], }, }, }, end end weak_near_litter_approx end con_nf
-- See: https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/OO.20polymorphism.3F/near/297629381 namespace O4 inductive Geo_Type | Point2D | Point3D | Point4D | Square2D deriving DecidableEq open Geo_Type structure Slots_Point2D where (x y : Float) deriving Repr structure Slots_Point3D extends Slots_Point2D where z : Float deriving Repr structure Slots_Point4D extends Slots_Point3D where w : Float deriving Repr structure Slots_Square2D extends Slots_Point2D where width : Float deriving Repr universe u def Geo_Type.Slots : Geo_Type → Type | Point2D => Slots_Point2D | Point3D => Slots_Point3D | Point4D => Slots_Point4D | Square2D => Slots_Square2D open Geo_Type def toRepr : (T : Geo_Type) → Repr T.Slots | Point2D => instReprSlots_Point2D | Point3D => instReprSlots_Point3D | Point4D => instReprSlots_Point4D | Square2D => instReprSlots_Square2D /-- Get casting function to first type from second type -/ def Geo_Type.cast : (t : Geo_Type) → (t' : Geo_Type) → Option (t'.Slots → t.Slots) | Point2D, Point2D => some id | Point2D, Point3D => some (λ x => x.toSlots_Point2D) | Point3D, Point3D => some id | Point2D, Point4D => some (λ x => x.toSlots_Point2D) | Point3D, Point4D => some (λ x => x.toSlots_Point3D) | Point4D, Point4D => some id | Point2D, Square2D => some (λ x => x.toSlots_Point2D) | Square2D, Square2D => some id | _, _ => none /-- Whether the second type is a subtype of the first. -/ def Geo_Type.supertype (t t' : Geo_Type) : Bool := (t.cast t').isSome theorem Geo_Type.supertype.trans (h : Geo_Type.supertype t t') (h' : Geo_Type.supertype t' t'') : Geo_Type.supertype t t'' := by cases t all_goals cases t' all_goals cases t'' all_goals simp at h try simp at h' try simp def Option.get : (x : Option α) → x.isSome → α | some v, _ => v | none, h => by simp [Option.isSome] at h /-- Get the cast function from a proof that `t'` is a subtype of `t`. -/ def Geo_Type.supertype.cast (h : Geo_Type.supertype t t') : t'.Slots → t.Slots := Option.get (Geo_Type.cast t t') h /-- Objects of subtype t -/ structure Obj (t : Geo_Type) where ty : Geo_Type sub : Geo_Type.supertype t ty slots : ty.Slots instance : Coe Slots_Point2D (Obj Point2D) where coe s := ⟨Point2D, rfl, s⟩ instance : Coe Slots_Point3D (Obj Point3D) where coe s := ⟨Point3D, rfl, s⟩ instance : Coe Slots_Point4D (Obj Point4D) where coe s := ⟨Point4D, rfl, s⟩ instance : Coe Slots_Square2D (Obj Square2D) where coe s := ⟨Square2D, rfl, s⟩ /-- Extract the slots from an `Obj`. -/ def Obj.get (o : Obj t) : t.Slots := Geo_Type.supertype.cast o.sub o.slots /-- Cast up, which can be done statically. -/ def Obj.cast_up (o : Obj t) (h : Geo_Type.supertype t' t := by rfl) : Obj t' where ty := o.ty sub := Geo_Type.supertype.trans h o.sub slots := o.slots def Obj.can_cast (o : Obj t) (t' : Geo_Type) : Bool := Geo_Type.supertype t' o.ty /-- Cast up or down using run-time information. -/ def Obj.cast (o : Obj t) (h : o.can_cast t') : Obj t' where ty := o.ty sub := h slots := o.slots /-- Example using a run-time cast. -/ def Obj.get_w (o : Obj Point2D) : Float := if h : o.can_cast Point4D then (o.cast h).get.w else 0 #eval ({x := 1, y := 2 : Slots_Point2D} : Obj Point2D).get_w -- 0.000000 #eval Id.run do let p := ({x := 1, y := 2, z := 3, w := 4 : Slots_Point4D} : Obj Point4D) return p.cast_up.get_w -- 4.000000 def s2: Slots_Point2D := {x := 1, y := 2} #eval s2 def o2: Obj Point2D := s2 #eval o2.slots end O4
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <vector> #include <deque> #include "NR.h" void export_Spike2(); void export_PSP_Kernel2(); void export_SpikeTrain(); void export_Tempotron(); void export_SpikingTempotron(); void setRNGenSeed(long seed) { NR::Rnd.setSeed(seed); } long getRNGenSeed() {return NR::Rnd.getSeed();} using namespace boost::python; template< template<class,class> class Container, class T > void export_container(const char * name){ class_<Container<T,std::allocator<T> > >(name) .def(vector_indexing_suite< Container<T,std::allocator<T> > >()) .def(init<int,T>()) .def(init<int>()) ; } BOOST_PYTHON_MODULE(_ST) { export_container<std::vector,double>("__vecdub"); export_container<std::deque,double>("__dequedub"); export_container<std::deque,long double>("__dequelongdouble"); export_container<std::deque,short>("__dequeshort"); export_container<std::vector, std::vector<double> >("__vecvecdouble"); export_container<std::deque, std::vector<double> >("__dequevecdouble"); export_container<std::deque, std::deque<double> >("__dequedequedouble"); def("setRNGenSeed",&setRNGenSeed); def("getRNGenSeed",&getRNGenSeed); export_Spike2(); export_PSP_Kernel2(); export_SpikeTrain(); export_Tempotron(); export_SpikingTempotron(); }
function [inference] = tapas_sem_hier_inference(inference, pars) %% % % [email protected] % copyright (C) 2016 % if ~isfield(inference, 'estimate_method') inference.estimate_method = @tapas_mcmc_blocked_estimate; end if ~isfield(inference, 'initialize_states') inference.initialize_states = @tapas_sem_hier_init_states; end if ~isfield(inference, 'initialize_state') inference.initialize_state = @tapas_sem_hier_init_state; end if ~isfield(inference, 'sampling_methods') inference.sampling_methods = { @(d, m, i, s) tapas_mh_mc3_tempering_sample_node(d, m, i, s, 2), ... @(d, m, i, s) tapas_sampler_dlinear_gibbs_node(d, m, i, s, 3), ... @tapas_sampler_mc3_tempering ... ... Use population mcmc step with generalized % Temperature for possibly Bayesian predictive distribution. }; end if ~isfield(inference, 'metasampling_methods') inference.metasampling_methods = {@tapas_mcmc_meta_diagnostics, ... @tapas_mcmc_meta_adaptive, ... % @tapas_mcmc_meta_adaptive_ti, ... }; end if ~isfield(inference, 'get_stored_state') inference.get_stored_state = @tapas_sem_hier_get_stored_state; end if ~isfield(inference, 'prepare_posterior') inference.prepare_posterior = @tapas_sem_hier_prepare_posterior; end if ~isfield(inference, 'mh_sampler') inference.mh_sampler = cell(4, 1); end if ~isfield(inference.mh_sampler{2}, 'propose_sample') inference.mh_sampler{2}.propose_sample = ... @tapas_mh_mc3_propose_gaussian_sample; inference.mh_sampler{2}.ar_rule = ... @tapas_mh_mc3g_arc; end if ~isfield(inference, 'niter') if isfield(pars, 'niter') inference.niter = pars.niter; else inference.niter = 5000; end end if ~isfield(inference, 'nburnin') if isfield(pars, 'nburnin') inference.nburnin = pars.nburnin; else inference.nburnin = 5000; end end if ~isfield(inference, 'mc3it') if isfield(pars, 'mc3it') inference.mc3it = pars.mc3it; else inference.mc3it = 10; end end if ~isfield(inference, 'thinning') if isfield(pars, 'thinning') inference.thinning = pars.thinning; else inference.thinning = 0; end end if ~isfield(inference, 'ndiag') if isfield(pars, 'ndiag') inference.ndiag = pars.ndiag; else inference.ndiag = 200; end end % Scale of the kernel if ~isfield(inference, 'kernel_scale') inference.kernel_scale = 0.1 * 0.1; end end
Neil Midgley , writing for The Daily Telegraph , hailed Rachel as " one of six latte @-@ swilling young New Yorkers who helped Friends redefine the kind of relationships that could form the heart of a US sitcom " . According to Jennifer Aniston : From Friends to Films author Kim Etingoff , audiences wanted to see Rachel " figure out life , " allowing the character to become " a favorite of many Friends fans throughout all ten seasons " . Writing for TalkTalk , Dominic Wills echoed that Rachel " became the general favourite " , while " No one had a bad word to say about Jennifer Aniston " . Rachel would go on to become the show 's breakout character , and is often revered as one of the greatest characters in television history . Us Weekly magazine ranked Rachel the most beloved television character of the past 20 years , citing her as " one of TV 's most endearing personalities " , while Entertainment Weekly ranked the character sixth on a similar list . AOL TV ranked Rachel among television 's hundred " Greatest Women " at number 23 , with author Kim Potts penning , " Rachel became one of viewers ' favorite Friends because she grew from what could have been a one @-@ note character ... into a more independent , caring pal " . CBS News placed Rachel and the cast of Friends at number 31 on its list of the " 50 greatest TV characters " . BuddyTV ranked Rachel the 15th funniest female character in sitcom history . <unk> collectively ranked Rachel , Monica and Phoebe 11th , 12th and 13th on the website 's list of the " Top 16 Female TV Characters of All Time " . Writing for Entertainmentwise , Georgina Littlejohn believes that Rachel 's influence is evident in the character Penny in the sitcom The Big Bang Theory , noting that both characters are " blonde , cute , funny , likeable girls @-@ next @-@ door " . Several baby name books and websites now commonly associate the name " Rachel " with the character . According to <unk> , the name peaked in popularity in 1996 , during the second season of Friends , becoming the ninth most popular female name in the United States that year .
function a = r8vec_permute_cyclic ( n, k, a ) %*****************************************************************************80 % %% R8VEC_PERMUTE_CYCLIC performs a cyclic permutation of an R8VEC. % % Discussion: % % An R8VEC is a vector of R8's. % % For 0 <= K < N, this function cyclically permutes the input vector % to have the form % % ( A(K+1), A(K+2), ..., A(N), A(1), ..., A(K) ) % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 22 August 2010 % % Author: % % John Burkardt % % Parameters: % % Input, integer N, the number of objects. % % Input, integer K, the increment used. % % Input/output, real A(N), the array to be permuted. % b = zeros ( size ( a ) ); for i = 1 : n ipk = i4_wrap ( i + k, 1, n ); b(i) = a(ipk); end a(1:n) = b(1:n); return end
#include("../src/CGP.jl") export p, funcs, MyInt, Ones, goallist2, goallist3 #using Base.Test #using Main.CGP #const MyInt = UInt16 # Also set in CGP.jl numinputs = 2 numoutputs = 2 nodearity = 2 numinteriors = 5 numlevelsback = 8 const context = construct_contexts(numinputs)[numinputs] goal1 = MyInt[ 0xb, 0xe ] goal2 = MyInt[ 0x6, 0x9 ] goal3 = MyInt[ 0xa, 0xe ] goallist2 = [goal1, goal2,goal3] goallist3 = [[0x50], [ 0x05], [ 0xf5], [ 0xa0], [ 0xe0], [ 0x0e], [ 0xf1], [ 0x80], [ 0x08], [ 0xfa]] p = Parameters(numinputs, numoutputs, nodearity, numinteriors, numlevelsback) const Ones = Main.CGP.construct_ones(numinputs)[numinputs] #const funcs = default_funcs() println("SetParams: ") print_parameters(p)
19/06/2014 · Today the average American’s health insurance payments fluctuate once a year. Imagine if that rate changed each day, determined in part by a sensor-rich. Incredibly, some insurers are even raising rates for autonomous vehicles. ROOT is a registered service mark of Root Insurance Company, Columbus, OH. This story. to tailor and design policy premiums. But not only auto insurers use big data and. If you are 60-69 your term life insurance premiums start at $76 and $100 for women and men respectively. See rates for other ages as well. a car. Nothing mind-blowing, but the kind of cheap, solid, basic transportation that’s increasingly hard to find in America as we kill off our small cars and move to. Car thefts increased last year. insurers when assessing the price of your motor insurance policy. “In recent years the average cost of motor insurance has been. Low-income people with diabetes are better able to afford their medications. Car thefts have increased by over. insurers when assessing the price of your motor insurance policy, in recent years the average cost of motor insurance has been. Campus Health Health Education Alcohol, Tobacco, and Other Drugs Smoking Tobacco. People begin smoking for many reasons—some start smoking to try to fit in with.
fun1=function(n1,n2) { add=(n2+5) print(add) } fun1(6,) fun2=function(n3,n4) { add=(n3+5) print(add) print(6,) } fun2(6) vec=c(1:3) sq=function(no) { sqr=no*no return(sqr) } sq(vec) mat=matrix(1:9,3,3,byrow=TRUE) sq(mat) fun3=function(no1) { 5*no1-1 } fun3(5)
[GOAL] α : Type u_1 β : Type u_2 X Y Z : Bipointed f : Bipointed.Hom X Y g : Bipointed.Hom Y Z ⊢ (g.toFun ∘ f.toFun) X.toProd.fst = Z.toProd.fst [PROOFSTEP] rw [Function.comp_apply, f.map_fst, g.map_fst] [GOAL] α : Type u_1 β : Type u_2 X Y Z : Bipointed f : Bipointed.Hom X Y g : Bipointed.Hom Y Z ⊢ (g.toFun ∘ f.toFun) X.toProd.snd = Z.toProd.snd [PROOFSTEP] rw [Function.comp_apply, f.map_snd, g.map_snd] [GOAL] α : Type u_1 β : Type u_2 X : Pointed Y : Bipointed f : pointedToBipointedFst.obj X ⟶ Y ⊢ (fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) f) = f [PROOFSTEP] apply Bipointed.Hom.ext [GOAL] case toFun α : Type u_1 β : Type u_2 X : Pointed Y : Bipointed f : pointedToBipointedFst.obj X ⟶ Y ⊢ ((fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) f)).toFun = f.toFun [PROOFSTEP] funext x [GOAL] case toFun.h α : Type u_1 β : Type u_2 X : Pointed Y : Bipointed f : pointedToBipointedFst.obj X ⟶ Y x : (pointedToBipointedFst.obj X).X ⊢ Bipointed.Hom.toFun ((fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) f)) x = Bipointed.Hom.toFun f x [PROOFSTEP] cases x [GOAL] case toFun.h.none α : Type u_1 β : Type u_2 X : Pointed Y : Bipointed f : pointedToBipointedFst.obj X ⟶ Y ⊢ Bipointed.Hom.toFun ((fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) f)) none = Bipointed.Hom.toFun f none [PROOFSTEP] exact f.map_snd.symm [GOAL] case toFun.h.some α : Type u_1 β : Type u_2 X : Pointed Y : Bipointed f : pointedToBipointedFst.obj X ⟶ Y val✝ : X.X ⊢ Bipointed.Hom.toFun ((fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) f)) (some val✝) = Bipointed.Hom.toFun f (some val✝) [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 X'✝ X✝ : Pointed Y✝ : Bipointed f : X'✝ ⟶ X✝ g : X✝ ⟶ bipointedToPointedFst.obj Y✝ ⊢ ↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }, left_inv := (_ : ∀ (f : pointedToBipointedFst.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedFst.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) f) = f) }) X'✝ Y✝).symm (f ≫ g) = pointedToBipointedFst.map f ≫ ↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }, left_inv := (_ : ∀ (f : pointedToBipointedFst.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedFst.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) f) = f) }) X✝ Y✝).symm g [PROOFSTEP] apply Bipointed.Hom.ext [GOAL] case toFun α : Type u_1 β : Type u_2 X'✝ X✝ : Pointed Y✝ : Bipointed f : X'✝ ⟶ X✝ g : X✝ ⟶ bipointedToPointedFst.obj Y✝ ⊢ (↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }, left_inv := (_ : ∀ (f : pointedToBipointedFst.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedFst.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) f) = f) }) X'✝ Y✝).symm (f ≫ g)).toFun = (pointedToBipointedFst.map f ≫ ↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }, left_inv := (_ : ∀ (f : pointedToBipointedFst.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedFst.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) f) = f) }) X✝ Y✝).symm g).toFun [PROOFSTEP] funext x [GOAL] case toFun.h α : Type u_1 β : Type u_2 X'✝ X✝ : Pointed Y✝ : Bipointed f : X'✝ ⟶ X✝ g : X✝ ⟶ bipointedToPointedFst.obj Y✝ x : (pointedToBipointedFst.obj X'✝).X ⊢ Bipointed.Hom.toFun (↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }, left_inv := (_ : ∀ (f : pointedToBipointedFst.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedFst.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) f) = f) }) X'✝ Y✝).symm (f ≫ g)) x = Bipointed.Hom.toFun (pointedToBipointedFst.map f ≫ ↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }, left_inv := (_ : ∀ (f : pointedToBipointedFst.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedFst.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) f) = f) }) X✝ Y✝).symm g) x [PROOFSTEP] cases x [GOAL] case toFun.h.none α : Type u_1 β : Type u_2 X'✝ X✝ : Pointed Y✝ : Bipointed f : X'✝ ⟶ X✝ g : X✝ ⟶ bipointedToPointedFst.obj Y✝ ⊢ Bipointed.Hom.toFun (↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }, left_inv := (_ : ∀ (f : pointedToBipointedFst.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedFst.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) f) = f) }) X'✝ Y✝).symm (f ≫ g)) none = Bipointed.Hom.toFun (pointedToBipointedFst.map f ≫ ↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }, left_inv := (_ : ∀ (f : pointedToBipointedFst.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedFst.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) f) = f) }) X✝ Y✝).symm g) none [PROOFSTEP] rfl [GOAL] case toFun.h.some α : Type u_1 β : Type u_2 X'✝ X✝ : Pointed Y✝ : Bipointed f : X'✝ ⟶ X✝ g : X✝ ⟶ bipointedToPointedFst.obj Y✝ val✝ : X'✝.X ⊢ Bipointed.Hom.toFun (↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }, left_inv := (_ : ∀ (f : pointedToBipointedFst.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedFst.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) f) = f) }) X'✝ Y✝).symm (f ≫ g)) (some val✝) = Bipointed.Hom.toFun (pointedToBipointedFst.map f ≫ ↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }, left_inv := (_ : ∀ (f : pointedToBipointedFst.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedFst.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedFst.obj X).toProd.fst = Y.toProd.fst) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.snd f.toFun, map_fst := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedFst.obj Y).point), map_snd := (_ : (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd = (fun o => Option.elim o Y.toProd.snd f.toFun) (pointedToBipointedFst.obj X).toProd.snd) }) f) = f) }) X✝ Y✝).symm g) (some val✝) [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 X : Pointed Y : Bipointed f : pointedToBipointedSnd.obj X ⟶ Y ⊢ (fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) f) = f [PROOFSTEP] apply Bipointed.Hom.ext [GOAL] case toFun α : Type u_1 β : Type u_2 X : Pointed Y : Bipointed f : pointedToBipointedSnd.obj X ⟶ Y ⊢ ((fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) f)).toFun = f.toFun [PROOFSTEP] funext x [GOAL] case toFun.h α : Type u_1 β : Type u_2 X : Pointed Y : Bipointed f : pointedToBipointedSnd.obj X ⟶ Y x : (pointedToBipointedSnd.obj X).X ⊢ Bipointed.Hom.toFun ((fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) f)) x = Bipointed.Hom.toFun f x [PROOFSTEP] cases x [GOAL] case toFun.h.none α : Type u_1 β : Type u_2 X : Pointed Y : Bipointed f : pointedToBipointedSnd.obj X ⟶ Y ⊢ Bipointed.Hom.toFun ((fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) f)) none = Bipointed.Hom.toFun f none [PROOFSTEP] exact f.map_fst.symm [GOAL] case toFun.h.some α : Type u_1 β : Type u_2 X : Pointed Y : Bipointed f : pointedToBipointedSnd.obj X ⟶ Y val✝ : X.X ⊢ Bipointed.Hom.toFun ((fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) f)) (some val✝) = Bipointed.Hom.toFun f (some val✝) [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 X'✝ X✝ : Pointed Y✝ : Bipointed f : X'✝ ⟶ X✝ g : X✝ ⟶ bipointedToPointedSnd.obj Y✝ ⊢ ↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }, left_inv := (_ : ∀ (f : pointedToBipointedSnd.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedSnd.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) f) = f) }) X'✝ Y✝).symm (f ≫ g) = pointedToBipointedSnd.map f ≫ ↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }, left_inv := (_ : ∀ (f : pointedToBipointedSnd.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedSnd.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) f) = f) }) X✝ Y✝).symm g [PROOFSTEP] apply Bipointed.Hom.ext [GOAL] case toFun α : Type u_1 β : Type u_2 X'✝ X✝ : Pointed Y✝ : Bipointed f : X'✝ ⟶ X✝ g : X✝ ⟶ bipointedToPointedSnd.obj Y✝ ⊢ (↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }, left_inv := (_ : ∀ (f : pointedToBipointedSnd.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedSnd.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) f) = f) }) X'✝ Y✝).symm (f ≫ g)).toFun = (pointedToBipointedSnd.map f ≫ ↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }, left_inv := (_ : ∀ (f : pointedToBipointedSnd.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedSnd.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) f) = f) }) X✝ Y✝).symm g).toFun [PROOFSTEP] funext x [GOAL] case toFun.h α : Type u_1 β : Type u_2 X'✝ X✝ : Pointed Y✝ : Bipointed f : X'✝ ⟶ X✝ g : X✝ ⟶ bipointedToPointedSnd.obj Y✝ x : (pointedToBipointedSnd.obj X'✝).X ⊢ Bipointed.Hom.toFun (↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }, left_inv := (_ : ∀ (f : pointedToBipointedSnd.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedSnd.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) f) = f) }) X'✝ Y✝).symm (f ≫ g)) x = Bipointed.Hom.toFun (pointedToBipointedSnd.map f ≫ ↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }, left_inv := (_ : ∀ (f : pointedToBipointedSnd.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedSnd.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) f) = f) }) X✝ Y✝).symm g) x [PROOFSTEP] cases x [GOAL] case toFun.h.none α : Type u_1 β : Type u_2 X'✝ X✝ : Pointed Y✝ : Bipointed f : X'✝ ⟶ X✝ g : X✝ ⟶ bipointedToPointedSnd.obj Y✝ ⊢ Bipointed.Hom.toFun (↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }, left_inv := (_ : ∀ (f : pointedToBipointedSnd.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedSnd.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) f) = f) }) X'✝ Y✝).symm (f ≫ g)) none = Bipointed.Hom.toFun (pointedToBipointedSnd.map f ≫ ↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }, left_inv := (_ : ∀ (f : pointedToBipointedSnd.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedSnd.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) f) = f) }) X✝ Y✝).symm g) none [PROOFSTEP] rfl [GOAL] case toFun.h.some α : Type u_1 β : Type u_2 X'✝ X✝ : Pointed Y✝ : Bipointed f : X'✝ ⟶ X✝ g : X✝ ⟶ bipointedToPointedSnd.obj Y✝ val✝ : X'✝.X ⊢ Bipointed.Hom.toFun (↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }, left_inv := (_ : ∀ (f : pointedToBipointedSnd.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedSnd.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) f) = f) }) X'✝ Y✝).symm (f ≫ g)) (some val✝) = Bipointed.Hom.toFun (pointedToBipointedSnd.map f ≫ ↑((fun X Y => { toFun := fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }, invFun := fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }, left_inv := (_ : ∀ (f : pointedToBipointedSnd.obj X ⟶ Y), (fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) ((fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) f) = f), right_inv := (_ : ∀ (f : X ⟶ bipointedToPointedSnd.obj Y), (fun f => { toFun := f.toFun ∘ some, map_point := (_ : Bipointed.Hom.toFun f (pointedToBipointedSnd.obj X).toProd.snd = Y.toProd.snd) }) ((fun f => { toFun := fun o => Option.elim o Y.toProd.fst f.toFun, map_fst := (_ : (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst = (fun o => Option.elim o Y.toProd.fst f.toFun) (pointedToBipointedSnd.obj X).toProd.fst), map_snd := (_ : Pointed.Hom.toFun f X.point = (bipointedToPointedSnd.obj Y).point) }) f) = f) }) X✝ Y✝).symm g) (some val✝) [PROOFSTEP] rfl
Formal statement is: lemma integral_restrict_Int: fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space" assumes "S \<in> sets lebesgue" "T \<in> sets lebesgue" shows "integral\<^sup>L (lebesgue_on T) (\<lambda>x. if x \<in> S then f x else 0) = integral\<^sup>L (lebesgue_on (S \<inter> T)) f" Informal statement is: If $S$ and $T$ are measurable sets, then the integral of $f$ over $S \cap T$ is equal to the integral of $f$ over $T$ restricted to $S$.
// // Created by LEI XU on 4/27/19. // #ifndef RASTERIZER_TEXTURE_H #define RASTERIZER_TEXTURE_H #include "global.hpp" #include <Eigen/Core> #include <opencv2/opencv.hpp> class Texture{ private: cv::Mat image_data; public: Texture(const std::string& name) { image_data = cv::imread(name); cv::cvtColor(image_data, image_data, cv::COLOR_RGB2BGR); width = image_data.cols; height = image_data.rows; } int width, height; Eigen::Vector3f getColor(float u, float v) { if(u<0)u = 0; if(u>1)u = 1; if(v<0)v = 0; if(v>1)v = 1; auto u_img = u * width; auto v_img = (1 - v) * height; auto u_min = floor(u_img),v_min = floor(v_img); auto u_max = std::min(width*1.0f,ceil(u_img)),v_max = std::min(height*1.0f,ceil(v_img)); auto rs = (u_img - u_min)/(u_max - u_min); auto rt = (v_img - v_min)/(v_max - v_min); auto ctop = image_data.at<cv::Vec3b>(v_max,u_min)*(1-rs) + image_data.at<cv::Vec3b>(v_max,u_max)*rs; auto cbot = image_data.at<cv::Vec3b>(v_min,u_min)*(1-rs) + image_data.at<cv::Vec3b>(v_min, u_max)*rs; // auto u_img2 = (1-u)*width; // auto v_img2 = v*height; // auto u_img = u*u_img1+(1-u)*u_img2; // auto v_img = v*v_img1+(1-v)*v_img2; // auto color = cbot*(1-rt)+ctop*rt; auto color = image_data.at<cv::Vec3b>(v_img,u_img); return Eigen::Vector3f(color[0], color[1], color[2]); } }; #endif //RASTERIZER_TEXTURE_H
%kkrect2pol 'Convert (real, imaginary) to (r, theta) Coordinates' % This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros krect2pol.pane file % % Parameters: % InputFile: i 'Input ', required: 'Input data object' % OutputFile: o 'Output', required: 'Resulting output data object' % % Example: o = kkrect2pol(i, {'i','';'o',''}) % % Khoros helpfile follows below: % % PROGRAM % krect2pol - Convert (real, imaginary) to (r, theta) Coordinates % % DESCRIPTION % The "Rect. to Polar" operator converts data from the rectangular to the % polar coordinate system for each complex data point in the input data % object, \fBInput". The conversion from rectangular to polar will result % in angles measured in radians. The data type of % the output data object, \fBOutput", will be the same as the data type % of \fBInput". % % Executing "Rect. to Polar" runs the program \fIkcmplx\fP % with the -r2p flag. % % "Map Data" 5 % .cI $DATAMANIP/repos/shared/man/sections/map_1input % % "Validity Mask" 5 % .cI $DATAMANIP/repos/shared/man/sections/mask_1input % % "Location and Time Data" 5 % .cI $DATAMANIP/repos/shared/man/sections/loc_and_time_1input % % % % EXAMPLES % % "SEE ALSO" % DATAMANIP::kcmplx, DATAMANIP::kpol2rect % % RESTRICTIONS % % REFERENCES % % COPYRIGHT % Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI") All rights reserved. % function varargout = kkrect2pol(varargin) if nargin ==0 Inputs={};arglist={'',''}; elseif nargin ==1 Inputs=varargin{1};arglist={'',''}; elseif nargin ==2 Inputs=varargin{1}; arglist=varargin{2}; else error('Usage: [out1,..] = kkrect2pol(Inputs,arglist).'); end if size(arglist,2)~=2 error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}') end narglist={'i', '__input';'o', '__output'}; maxval={0,0}; minval={0,0}; istoggle=[0,0]; was_set=istoggle * 0; paramtype={'InputFile','OutputFile'}; % identify the input arrays and assign them to the arguments as stated by the user if ~iscell(Inputs) Inputs = {Inputs}; end NumReqOutputs=1; nextinput=1; nextoutput=1; for ii=1:size(arglist,1) wasmatched=0; for jj=1:size(narglist,1) if strcmp(arglist{ii,1},narglist{jj,1}) % a given argument was matched to the possible arguments wasmatched = 1; was_set(jj) = 1; if strcmp(narglist{jj,2}, '__input') if (nextinput > length(Inputs)) error(['Input ' narglist{jj,1} ' has no corresponding input!']); end narglist{jj,2} = 'OK_in'; nextinput = nextinput + 1; elseif strcmp(narglist{jj,2}, '__output') if (nextoutput > nargout) error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']); end if (isempty(arglist{ii,2})) narglist{jj,2} = 'OK_out'; else narglist{jj,2} = arglist{ii,2}; end nextoutput = nextoutput + 1; if (minval{jj} == 0) NumReqOutputs = NumReqOutputs - 1; end elseif isstr(arglist{ii,2}) narglist{jj,2} = arglist{ii,2}; else if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2}) error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']); end if (minval{jj} ~= 0 | maxval{jj} ~= 0) if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0) error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']); elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0) error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']); elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0) error(['Argument ' arglist{ii,1} ' must be bigger than zero!']); elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0) error(['Argument ' arglist{ii,1} ' must be smaller than zero!']); elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj}) error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]); elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj}) error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]); end end end if ~strcmp(narglist{jj,2},'OK_out') & ~strcmp(narglist{jj,2},'OK_in') narglist{jj,2} = arglist{ii,2}; end end end if (wasmatched == 0 & ~strcmp(arglist{ii,1},'')) error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']); end end % match the remaining inputs/outputs to the unused arguments and test for missing required inputs for jj=1:size(narglist,1) if strcmp(paramtype{jj}, 'Toggle') if (narglist{jj,2} ==0) narglist{jj,1} = ''; end; narglist{jj,2} = ''; end; if ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj) narglist{jj,1} = ''; narglist{jj,2} = ''; end; if strcmp(narglist{jj,2}, '__input') if (minval{jj} == 0) % meaning this input is required if (nextinput > size(Inputs)) error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']); else narglist{jj,2} = 'OK_in'; nextinput = nextinput + 1; end else % this is an optional input if (nextinput <= length(Inputs)) narglist{jj,2} = 'OK_in'; nextinput = nextinput + 1; else narglist{jj,1} = ''; narglist{jj,2} = ''; end; end; else if strcmp(narglist{jj,2}, '__output') if (minval{jj} == 0) % this is a required output if (nextoutput > nargout & nargout > 1) error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']); else narglist{jj,2} = 'OK_out'; nextoutput = nextoutput + 1; NumReqOutputs = NumReqOutputs-1; end else % this is an optional output if (nargout - nextoutput >= NumReqOutputs) narglist{jj,2} = 'OK_out'; nextoutput = nextoutput + 1; else narglist{jj,1} = ''; narglist{jj,2} = ''; end; end end end end if nargout varargout = cell(1,nargout); else varargout = cell(1,1); end global KhorosRoot if exist('KhorosRoot') && ~isempty(KhorosRoot) w=['"' KhorosRoot]; else if ispc w='"C:\Program Files\dip\khorosBin\'; else [s,w] = system('which cantata'); w=['"' w(1:end-8)]; end end [varargout{:}]=callKhoros([w 'kcmplx" -r2p'],Inputs,narglist);
[GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁷ : CommSemiring R inst✝⁶ : AddCommMonoid M inst✝⁵ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁴ : CommRing R₂ inst✝³ : AddCommGroup M₂ inst✝² : Module R₂ M₂ e : Basis ι R M v✝ : ι' → M i : ι j : ι' inst✝¹ : Fintype ι inst✝ : DecidableEq ι v : ι → M ⊢ toMatrix e v = ↑(LinearMap.toMatrix e e) (↑(constr e ℕ) v) [PROOFSTEP] ext [GOAL] case a.h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁷ : CommSemiring R inst✝⁶ : AddCommMonoid M inst✝⁵ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁴ : CommRing R₂ inst✝³ : AddCommGroup M₂ inst✝² : Module R₂ M₂ e : Basis ι R M v✝ : ι' → M i : ι j : ι' inst✝¹ : Fintype ι inst✝ : DecidableEq ι v : ι → M i✝ x✝ : ι ⊢ toMatrix e v i✝ x✝ = ↑(LinearMap.toMatrix e e) (↑(constr e ℕ) v) i✝ x✝ [PROOFSTEP] rw [Basis.toMatrix_apply, LinearMap.toMatrix_apply, Basis.constr_basis] [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' inst✝ : Fintype ι ⊢ toMatrix (Pi.basisFun R ι) = transpose [PROOFSTEP] ext M i j [GOAL] case h.a.h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M✝ : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M✝ inst✝⁴ : Module R M✝ R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e : Basis ι R M✝ v : ι' → M✝ i✝ : ι j✝ : ι' inst✝ : Fintype ι M : ι → ι → R i j : ι ⊢ toMatrix (Pi.basisFun R ι) M i j = Mᵀ i j [PROOFSTEP] rfl [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' inst✝ : DecidableEq ι ⊢ toMatrix e ↑e = 1 [PROOFSTEP] unfold Basis.toMatrix [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' inst✝ : DecidableEq ι ⊢ (fun i j => ↑(↑e.repr (↑e j)) i) = 1 [PROOFSTEP] ext i j [GOAL] case a.h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e : Basis ι R M v : ι' → M i✝ : ι j✝ : ι' inst✝ : DecidableEq ι i j : ι ⊢ ↑(↑e.repr (↑e j)) i = OfNat.ofNat 1 i j [PROOFSTEP] simp [Basis.equivFun, Matrix.one_apply, Finsupp.single_apply, eq_comm] [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' inst✝ : DecidableEq ι' x : M ⊢ toMatrix e (update v j x) = updateColumn (toMatrix e v) j ↑(↑e.repr x) [PROOFSTEP] ext i' k [GOAL] case a.h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' inst✝ : DecidableEq ι' x : M i' : ι k : ι' ⊢ toMatrix e (update v j x) i' k = updateColumn (toMatrix e v) j (↑(↑e.repr x)) i' k [PROOFSTEP] rw [Basis.toMatrix, Matrix.updateColumn_apply, e.toMatrix_apply] [GOAL] case a.h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' inst✝ : DecidableEq ι' x : M i' : ι k : ι' ⊢ ↑(↑e.repr (update v j x k)) i' = if k = j then ↑(↑e.repr x) i' else ↑(↑e.repr (v k)) i' [PROOFSTEP] split_ifs with h [GOAL] case pos ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' inst✝ : DecidableEq ι' x : M i' : ι k : ι' h : k = j ⊢ ↑(↑e.repr (update v j x k)) i' = ↑(↑e.repr x) i' [PROOFSTEP] rw [h, update_same j x v] [GOAL] case neg ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' inst✝ : DecidableEq ι' x : M i' : ι k : ι' h : ¬k = j ⊢ ↑(↑e.repr (update v j x k)) i' = ↑(↑e.repr (v k)) i' [PROOFSTEP] rw [update_noteq h] [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e✝ : Basis ι R M v : ι' → M i : ι j : ι' inst✝ : DecidableEq ι e : Basis ι R₂ M₂ w : ι → R₂ˣ ⊢ toMatrix e ↑(unitsSMul e w) = Matrix.diagonal (Units.val ∘ w) [PROOFSTEP] ext i j [GOAL] case a.h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e✝ : Basis ι R M v : ι' → M i✝ : ι j✝ : ι' inst✝ : DecidableEq ι e : Basis ι R₂ M₂ w : ι → R₂ˣ i j : ι ⊢ toMatrix e (↑(unitsSMul e w)) i j = Matrix.diagonal (Units.val ∘ w) i j [PROOFSTEP] by_cases h : i = j [GOAL] case pos ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e✝ : Basis ι R M v : ι' → M i✝ : ι j✝ : ι' inst✝ : DecidableEq ι e : Basis ι R₂ M₂ w : ι → R₂ˣ i j : ι h : i = j ⊢ toMatrix e (↑(unitsSMul e w)) i j = Matrix.diagonal (Units.val ∘ w) i j [PROOFSTEP] simp [h, toMatrix_apply, unitsSMul_apply, Units.smul_def] [GOAL] case neg ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e✝ : Basis ι R M v : ι' → M i✝ : ι j✝ : ι' inst✝ : DecidableEq ι e : Basis ι R₂ M₂ w : ι → R₂ˣ i j : ι h : ¬i = j ⊢ toMatrix e (↑(unitsSMul e w)) i j = Matrix.diagonal (Units.val ∘ w) i j [PROOFSTEP] simp [h, toMatrix_apply, unitsSMul_apply, Units.smul_def, Ne.symm h] [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' inst✝ : Fintype ι ⊢ ∑ i : ι, toMatrix e v i j • ↑e i = v j [PROOFSTEP] simp_rw [e.toMatrix_apply, e.sum_repr] [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁸ : CommSemiring R inst✝⁷ : AddCommMonoid M inst✝⁶ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁵ : CommRing R₂ inst✝⁴ : AddCommGroup M₂ inst✝³ : Module R₂ M₂ e : Basis ι R M v✝ : ι' → M i : ι j : ι' S : Type u_9 inst✝² : Ring S inst✝¹ : Algebra R S inst✝ : Fintype ι b : Basis ι R S v : ι' → S ⊢ vecMul (↑b) (Matrix.map (toMatrix b v) ↑(algebraMap R S)) = v [PROOFSTEP] ext i [GOAL] case h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁸ : CommSemiring R inst✝⁷ : AddCommMonoid M inst✝⁶ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁵ : CommRing R₂ inst✝⁴ : AddCommGroup M₂ inst✝³ : Module R₂ M₂ e : Basis ι R M v✝ : ι' → M i✝ : ι j : ι' S : Type u_9 inst✝² : Ring S inst✝¹ : Algebra R S inst✝ : Fintype ι b : Basis ι R S v : ι' → S i : ι' ⊢ vecMul (↑b) (Matrix.map (toMatrix b v) ↑(algebraMap R S)) i = v i [PROOFSTEP] simp_rw [vecMul, dotProduct, Matrix.map_apply, ← Algebra.commutes, ← Algebra.smul_def, sum_toMatrix_smul_self] [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁸ : CommSemiring R inst✝⁷ : AddCommMonoid M inst✝⁶ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁵ : CommRing R₂ inst✝⁴ : AddCommGroup M₂ inst✝³ : Module R₂ M₂ e : Basis ι R M v✝ : ι' → M i✝ : ι j : ι' inst✝² : Fintype ι inst✝¹ : Fintype ι' inst✝ : DecidableEq ι' v : Basis ι' R M i : ι' ⊢ ↑(↑(toLin v e) (toMatrix e ↑v)) (↑v i) = ↑LinearMap.id (↑v i) [PROOFSTEP] rw [toLin_self, id_apply, e.sum_toMatrix_smul_self] [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e✝ : Basis ι R M v✝ : ι' → M i : ι j : ι' inst✝ : Fintype ι e : Basis ι R M v w : ι → M ⊢ toMatrix e (v + w) = toMatrix e v + toMatrix e w [PROOFSTEP] ext i j [GOAL] case a.h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e✝ : Basis ι R M v✝ : ι' → M i✝ : ι j✝ : ι' inst✝ : Fintype ι e : Basis ι R M v w : ι → M i j : ι ⊢ toMatrix e (v + w) i j = (toMatrix e v + toMatrix e w) i j [PROOFSTEP] change _ = _ + _ [GOAL] case a.h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e✝ : Basis ι R M v✝ : ι' → M i✝ : ι j✝ : ι' inst✝ : Fintype ι e : Basis ι R M v w : ι → M i j : ι ⊢ toMatrix e (v + w) i j = toMatrix e v i j + toMatrix e w i j [PROOFSTEP] rw [e.toMatrix_apply, Pi.add_apply, LinearEquiv.map_add] [GOAL] case a.h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e✝ : Basis ι R M v✝ : ι' → M i✝ : ι j✝ : ι' inst✝ : Fintype ι e : Basis ι R M v w : ι → M i j : ι ⊢ ↑(↑e.repr (v j) + ↑e.repr (w j)) i = toMatrix e v i j + toMatrix e w i j [PROOFSTEP] rfl [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e✝ : Basis ι R M v : ι' → M i : ι j : ι' inst✝ : Fintype ι e : Basis ι R M ⊢ ∀ (r : R) (x : ι → M), AddHom.toFun { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) } (r • x) = ↑(RingHom.id R) r • AddHom.toFun { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) } x [PROOFSTEP] intro c v [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e✝ : Basis ι R M v✝ : ι' → M i : ι j : ι' inst✝ : Fintype ι e : Basis ι R M c : R v : ι → M ⊢ AddHom.toFun { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) } (c • v) = ↑(RingHom.id R) c • AddHom.toFun { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) } v [PROOFSTEP] ext i j [GOAL] case a.h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e✝ : Basis ι R M v✝ : ι' → M i✝ : ι j✝ : ι' inst✝ : Fintype ι e : Basis ι R M c : R v : ι → M i j : ι ⊢ AddHom.toFun { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) } (c • v) i j = (↑(RingHom.id R) c • AddHom.toFun { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) } v) i j [PROOFSTEP] dsimp only [] [GOAL] case a.h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e✝ : Basis ι R M v✝ : ι' → M i✝ : ι j✝ : ι' inst✝ : Fintype ι e : Basis ι R M c : R v : ι → M i j : ι ⊢ toMatrix e (c • v) i j = (↑(RingHom.id R) c • toMatrix e v) i j [PROOFSTEP] rw [e.toMatrix_apply, Pi.smul_apply, LinearEquiv.map_smul] [GOAL] case a.h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e✝ : Basis ι R M v✝ : ι' → M i✝ : ι j✝ : ι' inst✝ : Fintype ι e : Basis ι R M c : R v : ι → M i j : ι ⊢ ↑(c • ↑e.repr (v j)) i = (↑(RingHom.id R) c • toMatrix e v) i j [PROOFSTEP] rfl [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e✝ : Basis ι R M v : ι' → M i : ι j : ι' inst✝ : Fintype ι e : Basis ι R M ⊢ LeftInverse (fun m j => ∑ i : ι, m i j • ↑e i) { toAddHom := { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) }, map_smul' := (_ : ∀ (c : R) (v : ι → M), AddHom.toFun { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) } (c • v) = ↑(RingHom.id R) c • AddHom.toFun { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) } v) }.toAddHom.toFun [PROOFSTEP] intro v [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e✝ : Basis ι R M v✝ : ι' → M i : ι j : ι' inst✝ : Fintype ι e : Basis ι R M v : ι → M ⊢ (fun m j => ∑ i : ι, m i j • ↑e i) (AddHom.toFun { toAddHom := { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) }, map_smul' := (_ : ∀ (c : R) (v : ι → M), AddHom.toFun { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) } (c • v) = ↑(RingHom.id R) c • AddHom.toFun { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) } v) }.toAddHom v) = v [PROOFSTEP] ext j [GOAL] case h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e✝ : Basis ι R M v✝ : ι' → M i : ι j✝ : ι' inst✝ : Fintype ι e : Basis ι R M v : ι → M j : ι ⊢ (fun m j => ∑ i : ι, m i j • ↑e i) (AddHom.toFun { toAddHom := { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) }, map_smul' := (_ : ∀ (c : R) (v : ι → M), AddHom.toFun { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) } (c • v) = ↑(RingHom.id R) c • AddHom.toFun { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) } v) }.toAddHom v) j = v j [PROOFSTEP] exact e.sum_toMatrix_smul_self v j [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e✝ : Basis ι R M v : ι' → M i : ι j : ι' inst✝ : Fintype ι e : Basis ι R M ⊢ Function.RightInverse (fun m j => ∑ i : ι, m i j • ↑e i) { toAddHom := { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) }, map_smul' := (_ : ∀ (c : R) (v : ι → M), AddHom.toFun { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) } (c • v) = ↑(RingHom.id R) c • AddHom.toFun { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) } v) }.toAddHom.toFun [PROOFSTEP] intro m [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e✝ : Basis ι R M v : ι' → M i : ι j : ι' inst✝ : Fintype ι e : Basis ι R M m : Matrix ι ι R ⊢ AddHom.toFun { toAddHom := { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) }, map_smul' := (_ : ∀ (c : R) (v : ι → M), AddHom.toFun { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) } (c • v) = ↑(RingHom.id R) c • AddHom.toFun { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) } v) }.toAddHom ((fun m j => ∑ i : ι, m i j • ↑e i) m) = m [PROOFSTEP] ext k l [GOAL] case a.h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁶ : CommSemiring R inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝³ : CommRing R₂ inst✝² : AddCommGroup M₂ inst✝¹ : Module R₂ M₂ e✝ : Basis ι R M v : ι' → M i : ι j : ι' inst✝ : Fintype ι e : Basis ι R M m : Matrix ι ι R k l : ι ⊢ AddHom.toFun { toAddHom := { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) }, map_smul' := (_ : ∀ (c : R) (v : ι → M), AddHom.toFun { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) } (c • v) = ↑(RingHom.id R) c • AddHom.toFun { toFun := toMatrix e, map_add' := (_ : ∀ (v w : ι → M), toMatrix e (v + w) = toMatrix e v + toMatrix e w) } v) }.toAddHom ((fun m j => ∑ i : ι, m i j • ↑e i) m) k l = m k l [PROOFSTEP] simp only [e.toMatrix_apply, ← e.equivFun_apply, ← e.equivFun_symm_apply, LinearEquiv.apply_symm_apply] [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝¹¹ : CommSemiring R inst✝¹⁰ : AddCommMonoid M inst✝⁹ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁸ : CommRing R₂ inst✝⁷ : AddCommGroup M₂ inst✝⁶ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' N : Type u_9 inst✝⁵ : AddCommMonoid N inst✝⁴ : Module R N b : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N inst✝³ : Fintype ι' inst✝² : Fintype κ inst✝¹ : Fintype κ' inst✝ : DecidableEq ι' ⊢ ↑(toLin b' c) (Basis.toMatrix c ↑c' * ↑(toMatrix b' c') f) = ↑(toLin b' c) (↑(toMatrix b' c) f) [PROOFSTEP] haveI := Classical.decEq κ' [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝¹¹ : CommSemiring R inst✝¹⁰ : AddCommMonoid M inst✝⁹ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁸ : CommRing R₂ inst✝⁷ : AddCommGroup M₂ inst✝⁶ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' N : Type u_9 inst✝⁵ : AddCommMonoid N inst✝⁴ : Module R N b : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N inst✝³ : Fintype ι' inst✝² : Fintype κ inst✝¹ : Fintype κ' inst✝ : DecidableEq ι' this : DecidableEq κ' ⊢ ↑(toLin b' c) (Basis.toMatrix c ↑c' * ↑(toMatrix b' c') f) = ↑(toLin b' c) (↑(toMatrix b' c) f) [PROOFSTEP] rw [toLin_toMatrix, toLin_mul b' c' c, toLin_toMatrix, c.toLin_toMatrix, id_comp] [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝¹³ : CommSemiring R inst✝¹² : AddCommMonoid M inst✝¹¹ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝¹⁰ : CommRing R₂ inst✝⁹ : AddCommGroup M₂ inst✝⁸ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' N : Type u_9 inst✝⁷ : AddCommMonoid N inst✝⁶ : Module R N b : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N inst✝⁵ : Fintype ι' inst✝⁴ : Fintype κ inst✝³ : Fintype κ' inst✝² : Fintype ι inst✝¹ : DecidableEq ι inst✝ : DecidableEq ι' ⊢ ↑(toLin b c') (↑(toMatrix b' c') f * Basis.toMatrix b' ↑b) = ↑(toLin b c') (↑(toMatrix b c') f) [PROOFSTEP] rw [toLin_toMatrix, toLin_mul b b' c', toLin_toMatrix, b'.toLin_toMatrix, comp_id] [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝¹³ : CommSemiring R inst✝¹² : AddCommMonoid M inst✝¹¹ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝¹⁰ : CommRing R₂ inst✝⁹ : AddCommGroup M₂ inst✝⁸ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' N : Type u_9 inst✝⁷ : AddCommMonoid N inst✝⁶ : Module R N b : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N inst✝⁵ : Fintype ι' inst✝⁴ : Fintype κ inst✝³ : Fintype κ' inst✝² : Fintype ι inst✝¹ : DecidableEq ι inst✝ : DecidableEq ι' ⊢ Basis.toMatrix c ↑c' * ↑(toMatrix b' c') f * Basis.toMatrix b' ↑b = ↑(toMatrix b c) f [PROOFSTEP] rw [basis_toMatrix_mul_linearMap_toMatrix, linearMap_toMatrix_mul_basis_toMatrix] [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝¹² : CommSemiring R inst✝¹¹ : AddCommMonoid M inst✝¹⁰ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁹ : CommRing R₂ inst✝⁸ : AddCommGroup M₂ inst✝⁷ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' N : Type u_9 inst✝⁶ : AddCommMonoid N inst✝⁵ : Module R N b : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N inst✝⁴ : Fintype ι' inst✝³ : Fintype κ inst✝² : Fintype κ' inst✝¹ : Fintype ι inst✝ : DecidableEq κ b₁ : Basis ι R M b₂ : Basis ι' R M b₃ : Basis κ R N A : Matrix ι' κ R ⊢ Basis.toMatrix b₁ ↑b₂ * A = ↑(toMatrix b₃ b₁) (↑(toLin b₃ b₂) A) [PROOFSTEP] have := basis_toMatrix_mul_linearMap_toMatrix b₃ b₁ b₂ (Matrix.toLin b₃ b₂ A) [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝¹² : CommSemiring R inst✝¹¹ : AddCommMonoid M inst✝¹⁰ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁹ : CommRing R₂ inst✝⁸ : AddCommGroup M₂ inst✝⁷ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' N : Type u_9 inst✝⁶ : AddCommMonoid N inst✝⁵ : Module R N b : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N inst✝⁴ : Fintype ι' inst✝³ : Fintype κ inst✝² : Fintype κ' inst✝¹ : Fintype ι inst✝ : DecidableEq κ b₁ : Basis ι R M b₂ : Basis ι' R M b₃ : Basis κ R N A : Matrix ι' κ R this : Basis.toMatrix b₁ ↑b₂ * ↑(toMatrix b₃ b₂) (↑(toLin b₃ b₂) A) = ↑(toMatrix b₃ b₁) (↑(toLin b₃ b₂) A) ⊢ Basis.toMatrix b₁ ↑b₂ * A = ↑(toMatrix b₃ b₁) (↑(toLin b₃ b₂) A) [PROOFSTEP] rwa [LinearMap.toMatrix_toLin] at this [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝¹³ : CommSemiring R inst✝¹² : AddCommMonoid M inst✝¹¹ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝¹⁰ : CommRing R₂ inst✝⁹ : AddCommGroup M₂ inst✝⁸ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' N : Type u_9 inst✝⁷ : AddCommMonoid N inst✝⁶ : Module R N b : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N inst✝⁵ : Fintype ι' inst✝⁴ : Fintype κ inst✝³ : Fintype κ' inst✝² : Fintype ι inst✝¹ : DecidableEq ι inst✝ : DecidableEq ι' b₁ : Basis ι R M b₂ : Basis ι' R M b₃ : Basis κ R N A : Matrix κ ι R ⊢ A * Basis.toMatrix b₁ ↑b₂ = ↑(toMatrix b₂ b₃) (↑(toLin b₁ b₃) A) [PROOFSTEP] have := linearMap_toMatrix_mul_basis_toMatrix b₂ b₁ b₃ (Matrix.toLin b₁ b₃ A) [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝¹³ : CommSemiring R inst✝¹² : AddCommMonoid M inst✝¹¹ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝¹⁰ : CommRing R₂ inst✝⁹ : AddCommGroup M₂ inst✝⁸ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' N : Type u_9 inst✝⁷ : AddCommMonoid N inst✝⁶ : Module R N b : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N inst✝⁵ : Fintype ι' inst✝⁴ : Fintype κ inst✝³ : Fintype κ' inst✝² : Fintype ι inst✝¹ : DecidableEq ι inst✝ : DecidableEq ι' b₁ : Basis ι R M b₂ : Basis ι' R M b₃ : Basis κ R N A : Matrix κ ι R this : ↑(toMatrix b₁ b₃) (↑(toLin b₁ b₃) A) * Basis.toMatrix b₁ ↑b₂ = ↑(toMatrix b₂ b₃) (↑(toLin b₁ b₃) A) ⊢ A * Basis.toMatrix b₁ ↑b₂ = ↑(toMatrix b₂ b₃) (↑(toLin b₁ b₃) A) [PROOFSTEP] rwa [LinearMap.toMatrix_toLin] at this [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝¹¹ : CommSemiring R inst✝¹⁰ : AddCommMonoid M inst✝⁹ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁸ : CommRing R₂ inst✝⁷ : AddCommGroup M₂ inst✝⁶ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' N : Type u_9 inst✝⁵ : AddCommMonoid N inst✝⁴ : Module R N b✝ : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N inst✝³ : Fintype ι' inst✝² : Fintype κ inst✝¹ : Fintype κ' inst✝ : Fintype ι b : Basis ι R (ι → R) A : Matrix ι ι R ⊢ Basis.toMatrix b ↑(Pi.basisFun R ι) * A = ↑of fun i j => ↑(↑b.repr (Aᵀ j)) i [PROOFSTEP] classical simp only [basis_toMatrix_mul _ _ (Pi.basisFun R ι), Matrix.toLin_eq_toLin'] ext i j rw [LinearMap.toMatrix_apply, Matrix.toLin'_apply, Pi.basisFun_apply, Matrix.mulVec_stdBasis_apply, Matrix.of_apply] [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝¹¹ : CommSemiring R inst✝¹⁰ : AddCommMonoid M inst✝⁹ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁸ : CommRing R₂ inst✝⁷ : AddCommGroup M₂ inst✝⁶ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' N : Type u_9 inst✝⁵ : AddCommMonoid N inst✝⁴ : Module R N b✝ : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N inst✝³ : Fintype ι' inst✝² : Fintype κ inst✝¹ : Fintype κ' inst✝ : Fintype ι b : Basis ι R (ι → R) A : Matrix ι ι R ⊢ Basis.toMatrix b ↑(Pi.basisFun R ι) * A = ↑of fun i j => ↑(↑b.repr (Aᵀ j)) i [PROOFSTEP] simp only [basis_toMatrix_mul _ _ (Pi.basisFun R ι), Matrix.toLin_eq_toLin'] [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝¹¹ : CommSemiring R inst✝¹⁰ : AddCommMonoid M inst✝⁹ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁸ : CommRing R₂ inst✝⁷ : AddCommGroup M₂ inst✝⁶ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' N : Type u_9 inst✝⁵ : AddCommMonoid N inst✝⁴ : Module R N b✝ : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N inst✝³ : Fintype ι' inst✝² : Fintype κ inst✝¹ : Fintype κ' inst✝ : Fintype ι b : Basis ι R (ι → R) A : Matrix ι ι R ⊢ ↑(toMatrix (Pi.basisFun R ι) b) (↑toLin' A) = ↑of fun i j => ↑(↑b.repr (Aᵀ j)) i [PROOFSTEP] ext i j [GOAL] case a.h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝¹¹ : CommSemiring R inst✝¹⁰ : AddCommMonoid M inst✝⁹ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁸ : CommRing R₂ inst✝⁷ : AddCommGroup M₂ inst✝⁶ : Module R₂ M₂ e : Basis ι R M v : ι' → M i✝ : ι j✝ : ι' N : Type u_9 inst✝⁵ : AddCommMonoid N inst✝⁴ : Module R N b✝ : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N inst✝³ : Fintype ι' inst✝² : Fintype κ inst✝¹ : Fintype κ' inst✝ : Fintype ι b : Basis ι R (ι → R) A : Matrix ι ι R i j : ι ⊢ ↑(toMatrix (Pi.basisFun R ι) b) (↑toLin' A) i j = ↑of (fun i j => ↑(↑b.repr (Aᵀ j)) i) i j [PROOFSTEP] rw [LinearMap.toMatrix_apply, Matrix.toLin'_apply, Pi.basisFun_apply, Matrix.mulVec_stdBasis_apply, Matrix.of_apply] [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝¹² : CommSemiring R inst✝¹¹ : AddCommMonoid M inst✝¹⁰ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁹ : CommRing R₂ inst✝⁸ : AddCommGroup M₂ inst✝⁷ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' N : Type u_9 inst✝⁶ : AddCommMonoid N inst✝⁵ : Module R N b : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N inst✝⁴ : Fintype ι' inst✝³ : Fintype κ inst✝² : Fintype κ' inst✝¹ : Fintype ι inst✝ : DecidableEq ι ⊢ ↑(toMatrix b b') id = Basis.toMatrix b' ↑b [PROOFSTEP] haveI := Classical.decEq ι' [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝¹² : CommSemiring R inst✝¹¹ : AddCommMonoid M inst✝¹⁰ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁹ : CommRing R₂ inst✝⁸ : AddCommGroup M₂ inst✝⁷ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' N : Type u_9 inst✝⁶ : AddCommMonoid N inst✝⁵ : Module R N b : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N inst✝⁴ : Fintype ι' inst✝³ : Fintype κ inst✝² : Fintype κ' inst✝¹ : Fintype ι inst✝ : DecidableEq ι this : DecidableEq ι' ⊢ ↑(toMatrix b b') id = Basis.toMatrix b' ↑b [PROOFSTEP] rw [← @basis_toMatrix_mul_linearMap_toMatrix _ _ ι, toMatrix_id, Matrix.mul_one] [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝¹³ : CommSemiring R inst✝¹² : AddCommMonoid M inst✝¹¹ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝¹⁰ : CommRing R₂ inst✝⁹ : AddCommGroup M₂ inst✝⁸ : Module R₂ M₂ e✝ : Basis ι R M v✝ : ι' → M i : ι j : ι' N : Type u_9 inst✝⁷ : AddCommMonoid N inst✝⁶ : Module R N b✝ : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N inst✝⁵ : Fintype ι' inst✝⁴ : Fintype κ inst✝³ : Fintype κ' inst✝² : Fintype ι inst✝¹ : DecidableEq ι inst✝ : DecidableEq ι' b : Basis ι R M v : ι' → M e : ι ≃ ι' ⊢ toMatrix (reindex b e) v = ↑(reindexAlgEquiv R e) (toMatrix b (v ∘ ↑e)) [PROOFSTEP] ext [GOAL] case a.h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝¹³ : CommSemiring R inst✝¹² : AddCommMonoid M inst✝¹¹ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝¹⁰ : CommRing R₂ inst✝⁹ : AddCommGroup M₂ inst✝⁸ : Module R₂ M₂ e✝ : Basis ι R M v✝ : ι' → M i : ι j : ι' N : Type u_9 inst✝⁷ : AddCommMonoid N inst✝⁶ : Module R N b✝ : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N inst✝⁵ : Fintype ι' inst✝⁴ : Fintype κ inst✝³ : Fintype κ' inst✝² : Fintype ι inst✝¹ : DecidableEq ι inst✝ : DecidableEq ι' b : Basis ι R M v : ι' → M e : ι ≃ ι' i✝ x✝ : ι' ⊢ toMatrix (reindex b e) v i✝ x✝ = ↑(reindexAlgEquiv R e) (toMatrix b (v ∘ ↑e)) i✝ x✝ [PROOFSTEP] simp only [Basis.toMatrix_apply, Basis.repr_reindex, Matrix.reindexAlgEquiv_apply, Matrix.reindex_apply, Matrix.submatrix_apply, Function.comp_apply, e.apply_symm_apply, Finsupp.mapDomain_equiv_apply] [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁸ : CommSemiring R inst✝⁷ : AddCommMonoid M inst✝⁶ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁵ : CommRing R₂ inst✝⁴ : AddCommGroup M₂ inst✝³ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' N : Type u_9 inst✝² : AddCommMonoid N inst✝¹ : Module R N b : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N ι'' : Type u_10 inst✝ : Fintype ι' b'' : ι'' → M ⊢ toMatrix b ↑b' * toMatrix b' b'' = toMatrix b b'' [PROOFSTEP] haveI := Classical.decEq ι [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁸ : CommSemiring R inst✝⁷ : AddCommMonoid M inst✝⁶ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁵ : CommRing R₂ inst✝⁴ : AddCommGroup M₂ inst✝³ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' N : Type u_9 inst✝² : AddCommMonoid N inst✝¹ : Module R N b : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N ι'' : Type u_10 inst✝ : Fintype ι' b'' : ι'' → M this : DecidableEq ι ⊢ toMatrix b ↑b' * toMatrix b' b'' = toMatrix b b'' [PROOFSTEP] haveI := Classical.decEq ι' [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁸ : CommSemiring R inst✝⁷ : AddCommMonoid M inst✝⁶ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁵ : CommRing R₂ inst✝⁴ : AddCommGroup M₂ inst✝³ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' N : Type u_9 inst✝² : AddCommMonoid N inst✝¹ : Module R N b : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N ι'' : Type u_10 inst✝ : Fintype ι' b'' : ι'' → M this✝ : DecidableEq ι this : DecidableEq ι' ⊢ toMatrix b ↑b' * toMatrix b' b'' = toMatrix b b'' [PROOFSTEP] haveI := Classical.decEq ι'' [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁸ : CommSemiring R inst✝⁷ : AddCommMonoid M inst✝⁶ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁵ : CommRing R₂ inst✝⁴ : AddCommGroup M₂ inst✝³ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' N : Type u_9 inst✝² : AddCommMonoid N inst✝¹ : Module R N b : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N ι'' : Type u_10 inst✝ : Fintype ι' b'' : ι'' → M this✝¹ : DecidableEq ι this✝ : DecidableEq ι' this : DecidableEq ι'' ⊢ toMatrix b ↑b' * toMatrix b' b'' = toMatrix b b'' [PROOFSTEP] ext i j [GOAL] case a.h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁸ : CommSemiring R inst✝⁷ : AddCommMonoid M inst✝⁶ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁵ : CommRing R₂ inst✝⁴ : AddCommGroup M₂ inst✝³ : Module R₂ M₂ e : Basis ι R M v : ι' → M i✝ : ι j✝ : ι' N : Type u_9 inst✝² : AddCommMonoid N inst✝¹ : Module R N b : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N ι'' : Type u_10 inst✝ : Fintype ι' b'' : ι'' → M this✝¹ : DecidableEq ι this✝ : DecidableEq ι' this : DecidableEq ι'' i : ι j : ι'' ⊢ (toMatrix b ↑b' * toMatrix b' b'') i j = toMatrix b b'' i j [PROOFSTEP] simp only [Matrix.mul_apply, Basis.toMatrix_apply, Basis.sum_repr_mul_repr] [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁹ : CommSemiring R inst✝⁸ : AddCommMonoid M inst✝⁷ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁶ : CommRing R₂ inst✝⁵ : AddCommGroup M₂ inst✝⁴ : Module R₂ M₂ e : Basis ι R M v : ι' → M i : ι j : ι' N : Type u_9 inst✝³ : AddCommMonoid N inst✝² : Module R N b : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N inst✝¹ : DecidableEq ι inst✝ : Fintype ι' ⊢ toMatrix b ↑b' * toMatrix b' ↑b = 1 [PROOFSTEP] rw [Basis.toMatrix_mul_toMatrix, Basis.toMatrix_self] [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁷ : CommSemiring R inst✝⁶ : AddCommMonoid M inst✝⁵ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁴ : CommRing R₂ inst✝³ : AddCommGroup M₂ inst✝² : Module R₂ M₂ e✝ : Basis ι R M v✝ : ι' → M i : ι j : ι' N : Type u_9 inst✝¹ : AddCommMonoid N inst✝ : Module R N b✝ : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N b : Basis ι R M v : ι' → M e : ι ≃ ι' ⊢ toMatrix (reindex b e) v = submatrix (toMatrix b v) (↑e.symm) _root_.id [PROOFSTEP] ext [GOAL] case a.h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁷ : CommSemiring R inst✝⁶ : AddCommMonoid M inst✝⁵ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁴ : CommRing R₂ inst✝³ : AddCommGroup M₂ inst✝² : Module R₂ M₂ e✝ : Basis ι R M v✝ : ι' → M i : ι j : ι' N : Type u_9 inst✝¹ : AddCommMonoid N inst✝ : Module R N b✝ : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f : M →ₗ[R] N b : Basis ι R M v : ι' → M e : ι ≃ ι' i✝ x✝ : ι' ⊢ toMatrix (reindex b e) v i✝ x✝ = submatrix (toMatrix b v) (↑e.symm) _root_.id i✝ x✝ [PROOFSTEP] simp only [Basis.toMatrix_apply, Basis.repr_reindex, Matrix.submatrix_apply, id.def, Finsupp.mapDomain_equiv_apply] [GOAL] ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁷ : CommSemiring R inst✝⁶ : AddCommMonoid M inst✝⁵ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁴ : CommRing R₂ inst✝³ : AddCommGroup M₂ inst✝² : Module R₂ M₂ e : Basis ι R M v✝ : ι' → M i : ι j : ι' N : Type u_9 inst✝¹ : AddCommMonoid N inst✝ : Module R N b✝ : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f✝ : M →ₗ[R] N b : Basis ι R M f : M ≃ₗ[R] N v : ι → N ⊢ toMatrix (Basis.map b f) v = toMatrix b (↑(LinearEquiv.symm f) ∘ v) [PROOFSTEP] ext [GOAL] case a.h ι : Type u_1 ι' : Type u_2 κ : Type u_3 κ' : Type u_4 R : Type u_5 M : Type u_6 inst✝⁷ : CommSemiring R inst✝⁶ : AddCommMonoid M inst✝⁵ : Module R M R₂ : Type u_7 M₂ : Type u_8 inst✝⁴ : CommRing R₂ inst✝³ : AddCommGroup M₂ inst✝² : Module R₂ M₂ e : Basis ι R M v✝ : ι' → M i : ι j : ι' N : Type u_9 inst✝¹ : AddCommMonoid N inst✝ : Module R N b✝ : Basis ι R M b' : Basis ι' R M c : Basis κ R N c' : Basis κ' R N f✝ : M →ₗ[R] N b : Basis ι R M f : M ≃ₗ[R] N v : ι → N i✝ x✝ : ι ⊢ toMatrix (Basis.map b f) v i✝ x✝ = toMatrix b (↑(LinearEquiv.symm f) ∘ v) i✝ x✝ [PROOFSTEP] simp only [Basis.toMatrix_apply, Basis.map, LinearEquiv.trans_apply, (· ∘ ·)]
# Characterization of Systems in the Time Domain *This Jupyter notebook is part of a [collection of notebooks](../index.ipynb) in the bachelors module Signals and Systems, Communications Engineering, Universität Rostock. Please direct questions and suggestions to [[email protected]](mailto:[email protected]).* ## Eigenfunctions An [eigenfunction](https://en.wikipedia.org/wiki/Eigenfunction) of a system is defined as the input signal $x(t)$ which produces the output signal $y(t) = \mathcal{H}\{ x(t) \} = \lambda \cdot x(t)$ with $\lambda \in \mathbb{C}$. The weight $\lambda$ associated with $x(t)$ is known as scalar eigenvalue of the system. Hence besides a weighting factor, an eigenfunction is not modified by passing through the system. [Complex exponential signals](../continuous_signals/standard_signals.ipynb#Complex-Exponential-Signal) $e^{s t}$ with $s \in \mathbb{C}$ are eigenfunctions of linear time-invariant (LTI) systems. This can be proven by applying the properties of LTI systems. Lets assume a generic LTI system with input signal $x(t) = e^{s t}$ and output signal $y(t) = \mathcal{H}\{ x(t) \}$. The response of the LTI system to the shifted input signal $x(t-\tau) = e^{s (t-\tau)}$ reads \begin{equation} y(t - \tau) = \mathcal{H}\{ x(t-\tau) \} = \mathcal{H}\{ e^{-s \tau} \cdot e^{s t} \} \end{equation} due to the assumed linearity of the system this can be reformulated as \begin{equation} y(t - \tau) = e^{-s \tau} \cdot \mathcal{H}\{ e^{s t} \} = e^{-s \tau} \cdot y(t) \end{equation} It is straightforward to show that $y(t) = \lambda e^{st}$ fulfills above difference equation. **Example** An LTI system whose input/output relation is given by the following inhomogeneous linear ordinary differential equation (ODE) with constant coefficients is considered \begin{equation} a_0 y(t) + a_1 \frac{d y(t)}{dt} + a_2 \frac{d^2 y(t)}{dt^2} = x(t) \end{equation} with $a_i \in \mathbb{R} \quad \forall i$. In the remainder, the output signal $y(t)$ of the system is computed by explicit solution of the ODE for $x(t) = e^{s t}$ as input signal. Integration constants are discarded for ease of illustration. ```python %matplotlib inline import sympy as sym sym.init_printing() t, s, a0, a1, a2 = sym.symbols('t s a:3') x = sym.exp(s * t) y = sym.Function('y')(t) ode = sym.Eq(a0*y + a1*y.diff(t) + a2*y.diff(t,2), x) solution = sym.dsolve(ode) solution.subs({'C1': 0, 'C2' : 0}) ``` **Exercises** * Is the complex exponential signal an eigenfunction of the system? * Introduce $x(t) = e^{s t}$ and $y(t) = \lambda \cdot e^{s t}$ into the ODE and solve manually for the eigenvalue $\lambda$. How is the result related to above result derived by solving the ODE? * Can you generalize your findings to an ODE of arbitrary order? **Example** The following inhomogeneous linear ODE with time-dependent coefficient is considered as an example for a time-variant linear system \begin{equation} t \cdot \frac{d y(t)}{dt} = x(t) \end{equation} The output signal $y(t)$ of the system for a complex exponential signal at the input $x(t) = e^{st}$ is computed by explicit solution of the ODE. Again integration constants are discarded. ```python ode = sym.Eq(t*y.diff(t), x) solution = sym.dsolve(ode) solution.subs('C1', 0) ``` Note, $\text{Ei}(\cdot)$ denotes the [exponential integral](http://docs.sympy.org/latest/modules/functions/special.html#sympy.functions.special.error_functions.Ei). The response $y(t)$ of the time-variant system is not equal to a weighted complex exponential signal $\lambda \cdot e^{s t}$. It can be concluded that complex exponentials are no eigenfunctions of this time-variant system. **Example** A final example considers the following non-linear inhomogeneous ODE with constant coefficients \begin{equation} \left( \frac{d y(t)}{dt} \right)^2 = x(t) \end{equation} as example for a non-linear time-invariant system. Again, the output signal $y(t)$ of the system for a complex exponential signal at the input $x(t) = e^{st}$ is computed by explicit solution of the ODE. As before, integration constants are discarded. ```python ode = sym.Eq(y.diff(t)**2, x) solution = sym.dsolve(ode) solution.subs('C1', 0) ``` Obviously for this non-linear system complex exponential signals are no eigenfunctions. ## Transfer Function The complex eigenvalue $\lambda$ characterizes the properties of the transfer of a complex exponential signal $e^{st}$ with frequency $s$ through an LTI system. It is commonly termed as [*transfer function*](https://en.wikipedia.org/wiki/Transfer_function) and denoted by $H(s)=\lambda(s)$. Using this definition, the output signal $y(t)$ of an LTI system with complex exponential signal at the input reads \begin{equation} y(t) = \mathcal{H} \{ e^{st} \} = H(s) \cdot e^{st} \end{equation} Note that the concept of the transfer function is directly linked to the linearity and time-invariance of a system. Only in this case, complex exponential signals are eigenfunctions of the system and $H(s)$ describes the properties of an LTI system with respect to these. Above equation can be rewritten in terms of the magnitude $| H(s) |$ and phase $\varphi(s) = \arg \{ H(s) \}$ of the complex transfer function $H(s)$ \begin{equation} y(t) = | H(s) | \cdot e^{s t + j \varphi(s)} \end{equation} The magnitude $| H(s) |$ provides the frequency dependent attenuation of the eigenfunction $e^{st}$ by the system, while $\varphi(s)$ provides the introduced phase-shift. ## Link between Transfer Function and Impulse Response In order to establish the link between the transfer function $H(s)$ and the impulse response $h(t)$ the output signal $y(t) = \mathcal{H} \{ x(t) \}$ of an LTI system with input signal $x(t)$ is considered. It is given by convolving the input signal with the impulse response \begin{equation} y(t) = x(t) * h(t) = \int_{-\infty}^{\infty} x(t-\tau) \cdot h(\tau) \; d\tau \end{equation} For a complex exponential signal as input $x(t) = e^{st}$ the output of an LTI system is given as $y(t) = \mathcal{H} \{ e^{st} \} = H(s) \cdot e^{st}$. Introducing both signals into above convolution yields \begin{equation} H(s) \cdot e^{st} = \int_{-\infty}^{\infty} e^{st} e^{-s \tau} \cdot h(\tau) \; d\tau \end{equation} which after rearranging terms results in \begin{equation} H(s) = \int_{-\infty}^{\infty} h(\tau) \cdot e^{-s \tau} \; d\tau \end{equation} under the assumption that the integrals converge. The transfer function $H(s)$ can be computed from the impulse response $h(t)$ by integrating over the impulse response multiplied with the complex exponential function $e^{- s t}$. This constitutes an integral transformation, which is later introduced in more detail as [Laplace transform](https://en.wikipedia.org/wiki/Laplace_transform). **Copyright** The notebooks are provided as [Open Educational Resource](https://de.wikipedia.org/wiki/Open_Educational_Resources). Feel free to use the notebooks for your own educational purposes. The text is licensed under [Creative Commons Attribution 4.0](https://creativecommons.org/licenses/by/4.0/), the code of the IPython examples under the [MIT license](https://opensource.org/licenses/MIT). Please attribute the work as follows: *Lecture Notes on Signals and Systems* by Sascha Spors.
theory flash11Rev imports flashPub begin section{*Main defintions*} lemma NI_FAckVsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_FAck ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_InvVsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Inv iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by (cut_tac a1 a2 a3 a4 , auto) lemma NI_InvAck_1VsInv11: (*Rule2VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iRule2 \<le> N" and a3:"iInv1 \<le> N" and a4:"iInv2 \<le> N" and a5:"iInv1~=iInv2 " and a6:"iRule1~=iRule2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_InvAck_1 iRule1 iRule2 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3 a4 a5 a6,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_InvAck_1_HomeVsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_InvAck_1_Home iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by (cut_tac a1 a2 a3 a4 , auto) lemma NI_InvAck_2VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_InvAck_2 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by (cut_tac a1 a2 a3 a4 , auto) lemma NI_Local_GetX_GetXVsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_GetX_GetX iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_GetX_Nak1VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_GetX_Nak1 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_GetX_Nak2VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_GetX_Nak2 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_GetX_Nak3VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_GetX_Nak3 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_GetX_PutX1VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_GetX_PutX1 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv2) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv1) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_GetX_PutX2VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_GetX_PutX2 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv2) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv1) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_GetX_PutX3VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_GetX_PutX3 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv2) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv1) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_GetX_PutX4VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_GetX_PutX4 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv2) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv1) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_GetX_PutX5VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_GetX_PutX5 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv2) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv1) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_GetX_PutX6VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_GetX_PutX6 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv2) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv1) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_GetX_PutX7VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_GetX_PutX7 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv2) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv1) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_GetX_PutX8VsInv11: (*Rule2VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iRule2 \<le> N" and a3:"iInv1 \<le> N" and a4:"iInv2 \<le> N" and a5:"iInv1~=iInv2 " and a6:"iRule1~=iRule2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_GetX_PutX8 N iRule1 iRule2 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1\<and>iRule2=iInv2) \<or>(iRule1=iInv1\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 )) \<or>(iRule1=iInv2\<and>iRule2=iInv1) \<or>(iRule1=iInv2\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 )) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv1) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 )) " by( cut_tac a1 a2 a3 a4 a5 a6 , auto) moreover {assume b1:"(iRule1=iInv1\<and>iRule2=iInv2)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 a5 a6 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv2) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv1\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 ))" have "?P3 s" apply( cut_tac a1 a2 a3 a4 a5 a6 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv2) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2\<and>iRule2=iInv1)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 a5 a6 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv1) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 ))" have "?P3 s" apply( cut_tac a1 a2 a3 a4 a5 a6 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv1) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv1)" have "?P2 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv2)" have "?P2 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 ))" have "?P1 s \<or> ?P2 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_GetX_PutX8_homeVsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_GetX_PutX8_home N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv2) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv1) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_GetX_PutX9VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_GetX_PutX9 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv2) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv1) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_GetX_PutX10VsInv11: (*Rule2VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iRule2 \<le> N" and a3:"iInv1 \<le> N" and a4:"iInv2 \<le> N" and a5:"iInv1~=iInv2 " and a6:"iRule1~=iRule2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_GetX_PutX10 N iRule1 iRule2 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1\<and>iRule2=iInv2) \<or>(iRule1=iInv1\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 )) \<or>(iRule1=iInv2\<and>iRule2=iInv1) \<or>(iRule1=iInv2\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 )) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv1) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 )) " by( cut_tac a1 a2 a3 a4 a5 a6 , auto) moreover {assume b1:"(iRule1=iInv1\<and>iRule2=iInv2)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 a5 a6 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv2) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv1\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 ))" have "?P3 s" apply( cut_tac a1 a2 a3 a4 a5 a6 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv2) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2\<and>iRule2=iInv1)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 a5 a6 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv1) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 ))" have "?P3 s" apply( cut_tac a1 a2 a3 a4 a5 a6 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv1) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv1)" have "?P2 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv2)" have "?P2 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 ))" have "?P1 s \<or> ?P2 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_GetX_PutX10_homeVsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_GetX_PutX10_home N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv2) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_Dirty'') ) ( Const false )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv1) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_GetX_PutX11VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_GetX_PutX11 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_local'') ) ( Const true )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv2) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Global ''Dir_local'') ) ( Const true )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv1) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_Get_GetVsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_Get_Get iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by (cut_tac a1 a2 a3 a4 , auto) lemma NI_Local_Get_Nak1VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_Get_Nak1 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_Get_Nak2VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_Get_Nak2 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_Get_Nak3VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_Get_Nak3 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_Get_Put1VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_Get_Put1 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_Get_Put2VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_Get_Put2 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_Get_Put3VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_Get_Put3 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_PutVsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_Put ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Local_PutXAcksDoneVsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Local_PutXAcksDone ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_NakVsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Nak iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Nak_ClearVsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Nak_Clear ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Nak_HomeVsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Nak_Home ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Remote_GetX_NakVsInv11: (*Rule2VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iRule2 \<le> N" and a3:"iInv1 \<le> N" and a4:"iInv2 \<le> N" and a5:"iInv1~=iInv2 " and a6:"iRule1~=iRule2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Remote_GetX_Nak iRule1 iRule2 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1\<and>iRule2=iInv2) \<or>(iRule1=iInv1\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 )) \<or>(iRule1=iInv2\<and>iRule2=iInv1) \<or>(iRule1=iInv2\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 )) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv1) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 )) " by( cut_tac a1 a2 a3 a4 a5 a6 , auto) moreover {assume b1:"(iRule1=iInv1\<and>iRule2=iInv2)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv1\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 ))" have "?P1 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2\<and>iRule2=iInv1)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 ))" have "?P1 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv1)" have "?P2 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv2)" have "?P2 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 ))" have "?P1 s \<or> ?P2 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Remote_GetX_Nak_HomeVsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Remote_GetX_Nak_Home iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by (cut_tac a1 a2 a3 a4 , auto) lemma NI_Remote_GetX_PutXVsInv11: (*Rule2VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iRule2 \<le> N" and a3:"iInv1 \<le> N" and a4:"iInv2 \<le> N" and a5:"iInv1~=iInv2 " and a6:"iRule1~=iRule2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Remote_GetX_PutX iRule1 iRule2 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1\<and>iRule2=iInv2) \<or>(iRule1=iInv1\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 )) \<or>(iRule1=iInv2\<and>iRule2=iInv1) \<or>(iRule1=iInv2\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 )) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv1) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 )) " by( cut_tac a1 a2 a3 a4 a5 a6 , auto) moreover {assume b1:"(iRule1=iInv1\<and>iRule2=iInv2)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 a5 a6 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv2) ) ( Const UNI_PutX )) ( eqn ( IVar ( Para ''CacheState'' iInv2) ) ( Const CACHE_E )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv1\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 ))" have "?P3 s" apply( cut_tac a1 a2 a3 a4 a5 a6 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Para ''CacheState'' iRule2) ) ( Const CACHE_E )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv2) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2\<and>iRule2=iInv1)" have "?P3 s" apply( cut_tac a1 a2 a3 a4 a5 a6 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv1) ) ( Const UNI_PutX )) ( eqn ( IVar ( Para ''CacheState'' iInv1) ) ( Const CACHE_E )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 ))" have "?P3 s" apply( cut_tac a1 a2 a3 a4 a5 a6 b1 , simp) apply(rule_tac x=" (neg ( andForm ( eqn ( IVar ( Para ''CacheState'' iRule2) ) ( Const CACHE_E )) ( eqn ( IVar ( Para ''UniMsg_Cmd'' iInv1) ) ( Const UNI_PutX )) ) ) " in exI,auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv1)" have "?P2 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv2)" have "?P2 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 ))" have "?P1 s \<or> ?P2 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Remote_GetX_PutX_HomeVsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Remote_GetX_PutX_Home iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by (cut_tac a1 a2 a3 a4 , auto) lemma NI_Remote_Get_Nak1VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Remote_Get_Nak1 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by (cut_tac a1 a2 a3 a4 , auto) lemma NI_Remote_Get_Nak2VsInv11: (*Rule2VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iRule2 \<le> N" and a3:"iInv1 \<le> N" and a4:"iInv2 \<le> N" and a5:"iInv1~=iInv2 " and a6:"iRule1~=iRule2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Remote_Get_Nak2 iRule1 iRule2 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1\<and>iRule2=iInv2) \<or>(iRule1=iInv1\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 )) \<or>(iRule1=iInv2\<and>iRule2=iInv1) \<or>(iRule1=iInv2\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 )) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv1) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 )) " by( cut_tac a1 a2 a3 a4 a5 a6 , auto) moreover {assume b1:"(iRule1=iInv1\<and>iRule2=iInv2)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv1\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 ))" have "?P1 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2\<and>iRule2=iInv1)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 ))" have "?P1 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv1)" have "?P2 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv2)" have "?P2 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 ))" have "?P1 s \<or> ?P2 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Remote_Get_Put1VsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Remote_Get_Put1 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by (cut_tac a1 a2 a3 a4 , auto) lemma NI_Remote_Get_Put2VsInv11: (*Rule2VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iRule2 \<le> N" and a3:"iInv1 \<le> N" and a4:"iInv2 \<le> N" and a5:"iInv1~=iInv2 " and a6:"iRule1~=iRule2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Remote_Get_Put2 iRule1 iRule2 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1\<and>iRule2=iInv2) \<or>(iRule1=iInv1\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 )) \<or>(iRule1=iInv2\<and>iRule2=iInv1) \<or>(iRule1=iInv2\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 )) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv1) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 )) " by( cut_tac a1 a2 a3 a4 a5 a6 , auto) moreover {assume b1:"(iRule1=iInv1\<and>iRule2=iInv2)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv1\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 ))" have "?P1 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2\<and>iRule2=iInv1)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 ))" have "?P1 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv1)" have "?P2 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>iRule2=iInv2)" have "?P2 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 )\<and>(iRule2~=iInv1 \<and>iRule2~=iInv2 ))" have "?P1 s \<or> ?P2 s" apply(cut_tac a1 a2 a3 a4 a5 a6 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Remote_PutVsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Remote_Put iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Remote_PutXVsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Remote_PutX iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_ReplaceVsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Replace iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by (cut_tac a1 a2 a3 a4 , auto) lemma NI_ReplaceHomeVsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_ReplaceHome ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_ReplaceHomeShrVldVsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_ReplaceHomeShrVld ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_ReplaceShrVldVsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_ReplaceShrVld iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by (cut_tac a1 a2 a3 a4 , auto) lemma NI_ShWbVsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_ShWb N ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_WbVsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (NI_Wb ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma PI_Local_GetX_GetX1VsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (PI_Local_GetX_GetX1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma PI_Local_GetX_GetX2VsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (PI_Local_GetX_GetX2 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma PI_Local_GetX_PutX1VsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (PI_Local_GetX_PutX1 N ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma PI_Local_GetX_PutX2VsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (PI_Local_GetX_PutX2 N ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma PI_Local_GetX_PutX3VsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (PI_Local_GetX_PutX3 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma PI_Local_GetX_PutX4VsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (PI_Local_GetX_PutX4 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma PI_Local_Get_GetVsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (PI_Local_Get_Get ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma PI_Local_Get_PutVsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (PI_Local_Get_Put ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma PI_Local_PutXVsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (PI_Local_PutX ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma PI_Local_ReplaceVsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (PI_Local_Replace ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma PI_Remote_GetVsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (PI_Remote_Get iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma PI_Remote_GetXVsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (PI_Remote_GetX iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"(iRule1=iInv1) \<or>(iRule1=iInv2) \<or>((iRule1~=iInv1 \<and>iRule1~=iInv2 )) " by( cut_tac a1 a2 a3 a4 , auto) moreover {assume b1:"(iRule1=iInv1)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"(iRule1=iInv2)" have "?P1 s" apply(cut_tac a1 a2 a3 a4 b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"((iRule1~=iInv1 \<and>iRule1~=iInv2 ))" have "?P2 s" apply(cut_tac a1 a2 a3 a4 b1 , auto intro!:forallVars1 simp add :invHoldForRule2'_def varsOfVar_def) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma PI_Remote_PutXVsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (PI_Remote_PutX iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by (cut_tac a1 a2 a3 a4 , auto) lemma PI_Remote_ReplaceVsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (PI_Remote_Replace iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by (cut_tac a1 a2 a3 a4 , auto) lemma StoreVsInv11: (*Rule1VsPInv2*) assumes a1:"iRule1 \<le> N" and a2:"iInv1 \<le> N" and a3:"iInv2 \<le> N" and a4:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (Store iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by (cut_tac a1 a2 a3 a4 , auto) lemma StoreHomeVsInv11: (*Rule0VsPInv2*) assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " shows "invHoldForRule' s (inv11 iInv1 iInv2 ) (StoreHome ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3, auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed end
isSorted : Ord a => List a -> Bool isSorted [] = True isSorted [x] = True isSorted (x :: t @ (y :: ys)) = x <= y && isSorted t minElem : Ord a => (l : List a) -> { auto p : isSorted l = True } -> Maybe a minElem l = head' l prove : Ord a => (l : List a) -> Maybe (isSorted l = True) prove [] = Just $ Refl prove [x] = Just $ Refl prove (x :: y :: ys) with (x <= y) | True = prove (y :: ys) | False = Nothing main : IO () main = do line <- getLine let list = map (cast { to = Integer }) $ words line case prove list of Just _ => printLn $ minElem list Nothing => printLn "input list is not sorted"
\SetAPI{J-C} \section{ObjRefStoreBehavior} \label{feature:ObjRefStoreBehavior} \ClearAPI Optimizes memory footprint of ambeth-internal instances of \type{ObjRefStore}: The entity type and idIndex property will be compiled into each sub-class at runtime. On a x64 system this reduces necessary heap by 17\% at least - in some circumstances up to 40\%. \begin{lstlisting}[style=Java,caption={Example usage to receive a memory optimized instance of \type{ObjRefStore} (Java)}] @Autowired protected IObjRefStoreEntryProvider objRefStoreEntryProvider; public ObjRefStore optimizedObjRefStore(Object id) { return objRefStoreEntryProvider.createObjRefStore(MyEntity.class, ObjRef.PRIMARY_KEY_INDEX, id); } \end{lstlisting} \begin{lstlisting}[style=Csharp,caption={Example usage to receive a memory optimized instance of \type{ObjRefStore} (C\#)}] [Autowired] public IObjRefStoreEntryProvider ObjRefStoreEntryProvider { protected get; set; } public ObjRefStore OptimizedObjRefStore(Object id) { return ObjRefStoreEntryProvider.CreateObjRefStore(typeof(MyEntity), ObjRef.PRIMARY_KEY_INDEX); } \end{lstlisting}
If $f$ is continuous on $S$, then $\lvert f \rvert$ is continuous on $S$.
"""Mounts for use in telescope tracking control loop. A set of classes that inherit from the abstract base class TelescopeMount, providing a common API for interacting with telescope mounts. The abstraction is not perfect and some mounts may require special interfaces that go beyond what is defined by TelescopeMount. This abstraction was chosen over existing options such as INDI or ASCOM because the developers found that these frameworks did not provide access to some of the low-level features of the hardware that are required for satellite tracking applications. In particular, these frameworks do not provide the ability to directly set the slew rates of the servos. The effort required to modify them to suit the needs of this project was deemed to be higher than the effort required to just roll our own solution that provides exactly what we need in a lightweight and tailored manner. """ from abc import ABC, abstractmethod import enum from enum import IntEnum from typing import NamedTuple, Tuple import time import numpy as np from astropy import units as u from astropy.coordinates import Longitude from configargparse import Namespace import point from track.config import ArgParser class MeridianSide(IntEnum): """Indicates side of mount meridian. This is significant for equatorial mounts.""" EAST = enum.auto() WEST = enum.auto() class MountEncoderPositions(NamedTuple): """Set of mount physical encoder positions. This contains positions for telescope mounts having two motorized axes, which should cover the vast majority of amateur mounts. This code is intended for use with equatorial mounts, altitude-azimuth mounts, and equatorial mounts where the polar axis is intentionally not aligned with the celesital pole. Therefore the members of this tuple do not use the conventional axis names such as "ra" for "right-ascension" or "dec" for "declination" since these names are not appropriate in all scenarios. Both attirubutes are instances of the Astropy Longitude class since the range of values allowed by this class is [0, 360) degrees which corresponds nicely with the range of raw encoder values of most mounts after converting to degrees. Attributes: encoder_0: The axis closer to the base of the mount. For an equatorial mount this is usually the right ascension axis. For az-alt mounts this is usually the azimuth axis. encoder_1: The axis further from the base of the mount but closer to the optical tube. For an equatorial mount this is usually the declination axis. For az-alt mounts this is usually the altitude axis. """ encoder_0: Longitude encoder_1: Longitude class TelescopeMount(ABC): """Abstract base class for telescope mounts. This class provides some abstract methods to provide a common interface for telescope mounts. """ @property @abstractmethod def slew_accel(self) -> float: """Expected acceleration of when changing slew rate in degrees per second squared""" raise NotImplementedError @abstractmethod def get_position(self, max_cache_age: float = 0.0) -> MountEncoderPositions: """Gets the current position of the mount. Args: max_cache_age: If the position has been read from the mount less than this many seconds ago the function may return a cached position value in lieu of reading the position from the mount. In cases where reading from the mount is relatively slow this may allow the function to return much more quickly. The default value is set to 0 seconds, in which case the function will never return a cached value. Returns: An instance of MountEncoderPositions where the attributes are set to the current values of the encoders. The mapping of encoder values to attribute indices in this object should match the mapping used in the slew() method. """ @abstractmethod def slew(self, axis: int, rate: float) -> None: """Command the mount to slew on one axis. Commands the mount to slew at a paritcular rate in one axis. A mount may enforce limits on the slew rate such as a maximum rate limit, acceleration limit, or max change in rate since the last command. Enforcement of such limits may result in the mount moving at a rate that is different than requested. The return values indicate whether a limit was exceeded and what slew rate was actually achieved. Args: axis: The index of the axis to which this operation applies. For typical mounts having two axes the allowed values would be 0 and 1. The axes should be numbered such that the axis closes to the pedestal or tripod is axis 0, the next-closest axis is 1, and so on. This mapping should match what is used in get_position. rate: The requested slew rate in degrees per second. The sign of the value indicates the direction of the slew. Raises: ValueError if the axis is out of range for the specific mount. ValueError if the magntiude of `rate` exceeds the max supported slew rate. """ @abstractmethod def get_slew_rate(self, axis: int) -> float: """Get current slew rate on one axis. Gets the current slew rate on one mount axis. This should ideally return the actual slew rate as opposed to the last requested slew rate passed to a call to `slew()` since requested rates are not always achieved instantly, if at all, due to various physical limitations such as acceleration time and slew rate limits. Args: axis: The index of the axis to which this operation applies. Same conventions as used by `slew()`. Returns: The current slew rate of the axis in degrees per second. """ @abstractmethod def safe(self) -> bool: """Bring mount into a safe state. This method will do whatever is necessary to bring the mount into a safe state, such that there is no risk to hardware if the program terminates immediately afterward and communication with the mount stops. At minimum this method will stop all motion. Returns: True if the mount was safed successfully. False otherwise. """ @abstractmethod def no_cross_encoder_positions(self) -> MountEncoderPositions: """Indicate encoder positions that should not be crossed. For most mounts cord wrap or other physical limitations make it infeasible to slew all the way around in either axis. For some mounts there exists a set of positions on each axis that should never be crossed. For example, on a German Equatorial mount the declination axis should never cross the position where the optical tube is 180 degrees away from the celesitial pole (since this is always at or below the horizon) and the right ascension axis should never need to be positioned such that the counter weight is facing directly up since for most mounts the optical tube would collide with the tripod or pier before reaching this position. The return value of this method can be used in control software to ensure that when moving towards a particular position that the direction is chosen such that it does not cross throught these positions. This may force the control software to take a longer path than it otherwise would. Returns: The encoder positions that should not be crossed. If there is no reasonable choice (such as for the azimuth axis of an alt-az mount) the attribute of the object can be set to None. """ def predict( self, times_from_start: np.ndarray, rate_commands: np.ndarray, position_axis_start: float, slew_rate_start: float, ) -> Tuple[np.ndarray, np.ndarray]: """Predict future axis positions based on a set of future commands. Note that the slew rate commands are assumed to be issued at the *start* of each time interval and the predicted positions correspond to the *end* of the same interval (which is also the start of the following interval). Consequently, rate_commands[0] is assumed to be executed immediately (0 seconds from now), followed by rate_commands[1] executed at times_from_start[0], etc., until the last command is issued at times_from_start[-2] and the final position prediction corresponds to the end of that interval at times_from_start[-1]. Note also that Astropy objects are not used in this method for performance reasons. Args: times_from_start: An array of times in seconds measured from the starting time (t = 0). The returned position predictions will correspond to these instants in time. rate_commands: An array of slew rate commands that are assumed to be sent to the mount in the future. The size of this array must match the size of times_from_start. Note that the mount is not able to achieve these rates instantly due to acceleration limits. The predicted positions take this into account. position_axis_start: The position of the mount axis at time t = 0. slew_rate_start: The slew rate of the mount axis at time t = 0. Returns: A tuple where the first element is an array of predicted mount axis encoder positions in degrees and the second element is an array of predicted slew rates in degrees per second. Each entry in these arrays corresponds to elements in the times_from_start array. """ positions_predicted = [] rates_predicted = [] position_current = float(position_axis_start) rate_at_start_of_step = float(slew_rate_start) time_steps = np.concatenate(((times_from_start[0],), np.diff(times_from_start))) slew_accel = self.slew_accel for time_step, rate_command in zip(time_steps, rate_commands): # solve for time_accel_end time_accel_end = np.abs(rate_command - rate_at_start_of_step) / slew_accel accel = slew_accel * np.sign(rate_command - rate_at_start_of_step) # acceleration continues to the end of this timestep if time_accel_end >= time_step: position_current += accel*time_step**2 + rate_at_start_of_step*time_step positions_predicted.append(position_current) rate_at_start_of_step += accel*time_step rates_predicted.append(rate_at_start_of_step) continue # no rate change this timestep if time_accel_end == 0: position_current += rate_at_start_of_step*time_step positions_predicted.append(position_current) rates_predicted.append(rate_at_start_of_step) continue # compute position at time_accel_end, the moment accel ends / commanded rate achieved position_at_accel_end = (accel*time_accel_end**2 + rate_at_start_of_step*time_accel_end + position_current) # compute position at end of timestep position_current = rate_command*(time_step - time_accel_end) + position_at_accel_end positions_predicted.append(position_current) rate_at_start_of_step = rate_command rates_predicted.append(rate_command) return np.array(positions_predicted) % 360, np.array(rates_predicted) class NexStarMount(TelescopeMount): """Interface class to facilitate tracking with NexStar telescopes. This class implements the abstract methods in the TelescopeMount base class. The interface to the NexStar hand controller is provided by the point package. Attributes: mount: A point.NexStar object which abstracts the low-level serial command interface to the NexStar hand controller. alt_min_limit: Lower limit on the mount's altitude, which can be used to prevent the optical tube from colliding with the mount. Limit is enforced during calls to slew(). alt_max_limit: Upper limit on the mount's altitude, which can be used to prevent the optical tube from colliding with the mount. Limit is enforced during calls to slew(). bypass_position_limits (bool): If True altitude limits will not be enforced. max_slew_rate: Maximum slew rate supported by the mount in degrees per second. cached_position (MountEncoderPositions): The most recently queried encoder positions or None if get_position() has not been called since this object was constructed. cached_position_time (float): A Unix timestamp corresponding to the time at which the value in cached_position was last updated. A value of None means cached_position has never been populated. """ class AxisName(IntEnum): """Mapping from axis index to/from names""" AZIMUTH = 0 ALTITUDE = 1 def short_name(self) -> str: """Abbreviated axis name""" return 'az' if self == self.AZIMUTH else 'alt' # pylint: disable=too-many-arguments def __init__( self, device_name: str, alt_min_limit: float = 0.0, alt_max_limit: float = 65.0, bypass_position_limits: bool = False, max_slew_rate: float = 16319.0/3600.0, slew_accel: float = 10.0, ): """Inits NexStarMount object. Initializes a NexStarMount object by constructing a point.NexStar object to communicate with the hand controller and sets initial values for several class attributes. Args: device_name: A string with the name of the serial device connected to the hand controller. For example, '/dev/ttyUSB0'. alt_min_limit: Lower limit on the mount's altitude. The default value is reasonable for a NexStar 130SLT. alt_max_limit: Upper limit on the mount's altitude. The default value is reasonable for a NexStar 130SLT. bypass_position_limits: If True altitude limits will not be enforced. max_slew_rate: The maximum slew rate supported by the mount. The default value (about 4.5 deg/s) is the max rate supported by the NexStar 130SLT hand controller as determined by experimentation. slew_accel: The approximate acceleration of the mount in degrees per second squared on changing slew rates. This directly affects the accuracy of `predict()` in the parent class. """ self.mount = point.NexStar(device_name) self.alt_min_limit = alt_min_limit self.alt_max_limit = alt_max_limit self.bypass_position_limits = bypass_position_limits self.max_slew_rate = max_slew_rate self._slew_accel = slew_accel self.cached_position = None self.cached_position_time = None self._rate_last_commanded = {self.AxisName.AZIMUTH: 0.0, self.AxisName.ALTITUDE: 0.0} @property def slew_accel(self) -> float: return self._slew_accel def get_position(self, max_cache_age: float = 0.0) -> MountEncoderPositions: """Gets the current position of the mount. Gets the current position coordinates of the mount. The positions returned are as reported by the mount with no corrections applied. The position is also cached inside this object for efficient altitude limit enforcement. Args: max_cache_age: If the position has been read from the mount less than this many seconds ago, the function may return a cached position value in lieu of reading the position from the mount. In cases where reading from the mount is relatively slow this may allow the function to return much more quickly. The default value is set to 0 seconds, in which case the function will never return a cached value. Returns: An instance of MountEncoderPositions where encoder_0 is the azimuth axis and encoder_1 is the altitude axis. """ if self.cached_position is not None: time_since_cached = time.time() - self.cached_position_time if time_since_cached < max_cache_age: return self.cached_position (az, alt) = self.mount.get_azalt() self.cached_position = MountEncoderPositions( Longitude(az*u.deg), Longitude(alt*u.deg), ) self.cached_position_time = time.time() return self.cached_position def slew(self, axis: int, rate: float) -> None: """Command the mount to slew on one axis. Commands the mount to slew at a particular rate in one axis. Each axis is controlled independently. To slew in both axes, call this function twice: once for each axis. If the slew is in the altitude axis and altitude limits have been set, the function will check the mount's current position against the limits. If the limit has been violated and the slew direction is not away from the limit, the slew rate in the altitude axis will be commanded to 0. Note that the altitude limit protection is not guaranteed to prevent a collision of the optical tube against the mount for a number of reasons: 1) The limit is only checked each time this function is called 2) The motors do not respond instantly when commanded to stop 3) Altitude knowledge is dependent on good alignment 4) The limits could be set improperly To prevent unnecessary reads of the mount position, the altitude limit check will attempt to use a cached position value. However if the cached value is too old it will read the mount's position directly. Args: axis: The axis to affect. rate: The slew rate in degrees per second. The sign of the value indicates the direction of the slew. Raises: ValueError if the axis is out of range for the specific mount. ValueError if the magntiude of `rate` exceeds the max supported slew rate. """ axis = self.AxisName(axis) if abs(rate) > self.max_slew_rate: raise ValueError(f'Requested rate ({rate}) exceeds max rate ({self.max_slew_rate})') # enforce altitude limits if axis == self.AxisName.ALTITUDE and not self.bypass_position_limits: position = self.get_position(0.25) if ((position[self.AxisName.ALTITUDE].deg >= self.alt_max_limit and rate > 0.0) or (position[self.AxisName.ALTITUDE].deg <= self.alt_min_limit and rate < 0.0)): rate = 0.0 # slew_var argument units are arcseconds per second self.mount.slew_var(axis, rate * 3600.0) self._rate_last_commanded[axis] = rate def get_slew_rate(self, axis: int) -> float: """Get current slew rate of one mount axis in degrees per second. For this mount the actual slew rate cannot be queried directly from the mount hardware, therefore the best we can do is cache the last commanded rate and return that. Since the mount enforces acceleration limits automatically the mount may not have achieved the last commanded rate if this method is called soon after a large rate change. A more accurate measure of instantaneous slew rate may be possible by querying the mount position twice to calculate delta position divided by delta time. Args: axis: The axis to which this applies. Returns: The current slew rate of this mount axis in degrees per second. """ return self._rate_last_commanded[axis] def safe(self) -> bool: """Bring mount into a safe state. For this mount the only action necessary is to command the slew rate to zero on both axes. Returns: Always returns True for this mount since there is no way to query the slew rate from the mount. """ for axis in self.AxisName: self.slew(axis, 0.0) return True def no_cross_encoder_positions(self) -> MountEncoderPositions: """Indicate encoder positions that should not be crossed. Since this is an alt-az mount, only the altitude axis has a range of values that cannot be crossed. For the azimuth axis there is no particular value that should not be crossed. Returns: MountEncoderPositions: Contains the encoder positions that should not be crossed. """ return MountEncoderPositions(None, Longitude(-90*u.deg, wrap_angle=180*u.deg)) class LosmandyGeminiMount(TelescopeMount): """Interface class for Losmandy equatorial mounts with Gemini 2. This class implements the abstract methods in the TelescopeMount base class. The interface to the Gemini 2 mount computer is provided by the point package. Attributes: mount: A point.Gemini2 object which abstracts the low-level serial or UDP command interface to Gemini 2. ra_west_limit: Right ascension west of meridian limit in degrees. ra_east_limit: Right ascension east of meridian limit in degrees. bypass_position_limits: Boolean, True when RA limits are bypassed. max_slew_rate: Maximum slew rate supported by the mount in degrees per second. cached_position (MountEncoderPositions): Cached from last time position was read from the mount or None if get_position() has not been called since this object was constructed. cached_position_time (float): Unix timestamp corresponding to the time when cached_position was updated or None if it has never been set. """ class AxisName(IntEnum): """Mapping from axis index to/from names""" RIGHT_ASCENSION = 0 DECLINATION = 1 def short_name(self) -> str: """Axis names as used by the point package API for this mount""" return 'ra' if self == self.RIGHT_ASCENSION else 'dec' # pylint: disable=too-many-arguments def __init__( self, device_name: str, ra_west_limit: float = 110.0, ra_east_limit: float = 110.0, bypass_position_limits: bool = False, max_slew_rate: float = 4.0, slew_accel: float = 20.0, max_slew_step: float = 0.5, use_multiprocessing: bool = True, ): """Inits LosmandyGeminiMount object. Initializes a LosmandyGeminiMount object by constructing a point.Gemini2 object to communicate with Gemini 2 and sets initial values for several class attributes. Args: device_name: A string with the name of the serial device connected to Gemini 2 or the host name or IP address of the Gemini network interface. For example, '/dev/ttyACM0' for serial or '192.168.1.1' for network connection. ra_west_limit: Limit right ascension axis to less than this many degrees from the meridian to the west. ra_east_limit: Limit right ascension axis to less than this many degrees from the meridian to the east. bypass_position_limits: If True RA axis limits will not be enforced. max_slew_rate: The maximum allowed slew rate magnitude in degrees per second. slew_accel: The desired acceleration of the mount in degrees per second squared when changing slew rates. Higher acceleration increases the likelihood of motor stalls. max_slew_step: The maximum change in slew rate per slew command in degrees per second. Higher limits increase the likelihood of motor stalls. """ self.mount = point.Gemini2( backend=point.gemini_backend.Gemini2BackendUDP(0.25, device_name), rate_limit=max_slew_rate, rate_step_limit=max_slew_step, accel_limit=slew_accel, use_multiprocessing=use_multiprocessing, ) # If Gemini startup is not complete the coordinates it reports will not correspond to its # position. This can lead to bad behaviors such as tracking motion that never stops and # inability of this code to enforce limits on the RA axis. if self.mount.startup_check() != point.gemini_commands.G2StartupStatus.DONE_EQUATORIAL: raise RuntimeError('Gemini has not completed startup!') self.ra_west_limit = ra_west_limit self.ra_east_limit = ra_east_limit self.bypass_position_limits = bypass_position_limits self.max_slew_rate = max_slew_rate self._slew_accel = slew_accel self.cached_position = None self.cached_position_time = None @property def slew_accel(self) -> float: return self._slew_accel def get_position(self, max_cache_age: float = 0.0) -> MountEncoderPositions: """Gets the current position of the mount. Gets the current position coordinates of the mount. The positions returned are as reported by the mount with no corrections applied. Args: max_cache_age: If the position has been read from the mount less than this many seconds ago, the function may return a cached position value in lieu of reading the position from the mount. In cases where reading from the mount is relatively slow this may allow the function to return much more quickly. The default value is set to 0 seconds, in which case the function will never return a cached value. Returns: An instance of MountEncoderPositions. """ if self.cached_position is not None: time_since_cached = time.time() - self.cached_position_time if time_since_cached < max_cache_age: return self.cached_position enq = self.mount.enq_macro() self.cached_position = MountEncoderPositions( Longitude(enq['pra'] * 180.0 / 1152000 * u.deg), # motor ticks to degrees Longitude(enq['pdec'] * 180.0 / 1152000 * u.deg), # motor ticks to degrees ) self.cached_position_time = time.time() return self.cached_position def slew(self, axis: int, rate: float) -> None: """Command the mount to slew on one axis. Commands the mount to slew at a particular rate in one axis. Each axis is controlled independently. To slew in both axes, call this function twice: once for each axis. Args: axis: The axis to affect. rate: The slew rate in degrees per second. The sign of the value indicates the direction of the slew. Raises: ValueError if the axis is out of range for the specific mount. ValueError if the magntiude of `rate` exceeds the max supported slew rate. """ axis = self.AxisName(axis) if abs(rate) > self.max_slew_rate: raise ValueError(f'Requested rate ({rate}) exceeds max rate ({self.max_slew_rate})') if axis == self.AxisName.RIGHT_ASCENSION and not self.bypass_position_limits: pra = self.get_position(0.25)[self.AxisName.RIGHT_ASCENSION.value] if ((pra.deg < 180 - self.ra_west_limit and rate < 0.0) or (pra.deg > 180 + self.ra_east_limit and rate > 0.0)): rate = 0.0 self.mount.slew(axis.short_name(), rate) def get_slew_rate(self, axis: int) -> float: """Get current slew rate of one mount axis in degrees per second.""" axis = self.AxisName(axis) return self.mount.get_slew_rate(axis.short_name()) def safe(self) -> bool: """Bring mount into a safe state by stopping motion. This method blocks until motion has ceased. Returns: True when motion is stopped. Will not return otherwise. """ # This method blocks until motion on both axes has ceased. self.mount.stop_motion() return True def no_cross_encoder_positions(self) -> MountEncoderPositions: """Indicate encoder positions that should not be crossed. At startup in the counterweight down position both encoders have a value of 180 degrees. The no-cross positions are exactly 180 degrees away from these startup values, at 0 degrees. Returns: MountEncoderPositions: Contains the encoder positions that should not be crossed. """ return MountEncoderPositions(Longitude(0*u.deg), Longitude(0*u.deg)) def add_program_arguments(parser: ArgParser, meridian_side_required=False) -> None: """Add program arguments for all mounts. Args: parser: The instance of ArgParser to which this function will add arguments. meridian_side_required: When True, the meridian-side command line argument will be set as required. When False the same argument is optional. """ mount_group = parser.add_argument_group( title='Mount Options', description='Options that apply to telescope mounts', ) mount_group.add_argument( '--mount-type', help='select mount type (nexstar or gemini)', default='gemini' ) mount_group.add_argument( '--mount-path', help='serial device node or hostname for mount command interface', default='/dev/ttyACM0' ) parser.add_argument( '--bypass-position-limits', help='bypass mount axis position limits', action='store_true' ) mount_group.add_argument( '--meridian-side', help='side of meridian for equatorial mounts to prefer', required=meridian_side_required, choices=tuple(m.name.lower() for m in MeridianSide), ) def make_mount_from_args(args: Namespace, use_multiprocessing: bool = True) -> TelescopeMount: """Construct the appropriate TelescopeMount instance based on the program arguments provided. Args: args: Set of program arguments. use_multiprocessing: Passed to the LosmandyGeminiMount constructor only. Ignored for other mount types. """ if args.mount_type == 'nexstar': return NexStarMount( device_name=args.mount_path, bypass_position_limits=args.bypass_position_limits ) elif args.mount_type == 'gemini': return LosmandyGeminiMount( device_name=args.mount_path, bypass_position_limits=args.bypass_position_limits, use_multiprocessing=use_multiprocessing, ) else: raise ValueError(f'Invalid mount-type: {args.mount_type}')
import numpy as np from utils.string_helper import _make_n_gram from collections import Counter import torch def compute_batch_cost(pred_str_list, pred_sent_2d_list, trg_str_list, trg_sent_2d_list, batch_size, cost_types, device): with torch.no_grad(): #num_cost_types = len(cost_types) batch_cost_list = [] #batch_cost_2d = np.zeros((batch_size, num_cost_types)) for i, cost_type in enumerate(cost_types): if cost_type == 0: cost_func = has_three_gram_repeat elif cost_type == 1: cost_func = min_len_cost else: raise ValueError("No matched cost function type.") batch_cost_list.append(cost_func(pred_str_list, pred_sent_2d_list, trg_str_list, trg_sent_2d_list, batch_size, device)) #batch_cost_2d[:, i] = cost_func(pred_str_list, pred_sent_2d_list, trg_str_list, trg_sent_2d_list, batch_size) batch_cost_2d = torch.stack(batch_cost_list, dim=1) # tensor: [batch, num_cost_types] return batch_cost_2d def num_three_gram_repeat(pred_str_list, pred_sent_2d_list, trg_str_list, trg_sent_2d_list, batch_size, device): # return the number of 3-gram repeat for each prediciton sequence in the batch batch_cost = np.zeros(batch_size) for batch_i, pred_str in enumerate(pred_str_list): three_gram_counter = Counter() three_gram_counter.update(_make_n_gram(pred_str, n=3)) three_gram_repeat = sum(c - 1 for g, c in three_gram_counter.items() if c > 1) batch_cost[batch_i] = three_gram_repeat return torch.from_numpy(batch_cost).type(torch.FloatTensor).to(device) # tensor: [batch_size] def has_three_gram_repeat(pred_str_list, pred_sent_2d_list, trg_str_list, trg_sent_2d_list, batch_size, device): # return the number of 3-gram repeat for each prediciton sequence in the batch #batch_cost = np.zeros(batch_size) batch_cost = [] for batch_i, pred_str in enumerate(pred_str_list): three_gram_counter = Counter() three_gram_counter.update(_make_n_gram(pred_str, n=3)) three_gram_repeat = sum(c - 1 for g, c in three_gram_counter.items() if c > 1) if three_gram_repeat > 0: cost = 1.0 else: cost = 0.0 batch_cost.append(cost) return torch.FloatTensor(batch_cost).to(device) # tensor: [batch_size] def min_len_cost(pred_str_list, pred_sent_2d_list, trg_str_list, trg_sent_2d_list, batch_size, device): batch_cost = [] for batch_i, pred_str in enumerate(pred_str_list): if len(pred_str) < 20: cost = 1.0 else: cost = 0.0 batch_cost.append(cost) return torch.FloatTensor(batch_cost).to(device) # tensor: [batch_size]
lemma connected_intermediate_closure: assumes cs: "connected s" and st: "s \<subseteq> t" and ts: "t \<subseteq> closure s" shows "connected t"
(* Copyright (C) 2017 M.A.L. Marques This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *) (* type: mgga_exc *) (* Equations are from the Appendix of Kurth1999_889 *) $include "gga_c_gapc.mpl" gap_par0[10] = 0.06483*((9*Pi)/4)^(2/3): (* this is approximately equal to 0.23878 *) (* Eq. (A4) *) kcis_G := (rs, xt) -> xt^2*n_total(rs)^(2/3)/8: (* Eq. (A9) *) kcis_t := (rs, xt) -> 2^(2/3)*xt/(8*sqrt(rs)): kcis_beta := 0.066725: (* Eq. (A7) *) kcis_gga0 := (rs, xt) -> f_pw(rs, 0)/(1 + kcis_beta*log(1 + kcis_t(rs, xt)^2/m_abs(f_pw(rs, 0)))): (* Eq. (A8) *) kcis_gga1 := (rs, xt) -> f_pw(rs, 1)/(1 + kcis_beta*log(1 + 2^(-1/3)*kcis_t(rs, xt)^2/m_abs(f_pw(rs, 1)))): (* Eq. (A5) *) (* The polarized parameters are the same as the unpolarized ones *) (* except that c_1, c_2, c_3 are multiplied by 0.7. 1.5, and 2.59 respectively *) kcis_eps_0 := (rs, xt) -> + (kcis_gga0(rs, xt) + gap_c1(rs, 0, gap_par0)*kcis_G(rs, xt)) / (1 + gap_c2(rs, 0, gap_par0)*kcis_G(rs, xt) + gap_c3(rs, 0, gap_par0)*kcis_G(rs, xt)^2): (* Eq. (A6) *) kcis_eps_1 := (rs, xt) -> + (kcis_gga1(rs, xt) + 0.7*gap_c1(rs, 0, gap_par0)*kcis_G(rs, xt)) / (1 + 1.5*gap_c2(rs, 0, gap_par0)*kcis_G(rs, xt) + 2.59*gap_c3(rs, 0, gap_par0)*kcis_G(rs, xt)^2): (* Eq. (A2) *) gap_f := (rs, z, xt) -> + kcis_eps_0(rs, xt) + f_zeta(z)*(kcis_eps_1(rs, xt) - kcis_eps_0(rs, xt)): (* Eq. (A1) *) kcis_f := (rs, z, xt, xs0, xs1, ts0, ts1) -> + gap_f(rs, z, xt) - xs0^2/(8*ts0) * opz_pow_n( z,1)/2 * gap_f(rs*(2/(1 + z))^(1/3), 1, xs0) - xs1^2/(8*ts1) * opz_pow_n(-z,1)/2 * gap_f(rs*(2/(1 - z))^(1/3), -1, xs1): f := (rs, z, xt, xs0, xs1, us0, us1, ts0, ts1) -> kcis_f(rs, z, xt, xs0, xs1, ts0, ts1):
%!TeX TXS-program:bibliography = txs:///biber %!TeX program = xelatex \documentclass[research,19]{idcc} \usepackage[utf8]{inputenc} \usepackage{graphicx} \usepackage{listings} \usepackage{hyperref} \hypersetup{ colorlinks, linkcolor={black}, citecolor={black}, urlcolor={blue} } \usepackage{float} \usepackage{acronym} \usepackage{setspace} \usepackage{etoolbox} %%% Just comment out one or the other of the "togglefalse/toggletrue" pairs \newtoggle{final} \newtoggle{blind} \togglefalse{final} %\toggletrue{final} %\toggletrue{blind} \togglefalse{blind} \iftoggle{blind}{ \usepackage{draftwatermark} \SetWatermarkText{blinded \today} \SetWatermarkLightness{0.9} \SetWatermarkScale{0.3} }{} \iftoggle{final}{}{ \usepackage{draftwatermark} \SetWatermarkText{SUBMITTED - DO NOT DISTRIBUTE} \SetWatermarkLightness{0.9} \SetWatermarkScale{0.3} } % to read the table \usepackage{csvsimple} \usepackage{longtable} \usepackage{booktabs} % for adding a flex space to the metajelo macro \usepackage{xspace} % to adjust floats \usepackage{placeins} % for hyphenating the TT font in the table \usepackage[htt]{hyphenat} % better tt font \usepackage[scaled=0.8]{beramono} \hyphenation{institution-Sustaina-bility super-Organization-Name institutionPolicy-FreeText} \input{acrodefs.tex} %\usepackage{natbib} %\usepackage[sorting=nyt,maxnames=10,backend=biber]{biblatex} \usepackage[style=apa,natbib,sortcites,backend=biber,date=year]{biblatex} \AtEveryBibitem{\clearfield{month}} \AtEveryBibitem{\clearfield{day}} %\DeclareLanguageMapping{american}{american-apa} \DeclareLanguageMapping{british}{british-apa} \addbibresource{references.bib} \addbibresource{references-zotero.bib} \addbibresource{aej-rep.bib} % Table \usepackage{array} \newcolumntype{L}[1]{>{\raggedright\let\newline\\\arraybackslash\hspace{0pt}}p{#1}} \newcolumntype{C}[1]{>{\centering\let\newline\\\arraybackslash\hspace{0pt}}p{#1}} \newcolumntype{R}[1]{>{\raggedleft\let\newline\\\arraybackslash\hspace{0pt}}p{#1}} % Different ways to cite URLS %\newcommand{\urlcite}[2]{\href{#1}{#2} \newcommand{\urlcite}[2]{#2\footnote{\url{#1}}} % \newcommand{\metajelo}{\texttt{metajelo}\xspace} % % Metadata \iftoggle{blind}{ \author{AUTHOR} \affil{University} \correspondence{Email: \email{[email protected]}} }% { % full names only when not blinded \author{Carl Lagoze} \affil{University of Michigan} \author{Lars Vilhuber} \affil{Cornell University} \correspondence{Lars Vilhuber. Email: \email{[email protected]}} } \title{metajelo: A metadata package for journals to support external linked objects} %\conference{14th International Digital Curation Conference} \submitted{December 2018} \begin{document} \maketitle \begin{abstract} \input{abstract} \end{abstract} \section{Introduction} \label{sec:intro} \input{idcc2019-introduction} \section{Background} \label{sec:background} \input{idcc2019-background.tex} \section{Use Case} \label{sec:usecase} \input{idcc2019-usecase} \section{Related Metadata and Efforts} \label{sec:related-metadata} \input{idcc2019-related-metadata} \section{Metadata Package} \label{sec:metadata-package} \label{sec:approach} \input{idcc2019-metadata-package} \FloatBarrier \section{Usability Notes} \label{sec:usability} \input{idcc2019-usability} \section{Acknowledgements} \label{sec:ack} \iftoggle{blind}{[Acknowledgements blinded.]}{ \input{idcc2019-acknowledgements}} %\bibliographystyle{chicagoa} %\bibliography{references.bib} \printbibliography %\appendix \FloatBarrier \section{Appendix: Detailed Use Cases} \label{app:cases} \newcommand{\suppDir}{supplementary_materials} \input{\suppDir/usecase-appendix} \FloatBarrier %\section{Appendix: Full query response for Use Case 1} %\lstinputlisting[language=xml]{\suppDir/datacite-api-100590.xml} \end{document}
module Specdris.Core import Specdris.Data.SpecInfo import Specdris.Data.SpecResult import Specdris.Data.SpecState %access export %default total ||| BTree with elements in the leafs. public export data Tree : Type -> Type where Leaf : (elem : a) -> Tree a Node : (left : Tree a) -> (right : Tree a) -> Tree a public export SpecTree' : FFI -> Type SpecTree' ffi = Tree (Either SpecInfo (IO' ffi SpecResult)) public export SpecTree : Type SpecTree = SpecTree' FFI_C namespace SpecTreeDo (>>=) : SpecTree' ffi -> (() -> SpecTree' ffi) -> SpecTree' ffi (>>=) leftTree f = let rightTree = f () in Node leftTree rightTree {- Evaluates every leaf in the `SpecTree` and folds the different `IO`s to collect a final `SpecState`. Test: describe "a" $ do describe "b" $ do it "c" test_io_c it "d" test_io_d Tree from Test: Node | ---------------------------------- | | Leaf Desc "a" Node | --------------------- | | Node Node | | ------------- --------------- | | | | Leaf Desc "b" Node Leaf It "d" Leaf test_io_d | ---------------- | | Leaf It "c" Leaf test_io_c -} evaluateTree : SpecTree' ffi -> SpecState -> (around : IO' ffi SpecResult -> IO' ffi SpecResult) -> (storeOutput : Bool) -> (level : Nat) -> IO' ffi SpecState -- description or it evaluateTree (Leaf (Left info)) state _ store level = let out = evalInfo info level in if store then pure $ addLine out state else do putStrLn' out pure state -- test case evaluateTree (Leaf (Right specIO)) state around store level = evalResult !(around specIO) state store level -- recursive step evaluateTree (Node left right) state around store level = case left of -- node containing a description/it -> new level of output indentation (Leaf _) => do newState <- evaluateTree left state around store (level + 1) evaluateTree right newState around store (level + 1) _ => do newState <- evaluateTree left state around store level evaluateTree right newState around store level evaluate : (around : IO' ffi SpecResult -> IO' ffi SpecResult) -> (storeOutput : Bool) -> SpecTree' ffi -> IO' ffi SpecState evaluate around store tree = evaluateTree tree neutral around store 0 randomBase : Integer randomBase = pow 2 32 randomInt : (seed : Integer) -> Integer randomInt seed = assert_total ((1664525 * seed + 1013904223) `prim__sremBigInt` randomBase) randomDouble : (seed : Integer) -> Double randomDouble seed = let value = randomInt seed in (cast {to = Double} value) / (cast {to = Double} randomBase) partial shuffle : {default randomDouble rand : Integer -> Double} -> SpecTree' ffi -> (seed : Integer) -> SpecTree' ffi shuffle {rand} (Node left@(Leaf _) right@(Leaf _)) seed = Node left right shuffle {rand} (Node left@(Leaf (Left (Describe _))) right) seed = Node left (shuffle {rand = rand} right seed) shuffle {rand} (Node left@(Node _ _) right@(Node _ _)) seed = let randVal = rand seed nextSeed = (cast {to = Integer} randVal) * 100 in if randVal > 0.5 then Node (shuffle {rand = rand} left nextSeed) (shuffle {rand = rand} right nextSeed) else Node (shuffle {rand = rand} right nextSeed) (shuffle {rand = rand} left nextSeed)
module Tactic.Monoid.Exp where open import Prelude open import Tactic.Reflection.Quote open import Tactic.Deriving.Quotable data Exp : Set where var : Nat → Exp ε : Exp _⊕_ : Exp → Exp → Exp unquoteDecl QuoteExp = deriveQuotable QuoteExp (quote Exp) flatten : Exp → List Nat flatten (var x) = x ∷ [] flatten ε = [] flatten (e ⊕ e₁) = flatten e ++ flatten e₁
Formal statement is: lemma closure_greaterThan[simp]: fixes a b::"'a::{no_top, linorder_topology, dense_order}" shows "closure {a<..} = {a..}" Informal statement is: The closure of the set of all real numbers greater than $a$ is the set of all real numbers greater than or equal to $a$.
(* Copyright (C) 2017 M.A.L. Marques This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *) (* type: lda_exc *) (* prefix: lda_c_chachiyo_params *params; assert(p->params != NULL); params = (lda_c_chachiyo_params * )(p->params); *) e0 := rs -> params_a_ap*log(1 + params_a_bp/rs + params_a_bp/rs^2): e1 := rs -> params_a_af*log(1 + params_a_bf/rs + params_a_bf/rs^2): f_chachiyo := (rs, zeta) -> e0(rs) + (e1(rs) - e0(rs))*f_zeta(zeta): f := (rs, zeta) -> f_chachiyo(rs, zeta):
Formal statement is: lemma AE_all_countable: "(AE x in M. \<forall>i. P i x) \<longleftrightarrow> (\<forall>i::'i::countable. AE x in M. P i x)" Informal statement is: For all countable $i$, $P_i$ holds almost everywhere if and only if $P_i$ holds almost everywhere for all countable $i$.
function joinvec(embed::WordEmbedding, words::Vector, fn::Function, wv::Array=[]) for word in words if !haskey(embed.embedding, word) warn("'$word' not present in the vocabulary") return wv end if isempty(wv) wv = vec(embed.embedding[word]) else wv = fn(wv, vec(embed.embedding[word])) end end wv end function find_nearest_words(embed::WordEmbedding, words::AbstractString; k=5) positive_words = AbstractString[] negative_words = AbstractString[] wordlist = positive_words for tok in split(words) tok = strip(tok) isempty(tok) && continue if tok == "+" wordlist = positive_words elseif tok == "-" wordlist = negative_words else push!(wordlist, tok) end end find_nearest_words(embed, positive_words, negative_words; k=k) end function find_nearest_words(embed::WordEmbedding, positive_words::Vector, negative_words::Vector; k=5) pq = PriorityQueue(Base.Order.Reverse) wv = joinvec(embed, positive_words, .+, Array[]) wv = joinvec(embed, negative_words, .-, wv) if !isempty(wv) for (w, embed_w) in embed.embedding ((w in positive_words) || (w in negative_words)) && continue dist = cosine_dist(wv, vec(embed_w)) enqueue!(pq, w, dist) (length(pq) > k) && dequeue!(pq) end end sort(collect(pq), by = t -> t[2]) end
open import Data.List using (List; _∷_; []) open import Data.Product using (_×_; _,_; Σ) open import Data.Unit using (⊤; tt) open import Relation.Binary.PropositionalEquality using (_≡_) module SystemT where data _∈_ {A : Set} : (x : A) (l : List A) → Set where -- type \in i0 : {x : A} {xs : List A} → x ∈ (x ∷ xs) iS : {x y : A} {xs : List A} → x ∈ xs → x ∈ (y ∷ xs) data TType : Set where base : TType _⟶_ : TType → TType → TType Context = List TType _,,_ : Context → TType → Context Γ ,, τ = τ ∷ Γ infixr 10 _⟶_ infixr 9 _,,_ infixr 8 _⊢_ data _⊢_ (Γ : Context) : TType → Set where -- Some constant of the base type whose type is immediate. c : Γ ⊢ base -- Variable. var : {τ : TType} → τ ∈ Γ → Γ ⊢ τ -- Function introduction. lam : {τ₁ τ₂ : TType} → Γ ,, τ₁ ⊢ τ₂ → Γ ⊢ τ₁ ⟶ τ₂ -- Function application. app : {τ₁ τ₂ : TType} → (Γ ⊢ τ₁ ⟶ τ₂) → Γ ⊢ τ₁ → Γ ⊢ τ₂ module Semantics (B : Set) (elB : B) where -- Interpretation of System T types to Agda types. ⟦_⟧t : TType → Set ⟦ base ⟧t = B ⟦ τ₁ ⟶ τ₂ ⟧t = ⟦ τ₁ ⟧t → ⟦ τ₂ ⟧t -- Interpretation of System T contexts to Agda types. ⟦_⟧c : Context → Set ⟦ [] ⟧c = ⊤ ⟦ τ ∷ Γ ⟧c = ⟦ Γ ⟧c × ⟦ τ ⟧t -- Interpretation of terms. ⟦_⟧ : {Γ : Context} {τ : TType} → (Γ ⊢ τ) → ⟦ Γ ⟧c → ⟦ τ ⟧t ⟦ c ⟧ γ = elB ⟦ var x ⟧ γ = {! !} ⟦ lam e ⟧ γ x = {! !} ⟦ app e₁ e₂ ⟧ γ = {! !}
navbarPage( # tab title windowTitle = "TAF Advice Tool", id = "tabset", fluid = TRUE, # navbar title title = shiny::div(img( src = "ICES_logo_orange.PNG", style = "margin-top: -14px; padding-right:10px;padding-bottom:10px", height = 60 )), #tabsetPanel(#id = "tabset", tabPanel( "Data Filtering", sidebarLayout( sidebarPanel = maps_panels, mainPanel = selectize_panel ) # ) ), tabPanel( "Stock Selection", DTOutput("tbl")#, # useShinyjs(), # inlineCSS(list("table1" = "font-size: 15px")) ), tabPanel( "Stock development over time", sidebarLayout( sidebarPanel = allocations_infopanel, mainPanel = allocations_plotspanel ) # includeMarkdown("Instructions.Rmd") ), tabPanel( "Catch Options & Advice", sidebarPanel( width = 3, DTOutput("Advice_View")#, # useShinyjs(), # inlineCSS(list("table2" = "font-size: 10px")) ), # browser(), # mainPanel(# this is not running # width = 9, # htmlOutput("Advice_Sentence"), # div( # class = "outer", # tags$style(type = "text/css", ".outer {position: relative; top: 61px; left: 0; right: 0; bottom: 61px; overflow: hidden; padding: 50}"), # plotlyOutput("catch_scenario_plot_1", width = "100%", height = "100%")), # # plotlyOutput("catch_scenario_plot_2"), # div( # class = "outer", # tags$style(type = "text/css", ".outer {position: relative; top: 61px; left: 0; right: 0; bottom: 61px; overflow: hidden; padding: 50}"), # plotlyOutput("catch_scenario_plot_2",width = "100%", height = "100%")), # # DTOutput("catch_scenario_table") # div( # class = "outer", # tags$style(type = "text/css", ".outer {position: relative; top: 61px; left: 0; right: 0; bottom: 61px; overflow: hidden; padding: 50}"), # DTOutput("catch_scenario_table",width = "100%", height = "100%")) # ) mainPanel( width = 9, plotlyOutput("catch_scenario_plot_1"), plotlyOutput("catch_scenario_plot_2"), DTOutput("catch_scenario_table") ) # verbatimTextOutput("In_Construction") ), tabPanel( "Resources", verbatimTextOutput("headline") ), #),# close tabsetpanel # extra tags, css etc tags$style(type = "text/css", "li {font-size: 20px;}"), tags$style(type = "text/css", "p {font-size: 21px;}"), tags$style(type = "text/css", "body {padding-top: 70px;}"), tags$head(tags$style(HTML("#go{background-color:#14c6dd}"))), ##dd4814 0range theme = shinytheme("united"), ##### need to work on this, the orange is part of the css theme united, check bslib in forked repo position = "fixed-top", tags$script(HTML("var header = $('.navbar > .container-fluid'); header.append('<div style=\"float:right\"><a href=\"https://github.com/ices-tools-dev/online-advice\"><img src=\"GitHub-Mark-32px.png\" alt=\"alt\" style=\"margin-top: -14px; padding-right:5px;padding-top:25px;\"></a></div>'); console.log(header)")) )
```python !pip install qiskit ``` Collecting qiskit Downloading https://files.pythonhosted.org/packages/6f/61/cb7506e17a2566dc8a31a3e1924d91ac0bdd8ff07c71ec698c06647b6306/qiskit-0.26.2.tar.gz Collecting qiskit-terra==0.17.4 [?25l Downloading https://files.pythonhosted.org/packages/b3/0c/3c7a8dd451dae0907263e9de9e3e34909e15e18c88a589b44581972c8511/qiskit_terra-0.17.4-cp37-cp37m-manylinux2010_x86_64.whl (6.0MB)  |████████████████████████████████| 6.0MB 5.2MB/s [?25hCollecting qiskit-aer==0.8.2 [?25l Downloading https://files.pythonhosted.org/packages/c2/d2/6ff15c370b5465b32529b528bf3f4ce1e01f74498be16203aa1c04b67022/qiskit_aer-0.8.2-cp37-cp37m-manylinux2010_x86_64.whl (18.0MB)  |████████████████████████████████| 18.0MB 215kB/s [?25hCollecting qiskit-ibmq-provider==0.13.1 [?25l Downloading https://files.pythonhosted.org/packages/be/99/74bbb901f88603a7d850d4889abc06d81ba702e4227151f4a5b66f2631fe/qiskit_ibmq_provider-0.13.1-py3-none-any.whl (228kB)  |████████████████████████████████| 235kB 47.1MB/s [?25hCollecting qiskit-ignis==0.6.0 [?25l Downloading https://files.pythonhosted.org/packages/54/be/a13c828e457e09d979667a61bddbd8c7246aafa94e2501b6a9154429cbea/qiskit_ignis-0.6.0-py3-none-any.whl (207kB)  |████████████████████████████████| 215kB 42.6MB/s [?25hCollecting qiskit-aqua==0.9.1 [?25l Downloading https://files.pythonhosted.org/packages/88/79/392c57b978decbb24b902344b536af52c40a751aed0ebbaefa8bc2964cb5/qiskit_aqua-0.9.1-py3-none-any.whl (2.1MB)  |████████████████████████████████| 2.1MB 31.4MB/s [?25hRequirement already satisfied: scipy>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.4.1) Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (2.6.0) Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (2.8.1) Collecting fastjsonschema>=2.10 Downloading https://files.pythonhosted.org/packages/d1/fb/ea090e917b18320f79be31d754bbe496b715175e865603cfce1eaed2e774/fastjsonschema-2.15.1-py3-none-any.whl Collecting ply>=3.10 [?25l Downloading https://files.pythonhosted.org/packages/a3/58/35da89ee790598a0700ea49b2a66594140f44dec458c07e8e3d4979137fc/ply-3.11-py2.py3-none-any.whl (49kB)  |████████████████████████████████| 51kB 5.7MB/s [?25hRequirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.7.1) Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (0.3.3) Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (5.4.8) Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.19.5) Collecting python-constraint>=1.4 Downloading https://files.pythonhosted.org/packages/37/8b/5f1bc2734ca611943e1d6733ee244238679f6410a10cd45ede55a61a8402/python-constraint-1.4.0.tar.bz2 Collecting retworkx>=0.8.0 [?25l Downloading https://files.pythonhosted.org/packages/9e/cd/70d436f170aa1ead2ac9e4c19c8838633355d48b530f09455eab0af2f98e/retworkx-0.9.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.4MB)  |████████████████████████████████| 1.5MB 27.3MB/s [?25hCollecting pybind11>=2.6 [?25l Downloading https://files.pythonhosted.org/packages/8d/43/7339dbabbc2793718d59703aace4166f53c29ee1c202f6ff5bf8a26c4d91/pybind11-2.6.2-py2.py3-none-any.whl (191kB)  |████████████████████████████████| 194kB 28.1MB/s [?25hCollecting websockets>=8 [?25l Downloading https://files.pythonhosted.org/packages/84/64/78c2b3fe37730b30dca3c93d1f7f4a4286767f86e7c04cf3571b39bc2fb7/websockets-9.1-cp37-cp37m-manylinux2010_x86_64.whl (103kB)  |████████████████████████████████| 112kB 53.2MB/s [?25hRequirement already satisfied: nest-asyncio!=1.1.0,>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (1.5.1) Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (2.23.0) Collecting requests-ntlm>=1.1.0 Downloading https://files.pythonhosted.org/packages/03/4b/8b9a1afde8072c4d5710d9fa91433d504325821b038e00237dc8d6d833dc/requests_ntlm-1.1.0-py2.py3-none-any.whl Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (1.24.3) Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.6.0->qiskit) (56.1.0) Requirement already satisfied: h5py<=3.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (3.1.0) Requirement already satisfied: scikit-learn<=0.24.1,>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (0.22.2.post1) Requirement already satisfied: pandas<=1.2.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (1.1.5) Collecting yfinance<=0.1.55 Downloading https://files.pythonhosted.org/packages/7a/e8/b9d7104d3a4bf39924799067592d9e59119fcfc900a425a12e80a3123ec8/yfinance-0.1.55.tar.gz Collecting quandl<=3.6.0 Downloading https://files.pythonhosted.org/packages/c2/58/9f0e69d836045e3865d263e9ed49f42b23a58526fdabb30f74c430baee3f/Quandl-3.6.0-py2.py3-none-any.whl Collecting dlx<=1.0.4 Downloading https://files.pythonhosted.org/packages/54/c0/b8fb5bb727e983b6f5251433ef941b48f38c65bb0bd6ec509e9185bcd406/dlx-1.0.4.tar.gz Collecting docplex<=2.20.204; sys_platform != "darwin" [?25l Downloading https://files.pythonhosted.org/packages/87/99/6f7c219b39fd58c84688ad0713eb932bfcf6be81fc74519e43ea9c915b56/docplex-2.20.204.tar.gz (611kB)  |████████████████████████████████| 614kB 31.8MB/s [?25hRequirement already satisfied: fastdtw<=0.3.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (0.3.4) Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-terra==0.17.4->qiskit) (1.15.0) Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra==0.17.4->qiskit) (1.2.1) Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (2020.12.5) Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (2.10) Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (3.0.4) Collecting ntlm-auth>=1.0.2 Downloading https://files.pythonhosted.org/packages/ff/84/97c550164b54942b0e908c31ef09d9469f3ba4cd7332a671e2125732f63b/ntlm_auth-1.5.0-py2.py3-none-any.whl Collecting cryptography>=1.3 [?25l Downloading https://files.pythonhosted.org/packages/b2/26/7af637e6a7e87258b963f1731c5982fb31cd507f0d90d91836e446955d02/cryptography-3.4.7-cp36-abi3-manylinux2014_x86_64.whl (3.2MB)  |████████████████████████████████| 3.2MB 32.7MB/s [?25hRequirement already satisfied: cached-property; python_version < "3.8" in /usr/local/lib/python3.7/dist-packages (from h5py<=3.1.0->qiskit-aqua==0.9.1->qiskit) (1.5.2) Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn<=0.24.1,>=0.20.0->qiskit-aqua==0.9.1->qiskit) (1.0.1) Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas<=1.2.3->qiskit-aqua==0.9.1->qiskit) (2018.9) Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance<=0.1.55->qiskit-aqua==0.9.1->qiskit) (0.0.9) Collecting lxml>=4.5.1 [?25l Downloading https://files.pythonhosted.org/packages/30/c0/d0526314971fc661b083ab135747dc68446a3022686da8c16d25fcf6ef07/lxml-4.6.3-cp37-cp37m-manylinux2014_x86_64.whl (6.3MB)  |████████████████████████████████| 6.3MB 28.8MB/s [?25hRequirement already satisfied: more-itertools in /usr/local/lib/python3.7/dist-packages (from quandl<=3.6.0->qiskit-aqua==0.9.1->qiskit) (8.7.0) Collecting inflection>=0.3.1 Downloading https://files.pythonhosted.org/packages/59/91/aa6bde563e0085a02a435aa99b49ef75b0a4b062635e606dab23ce18d720/inflection-0.5.1-py2.py3-none-any.whl Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit) (1.14.5) Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit) (2.20) Building wheels for collected packages: qiskit, python-constraint, yfinance, dlx, docplex Building wheel for qiskit (setup.py) ... [?25l[?25hdone Created wheel for qiskit: filename=qiskit-0.26.2-cp37-none-any.whl size=10491 sha256=f918bb498cb8dbde768f9544d24f28176928a4a92eaa20342c52edbb0938f4dd Stored in directory: /root/.cache/pip/wheels/89/89/34/524839952d5a58a7be9789e580bfc1ca883bf6579152444568 Building wheel for python-constraint (setup.py) ... [?25l[?25hdone Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24079 sha256=35b086ebd96ea7a2891fb5e52f5485c24ae251f78fec828a2895254c5038edb3 Stored in directory: /root/.cache/pip/wheels/34/31/15/7b070b25d0a549d20ce2e9fe6d727471c2c61ef904720fd40c Building wheel for yfinance (setup.py) ... [?25l[?25hdone Created wheel for yfinance: filename=yfinance-0.1.55-py2.py3-none-any.whl size=22616 sha256=5f1fe2d1709cbbfaf38cdf03a09dc41d437133e2554f1b41c2392074f45c9943 Stored in directory: /root/.cache/pip/wheels/04/98/cc/2702a4242d60bdc14f48b4557c427ded1fe92aedf257d4565c Building wheel for dlx (setup.py) ... [?25l[?25hdone Created wheel for dlx: filename=dlx-1.0.4-cp37-none-any.whl size=5712 sha256=1154e839748f8d28680d5d7c922c454909954f6b3a334a5b7633ba059156b7e1 Stored in directory: /root/.cache/pip/wheels/bb/ba/15/fdd0deb104df3254912998150ba9245668db06b00af5912d1a Building wheel for docplex (setup.py) ... [?25l[?25hdone Created wheel for docplex: filename=docplex-2.20.204-cp37-none-any.whl size=675362 sha256=9494f9dd2dec35c5b52e88a18051305c0b7307ab107312f9b0d514a546535200 Stored in directory: /root/.cache/pip/wheels/ae/2c/e2/a099ebb6fda8adeba9c5fc2e25659d195ad2f5c6cc5fb75fd4 Successfully built qiskit python-constraint yfinance dlx docplex ERROR: qiskit-aqua 0.9.1 has requirement retworkx<=0.8.0,>=0.7.0, but you'll have retworkx 0.9.0 which is incompatible. Installing collected packages: fastjsonschema, ply, python-constraint, retworkx, qiskit-terra, pybind11, qiskit-aer, websockets, ntlm-auth, cryptography, requests-ntlm, qiskit-ibmq-provider, qiskit-ignis, lxml, yfinance, inflection, quandl, dlx, docplex, qiskit-aqua, qiskit Found existing installation: lxml 4.2.6 Uninstalling lxml-4.2.6: Successfully uninstalled lxml-4.2.6 Successfully installed cryptography-3.4.7 dlx-1.0.4 docplex-2.20.204 fastjsonschema-2.15.1 inflection-0.5.1 lxml-4.6.3 ntlm-auth-1.5.0 ply-3.11 pybind11-2.6.2 python-constraint-1.4.0 qiskit-0.26.2 qiskit-aer-0.8.2 qiskit-aqua-0.9.1 qiskit-ibmq-provider-0.13.1 qiskit-ignis-0.6.0 qiskit-terra-0.17.4 quandl-3.6.0 requests-ntlm-1.1.0 retworkx-0.9.0 websockets-9.1 yfinance-0.1.55 ```python !pip install qiskit-nature ``` Collecting qiskit-nature [?25l Downloading https://files.pythonhosted.org/packages/4c/54/2562684ccf73215d3d85b65174ea06ee3f1b184422cfd81241a8a13491cd/qiskit_nature-0.1.3-py3-none-any.whl (1.5MB)  |████████████████████████████████| 1.5MB 6.5MB/s [?25hRequirement already satisfied: h5py in /usr/local/lib/python3.7/dist-packages (from qiskit-nature) (3.1.0) Requirement already satisfied: scipy>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-nature) (1.4.1) Requirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-nature) (0.22.2.post1) Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-nature) (56.1.0) Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-nature) (5.4.8) Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from qiskit-nature) (1.19.5) Requirement already satisfied: qiskit-terra>=0.17.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-nature) (0.17.4) Requirement already satisfied: cached-property; python_version < "3.8" in /usr/local/lib/python3.7/dist-packages (from h5py->qiskit-nature) (1.5.2) Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.20.0->qiskit-nature) (1.0.1) Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-nature) (2.8.1) Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-nature) (0.3.3) Requirement already satisfied: retworkx>=0.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-nature) (0.9.0) Requirement already satisfied: ply>=3.10 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-nature) (3.11) Requirement already satisfied: python-constraint>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-nature) (1.4.0) Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-nature) (1.7.1) Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-nature) (2.6.0) Requirement already satisfied: fastjsonschema>=2.10 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-nature) (2.15.1) Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-terra>=0.17.0->qiskit-nature) (1.15.0) Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra>=0.17.0->qiskit-nature) (1.2.1) Installing collected packages: qiskit-nature Successfully installed qiskit-nature-0.1.3 ```python !pip install pyscf ``` Collecting pyscf [?25l Downloading https://files.pythonhosted.org/packages/ef/d6/af4ce5035977cb011e4dbe9979bf254129a36d48cb569b86e57b5a72c5b1/pyscf-1.7.6.post1-cp37-cp37m-manylinux1_x86_64.whl (29.7MB)  |████████████████████████████████| 29.7MB 145kB/s [?25hRequirement already satisfied: numpy!=1.16,!=1.17,>1.8 in /usr/local/lib/python3.7/dist-packages (from pyscf) (1.19.5) Requirement already satisfied: scipy!=1.5.0,!=1.5.1 in /usr/local/lib/python3.7/dist-packages (from pyscf) (1.4.1) Requirement already satisfied: h5py>2.2 in /usr/local/lib/python3.7/dist-packages (from pyscf) (3.1.0) Requirement already satisfied: cached-property; python_version < "3.8" in /usr/local/lib/python3.7/dist-packages (from h5py>2.2->pyscf) (1.5.2) Installing collected packages: pyscf Successfully installed pyscf-1.7.6.post1 ```python from qiskit_nature.drivers import PySCFDriver #Importing pyscf module to enable simulation of chemical molecules molecule = 'Li 0.0 0.0 0.0; H 0.0 0.0 1.5474'#These represent the coordinates of the atoms in the molcule driver = PySCFDriver(atom=molecule) qmolecule = driver.run() ``` ```python n_mo = qmolecule.num_molecular_orbitals print(n_mo)#This prints the total number of molecular orbitals which is 6 here from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem #To produce list of fermionic operators from qiskit_nature.transformers import FreezeCoreTransformer #Freezing the core to reduce the number of qubits #In order to find out which orbitals to freeze, I checked the corresponding exact ground energy value by freezing all the orbitals in the range (0,5) and chose the ones which were closer to the threshold value tr = FreezeCoreTransformer(True,[3,4])#Freezing orbitals 3 and 4 problem = ElectronicStructureProblem(driver,[tr]) second_q_ops = problem.second_q_ops()#Generating the second-quantized operators main_op = second_q_ops[0]#Hamiltonian ``` 6 ```python from qiskit_nature.mappers.second_quantization import ParityMapper, BravyiKitaevMapper, JordanWignerMapper from qiskit_nature.converters.second_quantization.qubit_converter import QubitConverter #Setting up the mapper and qubit converter #Defining mapping for representing molecular orbitals using qubits mapper = ParityMapper() converter = QubitConverter(mapper=mapper, two_qubit_reduction=True)#,z2symmetry_reduction=[-1,1])#Uncomment to apply z2symmetry # The fermionic operators are mapped to qubit operators num_particles = (problem.molecule_data_transformed.num_alpha, problem.molecule_data_transformed.num_beta) qubit_op = converter.convert(main_op, num_particles=num_particles) print(qubit_op.z2_symmetries)#This prints the symmetries present in the molecule . I didn't apply z2symmetry because I already reduce the number of qubits to 4 ``` Z2 symmetries: Symmetries: IIIZII ZIIIII Single-Qubit Pauli X: IIIXII XIIIII Cliffords: 0.7071067811865475 * IIIZII + 0.7071067811865475 * IIIXII 0.7071067811865475 * ZIIIII + 0.7071067811865475 * XIIIII Qubit index: [2, 5] Tapering values: [-1, 1] ```python from qiskit_nature.circuit.library import HartreeFock #To implement hartreefrock state as the initial state num_particles = (problem.molecule_data_transformed.num_alpha, problem.molecule_data_transformed.num_beta) num_spin_orbitals = 2 * problem.molecule_data_transformed.num_molecular_orbitals init_state = HartreeFock(num_spin_orbitals, num_particles, converter) print(init_state) ``` ┌───┐ q_0: ┤ X ├ ├───┤ q_1: ┤ X ├ └───┘ q_2: ───── q_3: ───── ```python from qiskit.circuit.library import TwoLocal #Choosing a quantum circuit to approximate ground state #Parameters for q-UCC antatze num_particles = (problem.molecule_data_transformed.num_alpha, problem.molecule_data_transformed.num_beta) num_spin_orbitals = 2 * problem.molecule_data_transformed.num_molecular_orbitals #Using TwoLocal ansatz with the following parameters because it uses least number of CNOTs found out by Hit and Trial #Single qubit rotations that are placed on all qubits with independent parameters rotation_blocks = ['ry', 'rz'] #Entangling gates entanglement_blocks = 'cx' #How the qubits are entangled entanglement = 'linear' #Repetitions of rotation_blocks + entanglement_blocks with independent parameters repetitions = 1 # Not skipping the final rotation_blocks layer skip_final_rotation_layer = False ansatz = TwoLocal(qubit_op.num_qubits, rotation_blocks, entanglement_blocks, reps=repetitions, entanglement=entanglement, skip_final_rotation_layer=skip_final_rotation_layer) print(ansatz) ``` ┌──────────┐┌──────────┐ ┌──────────┐┌───────────┐ » q_0: ┤ RY(θ[0]) ├┤ RZ(θ[4]) ├──■──┤ RY(θ[8]) ├┤ RZ(θ[12]) ├─────────────» ├──────────┤├──────────┤┌─┴─┐└──────────┘└┬──────────┤┌───────────┐» q_1: ┤ RY(θ[1]) ├┤ RZ(θ[5]) ├┤ X ├─────■───────┤ RY(θ[9]) ├┤ RZ(θ[13]) ├» ├──────────┤├──────────┤└───┘ ┌─┴─┐ └──────────┘├───────────┤» q_2: ┤ RY(θ[2]) ├┤ RZ(θ[6]) ├────────┤ X ├──────────■──────┤ RY(θ[10]) ├» ├──────────┤├──────────┤ └───┘ ┌─┴─┐ ├───────────┤» q_3: ┤ RY(θ[3]) ├┤ RZ(θ[7]) ├─────────────────────┤ X ├────┤ RY(θ[11]) ├» └──────────┘└──────────┘ └───┘ └───────────┘» « «q_0: ───────────── « «q_1: ───────────── « ┌───────────┐ «q_2: ┤ RZ(θ[14]) ├ « ├───────────┤ «q_3: ┤ RZ(θ[15]) ├ « └───────────┘ ```python from qiskit import Aer #To specify the simulator for the algorithm to run on backend = Aer.get_backend('statevector_simulator') ``` ```python from qiskit.algorithms.optimizers import SLSQP optimizer = SLSQP(maxiter=2000)#This optimiser gave the correct energy value for the chosen ansatz ``` ```python from qiskit_nature.algorithms.ground_state_solvers.minimum_eigensolver_factories import NumPyMinimumEigensolverFactory from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver import numpy as np #Trying to solve the problem using exact diagonalization of the Hamiltonian def exact_diagonalizer(problem, converter): solver = NumPyMinimumEigensolverFactory() calc = GroundStateEigensolver(converter, solver) result = calc.solve(problem) return result result_exact = exact_diagonalizer(problem, converter) exact_energy = np.real(result_exact.eigenenergies[0]) print("Exact electronic energy", exact_energy) print(result_exact) # The targeted electronic energy for LiH is -1.086 Ha ``` Exact electronic energy -1.0887060157347406 === GROUND STATE ENERGY === * Electronic ground state energy (Hartree): -8.907396311316 - computed part: -1.088706015735 - FreezeCoreTransformer extracted energy part: -7.818690295581 ~ Nuclear repulsion energy (Hartree): 1.025934879643 > Total ground state energy (Hartree): -7.881461431673 === MEASURED OBSERVABLES === 0: # Particles: 2.000 S: 0.000 S^2: 0.000 M: 0.000 === DIPOLE MOMENTS === ~ Nuclear dipole moment (a.u.): [0.0 0.0 2.92416221] 0: * Electronic dipole moment (a.u.): [0.0 0.0 4.76300889] - computed part: [0.0 0.0 4.76695575] - FreezeCoreTransformer extracted energy part: [0.0 0.0 -0.00394686] > Dipole moment (a.u.): [0.0 0.0 -1.83884668] Total: 1.83884668 (debye): [0.0 0.0 -4.67388163] Total: 4.67388163 ```python from qiskit.algorithms import VQE from IPython.display import display, clear_output #Importing VQE to run the algorithim def callback(eval_count, parameters, mean, std): display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std)) clear_output(wait=True) counts.append(eval_count) values.append(mean) params.append(parameters) deviation.append(std) counts = [] values = [] params = [] deviation = [] #Default fixed small displacement try: initial_point = [0.01] * len(ansatz.ordered_parameters) except: initial_point = [0.01] * ansatz.num_parameters algorithm = VQE(ansatz, optimizer=optimizer, quantum_instance=backend, callback=callback, initial_point=initial_point) result = algorithm.compute_minimum_eigenvalue(qubit_op) print(result) ``` { 'aux_operator_eigenvalues': None, 'cost_function_evals': 851, 'eigenstate': array([-1.38503080e-03-3.73975129e-05j, 4.83798144e-03+6.36745268e-05j, -2.66978013e-02-3.06676159e-04j, 9.91386592e-01+1.39272516e-03j, 5.38283495e-02+5.40890327e-04j, 3.28152532e-04+9.93615636e-06j, -9.07220622e-04+4.32502418e-06j, 2.39114676e-02-3.84502735e-04j, 2.72891302e-03+4.22182794e-05j, 9.36230793e-06+1.71620611e-06j, -5.91311396e-06-6.28705625e-06j, -2.73155829e-04+2.34338973e-04j, -1.13726193e-01+2.30850218e-04j, -4.47959858e-04-1.66081270e-05j, 5.62790023e-04-7.93456918e-06j, -2.66622417e-04+1.18701780e-05j]), 'eigenvalue': -1.0863663677292887, 'optimal_parameters': { ParameterVectorElement(θ[4]): -0.004768579123950326, ParameterVectorElement(θ[12]): -0.010069423154352004, ParameterVectorElement(θ[5]): -0.0037985015266241207, ParameterVectorElement(θ[6]): -0.005513500988743045, ParameterVectorElement(θ[7]): -0.0010895487469465151, ParameterVectorElement(θ[8]): 0.05313368644547072, ParameterVectorElement(θ[9]): -0.00977072471667363, ParameterVectorElement(θ[10]): 0.047986900543765254, ParameterVectorElement(θ[13]): -0.011810269141820076, ParameterVectorElement(θ[14]): -0.017507464711468492, ParameterVectorElement(θ[15]): -0.012680710973539674, ParameterVectorElement(θ[1]): 0.005744855621419048, ParameterVectorElement(θ[11]): 0.44182324189775946, ParameterVectorElement(θ[0]): -2.8892613849526074, ParameterVectorElement(θ[3]): -0.44239241452227135, ParameterVectorElement(θ[2]): -3.1410072751603506}, 'optimal_point': array([-2.88926138e+00, 4.79869005e-02, 4.41823242e-01, -1.00694232e-02, -1.18102691e-02, -1.75074647e-02, -1.26807110e-02, 5.74485562e-03, -3.14100728e+00, -4.42392415e-01, -4.76857912e-03, -3.79850153e-03, -5.51350099e-03, -1.08954875e-03, 5.31336864e-02, -9.77072472e-03]), 'optimal_value': -1.0863663677292887, 'optimizer_evals': 851, 'optimizer_time': 9.800698041915894} ```python #Storing results in a dictionary from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller #Transpiling circuit into CNOTs and U gates pass_ = Unroller(['u', 'cx']) pm = PassManager(pass_) ansatz_tp = pm.run(ansatz) cnots = ansatz_tp.count_ops()['cx'] score = cnots accuracy_threshold = 4.0 #in mHa energy = result.optimal_value result_dict = { 'optimizer': optimizer.__class__.__name__, 'mapping': converter.mapper.__class__.__name__, 'ansatz': ansatz.__class__.__name__, 'rotation blocks': rotation_blocks, 'entanglement_blocks': entanglement_blocks, 'entanglement': entanglement, 'repetitions': repetitions, 'skip_final_rotation_layer': skip_final_rotation_layer, 'energy (Ha)': energy, 'error (mHa)': (energy-exact_energy)*1000, 'pass': (energy-exact_energy)*1000 <= accuracy_threshold, '# of parameters': len(result.optimal_point), 'final parameters': result.optimal_point, '# of evaluations': result.optimizer_evals, 'optimizer time': result.optimizer_time, '# of qubits': int(qubit_op.num_qubits), '# of CNOTs': cnots, 'score': score} #Plotting the results import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) ax.set_xlabel('Iterations') ax.set_ylabel('Energy') ax.grid() fig.text(0.7, 0.75, f'Energy: {result.optimal_value:.3f}\nScore: {score:.0f}') plt.title(f"{result_dict['optimizer']}-{result_dict['mapping']}\n{result_dict['ansatz']}") ax.plot(counts, values) ax.axhline(exact_energy, linestyle='--') fig_title = f"\ {result_dict['optimizer']}-\ {result_dict['mapping']}-\ {result_dict['ansatz']}-\ Energy({result_dict['energy (Ha)']:.3f})-\ Score({result_dict['score']:.0f})\ .png" fig.savefig(fig_title, dpi=300) #Displaying and saving the data import pandas as pd import os.path filename = 'results_h2.csv' if os.path.isfile(filename): result_df = pd.read_csv(filename) result_df = result_df.append([result_dict]) else: result_df = pd.DataFrame.from_dict([result_dict]) result_df.to_csv(filename) result_df[['optimizer','ansatz', '# of qubits', '# of parameters','rotation blocks', 'entanglement_blocks', 'entanglement', 'repetitions', 'error (mHa)', 'pass', 'score']] ``` ```python ```
\section{IPC and Threads} \label{ipc} \input{desc-ipc.tex} %\input{model-ipc.tex} \input{desc-threads.tex} %\input{model-threads.tex}
Require Import QArith_base. Require Import Qcanon. Require Import Equalities. Require Import Orders. Require Import OrdersTac. Local Open Scope Qc_scope. Module Qc_as_DT <: DecidableTypeFull. Lemma Qc_eq_bool_iff : forall x y, Qc_eq_bool x y = true <-> x = y. Proof. intros. split. apply Qc_eq_bool_correct. intro. unfold Qc_eq_bool. destruct (Qc_eq_dec x y). reflexivity. contradiction. Qed. Definition t := Qc. Definition eq := @eq Qc. Definition eq_equiv := @eq_equivalence Qc. Definition eqb := Qc_eq_bool. Definition eqb_eq := Qc_eq_bool_iff. Include BackportEq. Include HasEqBool2Dec. End Qc_as_DT. Module Qc_as_OT <: OrderedTypeFull. Lemma Qccompare_spec (x y : Qc) : CompareSpec (x=y) (x<y) (x>y) (x ?= y). Proof. now case_eq (x ?= y); constructor; [rewrite Qceq_alt | rewrite Qclt_alt | rewrite Qcgt_alt]. Qed. Include Qc_as_DT. Definition lt := Qclt. Definition le := Qcle. Definition compare := Qccompare. Instance lt_strorder : StrictOrder Qclt. Proof. split. intro. apply Qlt_irrefl. intros x y z. apply Qlt_trans. Qed. Instance lt_compat : Proper (eq==>eq==>iff) Qclt. Proof. intros x y Hxy z t Hzt. now rewrite Hxy, Hzt. Qed. Theorem le_lteq : forall x y : t, le x y <-> lt x y \/ eq x y. Proof. intros x y. unfold le,lt,eq. split; intro H. destruct (Qcle_lt_or_eq _ _ H). now left. right. assumption. destruct H. now apply Qlt_le_weak. subst. now apply Qcle_refl. Qed. Definition compare_spec (x y : Qc) := Qccompare_spec x y. End Qc_as_OT.
theory flash112Rev imports flashPub begin section{*Main defintions*} lemma NI_FAckVsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (NI_FAck ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by( auto) lemma NI_InvVsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Inv iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_InvAck_1VsInv112: (*Rule2VsPInv0*) assumes a1:"iRule1 \<le> N" and a2:"iRule2 \<le> N" and a3:"iRule1~=iRule2 " shows "invHoldForRule' s (inv112 ) (NI_InvAck_1 iRule1 iRule2 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_InvAck_1_HomeVsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_InvAck_1_Home iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_InvAck_2VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_InvAck_2 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Local_GetX_GetXVsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_GetX_GetX iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Local_GetX_Nak1VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_GetX_Nak1 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Local_GetX_Nak2VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_GetX_Nak2 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Local_GetX_Nak3VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_GetX_Nak3 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Local_GetX_PutX1VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_GetX_PutX1 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P1 s" apply(cut_tac a1 , auto) done then show "?P1 s\<or> ?P2 s\<or> ?P3 s" by blast qed lemma NI_Local_GetX_PutX2VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_GetX_PutX2 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P1 s" apply(cut_tac a1 , auto) done then show "?P1 s\<or> ?P2 s\<or> ?P3 s" by blast qed lemma NI_Local_GetX_PutX3VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_GetX_PutX3 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P1 s" apply(cut_tac a1 , auto) done then show "?P1 s\<or> ?P2 s\<or> ?P3 s" by blast qed lemma NI_Local_GetX_PutX4VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_GetX_PutX4 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P1 s" apply(cut_tac a1 , auto) done then show "?P1 s\<or> ?P2 s\<or> ?P3 s" by blast qed lemma NI_Local_GetX_PutX5VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_GetX_PutX5 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P1 s" apply(cut_tac a1 , auto) done then show "?P1 s\<or> ?P2 s\<or> ?P3 s" by blast qed lemma NI_Local_GetX_PutX6VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_GetX_PutX6 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P1 s" apply(cut_tac a1 , auto) done then show "?P1 s\<or> ?P2 s\<or> ?P3 s" by blast qed lemma NI_Local_GetX_PutX7VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_GetX_PutX7 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P1 s" apply(cut_tac a1 , auto) done then show "?P1 s\<or> ?P2 s\<or> ?P3 s" by blast qed lemma NI_Local_GetX_PutX8VsInv112: (*Rule2VsPInv0*) assumes a1:"iRule1 \<le> N" and a2:"iRule2 \<le> N" and a3:"iRule1~=iRule2 " shows "invHoldForRule' s (inv112 ) (NI_Local_GetX_PutX8 N iRule1 iRule2 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P1 s" apply(cut_tac a1 a2 a3 , auto) done then show "?P1 s\<or> ?P2 s\<or> ?P3 s" by blast qed lemma NI_Local_GetX_PutX8_homeVsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_GetX_PutX8_home N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P1 s" apply(cut_tac a1 , auto) done then show "?P1 s\<or> ?P2 s\<or> ?P3 s" by blast qed lemma NI_Local_GetX_PutX9VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_GetX_PutX9 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Local_GetX_PutX10VsInv112: (*Rule2VsPInv0*) assumes a1:"iRule1 \<le> N" and a2:"iRule2 \<le> N" and a3:"iRule1~=iRule2 " shows "invHoldForRule' s (inv112 ) (NI_Local_GetX_PutX10 N iRule1 iRule2 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Local_GetX_PutX10_homeVsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_GetX_PutX10_home N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Local_GetX_PutX11VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_GetX_PutX11 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P1 s" apply(cut_tac a1 , auto) done then show "?P1 s\<or> ?P2 s\<or> ?P3 s" by blast qed lemma NI_Local_Get_GetVsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_Get_Get iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Local_Get_Nak1VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_Get_Nak1 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Local_Get_Nak2VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_Get_Nak2 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Local_Get_Nak3VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_Get_Nak3 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Local_Get_Put1VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_Get_Put1 N iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Local_Get_Put2VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_Get_Put2 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Local_Get_Put3VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Local_Get_Put3 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P1 s" apply(cut_tac a1 , auto) done then show "?P1 s\<or> ?P2 s\<or> ?P3 s" by blast qed lemma NI_Local_PutVsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (NI_Local_Put ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"formEval ( andForm ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) s \<or>formEval ( andForm ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) (neg ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) ) s \<or>formEval ( andForm (neg ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) s \<or>formEval ( andForm (neg ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) (neg ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) ) s " by auto moreover {assume b1:"formEval ( andForm ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) s" have "?P1 s" apply(cut_tac b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"formEval ( andForm ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) (neg ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) ) s" have "?P1 s" apply(cut_tac b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"formEval ( andForm (neg ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) s" have "?P1 s" apply(cut_tac b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"formEval ( andForm (neg ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) (neg ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) ) s" have "?P1 s" apply(cut_tac b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma NI_Local_PutXAcksDoneVsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (NI_Local_PutXAcksDone ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P1 s" apply( auto) done then show "?P1 s\<or> ?P2 s\<or> ?P3 s" by blast qed lemma NI_NakVsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Nak iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Nak_ClearVsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (NI_Nak_Clear ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by( auto) lemma NI_Nak_HomeVsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (NI_Nak_Home ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by( auto) lemma NI_Remote_GetX_NakVsInv112: (*Rule2VsPInv0*) assumes a1:"iRule1 \<le> N" and a2:"iRule2 \<le> N" and a3:"iRule1~=iRule2 " shows "invHoldForRule' s (inv112 ) (NI_Remote_GetX_Nak iRule1 iRule2 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Remote_GetX_Nak_HomeVsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Remote_GetX_Nak_Home iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Remote_GetX_PutXVsInv112: (*Rule2VsPInv0*) assumes a1:"iRule1 \<le> N" and a2:"iRule2 \<le> N" and a3:"iRule1~=iRule2 " shows "invHoldForRule' s (inv112 ) (NI_Remote_GetX_PutX iRule1 iRule2 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Remote_GetX_PutX_HomeVsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Remote_GetX_PutX_Home iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Remote_Get_Nak1VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Remote_Get_Nak1 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Remote_Get_Nak2VsInv112: (*Rule2VsPInv0*) assumes a1:"iRule1 \<le> N" and a2:"iRule2 \<le> N" and a3:"iRule1~=iRule2 " shows "invHoldForRule' s (inv112 ) (NI_Remote_Get_Nak2 iRule1 iRule2 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Remote_Get_Put1VsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Remote_Get_Put1 iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Remote_Get_Put2VsInv112: (*Rule2VsPInv0*) assumes a1:"iRule1 \<le> N" and a2:"iRule2 \<le> N" and a3:"iRule1~=iRule2 " shows "invHoldForRule' s (inv112 ) (NI_Remote_Get_Put2 iRule1 iRule2 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1 a2 a3,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Remote_PutVsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Remote_Put iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_Remote_PutXVsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Remote_PutX iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_ReplaceVsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_Replace iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_ReplaceHomeVsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (NI_ReplaceHome ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by( auto) lemma NI_ReplaceHomeShrVldVsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (NI_ReplaceHomeShrVld ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by( auto) lemma NI_ReplaceShrVldVsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (NI_ReplaceShrVld iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma NI_ShWbVsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (NI_ShWb N ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by( auto) lemma NI_WbVsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (NI_Wb ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by( auto) lemma PI_Local_GetX_GetX1VsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (PI_Local_GetX_GetX1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by( auto) lemma PI_Local_GetX_GetX2VsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (PI_Local_GetX_GetX2 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by( auto) lemma PI_Local_GetX_PutX1VsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (PI_Local_GetX_PutX1 N ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P1 s" apply( auto) done then show "?P1 s\<or> ?P2 s\<or> ?P3 s" by blast qed lemma PI_Local_GetX_PutX2VsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (PI_Local_GetX_PutX2 N ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P1 s" apply( auto) done then show "?P1 s\<or> ?P2 s\<or> ?P3 s" by blast qed lemma PI_Local_GetX_PutX3VsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (PI_Local_GetX_PutX3 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P1 s" apply( auto) done then show "?P1 s\<or> ?P2 s\<or> ?P3 s" by blast qed lemma PI_Local_GetX_PutX4VsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (PI_Local_GetX_PutX4 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P1 s" apply( auto) done then show "?P1 s\<or> ?P2 s\<or> ?P3 s" by blast qed lemma PI_Local_Get_GetVsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (PI_Local_Get_Get ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by( auto) lemma PI_Local_Get_PutVsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (PI_Local_Get_Put ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have allCases:"formEval ( andForm ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) s \<or>formEval ( andForm ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) (neg ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) ) s \<or>formEval ( andForm (neg ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) s \<or>formEval ( andForm (neg ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) (neg ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) ) s " by auto moreover {assume b1:"formEval ( andForm ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) s" have "?P1 s" apply(cut_tac b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"formEval ( andForm ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) (neg ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) ) s" have "?P1 s" apply(cut_tac b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"formEval ( andForm (neg ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) s" have "?P1 s" apply(cut_tac b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } moreover {assume b1:"formEval ( andForm (neg ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) (neg ( eqn ( IVar ( Para ''InvMarked'' Home) ) ( Const true )) ) ) s" have "?P1 s" apply(cut_tac b1 , auto) done then have "?P1 s\<or> ?P2 s \<or> ?P3 s" by blast } ultimately show "?P1 s\<or> ?P2 s\<or> ?P3 s" by metis qed lemma PI_Local_PutXVsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (PI_Local_PutX ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P1 s" apply( auto) done then show "?P1 s\<or> ?P2 s\<or> ?P3 s" by blast qed lemma PI_Local_ReplaceVsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (PI_Local_Replace ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P1 s" apply( auto) done then show "?P1 s\<or> ?P2 s\<or> ?P3 s" by blast qed lemma PI_Remote_GetVsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (PI_Remote_Get iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma PI_Remote_GetXVsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (PI_Remote_GetX iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma PI_Remote_PutXVsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (PI_Remote_PutX iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma PI_Remote_ReplaceVsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (PI_Remote_Replace iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma StoreVsInv112: (*Rule1VsPInv0*) assumes a1:"iRule1 \<le> N" shows "invHoldForRule' s (inv112 ) (Store iRule1 ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") proof - have "?P2 s" by (cut_tac a1,auto ) then show "?P1 s\<or>?P2 s\<or>?P3 s" by auto qed lemma StoreHomeVsInv112: (*Rule0VsPInv0*) shows "invHoldForRule' s (inv112 ) (StoreHome ) (invariants N)" (is " ?P1 s\<or>?P2 s\<or>?P3 s") by( auto) end
import Data.String import Data.Vect StringOrInt : Bool -> Type StringOrInt False = String StringOrInt True = Int getStringOrInt : (isInt : Bool) -> StringOrInt isInt getStringOrInt False = "Ninety four" getStringOrInt True = 94 valToString : (isInt : Bool) -> StringOrInt isInt -> String valToString False y = trim y valToString True y = cast y valToString' : (isInt : Bool) -> (case isInt of False => String True => Int) -> String valToString' False y = trim y valToString' True y = cast y
Formal statement is: lemma prime_product: fixes p::nat assumes "prime (p * q)" shows "p = 1 \<or> q = 1" Informal statement is: If $p$ and $q$ are natural numbers such that $pq$ is prime, then $p = 1$ or $q = 1$.
> module Unique.Properties > import Data.Fin > import Control.Isomorphism > import Unique.Predicates > import Decidable.Predicates > import Finite.Predicates > import Sigma.Sigma > %default total > %access public export > ||| > uniqueLemma : {A : Type} -> {P : A -> Type} -> ((a : A) -> Unique (P a)) -> > (a1 : A) -> (a2 : A) -> (pa1 : P a1) -> (pa2 : P a2) -> > (a1 = a2) -> pa1 = pa2 > uniqueLemma {A} {P} prf a a pa1 pa2 Refl = prf a pa1 pa2 > %freeze uniqueLemma > ||| Unique properties are finite > uniqueFiniteLemma1 : {P : Type} -> P -> Unique P -> Finite P > uniqueFiniteLemma1 {P} p uP = MkSigma n (MkIso to from toFrom fromTo) where > n : Nat > n = S Z > to : P -> Fin n > to x = FZ > from : Fin n -> P > from FZ = p > from (FS k) = absurd k > toFrom : (k : Fin n) -> to (from k) = k > toFrom FZ = Refl > toFrom (FS k) = absurd k > fromTo : (x : P) -> from (to x) = x > fromTo x = uP p x > %freeze uniqueFiniteLemma1 > ||| Unique properties are finite > uniqueFiniteLemma2 : {P : Type} -> Not P -> Finite P > uniqueFiniteLemma2 {P} contra = MkSigma n (MkIso to from toFrom fromTo) where > n : Nat > n = Z > to : P -> Fin n > to x = void (contra x) > from : Fin n -> P > from k = absurd k > toFrom : (k : Fin n) -> to (from k) = k > toFrom k = absurd k > fromTo : (x : P) -> from (to x) = x > fromTo x = void (contra x) > %freeze uniqueFiniteLemma2 > ||| Decidable and unique properties are finite > decUniqueFiniteLemma : {P : Type} -> Dec P -> Unique P -> Finite P > decUniqueFiniteLemma (Yes p) uP = uniqueFiniteLemma1 p uP > decUniqueFiniteLemma (No contra) _ = uniqueFiniteLemma2 contra > %freeze decUniqueFiniteLemma > {- > ---}
A stunning development opportunity - large building with consent to convert to a dwelling. Attractive setting. 5/6 Bedrooms. Excellent views. Exciting design. Very accessible. Near to Thorverton. Paddock. 1.7 acres. Thorverton is a delightful and very popular Exe Valley village, which includes a primary school, two public houses, two churches, superb village hall, local cricket and football clubs, and a community shop/post office. The area is known for unspoilt and beautiful countryside and yet Thorverton is only 7 miles from the Cathedral and University City of Exeter, which has an extensive range of facilities befitting a city of its importance. Access to the M5 motorway can be made at Junctions 27, 28, 29 & 30. Mainline railway stations on the London Paddington and Waterloo lines can be found at Exeter (Tiverton Parkway next to Junction 27 of the M5 on the Paddington line too.) Exeter International Airport lies to the east of the city. To the north of Thorverton the market town of Tiverton has a further range of facilities, including the well renowned Blundell's School, which offers discounts to local pupils. Exeter has an excellent range of schools for all ages. The properties location and position are superb, looking out over rolling farmland. Thorverton is within walking distance and Exeter very accessible with quick commuting access along the A396. The plans showing the design of the property can be found on Www.middevon.gov.uk/ see below. The accommodation is over two floors with mezzanines covering about 400 M2. It includes entrance hall, study, open plan kitchen, dining and living area, sitting room, utility, cloakroom, landing, 5 bedrooms, 4 shower/bathrooms. There is large feature glazing taking advantage of the views and looking out over the land included with the property and beyond. Attached to the barn is a lean-to which provides garaging within the plans. The barn is surrounded by 1.7 acres providing space to create parking and turning and garden around the property as per the consent. Beyond the garden is an area of field positioned directly behind the barn. This will enable a main aspect of the barn to look down over its land. Change of use approval was granted on 20th December 2018 by Mid Devon District Council. Reference number 18/01620/PNCOU. On the home page click on planning. Then click on 'search and comment on planning applications.' Then click on 'search', and then finally, in the search box, enter in the reference number 18/01620/PNCOU. The documents can be looked at by clicking on 'documents'. The purchaser will be required to erect, as a minimum standard, a stock proof fence between points A, B and C. Strictly by appointment via the agents, Stags, on 01884 235705. In the centre of Thorverton turn opposite the Thorverton Arms signposted Cadbury, passing the Church on your left and proceed out of the village. After passing through the national speed limit signs take the next turning left, signposted Cadbury. Continue up the hill and down the other side and the barn will be found on the left. Mains electricity. Purchaser to install new water supply and private drainage. The vendor will supply water for an initial period of time while the property is developed.
\chapter{State Estimation} \label{state_estimation} % \textcolor{red}{TODO: Rewrite sections that don't flow and give credit where appropriate.} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \section{Ranging Setup and Calibration} \label{ranging} \label{txt:ranging} This section introduces the hardware and software setup for a set of wireless ranging modules to enable position tracking of the robot both as an as internal distance measurements (end cap to end cap) an in an external (world) reference frame. All MTRs of \SB{} are equipped with a DWM1000 ranging module from DecaWave Ltd. By employing ultra wideband technology, the low-cost DWM1000 modules provide wireless data transfer and highly accurate timestamps of transmitted and received packets. This allows the distance between two DWM1000 modules to be estimated by computing the time-of-flight of exchanged messages without the need for synchronized clocks. %We opted for this technology because it allows proprioceptive state estimation (distances between end caps), which %cannot be easily tracked directly via motor encoders.~\cite{ledergerber2015} Furthermore, we Using DWM1000 modules external to \SB{} as "fixed anchors" and placing them around the testing area, a world reference frame for ground truth and generation of a reward signal for the machine learning algorithms used for learning locomotion is obtained. %Our intention is that the fixed anchors will not be required in the final deployed %version of the robot, and are primarily for use during algorithm development. It is intended that the final deployed version of the robot and controller will not require fixed anchors, and they are primarily used during algorithm development. % We first introduce the basic sensor operation and our approach to efficiently estimate distances between a large number of sensor modules. % This is followed by a discussion of our ranging software and hardware setup. % Finally, we provide a calibration routine similar to a common motion capture system that allows for quick set up of the sensor network. \subsection{Sensor Operation} \subsubsection{Bidirectional Ranging} The DWM1000 modules are operated in the so-called \emph{symmetric double-sided two-way ranging} mode. In this mode, the modules exchange $3$ packets to estimate the time-of-flight between each other. While the time-of-flight of unsynchronized modules can be estimated with the exchange of only $2$ packets, the employed mode can significantly reduce measurement noise~\cite{decawave}. The basic ranging packet exchange is shown in Fig.~\ref{fig:bidirectional_ranging}. Module 1 sends out a \emph{poll} message containing an emission timestamp ($t_{SP}$) using its local clock. Module 2 receives this message and timestamps the time of arrival using its local clock ($t_{RP}$). Then, module 2 sends out a \emph{response} packet at time $t_{SR}$ (module 2's clock). Module 1 receives this packet at time $t_{RR}$ (module 1's clock). Module 1 now sends out a final message containing $t_{RR}$ and the emission time of the final message ($t_{SF}$, clock of module 1). Module 2 receives this information and timestamps it ($t_{RF}$). \begin{figure}[tpbh] \centering \includegraphics[width=.8\linewidth]{tex/img/bidirectional_ranging.pdf} \caption{Basic symmetric double-side two-way ranging packet exchange. Modules 1 and 2 exchange 3 packets (\emph{poll}, \emph{response}, and \emph{final}). Module 2 then estimates the distance between the modules based on the local timestamps.} \label{fig:bidirectional_ranging} \end{figure} Module 2 can now estimate the time-of-flight and the distance between itself and module 1 based on the 6 timestamps. The basic equations to estimate the distance between module $i$ and module $j$ (module $i$ initiates the ranging and module $j$ computes the distance) are given by: \begin{eqnarray} %ranging between i and j (j computes distance) a_{i} &=& t_{SF}^i-t_{SP}^i\\ b_{j,i} &=& t_{RF}^{j,i}-t_{RP}^{j,i}\\ %when j receives i c_{j,i} &=& t_{RF}^{j,i}-t_{SR}^j\\ d_{i,j} &=& t_{SF}^i-t_{RR}^{i,j} %i receives from j \end{eqnarray} \begin{eqnarray} {TOF}_{j,i} &\approx& \frac{1}{2}\left(c_{j,i}-d_{i,j}\frac{b_{j,i}}{a_i} \right)-\delta_{j,i}\\ \|\bm{N}_j - \bm{N}_i\| &\approx& \frac{1}{2\bm{C}}\left(c_{j,i}-d_{i,j}\frac{b_{j,i}}{a_i} \right)-o_{j,i} \label{eq:distance_estimation}\\ &\doteq& m_{j,i}-o_{j,i} . \end{eqnarray} The variables $a$, $b$, $c$, and $d$ are also visualized in Fig.~\ref{fig:bidirectional_ranging}. The time-of-flight calculation between two modules $i$ and $j$ ($TOF_{j,i}=TOF_{i,j}$) is hindered by a fixed measurement offset ($\delta_{j,i}=\delta_{i,j}$). This offset is due to antenna delays and other discrepancies between the timestamps and actual packet reception or emission. Whereas this offset is expected to be unique to each module, it was found that it is necessary to estimate this offset pairwise for closely located modules. The hypothesis is that the proximity of the robot's motors and the sensor's position near the end cap's metal structure influences the antenna characteristics between pairs of modules. Eq.~\ref{eq:distance_estimation} estimates the distances between the modules based on the time-of-flight calculation ($\bm{C}$ is the speed of light). Rewriting the time offset $\delta_{j,i}$ as a distance offset $o_{j,i}$ (with $o_{j,i}=o_{i,j}$). Here $\bm{N}_i$ and $\bm{N}_j$ refer to the positions of nodes $i$ and $j$ respectively (see Section~\ref{txt:ukf}). The variables $m_{j,i}$ represent the uncorrected distance estimates. %say offset symmetric %lessons learned: antenna effect, bidirectional offset, restart, rx rx, 1ns pulses The DWM1000 requires careful configuration for optimal performance. The main configuration settings are provided in Table~\ref{tbl:dwm1000}. The ranging modules tend to measure non line-of-sight paths near reflective surfaces (e.g. floor, computer monitors), which may cause filter instability. Using the DWM1000's built-in signal power estimator, such suspicious packets are rejected. In practice, between $30\%$ and $70\%$ of packets are rejected. \begin{table}[h] \centering \caption{DWM1000 configuration} \label{tbl:dwm1000} \begin{tabular}{llllll} {\bf bitrate} & {\bf channel} & {\bf preamble} & {\bf PRF} & {\bf preamble code} \\ \hline \SI{6.8}{\mega\bit\per\second} & 7 & 256 & \SI{64}{\mega\hertz} & 17 \end{tabular} \end{table} \subsubsection{Broadcast Ranging} Due to the large number of exchanged packets (3 per pair) bidirectional ranging between pairs of modules quickly becomes inefficient when the number of modules grows. An alternative approach was developed using timed broadcast messages that scales linearly in the number of modules (3 packets per module). In this setup one module periodically initiates a measurement sequence by sending out a \emph{poll} message. When another module receives this message it emits its own \emph{poll} message after a fixed delay based on its ID, followed by \emph{response} and \emph{final} messages after additional delays. Broadcast ranging is illustrated in Fig.~\ref{fig:broadcast_ranging}. \begin{figure}[tpbh] \centering \begin{turn}{270} \includegraphics[width=.6\linewidth]{tex/img/broadcast_ranging.pdf} \end{turn} \caption{Packet exchange between 4 modules for bidirectional pairwise and broadcast ranging. Timed broadcast messages allow for efficient ranging with a large number of modules. } \label{fig:broadcast_ranging} \end{figure} One disadvantage of the broadcasting approach is that the total measurement time between a pair of modules takes longer (up to \SI{60}{\milli\second} in the experimental setup) than a single pairwise bidirectional measurement (approx. \SI{3}{\milli\second}). However, broadcast ranging provides two measurements for each pair of modules per measurement iteration. Note that each module now needs to keep track of the \emph{poll} and \emph{final} packet reception times of all other modules. The \emph{final} packet becomes longer as each module needs to transmit the \emph{response} reception time ($t_{RR}$) of all other modules. %The simplified packet structures are: {%\small %\begin{bytefield}{22} % \begin{rightwordgroup}{poll}{ % \bitbox{7}{preamble} & % \bitbox{2}{0} & % \bitbox{2}{$i$} & % \bitbox{3}{$t_{SP}^i$} & % \bitbox{8}{checksum} % }\end{rightwordgroup} %\end{bytefield} %\begin{bytefield}{19} % \begin{rightwordgroup}{response}{ % \bitbox{7}{preamble} & % \bitbox{2}{1} & % \bitbox{2}{$i$} & % \bitbox{8}{checksum} % }\end{rightwordgroup} %\end{bytefield} %\begin{bytefield}{34} % \begin{rightwordgroup}{final}{ % \bitbox{7}{preamble} & % \bitbox{2}{2} & % \bitbox{2}{$i$} & % \bitbox{3}{$t_{SF}^i$} & % \bitbox{3}{$t_{RR}^{i,1}$} & % \bitbox{3}{\ldots} & % \bitbox{3}{$t_{RR}^{i,n}$} & % \bitbox{8}{checksum} % }\end{rightwordgroup} %\end{bytefield} %} \subsection{Ranging Setup} Each MTR of SUPERball was fitted with a DWM1000 module located approximately \SI{0.1}{\metre} from the end of the strut. To simplify the notation, the top of the MTRs (ends of the struts) and the position of the ranging sensor are assumed the same. In practice, this offset is taken into account in the output function of the filter (see Section~\ref{txt:ukf}). The broadcasting algorithm runs at \SI{15}{\hertz} and packet transmissions are spaced \SI{1}{\milli\second} apart. This allows for over $20$ modules to range. After one ranging iteration, each end cap transmits its measurements over WiFi to the ROS network. A ROS node then combines measurements from all MTRs, along with encoder and IMU data, into a single ROS message at \SI{10}{\hertz}. The fixed anchors operate in a similar way to the end caps, but are not connected to a ROS node and can not directly transmit data to the ROS network. This means that two measurements are obtained (one in each direction) for each pair of modules on the robot, but only a single measurement between the fixed anchors and the modules on the robot. \subsection{Calibration} \label{txt:calib} One of the design goals of this state estimation method is quick deployment in new environments without significant manual calibration. To achieve this, an automatic calibration procedure was implemented to jointly estimate the constellation of fixed modules (anchors, defining an external reference frame) and the pairwise sensor offsets ($o_{i,j}$). Calibration is performed - similar to common motion capture systems - by moving the robot around, while recording the uncorrected distance measurements ($m_{j,i}$). After recording a dataset, reconstruction error is minimized $L$ by optimizing over the offsets $\bm{o}$ ($o_{i,j}$ rearranged as a vector), the estimated anchor locations $\bm{N}^{est}$, and the estimated moving module locations $\bm{N}^{float}[1\ldots n_{samples}]$ (i.e. the module on the robot's end caps): \begin{align} \resizebox{.91\hsize}{!}{$L\left(i,j,t\right) = \left( \|\bm{N}^{anchor}_i - \bm{N}^{float}_{j}\left[t\right]\|-o_{j,i} - m_{i,j}\left[t\right] \right)^2$ \label{eq:l_single}}\\ \resizebox{.91\hsize}{!}{$L\left(\bm{o},\bm{N}^{anchor},\bm{N}^{float}[1\ldots n_{samples}]\right) = \sum_{i,j,t}\alpha_{j,t}L\left(i,j,t\right)$. \label{eq:l_full}} \end{align} The brackets in $\bm{N}^{float}[1\ldots n_{samples}]$ indicate the moving module locations (MTR positions) at a specific timestep. For example $\bm{N}^{float}[5]$ contains the estimated end cap positions at timestep 5 in the recorded dataset. In Eq.~\ref{eq:l_full}, $i$ iterates over anchors, $j$ iterates over moving nodes and $t$ iterates over samples. The indicator variables $\alpha_{j,t}$ are equal to $1$ when for sample $t$ there are at least $4$ valid measurements to the fixed module for moving module $j$ (i.e. the number of DOFs reduces). In practice, constraints are added on the bar lengths, which take the same form as Eq.~\ref{eq:l_single} with the offsets set to $0$. BFGS~\cite{battiti1990bfgs} is used to minimize Eq.~\ref{eq:l_full} with a dataset containing approximately $400$ timesteps selected randomly from a few minutes of movement of the robot. Although the algorithm works without prior knowledge, providing the relative positions of $3$ fixed nodes ($3$ manual measurements) significantly improves the success rate as there are no guarantees on global convergence. Once the external offsets (between the anchors and moving nodes) and the module positions are known, the offsets can be estimated between moving nodes in a straightforward way by computing the difference between the estimated internal distances and the uncorrected distance measurements. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \section{Filter Design} \label{txt:ukf} Tensegrity systems are nonlinear and exhibit hybrid dynamics due to cable slack conditions and interactions with the environment that involve collision and friction. This warrants a robust filter design to track the robot's behavior. The commonly used Extended Kalman Filter (EKF) does not perform well on highly nonlinear systems where first-order approximations offer poor representations of the propagation of uncertainties. Additionally the EKF requires computation of time-derivatives through system dynamics and output functions which is challenging for a model with complex hybrid dynamics. The sigma point Unscented Kalman Filter (UKF) does not require derivatives through the system dynamics and is third order accurate when propagating Gaussian Random Variables through nonlinear dynamics~\cite{wan2000unscented}. The computational cost of the UKF is comparable to that of the EKF, but for tensegrity systems which commonly have a large range of stiffnesses and a high number of state variables the time-update of the sigma points dominates computational cost. As such, the methods used to reduce computational cost of dynamic simulation will be described, then in the following section the outline of the specific UKF implementation for the \SB{} prototype. \subsection{Dynamic Modeling} \label{sec:dynamic_modeling_sb} The UKF requires a dynamic model which balances model fidelity and computational efficiency since it requires a large number of simulations to be run in parallel. The model implemented for the tensegrity system is a spring-mass net and the following incomplete list of simplifying assumptions where used: \begin{itemize} \item Only point masses located at each node point \item All internal and external forces are applied at nodes \item Members exert only linear stiffness and damping \item Unilateral forcing in cables \item Flat ground at a known height with Coulomb friction \item No bar or string collision modeling \end{itemize} %This is a common approach for modeling tensegrity systems, and force density approaches for this problem are described in \textcolor{red}{cite}. Below we describe some careful manipulation of the equations within this force density framework which allowed us to run the parallel simulations while leaving computational bandwidth for other requisite operations such as communication and data visualization. For a tensegrity with $n$ nodes and $m$ members, the member force densities, $\boldsymbol{q}\in\mathbb{R}^{m}$, can be transformed into nodal forces, $\boldsymbol{F_m}\in\mathbb{R}^{n\times 3}$, by using the current Cartesian nodal positions, $\boldsymbol{N}\in\mathbb{R}^{n\times 3}$, and the connectivity matrix, $\boldsymbol{C}\in\mathbb{R}^{m\times n}$, as described in \cite{skelton2009tensegrity}. This operation is described by the equation: $$ \boldsymbol{F_m} = \boldsymbol{C}^{T} diag(\boldsymbol{q}) \boldsymbol{C} \boldsymbol{N}, $$ where $diag(\cdot)$ represents the creation of a diagonal matrix with the vector argument along its main diagonal. First, note that $\boldsymbol{C} \boldsymbol{N}$ produces a matrix $\boldsymbol{U}\in\mathbb{R}^{m\times 3}$ where each row corresponds to a vector that points between the $i$th and $j$th nodes spanned by each member. Therefore, this first matrix multiplication can be replaced with vector indexing as $\boldsymbol{U}_{k} = \boldsymbol{N}_{i} - \boldsymbol{N}_{j}$, where the notation $\boldsymbol{U}_{k}$ is used to denote the $k$th row of matrix $\boldsymbol{U}$. If one then computes $\boldsymbol{V}=\boldsymbol{C}\frac{d\boldsymbol{N}}{dt}$ with the same method %%%% NOTE This was the old sentence, but X_{l} didn't make sense... So I assumed it was suppose to be U_{k}. Is that correct? %where we use the notation $\boldsymbol{X}_{l}$ to denote the $l$th row of matrix $\boldsymbol{X}$. If we then compute $\boldsymbol{V}=\boldsymbol{C}\frac{d\boldsymbol{N}}{dt}$ with the same method as $\boldsymbol{U}$, one would obtain a matrix of relative member velocities. The matrices $\boldsymbol{U}$ and $\boldsymbol{V}$ are used to calculate member lengths as $L_k = |\boldsymbol{U}_k|_2$ and member velocities as $\frac{d}{dt}(L_k) = \frac{\boldsymbol{U}_k(\boldsymbol{V}_k)^T}{L_k}.$ Member force densities, $\boldsymbol{q}$, are then calculated using Hooke's law and viscous damping as: $$ \boldsymbol{q}_k = K_k(1 - \frac{L_{0k}}{L_k}) - \frac{c_k}{L_k} \frac{d}{dt}(L_k). $$ Here $K_k$ and $c_k$ denote the $k$th member's stiffness and damping constants, respectively. Note that cables require some additional case handling to ensure unilateral forcing. Scaling each $\boldsymbol{U}_k$ by $\boldsymbol{q}_k$ yields a matrix whose rows correspond to vector forces of the members. Denote this matrix as $\boldsymbol{U}^q\in\mathbb{R}^{m\times 3}$, and note that $\boldsymbol{U}^q = diag(\boldsymbol{q}) \boldsymbol{C} \boldsymbol{N}$. Thus this matrix of member forces can be easily applied to the nodes using: $$ \boldsymbol{F_m} = \boldsymbol{C}^{T} \boldsymbol{U}^q. $$ A method for computing nodal forces exerted by the members is now obtained, and only ground interaction forces need to be computed, which will be denoted as $\boldsymbol{F}_g$. Ground interaction forces were computed using the numerical approach in~\cite{yamane2006stable}. The nodal accelerations can then be written as: $$ \frac{d^2\boldsymbol{N}}{dt^2} = \boldsymbol{M}^{-1}(\boldsymbol{F}_m+ \boldsymbol{F}_g) - \boldsymbol{G}, $$ where $\boldsymbol{M}\in\mathbb{R}^{n\times n}$ is a diagonal matrix whose diagonal entries are the masses of each node and $\boldsymbol{G}\in\mathbb{R}^{n\times 3}$ is matrix with identical rows equal to the vector acceleration due to gravity. It is then straightforward to simulate this second order ODE using traditional numerical methods. Note also that it is possible to propagate many parallel simulations efficiently by concatenating multiple $\boldsymbol{N}$ matrices column wise to produce $\boldsymbol{N}_{\parallel}\in\mathbb{R}^{n\times 3l}$ for $l$ parallel simulations. The resultant vectorization of many of the operations yields significant gains in computational speed with some careful handling of matrix dimensions. \subsection{UKF Implementation} A traditional UKF was implemented as outlined in \cite{wan2000unscented} with additive Gaussian noise for state variables and measurements. Several parameters are defined for tuning the behavior of the UKF, namely $\alpha$, $\beta$ and $\kappa$, where $\alpha$ determines the spread of the sigma points generated by the unscented transformation, $\beta$ is used to incorporate prior knowledge of distribution, and $\kappa$ is a secondary scaling parameter. Hand tuning obtained these parameters to the values $\alpha = 0.0139$, $\beta = 2$ for Gaussian distributions and $\kappa = 0$ and found this to yield an adequately stable filter. Defining state variables as $\boldsymbol{N}$ and $\frac{d\boldsymbol{N}}{dt}$ stacked in a vector $\boldsymbol{y}\in\mathbb{R}^{L}$ where $L = 6n$ is the number of state variables. Also, independent state noise is assumed with variance $\lambda_y = 0.4$ thus with covariance $\boldsymbol{R} = \lambda_y\bm{I}_L$. \begin{figure}[tpbh] \centering \includegraphics[width=0.7\linewidth]{tex/img/flow_chartSB.pdf} \caption{Block diagram of data flow within the system. Red signals are passed as ROS messages and blue signals are passed using the ranging modules. Note that each rod contains two ranging sensors located at each end of the rod. The gray control strategy block represents a to-be-designed state-feedback control strategy.} \label{fig:UKFflowChart} \end{figure} %For measurements we take the minimum angle between each bar vector and the z-axis, $\theta\in\mathbb{R}^{b}$ where $b$ is the number of bar angles available at the given time step and all ranging measures, $\boldsymbol{r}\in\mathbb{R}^{a}$, where $a$ is the number of ranging measures available at a given time step. The measurement data used is estimated orientation data from the robot's IMUs using a gradient descent AHRS algorithm based on~\cite{madgwick2011estimation}, $\theta\in\mathbb{R}^{b}$ where $b$ is the number of bar angles available at the given time step and all ranging measures, $\boldsymbol{r}\in\mathbb{R}^{a}$, where $a$ is the number of ranging measures available at a given time step. Independent noise is again assumed and represented by $\lambda_\theta$ and $\lambda_r$. The measurement covariance matrix is then defined as: $$ \boldsymbol{Q} = \left[ \begin{array}{ccc} \lambda_\theta\bm{I}_b & \boldsymbol{0} \\ \boldsymbol{0} & \lambda_r\bm{I}_a \end{array} \right]. $$ These user defined variables are then used within the framework of the UKF to forward propagate both the current expected value of the state as well as its covariance. Fig.~\ref{fig:UKFflowChart} shows an overview of the complete state estimation setup. \section{Filter Evaluation} \subsection{Experimental Setup} \begin{figure}[tpbh] \centering \includegraphics[width=\linewidth]{tex/img/matlab_figure_ranging_b45.pdf} \caption{Visualization of the UKF output. \SB{} sits in the middle of the plot surrounded by 8 ranging base stations. Lines between the robot and the base stations indicate valid ranging measures during this timestep.} \label{fig:SUPERballMATLAB} \end{figure} To evaluate the performance of the UKF, eight "fixed anchor" ranging base stations are used and calibrated as detailed in Section~\ref{txt:calib}. Each end cap of \SB{} was then able to get a distance measurement to each base station. This information was sent over ROS along with IMU data (yaw,pitch,roll) and cable rest lengths to the UKF. The base stations were placed in a pattern to cover an area of approximately \SI{91}{\meter^2}. Each base station's relative location to each other may be seen in Fig.~\ref{fig:SUPERballMATLAB}. \SB{} and the base stations were then used to show the UKF tracking a local trajectory of end caps and a global trajectory of the robotic system. In each of these experiments, the UKF was allowed time to settle from initial conditions upon starting the filter. This ensured that any erroneous states due to poor initial conditioning did not affect the filter's overall performance. \subsection{Local Trajectory Tracking} \begin{figure}[tpbh] \centering \includegraphics[width=1\linewidth]{tex/img/Node_tracking_1-11.pdf} \caption{Position plotted through time for both end cap 1 and end cap 2. The thin line represents the position output measured by the camera tracking system, and the bold line represents the position output from the UKF filter. As expected, there is a time domain lag between the measured and estimated positions.} \label{fig:smalldisplacement} \end{figure} In order to track a local trajectory, \SB{} remained stationary while two of its actuators tracked phase shifted stepwise sinusoidal patterns. During the period of actuation, two end cap trajectories were tracked on \SB{} and compared to the trajectory outputs of the UKF. One end cap was directly connected to an actuated cable (end cap 2), while the other end cap had no actuated cables affixed to it (end cap 1). To obtain a ground truth for the position trajectory, a camera that measured the position of each end cap was positioned next to the robot. Both end caps started at the same relative height and the majority of movement of both fell within the plane parallel to the camera. Fig.~\ref{fig:smalldisplacement} shows the measured and UKF global positions of the two end caps through time. % For this experiment, the cables between end caps 1 and 11 and end caps 12 and 8 were actuated. % The UKF is able to track the end cap movements quite well with some displacement error in the Y position for end cap 1. % Upon further inspection of the input data to the UKF, there was a high packet loss between end cap 1 and the base stations. % This coupled with a mismatched base model, might be the cause for this error. \subsection{Global Trajectory Tracking} \begin{figure}[tpbh] \centering \includegraphics[width=\linewidth]{tex/img/top_view.pdf} \caption{Top down view of the triangular faces to which the robot transitions during the global trajectory tracking experiment for various setting of the state estimator. The small inset illustrates the movement of the robot. The line shows the estimated center of mass (CoM) using the \emph{full} settings. Finding the initial position (origin) is hard for all settings, and without the IMUs the estimator does not find the correct initial face. After a first roll, tracking becomes more accurate. The offsets $\bm{o}$ have a minimal impact, which indicates that the calibration routine is sufficiently accurate. } \label{fig:3roll_triangles} \end{figure} For global trajectory tracking, \SB{} was actuated to induce a transition from one base triangle rolling through to another base triangle as presented in \cite{sabelhaus2015system}. %The state of \SB{} was tracked using the UKF. Ground truth for this experiment was ascertained by marking and measuring the positions of each base triangle's end caps before and after a face transition. %Fig.~\ref{fig:3roll_perspective} shows a 3D plot of the UKF generated states for the beginning and end of the experiment. %Each colored triangle represents a base triangle and the robot implements two full transitions starting from the red triangle and ending on the blue. 4 settings of the state estimator were evaluated. \emph{Full}: The state estimator as described in Section~\ref{txt:ukf} with all IMU and ranging sensors. \emph{no IMU}: Only the ranging sensors are enabled. \emph{full w. cst. offset}: Same as \emph{full}, but the offsets $\bm{o}$ are set to a constant instead of optimized individually. \emph{4 base station ranging sensors}: 50\% of the base station ranging sensors are disabled. The results of this experiment are presented in Fig.~\ref{fig:3roll_triangles}~and~\ref{fig:3roll_xz_position}. \begin{figure}[tpbh] \centering \includegraphics[width=\linewidth]{tex/img/roll_x_z_zoom.pdf} \caption{X and Y position of end cap 12 as a function of time for the various estimator settings. The end cap was initially off the ground and touches the ground after the first roll. This is not tracked correctly when the IMUs are disabled. The system works as expected when 4 base stations ranging sensors are disabled, but with slower convergence and more noise on the robot's position. Around \SI{60}{s} there's a spurious IMU value from which the state estimator recovers. } \label{fig:3roll_xz_position} \end{figure}
Formal statement is: lemma Lim_transform_within_open: assumes "(f \<longlongrightarrow> l) (at a within T)" and "open s" and "a \<in> s" and "\<And>x. x\<in>s \<Longrightarrow> x \<noteq> a \<Longrightarrow> f x = g x" shows "(g \<longlongrightarrow> l) (at a within T)" Informal statement is: If $f$ converges to $l$ at $a$ within $T$, and $g$ is equal to $f$ on $s$ except at $a$, where $s$ is an open set containing $a$, then $g$ converges to $l$ at $a$ within $T$.
Those legends over at Dakine have got 10 John John Florence signature leashes to giveaway and a JJF tailpad too – in case you're in need of a few new accessories. And all you gotta do is enter your email addy in the box below, easy. According to Dakine: “Dakine is honored to partner with the world's best surfer, John John Florence, to bring you this custom designed Kainui 6' X 1/4" Leash. “John John's riding style calls for a serious leash, the Kainui Leash offers the security you need in double overhead to triple overhead surf. Constructed of the highest quality 1/4-inch (6.5mm) urethane Dura-Cord for maximum strength to keep you connected to your board in even the strongest surf. And as for the pad? "Dakine is honoured to partner with the world's best surfer, John John Florence, to bring you this custom designed traction pad. Triple cut posi-traction was designed for John John's specific dimensions and aggressive riding style, while the five-piece traction design allows for adjustability, whether being used on an everyday thruster or step-up board. The 25mm vertical tail wedge was hand sculpted by John John himself, to provide the perfect shape for his form. "The addition of perforated surface allows water to flow through the kick while eliminating drag. All John John Florence products are packaged using sustainable recycled cardboard products with zero plastic – keeping our oceans clean for tomorrow." Boom! Whatcha waiting for? Get your name in there! For full ts&cs, go HERE.
import numpy as np from scipy.io import wavfile def read_wav_file(path): """Read wav file and returns numpy array and sampling rate""" sampling_rate, wav_file = wavfile.read(path) return wav_file, sampling_rate def process_pre_emphasis(signal, coefficient): """Amplify high frequencies, and balance frequency spectrum""" return np.append([signal[0]], signal[1:] - coefficient * signal[:-1], axis=0) def process_hamming(signal, sampling_rate, window_size, window_overlap): """Segment signal it and apply window function""" if window_size < window_overlap: exit("Window size smaller than overlap!") window_size = int(round(sampling_rate * window_size)) window_overlap = int(round(sampling_rate * window_overlap)) window_stride = window_size - window_overlap signal_len = len(signal) # size_of_signal = ((number_of_frames - 1) * (window_size - window_overlap)) + window_size number_of_frames = int(np.ceil((signal_len - window_size) / window_stride + 1)) signal_len_new = (number_of_frames - 1) * window_stride + window_size # np.arange ends on stop so add 1 more step indices = np.tile(np.arange(0, window_size), (number_of_frames, 1)) + np.tile( np.arange(0, signal_len_new - window_size + window_stride, window_stride), (window_size, 1)).T # pad zeros to end for evenly segmented windows zeros_to_append = signal_len_new - signal_len signal_padded = np.pad(signal, ((0, zeros_to_append), (0, 0)), 'constant', constant_values=0) # split to segments windows = signal_padded[indices.astype(np.int32, copy=False)] # apply hamming window function on segments windows = windows.transpose(0, 2, 1) windows *= np.hamming(window_size) return windows.transpose(0, 2, 1)
[STATEMENT] lemma width_upper_bound_V: "V \<noteq> {} \<Longrightarrow> width < card V" [PROOF STATE] proof (prove) goal (1 subgoal): 1. V \<noteq> {} \<Longrightarrow> width < card V [PROOF STEP] unfolding width_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. V \<noteq> {} \<Longrightarrow> (if V\<^bsub>T\<^esub> = {} then 0 else max_bag_card - 1) < card V [PROOF STEP] using max_bag_card_upper_bound_V max_bag_card_lower_bound_1 diff_less empty_tree_empty_V le_neq_implies_less less_imp_diff_less zero_less_one [PROOF STATE] proof (prove) using this: V \<noteq> {} \<Longrightarrow> max_bag_card \<le> card V V \<noteq> {} \<Longrightarrow> 0 < max_bag_card \<lbrakk>0 < ?n; 0 < ?m\<rbrakk> \<Longrightarrow> ?m - ?n < ?m V\<^bsub>T\<^esub> = {} \<Longrightarrow> V = {} \<lbrakk>?m \<le> ?n; ?m \<noteq> ?n\<rbrakk> \<Longrightarrow> ?m < ?n ?j < ?k \<Longrightarrow> ?j - ?n < ?k (0::?'a) < (1::?'a) goal (1 subgoal): 1. V \<noteq> {} \<Longrightarrow> (if V\<^bsub>T\<^esub> = {} then 0 else max_bag_card - 1) < card V [PROOF STEP] by presburger
Justice studies is an interdisciplinary area that blends topics from humanities departments (e.g., philosophy), social science departments (e.g., psychology, sociology, women’s studies), departments that include both humanities and social science faculty (e.g., history, political science), and professionally-oriented departments (education, family studies, social work). Some of the topics studied include courts, family violence, rights, substance abuse, juvenile justice, school law, children as witnesses, hate crimes, and community policing. The goal is to produce graduates who have a higher level of knowledge about law and justice in American society and in the world so that they will mature into more knowledgeable and effective citizens. The program offers a dual major and a minor in Justice Studies and an interdisciplinary minor in forensics.
lemma continuous_at_dist: "isCont (dist a) b"
The limit of the inverse of a function $g$ at $0$ exists if and only if the limit of $g$ at $\infty$ exists.
function C = mtimes(A, B) %* Multiplication of VALSDISCRETIZATION discretizations. % Copyright 2017 by The University of Oxford and The Chebfun Developers. % See http://www.chebfun.org/ for Chebfun information. C = A*B; end
#ifndef INCLUDED_TELEPATH_MATRIX_H #define INCLUDED_TELEPATH_MATRIX_H #include <cblas.h> #include "telepath/blas/traits.h" namespace telepath{ enum ORDER { ROW_MAJOR = CblasRowMajor, COL_MAJOR = CblasColMajor }; enum TRANSPOSE { NONE = CblasNoTrans, TRANS = CblasTrans, CONJ_TRANS = CblasConjTrans }; enum UPLO{ UPPER = CblasUpper, LOWER = CblasLower, }; /* Struct for storing BLAS matrix data */ template< typename T > struct matrix{ ORDER layout; TRANSPOSE trans; T* array; std::size_t rows; std::size_t cols; std::size_t ld; }; template< typename T > struct sym_matrix{ ORDER layout; TRANSPOSE trans; UPLO uplo; T* array; std::size_t rows; std::size_t cols; std::size_t ld; }; } //namespace telepath namespace blas{ template< typename T > struct Traits< const telepath::matrix<T> >{ using mat_t = typename telepath::matrix<T>; const mat_t& mat; constexpr Traits( const mat_t& m ) : mat( m ) { } constexpr telepath::ORDER layout() const{ return mat.layout; } constexpr telepath::TRANSPOSE trans() const{ return mat.trans; } constexpr const T* array() const{ return mat.array; } constexpr auto nrows() const{ return mat.rows; } constexpr auto ncols() const{ return mat.cols; } constexpr auto ld() const{ return mat.ld; } }; template< typename T > struct Traits< telepath::matrix<T> >{ using mat_t = typename telepath::matrix<T>; mat_t& mat; constexpr Traits( mat_t& m ) : mat( m ) { } constexpr telepath::ORDER layout() const{ return mat.layout; } constexpr telepath::TRANSPOSE trans() const{ return mat.trans; } inline T* array() { return mat.array; } constexpr const T* array() const{ return mat.array; } constexpr auto nrows() const{ return mat.rows; } constexpr auto ncols() const{ return mat.cols; } constexpr auto ld() const{ return mat.ld; } }; template< typename T > struct Traits< const telepath::sym_matrix<T> >{ using mat_t = telepath::sym_matrix<T>; const mat_t& mat; constexpr Traits( const mat_t& m ) : mat( m ) { } constexpr telepath::ORDER layout() const{ return mat.layout; } constexpr telepath::TRANSPOSE trans() const{ return mat.trans; } constexpr telepath::UPLO uplo() const{ return mat.uplo; } constexpr const T* array() const{ return mat.array; } constexpr auto nrows() const{ return mat.rows; } constexpr auto ncols() const{ return mat.cols; } constexpr auto ld() const{ return mat.ld; } }; template< typename T > struct Traits< telepath::sym_matrix<T> >{ using mat_t = typename telepath::sym_matrix<T>; mat_t& mat; constexpr Traits( mat_t& m ) : mat( m ) { } constexpr telepath::ORDER layout() const{ return mat.layout; } constexpr telepath::TRANSPOSE trans() const{ return mat.trans; } constexpr telepath::UPLO uplo() const{ return mat.uplo; } constexpr const T* array() const{ return mat.array; } inline T* array() { return mat.array; } constexpr auto nrows() const{ return mat.rows; } constexpr auto ncols() const{ return mat.cols; } constexpr auto ld() const{ return mat.ld; } }; template< typename T > struct MatrixTraits< telepath::matrix<T> >{ using mat = typename telepath::matrix<T>; using scalar_t = T; constexpr static CBLAS_ORDER layout( const mat& m ){ return (CBLAS_ORDER) m.layout; } constexpr static CBLAS_TRANSPOSE trans( const mat& m ){ return (CBLAS_TRANSPOSE) m.trans; } constexpr static auto nrows( const mat& m ){ return m.rows; } constexpr static auto ncols( const mat& m ){ return m.cols; } constexpr static T* array( mat& m ){ return m.array; } constexpr static const T* array( const mat& m ){ return m.array; } constexpr static auto ld( const mat& m ){ return m.ld; } }; template< typename T > struct MatrixTraits< telepath::sym_matrix<T> >{ using mat = typename telepath::sym_matrix<T>; using scalar_t = T; constexpr static CBLAS_ORDER layout( const mat& m ){ return (CBLAS_ORDER) m.layout; } constexpr static CBLAS_TRANSPOSE trans( const mat& m ){ return (CBLAS_TRANSPOSE) m.trans; } constexpr static CBLAS_UPLO uplo( const mat& m ){ return (CBLAS_UPLO) m.uplo; } constexpr static auto nrows( const mat& m ){ return m.rows; } constexpr static auto ncols( const mat& m ){ return m.cols; } constexpr static T* array( mat& m ){ return m.array; } constexpr static const T* array( const mat& m ){ return m.array; } constexpr static auto ld( const mat& m ){ return m.ld; } }; } //namespace blas #endif
Published 04/18/2019 08:19:14 pm at 04/18/2019 08:19:14 pm in Good Surge Protector For Computer. good surge protector for computer best surge protector for computer reviews. best surge protector for computer 2018 calender,good surge protector for computer,best surge protector for computer 2018,best surge protector for computer 2017 update,best surge protector for computer uk online,best surge protector for computer uk,best surge protector for computer 2017 cheap,best surge protector for computer 2017 macbook,best surge protector for computer ukulele,recommended surge protection for computers,what is the best surge protector for computers.
import time import tflearn import numpy as np import tensorflow as tf from Zhihu.RNN.RNN import RNNWrapper, FastLSTMCell from Util.Util import DataUtil class MnistGenerator: def __init__(self, im=None, om=None): self._im, self._om = im, om self._cursor = self._indices = None self._x, self._y = DataUtil.get_dataset("mnist", "../../_Data/mnist.txt", quantized=True, one_hot=True) self._x = self._x.reshape(-1, 28, 28) self._x_train, self._x_test = self._x[:1800], self._x[1800:] self._y_train, self._y_test = self._y[:1800], self._y[1800:] def refresh(self): self._cursor = 0 self._indices = np.random.permutation(len(self._x_train)) def gen(self, batch, test=False): if batch == 0: if test: return self._x_test, self._y_test return self._x_train, self._y_train end = min(self._cursor + batch, len(self._x_train)) start, self._cursor = self._cursor, end if start == end: self.refresh() end = batch start = self._cursor = 0 indices = self._indices[start:end] return self._x_train[indices], self._y_train[indices] if __name__ == '__main__': generator = MnistGenerator() print("=" * 60, "\n" + "My LSTM", "\n" + "-" * 60) tf.reset_default_graph() t = time.time() rnn = RNNWrapper() rnn.fit(28, 10, generator) print("Time Cost: {}".format(time.time() - t)) print("=" * 60, "\n" + "My Fast LSTM", "\n" + "-" * 60) tf.reset_default_graph() t = time.time() rnn = RNNWrapper() rnn.fit(28, 10, generator, cell=FastLSTMCell) print("Time Cost: {}".format(time.time() - t)) print("=" * 60, "\n" + "Tflearn", "\n" + "-" * 60) tf.reset_default_graph() t = time.time() net = tflearn.input_data(shape=[None, 28, 28]) net = tf.concat(tflearn.lstm(net, 128, return_seq=True)[-3:], axis=1) net = tflearn.fully_connected(net, 10, activation='softmax') net = tflearn.regression(net, optimizer='adam', batch_size=64, learning_rate=0.001, loss='categorical_crossentropy') model = tflearn.DNN(net, tensorboard_verbose=0) model.fit(*generator.gen(0), validation_set=generator.gen(0, True), show_metric=True) print("Time Cost: {}".format(time.time() - t))
/* * agentlib.h * * Created on: Jul. 5, 2019 * Author: takis */ #ifndef MY_INCLUDES_AGENTLIB_H_ #define MY_INCLUDES_AGENTLIB_H_ /******************************************************************************************************** * INCLUDES * ****************************************************************************************************** */ #include <vector> #include <string> #include <fstream> // my own includes #include <gsl/gsl_blas.h> #include <gsl/gsl_math.h> #include <math.h> /******************************************************************************************************** * MACROS * ****************************************************************************************************** */ #define Nx 100 // number of columns in physical environment #define Ny 100 // number of rows in physical environment #define MaxMapEntries 48 // maximum number of contexts #define MaxIterations 9999 // maximum number of times main mapping loop can execute #define SenseRange 75 // units of distance that the agent can "see" #define MinVectorNorm 0.01 // a landmark must be further away than 1 cm from the agent #define MATSIZE 8 // matrix dimension (MATSIZE x MATSIZE) for analysis /******************************************************************************************************** * TYPEDEFs * ****************************************************************************************************** */ typedef std::vector<std::vector<std::string> > vvs_t; // 2D vector type for the // physical environment typedef vvs_t::size_type vvs_sz_t; // size_type for 2D vector type typedef enum e_region_t // enumerate the possible regions { R0, R1, R2, R3, R4, R5 } region_t; typedef enum e_orient_t // enumerate the possible directions { North, NorthEast, East, SouthEast, South, SouthWest, West, NorthWest } orient_t; typedef enum e_scan_direction_t // scan goes from top left to bottom right, // or from bottom right to top left { SE, NW } scan_direction_t; struct loc_t // type for a location in the physical environment { vvs_sz_t X; vvs_sz_t Y; }; struct read_data_t // type for storing data read from file { std::string context; region_t region; }; struct dprec_t // define a type to store dot products and corresponding directions { orient_t dir; double dp; }; /******************************************************************************************************** * FUNCTION PROTOTYPES * ****************************************************************************************************** */ /* * function: sgn * purpose: determines the sign of a double variable * parameters: a real number (double) * returns: +1 or -1 (short int) * */ short int sgn(double); /* * function: load_known_contexts_from_file * purpose: reads pairs of tokens from a file of the form <string, unsigned_integer> <newline> * parameters: string consisting of the file name * returns: a vector of read_data_t elements * */ std::vector<read_data_t> loadKnownContextsfromFile(const std::string); /* * function: load_global_map_with_file_data * purpose: fills contextual/associative map data structure with information in vector of read_data_t elements * parameters: the associate map (passed by reference), and the vector of read_data_t elements, passed by constant reference * returns: nothing (void function)space * */ void loadGlobalMapwithFileData(std::map<std::string, region_t>&, const std::vector<read_data_t>&); /* * function: convertContextStringtoMatrix * purpose: takes a key string associated with the spatial associative map, and converts it into a matrix * parameters: the context string * returns: a matrix (of type gsl_matrix_float*) */ gsl_matrix_float *convertContextStringtoMatrix(const std::string&); /* * function: mat2Norm * purpose: compute the 2-norm of a matrix from the definition on page 291 of * Matrix Analysis, Horn & Johnson * parameters: a matrix of type gsl_matrix_float* * returns: the matrix 2-norm value */ float mat2Norm(const gsl_matrix_float); /* * function: matTr * purpose: yields the transformation matrix we need, T_k, where k=0,+/-1,+/-2,... * parameters: an integer (k) * returns: a matrix of type gsl_matrix_float* * */ gsl_matrix_float *matTr(int); /* * function: compareContexts * purpose: compare context matrices, return the closeness value * parameters: two matrices to be compared, of type gsl_matrix_float* * returns: a closeness value, the greater, the closer the matrices are */ float compareContexts(const gsl_matrix_float*, const gsl_matrix_float*); /* * function: alphaK * purpose: implements a continuous monotonically decreasing function * parameters: a real number, x (float) * returns: (float) exp(-x) */ float alphaK(const float); /* * function: agentScan360 * purpose: at a fixed position (loc_t, first parameter) in the physical environment, deduce the context string, * which consists of relative position data, e.g., lm_A to East, lm_B to SW, to be identified * as the key AEBSW for the associative map; * parameters: the agent's location, the associative map, the physical map, and the landmark locations * returns: nothing (changes are made to the associative map) */ void agentScan360(loc_t, std::map<std::string, region_t>&, const vvs_t&, const std::vector<loc_t>&, const std::vector<std::string>&); /* * function: scan * purpose: survey a rectangular subset of 2D space, either in a SE or a NW sense, using recursion * parameters: rA (top left corner of scan), rB (bottom right corner of scan), r0 (agent current location) * spatial_mem (associative map of space), physmap (physical map of space) * returns: nothing (void type, but changes are made to the spatial memory, a.k.a., the associate map) */ void scan(bool& done, const scan_direction_t, loc_t, loc_t, loc_t, std::map<std::string, region_t>&, const vvs_t&, const std::map<char, loc_t>&, const std::vector<std::string>&); // scan(bool& done, const scan_direction_t dir, loc_t rA, loc_t rB, loc_t r0, std::map<std::string, region_t>& spatial_mem, const vvs_t& physmap, const std::map<char, loc_t>& landmarks, const std::vector<std::string>& orient_str) #endif /* MY_INCLUDES_AGENTLIB_H_ */
PROGRAM TCOLCV CALL COLCV(IERR) C STOP END C SUBROUTINE COLCV (IERR) C C PURPOSE To provide a demonstration of the routines in C the package COLCONV and to test them. C C USAGE CALL COLCV (IERR) C C ARGUMENTS C C ON OUTPUT IERR C An integer variable C = 0, if the test is successful, C = 1, otherwise C C I/O If the test is successful, the message C C COLCONV TEST SUCCESSFUL C C is written on unit 6. C C Otherwise, the message C C COLCONV TEST SUCCESSFUL C C is written on unit 6. C C PRECISION Single C C REQUIRED PACKAGES COLCONV C C REQUIRED GKS LEVEL NONE C C LANGUAGE FORTRAN C C ALGORITHM TCOLCV executes six calls to test each of C the color conversions: C C HLS to RGB C RGB to HLS C HSV to RGB C RGB to HSV C YIQ to RGB C RGB to YIQ C C --------------------------------------------------------------------- C C Initialize the error flag. C IERR = 0 C C Set tolerance limit for HLS and HSV tests. C EPS = 0.00001 C C HLS to RGB. C CALL HLSRGB(120.,50.,100.,R,G,B) IF ( (ABS(R-1.) .GT. EPS) .OR. (ABS(G) .GT. EPS) .OR. * (ABS(B) .GT. EPS) ) IERR = 1 C C RGB to HLS. C CALL RGBHLS(1.,0.,0.,H,FL,S) IF ( (ABS(H-120.) .GT. EPS) .OR. (ABS(FL-50.) .GT. EPS) .OR. * (ABS(S-100.) .GT. EPS) ) IERR = 1 C C HSV to RGB. C CALL HSVRGB(120.,1.,1.,R,G,B) IF ( (ABS(R-0.) .GT. EPS) .OR. (ABS(G-1.) .GT. EPS) .OR. * (ABS(B-0.) .GT. EPS) ) IERR = 1 C C RGB to HSV. C CALL RGBHSV(0.,0.,1.,H,S,V) IF ( (ABS(H-240.) .GT. EPS) .OR. (ABS(S-1.) .GT. EPS) .OR. * (ABS(V-1.) .GT. EPS) ) IERR = 1 C C Set tolerance limit for YIQ tests. C EPS = 0.01 C C YIQ to RGB. C CALL YIQRGB(0.58701, -0.27431, -0.52299,R,G,B) IF ( (ABS(R-0.) .GT. EPS) .OR. (ABS(G-1.) .GT. EPS) .OR. * (ABS(B-0.) .GT. EPS) ) IERR = 1 C C RGB to YIQ. C CALL RGBYIQ(1.,1.,1.,Y,FI,Q) IF ( (ABS(Y-1.) .GT. EPS) .OR. (ABS(FI) .GT. EPS) .OR. * (ABS(Q) .GT. EPS) ) IERR = 1 C IF (IERR .EQ. 0) THEN WRITE (6,1001) ELSE WRITE (6,1002) ENDIF C RETURN C 1001 FORMAT (' COLCONV TEST SUCCESSFUL') 1002 FORMAT (' COLCONV TEST UNSUCCESSFUL') END
# CHEM 1000 - Spring 2022 Prof. Geoffrey Hutchison, University of Pittsburgh ## Recitation 2 - Matplotlib Python has several plotting libraries, but [Matplotlib](http://matplotlib.org) is a common tool for 2D plotting, particularly the `matplotlib.pyplot` sub-module. **Learning Objectives** - Understand how to create `numpy` arrays from lists, or regular sets of numbers - Apply mathematical operations and functions to `numpy` arrays (e.g. for plotting, analysis, vectors, etc.) **Attribution** Most of this material has been adapted from [Mathematical Python by Patrick Wills](https://github.com/patrickwalls/mathematical-python/blob/master/scipy/numpy.ipynb) Let's get started by importing `matplotlib.pyplot` and using `%matplotlib` [Jupyter magic](https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-matplotlib) to display plots in the notebook. ```python # import the key parts of matplotlib with the common abbreviation `plt` import matplotlib.pyplot as plt # tell matplotlib and Jupyter to include plots inline - in the notebook %matplotlib inline # make the inline backend include high-resolution 'retina' plots on high-res screens # not critical, but it makes a huge difference if you have a good screen %config InlineBackend.figure_format = 'retina' ``` That bit above (and similar versions) is "boilerplate" - I just copy and paste it to create plots, e.g.: ``` # import numpy and matplotlib import numpy as np import matplotlib.pyplot as plt # insert plots in the notebook %matplotlib inline %config InlineBackend.figure_format = 'retina' # bump up the font sizes plt.style.use('./chem1000.mplstyle') ``` ## Basic Plotting ### Procedure The general procedure to create a 2D line plot is: 1. Create a sequence of $x$ values. 2. Create a sequence of $y$ values. 3. Enter `plt.plot(x,y,[fmt],**kwargs)` - where `[fmt]` is an optional format string - `**kwargs` are optional keyword arguments specifying line properties of the plot 4. Use `pyplot` functions to add features to the figure such as a title, legend, grid lines, etc. 5. Enter `plt.show()` to display the resulting figure. Some code uses [format strings](https://matplotlib.org/devdocs/api/_as_gen/matplotlib.axes.Axes.plot.html) like 'ro', but it's generally easier to read and understand the keyword options, as discussed below. Let's begin with a basic example with a few random points: ```python x = [-5,-2,0,1,3] y = [2,-1,1,-4,3] plt.plot(x,y) plt.show() ``` The main things to notice are: 1. The sequences `x` and `y` define the coordinates of the points in the plot. 2. The line in the plot is constructed by connecting the points by straight lines. The second observation implies that if we want to plot a smooth curve then we need to plot lots of points otherwise the plot will not be smooth. For example, we could try plotting the parabola $y = x^2$ for $x$ from -2 .. 2 using only 5 points: ```python x = [-2,-1,0,1,2] y = [4,1,0,1,4] plt.plot(x,y) plt.show() ``` This is too few points to plot a smooth curve such as $y = x^2$ and so we need more points! Let's try again using the NumPy function `np.linspace` to create 100 points! ```python import numpy as np # we haven't done that yet in this notebook x = np.linspace(-2,2,100) # remember, this creates an array from -2 to +2 with 100 divisions (and includes both ±2) y = x**2 plt.plot(x,y) plt.show() ``` That's a better representation of the parabola $y = x^2$. Note that the number of points we use in a line plot (100 in this case) is completely arbitrary but the goal is to show a smooth graph for a smooth curve and so we just need to pick a big enough number depending on the function. But be careful not to generate too many points since a *very* large number of points will take a *long* time to plot! Instead of `np.linspace()` we could use `np.arange(start, end, resolution)` to set up our `x` variable.. read them in from a file, write them by hand.. it doesn't matter much. We just need to make sure we have `x` and `y` arrays that are the same length. ### Line Properties A line appearing in a plot has several properties including color, transparency, style, width and markers. We can set these properties when we call `plt.plot` using the following keyword arguments: | Property | Description | | :---: | :--- | | `alpha` | transparency (0.0 transparent through 1.0 opaque) | | `color` (or `c`) | any matplotlib color | | `label` | text appearing in legend | | `linestyle` (or `ls`) | `solid`, `dashed`, `dashdot`, `dotted` | | `linewidth` (or `lw`) | set width of the line | | `marker` | set marker style | | `markeredgecolor` (or `mec`) | any matplotlib color | | `markerfacecolor` (or `mfc`) | any matplotlib color | | `markersize` (or `ms`) | size of the marker | Note that we can specify a [matplotlib color](https://matplotlib.org/api/colors_api.html) in several different ways including by name such as `blue` or `red`, or by a [RGB](https://www.w3schools.com/colors/colors_rgb.asp) tuple such as `(1,0,1)` for purple. For example, let's plot the function $$ y = e^{-x^2}\cos(2 \pi x) \ \ , \ \ x \in [-2,2] $$ ```python x = np.linspace(-2,2,41) # range of 4, so 0.1 resolution, plus one to ensure we get -2 and +2 y = np.exp(-x**2) * np.cos(2*np.pi*x) plt.plot(x,y,alpha=0.4,label='Decaying Cosine', color='red',linestyle='dashed',linewidth=2, marker='o',markersize=5,markerfacecolor='blue', markeredgecolor='blue') plt.ylim(-2, 2) # set the limits on the y-axis to -2,2 plt.legend() #show the plot legend plt.show() ``` Notice that we used the pyplot function `plt.legend` to display the figure with a legend (showing the line label) and and `plt.ylim` to set the limits on the vertical axis to `[-2,2]`. Another example: $$ y = \frac{1}{1 + x^2} \ , \ x \in [-5,5] $$ with a dashed black line and square markers: ```python x = np.linspace(-5,5,41) y = 1/(1 + x**2) plt.plot(x,y,color='black',linestyle='dashed',marker='s') plt.show() ``` Format strings can be used as a shorthand, e.g. `'ks--'` where `k` denotes a black line, `s` a square marker and `--` a dashed line. #### Colors | Character | Color | | :---: | :---: | | `b` | blue | | `g` | green | | `r` | red | | `c` | cyan | | `m` | magenta | | `y` | yellow | | `k` | black | | `w` | white | Any Web / HTML color name is supported, lists can be found [e.g., Wikipedia](https://en.wikipedia.org/wiki/Web_colors#HTML_color_names). #### Markers | Character | Marker | | :---: | :---: | | `.` | point | | `o` | circle | | `v` | triangle down | | `^` | triangle up | | `s` | square | | `p` | pentagon | | `*` | star | | `+` | plus | | `x` | x | | `D` | diamond | #### Line Styles | Character | Line Style | | :---: | :---: | | `-` | solid line style | | `--` | dashed line style | | `-.` | dash-dot line style | | `:` | dotted line style | See the [matplotlib.pyplot.plot documentation](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html) for more options. ### Pyplot Functions There are many `pyplot` functions available for us to customize our figures. For example: | Fucntion | Description | | ---: | :--- | | `plt.xlim` | set $x$ limits | | `plt.ylim` | set $y$ limits | | `plt.xscale` | set $x$ scale, e.g. "linear", "log", "symlog" | | `plt.yscale` | set $y$ scale, e.g. "linear", "log", "symlog" | | `plt.xlabel` | add label to the horizontal axis | | `plt.ylabel` | add label to the vertical axis | | `plt.xticks` | set tick locations on the horizontal axis | | `plt.yticks` | set tick locations on the vertical axis | | `plt.grid` | add grid lines | | `plt.title` | add a title | | `plt.axis` | set axis properties (`equal`, `off`, `scaled`, etc.) | | `plt.legend` | display legend for several lines in the same figure | | `plt.savefig` | save figure (as .png, .pdf, etc.) to working directory | | `plt.figure` | create a new figure and set its properties | See the [pyplot documentation](https://matplotlib.org/api/pyplot_summary.html) for a full list of functions. ### Examples We can also include more than one plot in a figure. We just call `plt.plot()` more than once before `plt.show()`. Indeed, that's part of the point of `matplotlib.pyplot` - you build up a set of commands that modifies the figure before `plt.show()` turns it into a graphic. ```python x = np.arange(-3.0, 3.0, 0.1) # notice that this leaves off 3.0 y1 = -x**2 + 2*x - 1 y2 = x**2 + 2*x + 0.75 plt.plot(x, y1, color='black') plt.plot(x, y2, color='red') plt.ylim(-4,4) # set the limit on the y-axis to -4 .. 4 plt.show() ``` ### Taylor Polynomials Plot the function $y = \cos(x)$ along with its [Taylor polynomials](https://en.wikipedia.org/wiki/Taylor_series) of degrees 2 and 4. ```python x = np.linspace(-6,6,50) # Plot y = cos(x) y = np.cos(x) plt.plot(x,y,'b',label='cos(x)') # Plot degree 2 Taylor polynomial y2 = 1 - x**2/2 plt.plot(x,y2,color='red',label='Degree 2') # Plot degree 4 Taylor polynomial y4 = 1 - x**2/2 + x**4/24 plt.plot(x,y4,color='green',label='Degree 4') # Add features to our figure plt.legend() plt.grid(True,linestyle=':') plt.xlim([-6,6]) plt.ylim([-4,4]) plt.title('Taylor Polynomials of cos(x) at x=0') plt.xlabel('x') plt.ylabel('y') plt.show() ``` ### Subplots The `plt.subplot` can be used to create arrays of plots. The function takes at least 3 inputs $n$, $m$ and $i$ and creates a figure with a $n$ by $m$ grid of subplots and then sets the $i$th subplot (counting across the rows) as the current plot (ie. current axes object). For example, consider the [sawtooth wave](https://en.wikipedia.org/wiki/Sawtooth_wave) $$ f(t) = \frac{1}{2} - \frac{1}{\pi} \sum_{k=1}^{\infty} (-1)^k \frac{\sin(2 \pi k t)}{k} $$ and let $f_N(t)$ denote the $N$th partial sum of the sawtooth wave: $$ f_N(t) = \frac{1}{2} - \frac{1}{\pi} \sum_{k=1}^{N} (-1)^k \frac{\sin(2 \pi k t)}{k} $$ Create a 2 by 2 grid of subplots to plot the first 4 partial sums: \begin{align} f_1(t) &= \frac{1}{2} + \frac{\sin(2 \pi t)}{\pi} \\\ f_2(t) &= \frac{1}{2} + \frac{\sin(2 \pi t)}{\pi} - \frac{\sin(4 \pi t)}{2\pi} \\\ f_3(t) &= \frac{1}{2} + \frac{\sin(2 \pi t)}{\pi} - \frac{\sin(4 \pi t)}{2\pi} + \frac{\sin(6 \pi t)}{3\pi} \\\ f_4(t) &= \frac{1}{2} + \frac{\sin(2 \pi t)}{\pi} - \frac{\sin(4 \pi t)}{2\pi} + \frac{\sin(6 \pi t)}{3\pi} - \frac{\sin(8 \pi t)}{4\pi} \end{align} ```python t = np.linspace(0,4,200) fN = 1/2 for N in [1,2,3,4]: fN = fN - (-1)**N * np.sin(2*N*np.pi*t)/(N*np.pi) plt.subplot(2,2,N) plt.plot(t,fN) plt.title('N = {}'.format(N)) plt.tight_layout() # adds some space between the subplots plt.show() ``` ## Scatter plots A [scatter plot](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html) has 4 dimensions: $x$ coordinate, $y$ coordinate, and optionally size and color. Let's make a random scatter plot: ```python # Set the number of dots in the plot N = 200 # Create N different random x and y coordinates sampled uniformly from [0,1] x = np.random.rand(N) y = np.random.rand(N) # Create random array sampled uniformly from [5,25] # `size` array is used below to set the size of each dot size = 20*np.random.rand(N) + 5 # Create a figure of size 12 by 5 and create scatter plot # plt.figure(figsize=(12,5)) plt.scatter(x,y,s=size) plt.axis('off') plt.show() ``` ### Histograms Generate an array of 5000 random numbers sampled from the normal distribution and create a [histogram](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist.html). Let's also superimpose the normal distribution: $$ y = \frac{1}{\sqrt{2\pi}} e^{-x^2/2} $$ ```python samples = np.random.randn(5000) # bins = 20 (i.e., 20 equal-sized bins) # density = True means the histogram will be rescaled to reflect the total # of samples plt.hist(samples,bins=20, density=True, alpha=0.5, color=(0.3,0.8,0.1)) plt.title('Random Samples - Normal Distribution') plt.ylabel('Frequency') # second plot, adding a Gaussian curve by evaluating x, y across -4 to +4 x = np.linspace(-4,4,100) y = 1/(2*np.pi)**0.5 * np.exp(-x**2/2) plt.plot(x,y, alpha=0.8) plt.show() ``` ------- This notebook is from Prof. Geoffrey Hutchison, University of Pittsburgh https://github.com/ghutchis/chem1000 Most of this material has been adapted from [Mathematical Python by Patrick Wills](https://github.com/patrickwalls/mathematical-python/tree/master/scipy) <a rel="license" href="http://creativecommons.org/licenses/by/4.0/"></a>
last edited by Claire Valva on May 13, 2019, with update and cleanup on June 24, 2019 # Test ENSO simulations and plotting ```python # import packages import numpy as np from scipy.fftpack import fft, ifft, fftfreq, fftshift, ifftshift import scipy.integrate as sciint import pandas as pd from math import pi from sympy import solve, Poly, Eq, Function, exp, re, im from scipy.optimize import fsolve from decimal import Decimal import pickle import time import random import multiprocessing as mp from joblib import Parallel, delayed import numpy as np from scipy.signal import get_window, csd from scipy.signal.windows import hann, hanning, nuttall, flattop from scipy.fftpack import fft, ifft, fftfreq, fftshift, ifftshift #import matplotlib #matplotlib.use('Agg') import matplotlib.pyplot as plt import scipy.integrate as sciint import pandas as pd import datetime import matplotlib.cm as cm from math import pi import matplotlib.ticker as tck import datetime from sympy import solve, Poly, Eq, Function, exp, re, im from netCDF4 import Dataset, num2date # This is to read .nc files and time array from scipy.optimize import fsolve from decimal import Decimal import pickle import multiprocessing as mp from joblib import Parallel, delayed import matplotlib.colors as colors from seaborn import cubehelix_palette #for contour plot colors import seaborn as sns from decimal import Decimal import numpy.ma as ma import random #flatten season for plotting flatten = lambda l: [item for sublist in l for item in sublist] ``` ```python import scipy.stats as spyst ``` ```python from os import walk oldf = [] for (dirpath, dirnames, filenames) in walk('/scratch/midway2/clairev/enso_spectra/'): oldf.extend(filenames) break f = [] for named in oldf: if named[0:15] == "spectra_enso_02": f.append(named) ``` ```python ``` ```python def solve_f(X, Zofkt): # function to solve f coeff equation for trend analysis x,y = X f = Zofkt - x*np.exp(1j*y) return [np.real(f), np.imag(f)] def real_f(X,Zofkt): # function to wrap solve_f so that it can be used with fsolve x,y = X z = [x+0j,y+0j] actual_f = solve_f(z, Zofkt) return(actual_f) def fwithZ(entry): answers = fsolve(real_f, np.array([0,0]), args = entry) return answers # get function to generate random coeffs def entry_fft(amp, phase = random.uniform(0, 2*pi)): # takes amplitude and phase to give corresponding fourier coeff entry = amp*np.exp(1j*phase) return entry # write functions to make a longer ifft def ext_row(row, n): ext_f = np.zeros(((len(row) - 1) * n + 1,), dtype="complex128") ext_f[::n] = row * n return ext_f def ext_ifft_new(n, input_array): # add the zeros onto each end ext_f = [ext_row(entry,n) for entry in input_array] # make up for the formulat multiplying for array length olddim = len(input_array[5]) newdim = len(ext_f[0]) mult = newdim/olddim ext_f = np.multiply(ext_f, mult) adjusted_tested = np.fft.ifft2(ext_f) return adjusted_tested ``` ```python season_titles = ["Winter", "Spring", "Summer", "Fall"] seasons = ["winter", "spring", "summer", "fall"] # flatten season for plotting flatten = lambda l: [item for sublist in l for item in sublist] named = f[0] ``` ```python #file_name = "/scratch/midway2/clairev/enso_spectra/averaged/01_enso_avg_" + str(named[16:21]) #file_pickle = open(file_name, "rb") #d2_touse, d2_seasons, d2_averages = pickle.load(file_pickle) ``` ```python ens = ["nino", "nina", "neutral"] d2_names = [enso + " " + part for part in seasons for enso in ens] d2_names ``` ['ninowinter', 'ninawinter', 'neutralwinter', 'ninospring', 'ninaspring', 'neutralspring', 'ninosummer', 'ninasummer', 'neutralsummer', 'ninofall', 'ninafall', 'neutralfall'] ```python name = "01_enso_36.0N424" name[8:13] ``` '36.0N' ```python file_name = "/scratch/midway2/clairev/enso_sims/01_enso_36.0N424" file_pickle = open(file_name, "rb") pickled = pickle.load(file_pickle) ``` ```python flat_sims = [flatten(entry[0]) for entry in pickled] ``` ```python #make lists of el nino/regular/la nina years nino = [1980,1983,1987,1988,1992, 1995,1998,2003,2007,2010] neutral = [1979,1981,1982,1984,1985,1986,1990, 1991,1993,1994,1996,1997,2001,2002, 2004,2005,2006,2009,2013,2014,2015,2016] nina = [1989,1999,2000,2008,2011,2012] ``` ```python len_all = 38.0 nina_per = len(nina)/len_all nino_per = len(nino)/len_all neutral_per = len(neutral)/len_all all_pers = [nina_per, nino_per, neutral_per] ``` ```python all_pers ``` [0.15789473684210525, 0.2631578947368421, 0.5789473684210527] ```python # now plot them # weight them by years percentrage when plotting together for j in range(4): plt.clf(); plt.figure(figsize=(15, 5)); for k in range(3): #print("hi") plt.hist(x = np.real(flat_sims[j*3 + k]), bins = 100, density = True, alpha = 0.5, label = d2_names[j*3 + k]) plt.ylabel("density") plt.legend() plt.xlabel("geopotential height") plt.show() ``` ```python # sort them into each season phase_all = [[[[fwithZ(entry) for entry in sublist] for sublist in year] for year in season] for season in d2_seasons] # sort them into each season amps_all = [[[[entry[0] for entry in sublist] for sublist in year] for year in season] for season in phase_all] ps_all = [[[[entry[1] % (2 * np.pi) for entry in sublist] for sublist in year] for year in season] for season in phase_all] # adjust for winter averaging # TO DO: come up with better procedure rather # current: chopping off edges to make the same length for averaging norml = 359 longl = 364 def padded(to_pad, index): length = len(to_pad) if index == 0: zeros = longl - length to_pad = list(to_pad) for i in range(zeros): to_pad.append(0) return to_pad else: return to_pad #pad rows with zeros to account for leap year season_amps_adj = [[[padded(row, 0) for row in entry] for entry in amps_all[i]] for i in range(len(amps_all))] #pad rows with zeros to account for leap year season_phase_adj = [[[padded(row, 0) for row in entry] for entry in ps_all[i]] for i in range(len(ps_all))] #get average amplitude for each season avg_amps = [np.average(season, axis = 0) for season in season_amps_adj] #get std amplitude for each season std_amps = [np.std(season, axis = 0) for season in season_amps_adj] #get average phases for each season avg_phase = [spyst.circmean(season, axis = 0) for season in season_phase_adj] #get std phases for each season std_phase = [spyst.circstd(season, axis = 0) for season in season_phase_adj] import pickle file_name2 = "/scratch/midway2/clairev/enso_spectra/averaged/01_enso_avg_" + str(named[16:21]) file_pickle = open(file_name2,'wb') pickle.dump([avg_amps,std_amps,avg_phase,std_phase],file_pickle) file_pickle.close() ``` ```python # get function to generate random coeffs def entry_fft(amp,std, phase, stdphase): # takes amplitude and phase to give corresponding fourier coeff amp_new = np.random.normal(loc = amp, scale = std) phase_new = np.random.normal(loc = phase, scale = stdphase) entry = amp_new*np.exp(1j*phase_new) return entry # write functions to make a longer ifft def ext_row(row, n): ext_f = np.zeros(((len(row) - 1) * n + 1,), dtype="complex128") ext_f[::n] = row * n return ext_f def ext_ifft_new(n, input_array): # add the zeros onto each end ext_f = [ext_row(entry,n) for entry in input_array] # make up for the formulat multiplying for array length olddim = len(input_array[5]) newdim = len(ext_f[0]) mult = newdim/olddim # ext_f = np.multiply(mult, ext_f) adjusted_tested = np.fft.ifft2(ext_f) return adjusted_tested def combined(amps,stds,phases,stdphases, length): # combines generation of random phase with inverse transform newarray = [[entry_fft(amp = amps[wave][timed], std = stds[wave][timed], phase = phases[wave][timed], stdphase = stdphases[wave][timed]) for timed in range(len(amps[wave]))] for wave in range(len(amps))] newarray = [np.array(leaf) for leaf in newarray] iffted = ext_ifft_new(length, newarray) return iffted def repeater(season, stds, phases,stdphases, length, times): # repeats the phase creation and inverse transform newarray = [combined(season, stds, phases,stdphases,length) for leaf in range(times)] return(newarray) # set lims runlen = 75 runtimes = 1 repeattimes = 20 listed_parts = [] def repeater_2(amps,stds, phases,stdphases, length, times): #do procedure repeated_comp = [repeater(amps[i],stds[i], phases[i], stdphases[i], length, times) for i in range(len(amps))] #output.put(repeated_comp) #listed_parts.append(repeated_comp) import pickle file_name2 = "/scratch/midway2/clairev/enso_sims/01_enso_" + str(named[16:21]) + str(random.randint(1,1000)) file_pickle = open(file_name2,'wb') pickle.dump(repeated_comp,file_pickle) file_pickle.close() return repeated_comp toplot = repeater_2(avg_amps,std_amps, runlen, runtimes) ```
import Logic.Predicate.FirstOrder.Formula variable {L L₁ L₂ L₃ : Language} {μ : Type _} namespace Language namespace Hom variable (Φ : Hom L₁ L₂) {n : ℕ} open FirstOrder def onSubFormula₁' (Φ : Hom L₁ L₂) : ∀ {n}, SubFormula L₁ μ n → SubFormula L₂ μ n | _, ⊤ => ⊤ | _, ⊥ => ⊥ | _, SubFormula.rel r v => SubFormula.rel (Φ.onRel r) (fun i => Φ.onSubTerm (v i)) | _, SubFormula.nrel r v => SubFormula.nrel (Φ.onRel r) (fun i => Φ.onSubTerm (v i)) | _, p ⋏ q => Φ.onSubFormula₁' p ⋏ Φ.onSubFormula₁' q | _, p ⋎ q => Φ.onSubFormula₁' p ⋎ Φ.onSubFormula₁' q | _, ∀' p => ∀' Φ.onSubFormula₁' p | _, ∃' p => ∃' Φ.onSubFormula₁' p lemma onSubFormula₁'_neg {n} (p : SubFormula L₁ μ n) : Φ.onSubFormula₁' (~p) = ~Φ.onSubFormula₁' p := by induction p using SubFormula.rec' <;> simp[*, onSubFormula₁', ←SubFormula.neg_eq] def onSubFormula₁ (Φ : Hom L₁ L₂) {n} : SubFormula L₁ μ n →L SubFormula L₂ μ n where toFun := Φ.onSubFormula₁' map_top' := by simp[onSubFormula₁'] map_bot' := by simp[onSubFormula₁'] map_and' := by simp[onSubFormula₁'] map_or' := by simp[onSubFormula₁'] map_neg' := by simp[onSubFormula₁'_neg] map_imp' := by simp[SubFormula.imp_eq, onSubFormula₁'_neg, ←SubFormula.neg_eq, onSubFormula₁'] lemma onSubFormula₁_rel {k} (r : L₁.rel k) (v : Fin k → SubTerm L₁ μ n) : Φ.onSubFormula₁ (SubFormula.rel r v) = SubFormula.rel (Φ.onRel r) (fun i => Φ.onSubTerm (v i)) := rfl lemma onSubFormula₁_nrel {k} (r : L₁.rel k) (v : Fin k → SubTerm L₁ μ n) : Φ.onSubFormula₁ (SubFormula.nrel r v) = SubFormula.nrel (Φ.onRel r) (fun i => Φ.onSubTerm (v i)) := rfl @[simp] lemma onSubFormula₁_all (p : SubFormula L₁ μ (n + 1)) : Φ.onSubFormula₁ (∀' p) = ∀' Φ.onSubFormula₁ p := rfl @[simp] lemma onSubFormula₁_ex (p : SubFormula L₁ μ (n + 1)) : Φ.onSubFormula₁ (∃' p) = ∃' Φ.onSubFormula₁ p := rfl end Hom end Language namespace FirstOrder namespace SubFormula variable {L₁ L₂ : Language} (Φ : L₁ →ᵥ L₂) {μ₁ μ₂ : Type _} {n₁ n₂ : ℕ} lemma onSubFormula₁_bind (bound : Fin n₁ → SubTerm L₁ μ₂ n₂) (free : μ₁ → SubTerm L₁ μ₂ n₂) (p) : Φ.onSubFormula₁ (bind bound free p) = bind (fun x => Φ.onSubTerm (bound x)) (fun x => Φ.onSubTerm (free x)) (Φ.onSubFormula₁ p) := by induction p using rec' generalizing μ₂ n₂ <;> simp[*, SubTerm.onSubTerm_bind, Matrix.comp_vecCons, Function.comp, SubTerm.onSubTerm_bShift, Language.Hom.onSubFormula₁_rel, Language.Hom.onSubFormula₁_nrel, bind_rel, bind_nrel] lemma onSubFormula₁_map (bound : Fin n₁ → Fin n₂) (free : μ₁ → μ₂) (p) : Φ.onSubFormula₁ (map bound free p) = map bound free (Φ.onSubFormula₁ p) := by simp[map, onSubFormula₁_bind] lemma onSubFormula₁_subst (u) (p : SubFormula L₁ μ (n + 1)) : Φ.onSubFormula₁ (subst u p) = subst (Φ.onSubTerm u) (Φ.onSubFormula₁ p) := by simp[subst, onSubFormula₁_bind, Matrix.comp_vecConsLast, Function.comp] lemma onSubFormula₁_shift (p : SyntacticSubFormula L₁ n) : Φ.onSubFormula₁ (shift p) = shift (Φ.onSubFormula₁ p) := by simp[shift, onSubFormula₁_map] lemma onSubFormula₁_free (p : SyntacticSubFormula L₁ (n + 1)) : Φ.onSubFormula₁ (free p) = free (Φ.onSubFormula₁ p) := by simp[free, onSubFormula₁_bind]; congr; exact funext $ Fin.lastCases (by simp) (by simp) lemma onSubFormula₁_fix (p : SyntacticSubFormula L₁ n) : Φ.onSubFormula₁ (fix p) = fix (Φ.onSubFormula₁ p) := by simp[fix, onSubFormula₁_bind]; congr; funext x; cases x <;> simp end SubFormula variable {L : Language} [∀ k, DecidableEq (L.func k)] [∀ k, DecidableEq (L.rel k)] namespace SubFormula noncomputable def languageFunc : ∀ {n}, SubFormula L μ n → Finset (Σ k, L.func k) | _, ⊤ => ∅ | _, ⊥ => ∅ | _, rel _ v => Finset.bunionᵢ Finset.univ (fun i => SubTerm.languageFunc (v i)) | _, nrel _ v => Finset.bunionᵢ Finset.univ (fun i => SubTerm.languageFunc (v i)) | _, p ⋏ q => languageFunc p ∪ languageFunc q | _, p ⋎ q => languageFunc p ∪ languageFunc q | _, ∀' p => languageFunc p | _, ∃' p => languageFunc p noncomputable def languageRel : ∀ {n}, SubFormula L μ n → Finset (Σ k, L.rel k) | _, ⊤ => ∅ | _, ⊥ => ∅ | _, rel r _ => {⟨_, r⟩} | _, nrel r _ => {⟨_, r⟩} | _, p ⋏ q => languageRel p ∪ languageRel q | _, p ⋎ q => languageRel p ∪ languageRel q | _, ∀' p => languageRel p | _, ∃' p => languageRel p lemma languageFunc_rel_ss {k} (r : L.rel k) (v : Fin k → SubTerm L μ n) (i) : (v i).languageFunc ⊆ (rel r v).languageFunc := by intros x; simp[languageFunc]; intros h; exact ⟨i, h⟩ def toSubLanguage' (pf : ∀ k, L.func k → Prop) (pr : ∀ k, L.rel k → Prop) : ∀ {n} (p : SubFormula L μ n), (∀ k f, ⟨k, f⟩ ∈ p.languageFunc → pf k f) → (∀ k r, ⟨k, r⟩ ∈ p.languageRel → pr k r) → SubFormula (L.subLanguage pf pr) μ n | _, ⊤, _, _ => ⊤ | _, ⊥, _, _ => ⊥ | _, rel r v, hf, hr => rel ⟨r, hr _ r (by simp[languageRel])⟩ (fun i => (v i).toSubLanguage' pf pr (fun k f h => hf k f (languageFunc_rel_ss r v i h))) | _, nrel r v, hf, hr => nrel ⟨r, hr _ r (by simp[languageRel])⟩ (fun i => (v i).toSubLanguage' pf pr (fun k f h => hf k f (languageFunc_rel_ss r v i h))) | _, p ⋏ q, hf, hr => toSubLanguage' pf pr p (fun k f h => hf k f (Finset.mem_union_left _ h)) (fun k r h => hr k r (Finset.mem_union_left _ h)) ⋏ toSubLanguage' pf pr q (fun k f h => hf k f (Finset.mem_union_right _ h)) (fun k r h => hr k r (Finset.mem_union_right _ h)) | _, p ⋎ q, hf, hr => toSubLanguage' pf pr p (fun k f h => hf k f (Finset.mem_union_left _ h)) (fun k r h => hr k r (Finset.mem_union_left _ h)) ⋎ toSubLanguage' pf pr q (fun k f h => hf k f (Finset.mem_union_right _ h)) (fun k r h => hr k r (Finset.mem_union_right _ h)) | _, ∀' p, hf, hr => ∀' toSubLanguage' pf pr p (fun k f h => hf k f h) (fun k r h => hr k r h) | _, ∃' p, hf, hr => ∃' toSubLanguage' pf pr p (fun k f h => hf k f h) (fun k r h => hr k r h) @[simp] lemma onSubFormula_toSubLanguage' (pf : ∀ k, L.func k → Prop) (pr : ∀ k, L.rel k → Prop) {n} (p : SubFormula L μ n) (hf : ∀ k f, ⟨k, f⟩ ∈ p.languageFunc → pf k f) (hr : ∀ k r, ⟨k, r⟩ ∈ p.languageRel → pr k r) : L.ofSubLanguage.onSubFormula₁ (p.toSubLanguage' pf pr hf hr) = p := by induction p using rec' <;> simp[*, toSubLanguage', Language.Hom.onSubFormula₁_rel, Language.Hom.onSubFormula₁_nrel] noncomputable def languageFuncIndexed (p : SubFormula L μ n) (k) : Finset (L.func k) := Finset.preimage (languageFunc p) (Sigma.mk k) (Set.injOn_of_injective sigma_mk_injective _) noncomputable def languageRelIndexed (p : SubFormula L μ n) (k) : Finset (L.rel k) := Finset.preimage (languageRel p) (Sigma.mk k) (Set.injOn_of_injective sigma_mk_injective _) def language (p : SubFormula L μ n) : Language := Language.subLanguage L (fun k f => ⟨k, f⟩ ∈ languageFunc p) (fun k r => ⟨k, r⟩ ∈ languageRel p) noncomputable instance (p : SubFormula L μ n) (k) : Fintype (p.language.func k) := Fintype.subtype (languageFuncIndexed p k) (by simp[languageFuncIndexed]) noncomputable instance (p : SubFormula L μ n) (k) : Fintype (p.language.rel k) := Fintype.subtype (languageRelIndexed p k) (by simp[languageRelIndexed])
Andrew 's VC was displayed at the QEII Army Memorial Museum , Waiouru , New Zealand . On 2 December 2007 it was one of nine Victoria Crosses that were among a hundred medals stolen from the museum . On 16 February 2008 , New Zealand Police announced all the medals had been recovered as a result of a NZ $ 300 @,@ 000 reward offered by Michael Ashcroft and Tom Sturgess .
\documentclass{book} % Add search paths for input files \makeatletter \def\input@path{{../}{../../}{../texinputs/}} \makeatother \usepackage{amsmath} \usepackage{framed} \def\d{{\bf d}} \def\p{{\bf p}} \def\v{{\bf v}} \def\T{{\bf T}} \def\I{{\bf I}} \def\X{{\bf X}} \def\matl{\left(\begin{matrix}} \def\matr{\end{matrix}\right)} \input{artisynthDoc} \setcounter{tocdepth}{5} \setcounter{secnumdepth}{3} \title{Maspack Reference Manual} \author{John Lloyd} \setpubdate{Last update: Jun 15, 2016} \iflatexml \date{} \fi \begin{document} \frontmatter \maketitle \iflatexml{\large\pubdate}\fi \tableofcontents \chapter*{Preface} \addcontentsline{toc}{chapter}{\protect\numberline{}Preface} Maspack (modeling and simulation package) is a set of Java packages to support physical modeling and simulation. The purpose of this guide is to document some of these packages in detail, one package per chapter. At present, the guide is incomplete and documents only the property and rendering packages. More chapters will be added as resources permit. \mainmatter \input{properties} \input{rendering} \end{document}
Although the official language of Jamaica is Standard English, many Jamaicans also speak Patois which is a separate dialect/language. Jamaican Patois (also known as “Patwa”, “Patwah” or “Jamaican Creole”) is the language that is used by most Jamaicans in casual everyday conversations while Standard English is normally reserved for professional environments. "Jamaican Patois is a separate language from Jamaican English." Jamaican Patois is a strange language in that it has many borrowed words from many different languages, for example, English, Spanish and some West African languages. However, the pronunciations of these words are very similar to Jamaican English. One thing to keep in mind as you learn Jamaican Patois is that it is not a strict, rule-oriented language where there is a "right way" and a "wrong way" to say things. Some words can be pronounced and spelled differently but still mean the same thing (e.g. both ‘Pickney’ and ‘Pickeney’ translates to ‘Child'). The important thing is whether or not what you are saying can be understood. It's actually quite difficult to acquire the accent of a Jamaican, unless you've lived in Jamaica for many years, and even then, speaking patois fluently is not guaranteed. But with a little practice, you will be able to have at least a basic understanding of Jamaican Patois. Let us now take a look at some of the grammatical features of Jamaican Patois. Sentences in Jamaican Patois are built like English sentences in that, there is a subject, a predicate (or verb), and an object. However, there is no subject-verb agreement in Jamaican Patois. The verb does not change with the subject. Let us look at the table below. However, in Jamaican Patois a word can be pluralized by adding 'dem' to the end word or, inserting 'nuff' or a number at the beginning of the word. There is no differentiation in the use of pronouns to show gender. The pronoun 'im' can mean both or either 'he' or 'she'. There is no distinction between subject and object. The copula is a connecting word; for example, in Jamaican Patois the copula is the letter 'a' which is used for the particle as well as for the continuous tense. In Standard English it is never acceptable to use double negatives such as 'nobody does not'. However, in• Jamaican Patois double negatives are accepted. By now you probably have a basic understanding on the differences between Jamaican Patois and Standard English, for a more detailed guide, you can check out our how to speak Jamaican Patois series.
# Copyright (c) OpenMMLab. All rights reserved. import math import torch import torch.nn as nn import torch.nn.functional as F from ..builder import LOSSES from .utils import get_class_weight, weight_reduce_loss import numpy as np import pandas as pd import math import copy np.set_printoptions(threshold=np.inf) def pixel_cross_entropy(pred, label, weight=None, class_weight=None, reduction='mean', avg_factor=None, ignore_index=-100, alpha=1, gamma=0, pa=1, only_block=True): """The wrapper function for :func:`F.cross_entropy`""" # class_weight is a manual rescaling weight given to each class. # If given, has to be a Tensor of size C element-wise losses batch_num=label.shape[0] heigh=label.shape[1] width=label.shape[2] lab=[pd.DataFrame(np.argwhere(np.row_stack((lab,np.ones(width,dtype='int')))==1),columns=['value','key']).groupby('key',as_index=False).min().sort_values(by='key') for lab in label.tolist()] colidx=np.array([i for i in range(heigh)]) diclab=[dict(zip(sublab['key'],sublab['value'])) for sublab in lab] w=[np.array([colidx-subdiclab[i] for i in range(width)]).T for subdiclab in diclab] g=[np.array([heigh-subdiclab[i] for i in range(width)])/8 for subdiclab in diclab] a=copy.deepcopy(w) ###onlyblock set for suba in a: suba[suba>=0]=0 suba[suba<0]=-10000 #b=copy.deepcopy(w) b = label.cpu().numpy() - a #b 水下障碍物为1 其他为0 for subb in b: subb[subb == 0] = 2022 subb[subb != 2022] = 0 subb[subb == 2022] = 1 c = copy.deepcopy(b) #c 水下障碍物为0 其他为1 for subc in c: subc[subc == 0] = 2022 subc[subc == 1] = 0 subc[subc == 2022] = 1 #full water set d = copy.deepcopy(w) for subd in d: subd[subd >= 0] = 1 subd[subd < 0] = 0 e = copy.deepcopy(w) for sube in e: sube[sube >= 0] = 0 sube[sube < 0] = 1 a = np.array(a) b = np.array(b) c = np.array(c) d = np.array(d) e = np.array(e) #res = 1+ np.exp(-np.square(w)/(np.square(g)*2))/np.sqrt(2*math.pi) res = np.array([1 + np.exp(-np.square(w[i]) / (np.square(g[i]) * 2 + 1)) / (pa*np.sqrt(2 * math.pi)) for i in range(batch_num)]) #wio 水中的非水障碍物 #res1 = np.array([1 + w[i]/(1+w[i]) for i in range(batch_num)]) #wis 水中的天空 if only_block: res = res*b + c else: res = res*d + e loss = F.cross_entropy( pred, label, weight=class_weight, reduction='none', ignore_index=ignore_index) res = torch.tensor(res).requires_grad_(False).type(torch.cuda.FloatTensor).to(loss.get_device()) # print('res') # print(res.cpu().numpy()) # print('before_res_loss') # print(loss.cpu().numpy()) loss = res*loss # print('loss_shape') # print(loss.shape) # print(loss.cpu().numpy()) pt = torch.exp(-loss) focal_loss = alpha * (1 - pt) ** gamma * loss # print(focal_loss.shape) # apply weights and do the reduction if weight is not None: weight = weight.float() loss = weight_reduce_loss( focal_loss, weight=weight, reduction=reduction, avg_factor=avg_factor) return loss def cross_entropy(pred, label, weight=None, class_weight=None, reduction='mean', avg_factor=None, ignore_index=-100, alpha=1, gamma=0, pa=1, only_block=True): """The wrapper function for :func:`F.cross_entropy`""" # class_weight is a manual rescaling weight given to each class. loss = F.cross_entropy( pred, label, weight=class_weight, reduction='none', ignore_index=ignore_index) pt = torch.exp(-loss) focal_loss = alpha * (1 - pt) ** gamma * loss #print(focal_loss.shape) # apply weights and do the reduction if weight is not None: weight = weight.float() loss = weight_reduce_loss( focal_loss, weight=weight, reduction=reduction, avg_factor=avg_factor) return loss def _expand_onehot_labels(labels, label_weights, target_shape, ignore_index): """Expand onehot labels to match the size of prediction.""" bin_labels = labels.new_zeros(target_shape) valid_mask = (labels >= 0) & (labels != ignore_index) inds = torch.nonzero(valid_mask, as_tuple=True) if inds[0].numel() > 0: if labels.dim() == 3: bin_labels[inds[0], labels[valid_mask], inds[1], inds[2]] = 1 else: bin_labels[inds[0], labels[valid_mask]] = 1 valid_mask = valid_mask.unsqueeze(1).expand(target_shape).float() if label_weights is None: bin_label_weights = valid_mask else: bin_label_weights = label_weights.unsqueeze(1).expand(target_shape) bin_label_weights *= valid_mask return bin_labels, bin_label_weights def binary_cross_entropy(pred, label, weight=None, reduction='mean', avg_factor=None, class_weight=None, ignore_index=255, alpha=1, gamma=0, pa=1, only_block=True ): """Calculate the binary CrossEntropy loss. Args: pred (torch.Tensor): The prediction with shape (N, 1). label (torch.Tensor): The learning label of the prediction. weight (torch.Tensor, optional): Sample-wise loss weight. reduction (str, optional): The method used to reduce the loss. Options are "none", "mean" and "sum". avg_factor (int, optional): Average factor that is used to average the loss. Defaults to None. class_weight (list[float], optional): The weight for each class. ignore_index (int | None): The label index to be ignored. Default: 255 Returns: torch.Tensor: The calculated loss """ if pred.dim() != label.dim(): assert (pred.dim() == 2 and label.dim() == 1) or ( pred.dim() == 4 and label.dim() == 3), \ 'Only pred shape [N, C], label shape [N] or pred shape [N, C, ' \ 'H, W], label shape [N, H, W] are supported' label, weight = _expand_onehot_labels(label, weight, pred.shape, ignore_index) # weighted element-wise losses if weight is not None: weight = weight.float() loss = F.binary_cross_entropy_with_logits( pred, label.float(), pos_weight=class_weight, reduction='none') # do the reduction for the weighted loss loss = weight_reduce_loss( loss, weight, reduction=reduction, avg_factor=avg_factor) return loss def mask_cross_entropy(pred, target, label, reduction='mean', avg_factor=None, class_weight=None, ignore_index=None, alpha=1, gamma=0, pa=1, only_block=True): """Calculate the CrossEntropy loss for masks. Args: pred (torch.Tensor): The prediction with shape (N, C), C is the number of classes. target (torch.Tensor): The learning label of the prediction. label (torch.Tensor): ``label`` indicates the class label of the mask' corresponding object. This will be used to select the mask in the of the class which the object belongs to when the mask prediction if not class-agnostic. reduction (str, optional): The method used to reduce the loss. Options are "none", "mean" and "sum". avg_factor (int, optional): Average factor that is used to average the loss. Defaults to None. class_weight (list[float], optional): The weight for each class. ignore_index (None): Placeholder, to be consistent with other loss. Default: None. Returns: torch.Tensor: The calculated loss """ assert ignore_index is None, 'BCE loss does not support ignore_index' # TODO: handle these two reserved arguments assert reduction == 'mean' and avg_factor is None num_rois = pred.size()[0] inds = torch.arange(0, num_rois, dtype=torch.long, device=pred.device) pred_slice = pred[inds, label].squeeze(1) return F.binary_cross_entropy_with_logits( pred_slice, target, weight=class_weight, reduction='mean')[None] @LOSSES.register_module() class CrossEntropyLoss(nn.Module): """CrossEntropyLoss. Args: use_sigmoid (bool, optional): Whether the prediction uses sigmoid of softmax. Defaults to False. use_mask (bool, optional): Whether to use mask cross entropy loss. Defaults to False. reduction (str, optional): . Defaults to 'mean'. Options are "none", "mean" and "sum". class_weight (list[float] | str, optional): Weight of each class. If in str format, read them from a file. Defaults to None. loss_weight (float, optional): Weight of the loss. Defaults to 1.0. loss_name (str, optional): Name of the loss item. If you want this loss item to be included into the backward graph, `loss_` must be the prefix of the name. Defaults to 'loss_ce'. """ def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', class_weight=None, loss_weight=1.0, loss_name='loss_ce', alpha=1, gamma=0, use_pixel_weight=False, pa=1, only_block=True ): super(CrossEntropyLoss, self).__init__() assert (use_sigmoid is False) or (use_mask is False) self.use_sigmoid = use_sigmoid self.use_mask = use_mask self.reduction = reduction self.loss_weight = loss_weight self.class_weight = get_class_weight(class_weight) self.alpha = alpha self.gamma = gamma self.use_pixel_weight = use_pixel_weight self.pa = pa self.only_block = only_block if self.use_sigmoid: self.cls_criterion = binary_cross_entropy elif self.use_mask: self.cls_criterion = mask_cross_entropy elif self.use_pixel_weight: self.cls_criterion = pixel_cross_entropy else: self.cls_criterion = cross_entropy self._loss_name = loss_name def forward(self, cls_score, label, weight=None, avg_factor=None, reduction_override=None, **kwargs): """Forward function.""" assert reduction_override in (None, 'none', 'mean', 'sum') reduction = ( reduction_override if reduction_override else self.reduction) if self.class_weight is not None: class_weight = cls_score.new_tensor(self.class_weight) else: class_weight = None loss_cls = self.loss_weight * self.cls_criterion( cls_score, label, weight, class_weight=class_weight, reduction=reduction, avg_factor=avg_factor, alpha=self.alpha, gamma=self.gamma, pa=self.pa, only_block=self.only_block, **kwargs) return loss_cls @property def loss_name(self): """Loss Name. This function must be implemented and will return the name of this loss function. This name will be used to combine different loss items by simple sum operation. In addition, if you want this loss item to be included into the backward graph, `loss_` must be the prefix of the name. Returns: str: The name of this loss item. """ return self._loss_name
So you have your children writing every day. Great! Now, of course, you need to become their editor. Here is where some find a challenge in the natural approach to language arts. What if I don’t feel competent to edit my child’s writing? We’ll address the underlying problem with that argument further down, but for now — here are 10 ways to become a better editor of your child’s writing. 1. Read A Strong Start in Language. This Ruth Beechick title for beginning grades is recommended widely — from The Well-Trained Mind to Sonlight. Typically packaged as part of The Three Rs, A Strong Start in Language helps you become the editor from the beginning — from the time your child traces his first letters, to copywork, and through dictation. Read our full review (scroll down). 2. Read You Can Teach Your Child Successfully. Over 100 pages are devoted to writing in this followup to the Three Rs by Ruth Beechick mentioned above. The book speaks to you as your child’s tutor and therefore includes writing activities, writing lessons to get you started and that you can pattern your own lessons after, and suggestions for usage, grammar, mechanics, and spelling. Best of all it tells you what you can expect from your child at various levels on the writing scale. Very valuable reference to finding your way as you teach writing naturally to your children and we cannot recommend it highly enough. You can read our full review (scroll down). 3. Use Learning Grammar Through Writing. This handy reference published by Educators Publishing Service is now out of print. But it is worth finding. When you find a mistake in your child’s writing, you can find the coordinating pithy rule with an example to have your child copy into a grammar notebook. A checklist at the back helps you keep track of the skills you have covered. The best way to improve your editing is to read good writing. While you work through the suggestions above, you can be building your foundation in good writing at the same time. 5. Make use of a dictionary. Before the days of Kindle we had electronic dictionaries handy that included a grammar reference. Although somewhat pricey, the better models not only include the definitions, but also the etymology of the word. Most also come with a built-in thesaurus and other tools. If nothing else, a good dictionary can shed some light on how words are properly used in sentences. Not popular with some, but a valuable skill for understanding how words work in sentences. There are easy online courses that can help you quickly learn the basics. For simple and easy practice we like The Complete Book of Diagrams by Mary Daily published by The Riggs Institute Press, which also is a great help for Mom. 7. Use Learn to Write the Novel Way. While your child writes his novel as he works through this book, you have a guide that helps you edit your child’s writing. Learn by doing. Read our full review. 8. Read The Elements of Style. This widely recommended classic by Strunk and White holds the title for the most concise and simple usage, composition, and spelling reference. There is even an early version in the public domain. 9. Read How to Write Clearly by Ruth Beechick. Subtitled, The Meaning Approach, this is another handy writing reference that covers finding a topic, getting organized, outlining, using abstract and concrete terms, sentences, comma usage, active and passive voice, choosing words, usage, and more! Read our full review. It’s never too late. Having a working knowledge of how Latin works is probably one of the best ways to understand how the English language works. You will also want a grammar reference. Our favorite grammar reference is the Handbook of Grammar and Composition published by A Beka. We purchased it on a recommendation in The Well-Trained Mind and haven’t looked back. Now, back to the initial question: what if you don’t feel competent to edit your child’s writing? You do know how to write, yes? In this day of streaming output you may even write for a blog or other publication. Using the ideas above, you should be able to stay ahead of your child’s work. Of course, at some point, if you feel you are losing ground there are many qualified and reputable online writing tutors available. What to have your child do. More structure for those who need it. Where to put the writing. You’ll also want to have your child keep one of these.
# Problem: Find the moviment equations of the 2 DoF Scara arm. ## Frames and Variables Initialy, we need to define our reference frames and the symbolic variables.The first **Reference Frame** `B0`, is located in the same high as the arm and pointing in the rotating joint. The next frame,`B1`, is a **Moving Frame**. It follows the rotations of the first frame, therefora, related by a rotations of $\theta_1$ related to `B0`. Finally, the last frame rotates $\theta_2$ regarding `B1`. ```python # Funções e Bibliotecas Utilizadas from sympy import symbols, pprint, simplify, Eq, diff from sympy.physics.mechanics import * from sympy.physics.mechanics.functions import inertia init_vprinting() # Variáveis Simbólicas theta_1, theta_2 = dynamicsymbols('theta_1 theta_2') dtheta_1, dtheta_2 = dynamicsymbols('theta_1 theta_2', 1) tau_1, tau_2 = symbols('tau_1 tau_2') l_1, l_2 = symbols('l_1 l_2', positive = True) r_1, r_2 = symbols('r_1 r_2', positive = True) m_1, m_2, g = symbols('m_1 m_2 g') I_1_zz, I_2_zz = symbols('I_{1zz}, I_{2zz}') # Referenciais B0 = ReferenceFrame('B0') # Referencial Inercial B1 = ReferenceFrame('B1') B1.orient(B0, 'Axis', [theta_1, B0.z]) # Referencial móvel: theta_1 em relação a B0.z B2 = ReferenceFrame('B2') B2.orient(B1, 'Axis', [theta_2, B1.z]) # Referencial móvel: theta_2 em relação a B1.z ``` ## Points e Rigid Bodies Now that the frames are defined, we can start to place the fixed points.The points `CM_1` and `CM_2` represent the **Center of Mass ** of the arm's links. Each of this links have their own moment, `I_1` e `I_2`. Furthermore, points O and A represent the fixed joints. ```python # Pontos e Centros de Massa O = Point('O') O.set_vel(B0, 0) A = Point('A') A.set_pos(O, l_1 * B1.x) A.v2pt_theory(O, B0, B1) CM_1 = Point('CM_1') CM_1.set_pos(O, r_1 * B1.x) CM_1.v2pt_theory(O, B0, B1) CM_2 = Point('CM_2') CM_2.set_pos(A, r_2 * B2.x) CM_2.v2pt_theory(O, B0, B2) # Corpos Rígidos I_1 = inertia(B1, 0, 0, I_1_zz) E_1 = RigidBody('Elo_1', CM_1, B1, m_1, (I_1, CM_1)) # Elo 1 I_2 = inertia(B1, 0, 0, I_1_zz) E_2 = RigidBody('Elo_2', CM_2, B2, m_2, (I_2, CM_2)) # Elo 2 ``` ## Potencial Energy and Generalized Forces **Sympy** needs explicit definition of external potencial energies in the beodies.As the arm is only acting in the $(x,y)$ plane, the gravity force will not perfom any influence in the moviment equations. ```python # Energia Potencial P_1 = -m_1 * g * B0.z r_1_CM = CM_1.pos_from(O).express(B0) E_1.potential_energy = r_1_CM.dot(P_1) P_2 = -m_2 * g * B0.z r_2_CM = CM_2.pos_from(O).express(B0).simplify() E_2.potential_energy = r_2_CM.dot(P_2) # Forças/Momentos Generalizados FL = [(B1, tau_1 * B0.z),(B2, tau_2 * B0.z)] (E_2.potential_energy, E_1.potential_energy) ``` ## Lagrangian e Moviment Equations Finally, we can solve the langrangian and movimento equations of the system.In **Sympy**, we call the `Lagrangian` method andthe `LagrangesMethod` class to solve the system. ```python # Método de Lagrange L = Lagrangian(B0, E_1, E_2) L = L.simplify() LM = LagrangesMethod(L, [theta_1, theta_2], frame=B0, forcelist=FL) # Equações do Movimento L_eq = LM.form_lagranges_equations() L_eq ``` We still can decouple the **Moviment Equations** using the `rhs` method on the previous class. ```python # Equações Prontas para Solução Numérica rhs = LM.rhs() rhs ``` ```python ```
#' Class ngram #' #' An n-gram is an ordered sequence of n "words" taken from a body of "text". #' The terms "words" and "text" can easily be interpreted literally, or with a #' more loose interpretation. #' #' For example, consider the sequence "A B A C A B B". If we examine the #' 2-grams (or bigrams) of this sequence, they are #' #' A B, B A, A C, C A, A B, B B #' #' or without repetition: #' #' A B, B A, A C, C A, B B #' #' That is, we take the input string and group the "words" 2 at a time (because #' \code{n=2}). Notice that the number of n-grams and the number of words are #' not obviously related; counting repetition, the number of n-grams is equal #' to #' #' \code{nwords - n + 1} #' #' Bounds ignoring repetition are highly dependent on the input. A correct but #' useless bound is #' #' \code{\#ngrams = nwords - (\#repeats - 1) - (n - 1)} #' #' An \code{ngram} object is an S4 class container that stores some basic #' summary information (e.g., n), and several external pointers. For #' information on how to construct an \code{ngram} object, see #' \code{\link{ngram}}. #' #' @slot str_ptr #' A pointer to a copy of the original input string. #' @slot strlen #' The length of the string. #' @slot n #' The eponymous 'n' as in 'n-gram'. #' @slot ngl_ptr #' A pointer to the processed list of n-grams. #' @slot ngsize #' The length of the ngram list, or in other words, the number of #' unique n-grams in the input string. #' @slot sl_ptr #' A pointer to the list of words from the input string. #' #' @name ngram-class #' @seealso \code{\link{ngram}} #' @keywords Tokenization setClass("ngram", representation( str_ptr = "externalptr", strlen = "integer", n = "integer", ngl_ptr = "externalptr", ngsize = "integer", sl_ptr = "externalptr" ) )
# Extract bird traits # Install devtools if not available # if(!"remotes" %in% installed.packages()[,"Package"]) install.packages("remotes") # Install traitdata package from Github # remotes::install_github("RS-eco/traitdata") # load packages library(traitdata) library(dplyr) ## Load the Canadian dataset clpi <- read.csv("data-raw/CIEE_LPI_dataset.csv") # subset to birds sp_birds <- filter(lpd, Class %in% c("Aves", "Birds")) %>% summarise(sp = unique(Binomial)) # convert to a vector sp_birds <- sp_birds$sp ## 1. Extract avian elton traits # load Elton Traits data("elton_birds") # extract data clpi_eltonbirds <- elton_birds %>% # switch out species for _ in the species names to match the LPD mutate(scientificNameStd = gsub(" ", "_", scientificNameStd)) %>% # filter for species who are in the LPD dataset filter(scientificNameStd %in% sp_birds) %>% # subset to the traits we want subset(select = c(scientificNameStd, Diet.5Cat, BodyMass.Value)) # look at the dataset summary(clpi_eltonbirds) # check which species are missing body mass data clpi_eltonbirds[which(is.na(clpi_eltonbirds$Diet.5Cat)), "scientificNameStd"] clpi_eltonbirds[which(is.na(clpi_eltonbirds$BodyMass.Value)), "scientificNameStd"] colnames(clpi_eltonbirds)[1] <- "Binomial" ## 2. Extract avian body size # load avian body size data data("AvianBodySize") # extract data clpi_aviansize <- AvianBodySize %>% # switch out species for _ in the species names to match the LPD mutate(scientificNameStd = gsub(" ", "_", scientificNameStd)) %>% # filter for species who are in the LPD dataset filter(scientificNameStd %in% sp_birds) %>% # subset to the traits we want subset(select = c(scientificNameStd, M_mass, F_mass)) %>% # change -999.0 to NAs mutate(M_mass = replace(M_mass, M_mass == -999.0, NA), F_mass = replace(F_mass, F_mass == -999.0, NA)) # compute average for male and female mass # look at the dataset summary(clpi_aviansize) # check which species are missing body mass data clpi_aviansize[which(is.na(clpi_aviansize$mass)), "scientificNameStd"] colnames(clpi_aviansize)[1] <- "Binomial" ## Join to the larger clpi dataset clpi_birds <- clpi %>% left_join(clpi_eltonbirds, by = "Binomial") %>% left_join(clpi_aviansize, by = "Binomial") # change NAs to NULL clpi_birds[is.na(clpi_birds)] <- "NULL" head(clpi_birds) # write to rds saveRDS(clpi_birds, "data-clean/LPI_birds.rds")
# spare linear regression using stan library(distbayesianmc) if(T){ setwd("~/R_programming/distbayesianmc") source("~/R_programming/distbayesianmc/params_simulation/params_sparse_median.R") stan_code <- readChar(fileName, file.info(fileName)$size) mod <- rstan::stan_model(model_code = stan_code, auto_write = T) setwd("/scratch/alexander/distbayesianmc_sparselinear_median/") library(doParallel) registerDoParallel(cores=6) for(dataset in vec_datasets){ for(ssplits in vec_splits){ foreach(i_iter = 1:iters) %dopar% { #for(i_iter in 1:20){ dataset_loaded <- f_dataset_loader(dataset, highcorr = highcorr, nobs = nobs) splitted_data <- f_pack_split_data(dataset_loaded$X, dataset_loaded$y, Pparams = Pparams, ssplits=ssplits, iseed=i_iter, typesplit=typesplit) splitted_data <- f_prep_prior_median(splitted_data, scale = scale) f_stan_sampling_splitted_data_median(mod, splitted_data, dataset = dataset, i_seed = i_iter, iter = i_iter, typesplit = typesplit, nchain = nchain, typeprior=typeprior) } } } } df <- f_combine_const_data_in_frame(vec_splits, vec_datasets, vec_types_splits, 6, type_sim = "stan_median_") #f_plot_res_data_frame(df) f_plot_res_data_frame(df, vec_datasets = vec_datasets) save(df, file="res_sparselinear_ultrasmall_median.Rda") df %<>% mutate(medianlogsubpost = as.numeric(medianlogsubpost)) p1 <- ggplot(df, aes_string(x="splits", y="medianlogsubpost", fill="dataset")) + geom_boxplot() + scale_x_discrete(limits=as.character(sort(as.numeric(levels(df$splits))))) + theme_minimal()
Please feel free to call me at (845)215-5102 or e-mail to discuss any questions you may have and/or to place an order. The standard shipping charge is only $5.00 per order. Regarding privacy issues, rest assured that your personal information will not be shared with anyone. I want you to be happy with your scope. Live with it for awhile, and if you decide you are not satisfied, please contact me within 30 days after receiving it to discuss a refund or exchange as you wish. Thank you.
\documentclass{beamer} \usepackage{epsfig} \usepackage{kotex} \usepackage{graphicx} \usepackage{latexsym} \usepackage{amssymb} \usepackage{amsmath,amscd} \usepackage{multirow} \usepackage{array} \usepackage{caption} \usepackage{rotating} \usepackage{subfig} \usepackage{color} \usepackage{natbib} \usepackage{rotating} \usepackage{graphicx,lscape} \usepackage{amsmath, amsthm, amssymb} \usepackage{graphicx} \usepackage{epsfig} \usepackage{graphics,color, graphicx} \usepackage{latexsym} \usepackage{amssymb,amsmath,amscd} \usepackage{fancyvrb,enumerate} \usepackage{amsmath, amsthm, amssymb} \usepackage{multirow} \usepackage{mathtools} \usepackage{verbatim} \usepackage{afterpage} \usepackage[ruled,vlined]{algorithm2e} \usepackage{hyperref} \usepackage[flushleft]{threeparttable} \DeclarePairedDelimiter\abs{\lvert}{\rvert} \DeclarePairedDelimiter\norm{\lVert}{\rVert} \long\def\comment#1{} %\newtheorem*{thm}{Theorem} \newtheorem{thm}{Theorem}[section] \newtheorem{cor}[thm]{Corollary} \newtheorem{lem}[thm]{Lemma} \newcommand{\rb}[1]{\raisebox{-.5em}[0pt]{#1}} \renewcommand{\baselinestretch}{1.8} \renewcommand{\mid}{\, | \ } \newcommand{\eighth}{{\textstyle \frac{1}{8}}} \def \bY { \mathbf{ Y } } \def \bX { \mathbf{ X } } \def \bU { \mathbf{ U } } \def \bmu { \boldsymbol{ \mu } } \def \bSigma { \boldsymbol{ \Sigma } } \def \bphi { \boldsymbol{ \phi } } \def \bepsilon { \boldsymbol{ \epsilon } } \def \bD { \boldsymbol{\mathcal{D}} } \newcommand{\eqdis}{\overset{\mathrm{d}}{=\joinrel=}} \newcommand{\ba}{\mbox{\boldmath $a$}} \newcommand{\bg}{\mbox{\boldmath $g$}} \newcommand{\bx}{\mbox{\boldmath $x$}} \newcommand{\by}{\mbox{\boldmath $y$}} \newcommand{\bd}{\mbox{\boldmath $d$}} \newcommand{\bff}{\mbox{\boldmath $f$}} \newcommand{\bz}{\mbox{\boldmath $z$}} \newcommand{\bu}{\mbox{\boldmath $u$}} \newcommand{\bv}{\mbox{\boldmath $v$}} \newcommand{\bW}{\mbox{\boldmath $W$}} \newcommand{\bI}{\mbox{\boldmath $I$}} \newcommand{\bJ}{\mbox{\boldmath $J$}} \newcommand{\bL}{\mbox{\boldmath $L$}} \newcommand{\bQ}{\mbox{\boldmath $Q$}} \newcommand{\bZ}{\mbox{\boldmath $Z$}} \newcommand{\bV}{\mbox{\boldmath $V$}} \newcommand{\bG}{\mbox{\boldmath $G$}} \newcommand{\bdm}{\begin{displaymath}} \newcommand{\edm}{\end{displaymath}} \newcommand{\bnu}{\mbox{\boldmath $\nu$}} \newcommand{\btau}{\mbox{\boldmath $\tau$}} \newcommand{\biota}{\mbox{\boldmath $\iota$}} \newcommand{\bbeta}{\mbox{\boldmath $\beta$}} \newcommand{\bomega}{\mbox{\boldmath $\omega$}} \newcommand{\btheta}{\mbox{\boldmath $\theta$}} \newcommand{\bep}{\mbox{\boldmath $\epsilon$}} \newcommand{\bdelta}{\mbox{\boldmath $\delta$}} \newcommand{\balpha}{\mbox{\boldmath $\alpha$}} \newcommand{\bxi}{\mbox{\boldmath $\xi$}} \newcommand{\bgamma}{\mbox{\boldmath $\gamma$}} \newcommand{\bOmega}{\mbox{\boldmath $\Omega$}} \newcommand{\bPi}{\mbox{\boldmath $\Pi$}} \newcommand{\bzeta}{\mbox{\boldmath $\zeta$}} \newcommand{\bpsi}{\mbox{\boldmath $\psi$}} \newcommand{\bPsi}{\mbox{\boldmath $\Psi$}} \newcommand{\bl}{\mbox{\boldmath $l$}} \newcommand{\C}{{\rm Cov}} \newcommand{\bH}{\bold H} \newcommand{\blambda}{\mbox{\boldmath $\lambda$}} \newcommand{\bbh}{\bld h} \usetheme{metropolis} %\usetheme{default} %%\usecolortheme{lily} \usefonttheme[onlymath]{serif} % 수식 설정!! \title{Bootstrap aggregated classification for sparse functional data} %\date{\today} \date[Short Occasion]{July 24, 2020} \author{Hyunsung Kim} \institute[Deptartment of Statistics] {Department of Statistics\\ Chung-Ang University} % A subtitle is optional and this may be deleted %\subtitle{소제목} %\author{F.~Author\inst{1} \and S.~Another\inst{2}} % - Give the names in the same order as the appear in the paper. % - Use the \inst{?} command only if the authors have different % affiliation. %\institute[Universities of Somewhere and Elsewhere] % (optional, but mostly needed) %{ % \inst{1}% % Department of Computer Science\\ % University of Somewhere % \and % \inst{2}% % Department of Theoretical Philosophy\\ % University of Elsewhere} % - Use the \inst command only if there are several affiliations. % - Keep it simple, no one is interested in your street address. %\date{Conference Name, 2013} % - Either use conference name or its abbreviation. % - Not really informative to the audience, more for people (including % yourself) who are reading the slides online \subject{Bootstrap aggregated classification for sparse functional data} % This is only inserted into the PDF information catalog. Can be left % out. % If you have a file called "university-logo-filename.xxx", where xxx % is a graphic format that can be processed by latex or pdflatex, % resp., then you can add a logo as follows: % \pgfdeclareimage[height=0.5cm]{university-logo}{university-logo-filename} % \logo{\pgfuseimage{university-logo}} % Delete this, if you do not want the table of contents to pop up at % the beginning of each subsection: %\AtBeginSubsection[] %{ % \begin{frame}<beamer>{Outline} % \tableofcontents[currentsection,currentsubsection] % \end{frame} %} % Let's get started \begin{document} \begin{frame} \titlepage \end{frame} \begin{frame}{Outline} \setbeamertemplate{section in toc}[circle] % \setbeamertemplate{subsection in toc}[ball unnumbered] \tableofcontents % You might wish to add the option [pausesections] \end{frame} \section{Introduction} \begin{frame}{Introduction} \begin{itemize} \item{ Functional data is collected in the form of curves or functions in various fields such as meteorology and health science, among others and analyzing this is called functional data analysis (FDA). } \item{ Since functional data are defined on infinite dimensions, dimensionality reduction becomes a key issue and one of the powerful method is functional principal component analysis (FPCA) \citep{Silverman1996}. } \item{ In real-data analysis, functional data are commonly observed at sparse or irregular time points, therefore \cite{James2000} and \cite{Yao2005} proposed the FPCA method for sparse functional data with different ideas. } \end{itemize} \end{frame} \begin{frame}{Introduction} \begin{itemize} \item{ Similar to conventional multivariate data analysis, classifying into several groups is also important problem in FDA and there are some related works. } \item{ \cite{Lee2004} presented a support vector machine (SVM) based on FPC scores, and \cite{Rossi2006} proposed a functional SVM (FSVM), extending the SVM for functional data. } \item{ \cite{Song2008} compared classifiers based on FPC scores using linear discriminant analysis (LDA), quadratic discriminant analysis (QDA), a $k$-nearest neighbor (KNN) classifier, and SVM. } \item{ \cite{Gama2004} proposed a functional tree model and bootstrap aggregating (bagging) functional trees. } % \item{ % \cite{James2001} proposed a functional linear discriminant analysis (FLDA) for sparse functional data, implemented using an expectation-maximization (EM) algorithm. % } % \item{ % \cite{James2002} and \cite{Muller2005} extended a generalized linear model to a functional analogue. % } % \item{ % \cite{Leng2006} applied a functional logistic regression based on FPC scores to temporal gene expression data and compared the results with those of the B-spline basis method. % } \end{itemize} \end{frame} \begin{frame}{Introduction} \begin{itemize} \item{ In this study, we propose a new classification method for sparse functional data based on FPCA and bootstrap aggregating. } \item{ Bagging is an ensemble method that enhances predictions by combining the classifiers from the bootstrap samples. } \item{ By extending the bagging to functional data, we construct a bagged classification model, which combines classifiers based on the FPC scores from the bootstrap samples. } \end{itemize} \end{frame} \section{FPCA for sparse functional data}\label{ch2} \begin{frame}{Functional principal component analysis} \begin{itemize} \item{ $\left\{ X(t) : t \in \mathcal{T} \right\}$ : a square integrable random process in $L^2(\mathcal{T})$ \begin{itemize} \item[$\triangleright$]{ $\mu(t) = E\big[X(t)\big], ~~ t \in \mathcal{T}$ } \item[$\triangleright$]{ $G(s,t) = \text{cov}\big[X(s),X(t)\big], ~~ s, t \in \mathcal{T}$ } \end{itemize} } \item{ By Mercer's theorem, the covariance function can be represented as $$G(s,t) = \sum_{k=1}^\infty \lambda_k \phi_k(s) \phi_k(t),$$ where $\lambda_1 \ge \lambda_2 \ge \dots \ge 0 $ are nonnegative eigenvalues satisfying $\sum_{k=1}^\infty \lambda_k < \infty$, and $\phi_k$ is the corresponding orthonormal eigenfunction. } \end{itemize} \end{frame} \begin{frame}{Functional principal component analysis} \begin{itemize} \item{ Given $n$ random curves, $\bX = [ X_1(t) , \ldots, X_n(t) ]$, the Karhunen--Lo\`{e}ve expansion of $X_i(t)$ can be represented as \begin{equation*} X_i(t) = \mu(t) + \sum_{k=1}^\infty \xi_{ik} \phi_k(t), \hspace{0.5cm} t \in \mathcal{T}, \end{equation*} where $\xi_{ik} =\mathlarger{ \int}_{\mathcal{T} } \big( X_i(t) - \mu(t) \big)\phi_k(t) dt $ are uncorrelated variables with mean 0 and variance $\lambda_k$. } \end{itemize} \end{frame} \begin{frame}{Functional principal component analysis} \begin{itemize} \item{ The truncated approximation is written as \begin{equation*} X_i(t) \approx \mu(t) + \sum_{k=1}^K \xi_{ik} \phi_k(t), \hspace{0.5cm} t \in \mathcal{T}, \end{equation*} where $K$ is the number of basis functions. } \item{ $K$ is often selected using the proportion of variance explained (PVE), but the Akaike information criterion (AIC) or Bayesian information criterion (BIC) can also be used for consistency \citep{Yao2005,Li2013}. } \end{itemize} \end{frame} \begin{frame}{FPCA for sparse functional data} \begin{itemize} \item{ When each curve is observed at sparse or irregular time points, we cannot apply a conventional FPCA directly to the data. } \item{ Especially, the covariance function cannot be computed easily and the estimated FPC scores are biased. } \item{ \cite{James2000} proposed a reduced-rank model based on the mixed-effects model and estimated the FPC function and scores using an EM algorithm. } \item{ \cite{Yao2005} proposed the principal component analysis through the conditional expectation (PACE) method to obtain unbiased FPC scores. } \item{ Here, we consider PACE method. } \end{itemize} \end{frame} \begin{frame}{FPCA for sparse functional data by PACE} \begin{itemize} \item{ Consider an $i$th curve $\bX_i = \big( X_i(t_{i1}), \dots, X_i(t_{in_i}) \big)^T$ with the mean function $\bmu_i = \big( \mu(t_{i1}), \dots, \mu(t_{in_i}) \big)^T$. } \item{ Here, $t_{ij} \in \mathcal{T}$ is the $j$th time point observed in the $i$th curve $X_i$, for $i = 1, 2, \dots, n$, $j = 1, 2, \dots, n_i$. } \item{ Let $\bU_i = \big( U_i(t_{i1}), \dots, U_i(t_{in_i}) \big)^T$ be an observed $i$th curve with additional measurement errors, $\bepsilon_i = \big( \epsilon_i(t_{i1}), \dots, \epsilon_i(t_{in_i}) \big)^T$. } \end{itemize} \end{frame} \begin{frame}{FPCA for sparse functional data by PACE} \begin{itemize} \item{ Then, we have \begin{eqnarray*} %\bY_i = \bmu_i + \sum_{k=1}^\infty \xi_{ik} \bphi_{ik} + \bepsilon_i. U_i(t_{ij})& =&X_i(t_{ij}) + \epsilon_i(t_{ij})\\ & =& \mu(t_{ij}) + \sum_{k=1}^\infty \xi_{ik} \phi_k(t_{ij}) + \epsilon_i(t_{ij}), \hspace{0.5cm} t_{ij} \in \mathcal{T}, \end{eqnarray*} where $\epsilon_i(t_{ij})$ is an $i.i.d.$ error with mean zero and variance $\sigma^2$ and is assumed to be independent of $\xi_{ik}$, for $i = 1, 2, \dots, n$, $j = 1, 2, \dots, n_i$, $k=1, 2, \ldots $. } \end{itemize} \end{frame} \begin{frame}{FPCA for sparse functional data by PACE} \begin{itemize} \item{ Under the assumption that $\xi_{ik}$ and $\epsilon_i$ are jointly Gaussian, the best linear unbiased prediction (BLUP) of $\xi_{ik}$ is computed as \begin{equation*} \tilde \xi_{ik} = E[\xi_{ik} \vert \bU_i] = \lambda_k \bphi_{ik}^T\bSigma_{\bU_i}^{-1}(\bU_i - \bmu_i), \end{equation*} where $\bphi_{ik} = \big( \phi_k(t_{i1}), \dots, \phi_k(t_{in_i}) \big)^T$ is the $i$th FPC function, and $\bSigma_{\bU_i} = \text{cov}(\bU_i, \bU_i) = \text{cov}(\bX_i, \bX_i) + \sigma^2\mathbf{I}_{n_i}$. } \end{itemize} \end{frame} \begin{frame}{FPCA for sparse functional data by PACE} \begin{itemize} \item{ \cite{Yao2005} considered the following prediction for the trajectory $X_i(t)$ using the first $K$ eigenfunctions: \begin{eqnarray*} \hat X_i(t) =\hat \mu(t) + \sum_{k=1}^K \hat\xi_{ik} \hat \phi_k(t) , \end{eqnarray*} where $\hat \mu(t)$, $\hat\xi_{ik}$, and $\hat \phi_k(t) $ are estimations obtained from the entire data sample. } \end{itemize} \end{frame} \section{Ensemble classification via FPCA} \begin{frame}{Classification with functional predictors} \begin{itemize} \item{ To perform the classification for functional data, we consider the functional generalized linear model (FGLM) \citep{James2002, Muller2005}. } \item{ Given the $i$th functional curve $X_i(t)$ and the corresponding response $y_i$, the FGLM can be represented as \begin{eqnarray} g(\mu) &= \alpha + \mathlarger{\int}_{\mathcal{T}} \beta(t) X_i(t) dt , \label{fglm} \end{eqnarray} where $\mu = E(y_i | X_i)$, and $g(\cdot)$ is a link function. } \item{ Because we can only observe $X_i(t)$ at a finite time points $n_i$, the integral can be substituted by a summation. } \end{itemize} \end{frame} \begin{frame}{Classification with functional predictors} \begin{itemize} \item{ The estimate of the coefficient $\beta(\cdot)$ may be unstable because it is an extremely high-dimensional vector. } \item{ We can solve this problem by expanding $\beta(\cdot)$ using a set of basis functions. } \item{ By employing an FPCA, we can use data-driven orthonormal basis functions to represent $\beta(\cdot)$. } \end{itemize} \end{frame} \begin{frame}{Classification based on FPC scores} \begin{itemize} \item{ Let $\phi_k(t)$, for $k=1, 2, \ldots$, be an orthonormal basis function, and expand $X_i(t)$ and $\beta(t)$ as $$X_i(t) = \sum_{k=1}^K \xi_{ik} \phi_k(t), ~~~ \beta(t) = \sum_{k=1}^K \beta_k \phi_k(t)$$ using the $K$-truncated FPCA model described in Section \ref{ch2}. } \item{ Then, the FGLM in \eqref{fglm} is represented as \begin{equation*} g(\mu) = \alpha + \sum_{k=1}^K \beta_k \xi_{ik}. \end{equation*} } \item{ The estimation is stable because most of the variation can be expressed using a small number, $K$. } \end{itemize} \end{frame} \begin{frame}{Bootstrap aggregated functional classifier via sparse FPCA} \begin{block}{Bagging} \begin{itemize} \item{ Bootstrap aggregating (Bagging) is a popular ensemble method that uses the bootstrap idea proposed by \cite{Breiman1996}. } \item{ It extracts several samples with replacement and obtains the prediction by aggregating models from each bootstrap sample. } \end{itemize} \end{block} \end{frame} \begin{frame}{Bootstrap aggregated functional classifier via sparse FPCA} \begin{block}{Notations} \begin{itemize} \item{ $\bD = \left\{ \left( \bU_i, y_i \right) : i=1, \dots, n \right\}$ : the set of sparse $n$ curves with $\bU_i = \big( U_i(t_{i1}), \dots, U_i(t_{in_i}) \big)^T$. } \item{ $y_i \in \{1, \ldots, g\}$ : the response class label. \\ (Here, we assume $g=2$) } \item{ $\bD^{(b)} = \left\{ \left( \bU^{(b)}_i, y^{(b)}_i \right) : i=1, \dots, n \right\}$, for $b=1,\dots,B$ : a bootstrap resample from $\bD$. } \end{itemize} \end{block} \end{frame} \begin{frame}{Bootstrap aggregated functional classifier via sparse FPCA} \begin{block}{Algorithm} \begin{enumerate} \item For $b = 1, \dots, B$, repeat \begin{enumerate}[(a)] \item Generate a bootstrap resample $\bD^{(b)}$ from the data $\bD$. \item Perform FPCA for $\bD^{(b)}$. \item Estimate the FPC scores by PACE and chose $K$ FPCs. \item Construct a classifier using $K$ FPC scores. \end{enumerate} \item Given a new curve $\bU^*(t)$, \begin{enumerate}[(a)] \item Estimate the FPC scores by PACE from $\bD^{(b)}$, for $b = 1, \dots, B$. \item Obtain the prediction $\hat f^{(b)}$ from the $b$th classifier constructed in step 1-(d), for $b = 1, \dots, B$. \end{enumerate} \item Obtain the final prediction $\hat y_{bag}$ aggregated from $\hat f^{(1)}, \dots, \hat f^{(B)}$. \end{enumerate} \end{block} \end{frame} \begin{frame}{Aggregating methods} \begin{block}{Majority vote} \begin{itemize} \item{ The majority vote simply chooses the class that receives the highest total vote from all classifiers. } \item{ The bagged classifier by the majority vote is \begin{equation*} \hat y_{\text{bag}} = \arg\max_{ j \in \{1,2\} } \frac{ \sum_{b=1}^B \mathbf I \big\{ \hat f^{(b)}(x) = j \big\} }{B}, \end{equation*} where $\mathbf I$ is the indicator function. } \end{itemize} \end{block} \end{frame} \begin{frame}{Aggregating methods} \begin{block}{Out-of-bag (OOB) error weighted vote \citep{Pham2018}} \begin{itemize} \item{ Let $e_b$, for $b=1, \dots, B$, be the OOB errors from $B$ bootstrapped models. } \item{ By defining the weight as $w_b = 1/e_b$, the models that exhibit good performance receive higher weights. } \item{ If $e_b = 0$, which means there are no errors from the OOB samples, we set $e_b = \min \{ e_1, \dots, e_{b-1}, e_{b+1}, \dots, e_B \}$. } \item{ The bagged classifier using the OOB error weighted vote is \begin{equation*} \hat y_{\text{bag}} = \frac{\sum_{b=1}^B w_b \hat f^{(b)}(x)}{\sum_{b=1}^B w_b}. \end{equation*} } \end{itemize} \end{block} \end{frame} \section{Simulation studies} \begin{frame}{Simulation 1} \begin{itemize} \item{ We generate $N=200$ curves with two classes as $$U_{gi}(t_{ij} ) = \mu_g(t_{ij} ) + \sum_{k=1}^3 \xi_{gk} \phi_k(t_{ij} ) + \epsilon_i(t_{ij} ),~~i=1, \ldots , 100, ~j=1, \ldots, n_{ij},$$ where $g \in \{ 0, 1\}$ indicates a group label. } \item{ The FPC functions are defined as \begin{eqnarray} \phi_k(t)= \begin{cases} \cos(\pi kt /5) / \sqrt{5},~~ ~ k ~~\text{is odds}\\ \sin(\pi kt /5) / \sqrt{5},~~ ~ k ~~\text{is even,} \end{cases}\label{sim1} \end{eqnarray} } \item{ The FPC scores $\xi_{gk}$ are sampled from $i.i.d. \ N(0, \lambda_{gk})$, for $k=1,2,3$. } \item{ The measurement error $\epsilon_i(t)$ is sampled from $i.i.d. \ N(0, 0.5^2)$. } \end{itemize} \end{frame} \begin{frame}{Simulation 1} \begin{table}[h!] \footnotesize \centering \caption{[Simulation 1] The parameters for three models.}\label{t1} \tabcolsep=11.5pt \begin{tabular}{lccc} \hline Model & $g$ & $\mu_g(t)$ & $ (\lambda_{g1} ,\lambda_{g2},\lambda_{g3}) $ \\ \hline \multirow{2}{*}{(A) Different means and variances} & 0 & $t + \sin(t)$ & $(4, 2, 1)$ \\ & 1 & $t + \cos(t)$ & $(16, 8, 4)$ \\ \hline \multirow{2}{*}{(B) Different means } & 0 & $t + \sin(t)$ & $(4, 2, 1)$ \\ & 1 & $t + \cos(t)$ & $(4, 2, 1)$ \\ \hline \multirow{2}{*}{(C) Different variances} & 0 & $t + \sin(t)$ & $(4, 2, 1)$ \\ & 1 & $t + \sin(t)$ & $(16, 8, 4)$ \\ \hline \end{tabular} \end{table} \end{frame} \begin{frame}{Simulation 1} \begin{itemize} \item{ To make each curve sparse, the number of observations for the $i$th curve, $n_i$, is randomly selected from $\{5, 6, \ldots, 10\}$, and the corresponding time points $t_{ij}$, for $j=1, \dots, n_i$, are selected from $i.i.d. \ Uniform(0, 10)$. } \item{ For validation, we randomly split the generated data into a training and a test set, with 100 elements in each. } \item{ We compare the results of the proposed method with those of six single functional classification models: logistic regression, SVM with linear kernel, SVM with gaussian kernel, LDA, QDA, and naive Bayes. } \end{itemize} \end{frame} \begin{frame}{Simulation 1} \begin{table}[h!] \footnotesize \centering \caption{The average classification errors (\%) and standard errors (in parentheses) from 100 Monte Carlo repetitions for three designs of simulation 1.}\label{t2} \tabcolsep=5pt \tiny \begin{tabular}{cccccccc} \hline\hline & & Logistic & SVM & SVM & \multirow{2}{*}{LDA} & \multirow{2}{*}{QDA} & Naive \\ Model & Method & Regression & (Linear) & (Gaussian) & & & Bayes \\ \hline \multirow{3}{*}{(A)} & Single & 17.13 (4.86) & 17.03 (5.22) & 14.86 (5.26) & 16.38 (4.93) & 14.94 (5.20) & 16.12 (4.64) \\ & Majority vote & 14.98 (4.15) & 15.24 (4.29) & 12.81 (4.50) & 15.03 (4.11) & 13.55 (4.47) & 14.98 (4.21) \\ & OOB weight & 14.80 (3.95) & 14.83 (4.10) & \textbf{12.56 (4.33)} & 14.83 (4.00) & 13.02 (4.16) & 14.39 (4.02) \\ \hline \multirow{3}{*}{(B)} & Single & 11.42 (3.44) & 10.89 (3.47) & 11.60 (3.99) & 10.71 (3.48) & 12.19 (3.50) & 13.56 (4.23) \\ & Majority vote & 10.24 (3.24) & 10.14 (3.21) & 10.68 (3.57) & 10.04 (3.12) & 11.16 (3.33) & 12.06 (3.35) \\ & OOB weight & 10.30 (3.23) & \textbf{9.97 (3.18)} & 10.52 (3.41) & 10.04 (3.10) & 11.03 (3.30) & 11.82 (3.31) \\ \hline \multirow{3}{*}{(C)} & Single & 50.43 (5.72) & 49.38 (5.60) & 32.48 (4.89) & 50.46 (5.73) & 30.90 (4.45) & 30.31 (4.51) \\ & Majority vote & 49.62 (5.63) & 48.41 (6.16) & 31.11 (5.26) & 49.49 (5.70) & 30.70 (4.26) & 29.70 (4.42) \\ & OOB weight & 49.19 (5.78) & 48.20 (6.21) & 30.99 (5.32) & 49.01 (5.75) & 30.57 (4.18) & \textbf{29.59 (4.34)} \\ \hline\hline \end{tabular} \begin{tablenotes} \item[1] * The minimum error rate is marked in bold. \end{tablenotes} \end{table} \end{frame} \begin{frame}{Simulation 2} \begin{itemize} \item{ Simulation 2 is motivated by \cite{Yao2016}. } \item{ We generate $n=700$ curves as $$U_{i}(t) = \sum_{k=1}^{50} \xi_{ik} \phi_k(t) + \epsilon_i(t),~~i=1, \ldots , n.$$ } \item{ The FPC functions are generated as in \eqref{sim1}, and the FPC scores, $\xi_{ik}$, are sampled from $i.i.d. \ N(0, k^{-3/2})$, for $k=1, \ldots, 50$. } \item{ For the sparsity of the data, the number of observations for the $i$th curve, $n_i$, is randomly selected from $\{10, 11, \ldots, 20\}$, and the corresponding time points $t_{ij}$, for $j=1, \dots, n_i$, are selected from $i.i.d. \ Uniform(0, 10)$. } \item{ The measurement error $\epsilon_i(t)$ is sampled from $i.i.d. \ N(0, 0.1)$. } \end{itemize} \end{frame} \begin{frame}{Simulation 2} \begin{itemize} \item{ Now, we consider the following three models: \begin{align*} \text{(A)~~~} & f(U_i) = \exp(\langle \beta_1, U_i \rangle / 2) - 1, \\ \text{(B)~~~} &f(U_i) = \arctan(\pi \langle \beta_1, U_i \rangle) + \exp(\langle \beta_2, U_i \rangle / 3) - 1, \\ \text{(C)~~~} &f(U_i) = \arctan(\pi \langle \beta_1, U_i \rangle / 4), \end{align*} where $\langle f, g \rangle = \mathlarger{\int}_{\mathcal{T}} f(t) g(t) dt $ for $f, g \in L^2(\mathcal{T})$. } \item{ Here, $\beta_1(t) = \sum_{k=1}^{50} b_k \phi_k(t)$, where $b_k=1$ for $k=1,2$, $b_k=(k-2)^{-3}$ for $k=3, \ldots, 50$, and $\beta_2(t) = \sqrt{3/10}(t/5-1)$. } \end{itemize} \end{frame} \begin{frame}{Simulation 2} \begin{itemize} \item{ The class label for each curve, $U_i$, is defined as $y_i = \text{sign} \{ f(U_i) + \epsilon_i \}$, where $\epsilon_i \sim~i.i.d. \ N(0, 0.1).$ } \item{ We randomly split the generated data into 200 training curves and 500 test curves and compare the results of the proposed methods with those of the single classification models. } \end{itemize} \end{frame} \begin{frame}{Simulation 2} \begin{table}[ht] \footnotesize \centering \caption{The average classification errors (\%) and standard errors (in parentheses) from 100 Monte Carlo repetitions for three models in simulation 2.}\label{t3} \tabcolsep=5pt \tiny \begin{tabular}{cccccccc} \hline\hline & & Logistic & SVM & SVM & \multirow{2}{*}{LDA} & \multirow{2}{*}{QDA} & Naive \\ Model & Method & Regression & (Linear) & (Gaussian) & & & Bayes \\ \hline \multirow{3}{*}{A} & Single & 16.71 (2.33) & 16.82 (2.20) & 17.50 (2.76) & 16.62 (2.30) & 17.77 (2.56) & 18.41 (2.66) \\ & Majority vote & 15.62 (1.95) & 15.86 (1.87) & 16.19 (2.28) & 15.79 (1.96) & 16.51 (2.14) & 17.32 (2.42) \\ & OOB weight & \textbf{15.54 (1.93)} & 15.78 (1.83) & 16.17 (2.27) & 15.73 (1.89) & 16.43 (2.10) & 17.21 (2.40) \\ \hline \multirow{3}{*}{B} & Single & 12.85 (2.41) & 12.79 (2.40) & 13.27 (2.65) & 12.77 (2.40) & 13.83 (2.56) & 14.77 (2.74) \\ & Majority vote & 11.20 (1.84) & 11.14 (1.89) & 11.54 (1.98) & 11.19 (1.85) & 11.93 (2.03) & 13.29 (2.36) \\ & OOB weight & 11.11 (1.87) & \textbf{11.00 (1.81)} & 11.46 (1.94) & 11.11 (1.85) & 11.83 (2.00) & 13.08 (2.35) \\ \hline \multirow{3}{*}{C} & Single & 14.46 (2.17) & 14.34 (2.18) & 15.27 (2.69) & 14.29 (2.17) & 15.32 (2.36) & 16.05 (2.22) \\ & Majority vote & 13.15 (1.73) & 13.14 (1.78) & 13.62 (2.08) & 13.14 (1.82) & 13.78 (1.90) & 14.88 (2.09) \\ & OOB weight & 13.11 (1.77) & \textbf{13.06 (1.77)} & 13.54 (2.02) & 13.09 (1.80) & 13.74 (1.89) & 14.72 (2.08) \\ \hline\hline \end{tabular} \begin{tablenotes} \item[1] * The minimum error rate is marked in bold. \end{tablenotes} \end{table} \end{frame} \section{Real-data analysis} \begin{frame}{Real-data analysis - Berkely growth data} \begin{itemize} \item{ The Berkely growth data set \citep{Tuddenham1954} includes heights for 93 individuals (54 girls and 39 boys). } \item{ There are 31 observations from ages 1 to 18 for each curve. } \end{itemize} \begin{figure}[h] \centering \includegraphics[height=4cm,keepaspectratio=true]{img/growth.eps} \caption{The Berkely growth data of 93 individuals.} \label{fig1} \end{figure} \end{frame} \begin{frame}{Real-data analysis - Berkely growth data} \begin{itemize} \item{ For sparseness, we artificially sparsify the data. } \item{ The number of observations for each individual is randomly selected from $\{12,13, \ldots, 15\}$, and the corresponding time points are randomly selected from the original time points. } \item{ For validation, we randomly divide the 93 curves into 62 training and 31 test curves. } \item{ We repeat this process 100 times with different splits. } \end{itemize} \end{frame} \begin{frame}{Real-data analysis - Berkely growth data} \begin{table}[ht] \footnotesize \centering \caption{The average classification errors (\%) and standard errors (in parentheses) from 100 random splits of the Berkerly growth data.}\label{t4} \tabcolsep=6.5pt \tiny \begin{tabular}{ccccccc} \hline \hline & Logistic & SVM & SVM & \multirow{2}{*}{LDA} & \multirow{2}{*}{QDA} & Naive \\ Method & Regression & (Linear) & (Gaussian) & & & Bayes \\ \hline Single & 7.26 (4.80) & 5.26 (3.20) & 5.68 (4.03) & 5.81 (3.34) & 5.65 (3.35) & 5.65 (3.90) \\ Majority vote & 5.94 (4.12) & 4.90 (3.19) & 5.26 (3.51) & 5.39 (3.24) & 4.87 (3.57) & 5.45 (3.96) \\ OOB weight & 6.06 (4.36) & 5.13 (3.11) & 5.32 (3.68) & 5.42 (3.24) & \textbf{4.87 (3.42)} & 5.39 (3.97) \\ \hline \hline \end{tabular} \end{table} \end{frame} \begin{frame}{Real-data analysis - Spinal bone mineral density data} \begin{figure}[h] \centering \includegraphics[height=4cm,keepaspectratio=true]{img/spnbmd.eps} \caption{The spinal bone mineral density of 280 individuals.} \label{fig2} \end{figure} \end{frame} \begin{frame}{Real-data analysis - Spinal bone mineral density data} \begin{itemize} \item{ The spinal bone mineral density data \citep{Bachrach1999} contains spinal bone mineral densities for 280 individuals (153 females and 127 males). } \item{ Each curve was measured at sparse and irregular time points with 2 to 4 observations. } \item{ The data are randomly divided into 187 training and 93 test sets. } \item{ we apply the methods to 100 different splits of the data. } \end{itemize} \end{frame} \begin{frame}{Real-data analysis - Spinal bone mineral density data} \begin{table}[ht] \footnotesize \centering \caption{The average classification errors (\%) and standard errors (in parentheses) from 100 random splits of the spinal bone mineral density data}\label{t5} \tabcolsep=5pt \tiny \begin{tabular}{ccccccc} \hline \hline & Logistic & SVM & SVM & \multirow{2}{*}{LDA} & \multirow{2}{*}{QDA} & Naive \\ Method & Regression & (Linear) & (Gaussian) & & & Bayes \\ \hline Single & 32.20 (4.15) & 32.22 (4.21) & 32.64 (4.05) & 31.90 (4.22) & 34.21 (4.25) & 32.58 (4.02) \\ Majority vote & \textbf{31.12 (4.25)} & 31.39 (4.27) & 31.50 (4.56) & 31.16 (4.15) & 32.34 (3.90) & 31.29 (3.88) \\ OOB weight & 31.19 (4.15) & 31.45 (4.23) & 31.57 (4.44) & 31.28 (4.12) & 32.32 (3.95) & 31.27 (3.87) \\ \hline \hline \end{tabular} \end{table} \end{frame} \section{Conclusion and discussion} \begin{frame}{Conclusion and discussion} \begin{itemize} \item{ In this study, we propose a new ensemble classification method for sparse functional data, which is a bagged model that combines classifiers based on FPC scores. } \item{ To obtain FPC scores for sparse functinal data, we perform FPCA by PACE method. % Since observed curves are often sparse in real-data analyses, we use FPC scores estimated using the PACE method. } \item{ We consider two aggregating methods, a majority vote and an OOB weighted vote, and find that both methods outperform the single classifiers. } \item{ The results of several simulations confirm that the proposed classification model outperforms single classifiers in various situations. } \item{ In two real-data analyses, the proposed model shows better performance than the single model. % Here, we also apply the proposed method to real data. } \end{itemize} \end{frame} \begin{frame}{Conclusion and discussion} \begin{itemize} \item{ The proposed method can be easily extended to multi-class classification problems, in which we expect the aggregating method to outperform single classifiers. } \item{ In addition, other ensemble methods such as boosting and stacking can be used \citep{Opitz1999}. } \end{itemize} \end{frame} \section*{Reference} \begin{frame}[allowframebreaks] \frametitle<presentation>{Reference} \renewcommand{\section}[2]{} % delete "References" section title \begin{thebibliography}{9} \footnotesize \bibitem[{Bachrach et~al.(1999)}]{Bachrach1999} Bachrach, L. K., Hastie, T., Wang, M. C., Narasimhan, B., \& Marcus, R. (1999). Bone mineral acquisition in healthy Asian, Hispanic, black, and Caucasian youth: a longitudinal study. {\em The journal of clinical endocrinology \& metabolism}, {\bf 84}, 4702-4712. \bibitem[{Breiman(1996)}]{Breiman1996} Breiman, L. (1996). Bagging predictors. {\em Machine learning}, {\bf 24}, 123-140. \bibitem[{Breiman(1996)}]{Breiman1996b} Breiman, L. (1996). Out-of-bag estimation. Technical report, Statistics Dept., University of California at Berkeley, CA. \bibitem[{Ferraty and Vieu(2003)}]{Ferraty2003} Ferraty, F., \& Vieu, P. (2003). Curves discrimination: a nonparametric functional approach. {\em Computational Statistics \& Data Analysis}, {\bf 44}, 161-173. \bibitem[{Friedman et~al.(2001)}]{Friedman2001} Friedman, J., Hastie, T., \& Tibshirani, R. (2001). {\em The elements of statistical learning.}, Springer series in statistics, New York. \bibitem[{Gama(2004)}]{Gama2004} Gama, J. (2004). Functional trees. {\em Machine Learning}, {\bf 55}, 219-250. \bibitem[{Hall and Hosseini‐Nasab(2006)}]{Hall2006} Hall, P., \& Hosseini‐Nasab, M. (2006). On properties of functional principal components analysis. {\em Journal of the Royal Statistical Society: Series B (Statistical Methodology)}, {\bf 68}, 109-126. \bibitem[{James et~al.(2000)}]{James2000} James, G. M., Hastie, T. J., \& Sugar, C. A. (2000). Principal component models for sparse functional data. {\em Biometrika}, {\bf 87}, 587-602. \bibitem[{James and Hastie(2001)}]{James2001} James, G. M., \& Hastie, T. J. (2001). Functional linear discriminant analysis for irregularly sampled curves. {\em Journal of the Royal Statistical Society: Series B (Statistical Methodology)}, {\bf 63}, 533-550. \bibitem[{James(2002)}]{James2002} James, G. M. (2002). Generalized linear models with functional predictors. {\em Journal of the Royal Statistical Society: Series B (Statistical Methodology)}, {\bf 64}, 411-432. \bibitem[{Lee(2004)}]{Lee2004} Lee, H. J. (2004). Functional data analysis: classification and regression. Ph. D. Dissertation, Texas A\&M University. \bibitem[{Leng and Müller(2006)}]{Leng2006} Leng, X., \& Müller, H. G. (2006). Classification using functional data analysis for temporal gene expression data. {\em Bioinformatics}, {\bf 22}, 68-76. \bibitem[{Li et~al.(2013)}]{Li2013} Li, Y., Wang, N., \& Carroll, R. J. (2013). Selecting the number of principal components in functional data. {\em Journal of the American Statistical Association}, {\bf 108}, 1284-1294. \bibitem[{Müller(2005)}]{Muller2005a} Müller, H. G. (2005). Functional modelling and classification of longitudinal data. {\em Scandinavian Journal of Statistics}, {\bf 32}, 223-240. \bibitem[{Müller and Stadtmüller(2005)}]{Muller2005} Müller, H. G., \& Stadtmüller, U. (2005). Generalized functional linear models. {\em the Annals of Statistics}, {\bf 33}, 774-805. \bibitem[{Opitz and Maclin(1999)}]{Opitz1999} Opitz, D., \& Maclin, R. (1999). Popular ensemble methods: An empirical study. {\em Journal of artificial intelligence research}, {\bf 11}, 169-198. \bibitem[{Pham(2018)}]{Pham2018} Pham, H. T. (2018). Generalized weighting for bagged ensembles. Ph. D. Dissertation, Iowa State University. \bibitem[{Ramsay and Silverman(2005)}]{Ramsay2005} Ramsay, J. O., \& Silverman, B. W. (2005) {\em Functional Data Analysis}, 2nd ed., Springer Series in Statistics, New York. \bibitem[{Rossi and Villa(2006)}]{Rossi2006} Rossi, F., \& Villa, N. (2006). Support vector machine for functional data classification. {\em Neurocomputing}, {\bf 69}, 730-742. \bibitem[{Silverman(1996)}]{Silverman1996} Silverman, B. W. (1996). Smoothed functional principal components analysis by choice of norm. {\em The Annals of Statistics}, {\bf 24}, 1-24. \bibitem[{Song et~al.(2008)}]{Song2008} Song, J. J., Deng, W., Lee, H. J., \& Kwon, D. (2008). Optimal classification for time-course gene expression data using functional data analysis. {\em Computational biology and chemistry}, {\bf 32}, 426-432. \bibitem[{Tuddenham and Snyder(1954)}]{Tuddenham1954} Tuddenham, R. D., \& Snyder, M. M. (1954). Physical growth of California boys and girls from birth to eighteen years. {\em University of California publications in child development}, {\bf 1}, 183-364. \bibitem[{Yao et~al.(2005)}]{Yao2005} Yao, F., Müller, H. G., \& Wang, J. L. (2005). Functional data analysis for sparse longitudinal data. {\em Journal of the American Statistical Association}, {\bf 100}, 577-590. \bibitem[{Yao et~al.(2016)}]{Yao2016} Yao, F., Wu, Y., \& Zou, J. (2016). Probability-enhanced effective dimension reduction for classifying sparse functional data. {\em Test}, {\bf 25}, 1-22. \end{thebibliography} \end{frame} \begin{frame} \begin{center} \huge \textbf{Thank You!} \end{center} \end{frame} \end{document}
(* -----------------Description------------------------------------------------------ This file contains basic definitions of Bids, Asks and Fill (trade between Bid and Ask). These data types are also attached with eqType (i.e, domain with decidable Equality). We also define projection functions on list of Bids and Asks. Terms <==> Explanations Bid Type for a buy request Ask Type for an sell request fill_type Type for trade output bid_prices B projection of bid prices in B ask_prices A projection of ask prices in A bids_of F projection of bids in F asks_of F projection of asks in F Some important results: Lemma included_M_imp_included_bids : included M1 M2 -> included (bids_of M1) (bids_of M2). Lemma bids_of_perm: perm M M' -> perm (bids_of M) (bids_of M'). Lemma included_M_imp_included_asks : included M1 M2 -> included (asks_of M1) (asks_of M2). Lemma asks_of_perm: perm M M' -> perm (asks_of M) (asks_of M'). Lemma included_M_imp_included_tps: included M M'->included(trade_prices_of M)(trade_prices_of M'). Lemma tps_of_perm : perm M M' -> perm (trade_prices_of M) (trade_prices_of M'). ---------------------------------------------------------------------------------------- *) Require Import ssreflect ssrbool. Require Export Lists.List. Require Export GenReflect SetSpecs. Require Export DecList DecType MoreDecList. Section BidAsk. Record Bid:Type:= Mk_bid{ bp:> nat; idb: nat}. Definition b_eqb (x y:Bid): bool:= (idb x == idb y) && ( bp x == bp y). Record Ask:Type:= Mk_ask{ sp:>nat; ida: nat;}. Definition a_eqb (x y: Ask): bool:= (ida x == ida y) && ( sp x == sp y). (* Hypothesis unique_idb : forall b1 b2:Bid, (idb(b1) = idb(b2))-> (b1 = b2). Hypothesis unique_ida : forall a1 a2:Ask, (ida(a1) = ida(a2))-> (a1 = a2). *) (*---------------- Attaching Bid to the EqType ----------------------------------*) Lemma b_eqb_ref (x:Bid): b_eqb x x = true. Proof. unfold b_eqb. split_; apply /eqP;auto. Qed. Hint Resolve b_eqb_ref: auction. Lemma b_eqb_elim (x y:Bid): b_eqb x y -> x = y. Proof. { unfold b_eqb. move /andP. intro H. destruct H as [H1 H2]. destruct x; destruct y. move /eqP in H1. auto. } Qed. Lemma b_eqb_intro (x y:Bid): x=y -> b_eqb x y = true. Proof. { unfold b_eqb. intros H. apply /andP. split. apply /eqP. subst x. auto. apply /eqP. inversion H. auto. } Qed. Hint Immediate b_eqb_elim b_eqb_intro: auction. Lemma b_eqP (x y:Bid): reflect (x=y)(b_eqb x y). Proof. apply reflect_intro. split; auto with auction. Qed. Hint Resolve b_eqP: auction. Canonical bid_eqType: eqType:= {| Decidable.E:= Bid; Decidable.eqb:= b_eqb; Decidable.eqP:= b_eqP |}. (*------------------ Attaching Ask to EqType ------------------------------------ *) Lemma a_eqb_ref (x: Ask): a_eqb x x = true. Proof. { unfold a_eqb. apply /andP. split. apply /eqP. auto. apply /eqP. auto. } Qed. Hint Resolve a_eqb_ref: auction. Lemma a_eqb_elim (x y: Ask): a_eqb x y -> x = y. Proof. { unfold a_eqb. move /andP. intro H. destruct H as [H1 H2]. destruct x; destruct y. move /eqP in H1. auto. } Qed. Lemma a_eqb_intro (x y: Ask): x=y -> a_eqb x y = true. Proof. { unfold a_eqb. intros H. apply /andP. split. apply /eqP. subst x. auto. apply /eqP. inversion H. auto. } Qed. Hint Immediate a_eqb_elim a_eqb_intro: auction. Lemma a_eqP (x y: Ask): reflect (x=y)(a_eqb x y). Proof. apply reflect_intro. split; auto with auction. Qed. Hint Resolve a_eqP: auction. Canonical ask_eqType: eqType:= {| Decidable.E:= Ask; Decidable.eqb:= a_eqb; Decidable.eqP:= a_eqP |}. (*------------- Price projections for list of Bids and Asks--------------------------*) Fixpoint bid_prices (B: list Bid): (list nat):= match B with |nil => nil |b::B' => (bp b)::(bid_prices B') end. Lemma bid_prices_intro (B: list Bid) (b: Bid): In b B -> (In (bp b) (bid_prices B)). Proof. { intro H. induction B. simpl. simpl in H. contradiction. destruct H. subst b. simpl. left. auto. simpl. right. auto. } Qed. Lemma bid_prices_elim (B: list Bid): forall p, In p (bid_prices B)-> exists b, In b B /\ p = bp b. Proof. { intros p H. induction B. simpl in H. contradiction. simpl in H. destruct H as [H1 | H2]. exists a. split; auto. apply IHB in H2 as H0. destruct H0 as [b H0]. exists b. destruct H0. split. eauto. auto. } Qed. Lemma bid_prices_intro1 (B: list Bid) (B': list Bid): B [<=] B' -> ((bid_prices B) [<=] (bid_prices B')). Proof. { intro H. intros p. intro H1. assert (H2: exists b, In b B /\ p=bp b). apply bid_prices_elim. exact. destruct H2. destruct H0. assert (H3: In x B'). auto. subst p. eapply bid_prices_intro. exact. } Qed. Fixpoint ask_prices (A: list Ask): (list nat):= match A with |nil => nil |a::A' => (sp a)::(ask_prices A') end. Lemma ask_prices_intro (A: list Ask) (a: Ask): In a A -> (In (sp a) (ask_prices A)). Proof. { intro H. induction A. simpl. simpl in H. contradiction. destruct H. subst a. simpl. left. auto. simpl. right. auto. } Qed. Lemma ask_prices_elim (A: list Ask): forall p, In p (ask_prices A)-> exists a, In a A /\ p = sp a. Proof. { intros p H. induction A. simpl in H. contradiction. simpl in H. destruct H as [H1 | H2]. exists a. split; auto. apply IHA in H2 as H0. destruct H0 as [a0 H0]. exists a0. destruct H0. split. eauto. auto. } Qed. Lemma ask_prices_intro1 (A: list Ask) (A': list Ask): A [<=] A' -> ((ask_prices A) [<=] (ask_prices A')). Proof. { intro H. intros p. intro H1. assert (H2: exists a, In a A /\ p=sp a). apply ask_prices_elim. exact. destruct H2. destruct H0. assert (H3: In x A'). eauto. subst p. eapply ask_prices_intro. exact. } Qed. Hint Resolve bid_prices_elim bid_prices_intro bid_prices_intro1: core. Hint Resolve ask_prices_elim ask_prices_intro ask_prices_intro1: core. (* ------------definition of fill_type as record---------------------------- *) Record fill_type:Type:= Mk_fill { bid_of: Bid; ask_of: Ask; tp: nat }. Definition m_eqb (x y: fill_type): bool:= (bid_of x == bid_of y) && ( ask_of x == ask_of y) && (tp x == tp y). (*------------------ Attaching fill_type to eqType ------------------------------------ *) Lemma m_eqb_ref (x: fill_type): m_eqb x x = true. Proof. unfold m_eqb. apply /andP. split. apply /andP. split. all: apply /eqP; auto. Qed. Hint Resolve m_eqb_ref: auction. Lemma m_eqb_elim (x y: fill_type): m_eqb x y -> x = y. Proof. { unfold m_eqb. destruct x. destruct y. simpl. intros. move /andP in H. destruct H. move /andP in H. destruct H. move /eqP in H. move /eqP in H1. move /eqP in H0. rewrite H0. rewrite H1. rewrite H. auto. } Qed. Lemma m_eqb_intro (x y: fill_type): x=y -> m_eqb x y = true. Proof. { unfold m_eqb. intros H. apply /andP. split. apply /andP. split. apply /eqP. subst x. exact. apply /eqP. subst x. exact. apply /eqP. subst x. exact. } Qed. Hint Immediate m_eqb_elim m_eqb_intro: auction. Lemma m_eqP (x y: fill_type): reflect (x=y)(m_eqb x y). Proof. apply reflect_intro. split; auto with auction. Qed. Hint Resolve m_eqP: auction. Canonical fill_eqType: eqType:= {| Decidable.E:= fill_type; Decidable.eqb:= m_eqb; Decidable.eqP:= m_eqP |}. Fixpoint bids_of (F: list fill_type) : (list Bid) := match F with |nil => nil |f::F'=> (bid_of f)::(bids_of F') end. Lemma bids_of_intro (F: list fill_type) (m: fill_type): In m F -> (In (bid_of m) (bids_of F)). Proof. { intro H. induction F. simpl. simpl in H. contradiction. destruct H. subst m. simpl. left. auto. simpl. right. auto. } Qed. Lemma bids_of_nonempty (F: list fill_type): F<>nil -> (bids_of F)<>nil. Proof. intros. induction F. destruct H. auto. simpl. apply non_nil_size. simpl. omega. Qed. Lemma bids_of_elim0 (F: list fill_type) (m: fill_type): In m F -> In (bid_of m) (bids_of F). Proof. { induction F as [| a F']. simpl. auto. intros. simpl. simpl in H. destruct H. left. subst a. auto. right. apply IHF'. exact. } Qed. Lemma bids_of_delete (F: list fill_type) (m: fill_type): In m F -> NoDup (bids_of F) -> (bids_of (delete m F)) = (delete (bid_of m) (bids_of F)). Proof. { induction F as [| a F']. { simpl. auto. } { intros. simpl. destruct (m_eqb m a) eqn: Hma. { assert (Ht: (b_eqb (bid_of m) (bid_of a))=true). move /eqP in Hma. apply /eqP. subst m. auto. rewrite Ht. auto. } { destruct (b_eqb (bid_of m) (bid_of a)) eqn: Ham. { move /eqP in Ham. simpl. rewrite IHF'. move /eqP in Hma. eapply element_list with (b:=m)(a:=a). auto. exact. eauto. simpl in H. destruct H. move /eqP in Hma. apply eq_sym ; trivial. subst a. destruct Hma. auto. assert (Hbid: ~In (bid_of a) (bids_of F')). eauto. assert (Hbidm: In (bid_of m) (bids_of F')). apply bids_of_elim0. exact. rewrite Ham in Hbidm. contradiction. } { simpl. rewrite IHF'. move /eqP in Hma. destruct H. symmetry in H. contradiction. exact. eauto. auto. }}}} Qed. Lemma bids_of_elim (F: list fill_type): forall b, In b (bids_of F)-> exists m, In m F /\ b = bid_of m. Proof. { intros b H. induction F. simpl in H. contradiction. simpl in H. destruct H as [H1 | H2]. exists a. split; auto. apply IHF in H2 as H0. destruct H0 as [m H0]. exists m. destruct H0. split. eauto. auto. } Qed. Lemma bids_of_intro1 (M': list fill_type) (M: list fill_type): M [<=] M' -> ((bids_of M) [<=] (bids_of M')). Proof. { intro H. intros b. intro H1. assert (H2: exists m, In m M /\ b=bid_of m). apply bids_of_elim. exact. destruct H2. destruct H0. assert (H3: In x M'). auto. subst b. eapply bids_of_intro. exact. } Qed. Lemma bids_of_elim1 (M: list fill_type)(m: fill_type)(b: Bid): In b (bids_of (delete m M)) -> In b (bids_of M). Proof. { induction M. simpl. auto. simpl. intros. case (m_eqb m a) eqn: Hm. right. exact. simpl in H. destruct H. left. exact. apply IHM in H. right. exact. } Qed. Lemma count_in_deleted_bids (m: fill_type)(M: list fill_type): In m M -> count (bid_of m) (bids_of M) = S (count (bid_of m) (bids_of (delete m M))). Proof. { induction M. { simpl. auto. } { intro h1. destruct (m == a) eqn: h2. { simpl. rewrite h2. move /eqP in h2. subst a. simpl. replace (b_eqb (bid_of m) (bid_of m)) with true. auto. auto. } { assert (h1a: In m M). { move /eqP in h2. eapply element_list with (b:=m)(a:=a). auto. exact. } replace (delete m (a :: M)) with (a :: (delete m M)). { simpl. destruct (b_eqb (bid_of m) (bid_of a)) eqn: h3. { apply IHM in h1a as h1b. rewrite h1b. auto. } { auto. } } { simpl. rewrite h2. auto. } } } } Qed. Lemma included_M_imp_included_bids (M1 M2: list fill_type): included M1 M2 -> included (bids_of M1) (bids_of M2). Proof. { revert M2. induction M1 as [| m1]. { simpl. auto. } { intros M2 h1. assert (h2: In m1 M2). eauto. assert (h3: included M1 (delete m1 M2)). eauto. assert (h3a: included (bids_of M1) (bids_of (delete m1 M2))). { auto. } assert(h4:count (bid_of m1)(bids_of M2)= S (count (bid_of m1) (bids_of (delete m1 M2)))). { eauto using count_in_deleted_bids. } eapply included_intro. intro x. simpl. destruct (b_eqb x (bid_of m1)) eqn: C1. { (* ---- C1: x = b1 ---- *) move /b_eqP in C1. subst x. rewrite h4. eapply included_elim in h3a as h3b. instantiate (1 := bid_of m1) in h3b. omega. } { (*----- C1: x <> b1 ---- *) assert (h3b: included M1 M2). eapply included_elim4; apply h1. apply IHM1 in h3b as h3c. auto. } } } Qed. Lemma bids_of_perm (M M': list fill_type): perm M M' -> perm (bids_of M) (bids_of M'). Proof. { intro H. unfold perm in H. move /andP in H. destruct H. unfold perm. apply /andP. split. all: eapply included_M_imp_included_bids;exact. } Qed. Lemma bids_of_nodup (F: list fill_type): NoDup (bids_of F) -> NoDup F. Proof. { intro H. induction F. auto. assert (H1:NoDup (bids_of F)). simpl in H. eauto. apply IHF in H1 as H2. simpl in H. assert (~In (bid_of a) (bids_of F)). eauto. assert (~In a (F)). intro. assert (H4:In (bid_of a) (bids_of F)). apply bids_of_elim0. exact. contradiction. eauto. } Qed. Lemma bids_of_delete_delete (F: list fill_type) (m1 m2: fill_type): In m1 F -> In m2 F -> NoDup (bids_of F) -> (bids_of (delete m1 (delete m2 F))) = (delete (bid_of m1) (delete (bid_of m2) (bids_of F))). Proof. { intros. assert (Hm1m2: m1=m2\/m1<>m2). eapply reflect_EM. auto. destruct Hm1m2. { subst m1. simpl. assert (H2:(delete m2 (delete m2 F)) = delete m2 F). { assert (H3:~In m2 (delete m2 F) ). { apply delete_intro2. apply bids_of_nodup. exact. } apply delete_intro1 in H3. auto. } assert (H3:(delete (bid_of m2) (delete (bid_of m2) (bids_of F))) = (delete (bid_of m2) (bids_of F))). { assert (H4:~In (bid_of m2) (delete (bid_of m2) (bids_of F))). { apply delete_intro2. exact. } apply delete_intro1 in H4. auto. } rewrite H2. rewrite H3. apply bids_of_delete. exact. exact. } { assert (H3: (bids_of (delete m2 F)) = (delete (bid_of m2) (bids_of F))). apply bids_of_delete. exact. exact. assert (H4: (bids_of (delete m1 (delete m2 F))) = (delete (bid_of m1) ((delete (bid_of m2) (bids_of F))))). rewrite <- H3. apply bids_of_delete. apply delete_intro. exact. exact. { assert (H4: (bids_of (delete m2 F)) = delete (bid_of m2) (bids_of F)). apply bids_of_delete. exact. exact. rewrite H4. eauto. } exact. }} Qed. Fixpoint asks_of (F: list fill_type) : (list Ask) := match F with |nil => nil |f::F'=> (ask_of f)::(asks_of F') end. Lemma asks_of_intro (F: list fill_type) (m: fill_type): In m F -> (In (ask_of m) (asks_of F)). Proof. { intro H. induction F. simpl. simpl in H. contradiction. destruct H. subst m. simpl. left. auto. simpl. right. auto. } Qed. Lemma asks_of_nonempty (F: list fill_type): F<>nil -> (asks_of F)<>nil. Proof. intros. induction F. destruct H. auto. simpl. apply non_nil_size. simpl. omega. Qed. Lemma asks_of_elim0 (F: list fill_type) (m: fill_type): In m F -> In (ask_of m) (asks_of F). Proof. { induction F as [| a F']. simpl. auto. intros. simpl. simpl in H. destruct H. left. subst a. auto. right. apply IHF'. exact. } Qed. (*TODO: automate the following Lemma*) Lemma asks_of_delete (F: list fill_type) (m: fill_type): In m F -> NoDup (asks_of F) -> (asks_of (delete m F)) = (delete (ask_of m) (asks_of F)). Proof. { induction F as [| a F']. { simpl. auto. } { intros. simpl. destruct (m_eqb m a) eqn: Hma. { assert (Ht: (a_eqb (ask_of m) (ask_of a))=true). move /eqP in Hma. apply /eqP. subst m. auto. rewrite Ht. auto. } { destruct (a_eqb (ask_of m) (ask_of a)) eqn: Ham. { move /eqP in Ham. simpl. rewrite IHF'. move /eqP in Hma. destruct H. symmetry in H. contradiction. exact. eauto. simpl in H. destruct H. move /eqP in Hma. apply eq_sym ; trivial. subst a. destruct Hma. auto. assert (Hask: ~In (ask_of a) (asks_of F')). eauto. assert (Haskm: In (ask_of m) (asks_of F')). apply asks_of_elim0. exact. rewrite Ham in Haskm. contradiction. } { simpl. rewrite IHF'. move /eqP in Hma. destruct H. symmetry in H. contradiction. exact. eauto. auto. }}}} Qed. Lemma asks_of_elim (F: list fill_type): forall a, In a (asks_of F)-> exists m, In m F /\ a = ask_of m. Proof. { intros b H. induction F. simpl in H. contradiction. simpl in H. destruct H as [H1 | H2]. exists a. split; auto. apply IHF in H2 as H0. destruct H0 as [m H0]. exists m. destruct H0. split. eauto. auto. } Qed. Lemma asks_of_intro1 (M': list fill_type) (M: list fill_type): M [<=] M' -> ((asks_of M) [<=] (asks_of M')). Proof. { intro H. intros a. intro H1. assert (H2: exists m, In m M /\ a=ask_of m). apply asks_of_elim. exact. destruct H2. destruct H0. assert (H3: In x M'). auto. subst a. eapply asks_of_intro. exact. } Qed. Lemma asks_of_elim1 (M: list fill_type)(m: fill_type)(a: Ask): In a (asks_of (delete m M)) -> In a (asks_of M). Proof. { induction M. simpl. auto. simpl. intros. case (m_eqb m a0) eqn: Hm. right. exact. simpl in H. destruct H. left. exact. apply IHM in H. right. exact. } Qed. Lemma count_in_deleted_asks (m: fill_type)(M: list fill_type): In m M -> count (ask_of m) (asks_of M) = S (count (ask_of m) (asks_of (delete m M))). Proof. { induction M. { simpl. auto. } { intro h1. destruct (m == a) eqn: h2. { simpl. rewrite h2. move /eqP in h2. subst a. simpl. replace (a_eqb (ask_of m) (ask_of m)) with true. auto. auto. } { assert (h1a: In m M). { move /eqP in h2. eapply element_list with (b:=m)(a:=a). auto. exact. } replace (delete m (a :: M)) with (a :: (delete m M)). { simpl. destruct (a_eqb (ask_of m) (ask_of a)) eqn: h3. { apply IHM in h1a as h1b. rewrite h1b. auto. } { auto. } } { simpl. rewrite h2. auto. } } } } Qed. Lemma included_M_imp_included_asks (M1 M2: list fill_type): included M1 M2 -> included (asks_of M1) (asks_of M2). Proof. { revert M2. induction M1 as [| m1]. { simpl. auto. } { intros M2 h1. assert (h2: In m1 M2). eauto. assert (h3: included M1 (delete m1 M2)). eauto. assert (h3a: included (asks_of M1) (asks_of (delete m1 M2))). { auto. } assert(h4:count (ask_of m1)(asks_of M2)= S (count (ask_of m1) (asks_of (delete m1 M2)))). { eauto using count_in_deleted_asks. } eapply included_intro. intro x. simpl. destruct (a_eqb x (ask_of m1)) eqn: C1. { (* ---- C1: x = b1 ---- *) move /a_eqP in C1. subst x. rewrite h4. eapply included_elim in h3a as h3b. instantiate (1 := ask_of m1) in h3b. omega. } { (*----- C1: x <> b1 ---- *) assert (h3b: included M1 M2). eapply included_elim4; apply h1. apply IHM1 in h3b as h3c. auto. } } } Qed. Lemma asks_of_perm (M M': list fill_type): perm M M' -> perm (asks_of M) (asks_of M'). Proof. { intro H. unfold perm in H. move /andP in H. destruct H. unfold perm. apply /andP. split. all: eapply included_M_imp_included_asks;exact. } Qed. Lemma asks_of_nodup (F: list fill_type): NoDup (asks_of F) -> NoDup F. Proof. { intro H. induction F. auto. assert (H1:NoDup (asks_of F)). simpl in H. eauto. apply IHF in H1 as H2. simpl in H. assert (~In (ask_of a) (asks_of F)). eauto. assert (~In a (F)). intro. assert (H4:In (ask_of a) (asks_of F)). apply asks_of_elim0. exact. contradiction. eauto. } Qed. Lemma asks_of_delete_delete (F: list fill_type) (m1 m2: fill_type): In m1 F -> In m2 F -> NoDup (asks_of F) -> (asks_of (delete m1 (delete m2 F))) = (delete (ask_of m1) (delete (ask_of m2) (asks_of F))). Proof. { intros. assert (Hm1m2: m1=m2\/m1<>m2). eapply reflect_EM. auto. destruct Hm1m2. { subst m1. simpl. assert (H2:(delete m2 (delete m2 F)) = delete m2 F). { assert (H3:~In m2 (delete m2 F) ). { apply delete_intro2. apply asks_of_nodup. exact. } apply delete_intro1 in H3. auto. } assert (H3:(delete (ask_of m2) (delete (ask_of m2) (asks_of F))) = (delete (ask_of m2) (asks_of F))). { assert (H4:~In (ask_of m2) (delete (ask_of m2) (asks_of F))). { apply delete_intro2. exact. } apply delete_intro1 in H4. auto. } rewrite H2. rewrite H3. apply asks_of_delete. exact. exact. } { assert (H3: (asks_of (delete m2 F)) = (delete (ask_of m2) (asks_of F))). apply asks_of_delete. exact. exact. assert (H4: (asks_of (delete m1 (delete m2 F))) = (delete (ask_of m1) ((delete (ask_of m2) (asks_of F))))). rewrite <- H3. apply asks_of_delete. apply delete_intro. exact. exact. { assert (H4: (asks_of (delete m2 F)) = delete (ask_of m2) (asks_of F)). apply asks_of_delete. exact. exact. rewrite H4. eauto. } exact. }} Qed. Fixpoint trade_prices_of (F: list fill_type) : (list nat) := match F with |nil => nil |f::F'=> (tp f)::(trade_prices_of F') end. Lemma trade_prices_of_intro (F: list fill_type) (m: fill_type): In m F -> In (tp m) (trade_prices_of F). Proof. { intro H. induction F. eauto. destruct H. subst m. simpl. left;auto. simpl. right;auto. } Qed. Lemma trade_prices_of_elim (F: list fill_type): forall p, In p (trade_prices_of F) -> exists m, In m F /\ p = tp m. Proof. { intros p H. induction F. simpl in H. contradiction. simpl in H. destruct H. exists a. split. eauto. auto. apply IHF in H as H0. destruct H0 as [m H0]. destruct H0 as [H1 H2]. exists m. split;eauto. } Qed. Lemma count_in_deleted_tp (m: fill_type)(M: list fill_type): In m M -> count (tp m)(trade_prices_of M) = S (count (tp m) (trade_prices_of (delete m M))). Proof. { induction M. { simpl. auto. } { intro H1. destruct (m == a) eqn: H2. { simpl. rewrite H2. move /eqP in H2. subst a. simpl. replace (tp m =? tp m) with true. auto. auto. } { assert (H1a: In m M). { move /eqP in H2. eapply element_list with (b:=m)(a:=a). auto. exact. } replace (delete m (a :: M)) with (a :: (delete m M)). { simpl. destruct (tp m =? tp a) eqn: H3. { apply IHM in H1a as H1b. rewrite H1b. auto. } { auto. } } { simpl. rewrite H2. auto. } } } } Qed. Lemma included_M_imp_included_tps (M M': list fill_type): included M M' -> included (trade_prices_of M) (trade_prices_of M'). Proof. Proof. { revert M'. induction M as [| m]. { simpl. auto. } { intros M' H1. assert (H2: In m M'). eauto. assert (H3: included M (delete m M')). eauto. assert (H3a: included (trade_prices_of M) (trade_prices_of (delete m M'))). { auto. } assert(H4:count (tp m)(trade_prices_of M')= S (count (tp m) (trade_prices_of (delete m M')))). { eauto using count_in_deleted_tp. } eapply included_intro. intro x. simpl. destruct (x =? tp m) eqn: C1. { (* ---- C1: x = b1 ---- *) move /nat_eqP in C1. subst x. rewrite H4. eapply included_elim in H3a as H3b. instantiate (1 :=tp m) in H3b. omega. } { (*----- C1: x <> b1 ---- *) assert (H3b: included M M'). eapply included_elim4; apply H1. apply IHM in H3b as H3c. auto. } } } Qed. Lemma tps_of_perm (M M': list fill_type): perm M M' -> perm (trade_prices_of M) (trade_prices_of M'). Proof. { intro H. unfold perm in H. move /andP in H. destruct H. unfold perm. apply /andP. split. all: eapply included_M_imp_included_tps. exact. exact. } Qed. Hint Resolve bids_of_intro bids_of_elim asks_of_intro asks_of_elim: core. Hint Resolve trade_prices_of_intro trade_prices_of_elim: core. Hint Resolve asks_of_intro1 bids_of_intro1 asks_of_perm bids_of_perm: core. Hint Resolve bids_of_elim1 asks_of_elim1: core. End BidAsk. Definition b0 := {|bp:=0;idb:=0|}. Definition a0 := {|sp:=0;ida:=0|}. Definition m0 := {|bid_of:=b0;ask_of:=a0;tp:=0|}. Hint Resolve b_eqb_ref b_eqP : core. Hint Immediate b_eqb_elim b_eqb_intro: core. Hint Resolve a_eqb_ref a_eqP : core. Hint Immediate a_eqb_intro a_eqb_elim: core. Hint Resolve bid_prices_elim bid_prices_intro bid_prices_intro1: core. Hint Resolve ask_prices_elim ask_prices_intro ask_prices_intro1: core. Hint Resolve m_eqb_ref m_eqP: core. Hint Immediate m_eqb_elim m_eqb_intro: core. Hint Resolve bids_of_intro bids_of_elim asks_of_intro asks_of_elim: core. Hint Resolve trade_prices_of_intro trade_prices_of_elim: core. Hint Resolve asks_of_intro1 bids_of_intro1 asks_of_perm bids_of_perm: core. Hint Resolve bids_of_perm asks_of_perm tps_of_perm: core. Hint Resolve bids_of_elim1 asks_of_elim1: core.
State Before: k : Type u_2 V1 : Type u_3 P1 : Type u_1 V2 : Type ?u.423603 P2 : Type ?u.423606 V3 : Type ?u.423609 P3 : Type ?u.423612 V4 : Type ?u.423615 P4 : Type ?u.423618 inst✝¹² : Ring k inst✝¹¹ : AddCommGroup V1 inst✝¹⁰ : Module k V1 inst✝⁹ : AffineSpace V1 P1 inst✝⁸ : AddCommGroup V2 inst✝⁷ : Module k V2 inst✝⁶ : AffineSpace V2 P2 inst✝⁵ : AddCommGroup V3 inst✝⁴ : Module k V3 inst✝³ : AffineSpace V3 P3 inst✝² : AddCommGroup V4 inst✝¹ : Module k V4 inst✝ : AffineSpace V4 P4 p : P1 v : V1 c : k ⊢ ↑(lineMap p (v +ᵥ p)) c = c • v +ᵥ p State After: no goals Tactic: rw [lineMap_apply, vadd_vsub]
!---------------------------------------------------------------------! ! OWNER: Ithaca Combustion Enterprise, LLC ! ! COPYRIGHT: © 2012, Ithaca Combustion Enterprise, LLC ! ! LICENSE: BSD 3-Clause License (The complete text of the license can ! ! be found in the `LICENSE-ICE.txt' file included in the ISAT-CK7 ! ! source directory.) ! !---------------------------------------------------------------------! subroutine ell_line_proj( n, c, gg, x0, v, smin, smax ) ! Given the ellipsoid E = { x | norm(G^T * (x-c) ) <=1 ), ! where G is an n x n lower triangular, and given the line ! L = { x | x = x0 + v * s }, determine the line segment ! (smin, smax) which is the orthogonal projection of E onto L. ! The array gg contains the matrix G in packed format. ! Method: E = { x | x = c + G^{-T} u, |u| <=1} ! s = v^T * ( x - x0 ) / v^T * v ! = v^T * ( c - x0 + G^{-T} u ) / v^T * v ! = s0 + w^T * u, s0 = v^T * ( c - x0 ) / v^T * v, ! w = G^{-1} * v / v^T * v ! smax = s0 + |w|, smin = s0 - |w| ! S.B. Pope 6/12/04 implicit none integer, parameter :: k_dp = kind(1.d0) integer, intent(in) :: n real(k_dp), intent(in) :: c(n), gg((n*(n+1))/2), x0(n), v(n) real(k_dp), intent(out) :: smin, smax real(k_dp) :: vnormsq, w(n), s0, wnorm vnormsq = sum(v*v) ! v^T * v = |v|^2 if( vnormsq == 0.d0 ) then write(0,*)'ell_line_proj: |v| = 0' stop endif w = v / vnormsq s0 = sum( w * (c-x0) ) ! s0 = v^T ( c - x0 ) / |v|^2 call dtpsv( 'L', 'N', 'N', n, gg, w, 1 ) ! w = G^{-1} * v / v^T * v wnorm = sqrt( sum( w * w ) ) smin = s0 - wnorm smax = s0 + wnorm return end subroutine ell_line_proj
Require Import RefProofDeps. Require Import RData. Require Import EventReplay. Require Import MoverTypes. Require Import Constants. Require Import CommonLib. Require Import RefTactics. Require Import AbsAccessor.Spec. Require Import RunAux.Specs.reset_last_run_info. Require Import RunAux.LowSpecs.reset_last_run_info. Require Import RunAux.RefProof.RefRel. Local Open Scope string_scope. Local Open Scope Z_scope. Local Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor. Section Refine. Hint Unfold set_rec_last_run_info_esr_spec . Lemma reset_last_run_info_spec_exists: forall habd habd' labd rec (Hspec: reset_last_run_info_spec rec habd = Some habd') (Hrel: relate_RData habd labd), exists labd', reset_last_run_info_spec0 rec labd = Some labd' /\ relate_RData habd' labd'. Proof. intros. inv Hrel. destruct rec. unfold reset_last_run_info_spec, reset_last_run_info_spec0 in *. repeat autounfold in *. simpl in *. grewrite. eexists; split. reflexivity. constructor; reflexivity. Qed. End Refine.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 31 2018 @author: Sagar_D """ # Training the ANN with Stochastic Gradient Descent # First layer - input layer # Step 1: Randomly initialise the weights to small numbers close to 0 (but not 0) # Step 2: Input the first observation of the dataset in the input layer, each feature in one input node (11 input nodes) # Step 3: Activation function hidden layer (rectifier), sigmoid (good for output layer) # Step 4: Compare the predicted result o the actual result, measure the generated error # Step 5: Back-propagation - learning rate decideds how much we update the weights # Step 6: update the weights after each observation # Step 7: Train # Part 1 - Data Preprocessing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Churn_Modelling.csv') X = dataset.iloc[:, 3:13].values y = dataset.iloc[:, 13].values # Encoding categorical data # Encode before splitting because matrix X and independent variable Y must be already encoded # Found two categorical data (country, gender) # create dummy variables, avoid dummy variable trap from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X_1 = LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1]) labelencoder_X_2 = LabelEncoder() X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2]) onehotencoder = OneHotEncoder(categorical_features = [1]) X = onehotencoder.fit_transform(X).toarray() X = X[:, 1:] # Splitting the dataset into the Training set and Test set from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) # Feature Scaling # lots of high computation to ease calculation, we don't want one independent variable dominating from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # Part 2 - Making the ANN # Importing the Keras libraries and package # Sequential module - initialize neural network # Dense - layers of ANN import keras from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout # Initialising the ANN classifier = Sequential() # Adding the input layer and the first hidden layer with dropout # Take average of input + output for units/output_dim param in Dense # input_dim is necessary for the first layer as it was just initialized classifier.add(Dense(6, input_dim = 11, kernel_initializer = 'glorot_uniform', activation = 'relu' )) classifier.add(Dropout(p = 0.1)) # Adding the second hidden layer with dropout # doesn't need the input_dim params # kernel_initializer updates weights # activation function - rectifier classifier.add(Dense(6, kernel_initializer = 'glorot_uniform', activation = 'relu' )) classifier.add(Dropout(p = 0.1)) # Adding the output layer # dependent variable with more than two categories (3), output_dim needs to change (e.g. 3), activation function - sufmax classifier.add(Dense(1, kernel_initializer = 'glorot_uniform', activation = 'sigmoid' )) # Compiling the ANN - applying Stochastic Gradient Descent to whole ANN # Several different SGD algorithms # mathematical details based on the loss function # binary_crossentropy, categorical_cross_entropy classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) # Fitting the ANN to the Training Set # X_train, y_train, Batch size, Epochs (whole training set) classifier.fit(X_train, y_train, batch_size = 10, nb_epoch = 100) # Part 3 - Making the predictions and evaluating the model # Predicting the Test set results # Training set, see if the new data probability is right y_pred = classifier.predict(X_test) y_pred = (y_pred > 0.5) # Predicting a single new observation new_prediction = classifier.predict(sc.transform(np.array([[0, 0, 600, 1, 40, 3, 60000, 2, 1, 1, 50000]]))) new_prediction = (new_prediction > 0.5) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) # Part 4 - Evaluating, Imrpvoing and Tuning the ANN # Evaluating the ANN # Keras wrapper and Sci-kit Learn for k-Fold Cross Validation from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import cross_val_score from keras.models import Sequential from keras.layers import Dense def build_classifier(): classifier = Sequential() classifier.add(Dense(6, input_dim = 11, kernel_initializer = 'glorot_uniform', activation = 'relu' )) classifier.add(Dense(6, kernel_initializer = 'glorot_uniform', activation = 'relu' )) classifier.add(Dense(1, kernel_initializer = 'glorot_uniform', activation = 'sigmoid' )) classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) return classifier # k-Fold cross validator to check if the real relevant accuracy or the second one #ß and where we are in bias-variance tradeoffs classifier = KerasClassifier(build_fn = build_classifier, batch_size = 10, nb_epoch = 100) accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1) mean = accuracies.mean() variable = accuracies.std() # overfitting is when it's trained to much on the training set, less performant, test set # and training set, high variance in, Dropout Regulariatio to reduce overfitting if needed # Tuning the ANN, parameters learned during training (weights), stay fixed (hyperparamers - fixed, epochs, neurons) # parameter tuning best value of these hyperparameters, GridSearchCV with k-Fold Cross Validation from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import GridSearchCV from keras.models import Sequential from keras.layers import Dense def build_classifier(optimzer): classifier = Sequential() classifier.add(Dense(6, input_dim = 11, kernel_initializer = 'glorot_uniform', activation = 'relu' )) classifier.add(Dense(6, kernel_initializer = 'glorot_uniform', activation = 'relu' )) classifier.add(Dense(1, kernel_initializer = 'glorot_uniform', activation = 'sigmoid' )) classifier.compile(optimizer = optimzer, loss = 'binary_crossentropy', metrics = ['accuracy']) return classifier classifier = KerasClassifier(build_fn = build_classifier) parameters = {'batch_size': [25, 32], 'nb_epoch': [100, 500], 'optimzer': ['adam', 'rmsprop']} grid_search = GridSearchCV(estimator = classifier, param_grid = parameters, scoring = 'accuracy', s cv = 10) grid_search = grid_search.fit(X_train, y_train) best_parameters = grid_search.best_params_ best_accuracy = grid_search.best_score_
An astragalus ( ankle bone ) thought to belong to a species of Allosaurus was found at Cape Paterson , Victoria in Early Cretaceous beds in southeastern Australia . It was thought to provide evidence that Australia was a refugium for animals that had gone extinct elsewhere . This identification was challenged by Samuel Welles , who thought it more resembled that of an ornithomimid , but the original authors defended their identification . With fifteen years of new specimens and research to look at , Daniel Chure reexamined the bone and found that it was not Allosaurus , but could represent an allosauroid . Similarly , Yoichi Azuma and Phil Currie , in their description of <unk> , noted that the bone closely resembled that of their new genus . This specimen is sometimes referred to as " Allosaurus robustus " , an informal museum name . It may have belonged to something similar to , or the same as , <unk> , or it may represent an abelisaur . A speculative " polar " or " dwarf allosaur " was used for the " Spirits of the Ice Forest " episode of Walking with Dinosaurs .
// // syr2k.h // Linear Algebra Template Library // // Created by Rodney James on 1/4/12. // Copyright (c) 2012 University of Colorado Denver. All rights reserved. // #ifndef _syr2k_h #define _syr2k_h /// @file syr2k.h Performs multiplication of two matrices resulting in a symmetric matrix. #include <cctype> #include "latl.h" namespace LATL { /// @brief Performs multiplcation of real matrices resulting in a symmetric matrix. /// /// For real matrices A and B, real symmetric matrix C, and real scalars alpha and beta /// /// C := alpha*A*B'+alpha*B*A'+beta*C /// or /// /// C := alpha*A'*B+alpha*B'*A+beta*C /// is computed. /// @return 0 if success. /// @return -i if the ith argument is invalid. /// @tparam real_t Floating point type. /// @param uplo Specifies whether the upper or lower triangular part of the symmetric matrix C /// is to be referenced: /// /// if uplo = 'U' or 'u' then C is upper triangular, /// if uplo = 'L' or 'l' then C is lower triangular. /// @param trans Specifies the operation to be perfomed as follows: /// /// if trans = 'N' or 'n' then C := alpha*A*B'+alpha*B*A'+beta*C /// if trans = 'T' or 't' then C := alpha*A'*B+alpha*B'*A+beta*C /// if trans = 'C' or 'c' then C := alpha*A'*B+alpha*B'*A+beta*C /// @param n Specifies the order of the complex Hermitian matrix C. n>=0 /// @param k Specifies the other dimension of the complex matrices A and B. /// /// if trans = 'N' or 'n' then A and B are n-by-k /// if trans = 'T' or 't' then A and B are k-by-n /// if trans = 'C' or 'c' then A and B are k-by-n /// @param alpha Real scalar. /// @param A Pointer to real matrix. /// @param ldA Column length of the matrix A. If trans = 'N' or 'n' ldA>=n, otherwise ldA>=k. /// @param B Pointer to real matrix. /// @param ldB Column length of the matrix B. If trans = 'N' or 'n' ldB>=n, otherwise ldB>=k. /// @param beta Real scalar. /// @param C Pointer to real symmetric n-by-n matrix C. /// Only the upper or lower triangular part of C is referenced, depending on the value of uplo above. /// @param ldC Column length of the matrix C. ldC>=n /// @ingroup BLAS template <typename real_t> int SYR2K(char uplo, char trans, int_t n, int_t k, real_t alpha, real_t *A, int_t ldA, real_t *B, int_t ldB, real_t beta, real_t *C, int_t ldC) { using std::toupper; const real_t zero(0.0); const real_t one(1.0); int_t i,j,l; real_t *a,*b,*c,*at,*bt; real_t s,t; uplo=toupper(uplo); trans=toupper(trans); if((uplo!='U')&&(uplo!='L')) return -1; else if((trans!='N')&&(trans!='T')&&(trans!='C')) return -2; else if(n<0) return -3; else if(k<0) return -4; else if(ldA<((trans=='N')?n:k)) return -7; else if(ldB<((trans=='N')?n:k)) return -9; else if(ldC<n) return -12; else if((n==0)||(((alpha==zero)||(k==0))&&(beta==one))) return 0; if(alpha==zero) { if(uplo=='U') { c=C; for(j=0;j<n;j++) { for(i=0;i<=j;i++) c[i]*=beta; c+=ldC; } } else { c=C; for(j=0;j<n;j++) { for(i=j;i<n;i++) c[i]*=beta; c+=ldC; } } } else if(trans=='N') { if(uplo=='U') { c=C; for(j=0;j<n;j++) { for(i=0;i<=j;i++) c[i]*=beta; a=A; b=B; for(l=0;l<k;l++) { s=alpha*b[j]; t=alpha*a[j]; for(i=0;i<=j;i++) c[i]+=s*a[i]+t*b[i]; a+=ldA; b+=ldB; } c+=ldC; } } else { c=C; for(j=0;j<n;j++) { for(i=j;i<n;i++) c[i]*=beta; a=A; b=B; for(l=0;l<k;l++) { s=alpha*b[j]; t=alpha*a[j]; for(i=j;i<n;i++) c[i]+=s*a[i]+t*b[i]; a+=ldA; b+=ldB; } c+=ldC; } } } else { if(uplo=='U') { c=C; at=A; bt=B; for(j=0;j<n;j++) { a=A; b=B; for(i=0;i<=j;i++) { s=zero; t=zero; for(l=0;l<k;l++) { s+=b[l]*at[l]; t+=a[l]*bt[l]; } c[i]=alpha*t+alpha*s+beta*c[i]; a+=ldA; b+=ldB; } at+=ldA; bt+=ldB; c+=ldC; } } else { c=C; at=A; bt=B; for(j=0;j<n;j++) { a=A+j*ldA; b=B+j*ldB; for(i=j;i<n;i++) { s=zero; t=zero; for(l=0;l<k;l++) { s+=b[l]*at[l]; t+=a[l]*bt[l]; } c[i]=alpha*t+alpha*s+beta*c[i]; a+=ldA; b+=ldB; } at+=ldA; bt+=ldB; c+=ldC; } } } return 0; } /// @brief Performs multiplcation of complex matrices resulting in a symmetric matrix. /// /// For complex matrices A and B, complex Hermitian matrix C, and complex scalars alpha and beta /// /// C := alpha*A*B.'+alpha*B*A.'+beta*C /// or /// /// C := alpha*A.'*B+alpha*B.'*A+beta*C /// is computed. /// @return 0 if success. /// @return -i if the ith argument is invalid. /// @tparam real_t Floating point type. /// @param uplo Specifies whether the upper or lower triangular part of the symmetric matrix C /// is to be referenced: /// /// if uplo = 'U' or 'u' then C is upper triangular, /// if uplo = 'L' or 'l' then C is lower triangular. /// @param trans Specifies the operation to be perfomed as follows: /// /// if trans = 'N' or 'n' then C := alpha*A*B.'+alpha*B*A.'+beta*C /// if trans = 'T' or 'T' then C := alpha*A.'*B+alpha*B.'*A+beta*C /// @param n Specifies the order of the complex symmetric matrix C. n>=0 /// @param k Specifies the other dimension of the complex matrices A and B. /// /// if trans = 'N' or 'n' then A and B are n-by-k /// if trans = 'T' or 't' then A and B are k-by-n /// @param alpha Complex scalar. /// @param A Pointer to complex matrix. /// @param ldA Column length of the matrix A. If trans = 'N' or 'n' ldA>=n, otherwise ldA>=k. /// @param B Pointer to complex matrix. /// @param ldB Column length of the matrix B. If trans = 'N' or 'n' ldB>=n, otherwise ldB>=k. /// @param beta Complex scalar. /// @param C Pointer to complex symmetric n-by-n matrix C. /// Only the upper or lower triangular part of C is referenced, depending on the value of uplo above. /// @param ldC Column length of the matrix C. ldC>=n /// @ingroup BLAS template <typename real_t> int SYR2K(char uplo, char trans, int_t n, int_t k, complex<real_t> alpha, complex<real_t> *A, int_t ldA, complex<real_t> *B, int_t ldB, complex<real_t> beta, complex<real_t> *C, int_t ldC) { using std::toupper; const complex<real_t> zero(0.0,0.0); const complex<real_t> one(1.0,0.0); int_t i,j,l; complex<real_t> *a,*b,*c,*at,*bt; complex<real_t> s,t; uplo=toupper(uplo); trans=toupper(trans); if((uplo!='U')&&(uplo!='L')) return -1; else if((trans!='N')&&(trans!='T')) return -2; else if(n<0) return -3; else if(k<0) return -4; else if(ldA<((trans=='N')?n:k)) return -7; else if(ldB<((trans=='N')?n:k)) return -9; else if(ldC<n) return -12; else if((n==0)||(((alpha==zero)||(k==0))&&(beta==one))) return 0; if(alpha==zero) { if(uplo=='U') { c=C; for(j=0;j<n;j++) { for(i=0;i<=j;i++) c[i]*=beta; c+=ldC; } } else { c=C; for(j=0;j<n;j++) { for(i=j;i<n;i++) c[i]*=beta; c+=ldC; } } } else if(trans=='N') { if(uplo=='U') { c=C; for(j=0;j<n;j++) { for(i=0;i<=j;i++) c[i]*=beta; a=A; b=B; for(l=0;l<k;l++) { s=alpha*b[j]; t=alpha*a[j]; for(i=0;i<=j;i++) c[i]+=s*a[i]+t*b[i]; a+=ldA; b+=ldB; } c+=ldC; } } else { c=C; for(j=0;j<n;j++) { for(i=j;i<n;i++) c[i]*=beta; a=A; b=B; for(l=0;l<k;l++) { s=alpha*b[j]; t=alpha*a[j]; for(i=j;i<n;i++) c[i]+=s*a[i]+t*b[i]; a+=ldA; b+=ldB; } c+=ldC; } } } else { if(uplo=='U') { c=C; at=A; bt=B; for(j=0;j<n;j++) { a=A; b=B; for(i=0;i<=j;i++) { s=zero; t=zero; for(l=0;l<k;l++) { s+=b[l]*at[l]; t+=a[l]*bt[l]; } c[i]=alpha*t+alpha*s+beta*c[i]; a+=ldA; b+=ldB; } at+=ldA; bt+=ldB; c+=ldC; } } else { c=C; at=A; bt=B; for(j=0;j<n;j++) { a=A+j*ldA; b=B+j*ldB; for(i=j;i<n;i++) { s=zero; t=zero; for(l=0;l<k;l++) { s+=b[l]*at[l]; t+=a[l]*bt[l]; } c[i]=alpha*t+alpha*s+beta*c[i]; a+=ldA; b+=ldB; } at+=ldA; bt+=ldB; c+=ldC; } } } return 0; } #ifdef __latl_cblas #include <cblas.h> template <> int SYR2K<float>(char uplo, char trans, int_t n, int_t k, float alpha, float *A, int_t ldA, float *B, int_t ldB, float beta, float *C, int_t ldC) { using std::toupper; uplo=toupper(uplo); trans=toupper(trans); if((uplo!='U')&&(uplo!='L')) return -1; else if((trans!='N')&&(trans!='T')&&(trans!='C')) return -2; else if(n<0) return -3; else if(k<0) return -4; else if(ldA<((trans=='N')?n:k)) return -7; else if(ldB<((trans=='N')?n:k)) return -9; else if(ldC<n) return -12; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans); cblas_ssyr2k(CblasColMajor,Uplo,Trans,n,k,alpha,A,ldA,B,ldB,beta,C,ldC); return 0; } template <> int SYR2K<double>(char uplo, char trans, int_t n, int_t k, double alpha, double *A, int_t ldA, double *B, int_t ldB, double beta, double *C, int_t ldC) { using std::toupper; uplo=toupper(uplo); trans=toupper(trans); if((uplo!='U')&&(uplo!='L')) return -1; else if((trans!='N')&&(trans!='T')&&(trans!='C')) return -2; else if(n<0) return -3; else if(k<0) return -4; else if(ldA<((trans=='N')?n:k)) return -7; else if(ldB<((trans=='N')?n:k)) return -9; else if(ldC<n) return -12; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans); cblas_dsyr2k(CblasColMajor,Uplo,Trans,n,k,alpha,A,ldA,B,ldB,beta,C,ldC); return 0; } template <> int SYR2K<float>(char uplo, char trans, int_t n, int_t k, complex<float> alpha, complex<float> *A, int_t ldA, complex<float> *B, int_t ldB, complex<float> beta, complex<float> *C, int_t ldC) { using std::toupper; uplo=toupper(uplo); trans=toupper(trans); if((uplo!='U')&&(uplo!='L')) return -1; else if((trans!='N')&&(trans!='T')) return -2; else if(n<0) return -3; else if(k<0) return -4; else if(ldA<((trans=='N')?n:k)) return -7; else if(ldB<((trans=='N')?n:k)) return -9; else if(ldC<n) return -12; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans); cblas_csyr2k(CblasColMajor,Uplo,Trans,n,k,&alpha,A,ldA,B,ldB,&beta,C,ldC); return 0; } template <> int SYR2K<double>(char uplo, char trans, int_t n, int_t k, complex<double> alpha, complex<double> *A, int_t ldA, complex<double> *B, int_t ldB, complex<double> beta, complex<double> *C, int_t ldC) { using std::toupper; uplo=toupper(uplo); trans=toupper(trans); if((uplo!='U')&&(uplo!='L')) return -1; else if((trans!='N')&&(trans!='T')) return -2; else if(n<0) return -3; else if(k<0) return -4; else if(ldA<((trans=='N')?n:k)) return -7; else if(ldB<((trans=='N')?n:k)) return -9; else if(ldC<n) return -12; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans); cblas_zsyr2k(CblasColMajor,Uplo,Trans,n,k,&alpha,A,ldA,B,ldB,&beta,C,ldC); return 0; } #endif } #endif
\chapter{Solving for Camera Poses Based on Images} \label{ch:sfm} The ASP tool \texttt{camera\_solve} offers several ways to find the true position of frame camera images that do not come with any attached pose metadata. This can be useful with aerial, hand-held, and historical imagery for which such information may be incomplete or inaccurate. An overview of the tool and examples are provided in this chapter. Reference information for this tool can be found in Appendix \ref{camerasolve}. \section{Camera Solve Overview} The \texttt{camera\_solve} tool is implemented as a Python wrapper around two other tools. The first of these is the the THEIA software library, which is used to generate initial camera position estimates in a local coordinate space. You can learn more about THEIA at \url{http://www.theia-sfm.org/index.html}. The second tool is ASP's own \texttt{bundle\_adjust} tool. The second step improves the solution to account for lens distortion and transforms the solution from local to global coordinates by making use of additional input data. The tool only solves for the extrinsic camera parameters and the user must provide intrinsic camera information. You can use the \texttt{camera\_calibrate} tool (see Appendix \ref{cameracalibrate}) or other camera calibration software to solve for intrinsic parameters if you have access to the camera in question. The camera calibration information must be contained in a .tsai pinhole camera model file and must passed in using the \texttt{-\/-calib-file} option. You can find descriptions of our supported pinhole camera models in Appendix \ref{chapter:pinholemodels}. If no intrinsic camera information is known, it can be guessed by doing some experimentation. This is discussed in section \ref{findintrinsics}. In order to transform the camera models from local to world coordinates, one of three pieces of information may be used. These sources are listed below and described in more detail in the examples that follow: \begin{itemize}{} \item A set of ground control points of the same type used by \texttt{pc\_align}. The easiest way to generate these points is to use the ground control point writer tool available in the \texttt{stereo-gui} tool. \item A set of estimated camera positions (perhaps from a GPS unit) stored in a csv file. \item A DEM which a local point cloud can be registered to using \texttt{pc\_align}. This method can be more accurate if estimated camera positions are also used. The user must perform alignment to a DEM, that step is not handled by \texttt{camera\_solve}. \end{itemize}{} Power users can tweak the individual steps that \texttt{camera\_solve} goes through to optimize their results. This primarily involves setting up a custom flag file for THEIA and/or passing in settings to \texttt{bundle\_adjust}. \section{Example: Apollo 15 Metric Camera} \label{sfm:generic} To demonstrate the ability of the Ames Stereo Pipeline to process a generic frame camera we use images from the Apollo 15 Metric camera. The calibration information for this camera is available online and we have accurate digital terrain models we can use to verify our results. First download a pair of images: \begin{verbatim} > wget http://apollo.sese.asu.edu/data/metric/AS15/png/AS15-M-0414_MED.png > wget http://apollo.sese.asu.edu/data/metric/AS15/png/AS15-M-1134_MED.png \end{verbatim} \begin{figure}[h!] \centering \includegraphics[width=3.0in]{images/examples/pinhole/AS15-M-0414.png} \includegraphics[width=3.0in]{images/examples/pinhole/AS15-M-1134.png} \caption{The two Apollo 15 images.} \label{fig:pinhole-a15-input-images} \end{figure} In order to make the example run faster we use downsampled versions of the original images. The images at those links have already been downsampled by a factor of 4*sqrt(2) from the original images. This means that the effective pixel size has increased from five microns (0.005 millimeters) to 0.028284 millimeters. The next step is to fill out the rest of the pinhole camera model information we need. Using the data sheets available at \url{http://apollo.sese.asu.edu/SUPPORT_DATA/AS15_SIMBAY_SUMMARY.pdf} we can find the lens distortion parameters for metric camera. Looking at the ASP lens distortion models in Appendix \ref{chapter:pinholemodels}, we see that the description matches ASP's Brown-Conrady model. Using the example in the appendix we can fill out the rest of the sensor model file (metric\_model.tsai) so it looks as follows: \begin{verbatim} VERSION_3 fu = 76.080 fv = 76.080 cu = 57.246816 cv = 57.246816 u_direction = 1 0 0 v_direction = 0 1 0 w_direction = 0 0 1 C = 0 0 0 R = 1 0 0 0 1 0 0 0 1 pitch = 0.028284 BrownConrady xp = -0.006 yp = -0.002 k1 = -0.13361854e-5 k2 = 0.52261757e-09 k3 = -0.50728336e-13 p1 = -0.54958195e-06 p2 = -0.46089420e-10 phi = 2.9659070 \end{verbatim} These parameters use units of millimeters so we have to convert the nominal center point of the images from 2024 pixels to units of millimeters. Note that for some older images like these the nominal image center can be checked by looking for some sort of marking around the image borders that indicates where the center should lie. For these pictures there are black triangles at the center positions and they line up nicely with the center of the image. Before we try to solve for the camera positions we can run a simple tool to check the quality of our camera model file: \begin{verbatim} > undistort_image AS15-M-0414_MED.png metric_model.tsai -o corrected_414.tif \end{verbatim} It is difficult to tell if the distortion model is correct by using this tool but it should be obvious if there are any gross errors in your camera model file such as incorrect units or missing parameters. In this case the tool will fail to run or will produce a significantly distorted image. For certain distortion models the \texttt{undistort\_image} tool may take a long time to run. If your input images are not all from the same camera or were scanned such that the center point is not at the same pixel, you can run \texttt{camera\_solve} with one camera model file per input image. To do so pass a space-separated list of files surrounded by quotes to the \texttt{--calib-file} option such as \texttt{--calib-file "c1.tsai c2.tsai c3.tsai"}. If we do not see any obvious problems we can go ahead and run the \texttt{camera\_solve} tool: \begin{verbatim} > camera_solve out/ AS15-M-0414_MED.png AS15-M-1134_MED.png --datum D_MOON \ --calib-file metric_model.tsai \end{verbatim} We should get some camera models in the output folder and see a printout of the final bundle adjustment error among the program output information: \begin{verbatim} Cost: Initial 1.450385e+01 Final 7.461198e+00 Change 7.042649e+00 \end{verbatim} We can't generate a DEM with these local camera models but we can run stereo anyways and look at the intersection error in the fourth band of the \texttt{PC.tif} file. While there are many speckles in this example where stereo correlation failed the mean intersection error is low and we don't see any evidence of lens distortion error. \begin{verbatim} > stereo AS15-M-0414_MED.png AS15-M-1134_MED.png out/AS15-M-0414_MED.png.final.tsai \ out/AS15-M-1134_MED.png.final.tsai -t pinhole s_local/out --corr-timeout 300 \ --erode-max-size 100 > gdalinfo -stats s_local/out-PC.tif ... Band 4 Block=256x256 Type=Float32, ColorInterp=Undefined Minimum=0.000, Maximum=56.845, Mean=0.340, StdDev=3.512 Metadata: STATISTICS_MAXIMUM=56.844654083252 STATISTICS_MEAN=0.33962282293374 STATISTICS_MINIMUM=0 STATISTICS_STDDEV=3.5124044818554 \end{verbatim} The tool \texttt{point2mesh} (section \ref{point2mesh}) can be used to obtain a visualizable mesh from the point cloud. In order to generate a useful DEM, we need to move our cameras from local coordinates to global coordinates. The easiest way to do this is to obtain known ground control points (GCPs) which can be identified in the frame images. This will allow an accurate positioning of the cameras provided that the GCPs and the camera model parameters are accurate. To create GCPs see the instructions for the \texttt{stereo\_gui} tool in appendix \ref{bagcp}. For the Moon there are several ways to get DEMs and in this case we generated GCPs using \texttt{stereo\_gui} and a DEM generated from LRONAC images. After running this command: \begin{verbatim} > camera_solve out_gcp/ AS15-M-0414_MED.png AS15-M-1134_MED.png --datum D_MOON \ --calib-file metric_model.tsai --gcp-file ground_control_points.gcp \end{verbatim} we end up with results that can be compared with the a DEM created from LRONAC images. The stereo results on the Apollo 15 images leave something to be desired but the DEM they produced has been moved to the correct location. You can easily visualize the output camera positions using the \texttt{orbitviz} tool with the \texttt{--load-camera-solve} option as shown below. Green lines between camera positions mean that a sufficient number of matching interest points were found between those two images. \begin{verbatim} > stereo AS15-M-0414_MED.png AS15-M-1134_MED.png out_gcp/AS15-M-0414_MED.png.final.tsai \ out_gcp/AS15-M-1134_MED.png.final.tsai -t nadirpinhole s_global/out --corr-timeout 300 \ --erode-max-size 100 > orbitviz -t nadirpinhole -r moon out_gcp --load-camera-solve \end{verbatim} \begin{figure}[h!] \centering \subfigure[{\tt orbitviz display}]{\includegraphics[width=3.5in]{images/examples/pinhole/a15_orbitviz_display.png}} \hfil \subfigure[{\tt KML Screenshot}]{\includegraphics[width=3in]{images/examples/pinhole/a15_image_diff.png}} \caption{(a) Solved for camera positions plotted using orbitviz. (b) A narrow LRONAC DEM overlaid on the resulting DEM, both colormapped to the same elevation range.} \label{fig:pinhole-a15-result-image} \end{figure} ASP also supports the method of initializing the \texttt{camera\_solve} tool with estimated camera positions. This method will not move the cameras to exactly the right location but it should get them fairly close and at the correct scale, hopefully close enough to be used as-is or to be refined using \texttt{pc\_align} or some other method. To use this method, pass additional bundle adjust parameters to \texttt{camera\_solve} similar to the following line: \begin{verbatim} --bundle-adjust-params '--camera-positions nav.csv \ --csv-format "1:file 12:lat 13:lon 14:height_above_datum" --camera-weight 0.2' \end{verbatim} The nav data file you use must have a column (the "file" column) containing a string that can be matched to the input image files passed to \texttt{camera\_solve}. The tool looks for strings that are fully contained inside one of the image file names, so for example the field value \texttt{2009\_10\_20\_0778} would be matched with the input file \texttt{2009\_10\_20\_0778.JPG}. Chapter \ref{nextsteps} will discuss the \texttt{stereo} program in more detail and the other tools in ASP. \section{Example: IceBridge DMS Camera} \label{sfm:icebridge} The DMS (Digital Mapping System) Camera is a frame camera flown on as part of the NASA IceBridge program to collect digital terrain imagery of polar and Antarctic terrain (\url{http://nsidc.org/icebridge/portal/}). To process this data the steps are very similar to the steps described above for the Apollo Metric camera but there are some aspects which are particular to IceBridge. You can download DMS images from \url{ftp://n5eil01u.ecs.nsidc.org/SAN2/ICEBRIDGE_FTP/IODMS0_DMSraw_v01/}. A list of the available data types can be found at \url{https://nsidc.org/data/icebridge/instr_data_summary.html}. This example uses data from the November 5, 2009 flight over Antarctica. The following camera model (icebridge\_model.tsai) was used (see chapter \ref{chapter:pinholemodels} on camera models): \begin{verbatim} VERSION_3 fu = 28.429 fv = 28.429 cu = 17.9712 cv = 11.9808 u_direction = 1 0 0 v_direction = 0 1 0 w_direction = 0 0 1 C = 0 0 0 R = 1 0 0 0 1 0 0 0 1 pitch = 0.0064 Photometrix xp = 0.004 yp = -0.191 k1 = 1.31024e-04 k2 = -2.05354e-07 k3 = -5.28558e-011 p1 = 7.2359e-006 p2 = 2.2656e-006 b1 = 0.0 b2 = 0.0 \end{verbatim} Note that these images are RGB format which is not supported by all ASP tools. To use the files with ASP, first convert them to single channel images using a tool such as ImageMagick's \texttt{convert}, \texttt{gdal\_translate}, or \texttt{gdal\_edit.py}. Different conversion methods may produce slightly different results depending on the contents of your input images. Some conversion command examples are shown below: \begin{verbatim} convert rgb.jpg -colorspace Gray gray.jpg gdal_calc.py --overwrite --type=Float32 --NoDataValue=-32768 \ -A rgb.tif --A_band=1 -B rgb.tif --B_band=2 -C rgb.tif \ --C_band=3 --outfile=gray.tif --calc="A*0.2989+B*0.5870+C*0.1140" gdal_translate -b 1 rgb.jpg gray.jpg \end{verbatim} In the third command we used \texttt{gdal\_translate} to pick a single band rather than combining the three. Obtaining ground control points for icy locations on Earth can be particularly difficult because they are not well surveyed or because the terrain shifts over time. This may force you to use estimated camera positions to convert the local camera models into global coordinates. To make this easier for IceBridge data sets, ASP provides the \texttt{icebridge\_kmz\_to\_csv} tool (see appendix \ref{icebridgekmztocsv}) which extracts a list of estimated camera positions from the kmz files available for each IceBridge flight at \url{http://asapdata.arc.nasa.gov/dms/missions.html}. Another option which is useful when processing IceBridge data is the \texttt{-\/-position-filter-dist} option for \texttt{bundle\_adjust}. IceBridge data sets contain a large number of images and when processing many at once you can significantly decrease your processing time by using this option to limit interest-point matching to image pairs which are actually close enough to overlap. A good way to determine what distance to use is to load the camera position kmz file from their website into Google Earth and use the ruler tool to measure the distance between a pair of frames that are as far apart as you want to match. Commands using these options may look like this: \begin{verbatim} icebridge_kmz_to_csv 1000123_DMS_Frame_Events.kmz camera_positions.csv camera_solve out 2009_11_05_00667.JPG 2009_11_05_00668.JPG \ 2009_11_05_00669.JPG 2009_11_05_00670.JPG 2009_11_05_02947.JPG 2009_11_05_02948.JPG \ 2009_11_05_02949.JPG 2009_11_05_02950.JPG 2009_11_05_01381.JPG 2009_11_05_01382.JPG \ --datum WGS84 --calib-file icebridge_model.tsai \ --bundle-adjust-params '--camera-positions camera_positions.csv \ --csv-format "1:file 2:lon 3:lat 4:height_above_datum" --position-filter-dist 2000' orbitviz out --load-camera-solve --hide-labels -r wgs84 -t nadirpinhole \end{verbatim} Alternatively, the \texttt{camera\_solve} executable can be bypassed altogether. If a given image has already an orthoimage associated with it (check the IceBridge portal page), that provides enough information to guess an initial position of the camera, using the \texttt{ortho2pinhole} tool. Later, the obtained cameras can be bundle-adjusted. Here is how this tool can be used, on grayscale images: \begin{verbatim} ortho2pinhole raw_image.tif ortho_image.tif icebridge_model.tsai output_pinhole.tsai \end{verbatim} \begin{figure}[h!] \centering \subfigure[]{\includegraphics[width=3.5in]{images/examples/pinhole/icebridge_frame_dists.png}} \hfil \subfigure[]{\includegraphics[width=3in]{images/examples/pinhole/icebridge_orbitviz_display.png}} \caption{(a) Measuring the distance between estimated frame locations using Google Earth and an IceBridge kmz file. The kmz file is from the IceBridge website with no modifications. Using a position filter distance of 2000 meters will mostly limit image IP matching in this case to each image's immediate "neighbors". (b) Display of \texttt{camera\_solve} results for ten IceBridge images using \texttt{orbitviz}.} \label{fig:pinhole-icebridge-camera-results} \end{figure} Some IceBridge flights contain data from the Land, Vegetation, and Ice Sensor (LVIS) lidar which can be used to register DEMs created using DMS imagery. LVIS data can be downloaded at \url{ftp://n5eil01u.ecs.nsidc.org/SAN2/ICEBRIDGE/ILVIS2.001/}. The lidar data comes in plain text files that \texttt{pc\_align} and \texttt{point2dem} can parse using the following option: \begin{verbatim} --csv-format "5:lat 4:lon 6:height_above_datum" \end{verbatim} ASP provides the \texttt{lvis2kml} tool to help visualize the coverage and terrain contained in LVIS files, see Appendix \ref{lvis2kml} for details. The LVIS lidar coverage is sparse compared to the image coverage and you will have difficulty getting a good registration unless the region has terrain features such as hills or you are registering very large point clouds that overlap with the lidar coverage across a wide area. Otherwise \texttt{pc\_align} will simply slide the flat terrain to an incorrect location to produce a low-error fit with the narrow lidar tracks. This test case was specifically chosen to provide strong terrain features to make alignment more accurate but \texttt{pc\_align} still failed to produce a good fit until the lidar point cloud was converted into a smoothed DEM. \begin{verbatim} stereo 2009_11_05_02948.JPG 2009_11_05_02949.JPG out/2009_11_05_02948.JPG.final.tsai \ out/2009_11_05_02949.JPG.final.tsai st_run/out -t nadirpinhole point2dem ILVIS2_AQ2009_1105_R1408_055812.TXT --datum WGS_1984 \ --t_srs "+proj=stere +lat_0=-90 +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs" \ --csv-format "5:lat 4:lon 6:height_above_datum" --tr 30 \ --search-radius-factor 2.0 -o lvis pc_align --max-displacement 1000 lvis-DEM.tif st_run/out-PC.tif -o align_run/out \ --save-transformed-source-points --datum wgs84 --outlier-ratio 0.55 point2dem align_run/out-trans_source.tif --datum WGS_1984 \ --t_srs "+proj=stere +lat_0=-90 +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs" colormap align_run_big/out-trans_source-DEM.tif --min 200 --max 1500 colormap lvis-DEM.tif --min 200 --max 1500 image2qtree lvis-DEM_CMAP.tif image2qtree align_run_big/out-trans_source-DEM_CMAP.tif \end{verbatim} \begin{figure}[h!] \centering \includegraphics[width=5.5in]{images/examples/pinhole/icebridge_dem_overlay.png} \caption{LVIS lidar DEM overlaid on the ASP created DEM, both colormapped to the same elevation range. The ASP DEM could be improved but the registration is accurate. Notice how narrow the LVIS lidar coverage is compared to the field of view of the camera. You may want to experiment using the SGM algorithm to improve the coverage.} \label{fig:pinhole-icebridge-orbitviz} \end{figure} Other IceBridge flights contain data from the Airborne Topographic Mapper (ATM) lidar sensor. Data from this sensor comes packed in one of several formats (variants of .qi or .h5) so ASP provides the \texttt{extract\_icebridge\_ATM\_points} tool to convert them into plain text files, which later can be read into other ASP tools using the formatting: \begin{verbatim} --csv-format "1:lat 2:lon 3:height_above_datum" \end{verbatim} To run the tool, just pass in the name of the input file as an argument and a new file with a csv extension will be created in the same directory. Using the ATM sensor data is similar to using the LVIS sensor data. For some IceBridge flights, lidar-aligned DEM files generated from the DMS image files are available, see the web page here: \url{http://nsidc.org/data/iodms3} These files are improperly formatted and cannot be used by ASP as is. To correct them, run the \texttt{correct\_icebridge\_l3\_dem} tool as follows: \begin{verbatim} correct_icebridge_l3_dem IODMS3_20120315_21152106_07371_DEM.tif fixed_dem.tif 1 \end{verbatim} The third argument should be 1 if the DEM is in the northern hemisphere and 0 otherwise. The corrected DEM files can be used with ASP like any other DEM file. Chapter \ref{nextsteps} will discuss the \texttt{stereo} program in more detail and the other tools in ASP. \section{Solving For Intrinsic Camera Parameters} \label{findintrinsics} If nothing is known about the intrinsic camera parameters, it may be possible to guess them with some experimentation. One can assume that the distortion is non-existent, and that the optical center is at the image center, which makes it possible to compute $cu$ and $cv$. The pitch can be set to some small number, say $10^{-3}$ or $10^{-4}.$ The focal length can be initialized to equal $cu$ or a multiple of it. Then \texttt{camera\_solve} can be invoked, followed by \texttt{stereo}, \texttt{point2mesh}, and \texttt{point2dem -\/-errorimage}. If, at least towards the center of the image, things are not exploding, we are on a good track. Later, the camera parameters, especially the focal length, can be modified manually, and instead of using \texttt{camera\_solve} again, just \texttt{bundle\_adjust} can be called using the camera models found earlier, with the options to float some of the intrinsics, that is using \texttt{-\/-solve-intrinsics} and \texttt{-\/-intrinsics-to-float}. If the overall results look good, but the intersection error after invoking \texttt{point2dem} around the image corners looks large, it is time to use some distortion model and float it, again using \texttt{bundle\_adjust}. Sometimes if invoking this tool over many iterations the optical center and focal length may drift, and hence it may be helpful to have them fixed while solving for distortion. If a pre-existing DEM is available, the tool \texttt{geodiff} can be used to compare it with what ASP is creating.
A new HMS Campbeltown , a Type 22 Frigate , was launched on 7 October 1987 . She carried the ship 's bell from the first Campbeltown which was rescued during the raid and had been presented to the town of Campbelltown , Pennsylvania at the end of the Second World War . In 1988 the people of Campbelltown voted to lend the bell to the new ship for as long as she remained in Royal Navy service . The bell was returned to the town on 21 June 2011 when HMS Campbeltown was decommissioned .
State Before: ι : Type ?u.22707 α : Type u_1 inst✝¹ : Preorder α inst✝ : LocallyFiniteOrder α a a₁ a₂ b b₁ b₂ c x : α h : b₁ < b₂ ⊢ Ioc a b₁ ⊆ Ioo a b₂ State After: ι : Type ?u.22707 α : Type u_1 inst✝¹ : Preorder α inst✝ : LocallyFiniteOrder α a a₁ a₂ b b₁ b₂ c x : α h : b₁ < b₂ ⊢ Set.Ioc a b₁ ⊆ Set.Ioo a b₂ Tactic: rw [← coe_subset, coe_Ioc, coe_Ioo] State Before: ι : Type ?u.22707 α : Type u_1 inst✝¹ : Preorder α inst✝ : LocallyFiniteOrder α a a₁ a₂ b b₁ b₂ c x : α h : b₁ < b₂ ⊢ Set.Ioc a b₁ ⊆ Set.Ioo a b₂ State After: no goals Tactic: exact Set.Ioc_subset_Ioo_right h
(* Title: Countable Ordinals Author: Brian Huffman, 2005 Maintainer: Brian Huffman <brianh at cse.ogi.edu> *) section \<open>Ordinal Induction\<close> theory OrdinalInduct imports OrdinalDef begin subsection \<open>Zero and successor ordinals\<close> definition oSuc :: "ordinal \<Rightarrow> ordinal" where "oSuc x = oStrictLimit (\<lambda>n. x)" lemma less_oSuc[iff]: "x < oSuc x" by (metis oStrictLimit_ub oSuc_def) lemma oSuc_leI: "x < y \<Longrightarrow> oSuc x \<le> y" by (simp add: oStrictLimit_lub oSuc_def) instantiation ordinal :: "{zero, one}" begin definition ordinal_zero_def: "(0::ordinal) = oZero" definition ordinal_one_def [simp]: "(1::ordinal) = oSuc 0" instance .. end subsubsection \<open>Derived properties of 0 and oSuc\<close> lemma less_oSuc_eq_le: "(x < oSuc y) = (x \<le> y)" by (metis dual_order.strict_trans1 less_oSuc linorder_not_le oSuc_leI) lemma ordinal_0_le [iff]: "0 \<le> (x::ordinal)" by (simp add: oZero_least ordinal_zero_def) lemma ordinal_not_less_0 [iff]: "\<not> (x::ordinal) < 0" by (simp add: linorder_not_less) lemma ordinal_le_0 [iff]: "(x \<le> 0) = (x = (0::ordinal))" by (simp add: order_le_less) lemma ordinal_neq_0 [iff]: "(x \<noteq> 0) = (0 < (x::ordinal))" by (simp add: order_less_le) lemma ordinal_not_0_less [iff]: "(\<not> 0 < x) = (x = (0::ordinal))" by (simp add: linorder_not_less) lemma zero_less_oSuc [iff]: "0 < oSuc x" by (rule order_le_less_trans, rule ordinal_0_le, rule less_oSuc) lemma oSuc_not_0 [iff]: "oSuc x \<noteq> 0" by simp lemma less_oSuc0 [iff]: "(x < oSuc 0) = (x = 0)" by (simp add: less_oSuc_eq_le) lemma oSuc_less_oSuc [iff]: "(oSuc x < oSuc y) = (x < y)" by (simp add: less_oSuc_eq_le oSuc_le_eq_less) lemma oSuc_eq_oSuc [iff]: "(oSuc x = oSuc y) = (x = y)" by (metis less_oSuc less_oSuc_eq_le order_antisym) lemma oSuc_le_oSuc [iff]: "(oSuc x \<le> oSuc y) = (x \<le> y)" by (simp add: order_le_less) lemma le_oSucE: "\<lbrakk>x \<le> oSuc y; x \<le> y \<Longrightarrow> R; x = oSuc y \<Longrightarrow> R\<rbrakk> \<Longrightarrow> R" by (auto simp add: order_le_less less_oSuc_eq_le) lemma less_oSucE: "\<lbrakk>x < oSuc y; x < y \<Longrightarrow> P; x = y \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P" by (auto simp add: less_oSuc_eq_le order_le_less) subsection \<open>Strict monotonicity\<close> locale strict_mono = fixes f assumes strict_mono: "A < B \<Longrightarrow> f A < f B" lemmas strict_monoI = strict_mono.intro and strict_monoD = strict_mono.strict_mono lemma strict_mono_natI: fixes f :: "nat \<Rightarrow> 'a::order" shows "(\<And>n. f n < f (Suc n)) \<Longrightarrow> strict_mono f" using OrdinalInduct.strict_monoI lift_Suc_mono_less by blast lemma mono_natI: fixes f :: "nat \<Rightarrow> 'a::order" shows "(\<And>n. f n \<le> f (Suc n)) \<Longrightarrow> mono f" by (simp add: mono_iff_le_Suc) lemma strict_mono_mono: fixes f :: "'a::order \<Rightarrow> 'b::order" shows "strict_mono f \<Longrightarrow> mono f" by (auto intro!: monoI simp add: order_le_less strict_monoD) lemma strict_mono_monoD: fixes f :: "'a::order \<Rightarrow> 'b::order" shows "\<lbrakk>strict_mono f; A \<le> B\<rbrakk> \<Longrightarrow> f A \<le> f B" by (rule monoD[OF strict_mono_mono]) lemma strict_mono_cancel_eq: fixes f :: "'a::linorder \<Rightarrow> 'b::linorder" shows "strict_mono f \<Longrightarrow> (f x = f y) = (x = y)" by (metis OrdinalInduct.strict_monoD not_less_iff_gr_or_eq) lemma strict_mono_cancel_less: fixes f :: "'a::linorder \<Rightarrow> 'b::linorder" shows "strict_mono f \<Longrightarrow> (f x < f y) = (x < y)" using OrdinalInduct.strict_monoD linorder_neq_iff by fastforce lemma strict_mono_cancel_le: fixes f :: "'a::linorder \<Rightarrow> 'b::linorder" shows "strict_mono f \<Longrightarrow> (f x \<le> f y) = (x \<le> y)" by (meson linorder_not_less strict_mono_cancel_less) subsection \<open>Limit ordinals\<close> definition oLimit :: "(nat \<Rightarrow> ordinal) \<Rightarrow> ordinal" where "oLimit f = (LEAST k. \<forall>n. f n \<le> k)" lemma oLimit_leI: "\<forall>n. f n \<le> x \<Longrightarrow> oLimit f \<le> x" by (simp add: oLimit_def wellorder_Least_lemma(2)) lemma le_oLimit [iff]: "f n \<le> oLimit f" by (smt (verit, best) LeastI_ex leD oLimit_def oStrictLimit_ub ordinal_linear) lemma le_oLimitI: "x \<le> f n \<Longrightarrow> x \<le> oLimit f" by (erule order_trans, rule le_oLimit) lemma less_oLimitI: "x < f n \<Longrightarrow> x < oLimit f" by (erule order_less_le_trans, rule le_oLimit) lemma less_oLimitD: "x < oLimit f \<Longrightarrow> \<exists>n. x < f n" by (meson linorder_not_le oLimit_leI) lemma less_oLimitE: "\<lbrakk>x < oLimit f; \<And>n. x < f n \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P" by (auto dest: less_oLimitD) lemma le_oLimitE: "\<lbrakk>x \<le> oLimit f; \<And>n. x \<le> f n \<Longrightarrow> R; x = oLimit f \<Longrightarrow> R\<rbrakk> \<Longrightarrow> R" by (auto simp add: order_le_less dest: less_oLimitD) lemma oLimit_const [simp]: "oLimit (\<lambda>n. x) = x" by (meson dual_order.refl le_oLimit oLimit_leI order_antisym) lemma strict_mono_less_oLimit: "strict_mono f \<Longrightarrow> f n < oLimit f" by (meson OrdinalInduct.strict_monoD lessI less_oLimitI) lemma oLimit_eqI: "\<lbrakk>\<And>n. \<exists>m. f n \<le> g m; \<And>n. \<exists>m. g n \<le> f m\<rbrakk> \<Longrightarrow> oLimit f = oLimit g" by (meson le_oLimitI nle_le oLimit_leI) lemma oLimit_Suc: "f 0 < oLimit f \<Longrightarrow> oLimit (\<lambda>n. f (Suc n)) = oLimit f" by (smt (verit, ccfv_SIG) linorder_not_le nle_le oLimit_eqI oLimit_leI old.nat.exhaust) lemma oLimit_shift: "\<forall>n. f n < oLimit f \<Longrightarrow> oLimit (\<lambda>n. f (n + k)) = oLimit f" apply (induct_tac k, simp) by (metis (no_types, lifting) add_Suc_shift leD le_oLimit less_oLimitD not_less_iff_gr_or_eq oLimit_Suc) lemma oLimit_shift_mono: "mono f \<Longrightarrow> oLimit (\<lambda>n. f (n + k)) = oLimit f" by (meson le_add1 monoD oLimit_eqI) text "limit ordinal predicate" definition limit_ordinal :: "ordinal \<Rightarrow> bool" where "limit_ordinal x \<longleftrightarrow> (x \<noteq> 0) \<and> (\<forall>y. x \<noteq> oSuc y)" lemma limit_ordinal_not_0 [simp]: "\<not> limit_ordinal 0" by (simp add: limit_ordinal_def) lemma zero_less_limit_ordinal [simp]: "limit_ordinal x \<Longrightarrow> 0 < x" by (simp add: limit_ordinal_def) lemma limit_ordinal_not_oSuc [simp]: "\<not> limit_ordinal (oSuc p)" by (simp add: limit_ordinal_def) lemma oSuc_less_limit_ordinal: "limit_ordinal x \<Longrightarrow> (oSuc w < x) = (w < x)" by (metis limit_ordinal_not_oSuc oSuc_le_eq_less order_le_less) lemma limit_ordinal_oLimitI: "\<forall>n. f n < oLimit f \<Longrightarrow> limit_ordinal (oLimit f)" by (metis less_oLimitD less_oSuc less_oSucE limit_ordinal_def order_less_imp_triv ordinal_neq_0) lemma strict_mono_limit_ordinal: "strict_mono f \<Longrightarrow> limit_ordinal (oLimit f)" by (simp add: limit_ordinal_oLimitI strict_mono_less_oLimit) lemma limit_ordinalI: "\<lbrakk>0 < z; \<forall>x<z. oSuc x < z\<rbrakk> \<Longrightarrow> limit_ordinal z" using limit_ordinal_def by blast subsubsection \<open>Making strict monotonic sequences\<close> primrec make_mono :: "(nat \<Rightarrow> ordinal) \<Rightarrow> nat \<Rightarrow> nat" where "make_mono f 0 = 0" | "make_mono f (Suc n) = (LEAST x. f (make_mono f n) < f x)" lemma strict_mono_f_make_mono: "\<forall>n. f n < oLimit f \<Longrightarrow> strict_mono (\<lambda>n. f (make_mono f n))" by (rule strict_mono_natI, erule f_make_mono_less) lemma le_f_make_mono: "\<lbrakk>\<forall>n. f n < oLimit f; m \<le> make_mono f n\<rbrakk> \<Longrightarrow> f m \<le> f (make_mono f n)" apply (auto simp add: order_le_less) apply (case_tac n, simp_all) by (metis LeastI less_oLimitD linorder_le_less_linear not_less_Least order_le_less_trans) lemma make_mono_less: "\<forall>n. f n < oLimit f \<Longrightarrow> make_mono f n < make_mono f (Suc n)" by (meson f_make_mono_less le_f_make_mono linorder_not_less) declare make_mono.simps [simp del] lemma oLimit_make_mono_eq: assumes "\<forall>n. f n < oLimit f" shows "oLimit (\<lambda>n. f (make_mono f n)) = oLimit f" proof - have "k \<le> make_mono f k" for k by (induction k) (auto simp: Suc_leI assms make_mono_less order_le_less_trans) then show ?thesis by (meson assms le_f_make_mono oLimit_eqI) qed subsection \<open>Induction principle for ordinals\<close> lemma oLimit_le_oStrictLimit: "oLimit f \<le> oStrictLimit f" by (simp add: oLimit_leI oStrictLimit_ub order_less_imp_le) lemma oLimit_induct [case_names zero suc lim]: assumes zero: "P 0" and suc: "\<And>x. P x \<Longrightarrow> P (oSuc x)" and lim: "\<And>f. \<lbrakk>strict_mono f; \<forall>n. P (f n)\<rbrakk> \<Longrightarrow> P (oLimit f)" shows "P a" apply (rule oStrictLimit_induct) apply (rule zero[unfolded ordinal_zero_def]) apply (cut_tac f=f in oLimit_le_oStrictLimit) apply (simp add: order_le_less, erule disjE) apply (metis dual_order.order_iff_strict leD le_oLimit less_oStrictLimitD oSuc_le_eq_less suc) by (metis lim oLimit_make_mono_eq oStrictLimit_ub strict_mono_f_make_mono) lemma ordinal_cases [case_names zero suc lim]: assumes zero: "a = 0 \<Longrightarrow> P" and suc: "\<And>x. a = oSuc x \<Longrightarrow> P" and lim: "\<And>f. \<lbrakk>strict_mono f; a = oLimit f\<rbrakk> \<Longrightarrow> P" shows "P" apply (subgoal_tac "\<forall>x. a = x \<longrightarrow> P", force) apply (rule allI) apply (rule_tac a=x in oLimit_induct) apply (rule impI, erule zero) apply (rule impI, erule suc) apply (rule impI, erule lim, assumption) done end
module EqProof { A : Set } ( _==_ : A -> A -> Set ) (refl : {x : A} -> x == x) (trans : {x y z : A} -> x == y -> y == z -> x == z) where infix 2 eqProof>_ infixl 2 _===_ infix 3 _by_ eqProof>_ : (x : A) -> x == x eqProof> x = refl _===_ : {x y z : A} -> x == y -> y == z -> x == z xy === yz = trans xy yz _by_ : {x : A}(y : A) -> x == y -> x == y y by eq = eq
function subplot_stack(x, ys, str_title, colors) %function subplot_stack(x, ys, str_title, colors) % a tight stack of subplots to show L signal components % in % x [N,1] % ys [N,L] or ? if nargin == 1 && streq(x, 'test'), subplot_stack_test, return, end if nargin < 2, ir_usage, end if ~isvar('colors') || isempty(colors), colors = {'c', 'y'}; end if ~isvar('str_title') || isempty(str_title) str_title = ''; end if ~iscell(ys) ys = {ys}; end L = size(ys{1},2); apos = get(gca, 'position'); % current axes position for ll=1:L % pos = [0.1 0.1+0.8/L*(L-ll) 0.8 0.8/L]; pos = [apos(1) apos(2)+apos(4)/L*(L-ll) apos(3) apos(4)/L]; subplot('position', pos) % l b w h for ip=1:length(ys) plot( x, real(ys{ip}(:,ll)), colors{1+2*(ip-1)}, ... x, imag(ys{ip}(:,ll)), colors{2+2*(ip-1)}) if ip == 1, hold on, end end hold off axis tight ytick(0), set(gca, 'yticklabel', '') fontsize = 10; fontweight = 'normal'; texts(1.02, 0.8, sprintf('%d.', ll), ... 'fontsize', fontsize, 'fontweight', fontweight) if ll==1, title(str_title), end if ll<L xtick off end end function subplot_stack_test x = linspace(0,1,101)'; y = exp(2i*pi*x*[1:5]); if im clf, subplot(121) subplot_stack(x, y) end
(*<*) theory HOTL imports Main begin (*An Embedding of Higher-Order Temporal Logic (HOTL) in HOL *) (*>*) subsection \<open>HOTL - Higher order temporal logic \label{subsec:HOTL}\<close> text\<open> This section introduces the logical operators and data types we will be working with in \hyperref[subsec:Simulation]{Simulation}. \<close> subsubsection\<open>Data types \label{subsubsec:types}\<close> text\<open> There are two new data types @{text "g"} @{text "time"} and one derived data type @{text "\<sigma>"}. \<close> text\<open>% \noindent Type @{text "g"} is for governmental institutions, with @{text "Congress"} being Congress, @{text "P"} being the President and @{text "Courts"} being the Supreme Court as well as other courts set up by Congress. The legislative, executive and judicial powers shall later be bestowed upon these three instances of @{text "g"}. We use @{text "Courts"} rather than just the Supreme Court since Art. III, \S 1. states that the ``judicial Power [...] shall be vested in one supreme Court, and in such inferior Courts as the Congress may [...] ordain and establish." \<close> datatype g = Congress | P | Courts text\<open> \noindent There are four instances of time: @{text "t\<^sub>1"}-@{text "t\<^sub>3"} as in \ref{subsubsec:time} and @{text "t\<^sub>e"}, the instance that marks the end of time. At @{text "t\<^sub>1"} the 1947 version of the Constitution is valid. @{text "t\<^sub>2"} holds the version with an amended Art. V that allows for amendments that do not maintain states' suffrage and @{text "t\<^sub>3"} with the Constitution upholding dictatorship. Note that there is a fourth instance @{text "t\<^sub>e"}. We need this for technical reasons. Since we want to use an operator @{text "\<^bold>X"} that carries a formula from one instance to its successor, it is convenient to have a successor for each instance of time used. Unless we define a circular successor relation we need a further instance of time that can be the successor of @{text "t\<^sub>3"} to avoid inconsistencies. We shall point out where @{text "t\<^sub>e"} prevents inconsistencies when it becomes relevant below. \<close> datatype time = t\<^sub>1 |t\<^sub>2 |t\<^sub>3 |t\<^sub>e text\<open> \noindent Since we will only consider a formula's validity at a certain point in time we need a time dependant type for them, as well as operators lifted to that type. See the following definition of a time dependant formula's type. We will use it to explain what a lifted operator is and as a basis for our lifted operators.\<close> type_synonym \<sigma>="(time\<Rightarrow>bool)"(*Type of time dependant formulas *) text\<open>\noindent % Assume you have operator \[\text{ @{text "op::'a\<Rightarrow>bool"}}\] where @{text "'a"} is an arbitrary type and @{text "bool"} is Isabelle's version of the boolean type. A lifted version \[\text{@{text "op\<^sub>l::'a\<Rightarrow>\<sigma>"}}\] of @{text "op"} would be an operator such that for any argument @{text "arg::'a"} \[\text{@{text "op\<^sub>l arg \<equiv> \<Phi>(op)(arg)"}}\] with @{text "\<Phi>::('a\<Rightarrow>bool)\<Rightarrow>'a\<Rightarrow>\<sigma>"} being a suitable function to translate the notion of what @{text "op"} does to a notion of what it does at a particular instance of time. What this function @{text "\<Phi>"} looks like depends on @{text "op"}. See below how it is done for the operators we require. \<close> (*Lifted HOTL connectives: they operate on time dependant formulas(truth sets).*) subsubsection\<open>Lifted operators \label{subsubsec:op}\<close> text\<open> \noindent The following are lifted versions for standard logical operators @{text "{\<not>,\<and>,\<or>,\<longrightarrow>.\<longleftrightarrow>}"}, as well as for @{text "{=,!=}"} and for quantifiers @{text "{\<forall>,\<exists>}"}. Observe that the quantifiers lifted may each only be used for one type of argument. We shall go into detail about polymorphism in \ref{subsubsec:Polym}. Note also that they need an additional binding for the form we are used to. This is because the initial definition actually refers to operator $\Pi_{(\alpha \Rightarrow bool)\Rightarrow bool}$ which allows us to define a lifted @{text "\<forall>"} using only lambda abstraction% \footnote{S. \cite{sep-type-theory-church},``1.1 Fundamental Ideas"}. \<close> definition tneg :: "\<sigma>\<Rightarrow>\<sigma>" ("\<^bold>\<not>_"[52]53) where "\<^bold>\<not>\<phi> \<equiv> \<lambda>t. \<not>\<phi>(t)" definition tand :: "\<sigma>\<Rightarrow>\<sigma>\<Rightarrow>\<sigma>" (infixr"\<^bold>\<and>"51) where "\<phi>\<^bold>\<and>\<psi> \<equiv> \<lambda>t. \<phi>(t)\<and>\<psi>(t)" definition tor :: "\<sigma>\<Rightarrow>\<sigma>\<Rightarrow>\<sigma>" (infixr"\<^bold>\<or>"50) where "\<phi>\<^bold>\<or>\<psi> \<equiv> \<lambda>t. \<phi>(t)\<or>\<psi>(t)" definition timp :: "\<sigma>\<Rightarrow>\<sigma>\<Rightarrow>\<sigma>" (infixr"\<^bold>\<longrightarrow>"49) where "\<phi>\<^bold>\<longrightarrow> \<psi> \<equiv> \<lambda>t. \<phi>(t)\<longrightarrow>\<psi>(t)" definition tequ :: "\<sigma>\<Rightarrow>\<sigma>\<Rightarrow>\<sigma>" (infixr"\<^bold>\<longleftrightarrow>"48) where "\<phi>\<^bold>\<longleftrightarrow>\<psi> \<equiv> \<lambda>t. \<phi>(t)\<longleftrightarrow>\<psi>(t)" (**) definition teq :: "g\<Rightarrow>g\<Rightarrow>\<sigma>" (infixr"\<^bold>="40) where "\<phi>\<^bold>=\<psi> \<equiv> \<lambda>t. \<phi>=\<psi>" definition tneq :: "g\<Rightarrow>g\<Rightarrow>\<sigma>" (infixr"\<^bold>!="40) where "\<phi>\<^bold>!=\<psi> \<equiv> \<lambda>t.\<not>(\<phi>=\<psi>)" (**) definition tall_g :: "(g\<Rightarrow>\<sigma>)\<Rightarrow>\<sigma>" ("\<^bold>\<forall>\<^sub>g") where "\<^bold>\<forall>\<^sub>g\<Phi> \<equiv> \<lambda>t.\<forall>x. \<Phi>(x)(t)" definition tallB_g:: "(g\<Rightarrow>\<sigma>)\<Rightarrow>\<sigma>" (binder"\<^bold>\<forall>\<^sub>g"[8]9) where "\<^bold>\<forall>\<^sub>gx. \<phi>(x) \<equiv> \<^bold>\<forall>\<^sub>g\<phi>" (**) definition texi_g :: "(g\<Rightarrow>\<sigma>)\<Rightarrow>\<sigma>" ("\<^bold>\<exists>\<^sub>g") where "\<^bold>\<exists>\<^sub>g\<Phi> \<equiv> \<lambda>t.\<exists>x. \<Phi>(x)(t)" definition texiB_g:: "(g\<Rightarrow>\<sigma>)\<Rightarrow>\<sigma>" (binder"\<^bold>\<exists>\<^sub>g"[8]9) where "\<^bold>\<exists>\<^sub>gx. \<phi>(x) \<equiv> \<^bold>\<exists>\<^sub>g\<phi>" (**) definition tall_s :: "(\<sigma>\<Rightarrow>\<sigma>)\<Rightarrow>\<sigma>" ("\<^bold>\<forall>\<^sub>\<sigma>") where "\<^bold>\<forall>\<^sub>\<sigma>\<Phi> \<equiv> \<lambda>t.\<forall>\<phi>. \<Phi>(\<phi>)(t)" definition tallB_s:: "(\<sigma>\<Rightarrow>\<sigma>)\<Rightarrow>\<sigma>" (binder"\<^bold>\<forall>\<^sub>\<sigma>"[8]9) where "\<^bold>\<forall>\<^sub>\<sigma>\<phi>. \<Phi>(\<phi>) \<equiv> \<^bold>\<forall>\<^sub>\<sigma>\<Phi>" (**) definition texi_s :: "(\<sigma>\<Rightarrow>\<sigma>)\<Rightarrow>\<sigma>" ("\<^bold>\<exists>\<^sub>\<sigma>") where "\<^bold>\<exists>\<^sub>\<sigma>\<Phi> \<equiv> \<lambda>t. \<exists>\<phi>. \<Phi>(\<phi>)(t)" definition texiB_s:: "(\<sigma>\<Rightarrow>\<sigma>)\<Rightarrow>\<sigma>" (binder"\<^bold>\<exists>\<^sub>\<sigma>"[8]9) where "\<^bold>\<exists>\<^sub>\<sigma>\<phi>. \<Phi>(\<phi>) \<equiv> \<^bold>\<exists>\<^sub>\<sigma>\<Phi>" text\<open> \noindent The last operator we want to introduce is @{text "\<^bold>X"}. This requires a precedence relation. To stress the fact that we are talking about a \textit{future} instance of time when using @{text "\<^bold>X"} we call the relation @{text "succ"} for successor, rather than @{text "pred"} for predecessor. \<close> consts succ::"time\<Rightarrow>time\<Rightarrow>bool" axiomatization where t1_s_t2: "succ t\<^sub>1 t\<^sub>2" and t2_s_t3: "succ t\<^sub>2 t\<^sub>3" and t3_s_te: "succ t\<^sub>3 t\<^sub>e" and te_s_te: "succ t\<^sub>e t\<^sub>e" and Nt1_s_t1: "\<not>(succ t\<^sub>1 t\<^sub>1)" and Nt1_s_t3: "\<not>(succ t\<^sub>1 t\<^sub>3)" and Nt1_s_te: "\<not>(succ t\<^sub>1 t\<^sub>e)" and Nt2_s_t1: "\<not>(succ t\<^sub>2 t\<^sub>1)" and Nt2_s_t2: "\<not>(succ t\<^sub>2 t\<^sub>2)" and Nt2_s_te: "\<not>(succ t\<^sub>2 t\<^sub>e)" and Nt3_s_t1: "\<not>(succ t\<^sub>3 t\<^sub>1)" and Nt3_s_t2: "\<not>(succ t\<^sub>3 t\<^sub>2)" and Nt3_s_t3: "\<not>(succ t\<^sub>3 t\<^sub>3)" and Nte_s_t1: "\<not>(succ t\<^sub>e t\<^sub>1)" and Nte_s_t2: "\<not>(succ t\<^sub>e t\<^sub>2)" and Nte_s_t3: "\<not>(succ t\<^sub>e t\<^sub>3)" text\<open> \noindent So in Kripke semantics% \footnote{S. \cite{sep-logic-modal}} a visualisation of the instances with @{text "succ"} as accessibility relation would look as follows: \begin{center} \begin{tikzpicture}[scale=0.2] \tikzstyle{every node}+=[inner sep=0pt] \draw [black] (11.3,-8.6) circle (3); \draw (11.3,-8.6) node {$t_1$}; \draw [black] (23.9,-8.6) circle (3); \draw (23.9,-8.6) node {$t_2$}; \draw [black] (36.7,-8.6) circle (3); \draw (36.7,-8.6) node {$t_3$}; \draw [black] (48.9,-8.6) circle (3); \draw (48.9,-8.6) node {$t_e$}; \draw [black] (39.7,-8.6) -- (45.9,-8.6); \fill [black] (45.9,-8.6) -- (45.1,-8.1) -- (45.1,-9.1); \draw [black] (51.407,-6.973) arc (150.70984:-137.29016:2.25); \fill [black] (51.72,-9.6) -- (52.17,-10.43) -- (52.66,-9.56); \draw [black] (26.9,-8.6) -- (33.7,-8.6); \fill [black] (33.7,-8.6) -- (32.9,-8.1) -- (32.9,-9.1); \draw [black] (14.3,-8.6) -- (20.9,-8.6); \fill [black] (20.9,-8.6) -- (20.1,-8.1) -- (20.1,-9.1); \end{tikzpicture} \end{center}\<close> text\<open>\noindent % Based on @{text "succ"} we can then define @{text "\<^bold>X"}.\<close> definition tnext :: "\<sigma>\<Rightarrow>\<sigma>" ("\<^bold>X_") where "\<^bold>X\<phi> \<equiv> (\<lambda>t. \<forall>t'. ((succ t t') \<longrightarrow> \<phi> t'))" (*Global and local validity of lifted formulas*) subsubsection\<open>Validity \label{subsubsec:val}\<close> text\<open>\noindent % Lastly, we want to define a notion of \textit{validity}. We distinguish between global and local validity. A formula shall be globally valid when it is valid independently of the the current time. This is useful for universally valid definitions such as what we mean by \textit{dictatorship}. A formula shall be locally valid for a specific @{text "t"} if it is valid at that instance of time. \<close> definition global_valid :: "\<sigma> \<Rightarrow> bool" ("\<lfloor>_\<rfloor>"[7]8) where "\<lfloor>\<phi>\<rfloor> \<equiv> \<forall>t. \<phi> t" definition local_valid :: "\<sigma>\<Rightarrow>time \<Rightarrow> bool" ("\<lfloor>_\<rfloor>\<^sub>_"[9]10) where "\<lfloor>\<phi>\<rfloor>\<^sub>t \<equiv> \<phi> t" text\<open>\noindent % We conclude this section with checking satisfiability and enlisting all definitions in @{text "Defs"} so we may access them conveniently in proofs later on. Lemmas used to test the modelling begin with a @{text "T"} to signify that they are testing lemmas. The check for satisfiability is one such testing lemma. \<close> lemma T_basic_sat_HOTL:"True" nitpick[satisfy,user_axioms,show_all]oops (* Introducing "Defs" as the set of the above definitions; useful for convenient unfolding.*) named_theorems Defs declare tneg_def[Defs] tand_def[Defs] tor_def[Defs] timp_def[Defs] tequ_def[Defs] teq_def[Defs] tneq_def[Defs] tall_g_def[Defs] tallB_g_def[Defs] texi_g_def[Defs] texiB_g_def[Defs] tall_s_def[Defs] tallB_s_def[Defs] texi_s_def[Defs] texiB_s_def[Defs] tnext_def[Defs] global_valid_def[Defs] local_valid_def[Defs] (*<*) end (*>*)
# Run lint Playground.jl for Error or Critical level message msgs = lintpkg("Playground", returnMsgs=true) for m in msgs @test m.level < 2 end
Now, ten years later, Italy and its wonderful flavours continue to have a major influence on Jamie’s food and cooking. In Jamie’s Italy, he travels this famously gastronomic country paying homage to the classic dishes of each region and searching for new ideas to bring home. The result is a sensational collection of Italian recipes, old and new, that will ensure Italy’s influence reaches us all. On the menu is an array of magical ingredients and Mediterranean flavours all combined in Jamie’s inimitable way. From Parma ham to Parmesan, from pizza to panzanella, Jamie’s new book will transport you to Italy or at least bring Italy home to you.
Formal statement is: lemma simply_connected_inside_simple_path: fixes p :: "real \<Rightarrow> complex" shows "simple_path p \<Longrightarrow> simply_connected(inside(path_image p))" Informal statement is: If $p$ is a simple path, then the inside of the path image of $p$ is simply connected.
/* combination/gsl_combination.h * based on permutation/gsl_permutation.h by Brian Gough * * Copyright (C) 2001 Szymon Jaroszewicz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_COMBINATION_H__ #define __GSL_COMBINATION_H__ #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_types.h> #include <gsl/gsl_check_range.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS struct gsl_combination_struct { size_t n; size_t k; size_t *data; }; typedef struct gsl_combination_struct gsl_combination; gsl_combination *gsl_combination_alloc (const size_t n, const size_t k); gsl_combination *gsl_combination_calloc (const size_t n, const size_t k); void gsl_combination_init_first (gsl_combination * c); void gsl_combination_init_last (gsl_combination * c); void gsl_combination_free (gsl_combination * c); int gsl_combination_memcpy (gsl_combination * dest, const gsl_combination * src); int gsl_combination_fread (FILE * stream, gsl_combination * c); int gsl_combination_fwrite (FILE * stream, const gsl_combination * c); int gsl_combination_fscanf (FILE * stream, gsl_combination * c); int gsl_combination_fprintf (FILE * stream, const gsl_combination * c, const char *format); size_t gsl_combination_n (const gsl_combination * c); size_t gsl_combination_k (const gsl_combination * c); size_t * gsl_combination_data (const gsl_combination * c); size_t gsl_combination_get (const gsl_combination * c, const size_t i); int gsl_combination_valid (gsl_combination * c); int gsl_combination_next (gsl_combination * c); int gsl_combination_prev (gsl_combination * c); #ifdef HAVE_INLINE extern inline size_t gsl_combination_get (const gsl_combination * c, const size_t i) { #if GSL_RANGE_CHECK if (i >= c->k) { GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0); } #endif return c->data[i]; } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_COMBINATION_H__ */
/* @copyright Louis Dionne 2014 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #include <boost/hana/detail/assert.hpp> #include <boost/hana/detail/constexpr.hpp> #include <boost/hana/maybe.hpp> using namespace boost::hana; int main() { //! [main] BOOST_HANA_CONSTEXPR_LAMBDA auto plus = [](auto x, auto y) { return x + y; }; BOOST_HANA_CONSTEXPR_ASSERT(foldr(nothing, 1, plus) == 1); BOOST_HANA_CONSTEXPR_ASSERT(foldr(just(4), 1, plus) == 5); //! [main] }
Require Import Utils. Require Import Lia. Require Coq.Lists.List. Import List.ListNotations. Import Coq.NArith.BinNat. Import EqNotations. Record vector {A n} := { vector_list : list A; vector_wf : length_bin vector_list = n; }. Arguments vector : clear implicits. Notation bitvec := (vector bool). Declare Scope vector_scope. Delimit Scope vector_scope with vector. Bind Scope vector_scope with vector. Notation "[| |]" := {| vector_list := []; vector_wf := eq_refl |} (format "[| |]"). Notation "[| x |]" := {| vector_list := [x]; vector_wf := eq_refl |}. Notation "[| x ; y ; .. ; z |]" := {| vector_list := cons x (cons y .. [z] ..); vector_wf := eq_refl |}. Register vector as vcpu.vector.type. Register Build_vector as vcpu.vector.constructor. Register vector_list as vcpu.vector.list. Register vector_wf as vcpu.vector.wf. Definition mk_vector {A n} v_list v_wf : vector A n := {| vector_list := v_list; vector_wf := normalize_eq_binnat _ _ v_wf; |}. Lemma mk_vector_ext : forall {A n} (v_list : list A) (v_wf_1 v_wf_2 : length_bin v_list = n), mk_vector v_list v_wf_1 = mk_vector v_list v_wf_2. Proof. intros A n v_list v_wf_1 v_wf_2. unfold mk_vector. f_equal. apply normalize_eq_binnat_ext. Qed. Lemma mk_vector_ext_all : forall {A n} (v_list_1 v_list_2 : list A) (v_wf_1 : length_bin v_list_1 = n) (v_wf_2 : length_bin v_list_2 = n), v_list_1 = v_list_2 -> mk_vector v_list_1 v_wf_1 = mk_vector v_list_2 v_wf_2. Proof. intros A n v_list_1 v_list_2 v_wf_1 v_wf_2 H. subst v_list_2. apply mk_vector_ext. Qed. Lemma mk_vector_eq_refl : forall {A} (l : list A), mk_vector l eq_refl = {| vector_list := l; vector_wf := eq_refl |}. Proof. intros A l. unfold mk_vector. f_equal. apply normalize_eq_binnat_eq_refl. Qed. Definition vector_normalize {A n} (v : vector A n) : vector A n := mk_vector (vector_list v) (vector_wf v). Definition vector_similar {A n1 n2} (v1 : vector A n1) (v2 : vector A n2) := vector_list v1 = vector_list v2. Infix "~=" := vector_similar (at level 70) : type_scope. Register vector_similar as vcpu.vector.similar. Lemma vector_similar_ext : forall {A n} (v1 : vector A n) (v2 : vector A n), v1 = v2 -> v1 ~= v2. Proof. intros A n v1 v2 H. rewrite H. reflexivity. Qed. Register vector_similar_ext as vcpu.vector.similar_ext. #[program] Definition vector_head {A n} (v : vector A (N.succ n)) : A := match vector_list v with | x :: _ => x | [] => _ end. Next Obligation. intros A n v. specialize (vector_wf v) as H. destruct (vector_list v). - simpl in H. apply N.neq_0_succ in H. destruct H. - simpl. auto. Qed. #[program] Definition vector_tail {A n} (v : vector A (N.succ n)) : vector A n := {| vector_list := List.tl (vector_list v); |}. Next Obligation. intros A n v. specialize (vector_wf v) as H. destruct (vector_list v). - simpl in H. apply N.neq_0_succ in H. destruct H. - simpl. rewrite length_bin_cons in H. apply N.succ_inj in H. auto. Qed. Definition vector_dest {A n} (v : vector A (N.succ n)) : A * vector A n := (vector_head v, vector_tail v). Register vector_dest as vcpu.vector.dest. Definition vector_of_list {A} (l : list A) : vector A (length_bin l) := mk_vector l eq_refl. #[program] Definition vector_app {A n1 n2} (v1 : vector A n1) (v2 : vector A n2) : vector A (n1 + n2) := mk_vector (vector_list v1 ++ vector_list v2) _. Next Obligation. intros A n1 n2 v1 v2. rewrite length_bin_app. rewrite ? vector_wf. auto. Qed. Infix "++" := vector_app : vector_scope. Register vector_app as vcpu.vector.app. Lemma vector_app_mk_vector : forall A n1 n2 (v_list_1 v_list_2 : list A) (v_wf_1 : length_bin v_list_1 = n1) (v_wf_2 : length_bin v_list_2 = n2), ((mk_vector v_list_1 v_wf_1) ++ (mk_vector v_list_2 v_wf_2))%vector = mk_vector (v_list_1 ++ v_list_2) (vector_app_obligation_1 _ _ _(mk_vector v_list_1 v_wf_1) (mk_vector v_list_2 v_wf_2)). Proof. intros A n1 n2 v_list_1 v_list_2 v_wf_1 v_wf_2. unfold vector_app. apply mk_vector_ext. Qed. Definition vector_seq_bin s n : vector binnat n := mk_vector (list_seq_bin s n) (length_bin_list_seq_bin s n). Definition vector_select_bin {A n m} (values : vector A n) (indices : vector binnat m) default : vector A m := mk_vector (list_select_bin (vector_list values) (vector_list indices) default) (rew vector_wf indices in length_bin_list_select_bin _ _ _). Register vector_select_bin as vcpu.vector.select_bin. #[program] Definition vector_map {A B n} f (v : vector A n) : vector B n := mk_vector (List.map f (vector_list v)) _. Next Obligation. intros A B n f v. rewrite length_bin_list_map. apply (vector_wf v). Qed. Unset Program Cases. #[program] Definition vector_map2 f {n} (bv1 bv2 : bitvec n) : bitvec n := {| vector_list := List.map (fun '(b1, b2) => f b1 b2) (List.combine (vector_list bv1) (vector_list bv2)); |}. Next Obligation. intros f n bv1 bv2. rewrite length_bin_list_map. rewrite length_bin_list_combine. rewrite ? vector_wf. apply N.min_id. Qed. Set Program Cases. Definition vector_and {n} (bv1 bv2 : bitvec n) : bitvec n := vector_map2 andb bv1 bv2.
(* Title: HOL/Auth/n_g2kAbsAfter_lemma_inv__38_on_rules.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_g2kAbsAfter Protocol Case Study*} theory n_g2kAbsAfter_lemma_inv__38_on_rules imports n_g2kAbsAfter_lemma_on_inv__38 begin section{*All lemmas on causal relation between inv__38*} lemma lemma_inv__38_on_rules: assumes b1: "r \<in> rules N" and b2: "(f=inv__38 )" shows "invHoldForRule s f r (invariants N)" proof - have c1: "(\<exists> d. d\<le>N\<and>r=n_n_Store_i1 d)\<or> (\<exists> d. d\<le>N\<and>r=n_n_AStore_i1 d)\<or> (r=n_n_SendReqS_j1 )\<or> (r=n_n_SendReqEI_i1 )\<or> (r=n_n_SendReqES_i1 )\<or> (r=n_n_RecvReq_i1 )\<or> (r=n_n_SendInvE_i1 )\<or> (r=n_n_SendInvS_i1 )\<or> (r=n_n_SendInvAck_i1 )\<or> (r=n_n_RecvInvAck_i1 )\<or> (r=n_n_SendGntS_i1 )\<or> (r=n_n_SendGntE_i1 )\<or> (r=n_n_RecvGntS_i1 )\<or> (r=n_n_RecvGntE_i1 )\<or> (r=n_n_ASendReqIS_j1 )\<or> (r=n_n_ASendReqSE_j1 )\<or> (r=n_n_ASendReqEI_i1 )\<or> (r=n_n_ASendReqES_i1 )\<or> (r=n_n_SendReqEE_i1 )\<or> (r=n_n_ARecvReq_i1 )\<or> (r=n_n_ASendInvE_i1 )\<or> (r=n_n_ASendInvS_i1 )\<or> (r=n_n_ASendInvAck_i1 )\<or> (r=n_n_ARecvInvAck_i1 )\<or> (r=n_n_ASendGntS_i1 )\<or> (r=n_n_ASendGntE_i1 )\<or> (r=n_n_ARecvGntS_i1 )\<or> (r=n_n_ARecvGntE_i1 )" apply (cut_tac b1, auto) done moreover { assume d1: "(\<exists> d. d\<le>N\<and>r=n_n_Store_i1 d)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_Store_i1Vsinv__38) done } moreover { assume d1: "(\<exists> d. d\<le>N\<and>r=n_n_AStore_i1 d)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_AStore_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_SendReqS_j1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_SendReqS_j1Vsinv__38) done } moreover { assume d1: "(r=n_n_SendReqEI_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_SendReqEI_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_SendReqES_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_SendReqES_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_RecvReq_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_RecvReq_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_SendInvE_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_SendInvE_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_SendInvS_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_SendInvS_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_SendInvAck_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_SendInvAck_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_RecvInvAck_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_RecvInvAck_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_SendGntS_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_SendGntS_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_SendGntE_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_SendGntE_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_RecvGntS_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_RecvGntS_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_RecvGntE_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_RecvGntE_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_ASendReqIS_j1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ASendReqIS_j1Vsinv__38) done } moreover { assume d1: "(r=n_n_ASendReqSE_j1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ASendReqSE_j1Vsinv__38) done } moreover { assume d1: "(r=n_n_ASendReqEI_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ASendReqEI_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_ASendReqES_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ASendReqES_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_SendReqEE_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_SendReqEE_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_ARecvReq_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ARecvReq_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_ASendInvE_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ASendInvE_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_ASendInvS_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ASendInvS_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_ASendInvAck_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ASendInvAck_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_ARecvInvAck_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ARecvInvAck_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_ASendGntS_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ASendGntS_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_ASendGntE_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ASendGntE_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_ARecvGntS_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ARecvGntS_i1Vsinv__38) done } moreover { assume d1: "(r=n_n_ARecvGntE_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ARecvGntE_i1Vsinv__38) done } ultimately show "invHoldForRule s f r (invariants N)" by satx qed end
A function $f$ is continuous on a set $S$ if and only if for every point $a \in S$ and every sequence $(x_n)$ in $S$ that converges to $a$, the sequence $(f(x_n))$ converges to $f(a)$.
The NCBI BLAST databases are generated by the program \emph{formatdb}. The three files needed by Easel are index file, sequence file and header file.For protein databases these files end with the extension ".pin", ".psq" and ".phr" respectively. For DNA databases the extensions are ".nin", ".nsq" and ".nhr" respectively. The index file contains information about the database, i.e. version number, database type, file offsets, etc. The sequence file contains residues for each of the sequences. Finally, the header file contains the header information for each of the sequences. This document describes the structure of the NCBI version 4 database. If these files cannot be found, an alias file, extensions ".nal" or ".pal", is processed. The alias file is used to specify multiple volumes when databases are larger than 2 GB. \subsection{Index File (*.pin, *.nin)} The index file contains format information about the database. The layout of the version 4 index file is below: \bigskip \begin{center} \begin{tabular}{|l|l|p{3.5in}|} \hline Version & Int32 & Version number. \\ \hline Database type & Int32 & 0-DNA 1-Protein. \\ \hline Title length & Int32 & Length of the title string (\emph{T}). \\ \hline Title & Char[\emph{T}] & Title string. \\ \hline Timestamp length & Int32 & Length of the timestamp string (\emph{S}). \\ \hline Timestamp &Char[\emph{S}] & Time of the database creation. The length of the timestamp \emph{S} is increased to force 8 byte alignment of the remaining integer fields. The timestamp is padded with NULs to achieve this alignment. \\ \hline Number of sequences & Int32 & Number of sequences in the database (\emph{N}) \\ \hline Residue count & Int64 & Total number of residues in the database. Note: Unlike other integer fields, this field is stored in little endian. \\ \hline Maximum sequence & Int32 & Length of the longest sequence in the database \\ \hline Header offset table & Int32[\emph{N+1}] & Offsets into the sequence's header file (*.phr, *nhr). \\ \hline Sequence offset table & Int32[\emph{N+1}] & Offsets into the sequence's residue file (*.psq, *.nsq). \\ \hline Ambiguity offset table & Int32[\emph{N+1}] & Offset into the sequence's residue file (*.nsq). Note: This table is only in DNA databases. If the sequence does not have any ambiguity residues, then the offset points to the beginning of the next sequence. \\ \hline \end{tabular} \end{center} \bigskip The integer fields are stored in big endian format, except for the residue count which is stored in little endian. The two string fields, timestamp and title are preceded by a 32 bit length field. The title string is not NUL terminated. If the end of the timestamp field does not end on an offset that is a multiple of 8 bytes, NUL characters are padded to the end of the string to bring it to a multiple of 8 bytes. This forces all the following integer fields to be aligned on a 4-byte boundary for performance reasons. The length of the timestamp field reflects the NUL padding if any. The header offset table is a list of offsets to the beginning of each sequence's header. These are offsets into the header file (*.phr, *.nhr). The size of the header can be calculated by subtracting the offset of the next header from the current header. The sequence offset table is a list of offsets to the beginning of each sequence's residue data. These are offsets into the sequence file (*.psq, *.nsq). The size of the sequence can be calculated by subtracting the offset of the next sequence from the current sequence. Since one more offset is stored than the number of sequences in the database, no special code is needed in calculating the header size or sequence size for the last entry in the database. \subsection{Protein Sequence File (*.pin)} The sequence file contains the sequences, one after another. The sequences are in a binary format separated by a NUL byte. Each residue is encoded in eight bits. \bigskip \begin{center} \begin{tabular}{|c|c|c|c|c|c|c|c|} \hline Amino acid & Value & Amino acid & Value & Amino acid & Value & Amino acid & Value \\ \hline - & 0 & G & 7 & N & 13 & U & 24 \\ \hline A & 1 & H & 8 & O & 26 & V & 19 \\ \hline B & 2 & I & 9 & P & 14 & W & 20 \\ \hline C & 3 & J & 27 & Q & 15 & X & 21 \\ \hline D & 4 & K & 10 & R & 16 & Y & 22 \\ \hline E & 5 & L & 11 & S & 17 & Z & 23 \\ \hline F & 6 & M & 12 & T & 18 & * & 25 \\ \hline \end{tabular} \end{center} \subsection{DNA Sequence File (*.nsq)} The sequence file contains the sequences, one after another. The sequences are in a binary format but unlike the protein sequence file, the sequences are not separated by a NUL byte. The sequence is first compressed using two bits per residue then followed by an ambiguity correction table if necessary. If the sequence does not have an ambiguity table, the sequence's ambiguity index points to the beginning of the next sequence. \subsubsection{Two-bit encoding} The sequence is encoded first using two bits per nucleotide. \bigskip \begin{center} \begin{tabular}{|c|c|c|} \hline Nucleotide & Value & Binary \\ \hline A & 0 & 00 \\ \hline C & 1 & 01 \\ \hline G & 2 & 10 \\ \hline T or U & 3 & 11 \\ \hline \end{tabular} \end{center} \bigskip Any ambiguous residues are replaced by an 'A', 'C', 'G' or 'T' in the two bit encoding. To calculate the number of residues in the sequence, the least significant two bits in the last byte of the sequence needs to be examined. These last two bits indicate how many residues, if any, are encoded in the most significant bits of the last byte. \subsubsection{Ambiguity Table} To correct a sequence containing any degenerate residues, an ambiguity table follows the two bit encoded string. The start of the ambiguity table is pointed to by the ambiguity table index in the index file, "*.nin". The first four bytes contains the number of 32 bit words in the correction table. If the most significant bit is set in the count, then two 32 bit entries will be used for each correction. The 64 bit entries are used for sequence with more than 16 million residues. Each correction contains three pieces of information, the actual encoded nucleotide, how many nucleotides in the sequence are replaced by the correct nucleotide and finally the offset into the sequences to apply the correction. For 32 bit entries, the first 4 most significant bits encodes the nucleotide. Their bit pattern is true of their representation, i.e. the value of 'H' is equal to ('A'~or~'T'~or~'C'). \bigskip \begin{center} \begin{tabular}{|c|c|c|c|c|c|c|c|} \hline Nucleotide & Value & Nucleotide & Value & Nucleotide & Value & Nucleotide & Value \\ \hline - & 0 & G & 4 & T & 8 & K & 12 \\ \hline A & 1 & R & 5 & W & 9 & D & 13 \\ \hline C & 2 & S & 6 & Y & 10 & B & 14 \\ \hline M & 3 & V & 7 & H & 11 & N & 15 \\ \hline \end{tabular} \end{center} \bigskip The next field is the repeat count which is four bits wide. One is added to the count giving it the range of 1 -- 256. The last 24 bits is the offset into the sequence where the replacement starts. The first residue start at offset zero, the second at offset one, etc. With a 24 bit size, the offset can only address sequences around 16 million residues long. To address larger sequences, 64 bit entries are used. For 64 bit entries, the order of the entries stays the same, but their sizes change. The nucleotide remains at four bits. The repeat count is increased to 12 bits giving it the range of 1 -- 4096. The offset size is increased to 48 bits. \subsection{Header File (*.phr, *.nhr)} The header file contains the headers for each sequence, one after another. The sequences are in a binary encoded ASN.1 format. The length of a header can be calculated by subtracting the offset of the next sequence from the current sequence offset. The ASN.1 definition for the headers can be found in the NCBI toolkit in the following files: asn.all and fastadl.asn. The parsing of the header can be done with a simple recursive descent parser. The five basic types defined in the header are: \begin{itemize} \item Integer -- a variable length integer value. \item VisibleString -- a variable length string. \item Choice -- a union of one or more alternatives. \item Sequence -- an ordered collection of one or more types. \item SequenceOf -- an ordered collection of zero or more occurrences of a given type. \end{itemize} \subsubsection{Integer} The first byte of an encoded integer is a hex \verb+02+. The next byte is the number of bytes used to encode the integer value. The remaining bytes are the actual value. The value is encoded most significant byte first. \subsubsection{VisibleString} The first byte of a visible string is a hex \verb+1A+. The next byte starts encoding the length of the string. If the most significant bit is off, then the lower seven bits encode the length of the string, i.e. the string has a length less than 128. If the most significant bit is on, then the lower seven bits is the number of bytes that hold the length of the string, then the bytes encoding the string length, most significant bytes first. Following the length are the actual string characters. The strings are not NUL terminated. \subsubsection{Choice} The first byte indicates which selection of the choice. The choices start with a hex value \verb+A0+ for the first item, \verb+A1+ for the second, etc. The selection is followed by a hex \verb+80+. Two NUL bytes follow the choice. \subsubsection{Sequence} The first two bytes are a hex \verb+3080+. The header is then followed by the encoded sequence types. The first two bytes indicates which type of the sequence is encoded. This index starts with the hex value \verb+A080+ for the first item, \verb+A180+ for the second, etc. then followed by the encoded item and finally two NUL bytes, \verb+0000+, to indicate the end of that type. The next type in the sequence is then encoded. If an item is optional and is not defined, then none of it is encoded including the index and NUL bytes. This is repeated until the entire sequence has been encoded. Two NUL bytes then mark the end of the sequence. \subsubsection{SequenceOf} The first two bytes are a hex \verb+3080+. Then the lists of objects are encoded. Two NUL bytes encode the end of the list.
# Resolución de sistemas de ecuaciones lineales Juan Pablo Echeagaray González Data Science Club Academy 27 de septiembre del 2021 ## Librerías básicas Siempre vale la pena tener estas 2 librerías a la mano, numpy suele ser mucho más eficaz que las funciones nativas de python en cuanto a operaciones matemáticas se refiere, y matplotlib es básicamente el estándar para realizar visualizaciones en este lenguaje. ```python import numpy as np import sympy as sm ``` Para más información, consulta el cuaderno de OneNote de la clase. [Presiona aquí](https://tecmx-my.sharepoint.com/:o:/g/personal/a00830646_itesm_mx/EjsM5FC-YCxHnkM61ZZqfdwBub6PRS6cHAuM-EmeLETCEg?e=lLrH5s) para ver el cuaderno de OneNote. ## Ejemplos ### Ejemplo 1 ```python A = np.array([[1, 1, 1], [1, -1, 2], [2, 0, 3]]) b = np.array([[3], [2], [1]]) np.linalg.solve(A, b) ``` ```python augmented = np.concatenate((A, b), axis=1) augmented = sm.Matrix(augmented) augmented.rref()[0] ``` $\displaystyle \left[\begin{matrix}1 & 0 & \frac{3}{2} & 0\\0 & 1 & - \frac{1}{2} & 0\\0 & 0 & 0 & 1\end{matrix}\right]$ No te asustes por el error de la sección pasada, numpy ha funcionado como debería, y nos ha avisado que le fue imposible calcular el inverso de la matriz A, así que la función ```np.linalg.solve(A,b)``` nos dio un error. El siguiente paso que podemos tomar es calcular su forma **RREF**, *row reduced echelon form*, y de ahí hacer el análisis pertinente. En este caso se tiene una incosistencia, ya que no es posible que al multiplicar un conjunto de variables por 0 y sumarlas se obtenga un 1. ### Ejemplo 2 ```python A = np.array([[1, 1, 1], [1, -1, 2], [0, 1, 1]]) b = np.array([[3], [2], [2]]) x = np.linalg.solve(A, b) x ``` array([[1.], [1.], [1.]]) ```python augmented = np.concatenate((A, b), axis=1) augmented = sm.Matrix(augmented) augmented.rref()[0] ``` $\displaystyle \left[\begin{matrix}1 & 0 & 0 & 1\\0 & 1 & 0 & 1\\0 & 0 & 1 & 1\end{matrix}\right]$ Aquí tenemos un ejemplo bonito, la función ```np.linalg.solve(A,b)``` pudo encontrar un vector que satisfaciera la ecuación matricial del sistema. No es necesario que hagamos otra operación, pero de cualquier manera quisiera que veas cómo se ve la matriz en su forma RREF. Puedes notar que dentro de esa matriz se encuentra la mismísima matriz identidad I<sub>3</sub> , y a su derecha se encuentra el vector solución x. ### Ejemplo 3 ```python A = np.array([[1, 1, 1], [1, -1, 2], [2, 0, 3]]) b = np.array([[3], [2], [5]]) x = np.linalg.solve(A, b) x ``` ```python augmented = np.concatenate((A, b), axis=1) augmented = sm.Matrix(augmented) augmented.rref()[0] ``` $\displaystyle \left[\begin{matrix}1 & 0 & \frac{3}{2} & \frac{5}{2}\\0 & 1 & - \frac{1}{2} & \frac{1}{2}\\0 & 0 & 0 & 0\end{matrix}\right]$ Este es por mucho el ejemplo más interesante de los 3. La función ```np.linalg.solve(A,b)``` no pudo encontrar un vector que satisfaciera la ecuación matricial del sistema, y la forma **RREF** de la matriz tiene una fila entera de ceros. Esto no significa que la matriz no tenga soluciones; no, al contrario, tiene una cantidad infinita de ellas! Ve el cuaderno de la clase para que identifiques la forma que tiene la solución del sistema.
// Andrew Naplavkov #ifndef BARK_PROJ_STREAM_HPP #define BARK_PROJ_STREAM_HPP #include <bark/detail/wkb.hpp> #include <bark/proj/detail/transformation.hpp> #include <boost/none.hpp> namespace bark::proj { /// WKB visitor class stream { public: stream(const transformation& tf, PJ_DIRECTION dir) : tf_(tf), dir_(dir) {} void operator()(blob_view wkb) { wkb::istream is(wkb); wkb_ = wkb; begin_ = end(); wkb::geometry::accept(is, *this); flush(); } boost::none_t operator()(double x, double y) { *this << x << y; return boost::none; } template <class T> boost::none_t operator()(uint32_t count, T) { *this << count; return boost::none; } template <class T> void operator()(boost::none_t&, const boost::none_t&, T) { } template <class T, uint32_t Code> void operator()(wkb::tagged<T, Code>) { *this << wkb::HostEndian << Code; } template <class T> boost::none_t operator()(const boost::none_t&, T) { return boost::none; } private: const transformation& tf_; PJ_DIRECTION dir_; blob_view wkb_; double* begin_ = nullptr; double* end() { return (double*)wkb_.data(); } template <class T> stream& operator<<(T v) { flush(); *(T*)wkb_.data() = v; wkb_.remove_prefix(sizeof(T)); begin_ = end(); return *this; } stream& operator<<(double v) { *(double*)wkb_.data() = v; wkb_.remove_prefix(sizeof(double)); return *this; } void flush() { if (begin_ == end()) return; tf_.trans_generic(dir_, begin_, end()); begin_ = end(); } }; } // namespace bark::proj #endif // BARK_PROJ_STREAM_HPP
#redirect La Crêpe
Require Import Crypto.Specific.Framework.RawCurveParameters. Require Import Crypto.Util.LetIn. (*** Modulus : 2^198 - 17 Base: 24.75 ***) Definition curve : CurveParameters := {| sz := 8%nat; base := 24 + 3/4; bitwidth := 32; s := 2^198; c := [(1, 17)]; carry_chains := Some [seq 0 (pred 8); [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.
#pragma once #include <gsl/span> #include "halley/data_structures/vector.h" #include "component_schema.h" #include "custom_type_schema.h" #include "halley/data_structures/hash_map.h" #include "halley/text/halleystring.h" #include "message_schema.h" #include "system_message_schema.h" #include "system_schema.h" namespace YAML { class Node; } namespace Halley { struct CodegenSourceInfo { String filename; gsl::span<const gsl::byte> data; bool generate = false; }; class Codegen; class ECSData { public: void loadSources(Vector<CodegenSourceInfo> files); const HashMap<String, ComponentSchema>& getComponents() const; const HashMap<String, SystemSchema>& getSystems() const; const HashMap<String, MessageSchema>& getMessages() const; const HashMap<String, SystemMessageSchema>& getSystemMessages() const; const HashMap<String, CustomTypeSchema>& getCustomTypes() const; void clear(); int getRevision() const; private: void addSource(CodegenSourceInfo sourceInfo); void addComponent(YAML::Node rootNode, bool generate); void addSystem(YAML::Node rootNode, bool generate); void addMessage(YAML::Node rootNode, bool generate); void addSystemMessage(YAML::Node rootNode, bool generate); void addType(YAML::Node rootNode); String getInclude(String typeName) const; void validate(); void process(); HashMap<String, ComponentSchema> components; HashMap<String, SystemSchema> systems; HashMap<String, MessageSchema> messages; HashMap<String, SystemMessageSchema> systemMessages; HashMap<String, CustomTypeSchema> types; int revision = 0; }; }
Require Import VST.floyd.proofauto. Require Import VST.floyd.library. Require Import VST.progs.object. Instance CompSpecs : compspecs. make_compspecs prog. Defined. Definition Vprog : varspecs. mk_varspecs prog. Defined. Local Open Scope Z. Local Open Scope logic. Definition object_invariant := list Z -> val -> mpred. Definition tobject := tptr (Tstruct _object noattr). Definition reset_spec (instance: object_invariant) := WITH self: val, history: list Z PRE [ tobject] PROP () PARAMS (self) SEP (instance history self) POST [ tvoid ] PROP() RETURN () SEP(instance nil self). Definition twiddle_spec (instance: object_invariant) := WITH self: val, i: Z, history: list Z PRE [ tobject, tint] PROP (0 < i <= Int.max_signed / 4; 0 <= fold_right Z.add 0 history <= Int.max_signed / 4) PARAMS (self; Vint (Int.repr i)) SEP (instance history self) POST [ tint ] EX v: Z, PROP(2* fold_right Z.add 0 history < v <= 2* fold_right Z.add 0 (i::history)) RETURN (Vint (Int.repr v)) SEP(instance (i::history) self). Definition object_methods (instance: object_invariant) (mtable: val) : mpred := EX sh: share, EX reset: val, EX twiddle: val, !! readable_share sh && func_ptr' (reset_spec instance) reset * func_ptr' (twiddle_spec instance) twiddle * data_at sh (Tstruct _methods noattr) (reset,twiddle) mtable. Lemma object_methods_local_facts: forall instance p, object_methods instance p |-- !! isptr p. Proof. intros. unfold object_methods. Intros sh reset twiddle. entailer!. Qed. #[export] Hint Resolve object_methods_local_facts : saturate_local. Definition object_mpred (history: list Z) (self: val) : mpred := EX instance: object_invariant, EX mtable: val, (object_methods instance mtable * field_at Ews (Tstruct _object noattr) [StructField _mtable] mtable self* instance history self). Definition foo_invariant : object_invariant := (fun (history: list Z) p => withspacer Ews (sizeof size_t + sizeof tint) (2 * sizeof size_t) (field_at Ews (Tstruct _foo_object noattr) [StructField _data] (Vint (Int.repr (2*fold_right Z.add 0 history)))) p * malloc_token Ews (Tstruct _foo_object noattr) p). Definition foo_reset_spec := DECLARE _foo_reset (reset_spec foo_invariant). Definition foo_twiddle_spec := DECLARE _foo_twiddle (twiddle_spec foo_invariant). Definition make_foo_spec := DECLARE _make_foo WITH gv: globals PRE [ ] PROP () PARAMS() GLOBALS (gv) SEP (mem_mgr gv; object_methods foo_invariant (gv _foo_methods)) POST [ tobject ] EX p: val, PROP () RETURN (p) SEP (mem_mgr gv; object_mpred nil p; object_methods foo_invariant (gv _foo_methods)). Definition main_spec := DECLARE _main WITH gv: globals PRE [] main_pre prog tt gv POST [ tint ] EX i:Z, PROP(0<=i<=6) RETURN (Vint (Int.repr i)) SEP(TT). Definition Gprog : funspecs := ltac:(with_library prog [ foo_reset_spec; foo_twiddle_spec; make_foo_spec; main_spec]). Lemma object_mpred_i: forall (history: list Z) (self: val) (instance: object_invariant) (mtable: val), object_methods instance mtable * field_at Ews (Tstruct _object noattr) [StructField _mtable] mtable self * instance history self |-- object_mpred history self. Proof. intros. unfold object_mpred. Exists instance mtable; auto. Qed. Lemma body_foo_reset: semax_body Vprog Gprog f_foo_reset foo_reset_spec. Proof. unfold foo_reset_spec, foo_invariant, reset_spec. start_function. unfold withspacer; simpl; Intros. forward. (* self->data=0; *) entailer!. all: unfold withspacer; simpl; entailer!. (* needed if Archi.ptr64=true *) Qed. Lemma body_foo_twiddle: semax_body Vprog Gprog f_foo_twiddle foo_twiddle_spec. Proof. unfold foo_twiddle_spec, foo_invariant, twiddle_spec. start_function. unfold withspacer; simpl. Intros. forward. (* d = self->data; *) forward. (* self -> data = d+2*i; *) set (j:= Int.max_signed / 4) in *; compute in j; subst j. forget (fold_right Z.add 0 history) as h. entailer!. forward. (* return d+i; *) simpl. set (j:= Int.max_signed / 4) in *; compute in j; subst j. forget (fold_right Z.add 0 history) as h. entailer!. Exists (2 * fold_right Z.add 0 history + i). simpl; entailer!. rewrite Z.mul_add_distr_l, Z.add_comm. unfold withspacer; simpl. entailer!. Qed. Lemma split_object_methods: forall instance m, object_methods instance m |-- object_methods instance m * object_methods instance m. Proof. intros. unfold object_methods. Intros sh reset twiddle. Exists (fst (slice.cleave sh)) reset twiddle. Exists (snd (slice.cleave sh)) reset twiddle. rewrite (split_func_ptr' (reset_spec instance) reset) at 1. rewrite (split_func_ptr' (twiddle_spec instance) twiddle) at 1. entailer!. split. apply slice.cleave_readable1; auto. apply slice.cleave_readable2; auto. rewrite (data_at_share_join (fst (slice.cleave sh)) (snd (slice.cleave sh)) sh). auto. apply slice.cleave_join. Qed. Lemma body_make_foo: semax_body Vprog Gprog f_make_foo make_foo_spec. Proof. unfold make_foo_spec. start_function. forward_call (Tstruct _foo_object noattr, gv). Intros p. forward_if (PROP ( ) LOCAL (temp _p p; gvars gv) SEP (mem_mgr gv; malloc_token Ews (Tstruct _foo_object noattr) p; data_at_ Ews (Tstruct _foo_object noattr) p; object_methods foo_invariant (gv _foo_methods))). * change (Memory.EqDec_val p nullval) with (eq_dec p nullval). if_tac; entailer!. * forward_call 1. contradiction. * rewrite if_false by auto. Intros. forward. (* /*skip*/; *) entailer!. * unfold data_at_, field_at_, default_val; simpl. forward. (* p->mtable = &foo_methods; *) forward. (* p->data = 0; *) forward. (* return (struct object * ) p; *) Exists p. unfold object_mpred. Exists foo_invariant (gv _foo_methods). sep_apply (split_object_methods foo_invariant (gv _foo_methods)). unfold foo_invariant at 4. entailer!. simpl. unfold_data_at (field_at _ _ nil _ p). cancel. unfold withspacer; simpl. rewrite !field_at_data_at. simpl. apply derives_refl'. rewrite <- ?sepcon_assoc. (* needed if Archi.ptr64=true *) rewrite !field_compatible_field_address; auto with field_compatible. clear - H. (* TODO: simplify the following proof. *) destruct p; try contradiction. destruct H as [AL SZ]. repeat split; auto. simpl in *. unfold sizeof in *; simpl in *; lia. eapply align_compatible_rec_Tstruct; [reflexivity |]. simpl co_members; intros. simpl in H. if_tac in H; [| inv H]. inv H. inv H0. eapply align_compatible_rec_by_value. reflexivity. rewrite Z.add_0_r. simpl. unfold natural_alignment in AL. eapply Z.divide_trans; [ | apply AL]. apply prove_Zdivide. reflexivity. left; auto. Qed. Lemma make_object_methods: forall sh instance reset twiddle mtable, readable_share sh -> func_ptr' (reset_spec instance) reset * func_ptr' (twiddle_spec instance) twiddle * data_at sh (Tstruct _methods noattr) (reset, twiddle) mtable |-- object_methods instance mtable. Proof. intros. unfold object_methods. Exists sh reset twiddle. entailer!. Qed. Ltac method_call witness hist' result := repeat apply seq_assoc1; match goal with |- semax _ (PROPx _ (LOCALx ?Q (SEPx ?R))) (Ssequence (Sset ?mt (Efield (Ederef (Etempvar ?x _) _) _ _)) _) _ => match Q with context [temp ?x ?x'] => match R with context [object_mpred _ x'] => let instance := fresh "instance" in let mtable := fresh "mtable" in unfold object_mpred; Intros instance mtable; forward; unfold object_methods at 1; let sh := fresh "sh" in let r := fresh "r" in let t := fresh "t" in Intros sh r t; forward; forward_call witness; [ .. | try Intros result; sep_apply (make_object_methods sh instance r t mtable); [ auto .. | ]; sep_apply (object_mpred_i hist' x' instance mtable); deadvars; try clear dependent sh; try clear r; try clear t ] end end end. Lemma body_main: semax_body Vprog Gprog f_main main_spec. Proof. start_function. sep_apply (create_mem_mgr gv). (* assert_gvar _foo_methods. (* TODO: this is needed for a field_compatible later on *) *) fold noattr cc_default. (* 0. This part should be handled automatically by start_function *) gather_SEP (mapsto _ _ _ _) (data_at _ _ _ _); replace_SEP 0 (data_at Ews (Tstruct _methods noattr) (gv _foo_reset, gv _foo_twiddle) (gv _foo_methods)). { entailer!. unfold_data_at (data_at _ (Tstruct _methods _) _ (gv _foo_methods)). rewrite <- mapsto_field_at with (gfs := [StructField _twiddle]) (v:= (gv _foo_twiddle)) by auto with field_compatible. rewrite field_at_data_at. rewrite !field_compatible_field_address by auto with field_compatible. rewrite !isptr_offset_val_zero by auto. cancel. } (* 1. Prove that [mtable] is a proper method-table for foo-objects *) make_func_ptr _foo_twiddle. make_func_ptr _foo_reset. sep_apply (make_object_methods Ews foo_invariant(gv _foo_reset) (gv _foo_twiddle) (gv _foo_methods)); auto. (* 2. Build an instance of class [foo], called [p] *) forward_call (* p = make_foo(); *) gv. Intros p. assert_PROP (p<>Vundef) by entailer!. (* Illustration of an alternate method to prove the method calls. Method 1: comment out lines AA and BB and the entire range CC-DD. Method 2: comment out lines AA-BB, inclusive. *) (* AA *) try (tryif (method_call (p, @nil Z) (@nil Z) whatever; method_call (p, 3, @nil Z) [3%Z] i; [simpl; computable | ]) (* BB *) then fail else fail 99) . (* CC *) (* 4. first method-call *) unfold object_mpred. Intros instance mtable0. forward. (* mtable = p->mtable; *) unfold object_methods at 1. Intros sh r0 t0. forward. (* p_reset = mtable->reset; *) forward_call (* p_reset(p); *) (p, @nil Z). (* Finish the method-call by regathering the object p back together *) sep_apply (make_object_methods sh instance r0 t0 mtable0); auto. sep_apply (object_mpred_i [] p instance mtable0). deadvars!. clear. (* 5. second method-call *) unfold object_mpred. Intros instance mtable0. forward. (* mtable = p->mtable; *) unfold object_methods at 1. Intros sh r0 t0. forward. (* p_twiddle = mtable->twiddle; *) assert_PROP (p<>Vundef) by entailer!. forward_call (* i = p_twiddle(p,3); *) (p, 3, @nil Z). simpl. computable. Intros i. simpl in H0. sep_apply (make_object_methods sh instance r0 t0 mtable0); auto. sep_apply (object_mpred_i [3] p instance mtable0). deadvars!. simpl in H1. (* DD *) (* 6. return *) forward. (* return i; *) Exists i; entailer!. Qed.
(* Title: HOL/Auth/n_g2kAbsAfter_lemma_inv__83_on_rules.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_g2kAbsAfter Protocol Case Study*} theory n_g2kAbsAfter_lemma_inv__83_on_rules imports n_g2kAbsAfter_lemma_on_inv__83 begin section{*All lemmas on causal relation between inv__83*} lemma lemma_inv__83_on_rules: assumes b1: "r \<in> rules N" and b2: "(f=inv__83 )" shows "invHoldForRule s f r (invariants N)" proof - have c1: "(\<exists> d. d\<le>N\<and>r=n_n_Store_i1 d)\<or> (\<exists> d. d\<le>N\<and>r=n_n_AStore_i1 d)\<or> (r=n_n_SendReqS_j1 )\<or> (r=n_n_SendReqEI_i1 )\<or> (r=n_n_SendReqES_i1 )\<or> (r=n_n_RecvReq_i1 )\<or> (r=n_n_SendInvE_i1 )\<or> (r=n_n_SendInvS_i1 )\<or> (r=n_n_SendInvAck_i1 )\<or> (r=n_n_RecvInvAck_i1 )\<or> (r=n_n_SendGntS_i1 )\<or> (r=n_n_SendGntE_i1 )\<or> (r=n_n_RecvGntS_i1 )\<or> (r=n_n_RecvGntE_i1 )\<or> (r=n_n_ASendReqIS_j1 )\<or> (r=n_n_ASendReqSE_j1 )\<or> (r=n_n_ASendReqEI_i1 )\<or> (r=n_n_ASendReqES_i1 )\<or> (r=n_n_SendReqEE_i1 )\<or> (r=n_n_ARecvReq_i1 )\<or> (r=n_n_ASendInvE_i1 )\<or> (r=n_n_ASendInvS_i1 )\<or> (r=n_n_ASendInvAck_i1 )\<or> (r=n_n_ARecvInvAck_i1 )\<or> (r=n_n_ASendGntS_i1 )\<or> (r=n_n_ASendGntE_i1 )\<or> (r=n_n_ARecvGntS_i1 )\<or> (r=n_n_ARecvGntE_i1 )" apply (cut_tac b1, auto) done moreover { assume d1: "(\<exists> d. d\<le>N\<and>r=n_n_Store_i1 d)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_Store_i1Vsinv__83) done } moreover { assume d1: "(\<exists> d. d\<le>N\<and>r=n_n_AStore_i1 d)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_AStore_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_SendReqS_j1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_SendReqS_j1Vsinv__83) done } moreover { assume d1: "(r=n_n_SendReqEI_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_SendReqEI_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_SendReqES_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_SendReqES_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_RecvReq_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_RecvReq_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_SendInvE_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_SendInvE_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_SendInvS_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_SendInvS_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_SendInvAck_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_SendInvAck_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_RecvInvAck_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_RecvInvAck_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_SendGntS_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_SendGntS_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_SendGntE_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_SendGntE_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_RecvGntS_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_RecvGntS_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_RecvGntE_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_RecvGntE_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_ASendReqIS_j1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ASendReqIS_j1Vsinv__83) done } moreover { assume d1: "(r=n_n_ASendReqSE_j1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ASendReqSE_j1Vsinv__83) done } moreover { assume d1: "(r=n_n_ASendReqEI_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ASendReqEI_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_ASendReqES_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ASendReqES_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_SendReqEE_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_SendReqEE_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_ARecvReq_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ARecvReq_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_ASendInvE_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ASendInvE_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_ASendInvS_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ASendInvS_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_ASendInvAck_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ASendInvAck_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_ARecvInvAck_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ARecvInvAck_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_ASendGntS_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ASendGntS_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_ASendGntE_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ASendGntE_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_ARecvGntS_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ARecvGntS_i1Vsinv__83) done } moreover { assume d1: "(r=n_n_ARecvGntE_i1 )" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_n_ARecvGntE_i1Vsinv__83) done } ultimately show "invHoldForRule s f r (invariants N)" by satx qed end