text
stringlengths 0
3.34M
|
---|
/-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Scott Morrison, Simon Hudon
Definition and basic properties of endomorphisms and automorphisms of an object in a category.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.groupoid
import Mathlib.data.equiv.mul_add
import Mathlib.PostPort
universes v u u' v'
namespace Mathlib
namespace category_theory
/-- Endomorphisms of an object in a category. Arguments order in multiplication agrees with
`function.comp`, not with `category.comp`. -/
def End {C : Type u} [category_struct C] (X : C) := X ⟶ X
namespace End
protected instance has_one {C : Type u} [category_struct C] (X : C) : HasOne (End X) := { one := 𝟙 }
protected instance inhabited {C : Type u} [category_struct C] (X : C) : Inhabited (End X) :=
{ default := 𝟙 }
/-- Multiplication of endomorphisms agrees with `function.comp`, not `category_struct.comp`. -/
protected instance has_mul {C : Type u} [category_struct C] (X : C) : Mul (End X) :=
{ mul := fun (x y : End X) => y ≫ x }
@[simp] theorem one_def {C : Type u} [category_struct C] {X : C} : 1 = 𝟙 := rfl
@[simp] theorem mul_def {C : Type u} [category_struct C] {X : C} (xs : End X) (ys : End X) :
xs * ys = ys ≫ xs :=
rfl
/-- Endomorphisms of an object form a monoid -/
protected instance monoid {C : Type u} [category C] {X : C} : monoid (End X) :=
monoid.mk Mul.mul sorry 1 category.comp_id category.id_comp
/-- In a groupoid, endomorphisms form a group -/
protected instance group {C : Type u} [groupoid C] (X : C) : group (End X) :=
group.mk monoid.mul sorry monoid.one sorry sorry groupoid.inv
(div_inv_monoid.div._default monoid.mul sorry monoid.one sorry sorry groupoid.inv)
groupoid.comp_inv
end End
/--
Automorphisms of an object in a category.
The order of arguments in multiplication agrees with
`function.comp`, not with `category.comp`.
-/
def Aut {C : Type u} [category C] (X : C) := X ≅ X
namespace Aut
protected instance inhabited {C : Type u} [category C] (X : C) : Inhabited (Aut X) :=
{ default := iso.refl X }
protected instance group {C : Type u} [category C] (X : C) : group (Aut X) :=
group.mk (flip iso.trans) sorry (iso.refl X) sorry sorry iso.symm
(div_inv_monoid.div._default (flip iso.trans) sorry (iso.refl X) sorry sorry iso.symm) sorry
/--
Units in the monoid of endomorphisms of an object
are (multiplicatively) equivalent to automorphisms of that object.
-/
def units_End_equiv_Aut {C : Type u} [category C] (X : C) : units (End X) ≃* Aut X :=
mul_equiv.mk (fun (f : units (End X)) => iso.mk (units.val f) (units.inv f))
(fun (f : Aut X) => units.mk (iso.hom f) (iso.inv f) (iso.inv_hom_id' f) (iso.hom_inv_id' f))
sorry sorry sorry
end Aut
namespace functor
/-- `f.map` as a monoid hom between endomorphism monoids. -/
def map_End {C : Type u} [category C] (X : C) {D : Type u'} [category D] (f : C ⥤ D) :
End X →* End (obj f X) :=
monoid_hom.mk (map f) (map_id f X) sorry
/-- `f.map_iso` as a group hom between automorphism groups. -/
def map_Aut {C : Type u} [category C] (X : C) {D : Type u'} [category D] (f : C ⥤ D) :
Aut X →* Aut (obj f X) :=
monoid_hom.mk (map_iso f) (map_iso_refl f X) sorry
end Mathlib |
Formal statement is: lemma finite_set_avoid: fixes a :: "'a::metric_space" assumes "finite S" shows "\<exists>d>0. \<forall>x\<in>S. x \<noteq> a \<longrightarrow> d \<le> dist a x" Informal statement is: If $S$ is a finite set, then there exists a positive real number $d$ such that for all $x \in S$, if $x \neq a$, then $d \leq \|x - a\|$. |
-- Andreas, 2018-05-28, issue #3095, cannot make hidden shadowing variable visible
-- Andreas, 2019-07-15, issue #3919, make hidden variable visible in par. module
open import Agda.Builtin.Equality
module _ (A : Set) where
data Nat : Set where
suc : {n : Nat} → Nat
data IsSuc : Nat → Set where
isSuc : ∀{n} → IsSuc (suc {n})
test₁ : ∀{n} → IsSuc n → Set
test₁ p = aux p
where
aux : ∀{n} → IsSuc n → Set
aux isSuc = {!n!} -- C-c C-c
-- Expected: aux (isSuc {n}) = {!!}
-- Context:
-- p : IsSuc n
-- n : Nat (not in scope)
-- n₁ : Nat (not in scope)
-- WAS: ERROR
-- Ambiguous variable n
-- when checking that the expression ? has type Set
test₂ : ∀{m} → IsSuc m → Set
test₂ p = aux p
where
aux : ∀{n} → IsSuc n → Set
aux isSuc = {!m!} -- C-c C-c
-- Expected: cannot make hidden module parameter m visible
test₃ : ∀ m → IsSuc m → Set
test₃ m p = aux p refl
where
aux : ∀{n} → IsSuc n → m ≡ n → Set
aux isSuc refl = {!n!} -- C-c C-c
-- Expected: aux (isSuc {n}) refl = ?
test₄ : Nat → Nat
test₄ x = bar x
where
bar : Nat → Nat
bar y = {!x!} -- C-c C-c
-- Expected: cannot split on module parameter x
test₅ : Nat → {n : Nat} → Nat → Nat
test₅ = λ x y → {!n!} -- C-c C-c
-- Expected: cannot make hidden lambda-bound variable n visible
issue3919 : {n m : Nat} → n ≡ m
issue3919 = {!m!} -- C-c C-c
-- Expected: issue3919 {m = m} = ?
|
(* memory_model.thy *)
(* William Mansky *)
(* Memory model locales for PTRANS. *)
theory memory_model
imports "$AFP/List-Infinite/ListInfinite" AxiomaticModel
begin
(*
print_locale "ord"
instantiation option :: (ord) ord
begin
fun less_eq_option where
"(None \<le> None) = True"
| "(None \<le> (Some _ )) = True"
| "((Some _) \<le> None) = False"
| "((Some x) \<le> (Some y)) = (x \<le> y)"
fun less_option where
"(None < None) = False"
| "(None < (Some _)) = True"
| "((Some _) < None) = False"
| "((Some x) < (Some y)) = (x < y)"
instance proof qed
end
lemma map_add_dom_upd [simp]: "dom m' = {k} \<Longrightarrow> (m ++ m')(k \<mapsto> v) = m(k \<mapsto> v)"
by (auto intro!: ext simp add: map_add_def split: option.splits)
lemma dud_set [simp]: "{(l, v). False} = {}"
by simp
(* Extra utility function: enumerate the elements of a set in arbitrary order.
Useful for memory models. Could conceivably be replaced by Eps over finite_distinct_list. *)
thm finite_distinct_list
function list_of_set where
"list_of_set S = (if infinite S \<or> S = {} then [] else let a = SOME a. a \<in> S in a # list_of_set (S - {a}))"
by pat_completeness auto
termination
apply (relation "measure (\<lambda>S. card S)", auto)
apply (frule card_Diff_singleton, rule someI, simp)
apply (case_tac "card S", simp_all)
done
lemma list_of_set_empty [simp]: "list_of_set {} = []"
by simp
lemma list_of_set_inf [simp]: "infinite S \<Longrightarrow> list_of_set S = []"
by simp
lemma list_of_set_card [simp]: "(list_of_set S \<noteq> []) = (card S \<noteq> 0)"
by (auto simp add: Let_def)
declare list_of_set.simps [simp del]
lemma set_some [simp]: "S \<noteq> {} \<Longrightarrow> insert (SOME a. a \<in> S) S = S"
by (metis insert_absorb not_ex_in_conv someI)
lemma set_some2 [simp]: "S \<noteq> {} \<Longrightarrow> (SOME a. a \<in> S) \<in> S"
by (metis not_ex_in_conv someI)
lemma list_of_set_set [simp]: "finite S \<Longrightarrow> set (list_of_set S) = S"
apply (induct "card S" arbitrary: S, simp_all)
apply (rule trans, simp add: list_of_set.simps, simp add: Let_def)
done
corollary list_of_set_nth: "\<lbrakk>list_of_set S ! i = x; i < length (list_of_set S)\<rbrakk> \<Longrightarrow> x \<in> S"
apply (subgoal_tac "finite S", subgoal_tac "x \<in> set (list_of_set S)", simp,
simp add: set_conv_nth, force)
apply (auto simp add: list_of_set.simps split: if_splits)
done
lemma list_of_set_distinct [simp]: "distinct (list_of_set S)"
apply (induct "card S" arbitrary: S, clarsimp simp add: list_of_set.simps)
apply (rule_tac P=distinct in list_of_set.simps [THEN sym [THEN subst]], clarsimp simp add: Let_def)
done
datatype ('thread, 'loc, 'val) access = Read 'thread 'loc 'val | Write 'thread 'loc 'val
| ARW 'thread 'loc 'val 'val | Alloc 'thread 'loc | Free 'thread 'loc
primrec get_thread where
"get_thread (Read t _ _) = t" |
"get_thread (Write t _ _) = t" |
"get_thread (ARW t _ _ _) = t" |
"get_thread (Alloc t _) = t" |
"get_thread (Free t _) = t"
primrec get_loc where
"get_loc (Read _ l _) = l" |
"get_loc (Write _ l _) = l" |
"get_loc (ARW _ l _ _) = l" |
"get_loc (Alloc _ l) = l" |
"get_loc (Free _ l) = l"
primrec set_thread where
"set_thread t' (Read t l v) = Read t' l v" |
"set_thread t' (Write t l v) = Write t' l v" |
"set_thread t' (ARW t l v v') = ARW t' l v v'" |
"set_thread t' (Alloc t l) = Alloc t' l" |
"set_thread t' (Free t l) = Free t' l"
lemma set_get_thread [simp]: "set_thread (get_thread a) a = a"
by (case_tac a, auto)
lemma get_set_thread [simp]: "get_thread (set_thread t a) = t"
by (case_tac a, auto)
lemma set_thread_frees [simp]: "set_thread t' ` Free t ` S = Free t' ` S"
by (auto simp add: image_def)
abbreviation "get_ptrs ops \<equiv> get_loc ` ops"
type_synonym ('block, 'os) pointer = "'block * 'os"
type_synonym ('add, 'size) block_structure = "'add * 'size"
datatype ('add,'val,'size,'os) raw_block =
RawBlk "('add, 'size) block_structure" "('os \<rightharpoonup> 'val)"
type_synonym ('add, 'val, 'size) allocation = "(('add, 'size) block_structure) set"
type_synonym ('add,'val,'size,'os) block_allocation = "('add,'val,'size,'os) raw_block set"
fun get_addr_s where
"get_addr_s ((addr,_)::(('add,'size) block_structure)) = addr"
fun get_size_s where
"get_size_s ((_,s)::(('add,'size) block_structure)) = s"
fun get_addr where "get_addr ( RawBlk (addr,_) _) = addr"
fun get_size where "get_size (RawBlk(_,s) _) = s"
fun block_to_struct where "block_to_struct (RawBlk blk _) = blk"
declare[[show_types = true]]
declare[[show_sorts = true]]
(* locale for reasoning about blocks and the mapping of block offsets to memory locations *)
(* FUNCTIONS *)
(* block_s_start: partial function giving the first memory location of a
block_structure (if it exists)
block_exists: see assumptions for block existence conditions
block_start_os: gives the offset of a block that can be passed into block_s_ptr
such that the same memory location is returned as for block_s_start
block_s_ptr: partial function mapping offsets into a block to memory locations
size_to_offset: conversion between abstract types *)
(* ASSUMPTIONS *)
(* block_firstlast_offset: if a block exists, the start offset must be \<le> the offset
returned by calling size_to_offset on the block size (corresponds to the last memory
location of the block.
pointer_inbounds_exists: For any offset into a block that is between the start
and end offsets (inclusive), there must be a valid mapping to a memory location for
that offset.
block_s_same_add_same_loc: Two blocks with the same starting address must also have
the same starting memory location.
block_s_ptr_monotonic: block_s_ptr is a monotonic function
block_s_ptr_one_to_one: block_s_ptr is a one to one function
block_s_start_offset: Assumes that block_start_os is a total function. There will
exist an offset such that block_s_ptr and block_s_start will be equal (even if
it is because they both return None) *)
locale block_structure =
fixes block_s_start::"('add, 'size::ord) block_structure \<rightharpoonup> ('loc::ord)"
and block_exists::"('add, 'size::ord) block_structure \<Rightarrow> bool"
and block_start_os :: "('add, 'size::ord) block_structure \<Rightarrow> ('os::{ord,plus})"
and block_s_ptr::"('add, 'size) block_structure * 'os \<rightharpoonup> ('loc::ord)"
and size_to_offset::"'size \<Rightarrow> 'os"
and struct_to_rb::"('add,'size) block_structure \<Rightarrow> ('add,'val,'size,'os) raw_block"
assumes block_exists_defin: "block_exists blk = (\<exists>x. block_s_start(blk) = (Some x))"
and block_firstlast_offset:
"block_exists (addr,size1) \<Longrightarrow>
(block_start_os (addr,size1)) \<le> (size_to_offset size1)"
and pointer_inbounds_exists:
"\<lbrakk>block_exists (addr,size1); os \<ge> block_start_os(addr,size1);
os \<le> size_to_offset(size1)\<rbrakk> \<Longrightarrow>
\<exists> l. (block_s_ptr ((addr,size1),os) = (Some l))"
and block_s_same_add_same_loc:
"\<lbrakk>block_exists (add, size1); block_exists (add, size2)\<rbrakk> \<Longrightarrow>
block_s_start (add,size1) = block_s_start(add, size2)"
and block_s_ptr_monotonic: "\<lbrakk>os1 < os2; block_s_ptr(blk,os1) = Some x;
block_s_ptr(blk,os2) = Some y\<rbrakk> \<Longrightarrow> x < y"
and block_s_ptr_one_to_one: "\<lbrakk>block_s_ptr(blk,os1) = Some x;
block_s_ptr(blk,os2) = Some y;
(x = y)\<rbrakk> \<Longrightarrow> (os1 = os2)"
and block_s_start_offset: "\<exists>os_1. block_s_ptr(blk,os_1) = block_s_start(blk)"
and block_s_start_defin: "(block_s_start blk = block_s_ptr(blk,(block_start_os blk)))"
context block_structure
begin
fun good_block_s_ptr where
"good_block_s_ptr ((start,len), os) = ((block_exists (start,len)) \<and>
((block_start_os (start,len)) \<le> os) \<and> (os \<le> (size_to_offset len)))"
fun good_rb_s_pair where
"good_rb_s_pair blk1 blk2 =
((\<exists> os_1. (\<exists> os_2. ((good_block_s_ptr(blk1,os_1)) \<and>
(good_block_s_ptr(blk2,os_2)) \<and>
((good_block_s_ptr(blk1,os_1)) = (good_block_s_ptr(blk2,os_2)))))) \<longrightarrow>
(blk1 = blk2))"
fun good_allocation where
"good_allocation (alloc::('add,'val,'size) allocation) =
(\<forall> rb1 \<in> alloc. (\<forall> rb2 \<in> alloc. (good_rb_s_pair rb1 rb2)))"
fun good_block_allocation where
"good_block_allocation (alloc::('add,'val,'size,'os) block_allocation) =
good_allocation (block_to_struct ` alloc)"
lemma good_rb_s_pair_refl [simp]: "good_rb_s_pair a a"
apply auto
done
lemma good_rb_s_pair_symm [simp]: "good_rb_s_pair a b = good_rb_s_pair b a"
apply auto
done
lemma good_rb_s_pair_trans [simp]: "((good_allocation alloc) \<and>
(a \<in> alloc) \<and> (b \<in> alloc) \<and> (c \<in> alloc) \<and>
(good_rb_s_pair a b) \<and> (good_rb_s_pair b c) \<longrightarrow> good_rb_s_pair a c)"
apply auto
done
end
type_synonym ('block,'size, 'os) access_region = "('block * 'size * 'os)"
type_synonym ('add,'val,'size,'os) block_access_region =
"(('add,'val,'size,'os) raw_block,'size,'os) access_region"
type_synonym ('add,'val,'size,'os) block_s_access_region =
"(('add,'size) block_structure,'size,'os) access_region"
fun region_get_block where
"region_get_block ((b,s,os)::('block,'size, 'os) access_region) = b"
context block_structure
begin
(* Define the set of ptr or os that are "in" a region *)
fun os_in_region where
"os_in_region ((b,s,os1)::('add,'val,'size,'os) block_access_region) (os2::'os) =
((((block_start_os (block_to_struct b))+os1) \<le> os2) \<and>
(((block_start_os (block_to_struct b))+os1+(size_to_offset s)) \<ge> os2))"
fun region_eq where
"region_eq ((b1, s1, os1)::('add,'val,'size,'os) block_access_region)
((b2, s2, os2)::('add,'val,'size,'os) block_access_region) =
((block_s_ptr((block_to_struct b1),os1) = block_s_ptr((block_to_struct b2),os2))
\<and> (block_s_ptr((block_to_struct b1),(os1+(size_to_offset s1))) =
block_s_ptr((block_to_struct b2),(os2+(size_to_offset s2)))))"
lemma region_eq_all_ptr:
"region_eq (b1,s1,os1) (b2, s2, os2) \<Longrightarrow> (\<forall> (os_a::'os). \<exists> (os_b::'os).
(((os_in_region (b1,s1,os1) os_a) \<and> (os_in_region (b2,s2,os2) os_b))
\<and> (block_s_ptr((block_to_struct b1),os_a)) = block_s_ptr((block_to_struct b2),os_b)))"
oops
fun region_overlap where
"region_overlap ((b1, s1, os1)::('add,'val,'size,'os) block_access_region)
((b2, s2, os2)::(('add,'val,'size,'os) block_access_region)) = (\<exists> (os_a::'os).
(\<exists> (os_b::'os). ((os_a \<ge> os1) \<and> (os_b \<ge> os2) \<and> (os_a \<le> (os1+(size_to_offset s1))) \<and>
(os_b \<le> (os2+(size_to_offset s2))) \<and> (block_s_ptr((block_to_struct b1),os_a)) =
block_s_ptr((block_to_struct b2),os_b))))"
fun region_inbounds where
"region_inbounds ((b, s, os)::('add,'val,'size,'os) block_access_region)
= (((os + (size_to_offset s)) \<le> (size_to_offset (get_size b))) \<and>
(block_start_os((block_to_struct b)) \<le> os))"
(* tells us if a region describes an entire block *)
fun region_block_eq where
"region_block_eq ((b, s, os)::('add,'val,'size,'os) block_access_region)
= ((block_start_os((block_to_struct b)) = os) \<and> ((get_size_s(block_to_struct b)) = s))"
end
declare[[show_types = true]]
declare[[show_sorts = true]]
*)
context axiomaticModel begin
term observeMem
end
locale memory_model = axiomaticModel
where actions = "actions :: (aid_type, 'val, loc_type, 'lock, 'name, 'callID) action set"
and locations = "locations :: loc_type set"
and actionIDs = "actionIDs :: aid_type set"
and times = "times :: time_type set"
and threads = "threads :: 'tid set"
and locks = "locks :: 'lock set"
and names = "names :: 'name set"
and callIDs = "callIDs :: 'callID set"
for actions locations actionIDs times threads locks names callIDs +
fixes free_set::"(('tid \<times> time_type \<times> loc_type)
\<Rightarrow> (aid_type \<times> (aid_type, 'val, loc_type, 'lock, 'name, 'callID) action) option)
\<Rightarrow> time_type \<Rightarrow> loc_type set"
and can_read::"(('tid \<times> time_type \<times> loc_type)
\<Rightarrow> (aid_type \<times> (aid_type, 'val, loc_type, 'lock, 'name, 'callID) action) option)
\<Rightarrow>'tid \<Rightarrow> time_type \<Rightarrow> loc_type \<Rightarrow> 'val set"
and update_mem::"(('tid \<times> time_type \<times> loc_type)
\<Rightarrow> (aid_type \<times> (aid_type, 'val, loc_type, 'lock, 'name, 'callID) action) option)
\<Rightarrow> time_type \<Rightarrow> ('tid \<times> aid_type \<times>
(aid_type, 'val, loc_type, 'lock, 'name, 'callID) action) set
\<Rightarrow> (('tid \<times> time_type \<times> loc_type)
\<Rightarrow> (aid_type \<times> (aid_type, 'val, loc_type, 'lock, 'name, 'callID) action) option) \<Rightarrow> bool"
and start_mem:: "(('tid \<times> time_type \<times> loc_type)
\<Rightarrow> (aid_type \<times> (aid_type, 'val, loc_type, 'lock, 'name, 'callID) action) option)"
assumes alloc_not_free: "\<lbrakk>update_mem mem time ops mem'; (tid,aid,Create l) \<in> ops\<rbrakk> \<Longrightarrow>
l \<notin> free_set mem' time"
and stays_not_free: "\<lbrakk>update_mem mem time ops mem'; l \<notin> free_set mem time\<rbrakk> \<Longrightarrow>
l \<notin> free_set mem' time"
(*
datatype ('thread, 'add, 'size,'os) block_access =
bRead 'thread "('add,'size,'os) block_s_access_region" 'val
| bWrite 'thread "('add,'size,'os) block_s_access_region" 'val
| bARW 'thread "('add,'size,'os) block_s_access_region" 'val 'val
| bAlloc 'thread "('add,'size) block_structure"
| bFree 'thread "('add,'size) block_structure"
datatype ('thread, 'block, 'region,'val) block_access =
bRead 'thread 'region 'val
| bWrite 'thread 'region 'val
| bARW 'thread 'region 'val 'val
| bAlloc 'thread 'block
| bFree 'thread 'block
*)
(*
locale block_structur =
fixes good_block ::"'block \<Rightarrow> bool"
and good_region :: "'region \<Rightarrow> bool"
and block_overlap::"'block \<Rightarrow> 'block \<Rightarrow> bool"
and region_overlap::"'region \<Rightarrow> 'region \<Rightarrow> bool"
and subblock::"'block \<Rightarrow> 'block \<Rightarrow> bool"
and subregion :: "'region \<Rightarrow> 'region \<Rightarrow> bool"
and region_get_block ::"'region \<Rightarrow> 'block"
and block_as_region ::"'block \<Rightarrow> 'region"
and value_fits_region :: "'val \<Rightarrow> 'region \<Rightarrow> bool"
and region_fits_block ::"'region \<Rightarrow> 'block \<Rightarrow> bool"
(* define does_not_modify later *)
and does_not_modify :: "('thread, 'block, 'region,'val) block_access
\<Rightarrow> 'region \<Rightarrow> bool"
(* and get_access_region:: "('thread, 'block, 'region,'val) block_access \<Rightarrow> 'region"*)
assumes value_fits_bigger_region :
"\<lbrakk> subregion r1 r2; value_fits_region v r1 \<rbrakk> \<Longrightarrow> value_fits_region v r2"
and subblock_good: "\<lbrakk>good_block b ; subblock b' b\<rbrakk> \<Longrightarrow> good_block b'"
and region_overlap_symm: "region_overlap r r' \<Longrightarrow> region_overlap r' r"
(* and dummy: "\<exists> b. block_as_region b = block_as_region b" *)
fun (in block_structur) get_access_region::"('thread, 'block, 'region,'val) block_access \<Rightarrow> 'region" where
"get_access_region (bRead _ r _) = r" |
"get_access_region (bWrite _ r _) = r" |
"get_access_region (bARW _ r _ _) = r" |
"get_access_region (bAlloc _ b) = (block_as_region b)" |
"get_access_region (bFree _ b) = (block_as_region b)"
thm block_structur.get_access_region.simps
thm block_structur_def
locale basic_can_do = block_structur
where good_block = "good_block :: 'block \<Rightarrow> bool"
and good_region = "good_region :: 'region \<Rightarrow> bool"
for good_block
and good_region +
fixes can_do::"('thread, 'block, 'region,'val) block_access list \<Rightarrow>
('thread, 'block, 'region,'val) block_access \<Rightarrow> bool"
assumes base_allows_alloc: "good_block b \<Longrightarrow> (can_do [] (bAlloc t b))"
and free_allows_alloc: "\<lbrakk>good_block b; can_do m (bFree t b); subblock b' b\<rbrakk>
\<Longrightarrow> (can_do ((bFree t b)#m) (bAlloc t' b'))"
and alloc_allows_free: "\<lbrakk>good_block b; can_do m (bAlloc t b)\<rbrakk> \<Longrightarrow>
(can_do ((bAlloc t b)#m) (bFree t b))"
(* and alloc_allows_write: "\<lbrakk>good_block b; can_do m (bAlloc t b);
region_fits_block r b\<rbrakk> \<Longrightarrow>
(can_do ((bAlloc t b)#m) (bWrite t' r v))"*)
and alloc_allows_write_same_thread: "\<lbrakk>good_block b; can_do m (bAlloc t b);
region_fits_block r b\<rbrakk> \<Longrightarrow>
(can_do ((bAlloc t b)#m) (bWrite t r v))"
and write_any_value_same_thread: "\<lbrakk>value_fits_region v' r;
(can_do m (bWrite t r v))\<rbrakk> \<Longrightarrow> (can_do m (bWrite t r v'))"
and not_mod_write_drop: "\<lbrakk>can_do m opr; does_not_modify opr r;
can_do (opr#m) (bWrite t r v)\<rbrakk>
\<Longrightarrow> can_do m (bWrite t r v)"
and not_mod_write_add: "\<lbrakk>can_do m opr; does_not_modify opr r;
can_do m (bWrite t r v)\<rbrakk> \<Longrightarrow> can_do (opr#m) (bWrite t r v)"
and write_not_read_drop: "\<lbrakk>can_do m (bWrite t r v);
\<forall>r' v' .(region_overlap r r') \<longrightarrow> (opr \<noteq> (bRead t' r' v'));
can_do ((bWrite t r v)#m) opr\<rbrakk> \<Longrightarrow> can_do m opr"
and write_not_read_add: "\<lbrakk>can_do m (bWrite t r v);
\<forall>r' v' .(region_overlap r r') \<longrightarrow> (opr \<noteq> (bRead t' r' v'));
can_do m opr\<rbrakk> \<Longrightarrow> can_do ((bWrite t r v)#m) opr"
and read_only_written: "\<lbrakk>can_do m (bWrite t r v);
can_do ((bWrite t r v)#m) (bRead t' r v')\<rbrakk> \<Longrightarrow> v = v'"
and read_written: "can_do m (bWrite t r v) \<Longrightarrow>
can_do ((bWrite t r v)#m) (bRead t' r v)"
and read_noop_drop: "\<lbrakk>can_do m (bRead t r v); can_do ((bRead t r v)#m) opr\<rbrakk>
\<Longrightarrow> can_do m opr"
and read_noop_add: "\<lbrakk>can_do m (bRead t r v); can_do m opr\<rbrakk>
\<Longrightarrow> can_do ((bRead t r v)#m) opr"
and reg_drop: "\<lbrakk>\<not>(region_overlap (get_access_region opr) (get_access_region opr'));
can_do m opr; can_do (opr#m) opr'\<rbrakk> \<Longrightarrow> can_do m opr'"
and reg_add: "\<lbrakk>\<not>(region_overlap (get_access_region opr) (get_access_region opr'));
can_do m opr; can_do m opr'\<rbrakk> \<Longrightarrow> can_do (opr#m) opr'"
(*and reg_comm: "\<lbrakk>\<not>(region_overlap (get_access_region opr) (get_access_region opr'));
can_do (opr#m) opr'\<rbrakk> \<Longrightarrow> can_do (opr'#m) opr"*)
and prefix_closed: "\<lbrakk>can_do (opr#m) opr'\<rbrakk> \<Longrightarrow> can_do m opr"
lemma (in basic_can_do) reg_comm: "\<lbrakk>\<not>(region_overlap (get_access_region opr) (get_access_region opr'));
can_do (opr#m) opr'\<rbrakk> \<Longrightarrow> can_do (opr'#m) opr"
apply (rule reg_add)
apply (erule contrapos_nn)
apply (erule_tac r = "(get_access_region opr')" and r' = "(get_access_region opr)"
in region_overlap_symm)
prefer 2
apply (erule prefix_closed)
apply (erule reg_drop)
apply (erule prefix_closed)
apply auto
done
(* Commented out to the end
context block_structure
begin
primrec block_get_thread where
"block_get_thread (bRead t _ _) = t" |
"block_get_thread (bWrite t _ _) = t" |
"block_get_thread (bARW t _ _ _) = t" |
"block_get_thread (bAlloc t _) = t" |
"block_get_thread (bFree t _) = t"
fun block_get_region where
"block_get_region (bRead _ r _) = r" |
"block_get_region (bWrite _ r _) = r" |
"block_get_region (bARW _ r _ _) = r"|
"block_get_region (bAlloc _ b) = ((struct_to_rb b),(get_size_s b),(block_start_os(b)))" |
"block_get_region (bFree _ b) = ((struct_to_rb b),(get_size_s b),(block_start_os(b)))"
primrec block_get_block where
"block_get_block (bRead _ r _) = (region_get_block r)" |
"block_get_block (bWrite _ r _) = (region_get_block r)" |
"block_get_block (bARW _ r _ _) = (region_get_block r)" |
"block_get_block (bAlloc _ b) = (struct_to_rb b)" |
"block_get_block (bFree _ b) = (struct_to_rb b)"
primrec block_set_thread where
"block_set_thread t' (bRead t r v) = bRead t' r v" |
"block_set_thread t' (bWrite t r v) = bWrite t' r v" |
"block_set_thread t' (bARW t r v v') = bARW t' r v v'" |
"block_set_thread t' (bAlloc t l) = bAlloc t' l" |
"block_set_thread t' (bFree t l) = bFree t' l"
end
locale block_seq_can_do = fixes can_do::"('thread,'add,'val,'size,'os)
block_access list \<Rightarrow> ('thread,'add,'val,'size,'os) block_access \<Rightarrow> bool"
assumes base_allows_alloc: "(can_do [] (bAlloc t b))"
and free_allows_alloc: "\<lbrakk>can_do m (bFree t b); b=b'\<rbrakk>
\<Longrightarrow> (\<not>(can_do ((bFree t b)#m) (bFree t' b')))"
and alloc_allows_write: "\<lbrakk>can_do m (bAlloc t b);
region_inbounds ((struct_to_block b),s,os)\<rbrakk> \<Longrightarrow>
(can_do ((bAlloc t b)#m)
(bWrite t' ((struct_to_block b),s,os) v))"
and alloc_allows_alloc: "\<lbrakk>can_do m (bAlloc t b); b=b'\<rbrakk> \<Longrightarrow>
(\<not>(can_do ((bAlloc t b)#m) (bAlloc t' b')))"
and alloc_allows_free: "\<lbrakk>can_do m (bAlloc t b); b=b'\<rbrakk> \<Longrightarrow>
(can_do ((bAlloc t b)#m) (bFree t' b'))"
and write_any_value: "(can_do m (bWrite t r v)) = (can_do m (bWrite t' r v'))"(*
and not_mod_write: "\<lbrakk>can_do m (bRead t' r' v'); can_do m (bWrite t' r' v');
can_do m (bAlloc t' b); can_do m (bFree t' b); region_block_eq(b,s,os);
\<not>(region_overlap r r'); \<not>(region_overlap r (b,s,os))\<rbrakk> \<Longrightarrow>
((can_do ((bRead t' r' v')#m) (bWrite t r v)) =
(can_do (m) (bWrite t r v))) \<and>
((can_do ((bWrite t' r' v')#m) (bWrite t r v)) =
(can_do (m) (bWrite t r v))) \<and>
((can_do ((bAlloc t' b)#m) (bWrite t r v)) =
(can_do (m) (bWrite t r v))) \<and>
((can_do ((bFree t' b)#m) (bWrite t r v)) =
(can_do (m) (bWrite t r v)))"
and write_not_read: "\<lbrakk>can_do m (bWrite t r v); opr \<noteq> (bRead t' r v')\<rbrakk> \<Longrightarrow>
(can_do ((bWrite t r v)#m) opr) = (can_do m opr)"
and read_written: "\<lbrakk>can_do m (bWrite t r v)\<rbrakk> \<Longrightarrow> ((can_do ((bWrite t r v)#m)
(bRead t' r v')) = (v = v'))"
and read_noop: "\<lbrakk>can_do m (bRead t r v)\<rbrakk> \<Longrightarrow> (can_do ((bRead t r v)#m) opr =
can_do m opr)"*)(*
and loc_drop: "\<lbrakk>\<not>region_overlap((block_get_region opr) (block_get_region opr'));
(can_do m opr)\<rbrakk> \<Longrightarrow> (can_do (opr#m) opr') = (can_do m opr')"
and loc_comm: "\<lbrakk>\<not>region_overlap((block_get_region opr) (block_get_region opr'))\<rbrakk>
\<Longrightarrow> (can_do (opr#m) opr') = (can_do (opr'#m) opr)"*)
locale block_seq_can_do_extend = block_seq_can_do +
assumes base_disallows_free:"(\<not>(can_do [] (bFree t b)))"
and free_dissallows_free:"\<lbrakk>can_do m (bFree t b); b=b'\<rbrakk>
\<Longrightarrow> (\<not>(can_do ((bFree t b)#m) (bFree t' b')))"
locale seq_can_do = fixes can_do::"('thread, 'loc, 'val) access list \<Rightarrow>
('thread, 'loc, 'val) access \<Rightarrow> bool"
assumes base_allows: "(\<not>(can_do [] (Read t l v))) \<and> (can_do [] (Alloc t l))
\<and>(\<not>(can_do [] (Free t l)))"
and free_allows: "\<lbrakk>can_do m (Free t l)\<rbrakk> \<Longrightarrow> (\<not>(can_do ((Free t l)#m) (Read t' l v)))
\<and> (can_do ((Free t l)#m) (Alloc t' l)) \<and> (\<not>(can_do ((Free t l)#m) (Free t' l)))"
and alloc_allows: "\<lbrakk>can_do m (Alloc t l)\<rbrakk> \<Longrightarrow> (can_do ((Alloc t l)#m) (Write t l v))
\<and> (\<not>(can_do ((Alloc t l)#m) (Alloc t' l))) \<and> (can_do ((Alloc t l)#m) (Free t l))"
and write_any_value: "(can_do m (Write t l v)) = (can_do m (Write t l v'))"
and not_mod_write: "\<lbrakk>can_do m (Read t l v); can_do m (Write t l' v);
can_do m (Alloc t l'); can_do m (Free t l'); l \<noteq> l'\<rbrakk> \<Longrightarrow> ((can_do ((Read t l v)#m)
(Write t' l v)) = (can_do (m) (Write t' l v))) \<and> ((can_do ((Write t l' v)#m)
(Write t' l v)) = (can_do (m) (Write t' l v))) \<and> ((can_do ((Alloc t l')#m)
(Write t' l v)) = (can_do (m) (Write t' l v))) \<and> ((can_do ((Free t l')#m)
(Write t' l v)) = (can_do (m) (Write t' l v)))"
and write_not_read: "\<lbrakk>can_do m (Write t l v); opr \<noteq> (Read t' l v')\<rbrakk> \<Longrightarrow>
(can_do ((Write t l v)#m) opr) = (can_do m opr)"
and read_written: "\<lbrakk>can_do m (Write t l v)\<rbrakk> \<Longrightarrow> ((can_do ((Write t l v)#m)
(Read t' l v')) = (v = v'))"
and read_noop: "\<lbrakk>can_do m (Read t l v)\<rbrakk> \<Longrightarrow> (can_do ((Read t l v)#m) a = can_do m a)"
and loc_drop: "\<lbrakk>get_loc (opr) \<noteq> get_loc(opr'); (can_do m opr)\<rbrakk> \<Longrightarrow> (can_do (opr#m) opr')
= (can_do m opr')"
and loc_comm: "\<lbrakk>get_loc (opr) \<noteq> get_loc(opr')\<rbrakk> \<Longrightarrow> (can_do (opr#m) opr') =
(can_do (opr'#m) opr)"
(* how can we define a memory as only being a "good" allocation? *)
locale block_memory_model = fixes free_set::"'memory \<Rightarrow> 'a word set"
and can_read::"'memory \<Rightarrow> 'thread \<Rightarrow> 'loc \<Rightarrow> 'block set"
and update_mem::"'memory \<Rightarrow> ('thread, 'loc, 'val) block_access set \<Rightarrow> 'memory \<Rightarrow> bool"
and allocation::"'loc allocation"
and start_mem::'memory
(*and memory_max_word:: "'loc::len word" *) (*largest address *) (* note: we may want to condense these into one *)
and memory_max_int:: int
and memory_min:: int (* smallest address *)
(*assumes good_allocations: "\<lbrakk>update_mem mem ops mem'; good_allocation *)
(*assumes good_allocation_word: "good_allocation memory_max_word allocation"*)
assumes good_allocation_int: "good_allocation (word_of_int memory_max_int) allocation"
(* TSO memory model *)
locale TSO = fixes undef::'val begin
(* This isn't really a TSO-specific locale, but I might have other assumptions later.
More to the point, it's convenient to have a separate locale for each memory model, even if
they don't actually rely on separate assumptions. *)
abbreviation "free_set mem \<equiv> UNIV - dom (fst mem)"
definition "can_read mem t l \<equiv> case List.find (\<lambda>(l', v). l' = l) ((snd mem) t) of
Some (l, v) \<Rightarrow> {v} | None \<Rightarrow> {v. fst mem l = Some v}"
definition "can_read2 mem t l \<equiv> case mem of (mem_map, bufs) \<Rightarrow> (case List.find (\<lambda>(l', v). l' = l) (bufs t) of
Some (l, v) \<Rightarrow> {v} | None \<Rightarrow> {v. mem_map l = Some v})"
(* Switch to the inductive approach... sometime. *)
inductive update_mem where
no_atomic [intro]: "\<lbrakk>\<And>t l v v'. ARW t l v v' \<notin> ops; \<And>t. \<exists>up. bufs' t = up @ bufs t \<and>
set up = {(l, v) | l v. Write t l v \<in> ops} \<and> distinct up\<rbrakk> \<Longrightarrow>
update_mem (mem, bufs) ops (mem |` (UNIV - {l. \<exists>t. Free t l \<in> ops}) ++
(\<lambda>l. if \<exists>t. Alloc t l \<in> ops then Some undef else None), bufs')" |
update [intro]: "\<lbrakk>update_mem (mem, bufs) ops (mem', bufs'); bufs' t = buf @ [(l, v)]\<rbrakk> \<Longrightarrow>
update_mem (mem, bufs) ops (mem'(l \<mapsto> v), bufs'(t := buf))" |
atomic [intro!]: "bufs t = [] \<Longrightarrow> update_mem (mem, bufs) {ARW t l v v'} (mem(l \<mapsto> v'), bufs)"
abbreviation "start_mem \<equiv> (empty, \<lambda>t. [])"
lemma alloc_not_free: "\<lbrakk>update_mem mem ops mem'; Alloc t l \<in> ops; \<forall>t. Free t l \<notin> ops\<rbrakk> \<Longrightarrow>
l \<notin> free_set mem'"
by (induct rule: update_mem.induct, auto split: if_splits)
lemma stays_not_free: "\<lbrakk>update_mem mem ops mem'; l \<notin> free_set mem; \<forall>t. Free t l \<notin> ops\<rbrakk> \<Longrightarrow>
l \<notin> free_set mem'"
by (induct rule: update_mem.induct, auto split: if_splits)
end
sublocale TSO \<subseteq> memory_model free_set can_read update_mem start_mem
by (unfold_locales, metis alloc_not_free, metis stays_not_free)
context TSO begin
lemma update_none [intro!, simp]: "update_mem C {} C"
by (cases C, cut_tac ops="{}" and mem=a and bufs=b in no_atomic, auto simp add: restrict_map_def)
lemma can_read_thread: "\<lbrakk>v \<in> can_read (mem, b) t l; b t = b' t\<rbrakk> \<Longrightarrow>
v \<in> can_read (mem, b') t l"
by (auto simp add: can_read_def split: option.splits)
lemma first_entry: "\<lbrakk>update_mem (mem, bufs) {Write t l v} (mem', bufs');
bufs' t = a # rest\<rbrakk> \<Longrightarrow> a = (l, v)"
apply (drule_tac P="\<lambda>(mem, bufs) ops (mem', bufs'). \<forall>a rest. ops = {Write t l v} \<and>
bufs' t = a # rest \<longrightarrow> a = (l, v)" in update_mem.induct, simp_all, clarsimp)
apply (subgoal_tac "\<exists>up. bufs'a t = up @ bufs t \<and> set up = {ab. t = t \<and> (case ab of (la, va) \<Rightarrow>
la = l \<and> va = v)} \<and> distinct up", clarify, simp+)
apply (case_tac up, simp, simp)
apply (thin_tac "bufs'a t = ((aa, b) # resta)", force)
apply auto
apply (cases a, auto)
done
lemma update_map: "update_mem (mem, bufs) {} (mem', bufs') \<Longrightarrow>
\<exists>map. \<forall>mem2. update_mem (mem2, bufs) {} (mem2 ++ map, bufs')"
apply (drule_tac P="\<lambda>(mem, bufs) ops (mem', bufs'). ops = {} \<longrightarrow>
(\<exists>map. \<forall>mem2. update_mem (mem2, bufs) {} (mem2 ++ map, bufs'))" in update_mem.induct, auto)
apply (subgoal_tac "bufs' = bufs", rule_tac x=empty in exI, simp, rule ext)
apply (subgoal_tac "\<exists>up. bufs' x = (up @ bufs x) \<and> set up = {(l, v). False} \<and> distinct up", clarify, auto)
apply (rule_tac x="map(l \<mapsto> v)" in exI, auto)
done
lemma update_trans_rev: "\<lbrakk>update_mem (mem', bufs') {} (mem'', bufs'');
update_mem (mem, bufs) ops (mem', bufs')\<rbrakk> \<Longrightarrow> update_mem (mem, bufs) ops (mem'', bufs'')"
apply (drule_tac P="\<lambda>(mem', bufs') ops' (mem'', bufs''). ops' = {} \<and> update_mem (mem, bufs) ops (mem', bufs') \<longrightarrow>
update_mem (mem, bufs) ops (mem'', bufs'')" in update_mem.induct, auto simp add: restrict_map_def)
apply (subgoal_tac "bufs'a = bufsa", simp, rule ext)
apply (subgoal_tac "\<exists>up. bufs'a x = up @ bufsa x \<and> set up = {(l, v). False} \<and> distinct up",
clarify, auto)
done
lemma update_trans [trans]: "\<lbrakk>update_mem (mem, bufs) ops (mem', bufs');
update_mem (mem', bufs') {} (mem'', bufs'')\<rbrakk> \<Longrightarrow> update_mem (mem, bufs) ops (mem'', bufs'')"
by (erule update_trans_rev, simp)
lemma update_canonical: "\<lbrakk>update_mem (mem, bufs) ops (mem', bufs');
\<And>t l v v'. ARW t l v v' \<notin> ops\<rbrakk> \<Longrightarrow>
\<exists>writes bufs''. (\<forall>t. bufs'' t = writes t @ bufs t \<and> set (writes t) = {(l, v) | l v. Write t l v \<in> ops} \<and> distinct (writes t)) \<and>
update_mem (mem, bufs) ops (mem |` (UNIV - {l. \<exists>t. Free t l \<in> ops}) ++
(\<lambda>l. if \<exists>t. Alloc t l \<in> ops then Some undef else None), bufs'') \<and>
update_mem (mem |` (UNIV - {l. \<exists>t. Free t l \<in> ops}) ++
(\<lambda>l. if \<exists>t. Alloc t l \<in> ops then Some undef else None), bufs'') {} (mem', bufs')"
apply (drule_tac P="\<lambda>(mem, bufs) ops (mem', bufs'). (\<forall>t l v v'. ARW t l v v' \<notin> ops) \<longrightarrow>
(\<exists>writes bufs''. (\<forall>t. bufs'' t = writes t @ bufs t \<and>
set (writes t) = {(l, v) | l v. Write t l v \<in> ops} \<and> distinct (writes t)) \<and> update_mem (mem, bufs) ops
(mem |` (UNIV - {l. \<exists>t. Free t l \<in> ops}) ++ (\<lambda>l. if \<exists>t. Alloc t l \<in> ops then Some undef else None), bufs'') \<and>
update_mem (mem |` (UNIV - {l. \<exists>t. Free t l \<in> ops}) ++
(\<lambda>l. if \<exists>t. Alloc t l \<in> ops then Some undef else None), bufs'') {} (mem', bufs'))" in update_mem.induct, auto)
apply (rule_tac x="\<lambda>t. SOME up. bufs' t = up @ bufs t \<and> set up = {(l, v). Write t l v \<in> opsa} \<and>
distinct up" in exI)
apply (rule_tac x=bufs' in exI)
apply (rule conjI, clarsimp)
apply (rule someI_ex, auto)
done
corollary update_write: "\<lbrakk>update_mem (mem, bufs) {Write t l v} (mem', bufs')\<rbrakk> \<Longrightarrow>
update_mem (mem, bufs(t := (l, v) # bufs t)) {} (mem', bufs')"
apply (drule update_canonical, auto)
apply (subgoal_tac "bufs'' = bufs(t := (l, v) # bufs t)", simp add: restrict_map_def, rule ext,
clarsimp)
apply (erule_tac x=x in allE, rule conjI, clarsimp)
apply (case_tac "writes t", simp+, case_tac list, simp+)
apply clarsimp
done
lemma update_later: "\<lbrakk>update_mem (mem, bufs) {} (mem', bufs')\<rbrakk> \<Longrightarrow>
update_mem (mem, bufs) {Write t l v} (mem', bufs'(t := (l, v) # bufs' t))"
apply (drule_tac P="\<lambda>(mem, bufs) ops (mem', bufs'). ops = {} \<longrightarrow>
update_mem (mem, bufs) {Write t l v} (mem', bufs'(t := (l, v) # bufs' t))" in update_mem.induct, auto)
apply (cut_tac ops="{Write t l v}" in no_atomic, auto)
apply (drule_tac ops="{Write t l v}" in update, auto)
apply (drule_tac ops="{Write t l v}" and t=ta in update, auto)
by (metis (hide_lams, no_types) fun_upd_twist)
lemma update_later2: "\<lbrakk>update_mem (mem, bufs) {} (mem', bufs'(t := buf)); bufs' t = (l, v) # buf\<rbrakk> \<Longrightarrow>
update_mem (mem, bufs) {Write t l v} (mem', bufs')"
by (smt fun_upd_idem_iff fun_upd_upd list.inject update_later)
lemma update_past: "\<lbrakk>update_mem (mem, bufs) ops (mem', bufs'); t \<notin> get_thread ` ops\<rbrakk> \<Longrightarrow>
update_mem (mem, bufs(t := b @ bufs t)) ops (mem', bufs'(t := b @ bufs' t))"
apply (drule_tac P="\<lambda>(mem, bufs) ops (mem', bufs'). t \<notin> get_thread ` ops \<longrightarrow>
update_mem (mem, bufs(t := b @ bufs t)) ops (mem', bufs'(t := b @ bufs' t))"
in update_mem.induct, auto)
apply (rule no_atomic, auto)
apply (rule_tac x="[]" in exI, simp)
apply (subgoal_tac "\<forall>a b. Write t a b \<notin> opsa", subgoal_tac "\<exists>up. bufs' t = up @ bufs t
\<and> set up = {(l, v). Write t l v \<in> opsa} \<and> distinct up", clarify, simp, metis, auto)
apply (metis get_thread.simps(2) imageI)
apply (drule_tac bufs="bufs(t := b @ bufs t)" in update, auto)
apply (drule_tac bufs="bufs(t := b @ bufs t)" and t=ta in update, auto)
apply (simp add: fun_upd_twist)
done
lemma update_past2: "\<lbrakk>update_mem (mem, bufs) ops (mem', bufs');
\<And>l v. Write t l v \<notin> ops; \<And>l v v'. ARW t l v v' \<notin> ops\<rbrakk> \<Longrightarrow>
update_mem (mem, bufs(t := b @ bufs t)) ops (mem', bufs'(t := b @ bufs' t))"
apply (drule_tac P="\<lambda>(mem, bufs) ops (mem', bufs'). (\<forall>l v. Write t l v \<notin> ops) \<and>
(\<forall>l v v'. ARW t l v v' \<notin> ops) \<longrightarrow> update_mem (mem, bufs(t := b @ bufs t)) ops (mem', bufs'(t := b @ bufs' t))"
in update_mem.induct, auto)
apply (rule no_atomic, auto)
apply (subgoal_tac "\<exists>up. bufs' t = up @ bufs t \<and> set up = {(l, v). Write t l v \<in> opsa} \<and>
distinct up", simp)
apply (metis (full_types))
apply (drule_tac bufs="bufs(t := b @ bufs t)" in update, auto)
apply (drule_tac bufs="bufs(t := b @ bufs t)" and t=ta in update, auto simp add: fun_upd_twist)
done
lemma process_buffer: "\<lbrakk>update_mem (mem, bufs) ops (mem', bufs'); bufs' t = a @ b\<rbrakk> \<Longrightarrow>
update_mem (mem, bufs) ops (mem' ++ map_of b, bufs'(t := a))"
apply (induct b arbitrary: mem' bufs' rule: rev_induct, auto simp add: map_upd_triv)
apply (drule_tac t=t in update, auto)
apply force
done
end
(* assorted useful list lemmas*)
lemma map_upt_zip_Suc [simp]: "l' = map (\<lambda>(x, n). (x, Suc n)) l \<Longrightarrow> map (\<lambda>((l, v), n). (l, v) # map (Pair l) (f n)) l' =
map (\<lambda>((l, v), n). (l, v) # map (Pair l) (f (Suc n))) l"
by auto
declare map_Suc_upt [simp]
lemma zip_Suc [simp]: "zip l [Suc i..<Suc j] = map (\<lambda>(x, n). (x, Suc n)) (zip l [i..<j])"
by (simp only: zip_map2 [THEN sym], simp)
(* The redundant store produces buffers with redundant elements.
add_red is a general characterization of such buffers. *)
definition "add_red l f =
concat (map (\<lambda>((l, v), n). (l, v) # map (\<lambda>v. (l, v)) (f n)) (zip l [0..<length l]))"
lemma add_red_nil [simp]: "add_red [] f = []"
by (simp add: add_red_def)
lemma add_red_cons [simp]: "add_red (x # l) f = x # map (\<lambda>v. (fst x, v)) (f 0) @ add_red l (\<lambda>n. f (Suc n))"
apply (auto simp add: add_red_def)
apply (case_tac "map (\<lambda>((l, v), n). (l, v) # map (Pair l) (f n)) (zip (x # l) ([0..<length l] @ [length l]))", auto)
apply (case_tac "[0..<length l] @ [length l]", auto)
apply (case_tac "[0..<length l] @ [length l]", auto)
apply (case_tac "[0..<length l] @ [length l]", auto)
apply (cut_tac i=0 and j="Suc (length l)" and x=ba and xs=list in upt_eq_Cons_conv, auto)
apply (rule_tac f=concat in arg_cong)
apply (rule map_upt_zip_Suc)
by (metis upt_Suc_append zip_Suc)
lemma add_red_app [simp]: "add_red (l @ l') f = add_red l f @ add_red l' (\<lambda>n. f (n + length l))"
by (induct l arbitrary: f, auto)
lemma add_red_id [simp]: "(\<And>n. n < length l \<Longrightarrow> f n = []) \<Longrightarrow> add_red l f = l"
by (induct l arbitrary: f, auto)
lemma find_append: "(\<And>x. x \<in> set l \<Longrightarrow> \<not>P x) \<Longrightarrow> List.find P (l @ l') = List.find P l'"
by (induct l, auto)
lemma find_append2 [simp]: "List.find P l = None \<Longrightarrow> List.find P (l @ l') = List.find P l'"
by (induct l, auto)
lemma find_append3 [simp]: "List.find P l = Some x \<Longrightarrow> List.find P (l @ l') = Some x"
by (induct l, auto)
lemma add_red_find [simp]: "List.find (\<lambda>(l, v). l = x) (add_red buf f) =
List.find (\<lambda>(l, v). l = x) buf"
apply (induct buf arbitrary: f, auto)
apply (rule trans, rule find_append, auto)
done
context TSO begin
lemma update_red: "\<lbrakk>update_mem (mem, bufs) ops (mem', bufs'); \<And>t. red t = add_red (bufs t) (f t)\<rbrakk> \<Longrightarrow>
\<exists>red' f'. update_mem (mem, red) ops (mem', red') \<and> (\<forall>t. red' t = add_red (bufs' t) (f' t))"
apply (drule_tac P="\<lambda>(mem, bufs) ops (mem', bufs'). (\<forall>t. red t = add_red (bufs t) (f t)) \<longrightarrow>
(\<exists>red' f'. update_mem (mem, red) ops (mem', red') \<and> (\<forall>t. red' t = add_red (bufs' t) (f' t)))"
in update_mem.induct, auto)
apply (rule_tac x="\<lambda>t. (SOME up. bufs' t = up @ bufsa t \<and> set up = {(l, v). Write t l v \<in> ops} \<and>
distinct up) @ red t" in exI, auto)
apply (rule no_atomic, simp_all)
apply (cut_tac P="\<lambda>up. bufs' t = up @ bufsa t \<and> set up = {(l, v). Write t l v \<in> ops} \<and>
distinct up" in someI_ex, simp+)
apply (rule_tac x="\<lambda>t n. if n < length (SOME up. bufs' t = up @ bufsa t \<and>
set up = {(l, v). Write t l v \<in> ops} \<and> distinct up) then [] else f t (n - length (SOME up.
bufs' t = up @ bufsa t \<and> set up = {(l, v). Write t l v \<in> ops} \<and> distinct up))" in exI, clarsimp)
apply (subgoal_tac "\<exists>up. bufs' t = up @ bufsa t \<and> set up = {(l, v). Write t l v \<in> ops} \<and> distinct up",
clarify, clarsimp)
apply (cut_tac P="\<lambda>upa. up = upa \<and> set upa = {(l, v). Write t l v \<in> ops} \<and> distinct upa" in someI,
force, clarsimp)
apply metis
apply (drule_tac bufs=red and t=t and a="add_red buf (f' t)" in process_buffer, simp, clarsimp)
apply (subgoal_tac "dom (map_of (map (Pair l) (f' t (length buf)))) = {l} \<or> f' t (length buf) = []",
erule disjE, simp+)
apply (rule_tac x="red'(t := add_red buf (f' t))" in exI, clarsimp)
apply (rule_tac x=f' in exI, simp)
apply (rule_tac x="red'(t := add_red buf (f' t))" in exI, clarsimp)
apply (rule_tac x=f' in exI, simp)
apply (auto simp add: dom_map_of_conv_image_fst intro!: set_eqI)
apply (case_tac "f' t (length buf)", simp+)
apply (rule_tac x=red in exI, auto)+
done
lemma update_red1: "update_mem (mem, bufs) ops (mem', bufs') \<Longrightarrow>
\<exists>f'. update_mem (mem, bufs(t := add_red (bufs t) f)) ops (mem', bufs'(t := add_red (bufs' t) f'))"
apply (drule_tac P="\<lambda>(mem, bufs) ops (mem', bufs'). \<exists>f'. update_mem (mem, bufs(t := add_red (bufs t) f))
ops (mem', bufs'(t := add_red (bufs' t) f'))" in update_mem.induct, auto)
apply (rule_tac x="\<lambda>n. if n < length (SOME x. bufs' t = x @ bufs t \<and> set x = {(l, v). Write t l v \<in> ops} \<and> distinct x)
then [] else f (n - length (SOME x. bufs' t = x @ bufs t \<and> set x = {(l, v). Write t l v \<in> ops} \<and> distinct x))"
in exI, rule no_atomic, auto)
apply (cut_tac P="\<lambda>up. bufs' t = up @ bufs t \<and> set up = {(l, v). Write t l v \<in> ops} \<and>
distinct up" in someI_ex, force, clarsimp)
apply (rule_tac x="SOME x. bufs' t = x @ bufs t \<and> set x = {(l, v). Write t l v \<in> ops} \<and> distinct x"
in exI, clarsimp)
apply (rule_tac s="add_red ((SOME x. bufs' t = x @ bufs t \<and> set x = {(l, v). Write t l v \<in> ops} \<and> distinct x) @ bufs t)
(\<lambda>n. if n < length (SOME x. bufs' t = x @ bufs t \<and> set x = {(l, v). Write t l v \<in> ops} \<and> distinct x) then []
else f (n - length (SOME x. bufs' t = x @ bufs t \<and> set x = {(l, v). Write t l v \<in> ops} \<and> distinct x)))"
in trans, simp, simp (no_asm))
apply (drule_tac bufs="bufs(t := add_red (bufs t) f)" and t=t and a="add_red buf f'" in process_buffer,
simp, clarsimp)
apply (subgoal_tac "dom (map_of (map (Pair l) (f' (length buf)))) = {l} \<or> f' (length buf) = []",
auto simp add: dom_map_of_conv_image_fst intro!: set_eqI)
apply (metis (full_types) append_Nil fst_conv imageI in_set_conv_decomp list.exhaust)
apply (drule_tac bufs="bufs(t := add_red (bufs t) f)" in update, simp, force,
force simp add: fun_upd_twist)
apply force
done
lemma can_read_red: "b' t = add_red (b t) f \<Longrightarrow> can_read (mem, b') t = can_read (mem, b) t"
by (clarsimp intro!: ext simp add: can_read_def split: option.splits)
lemma can_read_red_loc: "\<lbrakk>b' t = (l', v) # add_red (b t) f; l' \<noteq> l\<rbrakk> \<Longrightarrow>
can_read (mem, b') t l = can_read (mem, b) t l"
by (clarsimp intro!: ext simp add: can_read_def split: option.splits)
end
(* Sequential consistency memory model *)
locale SC = fixes undef::'val begin
abbreviation "free_set mem \<equiv> UNIV - dom mem"
abbreviation "can_read mem t l \<equiv> {v. mem l = Some v}"
inductive update_mem where
no_atomic [intro]: "\<lbrakk>\<And>t l v v'. ARW t l v v' \<notin> ops; \<And>l. (\<forall>t v. Write t l v \<notin> ops) \<Longrightarrow> writes l = None;
\<And>t l v. Write t l v \<in> ops \<Longrightarrow> \<exists>t v. Write t l v \<in> ops \<and> writes l = Some v; finite ops\<rbrakk> \<Longrightarrow>
update_mem mem ops (mem |` (UNIV - {l. \<exists>t. Free t l \<in> ops}) ++
(\<lambda>l. if \<exists>t. Alloc t l \<in> ops then Some undef else None) ++ writes)" |
atomic [intro!]: "update_mem mem {ARW t l v v'} (mem(l \<mapsto> v'))"
abbreviation "start_mem \<equiv> empty"
lemma update_threads: "\<lbrakk>update_mem mem ops mem'; \<forall>a'\<in>ops'. \<exists>a\<in>ops. \<exists>t. a' = set_thread (t::'t)
(a::('t, 'l, 'val) access)\<rbrakk> \<Longrightarrow> update_mem mem ops' mem'"
apply (drule_tac P="\<lambda>mem ops mem'. \<forall>ops'. (\<forall>a'\<in>ops'. \<exists>a\<in>ops. \<exists>t. a' = set_thread t a) \<longrightarrow>
update_mem mem ops' mem'" in update_mem.induct, auto)
apply (subgoal_tac "{l. \<exists>t. Free t l \<in> opsa} = {l. \<exists>t. Free t l \<in> ops'a} \<and> (\<lambda>l. if \<exists>t. Alloc t l \<in>
opsa then Some undef else None) = (\<lambda>l. if \<exists>t. Alloc t l \<in> ops'a then Some undef else None)", simp)
apply (rule no_atomic, clarsimp)
apply (thin_tac "\<forall>a'\<in>ops'. \<exists>a\<in>ops. \<exists>t. a' = set_thread t a")
apply (erule_tac x="ARW t l v v'" in ballE, simp_all, clarsimp)
apply (case_tac a, simp_all)
apply (subgoal_tac "\<forall>t v. Write t l v \<notin> opsa", simp, clarsimp)
oops
lemma update_threads: "update_mem mem ops mem' \<Longrightarrow> update_mem mem (set_thread t ` ops) mem'"
apply (drule_tac P="\<lambda>mem ops mem'. update_mem mem (set_thread t ` ops) mem'" in update_mem.induct, auto)
apply (subgoal_tac "{l. \<exists>t. Free t l \<in> ops} = {l. \<exists>ta. Free ta l \<in> set_thread t ` ops} \<and> (\<lambda>l. if
\<exists>t. Alloc t l \<in> ops then Some undef else None) = (\<lambda>l. if \<exists>ta. Alloc ta l \<in> set_thread t ` ops
then Some undef else None)", simp)
apply (rule no_atomic, clarsimp)
apply (case_tac x, simp_all)
apply (subgoal_tac "\<forall>t v. Write t l v \<notin> ops", simp, clarsimp)
apply (erule_tac x=t in allE, erule_tac x=v in allE, force simp add: image_def)
apply (subgoal_tac "\<exists>t v. Write t l v \<in> ops \<and> writes l = Some v", clarsimp simp add: image_def)
apply (rule_tac x=t in exI, rule_tac x="Write tb l va" in bexI, simp+)
apply (clarsimp simp add: image_def)
apply (case_tac x, simp_all)
apply (auto simp add: image_def)
apply (rule_tac x=t in exI, rule bexI, simp_all)
apply (case_tac xa, simp_all, metis)
apply (rule ext, auto)
apply (rule_tac x=t in exI, rule bexI, simp_all)
apply (case_tac x, simp_all)
done
lemma stays_not_free: "\<lbrakk>update_mem mem ops mem'; l \<notin> free_set mem; \<forall>t. Free t l \<notin> ops\<rbrakk> \<Longrightarrow>
l \<notin> free_set mem'"
by (induct rule: update_mem.induct, auto split: if_splits)
lemma alloc_not_free: "\<lbrakk>update_mem mem ops mem'; Alloc t l \<in> ops; Free t l \<notin> ops\<rbrakk> \<Longrightarrow>
l \<notin> free_set mem'"
by (induct rule: update_mem.induct, auto split: if_splits)
end
sublocale SC \<subseteq> memory_model free_set can_read update_mem start_mem
by (unfold_locales, metis alloc_not_free, metis stays_not_free)
context SC begin
lemma update_none [intro!, simp]: "update_mem C {} C"
by (cut_tac no_atomic, auto simp add: restrict_map_def)
lemma update_none_only [simp, dest!]: "update_mem mem {} mem' \<Longrightarrow> mem' = mem"
by (erule update_mem.cases, auto simp add: restrict_map_def map_add_def)
lemma update_one_write [intro!, simp]: "mem' = mem(l \<mapsto> v) \<Longrightarrow>
update_mem mem {Write t l v} mem'"
by (cut_tac ops="{Write t l v}" and writes="[l \<mapsto> v]" in no_atomic, auto simp add: restrict_map_def)
lemma update_one_writeD [dest!, simp]: "update_mem mem {Write t l v} mem' \<Longrightarrow> mem' = mem(l \<mapsto> v)"
by (erule update_mem.cases, auto intro!: ext simp add: map_add_def split: option.splits)
lemma update_one_read [intro, simp]: "update_mem mem {Read t l v} mem"
by (cut_tac ops="{Read t l v}" in no_atomic, auto simp add: restrict_map_def)
lemma update_one_readD [dest!, simp]: "update_mem mem {Read t l v} mem' \<Longrightarrow> mem' = mem"
by (erule update_mem.cases, auto intro!: ext simp add: restrict_map_def map_add_def)
lemma update_one_alloc [intro!, simp]: "mem' = mem(l \<mapsto> undef) \<Longrightarrow>
update_mem mem {Alloc t l} mem'"
apply (cut_tac ops="{Alloc t l}" and mem=mem in no_atomic, auto simp add: restrict_map_def)
apply (subgoal_tac "mem ++ (\<lambda>la. if la = l then Some undef else None) = mem(l \<mapsto> undef)", simp,
auto intro!: ext simp add: map_add_def)
done
lemma update_one_allocD [dest!]: "update_mem mem {Alloc t l} mem' \<Longrightarrow> mem' = mem(l \<mapsto> undef)"
by (erule update_mem.cases, auto simp add: restrict_map_def map_add_def)
lemma update_frees [intro!, simp]: "\<lbrakk>mem' = mem |` (UNIV - S); finite S\<rbrakk> \<Longrightarrow>
update_mem mem (Free t ` S) mem'"
apply (cut_tac ops="Free t ` S" and mem=mem in no_atomic, auto)
apply (rule subst, rule_tac f="update_mem mem (Free t ` S)" in arg_cong, simp_all)
apply (auto intro!: ext simp add: map_add_def restrict_map_def, force)
done
lemma update_freesD [dest!, simp]: "update_mem mem (Free t ` S) mem' \<Longrightarrow>
mem' = mem |` (UNIV - S)"
apply (erule update_mem.cases, auto intro!: ext simp add: map_add_def restrict_map_def
split: option.splits)
apply (metis image_eqI)
apply (metis access.distinct(13) image_iff option.distinct(1))
apply (metis image_eqI)
by (metis access.distinct(13) image_iff option.distinct(1))
lemma update_ARW [intro!]: "mem' = mem(l \<mapsto> v') \<Longrightarrow> update_mem mem {ARW t l v v'} mem'"
by clarsimp
lemma update_ARWD [dest!]: "update_mem mem {ARW t l v v'} mem' \<Longrightarrow> mem' = mem(l \<mapsto> v')"
by (erule update_mem.cases, auto)
lemma update_past: "\<lbrakk>update_mem mem ops mem'; \<And>t v. Write t l v \<notin> ops;
\<And>t v v'. ARW t l v v' \<notin> ops; \<And>t. Free t l \<notin> ops; \<And>t. Alloc t l \<notin> ops\<rbrakk> \<Longrightarrow>
update_mem (mem(l := v)) ops (mem'(l := v))"
apply (induct rule: update_mem.induct, auto)
apply (cut_tac ops=ops and mem="mem(l := v)" and writes=writes in no_atomic, auto)
apply (rule_tac f1="update_mem (mem(l := v))" in arg_cong2 [THEN subst],
auto intro!: ext simp add: map_add_def restrict_map_def split: option.splits)
by (metis atomic fun_upd_twist)
end
locale undef = fixes undef::'val
sublocale undef \<subseteq> TSO: TSO .
sublocale undef \<subseteq> SC: SC .
context undef begin
(* SC can be modeled by TSO. *)
(*
lemma process_all_buffers [rule_format]: "\<lbrakk>update_mem (mem, bufs) ops (mem', bufs');
\<forall>t. bufs' t = ma t @ mb t; finite {t. mb t \<noteq> []}\<rbrakk> \<Longrightarrow>
\<exists>m'. update_mem (mem, bufs) ops (mem' ++ m', (\<lambda>t. ma t)) \<and>
(\<forall>l v. ((m' l = Some v) \<longrightarrow> (\<exists>t. map_of (mb t) l = Some v)) \<and>
(m' l = None \<longrightarrow> (\<forall>t. map_of (mb t) l = None)))"
apply (drule_tac P="\<lambda>S. \<forall>mem' bufs' ma mb. (update_mem (mem, bufs) ops (mem', bufs') \<and>
(\<forall>t. bufs' t = ma t @ mb t)) \<and> S = {t. mb t \<noteq> []} \<longrightarrow>
(\<exists>m'. update_mem (mem, bufs) ops (mem' ++ m', (\<lambda>t. ma t)) \<and>
(\<forall>l v. ((m' l = Some v) \<longrightarrow> (\<exists>t. map_of (mb t) l = Some v)) \<and>
(m' l = None \<longrightarrow> (\<forall>t. map_of (mb t) l = None))))" in finite_induct, auto)
apply (rule_tac x=empty in exI, simp)
apply (subgoal_tac "bufs'a = maa", simp)
apply (auto intro!: ext split: option.split)
apply (cut_tac a=x and B=F in insertI1, clarsimp)
apply (thin_tac "\<forall>t. bufs' t = ma t @ mb t")
apply (drule_tac bufs'=bufs'a and t=x and a="ma x" in process_buffer, auto)
apply (erule_tac x="mem'a ++ map_of (mb x)" in allE, erule_tac x="bufs'a(x := ma x)" in allE,
erule_tac x=ma in allE, erule_tac x="mb(x := [])" in allE, clarsimp, erule impE, force, clarsimp)
apply (rule_tac x="map_of (mb x) ++ m'" in exI, auto split: if_splits, metis, metis)
apply (erule_tac x=mem' in allE, erule_tac x=bufs' in allE, simp)
done
lemma SC_lt_update [simp, intro]: "update_mem_SC mem ops mem' \<Longrightarrow>
update_mem (mem, \<lambda>t. []) ops (mem', \<lambda>t. [])"
apply (erule update_mem_SC.cases, auto split: if_splits)
apply (cut_tac ops=ops and mem=mem and bufs="\<lambda>t. []" and
bufs'="\<lambda>t. list_of_set {(l, v) | l v. Write t l v \<in> ops \<and> writes l = Some v} @
list_of_set {(l, v) | l v. Write t l v \<in> ops \<and> writes l \<noteq> Some v}" in no_atomic, simp_all)
apply (subgoal_tac "finite {(l, v). Write t l v \<in> ops}", auto)
apply (rule finite_vimageI, auto simp add: inj_on_def)
apply (drule_tac ma="\<lambda>t. list_of_set {(l, v) | l v. Write t l v \<in> ops \<and> writes l = Some v}" and
mb="\<lambda>t. list_of_set {(l, v) | l v. Write t l v \<in> ops \<and> writes l \<noteq> Some v}" in process_all_buffers)
apply (simp split: if_splits)
apply clarsimp
apply (rule_tac B="{t. \<exists>a \<in> ops. get_thread a = t}" in finite_subset, clarsimp)
apply (clarsimp simp add: card_gt_0_iff, rule_tac x="Write x a b" in bexI, simp+)
apply clarsimp
apply (drule_tac ma="\<lambda>t. []" and
mb="\<lambda>t. list_of_set {(l, v) | l v. Write t l v \<in> ops \<and> writes l = Some v}" in process_all_buffers)
apply (simp split: if_splits)
apply clarsimp
apply (rule_tac B="{t. \<exists>a \<in> ops. get_thread a = t}" in finite_subset, clarsimp)
apply (clarsimp simp add: card_gt_0_iff, rule_tac x="Write x a b" in bexI, simp+)
apply clarsimp
apply (rule_tac x1="(mem |` (UNIV - {l. \<exists>t. Free t l \<in> ops}) ++
(\<lambda>l. if \<exists>t. Alloc t l \<in> ops then Some undef else None) ++ m' ++ m'a, \<lambda>t. case case if t \<in> dom threads
then Some (list_of_set {(l, v) |l v. Write t l v \<in> ops \<and> writes l = Some v} @
list_of_set {(l, v) |l v. Write t l v \<in> ops \<and> writes l \<noteq> Some v})
else None of
None \<Rightarrow> None | Some x \<Rightarrow> Some (list_of_set {(l, v) |l v. Write t l v \<in> ops \<and> writes l = Some v}) of
None \<Rightarrow> None | Some x \<Rightarrow> Some [])" in cong [THEN subst], simp, auto)
apply (subgoal_tac "m' ++ m'a = writes")
apply (metis map_add_assoc)
apply (rule ext, (erule_tac x=x in allE)+, clarsimp simp add: map_add_def split: option.split)
apply (case_tac "writes x", simp_all)
apply (subgoal_tac "\<forall>t v. Write t x v \<notin> ops", rule ccontr, clarsimp, erule disjE,
clarsimp split: if_splits)
apply (drule map_of_is_SomeD)
apply (subgoal_tac "finite {(l, v). Write t l v \<in> ops}", simp+)
apply (rule finite_vimageI, simp, simp add: inj_on_def)
apply (clarsimp split: if_splits)
apply (drule map_of_is_SomeD)
apply (subgoal_tac "finite {(l, v). Write t l v \<in> ops}", simp+)
apply (rule finite_vimageI, simp, simp add: inj_on_def)
apply (metis not_Some_eq)
apply (subgoal_tac "\<exists>t. Write t x a \<in> ops", clarsimp)
apply (rule conjI, clarsimp)
apply (erule_tac x=t in allE)
apply (clarsimp simp add: map_of_eq_None_iff)
apply (subgoal_tac "finite {(l, v). Write t l v \<in> ops}", simp+)
apply (erule notE, rule_tac x="(x, a)" in image_eqI, simp+)
apply (rule finite_vimageI, simp, simp add: inj_on_def)
apply clarsimp
apply (drule map_of_is_SomeD)
apply (subgoal_tac "finite {(l, v). Write ta l v \<in> ops}", simp+)
apply (rule finite_vimageI, simp, simp add: inj_on_def)
by (metis (hide_lams, full_types) not_Some_eq option.inject)
lemma make_bufs_can_read [simp]: "can_read (mem, \<lambda>t. []) t = can_read_SC mem t"
by (rule ext, simp add: can_read_def)
(* Because can_read and update_mem are the only interfaces to the memory provided by memory_model,
this implies that SC refines TSO for any language. Is there a way to make this explicit? *)
*)
end
locale PSO = fixes undef::'val begin
(* PSO memory model *)
abbreviation "free_set mem \<equiv> UNIV - dom (fst mem)"
definition "can_read mem t l \<equiv> case snd mem t l of v # buf \<Rightarrow> {v}
| [] \<Rightarrow> {v. fst mem l = Some v}"
inductive update_mem where
no_atomic [intro]: "\<lbrakk>\<And>t l v v'. ARW t l v v' \<notin> ops; \<And>t l. \<exists>up. bufs' t l = up @ bufs t l \<and>
set up = {v. Write t l v \<in> ops} \<and> distinct up\<rbrakk> \<Longrightarrow>
update_mem (mem, bufs) ops (mem |` (UNIV - {l. \<exists>t. Free t l \<in> ops}) ++
(\<lambda>l. if \<exists>t. Alloc t l \<in> ops then Some undef else None), bufs')" |
update [intro]: "\<lbrakk>update_mem (mem, bufs) ops (mem', bufs'); bufs' t l = buf @ [v]\<rbrakk> \<Longrightarrow>
update_mem (mem, bufs) ops (mem'(l \<mapsto> v), bufs'(t := (bufs' t)(l := buf)))" |
atomic [intro!]: "bufs t l = [] \<Longrightarrow>
update_mem (mem, bufs) {ARW t l v v'} (mem(l \<mapsto> v'), bufs)"
abbreviation "start_mem \<equiv> (empty, \<lambda>t l. [])"
lemma alloc_not_free: "\<lbrakk>update_mem mem ops mem'; Alloc t l \<in> ops; \<forall>t. Free t l \<notin> ops\<rbrakk> \<Longrightarrow>
l \<notin> free_set mem'"
by (induct rule: update_mem.induct, auto split: if_splits)
lemma stays_not_free: "\<lbrakk>update_mem mem ops mem'; l \<notin> free_set mem; \<forall>t. Free t l \<notin> ops\<rbrakk> \<Longrightarrow>
l \<notin> free_set mem'"
by (induct rule: update_mem.induct, auto split: if_splits)
end
sublocale PSO \<subseteq> memory_model free_set can_read update_mem start_mem
by (unfold_locales, metis alloc_not_free, metis stays_not_free)
context PSO begin
lemma update_none [intro!, simp]: "update_mem C {} C"
by (cases C, cut_tac ops="{}" and mem=a and bufs=b in no_atomic, auto simp add: restrict_map_def)
lemma process_buffer: "\<lbrakk>update_mem (mem, bufs) ops (mem', bufs'); bufs' t l = a @ v # b\<rbrakk> \<Longrightarrow>
update_mem (mem, bufs) ops (mem'(l \<mapsto> v), bufs'(t := (bufs' t)(l := a)))"
apply (induct b arbitrary: mem' bufs' v rule: rev_induct, auto simp add: map_upd_triv)
apply (drule_tac t=t and l=l in update, simp, force)
done
lemma update_later: "\<lbrakk>update_mem (mem, bufs) {} (mem', bufs')\<rbrakk> \<Longrightarrow>
update_mem (mem, bufs) {Write t l v} (mem', bufs'(t := (bufs' t)(l := v # bufs' t l)))"
apply (drule_tac P="\<lambda>(mem, bufs) ops (mem', bufs'). ops = {} \<longrightarrow>
update_mem (mem, bufs) {Write t l v} (mem', bufs'(t := (bufs' t)(l := v # bufs' t l)))"
in update_mem.induct, auto)
apply (cut_tac ops="{Write t l v}" in no_atomic, auto)
apply (drule_tac ops="{Write t l v}" in update, auto)
apply (drule_tac ops="{Write t l v}" and t=ta in update, auto simp add: fun_upd_twist)
apply (drule_tac ops="{Write t l v}" and l=la in update, auto simp add: fun_upd_twist)
apply (drule_tac ops="{Write t l v}" and t=ta in update, auto simp add: fun_upd_twist)
done
lemma update_later2: "\<lbrakk>update_mem (mem, bufs) {} (mem', bufs'(t := (bufs' t)(l := buf)));
bufs' t l = v # buf\<rbrakk> \<Longrightarrow> update_mem (mem, bufs) {Write t l v} (mem', bufs')"
by (smt fun_upd_idem_iff fun_upd_upd list.inject update_later)
lemma update_past2: "\<lbrakk>update_mem (mem, bufs) ops (mem', bufs');
\<And>v. Write t l v \<notin> ops; \<And>l v v'. ARW t l v v' \<notin> ops\<rbrakk> \<Longrightarrow>
update_mem (mem, bufs(t := (bufs t)(l := b @ bufs t l))) ops
(mem', bufs'(t := (bufs' t)(l := b @ bufs' t l)))"
apply (drule_tac P="\<lambda>(mem, bufs) ops (mem', bufs'). (\<forall>v. Write t l v \<notin> ops) \<and>
(\<forall>l v v'. ARW t l v v' \<notin> ops) \<longrightarrow> update_mem (mem, bufs(t := (bufs t)(l := b @ bufs t l))) ops
(mem', bufs'(t := (bufs' t)(l := b @ bufs' t l)))" in update_mem.induct, auto)
apply (rule no_atomic, auto)
apply (subgoal_tac "\<exists>up. bufs' t l = up @ bufs t l \<and> set up = {v. Write t l v \<in> opsa} \<and>
distinct up", simp)
apply (metis (full_types))
apply (drule_tac bufs="bufs(t := (bufs t)(l := b @ bufs t l))" in update, auto)
apply (drule_tac bufs="bufs(t := (bufs t)(l := b @ bufs t l))" and t=ta in update,
auto simp add: fun_upd_twist)
apply (drule_tac bufs="bufs(t := (bufs t)(l := b @ bufs t l))" in update,
auto simp add: fun_upd_twist)
apply (drule_tac bufs="bufs(t := (bufs t)(l := b @ bufs t l))" and t=ta in update,
auto simp add: fun_upd_twist)
done
lemma update_write: "\<lbrakk>update_mem (mem, bufs) {Write t l v} (mem', bufs')\<rbrakk> \<Longrightarrow>
update_mem (mem, bufs(t := (bufs t)(l := v # bufs t l))) {} (mem', bufs')"
apply (drule_tac P="\<lambda>(mem, bufs) ops (mem', bufs'). ops = {Write t l v} \<longrightarrow>
update_mem (mem, bufs(t := (bufs t)(l := v # bufs t l))) {} (mem', bufs')"
in update_mem.induct, auto)
apply (cut_tac ops="{}" and bufs="bufs(t := (bufs t)(l := v # bufs t l))" and
bufs'=bufs' in no_atomic, simp_all)
apply (subgoal_tac "\<exists>up. bufs' ta la = up @ bufs ta la \<and> set up = {va. va = v \<and> ta = t \<and> la = l} \<and>
distinct up", clarify, auto)
apply (case_tac up, auto, case_tac list, auto)
done
lemma update_trans_rev: "\<lbrakk>update_mem (mem', bufs') {} (mem'', bufs'');
update_mem (mem, bufs) ops (mem', bufs')\<rbrakk> \<Longrightarrow> update_mem (mem, bufs) ops (mem'', bufs'')"
apply (drule_tac P="\<lambda>(mem', bufs') ops' (mem'', bufs''). ops' = {} \<and> update_mem (mem, bufs) ops (mem', bufs') \<longrightarrow>
update_mem (mem, bufs) ops (mem'', bufs'')" in update_mem.induct, auto simp add: restrict_map_def)
apply (subgoal_tac "bufs'a = bufsa", auto)
done
end
*)
(* In PSO, redundant elements are added to the buffers for individual locations. *)
definition "add_red2 l f = concat (map (\<lambda>(v, n). v # f n) (zip l [0..<length l]))"
lemma add_red2_nil [simp]: "add_red2 [] f = []"
by (simp add: add_red2_def)
lemma upt_0 [simp]: "j > i \<Longrightarrow> [i..<j] ! 0 = i"
by (induct i, auto)
lemma add_red2_nil2 [simp]: "(add_red2 l f = []) = (l = [])"
apply (auto simp add: add_red2_def)
apply (case_tac l, auto)
apply (erule_tac x="(a, 0)" in ballE, auto simp add: set_conv_nth)
apply (erule_tac x=0 in allE, auto)
by (metis gr_implies_not0 le0 upt_0 upt_Suc zero_less_Suc)
lemma map_upt_zip_Suc2 [simp]: "l' = map (\<lambda>(x, n). (x, Suc n)) l \<Longrightarrow> map (\<lambda>(v, n). v # f n) l' =
map (\<lambda>(v, n). v # f (Suc n)) l"
by auto
lemma add_red2_cons [simp]: "add_red2 (x # l) f = x # f 0 @ add_red2 l (\<lambda>n. f (Suc n))"
apply (auto simp add: add_red2_def)
apply (case_tac "map (\<lambda>(v, n). v # f n) (zip (x # l) ([0..<length l] @ [length l]))", auto)
apply (case_tac "[0..<length l] @ [length l]", auto)
apply (case_tac "[0..<length l] @ [length l]", auto)
apply (case_tac "[0..<length l] @ [length l]", auto)
apply (cut_tac i=0 and j="Suc (length l)" and x=b and xs=list in upt_eq_Cons_conv, auto)
apply (rule_tac f=concat in arg_cong)
apply (rule map_upt_zip_Suc2)
by (metis upt_Suc_append zip_Suc)
lemma add_red2_app [simp]: "add_red2 (l @ l') f = add_red2 l f @ add_red2 l' (\<lambda>n. f (n + length l))"
by (induct l arbitrary: f, auto)
lemma add_red2_id [simp]: "(\<And>n. n < length l \<Longrightarrow> f n = []) \<Longrightarrow> add_red2 l f = l"
by (induct l arbitrary: f, auto)
context PSO begin
lemma update_red2: "\<lbrakk>update_mem (mem, bufs) ops (mem', bufs');
\<And>t l. red t l = add_red2 (bufs t l) (f t l)\<rbrakk> \<Longrightarrow>
\<exists>red' f'. update_mem (mem, red) ops (mem', red') \<and>
(\<forall>t l. red' t l = add_red2 (bufs' t l) (f' t l))"
apply (drule_tac P="\<lambda>(mem, bufs) ops (mem', bufs'). (\<forall>t l. red t l = add_red2 (bufs t l) (f t l)) \<longrightarrow>
(\<exists>red' f'. update_mem (mem, red) ops (mem', red') \<and> (\<forall>t l. red' t l = add_red2 (bufs' t l) (f' t l)))"
in update_mem.induct, auto)
apply (rule_tac x="\<lambda>t l. (SOME up. bufs' t l = up @ (bufsa t l) \<and> set up = {v. Write t l v \<in> ops} \<and>
distinct up) @ red t l" in exI, auto)
apply (rule no_atomic, simp_all)
apply (cut_tac P="\<lambda>up. bufs' t l = up @ bufsa t l \<and> set up = {v. Write t l v \<in> ops} \<and>
distinct up" in someI_ex, simp+)
apply (rule_tac x="\<lambda>t l n. if n < length (SOME up. bufs' t l = up @ bufsa t l \<and> set up =
{v. Write t l v \<in> ops} \<and> distinct up) then [] else f t l (n - length (SOME up. bufs' t l =
up @ bufsa t l \<and> set up = {v. Write t l v \<in> ops} \<and> distinct up))" in exI, clarsimp)
apply (subgoal_tac "\<exists>up. bufs' t l = up @ bufsa t l \<and> set up = {v. Write t l v \<in> ops} \<and> distinct up",
clarify, clarsimp)
apply (cut_tac P="\<lambda>upa. up = upa \<and> set upa = {v. Write t l v \<in> ops} \<and> distinct upa" in someI,
force, clarsimp)
apply metis
apply (drule_tac bufs=red and t=t and l=l and a="add_red2 buf (f' t l)" in process_buffer, force)
apply (rule_tac x="red'(t := (red' t)(l := add_red2 buf (f' t l)))" in exI, clarsimp, metis)
apply (rule_tac x=red in exI, auto)
done
lemma update_red2_one_buf: "\<lbrakk>update_mem (mem, bufs) ops (mem', bufs');
\<And>t'. t' \<noteq> t \<Longrightarrow> red t' = bufs t'; \<And>l. red t l = add_red2 (bufs t l) (f l)\<rbrakk> \<Longrightarrow>
\<exists>red' f'. update_mem (mem, red) ops (mem', red') \<and> (\<forall>t'. t' \<noteq> t \<longrightarrow> red' t' = bufs' t') \<and>
(\<forall>l. red' t l = add_red2 (bufs' t l) (f' l))"
apply (drule_tac P="\<lambda>(mem, bufs) ops (mem', bufs'). ((\<forall>t'. t' \<noteq> t \<longrightarrow> red t' = bufs t') \<and>
(\<forall>l. red t l = add_red2 (bufs t l) (f l))) \<longrightarrow> (\<exists>red' f'. update_mem (mem, red) ops (mem', red') \<and>
(\<forall>t'. t' \<noteq> t \<longrightarrow> red' t' = bufs' t') \<and> (\<forall>l. red' t l = add_red2 (bufs' t l) (f' l)))"
in update_mem.induct, simp_all, clarsimp)
apply (rule_tac x="bufs'(t := \<lambda>l. (SOME up. bufs' t l = up @ (bufsa t l) \<and> set up = {v. Write t l v \<in> ops} \<and>
distinct up) @ red t l)" in exI, clarsimp)
apply (rule conjI, rule no_atomic, simp_all)
apply (cut_tac P="\<lambda>up. bufs' t l = up @ bufsa t l \<and> set up = {v. Write t l v \<in> ops} \<and>
distinct up" in someI_ex, simp+)
apply (rule_tac x="\<lambda>l n. if n < length (SOME up. bufs' t l = up @ bufsa t l \<and> set up =
{v. Write t l v \<in> ops} \<and> distinct up) then [] else f l (n - length (SOME up. bufs' t l =
up @ bufsa t l \<and> set up = {v. Write t l v \<in> ops} \<and> distinct up))" in exI, clarsimp)
apply (subgoal_tac "\<exists>up. bufs' t l = up @ bufsa t l \<and> set up = {v. Write t l v \<in> ops} \<and> distinct up",
clarify, clarsimp)
apply (cut_tac P="\<lambda>upa. up = upa \<and> set upa = {v. Write t l v \<in> ops} \<and> distinct upa" in someI,
force, clarsimp)
apply metis
apply auto
apply (drule_tac bufs=red and t=t and l=l in process_buffer, force)
apply (rule_tac x="red'(t := (red' t)(l := add_red2 buf (f' l)))" in exI, clarsimp, metis)
apply (drule_tac bufs=red and t=ta and l=l in process_buffer, force)
apply (rule_tac x="red'(ta := (red' ta)(l := buf))" in exI, clarsimp, metis)
apply (rule_tac x=red in exI, auto)
apply (case_tac "ta = t", auto)
done
lemma can_read_red [simp]: "b' t l = add_red2 (b t l) f \<Longrightarrow>
can_read (mem, b') t l = can_read (mem, b) t l"
by (clarsimp intro!: ext simp add: can_read_def split: list.splits)
lemma can_read_loc: "b' t l = b t l \<Longrightarrow>
can_read (mem, b') t l = can_read (mem, b) t l"
by (clarsimp intro!: ext simp add: can_read_def split: list.splits)
lemma two_part_buf [simp]: "bufs t l = buf \<Longrightarrow> bufs(t := (bufs t)(l := buf)) = bufs"
by (clarsimp intro!: ext)
end
*)
end
|
function H= grid_addBars(fv, varargin)
%GRID_ADDBARS - Add a Colorbar to the Bottom of Each Subplot of a Grid Plot
%
%Synopsis:
% H= grid_addBars(FV, <opt>)
%
%Input:
% FV: data structure (like epo)
% OPT: struct or property/value list of optional properties:
% .Height - Height of the colorbar
% .HScale - Handle to the scale of the grid plot (returned by
% grid_plot as .scale), a colorbar will be placed next to
% the scale
% .ShiftAxes - 'position' or 'ylim'
% .CLim - Color limit of colorbar, either a 1-by-2 vector giving
% the limit or 'auto' (default)
% .Colormap - The colormap of colorbar, either a x-by-3 vector giving
% the explicit map, or one of the predefined maps (see
% help of 'colormap')
% .Channels - Channels for which bar should be added, either a cell
% of strings giving the channels names, or en empty array
% for all channels, or 'plus'
% .Scale* - with * in {'Height','Width','VPos','LeftShift',
% 'FontSize','Digits','Unit'} define the appearance of
% the scale
%
%Output:
% H - handle to graphic objects
%
%Caveat:
% You have to make sure that the FV data fits to the data that was displayed
% with grid_plot before (e.g. for the length of the vector in the time
% dimension). The channels are matched automatically. FV may have less
% channels than displayed by grid_plot.
%
%Example:
% H= grid_plot(epo, mnt, defopt_erps)
% epo_rsq= proc_r_square_signed(epo);
% grid_addBars(epo_rsq, 'HScale',H.scale)
props= {'VPos', 0, 'DOUBLE';
'Height', 1/15, 'DOUBLE';
'ShiftAxes', 'ylim', 'CHAR';
'ShiftAlso', {'scale'}, 'CELL{CHAR}';
'CLim', 'auto', 'CHAR|DOUBLE[2]';
'Colormap', flipud(gray(32)), 'DOUBLE[- 3]';
'UseLocalColormap', 1, 'BOOL';
'MoveBack', 0, 'BOOL';
'Box', 'on', 'CHAR';
'Visible', 'off', 'CHAR';
'AlphaStepsMode', 0, 'BOOL';
'HScale', [], 'STRUCT(ax)';
'ScaleHeight', .66, 'DOUBLE';
'ScaleWidth', .075, 'DOUBLE';
'ScaleVPos', .25, 'DOUBLE';
'ScaleLeftShift', .05, 'DOUBLE';
'ScaleFontSize', get(gca,'FontSize'), 'DOUBLE';
'ScaleDigits', 4 'DOUBLE';
'ScaleUnit', '' 'CHAR';
'Channels', '*' 'CHAR|DOUBLE'};
if nargin==0,
H= props; return
end
opt= opt_proplistToStruct(varargin{:});
[opt, isdefault]= opt_setDefaults(opt, props);
opt_checkProplist(opt, props);
if ndims(fv.x)>2
error('only one Class allowed');
end
if min(fv.x(:))<0,
if isdefault.CLim,
opt.CLim= 'sym';
end
end
if isdefault.Colormap && ...
(isequal(opt.CLim,'sym') || (isnumeric(opt.CLim) && opt.CLim(1)<0)),
opt.Colormap= cmap_posneg(21);
end
if isdefault.AlphaStepsMode && ...
isfield(fv, 'ClassName') && ...
~isempty(findstr(fv.ClassName{1},'alpha-steps')),
opt.AlphaStepsMode= 1;
end
if opt.AlphaStepsMode,
nValues= length(fv.alpha);
[opt, isdefault]= ...
opt_overrideIfDefault(opt, isdefault, ...
'CLim', [0 nValues], ...
'Colormap', flipud(gray(nValues+1)), ...
'ScaleUnit', '%');
end
if isdefault.ScaleUnit && isfield(fv, 'yUnit'),
opt.ScaleUnit= fv.yUnit;
end
if isdefault.ScaleVPos && isempty(opt.ScaleUnit),
opt.ScaleVPos= 0.5;
end
if isdefault.Visible && strcmpi(opt.Box, 'on'),
opt.Visible= 'on';
end
if isdefault.UseLocalColormap,
if visutil_isColormapUsed && ~isequal(opt.Colormap, get(gcf, 'colormap')),
opt.UseLocalColormap= 1;
end
end
[AxesStyle, lineStyle]= opt_extractPlotStyles(opt);
if opt.UseLocalColormap,
iswhite= find(all(opt.Colormap==1,2));
if ~isempty(iswhite),
opt.Colormap(iswhite,:)= 0.9999*[1 1 1];
end
H.image= 'sorry: fakeimage - no handle';
else
set(gcf, 'colormap',opt.Colormap);
end
if isnumeric(opt.Channels)
ax= opt.Channels;
else
ax= gridutil_getSubplots(opt.Channels);
end
% For image_localColormap we have to determine the CLim in advance.
% Therefore we need to determine the depicted channels.
% (If only image was used, this functions would be simpler.)
clab= cell(1, length(ax));
for ii= 1:length(ax),
clab{ii}= getfield(get(ax(ii), 'userData'), 'chan');
if iscell(clab{ii}),
clab{ii}= clab{ii}{1}; % for multiple channels per ax, choose only
% the first one
end
end
if strcmpi(opt.CLim, 'auto'),
ci= util_chanind(fv, clab);
mi= min(min(fv.x(:,ci)));
if mi>=0 && isdefault.CLim,
warning('know-it-all: switching to CLim mode ''0tomax''');
opt.CLim= '0tomax';
else
opt.CLim= [mi max(max(fv.x(:,ci)))];
end
elseif strcmpi(opt.CLim, 'sym'),
ci= util_chanind(fv, clab);
mi= min(min(fv.x(:,ci)));
ma= max(max(fv.x(:,ci)));
mm= max(abs(mi), ma);
opt.CLim= [-mm mm];
end
if strcmpi(opt.CLim, '0tomax'),
ci= util_chanind(fv, clab);
opt.CLim= [0 max(max(fv.x(:,ci)))];
end
jj= 0;
for ii= 1:length(ax),
set(ax(ii), 'YLimMode','manual');
ud= get(ax(ii), 'userData');
if iscell(ud.chan),
ud.chan= ud.chan{1}; % for multiple channels per axis take only the first
end
ci= util_chanind(fv, ud.chan);
if isempty(ci) && isempty(strmatch(ud.chan,opt.ShiftAlso,'exact')),
continue;
end
pos= get(ax(ii), 'position');
bar_pos= [pos(1:3) opt.Height*pos(4)];
bar_pos(2)= pos(2) + opt.VPos*(1-opt.Height)*pos(4);
switch(opt.ShiftAxes)
case {1,'position'},
if opt.VPos<0.5,
new_pos= [pos(1) pos(2)+bar_pos(4) pos(3) pos(4)*(1-opt.Height)];
else
new_pos= [pos(1:3) pos(4)*(1-opt.Height)];
if opt.VPos==1,
axis_raiseTitle(ax(ii), opt.Height);
end
end
set(ax(ii), 'position',new_pos);
case {2,'ylim'},
yLim= get(ax(ii), 'yLim');
if opt.VPos<0.5,
yLim(1)= yLim(1) - opt.Height*diff(yLim);
else
yLim(2)= yLim(2) + opt.Height*diff(yLim);
end
set(ax(ii), 'yLim',yLim);
otherwise,
error('ShiftAxes policy not known');
end
if isempty(ci),
continue;
end
jj= jj+1;
H.ax(jj)= axes('position', bar_pos);
set(H.ax(jj), AxesStyle{:});
hold on; % otherwise axis properties like ColorOrder are lost
if opt.UseLocalColormap,
fv.x(fv.x > opt.CLim(2)) = opt.CLim(2);
fv.x(fv.x < opt.CLim(1)) = opt.CLim(1);
image_localColormap(fv.x(:,ci)', opt.Colormap, 'CLim',opt.CLim);
else
H.image(jj)= image(fv.x(:,ci)', 'cDataMapping','scaled');
end
set(H.ax(jj), AxesStyle{:});
ud= struct('type','ERP plus: bar', 'chan', str_vec2str(fv.clab(ci)));
set(H.ax(jj), 'userData',ud);
hold off;
if strcmp(get(H.ax(jj), 'box'), 'on'),
set(H.ax(jj), 'LineWidth',0.3);
axis_redrawFrame(H.ax(jj));
end
end
if diff(opt.CLim)==0, opt.CLim(2)= opt.CLim(2)+eps; end
set(H.ax, 'xLim',[0.5 size(fv.x,1)+0.5], 'xTick',[], 'yTick',[], ...
'CLim',opt.CLim);
if opt.MoveBack,
obj_moveBack(H.ax);
end
if ~isempty(opt.HScale),
pos= get(opt.HScale.ax, 'position');
dh= pos(4)*(1-opt.ScaleHeight)*opt.ScaleVPos;
pos_cb= [pos(1)+(1-opt.ScaleWidth-opt.ScaleLeftShift)*pos(3) pos(2)+dh ...
opt.ScaleWidth*pos(3) opt.ScaleHeight*pos(4)];
H.scale.ax= axes('position', pos_cb);
CLim= opt.CLim;
colbar= linspace(CLim(1), CLim(2), size(opt.Colormap,1));
if opt.UseLocalColormap,
image_localColormap(colbar', opt.Colormap, 'CLim',opt.CLim);
else
H.scale.im= imagesc(1, colbar, [1:size(opt.Colormap,1)]');
end
axis_redrawFrame(H.scale.ax);
if opt.AlphaStepsMode,
yTick= 0:nValues;
if opt.UseLocalColormap, yTick= yTick+1; end %% Just a hack...
set(H.scale.ax, 'yTick',yTick, 'yTickLabel',100*[1 fv.alpha]);
else
ticks= visutil_goodContourValues(CLim(1), CLim(2), -3);
tickLabels= util_trunc(ticks, opt.ScaleDigits);
if opt.UseLocalColormap,
YLim= get(gca,'YLim');
ticks= (ticks-CLim(1))*diff(YLim)/diff(CLim)+YLim(1);
end
set(H.scale.ax, 'yTick',ticks, 'yTickLabel',tickLabels);
end
set(H.scale.ax, 'xTick',[], 'tickLength',[0 0], 'YDir','normal', ...
'FontSize',opt.ScaleFontSize);
if ~isempty(opt.ScaleUnit),
yLim= get(H.scale.ax, 'yLim');
H.scale.unit= text(1, yLim(2), opt.ScaleUnit);
set(H.scale.unit, 'horizontalAli','center', 'verticalAli','bottom');
end
end
if nargout==0,
clear H;
end
|
#' runQuest function
#'
#' This function builds a ggplot2 function to plot data
#' @param t Table of data
#' @param c Selected column to test
#' @param lim Limit to number of levels
#' @keywords factor limits
#' runQuest()
runQuest<-function(){
appDir<-system.file("quest", package = "quest")
if(appDir==""){
stop("Could not find directory. Try re-installing `quest`.", call. = FALSE)
}
shiny::runApp(appDir)
}
|
As of the end of the 2014 – 15 season , Aston Villa have spent 104 seasons in the top tier of English football ; the only club to have spent longer in the top flight are Everton , with 112 seasons , making Aston Villa versus Everton the most @-@ played fixture in English top @-@ flight football . Aston Villa were in an elite group of seven clubs that has played in every Premier League season , the other six being Tottenham Hotspur , Chelsea , Everton , Liverpool , Manchester United and Arsenal since its establishment in 1992 – 93 until they were relegated in 2016 . They are seventh in the All @-@ time FA Premier League table , and have the fifth highest total of major honours won by an English club with 21 wins .
|
[STATEMENT]
lemma horizontal_identity_is_ide:
assumes "H.ide \<mu>"
shows "ide \<mu>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ide \<mu>
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. ide \<mu>
[PROOF STEP]
have \<mu>: "arr \<mu>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. arr \<mu>
[PROOF STEP]
using assms H.ide_def composable_implies_arr(2)
[PROOF STATE]
proof (prove)
using this:
H.ide \<mu>
H.ide ?a \<equiv> ?a \<star> ?a \<noteq> H.null \<and> (\<forall>f. (f \<star> ?a \<noteq> H.null \<longrightarrow> f \<star> ?a = f) \<and> (?a \<star> f \<noteq> H.null \<longrightarrow> ?a \<star> f = f))
?\<nu> \<star> ?\<mu> \<noteq> null \<Longrightarrow> arr ?\<nu>
goal (1 subgoal):
1. arr \<mu>
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
arr \<mu>
goal (1 subgoal):
1. ide \<mu>
[PROOF STEP]
hence 1: "\<mu> \<star> dom \<mu> \<noteq> null"
[PROOF STATE]
proof (prove)
using this:
arr \<mu>
goal (1 subgoal):
1. \<mu> \<star> local.dom \<mu> \<noteq> null
[PROOF STEP]
using assms hom_connected H.ide_def
[PROOF STATE]
proof (prove)
using this:
arr \<mu>
H.ide \<mu>
(?\<nu> \<star> ?\<mu> \<noteq> null) = (local.dom ?\<nu> \<star> ?\<mu> \<noteq> null)
(?\<nu> \<star> ?\<mu> \<noteq> null) = (?\<nu> \<star> local.dom ?\<mu> \<noteq> null)
(?\<nu> \<star> ?\<mu> \<noteq> null) = (cod ?\<nu> \<star> ?\<mu> \<noteq> null)
(?\<nu> \<star> ?\<mu> \<noteq> null) = (?\<nu> \<star> cod ?\<mu> \<noteq> null)
H.ide ?a \<equiv> ?a \<star> ?a \<noteq> H.null \<and> (\<forall>f. (f \<star> ?a \<noteq> H.null \<longrightarrow> f \<star> ?a = f) \<and> (?a \<star> f \<noteq> H.null \<longrightarrow> ?a \<star> f = f))
goal (1 subgoal):
1. \<mu> \<star> local.dom \<mu> \<noteq> null
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
\<mu> \<star> local.dom \<mu> \<noteq> null
goal (1 subgoal):
1. ide \<mu>
[PROOF STEP]
have "\<mu> \<star> dom \<mu> = dom \<mu>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<mu> \<star> local.dom \<mu> = local.dom \<mu>
[PROOF STEP]
using assms 1 H.ide_def
[PROOF STATE]
proof (prove)
using this:
H.ide \<mu>
\<mu> \<star> local.dom \<mu> \<noteq> null
H.ide ?a \<equiv> ?a \<star> ?a \<noteq> H.null \<and> (\<forall>f. (f \<star> ?a \<noteq> H.null \<longrightarrow> f \<star> ?a = f) \<and> (?a \<star> f \<noteq> H.null \<longrightarrow> ?a \<star> f = f))
goal (1 subgoal):
1. \<mu> \<star> local.dom \<mu> = local.dom \<mu>
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<mu> \<star> local.dom \<mu> = local.dom \<mu>
goal (1 subgoal):
1. ide \<mu>
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
\<mu> \<star> local.dom \<mu> = local.dom \<mu>
goal (1 subgoal):
1. ide \<mu>
[PROOF STEP]
have "\<mu> \<star> dom \<mu> = \<mu>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<mu> \<star> local.dom \<mu> = \<mu>
[PROOF STEP]
using assms 1 H.ide_def [of \<mu>] null_agreement
[PROOF STATE]
proof (prove)
using this:
H.ide \<mu>
\<mu> \<star> local.dom \<mu> \<noteq> null
H.ide \<mu> \<equiv> \<mu> \<star> \<mu> \<noteq> H.null \<and> (\<forall>f. (f \<star> \<mu> \<noteq> H.null \<longrightarrow> f \<star> \<mu> = f) \<and> (\<mu> \<star> f \<noteq> H.null \<longrightarrow> \<mu> \<star> f = f))
H.null = null
goal (1 subgoal):
1. \<mu> \<star> local.dom \<mu> = \<mu>
[PROOF STEP]
by (metis \<mu> cod_cod cod_dom hcomp_simps\<^sub>W\<^sub>C(3) ideD(2) ide_char' paste_1)
[PROOF STATE]
proof (state)
this:
\<mu> \<star> local.dom \<mu> = \<mu>
goal (1 subgoal):
1. ide \<mu>
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
\<mu> \<star> local.dom \<mu> = local.dom \<mu>
\<mu> \<star> local.dom \<mu> = \<mu>
[PROOF STEP]
have "dom \<mu> = \<mu>"
[PROOF STATE]
proof (prove)
using this:
\<mu> \<star> local.dom \<mu> = local.dom \<mu>
\<mu> \<star> local.dom \<mu> = \<mu>
goal (1 subgoal):
1. local.dom \<mu> = \<mu>
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
local.dom \<mu> = \<mu>
goal (1 subgoal):
1. ide \<mu>
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
local.dom \<mu> = \<mu>
goal (1 subgoal):
1. ide \<mu>
[PROOF STEP]
using \<mu>
[PROOF STATE]
proof (prove)
using this:
local.dom \<mu> = \<mu>
arr \<mu>
goal (1 subgoal):
1. ide \<mu>
[PROOF STEP]
by (metis ide_dom)
[PROOF STATE]
proof (state)
this:
ide \<mu>
goal:
No subgoals!
[PROOF STEP]
qed |
State Before: α : Type u_1
β : Type ?u.1261185
γ : Type ?u.1261188
δ : Type ?u.1261191
m : MeasurableSpace α
μ ν : Measure α
inst✝⁴ : MeasurableSpace δ
inst✝³ : NormedAddCommGroup β
inst✝² : NormedAddCommGroup γ
E : Type u_2
m0 : MeasurableSpace α
inst✝¹ : NormedAddCommGroup E
inst✝ : SigmaFinite μ
C : ℝ≥0∞
hC : C < ⊤
f : α → E
hf_meas : AEStronglyMeasurable f μ
hf : ∀ (s : Set α), MeasurableSet s → ↑↑μ s ≠ ⊤ → (∫⁻ (x : α) in s, ↑‖f x‖₊ ∂μ) ≤ C
⊢ SigmaFinite (Measure.trim μ (_ : m ≤ m)) State After: no goals Tactic: rwa [@trim_eq_self _ m] |
/-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.list.sort
import Mathlib.data.multiset.basic
import Mathlib.data.string.basic
import Mathlib.PostPort
universes u_1
namespace Mathlib
/-!
# Construct a sorted list from a multiset.
-/
namespace multiset
/-- `sort s` constructs a sorted list from the multiset `s`.
(Uses merge sort algorithm.) -/
def sort {α : Type u_1} (r : α → α → Prop) [DecidableRel r] [is_trans α r] [is_antisymm α r] [is_total α r] (s : multiset α) : List α :=
quot.lift_on s (list.merge_sort r) sorry
@[simp] theorem coe_sort {α : Type u_1} (r : α → α → Prop) [DecidableRel r] [is_trans α r] [is_antisymm α r] [is_total α r] (l : List α) : sort r ↑l = list.merge_sort r l :=
rfl
@[simp] theorem sort_sorted {α : Type u_1} (r : α → α → Prop) [DecidableRel r] [is_trans α r] [is_antisymm α r] [is_total α r] (s : multiset α) : list.sorted r (sort r s) :=
quot.induction_on s fun (l : List α) => list.sorted_merge_sort r l
@[simp] theorem sort_eq {α : Type u_1} (r : α → α → Prop) [DecidableRel r] [is_trans α r] [is_antisymm α r] [is_total α r] (s : multiset α) : ↑(sort r s) = s :=
quot.induction_on s fun (l : List α) => quot.sound (list.perm_merge_sort r l)
@[simp] theorem mem_sort {α : Type u_1} (r : α → α → Prop) [DecidableRel r] [is_trans α r] [is_antisymm α r] [is_total α r] {s : multiset α} {a : α} : a ∈ sort r s ↔ a ∈ s :=
eq.mpr (id (Eq._oldrec (Eq.refl (a ∈ sort r s ↔ a ∈ s)) (Eq.symm (propext mem_coe))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a ∈ ↑(sort r s) ↔ a ∈ s)) (sort_eq r s))) (iff.refl (a ∈ s)))
@[simp] theorem length_sort {α : Type u_1} (r : α → α → Prop) [DecidableRel r] [is_trans α r] [is_antisymm α r] [is_total α r] {s : multiset α} : list.length (sort r s) = coe_fn card s :=
quot.induction_on s (list.length_merge_sort r)
protected instance has_repr {α : Type u_1} [has_repr α] : has_repr (multiset α) :=
has_repr.mk
fun (s : multiset α) =>
string.str string.empty (char.of_nat (bit1 (bit1 (bit0 (bit1 (bit1 (bit1 1))))))) ++
string.intercalate
(string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit1 (bit1 (bit0 1)))))))
(char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))))
(sort LessEq (map repr s)) ++
string.str string.empty (char.of_nat (bit1 (bit0 (bit1 (bit1 (bit1 (bit1 1)))))))
|
import Data.Vect
{-
data Vect : Nat -> Type -> Type where
Nil : Vect Z a
(::) : a -> Vect k a -> Vect (S k) a
-}
fourInts : Vect 4 Int
fourInts = [0, 1, 2, 3]
sixInts : Vect 6 Int
sixInts = [4, 5, 6, 7, 8, 9]
tenInts : Vect 10 Int
tenInts = fourInts ++ sixInts
--reverse fourInts
--map (\x => x+1) fourInts
|
(* Title: HOL/Auth/n_flash_nodata_cub_lemma_on_inv__77.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_flash_nodata_cub Protocol Case Study*}
theory n_flash_nodata_cub_lemma_on_inv__77 imports n_flash_nodata_cub_base
begin
section{*All lemmas on causal relation between inv__77 and some rule r*}
lemma n_PI_Remote_GetVsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Get src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Remote_GetXVsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_GetX src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Remote_PutXVsinv__77:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_PI_Remote_PutX dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Remote_ReplaceVsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Replace src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_NakVsinv__77:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Nak dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__0Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__1Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__2Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__0Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__1Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_HeadVsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_PutVsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_DirtyVsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_NakVsinv__77:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_PutVsinv__77:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_Put_HomeVsinv__77:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__0Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__1Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__2Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_GetX__part__0Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_GetX__part__1Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_GetX)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_1Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_2Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_3Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_4Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_5Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_6Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_HomeVsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8Vsinv__77:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__77:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10_HomeVsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10Vsinv__77:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_11Vsinv__77:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_NakVsinv__77:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutXVsinv__77:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutX_HomeVsinv__77:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutVsinv__77:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Put dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "((formEval (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true))) s))" by auto
moreover {
assume c1: "((formEval (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true)) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (neg (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately have "invHoldForRule s f r (invariants N)" by satx
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutXVsinv__77:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_PutX dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_InvVsinv__77:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Inv dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__77 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Local_GetX_PutX__part__0Vsinv__77:
assumes a1: "r=n_PI_Local_GetX_PutX__part__0 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_WbVsinv__77:
assumes a1: "r=n_NI_Wb " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_3Vsinv__77:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_1Vsinv__77:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__1Vsinv__77:
assumes a1: "r=n_PI_Local_GetX_GetX__part__1 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__0Vsinv__77:
assumes a1: "r=n_PI_Local_GetX_GetX__part__0 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_ReplaceVsinv__77:
assumes a1: "r=n_PI_Local_Replace " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_existsVsinv__77:
assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_PutXVsinv__77:
assumes a1: "r=n_PI_Local_PutX " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_PutVsinv__77:
assumes a1: "r=n_PI_Local_Get_Put " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_ShWbVsinv__77:
assumes a1: "r=n_NI_ShWb N " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__77:
assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__0 N " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_ReplaceVsinv__77:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Replace src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_Nak_HomeVsinv__77:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutXAcksDoneVsinv__77:
assumes a1: "r=n_NI_Local_PutXAcksDone " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__1Vsinv__77:
assumes a1: "r=n_PI_Local_GetX_PutX__part__1 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_Nak_HomeVsinv__77:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_exists_HomeVsinv__77:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Replace_HomeVsinv__77:
assumes a1: "r=n_NI_Replace_Home " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutVsinv__77:
assumes a1: "r=n_NI_Local_Put " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_ClearVsinv__77:
assumes a1: "r=n_NI_Nak_Clear " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_GetVsinv__77:
assumes a1: "r=n_PI_Local_Get_Get " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_HomeVsinv__77:
assumes a1: "r=n_NI_Nak_Home " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_2Vsinv__77:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__77:
assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__1 N " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_FAckVsinv__77:
assumes a1: "r=n_NI_FAck " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__77 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
Residential apartment units above Crepeville occasionally become available for rent. A (November 2005) Davis Enterprise advertisement described a 3 bedroom, 2 bath unit with washer/ dryer, central heat & air, gas range, CAT5 wiring, and two balconies overlooking Central Park. Asking price: $1,895 per month.
To learn more about rental housing in Davis, check out our Housing Guide as well as our Apartments pages.
20060717 11:37:35 nbsp Is this a nice place to live? Users/BrianDeLuca
20080531 17:39:42 nbsp The fact that its downtown and overlooks Central Park makes this so appealing to me. If I could afford it, Id totally move here. Users/SunjeetBaadkar
20080531 23:14:42 nbsp Dude, I would move if I could afford it. Users/CurlyGirl26
20080601 00:22:20 nbsp The location is great. What is the noise level like inside the apartments, with the restaurant right below? Users/IDoNotExist
20080601 12:09:00 nbsp I remember when this building didnt even exist... Users/StevenDaubert
20080601 13:17:35 nbsp I remember when Davisville first got dirt roads installed. My, that was a big improvement. The horses didnt have to step over as much stuff in the fields, and when your horse broke down, it was much easier to call for a toe (hoof) truck to replace your flat shoes.
But that was nothing compared to the sight of the dinosaurs who roamed around here 150 million years ago. Back then, the Sierras were just starting to get pushed up, and you cleared your own road with your dinosaur. (I had one of the new, fuel efficient, herbivores that used 10 times less energy than some of the meat eaters because you could convert the plants directly to energy. Unfortunately, those were big and ungainly, and I eventually traded in my old dinosaur of a dinosaur for a new, small, mammal. Then the meteor hit, and everyone realized that climate change wasnt just something that the scientists were talking about.)
I remember when Crepevilles building wasnt there too... Users/IDoNotExist
But you dont exist, so it doesnt count! Users/StevenDaubert
20080601 13:59:13 nbsp I remember when they were going to build a shopping center across the street from that building, where the gardens are now. Users/DonShor
20130129 21:16:39 nbsp Does anyone know if these apartments are loud because of Crepeville??? Users/TaylerAvakian
20130911 nbsp Does anyone have any pictures of what the apartment looks like on the inside? Users/MichelleNguyen
|
module Main
import System
import Effects
import Effect.Random
import Data.Vect
total
insert : Ord a => a -> Vect n a -> Vect (S n) a
insert x [] = [x]
insert x (y :: ys) = if (x < y) then x :: y :: ys else y :: insert x ys
vsort : Ord a => Vect n a -> Vect n a
vsort [] = []
vsort (x :: xs) = insert x (vsort xs)
mkSortVec : (n : Nat) -> Eff (Vect n Int) [RND]
mkSortVec Z = pure []
mkSortVec (S k) = pure (fromInteger !(rndInt 0 10000) :: !(mkSortVec k))
main : IO ()
main = do
arg <- getLine
let vec = runPure $ (srand 123456789 *> mkSortVec (fromInteger (cast arg)))
putStrLn "Made vector"
printLn (vsort vec)
|
[STATEMENT]
lemma b_rel_subtyping_merge_tL[sepref_frame_merge_rules]:
assumes "hn_ctxt A x y \<or>\<^sub>A hn_ctxt A' x y \<Longrightarrow>\<^sub>t hn_ctxt Am x y"
shows "hn_ctxt A x y \<or>\<^sub>A hn_ctxt (b_assn A' P') x y \<Longrightarrow>\<^sub>t hn_ctxt Am x y"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. hn_ctxt A x y \<or>\<^sub>A hn_ctxt (b_assn A' P') x y \<Longrightarrow>\<^sub>t hn_ctxt Am x y
[PROOF STEP]
using b_rel_subtyping_merge[of A x y A' Am "\<lambda>_. True" P', simplified] assms
[PROOF STATE]
proof (prove)
using this:
hn_ctxt A x y \<or>\<^sub>A hn_ctxt A' x y \<Longrightarrow>\<^sub>t hn_ctxt Am x y \<Longrightarrow> hn_ctxt A x y \<or>\<^sub>A hn_ctxt (b_assn A' P') x y \<Longrightarrow>\<^sub>t hn_ctxt Am x y
hn_ctxt A x y \<or>\<^sub>A hn_ctxt A' x y \<Longrightarrow>\<^sub>t hn_ctxt Am x y
goal (1 subgoal):
1. hn_ctxt A x y \<or>\<^sub>A hn_ctxt (b_assn A' P') x y \<Longrightarrow>\<^sub>t hn_ctxt Am x y
[PROOF STEP]
. |
lemma contour_integral_reverse_linepath: "continuous_on (closed_segment a b) f \<Longrightarrow> contour_integral (linepath a b) f = - (contour_integral(linepath b a) f)" |
/-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Scott Morrison
-/
import category_theory.opposites
import category_theory.groupoid
/-!
# Facts about epimorphisms and monomorphisms.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
The definitions of `epi` and `mono` are in `category_theory.category`,
since they are used by some lemmas for `iso`, which is used everywhere.
-/
universes v₁ v₂ u₁ u₂
namespace category_theory
variables {C : Type u₁} [category.{v₁} C]
instance unop_mono_of_epi {A B : Cᵒᵖ} (f : A ⟶ B) [epi f] : mono f.unop :=
⟨λ Z g h eq, quiver.hom.op_inj ((cancel_epi f).1 (quiver.hom.unop_inj eq))⟩
instance unop_epi_of_mono {A B : Cᵒᵖ} (f : A ⟶ B) [mono f] : epi f.unop :=
⟨λ Z g h eq, quiver.hom.op_inj ((cancel_mono f).1 (quiver.hom.unop_inj eq))⟩
instance op_mono_of_epi {A B : C} (f : A ⟶ B) [epi f] : mono f.op :=
⟨λ Z g h eq, quiver.hom.unop_inj ((cancel_epi f).1 (quiver.hom.op_inj eq))⟩
instance op_epi_of_mono {A B : C} (f : A ⟶ B) [mono f] : epi f.op :=
⟨λ Z g h eq, quiver.hom.unop_inj ((cancel_mono f).1 (quiver.hom.op_inj eq))⟩
/--
A split monomorphism is a morphism `f : X ⟶ Y` with a given retraction `retraction f : Y ⟶ X`
such that `f ≫ retraction f = 𝟙 X`.
Every split monomorphism is a monomorphism.
-/
@[ext, nolint has_nonempty_instance]
structure split_mono {X Y : C} (f : X ⟶ Y) :=
(retraction : Y ⟶ X)
(id' : f ≫ retraction = 𝟙 X . obviously)
restate_axiom split_mono.id'
attribute [simp, reassoc] split_mono.id
/-- `is_split_mono f` is the assertion that `f` admits a retraction -/
class is_split_mono {X Y : C} (f : X ⟶ Y) : Prop :=
(exists_split_mono : nonempty (split_mono f))
/-- A constructor for `is_split_mono f` taking a `split_mono f` as an argument -/
lemma is_split_mono.mk' {X Y : C} {f : X ⟶ Y} (sm : split_mono f) :
is_split_mono f := ⟨nonempty.intro sm⟩
/--
A split epimorphism is a morphism `f : X ⟶ Y` with a given section `section_ f : Y ⟶ X`
such that `section_ f ≫ f = 𝟙 Y`.
(Note that `section` is a reserved keyword, so we append an underscore.)
Every split epimorphism is an epimorphism.
-/
@[ext, nolint has_nonempty_instance]
structure split_epi {X Y : C} (f : X ⟶ Y) :=
(section_ : Y ⟶ X)
(id' : section_ ≫ f = 𝟙 Y . obviously)
restate_axiom split_epi.id'
attribute [simp, reassoc] split_epi.id
/-- `is_split_epi f` is the assertion that `f` admits a section -/
class is_split_epi {X Y : C} (f : X ⟶ Y) : Prop :=
(exists_split_epi : nonempty (split_epi f))
/-- A constructor for `is_split_epi f` taking a `split_epi f` as an argument -/
lemma is_split_epi.mk' {X Y : C} {f : X ⟶ Y} (se : split_epi f) :
is_split_epi f := ⟨nonempty.intro se⟩
/-- The chosen retraction of a split monomorphism. -/
noncomputable def retraction {X Y : C} (f : X ⟶ Y) [hf : is_split_mono f] : Y ⟶ X :=
hf.exists_split_mono.some.retraction
@[simp, reassoc]
lemma is_split_mono.id {X Y : C} (f : X ⟶ Y) [hf : is_split_mono f] : f ≫ retraction f = 𝟙 X :=
hf.exists_split_mono.some.id
/-- The retraction of a split monomorphism has an obvious section. -/
def split_mono.split_epi {X Y : C} {f : X ⟶ Y} (sm : split_mono f) : split_epi (sm.retraction) :=
{ section_ := f, }
/-- The retraction of a split monomorphism is itself a split epimorphism. -/
instance retraction_is_split_epi {X Y : C} (f : X ⟶ Y) [hf : is_split_mono f] :
is_split_epi (retraction f) :=
is_split_epi.mk' (split_mono.split_epi _)
/-- A split mono which is epi is an iso. -/
lemma is_iso_of_epi_of_is_split_mono {X Y : C} (f : X ⟶ Y) [is_split_mono f] [epi f] : is_iso f :=
⟨⟨retraction f, ⟨by simp, by simp [← cancel_epi f]⟩⟩⟩
/--
The chosen section of a split epimorphism.
(Note that `section` is a reserved keyword, so we append an underscore.)
-/
noncomputable def section_ {X Y : C} (f : X ⟶ Y) [hf : is_split_epi f] : Y ⟶ X :=
hf.exists_split_epi.some.section_
@[simp, reassoc]
lemma is_split_epi.id {X Y : C} (f : X ⟶ Y) [hf : is_split_epi f] : section_ f ≫ f = 𝟙 Y :=
hf.exists_split_epi.some.id
/-- The section of a split epimorphism has an obvious retraction. -/
def split_epi.split_mono {X Y : C} {f : X ⟶ Y} (se : split_epi f) : split_mono (se.section_) :=
{ retraction := f, }
/-- The section of a split epimorphism is itself a split monomorphism. -/
instance section_is_split_mono {X Y : C} (f : X ⟶ Y) [hf : is_split_epi f] :
is_split_mono (section_ f) :=
is_split_mono.mk' (split_epi.split_mono _)
/-- A split epi which is mono is an iso. -/
lemma is_iso_of_mono_of_is_split_epi {X Y : C} (f : X ⟶ Y) [mono f] [is_split_epi f] : is_iso f :=
⟨⟨section_ f, ⟨by simp [← cancel_mono f], by simp⟩⟩⟩
/-- Every iso is a split mono. -/
@[priority 100]
instance is_split_mono.of_iso {X Y : C} (f : X ⟶ Y) [is_iso f] : is_split_mono f :=
is_split_mono.mk' { retraction := inv f }
/-- Every iso is a split epi. -/
@[priority 100]
instance is_split_epi.of_iso {X Y : C} (f : X ⟶ Y) [is_iso f] : is_split_epi f :=
is_split_epi.mk' { section_ := inv f }
lemma split_mono.mono {X Y : C} {f : X ⟶ Y} (sm : split_mono f) : mono f :=
{ right_cancellation := λ Z g h w, begin replace w := w =≫ sm.retraction, simpa using w, end }
/-- Every split mono is a mono. -/
@[priority 100]
instance is_split_mono.mono {X Y : C} (f : X ⟶ Y) [hf : is_split_mono f] : mono f :=
hf.exists_split_mono.some.mono
lemma split_epi.epi {X Y : C} {f : X ⟶ Y} (se : split_epi f) : epi f :=
{ left_cancellation := λ Z g h w, begin replace w := se.section_ ≫= w, simpa using w, end }
/-- Every split epi is an epi. -/
@[priority 100]
instance is_split_epi.epi {X Y : C} (f : X ⟶ Y) [hf : is_split_epi f] : epi f :=
hf.exists_split_epi.some.epi
/-- Every split mono whose retraction is mono is an iso. -/
lemma is_iso.of_mono_retraction' {X Y : C} {f : X ⟶ Y} (hf : split_mono f)
[mono $ hf.retraction] : is_iso f :=
⟨⟨hf.retraction, ⟨by simp, (cancel_mono_id $ hf.retraction).mp (by simp)⟩⟩⟩
/-- Every split mono whose retraction is mono is an iso. -/
lemma is_iso.of_mono_retraction {X Y : C} (f : X ⟶ Y) [hf : is_split_mono f]
[hf' : mono $ retraction f] : is_iso f :=
@is_iso.of_mono_retraction' _ _ _ _ _ hf.exists_split_mono.some hf'
/-- Every split epi whose section is epi is an iso. -/
lemma is_iso.of_epi_section' {X Y : C} {f : X ⟶ Y} (hf : split_epi f)
[epi $ hf.section_] : is_iso f :=
⟨⟨hf.section_, ⟨(cancel_epi_id $ hf.section_).mp (by simp), by simp⟩⟩⟩
/-- Every split epi whose section is epi is an iso. -/
lemma is_iso.of_epi_section {X Y : C} (f : X ⟶ Y) [hf : is_split_epi f]
[hf' : epi $ section_ f] : is_iso f :=
@is_iso.of_epi_section' _ _ _ _ _ hf.exists_split_epi.some hf'
/-- A category where every morphism has a `trunc` retraction is computably a groupoid. -/
-- FIXME this has unnecessarily become noncomputable!
noncomputable
def groupoid.of_trunc_split_mono
(all_split_mono : ∀ {X Y : C} (f : X ⟶ Y), trunc (is_split_mono f)) :
groupoid.{v₁} C :=
begin
apply groupoid.of_is_iso,
intros X Y f,
trunc_cases all_split_mono f,
trunc_cases all_split_mono (retraction f),
apply is_iso.of_mono_retraction,
end
section
variables (C)
/-- A split mono category is a category in which every monomorphism is split. -/
class split_mono_category :=
(is_split_mono_of_mono : ∀ {X Y : C} (f : X ⟶ Y) [mono f], is_split_mono f)
/-- A split epi category is a category in which every epimorphism is split. -/
class split_epi_category :=
(is_split_epi_of_epi : ∀ {X Y : C} (f : X ⟶ Y) [epi f], is_split_epi f)
end
/-- In a category in which every monomorphism is split, every monomorphism splits. This is not an
instance because it would create an instance loop. -/
lemma is_split_mono_of_mono [split_mono_category C] {X Y : C} (f : X ⟶ Y) [mono f] :
is_split_mono f :=
split_mono_category.is_split_mono_of_mono _
/-- In a category in which every epimorphism is split, every epimorphism splits. This is not an
instance because it would create an instance loop. -/
lemma is_split_epi_of_epi [split_epi_category C] {X Y : C} (f : X ⟶ Y) [epi f] :
is_split_epi f := split_epi_category.is_split_epi_of_epi _
section
variables {D : Type u₂} [category.{v₂} D]
/-- Split monomorphisms are also absolute monomorphisms. -/
@[simps]
def split_mono.map {X Y : C} {f : X ⟶ Y} (sm : split_mono f) (F : C ⥤ D ) :
split_mono (F.map f) :=
{ retraction := F.map (sm.retraction),
id' := by { rw [←functor.map_comp, split_mono.id, functor.map_id], } }
/-- Split epimorphisms are also absolute epimorphisms. -/
@[simps]
def split_epi.map {X Y : C} {f : X ⟶ Y} (se : split_epi f) (F : C ⥤ D ) :
split_epi (F.map f) :=
{ section_ := F.map (se.section_),
id' := by { rw [←functor.map_comp, split_epi.id, functor.map_id], } }
instance {X Y : C} (f : X ⟶ Y) [hf : is_split_mono f] (F : C ⥤ D) : is_split_mono (F.map f) :=
is_split_mono.mk' (hf.exists_split_mono.some.map F)
instance {X Y : C} (f : X ⟶ Y) [hf : is_split_epi f] (F : C ⥤ D) : is_split_epi (F.map f) :=
is_split_epi.mk' (hf.exists_split_epi.some.map F)
end
end category_theory
|
module Demo.Other
%access public export
%default total
hello : String
hello = "hello"
|
The empty set is a domain. |
[STATEMENT]
lemma mor_Rep_IF:
"mor (UNIV :: 'a IF1 set) (UNIV :: 'a IF2 set) ctor1 ctor2
(car_init1 undefined) (car_init2 undefined) (str_init1 undefined) (str_init2 undefined) Rep_IF1 Rep_IF2"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. mor UNIV UNIV ctor1 ctor2 (car_init1 undefined) (car_init2 undefined) (str_init1 undefined) (str_init2 undefined) Rep_IF1 Rep_IF2
[PROOF STEP]
unfolding mor_def ctor1_def ctor2_def o_apply
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ((\<forall>a\<in>UNIV. Rep_IF1 a \<in> car_init1 undefined) \<and> (\<forall>a\<in>UNIV. Rep_IF2 a \<in> car_init2 undefined)) \<and> (\<forall>z\<in>F1in UNIV UNIV UNIV. Rep_IF1 (Abs_IF1 (str_init1 undefined (F1map id Rep_IF1 Rep_IF2 z))) = str_init1 undefined (F1map id Rep_IF1 Rep_IF2 z)) \<and> (\<forall>z\<in>F2in UNIV UNIV UNIV. Rep_IF2 (Abs_IF2 (str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))) = str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))
[PROOF STEP]
apply (rule conjI)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. (\<forall>a\<in>UNIV. Rep_IF1 a \<in> car_init1 undefined) \<and> (\<forall>a\<in>UNIV. Rep_IF2 a \<in> car_init2 undefined)
2. (\<forall>z\<in>F1in UNIV UNIV UNIV. Rep_IF1 (Abs_IF1 (str_init1 undefined (F1map id Rep_IF1 Rep_IF2 z))) = str_init1 undefined (F1map id Rep_IF1 Rep_IF2 z)) \<and> (\<forall>z\<in>F2in UNIV UNIV UNIV. Rep_IF2 (Abs_IF2 (str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))) = str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))
[PROOF STEP]
apply (rule conjI)
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<forall>a\<in>UNIV. Rep_IF1 a \<in> car_init1 undefined
2. \<forall>a\<in>UNIV. Rep_IF2 a \<in> car_init2 undefined
3. (\<forall>z\<in>F1in UNIV UNIV UNIV. Rep_IF1 (Abs_IF1 (str_init1 undefined (F1map id Rep_IF1 Rep_IF2 z))) = str_init1 undefined (F1map id Rep_IF1 Rep_IF2 z)) \<and> (\<forall>z\<in>F2in UNIV UNIV UNIV. Rep_IF2 (Abs_IF2 (str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))) = str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))
[PROOF STEP]
apply (rule ballI)
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<And>a. a \<in> UNIV \<Longrightarrow> Rep_IF1 a \<in> car_init1 undefined
2. \<forall>a\<in>UNIV. Rep_IF2 a \<in> car_init2 undefined
3. (\<forall>z\<in>F1in UNIV UNIV UNIV. Rep_IF1 (Abs_IF1 (str_init1 undefined (F1map id Rep_IF1 Rep_IF2 z))) = str_init1 undefined (F1map id Rep_IF1 Rep_IF2 z)) \<and> (\<forall>z\<in>F2in UNIV UNIV UNIV. Rep_IF2 (Abs_IF2 (str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))) = str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))
[PROOF STEP]
apply (rule Rep_IF1)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<forall>a\<in>UNIV. Rep_IF2 a \<in> car_init2 undefined
2. (\<forall>z\<in>F1in UNIV UNIV UNIV. Rep_IF1 (Abs_IF1 (str_init1 undefined (F1map id Rep_IF1 Rep_IF2 z))) = str_init1 undefined (F1map id Rep_IF1 Rep_IF2 z)) \<and> (\<forall>z\<in>F2in UNIV UNIV UNIV. Rep_IF2 (Abs_IF2 (str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))) = str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))
[PROOF STEP]
apply (rule ballI)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>a. a \<in> UNIV \<Longrightarrow> Rep_IF2 a \<in> car_init2 undefined
2. (\<forall>z\<in>F1in UNIV UNIV UNIV. Rep_IF1 (Abs_IF1 (str_init1 undefined (F1map id Rep_IF1 Rep_IF2 z))) = str_init1 undefined (F1map id Rep_IF1 Rep_IF2 z)) \<and> (\<forall>z\<in>F2in UNIV UNIV UNIV. Rep_IF2 (Abs_IF2 (str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))) = str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))
[PROOF STEP]
apply (rule Rep_IF2)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<forall>z\<in>F1in UNIV UNIV UNIV. Rep_IF1 (Abs_IF1 (str_init1 undefined (F1map id Rep_IF1 Rep_IF2 z))) = str_init1 undefined (F1map id Rep_IF1 Rep_IF2 z)) \<and> (\<forall>z\<in>F2in UNIV UNIV UNIV. Rep_IF2 (Abs_IF2 (str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))) = str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))
[PROOF STEP]
apply (rule conjI)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<forall>z\<in>F1in UNIV UNIV UNIV. Rep_IF1 (Abs_IF1 (str_init1 undefined (F1map id Rep_IF1 Rep_IF2 z))) = str_init1 undefined (F1map id Rep_IF1 Rep_IF2 z)
2. \<forall>z\<in>F2in UNIV UNIV UNIV. Rep_IF2 (Abs_IF2 (str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))) = str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z)
[PROOF STEP]
apply (rule ballI)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>z. z \<in> F1in UNIV UNIV UNIV \<Longrightarrow> Rep_IF1 (Abs_IF1 (str_init1 undefined (F1map id Rep_IF1 Rep_IF2 z))) = str_init1 undefined (F1map id Rep_IF1 Rep_IF2 z)
2. \<forall>z\<in>F2in UNIV UNIV UNIV. Rep_IF2 (Abs_IF2 (str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))) = str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z)
[PROOF STEP]
apply (rule Abs_IF1_inverse)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>z. z \<in> F1in UNIV UNIV UNIV \<Longrightarrow> str_init1 undefined (F1map id Rep_IF1 Rep_IF2 z) \<in> car_init1 undefined
2. \<forall>z\<in>F2in UNIV UNIV UNIV. Rep_IF2 (Abs_IF2 (str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))) = str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z)
[PROOF STEP]
apply (rule alg_F1set[OF alg_min_alg])
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<And>z. z \<in> F1in UNIV UNIV UNIV \<Longrightarrow> F1set2 (F1map id Rep_IF1 Rep_IF2 z) \<subseteq> car_init1 undefined
2. \<And>z. z \<in> F1in UNIV UNIV UNIV \<Longrightarrow> F1set3 (F1map id Rep_IF1 Rep_IF2 z) \<subseteq> car_init2 undefined
3. \<forall>z\<in>F2in UNIV UNIV UNIV. Rep_IF2 (Abs_IF2 (str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))) = str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z)
[PROOF STEP]
apply (rule ord_eq_le_trans[OF F1.set_map(2)])
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<And>z. z \<in> F1in UNIV UNIV UNIV \<Longrightarrow> Rep_IF1 ` F1set2 z \<subseteq> car_init1 undefined
2. \<And>z. z \<in> F1in UNIV UNIV UNIV \<Longrightarrow> F1set3 (F1map id Rep_IF1 Rep_IF2 z) \<subseteq> car_init2 undefined
3. \<forall>z\<in>F2in UNIV UNIV UNIV. Rep_IF2 (Abs_IF2 (str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))) = str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z)
[PROOF STEP]
apply (rule image_subsetI)
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<And>z x. \<lbrakk>z \<in> F1in UNIV UNIV UNIV; x \<in> F1set2 z\<rbrakk> \<Longrightarrow> Rep_IF1 x \<in> car_init1 undefined
2. \<And>z. z \<in> F1in UNIV UNIV UNIV \<Longrightarrow> F1set3 (F1map id Rep_IF1 Rep_IF2 z) \<subseteq> car_init2 undefined
3. \<forall>z\<in>F2in UNIV UNIV UNIV. Rep_IF2 (Abs_IF2 (str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))) = str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z)
[PROOF STEP]
apply (rule Rep_IF1)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>z. z \<in> F1in UNIV UNIV UNIV \<Longrightarrow> F1set3 (F1map id Rep_IF1 Rep_IF2 z) \<subseteq> car_init2 undefined
2. \<forall>z\<in>F2in UNIV UNIV UNIV. Rep_IF2 (Abs_IF2 (str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))) = str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z)
[PROOF STEP]
apply (rule ord_eq_le_trans[OF F1.set_map(3)])
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>z. z \<in> F1in UNIV UNIV UNIV \<Longrightarrow> Rep_IF2 ` F1set3 z \<subseteq> car_init2 undefined
2. \<forall>z\<in>F2in UNIV UNIV UNIV. Rep_IF2 (Abs_IF2 (str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))) = str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z)
[PROOF STEP]
apply (rule image_subsetI)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>z x. \<lbrakk>z \<in> F1in UNIV UNIV UNIV; x \<in> F1set3 z\<rbrakk> \<Longrightarrow> Rep_IF2 x \<in> car_init2 undefined
2. \<forall>z\<in>F2in UNIV UNIV UNIV. Rep_IF2 (Abs_IF2 (str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))) = str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z)
[PROOF STEP]
apply (rule Rep_IF2)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>z\<in>F2in UNIV UNIV UNIV. Rep_IF2 (Abs_IF2 (str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))) = str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z)
[PROOF STEP]
apply (rule ballI)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>z. z \<in> F2in UNIV UNIV UNIV \<Longrightarrow> Rep_IF2 (Abs_IF2 (str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z))) = str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z)
[PROOF STEP]
apply (rule Abs_IF2_inverse)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>z. z \<in> F2in UNIV UNIV UNIV \<Longrightarrow> str_init2 undefined (F2map id Rep_IF1 Rep_IF2 z) \<in> car_init2 undefined
[PROOF STEP]
apply (rule alg_F2set[OF alg_min_alg])
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>z. z \<in> F2in UNIV UNIV UNIV \<Longrightarrow> F2set2 (F2map id Rep_IF1 Rep_IF2 z) \<subseteq> car_init1 undefined
2. \<And>z. z \<in> F2in UNIV UNIV UNIV \<Longrightarrow> F2set3 (F2map id Rep_IF1 Rep_IF2 z) \<subseteq> car_init2 undefined
[PROOF STEP]
apply (rule ord_eq_le_trans[OF F2.set_map(2)])
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>z. z \<in> F2in UNIV UNIV UNIV \<Longrightarrow> Rep_IF1 ` F2set2 z \<subseteq> car_init1 undefined
2. \<And>z. z \<in> F2in UNIV UNIV UNIV \<Longrightarrow> F2set3 (F2map id Rep_IF1 Rep_IF2 z) \<subseteq> car_init2 undefined
[PROOF STEP]
apply (rule image_subsetI)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>z x. \<lbrakk>z \<in> F2in UNIV UNIV UNIV; x \<in> F2set2 z\<rbrakk> \<Longrightarrow> Rep_IF1 x \<in> car_init1 undefined
2. \<And>z. z \<in> F2in UNIV UNIV UNIV \<Longrightarrow> F2set3 (F2map id Rep_IF1 Rep_IF2 z) \<subseteq> car_init2 undefined
[PROOF STEP]
apply (rule Rep_IF1)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>z. z \<in> F2in UNIV UNIV UNIV \<Longrightarrow> F2set3 (F2map id Rep_IF1 Rep_IF2 z) \<subseteq> car_init2 undefined
[PROOF STEP]
apply (rule ord_eq_le_trans[OF F2.set_map(3)])
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>z. z \<in> F2in UNIV UNIV UNIV \<Longrightarrow> Rep_IF2 ` F2set3 z \<subseteq> car_init2 undefined
[PROOF STEP]
apply (rule image_subsetI)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>z x. \<lbrakk>z \<in> F2in UNIV UNIV UNIV; x \<in> F2set3 z\<rbrakk> \<Longrightarrow> Rep_IF2 x \<in> car_init2 undefined
[PROOF STEP]
apply (rule Rep_IF2)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
module Main
import Data.Vect
data Cat = Cas | Luna | Sherlock
f : (cat: Cat) -> String
getName : (cat: Cat) -> String
getName Cas = "Cas"
getName Luna = "Luna"
getName Sherlock = "Sherlock"
plusTwo : (n: Nat) -> Nat
plusTwo n = ?plusTwo_rhs
g : (n: Nat) -> (b: Bool) -> String
g n b = ?g_rhs
num : Nat
num = ?n_rhs
append : Vect n a -> Vect m a -> Vect (n + m) a
|
/-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Jens Wagemaker
Associated and irreducible elements.
-/
import order.galois_connection algebra.group data.equiv.basic data.multiset data.int.gcd
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
open lattice
def is_unit [monoid α] (a : α) : Prop := ∃u:units α, a = u
@[simp] theorem not_is_unit_zero [nonzero_comm_ring α] : ¬ is_unit (0 : α)
| ⟨⟨a, b, hab, hba⟩, rfl⟩ := have 0 * b = 1, from hab, by simpa using this
@[simp] theorem is_unit_one [monoid α] : is_unit (1:α) := ⟨1, rfl⟩
theorem units.is_unit_of_mul_one [comm_monoid α] (a b : α) (h : a * b = 1) : is_unit a :=
⟨units.mk_of_mul_eq_one a b h, rfl⟩
@[simp] theorem is_unit_mul_units [monoid α] (a : α) (u : units α) : is_unit (a * u) ↔ is_unit a :=
iff.intro
(assume ⟨v, hv⟩,
have is_unit (a * ↑u * ↑u⁻¹), by existsi v * u⁻¹; rw [hv, units.mul_coe],
by rwa [mul_assoc, units.mul_inv, mul_one] at this)
(assume ⟨v, hv⟩, hv.symm ▸ ⟨v * u, (units.mul_coe v u).symm⟩)
theorem is_unit_iff_dvd_one {α} [comm_semiring α] {x : α} : is_unit x ↔ x ∣ 1 :=
⟨by rintro ⟨u, rfl⟩; exact ⟨_, u.mul_inv.symm⟩,
λ ⟨y, h⟩, ⟨⟨x, y, h.symm, by rw [h, mul_comm]⟩, rfl⟩⟩
theorem is_unit_iff_forall_dvd {α} [comm_semiring α] {x : α} :
is_unit x ↔ ∀ y, x ∣ y :=
is_unit_iff_dvd_one.trans ⟨λ h y, dvd.trans h (one_dvd _), λ h, h _⟩
theorem is_unit_of_dvd_unit {α} [comm_semiring α] {x y : α}
(xy : x ∣ y) (hu : is_unit y) : is_unit x :=
is_unit_iff_dvd_one.2 $ dvd_trans xy $ is_unit_iff_dvd_one.1 hu
@[simp] theorem is_unit_nat {n : ℕ} : is_unit n ↔ n = 1 :=
iff.intro
(assume ⟨u, hu⟩, match n, u, hu, nat.units_eq_one u with _, _, rfl, rfl := rfl end)
(assume h, h.symm ▸ ⟨1, rfl⟩)
/-- `irreducible p` states that `p` is non-unit and only factors into units.
We explicitly avoid stating that `p` is non-zero, this would require a semiring. Assuming only a
monoid allows us to reuse irreducible for associated elements.
-/
@[class] def irreducible [monoid α] (p : α) : Prop :=
¬ is_unit p ∧ ∀a b, p = a * b → is_unit a ∨ is_unit b
@[simp] theorem not_irreducible_one [monoid α] : ¬ irreducible (1 : α) :=
by simp [irreducible]
@[simp] theorem not_irreducible_zero [semiring α] : ¬ irreducible (0 : α)
| ⟨hn0, h⟩ := have is_unit (0:α) ∨ is_unit (0:α), from h 0 0 ((mul_zero 0).symm),
this.elim hn0 hn0
theorem of_irreducible_mul {α} [monoid α] {x y : α} :
irreducible (x * y) → is_unit x ∨ is_unit y
| ⟨_, h⟩ := h _ _ rfl
theorem irreducible_or_factor {α} [monoid α] (x : α) (h : ¬ is_unit x) :
irreducible x ∨ ∃ a b, ¬ is_unit a ∧ ¬ is_unit b ∧ a * b = x :=
begin
haveI := classical.dec,
refine or_iff_not_imp_right.2 (λ H, _),
simp [h, irreducible] at H ⊢,
refine λ a b h, classical.by_contradiction $ λ o, _,
simp [not_or_distrib] at o,
exact H _ o.1 _ o.2 h.symm
end
theorem irreducible_iff_nat_prime : ∀(a : ℕ), irreducible a ↔ nat.prime a
| 0 := by simp [nat.not_prime_zero]
| 1 := by simp [nat.prime, one_lt_two]
| (n + 2) :=
have h₁ : ¬n + 2 = 1, from dec_trivial,
begin
simp [h₁, nat.prime, irreducible, (≥), nat.le_add_left 2 n, (∣)],
refine forall_congr (assume a, forall_congr $ assume b, forall_congr $ assume hab, _),
by_cases a = 1; simp [h],
split,
{ assume hb, simpa [hb] using hab.symm },
{ assume ha, subst ha,
have : n + 2 > 0, from dec_trivial,
refine nat.eq_of_mul_eq_mul_left this _,
rw [← hab, mul_one] }
end
def associated [monoid α] (x y : α) : Prop := ∃u:units α, x * u = y
local infix ` ~ᵤ ` : 50 := associated
namespace associated
@[refl] protected theorem refl [monoid α] (x : α) : x ~ᵤ x := ⟨1, by simp⟩
@[symm] protected theorem symm [monoid α] : ∀{x y : α}, x ~ᵤ y → y ~ᵤ x
| x _ ⟨u, rfl⟩ := ⟨u⁻¹, by rw [mul_assoc, units.mul_inv, mul_one]⟩
@[trans] protected theorem trans [monoid α] : ∀{x y z : α}, x ~ᵤ y → y ~ᵤ z → x ~ᵤ z
| x _ _ ⟨u, rfl⟩ ⟨v, rfl⟩ := ⟨u * v, by rw [units.mul_coe, mul_assoc]⟩
theorem unit_associated_one [monoid α] {u : units α} : (u : α) ~ᵤ 1 := ⟨u⁻¹, units.mul_inv u⟩
theorem associated_one_iff_is_unit [monoid α] {a : α} : (a : α) ~ᵤ 1 ↔ is_unit a :=
iff.intro
(assume h, let ⟨c, h⟩ := h.symm in h ▸ ⟨c, one_mul _⟩)
(assume ⟨c, h⟩, associated.symm ⟨c, by simp [h]⟩)
theorem associated_zero_iff_eq_zero [comm_semiring α] (a : α) : a ~ᵤ 0 ↔ a = 0 :=
iff.intro
(assume h, let ⟨u, h⟩ := h.symm in by simpa using h.symm)
(assume h, h ▸ associated.refl a)
theorem associated_one_of_mul_eq_one [comm_monoid α] {a : α} (b : α) (hab : a * b = 1) : a ~ᵤ 1 :=
show (units.mk_of_mul_eq_one a b hab : α) ~ᵤ 1, from unit_associated_one
theorem associated_one_of_associated_mul_one [comm_monoid α] {a b : α} :
a * b ~ᵤ 1 → a ~ᵤ 1
| ⟨u, h⟩ := associated_one_of_mul_eq_one (b * u) $ by simpa [mul_assoc] using h
theorem associated_of_dvd_dvd [integral_domain α] {a b : α} (hab : a ∣ b) (hba : b ∣ a) : a ~ᵤ b :=
begin
haveI := classical.dec_eq α,
rcases hab with ⟨c, rfl⟩,
rcases hba with ⟨d, a_eq⟩,
by_cases ha0 : a = 0,
{ simp [*] at * },
have : a * 1 = a * (c * d),
{ simpa [mul_assoc] using a_eq },
have : 1 = (c * d), from eq_of_mul_eq_mul_left ha0 this,
exact ⟨units.mk_of_mul_eq_one c d (this.symm), by rw [units.mk_of_mul_eq_one, units.val_coe]⟩
end
protected def setoid (α : Type*) [monoid α] : setoid α :=
{ r := associated, iseqv := ⟨associated.refl, λa b, associated.symm, λa b c, associated.trans⟩ }
end associated
local attribute [instance] associated.setoid
def associates (α : Type*) [monoid α] : Type* :=
quotient (associated.setoid α)
namespace associates
open associated
protected def mk {α : Type*} [monoid α] (a : α) : associates α :=
⟦ a ⟧
theorem mk_eq_mk_iff_associated [monoid α] {a b : α} :
associates.mk a = associates.mk b ↔ a ~ᵤ b :=
iff.intro quotient.exact quot.sound
theorem quotient_mk_eq_mk [monoid α] (a : α) : ⟦ a ⟧ = associates.mk a := rfl
theorem quot_mk_eq_mk [monoid α] (a : α) : quot.mk setoid.r a = associates.mk a := rfl
theorem forall_associated [monoid α] {p : associates α → Prop} :
(∀a, p a) ↔ (∀a, p (associates.mk a)) :=
iff.intro
(assume h a, h _)
(assume h a, quotient.induction_on a h)
instance [monoid α] : has_one (associates α) := ⟨⟦ 1 ⟧⟩
theorem one_eq_mk_one [monoid α] : (1 : associates α) = associates.mk 1 := rfl
instance [monoid α] : has_bot (associates α) := ⟨1⟩
section comm_monoid
variable [comm_monoid α]
instance : has_mul (associates α) :=
⟨λa' b', quotient.lift_on₂ a' b' (λa b, ⟦ a * b ⟧) $
assume a₁ a₂ b₁ b₂ ⟨c₁, h₁⟩ ⟨c₂, h₂⟩,
quotient.sound $ ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩⟩
theorem mk_mul_mk {x y : α} : associates.mk x * associates.mk y = associates.mk (x * y) :=
rfl
instance : comm_monoid (associates α) :=
{ one := 1,
mul := (*),
mul_one := assume a', quotient.induction_on a' $
assume a, show ⟦a * 1⟧ = ⟦ a ⟧, by simp,
one_mul := assume a', quotient.induction_on a' $
assume a, show ⟦1 * a⟧ = ⟦ a ⟧, by simp,
mul_assoc := assume a' b' c', quotient.induction_on₃ a' b' c' $
assume a b c, show ⟦a * b * c⟧ = ⟦a * (b * c)⟧, by rw [mul_assoc],
mul_comm := assume a' b', quotient.induction_on₂ a' b' $
assume a b, show ⟦a * b⟧ = ⟦b * a⟧, by rw [mul_comm] }
instance : preorder (associates α) :=
{ le := λa b, ∃c, a * c = b,
le_refl := assume a, ⟨1, by simp⟩,
le_trans := assume a b c ⟨f₁, h₁⟩ ⟨f₂, h₂⟩, ⟨f₁ * f₂, h₂ ▸ h₁ ▸ (mul_assoc _ _ _).symm⟩}
theorem prod_mk {p : multiset α} : (p.map associates.mk).prod = associates.mk p.prod :=
multiset.induction_on p (by simp; refl) $ assume a s ih, by simp [ih]; refl
theorem rel_associated_iff_map_eq_map {p q : multiset α} :
multiset.rel associated p q ↔ p.map associates.mk = q.map associates.mk :=
by rw [← multiset.rel_eq];
simp [multiset.rel_map_left, multiset.rel_map_right, mk_eq_mk_iff_associated]
theorem mul_eq_one_iff {x y : associates α} : x * y = 1 ↔ (x = 1 ∧ y = 1) :=
iff.intro
(quotient.induction_on₂ x y $ assume a b h,
have a * b ~ᵤ 1, from quotient.exact h,
⟨quotient.sound $ associated_one_of_associated_mul_one this,
quotient.sound $ associated_one_of_associated_mul_one $ by rwa [mul_comm] at this⟩)
(by simp {contextual := tt})
theorem prod_eq_one_iff {p : multiset (associates α)} :
p.prod = 1 ↔ (∀a ∈ p, (a:associates α) = 1) :=
multiset.induction_on p
(by simp)
(by simp [mul_eq_one_iff, or_imp_distrib, forall_and_distrib] {contextual := tt})
theorem coe_unit_eq_one : ∀u:units (associates α), (u : associates α) = 1
| ⟨u, v, huv, hvu⟩ := by rw [mul_eq_one_iff] at huv; exact huv.1
theorem is_unit_iff_eq_one (a : associates α) : is_unit a ↔ a = 1 :=
iff.intro
(assume ⟨u, h⟩, h.symm ▸ coe_unit_eq_one _)
(assume h, h.symm ▸ is_unit_one)
theorem is_unit_mk {a : α} : is_unit (associates.mk a) ↔ is_unit a :=
calc is_unit (associates.mk a) ↔ a ~ᵤ 1 :
by rw [is_unit_iff_eq_one, one_eq_mk_one, mk_eq_mk_iff_associated]
... ↔ is_unit a : associated_one_iff_is_unit
section order
theorem mul_mono {a b c d : associates α} (h₁ : a ≤ b) (h₂ : c ≤ d) :
a * c ≤ b * d :=
let ⟨x, hx⟩ := h₁, ⟨y, hy⟩ := h₂ in
⟨x * y, by simp [hx.symm, hy.symm, mul_comm, mul_assoc, mul_left_comm]⟩
theorem one_le {a : associates α} : 1 ≤ a :=
⟨a, one_mul a⟩
theorem prod_le_prod {p q : multiset (associates α)} (h : p ≤ q) : p.prod ≤ q.prod :=
begin
haveI := classical.dec_eq (associates α),
haveI := classical.dec_eq α,
suffices : p.prod ≤ (p + (q - p)).prod, { rwa [multiset.add_sub_of_le h] at this },
suffices : p.prod * 1 ≤ p.prod * (q - p).prod, { simpa },
exact mul_mono (le_refl p.prod) one_le
end
theorem le_mul_right {a b : associates α} : a ≤ a * b := ⟨b, rfl⟩
theorem le_mul_left {a b : associates α} : a ≤ b * a :=
by rw [mul_comm]; exact le_mul_right
end order
end comm_monoid
instance [has_zero α] [monoid α] : has_zero (associates α) := ⟨⟦ 0 ⟧⟩
instance [has_zero α] [monoid α] : has_top (associates α) := ⟨0⟩
section comm_semiring
variables [comm_semiring α]
@[simp] theorem mk_zero_eq (a : α) : associates.mk a = 0 ↔ a = 0 :=
⟨assume h, (associated_zero_iff_eq_zero a).1 $ quotient.exact h, assume h, h.symm ▸ rfl⟩
@[simp] theorem mul_zero : ∀(a : associates α), a * 0 = 0 :=
by rintros ⟨a⟩; show associates.mk (a * 0) = associates.mk 0; rw [mul_zero]
@[simp] theorem zero_mul : ∀(a : associates α), 0 * a = 0 :=
by rintros ⟨a⟩; show associates.mk (0 * a) = associates.mk 0; rw [zero_mul]
theorem mk_eq_zero_iff_eq_zero {a : α} : associates.mk a = 0 ↔ a = 0 :=
calc associates.mk a = 0 ↔ (a ~ᵤ 0) : mk_eq_mk_iff_associated
... ↔ a = 0 : associated_zero_iff_eq_zero a
theorem dvd_of_mk_le_mk {a b : α} : associates.mk a ≤ associates.mk b → a ∣ b
| ⟨c', hc'⟩ := (quotient.induction_on c' $ assume c hc,
let ⟨d, hd⟩ := (quotient.exact hc).symm in
⟨(↑d⁻¹) * c,
calc b = (a * c) * ↑d⁻¹ : by rw [← hd, mul_assoc, units.mul_inv, mul_one]
... = a * (↑d⁻¹ * c) : by ac_refl⟩) hc'
theorem mk_le_mk_of_dvd {a b : α} : a ∣ b → associates.mk a ≤ associates.mk b :=
assume ⟨c, hc⟩, ⟨associates.mk c, by simp [hc]; refl⟩
theorem mk_le_mk_iff_dvd_iff {a b : α} : associates.mk a ≤ associates.mk b ↔ a ∣ b :=
iff.intro dvd_of_mk_le_mk mk_le_mk_of_dvd
end comm_semiring
section integral_domain
variable [integral_domain α]
instance : partial_order (associates α) :=
{ le_antisymm := assume a' b',
quotient.induction_on₂ a' b' $ assume a b ⟨f₁', h₁⟩ ⟨f₂', h₂⟩,
(quotient.induction_on₂ f₁' f₂' $ assume f₁ f₂ h₁ h₂,
let ⟨c₁, h₁⟩ := quotient.exact h₁, ⟨c₂, h₂⟩ := quotient.exact h₂ in
quotient.sound $ associated_of_dvd_dvd
(h₁ ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _)
(h₂ ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _)) h₁ h₂
.. associates.preorder }
instance : lattice.order_bot (associates α) :=
{ bot := 1,
bot_le := assume a, one_le,
.. associates.partial_order }
instance : lattice.order_top (associates α) :=
{ top := 0,
le_top := assume a, ⟨0, mul_zero a⟩,
.. associates.partial_order }
theorem zero_ne_one : (0 : associates α) ≠ 1 :=
assume h,
have (0 : α) ~ᵤ 1, from quotient.exact h,
have (0 : α) = 1, from ((associated_zero_iff_eq_zero 1).1 this.symm).symm,
zero_ne_one this
theorem mul_eq_zero_iff {x y : associates α} : x * y = 0 ↔ x = 0 ∨ y = 0 :=
iff.intro
(quotient.induction_on₂ x y $ assume a b h,
have a * b = 0, from (associated_zero_iff_eq_zero _).1 (quotient.exact h),
have a = 0 ∨ b = 0, from mul_eq_zero_iff_eq_zero_or_eq_zero.1 this,
this.imp (assume h, h.symm ▸ rfl) (assume h, h.symm ▸ rfl))
(by simp [or_imp_distrib] {contextual := tt})
theorem prod_eq_zero_iff {s : multiset (associates α)} :
s.prod = 0 ↔ (0 : associates α) ∈ s :=
multiset.induction_on s (by simp; exact zero_ne_one.symm) $
assume a s, by simp [mul_eq_zero_iff, @eq_comm _ 0 a] {contextual := tt}
theorem irreducible_mk_iff (a : α) : irreducible (associates.mk a) ↔ irreducible a :=
begin
simp [irreducible, is_unit_mk],
apply and_congr (iff.refl _),
split,
{ assume h x y eq,
have : is_unit (associates.mk x) ∨ is_unit (associates.mk y),
from h _ _ (by rw [eq]; refl),
simpa [is_unit_mk] },
{ refine assume h x y, quotient.induction_on₂ x y (assume x y eq, _),
rcases quotient.exact eq.symm with ⟨u, eq⟩,
have : a = x * (y * u), by rwa [mul_assoc, eq_comm] at eq,
show is_unit (associates.mk x) ∨ is_unit (associates.mk y),
simpa [is_unit_mk] using h _ _ this }
end
end integral_domain
section normalization_domain
variable [normalization_domain α]
protected def out : associates α → α :=
begin
refine quotient.lift (λa, a * ↑(norm_unit a)) _,
letI := classical.dec_eq α,
rintros a _ ⟨u, rfl⟩,
by_cases a = 0, { simp [h] },
calc a * ↑(norm_unit a) = a * ↑(u * norm_unit a * u⁻¹) :
by rw [mul_comm u, mul_assoc, mul_inv_self, mul_one]
... = a * ↑u * ↑(norm_unit (a * ↑u)) :
by simp [h, norm_unit_mul, units.mul_coe, units.inv_coe, mul_assoc]
end
lemma out_mk (a : α) : (associates.mk a).out = a * ↑(norm_unit a) :=
rfl
@[simp] lemma out_one : (1 : associates α).out = 1 :=
calc (1 : associates α).out = 1 * ↑(norm_unit (1 : α)) : out_mk _
... = 1 : by simp
lemma out_mul (a b : associates α) : (a * b).out = a.out * b.out :=
begin
refine quotient.induction_on₂ a b (assume a b, _),
simp [associates.quotient_mk_eq_mk, out_mk, mk_mul_mk],
letI := classical.dec_eq α,
by_cases a = 0; by_cases b = 0; simp [*, mul_assoc, mul_comm, mul_left_comm]
end
lemma dvd_out_iff (a : α) (b : associates α) : a ∣ b.out ↔ associates.mk a ≤ b :=
quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff]
lemma out_dvd_iff (a : α) (b : associates α) : b.out ∣ a ↔ b ≤ associates.mk a :=
quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff]
@[simp] lemma out_top : (⊤ : associates α).out = 0 :=
calc (⊤ : associates α).out = 0 * ↑(norm_unit (0:α)) : out_mk _
... = 0 : by simp
@[simp] lemma norm_unit_out (a : associates α) : norm_unit a.out = 1 :=
quotient.induction_on a $ assume a,
by rw [associates.quotient_mk_eq_mk, associates.out_mk, norm_unit_mul_norm_unit]
end normalization_domain
end associates
def associates_int_equiv_nat : (associates ℤ) ≃ ℕ :=
begin
refine ⟨λz, z.out.nat_abs, λn, associates.mk n, _, _⟩,
{ refine (assume a, quotient.induction_on a $ assume a,
associates.mk_eq_mk_iff_associated.2 $ associated.symm $ ⟨norm_unit a, _⟩),
simp [associates.out_mk, associates.quotient_mk_eq_mk, associated,
int.coe_nat_abs_eq_mul_norm_unit.symm] },
{ assume n, simp [associates.out_mk, int.coe_nat_abs_eq_mul_norm_unit.symm] }
end
|
{-# LANGUAGE FlexibleContexts #-}
import Data.List
import Data.Function
import Control.Lens
import Control.Monad
import Numeric.LinearAlgebra
grid :: Integer -> Matrix Double
grid n = build (300, 300) (builder `on` (+1) . round)
where builder x y = let id = x + 10
in fromInteger . subtract 5
$ (id * y + n) * id `mod` 1000 `div` 100
main = getContents
>>= putStrLn
. (\(z, (x, y)) -> show (x+1) ++ "," ++ show (y+1) ++ "," ++ show z)
. (_2 %~ snd)
. maximumBy (compare `on` snd)
. zip ([1..300] :: [Int])
. map (liftM2 (,) maxElement maxIndex)
. zipWith corr2 (map (konst 1 . join (,)) [1..300])
. repeat . grid . read
|
Address(El Macero Court ) is a residential Culdesacs culdesac in El Macero.
Intersecting Streets
South El Macero Drive
|
Verb: When a rapper pronounces a word differently then it is traditionally pronounced as to make said word rhyme with a word it conventionally does not rhyme with.
Eminem is rhyme pinching when he mispronounces the word "by" to make it sound like it rhymes with the word "god" , even though these words do not congrue with a traditional rhyme.
Get a rhyme pinching mug for your bunkmate Bob.
When a rapper pronounces a word differently then it is traditionally pronounced as to make said word rhyme with a word it conventionally does not rhyme with.
Get a rhyme pinching mug for your mate Jovana. |
/-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
! This file was ported from Lean 3 source module data.polynomial.integral_normalization
! leanprover-community/mathlib commit 10bf4f825ad729c5653adc039dafa3622e7f93c9
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Data.Polynomial.AlgebraMap
import Mathbin.Data.Polynomial.Degree.Lemmas
import Mathbin.Data.Polynomial.Monic
/-!
# Theory of monic polynomials
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We define `integral_normalization`, which relate arbitrary polynomials to monic ones.
-/
open BigOperators Polynomial
namespace Polynomial
universe u v y
variable {R : Type u} {S : Type v} {a b : R} {m n : ℕ} {ι : Type y}
section IntegralNormalization
section Semiring
variable [Semiring R]
#print Polynomial.integralNormalization /-
/-- If `f : R[X]` is a nonzero polynomial with root `z`, `integral_normalization f` is
a monic polynomial with root `leading_coeff f * z`.
Moreover, `integral_normalization 0 = 0`.
-/
noncomputable def integralNormalization (f : R[X]) : R[X] :=
∑ i in f.support,
monomial i (if f.degree = i then 1 else coeff f i * f.leadingCoeff ^ (f.natDegree - 1 - i))
#align polynomial.integral_normalization Polynomial.integralNormalization
-/
#print Polynomial.integralNormalization_zero /-
@[simp]
theorem integralNormalization_zero : integralNormalization (0 : R[X]) = 0 := by
simp [integral_normalization]
#align polynomial.integral_normalization_zero Polynomial.integralNormalization_zero
-/
/- warning: polynomial.integral_normalization_coeff -> Polynomial.integralNormalization_coeff is a dubious translation:
lean 3 declaration is
forall {R : Type.{u1}} [_inst_1 : Semiring.{u1} R] {f : Polynomial.{u1} R _inst_1} {i : Nat}, Eq.{succ u1} R (Polynomial.coeff.{u1} R _inst_1 (Polynomial.integralNormalization.{u1} R _inst_1 f) i) (ite.{succ u1} R (Eq.{1} (WithBot.{0} Nat) (Polynomial.degree.{u1} R _inst_1 f) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) Nat (WithBot.{0} Nat) (HasLiftT.mk.{1, 1} Nat (WithBot.{0} Nat) (CoeTCₓ.coe.{1, 1} Nat (WithBot.{0} Nat) (WithBot.hasCoeT.{0} Nat))) i)) (Option.decidableEq.{0} Nat (fun (a : Nat) (b : Nat) => Nat.decidableEq a b) (Polynomial.degree.{u1} R _inst_1 f) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) Nat (WithBot.{0} Nat) (HasLiftT.mk.{1, 1} Nat (WithBot.{0} Nat) (CoeTCₓ.coe.{1, 1} Nat (WithBot.{0} Nat) (WithBot.hasCoeT.{0} Nat))) i)) (OfNat.ofNat.{u1} R 1 (OfNat.mk.{u1} R 1 (One.one.{u1} R (AddMonoidWithOne.toOne.{u1} R (AddCommMonoidWithOne.toAddMonoidWithOne.{u1} R (NonAssocSemiring.toAddCommMonoidWithOne.{u1} R (Semiring.toNonAssocSemiring.{u1} R _inst_1))))))) (HMul.hMul.{u1, u1, u1} R R R (instHMul.{u1} R (Distrib.toHasMul.{u1} R (NonUnitalNonAssocSemiring.toDistrib.{u1} R (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u1} R (Semiring.toNonAssocSemiring.{u1} R _inst_1))))) (Polynomial.coeff.{u1} R _inst_1 f i) (HPow.hPow.{u1, 0, u1} R Nat R (instHPow.{u1, 0} R Nat (Monoid.Pow.{u1} R (MonoidWithZero.toMonoid.{u1} R (Semiring.toMonoidWithZero.{u1} R _inst_1)))) (Polynomial.leadingCoeff.{u1} R _inst_1 f) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) (Polynomial.natDegree.{u1} R _inst_1 f) (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne)))) i))))
but is expected to have type
forall {R : Type.{u1}} [_inst_1 : Semiring.{u1} R] {f : Polynomial.{u1} R _inst_1} {i : Nat}, Eq.{succ u1} R (Polynomial.coeff.{u1} R _inst_1 (Polynomial.integralNormalization.{u1} R _inst_1 f) i) (ite.{succ u1} R (Eq.{1} (WithBot.{0} Nat) (Polynomial.degree.{u1} R _inst_1 f) (Nat.cast.{0} (WithBot.{0} Nat) (Semiring.toNatCast.{0} (WithBot.{0} Nat) (OrderedSemiring.toSemiring.{0} (WithBot.{0} Nat) (OrderedCommSemiring.toOrderedSemiring.{0} (WithBot.{0} Nat) (WithBot.orderedCommSemiring.{0} Nat (fun (a : Nat) (b : Nat) => instDecidableEqNat a b) Nat.canonicallyOrderedCommSemiring Nat.nontrivial)))) i)) (WithBot.instDecidableEqWithBot.{0} Nat (fun (a : Nat) (b : Nat) => instDecidableEqNat a b) (Polynomial.degree.{u1} R _inst_1 f) (Nat.cast.{0} (WithBot.{0} Nat) (Semiring.toNatCast.{0} (WithBot.{0} Nat) (OrderedSemiring.toSemiring.{0} (WithBot.{0} Nat) (OrderedCommSemiring.toOrderedSemiring.{0} (WithBot.{0} Nat) (WithBot.orderedCommSemiring.{0} Nat (fun (a : Nat) (b : Nat) => instDecidableEqNat a b) Nat.canonicallyOrderedCommSemiring Nat.nontrivial)))) i)) (OfNat.ofNat.{u1} R 1 (One.toOfNat1.{u1} R (Semiring.toOne.{u1} R _inst_1))) (HMul.hMul.{u1, u1, u1} R R R (instHMul.{u1} R (NonUnitalNonAssocSemiring.toMul.{u1} R (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u1} R (Semiring.toNonAssocSemiring.{u1} R _inst_1)))) (Polynomial.coeff.{u1} R _inst_1 f i) (HPow.hPow.{u1, 0, u1} R Nat R (instHPow.{u1, 0} R Nat (Monoid.Pow.{u1} R (MonoidWithZero.toMonoid.{u1} R (Semiring.toMonoidWithZero.{u1} R _inst_1)))) (Polynomial.leadingCoeff.{u1} R _inst_1 f) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) (Polynomial.natDegree.{u1} R _inst_1 f) (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1))) i))))
Case conversion may be inaccurate. Consider using '#align polynomial.integral_normalization_coeff Polynomial.integralNormalization_coeffₓ'. -/
theorem integralNormalization_coeff {f : R[X]} {i : ℕ} :
(integralNormalization f).coeff i =
if f.degree = i then 1 else coeff f i * f.leadingCoeff ^ (f.natDegree - 1 - i) :=
by
have : f.coeff i = 0 → f.degree ≠ i := fun hc hd => coeff_ne_zero_of_eq_degree hd hc
simp (config := { contextual := true }) [integral_normalization, coeff_monomial, this,
mem_support_iff]
#align polynomial.integral_normalization_coeff Polynomial.integralNormalization_coeff
#print Polynomial.integralNormalization_support /-
theorem integralNormalization_support {f : R[X]} : (integralNormalization f).support ⊆ f.support :=
by
intro
simp (config := { contextual := true }) [integral_normalization, coeff_monomial, mem_support_iff]
#align polynomial.integral_normalization_support Polynomial.integralNormalization_support
-/
#print Polynomial.integralNormalization_coeff_degree /-
theorem integralNormalization_coeff_degree {f : R[X]} {i : ℕ} (hi : f.degree = i) :
(integralNormalization f).coeff i = 1 := by rw [integral_normalization_coeff, if_pos hi]
#align polynomial.integral_normalization_coeff_degree Polynomial.integralNormalization_coeff_degree
-/
#print Polynomial.integralNormalization_coeff_natDegree /-
theorem integralNormalization_coeff_natDegree {f : R[X]} (hf : f ≠ 0) :
(integralNormalization f).coeff (natDegree f) = 1 :=
integralNormalization_coeff_degree (degree_eq_natDegree hf)
#align polynomial.integral_normalization_coeff_nat_degree Polynomial.integralNormalization_coeff_natDegree
-/
/- warning: polynomial.integral_normalization_coeff_ne_degree -> Polynomial.integralNormalization_coeff_ne_degree is a dubious translation:
lean 3 declaration is
forall {R : Type.{u1}} [_inst_1 : Semiring.{u1} R] {f : Polynomial.{u1} R _inst_1} {i : Nat}, (Ne.{1} (WithBot.{0} Nat) (Polynomial.degree.{u1} R _inst_1 f) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) Nat (WithBot.{0} Nat) (HasLiftT.mk.{1, 1} Nat (WithBot.{0} Nat) (CoeTCₓ.coe.{1, 1} Nat (WithBot.{0} Nat) (WithBot.hasCoeT.{0} Nat))) i)) -> (Eq.{succ u1} R (Polynomial.coeff.{u1} R _inst_1 (Polynomial.integralNormalization.{u1} R _inst_1 f) i) (HMul.hMul.{u1, u1, u1} R R R (instHMul.{u1} R (Distrib.toHasMul.{u1} R (NonUnitalNonAssocSemiring.toDistrib.{u1} R (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u1} R (Semiring.toNonAssocSemiring.{u1} R _inst_1))))) (Polynomial.coeff.{u1} R _inst_1 f i) (HPow.hPow.{u1, 0, u1} R Nat R (instHPow.{u1, 0} R Nat (Monoid.Pow.{u1} R (MonoidWithZero.toMonoid.{u1} R (Semiring.toMonoidWithZero.{u1} R _inst_1)))) (Polynomial.leadingCoeff.{u1} R _inst_1 f) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) (Polynomial.natDegree.{u1} R _inst_1 f) (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne)))) i))))
but is expected to have type
forall {R : Type.{u1}} [_inst_1 : Semiring.{u1} R] {f : Polynomial.{u1} R _inst_1} {i : Nat}, (Ne.{1} (WithBot.{0} Nat) (Polynomial.degree.{u1} R _inst_1 f) (Nat.cast.{0} (WithBot.{0} Nat) (Semiring.toNatCast.{0} (WithBot.{0} Nat) (OrderedSemiring.toSemiring.{0} (WithBot.{0} Nat) (OrderedCommSemiring.toOrderedSemiring.{0} (WithBot.{0} Nat) (WithBot.orderedCommSemiring.{0} Nat (fun (a : Nat) (b : Nat) => instDecidableEqNat a b) Nat.canonicallyOrderedCommSemiring Nat.nontrivial)))) i)) -> (Eq.{succ u1} R (Polynomial.coeff.{u1} R _inst_1 (Polynomial.integralNormalization.{u1} R _inst_1 f) i) (HMul.hMul.{u1, u1, u1} R R R (instHMul.{u1} R (NonUnitalNonAssocSemiring.toMul.{u1} R (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u1} R (Semiring.toNonAssocSemiring.{u1} R _inst_1)))) (Polynomial.coeff.{u1} R _inst_1 f i) (HPow.hPow.{u1, 0, u1} R Nat R (instHPow.{u1, 0} R Nat (Monoid.Pow.{u1} R (MonoidWithZero.toMonoid.{u1} R (Semiring.toMonoidWithZero.{u1} R _inst_1)))) (Polynomial.leadingCoeff.{u1} R _inst_1 f) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) (Polynomial.natDegree.{u1} R _inst_1 f) (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1))) i))))
Case conversion may be inaccurate. Consider using '#align polynomial.integral_normalization_coeff_ne_degree Polynomial.integralNormalization_coeff_ne_degreeₓ'. -/
theorem integralNormalization_coeff_ne_degree {f : R[X]} {i : ℕ} (hi : f.degree ≠ i) :
coeff (integralNormalization f) i = coeff f i * f.leadingCoeff ^ (f.natDegree - 1 - i) := by
rw [integral_normalization_coeff, if_neg hi]
#align polynomial.integral_normalization_coeff_ne_degree Polynomial.integralNormalization_coeff_ne_degree
/- warning: polynomial.integral_normalization_coeff_ne_nat_degree -> Polynomial.integralNormalization_coeff_ne_natDegree is a dubious translation:
lean 3 declaration is
forall {R : Type.{u1}} [_inst_1 : Semiring.{u1} R] {f : Polynomial.{u1} R _inst_1} {i : Nat}, (Ne.{1} Nat i (Polynomial.natDegree.{u1} R _inst_1 f)) -> (Eq.{succ u1} R (Polynomial.coeff.{u1} R _inst_1 (Polynomial.integralNormalization.{u1} R _inst_1 f) i) (HMul.hMul.{u1, u1, u1} R R R (instHMul.{u1} R (Distrib.toHasMul.{u1} R (NonUnitalNonAssocSemiring.toDistrib.{u1} R (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u1} R (Semiring.toNonAssocSemiring.{u1} R _inst_1))))) (Polynomial.coeff.{u1} R _inst_1 f i) (HPow.hPow.{u1, 0, u1} R Nat R (instHPow.{u1, 0} R Nat (Monoid.Pow.{u1} R (MonoidWithZero.toMonoid.{u1} R (Semiring.toMonoidWithZero.{u1} R _inst_1)))) (Polynomial.leadingCoeff.{u1} R _inst_1 f) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) (Polynomial.natDegree.{u1} R _inst_1 f) (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne)))) i))))
but is expected to have type
forall {R : Type.{u1}} [_inst_1 : Semiring.{u1} R] {f : Polynomial.{u1} R _inst_1} {i : Nat}, (Ne.{1} Nat i (Polynomial.natDegree.{u1} R _inst_1 f)) -> (Eq.{succ u1} R (Polynomial.coeff.{u1} R _inst_1 (Polynomial.integralNormalization.{u1} R _inst_1 f) i) (HMul.hMul.{u1, u1, u1} R R R (instHMul.{u1} R (NonUnitalNonAssocSemiring.toMul.{u1} R (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u1} R (Semiring.toNonAssocSemiring.{u1} R _inst_1)))) (Polynomial.coeff.{u1} R _inst_1 f i) (HPow.hPow.{u1, 0, u1} R Nat R (instHPow.{u1, 0} R Nat (Monoid.Pow.{u1} R (MonoidWithZero.toMonoid.{u1} R (Semiring.toMonoidWithZero.{u1} R _inst_1)))) (Polynomial.leadingCoeff.{u1} R _inst_1 f) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) (Polynomial.natDegree.{u1} R _inst_1 f) (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1))) i))))
Case conversion may be inaccurate. Consider using '#align polynomial.integral_normalization_coeff_ne_nat_degree Polynomial.integralNormalization_coeff_ne_natDegreeₓ'. -/
theorem integralNormalization_coeff_ne_natDegree {f : R[X]} {i : ℕ} (hi : i ≠ natDegree f) :
coeff (integralNormalization f) i = coeff f i * f.leadingCoeff ^ (f.natDegree - 1 - i) :=
integralNormalization_coeff_ne_degree (degree_ne_of_natDegree_ne hi.symm)
#align polynomial.integral_normalization_coeff_ne_nat_degree Polynomial.integralNormalization_coeff_ne_natDegree
#print Polynomial.monic_integralNormalization /-
theorem monic_integralNormalization {f : R[X]} (hf : f ≠ 0) : Monic (integralNormalization f) :=
monic_of_degree_le f.natDegree
(Finset.sup_le fun i h =>
WithBot.coe_le_coe.2 <| le_natDegree_of_mem_supp i <| integralNormalization_support h)
(integralNormalization_coeff_natDegree hf)
#align polynomial.monic_integral_normalization Polynomial.monic_integralNormalization
-/
end Semiring
section IsDomain
variable [Ring R] [IsDomain R]
#print Polynomial.support_integralNormalization /-
@[simp]
theorem support_integralNormalization {f : R[X]} : (integralNormalization f).support = f.support :=
by
by_cases hf : f = 0; · simp [hf]
ext i
refine' ⟨fun h => integral_normalization_support h, _⟩
simp only [integral_normalization_coeff, mem_support_iff]
intro hfi
split_ifs with hi <;> simp [hfi, hi, pow_ne_zero _ (leading_coeff_ne_zero.mpr hf)]
#align polynomial.support_integral_normalization Polynomial.support_integralNormalization
-/
end IsDomain
section IsDomain
variable [CommRing R] [IsDomain R]
variable [CommSemiring S]
/- warning: polynomial.integral_normalization_eval₂_eq_zero -> Polynomial.integralNormalization_eval₂_eq_zero is a dubious translation:
lean 3 declaration is
forall {R : Type.{u1}} {S : Type.{u2}} [_inst_1 : CommRing.{u1} R] [_inst_2 : IsDomain.{u1} R (Ring.toSemiring.{u1} R (CommRing.toRing.{u1} R _inst_1))] [_inst_3 : CommSemiring.{u2} S] {p : Polynomial.{u1} R (Ring.toSemiring.{u1} R (CommRing.toRing.{u1} R _inst_1))} (f : RingHom.{u1, u2} R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))) {z : S}, (Eq.{succ u2} S (Polynomial.eval₂.{u1, u2} R S (Ring.toSemiring.{u1} R (CommRing.toRing.{u1} R _inst_1)) (CommSemiring.toSemiring.{u2} S _inst_3) f z p) (OfNat.ofNat.{u2} S 0 (OfNat.mk.{u2} S 0 (Zero.zero.{u2} S (MulZeroClass.toHasZero.{u2} S (NonUnitalNonAssocSemiring.toMulZeroClass.{u2} S (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} S (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))))))))) -> (forall (x : R), (Eq.{succ u2} S (coeFn.{max (succ u1) (succ u2), max (succ u1) (succ u2)} (RingHom.{u1, u2} R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))) (fun (_x : RingHom.{u1, u2} R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))) => R -> S) (RingHom.hasCoeToFun.{u1, u2} R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))) f x) (OfNat.ofNat.{u2} S 0 (OfNat.mk.{u2} S 0 (Zero.zero.{u2} S (MulZeroClass.toHasZero.{u2} S (NonUnitalNonAssocSemiring.toMulZeroClass.{u2} S (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} S (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))))))))) -> (Eq.{succ u1} R x (OfNat.ofNat.{u1} R 0 (OfNat.mk.{u1} R 0 (Zero.zero.{u1} R (MulZeroClass.toHasZero.{u1} R (NonUnitalNonAssocSemiring.toMulZeroClass.{u1} R (NonUnitalNonAssocRing.toNonUnitalNonAssocSemiring.{u1} R (NonAssocRing.toNonUnitalNonAssocRing.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))))))))))) -> (Eq.{succ u2} S (Polynomial.eval₂.{u1, u2} R S (Ring.toSemiring.{u1} R (CommRing.toRing.{u1} R _inst_1)) (CommSemiring.toSemiring.{u2} S _inst_3) f (HMul.hMul.{u2, u2, u2} S S S (instHMul.{u2} S (Distrib.toHasMul.{u2} S (NonUnitalNonAssocSemiring.toDistrib.{u2} S (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} S (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3)))))) z (coeFn.{max (succ u1) (succ u2), max (succ u1) (succ u2)} (RingHom.{u1, u2} R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))) (fun (_x : RingHom.{u1, u2} R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))) => R -> S) (RingHom.hasCoeToFun.{u1, u2} R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))) f (Polynomial.leadingCoeff.{u1} R (Ring.toSemiring.{u1} R (CommRing.toRing.{u1} R _inst_1)) p))) (Polynomial.integralNormalization.{u1} R (Ring.toSemiring.{u1} R (CommRing.toRing.{u1} R _inst_1)) p)) (OfNat.ofNat.{u2} S 0 (OfNat.mk.{u2} S 0 (Zero.zero.{u2} S (MulZeroClass.toHasZero.{u2} S (NonUnitalNonAssocSemiring.toMulZeroClass.{u2} S (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} S (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3)))))))))
but is expected to have type
forall {R : Type.{u1}} {S : Type.{u2}} [_inst_1 : CommRing.{u1} R] [_inst_2 : IsDomain.{u1} R (Ring.toSemiring.{u1} R (CommRing.toRing.{u1} R _inst_1))] [_inst_3 : CommSemiring.{u2} S] {p : Polynomial.{u1} R (Ring.toSemiring.{u1} R (CommRing.toRing.{u1} R _inst_1))} (f : RingHom.{u1, u2} R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))) {z : S}, (Eq.{succ u2} S (Polynomial.eval₂.{u1, u2} R S (Ring.toSemiring.{u1} R (CommRing.toRing.{u1} R _inst_1)) (CommSemiring.toSemiring.{u2} S _inst_3) f z p) (OfNat.ofNat.{u2} S 0 (Zero.toOfNat0.{u2} S (CommMonoidWithZero.toZero.{u2} S (CommSemiring.toCommMonoidWithZero.{u2} S _inst_3))))) -> (forall (x : R), (Eq.{succ u2} ((fun ([email protected]._hyg.2391 : R) => S) x) (FunLike.coe.{max (succ u1) (succ u2), succ u1, succ u2} (RingHom.{u1, u2} R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))) R (fun (_x : R) => (fun ([email protected]._hyg.2391 : R) => S) _x) (MulHomClass.toFunLike.{max u1 u2, u1, u2} (RingHom.{u1, u2} R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))) R S (NonUnitalNonAssocSemiring.toMul.{u1} R (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))))) (NonUnitalNonAssocSemiring.toMul.{u2} S (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} S (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3)))) (NonUnitalRingHomClass.toMulHomClass.{max u1 u2, u1, u2} (RingHom.{u1, u2} R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))) R S (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1)))) (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} S (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))) (RingHomClass.toNonUnitalRingHomClass.{max u1 u2, u1, u2} (RingHom.{u1, u2} R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))) R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3)) (RingHom.instRingHomClassRingHom.{u1, u2} R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3)))))) f x) (OfNat.ofNat.{u2} ((fun ([email protected]._hyg.2391 : R) => S) x) 0 (Zero.toOfNat0.{u2} ((fun ([email protected]._hyg.2391 : R) => S) x) (CommMonoidWithZero.toZero.{u2} ((fun ([email protected]._hyg.2391 : R) => S) x) (CommSemiring.toCommMonoidWithZero.{u2} ((fun ([email protected]._hyg.2391 : R) => S) x) _inst_3))))) -> (Eq.{succ u1} R x (OfNat.ofNat.{u1} R 0 (Zero.toOfNat0.{u1} R (CommMonoidWithZero.toZero.{u1} R (CancelCommMonoidWithZero.toCommMonoidWithZero.{u1} R (IsDomain.toCancelCommMonoidWithZero.{u1} R (CommRing.toCommSemiring.{u1} R _inst_1) _inst_2))))))) -> (Eq.{succ u2} S (Polynomial.eval₂.{u1, u2} R S (Ring.toSemiring.{u1} R (CommRing.toRing.{u1} R _inst_1)) (CommSemiring.toSemiring.{u2} S _inst_3) f (HMul.hMul.{u2, u2, u2} S ((fun ([email protected]._hyg.2391 : R) => S) (Polynomial.leadingCoeff.{u1} R (Ring.toSemiring.{u1} R (CommRing.toRing.{u1} R _inst_1)) p)) S (instHMul.{u2} S (NonUnitalNonAssocSemiring.toMul.{u2} S (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} S (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))))) z (FunLike.coe.{max (succ u1) (succ u2), succ u1, succ u2} (RingHom.{u1, u2} R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))) R (fun (_x : R) => (fun ([email protected]._hyg.2391 : R) => S) _x) (MulHomClass.toFunLike.{max u1 u2, u1, u2} (RingHom.{u1, u2} R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))) R S (NonUnitalNonAssocSemiring.toMul.{u1} R (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))))) (NonUnitalNonAssocSemiring.toMul.{u2} S (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} S (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3)))) (NonUnitalRingHomClass.toMulHomClass.{max u1 u2, u1, u2} (RingHom.{u1, u2} R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))) R S (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1)))) (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} S (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))) (RingHomClass.toNonUnitalRingHomClass.{max u1 u2, u1, u2} (RingHom.{u1, u2} R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3))) R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3)) (RingHom.instRingHomClassRingHom.{u1, u2} R S (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_3)))))) f (Polynomial.leadingCoeff.{u1} R (Ring.toSemiring.{u1} R (CommRing.toRing.{u1} R _inst_1)) p))) (Polynomial.integralNormalization.{u1} R (Ring.toSemiring.{u1} R (CommRing.toRing.{u1} R _inst_1)) p)) (OfNat.ofNat.{u2} S 0 (Zero.toOfNat0.{u2} S (CommMonoidWithZero.toZero.{u2} S (CommSemiring.toCommMonoidWithZero.{u2} S _inst_3)))))
Case conversion may be inaccurate. Consider using '#align polynomial.integral_normalization_eval₂_eq_zero Polynomial.integralNormalization_eval₂_eq_zeroₓ'. -/
theorem integralNormalization_eval₂_eq_zero {p : R[X]} (f : R →+* S) {z : S} (hz : eval₂ f z p = 0)
(inj : ∀ x : R, f x = 0 → x = 0) :
eval₂ f (z * f p.leadingCoeff) (integralNormalization p) = 0 :=
calc
eval₂ f (z * f p.leadingCoeff) (integralNormalization p) =
p.support.attach.Sum fun i =>
f (coeff (integralNormalization p) i.1 * p.leadingCoeff ^ i.1) * z ^ i.1 :=
by
rw [eval₂, sum_def, support_integral_normalization]
simp only [mul_comm z, mul_pow, mul_assoc, RingHom.map_pow, RingHom.map_mul]
exact finset.sum_attach.symm
_ =
p.support.attach.Sum fun i =>
f (coeff p i.1 * p.leadingCoeff ^ (natDegree p - 1)) * z ^ i.1 :=
by
by_cases hp : p = 0; · simp [hp]
have one_le_deg : 1 ≤ nat_degree p :=
Nat.succ_le_of_lt (nat_degree_pos_of_eval₂_root hp f hz inj)
congr with i
congr 2
by_cases hi : i.1 = nat_degree p
· rw [hi, integral_normalization_coeff_degree, one_mul, leading_coeff, ← pow_succ,
tsub_add_cancel_of_le one_le_deg]
exact degree_eq_nat_degree hp
· have : i.1 ≤ p.nat_degree - 1 :=
Nat.le_pred_of_lt (lt_of_le_of_ne (le_nat_degree_of_ne_zero (mem_support_iff.mp i.2)) hi)
rw [integral_normalization_coeff_ne_nat_degree hi, mul_assoc, ← pow_add,
tsub_add_cancel_of_le this]
_ = f p.leadingCoeff ^ (natDegree p - 1) * eval₂ f z p :=
by
simp_rw [eval₂, sum_def, fun i => mul_comm (coeff p i), RingHom.map_mul, RingHom.map_pow,
mul_assoc, ← Finset.mul_sum]
congr 1
exact @Finset.sum_attach _ _ p.support _ fun i => f (p.coeff i) * z ^ i
_ = 0 := by rw [hz, _root_.mul_zero]
#align polynomial.integral_normalization_eval₂_eq_zero Polynomial.integralNormalization_eval₂_eq_zero
#print Polynomial.integralNormalization_aeval_eq_zero /-
theorem integralNormalization_aeval_eq_zero [Algebra R S] {f : R[X]} {z : S} (hz : aeval z f = 0)
(inj : ∀ x : R, algebraMap R S x = 0 → x = 0) :
aeval (z * algebraMap R S f.leadingCoeff) (integralNormalization f) = 0 :=
integralNormalization_eval₂_eq_zero (algebraMap R S) hz inj
#align polynomial.integral_normalization_aeval_eq_zero Polynomial.integralNormalization_aeval_eq_zero
-/
end IsDomain
end IntegralNormalization
end Polynomial
|
# A/B Testing Final Project
# Experiment Overview: Free Trial Screener
Control: Udacity courses have two options on the course overview page: "start free trial", and "access course materials".
- If the student clicks "start free trial", they will be asked to enter their credit card information, and then they will be enrolled in a free trial for the paid version of the course. After 14 days, they will automatically be charged unless they cancel first.
- If the student clicks "access course materials", they will be able to view the videos and take the quizzes for free, but they will not receive coaching support or a verified certificate, and they will not submit their final project for feedback.
Experiment: Udacity tested a change where if the student clicked "start free trial", they were asked how much time they had available to devote to the course.
- If the student indicated 5 or more hours per week, they would be taken through the checkout process as usual.
- If they indicated fewer than 5 hours per week, a message would appear indicating that Udacity courses usually require a greater time commitment for successful completion, and suggesting that the student might like to access the course materials for free. At this point, the student would have the option to continue enrolling in the free trial, or access the course materials for free instead.
This screenshot shows what the experiment looks like.
Hypothesis: this might set clearer expectations for students upfront, thus reducing the number of frustrated students who left the free trial because they didn't have enough time—without significantly reducing the number of students to continue past the free trial and eventually complete the course.
- If this hypothesis held true, Udacity could improve the overall student experience and improve coaches' capacity to support students who are likely to complete the course.
# Experiment Design
## Unit of diversion
The unit of diversion is a cookie, although if the student enrolls in the free trial, they are tracked by user-id from that point forward. The same user-id cannot enroll in the free trial twice. For users that do not enroll, their user-id is not tracked in the experiment, even if they were signed in when they visited the course overview page.
## Metric Choice
### Customer Funnel
### Invariant Metrics
> **Sanity check** can help check whether there’re things going wrong by looking at invariant metrics. There're two types of invariant metrics:
(1) population sizing metrics based on unit of diversion: experiment population and control population should be comparable.
(2) other invariants: the metrics that shouldn’t change in your experiment. We can check where the invariant metric falls under the overall process. If the feature affects the 2nd step in the customer funnel, then the metrics happens before the 2nd step can be used as invariant metrics.
**Number of Cookies**: number of unique cookies to visit the course overview page. This is the unit of diversion and should be even distributed among the control and experiment groups.
**Number of Clicks**: number of unique cookies to click the "Start free trial" buttion (which happens before the free trial screener is trigger). This metric is tracked before the experiment is triggered. So it should be comparable between the experiment and control groups.
**Click-through-probability**: number of unique cookies to click the "Start free trial" button divided by number of unique cookies to view the course overview page. This metric is also tracked before the experiment is triggered. So it should be comparable between the experiment and control groups.
### Evaluation metrics
> To evaluate the performance of the experiment, we should firstly choose a good metric, which can happen in any steps of the customer funnel after the experiment is triggered. Recall that the goal of the experiment is reducing the number of left students and encouraging more students to continue past the free trial.
To examine whether we can reach the goal in the experiment, our metrics should be in a rate or probability form, containing the following factors, which will change after the experiment and can impact our hypothesis:
- number of user-ids to enroll in the free trial (this is expected to decrease)
- number of user-ids to past the free-trial (this should not decrease significantly)
- number of user-ids who complete the course (hope this wil; increase)
Therefore, our final evaluation metrics are:
**Gross conversion**: number of user-ids to complete checkout and enroll in the free trial divided by number of unique cookies to click the "Start free trial" button.
(dmin = 0.01)
**Retention**: number of user-ids to remain enrolled past the 14-day boundary (and thus make at least one payment) divided by number of user-ids to complete checkout. (dmin = 0.01)
**Net conversion**: number of user-ids to remain enrolled past the 14-day boundary (and thus make at least one payment) divided by the number of unique cookies to click the "Start free trial" button. (dmin = 0.0075)
All the metrics have a predetermined practical significant value (dmin) which should be reached if we want to launch the experiment.
# Measuring Variability
For each metric you selected as an evaluation metric, estimate its standard deviation analytically, given a sample size of 5000 cookies visiting the course overview page. Do you expect the analytic estimates to be accurate? That is, for which metrics, if any, would you want to collect an empirical estimate of the variability if you had time?
Our three metrics are all in the form of probability, so we can assume them to be binomial distribution and used the formula to calculate the standard deviation of the sampling distribution for the proportion, or standard error:
\begin{align}
\sqrt{\frac{P*(1-P)}{N}}
\end{align}
Due to different unit of analysis these three metrics use, we should firstly calculate the number of unit of analysis.
- For **gross conversion** and **net conversion**, the unit of analysis is the number of unique cookies who click the button. In the baseline group, 40000 pageviews correspond to 3200 click on the button.
- For **retention**, the unit of analysis is number of users who complete checkout. In the baseline group, 40000 pageviews correspond to 660 checkouts and enrollments.
The following calculation is based on the [baseline data]()
```python
import pandas as pd
import numpy as np
```
```python
# Load the table
df = pd.read_excel("src/Baseline_Values.xlsx", header=None, names = ['metrics','value'])
df
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>metrics</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>Unique cookies to view course overview page pe...</td>
<td>40000.000000</td>
</tr>
<tr>
<td>1</td>
<td>Unique cookies to click "Start free trial" per...</td>
<td>3200.000000</td>
</tr>
<tr>
<td>2</td>
<td>Enrollments per day:</td>
<td>660.000000</td>
</tr>
<tr>
<td>3</td>
<td>Click-through-probability on "Start free trial":</td>
<td>0.080000</td>
</tr>
<tr>
<td>4</td>
<td>Probability of enrolling, given click:</td>
<td>0.206250</td>
</tr>
<tr>
<td>5</td>
<td>Probability of payment, given enroll:</td>
<td>0.530000</td>
</tr>
<tr>
<td>6</td>
<td>Probability of payment, given click</td>
<td>0.109313</td>
</tr>
</tbody>
</table>
</div>
```python
# Build a function to calculate variability
def variation(p,n):
return round(np.sqrt((p*(1-p))/n), 4)
```
```python
# Gross conversion
n = 5000 * (3200/40000)
p = 0.206250
print('Gross Conversion Standard Deviation: {}'.format(variation(p,n)))
```
Gross Conversion Standard Deviation: 0.0202
```python
# Net conversion
p = 0.109313
print('Net Conversion Standard Deviation: {}'.format(variation(p,n)))
```
Net Conversion Standard Deviation: 0.0156
```python
# Retention
n = 5000 * (660/40000)
p = 0.530000
print('Retention Standard Deviation: {}'.format(variation(p,n)))
```
Retention Standard Deviation: 0.0549
- For gross conversion and net conversion, their unit of analysis is the same as their unit of diversion, and therefore, their actual variability will be similar to the calculated variability.
- For retention, its unit of analysis is different from its unit of diversion, which means the actual variability might be a lot higher than what was calculated analytically.
# Calculating Sample Size
I won't use Bonferroni correction in my analysis phase. To decide the total number of pageviews I need, I'll set alpha = 0.05 and beta = 0.2.
The formula for sample size is:
As from the formula:
- z-beta = 0.84, if 1 - beta = 0.8
- z-alpha/2 = 1.96, if alpha = 0.05
- Standard deviation follows the formula that: ${SE}$ = $\frac{SD}{\sqrt{N}}$, which means we assume that the standard error is proportional to $\frac{1}{\sqrt{N}}$.
So I'll use the formula to firstly calculate the needed sample size, and then decide the total number of pageview needed.
```python
# Function for sample size
import scipy
from scipy import stats
def sample_size(n, p, dmin, alpha, beta):
SE = np.sqrt((p*(1-p))/n)
SD = SE * np.sqrt(n)
z_1 = abs(scipy.stats.norm.ppf(alpha/2))
z_2 = abs(scipy.stats.norm.ppf(beta))
each_size = 2*(SD**2)*((z_1+z_2)**2)/(dmin**2)
all_size = round(each_size * 2)
return all_size
```
```python
# Gross conversion
n = 5000 * (3200/40000)
p = 0.206250
dmin = 0.01
alpha = 0.05
beta = 0.2
all_size = int(sample_size(n,p,dmin,alpha,beta))
pageview_size_gross = int(all_size/(3200/40000))
print('Overall Sample Size Needed for Gross Conversion: {}'.format(all_size))
print('Overall Pageviews Needed for Gross Conversion: {}'.format(pageview_size_gross))
```
Overall Sample Size Needed for Gross Conversion: 51398
Overall Pageviews Needed for Gross Conversion: 642475
```python
# Net conversion
n = 5000 * (3200/40000)
p = 0.109313
dmin = 0.0075
alpha = 0.05
beta = 0.2
all_size = int(sample_size(n,p,dmin,alpha,beta))
pageview_size_net = int(all_size/(3200/40000))
print('Overall Sample Size Needed for Net Conversion: {}'.format(all_size))
print('Overall Pageviews Needed for Net Conversion: {}'.format(pageview_size_net))
```
Overall Sample Size Needed for Net Conversion: 54343
Overall Pageviews Needed for Net Conversion: 679287
```python
# Retention
n = 5000 * (660/40000)
p = 0.530000
dmin = 0.01
alpha = 0.05
beta = 0.2
all_size = int(sample_size(n,p,dmin,alpha,beta))
pageview_size_ret = int(all_size/(660/40000))
print('Overall Sample Size Needed for Retention: {}'.format(all_size))
print('Overall Pageviews Needed for Retention: {}'.format(pageview_size_ret))
```
Overall Sample Size Needed for Retention: 78206
Overall Pageviews Needed for Retention: 4739757
# Duration and Exposure
```python
df
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>metrics</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>Unique cookies to view course overview page pe...</td>
<td>40000.000000</td>
</tr>
<tr>
<td>1</td>
<td>Unique cookies to click "Start free trial" per...</td>
<td>3200.000000</td>
</tr>
<tr>
<td>2</td>
<td>Enrollments per day:</td>
<td>660.000000</td>
</tr>
<tr>
<td>3</td>
<td>Click-through-probability on "Start free trial":</td>
<td>0.080000</td>
</tr>
<tr>
<td>4</td>
<td>Probability of enrolling, given click:</td>
<td>0.206250</td>
</tr>
<tr>
<td>5</td>
<td>Probability of payment, given enroll:</td>
<td>0.530000</td>
</tr>
<tr>
<td>6</td>
<td>Probability of payment, given click</td>
<td>0.109313</td>
</tr>
</tbody>
</table>
</div>
```python
# From the table,we can see the unique page view each day is 40000.
# Assume that we divert 50% of the overall traffic to the experiment
fraction = 0.5
retention_day = round(pageview_size_ret/(40000*fraction))
print('Overall Days Needed for Retention Experiment: {}'.format(retention_day))
```
Overall Days Needed for Retention Experiment: 237
From the above calculation, we can know that if we want to use retention as a metric, we should spend 1185 days to gather enough pageviews for experiment, which is a pretty long-running experiment.
We have several choices to deal with this problem and shorten the experiment:
- Select another metric which need a smaller sample size
- Increase alpha (increase the possibility of false positive)
- Increase beta (increase the possibility of false negative)
- Increase dmin (increase the practical significance boundary to not try to detect a smaller change)
## Select another metric which need a smaller sample size
```python
# If we use gross conversion and still divert 50% of traffic to experiment
fraction = 0.5
gross_day = round(pageview_size_gross/(40000*fraction))
print('Overall Days Needed for Retention Experiment: {}'.format(gross_day))
```
Overall Days Needed for Retention Experiment: 32
```python
# If we use net conversion and still divert 50% of traffic to experiment
fraction = 0.5
net_day = round(pageview_size_net/(40000*fraction))
print('Overall Days Needed for Retention Experiment: {}'.format(net_day))
```
Overall Days Needed for Retention Experiment: 34
## Increase alpha (increase the possibility of false positive)
```python
import matplotlib.pyplot as plt
%matplotlib inline
alpha_list = np.linspace(0.05, 0.2, 40)
n = 5000 * (660/40000)
p = 0.530000
dmin = 0.01
beta = 0.2
pageview_size = [int(sample_size(n,p,dmin,alpha,beta)/(660/40000)) for alpha in alpha_list]
net_day = [round(i/(40000*fraction)) for i in pageview_size]
plt.plot(alpha_list, net_day)
plt.xlabel('alpha')
plt.ylabel('Days needed for experiment')
plt.show()
```
## Increase beta (increase the possibility of false negative)
```python
beta_list = np.linspace(0.1, 0.4, 40)
n = 5000 * (660/40000)
p = 0.530000
dmin = 0.01
alpha = 0.05
pageview_size = [int(sample_size(n,p,dmin,alpha,beta)/(660/40000)) for beta in beta_list]
net_day = [round(i/(40000*fraction)) for i in pageview_size]
plt.plot(beta_list, net_day)
plt.xlabel('beta')
plt.ylabel('Days needed for experiment')
plt.show()
```
## Increase dmin (increase the practical significance boundary to not try to detect a smaller change)
```python
dmin_list = np.linspace(0.01, 0.04, 40)
n = 5000 * (660/40000)
p = 0.530000
alpha = 0.05
beta = 0.2
pageview_size = [int(sample_size(n,p,dmin,alpha,beta)/(660/40000)) for dmin in dmin_list]
net_day = [round(i/(40000*fraction)) for i in pageview_size]
plt.plot(dmin_list, net_day)
plt.xlabel('dmin')
plt.ylabel('Days needed for experiment')
plt.show()
```
# Sanity check
Start by checking whether your invariant metrics are equivalent between the two groups.
- If the invariant metric is a simple count that should be randomly split between the 2 groups, I'll use a binomial test. I'll calculate a confidence interval around the fraction of events I expect to be assigned to the control group, and the observed value should be the actual fraction that was assigned to the control group.
- Otherwise, I'll need to construct a confidence interval for a difference in proportions, then check whether the difference between group values falls within that confidence level.
- If the sanity checks fail, I'll look at the day by day data and see if I can offer any insight into what is causing the problem.
```python
df_con = pd.read_excel("src/Final_Project_Results.xlsx", sheet_name="Control")
df_con.head()
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Date</th>
<th>Pageviews</th>
<th>Clicks</th>
<th>Enrollments</th>
<th>Payments</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>Sat, Oct 11</td>
<td>7723</td>
<td>687</td>
<td>134.0</td>
<td>70.0</td>
</tr>
<tr>
<td>1</td>
<td>Sun, Oct 12</td>
<td>9102</td>
<td>779</td>
<td>147.0</td>
<td>70.0</td>
</tr>
<tr>
<td>2</td>
<td>Mon, Oct 13</td>
<td>10511</td>
<td>909</td>
<td>167.0</td>
<td>95.0</td>
</tr>
<tr>
<td>3</td>
<td>Tue, Oct 14</td>
<td>9871</td>
<td>836</td>
<td>156.0</td>
<td>105.0</td>
</tr>
<tr>
<td>4</td>
<td>Wed, Oct 15</td>
<td>10014</td>
<td>837</td>
<td>163.0</td>
<td>64.0</td>
</tr>
</tbody>
</table>
</div>
```python
df_exp = pd.read_excel("src/Final_Project_Results.xlsx", sheet_name="Experiment")
df_exp.head()
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Date</th>
<th>Pageviews</th>
<th>Clicks</th>
<th>Enrollments</th>
<th>Payments</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>Sat, Oct 11</td>
<td>7716</td>
<td>686</td>
<td>105.0</td>
<td>34.0</td>
</tr>
<tr>
<td>1</td>
<td>Sun, Oct 12</td>
<td>9288</td>
<td>785</td>
<td>116.0</td>
<td>91.0</td>
</tr>
<tr>
<td>2</td>
<td>Mon, Oct 13</td>
<td>10480</td>
<td>884</td>
<td>145.0</td>
<td>79.0</td>
</tr>
<tr>
<td>3</td>
<td>Tue, Oct 14</td>
<td>9867</td>
<td>827</td>
<td>138.0</td>
<td>92.0</td>
</tr>
<tr>
<td>4</td>
<td>Wed, Oct 15</td>
<td>9793</td>
<td>832</td>
<td>140.0</td>
<td>94.0</td>
</tr>
</tbody>
</table>
</div>
## For count metrics
### Number of Cookies
```python
# Given that each cookie is randomly assigned to the control group or experiment group with probability of 0.5
def sanity_check(total_con, total_exp, p=0.5, alpha =0.05):
# Compute standard deviation of binomial distribution
SD = np.sqrt(p*(1-p)/(total_con+total_exp))
# Multiply by z-score to get margin of error
z_1 = abs(scipy.stats.norm.ppf(alpha/2))
margin = SD*z_1
# Compute confidence interval around 0.5
C_I_lower = 0.5-margin
C_I_higher = 0.5+margin
# Calculate observed fraction, which is number of observations assigned to the control group
observe_fraction = total_con/(total_con+total_exp)
# Check whether the observed fraction lies between the Confidence interval
print('Confidence Interval: [{:.4f}, {:.4f}]'.format(C_I_lower, C_I_higher))
print('Observed proportion: {:.4f}'.format(observe_fraction))
print('Pass the sanity check: ' + str((observe_fraction<C_I_higher)&(observe_fraction>C_I_lower)))
return None
```
```python
# Pageview Sanity Check
sanity_check(df_con.Pageviews.sum(), df_exp.Pageviews.sum(), p, alpha)
```
Confidence Interval: [0.4988, 0.5012]
Observed proportion: 0.5006
Pass the sanity check: True
### Number of Clicks
```python
# Clicks Sanity Check
sanity_check(df_con.Clicks.sum(), df_exp.Clicks.sum(), p, alpha)
```
Confidence Interval: [0.4959, 0.5041]
Observed Proportion: 0.5005
Pass the sanity check: True
## For proportion metric
### Click-through-probability
```python
def sanity_check_prop(click_con, click_exp, pageview_con, pageview_exp, alpha =0.05):
# Calculate the pooled proportion
p_pool = (click_con+click_exp)/(pageview_con+pageview_exp)
# Compute standard deviation of binomial distribution
SE_pooled = np.sqrt(p_pool*(1-p_pool)*(1/pageview_con+1/pageview_exp))
# Multiply by z-score to get margin of error
z_1 = abs(scipy.stats.norm.ppf(alpha/2))
margin = SE_pooled*z_1
# Calculate the observed difference in proportion between two groups
d = click_exp/pageview_exp - click_con/pageview_con
# Compute confidence interval around the observed difference
# We expect our estimation of difference between groups to be distributed normally,
# with a mean of 0 and a standard deviation of the pooled standard error.
C_I_lower = -margin
C_I_higher = margin
# Check whether the observed difference lies between the Confidence interval
print('Confidence Interval: [{}, {}]'.format(round(C_I_lower, 4), round(C_I_higher, 4)))
print('Observed difference: {}'.format(round(d,4)))
print('Pass the sanity check: ' + str((d<C_I_higher)&(d>C_I_lower)))
return None
```
```python
sanity_check_prop(df_con.Clicks.sum(), df_exp.Clicks.sum(), df_con.Pageviews.sum(), df_exp.Pageviews.sum(), alpha =0.05)
```
Confidence Interval: [-0.0013, 0.0013]
Observed difference: 0.0001
Pass the sanity check: True
# Check for Practical and Statistical Significance
For evaluation metrics, calculate a confidence interval for the difference between the experiment and control groups, and check whether each metric is statistically and/or practically significance.
- A metric is statistically significant if the confidence interval does not include 0 (that is, you can be confident there was a change).
- A metric is practically significant if the confidence interval does not include the practical significance boundary (that is, you can be confident there is a change that matters to the business.)
I'll **not use Bonferroni correction** in this case. Because an unfortunate byproduct of Bonferroni correction is that I may increase the number of false negatives, where there really is an effect but we can't detect it as statistically significant. In our case, all metrics matter to our business and ignoring some of them may hinder us from discovering problems. Therefore, false negatives are very costly, and I don't want to correct for multiple comparisons at all.
## Gross Conversion
```python
# The function is similar to the sanity check function above
def significance_prop(m_con, m_exp, N_con, N_exp, dmin, alpha =0.05):
# Calculate the pooled proportion
p_pool = (m_con+m_exp)/(N_con+N_exp)
# Compute standard deviation of binomial distribution
SE_pooled = np.sqrt(p_pool*(1-p_pool)*(1/N_con+1/N_exp))
# Multiply by z-score to get margin of error
z_1 = abs(scipy.stats.norm.ppf(alpha/2))
margin = SE_pooled*z_1
# Calculate the observed difference in proportion between two groups
diff = m_exp/N_exp - m_con/N_con
# Compute confidence interval around the observed difference
# We expect our estimation of difference between groups to be distributed normally,
# with a mean of diff and a standard deviation of the pooled standard error.
C_I_lower = diff-margin
C_I_higher = diff+margin
# Check whether the Confidence interval include 0 and the practical significance boundary
print('Confidence Interval: [{}, {}]'.format(round(C_I_lower, 4), round(C_I_higher, 4)))
print('Observed difference: {}'.format(round(diff,4)))
print('Statistically significan: ' + str((C_I_higher < 0) or (C_I_lower > 0)))
print('Practically significan: ' + str((C_I_higher < -dmin) or (C_I_lower > -dmin)))
return None
```
```python
# Gross conversion: number of user-ids to enroll in the free trial divided by number of unique click
# Clicks and enrollment should be collected in same days
df_con_em = df_con[df_con['Enrollments'].notnull()]
df_exp_em = df_exp[df_exp['Enrollments'].notnull()]
m_con = df_con_em.Enrollments.sum()
m_exp = df_exp_em.Enrollments.sum()
N_con = df_con_em.Clicks.sum()
N_exp = df_exp_em.Clicks.sum()
significance_prop(m_con, m_exp, N_con, N_exp, 0.01, alpha =0.05)
```
Confidence Interval: [-0.0291, -0.012]
Observed difference: -0.0206
Statistically significan: True
Practically significan: True
```python
# Net conversion: number of user-ids to remain enrolled after 14 days divided by the number of unique click
df_con_py = df_con[df_con['Payments'].notnull()]
df_exp_py = df_exp[df_exp['Payments'].notnull()]
m_con = df_con_py.Payments.sum()
m_exp = df_exp_py.Payments.sum()
N_con = df_con_py.Clicks.sum()
N_exp = df_exp_py.Clicks.sum()
significance_prop(m_con, m_exp, N_con, N_exp, 0.0075, alpha =0.05)
```
Confidence Interval: [-0.0116, 0.0019]
Observed difference: -0.0049
Statistically significan: False
Practically significan: False
```python
len(df_con[con_index].Clicks)
```
23
# Run Sign Tests
For each evaluation metric, do a sign test using the day-by-day breakdown. Sign test hypothesize that the probability of two outcomes (difference in two groups or not) have equal likelihood of 0.5. If the sign test does not agree with the confidence interval for the difference, see if you can figure out why.
## Gross conversion
```python
# Gather a list include all positive outcomes, which is the number of days when gross_conversion in experiment >
# gross_conversion in control group and negative outcomes
cases = np.array((df_exp_em.Enrollments/df_exp_em.Clicks >= df_con_em.Enrollments/df_con_em.Clicks) + 0)
cases
```
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
0])
```python
def signtest(positive_case):
posi = len(cases[cases==1])
case = len(cases)
p = binom_test(posi, case)
return p
```
```python
signtest(cases)
```
0.0025994777679443364
The sign test on gross conversion matches the confidence interval that the difference is statistically significant.
## Net conversion
```python
cases = np.array((df_exp_py.Payments/df_exp_py.Clicks >= df_con_py.Payments/df_con_py.Clicks) + 0)
cases
```
array([0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1,
1])
```python
signtest(cases)
```
0.6776394844055175
The sign test on net conversion matches the confidence interval that the difference is not statistically significant.
|
/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2019 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#ifndef MIOPEN_GUARD_MLOPEN_CONV_SOLUTION_HPP
#define MIOPEN_GUARD_MLOPEN_CONV_SOLUTION_HPP
#include <miopen/miopen.h>
#include <miopen/kernel_info.hpp>
#include <miopen/invoker.hpp>
#include <boost/optional.hpp>
#include <string>
#include <vector>
#include <ostream>
namespace miopen {
namespace solver {
/// Information required to build and run a kernel (or a set of kernels),
/// which is expected to perform computatons as per the problem config.
///
/// TODO: Currently best suits a subset of existing solvers,
/// namely some OpenCL-written forward direct convolutions.
/// Shall be refactored (possibly, to a class hierarchy).
struct ConvSolution
{
/// \todo Use better name than construction_params.
std::vector<KernelInfo> construction_params; // impl may consist of multiple kernels.
miopenStatus_t status;
std::string solver_id;
boost::optional<InvokerFactory> invoker_factory;
size_t workspce_sz;
int grp_tile1; // total number ALUs per group
int grp_tile0; // total number ALUs per group
int in_tile1; // size of in-tile in local memory
int in_tile0; // size of in-tile in local memory
int out_pix_tile1; // # of generated pixels per output per wk-item (ALU)
int out_pix_tile0; // # of generated pixels per output per wk-item (ALU)
int n_out_pix_tiles; // # output pixel tiles per wk-item (ALU)
int n_in_data_tiles; // # of blocks of different inputs in LDS
int n_stacks; // # of diff stacks (part of batch).
ConvSolution(miopenStatus_t status_ = miopenStatusSuccess)
: status(status_),
solver_id("<unknown>"),
invoker_factory(boost::none),
workspce_sz(0),
grp_tile1(-1),
grp_tile0(-1),
in_tile1(-1),
in_tile0(-1),
out_pix_tile1(-1),
out_pix_tile0(-1),
n_out_pix_tiles(-1),
n_in_data_tiles(-1),
n_stacks(-1)
{
}
inline bool Succeeded() const { return status == miopenStatusSuccess; }
};
std::ostream& operator<<(std::ostream& os, const ConvSolution& s);
void PrecompileSolutions(const Handle& h, const std::vector<ConvSolution>& sols);
} // namespace solver
} // namespace miopen
#endif
|
If $x$ is less than $b$, then the interior of the closed interval $[-\infty, x]$ is the open interval $(-\infty, x)$. |
//==============================================================================
// Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_SWAR_FUNCTIONS_SIMD_COMMON_GROUP_HPP_INCLUDED
#define BOOST_SIMD_SWAR_FUNCTIONS_SIMD_COMMON_GROUP_HPP_INCLUDED
#include <boost/simd/swar/functions/group.hpp>
#include <boost/simd/include/functions/simd/load.hpp>
#include <boost/simd/include/functions/simd/saturate.hpp>
#include <boost/simd/sdk/memory/aligned_type.hpp>
#include <boost/simd/sdk/meta/cardinal_of.hpp>
#include <boost/simd/sdk/meta/scalar_of.hpp>
#include <boost/simd/sdk/simd/details/native/meta/downgrade.hpp>
#include <boost/mpl/not.hpp>
#include <boost/type_traits/is_same.hpp>
/////////////////////////////////////////////////////////////////////////////
// Implementation when type A0 is downgradable
/////////////////////////////////////////////////////////////////////////////
namespace boost { namespace simd { namespace ext
{
BOOST_SIMD_FUNCTOR_IMPLEMENTATION_IF( boost::simd::tag::group_, tag::cpu_,
(A0)(X),
(boost::mpl::not_< boost::is_same<A0, typename dispatch::meta::downgrade<A0>::type> >),
((simd_<arithmetic_<A0>,X>))((simd_<arithmetic_<A0>,X>))
)
{
typedef typename dispatch::meta::downgrade<A0>::type result_type;
BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
{
A0 aa0 = boost::simd::saturate<result_type>(a0);
A0 aa1 = boost::simd::saturate<result_type>(a1);
static const size_t size = boost::simd::meta::cardinal_of<A0>::value;
typedef typename meta::scalar_of<result_type>::type sR;
BOOST_SIMD_ALIGNED_TYPE(sR) tmp[size*2];
for(size_t i = 0; i != size; ++i) tmp[i] = static_cast<sR>(aa0[i]);
for(size_t i = 0; i != size; ++i) tmp[i+size] = static_cast<sR>(aa1[i]);
return load<result_type>(&tmp[0], 0);
}
};
} } }
#endif
|
% minimum distance from nose of fly to ellipse of any other fly within 30
% degrees
function [data,units] = compute_dnose2ell_anglerange(trx,n,anglerange_str,varargin)
flies = trx.exp2flies{n};
nflies = numel(flies);
data = cell(1,nflies);
% name of closestfly stat
fn = sprintf('closestfly_nose2ell_angle_%sto%s',anglerange_str{:});
% access closestfly to ensure that dnose2ell_anglerange is computed
for i = 1:numel(flies),
trx(flies(i)).(fn);
end
%compute_closestfly_nose2ell_anglerange(trx,n,anglerange,varargin{:});
% anglerange_deg = round(anglerange*180/pi);
% fn = sprintf('dnose2ell_angle_%dto%d',anglerange_deg(1),anglerange_deg(2));
% fn = strrep(fn,'-','min');
% name of dnose2ell stat
fn = sprintf('dnose2ell_angle_%sto%s',anglerange_str{:});
for i1 = 1:nflies,
fly1 = flies(i1);
data{i1} = trx(fly1).(fn);
end
units = parseunits('mm');
|
Require Import Coq.Bool.Bool.
Require Import ExtLib.Structures.Sets.
Require Import ExtLib.Structures.Reducible.
Require Import ExtLib.Structures.Functor.
Set Implicit Arguments.
Set Strict Implicit.
(** Program with respect to the set interface **)
Section with_set.
Variable V : Type.
Context {set : Type}.
Context {Set_set : DSet set V}.
Definition contains_both (v1 v2 : V) (s : set) : bool :=
contains v1 s && contains v2 s.
(** Iteration requires foldability **)
Context {Foldable_set : Foldable set V}.
Definition toList (s : set) : list V :=
fold (@cons _) nil s.
End with_set.
(** Instantiate the set **)
Require Import ExtLib.Data.Set.ListSet.
Require Import ExtLib.ExtLib.
Eval compute in contains_both 0 1 empty.
Eval compute in toList (add true (add true empty)).
Eval compute in fmap negb (add true empty). |
The 1 Series offers all that BMW stands for in a compact package. Available with three or five doors, this sleek and sporty car is a joy to drive, exceptionally comfortable to ride in as a passenger and economical to own thanks to the range of innovative engines on offer. Here at Cowley Motor Company you'll find a great selection of quality used BMW 1 Series models, all of which have been thoroughly tested and checked before arriving on the forecourt. Take the chance to view our latest stock of used cars here on the website, before contacting a member of the team to discuss your requirements in more detail. |
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" |
Formal statement is: lemma open_contains_ball_eq: "open S \<Longrightarrow> x\<in>S \<longleftrightarrow> (\<exists>e>0. ball x e \<subseteq> S)" Informal statement is: A set $S$ is open if and only if for every $x \in S$, there exists an $e > 0$ such that the ball of radius $e$ centered at $x$ is contained in $S$. |
\chapter{Privacy, security and performance}
\label{chap:security}
\newcommand{\yes}{\(+\)\xspace}
\newcommand{\no}{\(-\)\xspace}
\newcommand{\maybe}{\(\pm\)\xspace}
\newcommand{\cat}[1]{\begin{em}#1\end{em}}
\section{Introduction}
In the previous chapters I showed the technical feasibility of a \ptfp system based on BLE.
As noted in the introduction, another requirement for such a system is social acceptance.
When location data was found to be collected on iPhones in 2011\urlref{http://radar.oreilly.com/2011/04/apple-location-tracking.html}{12 June 2014}, presumably violating user's privacy, this set of an worried reaction from the public\urlref{http://abcnews.go.com/Technology/apple-pushed-congress-answers-iphone-tracking/story?id=13426917}{12 June 2014}.
Recent realisation that one's phone can be tracked by shop owners, has led to its own angry reactions\urlref{http://www.nytimes.com/2013/07/15/business/attention-shopper-stores-are-tracking-your-cell.html}{12 June 2014}.
Since recent revelations on government data collection have most likely only strengthened the public's desire for privacy.
In this chapter I compare the privacy, security and performance of BLE based positioning systems to that of some well-known alternatives.
I score each method on 12 points in three categories: \yes, \no and \maybe
The system is set up so that \yes is always more desirable than \maybe, which in turn is more desirable than \no.
Many of the scores are debatable; where needed I give my arguments in the text.
I feel I scored the methods objectively, but someone else may come to other results on the same points.
The produced score card should therefore not be taken as a means to come to a single, final, score for each method; it does give a quick overview of some of the methods in use, and their strong and weak points.
\section{Methods}
The methods are divided in 4 categories: Non-technological methods are using a paper map and street signs, and asking for directions.
In traditional technological methods I distinguish traditional GPS, assisted GPS (A-GPS; GPS augmented with information from an internet connection), \wifi positioning.
I further consider RSS-based BLE positioning, such as discussed in the previous chapter, in combination with each of the fingerprint-database access methods from \sectionref{architecture}{database}, and finally the two alterative positioning methods from \sectionref{architecture}{alternative}.
Many methods can be implemented in different ways; if there is a prevalent default way, I look at that one, else I assume the way that scores best.
\section{Scoring}
\newcommand{\y}{& \cellcolor{yes} \(+\)}
\newcommand{\n}{& \cellcolor{no} \(-\)}
\newcommand{\m}{& \cellcolor{maybe} \(\pm\)}
\newcommand{\hlinethick}{\Xhline{2\arrayrulewidth}}
\begin{table}
\begin{tabular}{c | r!{\vrule width 2\arrayrulewidth}c|c!{\vrule width 2\arrayrulewidth}c|c|c!{\vrule width 2\arrayrulewidth}c|c|c|c!{\vrule width 2\arrayrulewidth}c!{\vrule width 2\arrayrulewidth}}
\multicolumn{2}{c!{\vrule width 2\arrayrulewidth}}{}
\h{Paper map and street signs}
\h{Ask for directions}
\h{GPS}
\h{A-GPS}
\h{\Wifi}
\h{BLE Global database}
\h{BLE in-\app database}
\h{BLE in-beacon database}
\h{BLE Bats \& Crickets}
\h{Listening beacons}
\\ \hlinethick
\rowspan{4}{Privacy}
& beacon owner \y \m \y \y \y \y \n \y \y \n
\\ \cline{2-11}
& database owner\y \y \y \m \n \n \y \y \y \y
\\ \cline{2-11}
& third party \y \y \y \y \y \y \y \y \y \n
\\ \cline{2-11}
& untackable \y \m \y \y \y \y \n \y \y \y
\\ \hlinethick
\rowspan{4}{Security}
& passive DOS \m \y \y \y \m \n \n \n \n \m
\\ \cline{2-11}
& active DOS \m \y \n \n \n \n \n \n \n \n
\\ \cline{2-11}
& passive spoof \m \y \y \y \m \n \n \n \n \m
\\ \cline{2-11}
& active spoof \m \m \n \n \n \n \n \n \n \n
\\ \hlinethick
\rowspan{7}{Performance}
& time to fix \m \m \n \y \m \y \y \m \y \y
\\ \cline{2-11}
& accuracy \m \m \m \m \n \m \m \m \y \y
\\ \cline{2-11}
& scalability \y \m \y \y \y \y \y \m \y \m
\\ \cline{2-11}
& affordable \m \y \n \n \m \m \y \y \y \m
\\ \cline{2-11}
& works indoors \n \y \n \n \y \y \y \y \y \y
\\ \cline{2-11}
& no internet \y \y \y \n \n \n \y \y \y \y
\\ \cline{2-11}
& up-to-date \n \m \y \y \y \y \n \y \y \y
\\ \hlinethick
\end{tabular}
\caption{Scores for different positioning methods}
\label{tbl:security-scoring}
\end{table}
\subsection{Privacy}
Privacy is the ability to do positioning without anybody else finding out that you are doing so.
In addition to the party for whom the positioning information is meant, there are three parties possibly involved.
The \cat{beacon owner} is the entity that manages the beacon-network.
The \cat{database owner} is the owner of the global database, for systems that use them.
\cat{Third-party} is an arbitrary eaves-dropper; it implies some large-scale automatic way of doing this, not just standing somewhere and watching.
A second, more serious, way in which privacy can be lost is if two positionings done (either in short succession or days apart) can be determined to be from the same \device; if not I determine the method to be \cat{untrackable}.
The paper map scores \yes on all four points: even though somebody may see you using the map, and recognise you next time, this is the same in all methods and not considered.
Asking for directions scores \yes on third party and database owner, however only \maybe on beacon owner (in this context the person asked is the beacon) and untrackable, since the person used for getting the directions, has information on your position and may recognise you next time.
GPS is a technique that does not require any signal from the phone to a central authority, so scores \yes on all privacy issues.
A-GPS on the other hand can be used in two ways: in Mobile Station Based mode, only global information is read from the internet, no revealing privacy sensitive data; in Mobile Station Assisted mode positioning data is sent to a central location, resulting in a \maybe for database owner.
I assume, without having confirmed, that in this latter case no information that could be used to track the device over requests is being sent, resulting in a \yes on untrackable.
Using \wifi positioning, a database owner learns the fingerprint query made (\no), but no other privacy sensitive data is shared.
BLE with a global database has equal privacy performance to \wifi.
An in-\app database has different characteristics.
Since the \app used to do the positioning is owned by the owner of the beacon network, the owner has access to both the position of the phone, and can identify the same phone again next time, so on both owner and untackable this method scores \no.
BLE with an in-beacon database does not need a third party, and downloads only ``global'' information from a beacon, giving the method two \yes s.
Bats \& Crickets score perfect on privacy, provided that the beacons broadcast their own position in the same way that was suggested for \aBRP-RPM beacons in \sectionref{architecture}{measurements-brp-rpm}.
Listening beacons do not use a global database(\yes), however the owner of the network knows the location of the \device (\no).
Whether subsequent requests are untrackable depends on how the position is relayed back to the phone, but it is possible to do this in a way that is secure and untrackable.
However a third party could place his own positioning listening beacons (e.g.\ in the shop next-door) and learn the \device's location that way.
\subsection{Security}
The security score illustrates how resilient the technique is against an attacker.
Two types of attacks can happen: either a denial-of-service, where the attacker makes sure that positioning fails, or a spoofing attack, where the attacker aims to let the positioning result in a different position than the actual position.
Either type of attack can happen in two ways: active, where the attacker has to be present, or has to have a device present, to succeed, or passive, which only requires that the attacker did something in the past.
If a technique is susceptible to a passive attack, this implies that it is at least as susceptible to an active attack.
The score on this section depends not only on whether an attack is theoretically possible, but also on whether it is practically feasible; for instance shooting a GPS satellite out of the sky is not considered feasible.
The paper map and street signs attack can be DOS'ed by an attacker removing the street signs, or spoofed by replacing street signs by fake ones.
This is a passive attack, however the practical feasibility is limited, and possibly a user will be able to navigate with just the map, even without street signs.
This technique therefore scores \maybe on all attacks.
Asking for directions is resilient to most attacks, however a motivated attacker could stake out a location and give a user wrong directions when asked.
Since this last one is doubtful to succeed, the technique scores \maybe on that one, and \yes on all others.
I do not consider destroying or moving satellites feasible, making both GPS and A-GPS resilient to passive attacks.
GPS signals can be jammed\citep{grant2009gps}, or spoofed\citep{tippenhauer2011requirements}, meaning that the techniques are not secure against active attacks.
It should be mentioned that none of the other positioning systems are resilient against active attacks, since signals can always be jammed or listened to and retransmitted on another location.
\Wifi positioning scores a \maybe for passive attacks, since the \wifi access points are usually not in a location where an attacker can disable or move them.
Since BLE positioning beacons will typically be placed in more accessible locations than \wifi (because of the shorter range and the lower cost of the beacons), any BLE beacon technique will be vulnerable to passive attacks, such as stealing or moving of beacons, as well.
This is equally true for Bats \& Crickets.
The listening beacons get a \maybe for these kinds of attacks, since they are networked and will be able to notice disruptions and possibly take appropriate corrective action.
\subsection{Performance}
Finally I look at how useful the systems are.
\cat{Time to (first) fix (TTFF)} describes how long it takes to get the first fix.
Less than 2 seconds scores \yes, less than a minute scores \maybe, more than a minute is \no.
\cat{Accuracy} scores a \yes if the position reported is within one meter of the true position, \maybe if it is within 5 meters, \no means more than 5 meter.
\cat{Scalability} means whether a system can cope with many clients positioning at the same time.
\cat{Affordable} talks about the cost of creating and managing the system, notably \begin{em}not\end{em} the cost of doing a single positioning.
Whether the system can be used indoors or without an internet connection being present is noted in the next two properties \cat{works indoors} and \cat{no internet}.
The final property, \cat{up-to-date} illustrates the ability of the system to quickly incorporate changes.
For paper map or asking directions, I estimate to have an answer within a minute, accurate to within a couple of meters.
Both systems work without internet, but where the asking directions is cheap and works indoors, paper maps and street signs only work outdoors, and require purchase of maps and maintenance of street signs.
Paper maps are scalable, however if thousands of people were to ask directions every day, very few would be happy to answer.
Maps are not up-to-date, while the knowledge of a person asked for directions may be up-to-date.
GPS and A-GPS differ mostly in the time to first fix (this being much shorter with A-GPS, seconds, as opposed to GPS's 12.5 minutes), and the need for internet (only A-GPS).
Accuracy may be slightly better with A-GPS (depending on the mode), but still not within a meter, while scalability is slightly worse for A-GPS, however not enough not to give it a \no.
Both systems are extremely expensive (not necessarily per user, but to launch and maintain in absolute cost) and do not work indoors since GPS signals do not penetrate buildings.
\Wifi has a \maybe time to first fix, since scanning the \wifi channels takes more than 2 seconds on newer phones that support 5GHz \wifi.
The accuracy is generally \no, but may be better in area of high access point density.
The system scales well and it costs a bit to maintain the central database.
It does work indoors and does not work without internet.
The BLE methods all give a quick time to first fix, except for in-beacon database, which needs time to download the database from the beacon, scoring \maybe.
The accuracy of BLE positioning is a topic of active research (to which this report hopefully makes a contribution).
It is not per-se better than \wifi, but since beacons are cheap and can be deployed in great numbers, I score this \maybe.
The in-beacon database may have problems scaling, since each initial positioning occupies a beacon for a while, to download the database and map, scoring \maybe on scaling, where the two other BLE technologies scale fine.
The central database costs some money to set-up and maintain, the other two BLE technologies are cheap.
All three work indoors, and only the central database needs an internet connection.
Finally, the update problems with an in-\app database have been discussed in \sectionref{architecture}{in-app-database}; both other BLE methods can receive updates easily.
Bats \& Crickets score very well on all points, however accuracy greatly depends on how accurate the time stamps on BLE packets are.
Finally the listening beacons technology has a fast time to first fix, (possibly) high accuracy, however the technology for this high accuracy will make the beacons more expensive.
Since one or more beacons are occupied to do the positioning, the systems scores \maybe on scaling.
It works indoors, and does not need an internet connection.
|
(** **********************************************************
Ralph Matthes
August 2022
*)
(** **********************************************************
constructs the final object of the bicategory of whiskered monoidal categories
this resides in a separate file because of the heavy dependencies
************************************************************)
Require Import UniMath.Foundations.All.
Require Import UniMath.MoreFoundations.All.
Require Import UniMath.CategoryTheory.Core.Categories.
Require Import UniMath.CategoryTheory.categories.StandardCategories.
Require Import UniMath.Bicategories.Core.Examples.BicatOfCats.
Require Import UniMath.Bicategories.DisplayedBicats.DispBicat.
Require Import UniMath.Bicategories.Limits.Final.
Require Import UniMath.Bicategories.Limits.Examples.BicatOfCatsLimits.
Require Import UniMath.Bicategories.Limits.Examples.TotalBicategoryLimits.
Require Import UniMath.CategoryTheory.Monoidal.WhiskeredBifunctors.
Require Import UniMath.CategoryTheory.Monoidal.Categories.
Require Import UniMath.Bicategories.MonoidalCategories.BicatOfWhiskeredMonCats.
Local Open Scope cat.
Definition unit_monoidal : monoidal (pr1 unit_category).
Proof.
use tpair.
- use tpair.
+ use make_bifunctor_data.
* exact (fun _ _ => tt).
* intros. apply idpath.
* intros. apply idpath.
+ exists tt.
repeat split; intro x; induction x; apply isapropunit.
- split.
+ abstract (repeat split).
+ abstract (
do 2 (split; [split; red; intros; [apply isasetunit | split; apply isasetunit] |]);
split;
[ do 3 (split; [red; intros; apply isasetunit |]);
split; apply isasetunit |
split; red; intros; apply isasetunit]).
Defined.
Definition unit_monoidal_disp_bifinal_obj : disp_bifinal_obj_stronger bidisp_monbicat_disp_bicat (_,,bifinal_cats).
Proof.
exists unit_monoidal.
use tpair.
- intros C M.
cbn.
use tpair.
+ use tpair.
* split; red; intros; apply idpath.
* abstract (repeat split).
+ split; red; intros; exists (idpath tt); abstract (split; apply isasetunit).
- intros x xx f g ff gg.
red; cbn; red; cbn.
split; red; intros; apply isasetunit.
Defined.
Definition bifinal_moncats : bifinal_obj monbicat.
Proof.
use total_bicat_final_stronger.
- exact monbicat_disp_2cells_isaprop.
- exact (_,,bifinal_cats).
- exact unit_monoidal_disp_bifinal_obj.
Defined.
|
lemma hol_pal_lem2: assumes S: "convex S" "open S" and abc: "a \<in> S" "b \<in> S" "c \<in> S" and "d \<noteq> 0" and lek: "d \<bullet> a \<le> k" "d \<bullet> b \<le> k" and holf1: "f holomorphic_on {z. z \<in> S \<and> d \<bullet> z < k}" and holf2: "f holomorphic_on {z. z \<in> S \<and> k < d \<bullet> z}" and contf: "continuous_on S f" shows "contour_integral (linepath a b) f + contour_integral (linepath b c) f + contour_integral (linepath c a) f = 0" |
"""Returns a random graph according to
the Barabási–Albert preferential attachment model
With labeled edges.
A graph of `number_of_nodes` nodes is grown by attaching new nodes each with
`number_of_edges` edges that are preferentially attached to existing nodes with high degree.
"""
import random
from typing import Iterable, Union
from networkx import MultiDiGraph, barabasi_albert_graph
from tqdm import tqdm
__all__ = ["labeled_barabasi_albert_graph"]
def labeled_barabasi_albert_graph(
number_of_nodes: int,
number_of_edges: int,
seed: Union[int, None] = None,
edge_labels: Iterable[str] = "abcd",
verbose: bool = True,
) -> MultiDiGraph:
"""Returns a random graph according
to the Barabási–Albert preferential attachment model
With labeled edges.
A graph of `number_of_nodes` nodes is grown by attaching new nodes each with
`number_of_edges` edges that are preferentially attached to existing nodes with high degree.
Parameters
----------
number_of_nodes : int
Number of nodes.
number_of_edges : int
Number of edges to attach from a new node to existing nodes.
seed : Union[int, RandomState, None]
Indicator of random number generation state.
edge_labels: Iterable[str]
Labels that will be used to mark the edges of the graph.
verbose : bool
If true, a progress bar will be displayed.
Examples
--------
>>> import cfpq_data
>>> g = cfpq_data.labeled_barabasi_albert_graph(42, 29, 42, verbose=False)
>>> g.number_of_nodes()
42
>>> g.number_of_edges()
754
Returns
-------
g : MultiDiGraph
A random graph according
to the Barabási–Albert preferential attachment model.
Raises
------
NetworkXError
If `m` does not satisfy ``1 <= m < n``.
References
----------
.. [1] A. L. Barabási and R. Albert "Emergence of scaling in
random networks", Science 286, pp 509-512, 1999.
.. [2] https://networkx.org/documentation/stable//reference/randomness.html#randomness
"""
g = MultiDiGraph(
barabasi_albert_graph(n=number_of_nodes, m=number_of_edges, seed=seed)
)
random.seed(seed)
for edge in tqdm(g.edges, disable=not verbose, desc="Generation..."):
label = random.choice(list(edge_labels))
g.edges[edge]["label"] = label
return g
|
A function $f$ is continuous at $x$ if and only if for every open set $t$ containing $f(x)$, there exists an open set $s$ containing $x$ such that $f(s) \subseteq t$. |
Require Import Crypto.Arithmetic.PrimeFieldTheorems.
Require Import Crypto.Specific.solinas32_2e256m189_11limbs.Synthesis.
(* TODO : change this to field once field isomorphism happens *)
Definition carry :
{ carry : feBW_loose -> feBW_tight
| forall a, phiBW_tight (carry a) = (phiBW_loose a) }.
Proof.
Set Ltac Profiling.
Time synthesize_carry ().
Show Ltac Profile.
Time Defined.
Print Assumptions carry.
|
Spem in alium was written by Thomas Tallis in c1570 and stands apart from most other choral music because it is written for 40 parts. Most choral music, regardless of the number of people in the choir, only has 4-6 parts. Just for its sheer flamboyance, Spem is famed among choristers due to the challenges of learning and performing it.
Delving into the details of how the music is constructed, rather than being written for a single choir of 40 voices, it is written for eight choirs each of five voices. Each choir comprises one soprano, one alto and either two tenors and one baritone, or one tenor and two baritones.
I decided it would be fun to experiment with recording it, although I don’t currently have access to a choir of 40 with the time to learn and perform it! I thought about William Orbit‘s recording of Barber’s Adagio for Strings and how well the gentle synthesised sounds worked for him. I’m no expert at electronic music but it is something I have played with in the past.
Being out of copyright, it was easy (and legal!) to obtain a MIDI file of Spem which contains the 40 parts as separate tracks. I imported it into my favourite musical editor, MuseScore, and had a look at the tracks.
For those not in the know, MIDI files don’t contain sound but rather are the computerised equivalent of sheet music – they contain instructions about what notes to play. The computer generates the sound during playback by using a soundfont, which contains sound samples. Just like a real font with a text document, you can change the soundfont for a different sound. The default soundfont with MuseScore is reasonably good but the choir sound is lacking. I downloaded a few free soundfonts until I found one with a choir sound that I liked.
As well as using a soundfont to play MIDI files back, MuseScore can generate a WAV or MP3 sound file from the MIDI file. I got MuseScore to export each choral part as a separate sound file, which can then be edited using a multi-track sound editor – in my case, Adobe Audition. I told MuseScore not to add any effects like reverb to the output, as I’ll do that later.
Traditionally, when performing Spem, the 40 choristers stand in a semicircular shape around the conductor, grouped in their eight choirs. This is how I configured my first attempt with the 40 singers standing in a semicircle.
I wondered about arranging the voices grouped not in choirs but in parts: into soprano, alto, tenor and baritone. This would mean all the high notes coming from the left and all the low notes from the right, and that would also sound odd.
Eventually I decided to sort the voices using a numerical pattern to split up the choirs and the parts so there would be no overall weighting. I made a spreadsheet to work out the ordering, and then spread the 40 voices over the arc, 5 degrees apart with a total spread of 200 degrees – just over a full semicircle.
With the positioning set, I applied gentle compression to each individual voice part to limit the dynamic range and then added a surround reverb to the master channel (i.e., after the parts have been mixed). I chose a cathedral reverb for a long duration and a large, swimmy effect.
The final recording was mastered for 5.1 surround but there’s also a stereo version for Internet compatibility.
As a bonus, I’ve also included Spem rendered for more traditional electronic synthesizers, with each of the eight choirs taking on a different synthesized sound.
Last but not least, I thought I’d render a recording of another of my favourite choral pieces, When to the temple Mary went by Johannes Eccard. It was written around the same time as Spem and also sound richer than the average choral motet because it is written for six parts rather than the more common four. I experimented with sounds but didn’t like either the choral or synth takes, so I decided to render it for string sextet. I think it works quite nicely, and if I can ever get my hands on a real string sextet then I will ask them to play it! |
Formal statement is: lemma (in t2_space) tendsto_unique: assumes "F \<noteq> bot" and "(f \<longlongrightarrow> a) F" and "(f \<longlongrightarrow> b) F" shows "a = b" Informal statement is: If $f$ converges to two different limits $a$ and $b$, then $a = b$. |
%compute dcentralheadang
function [data,units]=compute_dcentralheadang(trx,n)
larvae=trx.exp2flies{n};
numlarvae=numel(larvae);
%absdtailheadang=cell(1,numlarvae);
dcentralheadang=cell(1,numlarvae);
for i=1:numlarvae
larva=larvae(i);
% absdtailheadang{1,i}=real(acos(cos(tailheadang{1,i}(1:end-1)).*cos(tailheadang{1,i}(2:end))+sin(tailheadang{1,i}(1:end-1)).*sin(tailheadang{1,i}(2:end))))./trx(i).dt;
% temp=tailheadang{1,i}-pi/2;
% cosperp=sign(cos(temp(1:end-1)).*cos(tailheadang{1,i}(2:end))+sin(temp(1:end-1)).*sin(tailheadang{1,i}(2:end)));
% temp2=bsxfun(@times,absdtailheadang{1,i},cosperp);
dcentralheadang{1,i}=modrange(diff(trx(larva).centralheadang),-pi,pi)./trx(larva).dt;
% KB: this angle distance didn't make sense to me, changed to one that
% made sense to me
%dcentralheadang{1,i}=(mod1(trx(larva).centralheadang(2:end)-trx(larva).centralheadang(1:end-1),pi)-pi)./trx(larva).dt;
end
units=parseunits('rad/s');
data=dcentralheadang;
|
theory NatsBug
imports Main
"$HIPSTER_HOME/IsaHipster"
begin
datatype Nat = Z | S Nat
fun leq :: "Nat \<Rightarrow> Nat \<Rightarrow> bool" where
"leq Z _ = True"
| "leq _ Z = False"
| "leq (S x) (S y) = leq x y"
fun eqN :: "Nat \<Rightarrow> Nat \<Rightarrow> bool" where (* own definition for equality *)
"eqN Z Z = True"
| "eqN (S n) (S m) = eqN n m"
| "eqN _ _ = False"
(* less or equal to Z *)
fun lez :: "Nat \<Rightarrow> bool" where (* - as a function definition relying on Isabelle's equality *)
"lez x = (x = Z)"
fun lezP :: "Nat \<Rightarrow> bool" where (* - as a function definition via pattern matching *)
"lezP Z = True"
| "lezP _ = False"
fun lezzP :: "Nat \<Rightarrow> bool" where (* - as a function definition via our own equality *)
"lezzP x = eqN x Z"
definition leZ :: "Nat \<Rightarrow> bool" where (* - as a constant definition relying on Isabelle's equality *)
"leZ x \<equiv> (x = Z)"
definition leZZ :: "Nat \<Rightarrow> bool" where (* - as a constant definition relying on own equality *)
"leZZ x \<equiv> eqN x Z"
(* hipster_cond lezzP leq *) (* skipping of conditions in output solved *)
(* hipster_cond lezP leq *) (* skipping of conditions in output solved *)
(* hipster lezzP *) (* nothing weird, ok *)
(* hipster lezP *) (* everything trivial, ok*)
(* FIXME: 1. Isabelle's equality = (gets translated as a separate predicate Haskell
function equal_<Type> which will be missing in the original theory) *)
(* hipster lez *) (* equations only with lez are trivial, aren't returned *)
lemma unknown [thy_expl]: "equal_Nat x y = equal_Nat y x" (* free variable equal_Nat instead of equality = *)
oops
(** QUICK REFERENCE: Haskell transaltions **)
(* equal_Nat :: Nat -> Nat -> Bool
equal_Nat Z (S nat) = False
equal_Nat (S nat) Z = False
equal_Nat (S nata) (S nat) = equal_Nat nata nat
equal_Nat Z Z = True
leZ :: Nat -> Bool
leZ x = equal_Nat x Z
lez :: Nat -> Bool
lez x = equal_Nat x Z *)
(* eqN :: Nat -> Nat -> Bool
eqN Z Z = True
eqN (S n) (S m) = eqN n m
eqN (S v) Z = False
eqN Z (S v) = False
leZZ :: Nat -> Bool
leZZ x = eqN x Z
lezzP :: Nat -> Bool
lezzP x = eqN x Z
lezP :: Nat -> Bool
lezP Z = True
lezP (S v) = False *)
(* leq :: Nat -> Nat -> Bool
leq Z uu = True
leq (S v) Z = False
leq (S x) (S y) = leq x y *)
(* Notes to self *)
(* cond with: lezP leq*)
lemma dub00 [thy_expl]: "lezP y \<and> lezP x \<Longrightarrow> x = y" (* Hipster fails for some reason: no double induction? *)
apply(induction y, induction x)
by (simp_all)
(* Constant definition issues *)
(* leZ *)
lemma dub01 [thy_expl]: "leZ (S Z) = False" (* Hipster fails *)
(* Hipster does not get leZ_def, but it also fails when provided manually with it:
by (hipster_induct_simp_metis NatsBug.leZ_def) *)
by (simp add: leZ_def)
(* leZZ *)
lemma dub02 [thy_expl]: "eqN Z x = leZZ x" (* Hipster fails *)
apply (induction x)
by (simp_all add: leZZ_def)
end
|
# Thinking probabilistically - Continuous variables
> A Summary of lecture "Statistical Thinking in Python (Part 1)", via datacamp
- toc: true
- badges: true
- comments: true
- author: Chanseok Kang
- categories: [Python, Datacamp, Data_Science, Statistics]
- image: images/std-cdf.png
## Probability density functions
- Continuous variables
- Quantities that can take any value, not just discrete values
- Probability Density function (PDF)
- Continuous analog to the PMF
- Mathematical description of the relative likelihood of observing a value of a continuous variable
## Introduction to the Normal distribution
- Normal distribution
- Describes a continuous variable whose PDF has a single symmetric peak.
$$ \begin{align} \text{mean of a Normal distribution} & \neq \text{mean computed from data} \\ \text{st. dev of a Normal distribution} & \neq \text{st. dev computed from data} \end{align} $$
### The Normal PDF
In this exercise, you will explore the Normal PDF and also learn a way to plot a PDF of a known distribution using hacker statistics. Specifically, you will plot a Normal PDF for various values of the variance.
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
```
```python
# Draw 100000 samples from Normal distribution
# with stds of interest: samples_std1, samples_std3, stamples_std10
samples_std1 = np.random.normal(20, 1, 100000)
samples_std3 = np.random.normal(20, 3, 100000)
samples_std10 = np.random.normal(20, 10, 100000)
# Make histograms
_ = plt.hist(samples_std1, histtype='step', density=True, bins=100)
_ = plt.hist(samples_std3, histtype='step', density=True, bins=100)
_ = plt.hist(samples_std10, histtype='step', density=True,bins=100)
# Make a legend, set limits
_ = plt.legend(('std = 1', 'std = 3', 'std = 10'))
plt.ylim(-0.01, 0.42)
```
### The Normal CDF
Now that you have a feel for how the Normal PDF looks, let's consider its CDF. Using the samples you generated in the last exercise (in your namespace as ```samples_std1```, ```samples_std3```, and ```samples_std10```), generate and plot the CDFs.
```python
def ecdf(data):
"""Compute ECDF for a one-dimensional array of measurements."""
# Number of data points: n
n = len(data)
# x-data for the ECDF: x
x = np.sort(data)
# y-data for the ECDF: y
y = np.arange(1, n + 1) / n
return x, y
```
```python
# Generate CDFs
x_std1, y_std1 = ecdf(samples_std1)
x_std3, y_std3 = ecdf(samples_std3)
x_std10, y_std10 = ecdf(samples_std10)
# Plot CDFs
_ = plt.plot(x_std1, y_std1, marker='.', linestyle='none')
_ = plt.plot(x_std3, y_std3, marker='.', linestyle='none')
_ = plt.plot(x_std10, y_std10, marker='.', linestyle='none')
# Make a legend
_ = plt.legend(('std = 1', 'std = 3', 'std = 10'), loc='lower right')
plt.savefig('../images/std-cdf.png')
```
## The Normal distribution: Properties and warnings
### Are the Belmont Stakes results Normally distributed?
Since 1926, the Belmont Stakes is a 1.5 mile-long race of 3-year old thoroughbred horses. [Secretariat](https://en.wikipedia.org/wiki/Secretariat_(horse) ) ran the fastest Belmont Stakes in history in 1973. While that was the fastest year, 1970 was the slowest because of unusually wet and sloppy conditions. With these two outliers removed from the data set, compute the mean and standard deviation of the Belmont winners' times. Sample out of a Normal distribution with this mean and standard deviation using the ```np.random.normal()``` function and plot a CDF. Overlay the ECDF from the winning Belmont times. Are these close to Normally distributed?
Note: Justin scraped the data concerning the Belmont Stakes from the [Belmont Wikipedia page](https://en.wikipedia.org/wiki/Belmont_Stakes).
```python
df = pd.read_csv('./dataset/belmont.csv')
belmont_no_outliers = np.array([148.51, 146.65, 148.52, 150.7 , 150.42, 150.88, 151.57, 147.54,
149.65, 148.74, 147.86, 148.75, 147.5 , 148.26, 149.71, 146.56,
151.19, 147.88, 149.16, 148.82, 148.96, 152.02, 146.82, 149.97,
146.13, 148.1 , 147.2 , 146. , 146.4 , 148.2 , 149.8 , 147. ,
147.2 , 147.8 , 148.2 , 149. , 149.8 , 148.6 , 146.8 , 149.6 ,
149. , 148.2 , 149.2 , 148. , 150.4 , 148.8 , 147.2 , 148.8 ,
149.6 , 148.4 , 148.4 , 150.2 , 148.8 , 149.2 , 149.2 , 148.4 ,
150.2 , 146.6 , 149.8 , 149. , 150.8 , 148.6 , 150.2 , 149. ,
148.6 , 150.2 , 148.2 , 149.4 , 150.8 , 150.2 , 152.2 , 148.2 ,
149.2 , 151. , 149.6 , 149.6 , 149.4 , 148.6 , 150. , 150.6 ,
149.2 , 152.6 , 152.8 , 149.6 , 151.6 , 152.8 , 153.2 , 152.4 ,
152.2 ])
```
```python
# Compute mean and standard deviation: mu, sigma
mu = np.mean(belmont_no_outliers)
sigma = np.std(belmont_no_outliers)
# Sample out of a normal distribution with this mu and sigma: samples
samples = np.random.normal(mu, sigma, size=10000)
# Get the CDF of the samples and of the data
x_theor, y_theor = ecdf(belmont_no_outliers)
x, y = ecdf(samples)
# Plot the CDFs
_ = plt.plot(x_theor, y_theor)
_ = plt.plot(x, y, marker='.', linestyle='none')
_ = plt.xlabel('Belmont winning time (sec.)')
_ = plt.ylabel('CDF')
```
### What are the chances of a horse matching or beating Secretariat's record?
Assume that the Belmont winners' times are Normally distributed (with the 1970 and 1973 years removed), what is the probability that the winner of a given Belmont Stakes will run it as fast or faster than Secretariat?
```python
# Take a million samples out of the Normal distribution: samples
samples = np.random.normal(mu, sigma, size=1000000)
# Compute the fraction that are faster than 144 seconds: prob
prob = np.sum(samples < 144) / len(samples)
# Print the result
print('Probability of besting Secretariat:', prob)
```
Probability of besting Secretariat: 0.00057
## The Exponential distribution
- The waiting time between arrivals of a Poisson process is Exponentially distributed
### If you have a story, you can simulate it!
Sometimes, the story describing our probability distribution does not have a named distribution to go along with it. In these cases, fear not! You can always simulate it. We'll do that in this and the next exercise.
In earlier exercises, we looked at the rare event of no-hitters in Major League Baseball. Hitting the cycle is another rare baseball event. When a batter hits the cycle, he gets all four kinds of hits, a single, double, triple, and home run, in a single game. Like no-hitters, this can be modeled as a Poisson process, so the time between hits of the cycle are also Exponentially distributed.
How long must we wait to see both a no-hitter and then a batter hit the cycle? The idea is that we have to wait some time for the no-hitter, and then after the no-hitter, we have to wait for hitting the cycle. Stated another way, what is the total waiting time for the arrival of two different Poisson processes? The total waiting time is the time waited for the no-hitter, plus the time waited for the hitting the cycle.
Now, you will write a function to sample out of the distribution described by this story.
```python
def successive_poisson(tau1, tau2, size=1):
"""Compute time for arrival of 2 successive Poisson processes."""
# Draw samples out of first exponential distribution: t1
t1 = np.random.exponential(tau1, size)
# Draw samples out of second exponential distribution: t2
t2 = np.random.exponential(tau2, size)
return t1 + t2
```
### Distribution of no-hitters and cycles
Now, you'll use your sampling function to compute the waiting time to observe a no-hitter and hitting of the cycle. The mean waiting time for a no-hitter is 764 games, and the mean waiting time for hitting the cycle is 715 games.
```python
# Draw samples of waiting times: waiting_times
waiting_times = successive_poisson(764, 715, size=100000)
# Make the histogram
_ = plt.hist(waiting_times, bins=100, density=True, histtype='step')
# Label axes
_ = plt.xlabel('waiting times')
_ = plt.ylabel('PDF')
```
|
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
⊢ ∀ (p q : Bool), p ∆ q = xor p q
[PROOFSTEP]
decide
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ a ∆ b = b ∆ a
[PROOFSTEP]
simp only [symmDiff, sup_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ a ∆ a = ⊥
[PROOFSTEP]
rw [symmDiff, sup_idem, sdiff_self]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ a ∆ ⊥ = a
[PROOFSTEP]
rw [symmDiff, sdiff_bot, bot_sdiff, sup_bot_eq]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ ⊥ ∆ a = a
[PROOFSTEP]
rw [symmDiff_comm, symmDiff_bot]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a✝ b✝ c d a b : α
⊢ a ∆ b = ⊥ ↔ a = b
[PROOFSTEP]
simp_rw [symmDiff, sup_eq_bot_iff, sdiff_eq_bot_iff, le_antisymm_iff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a✝ b✝ c d a b : α
h : a ≤ b
⊢ a ∆ b = b \ a
[PROOFSTEP]
rw [symmDiff, sdiff_eq_bot_iff.2 h, bot_sup_eq]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a✝ b✝ c d a b : α
h : b ≤ a
⊢ a ∆ b = a \ b
[PROOFSTEP]
rw [symmDiff, sdiff_eq_bot_iff.2 h, sup_bot_eq]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a✝ b✝ c✝ d a b c : α
⊢ a ∆ b ≤ c ↔ a ≤ b ⊔ c ∧ b ≤ a ⊔ c
[PROOFSTEP]
simp_rw [symmDiff, sup_le_iff, sdiff_le_iff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ a ∆ b = (a ⊔ b) \ (a ⊓ b)
[PROOFSTEP]
simp [sup_sdiff, symmDiff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a✝ b✝ c d a b : α
h : Disjoint a b
⊢ a ∆ b = a ⊔ b
[PROOFSTEP]
rw [symmDiff, h.sdiff_eq_left, h.sdiff_eq_right]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ a ∆ b \ c = a \ (b ⊔ c) ⊔ b \ (a ⊔ c)
[PROOFSTEP]
rw [symmDiff, sup_sdiff_distrib, sdiff_sdiff_left, sdiff_sdiff_left]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ a ∆ b \ (a ⊓ b) = a ∆ b
[PROOFSTEP]
rw [symmDiff_sdiff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ a \ (b ⊔ a ⊓ b) ⊔ b \ (a ⊔ a ⊓ b) = a ∆ b
[PROOFSTEP]
simp [symmDiff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ a ∆ (b \ a) = a ⊔ b
[PROOFSTEP]
rw [symmDiff, sdiff_idem]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ a \ (b \ a) ⊔ b \ a = a ⊔ b
[PROOFSTEP]
exact
le_antisymm (sup_le_sup sdiff_le sdiff_le)
(sup_le le_sdiff_sup <| le_sdiff_sup.trans <| sup_le le_sup_right le_sdiff_sup)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ (a \ b) ∆ b = a ⊔ b
[PROOFSTEP]
rw [symmDiff_comm, symmDiff_sdiff_eq_sup, sup_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ a ∆ b ⊔ a ⊓ b = a ⊔ b
[PROOFSTEP]
refine' le_antisymm (sup_le symmDiff_le_sup inf_le_sup) _
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ a ⊔ b ≤ a ∆ b ⊔ a ⊓ b
[PROOFSTEP]
rw [sup_inf_left, symmDiff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ a ⊔ b ≤ (a \ b ⊔ b \ a ⊔ a) ⊓ (a \ b ⊔ b \ a ⊔ b)
[PROOFSTEP]
refine' sup_le (le_inf le_sup_right _) (le_inf _ le_sup_right)
[GOAL]
case refine'_1
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ a ≤ a \ b ⊔ b \ a ⊔ b
[PROOFSTEP]
rw [sup_right_comm]
[GOAL]
case refine'_1
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ a ≤ a \ b ⊔ b ⊔ b \ a
[PROOFSTEP]
exact le_sup_of_le_left le_sdiff_sup
[GOAL]
case refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ b ≤ a \ b ⊔ b \ a ⊔ a
[PROOFSTEP]
rw [sup_assoc]
[GOAL]
case refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ b ≤ a \ b ⊔ (b \ a ⊔ a)
[PROOFSTEP]
exact le_sup_of_le_right le_sdiff_sup
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ a ⊓ b ⊔ a ∆ b = a ⊔ b
[PROOFSTEP]
rw [sup_comm, symmDiff_sup_inf]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ a ∆ b ∆ (a ⊓ b) = a ⊔ b
[PROOFSTEP]
rw [← symmDiff_sdiff_inf a, sdiff_symmDiff_eq_sup, symmDiff_sup_inf]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ (a ⊓ b) ∆ (a ∆ b) = a ⊔ b
[PROOFSTEP]
rw [symmDiff_comm, symmDiff_symmDiff_inf]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ a ∆ c ≤ a ∆ b ⊔ b ∆ c
[PROOFSTEP]
refine' (sup_le_sup (sdiff_triangle a b c) <| sdiff_triangle _ b _).trans_eq _
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedCoheytingAlgebra α
a b c d : α
⊢ a \ b ⊔ b \ c ⊔ (c \ b ⊔ b \ a) = a ∆ b ⊔ b ∆ c
[PROOFSTEP]
rw [@sup_comm _ _ (c \ b), sup_sup_sup_comm, symmDiff, symmDiff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedHeytingAlgebra α
a b c d : α
⊢ a ⇔ b = b ⇔ a
[PROOFSTEP]
simp only [(· ⇔ ·), inf_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedHeytingAlgebra α
a b c d : α
⊢ a ⇔ a = ⊤
[PROOFSTEP]
rw [bihimp, inf_idem, himp_self]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedHeytingAlgebra α
a b c d : α
⊢ a ⇔ ⊤ = a
[PROOFSTEP]
rw [bihimp, himp_top, top_himp, inf_top_eq]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedHeytingAlgebra α
a b c d : α
⊢ ⊤ ⇔ a = a
[PROOFSTEP]
rw [bihimp_comm, bihimp_top]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedHeytingAlgebra α
a✝ b✝ c d a b : α
h : a ≤ b
⊢ a ⇔ b = b ⇨ a
[PROOFSTEP]
rw [bihimp, himp_eq_top_iff.2 h, inf_top_eq]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedHeytingAlgebra α
a✝ b✝ c d a b : α
h : b ≤ a
⊢ a ⇔ b = a ⇨ b
[PROOFSTEP]
rw [bihimp, himp_eq_top_iff.2 h, top_inf_eq]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedHeytingAlgebra α
a✝ b✝ c✝ d a b c : α
⊢ a ≤ b ⇔ c ↔ a ⊓ b ≤ c ∧ a ⊓ c ≤ b
[PROOFSTEP]
simp_rw [bihimp, le_inf_iff, le_himp_iff, and_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedHeytingAlgebra α
a b c d : α
⊢ a ⇔ b = a ⊔ b ⇨ a ⊓ b
[PROOFSTEP]
simp [himp_inf_distrib, bihimp]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedHeytingAlgebra α
a✝ b✝ c d a b : α
h : Codisjoint a b
⊢ a ⇔ b = a ⊓ b
[PROOFSTEP]
rw [bihimp, h.himp_eq_left, h.himp_eq_right]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedHeytingAlgebra α
a b c d : α
⊢ a ⇨ b ⇔ c = (a ⊓ c ⇨ b) ⊓ (a ⊓ b ⇨ c)
[PROOFSTEP]
rw [bihimp, himp_inf_distrib, himp_himp, himp_himp]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedHeytingAlgebra α
a b c d : α
⊢ a ⊔ b ⇨ a ⇔ b = a ⇔ b
[PROOFSTEP]
rw [himp_bihimp]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedHeytingAlgebra α
a b c d : α
⊢ ((a ⊔ b) ⊓ b ⇨ a) ⊓ ((a ⊔ b) ⊓ a ⇨ b) = a ⇔ b
[PROOFSTEP]
simp [bihimp]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : CoheytingAlgebra α
a : α
⊢ a ∆ ⊤ = ¬a
[PROOFSTEP]
simp [symmDiff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : CoheytingAlgebra α
a : α
⊢ ⊤ ∆ a = ¬a
[PROOFSTEP]
simp [symmDiff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : CoheytingAlgebra α
a : α
⊢ (¬a) ∆ a = ⊤
[PROOFSTEP]
rw [eq_top_iff, symmDiff, hnot_sdiff, sup_sdiff_self]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : CoheytingAlgebra α
a : α
⊢ ⊤ ≤ ¬a ⊔ a
[PROOFSTEP]
exact Codisjoint.top_le codisjoint_hnot_left
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : CoheytingAlgebra α
a : α
⊢ a ∆ (¬a) = ⊤
[PROOFSTEP]
rw [symmDiff_comm, hnot_symmDiff_self]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : CoheytingAlgebra α
a✝ a b : α
h : IsCompl a b
⊢ a ∆ b = ⊤
[PROOFSTEP]
rw [h.eq_hnot, hnot_symmDiff_self]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : HeytingAlgebra α
a : α
⊢ a ⇔ ⊥ = aᶜ
[PROOFSTEP]
simp [bihimp]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : HeytingAlgebra α
a : α
⊢ ⊥ ⇔ a = aᶜ
[PROOFSTEP]
simp [bihimp]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : HeytingAlgebra α
a✝ a b : α
h : IsCompl a b
⊢ a ⇔ b = ⊥
[PROOFSTEP]
rw [h.eq_compl, compl_bihimp_self]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ (a ⊔ b) \ (a ⊓ b) = a ∆ b
[PROOFSTEP]
rw [symmDiff_eq_sup_sdiff_inf]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ Disjoint (a ∆ b) (a ⊓ b)
[PROOFSTEP]
rw [symmDiff_eq_sup_sdiff_inf]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ Disjoint ((a ⊔ b) \ (a ⊓ b)) (a ⊓ b)
[PROOFSTEP]
exact disjoint_sdiff_self_left
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a ⊓ b ∆ c = (a ⊓ b) ∆ (a ⊓ c)
[PROOFSTEP]
rw [symmDiff_eq_sup_sdiff_inf, inf_sdiff_distrib_left, inf_sup_left, inf_inf_distrib_left, symmDiff_eq_sup_sdiff_inf]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a ∆ b ⊓ c = (a ⊓ c) ∆ (b ⊓ c)
[PROOFSTEP]
simp_rw [@inf_comm _ _ _ c, inf_symmDiff_distrib_left]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ c \ a ∆ b = c ⊓ a ⊓ b ⊔ c \ a ⊓ c \ b
[PROOFSTEP]
simp only [(· ∆ ·), sdiff_sdiff_sup_sdiff']
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ c \ a ∆ b = c ⊓ a ⊓ b ⊔ c \ (a ⊔ b)
[PROOFSTEP]
rw [sdiff_symmDiff, sdiff_sup, sup_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a ∆ b \ a = b \ a
[PROOFSTEP]
rw [symmDiff_def, sup_sdiff, sdiff_idem, sdiff_sdiff_self, bot_sup_eq]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a ∆ b \ b = a \ b
[PROOFSTEP]
rw [symmDiff_comm, symmDiff_sdiff_left]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a \ a ∆ b = a ⊓ b
[PROOFSTEP]
simp [sdiff_symmDiff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ b \ a ∆ b = a ⊓ b
[PROOFSTEP]
rw [symmDiff_comm, inf_comm, sdiff_symmDiff_left]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a ∆ b = a ⊔ b ↔ Disjoint a b
[PROOFSTEP]
refine' ⟨fun h => _, Disjoint.symmDiff_eq_sup⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
h : a ∆ b = a ⊔ b
⊢ Disjoint a b
[PROOFSTEP]
rw [symmDiff_eq_sup_sdiff_inf, sdiff_eq_self_iff_disjoint] at h
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
h : Disjoint (a ⊓ b) (a ⊔ b)
⊢ Disjoint a b
[PROOFSTEP]
exact h.of_disjoint_inf_of_le le_sup_left
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a ≤ a ∆ b ↔ Disjoint a b
[PROOFSTEP]
refine' ⟨fun h => _, fun h => h.symmDiff_eq_sup.symm ▸ le_sup_left⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
h : a ≤ a ∆ b
⊢ Disjoint a b
[PROOFSTEP]
rw [symmDiff_eq_sup_sdiff_inf] at h
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
h : a ≤ (a ⊔ b) \ (a ⊓ b)
⊢ Disjoint a b
[PROOFSTEP]
exact disjoint_iff_inf_le.mpr (le_sdiff_iff.1 <| inf_le_of_left_le h).le
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ b ≤ a ∆ b ↔ Disjoint a b
[PROOFSTEP]
rw [symmDiff_comm, le_symmDiff_iff_left, disjoint_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a ∆ b \ c ⊔ c \ a ∆ b = a \ (b ⊔ c) ⊔ b \ (a ⊔ c) ⊔ (c \ (a ⊔ b) ⊔ c ⊓ a ⊓ b)
[PROOFSTEP]
{rw [sdiff_symmDiff', @sup_comm _ _ (c ⊓ a ⊓ b), symmDiff_sdiff]
}
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a ∆ b \ c ⊔ c \ a ∆ b = a \ (b ⊔ c) ⊔ b \ (a ⊔ c) ⊔ (c \ (a ⊔ b) ⊔ c ⊓ a ⊓ b)
[PROOFSTEP]
rw [sdiff_symmDiff', @sup_comm _ _ (c ⊓ a ⊓ b), symmDiff_sdiff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a \ (b ⊔ c) ⊔ b \ (a ⊔ c) ⊔ (c \ (a ⊔ b) ⊔ c ⊓ a ⊓ b) = a \ (b ⊔ c) ⊔ b \ (a ⊔ c) ⊔ c \ (a ⊔ b) ⊔ a ⊓ b ⊓ c
[PROOFSTEP]
ac_rfl
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a \ b ∆ c ⊔ b ∆ c \ a = a \ (b ⊔ c) ⊔ a ⊓ b ⊓ c ⊔ (b \ (c ⊔ a) ⊔ c \ (b ⊔ a))
[PROOFSTEP]
{rw [sdiff_symmDiff', @sup_comm _ _ (a ⊓ b ⊓ c), symmDiff_sdiff]
}
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a \ b ∆ c ⊔ b ∆ c \ a = a \ (b ⊔ c) ⊔ a ⊓ b ⊓ c ⊔ (b \ (c ⊔ a) ⊔ c \ (b ⊔ a))
[PROOFSTEP]
rw [sdiff_symmDiff', @sup_comm _ _ (a ⊓ b ⊓ c), symmDiff_sdiff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a \ (b ⊔ c) ⊔ a ⊓ b ⊓ c ⊔ (b \ (c ⊔ a) ⊔ c \ (b ⊔ a)) = a \ (b ⊔ c) ⊔ b \ (a ⊔ c) ⊔ c \ (a ⊔ b) ⊔ a ⊓ b ⊓ c
[PROOFSTEP]
ac_rfl
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a ∆ b ∆ c = a ∆ (b ∆ c)
[PROOFSTEP]
rw [symmDiff_symmDiff_left, symmDiff_symmDiff_right]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a ∆ (b ∆ c) = b ∆ (a ∆ c)
[PROOFSTEP]
simp_rw [← symmDiff_assoc, symmDiff_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a ∆ b ∆ c = a ∆ c ∆ b
[PROOFSTEP]
simp_rw [symmDiff_assoc, symmDiff_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a ∆ b ∆ (c ∆ d) = a ∆ c ∆ (b ∆ d)
[PROOFSTEP]
simp_rw [symmDiff_assoc, symmDiff_left_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a ∆ (a ∆ b) = b
[PROOFSTEP]
simp [← symmDiff_assoc]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ b ∆ a ∆ a = b
[PROOFSTEP]
simp [symmDiff_assoc]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a ∆ b ∆ a = b
[PROOFSTEP]
rw [symmDiff_comm, symmDiff_symmDiff_cancel_left]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a ∆ b = a ↔ a ∆ b = a ∆ ⊥
[PROOFSTEP]
rw [symmDiff_bot]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a ∆ b = a ∆ ⊥ ↔ b = ⊥
[PROOFSTEP]
rw [symmDiff_right_inj]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
⊢ a ∆ b = b ↔ a = ⊥
[PROOFSTEP]
rw [symmDiff_comm, symmDiff_eq_left]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
ha : Disjoint a c
hb : Disjoint b c
⊢ Disjoint (a ∆ b) c
[PROOFSTEP]
rw [symmDiff_eq_sup_sdiff_inf]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
ha : Disjoint a c
hb : Disjoint b c
⊢ Disjoint ((a ⊔ b) \ (a ⊓ b)) c
[PROOFSTEP]
exact (ha.sup_left hb).disjoint_sdiff_left
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
ha : a ≤ c
⊢ a ∆ b = c ↔ c \ a = b
[PROOFSTEP]
rw [← symmDiff_of_le ha]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : GeneralizedBooleanAlgebra α
a b c d : α
ha : a ≤ c
⊢ a ∆ b = c ↔ a ∆ c = b
[PROOFSTEP]
exact ((symmDiff_right_involutive a).toPerm _).apply_eq_iff_eq_symm_apply.trans eq_comm
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ a ⇔ (b ⇔ c) = b ⇔ (a ⇔ c)
[PROOFSTEP]
simp_rw [← bihimp_assoc, bihimp_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ a ⇔ b ⇔ c = a ⇔ c ⇔ b
[PROOFSTEP]
simp_rw [bihimp_assoc, bihimp_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ a ⇔ b ⇔ (c ⇔ d) = a ⇔ c ⇔ (b ⇔ d)
[PROOFSTEP]
simp_rw [bihimp_assoc, bihimp_left_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ a ⇔ (a ⇔ b) = b
[PROOFSTEP]
simp [← bihimp_assoc]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ b ⇔ a ⇔ a = b
[PROOFSTEP]
simp [bihimp_assoc]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ a ⇔ b ⇔ a = b
[PROOFSTEP]
rw [bihimp_comm, bihimp_bihimp_cancel_left]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ a ∆ b = a ⊓ bᶜ ⊔ b ⊓ aᶜ
[PROOFSTEP]
simp only [(· ∆ ·), sdiff_eq]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ a ⇔ b = (a ⊔ bᶜ) ⊓ (b ⊔ aᶜ)
[PROOFSTEP]
simp only [(· ⇔ ·), himp_eq]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ a ∆ b = (a ⊔ b) ⊓ (aᶜ ⊔ bᶜ)
[PROOFSTEP]
rw [symmDiff_eq_sup_sdiff_inf, sdiff_eq, compl_inf]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ (a ∆ b)ᶜ = a ⇔ b
[PROOFSTEP]
simp_rw [symmDiff, compl_sup_distrib, compl_sdiff, bihimp, inf_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ bᶜ \ aᶜ ⊔ aᶜ \ bᶜ = a ∆ b
[PROOFSTEP]
simp_rw [compl_sdiff_compl, sdiff_eq, symmDiff_eq]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ a ∆ b = ⊤ ↔ IsCompl a b
[PROOFSTEP]
rw [symmDiff_eq', ← compl_inf, inf_eq_top_iff, compl_eq_top, isCompl_iff, disjoint_iff, codisjoint_iff, and_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ a ⇔ b = ⊥ ↔ IsCompl a b
[PROOFSTEP]
rw [bihimp_eq', ← compl_sup, sup_eq_bot_iff, compl_eq_bot, isCompl_iff, disjoint_iff, codisjoint_iff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ a ∆ (b ∆ c) = a ⊓ (b ⊓ c ⊔ bᶜ ⊓ cᶜ) ⊔ (b ⊓ cᶜ ⊔ c ⊓ bᶜ) ⊓ aᶜ
[PROOFSTEP]
{rw [symmDiff_eq, compl_symmDiff, bihimp_eq', symmDiff_eq]
}
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ a ∆ (b ∆ c) = a ⊓ (b ⊓ c ⊔ bᶜ ⊓ cᶜ) ⊔ (b ⊓ cᶜ ⊔ c ⊓ bᶜ) ⊓ aᶜ
[PROOFSTEP]
rw [symmDiff_eq, compl_symmDiff, bihimp_eq', symmDiff_eq]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ a ⊓ (b ⊓ c ⊔ bᶜ ⊓ cᶜ) ⊔ (b ⊓ cᶜ ⊔ c ⊓ bᶜ) ⊓ aᶜ = a ⊓ b ⊓ c ⊔ a ⊓ bᶜ ⊓ cᶜ ⊔ b ⊓ cᶜ ⊓ aᶜ ⊔ c ⊓ bᶜ ⊓ aᶜ
[PROOFSTEP]
{rw [inf_sup_left, inf_sup_right, ← sup_assoc, ← inf_assoc, ← inf_assoc]
}
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ a ⊓ (b ⊓ c ⊔ bᶜ ⊓ cᶜ) ⊔ (b ⊓ cᶜ ⊔ c ⊓ bᶜ) ⊓ aᶜ = a ⊓ b ⊓ c ⊔ a ⊓ bᶜ ⊓ cᶜ ⊔ b ⊓ cᶜ ⊓ aᶜ ⊔ c ⊓ bᶜ ⊓ aᶜ
[PROOFSTEP]
rw [inf_sup_left, inf_sup_right, ← sup_assoc, ← inf_assoc, ← inf_assoc]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ a ⊓ b ⊓ c ⊔ a ⊓ bᶜ ⊓ cᶜ ⊔ b ⊓ cᶜ ⊓ aᶜ ⊔ c ⊓ bᶜ ⊓ aᶜ = a ⊓ b ⊓ c ⊔ a ⊓ bᶜ ⊓ cᶜ ⊔ aᶜ ⊓ b ⊓ cᶜ ⊔ aᶜ ⊓ bᶜ ⊓ c
[PROOFSTEP]
congr 1
[GOAL]
case e_a
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ a ⊓ b ⊓ c ⊔ a ⊓ bᶜ ⊓ cᶜ ⊔ b ⊓ cᶜ ⊓ aᶜ = a ⊓ b ⊓ c ⊔ a ⊓ bᶜ ⊓ cᶜ ⊔ aᶜ ⊓ b ⊓ cᶜ
[PROOFSTEP]
congr 1
[GOAL]
case e_a.e_a
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ b ⊓ cᶜ ⊓ aᶜ = aᶜ ⊓ b ⊓ cᶜ
[PROOFSTEP]
rw [inf_comm, inf_assoc]
[GOAL]
case e_a
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
⊢ c ⊓ bᶜ ⊓ aᶜ = aᶜ ⊓ bᶜ ⊓ c
[PROOFSTEP]
apply inf_left_right_swap
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
h : Disjoint a b
⊢ c ≤ a ∆ c ⊔ b ∆ c
[PROOFSTEP]
trans c \ (a ⊓ b)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
h : Disjoint a b
⊢ c ≤ c \ (a ⊓ b)
[PROOFSTEP]
rw [h.eq_bot, sdiff_bot]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
h : Disjoint a b
⊢ c \ (a ⊓ b) ≤ a ∆ c ⊔ b ∆ c
[PROOFSTEP]
rw [sdiff_inf]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
h : Disjoint a b
⊢ c \ a ⊔ c \ b ≤ a ∆ c ⊔ b ∆ c
[PROOFSTEP]
exact sup_le_sup le_sup_right le_sup_right
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
h : Disjoint b c
⊢ a ≤ a ∆ b ⊔ a ∆ c
[PROOFSTEP]
simp_rw [symmDiff_comm a]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
π : ι → Type u_4
inst✝ : BooleanAlgebra α
a b c d : α
h : Disjoint b c
⊢ a ≤ b ∆ a ⊔ c ∆ a
[PROOFSTEP]
exact h.le_symmDiff_sup_symmDiff_left
|
theory Binary_Sum_Measure
imports Probability
begin
definition sum_measure (infixr "\<Oplus>\<^sub>M" 70) where
"A \<Oplus>\<^sub>M B = measure_of (space A <+> space B)
({Inl`X |X. X \<in> sets A} \<union> {Inr`X |X. X \<in> sets B})
(\<lambda>X. emeasure A (Inl -` X) + emeasure B (Inr -` X))"
lemma sum_measure_closed:
"{Inl`X |X. X \<in> sets A} \<union> {Inr`X |X. X \<in> sets B} \<subseteq> Pow (space A <+> space B)"
using sets.space_closed[of A] sets.space_closed[of B] by (auto intro!: imageI)
lemma space_sum_measure: "space (A \<Oplus>\<^sub>M B) = space A <+> space B"
unfolding sum_measure_def by (rule space_measure_of[OF sum_measure_closed])
lemma Inl_vimage_Inr [simp]: "Inl -` Inr ` X = {}"
and Inr_vimage_Inl [simp]: "Inr -` Inl ` Y = {}"
by auto
lemma sets_sum_measure:
"sets (sum_measure A B) = {Inl`X \<union> Inr`Y |X Y. X \<in> sets A \<and> Y \<in> sets B}"
proof-
let ?\<Omega> = "space A <+> space B"
let ?M = "{Inl`X |X. X \<in> sets A} \<union> {Inr`X |X. X \<in> sets B}"
let ?M' = "{Inl`X \<union> Inr`Y |X Y. X \<in> sets A \<and> Y \<in> sets B}"
have "sets (sum_measure A B) = sigma_sets ?\<Omega> ?M"
unfolding sum_measure_def using sum_measure_closed by (rule sets_measure_of)
also have "... = ?M'"
proof (intro equalityI subsetI)
fix X assume "X \<in> ?M'"
then obtain X1 X2 where X: "X = Inl`X1 \<union> Inr`X2" and "X1 \<in> sets A" "X2 \<in> sets B" by auto
hence X12: "Inl`X1 \<in> ?M" "Inr`X2 \<in> ?M" by blast+
thus "X \<in> sigma_sets ?\<Omega> ?M"
by (subst X) (intro sigma_sets_Un[OF sigma_sets.Basic sigma_sets.Basic] X12)
next
fix X assume X: "X \<in> sigma_sets ?\<Omega> ?M"
show "X \<in> ?M'"
proof (induction rule: sigma_sets.induct[OF X])
fix X assume "X \<in> ?M"
thus "X \<in> ?M'" by blast
next
show "{} \<in> ?M'" by blast
next
fix X assume X: "X \<in> ?M'"
then obtain X1 X2 where X: "X = Inl`X1 \<union> Inr`X2" and "X1 \<in> sets A" "X2 \<in> sets B" by auto
hence "Inl`(space A - X1) \<union> Inr`(space B - X2) \<in> ?M'" by auto
also have "Inl`(space A - X1) \<union> Inr`(space B - X2) = ?\<Omega> - X" by (subst X) blast
finally show "?\<Omega> - X \<in> ?M'" .
next
fix X :: "nat \<Rightarrow> _"
assume X: "\<And>i. X i \<in> ?M'"
def X1 \<equiv> "\<lambda>i. Inl -` X i" and X2 \<equiv> "\<lambda>i. Inr -` X i"
from X have X_decomp: "\<And>i. X i = Inl`X1 i \<union> Inr`X2 i"
unfolding X1_def X2_def using UNIV_sum by auto
hence "(\<Union>i. X i) = Inl`(\<Union>i. X1 i) \<union> Inr`(\<Union>i. X2 i)" by auto
moreover {
fix i
from X[of i] have "X1 i \<in> sets A" "X2 i \<in> sets B" unfolding X1_def X2_def
by (force simp: inj_vimage_image_eq)+
}
hence "(\<Union>i. X1 i) \<in> sets A" "(\<Union>i. X2 i) \<in> sets B" using sets.countable_UN by blast+
ultimately show "(\<Union>i. X i) \<in> ?M'" by blast
qed
qed
finally show ?thesis .
qed
lemma sets_sum_measure_cong [measurable_cong, cong]:
"sets M1 = sets M1' \<Longrightarrow> sets M2 = sets M2' \<Longrightarrow> sets (M1 \<Oplus>\<^sub>M M2) = sets (M1' \<Oplus>\<^sub>M M2')"
unfolding sets_sum_measure by (simp cong: sets_eq_imp_space_eq)
lemma sum_measureI1 [intro, simp, measurable]: "x \<in> sets A \<Longrightarrow> Inl`x \<in> sets (A \<Oplus>\<^sub>M B)"
and sum_measureI2 [intro, simp, measurable]: "x \<in> sets D \<Longrightarrow> Inr`x \<in> sets (C \<Oplus>\<^sub>M D)"
by (auto simp: sets_sum_measure)
lemma sum_measureE:
assumes "x \<in> sets (A \<Oplus>\<^sub>M B)"
obtains x1 x2 where "x = Inl`x1 \<union> Inr`x2"
using assms by (subst (asm) sets_sum_measure) blast
lemma measurable_sum_measureI1:
assumes 1: "f \<in> (space M1 <+> space M2) \<rightarrow> space M"
assumes 2: "\<And>X. X \<in> sets M \<Longrightarrow> Inl -` f -` X \<inter> space M1 \<in> sets M1"
assumes 3: "\<And>X. X \<in> sets M \<Longrightarrow> Inr -` f -` X \<inter> space M2 \<in> sets M2"
shows "f \<in> measurable (M1 \<Oplus>\<^sub>M M2) M"
proof (rule measurableI)
fix x assume "x \<in> space (M1 \<Oplus>\<^sub>M M2)"
with 1 show "f x \<in> space M" by (simp add: space_sum_measure Pi_iff)
next
fix X assume X: "X \<in> sets M"
have "f -` X = Inl`Inl-`f-`X \<union> Inr`Inr-`f-`X"
by (subst (1 2) image_vimage_eq, subst Int_Un_distrib[symmetric], subst UNIV_sum[symmetric]) simp
hence "f -` X \<inter> space (M1 \<Oplus>\<^sub>M M2) = Inl`(Inl-`f-`X \<inter> space M1) \<union> Inr`(Inr-`f-`X \<inter> space M2)"
by (auto simp: space_sum_measure)
with 2[OF X] 3[OF X] show "f -` X \<inter> space (M1 \<Oplus>\<^sub>M M2) \<in> sets (M1 \<Oplus>\<^sub>M M2)"
by (subst sets_sum_measure) blast
qed
lemma measurable_sum_measureI2:
fixes M1 :: "'a measure" and M2 :: "'b measure"
assumes 1: "f \<in> space M \<rightarrow> space M1 <+> space M2"
assumes 2: "\<And>X. X \<in> sets M1 \<Longrightarrow> f -` Inl ` X \<inter> space M \<in> sets M"
assumes 3: "\<And>X. X \<in> sets M2 \<Longrightarrow> f -` Inr ` X \<inter> space M \<in> sets M"
shows "f \<in> measurable M (M1 \<Oplus>\<^sub>M M2)"
unfolding sum_measure_def
proof (rule measurable_measure_of)
show "{Inl ` X |X. X \<in> sets M1} \<union> {Inr ` X |X. X \<in> sets M2} \<subseteq> Pow (space M1 <+> space M2)"
by (fact sum_measure_closed)
show "f \<in> space M \<rightarrow> space M1 <+> space M2" by fact
fix X assume "X \<in> {Inl ` X |X. X \<in> sets M1} \<union> {Inr ` X |X. X \<in> sets M2}"
thus "f -` X \<inter> space M \<in> sets M" using 2 3 by blast
qed
lemma measurable_Inl [measurable]: "Inl \<in> measurable M1 (M1 \<Oplus>\<^sub>M M2)"
by (rule measurable_sum_measureI2) (auto simp: vimage_image_eq)
lemma measurable_Inr [measurable]: "Inr \<in> measurable M2 (M1 \<Oplus>\<^sub>M M2)"
by (rule measurable_sum_measureI2) (auto simp: vimage_image_eq)
lemma measurable_case_sum [measurable (raw)]:
"f \<in> measurable M1 M \<Longrightarrow> g \<in> measurable M2 M \<Longrightarrow> case_sum f g \<in> measurable (M1 \<Oplus>\<^sub>M M2) M"
by (intro measurable_sum_measureI1) (auto dest: measurable_space simp: vimage_comp comp_def)
lemma measurable_sum:
assumes "f \<circ> Inl \<in> measurable M1 M" "f \<circ> Inr \<in> measurable M2 M"
shows "f \<in> measurable (M1 \<Oplus>\<^sub>M M2) M"
proof (rule measurable_sum_measureI1)
from assms show "f \<in> space M1 <+> space M2 \<rightarrow> space M"
by (auto simp: comp_def[abs_def] dest: measurable_space )
fix X assume X: "X \<in> sets M"
from X and assms show "Inl -` f -` X \<inter> space M1 \<in> sets M1"
and "Inr -` f -` X \<inter> space M2 \<in> sets M2" by (auto simp: vimage_comp)
qed
lemma emeasure_sum_measure:
assumes "A \<in> sets (M1 \<Oplus>\<^sub>M M2)"
shows "emeasure (M1 \<Oplus>\<^sub>M M2) A = emeasure M1 (Inl -` A) + emeasure M2 (Inr -` A)"
proof (rule emeasure_measure_of[OF sum_measure_def sum_measure_closed])
show "A \<in> sets (M1 \<Oplus>\<^sub>M M2)" by fact
show "positive (sets (M1 \<Oplus>\<^sub>M M2)) (\<lambda>X. emeasure M1 (Inl -` X) + emeasure M2 (Inr -` X))"
by (auto simp: sets_sum_measure positive_def intro!: ereal_add_nonneg_nonneg)
show "countably_additive (sets (M1 \<Oplus>\<^sub>M M2)) (\<lambda>X. emeasure M1 (Inl -` X) + emeasure M2 (Inr -` X))"
proof (rule countably_additiveI)
fix X :: "nat \<Rightarrow> _"
assume range_X: "range X \<subseteq> sets (M1 \<Oplus>\<^sub>M M2)"
assume disj_X: "disjoint_family X"
def X1 \<equiv> "\<lambda>i. Inl -` X i" and X2 \<equiv> "\<lambda>i. Inr -` X i"
{
fix i
from range_X have "X i \<in> sets (M1 \<Oplus>\<^sub>M M2)" by blast
hence "X1 i \<in> sets M1" "X2 i \<in> sets M2" unfolding X1_def X2_def
by (force simp: inj_vimage_image_eq sets_sum_measure)+
}
hence range_X12: "range X1 \<subseteq> sets M1" "range X2 \<subseteq> sets M2" by blast+
from disj_X have disj_X12: "disjoint_family X1" "disjoint_family X2"
by (auto simp: X1_def X2_def disjoint_family_on_def)
have "(\<Sum>i. emeasure M1 (Inl -` X i) + emeasure M2 (Inr -` X i)) =
(\<Sum>i. emeasure M1 (X1 i)) + (\<Sum>i. emeasure M2 (X2 i))"
unfolding X1_def X2_def by (intro suminf_add_ereal emeasure_nonneg)
also have "(\<Sum>i. emeasure M1 (X1 i)) = emeasure M1 (\<Union>i. X1 i)"
using range_X12(1) disj_X12(1) by (rule suminf_emeasure)
also have "(\<Sum>i. emeasure M2 (X2 i)) = emeasure M2 (\<Union>i. X2 i)"
using range_X12(2) disj_X12(2) by (rule suminf_emeasure)
also have "(\<Union>i. X1 i) = Inl -` (\<Union>i. X i)" by (auto simp: X1_def)
also have "(\<Union>i. X2 i) = Inr -` (\<Union>i. X i)" by (auto simp: X2_def)
finally show "(\<Sum>i. emeasure M1 (Inl -` X i) + emeasure M2 (Inr -` X i)) =
emeasure M1 (Inl -` (\<Union>i. X i)) + emeasure M2 (Inr -` (\<Union>i. X i))" .
qed
qed
lemma emeasure_sum_Inl: "A \<in> sets M1 \<Longrightarrow> emeasure (M1 \<Oplus>\<^sub>M M2) (Inl ` A) = emeasure M1 A"
by (subst emeasure_sum_measure) (auto simp: vimage_image_eq)
lemma emeasure_sum_Inr: "A \<in> sets M2 \<Longrightarrow> emeasure (M1 \<Oplus>\<^sub>M M2) (Inr ` A) = emeasure M2 A"
by (subst emeasure_sum_measure) (auto simp: vimage_image_eq)
locale sum_sigma_finite = M1: sigma_finite_measure M1 + M2: sigma_finite_measure M2
for M1 :: "'a measure" and M2 :: "'b measure"
sublocale sum_sigma_finite \<subseteq> P: sigma_finite_measure "M1 \<Oplus>\<^sub>M M2"
proof-
from M1.sigma_finite_countable guess A by (elim exE conjE)
note A = this
from M2.sigma_finite_countable guess B by (elim exE conjE)
note B = this
def AB \<equiv> "(\<lambda>X. Inl`X) ` A \<union> (\<lambda>X. Inr`X) ` B"
show "sigma_finite_measure (M1 \<Oplus>\<^sub>M M2)"
proof (unfold_locales, rule exI[of _ AB], intro conjI ballI)
from A(1) B(1) show "countable AB" by (simp add: AB_def)
from A(2) B(2) show "AB \<subseteq> sets (M1 \<Oplus>\<^sub>M M2)"
by (auto simp: AB_def intro!: sum_measureI1)
show "\<Union>AB = space (M1 \<Oplus>\<^sub>M M2)"
proof (intro equalityI subsetI)
fix x assume "x \<in> \<Union>AB"
with A(2-3) B(2-3) show "x \<in> space (M1 \<Oplus>\<^sub>M M2)" unfolding AB_def
by (cases x) (auto simp: space_sum_measure)
next
fix x assume "x \<in> space (M1 \<Oplus>\<^sub>M M2)"
with A(3) B(3) show "x \<in> \<Union>AB"
unfolding AB_def by (cases x) (auto simp: space_sum_measure inj_image_mem_iff)
qed
fix X assume "X \<in> AB"
moreover with `AB \<subseteq> sets (M1 \<Oplus>\<^sub>M M2)` have "X \<in> sets (M1 \<Oplus>\<^sub>M M2)" by blast
moreover note A(4) B(4)
ultimately show "emeasure (M1 \<Oplus>\<^sub>M M2) X \<noteq> \<infinity>"
unfolding AB_def by (fastforce simp: emeasure_sum_measure vimage_image_eq)
qed
qed
lemma sigma_finite_sum_measure:
assumes A: "sigma_finite_measure A" and B: "sigma_finite_measure B"
shows "sigma_finite_measure (A \<Oplus>\<^sub>M B)"
proof -
interpret A: sigma_finite_measure A by fact
interpret B: sigma_finite_measure B by fact
interpret AB: sum_sigma_finite A B ..
show ?thesis ..
qed
lemma AE_sum:
"(AE x in (M1 \<Oplus>\<^sub>M M2). P x) \<longleftrightarrow> (AE x in M1. P (Inl x)) \<and> (AE x in M2. P (Inr x))" (is "?Q = ?R")
proof
assume ?Q
then guess X by (rule AE_E)
note X = this
from X(1) have "{x \<in> space M1. \<not>P (Inl x)} \<subseteq> Inl -` X"
and "{x \<in> space M2. \<not>P (Inr x)} \<subseteq> Inr -` X"
by (auto simp: space_sum_measure)
moreover from X have "emeasure M1 (Inl -` X) + emeasure M2 (Inr -` X) = 0"
by (auto simp: emeasure_sum_measure)
hence "emeasure M1 (Inl -` X) = 0 \<and> emeasure M2 (Inr -` X) = 0"
by (subst (asm) ereal_add_nonneg_eq_0_iff) (simp_all add: emeasure_nonneg)
moreover from X have "Inl -` X \<in> sets M1" "Inr -` X \<in> sets M2"
by (fastforce simp: sets_sum_measure vimage_image_eq)+
ultimately show "(AE x in M1. P (Inl x)) \<and> (AE x in M2. P (Inr x))"
by (intro conjI AE_I) simp_all
next
assume ?R
hence R1: "AE x in M1. P (Inl x)" and R2: "AE x in M2. P (Inr x)" by blast+
from R1 guess X by (elim AE_E)
note X = this
from R2 guess Y by (elim AE_E)
note Y = this
from X Y have "{x \<in> space (M1 \<Oplus>\<^sub>M M2). \<not>P x} \<subseteq> Inl`X \<union> Inr`Y"
by (auto simp: space_sum_measure)
moreover from X Y have "emeasure (M1 \<Oplus>\<^sub>M M2) (Inl`X \<union> Inr`Y) = 0"
by (subst plus_emeasure[symmetric]) (auto simp: emeasure_sum_Inl emeasure_sum_Inr)
moreover from X Y have "Inl`X \<union> Inr`Y \<in> sets (M1 \<Oplus>\<^sub>M M2)" by simp
ultimately show ?Q by (rule AE_I)
qed
lemma AE_sumI:
"AE x in M1. P (Inl x) \<Longrightarrow> AE x in M2. P (Inr x) \<Longrightarrow> AE x in (M1 \<Oplus>\<^sub>M M2). P x"
by (simp add: AE_sum)
lemma AE_sumD1: "AE x in (M1 \<Oplus>\<^sub>M M2). P x \<Longrightarrow> AE x in M1. P (Inl x)"
and AE_sumD2: "AE x in (M1 \<Oplus>\<^sub>M M2). P x \<Longrightarrow> AE x in M2. P (Inr x)"
by (simp_all add: AE_sum)
end
|
from dataclasses import dataclass, field
from functools import cached_property
from pathlib import Path
from typing import Any, cast
import numpy
import soundfile
import soxr
AudioArray = numpy.ndarray[Any, numpy.dtype[Any]]
def read_file(path: Path, sample_rate: int) -> AudioArray:
"""Read audio file and convert to required sample rate."""
data, in_rate = cast(
tuple[AudioArray, int],
soundfile.read(path), # pyright: ignore[reportUnknownMemberType]
)
if in_rate == sample_rate:
return data
return cast(
AudioArray,
soxr.resample( # pyright: ignore[reportUnknownMemberType]
data, in_rate, sample_rate
),
)
@dataclass
class AudioFile:
path: Path
sample_rate: int = field(repr=False)
@cached_property
def data(self) -> AudioArray:
return read_file(self.path, self.sample_rate)
|
705 Grimes Other Need Riders! Heading for Glacier Nat'l Park in Montana and Grand Coulee area in Washington during Au more... 875.
701 Boyajian Other Join in a great supported bike ride along the coast of C.A.Fundraiser ride benefiting the constructi more... depends on how long you ride. |
/-
Copyright (c) 2022 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import model_theory.satisfiability
import combinatorics.simple_graph.basic
/-!
# First-Ordered Structures in Graph Theory
This file defines first-order languages, structures, and theories in graph theory.
## Main Definitions
* `first_order.language.graph` is the language consisting of a single relation representing
adjacency.
* `simple_graph.Structure` is the first-order structure corresponding to a given simple graph.
* `first_order.language.Theory.simple_graph` is the theory of simple graphs.
* `first_order.language.simple_graph_of_structure` gives the simple graph corresponding to a model
of the theory of simple graphs.
-/
universes u v w w'
namespace first_order
namespace language
open_locale first_order
open Structure
variables {L : language.{u v}} {α : Type w} {V : Type w'} {n : ℕ}
/-! ### Simple Graphs -/
/-- The language consisting of a single relation representing adjacency. -/
protected def graph : language :=
language.mk₂ empty empty empty empty unit
/-- The symbol representing the adjacency relation. -/
def adj : language.graph.relations 2 := unit.star
/-- Any simple graph can be thought of as a structure in the language of graphs. -/
def _root_.simple_graph.Structure (G : simple_graph V) :
language.graph.Structure V :=
Structure.mk₂ empty.elim empty.elim empty.elim empty.elim (λ _, G.adj)
namespace graph
instance : is_relational (language.graph) := language.is_relational_mk₂
instance : subsingleton (language.graph.relations n) :=
language.subsingleton_mk₂_relations
end graph
/-- The theory of simple graphs. -/
protected def Theory.simple_graph : language.graph.Theory :=
{adj.irreflexive, adj.symmetric}
@[simp] lemma Theory.simple_graph_model_iff [language.graph.Structure V] :
V ⊨ Theory.simple_graph ↔
irreflexive (λ x y : V, rel_map adj ![x,y]) ∧ symmetric (λ x y : V, rel_map adj ![x,y]) :=
by simp [Theory.simple_graph]
instance simple_graph_model (G : simple_graph V) :
@Theory.model _ V G.Structure Theory.simple_graph :=
begin
simp only [Theory.simple_graph_model_iff, rel_map_apply₂],
exact ⟨G.loopless, G.symm⟩,
end
variables (V)
/-- Any model of the theory of simple graphs represents a simple graph. -/
@[simps] def simple_graph_of_structure [language.graph.Structure V] [V ⊨ Theory.simple_graph] :
simple_graph V :=
{ adj := λ x y, rel_map adj ![x,y],
symm := relations.realize_symmetric.1 (Theory.realize_sentence_of_mem Theory.simple_graph
(set.mem_insert_of_mem _ (set.mem_singleton _))),
loopless := relations.realize_irreflexive.1 (Theory.realize_sentence_of_mem Theory.simple_graph
(set.mem_insert _ _)) }
variables {V}
@[simp] lemma _root_.simple_graph.simple_graph_of_structure (G : simple_graph V) :
@simple_graph_of_structure V G.Structure _ = G :=
by { ext, refl }
@[simp] lemma Structure_simple_graph_of_structure
[S : language.graph.Structure V] [V ⊨ Theory.simple_graph] :
(simple_graph_of_structure V).Structure = S :=
begin
ext n f xs,
{ exact (is_relational.empty_functions n).elim f },
{ ext n r xs,
rw iff_eq_eq,
cases n,
{ exact r.elim },
{ cases n,
{ exact r.elim },
{ cases n,
{ cases r,
change rel_map adj ![xs 0, xs 1] = _,
refine congr rfl (funext _),
simp [fin.forall_fin_two], },
{ exact r.elim } } } }
end
theorem Theory.simple_graph_is_satisfiable :
Theory.is_satisfiable Theory.simple_graph :=
⟨@Theory.Model.of _ _ unit (simple_graph.Structure ⊥) _ _⟩
end language
end first_order
|
function AltitudeDetector(arg0::jdouble, arg1::BodyShape)
return AltitudeDetector((jdouble, BodyShape), arg0, arg1)
end
function AltitudeDetector(arg0::jdouble, arg1::jdouble, arg2::BodyShape)
return AltitudeDetector((jdouble, jdouble, BodyShape), arg0, arg1, arg2)
end
function AltitudeDetector(arg0::jdouble, arg1::jdouble, arg2::jdouble, arg3::BodyShape)
return AltitudeDetector((jdouble, jdouble, jdouble, BodyShape), arg0, arg1, arg2, arg3)
end
function g(obj::AltitudeDetector, arg0::SpacecraftState)
return jcall(obj, "g", jdouble, (SpacecraftState,), arg0)
end
function get_altitude(obj::AltitudeDetector)
return jcall(obj, "getAltitude", jdouble, ())
end
function get_body_shape(obj::AltitudeDetector)
return jcall(obj, "getBodyShape", BodyShape, ())
end
|
{-# OPTIONS --cubical --safe #-}
module Cubical.HITs.Modulo.Base where
open import Cubical.Foundations.Function
open import Cubical.Foundations.HLevels
open import Cubical.Foundations.Isomorphism
open import Cubical.Foundations.Prelude
open import Cubical.Data.Empty
open import Cubical.Data.Fin
open import Cubical.Data.Nat
open import Cubical.Data.Unit renaming (Unit to ⊤)
open import Cubical.Relation.Nullary
NonZero : ℕ → Type₀
NonZero 0 = ⊥
NonZero _ = ⊤
private
variable
ℓ : Level
k : ℕ
-- The Modulo type is similar to the Fin type, but instead of being
-- inhabited by canonical values, the inhabitants are all naturals,
-- and paths are added between numbers that have the same residue.
--
-- This representation makes it easier to do certain arithmetic
-- without changing the modulus. For instance, we can just add any
-- natural to a Modulo k to get another, whereas with Fin k, we must
-- calculate the canonical representative.
--
-- The reason the path constructor is guarded is to avoid adding
-- non-trivial path structure to the k=0 case. If it were not guarded,
-- each `Modulo 0` would become like the circle, and guarding the
-- constructor is somewhat easier to work with than truncation.
--
-- Note also that unlike `Fin 0`, `Modulo 0` is equivalent to the naturals.
data Modulo (k : ℕ) : Type₀ where
embed : (n : ℕ) → Modulo k
pre-step : NonZero k → (n : ℕ) → embed n ≡ embed (k + n)
-- When we are working with k = suc k₀, the `step` alias is much
-- we can use this alias.
pattern step n i = pre-step _ n i
-- Helper to avoid having to case on `k` in certain places.
ztep : ∀{k} n → Path (Modulo k) (embed n) (embed (k + n))
ztep {0} n = refl
ztep {suc k} n = step n
-- The standard eliminator for `Modulo`.
elim
: (P : ∀ k → Modulo k → Type ℓ)
→ (e : ∀ k n → P k (embed n))
→ (st : ∀ k n → PathP (λ i → P (suc k) (step n i)) (e (suc k) n) (e (suc k) (suc k + n)))
→ (m : Modulo k) → P k m
elim P e st (embed n) = e _ n
elim {k = suc k} P e st (step n i) = st k n i
|
@doc """
Lattice
# Fields
- `dim :: Int`
- dimension of lattice
- `size :: Vector{Int}`
- length of lattice in each dimension
- `nsitetypes :: Int`
- the number of `sitetype`s
- `nbondtypes :: Int`
- the number of `bondtype`s
- `sites :: Vector{Vector{Int}}`
- list of site indecies for each `sitetype`
- `bonds :: Vector{Vector{Int}}`
- list of bond indecies for each `sitetype`
- `nsites :: Int`
- the number of sites
- `nbonds :: Int`
- the number of bonds
- `sitetypes :: Vector{Int}`
- `sitetype` of each site
- `bondtypes :: Vector{Int}`
- `bondtype` of each bond
- `transvector :: Matrix{Float64}`
- lattice vector represented in Cartesian system
- `@assert size(transvector) == (dim, dim)`
- `site_coords :: Matrix{Float64}`
- coordinate of each site represented in lattice system
- `@assert size(site_coords) == (dim, nsites)`
- `bond_dirs :: Matrix{Float64}`
- displacement of each bond represented in lattice system
- `@assert size(bond_dirs) == (dim, nbonds)`
- `neighborsites :: Vector{Vector{Int}}`
- list of indecies of neighbor sites of each site
- `neighborbonds :: Vector{Vector{Int}}`
- list of indecies of neighbor bonds of each site
- `source :: Vector{Int}`
- the index of an end site of each bond index
- `target :: Vector{Int}`
- the index of the other end site of each bond index
"""
mutable struct Lattice
dim :: Int
size :: Vector{Int}
nsitetypes :: Int
nbondtypes :: Int
sites :: Vector{Vector{Int}}
bonds :: Vector{Vector{Int}}
nsites :: Int
nbonds :: Int
sitetypes :: Vector{Int}
bondtypes :: Vector{Int}
transvector :: Matrix{Float64}
site_coords :: Matrix{Float64}
bond_dirs :: Matrix{Float64}
neighborsites :: Vector{Vector{Int}}
neighborbonds :: Vector{Vector{Int}}
source :: Vector{Int}
target :: Vector{Int}
end
import Base.size
import Distributions.dim
@doc """
dim(lat::Lattice)
dim(model::Model)
Returns the dimension of lattice.
"""
dim(lat::Lattice) = lat.dim
dim(model::Model) = dim(model.lat)
@doc """
size(lat::Lattice, [dim::Integer])
size(model::Model, [dim::Integer])
Returns the size of lattice.
"""
size(lat::Lattice) = lat.size
size(lat::Lattice, dim::Integer) = lat.size[dim]
size(model::Model) = size(model.lat)
size(model::Model, dim::Integer) = size(model.lat,dim)
@doc """
sites(lat::Lattice, sitetype::Integer)
sites(model::Model, sitetype::Integer)
Returns sites with `sitetype`
"""
sites(lat::Lattice, sitetype::Integer) = lat.sites[sitetype]
sites(model::Model, sitetype::Integer) = sites(model.lat, sitetype)
@doc """
numsites(lat::Lattice)
numsites(model::Model)
Returns the number of all sites.
"""
numsites(lat::Lattice) = lat.nsites
numsites(model::Model) = numsites(model.lat)
@doc """
numsites(lat::Lattice, sitetype::Integer)
numsites(model::Model, sitetype::Integer)
Returns the number of `sitetype` sites.
"""
numsites(lat::Lattice, sitetype::Integer) = length(lat.sites[sitetype])
numsites(model::Model, sitetype::Integer) = numsites(model.lat, sitetype)
@doc """
bonds(lat::Lattice, bondtype::Integer)
bonds(model::Model, bondtype::Integer)
Returns bonds with `bondtype`
"""
bonds(lat::Lattice, bondtype::Integer) = lat.bonds[bondtype]
bonds(model::Model, bondtype::Integer) = bonds(model.lat, bondtype)
@doc """
numbonds(lat::Lattice)
numbonds(model::Model)
Returns the number of all bonds.
"""
numbonds(lat::Lattice) = lat.nbonds
numbonds(model::Model) = numbonds(model.lat)
@doc """
numbonds(lat::Lattice, bondtype::Integer)
numbonds(model::Model, bondtype::Integer)
Returns the number of `bondtype` bonds.
"""
numbonds(lat::Lattice, bondtype::Integer) = length(lat.bonds[bondtype])
numbonds(model::Model, bondtype::Integer) = numbonds(model.lat, bondtype)
@doc """
numsitetypes(lat::Lattice)
numsitetypes(model::Model)
Returns the number of sitetypes.
"""
numsitetypes(lat::Lattice) = lat.nsitetypes
numsitetypes(model::Model) = numsitetypes(model.lat)
@doc """
numbondtypes(lat::Lattice)
numbondtypes(model::Model)
Returns the number of bondtypes.
"""
numbondtypes(lat::Lattice) = lat.nbondtypes
numbondtypes(model::Model) = numbondtypes(model.lat)
@doc """
neighborsites(lat::Lattice, site::Integer)
neighborsites(model::Model, site::Integer)
Returns the neighbor sites of `site`.
"""
neighborsites(lat::Lattice, site::Integer) = lat.neighborsites[site]
neighborsites(model::Model, site::Integer) = neighborsites(model.lat, site)
@doc """
neighborbonds(lat::Lattice, site::Integer)
neighborbonds(model::Model, site::Integer)
Returns the neighbor bonds of `site`.
"""
neighborbonds(lat::Lattice, site::Integer) = lat.neighborbonds[site]
neighborbonds(model::Model, site::Integer) = neighborbonds(model.lat, site)
@doc """
neighbors(lat::Lattice, site::Integer)
neighbors(model::Model, site::Integer)
Returns the neighbor sites and bonds of `site`.
"""
neighbors(lat::Lattice, site::Integer) = zip(neighborsites(lat,site), neighborbonds(lat,site))
neighbors(model::Model, site::Integer) = neighbors(model.lat, site)
@doc """
source(lat::Lattice, bond::Integer)
source(model::Model, bond::Integer)
Returns the source site of `bond`.
"""
source(lat::Lattice, bond::Integer) = lat.source[bond]
source(model::Model, bond::Integer) = source(model.lat, bond)
@doc """
target(lat::Lattice, bond::Integer)
target(model::Model, bond::Integer)
Returns the target site of `bond`.
"""
target(lat::Lattice, bond::Integer) = lat.target[bond]
target(model::Model, bond::Integer) = target(model.lat, bond)
@doc """
sitecoordinate(lat::Lattice, site::Integer)
sitecoordinate(model::Model, site::Integer)
Returns the coordinate of the `site` in the Cartesian system
"""
sitecoordinate(lat::Lattice, site::Integer) = lat.transvector * lat.site_coords[:,site]
sitecoordinate(model::Model, site::Integer) = sitecoordinate(model.lat, site)
@doc """
lattice_sitecoordinate(lat::Lattice, site::Integer)
lattice_sitecoordinate(model::Model, site::Integer)
Returns the coordinate of the `site` in the lattice system
"""
lattice_sitecoordinate(lat::Lattice, site::Integer) = lat.site_coords[:, site]
lattice_sitecoordinate(model::Model, site::Integer) = lattice_sitecoordinate(model.lat, site)
@doc """
sitetype(lat::Lattice, site::Integer)
sitetype(model::Model, site::Integer)
Returns the type of `site`
"""
sitetype(lat::Lattice, site::Integer) = lat.sitetypes[site]
sitetype(model::Model, site::Integer) = sitetype(model.lat, site)
@doc """
bondtype(lat::Lattice, bond::Integer)
bondtype(model::Model, bond::Integer)
Returns the type of `bond`
"""
bondtype(lat::Lattice, bond::Integer) = lat.bondtypes[bond]
bondtype(model::Model, bond::Integer) = bondtype(model.lat, bond)
@doc """
bonddirection(lat::Lattice, bond::Integer)
bonddirection(model::Model, bond::Integer)
Returns the direction of the `bond` as vector in the Cartesian system
"""
bonddirection(lat::Lattice, bond::Integer) = lat.transvector * lat.bond_dirs[:, bond]
bonddirection(model::Model, bond::Integer) = bonddirection(model.lat, bond)
@doc """
lattice_bonddirection(lat::Lattice, bond::Integer)
lattice_bonddirection(model::Model, bond::Integer)
Returns the direction of the `bond` as vector in the lattice system
"""
lattice_bonddirection(lat::Lattice, bond::Integer) = lat.bond_dirs[:, bond]
lattice_bonddirection(model::Model, bond::Integer) = lattice_bonddirection(model.lat, bond)
|
theory E2_9
imports Main
begin
fun add :: "nat \<Rightarrow> nat \<Rightarrow> nat" where
"add 0 n = n" |
"add (Suc m) n = Suc (add m n)"
fun itadd :: "nat \<Rightarrow> nat \<Rightarrow> nat" where
"itadd 0 n = n" |
"itadd (Suc m) n = itadd m (Suc n)"
lemma add_help [simp] : "add m (Suc n) = Suc (add m n)"
apply(induction m)
apply(auto)
done
lemma "itadd m n = add m n"
apply(induction m arbitrary: n)
apply(auto)
done
end
|
! { dg-do compile }
!
! PR fortran/51953
!
!
type t
end type t
class(t), allocatable :: a, c(:), e(:)
class(t), pointer :: b, d(:)
allocate (a, b, source=c(1))
allocate (c(4), d(6), source=e)
allocate (a, b, mold=f())
allocate (c(1), d(6), mold=g())
allocate (a, b, source=f())
allocate (c(1), d(6), source=g())
contains
function f()
class(t), allocatable :: f
end function
function g()
class(t), allocatable :: g(:)
end function
end
|
import Data.Vect
total allLengths : Vect len String -> Vect len Nat
allLengths [] = []
allLengths (x :: xs) = length x :: allLengths xs
|
module SimpleFFI.Renderer
import SimpleFFI.Spec
import Data.Either
import Data.List
import Data.SortedMap
import Text.PrettyPrint.Prettyprinter
import Text.PrettyPrint.Prettyprinter.Render.String
emptyLine : Doc ()
emptyLine = hardline <+> hardline
stringLit : String -> Doc ()
stringLit = dquotes . pretty
sepByLines : List (Doc ()) -> Doc ()
sepByLines ds@(d::_) = foldl1 (\acc, d => acc <+> emptyLine <+> d) ds
sepByLines [] = emptyDoc
indented : Doc () -> Doc ()
indented d = nest 2 (hardline <+> d) <+> hardline
inline : Doc ()
inline = pretty "%inline"
pubExport : Doc ()
pubExport = pretty "public export"
export_ : Doc ()
export_ = pretty "export" <+> hardline
typeHeader : Doc () -> Doc ()
typeHeader n = vcat [
inline,
pubExport,
n <++> colon <++> pretty "Type"
]
arr : Doc ()
arr = pretty " ->"
funType : List (Doc ()) -> Doc ()
funType = hsep . punctuate arr
namespaced : String -> Doc () -> Doc ()
namespaced n body = pretty ("namespace " ++ n) <+> indented body
prettyType : DartType -> Doc ()
prettyType ty = case ty of
BoolType => pretty "DartBool"
IntType => pretty "Int"
StringType => pretty "String"
DoubleType => pretty "Double"
VoidType => pretty "()"
NamedType n => pretty n
ListType a => parens (pretty "DartList" <++> prettyType a)
FunctionType ps ret =>
let sig = (prettyType <$> ps) ++ [pretty "IO" <++> prettyType ret]
in parens (funType sig)
structField : (String, DartType) -> Doc ()
structField (n, ty) =
parens $ hsep $ punctuate comma $ [stringLit n, prettyType ty]
fieldList : List (String, DartType) -> Doc ()
fieldList [] = pretty "[]"
fieldList fs =
enclose "[" "]"
(indented . vsep . punctuate comma $ (structField <$> fs))
foreignNameOf : {auto lib : Lib} -> String -> String
foreignNameOf name = name ++ "," ++ lib.package
typeDecl : {auto lib : Lib} -> String -> List (String, DartType) -> Doc ()
typeDecl name fields =
let
name' = pretty name
foreignTypeName = dquotes (pretty (foreignNameOf name))
struct = pretty "Struct" <++> foreignTypeName <++> fieldList fields
in
typeHeader name' <+> hardline <+> name' <++> equals <++> struct
fields : Class -> List Field
fields c = mapMaybe field c.members
where
field : Member -> Maybe Field
field (FieldMember f) = Just f
field _ = Nothing
nameAndType : Field -> (String, DartType)
nameAndType (Var n ty) = (n, ty)
nameAndType (Final n ty) = (n, ty)
typeDeclFor : {auto lib : Lib} -> Declaration -> Doc ()
typeDeclFor (ClassDecl c) =
typeDecl c.name (nameAndType <$> fields c)
typeDeclFor (EnumDecl n fs) =
typeDecl n []
typeDeclsForLib : LibDef -> List (Doc ())
typeDeclsForLib libDef =
let lib = libDef.lib
in typeDeclFor <$> libDef.declarations
this : Doc ()
this = pretty "this"
ioUnit : Doc ()
ioUnit = pretty "IO ()"
capitalize : String -> String
capitalize s =
let cs = unpack s
in pack ((toUpper <$> take 1 cs) ++ drop 1 cs)
setter : String -> String -> DartType -> Doc ()
setter owner field ty =
let
n = pretty ("set" ++ capitalize field)
field' = pretty field
ty' = prettyType ty
val = pretty "value"
in
export_
<+> n <++> colon <++> funType [ty', pretty owner, ioUnit] <+> hardline
<+> n <++> val <++> this <++> equals
<++> pretty "setField" <++> this <++> dquotes field' <++> val
getter : String -> String -> DartType -> Doc ()
getter owner field ty =
let
field' = pretty field
ty' = prettyType ty
in
export_
<+> field' <++> colon <++> funType [pretty owner, ty'] <+> hardline
<+> field' <++> this <++> equals
<++> pretty "getField" <++> this <++> dquotes field'
foreign' : Doc ()
foreign' = pretty "%foreign"
foreign : String -> Doc ()
foreign n = foreign' <++> dquotes (pretty ("Dart:" ++ n))
prettyParameter : Parameter -> Doc ()
prettyParameter (P n ty) = parens (pretty n <++> colon <++> prettyType ty)
prettyParameter _ = emptyDoc
partitionParameters : List Parameter -> (List (String, DartType), List (String, DartType))
partitionParameters ps = partitionEithers . flip map ps $ \case
P n ty => Left (n, ty)
N n ty => Right (n, ty)
parameterNames : List Parameter -> List (Doc ())
parameterNames ps = flip mapMaybe ps $ \case
P n _ => Just (pretty n)
_ => Nothing
parameters' : Doc ()
parameters'= pretty "NamedParameters"
namedParameterDeclarationsFor : String -> String -> List (String, DartType) -> Doc ()
namedParameterDeclarationsFor typeName _ [] = emptyDoc
namedParameterDeclarationsFor typeName ns ps = namespaced ns (sepByLines (tag :: (decl <$> ps)) <+> hardline <+> schema)
where
qualified : String -> Doc ()
qualified n = pretty (typeName ++ "." ++ ns ++ "." ++ n)
tag : Doc ()
tag = pretty "data Tag : Type where"
schema : Doc ()
schema = vcat [
inline,
pubExport,
parameters' <++> colon <++> pretty "Type",
parameters' <++> equals <++> pretty "Parameters" <++> list ((\(n, _) => qualified n) <$> ps)
]
decl : (String, DartType) -> Doc ()
decl (n, ty) = vcat [
inline,
pubExport,
pretty n <++> colon <++> pretty "Parameter" <++> qualified "Tag",
pretty n <++> equals <++> pretty "mkParameter" <++> hsep [stringLit n, prettyType ty]
]
ctorPrimsFor : {auto lib : Lib} -> {auto c : Class} -> String -> List Parameter -> Maybe DartType -> Maybe String -> List (Doc ())
ctorPrimsFor n ps ret foreignName =
let
funName = if length n == 0 then "new" else n
namedParameterNS = capitalize funName
input' = pretty c.name
ret' = case ret of
Nothing => input'
(Just ret) => prettyType ret
foreignName' = case foreignName of
Nothing => ""
(Just foreignName) => foreignName
prim__new = pretty " export %extern prim__dart_new : Type -> HVect positional -> Parameters named -> (1 x : %World) -> IORes " <++> ret'
(positionalPs, namedPs) = partitionParameters ps
positionalPs' = (\(n, ty) => parens (pretty n <++> colon <++> prettyType ty)) <$> positionalPs
psNames = pretty . fst <$> positionalPs
(ps', pTys', args') = if isNil namedPs
then (
hsep psNames,
positionalPs',
list psNames <++> parens (pretty "the (Parameters {tag = Void} [])" <++> list [])
) else (
hsep psNames <++> pretty "ps",
positionalPs' ++ [input' <+> dot <+> pretty namedParameterNS <+> dot <+> parameters'],
list psNames <++> pretty "ps"
)
funBody = pretty funName <++> ps' <++> equals <++> pretty "primIO $ prim__dart_new" <++> ret' <++> args'
funBodyForeign =
let prim_type = pretty $ "(Struct \"" ++ foreignName' ++ "\" [])"
in pretty funName <++> ps' <++> equals <++> pretty ("primIO $ " ++ namedParameterNS ++ ".prim__dart_new") <++> prim_type <++> args'
fun = vcat [
case foreignName of
Nothing => pretty ""
otherwise => prim__new <+> hardline,
inline,
pubExport,
pretty funName <++> colon <++> pretty "HasIO io =>" <++> funType (pTys' ++ [pretty "io" <++> ret']),
case foreignName of
Nothing => funBody
otherwise => funBodyForeign
]
in
if isNil namedPs
then [fun]
else [namedParameterDeclarationsFor c.name namedParameterNS namedPs, fun]
isIdrisKeyword : String -> Bool
isIdrisKeyword s = case s of
"of" => True
_ => False
functionPrimsFor : {auto lib : Lib} -> {auto c : Class} -> Function -> String -> Bool -> List (Doc ())
functionPrimsFor (Fun n ps ret) foreignName hasThis =
let
ret' = prettyType ret
ps' = prettyParameter <$> ps
psNames = parameterNames ps
primName = pretty ("prim__" ++ n)
primRet = pretty "PrimIO" <++> ret'
primParamTys = ps' ++ [primRet]
proxyParamTys = [pretty "io" <++> ret']
thisTy = the (Lazy (Doc())) (parens (this <++> colon <++> pretty c.name))
proxyName = pretty (if isIdrisKeyword n then n ++ "_" else n)
(positionalPs, namedPs) = partitionParameters ps
prim =
foreign foreignName <+> hardline
<+> primName <++> colon <++> funType (ifHasThis (thisTy :: primParamTys) primParamTys)
proxy =
export_ <+> proxyName <++> colon <++> pretty "HasIO io =>"
<++> funType (ps' ++ ifHasThis (thisTy :: proxyParamTys) proxyParamTys) <+> hardline
<+> proxyName <++> hsep psNames <++> ifHasThis (this <++> equals) equals
<++> pretty "primIO $" <++> primName <++> hsep (ifHasThis (this :: psNames) psNames)
in
if isNil namedPs
then [prim, proxy]
else ctorPrimsFor n ps (Just ret) (Just foreignName)
where
ifHasThis : Lazy a -> Lazy a -> a
ifHasThis ifTrue ifFalse = if hasThis then ifTrue else ifFalse
constPrim : {auto lib : Lib} -> String -> String -> DartType -> Doc ()
constPrim owner field ty =
export_ <+> foreign ("const " ++ owner ++ "." ++ field ++ "," ++ lib.package) <+> hardline
<+> pretty field <++> colon <++> prettyType ty
enumPrim : {auto lib : Lib} -> String -> String -> Doc ()
enumPrim n f = constPrim n f (NamedType n)
isAssignableFromInstance : String -> String -> Doc ()
isAssignableFromInstance super sub =
export_ <+> pretty "IsAssignableFrom" <++> pretty super <++> pretty sub <++> pretty "where"
classMemberPrim : {auto lib : Lib} -> Class -> Member -> List (Doc ())
classMemberPrim c m = case m of
Constructor n ps => ctorPrimsFor n ps Nothing Nothing
Method f@(Fun n _ _) => functionPrimsFor f ("." ++ n) True
Static f@(Fun n _ _) => functionPrimsFor f (foreignNameOf (c.name ++ "." ++ n)) False
FieldMember (Var n ty) => [getter c.name n ty, setter c.name n ty]
FieldMember (Final n ty) => [getter c.name n ty]
Extends ty => [isAssignableFromInstance ty c.name]
Const n ty => [constPrim c.name n ty]
prettyPrims : {auto lib : Lib} -> Declaration -> Maybe (Doc ())
prettyPrims (ClassDecl c) =
case concatMap (classMemberPrim c) c.members of
[] => Nothing
ms => Just $ namespaced c.name (sepByLines ms)
prettyPrims (EnumDecl n fs) =
Just $ namespaced n (vcat (enumPrim n <$> fs))
primsForLib : LibDef -> List (Doc ())
primsForLib libDef =
let lib = libDef.lib
in mapMaybe prettyPrims libDef.declarations
header : Doc () -> Doc ()
header n =
pretty "||| FFI definitions for the " <++> n <++> "API." <+> hardline
<+> pretty "module" <++> n <+> hardline <+> hardline
<+> pretty "import Dart.Core" <+> hardline
<+> pretty "import Dart.FFI"
export
renderModule : Module -> IO ()
renderModule ffi = do
let decls = concatMap typeDeclsForLib ffi.libs
let mutualDecls = pretty "mutual" <+> indented (sepByLines decls)
let prims = concatMap primsForLib ffi.libs
let doc = the (Doc ()) (sepByLines (header (pretty ffi.name) :: mutualDecls :: prims))
let pageWidth = AvailablePerLine 120 1
let options = record { layoutPageWidth = pageWidth } defaultLayoutOptions
renderIO $ layoutPretty options $ doc
|
[STATEMENT]
lemma cf_ntcf_comp_is_ntcf:
assumes "\<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>" and "\<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<BB>"
shows "\<HH> \<circ>\<^sub>C\<^sub>F\<^sub>-\<^sub>N\<^sub>T\<^sub>C\<^sub>F \<NN> : \<HH> \<circ>\<^sub>C\<^sub>F \<FF> \<mapsto>\<^sub>C\<^sub>F \<HH> \<circ>\<^sub>C\<^sub>F \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN> : \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF> \<mapsto>\<^sub>C\<^sub>F \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
[PROOF STEP]
proof-
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN> : \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF> \<mapsto>\<^sub>C\<^sub>F \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
[PROOF STEP]
interpret \<HH>: is_functor \<alpha> \<BB> \<CC> \<HH>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
[PROOF STEP]
by (rule assms(1))
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN> : \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF> \<mapsto>\<^sub>C\<^sub>F \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
[PROOF STEP]
interpret \<NN>: is_ntcf \<alpha> \<AA> \<BB> \<FF> \<GG> \<NN>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<BB>
[PROOF STEP]
by (rule assms(2))
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN> : \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF> \<mapsto>\<^sub>C\<^sub>F \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN> : \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF> \<mapsto>\<^sub>C\<^sub>F \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
[PROOF STEP]
proof(rule is_ntcfI)
[PROOF STATE]
proof (state)
goal (10 subgoals):
1. \<Z> \<alpha>
2. vfsequence (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)
3. \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
4. \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
5. vcard (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>) = 5\<^sub>\<nat>
6. ntcf_ntsmcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>) : cf_smcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF>) \<mapsto>\<^sub>S\<^sub>M\<^sub>C\<^sub>F cf_smcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG>) : cat_smc \<AA> \<mapsto>\<mapsto>\<^sub>S\<^sub>M\<^sub>C\<^bsub>\<alpha>\<^esub> cat_smc \<CC>
7. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTDom\<rparr> = \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF>
8. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTCod\<rparr> = \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG>
9. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTDGDom\<rparr> = \<AA>
10. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTDGCod\<rparr> = \<CC>
[PROOF STEP]
show "vfsequence (\<HH> \<circ>\<^sub>C\<^sub>F\<^sub>-\<^sub>N\<^sub>T\<^sub>C\<^sub>F \<NN>)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. vfsequence (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)
[PROOF STEP]
unfolding dghm_tdghm_comp_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. vfsequence [\<lambda>a\<in>\<^sub>\<circ>\<NN>\<lparr>NTDGDom\<rparr>\<lparr>Obj\<rparr>. \<HH>\<lparr>ArrMap\<rparr>\<lparr>\<NN>\<lparr>NTMap\<rparr>\<lparr>a\<rparr>\<rparr>, \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>\<lparr>NTDom\<rparr>, \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>\<lparr>NTCod\<rparr>, \<NN>\<lparr>NTDGDom\<rparr>, \<HH>\<lparr>HomCod\<rparr>]\<^sub>\<circ>
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
vfsequence (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)
goal (9 subgoals):
1. \<Z> \<alpha>
2. \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
3. \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
4. vcard (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>) = 5\<^sub>\<nat>
5. ntcf_ntsmcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>) : cf_smcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF>) \<mapsto>\<^sub>S\<^sub>M\<^sub>C\<^sub>F cf_smcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG>) : cat_smc \<AA> \<mapsto>\<mapsto>\<^sub>S\<^sub>M\<^sub>C\<^bsub>\<alpha>\<^esub> cat_smc \<CC>
6. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTDom\<rparr> = \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF>
7. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTCod\<rparr> = \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG>
8. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTDGDom\<rparr> = \<AA>
9. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTDGCod\<rparr> = \<CC>
[PROOF STEP]
from assms
[PROOF STATE]
proof (chain)
picking this:
\<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
\<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<BB>
[PROOF STEP]
show "\<HH> \<circ>\<^sub>C\<^sub>F \<FF> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>"
[PROOF STATE]
proof (prove)
using this:
\<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
\<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<BB>
goal (1 subgoal):
1. \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
[PROOF STEP]
by (cs_concl cs_intro: cat_cs_intros)
[PROOF STATE]
proof (state)
this:
\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
goal (8 subgoals):
1. \<Z> \<alpha>
2. \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
3. vcard (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>) = 5\<^sub>\<nat>
4. ntcf_ntsmcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>) : cf_smcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF>) \<mapsto>\<^sub>S\<^sub>M\<^sub>C\<^sub>F cf_smcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG>) : cat_smc \<AA> \<mapsto>\<mapsto>\<^sub>S\<^sub>M\<^sub>C\<^bsub>\<alpha>\<^esub> cat_smc \<CC>
5. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTDom\<rparr> = \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF>
6. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTCod\<rparr> = \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG>
7. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTDGDom\<rparr> = \<AA>
8. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTDGCod\<rparr> = \<CC>
[PROOF STEP]
from assms
[PROOF STATE]
proof (chain)
picking this:
\<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
\<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<BB>
[PROOF STEP]
show "\<HH> \<circ>\<^sub>C\<^sub>F \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>"
[PROOF STATE]
proof (prove)
using this:
\<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
\<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<BB>
goal (1 subgoal):
1. \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
[PROOF STEP]
by (cs_concl cs_intro: cat_cs_intros)
[PROOF STATE]
proof (state)
this:
\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
goal (7 subgoals):
1. \<Z> \<alpha>
2. vcard (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>) = 5\<^sub>\<nat>
3. ntcf_ntsmcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>) : cf_smcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF>) \<mapsto>\<^sub>S\<^sub>M\<^sub>C\<^sub>F cf_smcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG>) : cat_smc \<AA> \<mapsto>\<mapsto>\<^sub>S\<^sub>M\<^sub>C\<^bsub>\<alpha>\<^esub> cat_smc \<CC>
4. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTDom\<rparr> = \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF>
5. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTCod\<rparr> = \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG>
6. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTDGDom\<rparr> = \<AA>
7. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTDGCod\<rparr> = \<CC>
[PROOF STEP]
show "vcard (\<HH> \<circ>\<^sub>C\<^sub>F\<^sub>-\<^sub>N\<^sub>T\<^sub>C\<^sub>F \<NN>) = 5\<^sub>\<nat>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. vcard (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>) = 5\<^sub>\<nat>
[PROOF STEP]
unfolding dghm_tdghm_comp_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. vcard [\<lambda>a\<in>\<^sub>\<circ>\<NN>\<lparr>NTDGDom\<rparr>\<lparr>Obj\<rparr>. \<HH>\<lparr>ArrMap\<rparr>\<lparr>\<NN>\<lparr>NTMap\<rparr>\<lparr>a\<rparr>\<rparr>, \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>\<lparr>NTDom\<rparr>, \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>\<lparr>NTCod\<rparr>, \<NN>\<lparr>NTDGDom\<rparr>, \<HH>\<lparr>HomCod\<rparr>]\<^sub>\<circ> = 5\<^sub>\<nat>
[PROOF STEP]
by (simp add: nat_omega_simps)
[PROOF STATE]
proof (state)
this:
vcard (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>) = 5\<^sub>\<nat>
goal (6 subgoals):
1. \<Z> \<alpha>
2. ntcf_ntsmcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>) : cf_smcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF>) \<mapsto>\<^sub>S\<^sub>M\<^sub>C\<^sub>F cf_smcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG>) : cat_smc \<AA> \<mapsto>\<mapsto>\<^sub>S\<^sub>M\<^sub>C\<^bsub>\<alpha>\<^esub> cat_smc \<CC>
3. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTDom\<rparr> = \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF>
4. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTCod\<rparr> = \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG>
5. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTDGDom\<rparr> = \<AA>
6. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTDGCod\<rparr> = \<CC>
[PROOF STEP]
from assms
[PROOF STATE]
proof (chain)
picking this:
\<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
\<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<BB>
[PROOF STEP]
show "ntcf_ntsmcf (\<HH> \<circ>\<^sub>C\<^sub>F\<^sub>-\<^sub>N\<^sub>T\<^sub>C\<^sub>F \<NN>) :
cf_smcf (\<HH> \<circ>\<^sub>C\<^sub>F \<FF>) \<mapsto>\<^sub>S\<^sub>M\<^sub>C\<^sub>F cf_smcf (\<HH> \<circ>\<^sub>C\<^sub>F \<GG>) :
cat_smc \<AA> \<mapsto>\<mapsto>\<^sub>S\<^sub>M\<^sub>C\<^bsub>\<alpha>\<^esub> cat_smc \<CC>"
[PROOF STATE]
proof (prove)
using this:
\<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
\<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<BB>
goal (1 subgoal):
1. ntcf_ntsmcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>) : cf_smcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF>) \<mapsto>\<^sub>S\<^sub>M\<^sub>C\<^sub>F cf_smcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG>) : cat_smc \<AA> \<mapsto>\<mapsto>\<^sub>S\<^sub>M\<^sub>C\<^bsub>\<alpha>\<^esub> cat_smc \<CC>
[PROOF STEP]
by
(
cs_concl
cs_simp: slicing_commute[symmetric]
cs_intro: slicing_intros smc_cs_intros
)
[PROOF STATE]
proof (state)
this:
ntcf_ntsmcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>) : cf_smcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF>) \<mapsto>\<^sub>S\<^sub>M\<^sub>C\<^sub>F cf_smcf (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG>) : cat_smc \<AA> \<mapsto>\<mapsto>\<^sub>S\<^sub>M\<^sub>C\<^bsub>\<alpha>\<^esub> cat_smc \<CC>
goal (5 subgoals):
1. \<Z> \<alpha>
2. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTDom\<rparr> = \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF>
3. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTCod\<rparr> = \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG>
4. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTDGDom\<rparr> = \<AA>
5. (\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN>)\<lparr>NTDGCod\<rparr> = \<CC>
[PROOF STEP]
qed (auto simp: dghm_tdghm_comp_components(1) cat_cs_simps)
[PROOF STATE]
proof (state)
this:
\<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M\<^sub>-\<^sub>T\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<NN> : \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<FF> \<mapsto>\<^sub>C\<^sub>F \<HH> \<circ>\<^sub>D\<^sub>G\<^sub>H\<^sub>M \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
goal:
No subgoals!
[PROOF STEP]
qed |
If two loops are homotopic, and a third loop is homotopic to the second, then the third loop is homotopic to the first. |
function [soln,eqn,info] = StokesRT0(node,elem,bdFlag,pde,option)
%% STOKESRT0 Stokes equations: the lowest order Raviart-Thomas element in 2D.
%
% [soln,eqn,info] = StokesRT0(node,elem,bdFlag,pde,option)
% uses the lowest order of Raviart-Thomas element (RT0) to approximate
% velocity u and piecewise constant element (P0) to approximate pressure
% p, repectively.
%
% We solve the following equation:
% - grad div u + curl rot u + grad p = f in \Omega
% - div u = 0 in \Omega
% u = g on \Gamma
%
% ifem StokesRT0doc
%
% See also StokesBDM1B
%
% Based on a version by Ming Wang. Revised by Lin Zhong. Discussed with Jie
% Zhou and Long Chen. Further clean up by Long Chen.
%
% Copyright (C) Long Chen. See COPYRIGHT.txt for details.
if ~exist('option','var'), option = []; end
%% Data structure
elemunSort = elem;
[elem,bdFlag] = sortelem(elemunSort,bdFlag);
[elem2edge,edge] = dofedge(elem);
[Clambda,area,elemSign] = curlbasis(node,elem);
N = size(node,1); NT = size(elem,1); NE = size(edge,1);
Nu = NE; Np = NT; Ndof = Nu + Np;
%% Assemble matrices
t = cputime; % record assemble time
% Mv: Lumped mass matrix for vertex: P1 element
vecMv = accumarray([elem(:,1);elem(:,2);elem(:,3)],[area;area;area]/3,[N,1]);
% invMv = spdiags(1./vecMv,0,N,N);
Mv = spdiags(vecMv,0,N,N);
% Me: Mass matrix for RT0 element
Me = getmassmatvec(elem2edge,area,Clambda,'RT0');
%invMt: the inverse of Mass matrix for P0 element
invMt = spdiags(1./area,0,NT,NT);
% B: negative divergence operator
B = -icdmat(double(elem2edge),elemSign*[1 -1 1]);
% C: curl operator
C = icdmat(double(edge),[-1 1]);
% R: weak rot operator
R = spdiags(1./vecMv,0,N,N)*C'*Me;
% Vector Laplacian
A = B'*invMt*B + R'*Mv*R;
%% Assemble right hand side
locEdge = [2,3; 1 3; 1,2]; % ascend ordering
fu = zeros(Nu,1);% the right hand side of u
g = zeros(Np,1); % the right hand side of p
if ~isfield(pde,'f') || (isfield(pde,'f') && isreal(pde.f) && all(pde.f==0))
pde.f = [];
end
if ~isfield(option,'fquadorder')
option.fquadorder = 3; % default order is 3
end
if isfield(pde,'f') && ~isempty(pde.f)
[lambda,w] = quadpts(option.fquadorder);
nQuad = size(lambda,1);
bt = zeros(NT,3);
for p = 1:nQuad
% quadrature points in the x-y-z coordinate
pxy = lambda(p,1)*node(elem(:,1),:) ...
+ lambda(p,2)*node(elem(:,2),:) ...
+ lambda(p,3)*node(elem(:,3),:);
fp = pde.f(pxy);
for k = 1:3
i = locEdge(k,1); j = locEdge(k,2);
% phi_k = lambda_iClambda_j - lambda_jClambda_i;
phi_k = lambda(p,i)*Clambda(:,:,j)-lambda(p,j)*Clambda(:,:,i);
rhs = dot(phi_k,fp,2);
bt(:,k) = bt(:,k) + w(p)*rhs;
end
end
bt = bt.*repmat(area,1,3);
fu = accumarray(elem2edge(:),bt(:),[Nu 1]);
end
clear pxy fp bt rhs phi_k psi_k
%% Boundary condition and graddiv part of A
[u,p,ufreeDof,pDof,utbd] = getbdStokesRT0;
assembleTime = cputime - t;
%% Solve the system of linear equations
% set up solver type
if isempty(option) || ~isfield(option,'solver') % no option.solver
if Ndof <= 1e5 % Direct solver for small size systems
solver = 'direct';
else % Multigrid-type solver for large size systems
solver = 'mg';
end
else
solver = option.solver;
end
% solve the system
% get submatrices of ufreeDof
A0 = A(ufreeDof,ufreeDof);
B0 = B(:,ufreeDof);
f0 = fu(ufreeDof);
g0 = g;
if strcmp(solver,'direct') && ~isempty(ufreeDof)
t = cputime;
bigA = [A0, B0'; ...
B0, sparse(Np,Np)];
bigF = [f0; g0];
bigu = [u; p];
bigFreeDof = [ufreeDof; Nu+pDof];
bigu(bigFreeDof) = bigA(1:end-1,1:end-1)\bigF(1:end-1);
u = bigu(1:Nu);
p = bigu(Nu+1:end);
info.solverTime = cputime - t;
elseif strcmp(solver,'mg')
% option.solver = 'vcycle';
option.solver = 'WCYCLE';
[u(ufreeDof),p,info] = mgstokesRT0(A0,B0,f0,g0,u,p,node,elemunSort,ufreeDof,option);
end
%% Post-process
if length(pDof)~=Np % p is unique up to a constant
% impose the condition int(p)=0
c = sum(p.*area)/sum(area);
p = p - c;
end
w = R*u + utbd./vecMv;
psi = zeros(N,1);
% compute streamline function
if isfield(option,'stream') && option.stream
[As,Ms] = assemblematrix(node,elem);
[fixedNode,bdEdge,isBdNode] = findboundary(elem,bdFlag);
freeNode = ~isBdNode;
rhs = Ms*w;
streamoption.freeDof = freeNode;
psi(freeNode) = mg(As(freeNode,freeNode),rhs(freeNode),elemunSort,streamoption);
% assume u\cdot n = 0.
end
%% Output information
info.assembleTime = assembleTime;
%% Output
soln = struct('u',u,'p',p,'w',w,'psi',psi);
eqn = struct('A',A0,'B',B0,'Me',Me,'Mv',Mv,'f',f0,'g',g0,...
'edge',edge,'ufreeDof',ufreeDof,'pDof',pDof);
info.assembleTime = assembleTime;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunctions getbdStokesRT0
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [u,p,ufreeDof,pDof,utbd] = getbdStokesRT0
%% Boundary condition of Stokes equation: RT0-P0 elements
% Initial set up
utbd = zeros(N,1); % the line integral of u on the boundary (u.t, tau)|_\partial \Omega
u = zeros(Nu,1);
p = zeros(Np,1);
ufreeDof = (1:Nu)';
pDof = (1:Np-1)';
if ~exist('bdFlag','var'), bdFlag = []; end
if ~isfield(pde,'g_D'), pde.g_D = []; end
if ~isfield(pde,'g_N'), pde.g_N = []; end
if ~isfield(pde,'g_R'), pde.g_R = []; end
if isempty(pde.g_D) && isempty(pde.g_N) && isempty(pde.g_R)
bdFlag = [];
end
% Find Dirichlet boundary dof: fixedDof and pDof
isFixedDof = false(Nu,1);
if ~isempty(bdFlag)
isDirichlet(elem2edge(bdFlag(:)==1)) = true;
Dirichlet = edge(isDirichlet,:);
isFixedDof(isDirichlet) = true;
fixedDof = find(isFixedDof);
ufreeDof = find(~isFixedDof);
end
% Set up edge sign
% edgeSign records the inconsistency of asecond orientation and
% induced orientation for each boundary edges
edgeSign = ones(NE,1);
idx = (bdFlag(:,1) ~= 0 ) & (elemSign == -1) ; % the first edge is on boundary
edgeSign(elem2edge(idx,1)) = -1;
idx = (bdFlag(:,2) ~= 0 ) & (elemSign == 1) ; % the second edge is on boundary
edgeSign(elem2edge(idx,2)) = -1;
idx = (bdFlag(:,3) ~= 0 ) & (elemSign == -1) ; % the third edge is on boundary
edgeSign(elem2edge(idx,3)) = -1;
% Compute the boundary integral
if ~isempty(fixedDof) && ~isempty(pde.g_D) && ~(isnumeric(pde.g_D) && (pde.g_D == 0))
% else no bddof or g_D = 0 (no modification needed)
% 1. Normal component of u is imposed strongly
if (isnumeric(pde.g_D) && length(pde.g_D) == NE)
u(fixedDof) = pde.g_D(fixedDof);
else
u(fixedDof) = faceinterpolate(pde.g_D,node,edge(fixedDof,:),'RT0');
end
% 2. Tangential component of u is imposed weakly
[lambdagD,wgD] = quadpts1(3);
nQuadgD = size(lambdagD,1);
% quadrat = cputime bases 1--3--2
bdphi = lambdagD;
ve = node(Dirichlet(:,2),:) - node(Dirichlet(:,1),:);
ge = zeros(size(Dirichlet,1),2);
int_left = zeros(size(Dirichlet,1),2);
int_right = zeros(size(Dirichlet,1),2);
for pp = 1:nQuadgD
ppxy = lambdagD(pp,1)*node(Dirichlet(:,1),:) ...
+ lambdagD(pp,2)*node(Dirichlet(:,2),:);
gDp = pde.g_D(ppxy);
int_left = int_left + wgD(pp)*gDp*bdphi(pp,1);
int_right = int_right + wgD(pp)*gDp*bdphi(pp,2);
end
ge(:,1) = dot(int_left,ve,2).*edgeSign(fixedDof);
ge(:,2) = dot(int_right,ve,2).*edgeSign(fixedDof);
utbd = accumarray(Dirichlet(:), [ge(:,1); ge(:,2)],[N,1]);
end
% Modify the right hand side
fu = fu - A*u - Me*(C*(utbd./vecMv));
g = g - B*u;
g = g - mean(g);
end
end |
\input{preamble}
\begin{document}
\section{Subjects}
\begin{itemize}
\item Backpropagation
\item Deep Nets
\item PCA
\item Autoencoder
\end{itemize}
\section{Notes}
\subsection{Neurons and background}
Neurons consist of a dendritic tree (the input, which branches a lot), the
axon (the output, which branches a little bit) and the cell body with
nucleus.
Neurons work by having axons connected to dendritic trees, they give a
binary ($0$ or $1$) output, after an axon has sent a $1$, it has to
recharge.
In order to model this, we've got binary input $x_1,\dots, x_n$ which is
sent to the nucleus that sums the inputs together and outputs $1$ if the
input exceeds some threshold.
\begin{tikzpicture}
\node[textbox] (x11) {$x_1$};
\node[simplebox, right=of x11] (n1) {$x$};
\node[textbox, above=of n1, halfvdistance] (w1) {$w_1$};
\path[edgepath]
(x11) edge node {} (n1)
(w1) edge node {} (n1);
\node[textbox, below=of x11] (x1m) {$x_m$};
\node[simplebox, right=of x1m] (nm) {$x$};
\node[textbox, between=nm and n1] (wm) {$w_m$};
\node[simplebox, right=of n1, between=nm and n1] (sigma1) {$\Sigma$};
\node[simplebox, right=of sigma1] (threshold1) {threshold};
\node[textbox, right=of threshold1] (z) {z};
\draw[edgepath]
(x1m) edge node {} (nm)
(wm) edge node {} (nm)
(sigma1) edge node {} (threshold1)
(threshold1) edge node {} (z);
\draw[edgepath]
(n1) -| ++(0.7cm,-\nodedv) -- (sigma1);
\draw[edgepath]
(nm) -| ++(0.7cm,\nodedv) -- (sigma1);
\end{tikzpicture}
This models the following properties:
\begin{itemize}
\item All or non
\item Cumulative influence
\item Synaptic weight
\end{itemize}
But there are more properties that we might like to model, like:
\begin{itemize}
\item Refractory period, recovery time of each neuron.
\item Axonal bifurcation, each pulse will either go down one branch of
the axon or the other.
\item Time patterns, we don't know if the timing of when impulses hit
neurons matters.
\end{itemize}
So we actually don't know if what we are modelling is the essence of how
neurons work or not. But we will start with the simple model.
If we look at what a neural net actually is, then it's a vector of input
that goes through a ``box'' which uses some weights and threshold and then
outputs some vector $z$. Formally: $z = f(x,w,t)$. So the neural network is
just the function $f$, when we train the neural net, all we need to do is
change the weights and threshold. We can also think of the neural net as a
``function approximator''.
So, how do we measure the performance of the neural network? If we say the
desired result of the neural net $d$ is the function $g$ on the input
$x$, $d=g(x)$, then it would be natural to define the performance as:
$P=\|d-z\|$, this turns out to be mathematically inconvenient so instead we
will use the performance indicator: $P=\|d-z\|^2$.
What we want to do, is of course to maximize the performance. We can do
this using gradient descent, for example for the weights $w_1$ and $w_2$:
\begin{equation*}
\Delta w= \eta \left(\frac{\partial P}{\partial w_1}i+\frac{\partial
P}{\partial w_2}j\right)
\end{equation*}
Unfortunately, the function is not linear, and thus gradient descent
doesn't really work. This was an issue for a long time untill Paul Werbos
figure it out.
First of all, those thresholds are annoying as they are just extra baggage,
so we would like to reduce $z$ to be a function of just the inputs and
weights:
\begin{equation*}
z=f(x,w)
\end{equation*}
So what he proposed instead, was adding the bias input to each neuron $w_0$
which is always set to $1$.
\begin{tikzpicture}
\node[textbox, right=of n1, abovebetween] (w0) {$w_0$};
\node[textbox, right=of w0, yshift=0.5cm, xshift=-0.5cm] (b1) {$1$};
\node[textbox] (x11) {$x_1$};
\node[simplebox, right=of x11] (n1) {$x$};
\node[textbox, above=of n1, halfvdistance] (w1) {$w_1$};
\path[edgepath]
(x11) edge node {} (n1)
(w1) edge node {} (n1);
\node[textbox, below=of x11] (x1m) {$x_m$};
\node[simplebox, right=of x1m] (nm) {$x$};
\node[textbox, between=nm and n1] (wm) {$w_m$};
\node[simplebox, right=of n1, between=nm and n1] (sigma1)
{$\Sigma$};
\node[simplebox, right=of sigma1] (threshold1) {threshold};
\node[textbox, right=of threshold1] (z) {z};
\draw[edgepath]
(x1m) edge node {} (nm)
(wm) edge node {} (nm)
(sigma1) edge node {} (threshold1)
(threshold1) edge node {} (z)
(b1) edge node {} (w0);
\draw[edgepath]
(n1) -| ++(\nodedh,-\nodedv) -- (sigma1);
\draw[edgepath]
(nm) -| ++(\nodedh,\nodedv) -- (sigma1);
\draw[edgepath]
(w0) -| ++(-\nodedh,-\nodedv) -- (sigma1);
\end{tikzpicture}
And then we let $w_0=\text{threshold}$, then the threshold is effectively
$1$.\todo{revisit}
Step two, is to smooth the threshold function, which we could do by
applying the sigmoid function $\sigma(\alpha)=\frac{1}{1+e^{-\alpha}}$.
Then it will be $1$ if $\alpha$ is very big, and $0$ if $\alpha$ is very
small.
\sigmoidPlot
The generalized term ``activation function'' $\phi$ is in this case
$\sigma$, our
function is linear and we can take the partial derivatives to the
function. Now, suppose we have a very simple neural network:
\begin{tikzpicture}
\node[textbox] (x11) {$x_1$};
\node[simplebox, right=of x11] (n1) {$x$};
\node[textbox, above=of n1, halfvdistance] (w1) {$w_1$};
\node[simplebox, right=of n1] (sigmoid1) {sigmoid};
\path[edgepath]
(x11) edge node {} (n1)
(w1) edge node {} (n1)
(n1) edge node[above] {$P_1$} (sigmoid1);
\node[simplebox, right=of sigmoid1] (n2) {$x$};
\node[textbox, above=of n2, halfvdistance] (w2) {$w_2$};
\node[simplebox, right=of n2] (sigmoid2) {sigmoid};
\path[edgepath]
(sigmoid1) edge node[above] {y} (n2)
(w2) edge node {} (n2)
(n2) edge node[above] {$P_2$} (sigmoid2);
\node[textbox, right=of sigmoid2] (z) {z};
\path[edgepath]
(sigmoid2) edge node {} (z);
\end{tikzpicture}
Now we want to re-write the partial derivative using the chain rule:
\begin{equation*}
\frac{\partial P}{\partial w_2} = \frac{\partial P}{\partial z}
\frac{\partial z}{\partial w_2} = \frac{\partial P}{\partial z}
\frac{\partial z}{\partial p_2} \frac{\partial p_2}{\partial w_2}
\end{equation*}
We can do the same thing for $w_2$:
\begin{equation*}
\frac{\partial P}{\partial w_1} = \frac{\partial P}{\partial z}
\frac{\partial z}{\partial p_2} \frac{\partial p_2}{\partial y}
\frac{\partial y}{\partial p_1} \frac{\partial p_1}{\partial w_1}
\end{equation*}
We can rewrite these two products as:
\begin{align*}
\frac{\partial P}{\partial w_2}&= \frac{\partial p_2}{\partial w_2}
\frac{\partial z}{\partial p_2} \frac{\partial P}{\partial z}\\
\frac{\partial P}{\partial w_1}&=\frac{\partial p_1}{\partial w_1}
\frac{\partial y}{\partial p_1} \frac{\partial p_2}{\partial y}
\frac{\partial z}{\partial p_2} \frac{\partial P}{\partial z}
\end{align*}
Now we can compute the derivatives, in this example, the resulting
performance $P$ is:
\begin{equation*}
P=\frac{1}{2}(d-z)^2
\end{equation*}
And thus we can compute
\begin{equation*}
\frac{\partial P}{\partial w_2}= \frac{\partial p_2}{\partial w_2}
\frac{\partial z}{\partial p_2} (d-z)
\end{equation*}
$p_2$ is simply $p_2 w_2$ so we get:
\begin{equation*}
\frac{\partial P}{\partial w_2}= y
\frac{\partial z}{\partial p_2} (d-z)
\end{equation*}
Finally the derivative of the sigmoid function is simple:
\begin{equation*}
\frac{\partial P}{\partial w_2}= y
(1-\sigma(\alpha))\sigma(\alpha) (d-z)
\end{equation*}
In this case the output of the $\sigma$ is $z$ so:
\begin{equation*}
\frac{\partial P}{\partial w_2}= y
(1-z)z (d-z)
\end{equation*}
Now if we look at the derivative for $\frac{\partial P}{\partial w_1}$, it
turns out that the last two elements we needed to compute, was the same as
the last two elements in the computation of $\frac{\partial P}{\partial
w_2}$! So if we make a neural network, where each ``column of neurons'' or
layer is densely connected, i.e. each output from the previous layer
connects to each input from the next layer, then even though the amount of
connections increases exponentially, the computation of the derivatives do
not!
The thing to note here, is that the output of layer $i$ has to go through
layer $i+1$ in order to affect the performance indicator. So the derivative
for layer $i$ can re-use computation from the derivative of $i+1$. So the
amount of work we are gonna have to do will be:
\begin{itemize}
\item Linear in depth
\item With respect to width it, it will be proportional to the number
of connections and thus depends on $w^2$
\end{itemize}
This is the foundation for the backpropagation algorithm, and why neural
networks can efficiently learn.
\subsection{Notation}
\begin{itemize}
\item $n_l$ is the number of layers.
\item $s_l$ is the number of nodes in layer $l$ (not counting the bias
unit)
\item $L_l$ is layer $l$.
\item $L_0$ is the input layer, $L_{n_l}$ is the output layer
\item $W_{ij}^{(l)}$ is the weight associated with the connection
between unit $j$ in layer $l$ and unit $i$ in layer $l+1$
\item $b_i^{(l)}$ is the bias associated with unit $i$ in layer $l+1$
\item $a_i^{(l)}$ is the activation (or the output value) of unit $i$
in layer $l$. For $l=1$ we use $a_i^{(1)}=x_i$
\item $z_i^{(l)}=\sum_{j=1}^{n}W_{ij}^{(l)}x_j+b_i^{(l)}$ is a
convenience notation such that $a_i^{(l)}=\phi(z_i^{(l)})$
\end{itemize}
Let's look at this example network:
\begin{tikzpicture}
\node[inputnode] (x1) {$x_1$};
\node[inputnode, below=of x1] (x2) {$x_2$};
\node[inputnode, below=of x2] (x3) {$x_3$};
\node[inputnode, below=of x3] (b1) {$+1$};
\node[hiddennode, right=of x1] (h1) {};
\node[hiddennode, below=of h1] (h2) {};
\node[hiddennode, below=of h2] (h3) {};
\node[hiddennode, below=of h3] (b2) {$+1$};
\node[outputnode, right=of h1, between=h2 and h3] (o1) {};
\node[right=of o1] (o) {};
\path[edgepath]
(x1) edge node {} (h1)
(x1) edge node {} (h2)
(x1) edge node {} (h3)
(x2) edge node {} (h1)
(x2) edge node {} (h2)
(x2) edge node {} (h3)
(x3) edge node {} (h1)
(x3) edge node {} (h2)
(x3) edge node {} (h3)
(b1) edge node {} (h1)
(b1) edge node {} (h2)
(b1) edge node {} (h3)
(h1) edge node {$a_1^{(2)}$} (o1)
(h2) edge node {$a_2^{(2)}$} (o1)
(h3) edge node {$a_3^{(2)}$} (o1)
(b2) edge node {} (o1)
(o1) edge node[below] {$h_{W,b}(x)$} (o);
\end{tikzpicture}
This neural network represents the following computation:
\begin{align*}
a_1^{(2)} &=
\phi\left(W_{11}^{(1)}x_1+W_{12}^{(1)}x_2+W_{13}^{(1)}x_3+b_1^{(1)}\right)\\
a_2^{(2)} &=
\phi\left(W_{21}^{(1)}x_1+W_{22}^{(1)}x_2+W_{23}^{(1)}x_3+b_2^{(1)}\right)\\
a_3^{(2)} &=
\phi\left(W_{31}^{(1)}x_1+W_{32}^{(1)}x_2+W_{33}^{(1)}x_3+b_3^{(1)}\right)\\
h_{W,b}(x) &=
a_1^{(3)}=\phi\left(W_{11}^{(2)}a_1^{(2)}+W_{12}^{(2)}a_2^{(2)}+W_{13}^{(2)}a_3^{(2)}\right)
\end{align*}
If we extend the activation function, to work on vectors such that
$f([z_1,z_2,z_3])=\left[f(z_1), f(z_2), f(z_3)\right]$ then we can write
the previous equation in a more compact fashion:
\begin{align*}
z^{(2)}&=W^{(1)}x+b^{(1)}\\
a^{(2)}&=\phi\left(z^{(2)}\right)\\
z^{(3)}&=W^{(2)}a^{(2)}+b^{(2)}\\
h_{W,b}(x)&=a^{(3)}=\phi\left(z^{(3)}\right)
\end{align*}
Which can be generalized to:
\begin{align*}
z^{(l+1)}&=W^{(l)}a^{(l)}+b^{(l)}\\
a^{(l+1)}&=\phi\left(z^{(l+1)}\right)
\end{align*}
The most common neural networks, are $n_l$-layered networks where $L_1$ is
the input, $L_{n_l}$ the output and $L_i$ is densely connected to
$L_{i+1}$. In order to compute the output, we would simply have to compute
the activation of $L_2$, $L_3$ etc. up to layer $L_{n_l}$, this is an
example of a \textbf{feedforward} neural network, as there are no loops or
cycles.
\subsection{Backpropagation}
Suppose we have a training set $D = \{(x_1,y_1),\dots,(x_m,y_m)\}$, we can
then train our neural network with batch gradient descent, with the cost
function for single sample as:
\begin{equation*}
J(W,b;x,y)=\frac{1}{2}\|h_{W,b}(x)-y\|^2
\end{equation*}
This is simply a (one-half) squared-error cost function. The overall cost
function is then defined to be:
\begin{equation*}
J(W,b) =
\frac{1}{|D|}\sum_{i=1}^{|D|}\left(\frac{1}{2}\|h_{W,b}(x_i)-y_i\|^2\right)
\end{equation*}
If we add a weight decay term for regularization, then it becomes:
\begin{equation*}
J(W,b)=\frac{1}{|D|}\sum_{i=1}^{|D|}\left(\frac{1}{2}\|h_{W,b}(x_i)-y_i\|^2\right)
+ \frac{\lambda}{2}
\sum_{l=1}^{n_l-1}\sum_{i=1}^{s_l}\sum_{j=1}^{s_{l+1}}\left(W_{ji}^{(l)}\right)^2
\end{equation*}
Our goal now, is to minimize $J(W,b)$. To train our neural network, we will
initialize each parameter $W_{ij}^{(l)}$ and each $b_i^{(l)}$ to a small
random value near zero. If they are all the same value (e.g. $0$) then they
will end up learning the same function such that
$a_1^{(2)}=a_2^{(2)}=a_3^{(2)}=\dots$ for any input $x$.
Each iteration of gradient descent then updates the parameters $W,b$ as
follows:
\begin{align*}
W_{ij}^{(l)}&=W_{ij}^{(l)}-\eta \frac{\partial}{\partial
W_{ij}^{(l)}}J(W,b)\\
b_i^{(l)}&=-\eta \frac{\partial}{\partial b_i^{(l)}}J(W,b)
\end{align*}
Seems simple right? But how do we do this efficiently? The backpropagation
algorithm is the key. The intuition is that given some training example
$(x,y)$, we want to do a ``forward pass'' which computes all the
activations throughout the network, including the output value. Then for
each node $i$ in layer $l$, we compute an ``error term'' $\delta_i^{(l)}$
which measures how much that node was ``responsible'' for any errors in the
output.
For $\delta_i^{(nl)}$ we can simply compute the difference between the
activation and the true target label $y$. For hidden units, we don't have
the ``correct answer'' so instead we compute $\delta_i^{(l)}$ based on
weighted average of the error terms of the nodes that uses $a_i^{(l)}$ as
input. So in detail:
\begin{enumerate}
\item Perform a feedforward pass, computing the activations for layers
$L_2,L_3,\dots,L_{n_l}$
\item For each output unit $i$ in layer $n_l$, set
\begin{align*}
\delta_i^{(n_l)} &= \frac{\partial}{\partial z_i^{(n_l)}}
\frac{1}{2}\|y-h_{W,b}(x)\|^2 = \frac{\partial}{\partial
z_i^{(n_l)}} \frac{1}{2}
\left(\sqrt{(y_1-z_1^{(n_l)})^2+\dots+
(y_i-z_i^{(n_l)})^2+\dots+
(y_{s_l}-z_{s_l}^{(n_l)})^2}\right)^2\\
\delta_i^{(n_l)} &= -(y_i - a_i^{(n_l)}) \cdot
\phi'(z_i^{(n_l)})\\
\end{align*}
\item For $l=n_l-1, n_l-2,\dots, 2$
For each node $i$ in $L_l$ set
\begin{equation*}
\delta_i^{(l)}=\left(\sum_{j=1}^{s_{l+1}}W_{ji}^{(l)}\delta_j^{(l+1)}\phi'(z_i^{(l)})\right)
\end{equation*}
\item We can now compute the desired partial derivatives, as:
\begin{align*}
\frac{\partial}{\partial W_{ij}^{(l)}}J(W,b;x,y) &=
a_j^{(l)}\delta_i^{(l)}\\
\frac{\partial}{\partial b_i^{(l)}}J(W,b;x,y) &= \delta_i^{(l+1)}
\end{align*}
\end{enumerate}
We can then compute the derivatives with respect to the whole data-set, for
the overall cost function, as:
\begin{align*}
\frac{\partial}{\partial W_{ij}^{(l)}} J(W,b) &=
\left[\frac{1}{|D|}\sum_{i=1}^{|D|}\frac{\partial}{\partial
W_{ij}^{(l)}} J(W,b;x_i,y_i)\right] + \lambda W_{ij}^{(l)}\\
\frac{\partial}{\partial b_i^{(l)}} J(W,b) &=
\frac{1}{|D|}\sum_{i=1}^{|D|} \frac{\partial}{\partial b_i^{(l)}}
J(W,b;x_i, y_i)
\end{align*}
Numerical differentiation takes one evaluation of the neural net per weight
(\bigO{(\#weights)^2}), now with back propagation, we simply use each edge
in each pass \bigO{\#weights}.
\subsection{Deep Nets}
Deep nets are when we have many layers of neurons. Each layer transforms
the input into a ``better'' representation, and we will just repeat this
procedure, and keep getting ``better'' representations. Historically, this
has seemed to failed, this could either be because of a bad hypothesis or
an issue with the learning algorithm.
One of the approaches to fixing this is better architecture, for example
the convolutional network. Others are much more data, or computing power or
do find better weights before we do backpropagation or maybe the field just
needs to mature.
\subsubsection{Convolutional networks}
These are useful for, for example image recognition. The building blocks of
a convolutional network are as follow:
\begin{enumerate}
\item Convolution
\item Non Linearity
\item Pooling
\item Classification (fully connected layer)
\end{enumerate}
\subsubsection{Convolution}
First of all, convolution is like sliding a window over the image and
applying some filter to it. For example we could have a simple ``filter'',
``kernel'' or ``feature detector'' which is simply a $m\times n$ matrix
which slides over the image. For example the matrix:
\begin{equation*}
\begin{pmatrix}
1 & 0\\
0 & 1
\end{pmatrix}
\end{equation*}
might slide over the input:
\begin{equation*}
\begin{pmatrix}
1 & 0 & 1\\
0 & 2 & 0\\
1 & 0 & 3
\end{pmatrix}
\end{equation*}
Since the feature detector is $2\times 2$, it will look at first top-left 4
numbers, then it will slide $1$ pixel right and look at the top-right
numbers, then the bottom-left and then the bottom right. Producing the
following ``feature map'':
\begin{equation*}
\begin{pmatrix}
1*1 + 0*0 + 0*0 + 1*2 & 1*0 + 0*1 + 0*2 + 1*0\\
1*0 + 0*2 + 0*1 + 1*0 & 1*2 + 0*1 + 0*1 + 1*3
\end{pmatrix} = \begin{pmatrix}
3 & 0\\
0 & 5
\end{pmatrix}
\end{equation*}
The size of the ``feature map'' is controlled by three parameers:
\begin{itemize}
\item Depth corresponding to the number of filters
\item Stride is the number of pixels or indices we move the feature
detector with. In the above example it was 1
\item Zero-padding, we might zero-pad in order to be able to slide the
window around the edges of the matrix as well. Zero-padded convolution
is also called \textit{wide convolution} while non-zero-padded is
called \textit{narrow convolution}
\end{itemize}
\subsubsection{Non-linearity}
The non-linearity operation aims to introduce some non-linearity into the
data, as it real world data is often non-linear. An example of such an
operation is the ReLU opeartion, which simply sets any negative elements to
$0$. The result is the Rectified Feature Map
\subsubsection{Pooling}
Pooling reduces the dimensionality of each feature map but retains the most
important information. Pooling can be done in a number of different way
like Max, Average, Sum etc. It runs a window over the rectified feature
map, and runs some function on the entries in the window. It might, for
example, output the maximum value in the window, resulting in a smaller
feature map.
\subsubsection{Fully connected layer}
The result of one or more convolution and poolings, can then be put through
the fully connected layer which will try to use the information to perform
e.g. classification, as usual.
\subsection{PCA}
PCA tries to take some data in dimension $d$ in to some dimension $k$. A
neural net autoencoder can come up with something very similar to this.
\subsection{Autoencoder}
This is an auto-encoder:
\begin{tikzpicture}[node distance = 0.2cm and 1.5cm]
\node[inputnode] (x1) {$x_1$};
\node[inputnode, below=of x1] (x2) {$x_2$};
\node[inputnode, below=of x2] (x3) {$x_3$};
\node[inputnode, below=of x3] (x4) {$x_4$};
\node[inputnode, below=of x4] (x5) {$x_5$};
\node[inputnode, below=of x5] (x6) {$x_6$};
\node[inputnode, below=of x6] (b1) {$+1$};
\node[hiddennode, right=of x1, between=x2 and x3] (h1) {};
\node[hiddennode, below=of h1] (h2) {};
\node[hiddennode, below=of h2] (h3) {};
\node[hiddennode, below=of h3] (b2) {$+1$};
\node[right=of x1] (xx1) {};
\node[outputnode, right=of xx1] (o1) {$\hat{x_1}$};
\node[right=of o1] (oo1) {};
\node[outputnode, below=of o1] (o2) {$\hat{x_2}$};
\node[right=of o2] (oo2) {};
\node[outputnode, below=of o2] (o3) {$\hat{x_3}$};
\node[right=of o3] (oo3) {};
\node[outputnode, below=of o3] (o4) {$\hat{x_4}$};
\node[right=of o4] (oo4) {};
\node[outputnode, below=of o4] (o5) {$\hat{x_5}$};
\node[right=of o5] (oo5) {};
\node[outputnode, below=of o5] (o6) {$\hat{x_6}$};
\node[right=of o6] (oo6) {};
\node[textbox, right=of oo1, between=o3 and o4] (t) {$h_{W,b}(x)$};
\path[edgepath]
(x1) edge node {} (h1)
(x1) edge node {} (h2)
(x1) edge node {} (h3)
(x2) edge node {} (h1)
(x2) edge node {} (h2)
(x2) edge node {} (h3)
(x3) edge node {} (h1)
(x3) edge node {} (h2)
(x3) edge node {} (h3)
(x4) edge node {} (h1)
(x4) edge node {} (h2)
(x4) edge node {} (h3)
(x5) edge node {} (h1)
(x5) edge node {} (h2)
(x5) edge node {} (h3)
(x6) edge node {} (h1)
(x6) edge node {} (h2)
(x6) edge node {} (h3)
(b1) edge node {} (h1)
(b1) edge node {} (h2)
(b1) edge node {} (h3)
(h1) edge node {} (o1)
(h2) edge node {} (o1)
(h3) edge node {} (o1)
(h1) edge node {} (o2)
(h2) edge node {} (o2)
(h3) edge node {} (o2)
(h1) edge node {} (o3)
(h2) edge node {} (o3)
(h3) edge node {} (o3)
(h1) edge node {} (o4)
(h2) edge node {} (o4)
(h3) edge node {} (o4)
(h1) edge node {} (o5)
(h2) edge node {} (o5)
(h3) edge node {} (o5)
(h1) edge node {} (o6)
(h2) edge node {} (o6)
(h3) edge node {} (o6)
(b2) edge node {} (o1)
(b2) edge node {} (o2)
(b2) edge node {} (o3)
(b2) edge node {} (o4)
(b2) edge node {} (o5)
(b2) edge node {} (o6)
(o1) edge node {} (oo1)
(o2) edge node {} (oo2)
(o3) edge node {} (oo3)
(o4) edge node {} (oo4)
(o5) edge node {} (oo5)
(o6) edge node {} (oo6);
\end{tikzpicture}
The autoencoder tries to learn a function $h_{W,b}\approx x$, i.e. it takes
the input and tries to re-create it. This can be useful, as it effectively
tries to learn what features in the data is important if I have to know the
difference between two inputs but I can only do it in e.g. half the space.
So if there some of the input features are correlated, then this algorithm
will be able to discover some of those correlations. In fact it often ends
up learning a low-dimensional representation very similar to PCA's.
\subsection{Regularization}
We introduced weight decay regularization already, another good way to
regularize neural networks is the simple ``dropout'' technique, which
simply means that we ignore the output of some random neurons. This forces
the hidden neurons to be robust and approcimates averaging of exponentially
many models.
\subsection{Finding a good local minimum}
Our neural network is riddled with local minimum, so in order to find a
good local minimum, we will simply start the gradient descent from many
different starting points, so we end up in different local minimums and
choose the best one, hoping that it is a global minimum.
\end{document} |
function t = full(t)
%FULL Convert a ktensor to a (dense) tensor.
%
% T = FULL(C) converts a ktensor to a (dense) tensor.
%
% Examples
% X = ktensor([3; 2], rand(4,2), rand(5,2), rand(3,2));
% Y = full(A) %<-- equivalent dense tensor
%
% See also KTENSOR, TENSOR, KTENSOR/DOUBLE.
%
%MATLAB Tensor Toolbox.
%Copyright 2015, Sandia Corporation.
% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.
% http://www.sandia.gov/~tgkolda/TensorToolbox.
% Copyright (2015) Sandia Corporation. Under the terms of Contract
% DE-AC04-94AL85000, there is a non-exclusive license for use of this
% work by or on behalf of the U.S. Government. Export of this data may
% require a license from the United States Government.
% The full license terms can be found in the file LICENSE.txt
sz = size(t);
data = t.lambda' * khatrirao(t.u,'r')';
t = tensor(data,sz);
|
[STATEMENT]
lemma (in CRR_market) bernoulli_cond_exp:
assumes "N = bernoulli_stream q"
and "0 < q"
and "q < 1"
and "integrable N X"
shows "real_cond_exp N (stoch_proc_filt N geom_proc borel n) X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. real_cond_exp N (stoch_proc_filt N geom_proc borel n) X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. real_cond_exp N (stoch_proc_filt N geom_proc borel n) X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w
[PROOF STEP]
have aeq: "AE w in N. real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)) X w =
expl_cond_expect N (proj_stoch_proc geom_proc n) X w"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. AEeq N (real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)) X) (expl_cond_expect N (proj_stoch_proc geom_proc n) X)
[PROOF STEP]
using assms
bernoulli_AE_cond_exp
[PROOF STATE]
proof (prove)
using this:
N = bernoulli_stream q
0 < q
q < 1
integrable N X
\<lbrakk>?N = bernoulli_stream ?q; 0 < ?q; ?q < 1; integrable ?N ?X\<rbrakk> \<Longrightarrow> AEeq ?N (real_cond_exp ?N (fct_gen_subalgebra ?N (stream_space borel) (proj_stoch_proc geom_proc ?n)) ?X) (expl_cond_expect ?N (proj_stoch_proc geom_proc ?n) ?X)
goal (1 subgoal):
1. AEeq N (real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)) X) (expl_cond_expect N (proj_stoch_proc geom_proc n) X)
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
AEeq N (real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)) X) (expl_cond_expect N (proj_stoch_proc geom_proc n) X)
goal (1 subgoal):
1. real_cond_exp N (stoch_proc_filt N geom_proc borel n) X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w
[PROOF STEP]
have "\<forall>w. real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n))
X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>w. real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)) X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w
[PROOF STEP]
using assms bernoulli_real_cond_exp_AE
[PROOF STATE]
proof (prove)
using this:
N = bernoulli_stream q
0 < q
q < 1
integrable N X
\<lbrakk>?N = bernoulli_stream ?q; 0 < ?q; ?q < 1; integrable ?N ?X\<rbrakk> \<Longrightarrow> real_cond_exp ?N (fct_gen_subalgebra ?N (stream_space borel) (proj_stoch_proc geom_proc ?n)) ?X ?w = expl_cond_expect ?N (proj_stoch_proc geom_proc ?n) ?X ?w
goal (1 subgoal):
1. \<forall>w. real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)) X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<forall>w. real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)) X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w
goal (1 subgoal):
1. real_cond_exp N (stoch_proc_filt N geom_proc borel n) X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
\<forall>w. real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)) X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w
goal (1 subgoal):
1. real_cond_exp N (stoch_proc_filt N geom_proc borel n) X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w
[PROOF STEP]
have "stoch_proc_filt N geom_proc borel n = fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. stoch_proc_filt N geom_proc borel n = fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)
[PROOF STEP]
using assms geom_proc_stoch_proc_filt
[PROOF STATE]
proof (prove)
using this:
N = bernoulli_stream q
0 < q
q < 1
integrable N X
\<lbrakk>?N = bernoulli_stream ?q; 0 < ?q; ?q < 1\<rbrakk> \<Longrightarrow> stoch_proc_filt ?N geom_proc borel ?n = fct_gen_subalgebra ?N (stream_space borel) (proj_stoch_proc geom_proc ?n)
goal (1 subgoal):
1. stoch_proc_filt N geom_proc borel n = fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
stoch_proc_filt N geom_proc borel n = fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)
goal (1 subgoal):
1. real_cond_exp N (stoch_proc_filt N geom_proc borel n) X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
\<forall>w. real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)) X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w
stoch_proc_filt N geom_proc borel n = fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
\<forall>w. real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)) X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w
stoch_proc_filt N geom_proc borel n = fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)
goal (1 subgoal):
1. real_cond_exp N (stoch_proc_filt N geom_proc borel n) X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
real_cond_exp N (stoch_proc_filt N geom_proc borel n) X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w
goal:
No subgoals!
[PROOF STEP]
qed |
module TyTTP.Core.Promise
import Control.Monad.Trans
public export
record Callbacks e (m : Type -> Type) a where
constructor MkCallbacks
onSucceded : a -> m ()
onFailed : e -> m ()
public export
record Promise e (m : Type -> Type) a where
constructor MkPromise
continuation : Callbacks e m a -> m ()
export
Functor (Promise e m) where
map f (MkPromise ca) = MkPromise $ \cb => ca $ MkCallbacks (cb.onSucceded . f) cb.onFailed
mutual
export
Applicative (Promise e m) where
pure a = MkPromise $ \cb => cb.onSucceded a
fn <*> pa = fn >>= \f => map f pa
export
Monad (Promise e m) where
(>>=) (MkPromise conta) f = MkPromise $ \cb => conta $ MkCallbacks
{ onSucceded = \a =>
let MkPromise contb = f a
in contb cb
, onFailed = cb.onFailed
}
export
MonadTrans (Promise e) where
lift ma = MkPromise $ \cb => ma >>= cb.onSucceded
export
HasIO m => HasIO (Promise e m) where
liftIO = lift . liftIO
export
fail : e -> Promise e m a
fail e = MkPromise $ \cb => cb.onFailed e
|
(* Title: HOL/Library/List_Lenlexorder.thy
*)
section \<open>Lexicographic order on lists\<close>
theory List_Lenlexorder
imports Main
begin
instantiation list :: (ord) ord
begin
definition
list_less_def: "xs < ys \<longleftrightarrow> (xs, ys) \<in> lenlex {(u, v). u < v}"
definition
list_le_def: "(xs :: _ list) \<le> ys \<longleftrightarrow> xs < ys \<or> xs = ys"
instance ..
end
instance list :: (order) order
proof
have tr: "trans {(u, v::'a). u < v}"
using trans_def by fastforce
have \<section>: False
if "(xs,ys) \<in> lenlex {(u, v). u < v}" "(ys,xs) \<in> lenlex {(u, v). u < v}" for xs ys :: "'a list"
proof -
have "(xs,xs) \<in> lenlex {(u, v). u < v}"
using that transD [OF lenlex_transI [OF tr]] by blast
then show False
by (meson case_prodD lenlex_irreflexive less_irrefl mem_Collect_eq)
qed
show "xs \<le> xs" for xs :: "'a list" by (simp add: list_le_def)
show "xs \<le> zs" if "xs \<le> ys" and "ys \<le> zs" for xs ys zs :: "'a list"
using that transD [OF lenlex_transI [OF tr]] by (auto simp add: list_le_def list_less_def)
show "xs = ys" if "xs \<le> ys" "ys \<le> xs" for xs ys :: "'a list"
using \<section> that list_le_def list_less_def by blast
show "xs < ys \<longleftrightarrow> xs \<le> ys \<and> \<not> ys \<le> xs" for xs ys :: "'a list"
by (auto simp add: list_less_def list_le_def dest: \<section>)
qed
instance list :: (linorder) linorder
proof
fix xs ys :: "'a list"
have "total (lenlex {(u, v::'a). u < v})"
by (rule total_lenlex) (auto simp: total_on_def)
then show "xs \<le> ys \<or> ys \<le> xs"
by (auto simp add: total_on_def list_le_def list_less_def)
qed
instantiation list :: (linorder) distrib_lattice
begin
definition "(inf :: 'a list \<Rightarrow> _) = min"
definition "(sup :: 'a list \<Rightarrow> _) = max"
instance
by standard (auto simp add: inf_list_def sup_list_def max_min_distrib2)
end
lemma not_less_Nil [simp]: "\<not> x < []"
by (simp add: list_less_def)
lemma Nil_less_Cons [simp]: "[] < a # x"
by (simp add: list_less_def)
lemma Cons_less_Cons: "a # x < b # y \<longleftrightarrow> length x < length y \<or> length x = length y \<and> (a < b \<or> a = b \<and> x < y)"
using lenlex_length
by (fastforce simp: list_less_def Cons_lenlex_iff)
lemma le_Nil [simp]: "x \<le> [] \<longleftrightarrow> x = []"
unfolding list_le_def by (cases x) auto
lemma Nil_le_Cons [simp]: "[] \<le> x"
unfolding list_le_def by (cases x) auto
lemma Cons_le_Cons: "a # x \<le> b # y \<longleftrightarrow> length x < length y \<or> length x = length y \<and> (a < b \<or> a = b \<and> x \<le> y)"
by (auto simp: list_le_def Cons_less_Cons)
instantiation list :: (order) order_bot
begin
definition "bot = []"
instance
by standard (simp add: bot_list_def)
end
end
|
Closed February 2012
http://dixon.patch.com/articles/chevysfreshmexclosesitsdoorsindixon
Chevys is a Dixon restaurants restaurant in Dixon. It is a Southwestern style restaurant chain. Most of the restaurants are owned by the company, but some are locally owned by franchisees.
Chevys is owned by Real Mex Restaurants (which also owns Acapulco, and El Torito) of Long Beach, California. Real Mex used to own Fuzio, but sold them to Calmex, Inc.
20071009 23:14:52 nbsp A notice in the 20070531 Davis Enterprise, p. B5 suggests that they are owned by Calmex, Inc. It seems that a restaurant at 500 1st St. #11 is applying for an alcohol license. Users/SteveDavison
20080804 22:32:44 nbsp i work here. fuzio is no longer in our chain of restaraunts.
Users/NoraSandstedt
20080804 22:36:07 nbsp we also have happy hour monday through thursday from four to seven, and there is talk of starting karaoke nights weekly. Users/NoraSandstedt
|
(** * Algebra I. Part D. Rigs and rings. Vladimir Voevodsky. Aug. 2011 - . *)
Require Import UniMath.Algebra.Groups.
(** Contents
- Standard Algebraic Structures
- Rigs - semirings with 1, 0, and x * 0 = 0 * x = 0
- General definitions
- Homomorphisms of rigs (rig functions)
- Relations similar to "greater" or "greater or equal" on rigs
- Subobjects
- Quotient objects
- Direct products
- Opposite rigs
- Nonzero rigs
- Group of units
- Commutative rigs
- General definitions
- Relations similar to "greater" on commutative rigs
- Subobjects
- Quotient objects
- Direct products
- Opposite commutative rigs
- Rings
- General definitions
- Homomorphisms of rings
- Computation lemmas for rings
- Relations compatible with the additive structure on rings
- Relations compatible with the multiplicative structure on rings
- Relations "inversely compatible" with the multiplicative structure
on rings
- Relations on rings and ring homomorphisms
- Subobjects
- Quotient objects
- Direct products
- Opposite rings
- Ring of differences associated with a rig
- Canonical homomorphism to the ring associated with a rig (ring of
differences)
- Relations similar to "greater" or "greater or equal" on the ring
associated with a rig
- Relations and the canonical homomorphism to the ring associated
with a rig (ring of differences)
- Commutative rings
- General definitions
- Computational lemmas for commutative rings
- Subobjects
- Quotient objects
- Direct products
- Opposite commutative rings
- Commutative rigs to commutative rings
- Rings of fractions
- Canonical homomorphism to the ring of fractions
- Ring of fractions in the case when all elements which are being
inverted are cancelable
- Relations similar to "greater" or "greater or equal" on the rings
of fractions
- Relations and the canonical homomorphism to the ring of fractions
*)
(** ** Preamble *)
(** Settings *)
Unset Kernel Term Sharing.
(** Imports *)
Require Import UniMath.MoreFoundations.Sets.
Require Import UniMath.MoreFoundations.Orders.
Require Export UniMath.Algebra.Monoids.
Local Open Scope logic.
(** To upstream files *)
(** ** Standard Algebraic Structures (cont.) *)
(** *** Rigs - semirings with 1, 0 and x * 0 = 0 * x = 0 *)
(** **** General definitions *)
Definition rig : UU := total2 (λ X : setwith2binop, isrigops (@op1 X) (@op2 X)).
Definition make_rig {X : setwith2binop} (is : isrigops (@op1 X) (@op2 X)) : rig :=
tpair (λ X : setwith2binop, isrigops (@op1 X) (@op2 X)) X is.
Definition pr1rig : rig -> setwith2binop :=
@pr1 _ (λ X : setwith2binop, isrigops (@op1 X) (@op2 X)).
Coercion pr1rig : rig >-> setwith2binop.
Definition rigaxs (X : rig) : isrigops (@op1 X) (@op2 X) := pr2 X.
Definition rigop1axs (X : rig) : isabmonoidop (@op1 X) := rigop1axs_is (pr2 X).
Definition rigassoc1 (X : rig) : isassoc (@op1 X) := assocax_is (rigop1axs X).
Definition rigunel1 {X : rig} : X := unel_is (rigop1axs X).
Definition riglunax1 (X : rig) : islunit op1 (@rigunel1 X) := lunax_is (rigop1axs X).
Definition rigrunax1 (X : rig) : isrunit op1 (@rigunel1 X) := runax_is (rigop1axs X).
Definition rigmult0x (X : rig) : ∏ x : X, paths (op2 (@rigunel1 X) x) (@rigunel1 X) :=
rigmult0x_is (pr2 X).
Definition rigmultx0 (X : rig) : ∏ x : X, paths (op2 x (@rigunel1 X)) (@rigunel1 X) :=
rigmultx0_is (pr2 X).
Definition rigcomm1 (X : rig) : iscomm (@op1 X) := commax_is (rigop1axs X).
Definition rigop2axs (X : rig) : ismonoidop (@op2 X) := rigop2axs_is (pr2 X).
Definition rigassoc2 (X : rig) : isassoc (@op2 X) := assocax_is (rigop2axs X).
Definition rigunel2 {X : rig} : X := unel_is (rigop2axs X).
Definition riglunax2 (X : rig) : islunit op2 (@rigunel2 X) := lunax_is (rigop2axs X).
Definition rigrunax2 (X : rig) : isrunit op2 (@rigunel2 X) := runax_is (rigop2axs X).
Definition rigdistraxs (X : rig) : isdistr (@op1 X) (@op2 X) := pr2 (pr2 X).
Definition rigldistr (X : rig) : isldistr (@op1 X) (@op2 X) := pr1 (pr2 (pr2 X)).
Definition rigrdistr (X : rig) : isrdistr (@op1 X) (@op2 X) := pr2 (pr2 (pr2 X)).
Definition rigconstr {X : hSet} (opp1 opp2 : binop X) (ax11 : ismonoidop opp1)
(ax12 : iscomm opp1) (ax2 : ismonoidop opp2)
(m0x : ∏ x : X, paths (opp2 (unel_is ax11) x) (unel_is ax11))
(mx0 : ∏ x : X, paths (opp2 x (unel_is ax11)) (unel_is ax11))
(dax : isdistr opp1 opp2) : rig.
Proof.
intros. split with (make_setwith2binop X (make_dirprod opp1 opp2)). split.
- split with (make_dirprod (make_dirprod ax11 ax12) ax2).
apply (make_dirprod m0x mx0).
- apply dax.
Defined.
Definition rigaddabmonoid (X : rig) : abmonoid :=
make_abmonoid (make_setwithbinop X op1) (rigop1axs X).
Definition rigmultmonoid (X : rig) : monoid := make_monoid (make_setwithbinop X op2) (rigop2axs X).
Declare Scope rig_scope.
Notation "x + y" := (op1 x y) : rig_scope.
Notation "x * y" := (op2 x y) : rig_scope.
Notation "0" := (rigunel1) : rig_scope.
Notation "1" := (rigunel2) : rig_scope.
Delimit Scope rig_scope with rig.
(** **** Homomorphisms of rigs (rig functions) *)
Definition isrigfun {X Y : rig} (f : X -> Y) : UU :=
dirprod (@ismonoidfun (rigaddabmonoid X) (rigaddabmonoid Y) f)
(@ismonoidfun (rigmultmonoid X) (rigmultmonoid Y) f).
Definition make_isrigfun {X Y : rig} {f : X -> Y}
(H1 : @ismonoidfun (rigaddabmonoid X) (rigaddabmonoid Y) f)
(H2 : @ismonoidfun (rigmultmonoid X) (rigmultmonoid Y) f) : isrigfun f :=
make_dirprod H1 H2.
Definition isrigfunisaddmonoidfun {X Y : rig} {f : X -> Y} (H : isrigfun f) :
@ismonoidfun (rigaddabmonoid X) (rigaddabmonoid Y) f := dirprod_pr1 H.
Definition isrigfunismultmonoidfun {X Y : rig} {f : X -> Y} (H : isrigfun f) :
@ismonoidfun (rigmultmonoid X) (rigmultmonoid Y) f := dirprod_pr2 H.
Lemma isapropisrigfun {X Y : rig} (f : X -> Y) : isaprop (isrigfun f).
Proof.
use isapropdirprod.
- use isapropismonoidfun.
- use isapropismonoidfun.
Defined.
Opaque isapropisrigfun.
Definition rigfun (X Y : rig) : UU := total2 (fun f : X -> Y => isrigfun f).
Definition isasetrigfun (X Y : rig) : isaset (rigfun X Y).
Proof.
use isaset_total2.
- use isaset_set_fun_space.
- intros x. use isasetaprop. use isapropisrigfun.
Defined.
Opaque isasetrigfun.
Definition rigfunconstr {X Y : rig} {f : X -> Y} (is : isrigfun f) : rigfun X Y := tpair _ f is.
Definition pr1rigfun (X Y : rig) : rigfun X Y -> (X -> Y) := @pr1 _ _.
Coercion pr1rigfun : rigfun >-> Funclass.
Definition rigaddfun {X Y : rig} (f : rigfun X Y) :
monoidfun (rigaddabmonoid X) (rigaddabmonoid Y) := monoidfunconstr (pr1 (pr2 f)).
Definition rigmultfun {X Y : rig} (f : rigfun X Y) :
monoidfun (rigmultmonoid X) (rigmultmonoid Y) := monoidfunconstr (pr2 (pr2 f)).
Definition rigfun_to_unel_rigaddmonoid {X Y : rig} (f : rigfun X Y) : f (0%rig) = 0%rig :=
pr2 (pr1 (pr2 f)).
Definition rigfuncomp {X Y Z : rig} (f : rigfun X Y) (g : rigfun Y Z) : rigfun X Z.
Proof.
use rigfunconstr.
- exact (g ∘ f).
- use make_isrigfun.
+ exact (pr2 (monoidfuncomp (rigaddfun f) (rigaddfun g))).
+ exact (pr2 (monoidfuncomp (rigmultfun f) (rigmultfun g))).
Defined.
Lemma rigfun_paths {X Y : rig} (f g : rigfun X Y) (e : pr1 f = pr1 g) : f = g.
Proof.
use total2_paths_f.
- exact e.
- use proofirrelevance. use isapropisrigfun.
Defined.
Opaque rigfun_paths.
Definition rigiso (X Y : rig) : UU := total2 (λ f : X ≃ Y, isrigfun f).
Definition make_rigiso {X Y : rig} (f : X ≃ Y) (is : isrigfun f) : rigiso X Y := tpair _ f is.
Definition pr1rigiso (X Y : rig) : rigiso X Y -> X ≃ Y := @pr1 _ _.
Coercion pr1rigiso : rigiso >-> weq.
Definition rigisoisrigfun {X Y : rig} (f : rigiso X Y) : isrigfun f := pr2 f.
Definition rigaddiso {X Y : rig} (f : rigiso X Y) :
monoidiso (rigaddabmonoid X) (rigaddabmonoid Y) :=
@make_monoidiso (rigaddabmonoid X) (rigaddabmonoid Y) (pr1 f) (pr1 (pr2 f)).
Definition rigmultiso {X Y : rig} (f : rigiso X Y) :
monoidiso (rigmultmonoid X) (rigmultmonoid Y) :=
@make_monoidiso (rigmultmonoid X) (rigmultmonoid Y) (pr1 f) (pr2 (pr2 f)).
Definition rigiso_paths {X Y : rig} (f g : rigiso X Y) (e : pr1 f = pr1 g) : f = g.
Proof.
use total2_paths_f.
- exact e.
- use proofirrelevance. use isapropisrigfun.
Defined.
Opaque rigiso_paths.
Definition rigisotorigfun {X Y : rig} (f : rigiso X Y) : rigfun X Y := rigfunconstr (pr2 f).
Lemma isrigfuninvmap {X Y : rig} (f : rigiso X Y) : isrigfun (invmap f).
Proof.
intros. split.
- apply (ismonoidfuninvmap (rigaddiso f)).
- apply (ismonoidfuninvmap (rigmultiso f)).
Defined.
Definition invrigiso {X Y : rig} (f : rigiso X Y) : rigiso Y X :=
make_rigiso (invweq f) (isrigfuninvmap f).
Definition idrigiso (X : rig) : rigiso X X.
Proof.
use make_rigiso.
- exact (idweq X).
- use make_isrigfun.
+ use make_ismonoidfun.
* use make_isbinopfun.
intros x x'. use idpath.
* use idpath.
+ use make_ismonoidfun.
* use make_isbinopfun.
intros x x'. use idpath.
* use idpath.
Defined.
(** **** (X = Y) ≃ (rigiso X Y)
We use the following composition
(X = Y) ≃ (X ╝ Y)
≃ (rigiso' X Y)
≃ (rigiso X Y)
where the second weak equivalence is given by univalence for setwith2binop,
[setwith2binop_univalence]. The reason to define rigiso' is that it allows us to use
[setwith2binop_univalence].
*)
Local Definition rigiso' (X Y : rig) : UU :=
∑ D : (∑ w : X ≃ Y, istwobinopfun w),
((pr1 D) (@rigunel1 X) = @rigunel1 Y) × ((pr1 D) (@rigunel2 X) = @rigunel2 Y).
Local Definition make_rigiso' (X Y : rig) (w : X ≃ Y) (H1 : istwobinopfun w)
(H2 : w (@rigunel1 X) = @rigunel1 Y) (H3 : w (@rigunel2 X) = @rigunel2 Y) :
rigiso' X Y := tpair _ (tpair _ w H1) (make_dirprod H2 H3).
Definition rig_univalence_weq1 (X Y : rig) : (X = Y) ≃ (X ╝ Y) :=
total2_paths_equiv _ _ _.
Definition rig_univalence_weq2 (X Y : rig) : (X ╝ Y) ≃ (rigiso' X Y).
Proof.
use weqbandf.
- exact (setwith2binop_univalence X Y).
- intros e. cbn. use invweq. induction X as [X Xop]. induction Y as [Y Yop]. cbn in e.
cbn. induction e. use weqimplimpl.
+ intros i. use proofirrelevance. use isapropisrigops.
+ intros i. use make_dirprod.
* induction i. use idpath.
* induction i. use idpath.
+ use isapropdirprod.
* use setproperty.
* use setproperty.
+ use isapropifcontr. exact (@isapropisrigops X op1 op2 Xop Yop).
Defined.
Opaque rig_univalence_weq2.
Definition rig_univalence_weq3 (X Y : rig) : (rigiso' X Y) ≃ (rigiso X Y).
Proof.
use make_weq.
- intros i'.
use make_rigiso.
+ exact (pr1 (pr1 i')).
+ use make_isrigfun.
* use make_ismonoidfun.
-- use make_isbinopfun.
exact (dirprod_pr1 (pr2 (pr1 i'))).
-- exact (dirprod_pr1 (pr2 i')).
* use make_ismonoidfun.
-- use make_isbinopfun.
exact (dirprod_pr2 (pr2 (pr1 i'))).
-- exact (dirprod_pr2 (pr2 i')).
- use isweq_iso.
+ intros i. use make_rigiso'.
* exact (pr1rigiso _ _ i).
* use make_istwobinopfun.
-- exact (ismonoidfunisbinopfun (isrigfunisaddmonoidfun (rigisoisrigfun i))).
-- exact (ismonoidfunisbinopfun (isrigfunismultmonoidfun (rigisoisrigfun i))).
* exact (ismonoidfununel (isrigfunisaddmonoidfun (rigisoisrigfun i))).
* exact (ismonoidfununel (isrigfunismultmonoidfun (rigisoisrigfun i))).
+ intros x. use idpath.
+ intros x. use idpath.
Defined.
Opaque rig_univalence_weq3.
Definition rig_univlalence_map (X Y : rig) : X = Y → rigiso X Y.
Proof.
intros e. induction e. exact (idrigiso X).
Defined.
Lemma rig_univalence_isweq (X Y : rig) : isweq (rig_univlalence_map X Y).
Proof.
use isweqhomot.
- exact (weqcomp (rig_univalence_weq1 X Y)
(weqcomp (rig_univalence_weq2 X Y) (rig_univalence_weq3 X Y))).
- intros e. induction e.
use (pathscomp0 weqcomp_to_funcomp_app).
use weqcomp_to_funcomp_app.
- use weqproperty.
Defined.
Opaque rig_univalence_isweq.
Definition rig_univalence (X Y : rig) : (X = Y) ≃ (rigiso X Y).
Proof.
use make_weq.
- exact (rig_univlalence_map X Y).
- exact (rig_univalence_isweq X Y).
Defined.
Opaque rig_univalence.
(** **** Relations similar to "greater" or "greater or equal" on rigs *)
Definition isrigmultgt (X : rig) (R : hrel X) :=
∏ (a b c d : X), R a b -> R c d -> R (op1 (op2 a c) (op2 b d)) (op1 (op2 a d) (op2 b c)).
Definition isinvrigmultgt (X : rig) (R : hrel X) : UU :=
dirprod (∏ (a b c d : X), R (op1 (op2 a c) (op2 b d)) (op1 (op2 a d) (op2 b c)) -> R a b -> R c d)
(∏ (a b c d : X), R (op1 (op2 a c) (op2 b d)) (op1 (op2 a d) (op2 b c)) -> R c d -> R a b).
(** **** Subobjects *)
Definition issubrig {X : rig} (A : hsubtype X) : UU :=
dirprod (@issubmonoid (rigaddabmonoid X) A) (@issubmonoid (rigmultmonoid X) A).
Lemma isapropissubrig {X : rig} (A : hsubtype X) : isaprop (issubrig A).
Proof.
intros. apply (isofhleveldirprod 1).
- apply isapropissubmonoid.
- apply isapropissubmonoid.
Defined.
Definition subrig (X : rig) : UU := total2 (λ A : hsubtype X, issubrig A).
Definition make_subrig {X : rig} :
∏ (t : hsubtype X), (λ A : hsubtype X, issubrig A) t → ∑ A : hsubtype X, issubrig A :=
tpair (λ A : hsubtype X, issubrig A).
Definition pr1subrig (X : rig) : @subrig X -> hsubtype X :=
@pr1 _ (λ A : hsubtype X, issubrig A).
Definition subrigtosubsetswith2binop (X : rig) : subrig X -> @subsetswith2binop X :=
λ A : _, make_subsetswith2binop (pr1 A) (make_dirprod (pr1 (pr1 (pr2 A))) (pr1 (pr2 (pr2 A)))).
Coercion subrigtosubsetswith2binop : subrig >-> subsetswith2binop.
Definition rigaddsubmonoid {X : rig} : subrig X -> @subabmonoid (rigaddabmonoid X) :=
λ A : _, @make_submonoid (rigaddabmonoid X) (pr1 A) (pr1 (pr2 A)).
Definition rigmultsubmonoid {X : rig} : subrig X -> @submonoid (rigmultmonoid X) :=
λ A : _, @make_submonoid (rigmultmonoid X) (pr1 A) (pr2 (pr2 A)).
Lemma isrigcarrier {X : rig} (A : subrig X) : isrigops (@op1 A) (@op2 A).
Proof.
intros. split.
- split with (make_dirprod (isabmonoidcarrier (rigaddsubmonoid A))
(ismonoidcarrier (rigmultsubmonoid A))).
+ split.
* intro a. apply (invmaponpathsincl _ (isinclpr1carrier A)).
simpl. apply rigmult0x.
* intro a. apply (invmaponpathsincl _ (isinclpr1carrier A)).
simpl. apply rigmultx0.
- split.
* intros a b c. apply (invmaponpathsincl _ (isinclpr1carrier A)).
simpl. apply rigldistr.
* intros a b c. apply (invmaponpathsincl _ (isinclpr1carrier A)).
simpl. apply rigrdistr.
Defined.
Definition carrierofasubrig (X : rig) (A : subrig X) : rig.
Proof. intros. split with A. apply isrigcarrier. Defined.
Coercion carrierofasubrig : subrig >-> rig.
(** **** Quotient objects *)
Definition rigeqrel {X : rig} : UU := @twobinopeqrel X.
Identity Coercion id_rigeqrel : rigeqrel >-> twobinopeqrel.
Definition addabmonoideqrel {X : rig} (R : @rigeqrel X) :
@binopeqrel (rigaddabmonoid X) := @make_binopeqrel (rigaddabmonoid X) (pr1 R) (pr1 (pr2 R)).
Definition multmonoideqrel {X : rig} (R : @rigeqrel X) :
@binopeqrel (rigmultmonoid X) := @make_binopeqrel (rigmultmonoid X) (pr1 R) (pr2 (pr2 R)).
Lemma isrigquot {X : rig} (R : @rigeqrel X) :
isrigops (@op1 (setwith2binopquot R)) (@op2 (setwith2binopquot R)).
Proof.
intros. split.
- split with (make_dirprod (isabmonoidquot (addabmonoideqrel R))
(ismonoidquot (multmonoideqrel R))).
set (opp1 := @op1 (setwith2binopquot R)).
set (opp2 := @op2 (setwith2binopquot R)).
set (zr := setquotpr R (@rigunel1 X)).
split.
+ apply (setquotunivprop
R (λ x , make_hProp _ (setproperty (setwith2binopquot R) (opp2 zr x) zr))).
intro x. apply (maponpaths (setquotpr R) (rigmult0x X x)).
+ apply (setquotunivprop
R (λ x , make_hProp _ (setproperty (setwith2binopquot R) (opp2 x zr) zr))).
intro x. apply (maponpaths (setquotpr R) (rigmultx0 X x)).
- set (opp1 := @op1 (setwith2binopquot R)).
set (opp2 := @op2 (setwith2binopquot R)).
split.
+ unfold isldistr.
apply (setquotuniv3prop
R (λ x x' x'',
make_hProp _ (setproperty (setwith2binopquot R) (opp2 x'' (opp1 x x'))
(opp1 (opp2 x'' x) (opp2 x'' x'))))).
intros x x' x''. apply (maponpaths (setquotpr R) (rigldistr X x x' x'')).
+ unfold isrdistr.
apply (setquotuniv3prop
R (λ x x' x'',
make_hProp _ (setproperty (setwith2binopquot R) (opp2 (opp1 x x') x'')
(opp1 (opp2 x x'') (opp2 x' x''))))).
intros x x' x''. apply (maponpaths (setquotpr R) (rigrdistr X x x' x'')).
Defined.
Definition rigquot {X : rig} (R : @rigeqrel X) : rig :=
@make_rig (setwith2binopquot R) (isrigquot R).
(** **** Direct products *)
Lemma isrigdirprod (X Y : rig) :
isrigops (@op1 (setwith2binopdirprod X Y)) (@op2 (setwith2binopdirprod X Y)).
Proof.
intros. split.
- split with (make_dirprod
(isabmonoiddirprod (rigaddabmonoid X) (rigaddabmonoid Y))
(ismonoiddirprod (rigmultmonoid X) (rigmultmonoid Y))).
simpl. split.
+ intro xy. unfold setwith2binopdirprod. unfold op1. unfold op2.
unfold ismonoiddirprod. unfold unel_is. simpl. apply pathsdirprod.
apply (rigmult0x X). apply (rigmult0x Y).
+ intro xy. unfold setwith2binopdirprod. unfold op1. unfold op2.
unfold ismonoiddirprod. unfold unel_is. simpl. apply pathsdirprod.
apply (rigmultx0 X). apply (rigmultx0 Y).
- split.
+ intros xy xy' xy''. unfold setwith2binopdirprod. unfold op1. unfold op2.
simpl. apply pathsdirprod. apply (rigldistr X). apply (rigldistr Y).
+ intros xy xy' xy''. unfold setwith2binopdirprod. unfold op1. unfold op2.
simpl. apply pathsdirprod. apply (rigrdistr X). apply (rigrdistr Y).
Defined.
Definition rigdirprod (X Y : rig) : rig := @make_rig (setwith2binopdirprod X Y) (isrigdirprod X Y).
(** **** Opposite rigs *)
Local Open Scope rig.
(** Following Bourbaki's Algebra, I, §8.3, Example V *)
Definition opposite_rig (X : rig) : rig.
Proof.
(* Use the same underlying set and addition, flip the multiplication *)
refine (make_setwith2binop (pr1 (pr1rig X))
(make_dirprod (pr1 (pr2 (pr1rig X)))
(fun x y => y * x)%rig),, _).
unfold op2; cbn; fold (@op1 X) (@op2 X).
apply (make_isrigops (rigop1axs X)).
(* For these proofs, we just have to switch some arguments around *)
- apply make_ismonoidop.
* exact (fun x y z => !(rigassoc2 _ z y x)).
* refine (1,, _). (* same unit, opposite proofs *)
exact (make_dirprod (rigrunax2 _) (riglunax2 _)).
- exact (rigmultx0 _).
- exact (rigmult0x _).
- exact (make_dirprod (rigrdistr _) (rigldistr _)).
Defined.
(** In Emacs, use the function insert-char and choose SUPERSCRIPT ZERO *)
Notation "X ⁰" := (opposite_rig X) (at level 12) : rig_scope.
Definition opposite_opposite_rig (X : rig) : rigiso X ((X⁰)⁰).
Proof.
refine ((idfun X,, idisweq X),, _).
repeat split.
Defined.
(** **** Nonzero rigs *)
Definition isnonzerorig (X : rig) : hProp.
Proof.
intros; use make_hProp.
- exact (¬ (@paths X 1 0)).
- apply isapropneg.
Defined.
Local Close Scope rig.
(** *** Commutative rigs *)
(** **** General definitions *)
Definition commrig : UU := total2 (λ X : setwith2binop, iscommrigops (@op1 X) (@op2 X)).
Definition make_commrig (X : setwith2binop) (is : iscommrigops (@op1 X) (@op2 X)) : commrig :=
tpair (λ X : setwith2binop, iscommrigops (@op1 X) (@op2 X)) X is.
Definition commrigconstr {X : hSet} (opp1 opp2 : binop X)
(ax11 : ismonoidop opp1) (ax12 : iscomm opp1)
(ax2 : ismonoidop opp2) (ax22 : iscomm opp2)
(m0x : ∏ x : X, paths (opp2 (unel_is ax11) x) (unel_is ax11))
(mx0 : ∏ x : X, paths (opp2 x (unel_is ax11)) (unel_is ax11))
(dax : isdistr opp1 opp2) : commrig.
Proof.
intros. split with (make_setwith2binop X (make_dirprod opp1 opp2)).
split.
- split.
+ split with (make_dirprod (make_dirprod ax11 ax12) ax2).
apply (make_dirprod m0x mx0).
+ apply dax.
- apply ax22.
Defined.
Definition commrigtorig : commrig -> rig := λ X : _, @make_rig (pr1 X) (pr1 (pr2 X)).
Coercion commrigtorig : commrig >-> rig.
Definition rigcomm2 (X : commrig) : iscomm (@op2 X) := pr2 (pr2 X).
Definition commrigop2axs (X : commrig) : isabmonoidop (@op2 X) :=
tpair _ (rigop2axs X) (rigcomm2 X).
Definition commrigmultabmonoid (X : commrig) : abmonoid :=
make_abmonoid (make_setwithbinop X op2) (make_dirprod (rigop2axs X) (rigcomm2 X)).
(** **** (X = Y) ≃ (rigiso X Y)
We use the following composition
(X = Y) ≃ (make_commrig' X = make_commrig' Y)
≃ ((pr1 (make_commrig' X)) = (pr1 (make_commrig' Y)))
≃ (rigiso X Y)
where the third weak equivalence uses univalence for rigs, [rig_univalence]. We define
[commrig'] to be able to apply it.
*)
Local Definition commrig' : UU :=
∑ D : (∑ X : setwith2binop, isrigops (@op1 X) (@op2 X)), iscomm (@op2 (pr1 D)).
Local Definition make_commrig' (CR : commrig) : commrig' :=
tpair _ (tpair _ (pr1 CR) (dirprod_pr1 (pr2 CR))) (dirprod_pr2 (pr2 CR)).
Definition commrig_univalence_weq1 : commrig ≃ commrig' :=
weqtotal2asstol
(λ X : setwith2binop, isrigops (@op1 X) (@op2 X))
(fun y : (∑ (X : setwith2binop), isrigops (@op1 X) (@op2 X)) => iscomm (@op2 (pr1 y))).
Definition commrig_univalence_weq1' (X Y : commrig) : (X = Y) ≃ (make_commrig' X = make_commrig' Y) :=
make_weq _ (@isweqmaponpaths commrig commrig' commrig_univalence_weq1 X Y).
Definition commrig_univalence_weq2 (X Y : commrig) :
((make_commrig' X) = (make_commrig' Y)) ≃ ((pr1 (make_commrig' X)) = (pr1 (make_commrig' Y))).
Proof.
use subtypeInjectivity.
intros w. use isapropiscomm.
Defined.
Opaque commrig_univalence_weq2.
Definition commrig_univalence_weq3 (X Y : commrig) :
((pr1 (make_commrig' X)) = (pr1 (make_commrig' Y))) ≃ (rigiso X Y) :=
rig_univalence (pr1 (make_commrig' X)) (pr1 (make_commrig' Y)).
Definition commrig_univalence_map (X Y : commrig) : (X = Y) -> (rigiso X Y).
Proof.
intros e. induction e. exact (idrigiso X).
Defined.
Lemma commrig_univalence_isweq (X Y : commrig) : isweq (commrig_univalence_map X Y).
Proof.
use isweqhomot.
- exact (weqcomp (commrig_univalence_weq1' X Y)
(weqcomp (commrig_univalence_weq2 X Y) (commrig_univalence_weq3 X Y))).
- intros e. induction e.
use (pathscomp0 weqcomp_to_funcomp_app).
use weqcomp_to_funcomp_app.
- use weqproperty.
Defined.
Opaque commrig_univalence_isweq.
Definition commrig_univalence (X Y : commrig) : (X = Y) ≃ (rigiso X Y).
Proof.
use make_weq.
- exact (commrig_univalence_map X Y).
- exact (commrig_univalence_isweq X Y).
Defined.
Opaque commrig_univalence.
(** **** Relations similar to "greater" on commutative rigs *)
Lemma isinvrigmultgtif (X : commrig) (R : hrel X)
(is2 : ∏ a b c d, R (op1 (op2 a c) (op2 b d)) (op1 (op2 a d) (op2 b c)) -> R a b -> R c d) :
isinvrigmultgt X R.
Proof.
intros. split.
- apply is2.
- intros a b c d r rcd.
rewrite (rigcomm1 X (op2 a d) _) in r.
rewrite (rigcomm2 X a c) in r.
rewrite (rigcomm2 X b d) in r.
rewrite (rigcomm2 X b c) in r.
rewrite (rigcomm2 X a d) in r.
apply (is2 _ _ _ _ r rcd).
Defined.
(** **** Subobjects *)
Lemma iscommrigcarrier {X : commrig} (A : @subrig X) : iscommrigops (@op1 A) (@op2 A).
Proof.
intros. split with (isrigcarrier A).
apply (pr2 (@isabmonoidcarrier (commrigmultabmonoid X) (rigmultsubmonoid A))).
Defined.
(* ??? slows down at the last [ apply ] and at [ Defined ] (oct.16.2011 - does
not slow down anymore with two Dan's patches) *)
Definition carrierofasubcommrig {X : commrig} (A : @subrig X) : commrig :=
make_commrig A (iscommrigcarrier A).
(** **** Quotient objects *)
Lemma iscommrigquot {X : commrig} (R : @rigeqrel X) :
iscommrigops (@op1 (setwith2binopquot R)) (@op2 (setwith2binopquot R)).
Proof.
intros. split with (isrigquot R).
apply (pr2 (@isabmonoidquot (commrigmultabmonoid X) (multmonoideqrel R))).
Defined.
Definition commrigquot {X : commrig} (R : @rigeqrel X) : commrig :=
make_commrig (setwith2binopquot R) (iscommrigquot R).
(** **** Direct products *)
Lemma iscommrigdirprod (X Y : commrig) :
iscommrigops (@op1 (setwith2binopdirprod X Y)) (@op2 (setwith2binopdirprod X Y)).
Proof.
intros. split with (isrigdirprod X Y).
apply (pr2 (isabmonoiddirprod (commrigmultabmonoid X) (commrigmultabmonoid Y))).
Defined.
Definition commrigdirprod (X Y : commrig) : commrig :=
make_commrig (setwith2binopdirprod X Y) (iscommrigdirprod X Y).
(** **** Opposite commutative rigs *)
Local Open Scope rig.
(** We reuse much of the proof for general rigs *)
Definition opposite_commrig (X : commrig) : commrig :=
((pr1 (X⁰)),, (make_dirprod (pr2 (X⁰)) (fun x y => @rigcomm2 X y x))).
(** Commutativity makes taking the opposite trivial *)
Definition iso_commrig_opposite (X : commrig) : rigiso X (opposite_commrig X).
Proof.
refine ((idfun X,, idisweq X),, _).
repeat split.
unfold isbinopfun.
exact (fun x y => @rigcomm2 X x y).
Defined.
Local Close Scope rig.
(** *** Rings *)
(** **** General definitions *)
Definition ring : UU := total2 (λ X : setwith2binop, isringops (@op1 X) (@op2 X)).
Definition make_ring {X : setwith2binop} (is : isringops (@op1 X) (@op2 X)) : ring :=
tpair (λ X : setwith2binop, isringops (@op1 X) (@op2 X)) X is.
Definition pr1ring : ring -> setwith2binop :=
@pr1 _ (λ X : setwith2binop, isringops (@op1 X) (@op2 X)).
Coercion pr1ring : ring >-> setwith2binop.
Definition ringaxs (X : ring) : isringops (@op1 X) (@op2 X) := pr2 X.
Definition ringop1axs (X : ring) : isabgrop (@op1 X) := pr1 (pr1 (pr2 X)).
Definition ringassoc1 (X : ring) : isassoc (@op1 X) := assocax_is (ringop1axs X).
Definition ringunel1 {X : ring} : X := unel_is (ringop1axs X).
Definition ringlunax1 (X : ring) : islunit op1 (@ringunel1 X) := lunax_is (ringop1axs X).
Definition ringrunax1 (X : ring) : isrunit op1 (@ringunel1 X) := runax_is (ringop1axs X).
Definition ringinv1 {X : ring} : X -> X := grinv_is (ringop1axs X).
Definition ringlinvax1 (X : ring) : ∏ x : X, paths (op1 (ringinv1 x) x) ringunel1 :=
grlinvax_is (ringop1axs X).
Definition ringrinvax1 (X : ring) : ∏ x : X, paths (op1 x (ringinv1 x)) ringunel1 :=
grrinvax_is (ringop1axs X).
Definition ringcomm1 (X : ring) : iscomm (@op1 X) := commax_is (ringop1axs X).
Definition ringop2axs (X : ring) : ismonoidop (@op2 X) := pr2 (pr1 (pr2 X)).
Definition ringassoc2 (X : ring) : isassoc (@op2 X) := assocax_is (ringop2axs X).
Definition ringunel2 {X : ring} : X := unel_is (ringop2axs X).
Definition ringlunax2 (X : ring) : islunit op2 (@ringunel2 X) := lunax_is (ringop2axs X).
Definition ringrunax2 (X : ring) : isrunit op2 (@ringunel2 X) := runax_is (ringop2axs X).
Definition ringdistraxs (X : ring) : isdistr (@op1 X) (@op2 X) := pr2 (pr2 X).
Definition ringldistr (X : ring) : isldistr (@op1 X) (@op2 X) := pr1 (pr2 (pr2 X)).
Definition ringrdistr (X : ring) : isrdistr (@op1 X) (@op2 X) := pr2 (pr2 (pr2 X)).
Definition ringconstr {X : hSet} (opp1 opp2 : binop X) (ax11 : isgrop opp1) (ax12 : iscomm opp1)
(ax2 : ismonoidop opp2) (dax : isdistr opp1 opp2) : ring :=
@make_ring (make_setwith2binop X (make_dirprod opp1 opp2))
(make_dirprod (make_dirprod (make_dirprod ax11 ax12) ax2) dax).
Definition ringmultx0 (X : ring) : ∏ x : X, (op2 x ringunel1) = ringunel1 :=
ringmultx0_is (ringaxs X).
Definition ringmult0x (X : ring) : ∏ x : X, (op2 ringunel1 x) = ringunel1 :=
ringmult0x_is (ringaxs X).
Definition ringminus1 {X : ring} : X := ringminus1_is (ringaxs X).
Definition ringmultwithminus1 (X : ring) : ∏ x : X, paths (op2 ringminus1 x) (ringinv1 x) :=
ringmultwithminus1_is (ringaxs X).
Definition ringaddabgr (X : ring) : abgr := make_abgr (make_setwithbinop X op1) (ringop1axs X).
Coercion ringaddabgr : ring >-> abgr.
Definition ringmultmonoid (X : ring) : monoid := make_monoid (make_setwithbinop X op2) (ringop2axs X).
Declare Scope ring_scope.
Notation "x + y" := (op1 x y) : ring_scope.
Notation "x - y" := (op1 x (ringinv1 y)) : ring_scope.
Notation "x * y" := (op2 x y) : ring_scope.
Notation "0" := (ringunel1) : ring_scope.
Notation "1" := (ringunel2) : ring_scope.
Notation "-1" := (ringminus1) (at level 0) : ring_scope.
Notation " - x " := (ringinv1 x) : ring_scope.
Delimit Scope ring_scope with ring.
Definition ringtorig (X : ring) : rig := @make_rig _ (pr2 X).
Coercion ringtorig : ring >-> rig.
(** **** Homomorphisms of rings *)
Definition isringfun {X Y : ring} (f : X -> Y) := @isrigfun X Y f.
Definition ringfun (X Y : ring) := rigfun X Y.
Lemma isaset_ringfun (X Y : ring) : isaset (ringfun X Y).
Proof.
apply (isofhleveltotal2 2).
- use impred_isaset. intro x.
apply setproperty.
- intro f. apply isasetaprop.
apply isapropisrigfun.
Defined.
Definition ringfunconstr {X Y : ring} {f : X -> Y} (is : isringfun f) : ringfun X Y := rigfunconstr is.
Identity Coercion id_ringfun : ringfun >-> rigfun.
Definition ringaddfun {X Y : ring} (f : ringfun X Y) : monoidfun X Y := monoidfunconstr (pr1 (pr2 f)).
Definition ringmultfun {X Y : ring} (f : ringfun X Y) :
monoidfun (ringmultmonoid X) (ringmultmonoid Y) := monoidfunconstr (pr2 (pr2 f)).
Definition ringiso (X Y : ring) := rigiso X Y.
Definition make_ringiso {X Y : ring} (f : X ≃ Y) (is : isringfun f) : ringiso X Y := tpair _ f is.
Identity Coercion id_ringiso : ringiso >-> rigiso.
Definition isringfuninvmap {X Y : ring} (f : ringiso X Y) : isringfun (invmap f) := isrigfuninvmap f.
(** **** (X = Y) ≃ (ringiso X Y)
We use the following composition
(X = Y) ≃ (make_ring' X = make_ring' Y)
≃ ((pr1 (make_ring' X)) = (pr1 (make_ring' Y)))
≃ (ringiso X Y)
where the third weak equivalence is given by univalence for rigs, [rig_univalence]. We define
ring' to be able to apply [rig_univalence].
*)
Local Definition ring' : UU :=
∑ D : (∑ X : setwith2binop, isrigops (@op1 X) (@op2 X)),
invstruct (@op1 (pr1 D)) (dirprod_pr1 (dirprod_pr1 (pr1 (pr1 (pr2 D))))).
Local Definition make_ring' (R : ring) : ring'.
Proof.
use tpair.
- use tpair.
+ exact (pr1 R).
+ use make_isrigops.
* use make_isabmonoidop.
-- exact (pr1 (dirprod_pr1 (dirprod_pr1 (dirprod_pr1 (pr2 R))))).
-- exact (dirprod_pr2 (dirprod_pr1 (dirprod_pr1 (pr2 R)))).
* exact (dirprod_pr2 (dirprod_pr1 (pr2 R))).
* exact (@mult0x_is_l (pr1 R) (@op1 (pr1 R)) (@op2 (pr1 R))
(dirprod_pr1 (dirprod_pr1 (dirprod_pr1 (pr2 R))))
(dirprod_pr2 (dirprod_pr1 (pr2 R))) (dirprod_pr2 (pr2 R))).
* exact (@multx0_is_l (pr1 R) (@op1 (pr1 R)) (@op2 (pr1 R))
(dirprod_pr1 (dirprod_pr1 (dirprod_pr1 (pr2 R))))
(dirprod_pr2 (dirprod_pr1 (pr2 R))) (dirprod_pr2 (pr2 R))).
* exact (dirprod_pr2 (pr2 R)).
- exact (pr2 (dirprod_pr1 (dirprod_pr1 (dirprod_pr1 (pr2 R))))).
Defined.
Local Definition make_ring_from_ring' (R : ring') : ring.
Proof.
use make_ring.
- exact (pr1 (pr1 R)).
- use make_isringops.
+ use make_isabgrop.
* use make_isgrop.
-- exact (dirprod_pr1 (dirprod_pr1 (pr1 (dirprod_pr1 (pr2 (pr1 R)))))).
-- exact (pr2 R).
* exact (dirprod_pr2 (dirprod_pr1 (pr1 (dirprod_pr1 (pr2 (pr1 R)))))).
+ exact (dirprod_pr2 (pr1 (dirprod_pr1 (pr2 (pr1 R))))).
+ exact (dirprod_pr2 (pr2 (pr1 R))).
Defined.
Definition ring_univalence_weq1 : ring ≃ ring'.
Proof.
use make_weq.
- intros R. exact (make_ring' R).
- use isweq_iso.
+ intros R'. exact (make_ring_from_ring' R').
+ intros R. use idpath.
+ intros R'.
use total2_paths_f.
* use total2_paths_f.
-- use idpath.
-- use proofirrelevance. use isapropisrigops.
* use proofirrelevance. use isapropinvstruct.
Defined.
Definition ring_univalence_weq1' (X Y : ring) : (X = Y) ≃ (make_ring' X = make_ring' Y) :=
make_weq _ (@isweqmaponpaths ring ring' ring_univalence_weq1 X Y).
Definition ring_univalence_weq2 (X Y : ring) :
((make_ring' X) = (make_ring' Y)) ≃ ((pr1 (make_ring' X)) = (pr1 (make_ring' Y))).
Proof.
use subtypeInjectivity.
intros w. use isapropinvstruct.
Defined.
Opaque ring_univalence_weq2.
Definition ring_univalence_weq3 (X Y : ring) :
((pr1 (make_ring' X)) = (pr1 (make_ring' Y))) ≃ (rigiso X Y) :=
rig_univalence (pr1 (make_ring' X)) (pr1 (make_ring' Y)).
Definition ring_univalence_map (X Y : ring) : (X = Y) -> (ringiso X Y).
Proof.
intros e. induction e. exact (idrigiso X).
Defined.
Lemma ring_univalence_isweq (X Y : ring) : isweq (ring_univalence_map X Y).
Proof.
use isweqhomot.
- exact (weqcomp (ring_univalence_weq1' X Y)
(weqcomp (ring_univalence_weq2 X Y) (ring_univalence_weq3 X Y))).
- intros e. induction e.
use (pathscomp0 weqcomp_to_funcomp_app).
use weqcomp_to_funcomp_app.
- use weqproperty.
Defined.
Opaque ring_univalence_isweq.
Definition ring_univalence (X Y : ring) : (X = Y) ≃ (ringiso X Y).
Proof.
use make_weq.
- exact (ring_univalence_map X Y).
- exact (ring_univalence_isweq X Y).
Defined.
Opaque ring_univalence.
(** **** Computation lemmas for rings *)
Local Open Scope ring_scope.
Definition ringinvunel1 (X : ring) : -0 = 0 := grinvunel X.
Lemma ringismultlcancelableif (X : ring) (x : X) (isl : ∏ y, paths (x * y) 0 -> y = 0) :
islcancelable op2 x.
Proof.
intros.
apply (@isinclbetweensets X X).
- apply setproperty.
- apply setproperty.
- intros x1 x2 e.
set (e' := maponpaths (λ a, a + (x * (-x2))) e). simpl in e'.
rewrite (pathsinv0 (ringldistr X _ _ x)) in e'.
rewrite (pathsinv0 (ringldistr X _ _ x)) in e'.
rewrite (ringrinvax1 X x2) in e'.
rewrite (ringmultx0 X _) in e'.
set (e'' := isl (x1 - x2) e').
set (e''' := maponpaths (λ a, a + x2) e''). simpl in e'''.
rewrite (ringassoc1 X _ _ x2) in e'''.
rewrite (ringlinvax1 X x2) in e'''.
rewrite (ringlunax1 X _) in e'''.
rewrite (ringrunax1 X _) in e'''.
apply e'''.
Defined.
Opaque ringismultlcancelableif.
Lemma ringismultrcancelableif (X : ring) (x : X) (isr : ∏ y, paths (y * x) 0 -> y = 0) :
isrcancelable op2 x.
Proof.
intros. apply (@isinclbetweensets X X).
- apply setproperty.
- apply setproperty.
- intros x1 x2 e.
set (e' := maponpaths (λ a, a + ((-x2) * x)) e). simpl in e'.
rewrite (pathsinv0 (ringrdistr X _ _ x)) in e'.
rewrite (pathsinv0 (ringrdistr X _ _ x)) in e'.
rewrite (ringrinvax1 X x2) in e'.
rewrite (ringmult0x X _) in e'.
set (e'' := isr (x1 - x2) e').
set (e''' := maponpaths (λ a, a + x2) e''). simpl in e'''.
rewrite (ringassoc1 X _ _ x2) in e'''.
rewrite (ringlinvax1 X x2) in e'''.
rewrite (ringlunax1 X _) in e'''.
rewrite (ringrunax1 X _) in e'''.
apply e'''.
Defined.
Opaque ringismultrcancelableif.
Lemma ringismultcancelableif (X : ring) (x : X) (isl : ∏ y, paths (x * y) 0 -> y = 0)
(isr : ∏ y, paths (y * x) 0 -> y = 0) : iscancelable op2 x.
Proof.
intros.
apply (make_dirprod (ringismultlcancelableif X x isl) (ringismultrcancelableif X x isr)).
Defined.
Lemma ringlmultminus (X : ring) (a b : X) : paths ((- a) * b) (- (a * b)).
Proof.
intros. apply (@grrcan X _ _ (a * b)).
change (paths (-a * b + a * b) (- (a * b) + a * b)).
rewrite (ringlinvax1 X _). rewrite (pathsinv0 (ringrdistr X _ _ _)).
rewrite (ringlinvax1 X _). rewrite (ringmult0x X _).
apply idpath.
Defined.
Opaque ringlmultminus.
Lemma ringrmultminus (X : ring) (a b : X) : paths (a * (- b)) (- (a * b)).
Proof.
intros. apply (@grrcan X _ _ (a * b)).
change (paths (a * (- b) + a * b) (- (a * b) + a * b)).
rewrite (ringlinvax1 X _). rewrite (pathsinv0 (ringldistr X _ _ _)).
rewrite (ringlinvax1 X _). rewrite (ringmultx0 X _).
apply idpath.
Defined.
Opaque ringrmultminus.
Lemma ringmultminusminus (X : ring) (a b : X) : paths (-a * - b) (a * b).
Proof.
intros. apply (@grrcan X _ _ (- a * b)). simpl.
rewrite (pathsinv0 (ringldistr X _ _ (- a))).
rewrite (pathsinv0 (ringrdistr X _ _ b)).
rewrite (ringlinvax1 X b). rewrite (ringrinvax1 X a).
rewrite (ringmult0x X _). rewrite (ringmultx0 X _).
apply idpath.
Defined.
Opaque ringmultminusminus.
Lemma ringminusminus (X : ring) (a : X) : --a = a.
Proof. intros. apply (grinvinv X a). Defined.
Definition ringinvmaponpathsminus (X : ring) {a b : X} : -a = -b -> a = b := grinvmaponpathsinv X.
(** **** Relations compatible with the additive structure on rings *)
Definition ringfromgt0 (X : ring) {R : hrel X} (is0 : @isbinophrel X R)
{x : X} (is : R x 0) : R 0 (- x) := grfromgtunel X is0 is.
Definition ringtogt0 (X : ring) {R : hrel X} (is0 : @isbinophrel X R) {x : X}
(is : R 0 (- x)) : R x 0 := grtogtunel X is0 is.
Definition ringfromlt0 (X : ring) {R : hrel X} (is0 : @isbinophrel X R) {x : X}
(is : R 0 x) : R (- x) 0 := grfromltunel X is0 is.
Definition ringtolt0 (X : ring) {R : hrel X} (is0 : @isbinophrel X R) {x : X}
(is : R (- x) 0) : R 0 x := grtoltunel X is0 is.
(** **** Relations compatible with the multiplicative structure on rings *)
Definition isringmultgt (X : ring) (R : hrel X) : UU := ∏ a b, R a 0 -> R b 0 -> R (a * b) 0.
Lemma ringmultgt0lt0 (X : ring) {R : hrel X} (is0 : @isbinophrel X R) (is : isringmultgt X R) {x y : X}
(isx : R x 0) (isy : R 0 y) : R 0 (x * y).
Proof.
intros.
set (isy' := grfromltunel X is0 isy).
assert (r := is _ _ isx isy').
change (pr1 (R (x * (- y)) 0)) in r.
rewrite (ringrmultminus X _ _) in r.
assert (r' := grfromgtunel X is0 r).
change (pr1 (R 0 (- - (x * y)))) in r'.
rewrite (ringminusminus X (x * y)) in r'.
apply r'.
Defined.
Opaque ringmultgt0lt0.
Lemma ringmultlt0gt0 (X : ring) {R : hrel X} (is0 : @isbinophrel X R) (is : isringmultgt X R) {x y : X}
(isx : R 0 x) (isy : R y 0) : R 0 (x * y).
Proof.
intros.
set (isx' := grfromltunel X is0 isx).
assert (r := is _ _ isx' isy).
change (pr1 (R ((- x) * y) 0)) in r.
rewrite (ringlmultminus X _ _) in r.
assert (r' := grfromgtunel X is0 r).
change (pr1 (R 0 (- - (x * y)))) in r'.
rewrite (ringminusminus X (x * y)) in r'.
apply r'.
Defined.
Opaque ringmultlt0gt0.
Lemma ringmultlt0lt0 (X : ring) {R : hrel X} (is0 : @isbinophrel X R) (is : isringmultgt X R) {x y : X}
(isx : R 0 x) (isy : R 0 y) : R (x * y) 0.
Proof.
intros.
set (rx := ringfromlt0 _ is0 isx).
assert (ry := ringfromlt0 _ is0 isy).
assert (int := is _ _ rx ry).
rewrite (ringmultminusminus X _ _) in int.
apply int.
Defined.
Opaque ringmultlt0lt0.
Lemma isringmultgttoislringmultgt (X : ring) {R : hrel X} (is0 : @isbinophrel X R)
(is : isringmultgt X R) : ∏ a b c : X, R c 0 -> R a b -> R (c * a) (c * b).
Proof.
intros a b c rc0 rab.
set (rab':= (pr2 is0) _ _ (- b) rab). clearbody rab'.
change (pr1 (R (a - b) (b - b))) in rab'.
rewrite (ringrinvax1 X b) in rab'.
set (r' := is _ _ rc0 rab'). clearbody r'.
set (r'' := (pr2 is0) _ _ (c * b) r'). clearbody r''.
change (pr1 (R (c * (a - b) + c * b) (0 + c * b))) in r''.
rewrite (ringlunax1 X _) in r''.
rewrite (pathsinv0 (ringldistr X _ _ c)) in r''.
rewrite (ringassoc1 X a _ _) in r''.
rewrite (ringlinvax1 X b) in r''.
rewrite (ringrunax1 X _) in r''.
apply r''.
Defined.
Opaque isringmultgttoislringmultgt.
Lemma islringmultgttoisringmultgt (X : ring) {R : hrel X}
(is : ∏ a b c : X, R c 0 -> R a b -> R (c * a) (c * b)) : isringmultgt X R.
Proof.
intros. intros a b ra rb.
set (int := is b 0 a ra rb). clearbody int. rewrite (ringmultx0 X _) in int.
apply int.
Defined.
Opaque islringmultgttoisringmultgt.
Lemma isringmultgttoisrringmultgt (X : ring) {R : hrel X} (is0 : @isbinophrel X R)
(is : isringmultgt X R) : ∏ a b c : X, R c 0 -> R a b -> R (a * c) (b * c).
Proof.
intros a b c rc0 rab.
set (rab' := (pr2 is0) _ _ (- b) rab). clearbody rab'.
change (pr1 (R (a - b) (b - b))) in rab'.
rewrite (ringrinvax1 X b) in rab'.
set (r' := is _ _ rab' rc0). clearbody r'.
set (r'' := (pr2 is0) _ _ (b * c) r'). clearbody r''.
change (pr1 (R ((a - b) * c + b * c) (0 + b * c))) in r''.
rewrite (ringlunax1 X _) in r''.
rewrite (pathsinv0 (ringrdistr X _ _ c)) in r''.
rewrite (ringassoc1 X a _ _) in r''.
rewrite (ringlinvax1 X b) in r''.
rewrite (ringrunax1 X _) in r''.
apply r''.
Defined.
Opaque isringmultgttoisrringmultgt.
Lemma isrringmultgttoisringmultgt (X : ring) {R : hrel X}
(is1 : ∏ a b c : X, R c 0 -> R a b -> R (a * c) (b * c)) : isringmultgt X R.
Proof.
intros. intros a b ra rb.
set (int := is1 _ _ _ rb ra). clearbody int.
rewrite (ringmult0x X _) in int. apply int.
Defined.
Opaque isrringmultgttoisringmultgt.
Lemma isringmultgtaspartbinophrel (X : ring) (R : hrel X) (is0 : @isbinophrel X R) :
(isringmultgt X R) <-> (@ispartbinophrel (ringmultmonoid X) (λ a, R a 0) R).
Proof.
intros. split.
- intro ism. split.
+ apply (isringmultgttoislringmultgt X is0 ism).
+ apply (isringmultgttoisrringmultgt X is0 ism).
- intro isp. apply (islringmultgttoisringmultgt X (pr1 isp)).
Defined.
Lemma isringmultgttoisrigmultgt (X : ring) {R : hrel X} (is0 : @isbinophrel X R)
(is : isringmultgt X R) : isrigmultgt X R.
Proof.
intros. set (rer := abmonoidrer X). simpl in rer.
intros a b c d rab rcd.
assert (intab : R (a - b) 0).
{
destruct (ringrinvax1 X b).
apply ((pr2 is0) _ _ (- b)).
apply rab.
}
assert (intcd : R (c - d) 0).
{
destruct (ringrinvax1 X d).
apply ((pr2 is0) _ _ (- d)).
apply rcd.
}
set (int := is _ _ intab intcd). rewrite (ringrdistr X _ _ _) in int.
rewrite (ringldistr X _ _ _) in int. rewrite (ringldistr X _ _ _) in int.
set (int' := (pr2 is0) _ _ (a * d + b * c) int). clearbody int'.
simpl in int'.
rewrite (ringlunax1 _) in int'. rewrite (ringcomm1 X (- b * c) _) in int'.
rewrite (rer _ (a * - d) _ _) in int'.
rewrite (ringassoc1 X _ (a * - d + - b * c) _) in int'.
rewrite (rer _ _ (a * d) _) in int'.
rewrite (pathsinv0 (ringldistr X _ _ a)) in int'.
rewrite (ringlinvax1 X d) in int'.
rewrite (ringmultx0 X _) in int'.
rewrite (pathsinv0 (ringrdistr X _ _ c)) in int'.
rewrite (ringlinvax1 X b) in int'.
rewrite (ringmult0x X _) in int'.
rewrite (ringrunax1 X _) in int'.
rewrite (ringrunax1 X _) in int'.
rewrite (ringmultminusminus X b d) in int'.
apply int'.
Defined.
Opaque isringmultgttoisrigmultgt.
Lemma isrigmultgttoisringmultgt (X : ring) {R : hrel X} (is : isrigmultgt X R) : isringmultgt X R.
Proof.
intros. intros a b ra0 rb0. set (is' := is _ _ _ _ ra0 rb0). simpl in is'.
fold (pr1ring) in is'. rewrite 2? (ringmult0x X _) in is'.
rewrite (ringmultx0 X _) in is'. rewrite 2? (ringrunax1 X _) in is'.
exact is'.
Defined.
Opaque isrigmultgttoisringmultgt.
(** **** Relations "inversely compatible" with the multiplicative structure on rings *)
Definition isinvringmultgt (X : ring) (R : hrel X) : UU :=
dirprod (∏ a b, R (a * b) 0 -> R a 0 -> R b 0) (∏ a b, R (a * b) 0 -> R b 0 -> R a 0).
Lemma isinvringmultgttoislinvringmultgt (X : ring) {R : hrel X} (is0 : @isbinophrel X R)
(is : isinvringmultgt X R) : ∏ a b c : X, R c 0 -> R (c * a) (c * b) -> R a b.
Proof.
intros a b c rc0 r.
set (rab':= (pr2 is0) _ _ (c * - b) r).
clearbody rab'.
change (pr1 (R (c * a + c * - b) (c * b + c * - b))) in rab'.
rewrite (pathsinv0 (ringldistr X _ _ c)) in rab'.
rewrite (pathsinv0 (ringldistr X _ _ c)) in rab'.
rewrite (ringrinvax1 X b) in rab'. rewrite (ringmultx0 X _) in rab'.
set (r' := (pr1 is) _ _ rab' rc0). clearbody r'.
set (r'' := (pr2 is0) _ _ b r'). clearbody r''.
change (pr1 (R (a - b + b) (0 + b))) in r''.
rewrite (ringlunax1 X _) in r''. rewrite (ringassoc1 X a _ _) in r''.
rewrite (ringlinvax1 X b) in r''. rewrite (ringrunax1 X _) in r''.
apply r''.
Defined.
Opaque isinvringmultgttoislinvringmultgt.
Lemma isinvringmultgttoisrinvringmultgt (X : ring) {R : hrel X} (is0 : @isbinophrel X R)
(is : isinvringmultgt X R) : ∏ a b c : X, R c 0 -> R (a * c) (b * c) -> R a b.
Proof.
intros a b c rc0 r.
set (rab':= (pr2 is0) _ _ (- b * c) r). clearbody rab'.
change (pr1 (R (a * c + - b * c) (b * c + - b * c))) in rab'.
rewrite (pathsinv0 (ringrdistr X _ _ c)) in rab'.
rewrite (pathsinv0 (ringrdistr X _ _ c)) in rab'.
rewrite (ringrinvax1 X b) in rab'.
rewrite (ringmult0x X _) in rab'.
set (r' := (pr2 is) _ _ rab' rc0).
clearbody r'. set (r'' := (pr2 is0) _ _ b r').
clearbody r''. change (pr1 (R (a - b + b) (0 + b))) in r''.
rewrite (ringlunax1 X _) in r''. rewrite (ringassoc1 X a _ _) in r''.
rewrite (ringlinvax1 X b) in r''. rewrite (ringrunax1 X _) in r''.
apply r''.
Defined.
Opaque isinvringmultgttoisrinvringmultgt.
Lemma islrinvringmultgttoisinvringmultgt (X : ring) {R : hrel X}
(isl : ∏ a b c : X, R c 0 -> R (c * a) (c * b) -> R a b)
(isr : ∏ a b c : X, R c 0 -> R (a * c) (b * c) -> R a b) : isinvringmultgt X R.
Proof.
intros. split.
- intros a b rab ra.
rewrite (pathsinv0 (ringmultx0 X a)) in rab.
apply (isl _ _ _ ra rab).
- intros a b rab rb.
rewrite (pathsinv0 (ringmult0x X b)) in rab.
apply (isr _ _ _ rb rab).
Defined.
Opaque islrinvringmultgttoisinvringmultgt.
Lemma isinvringmultgtaspartinvbinophrel (X : ring) (R : hrel X) (is0 : @isbinophrel X R) :
(isinvringmultgt X R) <-> (@ispartinvbinophrel (ringmultmonoid X) (λ a, R a 0) R).
Proof.
intros. split.
- intro ism. split.
+ apply (isinvringmultgttoislinvringmultgt X is0 ism).
+ apply (isinvringmultgttoisrinvringmultgt X is0 ism).
- intro isp.
apply (islrinvringmultgttoisinvringmultgt X (pr1 isp) (pr2 isp)).
Defined.
Lemma isinvringmultgttoisinvrigmultgt (X : ring) {R : hrel X}
(is0 : @isbinophrel X R) (is : isinvringmultgt X R) : isinvrigmultgt X R.
Proof.
intros. set (rer := abmonoidrer X). simpl in rer. split.
- intros a b c d r rab.
set (r' := (pr2 is0) _ _ (a * - d + - b * c) r). clearbody r'. simpl in r'.
rewrite (rer _ (b * c) _ _) in r'.
rewrite (pathsinv0 (ringldistr X _ _ a)) in r'.
rewrite (pathsinv0 (ringrdistr X _ _ c)) in r'.
rewrite (ringrinvax1 X d) in r'.
rewrite (ringrinvax1 X b) in r'.
rewrite (ringmult0x X _) in r'.
rewrite (ringmultx0 X _) in r'.
rewrite (ringlunax1 X) in r'.
rewrite (rer _ (b * d) _ _) in r'.
rewrite (pathsinv0 (ringldistr X _ _ a)) in r'.
simpl in r'.
fold pr1ring in r'. (* fold stopped working *)
change (pr1 X) with (pr1ring X) in r'.
rewrite (pathsinv0 (ringmultminusminus X b d)) in r'.
rewrite (pathsinv0 (ringldistr X _ _ (- b))) in r'.
rewrite (ringcomm1 X _ c) in r'.
rewrite (pathsinv0 (ringrdistr X _ _ _)) in r'.
set (rab' := (pr2 is0) _ _ (- b) rab). clearbody rab'.
simpl in rab'. rewrite (ringrinvax1 X b) in rab'.
set (rcd' := (pr1 is) _ _ r' rab').
set (rcd'' := (pr2 is0) _ _ d rcd'). simpl in rcd''.
rewrite (ringassoc1 _ _ _) in rcd''. rewrite (ringlinvax1 X _) in rcd''.
rewrite (ringlunax1 X _) in rcd''. rewrite (ringrunax1 X _) in rcd''.
apply rcd''.
- intros a b c d r rcd.
set (r' := (pr2 is0) _ _ (a * - d + - b * c) r). clearbody r'. simpl in r'.
rewrite (rer _ (b * c) _ _) in r'.
rewrite (pathsinv0 (ringldistr X _ _ a)) in r'.
rewrite (pathsinv0 (ringrdistr X _ _ c)) in r'.
rewrite (ringrinvax1 X d) in r'.
rewrite (ringrinvax1 X b) in r'.
rewrite (ringmult0x X _) in r'.
rewrite (ringmultx0 X _) in r'.
rewrite (ringlunax1 X) in r'.
rewrite (rer _ (b * d) _ _) in r'.
rewrite (pathsinv0 (ringldistr X _ _ a)) in r'.
simpl in r'.
fold pr1ring in r'. (* fold stopped working *)
change (pr1 X) with (pr1ring X) in r'.
rewrite (pathsinv0 (ringmultminusminus X b d)) in r'.
rewrite (pathsinv0 (ringldistr X _ _ (- b))) in r'.
rewrite (ringcomm1 X _ c) in r'.
rewrite (pathsinv0 (ringrdistr X _ _ _)) in r'.
set (rcd' := (pr2 is0) _ _ (- d) rcd). clearbody rcd'. simpl in rcd'.
rewrite (ringrinvax1 X d) in rcd'.
set (rab' := (pr2 is) _ _ r' rcd').
set (rab'' := (pr2 is0) _ _ b rab'). simpl in rab''.
rewrite (ringassoc1 _ _ _) in rab''.
rewrite (ringlinvax1 X _) in rab''.
rewrite (ringlunax1 X _) in rab''.
rewrite (ringrunax1 X _) in rab''.
apply rab''.
Defined.
Opaque isinvringmultgttoisinvrigmultgt.
(** **** Relations on rings and ring homomorphisms *)
Lemma ringaddhrelandfun {X Y : ring} (f : ringfun X Y) (R : hrel Y) (isr : @isbinophrel Y R) :
@isbinophrel X (λ x x', R (f x) (f x')).
Proof. intros. apply (binophrelandfun (ringaddfun f) R isr). Defined.
Lemma ringmultgtandfun {X Y : ring} (f : ringfun X Y) (R : hrel Y) (isr : isringmultgt Y R) :
isringmultgt X (λ x x', R (f x) (f x')).
Proof.
intros. intros a b ra rb.
set (ax0 := (pr2 (pr1 (pr2 f))) : (f 0) = 0).
set (ax1 := (pr1 (pr2 (pr2 f))) : ∏ a b, paths (f (a * b)) ((f a) * (f b))).
rewrite ax0 in ra. rewrite ax0 in rb.
rewrite ax0. rewrite (ax1 _ _).
apply (isr _ _ ra rb).
Defined.
Lemma ringinvmultgtandfun {X Y : ring} (f : ringfun X Y) (R : hrel Y) (isr : isinvringmultgt Y R) :
isinvringmultgt X (λ x x', R (f x) (f x')).
Proof.
intros.
set (ax0 := (pr2 (pr1 (pr2 f))) : (f 0) = 0).
set (ax1 := (pr1 (pr2 (pr2 f))) : ∏ a b, paths (f (a * b)) ((f a) * (f b))).
split.
- intros a b rab ra.
rewrite ax0 in ra. rewrite ax0 in rab.
rewrite ax0. rewrite (ax1 _ _) in rab.
apply ((pr1 isr) _ _ rab ra).
- intros a b rab rb. rewrite ax0 in rb.
rewrite ax0 in rab. rewrite ax0.
rewrite (ax1 _ _) in rab.
apply ((pr2 isr) _ _ rab rb).
Defined.
Close Scope ring_scope.
(** **** Subobjects *)
Definition issubring {X : ring} (A : hsubtype X) : UU :=
dirprod (@issubgr X A) (@issubmonoid (ringmultmonoid X) A).
Lemma isapropissubring {X : ring} (A : hsubtype X) : isaprop (issubring A).
Proof.
intros. apply (isofhleveldirprod 1).
- apply isapropissubgr.
- apply isapropissubmonoid.
Defined.
Definition subring (X : ring) : UU := total2 (λ A : hsubtype X, issubring A).
Definition make_gsubring {X : ring} :
∏ (t : hsubtype X), (λ A : hsubtype X, issubring A) t → ∑ A : hsubtype X, issubring A :=
tpair (λ A : hsubtype X, issubring A).
Definition pr1subring (X : ring) : @subring X -> hsubtype X :=
@pr1 _ (λ A : hsubtype X, issubring A).
Definition subringtosubsetswith2binop (X : ring) : subring X -> @subsetswith2binop X :=
λ A : _, make_subsetswith2binop
(pr1 A) (make_dirprod (pr1 (pr1 (pr1 (pr2 A)))) (pr1 (pr2 (pr2 A)))).
Coercion subringtosubsetswith2binop : subring >-> subsetswith2binop.
Definition addsubgr {X : ring} : subring X -> @subgr X :=
λ A : _, @make_subgr X (pr1 A) (pr1 (pr2 A)).
Definition multsubmonoid {X : ring} : subring X -> @submonoid (ringmultmonoid X) :=
λ A : _, @make_submonoid (ringmultmonoid X) (pr1 A) (pr2 (pr2 A)).
Lemma isringcarrier {X : ring} (A : subring X) : isringops (@op1 A) (@op2 A).
Proof.
intros.
split with (make_dirprod (isabgrcarrier (addsubgr A)) (ismonoidcarrier (multsubmonoid A))).
split.
- intros a b c.
apply (invmaponpathsincl _ (isinclpr1carrier A)).
simpl. apply ringldistr.
- intros a b c.
apply (invmaponpathsincl _ (isinclpr1carrier A)).
simpl. apply ringrdistr.
Defined.
Definition carrierofasubring (X : ring) (A : subring X) : ring.
Proof. intros. split with A. apply isringcarrier. Defined.
Coercion carrierofasubring : subring >-> ring.
(** **** Quotient objects *)
Definition ringeqrel {X : ring} := @twobinopeqrel X.
Identity Coercion id_ringeqrel : ringeqrel >-> twobinopeqrel.
Definition ringaddabgreqrel {X : ring} (R : @ringeqrel X) :
@binopeqrel X := @make_binopeqrel X (pr1 R) (pr1 (pr2 R)).
Definition ringmultmonoideqrel {X : ring} (R : @ringeqrel X) :
@binopeqrel (ringmultmonoid X) := @make_binopeqrel (ringmultmonoid X) (pr1 R) (pr2 (pr2 R)).
Lemma isringquot {X : ring} (R : @ringeqrel X) :
isringops (@op1 (setwith2binopquot R)) (@op2 (setwith2binopquot R)).
Proof.
intros.
split with (make_dirprod (isabgrquot (ringaddabgreqrel R)) (ismonoidquot (ringmultmonoideqrel R))).
simpl.
set (opp1 := @op1 (setwith2binopquot R)).
set (opp2 := @op2 (setwith2binopquot R)).
split.
- unfold isldistr.
apply (setquotuniv3prop
R (λ x x' x'', make_hProp _ (setproperty (setwith2binopquot R) (opp2 x'' (opp1 x x'))
(opp1 (opp2 x'' x) (opp2 x'' x'))))).
intros x x' x''. apply (maponpaths (setquotpr R) (ringldistr X x x' x'')).
- unfold isrdistr.
apply (setquotuniv3prop
R (λ x x' x'', make_hProp _ (setproperty (setwith2binopquot R) (opp2 (opp1 x x') x'')
(opp1 (opp2 x x'') (opp2 x' x''))))).
intros x x' x''. apply (maponpaths (setquotpr R) (ringrdistr X x x' x'')).
Defined.
Definition ringquot {X : ring} (R : @ringeqrel X) : ring :=
@make_ring (setwith2binopquot R) (isringquot R).
(** **** Direct products *)
Lemma isringdirprod (X Y : ring) :
isringops (@op1 (setwith2binopdirprod X Y)) (@op2 (setwith2binopdirprod X Y)).
Proof.
intros.
split with (make_dirprod (isabgrdirprod X Y)
(ismonoiddirprod (ringmultmonoid X) (ringmultmonoid Y))).
simpl. split.
- intros xy xy' xy''. unfold setwith2binopdirprod.
unfold op1. unfold op2. simpl.
apply pathsdirprod.
+ apply (ringldistr X).
+ apply (ringldistr Y).
- intros xy xy' xy''. unfold setwith2binopdirprod.
unfold op1. unfold op2. simpl.
apply pathsdirprod.
+ apply (ringrdistr X).
+ apply (ringrdistr Y).
Defined.
Definition ringdirprod (X Y : ring) : ring := @make_ring (setwith2binopdirprod X Y) (isringdirprod X Y).
(** **** Opposite rings *)
Local Open Scope rig.
(** We just need to reuse and rearrange the opposite rig *)
Definition opposite_ring (X : ring) : ring.
Proof.
refine (pr1 (X⁰),, _).
split.
- split.
apply make_isabgrop.
* exact (pr1 (rigop1axs (X⁰)),, pr2 (pr1 (ringop1axs X))).
* exact (pr2 (ringop1axs X)).
* exact (rigop2axs (X⁰)).
- exact (rigdistraxs (X⁰)).
Defined.
Notation "X ⁰" := (opposite_ring X) (at level 12) : ring_scope.
Local Close Scope rig.
(** **** Ring of differences associated with a rig *)
Local Open Scope rig_scope.
Definition rigtoringaddabgr (X : rig) : abgr := abgrdiff (rigaddabmonoid X).
Definition rigtoringcarrier (X : rig) : hSet := pr1 (pr1 (rigtoringaddabgr X)).
Definition rigtoringop1int (X : rig) : binop (X × X) :=
λ x x', make_dirprod ((pr1 x) + (pr1 x')) ((pr2 x) + (pr2 x')).
Definition rigtoringop1 (X : rig) : binop (rigtoringcarrier X) := @op (rigtoringaddabgr X).
Definition rigtoringop1axs (X : rig) : isabgrop (rigtoringop1 X) := pr2 (rigtoringaddabgr X).
Definition rigtoringunel1 (X : rig) : rigtoringcarrier X := unel (rigtoringaddabgr X).
Definition eqrelrigtoring (X : rig) : eqrel (X × X) := eqrelabgrdiff (rigaddabmonoid X).
Definition rigtoringop2int (X : rig) : binop (X × X) :=
λ xx xx' : dirprod X X,
make_dirprod (pr1 xx * pr1 xx' + pr2 xx * pr2 xx') (pr1 xx * pr2 xx' + pr2 xx * pr1 xx').
Definition rigtoringunel2int (X : rig) : dirprod X X := make_dirprod 1 0.
Lemma rigtoringop2comp (X : rig) :
iscomprelrelfun2 (eqrelrigtoring X) (eqrelrigtoring X) (rigtoringop2int X).
Proof.
intros. apply iscomprelrelfun2if.
- intros xx xx' aa. simpl.
apply @hinhfun. intro tt1. destruct tt1 as [ x0 e ].
split with (x0 * pr2 aa + x0 * pr1 aa).
set (rd := rigrdistr X). set (cm1 := rigcomm1 X).
set (as1 := rigassoc1 X). set (rr := abmonoidoprer (rigop1axs X)).
rewrite (cm1 (pr1 xx * pr1 aa) (pr2 xx * pr2 aa)).
rewrite (rr _ (pr1 xx * pr1 aa) (pr1 xx' * pr2 aa) _).
rewrite (cm1 (pr2 xx * pr2 aa) (pr1 xx' * pr2 aa)).
destruct (rd (pr1 xx) (pr2 xx') (pr1 aa)).
destruct (rd (pr1 xx') (pr2 xx) (pr2 aa)).
rewrite (rr ((pr1 xx' + pr2 xx) * pr2 aa)
((pr1 xx + pr2 xx') * pr1 aa) (x0 * pr2 aa) (x0 * pr1 aa)).
destruct (rd (pr1 xx' + pr2 xx) x0 (pr2 aa)).
destruct (rd (pr1 xx + pr2 xx') x0 (pr1 aa)).
rewrite (cm1 (pr1 xx' * pr1 aa) (pr2 xx' * pr2 aa)).
rewrite (rr _ (pr1 xx' * pr1 aa) (pr1 xx * pr2 aa) _).
rewrite (cm1 (pr2 xx' * pr2 aa) (pr1 xx * pr2 aa)).
destruct (rd (pr1 xx') (pr2 xx) (pr1 aa)).
destruct (rd (pr1 xx) (pr2 xx') (pr2 aa)).
rewrite (rr ((pr1 xx + pr2 xx') * pr2 aa)
((pr1 xx' + pr2 xx) * pr1 aa) (x0 * pr2 aa) (x0 * pr1 aa)).
destruct (rd (pr1 xx + pr2 xx') x0 (pr2 aa)).
destruct (rd (pr1 xx' + pr2 xx) x0 (pr1 aa)).
destruct e. apply idpath.
- intros aa xx xx'. simpl. apply @hinhfun. intro tt1.
destruct tt1 as [ x0 e ]. split with (pr1 aa * x0 + pr2 aa * x0).
set (ld := rigldistr X). set (cm1 := rigcomm1 X).
set (as1 := rigassoc1 X). set (rr := abmonoidoprer (rigop1axs X)).
rewrite (rr _ (pr2 aa * pr2 xx) (pr1 aa * pr2 xx') _).
destruct (ld (pr1 xx) (pr2 xx') (pr1 aa)).
destruct (ld (pr2 xx) (pr1 xx') (pr2 aa)).
rewrite (rr _ (pr2 aa * (pr2 xx + pr1 xx')) (pr1 aa * x0) _).
destruct (ld (pr1 xx + pr2 xx') x0 (pr1 aa)).
destruct (ld (pr2 xx + pr1 xx') x0 (pr2 aa)).
rewrite (rr _ (pr2 aa * pr2 xx') (pr1 aa * pr2 xx) _).
destruct (ld (pr1 xx') (pr2 xx) (pr1 aa)).
destruct (ld (pr2 xx') (pr1 xx) (pr2 aa)).
rewrite (rr _ (pr2 aa * (pr2 xx' + pr1 xx)) (pr1 aa * x0) _).
destruct (ld (pr1 xx' + pr2 xx) x0 (pr1 aa)).
destruct (ld (pr2 xx' + pr1 xx) x0 (pr2 aa)).
rewrite (cm1 (pr2 xx) (pr1 xx')).
rewrite (cm1 (pr2 xx') (pr1 xx)).
destruct e. apply idpath.
Defined.
Opaque rigtoringop2comp.
Definition rigtoringop2 (X : rig) : binop (rigtoringcarrier X) :=
setquotfun2 (eqrelrigtoring X) (eqrelrigtoring X) (rigtoringop2int X) (rigtoringop2comp X).
Lemma rigtoringassoc2 (X : rig) : isassoc (rigtoringop2 X).
Proof.
unfold isassoc.
apply (setquotuniv3prop _ (λ x x' x'', _ = _)).
intros x x' x''.
change (paths (setquotpr (eqrelrigtoring X) (rigtoringop2int X (rigtoringop2int X x x') x''))
(setquotpr (eqrelrigtoring X) (rigtoringop2int X x (rigtoringop2int X x' x'')))).
apply (maponpaths (setquotpr (eqrelrigtoring X))). unfold rigtoringop2int.
simpl.
set (rd := rigrdistr X). set (ld := rigldistr X).
set (cm1 := rigcomm1 X).
set (as1 := rigassoc1 X). set (as2 := rigassoc2 X).
set (rr := abmonoidoprer (rigop1axs X)). apply pathsdirprod.
rewrite (rd _ _ (pr1 x'')). rewrite (rd _ _ (pr2 x'')).
rewrite (ld _ _ (pr1 x)). rewrite (ld _ _ (pr2 x)).
destruct (as2 (pr1 x) (pr1 x') (pr1 x'')).
destruct (as2 (pr1 x) (pr2 x') (pr2 x'')).
destruct (as2 (pr2 x) (pr1 x') (pr2 x'')).
destruct (as2 (pr2 x) (pr2 x') (pr1 x'')).
destruct (cm1 (pr2 x * pr2 x' * pr1 x'') (pr2 x * pr1 x' * pr2 x'')).
rewrite (rr _ (pr2 x * pr2 x' * pr1 x'') (pr1 x * pr2 x' * pr2 x'') _).
apply idpath.
rewrite (rd _ _ (pr1 x'')). rewrite (rd _ _ (pr2 x'')).
rewrite (ld _ _ (pr1 x)). rewrite (ld _ _ (pr2 x)).
destruct (as2 (pr1 x) (pr1 x') (pr2 x'')).
destruct (as2 (pr1 x) (pr2 x') (pr1 x'')).
destruct (as2 (pr2 x) (pr1 x') (pr1 x'')).
destruct (as2 (pr2 x) (pr2 x') (pr2 x'')).
destruct (cm1 (pr2 x * pr2 x' * pr2 x'') (pr2 x * pr1 x' * pr1 x'')).
rewrite (rr _ (pr1 x * pr2 x' * pr1 x'') (pr2 x * pr2 x' * pr2 x'') _).
apply idpath.
Defined.
Opaque rigtoringassoc2.
Definition rigtoringunel2 (X : rig) : rigtoringcarrier X :=
setquotpr (eqrelrigtoring X) (rigtoringunel2int X).
Lemma rigtoringlunit2 (X : rig) : islunit (rigtoringop2 X) (rigtoringunel2 X).
Proof.
unfold islunit.
apply (setquotunivprop _ (λ x, _ = _)).
intro x.
change (paths (setquotpr (eqrelrigtoring X) (rigtoringop2int X (rigtoringunel2int X) x))
(setquotpr (eqrelrigtoring X) x)).
apply (maponpaths (setquotpr (eqrelrigtoring X))).
unfold rigtoringop2int. simpl. destruct x as [ x1 x2 ]. simpl.
set (lu2 := riglunax2 X). set (ru1 := rigrunax1 X). set (m0x := rigmult0x X).
apply pathsdirprod.
- rewrite (lu2 x1). rewrite (m0x x2). apply (ru1 x1).
- rewrite (lu2 x2). rewrite (m0x x1). apply (ru1 x2).
Defined.
Opaque rigtoringlunit2.
Lemma rigtoringrunit2 (X : rig) : isrunit (rigtoringop2 X) (rigtoringunel2 X).
Proof.
unfold isrunit.
apply (setquotunivprop _ (λ x, _ = _)).
intro x.
change (paths (setquotpr (eqrelrigtoring X) (rigtoringop2int X x (rigtoringunel2int X)))
(setquotpr (eqrelrigtoring X) x)).
apply (maponpaths (setquotpr (eqrelrigtoring X))). unfold rigtoringop2int.
simpl. destruct x as [ x1 x2 ]. simpl.
set (ru1 := rigrunax1 X). set (ru2 := rigrunax2 X).
set (lu1 := riglunax1 X). set (mx0 := rigmultx0 X).
apply pathsdirprod.
- rewrite (ru2 x1). rewrite (mx0 x2). apply (ru1 x1).
- rewrite (ru2 x2). rewrite (mx0 x1). apply (lu1 x2).
Defined.
Opaque rigtoringrunit2.
Definition rigtoringisunit (X : rig) : isunit (rigtoringop2 X) (rigtoringunel2 X) :=
make_dirprod (rigtoringlunit2 X) (rigtoringrunit2 X).
Definition rigtoringisunital (X : rig) : isunital (rigtoringop2 X) :=
tpair _ (rigtoringunel2 X) (rigtoringisunit X).
Definition rigtoringismonoidop2 (X : rig) : ismonoidop (rigtoringop2 X) :=
make_dirprod (rigtoringassoc2 X) (rigtoringisunital X).
Lemma rigtoringldistr (X : rig) : isldistr (rigtoringop1 X) (rigtoringop2 X).
Proof.
unfold isldistr.
apply (setquotuniv3prop _ (λ x x' x'', _ = _)).
intros x x' x''.
change (paths (setquotpr (eqrelrigtoring X) (rigtoringop2int X x'' (rigtoringop1int X x x')))
(setquotpr (eqrelrigtoring X) (rigtoringop1int X (rigtoringop2int X x'' x)
(rigtoringop2int X x'' x')))).
apply (maponpaths (setquotpr (eqrelrigtoring X))).
unfold rigtoringop1int. unfold rigtoringop2int. simpl.
set (ld := rigldistr X). set (cm1 := rigcomm1 X).
set (rr := abmonoidoprer (rigop1axs X)).
apply pathsdirprod.
- rewrite (ld _ _ (pr1 x'')). rewrite (ld _ _ (pr2 x'')).
apply (rr _ (pr1 x'' * pr1 x') (pr2 x'' * pr2 x) _).
- rewrite (ld _ _ (pr1 x'')). rewrite (ld _ _ (pr2 x'')).
apply (rr _ (pr1 x'' * pr2 x') (pr2 x'' * pr1 x) _).
Defined.
Opaque rigtoringldistr.
Lemma rigtoringrdistr (X : rig) : isrdistr (rigtoringop1 X) (rigtoringop2 X).
Proof.
unfold isrdistr.
apply (setquotuniv3prop _ (λ x x' x'', _ = _)).
intros x x' x''.
change (paths (setquotpr (eqrelrigtoring X) (rigtoringop2int X (rigtoringop1int X x x') x''))
(setquotpr (eqrelrigtoring X)
(rigtoringop1int X (rigtoringop2int X x x'') (rigtoringop2int X x' x'')))).
apply (maponpaths (setquotpr (eqrelrigtoring X))).
unfold rigtoringop1int. unfold rigtoringop2int. simpl.
set (rd := rigrdistr X). set (cm1 := rigcomm1 X).
set (rr := abmonoidoprer (rigop1axs X)).
apply pathsdirprod.
- rewrite (rd _ _ (pr1 x'')). rewrite (rd _ _ (pr2 x'')).
apply (rr _ (pr1 x' * pr1 x'') (pr2 x * pr2 x'') _).
- rewrite (rd _ _ (pr1 x'')). rewrite (rd _ _ (pr2 x'')).
apply (rr _ (pr1 x' * pr2 x'') (pr2 x * pr1 x'') _).
Defined.
Opaque rigtoringrdistr.
Definition rigtoringdistr (X : rig) : isdistr (rigtoringop1 X) (rigtoringop2 X) :=
make_dirprod (rigtoringldistr X) (rigtoringrdistr X).
Definition rigtoring (X : rig) : ring.
Proof.
split with (@make_setwith2binop (rigtoringcarrier X) (make_dirprod (rigtoringop1 X) (rigtoringop2 X))).
split.
- apply (make_dirprod (rigtoringop1axs X) (rigtoringismonoidop2 X)).
- apply (rigtoringdistr X).
Defined.
(** **** Canonical homomorphism to the ring associated with a rig (ring of differences) *)
Definition toringdiff (X : rig) (x : X) : rigtoring X := setquotpr _ (make_dirprod x 0).
Lemma isbinop1funtoringdiff (X : rig) : @isbinopfun (rigaddabmonoid X) (rigtoring X) (toringdiff X).
Proof.
intros. unfold isbinopfun. intros x x'.
apply (isbinopfuntoabgrdiff (rigaddabmonoid X) x x').
Defined.
Opaque isbinop1funtoringdiff.
Lemma isunital1funtoringdiff (X : rig) : (toringdiff X 0) = 0%ring.
Proof. apply idpath. Defined.
Opaque isunital1funtoringdiff.
Definition isaddmonoidfuntoringdiff (X : rig) :
@ismonoidfun (rigaddabmonoid X) (rigtoring X) (toringdiff X) :=
make_dirprod (isbinop1funtoringdiff X) (isunital1funtoringdiff X).
Lemma isbinop2funtoringdiff (X : rig) :
@isbinopfun (rigmultmonoid X) (ringmultmonoid (rigtoring X)) (toringdiff X).
Proof.
intros. unfold isbinopfun. intros x x'.
change (paths (setquotpr _ (make_dirprod (x * x') 0))
(setquotpr (eqrelrigtoring X)
(rigtoringop2int X (make_dirprod x 0) (make_dirprod x' 0)))).
apply (maponpaths (setquotpr _)). unfold rigtoringop2int. simpl.
apply pathsdirprod.
- rewrite (rigmultx0 X _). rewrite (rigrunax1 X _). apply idpath.
- rewrite (rigmult0x X _). rewrite (rigmultx0 X _). rewrite (rigrunax1 X _).
apply idpath.
Defined.
Lemma isunital2funtoringdiff (X : rig) : (toringdiff X 1) = 1%ring.
Proof. apply idpath. Defined.
Opaque isunital2funtoringdiff.
Definition ismultmonoidfuntoringdiff (X : rig) :
@ismonoidfun (rigmultmonoid X) (ringmultmonoid (rigtoring X)) (toringdiff X) :=
make_dirprod (isbinop2funtoringdiff X) (isunital2funtoringdiff X).
Definition isrigfuntoringdiff (X : rig) : @isrigfun X (rigtoring X) (toringdiff X) :=
make_dirprod (isaddmonoidfuntoringdiff X) (ismultmonoidfuntoringdiff X).
Definition isincltoringdiff (X : rig) (iscanc : ∏ x : X, @isrcancelable X (@op1 X) x) :
isincl (toringdiff X) := isincltoabgrdiff (rigaddabmonoid X) iscanc.
(** **** Relations similar to "greater" or "greater or equal" on the ring associated with a rig *)
Definition rigtoringrel (X : rig) {R : hrel X} (is : @isbinophrel (rigaddabmonoid X) R) :
hrel (rigtoring X) := abgrdiffrel (rigaddabmonoid X) is.
Lemma isringrigtoringmultgt (X : rig) {R : hrel X} (is0 : @isbinophrel (rigaddabmonoid X) R)
(is : isrigmultgt X R) : isringmultgt (rigtoring X) (rigtoringrel X is0).
Proof.
intros.
set (assoc := rigassoc1 X). set (comm := rigcomm1 X).
set (rer := (abmonoidrer (rigaddabmonoid X)) :
∏ a b c d : X, paths ((a + b) + (c + d)) ((a + c) + (b + d))).
set (ld := rigldistr X). set (rd := rigrdistr X).
assert (int : ∏ a b, isaprop (rigtoringrel X is0 a ringunel1 -> rigtoringrel X is0 b ringunel1 ->
rigtoringrel X is0 (a * b) ringunel1)).
{
intros a b.
apply impred. intro.
apply impred. intro.
apply (pr2 _).
}
unfold isringmultgt.
apply (setquotuniv2prop _ (λ a b, make_hProp _ (int a b))).
intros xa1 xa2.
change ((abgrdiffrelint (rigaddabmonoid X) R) xa1 (make_dirprod (@rigunel1 X) (@rigunel1 X)) ->
(abgrdiffrelint (rigaddabmonoid X) R) xa2 (make_dirprod (@rigunel1 X) (@rigunel1 X)) ->
(abgrdiffrelint (rigaddabmonoid X) R (@rigtoringop2int X xa1 xa2)
(make_dirprod (@rigunel1 X) (@rigunel1 X)))).
unfold abgrdiffrelint. simpl. apply hinhfun2. intros t22 t21.
set (c2 := pr1 t21). set (c1 := pr1 t22).
set (r1 := pr2 t21). set (r2 := pr2 t22).
set (x1 := pr1 xa1). set (a1 := pr2 xa1).
set (x2 := pr1 xa2). set (a2 := pr2 xa2).
split with
((x1 * c2 + a1 * c2) + ((c1 * x2 + c1 * c2) + (c1 * a2 + c1 * c2))).
change (pr1 (R (x1 * x2 + a1 * a2 + 0 +
((x1 * c2 + a1 * c2) + ((c1 * x2 + c1 * c2) + (c1 * a2 + c1 * c2))))
(0 + (x1 * a2 + a1 * x2) +
(x1 * c2 + a1 * c2 + ((c1 * x2 + c1 * c2) + (c1 * a2 + c1 * c2)))))).
rewrite (riglunax1 X _). rewrite (rigrunax1 X _).
rewrite (assoc (x1 * c2) _ _).
rewrite (rer _ (a1 * a2) _ _). rewrite (rer _ (a1 * x2) _ _).
rewrite (pathsinv0 (assoc (a1 * a2) _ _)).
rewrite (pathsinv0 (assoc (a1 * x2) _ _)).
rewrite (pathsinv0 (assoc (x1 * x2 + _) _ _)).
rewrite (pathsinv0 (assoc (x1 * a2 + _) _ _)).
rewrite (rer _ (a1 * a2 + _) _ _). rewrite (rer _ (a1 * x2 + _) _ _).
rewrite (pathsinv0 (ld _ _ x1)). rewrite (pathsinv0 (ld _ _ x1)).
rewrite (pathsinv0 (ld _ _ c1)). rewrite (pathsinv0 (ld _ _ c1)).
rewrite (pathsinv0 (ld _ _ a1)). rewrite (pathsinv0 (ld _ _ a1)).
rewrite (pathsinv0 (rd _ _ (x2 + c2))).
rewrite (pathsinv0 (rd _ _ (a2 + c2))).
rewrite (comm (a1 * _) _). rewrite (rer _ (c1 * _) _ _).
rewrite (pathsinv0 (rd _ _ (x2 + c2))).
rewrite (pathsinv0 (rd _ _ (a2 + c2))).
clearbody r1. clearbody r2.
change (pr1 (R (x2 + 0 + c2) (0 + a2 + c2))) in r1.
change (pr1 (R (x1 + 0 + c1) (0 + a1 + c1))) in r2.
rewrite (rigrunax1 X _) in r1. rewrite (riglunax1 X _) in r1.
rewrite (rigrunax1 X _) in r2. rewrite (riglunax1 X _) in r2.
rewrite (comm c1 a1).
apply (is _ _ _ _ r2 r1).
Defined.
Opaque isringrigtoringmultgt.
Definition isdecrigtoringrel (X : rig) {R : hrel X} (is : @isbinophrel (rigaddabmonoid X) R)
(is' : @isinvbinophrel (rigaddabmonoid X) R) (isd : isdecrel R) :
isdecrel (rigtoringrel X is).
Proof. intros. apply (isdecabgrdiffrel (rigaddabmonoid X) is is' isd). Defined.
Lemma isinvringrigtoringmultgt (X : rig) {R : hrel X} (is0 : @isbinophrel (rigaddabmonoid X) R)
(is1 : @isinvbinophrel (rigaddabmonoid X) R) (is : isinvrigmultgt X R) :
isinvringmultgt (rigtoring X) (rigtoringrel X is0).
Proof.
intros. split.
- assert (int : ∏ a b, isaprop (rigtoringrel X is0 (a * b) ringunel1 ->
rigtoringrel X is0 a ringunel1 ->
rigtoringrel X is0 b ringunel1)).
intros.
apply impred. intro.
apply impred. intro.
apply (pr2 _).
apply (setquotuniv2prop _ (λ a b, make_hProp _ (int a b))).
intros xa1 xa2.
change ((abgrdiffrelint (rigaddabmonoid X) R (@rigtoringop2int X xa1 xa2)
(make_dirprod (@rigunel1 X) (@rigunel1 X))) ->
(abgrdiffrelint (rigaddabmonoid X) R) xa1 (make_dirprod (@rigunel1 X) (@rigunel1 X)) ->
(abgrdiffrelint (rigaddabmonoid X) R) xa2 (make_dirprod (@rigunel1 X) (@rigunel1 X))).
unfold abgrdiffrelint. simpl. apply hinhfun2. intros t22 t21.
set (c2 := pr1 t22). set (c1 := pr1 t21).
set (r1 := pr2 t21). set (r2 := pr2 t22).
set (x1 := pr1 xa1). set (a1 := pr2 xa1).
set (x2 := pr1 xa2). set (a2 := pr2 xa2).
simpl in r2. clearbody r2.
change (pr1 (R (x1 * x2 + a1 * a2 + 0 + c2) (0 + (x1 * a2 + a1 * x2) + c2))) in r2.
rewrite (riglunax1 X _) in r2. rewrite (rigrunax1 X _) in r2.
rewrite (rigrunax1 X _). rewrite (riglunax1 X _).
set (r2' := (pr2 is1) _ _ c2 r2). clearbody r1.
change (pr1 (R (x1 + 0 + c1) (0 + a1 + c1))) in r1.
rewrite (riglunax1 X _) in r1. rewrite (rigrunax1 X _) in r1.
set (r1' := (pr2 is1) _ _ c1 r1). split with 0.
rewrite (rigrunax1 X _). rewrite (rigrunax1 X _).
apply ((pr1 is) _ _ _ _ r2' r1').
- assert (int : ∏ a b, isaprop (rigtoringrel X is0 (a * b) ringunel1 ->
rigtoringrel X is0 b ringunel1 ->
rigtoringrel X is0 a ringunel1)).
intros.
apply impred. intro.
apply impred. intro.
apply (pr2 _).
apply (setquotuniv2prop _ (λ a b, make_hProp _ (int a b))).
intros xa1 xa2.
change ((abgrdiffrelint (rigaddabmonoid X) R (@rigtoringop2int X xa1 xa2)
(make_dirprod (@rigunel1 X) (@rigunel1 X))) ->
(abgrdiffrelint (rigaddabmonoid X) R) xa2 (make_dirprod (@rigunel1 X) (@rigunel1 X)) ->
(abgrdiffrelint (rigaddabmonoid X) R) xa1 (make_dirprod (@rigunel1 X) (@rigunel1 X))).
unfold abgrdiffrelint. simpl. apply hinhfun2. intros t22 t21.
set (c2 := pr1 t22). set (c1 := pr1 t21).
set (r1 := pr2 t21). set (r2 := pr2 t22).
set (x1 := pr1 xa1). set (a1 := pr2 xa1).
set (x2 := pr1 xa2). set (a2 := pr2 xa2).
simpl in r2. clearbody r2.
change (pr1 (R (x1 * x2 + a1 * a2 + 0 + c2)
(0 + (x1 * a2 + a1 * x2) + c2))) in r2.
rewrite (riglunax1 X _) in r2. rewrite (rigrunax1 X _) in r2.
rewrite (rigrunax1 X _). rewrite (riglunax1 X _).
set (r2' := (pr2 is1) _ _ c2 r2). clearbody r1.
change (pr1 (R (x2 + 0 + c1) (0 + a2 + c1))) in r1.
rewrite (riglunax1 X _) in r1. rewrite (rigrunax1 X _) in r1.
set (r1' := (pr2 is1) _ _ c1 r1). split with 0.
rewrite (rigrunax1 X _). rewrite (rigrunax1 X _).
apply ((pr2 is) _ _ _ _ r2' r1').
Defined.
Opaque isinvringrigtoringmultgt.
(** **** Relations and the canonical homomorphism to the ring associated with a rig (ring of differences) *)
Definition iscomptoringdiff (X : rig) {L : hrel X} (is0 : @isbinophrel (rigaddabmonoid X) L) :
iscomprelrelfun L (rigtoringrel X is0) (toringdiff X) := iscomptoabgrdiff (rigaddabmonoid X) is0.
Opaque iscomptoringdiff.
Close Scope rig_scope.
(** *** Commutative rings *)
(** **** General definitions *)
Definition iscommring (X : setwith2binop) : UU := iscommringops (@op1 X) (@op2 X).
Definition commring : UU := total2 (λ X : setwith2binop, iscommringops (@op1 X) (@op2 X)).
Definition make_commring (X : setwith2binop) (is : iscommringops (@op1 X) (@op2 X)) :
∑ X0 : setwith2binop, iscommringops op1 op2 :=
tpair (λ X : setwith2binop, iscommringops (@op1 X) (@op2 X)) X is.
Definition commringconstr {X : hSet} (opp1 opp2 : binop X)
(ax11 : isgrop opp1) (ax12 : iscomm opp1)
(ax21 : ismonoidop opp2) (ax22 : iscomm opp2)
(dax : isdistr opp1 opp2) : commring :=
@make_commring (make_setwith2binop X (make_dirprod opp1 opp2))
(make_dirprod (make_dirprod (make_dirprod (make_dirprod ax11 ax12) ax21) dax) ax22).
Definition commringtoring : commring -> ring := λ X : _, @make_ring (pr1 X) (pr1 (pr2 X)).
Coercion commringtoring : commring >-> ring.
Definition ringcomm2 (X : commring) : iscomm (@op2 X) := pr2 (pr2 X).
Definition commringop2axs (X : commring) : isabmonoidop (@op2 X) :=
tpair _ (ringop2axs X) (ringcomm2 X).
Definition ringmultabmonoid (X : commring) : abmonoid :=
make_abmonoid (make_setwithbinop X op2) (make_dirprod (ringop2axs X) (ringcomm2 X)).
Definition commringtocommrig (X : commring) : commrig := make_commrig _ (pr2 X).
Coercion commringtocommrig : commring >-> commrig.
(** **** (X = Y) ≃ (ringiso X Y)
We use the following composition
(X = Y) ≃ (make_commring' X = make_commring' Y)
≃ ((pr1 (make_commring' X)) = (pr1 (make_commring' Y)))
≃ (ringiso X Y)
where the third weak equivalence is given by univalence for ring, [ring_univalence]. We define
[commring'] to be able to use [ring_univalence].
*)
Local Definition commring' : UU :=
∑ D : (∑ X : setwith2binop, isringops (@op1 X) (@op2 X)), iscomm (@op2 (pr1 D)).
Local Definition make_commring' (CR : commring) : commring' :=
tpair _ (tpair _ (pr1 CR) (dirprod_pr1 (pr2 CR))) (dirprod_pr2 (pr2 CR)).
Definition commring_univalence_weq1 : commring ≃ commring' :=
weqtotal2asstol
(λ X : setwith2binop, isringops (@op1 X) (@op2 X))
(fun y : (∑ (X : setwith2binop), isringops (@op1 X) (@op2 X)) => iscomm (@op2 (pr1 y))).
Definition commring_univalence_weq1' (X Y : commring) : (X = Y) ≃ (make_commring' X = make_commring' Y) :=
make_weq _ (@isweqmaponpaths commring commring' commring_univalence_weq1 X Y).
Definition commring_univalence_weq2 (X Y : commring) :
((make_commring' X) = (make_commring' Y)) ≃ ((pr1 (make_commring' X)) = (pr1 (make_commring' Y))).
Proof.
use subtypeInjectivity.
intros w. use isapropiscomm.
Defined.
Opaque commring_univalence_weq2.
Definition commring_univalence_weq3 (X Y : commring) :
((pr1 (make_commring' X)) = (pr1 (make_commring' Y))) ≃ (ringiso X Y) :=
ring_univalence (pr1 (make_commring' X)) (pr1 (make_commring' Y)).
Definition commring_univalence_map (X Y : commring) : (X = Y) -> (ringiso X Y).
Proof.
intros e. induction e. exact (idrigiso X).
Defined.
Lemma commring_univalence_isweq (X Y : commring) : isweq (commring_univalence_map X Y).
Proof.
use isweqhomot.
- exact (weqcomp (commring_univalence_weq1' X Y)
(weqcomp (commring_univalence_weq2 X Y) (commring_univalence_weq3 X Y))).
- intros e. induction e.
use (pathscomp0 weqcomp_to_funcomp_app).
use weqcomp_to_funcomp_app.
- use weqproperty.
Defined.
Opaque commring_univalence_isweq.
Definition commring_univalence (X Y : commring) : (X = Y) ≃ (ringiso X Y).
Proof.
use make_weq.
- exact (commring_univalence_map X Y).
- exact (commring_univalence_isweq X Y).
Defined.
Opaque commring_univalence.
(** **** Computational lemmas for commutative rings *)
Local Open Scope ring_scope.
Lemma commringismultcancelableif (X : commring) (x : X) (isl : ∏ y, paths (x * y) 0 -> y = 0) :
iscancelable op2 x.
Proof.
intros. split.
- apply (ringismultlcancelableif X x isl).
- assert (isr : ∏ y, paths (y * x) 0 -> y = 0).
intros y e. rewrite (ringcomm2 X _ _) in e. apply (isl y e).
apply (ringismultrcancelableif X x isr).
Defined.
Opaque commringismultcancelableif.
Close Scope ring_scope.
(** **** Subobjects *)
Lemma iscommringcarrier {X : commring} (A : @subring X) : iscommringops (@op1 A) (@op2 A).
Proof.
intros. split with (isringcarrier A).
apply (pr2 (@isabmonoidcarrier (ringmultabmonoid X) (multsubmonoid A))).
Defined.
Definition carrierofasubcommring {X : commring} (A : @subring X) : commring :=
make_commring A (iscommringcarrier A).
(** **** Quotient objects *)
Lemma iscommringquot {X : commring} (R : @ringeqrel X) :
iscommringops (@op1 (setwith2binopquot R)) (@op2 (setwith2binopquot R)).
Proof.
intros. split with (isringquot R).
apply (pr2 (@isabmonoidquot (ringmultabmonoid X) (ringmultmonoideqrel R))).
Defined.
Definition commringquot {X : commring} (R : @ringeqrel X) : commring :=
make_commring (setwith2binopquot R) (iscommringquot R).
(** **** Direct products *)
Lemma iscommringdirprod (X Y : commring) :
iscommringops (@op1 (setwith2binopdirprod X Y)) (@op2 (setwith2binopdirprod X Y)).
Proof.
intros. split with (isringdirprod X Y).
apply (pr2 (isabmonoiddirprod (ringmultabmonoid X) (ringmultabmonoid Y))).
Defined.
Definition commringdirprod (X Y : commring) : commring :=
make_commring (setwith2binopdirprod X Y) (iscommringdirprod X Y).
(** **** Opposite commutative rings *)
Local Open Scope ring.
(** We reuse much of the proof for general rigs *)
Definition opposite_commring (X : commring) : commring :=
((pr1 (X⁰)),, (make_dirprod (pr2 (X⁰)) (fun x y => @ringcomm2 X y x))).
(** Commutativity makes taking the opposite trivial *)
Definition iso_commring_opposite (X : commring) : rigiso X (opposite_commring X) :=
iso_commrig_opposite X.
Local Close Scope rig.
(** **** Commutative rigs to commutative rings *)
Local Open Scope rig_scope.
Lemma commrigtocommringcomm2 (X : commrig) : iscomm (rigtoringop2 X).
Proof.
unfold iscomm.
apply (setquotuniv2prop _ (λ x x', _ = _)).
intros x x'.
change (paths (setquotpr (eqrelrigtoring X) (rigtoringop2int X x x'))
(setquotpr (eqrelrigtoring X) (rigtoringop2int X x' x))).
apply (maponpaths (setquotpr (eqrelrigtoring X))).
unfold rigtoringop2int.
set (cm1 := rigcomm1 X). set (cm2 := rigcomm2 X).
apply pathsdirprod.
- rewrite (cm2 (pr1 x) (pr1 x')). rewrite (cm2 (pr2 x) (pr2 x')).
apply idpath.
- rewrite (cm2 (pr1 x) (pr2 x')). rewrite (cm2 (pr2 x) (pr1 x')).
apply cm1.
Defined.
Opaque commrigtocommringcomm2.
Definition commrigtocommring (X : commrig) : commring.
Proof.
split with (rigtoring X). split.
- apply (pr2 (rigtoring X)).
- apply (commrigtocommringcomm2 X).
Defined.
Close Scope rig_scope.
(** **** Rings of fractions *)
Local Open Scope ring_scope.
Definition commringfracop1int (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
binop (X × S) := λ x1s1 x2s2 : dirprod X S,
@make_dirprod X S (((pr1 (pr2 x2s2)) * (pr1 x1s1)) +
((pr1 (pr2 x1s1)) * (pr1 x2s2)))
(@op S (pr2 x1s1) (pr2 x2s2)).
Definition commringfracop2int (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
binop (X × S) := abmonoidfracopint (ringmultabmonoid X) S.
Definition commringfracunel1int (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
dirprod X S := make_dirprod 0 (unel S).
Definition commringfracunel2int (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
dirprod X S := make_dirprod 1 (unel S).
Definition commringfracinv1int (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
dirprod X S -> dirprod X S := λ xs : _, make_dirprod ((-1) * (pr1 xs)) (pr2 xs).
Definition eqrelcommringfrac (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
eqrel (X × S) := eqrelabmonoidfrac (ringmultabmonoid X) S.
Lemma commringfracl1 (X : commring) (x1 x2 x3 x4 a1 a2 s1 s2 s3 s4 : X)
(eq1 : paths ((x1 * s2) * a1) ((x2 * s1) * a1))
(eq2 : paths ((x3 * s4) * a2) ((x4 * s3) * a2)) :
paths ((((s3 * x1) + (s1 * x3)) * (s2 * s4)) * (a1 * a2))
((((s4 * x2) + (s2 * x4)) * (s1 * s3)) * (a1 * a2)).
Proof.
intros.
set (rdistr := ringrdistr X). set (assoc2 := ringassoc2 X).
set (op2axs := commringop2axs X). set (comm2 := ringcomm2 X).
set (rer := abmonoidoprer op2axs).
rewrite (rdistr (s3 * x1) (s1 * x3) (s2 * s4)).
rewrite (rdistr (s4 * x2) (s2 * x4) (s1 * s3)).
rewrite (rdistr ((s3 * x1) * (s2 * s4)) ((s1 * x3) * (s2 * s4)) (a1 * a2)).
rewrite (rdistr ((s4 * x2) * (s1 * s3)) ((s2 * x4) * (s1 * s3)) (a1 * a2)).
clear rdistr.
assert (e1 : paths (((s3 * x1) * (s2 * s4)) * (a1 * a2))
(((s4 * x2) * (s1 * s3)) * (a1 * a2))).
{
destruct (assoc2 (s3 * x1) s2 s4).
rewrite (assoc2 s3 x1 s2). rewrite (rer (s3 * (x1 * s2)) s4 a1 a2).
rewrite (assoc2 s3 (x1 * s2) a1).
destruct (assoc2 (s4 * x2) s1 s3).
rewrite (assoc2 s4 x2 s1). rewrite (rer (s4 * (x2 * s1)) s3 a1 a2).
rewrite (assoc2 s4 (x2 * s1) a1). destruct eq1.
rewrite (comm2 s3 ((x1 * s2) * a1)). rewrite (comm2 s4 ((x1 * s2) * a1)).
rewrite (rer ((x1 * s2) * a1) s3 s4 a2).
apply idpath.
}
assert (e2 : paths (((s1 * x3) * (s2 * s4)) * (a1 * a2))
(((s2 * x4) * (s1 * s3)) * (a1 * a2))).
{
destruct (comm2 s4 s2). destruct (comm2 s3 s1). destruct (comm2 a2 a1).
destruct (assoc2 (s1 * x3) s4 s2). destruct (assoc2 (s2 * x4) s3 s1).
rewrite (assoc2 s1 x3 s4). rewrite (assoc2 s2 x4 s3).
rewrite (rer (s1 * (x3 * s4)) s2 a2 a1).
rewrite (rer (s2 * (x4 * s3)) s1 a2 a1).
rewrite (assoc2 s1 (x3 * s4) a2).
rewrite (assoc2 s2 (x4 * s3) a2).
destruct eq2. destruct (comm2 ((x3 * s4) * a2) s1).
destruct (comm2 ((x3 *s4) * a2) s2).
rewrite (rer ((x3 * s4) * a2) s1 s2 a1).
apply idpath.
}
destruct e1. destruct e2. apply idpath.
Defined.
Opaque commringfracl1.
Lemma commringfracop1comp (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
iscomprelrelfun2 (eqrelcommringfrac X S) (eqrelcommringfrac X S) (commringfracop1int X S).
Proof.
intros. intros xs1 xs2 xs3 xs4. simpl.
set (ff := @hinhfun2). simpl in ff. apply ff. clear ff.
intros tt1 tt2. split with (@op S (pr1 tt1) (pr1 tt2)).
set (eq1 := pr2 tt1). simpl in eq1.
set (eq2 := pr2 tt2). simpl in eq2.
unfold pr1carrier.
apply (commringfracl1 X (pr1 xs1) (pr1 xs2) (pr1 xs3) (pr1 xs4)
(pr1 (pr1 tt1)) (pr1 (pr1 tt2)) (pr1 (pr2 xs1))
(pr1 (pr2 xs2)) (pr1 (pr2 xs3)) (pr1 (pr2 xs4)) eq1 eq2).
Defined.
Opaque commringfracop1comp.
Definition commringfracop1 (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
binop (setquotinset (eqrelcommringfrac X S)) :=
setquotfun2 (eqrelcommringfrac X S) (eqrelcommringfrac X S)
(commringfracop1int X S) (commringfracop1comp X S).
Lemma commringfracl2 (X : commring) (x x' x'' s s' s'' : X) :
paths ((s'' * ((s' * x) + (s * x'))) + ((s * s') * x''))
(((s' * s'') * x) + (s * ((s'' * x') + (s' * x'')))).
Proof.
intros.
set (ldistr := ringldistr X). set (comm2 := ringcomm2 X).
set (assoc2 := ringassoc2 X). set (assoc1 := ringassoc1 X).
rewrite (ldistr (s' * x) (s * x') s'').
rewrite (ldistr (s'' * x') (s' * x'') s).
destruct (comm2 s'' s').
destruct (assoc2 s'' s' x). destruct (assoc2 s'' s x').
destruct (assoc2 s s'' x').
destruct (comm2 s s'').
destruct (assoc2 s s' x'').
apply (assoc1 ((s'' * s') * x) ((s * s'') * x') ((s * s') * x'')).
Defined.
Opaque commringfracl2.
Lemma commringfracassoc1 (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
isassoc (commringfracop1 X S).
Proof.
intros.
set (R := eqrelcommringfrac X S).
set (add1int := commringfracop1int X S).
set (add1 := commringfracop1 X S).
unfold isassoc.
assert (int : ∏ (xs xs' xs'' : dirprod X S),
paths (setquotpr R (add1int (add1int xs xs') xs''))
(setquotpr R (add1int xs (add1int xs' xs'')))).
unfold add1int. unfold commringfracop1int. intros xs xs' xs''.
apply (@maponpaths _ _ (setquotpr R)). simpl. apply pathsdirprod.
- unfold pr1carrier.
apply (commringfracl2 X (pr1 xs) (pr1 xs') (pr1 xs'') (pr1 (pr2 xs))
(pr1 (pr2 xs')) (pr1 (pr2 xs''))).
- apply (invmaponpathsincl _ (isinclpr1carrier (pr1 S))).
unfold pr1carrier. simpl. set (assoc2 := ringassoc2 X).
apply (assoc2 (pr1 (pr2 xs)) (pr1 (pr2 xs')) (pr1 (pr2 xs''))).
- apply (setquotuniv3prop R (λ x x' x'', _ = _)), int.
Defined.
Opaque commringfracassoc1.
Lemma commringfraccomm1 (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
iscomm (commringfracop1 X S).
Proof.
intros.
set (R := eqrelcommringfrac X S).
set (add1int := commringfracop1int X S).
set (add1 := commringfracop1 X S).
unfold iscomm.
apply (setquotuniv2prop _ (λ x x', _ = _)).
intros xs xs'.
apply (@maponpaths _ _ (setquotpr R) (add1int xs xs') (add1int xs' xs)).
unfold add1int. unfold commringfracop1int.
destruct xs as [ x s ]. destruct s as [ s iss ].
destruct xs' as [ x' s' ]. destruct s' as [ s' iss' ].
simpl.
apply pathsdirprod.
- change (paths ((s' * x) + (s * x')) ((s * x') + (s' * x))).
destruct (ringcomm1 X (s' * x) (s * x')). apply idpath.
- apply (invmaponpathsincl _ (isinclpr1carrier (pr1 S))).
simpl. change (paths (s * s') (s' * s)). apply (ringcomm2 X).
Defined.
Opaque commringfraccomm1.
Definition commringfracunel1 (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
setquot (eqrelcommringfrac X S) := setquotpr (eqrelcommringfrac X S) (commringfracunel1int X S).
Definition commringfracunel2 (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
setquot (eqrelcommringfrac X S) := setquotpr (eqrelcommringfrac X S) (commringfracunel2int X S).
Lemma commringfracinv1comp (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
iscomprelrelfun (eqrelcommringfrac X S) (eqrelcommringfrac X S) (commringfracinv1int X S).
Proof.
intros.
set (assoc2 := ringassoc2 X). intros xs xs'. simpl.
set (ff := @hinhfun). simpl in ff. apply ff. clear ff.
intro tt0. split with (pr1 tt0).
set (x := pr1 xs). set (s := pr1 (pr2 xs)).
set (x' := pr1 xs'). set (s' := pr1 (pr2 xs')).
set (a0 := pr1 (pr1 tt0)).
change (paths (-1 * x * s' * a0) (-1 * x' * s * a0)).
rewrite (assoc2 -1 x s'). rewrite (assoc2 -1 x' s).
rewrite (assoc2 -1 (x * s') a0). rewrite (assoc2 -1 (x' * s) a0).
apply (maponpaths (λ x0 : X, -1 * x0) (pr2 tt0)).
Defined.
Definition commringfracinv1 (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
setquot (eqrelcommringfrac X S) → setquot (eqrelcommringfrac X S) :=
setquotfun (eqrelcommringfrac X S) (eqrelcommringfrac X S)
(commringfracinv1int X S) (commringfracinv1comp X S).
Lemma commringfracisinv1 (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
isinv (commringfracop1 X S) (commringfracunel1 X S) (commringfracinv1 X S).
Proof.
intros.
assert (isl : islinv (commringfracop1 X S) (commringfracunel1 X S) (commringfracinv1 X S)).
{
set (R := eqrelcommringfrac X S).
set (add1int := commringfracop1int X S).
set (add1 := commringfracop1 X S).
set (inv1 := commringfracinv1 X S).
set (inv1int := commringfracinv1int X S).
set (qunel1int := commringfracunel1int X S).
set (qunel1 := commringfracunel1 X S).
set (assoc2 := ringassoc2 X).
unfold islinv.
apply (setquotunivprop _ (λ x, _ = _)).
intro xs.
apply (iscompsetquotpr R (add1int (inv1int xs) xs) qunel1int).
simpl. apply hinhpr. split with (unel S).
set (x := pr1 xs). set (s := pr1 (pr2 xs)).
change (paths ((s * (-1 * x) + s * x) * 1 * 1) (0 * (s * s) * 1)).
destruct (ringldistr X (-1 * x) x s).
rewrite (ringmultwithminus1 X x). rewrite (ringlinvax1 X x).
rewrite (ringmultx0 X s). rewrite (ringmult0x X 1).
rewrite (ringmult0x X 1). rewrite (ringmult0x X (s * s)).
apply (pathsinv0 (ringmult0x X 1)).
}
apply (make_dirprod isl (weqlinvrinv (commringfracop1 X S) (commringfraccomm1 X S)
(commringfracunel1 X S) (commringfracinv1 X S) isl)).
Defined.
Opaque commringfracisinv1.
Lemma commringfraclunit1 (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
islunit (commringfracop1 X S) (commringfracunel1 X S).
Proof.
intros.
set (R := eqrelcommringfrac X S). set (add1int := commringfracop1int X S).
set (add1 := commringfracop1 X S). set (un1 := commringfracunel1 X S).
unfold islunit.
apply (setquotunivprop R (λ x, _ = _)).
intro xs.
assert (e0 : paths (add1int (commringfracunel1int X S) xs) xs).
{
unfold add1int. unfold commringfracop1int.
destruct xs as [ x s ]. destruct s as [ s iss ].
apply pathsdirprod.
- simpl. change (paths ((s * 0) + (1 * x)) x).
rewrite (@ringmultx0 X s).
rewrite (ringlunax2 X x).
rewrite (ringlunax1 X x).
apply idpath.
- apply (invmaponpathsincl _ (isinclpr1carrier (pr1 S))).
change (paths (1 * s) s). apply (ringlunax2 X s).
}
apply (maponpaths (setquotpr R) e0).
Defined.
Opaque commringfraclunit1.
Lemma commringfracrunit1 (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
isrunit (commringfracop1 X S) (commringfracunel1 X S).
Proof.
intros.
apply (weqlunitrunit (commringfracop1 X S) (commringfraccomm1 X S)
(commringfracunel1 X S) (commringfraclunit1 X S)).
Defined.
Opaque commringfracrunit1.
Definition commringfracunit1 (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
ismonoidop (commringfracop1 X S) :=
tpair _ (commringfracassoc1 X S)
(tpair _ (commringfracunel1 X S)
(make_dirprod (commringfraclunit1 X S) (commringfracrunit1 X S))).
Definition commringfracop2 (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
binop (setquotinset (eqrelcommringfrac X S)) := abmonoidfracop (ringmultabmonoid X) S.
Lemma commringfraccomm2 (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
iscomm (commringfracop2 X S).
Proof. intros. apply (commax (abmonoidfrac (ringmultabmonoid X) S)). Defined.
Opaque commringfraccomm2.
Lemma commringfracldistr (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
isldistr (commringfracop1 X S) (commringfracop2 X S).
Proof.
intros.
set (R := eqrelcommringfrac X S).
set (mult1int := commringfracop2int X S).
set (mult1 := commringfracop2 X S).
set (add1int := commringfracop1int X S).
set (add1 := commringfracop1 X S).
unfold isldistr.
apply (setquotuniv3prop _ (λ x x' x'', _ = _)).
intros xs xs' xs''.
apply (iscompsetquotpr R (mult1int xs'' (add1int xs xs'))
(add1int (mult1int xs'' xs) (mult1int xs'' xs'))).
destruct xs as [ x s ]. destruct xs' as [ x' s' ].
destruct xs'' as [ x'' s'' ]. destruct s'' as [ s'' iss'' ].
simpl. apply hinhpr. split with (unel S).
destruct s as [ s iss ]. destruct s' as [ s' iss' ]. simpl.
change (paths (((x'' * ((s' * x) + (s * x'))) * ((s'' * s) * (s'' * s'))) * 1)
(((((s'' * s') * (x'' * x)) + ((s'' * s) * (x'' * x'))) *
(s'' * (s * s'))) * 1)).
rewrite (ringldistr X (s' * x) (s * x') x'').
rewrite (ringrdistr X _ _ ((s'' * s) * (s'' * s'))).
rewrite (ringrdistr X _ _ (s'' * (s * s'))).
set (assoc := ringassoc2 X). set (comm := ringcomm2 X).
set (rer := @abmonoidoprer X (@op2 X) (commringop2axs X)).
assert (e1 : paths ((x'' * (s' * x)) * ((s'' * s) * (s'' * s')))
(((s'' * s') * (x'' * x)) * (s'' * (s * s')))).
{
destruct (assoc x'' s' x). destruct (comm s' x'').
rewrite (assoc s' x'' x). destruct (comm (x'' * x) s').
destruct (comm (x'' * x) (s'' * s')). destruct (assoc s'' s s').
destruct (comm (s'' * s') (s'' * s)). destruct (comm s' (s'' * s)).
destruct (rer (x'' * x) s' (s'' * s') (s'' * s)).
apply idpath.
}
assert (e2 : paths ((x'' * (s * x')) * ((s'' * s) * (s'' * s')))
(((s'' * s) * (x'' * x')) * (s'' * (s * s')))).
{
destruct (assoc x'' s x'). destruct (comm s x'').
rewrite (assoc s x'' x'). destruct (comm (x'' * x') s).
destruct (comm (x'' * x') (s'' * s)).
destruct (rer (x'' * x') (s'' * s) s (s'' * s')).
destruct (assoc s s'' s'). destruct (assoc s'' s s').
destruct (comm s s'').
apply idpath.
}
rewrite e1. rewrite e2. apply idpath.
Defined.
Opaque commringfracldistr.
Lemma commringfracrdistr (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
isrdistr (commringfracop1 X S) (commringfracop2 X S).
Proof.
intros.
apply (weqldistrrdistr (commringfracop1 X S) (commringfracop2 X S)
(commringfraccomm2 X S) (commringfracldistr X S)).
Defined.
(** Notes :
1. Construction of the addition on the multiplicative monoid of fractions
requires only commutativity and associativity of multiplication and (right)
distributivity. No properties of the addition are used.
2. The proof of associtivity for the addition on the multiplicative monoid of
fractions requires in the associativity of the original addition but no other
properties.
*)
Definition commringfrac (X : commring) (S : @subabmonoid (ringmultabmonoid X)) : commring.
Proof.
intros.
set (R := eqrelcommringfrac X S).
set (mult1 := commringfracop2 X S).
set (add1 := commringfracop1 X S).
set (uset := setquotinset R).
apply (commringconstr add1 mult1).
- split with (commringfracunit1 X S).
split with (commringfracinv1 X S).
apply (commringfracisinv1 X S).
- apply (commringfraccomm1 X S).
- apply (pr2 (abmonoidfrac (ringmultabmonoid X) S)).
- apply (commringfraccomm2 X S).
- apply (make_dirprod (commringfracldistr X S) (commringfracrdistr X S)).
Defined.
Definition prcommringfrac (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
X -> S -> commringfrac X S := λ x s, setquotpr _ (make_dirprod x s).
Lemma invertibilityincommringfrac (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
∏ a a' : S, isinvertible (@op2 (commringfrac X S)) (prcommringfrac X S (pr1 a) a').
Proof.
intros.
apply (invertibilityinabmonoidfrac (ringmultabmonoid X) S).
Defined.
(** **** Canonical homomorphism to the ring of fractions *)
Definition tocommringfrac (X : commring) (S : @subabmonoid (ringmultabmonoid X)) (x : X) :
commringfrac X S := setquotpr _ (make_dirprod x (unel S)).
Lemma isbinop1funtocommringfrac (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
@isbinopfun X (commringfrac X S) (tocommringfrac X S).
Proof.
intros. unfold isbinopfun. intros x x'.
change (paths (setquotpr _ (make_dirprod (x + x') (unel S)))
(setquotpr (eqrelcommringfrac X S)
(commringfracop1int X S (make_dirprod x (unel S))
(make_dirprod x' (unel S))))).
apply (maponpaths (setquotpr _)). unfold commringfracop1int.
simpl. apply pathsdirprod.
- rewrite (ringlunax2 X _). rewrite (ringlunax2 X _). apply idpath.
- change (paths (unel S) (op (unel S) (unel S))).
apply (pathsinv0 (runax S _)).
Defined.
Opaque isbinop1funtocommringfrac.
Lemma isunital1funtocommringfrac (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
(tocommringfrac X S 0) = 0.
Proof. intros. apply idpath. Defined.
Opaque isunital1funtocommringfrac.
Definition isaddmonoidfuntocommringfrac (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
@ismonoidfun X (commringfrac X S) (tocommringfrac X S) :=
make_dirprod (isbinop1funtocommringfrac X S) (isunital1funtocommringfrac X S).
Definition tocommringfracandminus0 (X : commring) (S : @subabmonoid (ringmultabmonoid X)) (x : X) :
paths (tocommringfrac X S (- x)) (- tocommringfrac X S x) :=
grinvandmonoidfun _ _ (isaddmonoidfuntocommringfrac X S) x.
Definition tocommringfracandminus (X : commring) (S : @subabmonoid (ringmultabmonoid X)) (x y : X) :
paths (tocommringfrac X S (x - y)) (tocommringfrac X S x - tocommringfrac X S y).
Proof.
intros.
rewrite ((isbinop1funtocommringfrac X S x (- y)) :
paths (tocommringfrac X S (x - y))
((tocommringfrac X S x + tocommringfrac X S (- y)))).
rewrite (tocommringfracandminus0 X S y).
apply idpath.
Defined.
Opaque tocommringfracandminus.
Definition isbinop2funtocommringfrac (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
@isbinopfun (ringmultmonoid X) (ringmultmonoid (commringfrac X S)) (tocommringfrac X S) :=
isbinopfuntoabmonoidfrac (ringmultabmonoid X) S.
Opaque isbinop2funtocommringfrac.
Lemma isunital2funtocommringfrac (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
(tocommringfrac X S 1) = 1.
Proof. intros. apply idpath. Defined.
Opaque isunital2funtocommringfrac.
Definition ismultmonoidfuntocommringfrac (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
@ismonoidfun (ringmultmonoid X) (ringmultmonoid (commringfrac X S)) (tocommringfrac X S) :=
make_dirprod (isbinop2funtocommringfrac X S) (isunital2funtocommringfrac X S).
Definition isringfuntocommringfrac (X : commring) (S : @subabmonoid (ringmultabmonoid X)) :
@isringfun X (commringfrac X S) (tocommringfrac X S) :=
make_dirprod (isaddmonoidfuntocommringfrac X S) (ismultmonoidfuntocommringfrac X S).
(** **** Ring of fractions in the case when all elements which are being inverted are cancelable *)
Definition hrelcommringfrac0 (X : commring) (S : @submonoid (ringmultabmonoid X)) :
hrel (X × S) :=
λ xa yb : setdirprod X S, (pr1 xa) * (pr1 (pr2 yb)) = (pr1 yb) * (pr1 (pr2 xa)).
Lemma weqhrelhrel0commringfrac (X : commring) (S : @submonoid (ringmultabmonoid X))
(iscanc : ∏ a : S, isrcancelable (@op2 X) (pr1carrier _ a)) (xa xa' : dirprod X S) :
(eqrelcommringfrac X S xa xa') ≃ (hrelcommringfrac0 X S xa xa').
Proof.
intros. unfold eqrelabmonoidfrac. unfold hrelabmonoidfrac. simpl.
apply weqimplimpl.
- apply (@hinhuniv _ (_ = _)).
intro ae. destruct ae as [ a eq ].
apply (invmaponpathsincl _ (iscanc a) _ _ eq).
- intro eq. apply hinhpr. split with (unel S).
rewrite (ringrunax2 X). rewrite (ringrunax2 X).
apply eq.
- apply (isapropishinh _).
- apply (setproperty X).
Defined.
Opaque weqhrelhrel0abmonoidfrac.
Lemma isinclprcommringfrac (X : commring) (S : @submonoid (ringmultabmonoid X))
(iscanc : ∏ a : S, isrcancelable (@op2 X) (pr1carrier _ a)) :
∏ a' : S, isincl (λ x, prcommringfrac X S x a').
Proof.
intros. apply isinclbetweensets.
apply (setproperty X). apply (setproperty (commringfrac X S)).
intros x x'. intro e.
set (e' := invweq (weqpathsinsetquot
(eqrelcommringfrac X S) (make_dirprod x a') (make_dirprod x' a')) e).
set (e'' := weqhrelhrel0commringfrac
X S iscanc (make_dirprod _ _) (make_dirprod _ _) e').
simpl in e''. apply (invmaponpathsincl _ (iscanc a')). apply e''.
Defined.
Definition isincltocommringfrac (X : commring) (S : @submonoid (ringmultabmonoid X))
(iscanc : ∏ a : S, isrcancelable (@op2 X) (pr1carrier _ a)) :
isincl (tocommringfrac X S) := isinclprcommringfrac X S iscanc (unel S).
Lemma isdeceqcommringfrac (X : commring) (S : @submonoid (ringmultabmonoid X))
(iscanc : ∏ a : S, isrcancelable (@op2 X) (pr1carrier _ a)) (is : isdeceq X) :
isdeceq (commringfrac X S).
Proof.
intros. apply (isdeceqsetquot (eqrelcommringfrac X S)). intros xa xa'.
apply (isdecpropweqb (weqhrelhrel0commringfrac X S iscanc xa xa')).
apply isdecpropif. unfold isaprop. simpl.
set (int := setproperty X (pr1 xa * pr1 (pr2 xa')) (pr1 xa' * pr1 (pr2 xa))).
simpl in int. apply int. unfold hrelcommringfrac0.
simpl. apply (is _ _).
Defined.
(** **** Relations similar to "greater" or "greater or equal" on the rings of fractions *)
Lemma ispartbinopcommringfracgt (X : commring) (S : @submonoid (ringmultabmonoid X)) {R : hrel X}
(is0 : @isbinophrel (rigaddabmonoid X) R) (is1 : isringmultgt X R)
(is2 : ∏ c : X, S c -> R c 0) : @ispartbinophrel (ringmultabmonoid X) S R.
Proof.
intros. split.
- intros a b c s rab.
apply (isringmultgttoislringmultgt X is0 is1 _ _ _ (is2 c s) rab).
- intros a b c s rab.
apply (isringmultgttoisrringmultgt X is0 is1 _ _ _ (is2 c s) rab).
Defined.
Definition commringfracgt (X : commring) (S : @submonoid (ringmultabmonoid X)) {R : hrel X}
(is0 : @isbinophrel (rigaddabmonoid X) R) (is1 : isringmultgt X R)
(is2 : ∏ c : X, S c -> R c 0) : hrel (commringfrac X S) :=
abmonoidfracrel (ringmultabmonoid X) S (ispartbinopcommringfracgt X S is0 is1 is2).
Lemma isringmultcommringfracgt (X : commring) (S : @submonoid (ringmultabmonoid X)) {R : hrel X}
(is0 : @isbinophrel (rigaddabmonoid X) R) (is1 : isringmultgt X R)
(is2 : ∏ c : X, S c -> R c 0) : isringmultgt (commringfrac X S) (commringfracgt X S is0 is1 is2).
Proof.
intros.
set (rer2 := (abmonoidrer (ringmultabmonoid X)) :
∏ a b c d : X, paths ((a * b) * (c * d)) ((a * c) * (b * d))).
apply islringmultgttoisringmultgt.
assert (int : ∏ (a b c : ringaddabgr (commringfrac X S)),
isaprop (commringfracgt X S is0 is1 is2 c 0 ->
commringfracgt X S is0 is1 is2 a b ->
commringfracgt X S is0 is1 is2 (c * a) (c * b))).
{
intros a b c.
apply impred. intro.
apply impred. intro.
apply (pr2 _).
}
apply (setquotuniv3prop _ (λ a b c, make_hProp _ (int a b c))).
intros xa1 xa2 xa3.
change (abmonoidfracrelint (ringmultabmonoid X) S R xa3 (make_dirprod 0 (unel S)) ->
abmonoidfracrelint (ringmultabmonoid X) S R xa1 xa2 ->
abmonoidfracrelint (ringmultabmonoid X) S R
(commringfracop2int X S xa3 xa1)
(commringfracop2int X S xa3 xa2)).
simpl. apply hinhfun2. intros t21 t22.
set (c1s := pr1 t21). set (c1 := pr1 c1s). set (r1 := pr2 t21).
set (c2s := pr1 t22). set (c2 := pr1 c2s). set (r2 := pr2 t22).
set (x1 := pr1 xa1). set (a1 := pr1 (pr2 xa1)).
set (x2 := pr1 xa2). set (a2 := pr1 (pr2 xa2)).
set (x3 := pr1 xa3). set (a3 := pr1 (pr2 xa3)).
split with (@op S c1s c2s).
change (pr1 (R (x3 * x1 * (a3 * a2) * (c1 * c2))
(x3 * x2 * (a3 * a1) * (c1 * c2)))).
rewrite (ringcomm2 X a3 a2).
rewrite (ringcomm2 X a3 a1).
rewrite (ringassoc2 X _ _ (c1 * c2)).
rewrite (ringassoc2 X (x3 * x2) _ (c1 * c2)).
rewrite (rer2 _ a3 c1 _).
rewrite (rer2 _ a3 c1 _).
rewrite (ringcomm2 X a2 c1).
rewrite (ringcomm2 X a1 c1).
rewrite (pathsinv0 (ringassoc2 X (x3 * x1) _ _)).
rewrite (pathsinv0 (ringassoc2 X (x3 * x2) _ _)).
rewrite (rer2 _ x1 c1 _). rewrite (rer2 _ x2 c1 _).
rewrite (ringcomm2 X a3 c2).
rewrite (pathsinv0 (ringassoc2 X _ c2 a3)).
rewrite (pathsinv0 (ringassoc2 X _ c2 _)).
apply ((isringmultgttoisrringmultgt X is0 is1) _ _ _ (is2 _ (pr2 (pr2 xa3)))).
rewrite (ringassoc2 X _ _ c2). rewrite (ringassoc2 X _ (x2 * a1) c2).
simpl in r1. clearbody r1. simpl in r2. clearbody r2.
change (pr1 (R (x3 * 1 * c1) (0 * a3 * c1))) in r1.
rewrite (ringrunax2 _ _) in r1. rewrite (ringmult0x X _) in r1.
rewrite (ringmult0x X _) in r1.
apply ((isringmultgttoislringmultgt X is0 is1) _ _ _ r1 r2).
Defined.
Opaque isringmultcommringfracgt.
Lemma isringaddcommringfracgt (X : commring) (S : @submonoid (ringmultabmonoid X)) {R : hrel X}
(is0 : @isbinophrel (rigaddabmonoid X) R) (is1 : isringmultgt X R)
(is2 : ∏ c : X, S c -> R c 0) : @isbinophrel (commringfrac X S) (commringfracgt X S is0 is1 is2).
Proof.
intros.
set (rer2 := (abmonoidrer (ringmultabmonoid X)) :
∏ a b c d : X, paths ((a * b) * (c * d)) ((a * c) * (b * d))).
apply isbinophrelif. intros a b. apply (ringcomm1 (commringfrac X S) a b).
assert (int : ∏ (a b c : ringaddabgr (commringfrac X S)),
isaprop (commringfracgt X S is0 is1 is2 a b ->
commringfracgt X S is0 is1 is2 (op c a) (op c b))).
{
intros a b c.
apply impred. intro.
apply (pr2 _).
}
apply (setquotuniv3prop _ (λ a b c, make_hProp _ (int a b c))).
intros xa1 xa2 xa3.
change (abmonoidfracrelint (ringmultabmonoid X) S R xa1 xa2 ->
abmonoidfracrelint (ringmultabmonoid X) S R
(commringfracop1int X S xa3 xa1)
(commringfracop1int X S xa3 xa2)).
simpl. apply hinhfun. intro t2.
set (c0s := pr1 t2). set (c0 := pr1 c0s). set (r := pr2 t2).
split with c0s.
set (x1 := pr1 xa1). set (a1 := pr1 (pr2 xa1)).
set (x2 := pr1 xa2). set (a2 := pr1 (pr2 xa2)).
set (x3 := pr1 xa3). set (a3 := pr1 (pr2 xa3)).
change (pr1 (R ((a1 * x3 + a3 * x1) * (a3 * a2) * c0)
((a2 * x3 + a3 * x2) * (a3 * a1) * c0))).
rewrite (ringassoc2 X _ _ c0). rewrite (ringassoc2 X _ (a3 * _) c0).
rewrite (ringrdistr X _ _ _). rewrite (ringrdistr X _ _ _).
rewrite (rer2 _ x3 _ _). rewrite (rer2 _ x3 _ _).
rewrite (ringcomm2 X a3 a2). rewrite (ringcomm2 X a3 a1).
rewrite (pathsinv0 (ringassoc2 X a1 a2 a3)).
rewrite (pathsinv0 (ringassoc2 X a2 a1 a3)).
rewrite (ringcomm2 X a1 a2). apply ((pr1 is0) _ _ _).
rewrite (ringcomm2 X a2 a3). rewrite (ringcomm2 X a1 a3).
rewrite (ringassoc2 X a3 a2 c0). rewrite (ringassoc2 X a3 a1 c0).
rewrite (rer2 _ x1 a3 _). rewrite (rer2 _ x2 a3 _).
rewrite (pathsinv0 (ringassoc2 X x1 _ _)).
rewrite (pathsinv0 (ringassoc2 X x2 _ _)).
apply ((isringmultgttoislringmultgt X is0 is1)
_ _ _ (is2 _ (pr2 (@op S (pr2 xa3) (pr2 xa3)))) r).
Defined.
Opaque isringaddcommringfracgt.
Definition isdeccommringfracgt (X : commring) (S : @submonoid (ringmultabmonoid X)) {R : hrel X}
(is0 : @isbinophrel (rigaddabmonoid X) R) (is1 : isringmultgt X R)
(is2 : ∏ c : X, S c -> R c 0) (is' : @ispartinvbinophrel (ringmultabmonoid X) S R)
(isd : isdecrel R) : isdecrel (commringfracgt X S is0 is1 is2).
Proof.
intros.
apply (isdecabmonoidfracrel
(ringmultabmonoid X) S (ispartbinopcommringfracgt X S is0 is1 is2) is' isd).
Defined.
Lemma StrongOrder_correct_commrngfrac (X : commring) (Y : @subabmonoid (ringmultabmonoid X))
(gt : StrongOrder X)
Hgt Hle Hmult Hpos :
commringfracgt X Y (R := gt) Hle Hmult Hpos = StrongOrder_abmonoidfrac Y gt Hgt.
Proof.
apply funextfun ; intros x.
apply funextfun ; intros y.
apply (maponpaths (λ H, abmonoidfracrel (ringmultabmonoid X) Y H x y)).
apply isaprop_ispartbinophrel.
Defined.
(** **** Relations and the canonical homomorphism to the ring of fractions *)
Definition iscomptocommringfrac (X : commring) (S : @submonoid (ringmultabmonoid X)) {L : hrel X}
(is0 : @isbinophrel (rigaddabmonoid X) L) (is1 : isringmultgt X L)
(is2 : ∏ c : X, S c -> L c 0) :
iscomprelrelfun L (commringfracgt X S is0 is1 is2) (tocommringfrac X S) :=
iscomptoabmonoidfrac (ringmultabmonoid X) S (ispartbinopcommringfracgt X S is0 is1 is2).
Opaque iscomptocommringfrac.
Close Scope ring_scope.
(* End of the file *)
|
<!-- dom:TITLE: Project for [Nuclear Talent](http://www.nucleartalent.org) course on *Many-body methods for nuclear physics, from Structure to Reactions* at [Henan Normal University, P.R. China](http://www.htu.cn/english/), July 16-August 5 2018 -->
# Project for [Nuclear Talent](http://www.nucleartalent.org) course on *Many-body methods for nuclear physics, from Structure to Reactions* at [Henan Normal University, P.R. China](http://www.htu.cn/english/), July 16-August 5 2018
<!-- dom:AUTHOR: Kevin Fossez at [National Superconducting Cyclotron Laboratory](http://www.nscl.msu.edu/), [Michigan State University](http://www.msu.edu/), East Lansing, MI 48824, USA -->
<!-- Author: -->
**Kevin Fossez**, [National Superconducting Cyclotron Laboratory](http://www.nscl.msu.edu/), [Michigan State University](http://www.msu.edu/), East Lansing, MI 48824, USA
<!-- dom:AUTHOR: Morten Hjorth-Jensen at [National Superconducting Cyclotron Laboratory](http://www.nscl.msu.edu/) and [Department of Physics and Astronomy](https://www.pa.msu.edu/), [Michigan State University](http://www.msu.edu/), East Lansing, MI 48824, USA -->
<!-- Author: --> **Morten Hjorth-Jensen**, [National Superconducting Cyclotron Laboratory](http://www.nscl.msu.edu/) and [Department of Physics and Astronomy](https://www.pa.msu.edu/), [Michigan State University](http://www.msu.edu/), East Lansing, MI 48824, USA
<!-- dom:AUTHOR: Baishan Hu at [School of Physics, Peking University, Beijing 100871, P.R. China](http://english.pku.edu.cn/) -->
<!-- Author: --> **Baishan Hu**, [School of Physics, Peking University, Beijing 100871, P.R. China](http://english.pku.edu.cn/)
<!-- dom:AUTHOR: Weiguang Jiang at [Department of Physics and Astronomy](https://www.phys.utk.edu/), [University of Tennessee](http://www.utk.edu/), Knoxville, TN 37996-1200, USA and [Oak Ridge National Laboratory](http://www.ornl.gov/), Oak Ridge, TN, USA -->
<!-- Author: --> **Weiguang Jiang**, [Department of Physics and Astronomy](https://www.phys.utk.edu/), [University of Tennessee](http://www.utk.edu/), Knoxville, TN 37996-1200, USA and [Oak Ridge National Laboratory](http://www.ornl.gov/), Oak Ridge, TN, USA
<!-- dom:AUTHOR: Thomas Papenbrock at [Department of Physics and Astronomy](https://www.phys.utk.edu/), [University of Tennessee](http://www.utk.edu/), Knoxville, TN 37996-1200, USA and [Oak Ridge National Laboratory](http://www.ornl.gov/), Oak Ridge, TN, USA -->
<!-- Author: --> **Thomas Papenbrock**, [Department of Physics and Astronomy](https://www.phys.utk.edu/), [University of Tennessee](http://www.utk.edu/), Knoxville, TN 37996-1200, USA and [Oak Ridge National Laboratory](http://www.ornl.gov/), Oak Ridge, TN, USA
<!-- dom:AUTHOR: Ragnar Stroberg at [Departmentof Physics, Reed College](http://www.reed.edu/), Portland, OR, 97202 and [Department of Physics, University of Washington](https://sharepoint.washington.edu/phys/Pages/default.aspx), Seattle, WA 98195-1560, USA -->
<!-- Author: --> **Ragnar Stroberg**, [Departmentof Physics, Reed College](http://www.reed.edu/), Portland, OR, 97202 and [Department of Physics, University of Washington](https://sharepoint.washington.edu/phys/Pages/default.aspx), Seattle, WA 98195-1560, USA
<!-- dom:AUTHOR: Zhonghao Sun at [Department of Physics and Astronomy](https://www.phys.utk.edu/), [University of Tennessee](http://www.utk.edu/), Knoxville, TN 37996-1200, USA and [Oak Ridge National Laboratory](http://www.ornl.gov/), Oak Ridge, TN, USA -->
<!-- Author: --> **Zhonghao Sun**, [Department of Physics and Astronomy](https://www.phys.utk.edu/), [University of Tennessee](http://www.utk.edu/), Knoxville, TN 37996-1200, USA and [Oak Ridge National Laboratory](http://www.ornl.gov/), Oak Ridge, TN, USA
<!-- dom:AUTHOR: Yu-Min Zhao at [School of Physics and Astronomy, Shanghai Jiao Tong University](http://www.physics.sjtu.edu.cn/en/about/news/3), Shanghai 200240, P.R. China -->
<!-- Author: --> **Yu-Min Zhao**, [School of Physics and Astronomy, Shanghai Jiao Tong University](http://www.physics.sjtu.edu.cn/en/about/news/3), Shanghai 200240, P.R. China
Date: **Jul 17, 2018**
## Introduction
An essential element of the Talent courses is to develop a large
project(s) which allows you to study and understand theoretical
concepts in nuclear physics. These concepts will in turn allow you to
interpret results from experiments and understand the pertinent
physics in terms of the underlying forces and laws of motion.
Together with the regular lectures in the morning, the hope is that
during these three weeks you will be able to write and run a program
which implements at least one of the methods discussed during the
lectures. The lectures will also cover additional material which aims
at giving you a broader view on what can be achieved with the methods
to be discussed. Combined with the 'hands-on' afternoon sessions, the
hope is that the lectures and the computational projects will together
allow you to achieve these goals.
The project is divided in four main parts. The first part deals with
a simple pairing model and the development of a shell-model program
related to this model. This program can then serve as a benchmark
program for the Coupled Cluster theory and in-medium SRG codes to be
developed. The latter form the remaining parts of the project.
If you have not used version control before now, it is time to do so.
Proper version control is central to a good ethical scientific conduct.
We do require that you use some kind of version control software when working on the projects. We recommend strongly [github](https://github.com/). All lectures and additional material are available at the github [address of the course](https://github.com/NuclearTalent/ManyBody2018).
Furthermore, before coming to the course, we recommend that you refresh your knowledge on second quantization.
## Some basic ingredients for a successful numerical project
When building up a numerical project there are several elements you should think of, amongst these we take the liberty of mentioning the following:
1. How to structure a code in terms of functions
2. How to make a module
3. How to read input data flexibly from the command line
4. How to create graphical/web user interfaces
5. How to write unit tests (test functions)
6. How to refactor code in terms of classes (instead of functions only), in our case you think of a system and a solver class
7. How to conduct and automate large-scale numerical experiments
8. How to write scientific reports in various formats (LaTeX, HTML)
The conventions and techniques outlined here will save you a lot of time when you incrementally extend software over time from simpler to more complicated problems. In particular, you will benefit from many good habits:
1. New code is added in a modular fashion to a library (modules)
2. Programs are run through convenient user interfaces
3. It takes one quick command to let all your code undergo heavy testing
4. Tedious manual work with running programs is automated,
5. Your scientific investigations are reproducible, scientific reports with top quality typesetting are produced both for paper and electronic devices.
We expect you to form working
groups consisting of typically three (or more) participants. Every
group should establish its own Github or Gitlab repository for the
project.
## Part 1, pairing problem
In the first part of the project we will thus work with a simplified Hamiltonian consisting of a one-body operator and a so-called
pairing interaction term. It is a model which to a large extent mimicks some central features of
atomic nuclei, certain atoms and systems which exhibit superfluiditity or superconductivity.
Pairing plays a central role in nuclear physics, in particular, for identical particles it makes up large fractions of the correlations among particles. The partial wave $^{1}S_0$ of the nucleon-nucleon force plays a central role in setting up pairing correlations in nuclei. Without this particular partial wave, the $J=0$ ground state spin assignment for many nuclei with even numbers of particles would not be possible.
We define first the Hamiltonian, with a definition of the model space and
the single-particle basis. Thereafter, we present the various steps which are needed to develop a shell-model program for studying the pairing problem.
The Hamiltonian acting in the complete Hilbert space (usually infinite
dimensional) consists of an unperturbed one-body part, $\hat{H}_0$,
and a perturbation $\hat{H}_I$.
We limit ourselves to at most two-body interactions, our Hamiltonian is
then represented by the following operators
<!-- Equation labels as ordinary links -->
<div id="eq:hamiltonian"></div>
$$
\begin{equation}
\hat{H} = \hat{H}_0 +\hat{H}_I=\sum_{pq}\langle p |h_0|q\rangle a_{p}^{\dagger}a_{q} +\frac{1}{4}\sum_{pqrs}\langle pq| V|rs\rangle a_{p}^{\dagger}a_{q}^{\dagger}a_{s}a_{r},
\label{eq:hamiltonian} \tag{1}
\end{equation}
$$
where $a_{p}^{\dagger}$ and $a_{q}$ etc are standard fermion creation and annihilation operators, respectively,
and $pqrs$ represent all possible single-particle quantum numbers.
The full single-particle space is defined by the completeness relation
$\hat{1} = \sum_{p =1}^{\infty}|p \rangle \langle p|$.
In our calculations we will let the single-particle states $|p\rangle$
be eigenfunctions of the one-particle operator $\hat{h}_0$.
The above Hamiltonian
acts in turn on various many-body Slater determinants constructed from the single-basis defined by the one-body
operator $\hat{h}_0$.
Our specific model consists of only $2$ doubly-degenerate and equally spaced
single-particle levels labeled by $p=1,2,\dots$ and spin $\sigma=\pm
1$.
In Eq. ([eq:hamiltonian](#eq:hamiltonian)) the labels $pqrs$ could also include spin $\sigma$. From now and for the rest of this project, labels like $pqrs$ represent the states without spin. The spin quantum numbers need to be accounted for explicitely.
We write
the Hamiltonian as
$$
\hat{H} = \hat{H}_0 +\hat{H}_I=\hat{H}_0 + \hat{V} ,
$$
where
$$
\hat{H}_0=\xi\sum_{p\sigma}(p-1)a_{p\sigma}^{\dagger}a_{p\sigma}.
$$
Here, $H_0$ is the unperturbed Hamiltonian with a spacing between
successive single-particle states given by $\xi$, which we will set to
a constant value $\xi=1$ without loss of generality.
The two-body
operator $\hat{V}$ has one term only. It represents the
pairing contribution and carries a constant strength $g$
and is given by
$$
\langle q+q-| V|s+s-\rangle = -g
$$
where $g$ is a constant. The above labeling means that for a general matrix elements
$\langle pq| V|rs\rangle$ we require that the states $p$ and $q$ (and $r$ and $s$) have the same number
quantum number $q$ but opposite spins. The two spins values are
$\sigma = \pm 1$.
When setting up the Hamiltonian matrix you need to figure out how to make the two-body interaction antisymmetric.
The variables $\sigma=\pm$ represent the two possible spin values. The
interaction can only couple pairs and excites therefore only two
particles at the time.
In our model we have kept both the interaction strength and the single-particle level as constants.
In a realistic system like the atomic nucleus this is not the case.
The unperturbed Hamiltonian $\hat{H}_0$ and $\hat{V}$ commute
with the spin projection $\hat{S}_z$ and the total spin
$\hat{S}^2$.
This is an important feature of our system that allows us to block-diagonalize
the full Hamiltonian. In this project we will focus only on total spin $S=0$, this case is normally called the no-broken pair case.
### Part 1a: Paper and pencil gym while we wait for the more serious stuff
Show that the
unperturbed Hamiltonian $\hat{H}_0$ and $\hat{V}$ commute
with both the spin projection $\hat{S}_z$ and the total spin
$\hat{S}^2$, given by
$$
\hat{S}_z := \frac{1}{2}\sum_{p\sigma} \sigma a^{\dagger}_{p\sigma}a_{p\sigma}
$$
and
$$
\hat{S}^2 := \hat{S}_z^2 + \frac{1}{2}(\hat{S}_+\hat{S}_- +
\hat{S}_-\hat{S}_+),
$$
where
$$
\hat{S}_\pm := \sum_{p} a^{\dagger}_{p\pm} a_{p\mp}.
$$
This is an important feature of our system that allows us to block-diagonalize
the full Hamiltonian. We will focus on total spin $S=0$.
In this case, it is convenient to define the so-called pair creation and pair
annihilation operators
$$
\hat{P}^{+}_p = a^{\dagger}_{p+}a^{\dagger}_{p-},
$$
and
$$
\hat{P}^{-}_p = a_{p-}a_{p+},
$$
respectively.
The Hamiltonian (with $\xi=1$) we will use can be written as
$$
\hat{H}=\sum_{p\sigma}(p-1)a_{p\sigma}^{\dagger}a_{p\sigma}
-g\sum_{pq}\hat{P}^{+}_p\hat{P}^{-}_q.
$$
Show that Hamiltonian commutes with the product of the pair creation and annihilation operators.
This model corresponds to a system with no broken pairs. This means that the Hamiltonian can only link two-particle states in so-called spin-reversed states.
### Part 1b: Simpler case
Assume now that the effective Hilbert space consists only of the two lowest single-particle states and that we have two particles only.
Set up the possible two-particle configurations when we have only two single-particle states, that is $p=1$ and $p=2$.
Construct thereafter the Hamiltonian matrix using second quantization and for example Wick's theorem
for a system with no broken pairs and spin $S=0$ (with projection $S_z=0$) for the case of the two lowest single-particle levels and two particles only. This gives you a
$2\times 2$ matrix to be diagonalized.
Find the eigenvalues by diagonalizing the Hamiltonian matrix.
Vary your results for selected values of $g\in [-1,1]$ and comment your results.
### Part 1c: Setting up the Hamiltonian matrix
Construct thereafter the Hamiltonian matrix for a system with no broken pairs and spin $S=0$ for the case of the four lowest single-particle levels. Our system consists of four particles only.
Our single-particle space consists of only the four lowest levels
$p=1,2,3,4$. You need to set up all possible Slater determinants and the Hamiltonian matrix using second quantization and
find all eigenvalues by diagonalizing the Hamiltonian matrix.
Vary your results for values of $g\in [-1,1]$. Your Hamiltonian matrix is a $6\times 6$ matrix.
These results will serve as a benchmark for the construction of our shell-model program and the CC and IMSRG programs.
We refer to this as the exact results. Comment the behavior of the ground state as function of $g$.
To help, your final Hamiltonian matrix reads
$$
H = \left (
\begin{array}{cccccc}
2\delta -2g & -g & -g & -g & -g & 0 \\
-g & 4\delta -2g & -g & -g & -0 & -g \\
-g & -g & 6\delta -2g & 0 & -g & -g \\
-g & -g & 0 & 6\delta-2g & -g & -g \\
-g & 0 & -g & -g & 8\delta-2g & -g \\
0 & -g & -g & -g & -g & 10\delta -2g
\end{array} \right )
$$
### Part 1d: Diagonalizing the Hamiltonian matrix
Our next step is to develop a code which sets up the above Hamiltonian matrices for two and four particles in 2 and 4 single-particles states (the same as what you did in exercises b) and c) and obtain the eigenvalues.
To achieve this you should
* Decide whether you want to read from file the single-particle data and the matrix elements in $m$-scheme, or set them up internally in your code. The latter is the simplest possibility for the pairing model, whereas the first option gives you a more general code which can be extended to the more realistic cases discussed in the second part.
* Based on the single-particle basis, write a function which sets up all possible Slater determinants which have total $M=0$. Test that this function reproduces the cases in b) and c). If you make this function more general, it can then be reused for say a shell-model calculation of $sd$-shell nuclei in the second part.
* Use the Slater determinant basis from the previous step to set up the Hamiltonian matrix.
* With the Hamiltonian matrix, you can finally diagonalize the matrix and obtain the final eigenvalues and test against the results of b) and c).
Codes to diagonalize in C++ or Fortran can be provided. For Python, numpy contains eigenvalue solvers based on for example Householder's and Givens' algorithms. These are topics which can we discuss separately. The lecture slides contain a rather detailed recipe
on how to construct a Slater determinant basis and how to set up the Hamiltonian matrix to diagonalize.
### Part 1e: Further benchmarks and optional part
In developing the code it also useful to test against cases which have closed-form solutions. One obvious case is that of removing the
two-body interaction. Then we have only the single-particle energies.
For the case of degenerate single-particle orbits, that is one value of total single-particle angular momentum only $j$, with degeneracy $\Omega=2j+1$, one can show that the ground state energy $E_0$ is with $n$ particles
$$
E_0= -\frac{g}{4}n\left(\Omega-n+2\right).
$$
Challenge: Enlarge now your system to six and eight fermions and to $p=6$ and $p=8$ single-particle states, respectively. Run your program for a degenerate single-particle state with degeneracy $\Omega$ and test
against the exact result for the ground state. Introduce thereafter a finite single-particle spacing and study the results as you vary $g$, as done in b) and c). Comment your results.
## Part 2: Coupled cluster calculations with doubles excitations only for the pairing model
This project serves as a continuation
of the pairing model with the aim being to solve the same problem but
now by developing a program that implements the coupled cluster method
with double excitations only. In doing so you will find it convenient
to write classes which define the single-particle basis and the
Hamiltonian. Your functions that solve the coupled cluster equations
will then just need to set up variables which point to interaction
elements and single-particle states with their pertinent quantum
numbers. Use for example the setup discussed in the FCI lectures for
the pairing model.
1. Explain why no single excitations are involved in this model.
2. Set up the coupled cluster equations for doubles excitations and convince yourself about their meaning and correctness.
3. Write a class which holds single-particle data like specific quantum numbers, single-particle Hamiltonian etc. Write also a class which sets up and stores two-body matrix elements defined by the single-particle states. Write thereafter functions/classes which implement the coupled cluster method with doubles only.
4. Compare your results with tose from the exact diagonalization with and without the $4p4h$ excitation. Compare also your results to perturbation theory at different orders, in particular to second order. Discuss your results.
## Part 3: Coupled cluster calculations with doubles excitations only for infinite nuclear matter
This project forms one possible final path for the remaining two weeks. It can also be extended in order to define the final project. You should be able to use the program you developed in connection with the
solution of the pairing model.
1. Explain why we don't have single excitations in infinite matter.
2. Set up the relavent quantum numbers for a cartesian basis with plane waves in three dimensions. Make the according changes to the code you developed in connection with the pairing model. Implement periodic boundary conditions.
3. Replace the two-body interaction from the pairing model with the Minnesota potential model discussed during the [lectures](https://github.com/NuclearTalent/Course2ManyBodyMethods/blob/master/doc/pub/cc/pdf/Lectures1-2_TALENT_NuclearMatter_GH.pdf).
4. Use the program you developed in connection with the pairing model to perform coupled cluster calculations in infinite matter with doubles excitations. Perform coupled cluster calculations for infinite neutron matter with the Minnesota interaction for $N=14$ neutrons. Limit yourself to two-particle and two-hole intermediate excitations only.
## Part 4: IMSRG code for the pairing model and infinite matter
Our final step consists in modifying the above program in order to include the IMSRG method, applying it to both the pairing model and infinite neutron matter.
Compare your results with those obtained with Coupled Cluster theory and comment your results obtained with the pairing model as well as those for infinite neutron matter.
|
-- ----------------------------------------------------------- [ Intention.idr ]
-- Module : Intention.idr
-- Copyright : (c) Jan de Muijnck-Hughes
-- License : see LICENSE
-- --------------------------------------------------------------------- [ EOH ]
||| This section details the combinator for intentional link insertion.
|||
||| Correctness/Soundness Properties of an Intentional Link
|||
||| 1. The link should use elements that are in the model.
||| 2. The destination cannot have type: Resource
||| 3. The src and destination must not be the same.
|||
module GRL.Property.Intention
import public Decidable.Equality
import public Data.AVL.Graph
import public Data.List
import GRL.Model
import GRL.IR
import GRL.Common
%access export
-- ---------------------------------------------- [ Intentional Link Insertion ]
examineLink : GExpr INTENT -> Bool
examineLink (ILink cTy c x (Elem RESty n s)) = False
examineLink (ILink cTy c x y) = not $ eqGExpr x y
inModel : GExpr ELEM -> GModel -> Bool
inModel (Elem ty n s) m = hasGoal n m
validLink : GExpr INTENT -> GModel -> Bool
validLink (ILink cTy ty x y) m = (inModel x m) && (inModel y m)
%hint
checkIntentBool : GExpr INTENT -> GModel -> Bool
checkIntentBool l m = validLink l m && examineLink l
-- --------------------------------------------------------------------- [ EOF ]
|
function v=shear_bulk2poisson(mu,k)
v=((3.*k)-(2.*mu))./((6.*k)+(2.*mu));
end
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% 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 3 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, see <http://www.gnu.org/licenses/>.
|
While in England , Andrew met Bessie Ball , of Nottingham , and they were married on 12 November 1918 . The couple had five children although one died in infancy . Upon discharge from the NZEF in August 1919 , he joined the New Zealand Staff Corps and served in a number of administrative positions for the next several years . From 1927 to 1929 he served with the Highland Light Infantry in British India on an officer exchange program . On his return to New Zealand he was appointed adjutant of the 1st Wellington Regiment . In 1937 , having been promoted to captain , he commanded the New Zealand contingent sent to London for the coronation of King George VI and Queen Elizabeth .
|
module Bench
include("args.jl")
#
import Bench.Args: generate, smallest, tag
import BenchmarkTools: BenchmarkGroup, @benchmarkable
function valid(f, args)
try
f(args...)
return true
catch
return false
end
end
function push!(suite, ns, f, args)
key = Tuple( (f, tag.(args)...) )
suite[key] = BenchmarkGroup(collect(key))
for n in ns
arg = generate(n, args)
suite[key][n] = @benchmarkable $f( $arg... )
end
end
function productsuite(ns, fs, arglist...)
suite = BenchmarkGroup()
for f in fs
for args in Iterators.product(arglist...)
push!(suite, ns, f, args)
end
end
return suite
end
end # module
|
The iPhone 3G S (S stands for Speed, by the way) will indeed be speedy and considerably faster then the current iPhone (3G). The latest iPhone will sport a 600 MHz processor and 256MB of RAM. When compared to the iPhone 3G which has a 412MHz processor and 128MB of RAM it is definitely a notable speed increase. For those wondering, the second generation iPod Touch has a 532MHz processor. The faster processor and additional RAM in the iPhone 3G S will be welcome by app store developers without a doubt. I certainly expect to see more games coming to the iPhone 3G S – it may very well be the “funnest iPhone ever”.
The iPhone 3G S also has more pipelines, larger L1 cache, and even has an L2 cache of 256KB (the iPhone 3G does not have an L2 cache). Additionally, the new iPhone is using a PowerVR SGX graphics processing unit which provides support for OpenGL ES 2.0. The latest iPhone hardware is on par with that of the Palm Pre. In fact, they are essentially running the same hardware (at least for CPU/GPU).
I fully expect the new iPhone to perform as Apple claims (up to 2x faster) in typical usage. Nonetheless, this is seriously a beast of a phone mobile device. |
The professions of architect , master craftsman , carpenter , and structural engineer did not have the high status of the Confucian scholar @-@ officials during the dynastic era . Architectural knowledge had been passed down orally for thousands of years , usually from craftsman fathers to their sons . There were also government agencies and schools for construction , building , and engineering . The Song dynasty 's building manuals aided not only the various private workshops , but also the craftsmen employed by the central government .
|
[STATEMENT]
lemma smooth_on_compose:
fixes g::"_\<Rightarrow>_::euclidean_space"
assumes "k-smooth_on T f" "k-smooth_on S g" "open S" "open T" "g ` S \<subseteq> T"
shows "k-smooth_on S (f o g)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. k-smooth_on S (f \<circ> g)
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
k-smooth_on T f
k-smooth_on S g
open S
open T
g ` S \<subseteq> T
goal (1 subgoal):
1. k-smooth_on S (f \<circ> g)
[PROOF STEP]
by (rule smooth_on_compose2) auto |
Formal statement is: lemma fst_vimage_eq_Times: "fst -` S = S \<times> UNIV" Informal statement is: The preimage of a set $S$ under the first projection is $S \times \mathbb{R}$. |
State Before: R : Type u_1
A : Type u_2
B : Type u_3
C : Type u_4
inst✝⁹ : Monoid R
inst✝⁸ : NonUnitalNonAssocSemiring A
inst✝⁷ : DistribMulAction R A
inst✝⁶ : Star A
inst✝⁵ : NonUnitalNonAssocSemiring B
inst✝⁴ : DistribMulAction R B
inst✝³ : Star B
inst✝² : NonUnitalNonAssocSemiring C
inst✝¹ : DistribMulAction R C
inst✝ : Star C
f : A →⋆ₙₐ[R] B
g : A →⋆ₙₐ[R] C
⊢ comp (fst R B C) (prod f g) = f State After: case h
R : Type u_1
A : Type u_2
B : Type u_3
C : Type u_4
inst✝⁹ : Monoid R
inst✝⁸ : NonUnitalNonAssocSemiring A
inst✝⁷ : DistribMulAction R A
inst✝⁶ : Star A
inst✝⁵ : NonUnitalNonAssocSemiring B
inst✝⁴ : DistribMulAction R B
inst✝³ : Star B
inst✝² : NonUnitalNonAssocSemiring C
inst✝¹ : DistribMulAction R C
inst✝ : Star C
f : A →⋆ₙₐ[R] B
g : A →⋆ₙₐ[R] C
x✝ : A
⊢ ↑(comp (fst R B C) (prod f g)) x✝ = ↑f x✝ Tactic: ext State Before: case h
R : Type u_1
A : Type u_2
B : Type u_3
C : Type u_4
inst✝⁹ : Monoid R
inst✝⁸ : NonUnitalNonAssocSemiring A
inst✝⁷ : DistribMulAction R A
inst✝⁶ : Star A
inst✝⁵ : NonUnitalNonAssocSemiring B
inst✝⁴ : DistribMulAction R B
inst✝³ : Star B
inst✝² : NonUnitalNonAssocSemiring C
inst✝¹ : DistribMulAction R C
inst✝ : Star C
f : A →⋆ₙₐ[R] B
g : A →⋆ₙₐ[R] C
x✝ : A
⊢ ↑(comp (fst R B C) (prod f g)) x✝ = ↑f x✝ State After: no goals Tactic: rfl |
using ComoniconTestUtils
using ComoniconZSHCompletion: emit_zshcompletion
using Test
using Random
Random.seed!(42)
@testset "test completion" for _ in 1:5
cmd = rand_command()
script = emit_zshcompletion(cmd)
@test occursin("#compdef _$(cmd.root.name) $(cmd.root.name)", script)
@test occursin("function _$(cmd.root.name)() {", script)
end
|
(* bad *)
From Coq Require Import
Lists.List Logic.ProofIrrelevance ZArith.ZArith.
From DEZ.Has Require Export
OneSortedEnumeration OneSortedCardinality.
From DEZ.Is Require Export
OneSortedFinite Isomorphic TwoSortedBimodule
Ring TwoSortedUnitalAssociativeAlgebra.
From DEZ.Justifies Require Export
OneSortedPositiveOperations OneSortedNaturalOperations
OneSortedIntegerOperations.
From DEZ.Justifies Require Export
ZTheorems.
From DEZ.Supports Require Import
OneSortedArithmeticNotations.
From DEZ.Supports Require Import
OneSortedMultiplicativeOperationNotations.
Import ListNotations.
Import Addition.Subclass Zero.Subclass Negation.Subclass
Multiplication.Subclass One.Subclass.
Definition Nseq (start len : N) : list N :=
map N.of_nat (seq (N.to_nat start) (N.to_nat len)).
(* From Coq Require Import
FSets.FMapAVL Structures.OrderedTypeEx.
Module Import Map := FMapAVL.Make Positive_as_OT. *)
From Coq Require Import
FSets.FMapList Structures.OrderedTypeEx.
Module Import Map := FMapList.Make Positive_as_OT.
From Coq Require Import
FSets.FMapFacts.
Module Props := WProperties_fun Positive_as_OT Map.
Module Mapper := Props.F.
Definition Map_max_key {A : Type} (xs : Map.t A) : option key :=
Map.fold (fun (n : key) (x : A) (ms : option key) =>
match ms with
| Some m => Some (Pos.max n m)
| None => Some n
end) xs None.
Definition Map_max_key_def {A : Type} (d : key) (xs : Map.t A) : key :=
Map.fold (fun (n : key) (x : A) (m : key) => Pos.max n m) xs d.
Section Context.
Context (A B : Type) `{IsTwoBimod A B}.
Record tensor : Type := {
ht : A;
tt : Map.t (list B);
}.
Definition proper (p : tensor) : Prop :=
forall (k : key) (x : list B),
MapsTo k x (tt p) -> length x = Pos.to_nat k.
Definition Add (p q : tensor) : tensor := {|
ht := Addition.add (ht p) (ht q);
tt := Map.map2 (fun (as' bs : option (list B)) => match as', bs with
| Some a, Some b => Some (List.map (prod_uncurry Addition.add) (combine a b))
| Some a, None => Some a
| None, Some b => Some b
| None, None => None
end) (tt p) (tt q)
|}.
Definition Zero : tensor := {|
ht := zero;
tt := Map.empty (list B);
|}.
Definition Neg (p : tensor) : tensor :={|
ht := neg (ht p);
tt := Map.map (List.map neg) (tt p);
|}.
Definition ActL (a : A) (p : tensor) : tensor :=
{| ht := ht p; tt := Map.map (List.map (act_l a)) (tt p) |}.
Definition ActR (p : tensor) (a : A) : tensor :=
{| ht := ht p; tt := Map.map (List.map (flip act_r a)) (tt p) |}.
Global Instance N_has_bin_op : HasBinOp N := N.add.
Global Instance N_has_null_op : HasNullOp N := N.zero.
(** Instant tensor algebra; just add water. *)
End Context.
(* Section Tests.
Local Open Scope Z_scope.
Instance positive_has_one : HasOne positive := xH.
Instance Z3_has_add : HasAdd (Z * Z * Z) :=
fun x y : Z * Z * Z =>
match x, y with
| (x0, x1, x2), (y0, y1, y2) => (x0 + y0, x1 + y1, x2 + y2)
end.
Instance Z3_has_neg : HasNeg (Z * Z * Z) :=
fun x : Z * Z * Z =>
match x with
| (x0, x1, x2) => (- x0, - x1, - x2)
end.
Instance Z3_has_act_l : HasActL Z (Z * Z * Z) :=
fun (a : Z) (x : Z * Z * Z) =>
match x with
| (x0, x1, x2) => (a * x0, a * x1, a * x2)
end.
Instance Z3_has_act_r : HasActR Z (Z * Z * Z) :=
fun (x : Z * Z * Z) (a : Z) =>
match x with
| (x0, x1, x2) => (x0 * a, x1 * a, x2 * a)
end.
Let p : tensor := {|
ht := Z.zero;
tt := Props.of_list [
(1%positive, [(0, 0, 0)]);
(2%positive, [(1, 0, 0); (1, 0, 0)]);
(3%positive, [(0, 0, 7); (0, 1, 0); (1, 0, 0)])];
|}.
Let q : tensor := {|
ht := Z.zero;
tt := Props.of_list [
(1%positive, [(2, 1, 0)]);
(2%positive, [(1, 0, 0); (1, 0, 0)]);
(3%positive, [(0, 1, 0); (0, 1, 0); (0, 0, 1)])];
|}.
Let r : tensor := {|
ht := Z.zero;
tt := Props.of_list [
(1%positive, [(0, 0, 0)]);
(2%positive, [(0, 0, 0); (0, 0, 0)]);
(3%positive, [(1, 0, 0); (1, 0, 0); (2, 1, 0)]);
(4%positive, [(0, 0, 7); (0, 1, 0); (1, 0, 0); (2, 1, 0)]);
(5%positive, [(1, 0, 0); (1, 0, 0); (0, 1, 0); (0, 1, 0); (0, 0, 1)]);
(6%positive, [(0, 0, 7); (0, 1, 0); (1, 0, 0); (0, 1, 0); (0, 1, 0); (0, 0, 1)])];
|}.
Compute GrdMul p q.
Compute r.
End Tests. *)
|
function EigenDecomposition(arg0::RealMatrix)
return EigenDecomposition((RealMatrix,), arg0)
end
function EigenDecomposition(arg0::Vector{jdouble}, arg1::Vector{jdouble})
return EigenDecomposition((Vector{jdouble}, Vector{jdouble}), arg0, arg1)
end
function get_d(obj::EigenDecomposition)
return jcall(obj, "getD", RealMatrix, ())
end
function get_determinant(obj::EigenDecomposition)
return jcall(obj, "getDeterminant", jdouble, ())
end
function get_eigenvector(obj::EigenDecomposition, arg0::jint)
return jcall(obj, "getEigenvector", RealVector, (jint,), arg0)
end
function get_imag_eigenvalue(obj::EigenDecomposition, arg0::jint)
return jcall(obj, "getImagEigenvalue", jdouble, (jint,), arg0)
end
function get_imag_eigenvalues(obj::EigenDecomposition)
return jcall(obj, "getImagEigenvalues", Vector{jdouble}, ())
end
function get_real_eigenvalue(obj::EigenDecomposition, arg0::jint)
return jcall(obj, "getRealEigenvalue", jdouble, (jint,), arg0)
end
function get_real_eigenvalues(obj::EigenDecomposition)
return jcall(obj, "getRealEigenvalues", Vector{jdouble}, ())
end
function get_solver(obj::EigenDecomposition)
return jcall(obj, "getSolver", DecompositionSolver, ())
end
function get_square_root(obj::EigenDecomposition)
return jcall(obj, "getSquareRoot", RealMatrix, ())
end
function get_v(obj::EigenDecomposition)
return jcall(obj, "getV", RealMatrix, ())
end
function get_vt(obj::EigenDecomposition)
return jcall(obj, "getVT", RealMatrix, ())
end
function has_complex_eigenvalues(obj::EigenDecomposition)
return jcall(obj, "hasComplexEigenvalues", jboolean, ())
end
|
(*
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: work_gga_x *)
kappa := 0.8040:
mu := 0.2195149727645171:
m := 100:
gamm := m*mu/kappa:
Cx := kappa/m:
f0 := s -> 1 + add(Cx * (gamm*s^2/(1 + gamm*s^2))^i, i=1..m):
f := x -> f0(X2S*x):
|
module SkepticLang.PairUtils
%access public export
||| Compares the second element in two pairs.
|||
||| @x the first pair
||| @y the second pair
compareSnd : Ord b => (x : (a, b)) -> (y : (a, b)) -> Ordering
compareSnd (_, x') (_, y') = compare x' y'
|
using Test
ProjDir = joinpath(dirname(@__FILE__), "..", "examples", "BernoulliInitTheta")
cd(ProjDir) do
isdir("tmp") &&
rm("tmp", recursive=true);
bernoullimodel = "
data {
int<lower=1> N;
int<lower=0,upper=1> y[N];
}
parameters {
real<lower=0,upper=1> theta;
}
model {
theta ~ beta(1,1);
y ~ bernoulli(theta);
}
"
bernoullidata = [
Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]),
Dict("N" => 10, "y" => [0, 1, 0, 0, 0, 0, 1, 0, 0, 1]),
Dict("N" => 10, "y" => [0, 0, 0, 0, 0, 0, 1, 0, 1, 1]),
Dict("N" => 10, "y" => [0, 0, 0, 1, 0, 0, 0, 1, 0, 1])
]
theta_init = [0.1, 0.4, 0.5, 0.9]
bernoulliinit = Dict[
Dict("theta" => theta_init[1]),
Dict("theta" => theta_init[2]),
Dict("theta" => theta_init[3]),
Dict("theta" => theta_init[4]),
]
monitor = ["theta", "lp__", "accept_stat__"]
stanmodel = Stanmodel(name="bernoulli",
model=bernoullimodel,
init=Stan.Init(init=bernoulliinit),
adapt=1);
rc, a3d, cnames = stan(stanmodel, bernoullidata, CmdStanDir=CMDSTAN_HOME)
if rc == 0
sdf = read_summary(stanmodel)
@test sdf[sdf.parameters .== :theta, :mean][1] ≈ 0.34 rtol=0.1
end
isdir("tmp") &&
rm("tmp", recursive=true);
end # cd
|
State Before: α : Type ?u.27142
β : Type ?u.27145
K : Type u_1
inst✝¹ : DivisionMonoid K
inst✝ : HasDistribNeg K
a✝ b✝ a b : K
⊢ b / -a = b * (1 / -a) State After: no goals Tactic: rw [← inv_eq_one_div, division_def] State Before: α : Type ?u.27142
β : Type ?u.27145
K : Type u_1
inst✝¹ : DivisionMonoid K
inst✝ : HasDistribNeg K
a✝ b✝ a b : K
⊢ b * (1 / -a) = b * -(1 / a) State After: no goals Tactic: rw [one_div_neg_eq_neg_one_div] State Before: α : Type ?u.27142
β : Type ?u.27145
K : Type u_1
inst✝¹ : DivisionMonoid K
inst✝ : HasDistribNeg K
a✝ b✝ a b : K
⊢ b * -(1 / a) = -(b * (1 / a)) State After: no goals Tactic: rw [neg_mul_eq_mul_neg] State Before: α : Type ?u.27142
β : Type ?u.27145
K : Type u_1
inst✝¹ : DivisionMonoid K
inst✝ : HasDistribNeg K
a✝ b✝ a b : K
⊢ -(b * (1 / a)) = -(b / a) State After: no goals Tactic: rw [mul_one_div] |
#include "ntl/map.hpp"
#include "parser.hpp"
#include "firewall.hpp"
#include <functional>
#include <boost/operators.hpp>
void firewall::step(axi_data_stream& in, axi_data_stream& data_out, bool_stream& classify_out, gateway_registers& g)
{
#pragma HLS inline
#pragma HLS stream variable=invalid_udp depth=16
gateway.gateway(g, [&](int addr, gateway_data& data) -> int { return rpc(addr, data); });
dup_data.step(in);
parse.step(dup_data._streams[0]);
dup_metadata.step(parse.out);
ntl::map(dup_metadata._streams[0], hash.lookups, [](const metadata& m) {
return hash_tag{m.ip_source, m.ip_dest, m.udp_source, m.udp_dest};
});
hash.hash_table();
ntl::map(dup_metadata._streams[1], invalid_udp, [](const metadata& m) {
return !m.valid_udp();
});
ntl::map(hash.results, result_with_default, [](const ntl::maybe<std::tuple<uint32_t, hash_t::mapped_type> >& val) {
return val.valid() ? std::get<1>(val.value()) : ap_uint<1>(0);
});
merge_hash_results.step(std::logical_or<ap_uint<1> >(),
result_with_default, invalid_udp);
link(merge_hash_results.out, classify_out);
link(dup_data._streams[1], data_out);
}
int firewall::rpc(int addr, gateway_data& data)
{
switch (addr) {
case FIREWALL_ADD:
return hash.gateway_add_entry(std::make_tuple(data.tag, data.result), &data.status);
case FIREWALL_DEL:
return hash.gateway_delete_entry(data.tag, &data.status);
default:
return ntl::GW_FAIL;
}
}
void firewall_top(ntl::stream<ntl::raw_axi_data, ntl::axi_stream_tag>& in,
ntl::stream<ntl::raw_axi_data, ntl::axi_stream_tag>& data_out,
bool_stream& classify_out, gateway_registers& g)
{
#pragma HLS dataflow
#pragma HLS interface ap_ctrl_none port=return
#pragma HLS interface axis port=in._stream
#pragma HLS interface axis port=data_out._stream
GATEWAY_OFFSET(g, 0x100, 0x118, 0xfc)
static firewall f;
static axi_data_stream in_fifo, out_fifo;
ntl::link(in, in_fifo);
#pragma HLS stream variable=out_fifo depth=16
ntl::link(out_fifo, data_out);
f.step(in_fifo, out_fifo, classify_out, g);
}
|
If $f$ is a holomorphic function on a connected open set $A$ that contains the closed disk of radius $r$ centered at the origin, and $f$ has no zeros in the open disk of radius $r$ centered at the origin, then the $n$th derivative of $f$ at the origin is equal to the sum of the residues of $f$ at the zeros of $f$ in the closed disk of radius $r$ centered at the origin, plus the integral of $f$ over the circle of radius $r$ centered at the origin. |
! Copyright (c) 2016 Alex Kramer <[email protected]>
! See the LICENSE.txt file at the top-level of this distribution.
module vd
use ieee_arithmetic
use numerics, only: numerics_cmplx_phase, numerics_d1, numerics_d2
use log, only: log_log_critical, log_stderr
use precision, only: ip, fp
implicit none
private
public :: vd_get_local_quantities
public :: vd_get_indices
public :: vd_validate_quantum_update
public :: vd_obj
type vd_obj
! Base class for VD point
! Total probability flux through virtual detector
real(fp) :: net_flux
! Semi-classical binning flag
logical :: semi_classical
! Number of standard deviations to include in quantum VD binning
integer(ip) :: vd_np_stdev
! Whether detector is disjoint or not
! Non-disjoint detectors allocate their own momentum distribution count
! array
! Disjoint detectors are passed a pointer to an overall momentum
! distribution count array
logical :: vd_disjoint
! Temporal grid step
real(fp) :: dt
! Units
real(fp) :: hbar
real(fp) :: m
contains
procedure :: init_vd_base => vd_obj_init
end type vd_obj
contains
subroutine vd_obj_init(this, dt, sc, vd_disjoint, hbar, m, vd_np_stdev)
! Initialize base class. This helps to eliminate code reuse in subtypes
!
! This method is exposed as this%init_vd_base
! In an inherited type, it is exposed as this%vd_obj%init_vd_base
!
! this :: vd_obj instance
! dt :: temporal grid step
! sc :: semi-classical flag
! vd_disjoint :: disjoint VD flag
! hbar :: units
! m :: particle mass
! vd_np_stdev :: REQUIRED if sc = False, number of standard deviations to
! include in quantum VD binning
class(vd_obj), intent(inout) :: this
real(fp), intent(in) :: dt
logical, intent(in) :: sc
logical, intent(in) :: vd_disjoint
real(fp), intent(in) :: hbar
real(fp), intent(in) :: m
integer(ip), intent(in), optional :: vd_np_stdev
this%dt = dt
this%semi_classical = sc
this%hbar = hbar
this%m = m
this%vd_disjoint = vd_disjoint
if (present(vd_np_stdev)) then
this%vd_np_stdev = vd_np_stdev
end if
this%net_flux = 0.0_fp
end subroutine vd_obj_init
subroutine vd_get_indices(nx, nxl_ext, nxr_ext, nxl_vd, nxr_vd, xl_min, &
xl_max, xr_min, xr_max)
! Get VD indices relative to total spatial grid
!
! This method also checks whether the external and VD region sizes are
! coherent, and stops with an error if not.
!
! nx :: spatial grid size
! nxl_ext :: number of left external points
! nxr_ext :: number of right external points
! nxl_vd :: number of left VD points
! nxr_vd :: number of right VD points
! xl_min :: left VD minimum index (returned value)
! xl_max :: left VD maximum index (returned value)
! xr_min :: right VD minimum index (returned value)
! xr_max :: right VD maximum index (returned value)
integer, intent(in) :: nx
integer, intent(in) :: nxl_vd, nxl_ext
integer, intent(in) :: nxr_vd, nxr_ext
integer, intent(out) :: xl_min, xl_max
integer, intent(out) :: xr_min, xr_max
! Make sure external and VD region sizes make sense
call vd_validate_spatial_input(nx, nxl_ext, nxr_ext, nxl_vd, nxr_vd)
! We have to be careful here, since Fortran arrays are 1-indexed
xl_min = nxl_ext + 1
xl_max = nxl_ext + nxl_vd
! Account for no virtual detectors
! We use a trick so that iterations like vd_xl_min - 1, vd-xl_mmax + 1
! don't actually iterate.
! Note that this means we *cannot* use array slices, we must use a do loop
if (xl_min > xl_max) then
xl_min = 0
xl_max = -nx
end if
xr_max = nx - nxr_ext
xr_min = xr_max - (nxr_vd - 1)
if (xr_min > xr_max) then
xr_min = 0
xr_max = -nx
end if
end subroutine vd_get_indices
subroutine vd_get_local_quantities(psi_arr, dx, m, hbar, p_mu, p_var, j)
! Get local p_mu, p_var, j quantities
!
! psi_arr :: 3-element slice of wavefunction surround the virtual detector,
! in the desired spatial component direction. We require three elements
! because we use three-point finite differencing for derivatives.
! dx :: spatial component grid step
! m :: mass
! hbar :: units
! p_mu :: local component momentum value (to be returned)
! p_var :: local component momentum variance (to be returned)
! j :: local component flux (to be returned)
complex(fp), intent(in) :: psi_arr(3)
real(fp), intent(in) :: dx
real(fp), intent(in) :: m
real(fp), intent(in) :: hbar
real(fp), intent(inout) :: p_mu
real(fp), intent(inout) :: p_var
real(fp), intent(inout) :: j
real(fp) :: eps_fp
integer(ip) :: i_x
real(fp) :: phi_arr(3), mag_arr(3), p_arr(3), p_var_arr(3)
complex(fp) :: z
eps_fp = epsilon(1.0_fp)
do i_x = 1, 3
z = psi_arr(i_x)
phi_arr(i_x) = numerics_cmplx_phase(z) * hbar
mag_arr(i_x) = abs(z)**2
end do
! Get local (mean) momentum
call numerics_d1(phi_arr, p_arr, dx)
p_mu = p_arr(2)
! Get local current
j = mag_arr(2) / m * p_mu
! Calculate local momentum variance
! Note that this is numerically unstable!
call numerics_d2(log(mag_arr), p_var_arr, dx)
p_var = - hbar**2 / 4.0_fp * p_var_arr(2)
! There are cases in which the values of mag_arr are less than machine
! precision so that the derivative operation above is completely
! numerically unstable. In these cases, we attempt to solve this by setting
! the variance equal to the machine epsilon. This can be justified
! (informally) using L'Hopital's rule:
!
! d^2/dx^2 log(rho) = 1 / rho^2 ( rho * rho'' - rho''^2)
!
! If rho <= eps locally then rho' and rho'' <= rho, so
! d^2/dx^2 log(rho) <= eps, which means we can't have a better estimate
! than setting p_var to be the machine epsilon.
if (ieee_is_nan(p_var) .or. (p_var .lt. eps_fp)) then
p_var = eps_fp
end if
end subroutine vd_get_local_quantities
subroutine vd_validate_spatial_input(nx, nxl_ext, nxr_ext, nxl_vd, nxr_vd)
! Validate spatial grid setup and exit abnormally if errors are found
!
! nx :: number of spatial grid points
! nxl_ext :: number of left external grid points
! nxr_ext :: number of right external grid points
! nxl_vd :: number of left virtual detector points
! nxr_vd :: number of right virtuald detector points
integer(ip) :: nx
integer(ip) :: nxl_ext
integer(ip) :: nxr_ext
integer(ip) :: nxl_vd
integer(ip) :: nxr_vd
logical :: sane
character(:), allocatable :: error_msg
! sane = (nxl_ext .gt. 0) .and. (nxr_ext .gt. 0)
! if (.not. sane) then
! error_msg = "No external region defined in numerical grid; "// &
! "stopping abnormally."
! call log_log_critical(error_msg, log_stderr)
! stop 0
! end if
sane = (nxl_vd .gt. 0) .or. (nxr_vd .gt. 0)
if (.not. sane) then
error_msg = "At least one virtual detectors must be present in "// &
"numerical grid; stopping abnormally."
call log_log_critical(error_msg, log_stderr)
stop 0
end if
sane = .true.
if ( (nxl_vd .gt. 0 .and. nxl_ext .eq. 0) .or. &
(nxr_vd .gt. 0 .and. nxr_ext .eq. 0) ) then
sane = .false.
error_msg = "At least 1 external point required for a virtual "// &
"detector to be present; stopping abnormally."
call log_log_critical(error_msg, log_stderr)
stop 0
end if
sane = (nx .gt. nxl_ext + nxr_ext + nxl_vd + nxr_vd)
if (.not. sane) then
error_msg = "Numerical grid size greater than number of allocated "// &
"points; no internal region possible; exiting abnormally."
call log_log_critical(error_msg, log_stderr)
stop 0
end if
end subroutine vd_validate_spatial_input
subroutine vd_validate_quantum_update(i_p_min, i_p_max, np, valid)
integer(ip), intent(inout) :: i_p_min, i_p_max
integer(ip), intent(in) :: np
logical, intent(inout) :: valid
valid = .true.
! If p_min > this%p_max or p_max < this%p_min we don't do anything
if ( (i_p_min .eq. 0_ip) .or. (i_p_max .eq. -1_ip) ) then
valid = .false.
else
! If p_mmin < this%p_min, we start at this%p_min
if (i_p_min .eq. -1_ip) then
i_p_min = 1_ip
end if
! If p_max > this%p_max, we end at this%p_max
if (i_p_max .eq. 0_ip) then
i_p_max = np
end if
end if
end subroutine vd_validate_quantum_update
end module vd
|
# Black-Scholes Option Pricing Model
Black–Scholes–Merton model is a mathematical model for the dynamics of a financial market containing derivative investment instruments. From the partial differential equation in the model, known as the Black–Scholes equation, one can deduce the Black–Scholes formula, which gives a theoretical estimate of the price of European-style options and shows that the option has a unique price regardless of the risk of the security and its expected return (instead replacing the security's expected return with the risk-neutral rate).
The key idea behind the model is to hedge the option by buying and selling the underlying asset in just the right way and, as a consequence, to eliminate risk. This type of hedging is called "continuously revised delta hedging" and is the basis of more complicated hedging strategies such as those engaged in by investment banks and hedge funds.
The Black–Scholes model assumes that the market consists of at least one risky asset, usually called the stock, and one riskless asset, usually called the money market, cash, or bond.
Now we make assumptions on the assets (which explain their names):
- (riskless rate) The rate of return on the riskless asset is constant and thus called the risk-free interest rate.
- (random walk) The instantaneous log return of stock price is an infinitesimal random walk with drift; more precisely, it is a geometric Brownian motion, and we will assume its drift and volatility are constant (if they are time-varying, we can deduce a suitably modified Black–Scholes formula quite simply, as long as the volatility is not random).
- The stock does not pay a dividend.
Assumptions on the market:
- There is no arbitrage opportunity (i.e., there is no way to make a riskless profit).
- It is possible to borrow and lend any amount, even fractional, of cash at the riskless rate.
- It is possible to buy and sell any amount, even fractional, of the stock (this includes short selling).
- The above transactions do not incur any fees or costs (i.e., frictionless market).
The Black-Scholes formula:
\begin{equation}
\frac{\partial V}{ \partial t} + \frac{1}{2}\sigma^{2} S^{2} \frac{\partial^{2} V}{\partial S^2} + r S \frac{\partial V}{\partial S} - r V = 0
\end{equation}
"The Greeks" measure the sensitivity of the value of a derivative or a portfolio to changes in parameter value(s) while holding the other parameters fixed. They are partial derivatives of the price with respect to the parameter values. One Greek, "gamma" is a partial derivative of another Greek, "delta" in this case.
The Greeks are important not only in the mathematical theory of finance, but also for those actively trading. Financial institutions will typically set (risk) limit values for each of the Greeks that their traders must not exceed. Delta is the most important Greek since this usually confers the largest risk. Many traders will zero their delta at the end of the day if they are speculating and following a delta-neutral hedging approach as defined by Black–Scholes.
Typically the following Greeks are of interest: Delta, Vega and Gamma.
Black-Scholes Call and Put Option Price Formulas:
$C=S_{0}*N(d_{1})-Ke^{-rt}*N(d_{2})$
$P=Ke^{-rt}*N(-d_{2})-S_{0}*N(-d_{1})$
where $N(x)$ is the standard normal cumulative distribution function
$d_{1}=\frac{\ln{\frac{S_{o}}{K}}+t(r+\frac{\sigma^{2}}{2})}{\sigma\sqrt{t}}$
$d_{2}=d_{1}-\sigma\sqrt{t}$
```python
import math
from scipy import stats
```
```python
# Option parameters
K = 110 # strike price
r = .04 # interest rate
sigma = .3 # volatility - standard deviation of the stock
T = 1 # time maturity
S0 = 100 # starting price of the stock
```
```python
def get_black_scholes_simulation_results(K, r, sigma, T, S0, is_call=True):
"""
Calculates option price using Black-Scholes model,
returns the option value and the dict of calculated greeks in the form of a list
"""
d1 = (math.log(S0 / K) +
(r + (0.5 * sigma**2)) * T) / (sigma * math.sqrt(T))
d2 = d1 - (sigma * math.sqrt(T))
if is_call:
call_value = S0 * stats.norm.cdf(d1, 0, 1) - K * math.exp(
-r * T) * stats.norm.cdf(d2, 0, 1)
delta_call = stats.norm.cdf(d1, 0, 1)
gamma_call = stats.norm.pdf(d1, 0, 1) / (S0 * sigma * math.sqrt(T))
theta_call = -(r * K * math.exp(-r * T) * stats.norm.cdf(d2, 0, 1)) - (
sigma * S0 * stats.norm.pdf(d1, 0, 1) / (2 * math.sqrt(T)))
rho_call = T * K * math.exp(-r * T) * stats.norm.cdf(d2, 0, 1)
vega_call = math.sqrt(T) * S0 * stats.norm.pdf(d1, 0, 1)
return [
call_value, {
'delta': delta_call,
'gamma': gamma_call,
'theta': theta_call,
'rho': rho_call,
'vega': vega_call
}
]
else:
put_value = K * math.exp(-r * T) * stats.norm.cdf(-d2, 0, 1) - (
S0 * stats.norm.cdf(-d1, 0, 1))
delta_put = -stats.norm.cdf(-d1, 0, 1)
gamma_put = stats.norm.pdf(d1, 0, 1) / (S0 * sigma * math.sqrt(T))
theta_put = (r * K * math.exp(-r * T) * stats.norm.cdf(-d2, 0, 1)) - (
sigma * S0 * stats.norm.pdf(d1, 0, 1) / (2 * math.sqrt(T)))
rho_put = -T * K * math.exp(-r * T) * stats.norm.cdf(-d2, 0, 1)
vega_put = math.sqrt(T) * S0 * stats.norm.pdf(d1, 0, 1)
return [
put_value, {
'delta': delta_put,
'gamma': gamma_put,
'theta': theta_put,
'rho': rho_put,
'vega': vega_put
}
]
```
```python
bs_call_results = get_black_scholes_simulation_results(K, r, sigma, T, S0)
bs_put_results = get_black_scholes_simulation_results(K, r, sigma, T, S0, is_call=False)
print('\nVanila European Call:\n' + '\nValue: ' + str(bs_call_results[0]) + '\nDelta: ' +
str(bs_call_results[1]['delta']))
print('\nVanila European Put:\n' + '\nValue: ' + str(bs_put_results[0]) + '\nDelta: ' +
str(bs_put_results[1]['delta']))
```
Vanila European Call:
Value: 9.625357828843697
Delta: 0.48629214299030143
Vanila European Put:
Value: 15.312196135599244
Delta: -0.5137078570096986
|
The set of points in $\mathbb{R}^n$ whose $i$th coordinate is in $B_i$ is equal to the set of points in $\mathbb{R}^n$ whose $i$th coordinate is in $B_i$ for all $i$. |
import os
import gc
import sys
import json
import time
import random
import logging
import warnings
from pathlib import Path
from functools import partial
from collections import OrderedDict
import cv2
import yaml
import psutil
import torch
import numpy as np
import pandas as pd
from tqdm import tqdm
import rasterio as rio
from PIL import Image
#import nvidia_smi
import albumentations as albu
import albumentations.pytorch as albu_pt
warnings.filterwarnings("ignore", category=rio.errors.NotGeoreferencedWarning)
import segmentation_models_pytorch as smp
import ttach as tta
import nvidia_smi
class TFReader:
"""Reads tiff files.
If subdatasets are available, then use them, otherwise just handle as usual.
"""
def __init__(self, path_to_tiff_file: str):
self.ds = rio.open(path_to_tiff_file)
self.subdatasets = self.ds.subdatasets
# print('subs:', self.subdatasets)
self.is_subsets_avail = len(self.subdatasets) > 1 # 0? WTF
if self.is_subsets_avail:
path_to_subdatasets = self.ds.subdatasets
self.list_ds = [rio.open(path_to_subdataset)
for path_to_subdataset in path_to_subdatasets]
def read(self, window=None, boundless=True):
if window is not None:
ds_kwargs = {'window': window, 'boundless': boundless}
else:
ds_kwargs = {}
if self.is_subsets_avail:
t = [ds.read(**ds_kwargs) for ds in self.list_ds]
output = np.vstack(t)
else:
output = self.ds.read(**ds_kwargs)
return output
@property
def shape(self):
return self.ds.shape
def __del__(self):
del self.ds
if self.is_subsets_avail:
del self.list_ds
def close(self):
self.ds.close()
if self.is_subsets_avail:
for i in range(len(self.list_ds)):
self.list_ds[i].close()
def get_images(train=False):
p = 'train' if train else 'test'
return list(Path(f'/kaggle/input/hubmap-kidney-segmentation/{p}').glob('*.tiff'))
def get_random_crops(n=8, ss=512):
imgs = get_images(False)
img = random.choice(imgs)
tfr = TFReader(img)
W, H = tfr.shape
for i in range(n):
x, y, w, h = random.randint(5000, W - 5000), random.randint(5000, H - 5000), ss, ss
res = tfr.read(window=((y, y + h), (x, x + w)))
yield res
tfr.close()
def test_tf_reader():
window = ((5000, 5100), (5000, 5100))
imgs = get_images(False)
for img in imgs:
tfr = TFReader(img)
res = tfr.read(window=window)
print(img.name, tfr.shape, tfr.is_subsets_avail, res.shape, res.dtype, res.max())
tfr.close()
def mb_to_gb(size_in_mb): return round(size_in_mb / (1024 * 1024 * 1024), 3)
def get_ram_mems():
total, avail, used = mb_to_gb(psutil.virtual_memory().total), \
mb_to_gb(psutil.virtual_memory().available), \
mb_to_gb(psutil.virtual_memory().used)
return f'Total RAM : {total} GB, Available RAM: {avail} GB, Used RAM: {used} GB'
def load_model(model, model_folder_path):
model = _load_model_state(model, model_folder_path)
model.eval()
return model
def _load_model_state(model, path):
path = Path(path)
state_dict = torch.load(path, map_location=torch.device('cpu'))['model_state']
new_state_dict = OrderedDict()
for k, v in state_dict.items():
if k.startswith('module'):
k = k.lstrip('module')[1:]
new_state_dict[k] = v
del state_dict
model.load_state_dict(new_state_dict)
del new_state_dict
return model
class ToTensor(albu_pt.ToTensorV2):
def apply_to_mask(self, mask, **params): return torch.from_numpy(mask).permute((2, 0, 1))
def apply(self, image, **params): return torch.from_numpy(image).permute((2, 0, 1))
def rescale(batch_img, scale):
return torch.nn.functional.interpolate(batch_img, scale_factor=(scale, scale), mode='bilinear', align_corners=False)
class MegaModel():
def __init__(self, model_folders, use_tta=True, use_cuda=True, threshold=.5, half_mode=False):
self.use_cuda = use_cuda
self.threshold = threshold
self.use_tta = use_tta
self.half_mode = half_mode
self.averaging = 'mean'
self._model_folders = model_folders # list(Path(root).glob('*')) # root / model1 ; model2; model3; ...
self._model_types = [
smp.UnetPlusPlus(encoder_name='timm-regnety_016', encoder_weights=None, decoder_attention_type='scse'),
smp.Unet(encoder_name='timm-regnetx_032', encoder_weights=None),
smp.Unet(encoder_name='timm-regnety_016', encoder_weights=None),
smp.Unet(encoder_name='timm-regnety_016', encoder_weights=None, decoder_attention_type='scse')
]
self._model_scales = [3, 3, 3, 3]
assert len(self._model_types) == len(self._model_folders)
assert len(self._model_scales) == len(self._model_folders)
self.models = self.models_init()
mean, std = [0.6226, 0.4284, 0.6705], [0.1246, 0.1719, 0.0956]
self.itransform = albu.Compose([albu.Normalize(mean=mean, std=std), ToTensor()])
# print(self.models)
def models_init(self):
models = {}
tta_transforms = tta.Compose(
[
tta.HorizontalFlip(),
tta.Rotate90(angles=[0, 90])
]
)
for mt, mf, ms in zip(self._model_types, self._model_folders, self._model_scales):
mf = Path(mf)
model_names = list(mf.rglob('*.pth'))
mm = []
for mn in model_names:
m = load_model(mt, mn)
# print(mn)
if self.use_tta: m = tta.SegmentationTTAWrapper(m, tta_transforms, merge_mode='mean')
if self.use_cuda: m = m.cuda()
if self.half_mode: m = m.half()
mm.append(m)
models[mf] = {'scale': ms, 'models': mm}
return models
def _prepr(self, img, scale):
ch, H, W, dtype = *img.shape, img.dtype
assert ch == 3 and dtype == np.uint8
img = img.transpose(1, 2, 0)
img = cv2.resize(img, (W // scale, H // scale), interpolation=cv2.INTER_AREA)
return self.itransform(image=img)['image']
def each_forward(self, model, scale, batch):
# print(batch.shape, batch.dtype, batch.max(), batch.min())
with torch.no_grad():
res = model(batch)
res = torch.sigmoid(res)
res = rescale(res, scale)
return res
def __call__(self, imgs, cuda=True):
batch = None
scale = None
preds = []
for mod_name, params in self.models.items(): # [{'a/b/c/1231.pth':{'type':Unet,'scale':3 }}, .. ]
_scale = params['scale']
if batch is None or scale != _scale:
scale = _scale
batch = [self._prepr(i, scale) for i in imgs]
batch = torch.stack(batch, axis=0)
if self.half_mode: batch = batch.half()
if self.use_cuda: batch = batch.cuda()
# print(batch.shape, batch.dtype, batch.max())
models = params['models']
_predicts = torch.stack([self.each_forward(m, scale, batch) for m in models])
preds.append(_predicts)
res = torch.vstack(preds).mean(0)
res = res > self.threshold
return res
class Dummymodel(torch.nn.Module):
def forward(self, x):
x[x < .5] = 0.9
return x
def infer(imgs, model):
assert isinstance(imgs, list)
# c, h, w = imgs[0].shape
# batch = torch.rand(len(imgs), 1, h, w).float()
with torch.no_grad():
predicts = model(imgs)
return predicts
def get_infer_func(model_folders, use_tta, use_cuda, threshold):
m = MegaModel(model_folders=model_folders, use_tta=use_tta, use_cuda=use_cuda, threshold=threshold)
return partial(infer, model=m)
def get_gpu_mems():
nvidia_smi.nvmlInit()
handle = nvidia_smi.nvmlDeviceGetHandleByIndex(0)
info = nvidia_smi.nvmlDeviceGetMemoryInfo(handle)
total, avail, used = mb_to_gb(info.total), \
mb_to_gb(info.free), \
mb_to_gb(info.used)
nvidia_smi.nvmlShutdown()
return f'Total GPU mem: {total} GB, Available GPU mem: {avail} GB, Used GPU mem: {used} GB'
def _count_blocks(dims, block_size):
nXBlocks = (int)((dims[0] + block_size[0] - 1) / block_size[0])
nYBlocks = (int)((dims[1] + block_size[1] - 1) / block_size[1])
return nXBlocks, nYBlocks
def generate_block_coords(H, W, block_size):
h, w = block_size
nYBlocks = (int)((H + h - 1) / h)
nXBlocks = (int)((W + w - 1) / w)
for X in range(nXBlocks):
cx = X * h
for Y in range(nYBlocks):
cy = Y * w
yield cy, cx, h, w
def pad_block(y, x, h, w, pad): return np.array([y - pad, x - pad, h + 2 * pad, w + 2 * pad])
def crop(src, y, x, h, w): return src[..., y:y + h, x:x + w]
def crop_rio(ds, y, x, h, w):
block = ds.read(window=((y, y + h), (x, x + w)), boundless=True)
# block = np.zeros((3, h, w), dtype = np.uint8)
return block
def paste(src, block, y, x, h, w): src[..., y:y + h, x:x + w] = block
def paste_crop(src, part, block_cd, pad):
_, H, W = src.shape
y, x, h, w = block_cd
h, w = min(h, H - y), min(w, W - x)
part = crop(part, pad, pad, h, w)
paste(src, part, *block_cd)
def mp_func_wrapper(func, args): return func(*args)
def chunkify(l, n): return [l[i:i + n] for i in range(0, len(l), n)]
def mask2rle(img):
pixels = img.T.flatten()
pixels[0] = 0
pixels[-1] = 0
runs = np.where(pixels[1:] != pixels[:-1])[0] + 2
runs[1::2] -= runs[::2]
return ' '.join(str(x) for x in runs)
def infer_blocks(blocks, do_inference):
blocks = do_inference(blocks).cpu().numpy()
if isinstance(blocks, tuple): blocks = blocks[0]
# print(blocks.shape, blocks.dtype, blocks.max())
# c, h, w = blocks[0].shape
# blocks = np.ones((len(blocks), 1, h, w), dtype=np.int32)
# blocks = blocks > threshold
return blocks # .astype(np.uint8)
def start(img_name, do_inference):
logger.info('Start')
scale = 3
s = 512
block_size = s * scale
batch_size = 8
pad = s // 4 * scale
ds = TFReader(str(img_name))
H, W = ds.shape
cds = list(generate_block_coords(H, W, block_size=(block_size, block_size)))
# cds = cds[:36]
total_blocks = len(cds)
mask = np.zeros((1, H, W)).astype(np.bool)
count = 0
batch = []
for block_cd in tqdm(cds):
if len(batch) == batch_size:
blocks = [b[0] for b in batch]
block_cds = [b[1] for b in batch]
logger.info(get_gpu_mems())
block_masks = infer_blocks(blocks, do_inference)
[paste_crop(mask, block_mask, block_cd, pad) for block_mask, block_cd, _ in
zip(block_masks, block_cds, blocks)]
batch = []
gc.collect()
padded_block_cd = pad_block(*block_cd, pad)
block = crop_rio(ds, *(padded_block_cd))
batch.append((block, block_cd))
# print(block_cd, block.shape)
count += 1
if batch:
blocks = [b[0] for b in batch]
block_cds = [b[1] for b in batch]
logger.info(get_gpu_mems())
block_masks = infer_blocks(blocks, do_inference)
[paste_crop(mask, block_mask, block_cd, pad) for block_mask, block_cd, _ in zip(block_masks, block_cds, blocks)]
# print('Drop last batch', len(batch))
batch = []
print(mask.shape, mask.dtype, mask.max(), mask.min(), mask.sum() / np.prod(mask.shape))
# mask = (mask > threshold).astype(np.uint8)
ds.close()
print('to rle: ')
rle = mask2rle(mask)
return rle
logger = logging.getLogger('dev')
logger.setLevel(logging.INFO)
fileHandler = logging.FileHandler('/kaggle/working/log.log')
fileHandler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)
model_folders = ['../input/pambmod8/models8/UnetPlusPlus_timm-regnety_016_scse',
'../input/pambmod8/models8/Unet_timm-regnetx_032',
'../input/pambmod8/models8/Unet_timm-regnety_016',
'../input/pambmod8/models8/Unet_timm-regnety_016_scse'
]
threshold = 0.55
use_tta=True
use_cuda=True
do_inference = get_infer_func(model_folders, use_tta=use_tta, use_cuda=use_cuda, threshold=threshold)
imgs = get_images()
subm = {}
for img_name in imgs:
print(img_name)
rle = start(img_name, do_inference=do_inference)
subm[img_name.stem] = {'id':img_name.stem, 'predicted': rle}
df_sub = pd.DataFrame(subm).T
df_sub.to_csv('submission.csv', index=False)
|
The sign has arrived and I couldn’t be more thrilled! It’s PERFECT!!! Thanks a million! |
C @(#)incr1red.f 20.3 2/13/96
C****************************************************************
C
C File: incr1red.f
C
C Purpose: Integer function to increment original branch nb
C indices.
C
C Author: Walt Powell Date: 14 December 1992
C Called by: reduct.f
C
C****************************************************************
C
integer function incr1red (ptr, oldptr, nb, k2, id, ksw)
integer ptr, oldptr
character id*1
include 'ipfinc/parametr.inc'
include 'ipfinc/blank.inc'
include 'ipfinc/bus.inc'
include 'ipfinc/branch.inc'
C
C Increment indices for YMTRX
C
c ksw assignments: 1 - normal
c 2 - e-o-f ptr (kx-ky-brnch)
c 3 - e-o-f jt (yred)
c 4 - e-o-f ptr and jt
c
1920 if (ksw .eq. 1 .or. ksw .eq. 3) then
if (ptr .eq. 0) then
ptr = kbsdta(16,nb)
oldptr = 0
else
oldptr = ptr
ptr = brnch_nxt(ptr)
endif
if (ptr .gt. 0) then
k2=ky(ptr)
if (brtype(ptr) .eq. 2 .or. brtype(ptr) .eq. 7)
& go to 1920
id = brid(ptr)
else
ksw = ksw + 1
k2=0
endif
endif
incr1red = ksw
return
end
|
lemma Lim_component_eq: fixes f :: "'a \<Rightarrow> 'b::euclidean_space" assumes net: "(f \<longlongrightarrow> l) net" "\<not> trivial_limit net" and ev:"eventually (\<lambda>x. f(x)\<bullet>i = b) net" shows "l\<bullet>i = b" |
State Before: R : Type u
S : Type v
k : Type y
A : Type z
a b : R
n : ℕ
inst✝¹ : Field R
p q : R[X]
inst✝ : CommSemiring k
ϕ : R →+* k
f g : R[X]
α : k
hf : eval₂ ϕ α f = 0
hg : eval₂ ϕ α g = 0
⊢ eval₂ ϕ α (EuclideanDomain.gcd f g) = 0 State After: no goals Tactic: rw [EuclideanDomain.gcd_eq_gcd_ab f g, Polynomial.eval₂_add, Polynomial.eval₂_mul,
Polynomial.eval₂_mul, hf, hg, MulZeroClass.zero_mul, MulZeroClass.zero_mul, zero_add] |
[STATEMENT]
lemma C_eq_normalizePrQ:
"DenyAll \<in> set (policy2list p) \<Longrightarrow> allNetsDistinct (policy2list p) \<Longrightarrow>
all_in_list (policy2list p) (Nets_List p) \<Longrightarrow>
Cp (list2FWpolicy (normalizePrQ p)) = Cp p"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>DenyAll \<in> set (policy2list p); allNetsDistinct (policy2list p); all_in_list (policy2list p) (Nets_List p)\<rbrakk> \<Longrightarrow> Cp (list2FWpolicy (normalizePrQ p)) = Cp p
[PROOF STEP]
unfolding normalizePrQ_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>DenyAll \<in> set (policy2list p); allNetsDistinct (policy2list p); all_in_list (policy2list p) (Nets_List p)\<rbrakk> \<Longrightarrow> Cp (list2FWpolicy (removeAllDuplicates (insertDenies (separate (qsort (removeShadowRules2 (remdups (rm_MT_rules Cp (insertDeny (removeShadowRules1 (policy2list p)))))) (Nets_List p)))))) = Cp p
[PROOF STEP]
using C_eq_compileQ
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>DenyAll \<in> set (policy2list ?p); all_in_list (policy2list ?p) ?l; allNetsDistinct (policy2list ?p)\<rbrakk> \<Longrightarrow> Cp (list2FWpolicy (removeAllDuplicates (insertDenies (separate (qsort (removeShadowRules2 (remdups (rm_MT_rules Cp (insertDeny (removeShadowRules1 (policy2list ?p)))))) ?l))))) = Cp ?p
goal (1 subgoal):
1. \<lbrakk>DenyAll \<in> set (policy2list p); allNetsDistinct (policy2list p); all_in_list (policy2list p) (Nets_List p)\<rbrakk> \<Longrightarrow> Cp (list2FWpolicy (removeAllDuplicates (insertDenies (separate (qsort (removeShadowRules2 (remdups (rm_MT_rules Cp (insertDeny (removeShadowRules1 (policy2list p)))))) (Nets_List p)))))) = Cp p
[PROOF STEP]
by auto |
Load LFindLoad.
From lfind Require Import LFind.
From QuickChick Require Import QuickChick.
From adtind Require Import goal33.
Derive Show for natural.
Derive Arbitrary for natural.
Instance Dec_Eq_natural : Dec_Eq natural.
Proof. dec_eq. Qed.
Lemma conj18eqsynthconj2 : forall (lv0 : natural) (lv1 : natural) (lv2 : natural), (@eq natural (plus (plus lv0 lv1) lv2) (plus lv2 (plus lv1 lv0))).
Admitted.
QuickChick conj18eqsynthconj2.
|
module Data.IOArray
import Data.IOArray.Prims
import Data.List
%default total
export
record IOArray elem where
constructor MkIOArray
maxSize : Int
content : ArrayData (Maybe elem)
export
max : IOArray elem -> Int
max = maxSize
export
newArray : HasIO io => Int -> io (IOArray elem)
newArray size
= pure (MkIOArray size !(primIO (prim__newArray size Nothing)))
export
writeArray : HasIO io => IOArray elem -> Int -> elem -> io Bool
writeArray arr pos el
= if pos < 0 || pos >= max arr
then pure False
else do primIO (prim__arraySet (content arr) pos (Just el))
pure True
export
readArray : HasIO io => IOArray elem -> Int -> io (Maybe elem)
readArray arr pos
= if pos < 0 || pos >= max arr
then pure Nothing
else primIO (prim__arrayGet (content arr) pos)
-- Make a new array of the given size with the elements copied from the
-- other array
export
newArrayCopy : HasIO io =>
(newsize : Int) -> IOArray elem -> io (IOArray elem)
newArrayCopy newsize arr
= do let newsize' = if newsize < max arr then max arr else newsize
arr' <- newArray newsize'
copyFrom (content arr) (content arr') (max arr - 1)
pure arr'
where
copyFrom : ArrayData (Maybe elem) ->
ArrayData (Maybe elem) ->
Int -> io ()
copyFrom old new pos
= if pos < 0
then pure ()
else do el <- primIO $ prim__arrayGet old pos
primIO $ prim__arraySet new pos el
copyFrom old new $ assert_smaller pos (pos - 1)
export
toList : HasIO io => IOArray elem -> io (List (Maybe elem))
toList arr = iter 0 (max arr) []
where
iter : Int -> Int -> List (Maybe elem) -> io (List (Maybe elem))
iter pos end acc
= if pos >= end
then pure (reverse acc)
else do el <- readArray arr pos
assert_total (iter (pos + 1) end (el :: acc))
export
fromList : HasIO io => List (Maybe elem) -> io (IOArray elem)
fromList ns
= do arr <- newArray (cast (length ns))
addToArray 0 ns arr
pure arr
where
addToArray : Int -> List (Maybe elem) -> IOArray elem -> io ()
addToArray loc [] arr = pure ()
addToArray loc (Nothing :: ns) arr = addToArray (loc + 1) ns arr
addToArray loc (Just el :: ns) arr
= do primIO $ prim__arraySet (content arr) loc (Just el)
addToArray (loc + 1) ns arr
|
<h1 style='font-size:4rem;color:orange;'>Math 267 Project #4
# Dynamical Systems
In simplest terms a Dynamical System is a point moving in space. We call this space a phase space
and the path for the point a trajectory or orbit. The point could represent an actual particle that is moving in physical space or it could represent the instantaneous state of our Dynamical System. The trajectory thus illustrates how the system evolves with time. The evolution follows a vector field. The trajectories could be fixed points, spirals, closed loops that represent periodic behavior or the trajectory could be a chaotic orbit. Both the predator-prey system and the mass-spring system are examples of Dynamical Systems. For the predator-prey system a point the phase space (the xy plane) represents the current population of the foxes and rabbits. For the mass spring system a point represents the current position and velocity of the mass. Thus for this case the instantaneous energy in the system is a function of the point. More on this later..
---
# The Pendulum
The equation of motion for a driven damped pendulum with mass 1 and arm length 1 is:
$$ \theta''(t) + b\; \theta'(t) + g \sin(\theta) = A \sin(\omega_f t)$$
where $\theta$ is the angular displacement for the pendulum. The forcing term is a sinusoidal driving force with an amplitude of A and a period of $2 \pi / \omega_f$. We derive this equation in class. Please refer to your text for further details. It is assumed that the pendulum is attached to a wall such that it is free to rotate through 360 degrees, thus $\omega + 2\pi$ and $\omega$ correspond to the same pendulum position. We can reduce this second order equation to a system by introducing the variable $\omega = \theta’$ , where $\omega$ represents the angular velocity for the pendulum motion. For convenience let us assume that units are chosen so that g = 1. The system is written as:
\begin{align}
\theta'(t) &= \; \omega(t) \\
\omega'(t) &= -b \omega(t) + A \sin(\omega_ft)
\end{align}
## 1. The unforced and undamped Pendulum.
For the case where there is both no damping or external forcing, the equation for the pendulum
becomes:
$$\theta'(t) + \sin(\theta) = 0$$
This equation while simple in appearance cannot be solve analytically. For small $\theta$ we could use the small angle approximation, namely $\sin(\theta) ≈\theta$, and the equation becomes linear. Otherwise numerical methods are required to solve the system. We can however get an idea of what the solutions should look like. With no damping or means to dissipate the energy, the energy E will be constant along all solutions of the system. The total energy in the system, the potential and kinetic energy, is given by the energy function:
$$E(\theta,\omega) = \frac{1}{2} \omega^2 + 1 - \cos(\theta)$$.
Each trajectory in the phase plane is confined to one or another of the level curves for the energy function. So by plotting the contour map for the energy function we get an idea of what the trajectories should look like. A plot of the contour map for the energy function is shown in the figure below. If we add directions to the level curves we have a phase portrait for the pendulum system. Note that only a unique trajectory can pass through each point in the phase plane. Why?
To determine the direction for these trajectories we simply look at the vector field for the system. Writing the unforced, undamped equation as a system gives
\begin{align}
\theta'(t) &= \; f(\theta, \omega) =\omega \\
\omega'(t) &= \;g(\theta,\omega)= -\sin(\omega).
\end{align}
So our vector field is:
$$\mathbf{F}(θ,ω) = (f(θ,ω),g(θ,ω)) = (ω,-sin(θ)).$$
Evaluating the vector field at the point (0,1) gives $F(0,1) = (1,0)$ and the trajectory is thus pointing to the right at this point meaning that $\theta$ is increasing. Repeating this for other points in the phase plane allows us to attach direction arrows to the contour curves. The phase portrait for the undamped pendulum is shown in the figure below.
The solution curves encircling the origin where $-π < θ(t) < π$ correspond to the pendulum oscillating about the downward rest position. The solution curve at the top of the phase portrait corresponds to the pendulum spinning forever in the clockwise direction. The opposite is true for the trajectory at the bottom of the phase portrait.
---
## 2. The unforced and damped Pendulum
For the case where there is damping but no external forcing, the equations for the pendulum becomes:
\begin{align}
\theta'(t) &= \; f(\theta, \omega) =\omega \\
\omega'(t) &= \;g(\theta,\omega)= -\sin(\theta)-b\omega.
\end{align}
The equilibrium points for this plane autonomous system are determined by setting:
$$\mathbf{F}(θ, ω) = 0 \;or f (θ, ω) = g(θ, ω) = 0$$
Solving gives the points (0, 0) and (0, π).
These points correspond to the pendulum being positioned either in the downward rest position or straight up (θ=π). To determine the stability of these points we need to linearize the system by computing the Jacobian matrix. See 10.3 in the text for further information on the Jacobian. The Jacobian matrix A for the system is defined as a matrix of partial derivatives.
\begin{align} A=
\begin{pmatrix}
\frac{\partial}{\partial \theta}f(\theta,\omega)
& \frac{\partial}{\partial \omega}f(\theta,\omega)\\
\frac{\partial}{\partial \theta}g(\theta,\omega)
& \frac{\partial}{\partial \omega}g(\theta,\omega)
\end{pmatrix}
\end{align}
For the undriven, damped pendulum system the Jacobian is:
\begin{align} A=
\begin{pmatrix}
0 & 1\\
-\cos(\theta)
& -b
\end{pmatrix}
\end{align}
Now to determine the stability of an equilibrium point, the Jacobian is evaluated at that point and the eigenvalues are tested. For example, for the equilibrium point (0,0) (the rest position) the linearized system is:
\begin{align}
\begin{pmatrix}
\theta'(t) \\
\omega'(t)
\end{pmatrix}=
\begin{pmatrix}
0 & 1 \\
-1 & -b
\end{pmatrix}\cdot
\begin{pmatrix}
\theta(t) \\
\omega(t)
\end{pmatrix}
\end{align}
With a damping constant b = 0, the eigenvalues are pure imaginary and the origin is a “center” thus the trajectories will be closed loops with the origin as their center. For b>0 both eigenvalues will have negative real parts and the point (0,0) will be an attractor. Which is what we expect.
---
## 3. The forced and damped Pendulum
For the case where there is damping and external forcing, the equations for the pendulum becomes:
\begin{align}
\theta'(t) &=\omega \\
\omega'(t) &= \; -\sin(\theta)-b\omega + A \sin(\omega_f t).
\end{align}
This is where things get interesting and we will see that for certain parameter values the pendulum will exhibit chaotic behavior. Sensitive dependence on initial conditions is a hallmark of chaos. The plot below shows the response of a pendulum to the following initial conditions. For s(t) the initial angular displacement θ(0) = 0 and for u(t) the initial displacement is θ(0) = 0.001. We notice the curves diverge considerably after about 40 seconds. This is sensitive dependence on initial conditions.
---
### Run the cell below to import necessary libraries.
```python
# import libraries
import numpy as np
from numpy import sin,pi
import matplotlib.pyplot as plt
from IPython.display import Image
# uncomment the line below if you are running a macbook
#%config InlineBackend.figure_format ='retina'
```
## Exericse 1.a
For this exercise you will approximate the solution of an unforced, undamped defined by the system:
\begin{align}
\theta'(t) &= \; \omega \\
\omega'(t) &= \; -\sin(\theta).
\end{align}
You are to create two plots of $\theta$ versus t. For the first plot solve the sytem with initial condition:
$$
\begin{align}
\theta(0) &= \;0.1 \\
\omega(0) &= \; 0
\end{align}
$$
For the second plot solve the system with the initial conditions:
$$
\begin{align}
\theta(0) &= \;1 \\
\omega(0) &= \; 0
\end{align}
$$
Use the improved Euler method( Δt=h = 0.1) and a time interval of 12 seconds.
## Complete the code cell below to solve the sytstem.
```python
# define the slope functions
def f(theta,omega,t=None):
return omega
def g(theta,omega,t=None):
return -np.sin(theta)
h = 0.1 # set delta t
t = np.arange(0,12,h)
# Initialize arrays to store the results.
theta = np.zeros_like(t)
omega = np.zeros_like(t)
# Set initial conditions:
theta[0] = 0
omega[0] = 0.1
# implement the Improved Euler's method
# Your code goes here, look at project #2
```
### Execute the cell below to graph your results.
You should see a sinusoid as the pendulum is set into infinite oscillation (no damping).
```python
plt.figure(figsize=(8,5))
plt.plot(t,theta)
plt.grid()
plt.xlabel('t')
plt.ylabel(r'$\theta$');
plt.plot(2*np.pi,0,'o')
plt.title(r"Exercise #1a. $\theta(0)=0\;,\omega(0)=0.1$");
```
### Execute the cell below to graph the trajectory in the phase plane.
You should see a small circle as the pendulum is set into infinite oscillation (no damping).
```python
plt.figure(figsize=(8,5))
plt.plot(theta,omega,linewidth=2)
plt.xlim(-2*pi,2*pi)
plt.ylim(-4,4)
plt.grid()
plt.xlabel(r'$\theta$-displacement')
plt.ylabel(r'$\omega$');
plt.xticks([-2*pi,-pi,0,pi,2*pi],['-2$\pi$','$-\pi$',0,'$\pi$','$2\pi$'])
plt.title(r"Trajectory for pendulum-Exercise #1a. $\theta(0)=0\;,\omega(0)=0.1$");
```
## Exercise 1.b
Repeat the steps above for $\theta(0)=0 \;\text{and}\; \omega(0) = 1.0$ Copy and paste cells above and make the necessary modifications. Make a plot of $\theta$ versus t. Also plot the trajectory in the phase plane. Make the appropriate change to the title of your plot.
```python
```
```python
```
## Exericse 2.
Use the improved Euler’s method to approximate and graph the solution of the above system with the initial conditions θ(0) = 0 and ω(0) =2.5. Create a θ versus t and a phase plot. Your $\theta$ versus t plot will not be a sinusoid. Again plot your results for the interval [0,12].
```python
```
```python
```
## Exercise 3.
Use the improved Euler’s method to approximate and graph the solution of the above system with a damping constant of b = 0.5. Use the initial conditions θ(0) = 1 and ω(0) =0. Create a θ versus t plot
and a phase plot θ versus ω. Give each plot the following title: "Exercise #3 damped pendulum b=0.5".
```python
# Your code here.
```
```python
```
```python
```
## Exercise 4
In the following exercises we will approximate and graph the solutions for the forced,damped pendulum system with different damping constants. For each exercise we use A = 1.5, ωf = 2/3, and initial condition (θ(0) ,ω(0)) = (0,0).
## Exercise 4.a
Use the improved Euler method to solve the system with b = 0.8, h= Δt=0.1 and time interval of \[0,90]. Make a $\theta$ versus t plot and a phase plot. Give your graphs appropriate titles.
Note: When creating the phase plot we want to omit the transient from the plot and only view the steady state response. This can be accomplished by plotting just the last third of our data values as follows:
```python
plt.plot(theta[600:900],omega[600:900],linewidth=1)
```
Also note a line width of 1 is recommended for the phase plot.
```python
# define the slope functions
b=0.8
def f(theta,omega,t):
return omega
def g(theta,omega,t):
return -np.sin(theta) -b*omega + 1.5*np.sin(2/3*t)
# Your code starts here....
```
### Execute the cell below to graph your results.
```python
plt.figure(figsize=(8,5))
plt.plot(t,theta)
plt.grid()
plt.xlabel('t')
plt.ylabel(r'$\theta$');
plt.title(r"Exercise #4a. b =0.8");
```
### Execute the cell below to see the trajectory in the phase plane for this problem.
```python
plt.figure(figsize=(10,7))
plt.plot(theta[600:900],omega[600:900],linewidth=1)
plt.xlim(-2*pi,2*pi)
plt.ylim(-4,4)
plt.grid()
plt.xlabel(r'$\theta$-displacement')
plt.ylabel(r'$\omega$');
plt.xticks([-2*pi,-pi,0,pi,2*pi],['-2$\pi$','$-\pi$',0,'$\pi$','$2\pi$'])
plt.title(r"Exercise #4a. b =0.8");
```
## Exercise 4.b
Change b = 0.735 and repeat the steps above. Use h = 0.1 and a time interval of \[0,90].
```python
# Place your code here to solve the system in this cell.
```
```python
# Place your code here to make a theta versus t plot in this cell.
```
### Execute the cell below to see the trajectory in the phase plane for this problem.
```python
plt.figure(figsize=(10,7))
plt.plot(theta[600:900],omega[600:900],linewidth=1)
plt.xlim(-2*pi,2*pi)
plt.ylim(-4,4)
plt.grid()
plt.xlabel(r'$\theta$-displacement')
plt.ylabel(r'$\omega$');
plt.xticks([-2*pi,-pi,0,pi,2*pi],['-2$\pi$','$-\pi$',0,'$\pi$','$2\pi$'])
plt.title(r"Exercise #4b. b =0.735");
```
## Exercise 5.
Write the necessary code to recreate the plot that demonstrates sensive dependence on intial condtions. See \#3 above The plot labeled s(t) has an initial value of 0.0 and u(t) has intial value of 0.001. The sinusoid input has an amplitude of 1 and omega = 2/3. The damping for the spring is 0.05. Plot the output for the range (0,80).
For this exercise you will be solving the system twice. Just cut and past code above make the necessary modificatons and in the last line of the cell enter the Python
command.
```python
s=theta;
```
Do the same for a second cell and again end with the command:
```python
u=theta;
```
```python
# Your code here.
```
```python
# Your code here.
```
### Execute the cell below to see a plot of your results
```python
plt.figure(figsize=(8,5))
plt.plot(t,s,label="$s(t)$")
plt.plot(t,u,label="$u(t)$")
plt.grid()
plt.xlabel('t')
plt.legend()
plt.title(r"Exercise #5");
```
## Answer the questions below. You can edit the text cell to enter your answers.
1. For exercises 1.a and 1.b compute the period of oscillation using the small angle approximation. Compare this to the value obtained from the graphs and explain the results.
2. Explain the results of exercise 2, that is, explain the shape of the graphs.
3. Look at the phase plots for exercise \#4. Outputs for both b = 0.8 and b = 0.735 are periodic. How does the period of the output (b=0.735) compare to the output for b=0.8.
To see your input along with the output add the line to the cell that creates the theta versus t plot.
```python
plt.plot(t,1.5*sin(2/3*t))
```
4. In exercise 5. we see that a very small change in initial conditions produce a dramatic change in output. Will the same phenomenon occur with the spring-mass system? In other words can our spring-mass system exhibit sensitive dependence on initial conditions?
|
#' Get a vector of lemma
#'
#' For certain semantic roles syntactic information is not sufficient.
#' Distinguishing between saying and doing something, for instance, requires
#' looking at the specific lemma of the verb.
#' This function returns a vector of lemma for certain categories of verbs.
#'
#' Note that these are not complete lists, and what list works best
#' also depends on the interests of the researcher. For instance, does "believe"
#' (e.g., "Trump believed that ...") indicate a quote or not?
#'
#' @param what Name of the verb category.
#'
#' @return
#' @export
verb_lemma <- function(what = c('be', 'quote','should')) {
what = match.arg(what)
if (what == 'be') lemma = c('be')
if (what == 'quote') lemma = c("tell", "acknowledge", "admit", "affirm", "allege", "argue", "announce", "assert", "attest", "avow", "call", "claim", "comment", "concede", "confirm", "declare", "deny", "describe","exclaim", "express", "insist", "mention", "note", "post","predict", "proclaim", "promise", "reply", "refer", "remark", "report", "say", "state", "suggest", "talk", "tell", "think","warn","write", "add")
if (what == 'should') lemma = c('should','must')
lemma
}
#' Function that adds column for modifiers
#'
#' Adds a column 'mod' that indicates if a token is negated (not, never), or has certain aux relation (should, must)
#'
#' @param tokens A tokenindex
#' @param verbose If true, report progress of queries
#'
#' @return A tokenindex
#' @export
ud_mods <- function(tokens, should_verbs = verb_lemma('should'), verbose=T) {
neg = tquery(label='not', fill=F,
children(label='not', relation='dobj', req=F),
children(relation='neg'))
should = tquery(label='should', fill=F,
children(label='should', relation='dobj', req=F),
children(relation = 'aux', lemma=should_verbs))
should_not = tquery(label='should_not', fill=F,
children(label='should_not', relation='dobj', req=F),
children(relation = 'neg'),
children(relation = 'aux', lemma=should_verbs))
tokens = rsyntax::annotate(tokens, 'mod', sn=should_not, neg=neg, should=should, overwrite=T, verbose=verbose)
tokens$mod_id = NULL
tokens$mod_fill = NULL
tokens
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.