text
stringlengths 0
3.34M
|
---|
(************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
(* v * INRIA, CNRS and contributors - Copyright 1999-2018 *)
(* <O___,, * (see CREDITS file for the list of authors) *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
Require Export Coq.funind.FunInd.
Require Import PeanoNat.
Require Compare_dec.
Require Wf_nat.
Section Iter.
Variable A : Type.
Fixpoint iter (n : nat) : (A -> A) -> A -> A :=
fun (fl : A -> A) (def : A) =>
match n with
| O => def
| S m => fl (iter m fl def)
end.
End Iter.
Theorem le_lt_SS x y : x <= y -> x < S (S y).
Proof.
intros. now apply Nat.lt_succ_r, Nat.le_le_succ_r.
Qed.
Theorem Splus_lt x y : y < S (x + y).
Proof.
apply Nat.lt_succ_r. rewrite Nat.add_comm. apply Nat.le_add_r.
Qed.
Theorem SSplus_lt x y : x < S (S (x + y)).
Proof.
apply le_lt_SS, Nat.le_add_r.
Qed.
Inductive max_type (m n:nat) : Set :=
cmt : forall v, m <= v -> n <= v -> max_type m n.
Definition max m n : max_type m n.
Proof.
destruct (Compare_dec.le_gt_dec m n) as [h|h].
- exists n; [exact h | apply le_n].
- exists m; [apply le_n | apply Nat.lt_le_incl; exact h].
Defined.
Definition Acc_intro_generator_function := fun A R => @Acc_intro_generator A R 100.
|
/-
Copyright (c) 2020 David Wärn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Wärn
-/
import data.equiv.encodable.basic
import order.atoms
/-!
# Order ideals, cofinal sets, and the Rasiowa–Sikorski lemma
## Main definitions
Throughout this file, `P` is at least a preorder, but some sections require more
structure, such as a bottom element, a top element, or a join-semilattice structure.
- `order.ideal P`: the type of nonempty, upward directed, and downward closed subsets of `P`.
Dual to the notion of a filter on a preorder.
- `order.is_ideal P`: a predicate for when a `set P` is an ideal.
- `order.ideal.principal p`: the principal ideal generated by `p : P`.
- `order.ideal.is_proper P`: a predicate for proper ideals.
Dual to the notion of a proper filter.
- `order.ideal.is_maximal`: a predicate for maximal ideals.
Dual to the notion of an ultrafilter.
- `ideal_inter_nonempty P`: a predicate for when the intersection of any two ideals of
`P` is nonempty.
- `ideal_Inter_nonempty P`: a predicate for when the intersection of all ideals of
`P` is nonempty.
- `order.cofinal P`: the type of subsets of `P` containing arbitrarily large elements.
Dual to the notion of 'dense set' used in forcing.
- `order.ideal_of_cofinals p 𝒟`, where `p : P`, and `𝒟` is a countable family of cofinal
subsets of P: an ideal in `P` which contains `p` and intersects every set in `𝒟`. (This a form
of the Rasiowa–Sikorski lemma.)
## References
- <https://en.wikipedia.org/wiki/Ideal_(order_theory)>
- <https://en.wikipedia.org/wiki/Cofinal_(mathematics)>
- <https://en.wikipedia.org/wiki/Rasiowa%E2%80%93Sikorski_lemma>
Note that for the Rasiowa–Sikorski lemma, Wikipedia uses the opposite ordering on `P`,
in line with most presentations of forcing.
## Tags
ideal, cofinal, dense, countable, generic
-/
namespace order
variables {P : Type*}
/-- An ideal on a preorder `P` is a subset of `P` that is
- nonempty
- upward directed (any pair of elements in the ideal has an upper bound in the ideal)
- downward closed (any element less than an element of the ideal is in the ideal). -/
structure ideal (P) [preorder P] :=
(carrier : set P)
(nonempty : carrier.nonempty)
(directed : directed_on (≤) carrier)
(mem_of_le : ∀ {x y : P}, x ≤ y → y ∈ carrier → x ∈ carrier)
/-- A subset of a preorder `P` is an ideal if it is
- nonempty
- upward directed (any pair of elements in the ideal has an upper bound in the ideal)
- downward closed (any element less than an element of the ideal is in the ideal). -/
@[mk_iff] structure is_ideal {P} [preorder P] (I : set P) : Prop :=
(nonempty : I.nonempty)
(directed : directed_on (≤) I)
(mem_of_le : ∀ {x y : P}, x ≤ y → y ∈ I → x ∈ I)
/-- Create an element of type `order.ideal` from a set satisfying the predicate
`order.is_ideal`. -/
def is_ideal.to_ideal [preorder P] {I : set P} (h : is_ideal I) : ideal P :=
⟨I, h.1, h.2, h.3⟩
namespace ideal
section preorder
variables [preorder P] {x y : P} {I J : ideal P}
/-- The smallest ideal containing a given element. -/
def principal (p : P) : ideal P :=
{ carrier := { x | x ≤ p },
nonempty := ⟨p, le_refl _⟩,
directed := λ x hx y hy, ⟨p, le_refl _, hx, hy⟩,
mem_of_le := λ x y hxy hy, le_trans hxy hy, }
instance [inhabited P] : inhabited (ideal P) :=
⟨ideal.principal $ default P⟩
/-- An ideal of `P` can be viewed as a subset of `P`. -/
instance : has_coe (ideal P) (set P) := ⟨carrier⟩
/-- For the notation `x ∈ I`. -/
instance : has_mem P (ideal P) := ⟨λ x I, x ∈ (I : set P)⟩
@[simp] lemma mem_coe : x ∈ (I : set P) ↔ x ∈ I := iff_of_eq rfl
@[simp] lemma mem_principal : x ∈ principal y ↔ x ≤ y := by refl
/-- Two ideals are equal when their underlying sets are equal. -/
@[ext] lemma ext : ∀ (I J : ideal P), (I : set P) = J → I = J
| ⟨_, _, _, _⟩ ⟨_, _, _, _⟩ rfl := rfl
@[simp, norm_cast] lemma ext_set_eq {I J : ideal P} : (I : set P) = J ↔ I = J :=
⟨by ext, congr_arg _⟩
lemma ext'_iff {I J : ideal P} : I = J ↔ (I : set P) = J := ext_set_eq.symm
lemma is_ideal (I : ideal P) : is_ideal (I : set P) := ⟨I.2, I.3, I.4⟩
/-- The partial ordering by subset inclusion, inherited from `set P`. -/
instance : partial_order (ideal P) := partial_order.lift coe ext
@[trans] lemma mem_of_mem_of_le : x ∈ I → I ≤ J → x ∈ J :=
@set.mem_of_mem_of_subset P x I J
@[simp] lemma principal_le_iff : principal x ≤ I ↔ x ∈ I :=
⟨λ (h : ∀ {y}, y ≤ x → y ∈ I), h (le_refl x),
λ h_mem y (h_le : y ≤ x), I.mem_of_le h_le h_mem⟩
lemma mem_compl_of_ge {x y : P} : x ≤ y → x ∈ (I : set P)ᶜ → y ∈ (I : set P)ᶜ :=
λ h, mt (I.mem_of_le h)
/-- A proper ideal is one that is not the whole set.
Note that the whole set might not be an ideal. -/
@[mk_iff] class is_proper (I : ideal P) : Prop := (ne_univ : (I : set P) ≠ set.univ)
lemma is_proper_of_not_mem {I : ideal P} {p : P} (nmem : p ∉ I) : is_proper I :=
⟨λ hp, begin
change p ∉ ↑I at nmem,
rw hp at nmem,
exact nmem (set.mem_univ p),
end⟩
/-- An ideal is maximal if it is maximal in the collection of proper ideals.
Note that we cannot use the `is_coatom` class because `P` might not have a `top` element.
-/
@[mk_iff] class is_maximal (I : ideal P) extends is_proper I : Prop :=
(maximal_proper : ∀ ⦃J : ideal P⦄, I < J → (J : set P) = set.univ)
variable (P)
/-- A preorder `P` has the `ideal_inter_nonempty` property if the
intersection of any two ideals is nonempty.
Most importantly, a `semilattice_sup` preorder with this property
satisfies that its ideal poset is a lattice.
-/
class ideal_inter_nonempty : Prop :=
(inter_nonempty : ∀ (I J : ideal P), ((I : set P) ∩ (J : set P)).nonempty)
/-- A preorder `P` has the `ideal_Inter_nonempty` property if the
intersection of all ideals is nonempty.
Most importantly, a `semilattice_sup` preorder with this property
satisfies that its ideal poset is a complete lattice.
-/
class ideal_Inter_nonempty : Prop :=
(Inter_nonempty : (⋂ (I : ideal P), (I : set P)).nonempty)
variable {P}
lemma inter_nonempty [ideal_inter_nonempty P] :
∀ (I J : ideal P), ((I : set P) ∩ (J : set P)).nonempty :=
ideal_inter_nonempty.inter_nonempty
lemma Inter_nonempty [ideal_Inter_nonempty P] :
(⋂ (I : ideal P), (I : set P)).nonempty :=
ideal_Inter_nonempty.Inter_nonempty
lemma ideal_Inter_nonempty.exists_all_mem [ideal_Inter_nonempty P] :
∃ a : P, ∀ I : ideal P, a ∈ I :=
begin
change ∃ (a : P), ∀ (I : ideal P), a ∈ (I : set P),
rw ← set.nonempty_Inter,
exact Inter_nonempty,
end
lemma ideal_Inter_nonempty_of_exists_all_mem (h : ∃ a : P, ∀ I : ideal P, a ∈ I) :
ideal_Inter_nonempty P :=
{ Inter_nonempty := by rwa set.nonempty_Inter }
lemma ideal_Inter_nonempty_iff :
ideal_Inter_nonempty P ↔ ∃ a : P, ∀ I : ideal P, a ∈ I :=
⟨λ _, by exactI ideal_Inter_nonempty.exists_all_mem, ideal_Inter_nonempty_of_exists_all_mem⟩
end preorder
section order_bot
variables [preorder P] [order_bot P] {I : ideal P}
/-- A specific witness of `I.nonempty` when `P` has a bottom element. -/
@[simp] lemma bot_mem : ⊥ ∈ I :=
I.mem_of_le bot_le I.nonempty.some_mem
/-- There is a bottom ideal when `P` has a bottom element. -/
instance : order_bot (ideal P) :=
{ bot := principal ⊥,
bot_le := by simp }
@[priority 100]
instance order_bot.ideal_Inter_nonempty : ideal_Inter_nonempty P :=
by { rw ideal_Inter_nonempty_iff, exact ⟨⊥, λ I, bot_mem⟩ }
end order_bot
section order_top
variables [preorder P] [order_top P]
/-- There is a top ideal when `P` has a top element. -/
instance : order_top (ideal P) :=
{ top := principal ⊤,
le_top := λ I x h, le_top }
@[simp] lemma coe_top : ((⊤ : ideal P) : set P) = set.univ :=
set.univ_subset_iff.1 (λ p _, le_top)
lemma top_of_mem_top {I : ideal P} (mem_top : ⊤ ∈ I) : I = ⊤ :=
begin
ext,
change x ∈ I ↔ x ∈ ((⊤ : ideal P) : set P),
split,
{ simp [coe_top] },
{ exact λ _, I.mem_of_le le_top mem_top }
end
lemma is_proper_of_ne_top {I : ideal P} (ne_top : I ≠ ⊤) : is_proper I :=
is_proper_of_not_mem (λ h, ne_top (top_of_mem_top h))
lemma is_proper.ne_top {I : ideal P} (hI : is_proper I) : I ≠ ⊤ :=
begin
intro h,
rw [ext'_iff, coe_top] at h,
apply hI.ne_univ,
assumption,
end
lemma is_proper.top_not_mem {I : ideal P} (hI : is_proper I) : ⊤ ∉ I :=
by { by_contra, exact hI.ne_top (top_of_mem_top h) }
lemma _root_.is_coatom.is_proper {I : ideal P} (hI : is_coatom I) : is_proper I :=
is_proper_of_ne_top hI.1
lemma is_proper_iff_ne_top {I : ideal P} : is_proper I ↔ I ≠ ⊤ :=
⟨λ h, h.ne_top, λ h, is_proper_of_ne_top h⟩
lemma is_maximal.is_coatom {I : ideal P} (h : is_maximal I) : is_coatom I :=
⟨is_maximal.to_is_proper.ne_top,
λ _ _, by { rw [ext'_iff, coe_top], exact is_maximal.maximal_proper ‹_› }⟩
lemma is_maximal.is_coatom' {I : ideal P} [is_maximal I] : is_coatom I :=
is_maximal.is_coatom ‹_›
lemma _root_.is_coatom.is_maximal {I : ideal P} (hI : is_coatom I) : is_maximal I :=
{ maximal_proper := λ _ _, by simp [hI.2 _ ‹_›],
..is_coatom.is_proper ‹_› }
lemma is_maximal_iff_is_coatom {I : ideal P} : is_maximal I ↔ is_coatom I :=
⟨λ h, h.is_coatom, λ h, h.is_maximal⟩
end order_top
section semilattice_sup
variables [semilattice_sup P] {x y : P} {I : ideal P}
/-- A specific witness of `I.directed` when `P` has joins. -/
lemma sup_mem (x y ∈ I) : x ⊔ y ∈ I :=
let ⟨z, h_mem, hx, hy⟩ := I.directed x ‹_› y ‹_› in
I.mem_of_le (sup_le hx hy) h_mem
@[simp] lemma sup_mem_iff : x ⊔ y ∈ I ↔ x ∈ I ∧ y ∈ I :=
⟨λ h, ⟨I.mem_of_le le_sup_left h, I.mem_of_le le_sup_right h⟩,
λ h, sup_mem x y h.left h.right⟩
end semilattice_sup
section semilattice_sup_ideal_inter_nonempty
variables [semilattice_sup P] [ideal_inter_nonempty P] {x : P} {I J K : ideal P}
/-- The intersection of two ideals is an ideal, when it is nonempty and `P` has joins. -/
def inf (I J : ideal P) : ideal P :=
{ carrier := I ∩ J,
nonempty := inter_nonempty I J,
directed := λ x ⟨_, _⟩ y ⟨_, _⟩, ⟨x ⊔ y, ⟨sup_mem x y ‹_› ‹_›, sup_mem x y ‹_› ‹_›⟩, by simp⟩,
mem_of_le := λ x y h ⟨_, _⟩, ⟨mem_of_le I h ‹_›, mem_of_le J h ‹_›⟩ }
/-- There is a smallest ideal containing two ideals, when their intersection is nonempty and
`P` has joins. -/
def sup (I J : ideal P) : ideal P :=
{ carrier := {x | ∃ (i ∈ I) (j ∈ J), x ≤ i ⊔ j},
nonempty := by { cases inter_nonempty I J, exact ⟨w, w, h.1, w, h.2, le_sup_left⟩ },
directed := λ x ⟨xi, _, xj, _, _⟩ y ⟨yi, _, yj, _, _⟩,
⟨x ⊔ y,
⟨xi ⊔ yi, sup_mem xi yi ‹_› ‹_›,
xj ⊔ yj, sup_mem xj yj ‹_› ‹_›,
sup_le
(calc x ≤ xi ⊔ xj : ‹_›
... ≤ (xi ⊔ yi) ⊔ (xj ⊔ yj) : sup_le_sup le_sup_left le_sup_left)
(calc y ≤ yi ⊔ yj : ‹_›
... ≤ (xi ⊔ yi) ⊔ (xj ⊔ yj) : sup_le_sup le_sup_right le_sup_right)⟩,
le_sup_left, le_sup_right⟩,
mem_of_le := λ x y _ ⟨yi, _, yj, _, _⟩, ⟨yi, ‹_›, yj, ‹_›, le_trans ‹x ≤ y› ‹_›⟩ }
lemma sup_le : I ≤ K → J ≤ K → sup I J ≤ K :=
λ hIK hJK x ⟨i, hiI, j, hjJ, hxij⟩,
K.mem_of_le hxij $ sup_mem i j (mem_of_mem_of_le hiI hIK) (mem_of_mem_of_le hjJ hJK)
instance : lattice (ideal P) :=
{ sup := sup,
le_sup_left := λ I J (i ∈ I), by { cases nonempty J, exact ⟨i, ‹_›, w, ‹_›, le_sup_left⟩ },
le_sup_right := λ I J (j ∈ J), by { cases nonempty I, exact ⟨w, ‹_›, j, ‹_›, le_sup_right⟩ },
sup_le := @sup_le _ _ _,
inf := inf,
inf_le_left := λ I J, set.inter_subset_left I J,
inf_le_right := λ I J, set.inter_subset_right I J,
le_inf := λ I J K, set.subset_inter,
.. ideal.partial_order }
@[simp] lemma mem_inf : x ∈ I ⊓ J ↔ x ∈ I ∧ x ∈ J := iff_of_eq rfl
@[simp] lemma mem_sup : x ∈ I ⊔ J ↔ ∃ (i ∈ I) (j ∈ J), x ≤ i ⊔ j := iff_of_eq rfl
lemma lt_sup_principal_of_not_mem (hx : x ∉ I) : I < I ⊔ principal x :=
begin
apply lt_of_le_of_ne le_sup_left,
intro h,
simp at h,
exact hx h
end
end semilattice_sup_ideal_inter_nonempty
section ideal_Inter_nonempty
variables [preorder P] [ideal_Inter_nonempty P]
@[priority 100]
instance ideal_Inter_nonempty.ideal_inter_nonempty : ideal_inter_nonempty P :=
{ inter_nonempty := λ _ _, begin
obtain ⟨a, ha⟩ : ∃ a : P, ∀ I : ideal P, a ∈ I := ideal_Inter_nonempty.exists_all_mem,
exact ⟨a, ha _, ha _⟩
end }
variables {α β γ : Type*} {ι : Sort*}
lemma ideal_Inter_nonempty.all_Inter_nonempty {f : ι → ideal P} :
(⋂ x, (f x : set P)).nonempty :=
begin
obtain ⟨a, ha⟩ : ∃ a : P, ∀ I : ideal P, a ∈ I := ideal_Inter_nonempty.exists_all_mem,
exact ⟨a, by simp [ha]⟩
end
lemma ideal_Inter_nonempty.all_bInter_nonempty {f : α → ideal P} {s : set α} :
(⋂ x ∈ s, (f x : set P)).nonempty :=
begin
obtain ⟨a, ha⟩ : ∃ a : P, ∀ I : ideal P, a ∈ I := ideal_Inter_nonempty.exists_all_mem,
exact ⟨a, by simp [ha]⟩
end
end ideal_Inter_nonempty
section semilattice_sup_ideal_Inter_nonempty
variables [semilattice_sup P] [ideal_Inter_nonempty P] {x : P} {I J K : ideal P}
instance : has_Inf (ideal P) :=
{ Inf := λ s, { carrier := ⋂ (I ∈ s), (I : set P),
nonempty := ideal_Inter_nonempty.all_bInter_nonempty,
directed := λ x hx y hy, ⟨x ⊔ y, ⟨λ S ⟨I, hS⟩,
begin
simp only [←hS, sup_mem_iff, mem_coe, set.mem_Inter],
intro hI,
rw set.mem_bInter_iff at *,
exact ⟨hx _ hI, hy _ hI⟩
end,
le_sup_left, le_sup_right⟩⟩,
mem_of_le := λ x y hxy hy,
begin
rw set.mem_bInter_iff at *,
exact λ I hI, mem_of_le I ‹_› (hy I hI)
end } }
variables {s : set (ideal P)}
@[simp] lemma mem_Inf : x ∈ Inf s ↔ ∀ I ∈ s, x ∈ I :=
by { change x ∈ (⋂ (I ∈ s), (I : set P)) ↔ ∀ I ∈ s, x ∈ I, simp }
@[simp] lemma coe_Inf : ↑(Inf s) = ⋂ (I ∈ s), (I : set P) := rfl
lemma Inf_le (hI : I ∈ s) : Inf s ≤ I :=
λ _ hx, hx I ⟨I, by simp [hI]⟩
lemma le_Inf (h : ∀ J ∈ s, I ≤ J) : I ≤ Inf s :=
λ _ _, by { simp only [mem_coe, coe_Inf, set.mem_Inter], tauto }
lemma is_glb_Inf : is_glb s (Inf s) := ⟨λ _, Inf_le, λ _, le_Inf⟩
instance : complete_lattice (ideal P) :=
{ ..ideal.lattice,
..complete_lattice_of_Inf (ideal P) (λ _, @is_glb_Inf _ _ _ _) }
end semilattice_sup_ideal_Inter_nonempty
section semilattice_inf
variable [semilattice_inf P]
@[priority 100]
instance semilattice_inf.ideal_inter_nonempty : ideal_inter_nonempty P :=
{ inter_nonempty := λ I J, begin
cases I.nonempty with i _,
cases J.nonempty with j _,
exact ⟨i ⊓ j, I.mem_of_le inf_le_left ‹_›, J.mem_of_le inf_le_right ‹_›⟩
end }
end semilattice_inf
section distrib_lattice
variables [distrib_lattice P]
variables {I J : ideal P}
lemma eq_sup_of_le_sup {x i j: P} (hi : i ∈ I) (hj : j ∈ J) (hx : x ≤ i ⊔ j):
∃ (i' ∈ I) (j' ∈ J), x = i' ⊔ j' :=
begin
refine ⟨x ⊓ i, I.mem_of_le inf_le_right hi, x ⊓ j, J.mem_of_le inf_le_right hj, _⟩,
calc
x = x ⊓ (i ⊔ j) : left_eq_inf.mpr hx
... = (x ⊓ i) ⊔ (x ⊓ j) : inf_sup_left,
end
lemma coe_sup_eq : ↑(I ⊔ J) = {x | ∃ i ∈ I, ∃ j ∈ J, x = i ⊔ j} :=
begin
ext,
rw [mem_coe, mem_sup],
exact ⟨λ ⟨_, _, _, _, _⟩, eq_sup_of_le_sup ‹_› ‹_› ‹_›,
λ ⟨i, _, j, _, _⟩, ⟨i, ‹_›, j, ‹_›, le_of_eq ‹_›⟩⟩
end
end distrib_lattice
section boolean_algebra
variables [boolean_algebra P] {x : P} {I : ideal P}
lemma is_proper.not_mem_of_compl_mem (hI : is_proper I) (hxc : xᶜ ∈ I) : x ∉ I :=
begin
intro hx,
apply hI.top_not_mem,
have ht : x ⊔ xᶜ ∈ I := sup_mem _ _ ‹_› ‹_›,
rwa sup_compl_eq_top at ht,
end
lemma is_proper.not_mem_or_compl_not_mem (hI : is_proper I) : x ∉ I ∨ xᶜ ∉ I :=
have h : xᶜ ∈ I → x ∉ I := hI.not_mem_of_compl_mem, by tauto
end boolean_algebra
end ideal
/-- For a preorder `P`, `cofinal P` is the type of subsets of `P`
containing arbitrarily large elements. They are the dense sets in
the topology whose open sets are terminal segments. -/
structure cofinal (P) [preorder P] :=
(carrier : set P)
(mem_gt : ∀ x : P, ∃ y ∈ carrier, x ≤ y)
namespace cofinal
variables [preorder P]
instance : inhabited (cofinal P) :=
⟨{ carrier := set.univ, mem_gt := λ x, ⟨x, trivial, le_refl _⟩ }⟩
instance : has_mem P (cofinal P) := ⟨λ x D, x ∈ D.carrier⟩
variables (D : cofinal P) (x : P)
/-- A (noncomputable) element of a cofinal set lying above a given element. -/
noncomputable def above : P := classical.some $ D.mem_gt x
lemma above_mem : D.above x ∈ D :=
exists.elim (classical.some_spec $ D.mem_gt x) $ λ a _, a
lemma le_above : x ≤ D.above x :=
exists.elim (classical.some_spec $ D.mem_gt x) $ λ _ b, b
end cofinal
section ideal_of_cofinals
variables [preorder P] (p : P) {ι : Type*} [encodable ι] (𝒟 : ι → cofinal P)
/-- Given a starting point, and a countable family of cofinal sets,
this is an increasing sequence that intersects each cofinal set. -/
noncomputable def sequence_of_cofinals : ℕ → P
| 0 := p
| (n+1) := match encodable.decode ι n with
| none := sequence_of_cofinals n
| some i := (𝒟 i).above (sequence_of_cofinals n)
end
lemma sequence_of_cofinals.monotone : monotone (sequence_of_cofinals p 𝒟) :=
by { apply monotone_nat_of_le_succ, intros n, dunfold sequence_of_cofinals,
cases encodable.decode ι n, { refl }, { apply cofinal.le_above }, }
lemma sequence_of_cofinals.encode_mem (i : ι) :
sequence_of_cofinals p 𝒟 (encodable.encode i + 1) ∈ 𝒟 i :=
by { dunfold sequence_of_cofinals, rw encodable.encodek, apply cofinal.above_mem, }
/-- Given an element `p : P` and a family `𝒟` of cofinal subsets of a preorder `P`,
indexed by a countable type, `ideal_of_cofinals p 𝒟` is an ideal in `P` which
- contains `p`, according to `mem_ideal_of_cofinals p 𝒟`, and
- intersects every set in `𝒟`, according to `cofinal_meets_ideal_of_cofinals p 𝒟`.
This proves the Rasiowa–Sikorski lemma. -/
def ideal_of_cofinals : ideal P :=
{ carrier := { x : P | ∃ n, x ≤ sequence_of_cofinals p 𝒟 n },
nonempty := ⟨p, 0, le_refl _⟩,
directed := λ x ⟨n, hn⟩ y ⟨m, hm⟩,
⟨_, ⟨max n m, le_refl _⟩,
le_trans hn $ sequence_of_cofinals.monotone p 𝒟 (le_max_left _ _),
le_trans hm $ sequence_of_cofinals.monotone p 𝒟 (le_max_right _ _) ⟩,
mem_of_le := λ x y hxy ⟨n, hn⟩, ⟨n, le_trans hxy hn⟩, }
lemma mem_ideal_of_cofinals : p ∈ ideal_of_cofinals p 𝒟 := ⟨0, le_refl _⟩
/-- `ideal_of_cofinals p 𝒟` is `𝒟`-generic. -/
lemma cofinal_meets_ideal_of_cofinals (i : ι) : ∃ x : P, x ∈ 𝒟 i ∧ x ∈ ideal_of_cofinals p 𝒟 :=
⟨_, sequence_of_cofinals.encode_mem p 𝒟 i, _, le_refl _⟩
end ideal_of_cofinals
end order
|
Inductive pos : Set :=
| S1 : pos
| S : pos -> pos.
Fixpoint plus(n m:pos) : pos :=
match n with
| S1 => S m
| S l => S (plus l m)
end.
Infix "+" := plus.
Lemma succ_equal : forall n m : pos, (n = m) -> (S n = S m).
Proof.
intros.
induction n.
rewrite <- H.
auto.
rewrite H.
auto.
Qed.
Theorem plus_assoc : forall n m p, n + (m + p) = (n + m) + p.
Proof.
intros.
induction n.
simpl.
auto.
simpl.
apply succ_equal.
auto.
Qed. |
[STATEMENT]
lemma and_and_mask_simple:
"y AND mask n = mask n \<Longrightarrow> (x AND y) AND mask n = x AND mask n"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. y AND mask n = mask n \<Longrightarrow> (x AND y) AND mask n = x AND mask n
[PROOF STEP]
by (simp add: ac_simps) |
Formal statement is: lemma vector_eq_ldot: "(\<forall>x. x \<bullet> y = x \<bullet> z) \<longleftrightarrow> y = z" Informal statement is: Two vectors are equal if and only if they have the same dot product with every vector. |
(* This program is free software; you can redistribute it and/or *)
(* modify it under the terms of the GNU Lesser General Public License *)
(* as published by the Free Software Foundation; either version 2.1 *)
(* 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 Lesser General Public *)
(* License along with this program; if not, write to the Free *)
(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)
(* 02110-1301 USA *)
Require Import List.
Require Term.
Unset Standard Proposition Elimination Names.
(** A substitution is a list of term plus a shift to apply to remaining
variables. The encoding is close to Joachimski, but uses normal lists
*)
Record substitution : Set :=
mk_sub { support :> list Term.term ; shift : nat }.
Notation " l # n " := (mk_sub l n) (at level 20).
Require Export Term.
Definition sublift (rs:substitution) :=
([0] :: map (up 0) rs)#(S rs.(shift)).
Hint Unfold sublift.
Fixpoint sub (r:term)(rs:substitution) {struct r} : term :=
match r with
| [k] => nth k rs [k-length rs+rs.(shift)]
| r;s => (sub r rs);(sub s rs)
| \rho,r => \rho, sub r (sublift rs)
end.
(** The main intended use is for beta reduction:
substitution of size 1 and shift 0. Example: *)
Definition sub1 (r:term) := (r::nil)#0.
Coercion sub1 : term >-> substitution.
Eval compute in (sub (\Iota, (([0];[1]);[2];[3])) [7]).
(** The identity substitution *)
Definition id (k:nat) : substitution := (map Var (seq 0 k)) # k.
Ltac map_map_S :=
rewrite map_map; simpl; rewrite <- map_map with (f:=S); try rewrite seq_shift.
Lemma map_up : forall l, map (up 0) (map Var l) = map Var (map S l).
Proof.
intros; map_map_S; auto.
Qed.
Lemma sublift_id : forall k, sublift (id k) = id (S k).
Proof.
intros; unfold sublift; simpl; rewrite map_up; rewrite seq_shift; auto.
Qed.
Lemma sublift_id_s : forall k s, sublift (((id k)++s::nil)#k) =
(id (S k)++(up 0 s))#(S k).
Proof.
intros; unfold sublift,id; simpl.
rewrite map_app; map_map_S; auto.
Qed.
Lemma sub_id : forall r k, sub r (id k) = r.
Proof.
induction r; intros; simpl.
destruct (le_lt_dec k n).
rewrite nth_overflow; simpl_list; auto; tomega.
simp; rewrite seq_nth; auto.
simpl; rewrite IHr1; rewrite IHr2;auto.
rewrite sublift_id; rewrite IHr; auto.
Qed.
(** sub and occurs *)
Lemma sub_occurs :
forall r (rs:substitution) k, shift rs <= length rs ->
occurs (k + length rs - rs.(shift)) r = false ->
existsb (occurs k) rs = false ->
occurs k (sub r rs) = false.
Proof.
induction r; intros.
simpl.
destruct (le_lt_dec (length rs) n).
rewrite nth_overflow; auto.
simpl; destruct (eq_nat_dec (n - length rs + shift rs) k); auto.
simpl in H0; destruct (eq_nat_dec n (k + length rs - shift rs)); auto.
impossible.
rewrite existsb_nth; auto.
simpl in H0; auto.
destruct (orb_false_elim _ _ H0); clear H0.
simpl; rewrite (IHr1 rs k); auto.
rewrite (IHr2 rs k); auto.
simpl.
apply IHr.
simp; auto with arith.
rewrite <- H0; simpl; simpl_list; f_equal; omega.
simpl.
generalize H1.
clear H1 H0 H IHr r t.
induction (rs.(support)); simpl; auto.
rewrite lift_up.
intros.
destruct (orb_false_elim _ _ H1); clear H1; auto with bool.
rewrite IHl; auto.
replace (S k) with (1+k); auto.
rewrite lift_occurs; auto with arith bool.
Qed.
(* begin hide *)
Ltac decide_nth3 :=
match goal with |- context [nth ?n (?l++?s::nil) ?d] =>
let tmp := fresh in
(destruct (lt_eq_lt_dec (length l) n) as [[tmp|tmp]|tmp];
generalize tmp; clear tmp; simp;
[ impossible || (intro tmp; rewrite nth_overflow;[idtac|simp; try omega])
| impossible || (intro tmp; rewrite app_nth2; [idtac|simp; try omega])
| impossible || (intro tmp; rewrite app_nth1; [idtac|simp; try omega];
simp; try (rewrite seq_nth; [idtac|simp; try omega]))])
end.
(* end hide *)
Lemma sub_occurs2 : forall r l k n, k < l -> k < n ->
occurs k r = occurs k (sub r ((id l ++ [n]::nil) # l)).
Proof.
induction r; simpl; auto.
intros; simpl.
replace ([n0]::nil) with (map Var ((n0)::nil)); auto.
rewrite <- map_app.
simp; auto; [generalize n1;clear n1|generalize e; clear e];
decide_nth3; subst;simp; try impossible.
intros; simpl in *; rewrite <- IHr1; auto; rewrite <- IHr2; auto.
intros.
rewriteconv sublift_id_s; simpl.
generalize (IHr (S l) (S k) (S n)); simpl; auto with arith.
Qed.
Lemma subk_occurs_gen : forall r l k,
occurs (S l+k) r = false ->
occurs l r = occurs (l+k) (sub r (((id l)++[l+k]::nil)#l)).
Proof.
induction r; simpl; intros.
replace ([l+k]::nil) with (map Var ((l+k)::nil)); auto.
rewrite <- map_app.
simpl_list; simpl.
simp; auto; [generalize n0 | generalize e]; subst;
decide_nth3; simp; impossible.
simpl in *.
destruct (orb_false_elim _ _ H); clear H.
rewrite <- IHr1; auto; rewrite <- IHr2; auto.
rewriteconv sublift_id_s; simpl.
rewrite (IHr (S l) k); simpl; auto.
Qed.
Lemma subk_occurs : forall r k,
occurs (S k) r = false ->
occurs 0 r = occurs k (sub r k).
Proof.
exact (fun r => subk_occurs_gen r 0).
Qed.
(** Down corresponds to a dummy substitution *)
Lemma down_sub : forall r l s, occurs l r = false ->
down l r = sub r (((id l)++s::nil)#l).
Proof.
induction r; simpl; intros.
simp; try discriminate; decide_nth3; tomega.
destruct (orb_false_elim _ _ H).
rewrite IHr1 with l s; auto; rewrite IHr2 with l s; auto.
rewriteconv sublift_id_s.
rewrite (IHr (S l) (up 0 s)); auto.
Qed.
(** Swapping 0 and k *)
Definition swap0 (k:nat) : substitution :=
((map (up 0) (id k) ++ [0]::nil)# S (S k)).
Definition sub_swap0 (r:term)(k:nat) := sub r (swap0 k).
|
theory T70
imports Main
begin
lemma "(
(\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) &
(\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) &
(\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) &
(\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) &
(\<forall> x::nat. invo(invo(x)) = x)
) \<longrightarrow>
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z)))
"
nitpick[card nat=4,timeout=86400]
oops
end |
module Sing
%default total
data Fing : Type -> Type where
StringFing : String -> Fing String
BoolFing : Bool -> Fing Bool
stringFing : Fing String -> String
stringFing (StringFing s) = s
boolFing : Fing Bool -> Bool
boolFing (BoolFing b) = b
|
.chr_lengths = import('./chr_lengths')$chr_lengths
#' Read a BAM or BED file to read_bam object
#'
#' @param fname A character vector of file name(s) of BAM files
#' @param ... Arguments passed to AneuFinder
read_bam = function(fname, ...) {
UseMethod("read_bam")
}
read_bam.list = function(fnames, ...) {
lapply(fnames, read_bam, ...)
}
read_bam.character = function(fname, ..., assembly=NULL) {
bai = paste0(fname, ".bai")
# There is no real reason we should have to sort a bam in order to read
# the reads into a GRanges object. However, the GenomicAlignments::readGAlignments
# function needs it, so let's sort/index until we find a better option.
if (!file.exists(bai)) {
message("[read_bam] creating index file")
idx = try(Rsamtools::indexBam(fname))
if (class(idx) == "try-error") {
tmp = file.path(tempdir(), basename(fname))
message("[read_bam] indexing failed, creating temporary sorted bam")
Rsamtools::sortBam(fname, tools::file_path_sans_ext(tmp))
on.exit(unlink(tmp))
}
Rsamtools::indexBam(tmp)
fname = tmp
bai = paste0(fname, ".bai")
}
if (!is.null(assembly)) {
ff = .chr_lengths(Rsamtools::BamFile(fname))
fa = .chr_lengths(assembly)
cmp = merge(data.frame(chr=names(ff), file=unname(ff)),
data.frame(chr=names(fa), assembly=unname(fa)),
by="chr")
if (!all(cmp$file == cmp$assembly, na.rm=TRUE)) {
print(cmp)
stop("Assembly length mismatch")
}
}
AneuFinder::bam2GRanges(fname, bai, ...)
}
read_bam.default = function(fname, ...) {
stop("Do not know how to handle argument of class: ", sQuote(class(fname)))
}
|
[STATEMENT]
lemma eqButUID_trans[trans]:
assumes "eqButUID s s1" and "eqButUID s1 s2" shows "eqButUID s s2"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. eqButUID s s2
[PROOF STEP]
using assms eqButUIDf_trans
[PROOF STATE]
proof (prove)
using this:
eqButUID s s1
eqButUID s1 s2
\<lbrakk>eqButUIDf ?frds ?frds1.0; eqButUIDf ?frds1.0 ?frds2.0\<rbrakk> \<Longrightarrow> eqButUIDf ?frds ?frds2.0
goal (1 subgoal):
1. eqButUID s s2
[PROOF STEP]
unfolding eqButUID_def
[PROOF STATE]
proof (prove)
using this:
admin s = admin s1 \<and> pendingUReqs s = pendingUReqs s1 \<and> userReq s = userReq s1 \<and> userIDs s = userIDs s1 \<and> user s = user s1 \<and> pass s = pass s1 \<and> pendingFReqs s = pendingFReqs s1 \<and> friendReq s = friendReq s1 \<and> friendIDs s = friendIDs s1 \<and> postIDs s = postIDs s1 \<and> admin s = admin s1 \<and> post s = post s1 \<and> vis s = vis s1 \<and> owner s = owner s1 \<and> pendingSApiReqs s = pendingSApiReqs s1 \<and> sApiReq s = sApiReq s1 \<and> serverApiIDs s = serverApiIDs s1 \<and> serverPass s = serverPass s1 \<and> outerPostIDs s = outerPostIDs s1 \<and> outerPost s = outerPost s1 \<and> outerVis s = outerVis s1 \<and> outerOwner s = outerOwner s1 \<and> eqButUIDf (sentOuterFriendIDs s) (sentOuterFriendIDs s1) \<and> recvOuterFriendIDs s = recvOuterFriendIDs s1 \<and> pendingCApiReqs s = pendingCApiReqs s1 \<and> cApiReq s = cApiReq s1 \<and> clientApiIDs s = clientApiIDs s1 \<and> clientPass s = clientPass s1 \<and> sharedWith s = sharedWith s1
admin s1 = admin s2 \<and> pendingUReqs s1 = pendingUReqs s2 \<and> userReq s1 = userReq s2 \<and> userIDs s1 = userIDs s2 \<and> user s1 = user s2 \<and> pass s1 = pass s2 \<and> pendingFReqs s1 = pendingFReqs s2 \<and> friendReq s1 = friendReq s2 \<and> friendIDs s1 = friendIDs s2 \<and> postIDs s1 = postIDs s2 \<and> admin s1 = admin s2 \<and> post s1 = post s2 \<and> vis s1 = vis s2 \<and> owner s1 = owner s2 \<and> pendingSApiReqs s1 = pendingSApiReqs s2 \<and> sApiReq s1 = sApiReq s2 \<and> serverApiIDs s1 = serverApiIDs s2 \<and> serverPass s1 = serverPass s2 \<and> outerPostIDs s1 = outerPostIDs s2 \<and> outerPost s1 = outerPost s2 \<and> outerVis s1 = outerVis s2 \<and> outerOwner s1 = outerOwner s2 \<and> eqButUIDf (sentOuterFriendIDs s1) (sentOuterFriendIDs s2) \<and> recvOuterFriendIDs s1 = recvOuterFriendIDs s2 \<and> pendingCApiReqs s1 = pendingCApiReqs s2 \<and> cApiReq s1 = cApiReq s2 \<and> clientApiIDs s1 = clientApiIDs s2 \<and> clientPass s1 = clientPass s2 \<and> sharedWith s1 = sharedWith s2
\<lbrakk>eqButUIDf ?frds ?frds1.0; eqButUIDf ?frds1.0 ?frds2.0\<rbrakk> \<Longrightarrow> eqButUIDf ?frds ?frds2.0
goal (1 subgoal):
1. admin s = admin s2 \<and> pendingUReqs s = pendingUReqs s2 \<and> userReq s = userReq s2 \<and> userIDs s = userIDs s2 \<and> user s = user s2 \<and> pass s = pass s2 \<and> pendingFReqs s = pendingFReqs s2 \<and> friendReq s = friendReq s2 \<and> friendIDs s = friendIDs s2 \<and> postIDs s = postIDs s2 \<and> admin s = admin s2 \<and> post s = post s2 \<and> vis s = vis s2 \<and> owner s = owner s2 \<and> pendingSApiReqs s = pendingSApiReqs s2 \<and> sApiReq s = sApiReq s2 \<and> serverApiIDs s = serverApiIDs s2 \<and> serverPass s = serverPass s2 \<and> outerPostIDs s = outerPostIDs s2 \<and> outerPost s = outerPost s2 \<and> outerVis s = outerVis s2 \<and> outerOwner s = outerOwner s2 \<and> eqButUIDf (sentOuterFriendIDs s) (sentOuterFriendIDs s2) \<and> recvOuterFriendIDs s = recvOuterFriendIDs s2 \<and> pendingCApiReqs s = pendingCApiReqs s2 \<and> cApiReq s = cApiReq s2 \<and> clientApiIDs s = clientApiIDs s2 \<and> clientPass s = clientPass s2 \<and> sharedWith s = sharedWith s2
[PROOF STEP]
by metis |
Require Import Arith.
Require Import List.
Require Import FunInd.
(* obliczenie nie zostawia "sladu" w dowodzie *)
Fact triv :
forall n, 0 + n = n.
Proof.
intro n.
rewrite plus_O_n.
reflexivity.
Qed.
Print triv.
Fact triv' :
forall n, 0 + n = n.
Proof.
intro n.
reflexivity.
Qed.
Print triv'.
Inductive even : nat -> Prop :=
| evenO : even O
| evenSS : forall n, even n -> even (S (S n)).
Hint Constructors even.
Lemma even1046: even 1046.
Time repeat constructor.
Qed.
Print even1046.
(* dowod przez refleksje - slaba specyfikacja *)
Function check_even (n:nat) : bool :=
match n with
| O => true
| 1 => false
| S (S n0) => check_even n0
end.
Lemma check_even_correct :
forall n, check_even n = true -> even n.
Proof.
intro n.
functional induction (check_even n); intros; auto. discriminate.
Qed.
Ltac prove_even n :=
exact (check_even_correct n (refl_equal true)).
Lemma even4000 :
even 4000.
Proof.
(*Time repeat constructor.*)
Time prove_even 4000.
(* wystarczy sprawdzic, czy check_even 4000 = true *)
Qed.
Print even4000.
Lemma false_even1247 :
even 1247.
Proof.
(*prove_even 1247.*)
Abort.
(* silna specyfikacja *)
Inductive option (P:Prop) : Set :=
| proof : P -> option P
| noproof : option P.
Definition get_form {P} (x: option P) : Prop :=
match x with
| proof _ p => P
| noproof _ => True
end.
Definition get_proof {P} (x: option P) : get_form x :=
match x with
| proof _ p => p
| noproof _ => I
end.
Eval compute in get_form (proof _ (refl_equal 0)).
Eval compute in get_proof (proof _ (refl_equal 0)).
Eval compute in get_form (noproof (0=0)).
Notation " x <- a1 ; a2 " :=
(match a1 with
| proof _ x => a2
| noproof _ => _
end) (at level 60).
Notation " [ x ] " := (proof _ x).
Notation " ! " := (@noproof _).
Definition check_even' : forall (n:nat), option (even n).
refine (fix check n : option (even n) :=
match n with
| 0 => [evenO]
| 1 => !
| S (S n0) =>
p <- check n0; [evenSS _ p]
end).
destruct (check n0); [repeat constructor | constructor 2]; trivial.
Defined.
Eval compute in (check_even' 32).
Eval compute in (check_even' 33).
Eval compute in (get_proof (check_even' 32)).
Eval compute in (get_form (check_even' 32)).
Eval compute in (get_proof (check_even' 33)).
Ltac prove_even_strong :=
match goal with
| [ |- even ?n ] => exact (get_proof (check_even' n))
end.
Lemma strong_even4000 :
even 4000.
Proof.
Time prove_even_strong.
Time Defined.
Print strong_even4000.
(*Eval compute in strong_even4000.*)
Lemma even17 :
even 17.
Proof.
(*prove_even_strong.*)
Abort.
Require Import Bool.
Print reflect.
Check reflect (even 2) (check_even 2).
Lemma even_reflect :
forall n, reflect (even n) (check_even n).
Proof.
intro n.
Check iff_reflect.
apply iff_reflect.
split.
- induction 1; auto.
- apply check_even_correct.
Qed.
Lemma even1046_reflect :
even 1046.
Proof.
assert (hh:=even_reflect 1046).
inversion hh.
trivial.
Time Qed.
Print even1046_reflect.
|
I agree with many of your points and am curious what you think the better combination is. Another question may be why would McDonalds/Coinstar want to sell?
Here is one potential buyer: PayPal/Ebay. The purpose would be to showcase mobile payments.
You have this backwards.. Redbox should buy blockbuster.. convert all those Blockbuster retail outlets into Redbox lounges by installing like 10 networked Redbox kiosks inside each to keep offering the full blockbuster selection and just doing away with the staff.. put in a sofa and a widescreen so folks could watch trailers at their leisure….. then in phase 2.. Redbox sells off all that commerial real estate wtih one requirement.. Redbox can maintain at least one kiosk at that site forever..
Look at you’ll….Your wanting to take away more jobs from Americans and give more to the already rich corporations! you people make me sick!
Don’t make a deal with the devil, Redbox.
Well, I just started using Redbox a few weeks ago after seeing it in Wal-Mart and hearing friends sing its praises for over a month. I decided to give it a try – and I love it! Now I’ve got more friends started using it too!
See, I used to work for Blockbuster and it was during that transitional time when they got rid of “late fees” and started Blockbuster Online and all that. I remember the first day I had to sort out all the returned-by-mail movies and get new ones ready to be shipped out. Blockbuster has definitely TRIED to keep up with progress. I’ve even had their “Rewards” program for the last 2 years and got more than my share of free movies every month (without buying anything more than the $10 Rewards card – I learned a few tricks of the trade).
But with all that, I can just say that Blockbuster is going down. Their prices are sky high. Their selection is still the best (for non-online vendors), but you can buy an old movie off eBay for the same price you’d rent one there.
I agree with what someone else said, Blockbuster shouldn’t be able to afford Redbox. Redbox is just so much better. If Blockbuster DID manage to buy Redbox, they’d probably jack up the rental prices.
The idea of Redbox buying Blockbuster and converting all the Blockbuster stores into Redbox lounges really isn’t a bad idea. That’s the only thing Redbox lacks – a decent selection of older titles. For probably a small rental price (or more crowding of current locations), they can have specialized Redbox kiosks, like “Classics” (meaning all good older movies, not just movies from the 50s), “Sci-Fi”, “Action”, whatever. They still wouldn’t have to pay employees (beyond the basics), but they’d be able to further eat into Blockbuster’s customer base that way and gain more loyalty from their own customer base.
The lounge idea sounds great. You still could have the lounge managed by and employee or two (one during slow times, two at peak). They could be Movie Experts or something along the lines of the Genius from the Apple Store. Besides monitoring the kiosks, they could be there to suggest films. They also could sell the extras like sodas, candy, chips, etc.
The idea of having kiosks for new releases, comedies, classics, dramas, indies, foreign, documentaries, etc. is great. But, another great thing would be game kiosks (360, PS3, and Wii).
I also think that you could do a unlimited package with kiosks, where rather than pay $1/day, you simply pay the monthly fee.
One other possibilty (and McDonald’s wouldn’t like it) would be for Blockbuster to sell dinner to go (pizzas — perhaps just take n bake) inside their stores, with the kiosks in what normally would be the dining area.
Regardless, I think Blockbuster ultimately be forced to change the direction with its B&M stores. This would be one way to change their footprint.
Redbox doesn’t need blockbuster to grow their business. Their kiosks are better business model than any traditional video store. What Readbox needs is securing strategic locations where traffic is stopping, like airports, hospitals, gas stations, places outside all the hotels and motels, any places where there are people waiting for unrelated services and having time to kill.
NO, NO, NO…it would be a tragedy to sell, in my opinion. I agree with Mikey above…we like you just the way you are!
nooooooooooooooo REDBOX it’s just fine the way it is, i try blockbuster before and i didn’t like it at all, in the other hand i love redbox and would not change it for nothing!!! Redbox is just so much better.
Please listen up folks…………NO! No Way! No Way in Hell !!! Should Redbox sell………………..just keep improving what you already have to offer and forget Blockbuster, unless Redbox has a desire to purchase Blockbuster/Netflex to enlarge Redbox’s service/business. For now we love you Redbox just the way you are……..
I say keep the red box and keep teaming up with grocery stores, McDonalds, and wal-mart to house them….not block busters.
The only contract I would take out with blockbusters, if I were red box, would be one to house and possibly fill the machines…I wouldn’t let blockbuster buy them, but you could team up under contract for blockbuster staff to fill them and even have one at blockbusters for customer convenience, then give blockbusters a kickback on % of sales….
NO Blockbuster shouldn’t touch Red Box. Maybe Red Box could do online renting of older movies and keep the Red Box ease of use for the newer movies.
If a big company like them gets hold of this it may morph into something UGLY.
Blockbuster won’t buy redbox, they’re currently offering $1 billion for circuit city.
Leave Redbox alone; it works great. Why turn something good over to a company that is doing so poorly?
leave the redbox alone. blockbuster will raise the prices.
I don’t think it will be a reality because from what I underestand, Redbox pretty much breaks even on the video rental end. Their main income comes from leasing the kiosks to retail stores, who uses them as traffic generators. McDonald’s gets two visits for each rental transaction — one to rent the movie, another to return it. That’s TWO chances to sell you a Coke, Coffee, or even bring home dinner.
Someone suggested putting Redbox’s in airports, hotels, etc. That wouldn’t fit their busiess model, as you are already going to be at the airport anyway — having a Redbox there doesn’t lure you to the airport vs. the train station or driving your own vehicle.
Second, having a rental lounge staffed with employees would not work – employees could dispense videos from racks much more inexpensively than costly machines, so you’re back to a plain ol’ retail locaction.
McDonald’s would be very unlikely–at least while there are Redbox’s inside of McDonald’s stores–to allow them to sell drinks, chips, etc, as that would compete with their food business, and if you still had the ability to rent/return anywhere, McDs would be losing traffic generation benefits, while redbox would be competing with them in food sales. McDonald’s at one time saw retailers that sold microwave ovens as competitors, as it was a means for people to get hot food fast, vs. running down the street to the golden arches.
Don’t forget, that most of Redbox’s founders are former McDonald’s executives — While they owe no allegience to McDonald’s, there are undoubtedly many unwritten agreements that exist. Don’t forget that McDonald’s is MUCH larger a corporation than Redbox — they could crush Redbox if they wanted to. This is a company who has been known to buy real estate and open a location and sell dime hamburgers across the street from a licencee that had fallen from favor.
I think that Blockbuster is a dinosaur. As such, it should go the way of dinosaurs. Part of my feeling stems from Blockbuster’s unfriendly treatment of Director’s in the way it arbitrarily edited movies without consent. But also it charges way too much for rentals when there are so many better options such as Redbox and Netflix.
Now Blockbuster wants to buy Circuit City and Redbox? I think Redbox can do better and so can Circuit City. Perhaps they should get together and buy Blockbuster?
if it ain’t broke, don’t fix it! i’m very pleased with red box. there are enough movies and the price is right. if blockbuster puts there fingers in the pie; forget about the price and convenience. no to blockbuster!
the idea of having 2 redbox at a location is great.
i would like to see more old clasics..gone with the wind,humphry bogart,jimmy cagney the 30 and 40 movies like tntetc.
I actually think combining an electronics retailer and Circuit City might not be a bad move. Circuit City is in serious need of restructuring, as it really can’t compete with Best Buy.
I really don’t think BBI will try and ruin the convenience of Redbox. Several years ago, BBI purchased an online DVD store based in Phoenix. They actually improved on that company’s offering and came up with a viable competitor to Netflix.
At this point, BBI could buy DVDPlay, The New Release, or any of the other kiosk businesses OR buy Redbox OR start their own.
By getting into home electronics, Blockbuster can cross market DVD/Blu-Ray players for DVD rentals, consoles for game rentals, its STB for Movielink, portable players for Movielink, and televisions to bring it all together. It could put Blockbuster video stores directly into existing Circuit City stores — which would put it a step ahead of Best Buy. Or, it could put Blockbuster-branded kiosks into Circuit City. The Blockbuster stores could tap Circuit City’s inventory for its own stores. The possibilities are limitless.
Oh, and a rental from BBI is cheaper than a rental from Comcast OnDemand … by about 50 cents. Plus, I get 9 (2+7) to 14 days (7+7) to return the movie. Simple as that. Plus, I like to use BBI to acquire hard to find films.
On the surface Redbox is cheaper. $1/night, but I have had my latest rentals since last Tuesday. Guess what? I could have rented the movies for less at Blockbuster.
Guess what? You could have taken them back a lot earlier too…..HELLO!!
NO. i had more trouble with blockbuster and none with you. don’t ruin a good thing. PLEASE!
Please!!!!!!! NO!!!!!!!!!!!!!!!!!!! All they would do is jack the price up. Don’t mess with this great thing!!!!!!!
It would be a shame to mess up a good thing. There are a lot of people on limited budgets and REDBOX has been a welcome breath of fresh air. To sell to blockbuster would mean the end of a very good thing, because they would raise prices. The old saying “if it ain’t broke don’t fix it” surely applies here.
Please do not sell out to Blockbuster! I’m barely able to make ends meet on a limited income and if it weren’t for Redbox, I wouldn’t be able to rent DVDs at all. With Redbox, I am able to rent a different movie each week for LESS than one single rental from Blockbuster. Four movies for less than the price of one…? It doesn’t take a rocket scientist to figure that out!
As this country moves further into a recession, every penny counts. Redbox is and will be a godsend for those feeling the financial crunch. Blockbuster executives are well aware they may be out of a job once the recession in “full bloom” so trying to corner the market by having a monopoly is in “their” best interest, not the public’s.
Do not sell out to the “big guys”! Keep Redbox the way it was intended: friendly, affordable and fun!
I feel that they are both different places. Blockbuster has tons of copies of a movie while redbox has only one or two. Sometimes it is hard to get a new movie from redbox because they dont have it. I think it should remain the way it is but redbox should put more machines in even more places.
#1: User goes onto Redbox website (or maybe kiosk-based selection) to select a movie they want to watch which isn’t currently in stock.
#2: Redbox checks other semi-local Redbox locations to see if an existing hard copy could be shipped/brought in within a couple days.
Would not want Blockbuster to buy Redbox. Agree with comments they would just jack up prices and mess things up.
Think the ideas of a Redbox lounge with multiple kiosks or a burn on demand machine for non-stocked titles would be good ideas, but both would require big capital outlays for new equipment or buildings and staff. Living in a town with both video stores going bankrupt within a couple of weeks of each other, I really appreciate the RedBox machines to get just the movies I want when I want them for a minimal rental charge or sometimes for free with a discount code.
No buying of redbox by blockbusters. The media mass monopoly of buying and taking over is getting ridiculously out of hand. One of the viewers is correct in stating that Redbox is friendly affordable and fun. In times of recession this is the only affordable entertainment left.
Blockbuster is a waste. Redbox should never let them buy out. 1st if it’s online renting netflix is better the movies come in about the same time when shipping. however blockbuster is only ships mon-fri netflix is mon- sat. Netflix on the 8 plan i am getting about 16 a week, on blockbuster i was on the 3 unlimited in store plan and still only getting like 5 a week. that’s something else if you have the instore you return it and the next bussiness day they will ship out. That’s not true. On the week end i would have all in and monday 1 would be shipped and tuesday 1 and wednesday 1. sometimes it was friday before they even sent out the one from the weekend. When calling and complianing all they said was sometimes after the weekend we get busy. But a whole week? come on. And if your talking about the in-store deals. On blockbusters unlimited 2 at a time 29.99 there’s one better hollywood video has 3 at a time for 14.99 just not the hot new releases or everything in the store 3 at a time for the same price as blockbuster 29.99. So again blockbuster has been beaten again. with blockbuster i got more cracked dvd in the mail then with netflix and with the store i have gotten more really bad scratched dvd then hollywood video. So in every part of the dvd business blockbuster is a waste of time, there is better and cheaper where ever you look. Even with the instore rewards program which is none like anyone i have found yet, theres still problems. The one free every month you have to have a transaction to get the free one, so buy something. Rent 5 get one well max 2 a month, there’s no trick there. And once you mon, tues, and wed rent one get one, no trick here. each rental costs 4.65 or around that it’s 4.50 plus tax where I go. Ok so if you use your 10 rentals on mon-wed you get 12 after paying for 5 plus the free one which you get after getting something you will pay 46.25 for 23 dvd’s which is 2.01 per disc. Still not as good as renting from redbox. So it a nutshell STAY AWAY FROM BLOCKBUSTER. There’s someone better no mater what you want to do. |
(*
* Copyright 2014, General Dynamics C4 Systems
*
* SPDX-License-Identifier: GPL-2.0-only
*)
(*
CSpace invariants
*)
theory ArchCSpaceInv_AI
imports CSpaceInv_AI
begin
context Arch begin global_naming AARCH64
definition
safe_ioport_insert :: "cap \<Rightarrow> cap \<Rightarrow> 'a::state_ext state \<Rightarrow> bool"
where
"safe_ioport_insert newcap oldcap \<equiv> \<lambda>_. True"
lemma safe_ioport_insert_triv:
"\<not>is_arch_cap newcap \<Longrightarrow> safe_ioport_insert newcap oldcap s"
by (clarsimp simp: safe_ioport_insert_def)
lemma set_cap_ioports':
"\<lbrace>\<lambda>s. valid_ioports s \<and> cte_wp_at (\<lambda>cap'. safe_ioport_insert cap cap' s) ptr s\<rbrace>
set_cap cap ptr
\<lbrace>\<lambda>rv. valid_ioports\<rbrace>"
by wpsimp
lemma replace_cap_invs:
"\<lbrace>\<lambda>s. invs s \<and> cte_wp_at (replaceable s p cap) p s
\<and> cap \<noteq> cap.NullCap
\<and> ex_cte_cap_wp_to (appropriate_cte_cap cap) p s
\<and> s \<turnstile> cap\<rbrace>
set_cap cap p
\<lbrace>\<lambda>rv s. invs s\<rbrace>"
apply (simp add: invs_def valid_state_def valid_mdb_def2 valid_arch_mdb_def)
apply (rule hoare_pre)
apply (wp replace_cap_valid_pspace
set_cap_caps_of_state2 set_cap_idle
replace_cap_ifunsafe valid_irq_node_typ
set_cap_typ_at set_cap_irq_handlers
set_cap_valid_arch_caps
set_cap_cap_refs_respects_device_region_replaceable)
apply (clarsimp simp: valid_pspace_def cte_wp_at_caps_of_state
replaceable_def)
apply (rule conjI)
apply (fastforce simp: tcb_cap_valid_def
dest!: cte_wp_tcb_cap_valid [OF caps_of_state_cteD])
apply (rule conjI)
apply (erule_tac P="\<lambda>cps. mdb_cte_at cps (cdt s)" in rsubst)
apply (rule ext)
apply (safe del: disjE)[1]
apply (simp add: gen_obj_refs_empty final_NullCap)+
apply (rule conjI)
apply (simp add: untyped_mdb_def is_cap_simps)
apply (erule disjE)
apply (clarsimp, rule conjI, clarsimp+)[1]
apply (erule allEI, erule allEI)
apply (drule_tac x="fst p" in spec, drule_tac x="snd p" in spec)
apply (clarsimp simp: gen_obj_refs_subset)
apply (drule(1) disjoint_subset, erule (1) notE)
apply (rule conjI)
apply (erule descendants_inc_minor)
apply simp
apply (elim disjE)
apply clarsimp
apply clarsimp
apply (rule conjI)
apply (erule disjE)
apply (simp add: fun_upd_def[symmetric] fun_upd_idem)
apply (simp add: untyped_inc_def not_is_untyped_no_range)
apply (rule conjI)
apply (erule disjE)
apply (simp add: fun_upd_def[symmetric] fun_upd_idem)
apply (simp add: ut_revocable_def)
apply (rule conjI)
apply (erule disjE)
apply (clarsimp simp: irq_revocable_def)
apply clarsimp
apply (clarsimp simp: irq_revocable_def)
apply (rule conjI)
apply (erule disjE)
apply (simp add: fun_upd_def[symmetric] fun_upd_idem)
apply (simp add: reply_master_revocable_def)
apply (rule conjI)
apply (erule disjE)
apply (simp add: fun_upd_def[symmetric] fun_upd_idem)
apply (clarsimp simp add: reply_mdb_def)
apply (thin_tac "\<forall>a b. (a, b) \<in> cte_refs cp nd \<and> Q a b\<longrightarrow> R a b" for cp nd Q R)
apply (thin_tac "is_pt_cap cap \<longrightarrow> P" for cap P)+
apply (rule conjI)
apply (unfold reply_caps_mdb_def)[1]
apply (erule allEI, erule allEI)
apply (clarsimp split: if_split simp add: is_cap_simps
simp del: split_paired_Ex split_paired_All)
apply (rename_tac ptra ptrb rights')
apply (rule_tac x="(ptra,ptrb)" in exI)
apply fastforce
apply (unfold reply_masters_mdb_def)[1]
apply (erule allEI, erule allEI)
subgoal by (fastforce split: if_split_asm simp: is_cap_simps)
apply (rule conjI)
apply (erule disjE)
apply (clarsimp simp add: is_reply_cap_to_def)
apply (drule caps_of_state_cteD)
apply (subgoal_tac "cte_wp_at (is_reply_cap_to t) p s")
apply (erule(1) valid_reply_capsD [OF has_reply_cap_cte_wpD])
apply (erule cte_wp_at_lift)
apply (fastforce simp add:is_reply_cap_to_def)
apply (simp add: is_cap_simps)
apply (frule(1) valid_global_refsD2)
apply (frule(1) cap_refs_in_kernel_windowD)
apply (rule conjI)
apply (erule disjE)
apply (clarsimp simp: valid_reply_masters_def cte_wp_at_caps_of_state)
apply (cases p, fastforce simp:is_master_reply_cap_to_def)
apply (simp add: is_cap_simps)
apply (elim disjE)
apply simp
apply (clarsimp simp: valid_table_capsD[OF caps_of_state_cteD]
valid_arch_caps_def unique_table_refs_no_cap_asidE)
apply (rule conjI, clarsimp)
apply (rule conjI, rule Ball_emptyI, simp add: gen_obj_refs_subset)
by clarsimp
definition
"is_simple_cap_arch cap \<equiv> \<not>is_pt_cap cap"
lemma is_simple_cap_arch:
"\<not>is_arch_cap cap \<Longrightarrow> is_simple_cap_arch cap"
by (simp add: is_cap_simps is_simple_cap_arch_def)
(* True when cap' is derived from cap. *)
definition
"is_derived_arch cap' cap \<equiv>
(is_pt_cap cap' \<longrightarrow> cap_asid cap = cap_asid cap' \<and> cap_asid cap' \<noteq> None) \<and>
(vs_cap_ref cap = vs_cap_ref cap' \<or> is_frame_cap cap)"
lemma is_derived_arch_non_arch:
"\<lbrakk> \<not> is_arch_cap cap; \<not> is_arch_cap cap' \<rbrakk> \<Longrightarrow> is_derived_arch cap cap'"
unfolding is_derived_arch_def vs_cap_ref_def is_arch_cap_def is_pt_cap_def
by (auto split: cap.splits)
lemmas cap_master_arch_cap_simps = cap_master_arch_cap_def[split_simps arch_cap.split]
lemmas cap_master_cap_def = cap_master_cap_def[simplified cap_master_arch_cap_def]
lemma same_master_cap_same_types:
"cap_master_cap cap = cap_master_cap cap' \<Longrightarrow>
is_pt_cap cap = is_pt_cap cap' \<and>
is_frame_cap cap = is_frame_cap cap' \<and>
is_ap_cap cap = is_ap_cap cap'"
by (clarsimp simp: cap_master_cap_def is_cap_simps split: cap.splits arch_cap.splits)
lemma is_derived_cap_arch_asid_issues:
"\<lbrakk> is_derived_arch cap cap'; cap_master_cap cap = cap_master_cap cap' \<rbrakk>
\<Longrightarrow> (is_pt_cap cap \<longrightarrow> cap_asid cap \<noteq> None) \<and>
(is_frame_cap cap \<or> (vs_cap_ref cap = vs_cap_ref cap'))"
apply (simp add: is_derived_arch_def)
by (auto simp: cap_master_cap_def is_cap_simps cap_asid_def
split: cap.splits arch_cap.splits option.splits)
lemma is_derived_cap_arch_asid:
"\<lbrakk> is_derived_arch cap cap'; cap_master_cap cap = cap_master_cap cap'; is_pt_cap cap' \<rbrakk>
\<Longrightarrow> cap_asid cap = cap_asid cap'"
unfolding is_derived_arch_def
apply (cases cap; cases cap'; simp)
by (auto simp: is_cap_simps cap_master_cap_def split: arch_cap.splits)
definition safe_parent_for_arch :: "cap \<Rightarrow> cap \<Rightarrow> bool" where
"safe_parent_for_arch cap parent \<equiv> False"
lemma safe_parent_for_arch_not_arch:
"\<not>is_arch_cap cap \<Longrightarrow> \<not>safe_parent_for_arch cap p"
by (clarsimp simp: safe_parent_for_arch_def is_cap_simps)
lemma safe_parent_cap_range_arch:
"safe_parent_for_arch cap pcap \<Longrightarrow> cap_range cap \<subseteq> cap_range pcap"
by (clarsimp simp: safe_parent_for_arch_def cap_range_def)
definition
"cap_asid_base_arch cap \<equiv> case cap of
ASIDPoolCap _ asid \<Rightarrow> Some asid
| _ \<Rightarrow> None"
declare cap_asid_base_arch_def[abs_def, simp]
definition cap_asid_base :: "cap \<Rightarrow> asid option" where
"cap_asid_base cap \<equiv> arch_cap_fun_lift cap_asid_base_arch None cap"
lemmas cap_asid_base_simps [simp] =
cap_asid_base_def [simplified, split_simps cap.split arch_cap.split]
definition
"cap_vptr_arch acap \<equiv> case acap of
(FrameCap _ _ _ _ (Some (_, vptr))) \<Rightarrow> Some vptr
| (PageTableCap _ _ (Some (_, vptr))) \<Rightarrow> Some vptr
| _ \<Rightarrow> None"
definition
"cap_vptr cap \<equiv> arch_cap_fun_lift cap_vptr_arch None cap"
declare cap_vptr_arch_def[abs_def, simp]
lemmas cap_vptr_simps [simp] =
cap_vptr_def [simplified, split_simps cap.split arch_cap.split option.split prod.split]
end
context begin interpretation Arch .
requalify_facts replace_cap_invs
end
end
|
filter.independent.variables = function( x, vtype="R0.mass") {
if (vtype %in% c("R0.mass", "R1.no") ) {
if (exists( "t", x)) {
ii = which( x$t > 14 )
if (length(ii) > 0) x$t[ii] = 14
}
if (exists( "tmean", x)) {
ii = which( x$tmean > 10 )
if (length(ii) > 0) x$tmean[ ii ] = 10
}
if (exists( "z", x)) {
ii = which( x$z > log(600) )
if (length(ii) > 0) x$z[ii] = log(600)
ii = which( x$z < log(25) )
if (length(ii) > 0) x$z[ii] = log(25)
}
if (exists( "dZ", x)) {
ii = which( x$dZ < -8 )
if (length(ii) > 0) x$dZ[ii] = -8
ii = which( x$dZ > -2 )
if (length(ii) > 0) x$dZ[ii] = -2
}
if (exists( "tamp", x)) {
ii = which( x$tamp> 12 )
if (length(ii) > 0) x$tamp[ ii ] = 12
}
if (exists( "dt.annual", x)) {
ii = which( x$dt.annual < -3 )
if (length(ii) > 0) x$dt.annual[ ii ] = -3
ii = which( x$dt.annual > 3 )
if (length(ii) > 0) x$dt.annual[ ii ] = 3
}
if (exists( "dt.seasonal", x)) {
ii = which( x$dt.seasonal < -3 )
if (length(ii) > 0) x$dt.seasonal[ii ] = -3
ii = which( x$dt.seasonal > 3 )
if (length(ii) > 0) x$dt.seasonal[ ii ] = 3
}
if (exists( "smr", x)) {
ii = which( x$smr < 0.0045 )
if (length(ii) > 0) x$smr[ ii ] = 0.0045
ii = which( x$smr > 0.0065 )
if (length(ii) > 0) x$smr[ii ] = 0.0065
}
if (exists( "mr", x)) {
ii = which( x$mr < 0 )
if (length(ii) > 0) x$mr[ ii ] = 0
ii = which( x$mr > 50 )
if (length(ii) > 0) x$mr[ ii ] = 50
}
if (exists( "ca1", x)) {
ii = which( x$ca1 < -2.5 )
if (length(ii) > 0) x$ca1[ ii] = -2.5
ii = which( x$ca1 > 2 )
if (length(ii) > 0) x$ca1[ ii ] = 2
}
if (exists( "ca2", x)) {
ii = which( x$ca2 < -2.0 )
if (length(ii) > 0) x$ca2[ ii ] = -2.0
ii = which( x$ca2 > 2.0 )
if (length(ii) > 0) x$ca2[ ii ] = 2.0
}
if (exists( "Npred", x)) {
ii = which( x$Npred > 130 )
if (length(ii) > 0) x$Npred[ ii] = 130
}
if (exists( "Z", x)) {
ii = which( x$Z > 0.41 )
if (length(ii) > 0) x$Z[ ii ] = 0.41
}
}
return (x)
}
|
Formal statement is: lemma continuous_ge_on_closure: fixes a::real assumes f: "continuous_on (closure s) f" and x: "x \<in> closure(s)" and xlo: "\<And>x. x \<in> s ==> f(x) \<ge> a" shows "f(x) \<ge> a" Informal statement is: If $f$ is continuous on the closure of $s$ and $f(x) \geq a$ for all $x \in s$, then $f(x) \geq a$ for all $x \in \overline{s}$. |
/*=============================================================================
Copyright (c) 2016 Paul W. Bible
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef ALLOWED_RELATIONSHIP_XML_GO_PARSER
#define ALLOWED_RELATIONSHIP_XML_GO_PARSER
#include <ggtk/GoParserInterface.hpp>
#include <ggtk/GoEnums.hpp>
#include <ggtk/RelationshipPolicyInterface.hpp>
#include <ggtk/xml/rapidxml_utils.hpp>
#include <ggtk/xml/rapidxml.hpp>
#include <vector>
#include <string>
#include <boost/tokenizer.hpp>
/*! \class AllowedRelationshipXmlGoParser
\brief A class to parse only a specified set of relationships
This class will read a Gene Ontology XML file and add only those relationship
which are specified to the graph. The most important method of this class if the
parseGoFile which takes the file name as a parameter.
Implements GoParserInterface
*/
class AllowedRelationshipXmlGoParser : public GoParserInterface{
public:
//! Method to parse the go file, should be an XML file
/*!
This method will read a Gene Ontology XML file and add only those relationship
which are specified to the graph.
*/
inline GoGraph* parseGoFile(std::string filename){
//graph object to be returned
GoGraph* graph = new GoGraph();
//open xmlfile
rapidxml::file<> xmlFile(filename.c_str());
//initialize document
rapidxml::xml_document<> doc;
doc.parse<0>(xmlFile.data());
//create an xml node
rapidxml::xml_node<> *node;
for(node = doc.first_node("obo")->first_node(); node; node = node->next_sibling()){
//get node name
std::string type = node->name();
//if node is a GO term
if(type == "term"){
std::string term,name,description,ontology;
//vector to hold go accession ids of related terms.
std::vector<std::string> relatedTerms;
std::vector<std::string> relatedTermRelationship;
bool isObsolete = false;
rapidxml::xml_node<> *childNode;
for(childNode = node->first_node(); childNode; childNode = childNode->next_sibling()){
std::string attr = childNode->name();
//attribute specific action
if(attr == "id"){
//go accession id
term = childNode->value();
}else if(attr == "name"){
//go natural language name/title
name = childNode->value();
}else if(attr == "namespace"){
//go ontology, BP,MF,CC
ontology = childNode->value();
}else if(attr == "def"){
//go term definition, long form description
description = childNode->first_node("defstr")->value();
}else if(attr == "is_a"){
//is_a relationship
std::string relatedTerm = childNode->value();
//add related term to vector for adding later
relatedTerms.push_back(relatedTerm);
//add attr as relationship, attr must = "is_a" here
relatedTermRelationship.push_back(attr);
}else if(attr == "is_obsolete"){
//if obsolete set flag.
isObsolete = true;
//early exit from loop
break;
}else if(attr == "relationship"){
//extract relationship
std::string type = childNode->first_node("type")->value();
//extract term to which related
std::string toTerm = childNode->first_node("to")->value();
//add all types of relationships
relatedTerms.push_back(toTerm);
relatedTermRelationship.push_back(type);
}
}//for each attribute node
//if term is obsolete continue, do not add to graph
///////////////////////////////////////////////////////
// Main work, add nodes, add related nodes, add edges
///////////////////////////////////////////////////////
if(!isObsolete){
//add the current term to the graph
graph->insertTerm(term,name,description,ontology);
//loop over all related terms
for(std::size_t i = 0; i < relatedTerms.size(); ++i){
//create a temp variable for readability
std::string relatedTerm = relatedTerms.at(i);
//std::cout << relatedTerm << "\t";
//create a temp variable for readability
std::string relationship = relatedTermRelationship.at(i);
//std::cout << relationship << std::endl;
GO::Relationship relationsihpType = GO::relationshipStringToCode(relationship);
if(!relationshipPolicy->isAllowed(relationsihpType)){continue;}
//insert related terms, there are just stubs to be overwritten later on
graph->insertTerm(relatedTerm,"name","description","ontology");
//insert edge
graph->insertRelationship(term,relatedTerm,relationship);
}//end for, each related term
}
}//end if, is term?
}//end for, for each node in obo, source, header, term
//call to initialize the graph's vertex to index maps
graph->initMaps();
//return the graph pointer
return graph;
}//end method parseGoFile
//! A method to test if a file fits the accepted format
/*!
Returns true if the file matches accepted format, false otherwise
*/
inline bool isFileGood(const std::string &filename){
std::ifstream in(filename.c_str());
if (!in.good()){
return false;
}else{
in.close();
}
std::size_t count = 0;
//open xmlfile
rapidxml::file<> xmlFile(filename.c_str());
//initialize document
rapidxml::xml_document<> doc;
try{
doc.parse<0>(xmlFile.data());
}
catch (rapidxml::parse_error pe){
return false;
}
//create an xml node
rapidxml::xml_node<> *node;
for (node = doc.first_node("obo")->first_node(); node; node = node->next_sibling()){
std::string type = node->name();
if (type == "term"){
count += 1;
if (count == 3){
break;
}
}
}
if (count < 3){
return false;
}else{
return true;
}
}
//! a method to create a new instance of this class for use in a factory
/*!
creats a new pointer to the parser, used by the factory for go parsers.
*/
inline GoParserInterface* clone(){
return new AllowedRelationshipXmlGoParser(relationshipPolicy);
}//end method clone
//! a method to set the policy
/*!
sets the policy of the parser
*/
inline void setPolicy(RelationshipPolicyInterface* policy){
relationshipPolicy = policy;
}//end method setPolicy
//! A parameterized constructor
/*!
constructor that sets the policy
*/
inline AllowedRelationshipXmlGoParser(RelationshipPolicyInterface* policy){
setPolicy(policy);
}//end parameterized constructor, AllowedRelationshipXmlGoParser
private:
//! A RelationshipPolicyInterface
/*! This RelationshipPolicyInterface holds the relationships to be allowed during parsing */
RelationshipPolicyInterface* relationshipPolicy;
};
#endif
|
The function $x \mapsto c x$ is a bounded linear operator on $\mathbb{R}$. |
The function $x \mapsto c x$ is a bounded linear operator on $\mathbb{R}$. |
[STATEMENT]
lemma enum_strict_mono: "i \<le> n \<Longrightarrow> j \<le> n \<Longrightarrow> enum i < enum j \<longleftrightarrow> i < j"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>i \<le> n; j \<le> n\<rbrakk> \<Longrightarrow> (enum i < enum j) = (i < j)
[PROOF STEP]
using enum_mono[of i j] enum_inj[of i j]
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>i \<le> n; j \<le> n\<rbrakk> \<Longrightarrow> (enum i \<le> enum j) = (i \<le> j)
\<lbrakk>i \<le> n; j \<le> n\<rbrakk> \<Longrightarrow> (enum i = enum j) = (i = j)
goal (1 subgoal):
1. \<lbrakk>i \<le> n; j \<le> n\<rbrakk> \<Longrightarrow> (enum i < enum j) = (i < j)
[PROOF STEP]
by (auto simp: le_less) |
The pseudo-division of two polynomials is the same as the pseudo-division of their coefficients. |
lemma mult_nat_left_at_top: "c > 0 \<Longrightarrow> filterlim (\<lambda>x. c * x) at_top sequentially" for c :: nat |
subroutine advect_mom
use vars
use params, only: docolumn
implicit none
integer i,j,k
real du(nx,ny,nz,3)
if(docolumn) return
call t_startf ('advect_mom')
if(dostatis) then
do k=1,nzm
do j=1,ny
do i=1,nx
du(i,j,k,1)=dudt(i,j,k,na)
du(i,j,k,2)=dvdt(i,j,k,na)
du(i,j,k,3)=dwdt(i,j,k,na)
end do
end do
end do
endif
call advect2_mom_xy()
call advect2_mom_z()
if(dostatis) then
do k=1,nzm
do j=1,ny
do i=1,nx
du(i,j,k,1)=dudt(i,j,k,na)-du(i,j,k,1)
du(i,j,k,2)=dvdt(i,j,k,na)-du(i,j,k,2)
du(i,j,k,3)=dwdt(i,j,k,na)-du(i,j,k,3)
end do
end do
end do
call stat_tke(du,tkeleadv)
call stat_mom(du,momleadv)
call setvalue(twleadv,nzm,0.)
call setvalue(qwleadv,nzm,0.)
call stat_sw1(du,twleadv,qwleadv)
endif
call t_stopf ('advect_mom')
end subroutine advect_mom
|
May 26, 2018· Sand Washing Machine Price. sand washing plant india report offers 4142 sand washing machine price products. . SDSY 2FG-24 2017 Hot Sale in India Low Price 50tph Sprial Sand Washing Machine. Quotation More. Washed Sand Prices.
machinery for manufacture of m sand - slapsw.org. machinery for manufacture of m sand. machinery for manufacture of m sand . Find the Right and the Top rock sand making machinery in india for your coal handling plant!
One of the keys to making an aesthetically pleasing aquarium is by choosing the right type of substrate that is used to provide a base for aquarium decoration or live plants, depending on your requirements.
China Sand Making Machine manufacturers – Select 2017 high quality Sand Making Machine products in best price from certified Chinese Sand Machine DBM stone crusher,DBM sand making machine,stone crushing plant,mobile crusher machine. |
/-
Copyright (c) 2019 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import control.monad.basic
import data.fintype.basic
import data.list.prod_sigma
/-!
Type class for finitely enumerable types. The property is stronger
than `fintype` in that it assigns each element a rank in a finite
enumeration.
-/
universes u v
open finset
/-- `fin_enum α` means that `α` is finite and can be enumerated in some order,
i.e. `α` has an explicit bijection with `fin n` for some n. -/
class fin_enum (α : Sort*) :=
(card : ℕ)
(equiv [] : α ≃ fin card)
[dec_eq : decidable_eq α]
attribute [instance, priority 100] fin_enum.dec_eq
namespace fin_enum
variables {α : Type u} {β : α → Type v}
/-- transport a `fin_enum` instance across an equivalence -/
def of_equiv (α) {β} [fin_enum α] (h : β ≃ α) : fin_enum β :=
{ card := card α,
equiv := h.trans (equiv α),
dec_eq := (h.trans (equiv _)).decidable_eq }
/-- create a `fin_enum` instance from an exhaustive list without duplicates -/
def of_nodup_list [decidable_eq α] (xs : list α) (h : ∀ x : α, x ∈ xs) (h' : list.nodup xs) :
fin_enum α :=
{ card := xs.length,
equiv := ⟨λ x, ⟨xs.index_of x,by rw [list.index_of_lt_length]; apply h⟩,
λ ⟨i,h⟩, xs.nth_le _ h,
λ x, by simp [of_nodup_list._match_1],
λ ⟨i,h⟩, by simp [of_nodup_list._match_1,*]; rw list.nth_le_index_of;
apply list.nodup_dedup ⟩ }
/-- create a `fin_enum` instance from an exhaustive list; duplicates are removed -/
def of_list [decidable_eq α] (xs : list α) (h : ∀ x : α, x ∈ xs) : fin_enum α :=
of_nodup_list xs.dedup (by simp *) (list.nodup_dedup _)
/-- create an exhaustive list of the values of a given type -/
def to_list (α) [fin_enum α] : list α :=
(list.fin_range (card α)).map (equiv α).symm
open function
@[simp] lemma mem_to_list [fin_enum α] (x : α) : x ∈ to_list α :=
by simp [to_list]; existsi equiv α x; simp
@[simp] lemma nodup_to_list [fin_enum α] : list.nodup (to_list α) :=
by simp [to_list]; apply list.nodup.map; [apply equiv.injective, apply list.nodup_fin_range]
/-- create a `fin_enum` instance using a surjection -/
def of_surjective {β} (f : β → α) [decidable_eq α] [fin_enum β] (h : surjective f) : fin_enum α :=
of_list ((to_list β).map f) (by intro; simp; exact h _)
/-- create a `fin_enum` instance using an injection -/
noncomputable def of_injective {α β} (f : α → β) [decidable_eq α] [fin_enum β] (h : injective f) :
fin_enum α :=
of_list ((to_list β).filter_map (partial_inv f))
begin
intro x,
simp only [mem_to_list, true_and, list.mem_filter_map],
use f x,
simp only [h, function.partial_inv_left],
end
instance pempty : fin_enum pempty :=
of_list [] (λ x, pempty.elim x)
instance empty : fin_enum empty :=
of_list [] (λ x, empty.elim x)
instance punit : fin_enum punit :=
of_list [punit.star] (λ x, by cases x; simp)
instance prod {β} [fin_enum α] [fin_enum β] : fin_enum (α × β) :=
of_list ( (to_list α).product (to_list β) ) (λ x, by cases x; simp)
instance sum {β} [fin_enum α] [fin_enum β] : fin_enum (α ⊕ β) :=
of_list ( (to_list α).map sum.inl ++ (to_list β).map sum.inr ) (λ x, by cases x; simp)
instance fin {n} : fin_enum (fin n) :=
of_list (list.fin_range _) (by simp)
instance quotient.enum [fin_enum α] (s : setoid α)
[decidable_rel ((≈) : α → α → Prop)] : fin_enum (quotient s) :=
fin_enum.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩))
/-- enumerate all finite sets of a given type -/
def finset.enum [decidable_eq α] : list α → list (finset α)
| [] := [∅]
| (x :: xs) :=
do r ← finset.enum xs,
[r,{x} ∪ r]
@[simp]lemma finset.mem_enum [decidable_eq α] (s : finset α) (xs : list α) :
s ∈ finset.enum xs ↔ ∀ x ∈ s, x ∈ xs :=
begin
induction xs generalizing s; simp [*,finset.enum],
{ simp [finset.eq_empty_iff_forall_not_mem,(∉)], refl },
{ split, rintro ⟨a,h,h'⟩ x hx,
cases h',
{ right, apply h, subst a, exact hx, },
{ simp only [h', mem_union, mem_singleton] at hx ⊢, cases hx,
{ exact or.inl hx },
{ exact or.inr (h _ hx) } },
intro h, existsi s \ ({xs_hd} : finset α),
simp only [and_imp, union_comm, mem_sdiff, mem_singleton],
simp only [or_iff_not_imp_left] at h,
existsi h,
by_cases xs_hd ∈ s,
{ have : {xs_hd} ⊆ s, simp only [has_subset.subset, *, forall_eq, mem_singleton],
simp only [union_sdiff_of_subset this, or_true, finset.union_sdiff_of_subset,
eq_self_iff_true], },
{ left, symmetry, simp only [sdiff_eq_self],
intro a, simp only [and_imp, mem_inter, mem_singleton, not_mem_empty],
intros h₀ h₁, subst a, apply h h₀, } }
end
instance finset.fin_enum [fin_enum α] : fin_enum (finset α) :=
of_list (finset.enum (to_list α)) (by intro; simp)
instance subtype.fin_enum [fin_enum α] (p : α → Prop) [decidable_pred p] : fin_enum {x // p x} :=
of_list ((to_list α).filter_map $ λ x, if h : p x then some ⟨_,h⟩ else none)
(by rintro ⟨x,h⟩; simp; existsi x; simp *)
instance (β : α → Type v)
[fin_enum α] [∀ a, fin_enum (β a)] : fin_enum (sigma β) :=
of_list
((to_list α).bind $ λ a, (to_list (β a)).map $ sigma.mk a)
(by intro x; cases x; simp)
instance psigma.fin_enum [fin_enum α] [∀ a, fin_enum (β a)] :
fin_enum (Σ' a, β a) :=
fin_enum.of_equiv _ (equiv.psigma_equiv_sigma _)
instance psigma.fin_enum_prop_left {α : Prop} {β : α → Type v} [∀ a, fin_enum (β a)] [decidable α] :
fin_enum (Σ' a, β a) :=
if h : α then of_list ((to_list (β h)).map $ psigma.mk h) (λ ⟨a,Ba⟩, by simp)
else of_list [] (λ ⟨a,Ba⟩, (h a).elim)
instance psigma.fin_enum_prop_right {β : α → Prop} [fin_enum α] [∀ a, decidable (β a)] :
fin_enum (Σ' a, β a) :=
fin_enum.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩
instance psigma.fin_enum_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] :
fin_enum (Σ' a, β a) :=
if h : ∃ a, β a
then of_list [⟨h.fst,h.snd⟩] (by rintro ⟨⟩; simp)
else of_list [] (λ a, (h ⟨a.fst,a.snd⟩).elim)
@[priority 100]
instance [fin_enum α] : fintype α :=
{ elems := univ.map (equiv α).symm.to_embedding,
complete := by intros; simp; existsi (equiv α x); simp }
/-- For `pi.cons x xs y f` create a function where every `i ∈ xs` is mapped to `f i` and
`x` is mapped to `y` -/
def pi.cons [decidable_eq α] (x : α) (xs : list α) (y : β x)
(f : Π a, a ∈ xs → β a) :
Π a, a ∈ (x :: xs : list α) → β a
| b h :=
if h' : b = x then cast (by rw h') y
else f b (list.mem_of_ne_of_mem h' h)
/-- Given `f` a function whose domain is `x :: xs`, produce a function whose domain
is restricted to `xs`. -/
def pi.tail {x : α} {xs : list α} (f : Π a, a ∈ (x :: xs : list α) → β a) :
Π a, a ∈ xs → β a
| a h := f a (list.mem_cons_of_mem _ h)
/-- `pi xs f` creates the list of functions `g` such that, for `x ∈ xs`, `g x ∈ f x` -/
def pi {β : α → Type (max u v)} [decidable_eq α] : Π xs : list α, (Π a, list (β a)) →
list (Π a, a ∈ xs → β a)
| [] fs := [λ x h, h.elim]
| (x :: xs) fs :=
fin_enum.pi.cons x xs <$> fs x <*> pi xs fs
lemma mem_pi {β : α → Type (max u v)} [fin_enum α] [∀a, fin_enum (β a)] (xs : list α)
(f : Π a, a ∈ xs → β a) :
f ∈ pi xs (λ x, to_list (β x)) :=
begin
induction xs; simp [pi,-list.map_eq_map] with monad_norm functor_norm,
{ ext a ⟨ ⟩ },
{ existsi pi.cons xs_hd xs_tl (f _ (list.mem_cons_self _ _)),
split, exact ⟨_,rfl⟩,
existsi pi.tail f, split,
{ apply xs_ih, },
{ ext x h, simp [pi.cons], split_ifs, subst x, refl, refl }, }
end
/-- enumerate all functions whose domain and range are finitely enumerable -/
def pi.enum (β : α → Type (max u v)) [fin_enum α] [∀a, fin_enum (β a)] : list (Π a, β a) :=
(pi (to_list α) (λ x, to_list (β x))).map (λ f x, f x (mem_to_list _))
lemma pi.mem_enum {β : α → Type (max u v)} [fin_enum α] [∀a, fin_enum (β a)] (f : Π a, β a) :
f ∈ pi.enum β :=
by simp [pi.enum]; refine ⟨λ a h, f a, mem_pi _ _, rfl⟩
instance pi.fin_enum {β : α → Type (max u v)}
[fin_enum α] [∀a, fin_enum (β a)] : fin_enum (Πa, β a) :=
of_list (pi.enum _) (λ x, pi.mem_enum _)
instance pfun_fin_enum (p : Prop) [decidable p] (α : p → Type*)
[Π hp, fin_enum (α hp)] : fin_enum (Π hp : p, α hp) :=
if hp : p then of_list ( (to_list (α hp)).map $ λ x hp', x ) (by intro; simp; exact ⟨x hp,rfl⟩)
else of_list [λ hp', (hp hp').elim] (by intro; simp; ext hp'; cases hp hp')
end fin_enum
|
module Minecraft.Core.Item.Export
import public Minecraft.Core.Item
%default total
|
#ifndef OPENMC_TALLIES_FILTER_CELL_H
#define OPENMC_TALLIES_FILTER_CELL_H
#include <cstdint>
#include <unordered_map>
#include <gsl/gsl>
#include "openmc/tallies/filter.h"
#include "openmc/vector.h"
namespace openmc {
//==============================================================================
//! Specifies which geometric cells tally events reside in.
//==============================================================================
class CellFilter : public Filter
{
public:
//----------------------------------------------------------------------------
// Constructors, destructors
~CellFilter() = default;
//----------------------------------------------------------------------------
// Methods
std::string type() const override {return "cell";}
void from_xml(pugi::xml_node node) override;
void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match)
const override;
void to_statepoint(hid_t filter_group) const override;
std::string text_label(int bin) const override;
//----------------------------------------------------------------------------
// Accessors
const vector<int32_t>& cells() const { return cells_; }
void set_cells(gsl::span<int32_t> cells);
protected:
//----------------------------------------------------------------------------
// Data members
//! The indices of the cells binned by this filter.
vector<int32_t> cells_;
//! A map from cell indices to filter bin indices.
std::unordered_map<int32_t, int> map_;
};
} // namespace openmc
#endif // OPENMC_TALLIES_FILTER_CELL_H
|
(*
Theory: PDF_Values.thy
Author: Manuel Eberl
Defines the values and types in the PDF language and the corresponding stock measure spaces.
Additionally, some functions and lemmas for lifting functions on the HOL types (int, real, \<dots>)
to PDF values are provided.
*)
header {* Source Language Values *}
theory PDF_Values
imports Giry_Monad Density_Predicates Measure_Embeddings PDF_Misc
begin
subsection {* Values and stock measures *}
datatype pdf_type = UNIT | BOOL | INTEG | REAL | PRODUCT pdf_type pdf_type
datatype val = UnitVal | BoolVal bool | IntVal int | RealVal real |
PairVal val val ("<|_, _|>" [0, 61] 1000)
abbreviation "TRUE \<equiv> BoolVal True"
abbreviation "FALSE \<equiv> BoolVal False"
type_synonym vname = "nat"
type_synonym state = "vname \<Rightarrow> val"
definition "RealPairVal \<equiv> \<lambda>(x,y). <|RealVal x, RealVal y|>"
definition "extract_real_pair \<equiv> \<lambda><|RealVal x, RealVal y|> \<Rightarrow> (x,y)"
definition "IntPairVal \<equiv> \<lambda>(x,y). <|IntVal x, IntVal y|>"
definition "extract_int_pair \<equiv> \<lambda><|IntVal x, IntVal y|> \<Rightarrow> (x,y)"
lemma inj_RealPairVal: "inj RealPairVal" by (auto simp: RealPairVal_def intro!: injI)
lemma inj_IntPairVal: "inj IntPairVal" by (auto simp: IntPairVal_def intro!: injI)
primrec stock_measure :: "pdf_type \<Rightarrow> val measure" where
"stock_measure UNIT = count_space {UnitVal}"
| "stock_measure INTEG = count_space (range IntVal)"
| "stock_measure BOOL = count_space (range BoolVal)"
| "stock_measure REAL = embed_measure lborel RealVal"
| "stock_measure (PRODUCT t1 t2) =
embed_measure (stock_measure t1 \<Otimes>\<^sub>M stock_measure t2) (\<lambda>(a, b). PairVal a b)"
lemma sigma_finite_stock_measure[simp]: "sigma_finite_measure (stock_measure t)"
by (induction t)
(auto intro!: sigma_finite_measure_count_space_countable sigma_finite_pair_measure
sigma_finite_embed_measure injI sigma_finite_lborel)
fun val_type :: "val \<Rightarrow> pdf_type" where
"val_type (BoolVal b) = BOOL"
| "val_type (IntVal i) = INTEG"
| "val_type UnitVal = UNIT"
| "val_type (RealVal r) = REAL"
| "val_type (<|v1 , v2|>) = (PRODUCT (val_type v1) (val_type v2))"
definition "type_universe t = {v. val_type v = t}"
lemma space_stock_measure[simp]:
"space (stock_measure t) = type_universe t"
by (induction t) (auto simp: space_embed_measure space_pair_measure type_universe_def
elim: val_type.elims)
lemma val_in_type_universe[simp]:
"v \<in> type_universe (val_type v)"
by (simp add: type_universe_def)
lemma type_universe_type[simp]:
"w \<in> type_universe t \<Longrightarrow> val_type w = t"
by (simp add: type_universe_def)
lemma type_universe_nonempty[simp]:
"type_universe t \<noteq> {}"
by (subst space_stock_measure[symmetric], induction t)
(auto simp: space_pair_measure space_embed_measure simp del: space_stock_measure)
lemma inj_RealVal[simp]: "inj RealVal" by (auto intro!: inj_onI)
lemma inj_IntVal[simp]: "inj IntVal" by (auto intro!: inj_onI)
lemma inj_BoolVal[simp]: "inj BoolVal" by (auto intro!: inj_onI)
lemma inj_PairVal: "inj (\<lambda>(x, y). <| x , y |>)" by (auto intro: injI)
lemma nn_integral_BoolVal:
assumes "\<And>x. x \<in> space (stock_measure BOOL) \<Longrightarrow> f x \<ge> 0"
shows "(\<integral>\<^sup>+x. f x \<partial>stock_measure BOOL) = f (BoolVal True) + f (BoolVal False)"
proof-
have A: "range BoolVal = {BoolVal True, BoolVal False}" by auto
from assms show ?thesis
by (subst stock_measure.simps, subst A, subst nn_integral_count_space_finite)
(simp_all add: max_def A)
qed
lemma nn_integral_RealVal:
assumes "f \<in> borel_measurable (embed_measure lborel RealVal)"
shows "(\<integral>\<^sup>+x. f x \<partial>embed_measure lborel RealVal) = (\<integral>\<^sup>+x. f (RealVal x) \<partial>lborel)"
using assms by (subst embed_measure_eq_distr, simp, subst nn_integral_distr) simp_all
lemma nn_integral_IntVal:
"(\<integral>\<^sup>+x. f x \<partial>count_space (range IntVal)) = (\<integral>\<^sup>+x. f (IntVal x) \<partial>count_space UNIV)"
by (subst embed_measure_count_space[symmetric], simp, subst embed_measure_eq_distr,
simp, subst nn_integral_distr) (simp_all add: space_embed_measure)
definition extract_pair where "extract_pair \<equiv> \<lambda> <|v,w|> \<Rightarrow> (v,w)"
definition extract_bool where "extract_bool \<equiv> \<lambda> BoolVal v \<Rightarrow> v"
definition extract_real where "extract_real \<equiv> \<lambda> RealVal v \<Rightarrow> v | _ \<Rightarrow> 0"
definition extract_int where "extract_int \<equiv> \<lambda> IntVal v \<Rightarrow> v | _ \<Rightarrow> 0"
lemma BOOL_E: "\<lbrakk>val_type v = BOOL; \<And>b. v = BoolVal b \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P"
using assms by (cases v) auto
lemma REAL_E: "\<lbrakk>val_type v = REAL; \<And>b. v = RealVal b \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P"
using assms by (cases v) auto
lemma measurable_extract_pair[measurable]:
"extract_pair \<in> measurable (embed_measure (M \<Otimes>\<^sub>M N) (\<lambda>(x,y). <|x,y|>)) (M \<Otimes>\<^sub>M N)"
apply (rule measurable_embed_measure1)
apply (subst measurable_cong[of _ _ "\<lambda>x. x"])
apply (auto simp: extract_pair_def)
done
lemma measurable_extract_real[measurable]:
"extract_real \<in> measurable (embed_measure lborel RealVal) borel"
apply (rule measurable_embed_measure1)
apply (subst measurable_cong[of _ _ "\<lambda>x. x"])
apply (auto simp: extract_real_def)
done
lemma measurable_extract_int[measurable]:
"extract_int \<in> measurable (count_space (range IntVal)) (count_space UNIV)"
by (rule measurable_count_space)
lemma measurable_extract_bool[measurable]:
"extract_bool \<in> measurable (count_space (range BoolVal)) (count_space UNIV)"
by (rule measurable_count_space)
lemma count_space_BoolVal_prod[simp]:
"count_space (range BoolVal) \<Otimes>\<^sub>M count_space (range BoolVal) =
count_space (range BoolVal \<times> range BoolVal)"
by (rule pair_measure_countable) simp_all
lemma measurable_PairVal1:
assumes "x \<in> space (stock_measure t1)"
shows "PairVal x \<in> measurable (stock_measure t2)
(embed_measure (stock_measure t1 \<Otimes>\<^sub>M stock_measure t2) (split PairVal))"
using assms inj_PairVal by simp
lemma measurable_stock_measure_val_type:
assumes "f \<in> measurable M (stock_measure t)" "x \<in> space M"
shows "val_type (f x) = t"
using assms by (auto dest!: measurable_space)
lemma type_universe_eq_imp_type_eq:
assumes "type_universe t1 = type_universe t2"
shows "t1 = t2"
proof-
from type_universe_nonempty obtain v where A: "v \<in> type_universe t1" by blast
hence "t1 = val_type v" by simp
also from A and assms have "v \<in> type_universe t2" by simp
hence "val_type v = t2" by simp
finally show ?thesis .
qed
lemma type_universe_eq_iff[simp]: "type_universe t1 = type_universe t2 \<longleftrightarrow> t1 = t2"
by (blast intro: type_universe_eq_imp_type_eq)
lemma singleton_in_stock_measure[simp]:
"{v} \<in> sets (stock_measure (val_type v))"
proof (induction v)
case (PairVal v1 v2)
have A: "{<|v1, v2|>} = (\<lambda>(v1,v2). <|v1,v2|>) ` ({v1}\<times>{v2})" by simp
from pair_measureI[OF PairVal.IH] show ?case
by (simp only: val_type.simps stock_measure.simps A in_sets_embed_measure)
qed (auto simp: sets_embed_measure)
lemma emeasure_stock_measure_singleton_finite[simp]:
"emeasure (stock_measure (val_type v)) {v} \<noteq> \<infinity>"
proof (induction v)
case (RealVal r)
have A: "{RealVal r} = RealVal ` {r}" by simp
have "RealVal ` {r} \<in> sets (embed_measure lborel RealVal)"
by (rule in_sets_embed_measure) simp
thus ?case by (simp only: A val_type.simps stock_measure.simps emeasure_embed_measure
inj_RealVal inj_vimage_image_eq) simp
next
case (PairVal v1 v2)
let ?M = "\<lambda>x. stock_measure (val_type x)"
interpret sigma_finite_measure "stock_measure (val_type v2)"
by (rule sigma_finite_stock_measure)
have A: "{<|v1, v2|>} = (\<lambda>(v1,v2). <|v1,v2|>) ` ({v1}\<times>{v2})" by simp
have B: "{v1}\<times>{v2} \<in> ?M v1 \<Otimes>\<^sub>M ?M v2"
by (intro pair_measureI singleton_in_stock_measure)
hence "emeasure (?M (<|v1,v2|>)) {<|v1,v2|>} = emeasure (?M v1) {v1} * emeasure (?M v2) {v2}"
by (simp only: stock_measure.simps val_type.simps A emeasure_embed_measure_image inj_PairVal
inj_vimage_image_eq emeasure_pair_measure_Times singleton_in_stock_measure B)
with PairVal.IH show ?case by simp
qed simp_all
subsection {* Measures on states *}
definition state_measure :: "vname set \<Rightarrow> (vname \<Rightarrow> pdf_type) \<Rightarrow> state measure" where
"state_measure V \<Gamma> \<equiv> \<Pi>\<^sub>M y\<in>V. stock_measure (\<Gamma> y)"
lemma state_measure_nonempty[simp]: "space (state_measure V \<Gamma>) \<noteq> {}"
by (simp add: state_measure_def space_PiM PiE_eq_empty_iff)
lemma state_measure_var_type:
"\<sigma> \<in> space (state_measure V \<Gamma>) \<Longrightarrow> x \<in> V \<Longrightarrow> val_type (\<sigma> x) = \<Gamma> x"
by (auto simp: state_measure_def space_PiM dest!: PiE_mem)
lemma merge_in_state_measure:
"x \<in> space (state_measure A \<Gamma>) \<Longrightarrow> y \<in> space (state_measure B \<Gamma>) \<Longrightarrow>
merge A B (x, y) \<in> space (state_measure (A\<union>B) \<Gamma>)" unfolding state_measure_def
by (rule measurable_space, rule measurable_merge) (simp add: space_pair_measure)
lemma comp_in_state_measure:
assumes "\<sigma> \<in> space (state_measure V \<Gamma>)"
shows "\<sigma> \<circ> f \<in> space (state_measure (f -` V) (\<Gamma> \<circ> f))"
using assms by (auto simp: state_measure_def space_PiM)
lemma sigma_finite_state_measure[intro]:
"finite V \<Longrightarrow> sigma_finite_measure (state_measure V \<Gamma>)" unfolding state_measure_def
by (auto intro!: product_sigma_finite.sigma_finite simp: product_sigma_finite_def)
subsection {* Equalities of measure embeddings *}
lemma embed_measure_RealPairVal:
"stock_measure (PRODUCT REAL REAL) = embed_measure lborel RealPairVal"
proof-
have [simp]: "(\<lambda>(x, y). <| x , y |>) \<circ> (\<lambda>(x, y). (RealVal x, RealVal y)) = RealPairVal"
unfolding RealPairVal_def by auto
have "stock_measure (PRODUCT REAL REAL) =
embed_measure (embed_measure lborel (\<lambda>(x, y). (RealVal x, RealVal y))) (split PairVal)"
by (auto simp: embed_measure_prod sigma_finite_lborel lborel_prod)
also have "... = embed_measure lborel RealPairVal"
by (subst embed_measure_comp) (auto intro!: injI)
finally show ?thesis .
qed
lemma embed_measure_IntPairVal:
"stock_measure (PRODUCT INTEG INTEG) = (count_space (range IntPairVal))"
proof-
have [simp]: "(\<lambda>(x, y). <| x , y |>) ` (range IntVal \<times> range IntVal) = range IntPairVal"
by (auto simp: IntPairVal_def)
show ?thesis by (auto simp: embed_measure_prod embed_measure_count_space inj_PairVal)
qed
subsection {* Monadic operations on values *}
definition "return_val x = return (stock_measure (val_type x)) x"
lemma sets_return_val: "sets (return_val x) = sets (stock_measure (val_type x))"
by (simp add: return_val_def)
lemma measurable_return_val[simp]:
"return_val \<in> measurable (stock_measure t) (subprob_algebra (stock_measure t))"
unfolding return_val_def[abs_def]
apply (subst measurable_cong)
apply (subst (asm) space_stock_measure, subst type_universe_type, assumption, rule refl)
apply (rule return_measurable)
done
lemma bind_return_val:
assumes "space M \<noteq> {}" "f \<in> measurable M (stock_measure t')"
shows "M \<guillemotright>= (\<lambda>x. return_val (f x)) = distr M (stock_measure t') f"
using assms
by (subst bind_return_distr[symmetric])
(auto simp: return_val_def intro!: bind_cong dest: measurable_stock_measure_val_type)
lemma bind_return_val':
assumes "val_type x = t" "f \<in> measurable (stock_measure t) (stock_measure t')"
shows "return_val x \<guillemotright>= (\<lambda>x. return_val (f x)) = return_val (f x)"
proof-
have "return_val x \<guillemotright>= (\<lambda>x. return_val (f x)) = return (stock_measure t') (f x)"
apply (subst bind_return_val, unfold return_val_def, simp)
apply (insert assms, simp cong: measurable_cong_sets) []
apply (subst distr_return, simp_all add: assms type_universe_def
del: type_universe_type)
done
also from assms(2) have "f x \<in> space (stock_measure t')"
by (rule measurable_space)
(simp add: assms(1) type_universe_def del: type_universe_type)
hence "return (stock_measure t') (f x) = return_val (f x)"
by (simp add: return_val_def)
finally show ?thesis .
qed
lemma bind_return_val'':
assumes "f \<in> measurable (stock_measure (val_type x)) (subprob_algebra M)"
shows "return_val x \<guillemotright>= f = f x"
unfolding return_val_def by (subst bind_return[OF assms]) simp_all
lemma bind_assoc_return_val:
assumes sets_M: "sets M = sets (stock_measure t)"
assumes Mf: "f \<in> measurable (stock_measure t) (stock_measure t')"
assumes Mg: "g \<in> measurable (stock_measure t') (stock_measure t'')"
shows "(M \<guillemotright>= (\<lambda>x. return_val (f x))) \<guillemotright>= (\<lambda>x. return_val (g x)) =
M \<guillemotright>= (\<lambda>x. return_val (g (f x)))"
proof-
have "(M \<guillemotright>= (\<lambda>x. return_val (f x))) \<guillemotright>= (\<lambda>x. return_val (g x)) =
M \<guillemotright>= (\<lambda>x. return_val (f x) \<guillemotright>= (\<lambda>x. return_val (g x)))"
apply (subst bind_assoc)
apply (rule measurable_compose[OF _ measurable_return_val])
apply (subst measurable_cong_sets[OF sets_M refl], rule Mf)
apply (rule measurable_compose[OF Mg measurable_return_val], rule refl)
done
also have "... = M \<guillemotright>= (\<lambda>x. return_val (g (f x)))"
apply (intro bind_cong ballI)
apply (subst (asm) sets_eq_imp_space_eq[OF sets_M])
apply (drule measurable_space[OF Mf])
apply (subst bind_return_val'[where t = t' and t' = t''])
apply (simp_all add: Mg)
done
finally show ?thesis .
qed
lemma bind_return_val_distr:
assumes sets_M: "sets M = sets (stock_measure t)"
assumes Mf: "f \<in> measurable (stock_measure t) (stock_measure t')"
shows "M \<guillemotright>= return_val \<circ> f = distr M (stock_measure t') f"
proof-
have "M \<guillemotright>= return_val \<circ> f = M \<guillemotright>= return (stock_measure t') \<circ> f"
apply (intro bind_cong ballI)
apply (subst (asm) sets_eq_imp_space_eq[OF sets_M])
apply (drule measurable_space[OF Mf])
apply (simp add: return_val_def o_def)
done
also have "... = distr M (stock_measure t') f"
apply (rule bind_return_distr)
apply (simp add: sets_eq_imp_space_eq[OF sets_M])
apply (subst measurable_cong_sets[OF sets_M refl], rule Mf)
done
finally show ?thesis .
qed
subsection {* Lifting of functions *}
definition lift_RealVal where
"lift_RealVal f \<equiv> \<lambda> RealVal v \<Rightarrow> RealVal (f v) | _ \<Rightarrow> RealVal (f 0)"
definition lift_IntVal where
"lift_IntVal f \<equiv> \<lambda> IntVal v \<Rightarrow> IntVal (f v) | _ \<Rightarrow> IntVal (f 0)"
definition lift_RealIntVal where
"lift_RealIntVal f g \<equiv> \<lambda> IntVal v \<Rightarrow> IntVal (f v) | RealVal v \<Rightarrow> RealVal (g v)"
definition lift_RealIntVal2 where
"lift_RealIntVal2 f g \<equiv> \<lambda> <|IntVal v, IntVal w|> \<Rightarrow> IntVal (f v w)
| <|RealVal v, RealVal w|> \<Rightarrow> RealVal (g v w)"
definition lift_Comp where
"lift_Comp f g \<equiv> \<lambda> <|IntVal v, IntVal w|> \<Rightarrow> BoolVal (f v w)
| <|RealVal v, RealVal w|> \<Rightarrow> BoolVal (g v w)"
lemma lift_RealIntVal_Real:
"x \<in> space (stock_measure REAL) \<Longrightarrow> lift_RealIntVal f g x = lift_RealVal g x"
by (auto simp: space_embed_measure lift_RealIntVal_def lift_RealVal_def)
lemma lift_RealIntVal_Int:
"x \<in> space (stock_measure INTEG) \<Longrightarrow> lift_RealIntVal f g x = lift_IntVal f x"
by (auto simp: space_embed_measure lift_RealIntVal_def lift_IntVal_def)
lemma measurable_lift_RealVal[measurable]:
assumes "f \<in> borel_measurable borel"
shows "lift_RealVal f \<in> measurable (embed_measure lborel RealVal) (embed_measure lborel RealVal)"
(is "_ \<in> measurable ?M _")
proof-
have "lift_RealVal f = RealVal \<circ> f \<circ> extract_real"
unfolding lift_RealVal_def extract_real_def by (intro ext) (auto split: val.split)
also have "RealVal \<in> measurable borel ?M" by simp
hence "RealVal \<circ> f \<circ> extract_real \<in> measurable ?M ?M"
by (intro measurable_comp) (blast intro!: measurable_extract_real assms)+
finally show ?thesis .
qed
lemma measurable_lift_IntVal[simp]:
"lift_IntVal f \<in> range IntVal \<rightarrow> range IntVal"
by (auto simp: lift_IntVal_def)
lemma measurable_lift_Comp_RealVal[measurable]:
assumes "Measurable.pred (borel \<Otimes>\<^sub>M borel) (split g)"
shows "lift_Comp f g \<in> measurable (embed_measure (embed_measure lborel RealVal \<Otimes>\<^sub>M
embed_measure lborel RealVal) (split PairVal))
(count_space (range BoolVal))"
(is "_ \<in> measurable ?M ?N")
proof-
have "\<And>x. x \<in> space ?M \<Longrightarrow> lift_Comp f g x =
(BoolVal \<circ> (\<lambda>x. g (fst x) (snd x)) \<circ>
(\<lambda>(x,y). (extract_real x, extract_real y)) \<circ> extract_pair) x"
by (auto simp: o_def extract_real_def extract_pair_def
lift_Comp_def space_pair_measure space_embed_measure split: val.split)
moreover have "... \<in> measurable ?M ?N"
by (intro measurable_comp, rule measurable_extract_pair, subst measurable_split_conv,
rule measurable_Pair, rule measurable_compose[OF measurable_fst measurable_extract_real],
rule measurable_compose[OF measurable_snd measurable_extract_real],
subst measurable_split_conv[symmetric], rule assms, simp)
ultimately show ?thesis by (simp cong: measurable_cong)
qed
lemma measurable_lift_Comp_IntVal[simp]:
"lift_Comp f g \<in> measurable (embed_measure (count_space (range IntVal) \<Otimes>\<^sub>M
count_space (range IntVal)) (split PairVal))
(count_space (range BoolVal))"
by (auto simp: lift_Comp_def embed_measure_count_space inj_PairVal)
lemma measurable_lift_RealIntVal_IntVal[simp]:
"lift_RealIntVal f g \<in> range IntVal \<rightarrow> range IntVal"
by (auto simp: embed_measure_count_space lift_RealIntVal_def)
lemma measurable_lift_RealIntVal_RealVal[measurable]:
assumes "g \<in> borel_measurable borel"
shows "lift_RealIntVal f g \<in>
measurable (embed_measure lborel RealVal) (embed_measure lborel RealVal)"
(is "_ \<in> measurable ?M _")
proof-
have "\<And>x. x \<in> space ?M \<Longrightarrow> lift_RealIntVal f g x = lift_RealVal g x"
unfolding lift_RealVal_def lift_RealIntVal_def
by (auto split: val.split simp: space_embed_measure)
with assms and measurable_lift_RealVal show ?thesis by (simp cong: measurable_cong)
qed
lemma measurable_lift_RealIntVal2_IntVal[measurable]:
"lift_RealIntVal2 f g \<in> measurable (embed_measure (count_space (range IntVal) \<Otimes>\<^sub>M
count_space (range IntVal)) (split PairVal))
(count_space (range IntVal))"
by (auto simp: lift_RealIntVal2_def embed_measure_count_space inj_PairVal)
lemma measurable_lift_RealIntVal2_RealVal[measurable]:
assumes "(\<lambda>x. g (fst x) (snd x)) \<in> borel_measurable (borel \<Otimes>\<^sub>M borel)"
shows "lift_RealIntVal2 f g \<in> measurable (embed_measure (embed_measure lborel RealVal \<Otimes>\<^sub>M
embed_measure lborel RealVal) (split PairVal))
(embed_measure lborel RealVal)"
(is "_ \<in> measurable ?M ?N")
proof-
have "\<And>x. x \<in> space ?M \<Longrightarrow> lift_RealIntVal2 f g x =
(RealVal \<circ> (\<lambda>x. g (fst x) (snd x)) \<circ>
(\<lambda>(x,y). (extract_real x, extract_real y)) \<circ> extract_pair) x"
by (auto simp: o_def extract_real_def extract_pair_def
lift_RealIntVal2_def space_pair_measure space_embed_measure split: val.split)
moreover have "... \<in> measurable ?M ?N"
by (intro measurable_comp, rule measurable_extract_pair, subst measurable_split_conv,
rule measurable_Pair, rule measurable_compose[OF measurable_fst measurable_extract_real],
rule measurable_compose[OF measurable_snd measurable_extract_real], rule assms,
subst measurable_lborel2[symmetric], rule measurable_embed_measure2, rule inj_RealVal)
ultimately show ?thesis by (simp cong: measurable_cong)
qed
lemma distr_lift_RealVal:
fixes f
assumes Mf: "f \<in> borel_measurable borel"
assumes pdens: "has_subprob_density M (stock_measure REAL) \<delta>"
assumes dens': "\<And>M \<delta>. has_subprob_density M lborel \<delta> \<Longrightarrow> has_density (distr M borel f) lborel (g \<delta>)"
defines "N \<equiv> distr M (stock_measure REAL) (lift_RealVal f)"
shows "has_density N (stock_measure REAL) (g (\<lambda>x. \<delta> (RealVal x)) \<circ> extract_real)"
proof (rule has_densityI)
from assms(2) have dens: "has_density M (stock_measure REAL) \<delta>"
unfolding has_subprob_density_def by simp
have MRV: "RealVal \<in> measurable borel (embed_measure lborel RealVal)"
by (subst measurable_lborel2[symmetric], rule measurable_embed_measure2) simp
from dens have sets_M: "sets M = sets (embed_measure lborel RealVal)" by (auto dest: has_densityD)
have "N = distr M (stock_measure REAL) (lift_RealVal f)" by (simp add: N_def)
also have "lift_RealVal f = RealVal \<circ> f \<circ> extract_real"
unfolding lift_RealVal_def extract_real_def by (intro ext) (auto simp: o_def split: val.split)
also have "distr M (stock_measure REAL) ... =
distr (distr (distr M lborel extract_real) borel f) (stock_measure REAL) RealVal"
apply (subst distr_distr[symmetric], intro measurable_comp, rule assms(1), simp add: MRV)
apply (subst measurable_cong_sets[OF sets_M refl], rule measurable_extract_real)
apply (subst distr_distr[symmetric], subst stock_measure.simps, rule MRV,
simp_all add: assms(1) cong: distr_cong)
done
also have dens'': "has_density (distr (distr M lborel extract_real) borel f) lborel (g (\<delta> \<circ> RealVal))"
by (intro dens' has_subprob_density_embed_measure'') (insert pdens, simp_all add: extract_real_def)
hence "distr (distr M lborel extract_real) borel f = density lborel (g (\<delta> \<circ> RealVal))"
by (rule has_densityD)
also have "distr ... (stock_measure REAL) RealVal = embed_measure ... RealVal" (is "_ = ?M")
by (subst embed_measure_eq_distr[OF inj_RealVal], intro distr_cong)
(simp_all add: sets_embed_measure)
also have "... = density (embed_measure lborel RealVal) (g (\<lambda>x. \<delta> (RealVal x)) \<circ> extract_real)"
using dens''[unfolded o_def]
apply (subst density_embed_measure', simp, simp add: extract_real_def)
apply (erule has_densityD, simp add: o_def)
done
finally show "N = density (stock_measure REAL) (g (\<lambda>x. \<delta> (RealVal x)) \<circ> extract_real)" by simp
from dens''[unfolded o_def]
show "g (\<lambda>x. \<delta> (RealVal x)) \<circ> extract_real \<in> borel_measurable (stock_measure REAL)"
by (intro measurable_comp, subst stock_measure.simps)
(rule measurable_extract_real, subst measurable_lborel2[symmetric], erule has_densityD)
fix x assume "x \<in> space (stock_measure REAL)"
thus "(g (\<lambda>x. \<delta> (RealVal x)) \<circ> extract_real) x \<ge> 0" unfolding o_def
by (intro has_densityD(2)[OF dens''[unfolded o_def]]) auto
qed (subst space_stock_measure, simp)
lemma distr_lift_IntVal:
fixes f
assumes pdens: "has_density M (stock_measure INTEG) \<delta>"
assumes dens': "\<And>M \<delta>. has_density M (count_space UNIV) \<delta> \<Longrightarrow>
has_density (distr M (count_space UNIV) f) (count_space UNIV) (g \<delta>)"
defines "N \<equiv> distr M (stock_measure INTEG) (lift_IntVal f)"
shows "has_density N (stock_measure INTEG) (g (\<lambda>x. \<delta> (IntVal x)) \<circ> extract_int)"
proof (rule has_densityI)
let ?R = "count_space UNIV" and ?S = "count_space (range IntVal)"
have Mf: "f \<in> measurable ?R ?R" by simp
have MIV: "IntVal \<in> measurable ?R ?S" by simp
from assms(1) have dens: "has_density M (stock_measure INTEG) \<delta>"
unfolding has_subprob_density_def by simp
from dens have sets_M: "sets M = sets ?S" by (auto dest!: has_densityD(3))
have "N = distr M (stock_measure INTEG) (lift_IntVal f)" by (simp add: N_def)
also have "lift_IntVal f = IntVal \<circ> f \<circ> extract_int"
unfolding lift_IntVal_def extract_int_def by (intro ext) (auto simp: o_def split: val.split)
also have "distr M (stock_measure INTEG) ... =
distr (distr (distr M ?R extract_int) ?R f) (stock_measure INTEG) IntVal"
apply (subst distr_distr[symmetric], intro measurable_comp, rule Mf, simp)
apply (subst measurable_cong_sets[OF sets_M refl], simp)
apply (subst distr_distr[symmetric], subst stock_measure.simps, rule MIV, simp_all add: Mf)
done
also have dens'': "has_density (distr (distr M ?R extract_int) ?R f) ?R (g (\<delta> \<circ> IntVal))"
by (intro dens' has_density_embed_measure'')
(insert dens, simp_all add: extract_int_def embed_measure_count_space)
hence "distr (distr M ?R extract_int) ?R f = density ?R (g (\<delta> \<circ> IntVal))"
by (rule has_densityD)
also have "distr ... (stock_measure INTEG) IntVal = embed_measure ... IntVal" (is "_ = ?M")
by (subst embed_measure_eq_distr[OF inj_IntVal], intro distr_cong)
(auto simp: sets_embed_measure subset_image_iff)
also have "... = density (embed_measure ?R IntVal) (g (\<lambda>x. \<delta> (IntVal x)) \<circ> extract_int)"
using dens''[unfolded o_def]
apply (subst density_embed_measure', simp, simp add: extract_int_def)
apply (erule has_densityD, simp add: o_def)
done
finally show "N = density (stock_measure INTEG) (g (\<lambda>x. \<delta> (IntVal x)) \<circ> extract_int)"
by (simp add: embed_measure_count_space)
from dens''[unfolded o_def]
show "g (\<lambda>x. \<delta> (IntVal x)) \<circ> extract_int \<in> borel_measurable (stock_measure INTEG)"
by (simp add: embed_measure_count_space)
fix x assume "x \<in> space (stock_measure INTEG)"
thus "(g (\<lambda>x. \<delta> (IntVal x)) \<circ> extract_int) x \<ge> 0" unfolding o_def
by (intro has_densityD(2)[OF dens''[unfolded o_def]]) auto
qed (subst space_stock_measure, simp)
lemma measurable_extract_real_pair[measurable]:
"extract_real_pair \<in> borel_measurable (stock_measure (PRODUCT REAL REAL))"
proof-
let ?f = "\<lambda>x. (extract_real (fst (extract_pair x)), extract_real (snd (extract_pair x)))"
have "?f \<in> borel_measurable (stock_measure (PRODUCT REAL REAL))" by simp
also have "?f \<in> borel_measurable (stock_measure (PRODUCT REAL REAL)) \<longleftrightarrow>
extract_real_pair \<in> borel_measurable (stock_measure (PRODUCT REAL REAL))"
by (intro measurable_cong)
(auto simp: extract_real_pair_def space_embed_measure
space_pair_measure extract_real_def extract_pair_def)
finally show ?thesis .
qed
lemma distr_lift_RealPairVal:
fixes f f' g
assumes Mf: "split f \<in> borel_measurable borel"
assumes pdens: "has_subprob_density M (stock_measure (PRODUCT REAL REAL)) \<delta>"
assumes dens': "\<And>M \<delta>. has_subprob_density M lborel \<delta> \<Longrightarrow> has_density (distr M borel (split f)) lborel (g \<delta>)"
defines "N \<equiv> distr M (stock_measure REAL) (lift_RealIntVal2 f' f)"
shows "has_density N (stock_measure REAL) (g (\<lambda>x. \<delta> (RealPairVal x)) \<circ> extract_real)"
proof (rule has_densityI)
from assms(2) have dens: "has_density M (stock_measure (PRODUCT REAL REAL)) \<delta>"
unfolding has_subprob_density_def by simp
have sets_M: "sets M = sets (stock_measure (PRODUCT REAL REAL))"
by (auto simp: has_subprob_densityD[OF pdens])
hence [simp]: "space M = space (stock_measure (PRODUCT REAL REAL))"
by (rule sets_eq_imp_space_eq)
have meas_M[simp]: "measurable M = measurable (stock_measure (PRODUCT REAL REAL))"
by (intro ext measurable_cong_sets) (simp_all add: sets_M)
have MRV: "RealVal \<in> measurable borel (embed_measure lborel RealVal)"
by (subst measurable_lborel2[symmetric], rule measurable_embed_measure2) simp
have "N = distr M (stock_measure REAL) (lift_RealIntVal2 f' f)" by (simp add: N_def)
also have "... = distr M (stock_measure REAL) (RealVal \<circ> split f \<circ> extract_real_pair)"
by (intro distr_cong) (auto simp: lift_RealIntVal2_def extract_real_pair_def
space_embed_measure space_pair_measure)
also have "... = distr (distr (distr M lborel extract_real_pair) borel (split f))
(stock_measure REAL) RealVal"
apply (subst distr_distr[symmetric], intro measurable_comp, rule assms(1), simp add: MRV)
apply (subst meas_M, rule measurable_extract_real_pair)
apply (subst distr_distr[symmetric], subst stock_measure.simps, rule MRV,
simp_all add: assms(1) cong: distr_cong)
done
also have dens'': "has_density (distr (distr M lborel extract_real_pair) borel (split f)) lborel
(g (\<delta> \<circ> RealPairVal))" using inj_RealPairVal embed_measure_RealPairVal
by (intro dens' has_subprob_density_embed_measure'')
(insert pdens, simp_all add: extract_real_pair_def RealPairVal_def split: prod.split)
hence "distr (distr M lborel extract_real_pair) borel (split f) =
density lborel (g (\<delta> \<circ> RealPairVal))" by (rule has_densityD)
also have "distr ... (stock_measure REAL) RealVal = embed_measure ... RealVal" (is "_ = ?M")
by (subst embed_measure_eq_distr[OF inj_RealVal], intro distr_cong)
(simp_all add: sets_embed_measure)
also have "... = density (embed_measure lborel RealVal) (g (\<lambda>x. \<delta> (RealPairVal x)) \<circ> extract_real)"
using dens''[unfolded o_def]
by (subst density_embed_measure', simp, simp add: extract_real_def)
(erule has_densityD, simp add: o_def)
finally show "N = density (stock_measure REAL) (g (\<lambda>x. \<delta> (RealPairVal x)) \<circ> extract_real)" by simp
from dens''[unfolded o_def]
show "g (\<lambda>x. \<delta> (RealPairVal x)) \<circ> extract_real \<in> borel_measurable (stock_measure REAL)"
by (intro measurable_comp, subst stock_measure.simps)
(rule measurable_extract_real, subst measurable_lborel2[symmetric], erule has_densityD)
fix x assume "x \<in> space (stock_measure REAL)"
thus "(g (\<lambda>x. \<delta> (RealPairVal x)) \<circ> extract_real) x \<ge> 0" unfolding o_def
by (intro has_densityD(2)[OF dens''[unfolded o_def]]) auto
qed (subst space_stock_measure, simp)
lemma distr_lift_IntPairVal:
fixes f f'
assumes pdens: "has_density M (stock_measure (PRODUCT INTEG INTEG)) \<delta>"
assumes dens': "\<And>M \<delta>. has_density M (count_space UNIV) \<delta> \<Longrightarrow>
has_density (distr M (count_space UNIV) (split f))
(count_space UNIV) (g \<delta>)"
defines "N \<equiv> distr M (stock_measure INTEG) (lift_RealIntVal2 f f')"
shows "has_density N (stock_measure INTEG) (g (\<lambda>x. \<delta> (IntPairVal x)) \<circ> extract_int)"
proof (rule has_densityI)
let ?R = "count_space UNIV" and ?S = "count_space (range IntVal)"
and ?T = "count_space (range IntPairVal)" and ?tp = "PRODUCT INTEG INTEG"
have Mf: "f \<in> measurable ?R ?R" by simp
have MIV: "IntVal \<in> measurable ?R ?S" by simp
from assms(1) have dens: "has_density M (stock_measure ?tp) \<delta>"
unfolding has_subprob_density_def by simp
from dens have "M = density (stock_measure ?tp) \<delta>" by (rule has_densityD)
hence sets_M: "sets M = sets ?T" by (subst embed_measure_IntPairVal[symmetric]) auto
hence [simp]: "space M = space ?T" by (rule sets_eq_imp_space_eq)
from sets_M have [simp]: "measurable M = measurable (count_space (range IntPairVal))"
by (intro ext measurable_cong_sets) simp_all
have "N = distr M (stock_measure INTEG) (lift_RealIntVal2 f f')" by (simp add: N_def)
also have "... = distr M (stock_measure INTEG) (IntVal \<circ> split f \<circ> extract_int_pair)"
by (intro distr_cong) (auto simp: lift_RealIntVal2_def extract_int_pair_def
space_embed_measure space_pair_measure IntPairVal_def)
also have "... = distr (distr (distr M (count_space UNIV) extract_int_pair)
(count_space UNIV) (split f)) (stock_measure INTEG) IntVal"
apply (subst distr_distr[of _ ?R, symmetric], simp, simp)
apply (subst distr_distr[symmetric], subst stock_measure.simps, rule MIV,
simp_all add: assms(1) cong: distr_cong)
done
also have dens'': "has_density (distr (distr M (count_space UNIV) extract_int_pair) ?R (split f)) ?R
(g (\<delta> \<circ> IntPairVal))" using inj_IntPairVal embed_measure_IntPairVal
by (intro dens' has_density_embed_measure'')
(insert dens, simp_all add: extract_int_def embed_measure_count_space
extract_int_pair_def IntPairVal_def split: prod.split)
hence "distr (distr M (count_space UNIV) extract_int_pair) ?R (split f) =
density ?R (g (\<delta> \<circ> IntPairVal))" by (rule has_densityD)
also have "distr ... (stock_measure INTEG) IntVal = embed_measure ... IntVal" (is "_ = ?M")
by (subst embed_measure_eq_distr[OF inj_IntVal], intro distr_cong)
(auto simp: sets_embed_measure subset_image_iff)
also have "... = density (embed_measure ?R IntVal) (g (\<lambda>x. \<delta> (IntPairVal x)) \<circ> extract_int)"
using dens''[unfolded o_def]
by (subst density_embed_measure', simp, simp add: extract_int_def)
(erule has_densityD, simp add: o_def)
finally show "N = density (stock_measure INTEG) (g (\<lambda>x. \<delta> (IntPairVal x)) \<circ> extract_int)"
by (simp add: embed_measure_count_space)
from dens''[unfolded o_def]
show "g (\<lambda>x. \<delta> (IntPairVal x)) \<circ> extract_int \<in> borel_measurable (stock_measure INTEG)"
by (simp add: embed_measure_count_space)
fix x assume "x \<in> space (stock_measure INTEG)"
thus "(g (\<lambda>x. \<delta> (IntPairVal x)) \<circ> extract_int) x \<ge> 0" unfolding o_def
by (intro has_densityD(2)[OF dens''[unfolded o_def]]) auto
qed (subst space_stock_measure, simp)
end
|
theory T185
imports Main
begin
lemma "(
(\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) &
(\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) &
(\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) &
(\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) &
(\<forall> x::nat. invo(invo(x)) = x)
) \<longrightarrow>
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z)))
"
nitpick[card nat=7,timeout=86400]
oops
end |
using Halide
using Test
@testset "Halide.jl" begin
# Write your tests here.
end
|
Formal statement is: corollary\<^marker>\<open>tag unimportant\<close> independent_card_le: fixes S :: "'a::euclidean_space set" assumes "independent S" shows "card S \<le> DIM('a)" Informal statement is: If $S$ is a set of linearly independent vectors in $\mathbb{R}^n$, then $|S| \leq n$. |
lemma upd_inj: "i < n \<Longrightarrow> j < n \<Longrightarrow> upd i = upd j \<longleftrightarrow> i = j" |
(* Author: Tobias Nipkow *)
section \<open>Braun Trees\<close>
theory Braun_Tree
imports "HOL-Library.Tree_Real"
begin
text \<open>Braun Trees were studied by Braun and Rem~\<^cite>\<open>"BraunRem"\<close>
and later Hoogerwoord~\<^cite>\<open>"Hoogerwoord"\<close>.\<close>
fun braun :: "'a tree \<Rightarrow> bool" where
"braun Leaf = True" |
"braun (Node l x r) = ((size l = size r \<or> size l = size r + 1) \<and> braun l \<and> braun r)"
lemma braun_Node':
"braun (Node l x r) = (size r \<le> size l \<and> size l \<le> size r + 1 \<and> braun l \<and> braun r)"
by auto
text \<open>The shape of a Braun-tree is uniquely determined by its size:\<close>
lemma braun_unique: "\<lbrakk> braun (t1::unit tree); braun t2; size t1 = size t2 \<rbrakk> \<Longrightarrow> t1 = t2"
proof (induction t1 arbitrary: t2)
case Leaf thus ?case by simp
next
case (Node l1 _ r1)
from Node.prems(3) have "t2 \<noteq> Leaf" by auto
then obtain l2 x2 r2 where [simp]: "t2 = Node l2 x2 r2" by (meson neq_Leaf_iff)
with Node.prems have "size l1 = size l2 \<and> size r1 = size r2" by auto
thus ?case using Node.prems(1,2) Node.IH by auto
qed
text \<open>Braun trees are almost complete:\<close>
lemma acomplete_if_braun: "braun t \<Longrightarrow> acomplete t"
proof(induction t)
case Leaf show ?case by (simp add: acomplete_def)
next
case (Node l x r) thus ?case using acomplete_Node_if_wbal2 by force
qed
subsection \<open>Numbering Nodes\<close>
text \<open>We show that a tree is a Braun tree iff a parity-based
numbering (\<open>braun_indices\<close>) of nodes yields an interval of numbers.\<close>
fun braun_indices :: "'a tree \<Rightarrow> nat set" where
"braun_indices Leaf = {}" |
"braun_indices (Node l _ r) = {1} \<union> (*) 2 ` braun_indices l \<union> Suc ` (*) 2 ` braun_indices r"
lemma braun_indices1: "0 \<notin> braun_indices t"
by (induction t) auto
lemma finite_braun_indices: "finite(braun_indices t)"
by (induction t) auto
text "One direction:"
lemma braun_indices_if_braun: "braun t \<Longrightarrow> braun_indices t = {1..size t}"
proof(induction t)
case Leaf thus ?case by simp
next
have *: "(*) 2 ` {a..b} \<union> Suc ` (*) 2 ` {a..b} = {2*a..2*b+1}" (is "?l = ?r") for a b
proof
show "?l \<subseteq> ?r" by auto
next
have "\<exists>x2\<in>{a..b}. x \<in> {Suc (2*x2), 2*x2}" if *: "x \<in> {2*a .. 2*b+1}" for x
proof -
have "x div 2 \<in> {a..b}" using * by auto
moreover have "x \<in> {2 * (x div 2), Suc(2 * (x div 2))}" by auto
ultimately show ?thesis by blast
qed
thus "?r \<subseteq> ?l" by fastforce
qed
case (Node l x r)
hence "size l = size r \<or> size l = size r + 1" (is "?A \<or> ?B") by auto
thus ?case
proof
assume ?A
with Node show ?thesis by (auto simp: *)
next
assume ?B
with Node show ?thesis by (auto simp: * atLeastAtMostSuc_conv)
qed
qed
text "The other direction is more complicated. The following proof is due to Thomas Sewell."
lemma disj_evens_odds: "(*) 2 ` A \<inter> Suc ` (*) 2 ` B = {}"
using double_not_eq_Suc_double by auto
lemma card_braun_indices: "card (braun_indices t) = size t"
proof (induction t)
case Leaf thus ?case by simp
next
case Node
thus ?case
by(auto simp: UNION_singleton_eq_range finite_braun_indices card_Un_disjoint
card_insert_if disj_evens_odds card_image inj_on_def braun_indices1)
qed
lemma braun_indices_intvl_base_1:
assumes bi: "braun_indices t = {m..n}"
shows "{m..n} = {1..size t}"
proof (cases "t = Leaf")
case True then show ?thesis using bi by simp
next
case False
note eqs = eqset_imp_iff[OF bi]
from eqs[of 0] have 0: "0 < m"
by (simp add: braun_indices1)
from eqs[of 1] have 1: "m \<le> 1"
by (cases t; simp add: False)
from 0 1 have eq1: "m = 1" by simp
from card_braun_indices[of t] show ?thesis
by (simp add: bi eq1)
qed
lemma even_of_intvl_intvl:
fixes S :: "nat set"
assumes "S = {m..n} \<inter> {i. even i}"
shows "\<exists>m' n'. S = (\<lambda>i. i * 2) ` {m'..n'}"
apply (rule exI[where x="Suc m div 2"], rule exI[where x="n div 2"])
apply (fastforce simp add: assms mult.commute)
done
lemma odd_of_intvl_intvl:
fixes S :: "nat set"
assumes "S = {m..n} \<inter> {i. odd i}"
shows "\<exists>m' n'. S = Suc ` (\<lambda>i. i * 2) ` {m'..n'}"
proof -
have step1: "\<exists>m'. S = Suc ` ({m'..n - 1} \<inter> {i. even i})"
apply (rule_tac x="if n = 0 then 1 else m - 1" in exI)
apply (auto simp: assms image_def elim!: oddE)
done
thus ?thesis
by (metis even_of_intvl_intvl)
qed
lemma image_int_eq_image:
"(\<forall>i \<in> S. f i \<in> T) \<Longrightarrow> (f ` S) \<inter> T = f ` S"
"(\<forall>i \<in> S. f i \<notin> T) \<Longrightarrow> (f ` S) \<inter> T = {}"
by auto
lemma braun_indices1_le:
"i \<in> braun_indices t \<Longrightarrow> Suc 0 \<le> i"
using braun_indices1 not_less_eq_eq by blast
lemma braun_if_braun_indices: "braun_indices t = {1..size t} \<Longrightarrow> braun t"
proof(induction t)
case Leaf
then show ?case by simp
next
case (Node l x r)
obtain t where t: "t = Node l x r" by simp
from Node.prems have eq: "{2 .. size t} = (\<lambda>i. i * 2) ` braun_indices l \<union> Suc ` (\<lambda>i. i * 2) ` braun_indices r"
(is "?R = ?S \<union> ?T")
apply clarsimp
apply (drule_tac f="\<lambda>S. S \<inter> {2..}" in arg_cong)
apply (simp add: t mult.commute Int_Un_distrib2 image_int_eq_image braun_indices1_le)
done
then have ST: "?S = ?R \<inter> {i. even i}" "?T = ?R \<inter> {i. odd i}"
by (simp_all add: Int_Un_distrib2 image_int_eq_image)
from ST have l: "braun_indices l = {1 .. size l}"
by (fastforce dest: braun_indices_intvl_base_1 dest!: even_of_intvl_intvl
simp: mult.commute inj_image_eq_iff[OF inj_onI])
from ST have r: "braun_indices r = {1 .. size r}"
by (fastforce dest: braun_indices_intvl_base_1 dest!: odd_of_intvl_intvl
simp: mult.commute inj_image_eq_iff[OF inj_onI])
note STa = ST[THEN eqset_imp_iff, THEN iffD2]
note STb = STa[of "size t"] STa[of "size t - 1"]
then have sizes: "size l = size r \<or> size l = size r + 1"
apply (clarsimp simp: t l r inj_image_mem_iff[OF inj_onI])
apply (cases "even (size l)"; cases "even (size r)"; clarsimp elim!: oddE; fastforce)
done
from l r sizes show ?case
by (clarsimp simp: Node.IH)
qed
lemma braun_iff_braun_indices: "braun t \<longleftrightarrow> braun_indices t = {1..size t}"
using braun_if_braun_indices braun_indices_if_braun by blast
(* An older less appealing proof:
lemma Suc0_notin_double: "Suc 0 \<notin> ( * ) 2 ` A"
by(auto)
lemma zero_in_double_iff: "(0::nat) \<in> ( * ) 2 ` A \<longleftrightarrow> 0 \<in> A"
by(auto)
lemma Suc_in_Suc_image_iff: "Suc n \<in> Suc ` A \<longleftrightarrow> n \<in> A"
by(auto)
lemmas nat_in_image = Suc0_notin_double zero_in_double_iff Suc_in_Suc_image_iff
lemma disj_union_eq_iff:
"\<lbrakk> L1 \<inter> R2 = {}; L2 \<inter> R1 = {} \<rbrakk> \<Longrightarrow> L1 \<union> R1 = L2 \<union> R2 \<longleftrightarrow> L1 = L2 \<and> R1 = R2"
by blast
lemma inj_braun_indices: "braun_indices t1 = braun_indices t2 \<Longrightarrow> t1 = (t2::unit tree)"
proof(induction t1 arbitrary: t2)
case Leaf thus ?case using braun_indices.elims by blast
next
case (Node l1 x1 r1)
have "t2 \<noteq> Leaf"
proof
assume "t2 = Leaf"
with Node.prems show False by simp
qed
thus ?case using Node
by (auto simp: neq_Leaf_iff insert_ident nat_in_image braun_indices1
disj_union_eq_iff disj_evens_odds inj_image_eq_iff inj_def)
qed
text \<open>How many even/odd natural numbers are there between m and n?\<close>
lemma card_Icc_even_nat:
"card {i \<in> {m..n::nat}. even i} = (n+1-m + (m+1) mod 2) div 2" (is "?l m n = ?r m n")
proof(induction "n+1 - m" arbitrary: n m)
case 0 thus ?case by simp
next
case Suc
have "m \<le> n" using Suc(2) by arith
hence "{m..n} = insert m {m+1..n}" by auto
hence "?l m n = card {i \<in> insert m {m+1..n}. even i}" by simp
also have "\<dots> = ?r m n" (is "?l = ?r")
proof (cases)
assume "even m"
hence "{i \<in> insert m {m+1..n}. even i} = insert m {i \<in> {m+1..n}. even i}" by auto
hence "?l = card {i \<in> {m+1..n}. even i} + 1" by simp
also have "\<dots> = (n-m + (m+2) mod 2) div 2 + 1" using Suc(1)[of n "m+1"] Suc(2) by simp
also have "\<dots> = ?r" using \<open>even m\<close> \<open>m \<le> n\<close> by auto
finally show ?thesis .
next
assume "odd m"
hence "{i \<in> insert m {m+1..n}. even i} = {i \<in> {m+1..n}. even i}" by auto
hence "?l = card ..." by simp
also have "\<dots> = (n-m + (m+2) mod 2) div 2" using Suc(1)[of n "m+1"] Suc(2) by simp
also have "\<dots> = ?r" using \<open>odd m\<close> \<open>m \<le> n\<close> even_iff_mod_2_eq_zero[of m] by simp
finally show ?thesis .
qed
finally show ?case .
qed
lemma card_Icc_odd_nat: "card {i \<in> {m..n::nat}. odd i} = (n+1-m + m mod 2) div 2"
proof -
let ?A = "{i \<in> {m..n}. odd i}"
let ?B = "{i \<in> {m+1..n+1}. even i}"
have "card ?A = card (Suc ` ?A)" by (simp add: card_image)
also have "Suc ` ?A = ?B" using Suc_le_D by(force simp: image_iff)
also have "card ?B = (n+1-m + (m) mod 2) div 2"
using card_Icc_even_nat[of "m+1" "n+1"] by simp
finally show ?thesis .
qed
lemma compact_Icc_even: assumes "A = {i \<in> {m..n}. even i}"
shows "A = (\<lambda>j. 2*(j-1) + m + m mod 2) ` {1..card A}" (is "_ = ?A")
proof
let ?a = "(n+1-m + (m+1) mod 2) div 2"
have "\<exists>j \<in> {1..?a}. i = 2*(j-1) + m + m mod 2" if *: "i \<in> {m..n}" "even i" for i
proof -
let ?j = "(i - (m + m mod 2)) div 2 + 1"
have "?j \<in> {1..?a} \<and> i = 2*(?j-1) + m + m mod 2" using * by(auto simp: mod2_eq_if) presburger+
thus ?thesis by blast
qed
thus "A \<subseteq> ?A" using assms
by(auto simp: image_iff card_Icc_even_nat simp del: atLeastAtMost_iff)
next
let ?a = "(n+1-m + (m+1) mod 2) div 2"
have 1: "2 * (j - 1) + m + m mod 2 \<in> {m..n}" if *: "j \<in> {1..?a}" for j
using * by(auto simp: mod2_eq_if)
have 2: "even (2 * (j - 1) + m + m mod 2)" for j by presburger
show "?A \<subseteq> A"
apply(simp add: assms card_Icc_even_nat del: atLeastAtMost_iff One_nat_def)
using 1 2 by blast
qed
lemma compact_Icc_odd:
assumes "B = {i \<in> {m..n}. odd i}" shows "B = (\<lambda>i. 2*(i-1) + m + (m+1) mod 2) ` {1..card B}"
proof -
define A :: " nat set" where "A = Suc ` B"
have "A = {i \<in> {m+1..n+1}. even i}"
using Suc_le_D by(force simp add: A_def assms image_iff)
from compact_Icc_even[OF this]
have "A = Suc ` (\<lambda>i. 2 * (i - 1) + m + (m + 1) mod 2) ` {1..card A}"
by (simp add: image_comp o_def)
hence B: "B = (\<lambda>i. 2 * (i - 1) + m + (m + 1) mod 2) ` {1..card A}"
using A_def by (simp add: inj_image_eq_iff)
have "card A = card B" by (metis A_def bij_betw_Suc bij_betw_same_card)
with B show ?thesis by simp
qed
lemma even_odd_decomp: assumes "\<forall>x \<in> A. even x" "\<forall>x \<in> B. odd x" "A \<union> B = {m..n}"
shows "(let a = card A; b = card B in
a + b = n+1-m \<and>
A = (\<lambda>i. 2*(i-1) + m + m mod 2) ` {1..a} \<and>
B = (\<lambda>i. 2*(i-1) + m + (m+1) mod 2) ` {1..b} \<and>
(a = b \<or> a = b+1 \<and> even m \<or> a+1 = b \<and> odd m))"
proof -
let ?a = "card A" let ?b = "card B"
have "finite A \<and> finite B"
by (metis \<open>A \<union> B = {m..n}\<close> finite_Un finite_atLeastAtMost)
hence ab: "?a + ?b = Suc n - m"
by (metis Int_emptyI assms card_Un_disjoint card_atLeastAtMost)
have A: "A = {i \<in> {m..n}. even i}" using assms by auto
hence A': "A = (\<lambda>i. 2*(i-1) + m + m mod 2) ` {1..?a}" by(rule compact_Icc_even)
have B: "B = {i \<in> {m..n}. odd i}" using assms by auto
hence B': "B = (\<lambda>i. 2*(i-1) + m + (m+1) mod 2) ` {1..?b}" by(rule compact_Icc_odd)
have "?a = ?b \<or> ?a = ?b+1 \<and> even m \<or> ?a+1 = ?b \<and> odd m"
apply(simp add: Let_def mod2_eq_if
card_Icc_even_nat[of m n, simplified A[symmetric]]
card_Icc_odd_nat[of m n, simplified B[symmetric]] split!: if_splits)
by linarith
with ab A' B' show ?thesis by simp
qed
lemma braun_if_braun_indices: "braun_indices t = {1..size t} \<Longrightarrow> braun t"
proof(induction t)
case Leaf
then show ?case by simp
next
case (Node t1 x2 t2)
have 1: "i > 0 \<Longrightarrow> Suc(Suc(2 * (i - Suc 0))) = 2*i" for i::nat by(simp add: algebra_simps)
have 2: "i > 0 \<Longrightarrow> 2 * (i - Suc 0) + 3 = 2*i + 1" for i::nat by(simp add: algebra_simps)
have 3: "( * ) 2 ` braun_indices t1 \<union> Suc ` ( * ) 2 ` braun_indices t2 =
{2..size t1 + size t2 + 1}" using Node.prems
by (simp add: insert_ident Icc_eq_insert_lb_nat nat_in_image braun_indices1)
thus ?case using Node.IH even_odd_decomp[OF _ _ 3]
by(simp add: card_image inj_on_def card_braun_indices Let_def 1 2 inj_image_eq_iff image_comp
cong: image_cong_simp)
qed
*)
end |
open import Relation.Binary.PropositionalEquality using (_≡_; _≢_; refl)
open import Data.Fin using (Fin)
open import Data.Nat using (ℕ)
open import Data.Product using (_×_; _,_)
open import Data.Vec using (Vec; lookup; _[_]≔_)
open import Common
data Local (n : ℕ) : Set where
endL : Local n
sendSingle recvSingle : Fin n -> Label -> Local n -> Local n
private
variable
n : ℕ
p p′ q : Fin n
l l′ : Label
lSub lSub′ : Local n
endL≢sendSingle : ∀ { lSub } -> endL {n} ≢ sendSingle q l lSub
endL≢sendSingle ()
endL≢recvSingle : ∀ { lSub } -> endL {n} ≢ recvSingle q l lSub
endL≢recvSingle ()
sendSingle-injective :
sendSingle {n} p l lSub ≡ sendSingle p′ l′ lSub′
-> p ≡ p′ × l ≡ l′ × lSub ≡ lSub′
sendSingle-injective refl = refl , refl , refl
recvSingle-injective :
recvSingle {n} p l lSub ≡ recvSingle p′ l′ lSub′
-> p ≡ p′ × l ≡ l′ × lSub ≡ lSub′
recvSingle-injective refl = refl , refl , refl
Configuration : ℕ -> Set
Configuration n = Vec (Local n) n
data _-_→l_ {n : ℕ} : (Fin n × Local n) -> Action n -> (Fin n × Local n) -> Set where
→l-send :
∀ { lp lpSub }
-> (p : Fin n)
-> lp ≡ sendSingle q l lpSub
-> (p≢q : p ≢ q)
-> (p , lp) - (action p q p≢q l) →l (p , lpSub)
→l-recv :
∀ { lp lpSub }
-> (p : Fin n)
-> lp ≡ recvSingle q l lpSub
-> (q≢p : q ≢ p)
-> (p , lp) - (action q p q≢p l) →l (p , lpSub)
data _-_→c_ {n : ℕ} : Configuration n -> Action n -> Configuration n -> Set where
→c-comm :
∀ { lp lp′ lq lq′ c′ p≢q-p p≢q-q }
-> (c : Configuration n)
-> (p≢q : p ≢ q)
-> lp ≡ lookup c p
-> lq ≡ lookup c q
-> c′ ≡ c [ p ]≔ lp′ [ q ]≔ lq′
-> (p , lp) - (action p q p≢q-p l) →l (p , lp′)
-> (q , lq) - (action p q p≢q-q l) →l (q , lq′)
-> c - (action p q p≢q l) →c c′
|
module Collections.BSTree.Map.Core
import Collections.Util.Bnd
import Control.Relation
import Decidable.Order.Strict
||| A verified binary search tree with erased proofs.
|||
||| The keys in the tree are constrained by min/max bounds, which make use of `Bnd` to extend the
||| tree key type with `Top` and `Bot` values. This allows for a natural way to leave bounds
||| unconstrained (by having a minimum of `Bot` or a maximum of `Top`).
|||
||| @ ord The ordering implementations used in the tree. Since these are w.r.t. a type `kTy`, the
||| type of tree keys is defined implicitly by `ord`.
||| @ vTy The data type to carry in nodes in addition to the key type `kTy`.
||| @ mn The minimum value constraint, proving that `rel mn (Mid x)` for all values `x` in the
||| tree.
||| @ mx The maximum value constraint, proving that `rel (Mid x) mx` for all values `x` in the
||| tree.
public export
data BST : {0 rel : kTy -> kTy -> Type} ->
(pre : StrictPreorder kTy rel) ->
(tot : StrictOrdered kTy rel) ->
(0 vTy : Type) ->
(0 mn,mx : Bnd kTy) ->
Type where
||| An empty tree node.
|||
||| @ prf An ordering proof on the min and max constraints of this node. Since an in-order
||| traversal of a binary tree is an empty-node-empty-... alternation, storing ordering
||| information in the empty nodes is a natural way to store evidence that the nodes are in
||| order.
Empty : {pre : StrictPreorder kTy rel} ->
{tot : StrictOrdered kTy rel} ->
(0 prf : BndLT rel mn mx) ->
BST pre tot vTy mn mx
||| A node with a value and with left and right subtrees, each with appropriate bounds relative
||| to the key `k` of the node.
|||
||| @ k The key value of the node
||| @ v The data value of the node
||| @ l The left subtree
||| @ r The right subtree
Node : {0 rel : kTy -> kTy -> Type} ->
{pre : StrictPreorder kTy rel} ->
{tot : StrictOrdered kTy rel} ->
(k : kTy) ->
(v : vTy) ->
(l : BST pre tot vTy mn (Mid k)) ->
(r : BST pre tot vTy (Mid k) mx) ->
BST pre tot vTy mn mx
%name BST t,u,v
||| A verified binary search tree with erased proofs.
|||
||| This is an alias for the more generic `BST` (which accepts min/max bounds for its contents).
||| The bounds are necessary for verifying the structure of a tree, but the root node of any
||| `BST` will always be unconstrained. So generally, `BST` can be considered an implementation
||| detail.
|||
||| @ rel The strict total ordering used in the tree. Since a `StrictOrdered` impl is w.r.t. a type
||| `kTy`, the type of tree values is defined implicitly by `ord`.
||| @ vTy The type for values stored in nodes of the tree.
public export
BSTree : {0 kTy : Type} ->
(0 rel : kTy -> kTy -> Type) ->
{auto pre : StrictPreorder kTy rel} ->
{auto tot : StrictOrdered kTy rel} ->
(0 vTy : Type) ->
Type
BSTree rel {pre} {tot} vTy = BST pre tot vTy Bot Top
%name BSTree t,u,v
||| Proof that the minimum bound can be decreased arbitrarily.
public export
extendMin : {0 rel : kTy -> kTy -> Type} ->
{pre : StrictPreorder kTy rel} ->
{tot : StrictOrdered kTy rel} ->
(0 prf : BndLT rel mn' mn) ->
BST pre tot vTy mn mx ->
BST pre tot vTy mn' mx
extendMin {pre} prf (Empty prf') = Empty $ transitive {x=mn'} {y=mn} {z=mx} prf prf'
extendMin prf (Node k v l r) = Node k v (extendMin prf l) r
||| Proof that the maximum bound can be increased arbitrarily.
public export
extendMax : {0 rel : kTy -> kTy -> Type} ->
{pre : StrictPreorder kTy rel} ->
{tot : StrictOrdered kTy rel} ->
(0 prf : BndLT rel mx mx') ->
BST pre tot vTy mn mx ->
BST pre tot vTy mn mx'
extendMax {pre} prf (Empty prf') = Empty $ transitive {x=mn} {y=mx} {z=mx'} prf' prf
extendMax prf (Node k v l r) = Node k v l (extendMax prf r)
|
(*
* Copyright 2018, Data61
* Commonwealth Scientific and Industrial Research Organisation (CSIRO)
* ABN 41 687 119 230.
*
* This software may be distributed and modified according to the terms of
* the BSD 2-Clause license. Note that NO WARRANTY is provided.
* See "LICENSE_BSD2.txt" for details.
*
* @TAG(DATA61_BSD)
*)
theory Specialised_Lemma_Utils
imports Utils
begin
text\<open> This theory file contains utility functions that are specific to the generation and proof of
the specialised lemmas.
\<close>
ML\<open> datatype bucket =
TakeBoxed
| TakeUnboxed
| PutBoxed
| LetPutBoxed
| PutUnboxed
| MemberBoxed
| MemberReadOnly
| TagDef
| Esac
| Case
| ValRelSimp
| IsValidSimp
| TypeRelSimp
| HeapSimp \<close>
ML\<open> fun bucket_to_string bucket = case bucket of
TakeBoxed => "TakeBoxed"
| TakeUnboxed => "TakeUnboxed"
| PutBoxed => "PutBoxed"
| LetPutBoxed => "LetPutBoxed"
| PutUnboxed => "PutUnboxed"
| MemberBoxed => "MemberBoxed"
| MemberReadOnly => "MemberReadOnly"
| TagDef => "TagDef"
| Esac => "Esac"
| Case => "Case"
| ValRelSimp => "ValRelSimp"
| IsValidSimp => "IsValidSimp"
| TypeRelSimp => "TypeRelSimp"
| HeapSimp => "HeapSimp"
\<close>
ML\<open> structure Unborn_Thms = Proof_Data
(* Unborn_Thms is a list of thm-names which I tried to prove but failed to do so.
* Note that I do not include thm-names if I tried to cheat.*)
(type T = string list;
fun init _ = [];)
\<close>
ML\<open> fun add_unborns unborn_thm = Unborn_Thms.map (fn unborn_thms => unborn_thm::unborn_thms); \<close>
text\<open> Lemma buckets. \<close>
ML \<open> structure TakeBoxed = Named_Thms_Ext
(val name = @{binding "TakeBoxed"}
val description = "Theorems for boxed takes.") \<close>
ML \<open> structure TakeUnboxed = Named_Thms_Ext
(val name = @{binding "TakeUnboxed"}
val description = "Theorems for unboxed takes.") \<close>
ML \<open> structure PutBoxed = Named_Thms_Ext
(val name = @{binding "PutBoxed"}
val description = "Theorems for boxed puts.") \<close>
ML \<open> structure LetPutBoxed = Named_Thms_Ext
(val name = @{binding "LetPutBoxed"}
val description = "Theorems for boxed let-puts.") \<close>
ML \<open> structure PutUnboxed = Named_Thms_Ext
(val name = @{binding "PutUnboxed"}
val description = "Theorems for unboxed puts.") \<close>
ML \<open> structure MemberReadOnly = Named_Thms_Ext
(val name = @{binding "MemberReadOnly"}
val description = "Theorems for read-only member.") \<close>
ML \<open> structure MemberBoxed = Named_Thms_Ext
(val name = @{binding "MemberBoxed"}
val description = "Theorems for boxed member.") \<close>
ML \<open> structure Case = Named_Thms_Ext
(val name = @{binding "Case"}
val description = "Theorems for case.") \<close>
ML \<open> structure ValRelSimp = Named_Thms_Ext
(val name = @{binding "ValRelSimp"}
val description = "Simplification rules about value relation.") \<close>
ML \<open> structure IsValidSimp = Named_Thms_Ext
(val name = @{binding "IsValidSimp"}
val description = "Simplification rules about is_valid.") \<close>
ML \<open> structure TypeRelSimp = Named_Thms_Ext
(val name = @{binding "TypeRelSimp"}
val description = "Simplification rules about type relation.") \<close>
ML \<open> structure HeapSimp = Named_Thms_Ext
(val name = @{binding "HeapSimp"}
val description = "Simplification rules about heap relation.") \<close>
setup\<open> (* Set up lemma buckets.*)
TakeBoxed.setup o TakeUnboxed.setup o PutUnboxed.setup o PutBoxed.setup o
MemberReadOnly.setup o MemberBoxed.setup o Case.setup o
ValRelSimp.setup o IsValidSimp.setup o
TypeRelSimp.setup o HeapSimp.setup \<close>
ML\<open> fun local_setup_add_thm bucket thm = case bucket of
TakeBoxed => TakeBoxed.add_local thm
| TakeUnboxed => TakeUnboxed.add_local thm
| PutBoxed => PutBoxed.add_local thm
| LetPutBoxed => LetPutBoxed.add_local thm
| PutUnboxed => PutUnboxed.add_local thm
| MemberBoxed => MemberBoxed.add_local thm
| MemberReadOnly=> MemberReadOnly.add_local thm
| ValRelSimp => ValRelSimp.add_local thm
| IsValidSimp => IsValidSimp.add_local thm
| TypeRelSimp => TypeRelSimp.add_local thm
| HeapSimp => HeapSimp.add_local thm
| Case => Case.add_local thm
| _ => error "add_thm in Value_Relation_Generation.thy failed."
\<close>
ML\<open> fun setup_add_thm bucket thm = case bucket of
TakeBoxed => TakeBoxed.add_thm thm |> Context.theory_map
| TakeUnboxed => TakeUnboxed.add_thm thm |> Context.theory_map
| PutBoxed => PutBoxed.add_thm thm |> Context.theory_map
| LetPutBoxed => LetPutBoxed.add_thm thm |> Context.theory_map
| PutUnboxed => PutUnboxed.add_thm thm |> Context.theory_map
| MemberBoxed => MemberBoxed.add_thm thm |> Context.theory_map
| MemberReadOnly=> MemberReadOnly.add_thm thm |> Context.theory_map
| Case => Case.add_thm thm |> Context.theory_map
| ValRelSimp => ValRelSimp.add_thm thm |> Context.theory_map
| IsValidSimp => IsValidSimp.add_thm thm |> Context.theory_map
| TypeRelSimp => TypeRelSimp.add_thm thm |> Context.theory_map
| HeapSimp => HeapSimp.add_thm thm |> Context.theory_map
| _ => error "add_thm in SpecialisedLemmaForTakePut.thy failed."
\<close>
ML\<open> val local_setup_put_lemmas_in_bucket =
let
fun note (name:string) (getter) lthy = Local_Theory.note ((Binding.make (name, @{here}), []), getter lthy) lthy |> snd;
in
note "type_rel_simp" TypeRelSimp.get #>
note "val_rel_simp" ValRelSimp.get #>
note "take_boxed" TakeBoxed.get #>
note "take_unboxed" TakeUnboxed.get #>
note "put_boxed" PutBoxed.get #>
note "let_put_boxed" LetPutBoxed.get #>
note "put_unboxed" PutUnboxed.get #>
note "member_boxed" MemberBoxed.get #>
note "member_readonly" MemberReadOnly.get #>
note "case" Case.get #>
note "is_valid_simp" IsValidSimp.get #>
note "heap_simp" HeapSimp.get
end;
\<close>
ML\<open> type lem = { name: string, bucket: bucket, prop: term, mk_tactic: Proof.context -> tactic }; \<close>
ML\<open> val cheat_specialised_lemmas =
Attrib.setup_config_bool @{binding "cheat_specialised_lemmas"} (K false);
\<close>
(* An example to show how to manupulate this flag.*)
declare [[ cheat_specialised_lemmas = false ]]
ML\<open> (* type definition on the ML-level.*)
datatype sigil = ReadOnly | Writable | Unboxed
datatype uval = UProduct of string
| USum of string * term (* term contains argument to TSum (excluding TSum itself) *)
| URecord of string * sigil
| UAbstract of string;
;
type uvals = uval list;\<close>
ML\<open> (* unify_sigils to remove certain kind of duplication.*)
fun unify_sigils (URecord (ty_name,_)) = URecord (ty_name,Writable)
| unify_sigils uval = uval
(* value-relations and type-relations are independent of sigils.
* If we have multiple uvals with different sigils but with the same type and name,
* we should count them as one to avoid trying to instantiate the same thing multiple times.*)
\<close>
ML\<open> (* unify_usum_tys *)
fun unify_usum_tys (USum (ty_name,_)) = USum (ty_name, Term.dummy)
| unify_usum_tys uval = uval
\<close>
ML\<open> (* unify_uabstract *)
fun unify_uabstract (UAbstract _) = UAbstract "dummy"
| unify_uabstract uval = uval;
\<close>
ML\<open> (* get_usums, get_uproducts, get_urecords *)
fun get_usums uvals = filter (fn uval => case uval of (USum _) => true | _ => false) uvals
fun get_uproducts uvals = filter (fn uval => case uval of (UProduct _) => true | _ => false) uvals
fun get_urecords uvals = filter (fn uval => case uval of (URecord _) => true | _ => false) uvals
\<close>
ML\<open> (* get_uval_name *)
fun get_uval_name (URecord (ty_name, _)) = ty_name
| get_uval_name (USum (ty_name, _)) = ty_name
| get_uval_name (UProduct ty_name) = ty_name
| get_uval_name (UAbstract ty_name) = ty_name
\<close>
ML\<open> fun get_uval_names uvals = map get_uval_name uvals;\<close>
ML\<open> (* get_uval_sigil *)
fun get_uval_sigil (URecord (_, sigil)) = sigil
| get_uval_sigil _ = error "get_uval_sigil failed. The tyep of this argument is not URecord."
\<close>
ML\<open> val get_uval_writable_records =
filter (fn uval => case uval of (URecord (_, Writable)) => true | _ => false);
\<close>
ML\<open> val get_uval_unbox_records =
filter (fn uval => case uval of (URecord (_, Unboxed)) => true | _ => false);
\<close>
ML\<open> val get_uval_readonly_records =
filter (fn uval => case uval of (URecord (_, ReadOnly)) => true | _ => false);
\<close>
ML\<open> fun usum_list_of_types _ uval = case uval of
USum (_, variants) => HOLogic.dest_list variants
| _ => error ("usum_list_of_types: not USum")
\<close>
ML\<open> fun is_UAbstract (UAbstract _) = true
| is_UAbstract _ = false;
\<close>
ML\<open> fun get_ty_nm_C uval = uval |> get_uval_name |> (fn nm => nm ^ "_C"); \<close>
ML\<open> fun heap_info_uval_to_struct_info (heap:HeapLiftBase.heap_info) (uval:uval) =
let
val uval_C_nm = get_uval_name uval ^ "_C";
in
Symtab.lookup (#structs heap) uval_C_nm
|> Utils.the' ("This heap_info does not have structs." ^ uval_C_nm)
end : HeapLiftBase.struct_info;
\<close>
ML\<open> fun heap_info_uval_to_field_names heap_info uval =
heap_info_uval_to_struct_info heap_info uval |> #field_info |> map #name;
\<close>
ML\<open> fun heap_info_uval_to_field_types heap_info uval =
heap_info_uval_to_struct_info heap_info uval |> #field_info |> map #field_type;
\<close>
text\<open> The functions related to AutoCorres.\<close>
ML\<open> fun ac_mk_struct_info_for file_nm thy uval =
(* checks if autocorres generates struct_info for a given uval. Returns a boolean value.*)
let
val st_C_nm = get_ty_nm_C uval;
val heap_info = Symtab.lookup (HeapInfo.get thy) file_nm
|> Utils.the' "heap_info in ac_mk_struct_info_for failed."
|> #heap_info;
val flag = Symtab.lookup (#structs heap_info) st_C_nm |> is_some;
in flag end;
\<close>
ML\<open> fun get_uvals_for_which_ac_mk_st_info file_nm thy uvals =
(* returns a list of uvals for which autocorres creates struct info.*)
filter (ac_mk_struct_info_for file_nm thy) uvals;
\<close>
ML\<open> fun get_uvals_for_which_ac_mk_heap_getters file_nm thy uvals =
(* returns a list of uvals for which autocorres creates #heap_getters info.*)
filter (fn uval => ac_mk_heap_getters_for file_nm thy (get_ty_nm_C uval)) uvals;
\<close>
end
|
[GOAL]
R : Type u
inst✝¹ : Semiring R
inst✝ : Nontrivial R
⊢ #(AddMonoidAlgebra R ℕ) = max #R ℵ₀
[PROOFSTEP]
rw [AddMonoidAlgebra, mk_finsupp_lift_of_infinite, lift_uzero, max_comm]
[GOAL]
R : Type u
inst✝¹ : Semiring R
inst✝ : Nontrivial R
⊢ max (#R) (lift #ℕ) = max #R ℵ₀
[PROOFSTEP]
rfl
[GOAL]
R : Type u
inst✝ : Semiring R
⊢ #R[X] ≤ max #R ℵ₀
[PROOFSTEP]
cases subsingleton_or_nontrivial R
[GOAL]
case inl
R : Type u
inst✝ : Semiring R
h✝ : Subsingleton R
⊢ #R[X] ≤ max #R ℵ₀
[PROOFSTEP]
exact (mk_eq_one _).trans_le (le_max_of_le_right one_le_aleph0)
[GOAL]
case inr
R : Type u
inst✝ : Semiring R
h✝ : Nontrivial R
⊢ #R[X] ≤ max #R ℵ₀
[PROOFSTEP]
exact cardinal_mk_eq_max.le
|
[STATEMENT]
lemma edge_density_commute: "edge_density X Y = edge_density Y X"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. edge_density X Y = edge_density Y X
[PROOF STEP]
by (simp add: edge_density_def card_all_edges_between_commute mult.commute) |
{-# OPTIONS --cubical --safe #-}
module Lens where
open import Lens.Definition public
open import Lens.Operators public
open import Lens.Composition public
open import Lens.Pair public
|
\documentclass{subfile}
\begin{document}
\section{VNO}\label{sec:vno}
\end{document} |
\input{preamble}
\begin{document}
%==[ TITLE PAGE ]===============================================================
\thispagestyle{empty}
\noindent
\resizebox{\linewidth}{!}{\scshape CoDi}\\[0.62em]
\resizebox{\linewidth}{!}{\scshape Commutative Diagrams for \TeX}\\[1.62em]
\resizebox{\linewidth}{!}{\scshape enchiridion}\par
\vfill
\marginpar{
\resizebox{\linewidth}{!}{\scshape <<VERSION>>}\\[0.62em]
\resizebox{\linewidth}{!}{\scshape \today}
}
%==[ FOREWORD ]=================================================================
\newpage
\begin{adjustwidth}{.47\textwidth-\marginparwidth-\marginparsep}{.47\textwidth}
\noindent\CoDi\ is a \TikZ\ library. Its aim is\linebreak
making commutative diagrams\linebreak
easy to design, parse and tweak.\par
\end{adjustwidth}
\newpage
\section{Preliminaries}
\input{preliminaries}
\newpage
\section{Quick tour}
\input{quick-tour}
\newpage
\section{Alternatives}
\input{alternatives}
\newpage
\section{Syntax: objects}
\input{syntax-objects}
\newpage
\section{Syntax: morphisms}
\input{syntax-morphisms}
\newpage
\section{Names}
\input{names}
\newpage
\subsection{Names: shortcuts}
\input{names-shortcuts}
\newpage
\subsection{Names: expansion}
\input{names-expansion}
\newpage
\subsection{Names: replacement}
\input{names-replacement}
\newpage
\subsection{Names: overwriting}
\input{names-overwriting}
\newpage
\section{Styles: scopes}
\input{styles-scopes}
\newpage
\section{Styles: diagrams}
\input{styles-diagrams}
\newpage
\section{Styles: layouts}
\input{styles-layouts}
\newpage
\section{Styles: objects}
\input{styles-objects}
\newpage
\section{Styles: arrows}
\input{styles-arrows}
\newpage
\section{Styles: labels}
\input{styles-labels}
\newpage
\section{Gallery}
\input{gallery}
% \input{test}
\end{document}
|
theory T185
imports Main
begin
lemma "(
(\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) &
(\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) &
(\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) &
(\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) &
(\<forall> x::nat. invo(invo(x)) = x)
) \<longrightarrow>
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z)))
"
nitpick[card nat=10,timeout=86400]
oops
end |
(* This Isabelle theory is produced using the TIP tool offered at the following website:
https://github.com/tip-org/tools
This file was originally provided as part of TIP benchmark at the following website:
https://github.com/tip-org/benchmarks
Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly
to make it compatible with Isabelle2017.*)
theory TIP_int_add_ident_right
imports "../../Test_Base"
begin
datatype Nat = Z | S "Nat"
datatype Integer = P "Nat" | N "Nat"
definition(*fun*) zero :: "Integer" where
"zero = P Z"
fun pred :: "Nat => Nat" where
"pred (S y) = y"
fun plus2 :: "Nat => Nat => Nat" where
"plus2 (Z) y = y"
| "plus2 (S z) y = S (plus2 z y)"
fun t2 :: "Nat => Nat => Integer" where
"t2 x y =
(let fail :: Integer =
(case y of
Z => P x
| S z =>
(case x of
Z => N y
| S x2 => t2 x2 z))
in (case x of
Z =>
(case y of
Z => P Z
| S x4 => fail)
| S x3 => fail))"
fun plus :: "Integer => Integer => Integer" where
"plus (P m) (P n) = P (plus2 m n)"
| "plus (P m) (N o2) = t2 m (plus2 (S Z) o2)"
| "plus (N m2) (P n2) = t2 n2 (plus2 (S Z) m2)"
| "plus (N m2) (N n3) = N (plus2 (plus2 (S Z) m2) n3)"
theorem property0 :
"(x = (plus x zero))"
oops
end
|
library("testthat");
source("../equalSizedBins.r");
# q1 == minX and q2 == minXX
x1Binned = equalSizedBins(rbind(1,1,1,1,1,2,2,2,3,3));
expect_equal(x1Binned, rbind(0,0,0,0,0,1,1,1,2,2));
# q1 == minX and q2 == maxXX
x1Binned = equalSizedBins(rbind(1,1,1,1,1,2,2,3,3,3));
expect_equal(x1Binned, rbind(0,0,0,0,0,1,1,2,2,2));
# q1 == minX and normal split
x1Binned = equalSizedBins(rbind(1,1,1,1,1,2,3,4,5,6));
expect_equal(x1Binned, rbind(0,0,0,0,0,1,1,2,2,2));
# q3 == maxX and q1 == minXX
x1Binned = equalSizedBins(rbind(1,1,1,2,2,3,3,3,3,3));
expect_equal(x1Binned, rbind(0,0,0,1,1,2,2,2,2,2));
# q3 == maxX and q1 == maxXX
x1Binned = equalSizedBins(rbind(1,1,2,2,2,3,3,3,3,3));
expect_equal(x1Binned, rbind(0,0,1,1,1,2,2,2,2,2));
# q3 == maxX and q1 == maxXX
x1Binned = equalSizedBins(rbind(1,2,3,4,5,6,6,6,6,6));
expect_equal(x1Binned, rbind(0,0,1,1,1,2,2,2,2,2));
# q1==q2
x1Binned = equalSizedBins(rbind(1,2,2,2,2,2,2,2,2,3));
expect_equal(x1Binned, rbind(0,1,1,1,1,1,1,1,1,2));
# main case - nicely separates into 3 bins
x1Binned = equalSizedBins(rbind(1,2,3,4,5,6,7,8,9,10));
expect_equal(x1Binned, rbind(0,0,0,1,1,1,2,2,2,2));
|
Formal statement is: lemma open_path_connected_component: fixes S :: "'a :: real_normed_vector set" shows "open S \<Longrightarrow> path_component S x = connected_component S x" Informal statement is: If $S$ is an open set, then the path component of $x$ in $S$ is the same as the connected component of $x$ in $S$. |
import codecs
import numpy
from scipy.sparse import csr_matrix, save_npz
#6880 unknown
words = []
with codecs.open('../plain/actor_dic.utf8', 'r', encoding='utf8') as fa:
lines = fa.readlines()
lines = [line.strip() for line in lines]
words.extend(lines)
rxwdict = dict(zip(words,range(1, 1+len(words))))
rxwdict['。'] = 0
oov = []
dims=11
embedding_matrix = numpy.zeros((len(words)+1, int(dims)))
with codecs.open('weibo_nactors.csv', 'r', encoding='utf8') as ff:
lines = ff.readlines()
lines = [line.strip() for line in lines]
for line in lines:
if 'verifyName' in line:
continue
word, coefs = line.split(',', maxsplit=1)
if word in rxwdict.keys():
embedding_matrix[rxwdict[word]] = numpy.fromstring(coefs, 'f', sep=',')
else:
npy = numpy.fromstring(coefs, 'f', sep=',')
assert len(npy) == dims, (len(npy), word, npy)
oov.append(npy)
# print('mean:', len(oov))
# mean = numpy.mean(oov)
print(embedding_matrix.shape)
zeroind = numpy.where(~embedding_matrix.any(axis=1))[0]
print(zeroind)
# embedding_matrix[zeroind] = mean
# normalize
embedding_matrix = embedding_matrix/embedding_matrix.max(axis=0)
sparsem = csr_matrix(embedding_matrix)
save_npz("weibo_wembedding.npz", matrix=sparsem)
zeroind = numpy.where(~embedding_matrix.any(axis=1))[0]
print(zeroind) |
-- Razonamiento ecuacional sobre intercambio en pares
-- ==================================================
import data.prod
open prod
variables {α : Type*} {β : Type*}
variable (x : α)
variable (y : β)
-- ----------------------------------------------------
-- Ejercicio 1. Definir la función
-- intercambia :: α × β → β × α
-- tal que (intercambia p) es el par obtenido
-- intercambiando las componentes del par p. Por
-- ejemplo,
-- intercambia (5,7) = (7,5)
-- ----------------------------------------------------
def intercambia : α × β → β × α
| (x,y) := (y, x)
-- #eval intercambia (5,7)
-- ----------------------------------------------------
-- Ejercicio 2. Demostrar el lema
-- intercambia_simp : intercambia p = (p.2, p.1)
-- ----------------------------------------------------
@[simp]
lemma intercambia_simp :
intercambia (x,y) = (y,x) :=
rfl
-- ----------------------------------------------------
-- Ejercicio 3. (p.6) Demostrar que
-- intercambia (intercambia (x,y)) = (x,y)
-- ----------------------------------------------------
-- 1ª demostración
example :
intercambia (intercambia (x,y)) = (x,y) :=
calc intercambia (intercambia (x,y))
= intercambia (y,x) : by rw intercambia_simp
... = (x,y) : by rw intercambia_simp
-- 2ª demostración
example :
intercambia (intercambia (x,y)) = (x,y) :=
calc intercambia (intercambia (x,y))
= intercambia (y,x) : by simp
... = (x,y) : by simp
-- 3ª demostración
example :
intercambia (intercambia (x,y)) = (x,y) :=
by simp
-- 4ª demostración
example :
intercambia (intercambia (x,y)) = (x,y) :=
rfl
-- 5ª demostración
example :
intercambia (intercambia (x,y)) = (x,y) :=
begin
rw intercambia_simp,
rw intercambia_simp,
end
-- Comentarios sobre la función swap:
-- + Es equivalente a la función intercambia.
-- + Para usarla hay que importar la librería data.prod
-- y abrir espacio de nombre prod el escribiendo al
-- principio del fichero
-- import data.prod
-- open prod
-- + Se puede evaluar. Por ejemplo,
-- #eval swap (5,7)
-- + Se puede demostrar. Por ejemplo,
-- example :
-- swap (swap (x,y)) = (x,y) :=
-- rfl
--
-- example :
-- swap (swap (x,y)) = (x,y) :=
-- -- by library_search
-- swap_swap (x,y)
|
[STATEMENT]
lemma le_Limsup:
assumes F: "F \<noteq> bot" and x: "\<forall>\<^sub>F x in F. l \<le> f x"
shows "l \<le> Limsup F f"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. l \<le> Limsup F f
[PROOF STEP]
using F Liminf_bounded[of l f F] Liminf_le_Limsup[of F f] order.trans x
[PROOF STATE]
proof (prove)
using this:
F \<noteq> bot
\<forall>\<^sub>F n in F. l \<le> f n \<Longrightarrow> l \<le> Liminf F f
F \<noteq> bot \<Longrightarrow> Liminf F f \<le> Limsup F f
\<lbrakk>?a \<le> ?b; ?b \<le> ?c\<rbrakk> \<Longrightarrow> ?a \<le> ?c
\<forall>\<^sub>F x in F. l \<le> f x
goal (1 subgoal):
1. l \<le> Limsup F f
[PROOF STEP]
by blast |
State Before: B : Type u
inst✝ : Bicategory B
a b c d e : B
f : a ⟶ b
g h : b ⟶ c
η : g ≅ h
⊢ f ◁ η.inv ≫ f ◁ η.hom = 𝟙 (f ≫ h) State After: no goals Tactic: rw [← whiskerLeft_comp, inv_hom_id, whiskerLeft_id] |
-- @@stderr --
dtrace: failed to compile script test/unittest/inline/err.D_DECL_IDRED.redef1.d: [D_DECL_IDRED] line 21: identifier redefined: foo
current: inline definition
previous: scalar inline
|
(* *********************************************************************)
(* *)
(* The Compcert verified compiler *)
(* *)
(* Xavier Leroy, INRIA Paris-Rocquencourt *)
(* *)
(* Copyright Institut National de Recherche en Informatique et en *)
(* Automatique. All rights reserved. This file is distributed *)
(* under the terms of the INRIA Non-Commercial License Agreement. *)
(* *)
(* *********************************************************************)
(** Typing rules for LTLin. *)
Require Import Coqlib.
Require Import Maps.
Require Import AST.
Require Import Integers.
Require Import Memdata.
Require Import Op.
Require Import RTL.
Require Import Locations.
Require Import LTLin.
Require LTLtyping.
Require Import Conventions.
(** The following predicates define a type system for LTLin similar to that
of LTL. *)
Section WT_INSTR.
Variable funsig: signature.
Inductive wt_instr : instruction -> Prop :=
| wt_Lopmove:
forall r1 r,
Loc.type r1 = Loc.type r -> loc_acceptable r1 -> loc_acceptable r ->
wt_instr (Lop Omove (r1 :: nil) r)
| wt_Lop:
forall op args res,
op <> Omove ->
(List.map Loc.type args, Loc.type res) = type_of_operation op ->
locs_acceptable args -> loc_acceptable res ->
wt_instr (Lop op args res)
| wt_Lload:
forall chunk addr args dst,
List.map Loc.type args = type_of_addressing addr ->
Loc.type dst = type_of_chunk chunk ->
locs_acceptable args -> loc_acceptable dst ->
wt_instr (Lload chunk addr args dst)
| wt_Lstore:
forall chunk addr args src,
List.map Loc.type args = type_of_addressing addr ->
Loc.type src = type_of_chunk chunk ->
locs_acceptable args -> loc_acceptable src ->
wt_instr (Lstore chunk addr args src)
| wt_Lcall:
forall sig ros args res,
List.map Loc.type args = sig.(sig_args) ->
Loc.type res = proj_sig_res sig ->
LTLtyping.call_loc_acceptable sig ros ->
locs_acceptable args -> loc_acceptable res ->
wt_instr (Lcall sig ros args res)
| wt_Ltailcall:
forall sig ros args,
List.map Loc.type args = sig.(sig_args) ->
LTLtyping.call_loc_acceptable sig ros ->
locs_acceptable args ->
sig.(sig_res) = funsig.(sig_res) ->
tailcall_possible sig ->
wt_instr (Ltailcall sig ros args)
| wt_Lbuiltin:
forall ef args res,
List.map Loc.type args = (ef_sig ef).(sig_args) ->
Loc.type res = proj_sig_res (ef_sig ef) ->
arity_ok (ef_sig ef).(sig_args) = true \/ ef_reloads ef = false ->
locs_acceptable args -> loc_acceptable res ->
wt_instr (Lbuiltin ef args res)
| wt_Llabel: forall lbl,
wt_instr (Llabel lbl)
| wt_Lgoto: forall lbl,
wt_instr (Lgoto lbl)
| wt_Lcond:
forall cond args lbl,
List.map Loc.type args = type_of_condition cond ->
locs_acceptable args ->
wt_instr (Lcond cond args lbl)
| wt_Ljumptable:
forall arg tbl,
Loc.type arg = Tint ->
loc_acceptable arg ->
list_length_z tbl * 4 <= Int.max_unsigned ->
wt_instr (Ljumptable arg tbl)
| wt_Lreturn:
forall optres,
option_map Loc.type optres = funsig.(sig_res) ->
match optres with None => True | Some r => loc_acceptable r end ->
wt_instr (Lreturn optres).
Definition wt_code (c: code) : Prop :=
forall i, In i c -> wt_instr i.
End WT_INSTR.
Record wt_function (f: function): Prop :=
mk_wt_function {
wt_params:
List.map Loc.type f.(fn_params) = f.(fn_sig).(sig_args);
wt_acceptable:
locs_acceptable f.(fn_params);
wt_norepet:
Loc.norepet f.(fn_params);
wt_instrs:
wt_code f.(fn_sig) f.(fn_code)
}.
Inductive wt_fundef: fundef -> Prop :=
| wt_fundef_external: forall ef,
wt_fundef (External ef)
| wt_function_internal: forall f,
wt_function f ->
wt_fundef (Internal f).
Definition wt_program (p: program): Prop :=
forall i f, In (i, f) (prog_funct p) -> wt_fundef f.
|
/-
Copyright (c) 2021 Jakob Scholbach. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jakob Scholbach, Joël Riou
-/
import category_theory.comm_sq
/-!
# Lifting properties
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the lifting property of two morphisms in a category and
shows basic properties of this notion.
## Main results
- `has_lifting_property`: the definition of the lifting property
## Tags
lifting property
@TODO :
1) define llp/rlp with respect to a `morphism_property`
2) retracts, direct/inverse images, (co)products, adjunctions
-/
universe v
namespace category_theory
open category
variables {C : Type*} [category C] {A B B' X Y Y' : C}
(i : A ⟶ B) (i' : B ⟶ B') (p : X ⟶ Y) (p' : Y ⟶ Y')
/-- `has_lifting_property i p` means that `i` has the left lifting
property with respect to `p`, or equivalently that `p` has
the right lifting property with respect to `i`. -/
class has_lifting_property : Prop :=
(sq_has_lift : ∀ {f : A ⟶ X} {g : B ⟶ Y} (sq : comm_sq f i p g), sq.has_lift)
@[priority 100]
instance sq_has_lift_of_has_lifting_property {f : A ⟶ X} {g : B ⟶ Y} (sq : comm_sq f i p g)
[hip : has_lifting_property i p] : sq.has_lift := by apply hip.sq_has_lift
namespace has_lifting_property
variables {i p}
lemma op (h : has_lifting_property i p) : has_lifting_property p.op i.op :=
⟨λ f g sq, begin
simp only [comm_sq.has_lift.iff_unop, quiver.hom.unop_op],
apply_instance,
end⟩
lemma unop {A B X Y : Cᵒᵖ} {i : A ⟶ B} {p : X ⟶ Y}
(h : has_lifting_property i p) : has_lifting_property p.unop i.unop :=
⟨λ f g sq, begin
rw comm_sq.has_lift.iff_op,
simp only [quiver.hom.op_unop],
apply_instance,
end⟩
lemma iff_op : has_lifting_property i p ↔ has_lifting_property p.op i.op := ⟨op, unop⟩
lemma iff_unop {A B X Y : Cᵒᵖ} (i : A ⟶ B) (p : X ⟶ Y) :
has_lifting_property i p ↔ has_lifting_property p.unop i.unop := ⟨unop, op⟩
variables (i p)
@[priority 100]
instance of_left_iso [is_iso i] : has_lifting_property i p :=
⟨λ f g sq, comm_sq.has_lift.mk'
{ l := inv i ≫ f,
fac_left' := by simp only [is_iso.hom_inv_id_assoc],
fac_right' := by simp only [sq.w, assoc, is_iso.inv_hom_id_assoc], }⟩
@[priority 100]
instance of_right_iso [is_iso p] : has_lifting_property i p :=
⟨λ f g sq, comm_sq.has_lift.mk'
{ l := g ≫ inv p,
fac_left' := by simp only [← sq.w_assoc, is_iso.hom_inv_id, comp_id],
fac_right' := by simp only [assoc, is_iso.inv_hom_id, comp_id], }⟩
instance of_comp_left [has_lifting_property i p] [has_lifting_property i' p] :
has_lifting_property (i ≫ i') p :=
⟨λ f g sq, begin
have fac := sq.w,
rw assoc at fac,
exact comm_sq.has_lift.mk'
{ l := (comm_sq.mk (comm_sq.mk fac).fac_right).lift,
fac_left' := by simp only [assoc, comm_sq.fac_left],
fac_right' := by simp only [comm_sq.fac_right], },
end⟩
instance of_comp_right [has_lifting_property i p] [has_lifting_property i p'] :
has_lifting_property i (p ≫ p') :=
⟨λ f g sq, begin
have fac := sq.w,
rw ← assoc at fac,
let sq₂ := (comm_sq.mk ((comm_sq.mk fac).fac_left.symm)).lift,
exact comm_sq.has_lift.mk'
{ l := (comm_sq.mk ((comm_sq.mk fac).fac_left.symm)).lift,
fac_left' := by simp only [comm_sq.fac_left],
fac_right' := by simp only [comm_sq.fac_right_assoc, comm_sq.fac_right], },
end⟩
lemma of_arrow_iso_left {A B A' B' X Y : C} {i : A ⟶ B} {i' : A' ⟶ B'}
(e : arrow.mk i ≅ arrow.mk i') (p : X ⟶ Y)
[hip : has_lifting_property i p] : has_lifting_property i' p :=
by { rw arrow.iso_w' e, apply_instance, }
lemma of_arrow_iso_right {A B X Y X' Y' : C} (i : A ⟶ B) {p : X ⟶ Y} {p' : X' ⟶ Y'}
(e : arrow.mk p ≅ arrow.mk p')
[hip : has_lifting_property i p] : has_lifting_property i p' :=
by { rw arrow.iso_w' e, apply_instance, }
lemma iff_of_arrow_iso_left {A B A' B' X Y : C} {i : A ⟶ B} {i' : A' ⟶ B'}
(e : arrow.mk i ≅ arrow.mk i') (p : X ⟶ Y) :
has_lifting_property i p ↔ has_lifting_property i' p :=
by { split; introI, exacts [of_arrow_iso_left e p, of_arrow_iso_left e.symm p], }
lemma iff_of_arrow_iso_right {A B X Y X' Y' : C} (i : A ⟶ B) {p : X ⟶ Y} {p' : X' ⟶ Y'}
(e : arrow.mk p ≅ arrow.mk p') :
has_lifting_property i p ↔ has_lifting_property i p' :=
by { split; introI, exacts [of_arrow_iso_right i e, of_arrow_iso_right i e.symm], }
end has_lifting_property
end category_theory
|
MovingAverage := function(n)
local sma, buffer, pos, sum, len;
buffer := List([1 .. n], i -> 0);
pos := 0;
len := 0;
sum := 0;
sma := function(x)
pos := RemInt(pos, n) + 1;
sum := sum + x - buffer[pos];
buffer[pos] := x;
len := Minimum(len + 1, n);
return sum/len;
end;
return sma;
end;
f := MovingAverage(3);
f(1); # 1
f(2); # 3/2
f(3); # 2
f(4); # 3
f(5); # 4
f(5); # 14/3
f(4); # 14/3
f(3); # 4
f(2); # 3
f(1); # 2
|
Formal statement is: lemma (in t2_space) compact_imp_closed: assumes "compact s" shows "closed s" Informal statement is: In a T2 space, compact sets are closed. |
/-
Copyright (c) 2021 Lu-Ming Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Lu-Ming Zhang
-/
import linear_algebra.matrix.trace
/-!
# Hadamard product of matrices
This file defines the Hadamard product `matrix.hadamard`
and contains basic properties about them.
## Main definition
- `matrix.hadamard`: defines the Hadamard product,
which is the pointwise product of two matrices of the same size.
## Notation
* `⊙`: the Hadamard product `matrix.hadamard`;
## References
* <https://en.wikipedia.org/wiki/hadamard_product_(matrices)>
## Tags
hadamard product, hadamard
-/
variables {α β γ m n : Type*}
variables {R : Type*}
namespace matrix
open_locale matrix big_operators
/-- `matrix.hadamard` defines the Hadamard product,
which is the pointwise product of two matrices of the same size.-/
def hadamard [has_mul α] (A : matrix m n α) (B : matrix m n α) : matrix m n α :=
of $ λ i j, A i j * B i j
-- TODO: set as an equation lemma for `hadamard`, see mathlib4#3024
@[simp]
lemma hadamard_apply [has_mul α] (A : matrix m n α) (B : matrix m n α) (i j) :
hadamard A B i j = A i j * B i j := rfl
localized "infix (name := matrix.hadamard) ` ⊙ `:100 := matrix.hadamard" in matrix
section basic_properties
variables (A : matrix m n α) (B : matrix m n α) (C : matrix m n α)
/- commutativity -/
lemma hadamard_comm [comm_semigroup α] : A ⊙ B = B ⊙ A :=
ext $ λ _ _, mul_comm _ _
/- associativity -/
lemma hadamard_assoc [semigroup α] : A ⊙ B ⊙ C = A ⊙ (B ⊙ C) :=
ext $ λ _ _, mul_assoc _ _ _
/- distributivity -/
lemma hadamard_add [distrib α] : A ⊙ (B + C) = A ⊙ B + A ⊙ C :=
ext $ λ _ _, left_distrib _ _ _
lemma add_hadamard [distrib α] : (B + C) ⊙ A = B ⊙ A + C ⊙ A :=
ext $ λ _ _, right_distrib _ _ _
/- scalar multiplication -/
section scalar
@[simp] lemma smul_hadamard [has_mul α] [has_smul R α] [is_scalar_tower R α α] (k : R) :
(k • A) ⊙ B = k • A ⊙ B :=
ext $ λ _ _, smul_mul_assoc _ _ _
@[simp] lemma hadamard_smul [has_mul α] [has_smul R α] [smul_comm_class R α α] (k : R):
A ⊙ (k • B) = k • A ⊙ B :=
ext $ λ _ _, mul_smul_comm _ _ _
end scalar
section zero
variables [mul_zero_class α]
@[simp] lemma hadamard_zero : A ⊙ (0 : matrix m n α) = 0 :=
ext $ λ _ _, mul_zero _
@[simp] lemma zero_hadamard : (0 : matrix m n α) ⊙ A = 0 :=
ext $ λ _ _, zero_mul _
end zero
section one
variables [decidable_eq n] [mul_zero_one_class α]
variables (M : matrix n n α)
lemma hadamard_one : M ⊙ (1 : matrix n n α) = diagonal (λ i, M i i) :=
by { ext, by_cases h : i = j; simp [h] }
lemma one_hadamard : (1 : matrix n n α) ⊙ M = diagonal (λ i, M i i) :=
by { ext, by_cases h : i = j; simp [h] }
end one
section diagonal
variables [decidable_eq n] [mul_zero_class α]
lemma diagonal_hadamard_diagonal (v : n → α) (w : n → α) :
diagonal v ⊙ diagonal w = diagonal (v * w) :=
ext $ λ _ _, (apply_ite2 _ _ _ _ _ _).trans (congr_arg _ $ zero_mul 0)
end diagonal
section trace
variables [fintype m] [fintype n]
variables (R) [semiring α] [semiring R] [module R α]
lemma sum_hadamard_eq : ∑ (i : m) (j : n), (A ⊙ B) i j = trace (A ⬝ Bᵀ) :=
rfl
lemma dot_product_vec_mul_hadamard [decidable_eq m] [decidable_eq n] (v : m → α) (w : n → α) :
dot_product (vec_mul v (A ⊙ B)) w = trace (diagonal v ⬝ A ⬝ (B ⬝ diagonal w)ᵀ) :=
begin
rw [←sum_hadamard_eq, finset.sum_comm],
simp [dot_product, vec_mul, finset.sum_mul, mul_assoc],
end
end trace
end basic_properties
end matrix
|
open import Common.Prelude
module TestHarness where
record ⊤ : Set where
data ⊥ : Set where
T : Bool → Set
T true = ⊤
T false = ⊥
infixr 4 _,_
data Asserts : Set where
ε : Asserts
_,_ : Asserts → Asserts → Asserts
assert : (b : Bool) → {b✓ : T b} → String → Asserts
Tests : Set
Tests = ⊤ → Asserts
|
{-# OPTIONS --without-K --safe #-}
module Categories.Diagram.Finite where
open import Level
open import Categories.Category
open import Categories.Category.Finite renaming (Finite to FiniteC)
open import Categories.Functor
private
variable
o ℓ e : Level
J C : Category o ℓ e
record Finite (F : Functor J C) : Set (levelOfTerm F) where
field
finite : FiniteC J
open Functor F public
open FiniteC finite public
|
import tactic
import topology.basic
/-!
Starting with a theorem
If f: X → Y is a function then the folowing are equivalent:
1) f is surjective;
2) ∃ g : Y → X such that "g is a one-sided inverse of f" i.e. ∀ y ∈ Y, f(g(y)) = y
i.e. f∘g = id_y
The proof:
1 ⇒ 2:
Define g thus if y ∈ Y, by surjectivity of f ⇒ ∃ x ∈ X s.t. f(x) = y
Define g(y) to be this x. ∎
2 ⇒ 1
If y ∈ Y need x ∈ X such that f(x) = y.
But x = g(y) works. ∎
Surjectivity of f means {x ∈ X | f(x) = y} ≠ ∅
This proof uses axiom of choice
Try proving this in Lean.
-/
variables (X Y : Type) (f : X → Y)
example (f g: X → Y) (h: f = g) : ∀ x, f x = g x :=
begin
intro x,
exact congr_fun h x,
end
example : function.surjective f ↔
∃ g : Y → X, f ∘ g = id :=
begin
split, {
intro h,
-- Nonsense
--have h37 : f = f, refl,
let g_not_working : Y → X, {
-- Lean has two universes Type and Prop
-- examples of types ℝ, ℕ, G (a group)
-- examples of Prop "2+2=4", "2+2=5", Fer;at last Theorem
-- examples of terms π, 7, 9 or proofs of 2+2=4
-- but everything is a term which has type of the "above layer"
-- Prop is a term of Type, and Type is a term of Type 1, which is a term of Type2, etc.
-- Note Type is identical to Type0
-- And Prop = Sort0, Type = Sort1, Type1 = Sort2, etc.
intro y,
unfold function.surjective at h,
specialize h y,
-- Try to use axiom of choice
-- how to get a from h,
-- "cases h with x hx" does not work as we shouldn't be creating data in tactic mode
-- see below
-- the fix is to not do this
sorry,
},
-- need an axiom of choice tactic
choose g hg using h,
use g,
-- extentionality tactic for functions
ext y,
exact hg y,
}, {
intro h,
cases h with g hg,
replace hg := congr_fun hg,
change ∀ y, f (g y) = y at hg,
intro y,
use g y,
apply hg,
-- Golfed version
-- rintro ⟨g, hg⟩ y,
-- exact ⟨g y, (congr_fun hg) y⟩,
}
end
#check Y → X
#check f
#check Exists
#check @Exists.rec
#check @nat.rec
example (a : ℕ) : ℕ :=
begin
cases a,
sorry, sorry,
end
-- bad case because of recursive
example (h : ∃ x : ℕ, x = x) : ℕ :=
begin
cases h,
sorry,
end
/-
In Lean the axiom of choice is your route from Prop to Type
Proofs are not stored.
Axiom of choice in Lean is a function (∃ x: X, px) → X
-/
#check nonempty
#check @classical.choice
-- Need to write non computable as we're using axiom of choice
noncomputable def foo : ℕ :=
begin
have h : nonempty ℕ,
{ exact ⟨2⟩ },
exact classical.choice h,
end
/-!
# Second hour
-/
class has_star (α : Type) :=
{ starry_element : α }
notation `★` := has_star.starry_element
instance : has_star ℕ :=
{ starry_element := 37 }
#eval 30 + ★
instance : has_star ℤ :=
{ starry_element := 42 }
#eval (30 : ℤ) + ★
class my_group (G: Type) extends has_mul G, has_one G, has_inv G :=
( mul_assoc : ∀ g h k : G, g * (h * k) = (g * h) * k)
-- Has error, because Lean doesn't know what is meant by 1
-- One fix is to add has_one to the extends
( one_mul : ∀ g : G, 1 * g = g)
-- Or use
-- ( one_mul : ∃ e : G, ∀ g : G, e * g = g)
-- But then how do we "get" the identity, so use initial thing
( inv_mul : ∀ g, g * g⁻¹ = (1 : G))
structure my_group_iso (G H : Type)
[group G] [group H] :=
(f : G → H)
(hmul : ∀ a b : G, f(a * b) = f a * f b)
(hbij : function.bijective f)
example (G H : Type) [group G] [group H] (e : my_group_iso G H): G :=
-- hard to access the inverse function
begin
sorry,
end
structure my_homeomorphism (X Y : Type)
[topological_space X] [topological_space Y] :=
(f : X → Y)
--(hf : function.bijective f) -- terrible idea
-- Just carry the inverse around by adding it to the structure
(g : Y → X)
(h_cont : continuous f)
(h_cont_inv : continuous g)
(h1 : f ∘ g = id)
(h2 : g ∘ f = id)
#check equiv
#check equiv ℕ ℕ
example : ℕ ≃ ℕ :=
{
to_fun := λ x, x,
inv_fun := λ y, y,
left_inv := begin intro x, dsimp only, refl, end,
right_inv := begin intro y, refl, end,
}
example (P: Prop) (h1 : P) (h2 : P) : h1 = h2 :=
begin
refl,
end
def e1 : ℤ ≃ ℤ :=
{
to_fun := id,
inv_fun := id,
left_inv := λ x, rfl,
right_inv := λ y, rfl,
}
def e2 : ℤ ≃ ℤ :=
{
to_fun := λ x, -x,
inv_fun := λ y, -y,
left_inv := λ x, begin dsimp only, ring, end,
right_inv := λ y, begin dsimp, ring, end,
}
example (X Y : Type) (e : X ≃ Y) : Y ≃ X :=
--equiv.symm e
-- or
e.symm
def foobar (X Y : Type) (e : X ≃ Y) : X → Y := e
#print foobar
-- coercion is happening
example (X Y : Type) (e : X ≃ Y) : Y → X := e.symm
example (Z : Type) (e : X ≃ Y) (f : Y ≃ Z): X ≃ Z := e.trans f
/-!
# Some tricks
-/
-- Get gols for all ands
example (P Q : Prop) : P ∧ Q ∧ P ∧ P :=
begin
refine ⟨_, _, _, _⟩,
sorry, sorry, sorry, sorry,
end |
Formal statement is: lemma aff_dim_convex_hull: fixes S :: "'n::euclidean_space set" shows "aff_dim (convex hull S) = aff_dim S" Informal statement is: The affine dimension of the convex hull of a set is equal to the affine dimension of the set. |
= BRIX11 run test command
== Collection
ciaox11
== Usage
brix11 run test [options] [TEST [test-options]]|[-- test-options]
=== options
TEST := Path to project folder or test script (extension guessed if not supplied).
Default script name = 'run_test.pl'
(any test-options will be passed unchecked to the script)
--program=TOOL Use TOOL to execute test script.
Default: guessed from extension (supported: .pl .sh .rb .py).
--debug Run test using Debug deployment environment (only applicable for msvc/icc builds).
--release Run test using Release deployment environment (only applicable for msvc/icc builds).
-f, --force Force all tasks to run even if their dependencies do not require them to.
Default: off
-v, --verbose Run with increased verbosity level. Repeat to increase more.
Default: 0
-h, --help Show this help message.
_NOTE_
The *--debug* and *--release* switches are only available on Windows platforms and applicable for
build environments utilizing the MSVC or ICC compiler toolsets.
== Description
Executes a test runner script.
== Example
$ brix11 run test
Executes the runner script 'run_test.pl' in the current directory using it's default runner tool
(perl) without arguments.
$ brix11 run test -- -debug
Executes the runner script 'run_test.pl' in the current directory using it's default runner tool
(perl) with argument '-debug'.
$ brix11 run test --program sandbox my_test.pl -debug
Executes the runner script 'my_test.pl' in the current directory using the tool 'sandbox' with
argument '-debug'.
$ brix11 run test --debug
Executes the runner script 'run_test.pl' in the current directory using the debug deployment
environment.
$ brix11 run test --debug -- -debug
Executes the runner script 'run_test.pl' in the current directory using the debug deployment
environment with argument '-debug' passed to the runner script 'run_test.pl'.
|
/-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Floris van Doorn
-/
import algebra.big_operators.basic
import algebra.module.basic
import data.finset.preimage
import data.set.finite
import group_theory.submonoid.basic
/-!
# Pointwise addition, multiplication, scalar multiplication and vector subtraction of sets.
This file defines pointwise algebraic operations on sets.
* For a type `α` with multiplication, multiplication is defined on `set α` by taking
`s * t` to be the set of all `x * y` where `x ∈ s` and `y ∈ t`. Similarly for addition.
* For `α` a semigroup, `set α` is a semigroup.
* If `α` is a (commutative) monoid, we define an alias `set_semiring α` for `set α`, which then
becomes a (commutative) semiring with union as addition and pointwise multiplication as
multiplication.
* For a type `β` with scalar multiplication by another type `α`, this
file defines a scalar multiplication of `set β` by `set α` and a separate scalar
multiplication of `set β` by `α`.
* We also define pointwise multiplication on `finset`.
Appropriate definitions and results are also transported to the additive theory via `to_additive`.
## Implementation notes
* The following expressions are considered in simp-normal form in a group:
`(λ h, h * g) ⁻¹' s`, `(λ h, g * h) ⁻¹' s`, `(λ h, h * g⁻¹) ⁻¹' s`, `(λ h, g⁻¹ * h) ⁻¹' s`,
`s * t`, `s⁻¹`, `(1 : set _)` (and similarly for additive variants).
Expressions equal to one of these will be simplified.
* We put all instances in the locale `pointwise`, so that these instances are not available by
default. Note that we do not mark them as reducible (as argued by note [reducible non-instances])
since we expect the locale to be open whenever the instances are actually used (and making the
instances reducible changes the behavior of `simp`).
## Tags
set multiplication, set addition, pointwise addition, pointwise multiplication,
pointwise subtraction
-/
open function
variables {α β γ : Type*}
namespace set
/-! ### Properties about 1 -/
section one
variables [has_one α] {s : set α} {a : α}
/-- The set `(1 : set α)` is defined as `{1}` in locale `pointwise`. -/
@[to_additive
/-"The set `(0 : set α)` is defined as `{0}` in locale `pointwise`. "-/]
protected def has_one : has_one (set α) := ⟨{1}⟩
localized "attribute [instance] set.has_one set.has_zero" in pointwise
@[to_additive]
lemma singleton_one : ({1} : set α) = 1 := rfl
@[simp, to_additive]
lemma mem_one : a ∈ (1 : set α) ↔ a = 1 := iff.rfl
@[to_additive]
lemma one_mem_one : (1 : α) ∈ (1 : set α) := eq.refl _
@[simp, to_additive]
lemma one_subset : 1 ⊆ s ↔ (1 : α) ∈ s := singleton_subset_iff
@[to_additive]
lemma one_nonempty : (1 : set α).nonempty := ⟨1, rfl⟩
@[simp, to_additive]
lemma image_one {f : α → β} : f '' 1 = {f 1} := image_singleton
end one
open_locale pointwise
/-! ### Properties about multiplication -/
section mul
variables {s s₁ s₂ t t₁ t₂ u : set α} {a b : α}
/-- The set `(s * t : set α)` is defined as `{x * y | x ∈ s, y ∈ t}` in locale `pointwise`. -/
@[to_additive
/-" The set `(s + t : set α)` is defined as `{x + y | x ∈ s, y ∈ t}` in locale `pointwise`."-/]
protected def has_mul [has_mul α] : has_mul (set α) := ⟨image2 has_mul.mul⟩
localized "attribute [instance] set.has_mul set.has_add" in pointwise
section has_mul
variables {ι : Sort*} {κ : ι → Sort*} [has_mul α]
@[simp, to_additive]
lemma image2_mul : image2 has_mul.mul s t = s * t := rfl
@[to_additive]
lemma mem_mul : a ∈ s * t ↔ ∃ x y, x ∈ s ∧ y ∈ t ∧ x * y = a := iff.rfl
@[to_additive]
lemma mul_mem_mul (ha : a ∈ s) (hb : b ∈ t) : a * b ∈ s * t := mem_image2_of_mem ha hb
@[to_additive]
lemma mul_subset_mul (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ * s₂ ⊆ t₁ * t₂ := image2_subset h₁ h₂
@[to_additive add_image_prod]
lemma image_mul_prod : (λ x : α × α, x.fst * x.snd) '' (s ×ˢ t) = s * t := image_prod _
@[simp, to_additive] lemma empty_mul : ∅ * s = ∅ := image2_empty_left
@[simp, to_additive] lemma mul_empty : s * ∅ = ∅ := image2_empty_right
@[simp, to_additive] lemma mul_singleton : s * {b} = (* b) '' s := image2_singleton_right
@[simp, to_additive] lemma singleton_mul : {a} * t = ((*) a) '' t := image2_singleton_left
@[simp, to_additive]
lemma singleton_mul_singleton : ({a} : set α) * {b} = {a * b} := image2_singleton
@[to_additive] lemma mul_subset_mul_left (h : t₁ ⊆ t₂) : s * t₁ ⊆ s * t₂ := image2_subset_left h
@[to_additive] lemma mul_subset_mul_right (h : s₁ ⊆ s₂) : s₁ * t ⊆ s₂ * t := image2_subset_right h
@[to_additive] lemma union_mul : (s₁ ∪ s₂) * t = s₁ * t ∪ s₂ * t := image2_union_left
@[to_additive] lemma mul_union : s * (t₁ ∪ t₂) = s * t₁ ∪ s * t₂ := image2_union_right
@[to_additive]
lemma inter_mul_subset : (s₁ ∩ s₂) * t ⊆ s₁ * t ∩ (s₂ * t) := image2_inter_subset_left
@[to_additive]
lemma mul_inter_subset : s * (t₁ ∩ t₂) ⊆ s * t₁ ∩ (s * t₂) := image2_inter_subset_right
@[to_additive]
lemma Union_mul_left_image : (⋃ a ∈ s, (λ x, a * x) '' t) = s * t := Union_image_left _
@[to_additive]
lemma Union_mul_right_image : (⋃ a ∈ t, (λ x, x * a) '' s) = s * t := Union_image_right _
@[to_additive]
lemma Union_mul (s : ι → set α) (t : set α) : (⋃ i, s i) * t = ⋃ i, s i * t :=
image2_Union_left _ _ _
@[to_additive]
lemma mul_Union (s : set α) (t : ι → set α) : s * (⋃ i, t i) = ⋃ i, s * t i :=
image2_Union_right _ _ _
@[to_additive]
lemma Union₂_mul (s : Π i, κ i → set α) (t : set α) : (⋃ i j, s i j) * t = ⋃ i j, s i j * t :=
image2_Union₂_left _ _ _
@[to_additive]
lemma mul_Union₂ (s : set α) (t : Π i, κ i → set α) : s * (⋃ i j, t i j) = ⋃ i j, s * t i j :=
image2_Union₂_right _ _ _
@[to_additive]
lemma Inter_mul_subset (s : ι → set α) (t : set α) : (⋂ i, s i) * t ⊆ ⋂ i, s i * t :=
image2_Inter_subset_left _ _ _
@[to_additive]
lemma mul_Inter_subset (s : set α) (t : ι → set α) : s * (⋂ i, t i) ⊆ ⋂ i, s * t i :=
image2_Inter_subset_right _ _ _
@[to_additive]
lemma Inter₂_mul_subset (s : Π i, κ i → set α) (t : set α) :
(⋂ i j, s i j) * t ⊆ ⋂ i j, s i j * t :=
image2_Inter₂_subset_left _ _ _
@[to_additive]
lemma mul_Inter₂_subset (s : set α) (t : Π i, κ i → set α) :
s * (⋂ i j, t i j) ⊆ ⋂ i j, s * t i j :=
image2_Inter₂_subset_right _ _ _
/-- Under `[has_mul M]`, the `singleton` map from `M` to `set M` as a `mul_hom`, that is, a map
which preserves multiplication. -/
@[to_additive "Under `[has_add A]`, the `singleton` map from `A` to `set A` as an `add_hom`,
that is, a map which preserves addition.", simps]
def singleton_mul_hom : mul_hom α (set α) :=
{ to_fun := singleton,
map_mul' := λ a b, singleton_mul_singleton.symm }
end has_mul
@[simp, to_additive]
lemma image_mul_left [group α] : ((*) a) '' t = ((*) a⁻¹) ⁻¹' t :=
by { rw image_eq_preimage_of_inverse; intro c; simp }
@[simp, to_additive]
lemma image_mul_right [group α] : (* b) '' t = (* b⁻¹) ⁻¹' t :=
by { rw image_eq_preimage_of_inverse; intro c; simp }
@[to_additive]
lemma image_mul_left' [group α] : (λ b, a⁻¹ * b) '' t = (λ b, a * b) ⁻¹' t := by simp
@[to_additive]
lemma image_mul_right' [group α] : (* b⁻¹) '' t = (* b) ⁻¹' t := by simp
@[simp, to_additive]
lemma preimage_mul_left_singleton [group α] : ((*) a) ⁻¹' {b} = {a⁻¹ * b} :=
by rw [← image_mul_left', image_singleton]
@[simp, to_additive]
lemma preimage_mul_right_singleton [group α] : (* a) ⁻¹' {b} = {b * a⁻¹} :=
by rw [← image_mul_right', image_singleton]
@[simp, to_additive]
lemma preimage_mul_left_one [group α] : ((*) a) ⁻¹' 1 = {a⁻¹} :=
by rw [← image_mul_left', image_one, mul_one]
@[simp, to_additive]
lemma preimage_mul_right_one [group α] : (* b) ⁻¹' 1 = {b⁻¹} :=
by rw [← image_mul_right', image_one, one_mul]
@[to_additive]
lemma preimage_mul_left_one' [group α] : (λ b, a⁻¹ * b) ⁻¹' 1 = {a} := by simp
@[to_additive]
lemma preimage_mul_right_one' [group α] : (* b⁻¹) ⁻¹' 1 = {b} := by simp
@[to_additive]
protected lemma mul_comm [comm_semigroup α] : s * t = t * s :=
by simp only [← image2_mul, image2_swap _ s, mul_comm]
/-- `set α` is a `mul_one_class` under pointwise operations if `α` is. -/
@[to_additive /-"`set α` is an `add_zero_class` under pointwise operations if `α` is."-/]
protected def mul_one_class [mul_one_class α] : mul_one_class (set α) :=
{ mul_one := λ s, by { simp only [← singleton_one, mul_singleton, mul_one, image_id'] },
one_mul := λ s, by { simp only [← singleton_one, singleton_mul, one_mul, image_id'] },
..set.has_one, ..set.has_mul }
/-- `set α` is a `semigroup` under pointwise operations if `α` is. -/
@[to_additive /-"`set α` is an `add_semigroup` under pointwise operations if `α` is. "-/]
protected def semigroup [semigroup α] : semigroup (set α) :=
{ mul_assoc := λ _ _ _, image2_assoc mul_assoc,
..set.has_mul }
/-- `set α` is a `monoid` under pointwise operations if `α` is. -/
@[to_additive /-"`set α` is an `add_monoid` under pointwise operations if `α` is. "-/]
protected def monoid [monoid α] : monoid (set α) :=
{ ..set.semigroup,
..set.mul_one_class }
/-- `set α` is a `comm_monoid` under pointwise operations if `α` is. -/
@[to_additive /-"`set α` is an `add_comm_monoid` under pointwise operations if `α` is. "-/]
protected def comm_monoid [comm_monoid α] : comm_monoid (set α) :=
{ mul_comm := λ _ _, set.mul_comm, ..set.monoid }
localized "attribute [instance] set.mul_one_class set.add_zero_class set.semigroup set.add_semigroup
set.monoid set.add_monoid set.comm_monoid set.add_comm_monoid" in pointwise
@[to_additive nsmul_mem_nsmul]
lemma pow_mem_pow [monoid α] (ha : a ∈ s) (n : ℕ) :
a ^ n ∈ s ^ n :=
begin
induction n with n ih,
{ rw pow_zero,
exact set.mem_singleton 1 },
{ rw pow_succ,
exact set.mul_mem_mul ha ih },
end
@[to_additive empty_nsmul]
lemma empty_pow [monoid α] (n : ℕ) (hn : n ≠ 0) : (∅ : set α) ^ n = ∅ :=
by rw [← tsub_add_cancel_of_le (nat.succ_le_of_lt $ nat.pos_of_ne_zero hn), pow_succ, empty_mul]
instance decidable_mem_mul [monoid α] [fintype α] [decidable_eq α]
[decidable_pred (∈ s)] [decidable_pred (∈ t)] :
decidable_pred (∈ s * t) :=
λ _, decidable_of_iff _ mem_mul.symm
instance decidable_mem_pow [monoid α] [fintype α] [decidable_eq α]
[decidable_pred (∈ s)] (n : ℕ) :
decidable_pred (∈ (s ^ n)) :=
begin
induction n with n ih,
{ simp_rw [pow_zero, mem_one], apply_instance },
{ letI := ih, rw pow_succ, apply_instance }
end
@[to_additive]
lemma subset_mul_left [mul_one_class α] (s : set α) {t : set α} (ht : (1 : α) ∈ t) : s ⊆ s * t :=
λ x hx, ⟨x, 1, hx, ht, mul_one _⟩
@[to_additive]
lemma subset_mul_right [mul_one_class α] {s : set α} (t : set α) (hs : (1 : α) ∈ s) : t ⊆ s * t :=
λ x hx, ⟨1, x, hs, hx, one_mul _⟩
lemma pow_subset_pow [monoid α] (hst : s ⊆ t) (n : ℕ) :
s ^ n ⊆ t ^ n :=
begin
induction n with n ih,
{ rw pow_zero,
exact subset.rfl },
{ rw [pow_succ, pow_succ],
exact mul_subset_mul hst ih },
end
@[simp, to_additive]
lemma univ_mul_univ [monoid α] : (univ : set α) * univ = univ :=
begin
have : ∀x, ∃a b : α, a * b = x := λx, ⟨x, ⟨1, mul_one x⟩⟩,
simpa only [mem_mul, eq_univ_iff_forall, mem_univ, true_and]
end
@[simp, to_additive]
lemma mul_univ [group α] (hs : s.nonempty) : s * (univ : set α) = univ :=
let ⟨a, ha⟩ := hs in eq_univ_of_forall $ λ b, ⟨a, a⁻¹ * b, ha, trivial, mul_inv_cancel_left _ _⟩
@[simp, to_additive]
lemma univ_mul [group α] (ht : t.nonempty) : (univ : set α) * t = univ :=
let ⟨a, ha⟩ := ht in eq_univ_of_forall $ λ b, ⟨b * a⁻¹, a, trivial, ha, inv_mul_cancel_right _ _⟩
/-- `singleton` is a monoid hom. -/
@[to_additive singleton_add_hom "singleton is an add monoid hom"]
def singleton_hom [monoid α] : α →* set α :=
{ to_fun := singleton, map_one' := rfl, map_mul' := λ a b, singleton_mul_singleton.symm }
@[to_additive]
lemma nonempty.mul [has_mul α] : s.nonempty → t.nonempty → (s * t).nonempty := nonempty.image2
@[to_additive]
lemma finite.mul [has_mul α] (hs : finite s) (ht : finite t) : finite (s * t) :=
hs.image2 _ ht
/-- multiplication preserves finiteness -/
@[to_additive "addition preserves finiteness"]
def fintype_mul [has_mul α] [decidable_eq α] (s t : set α) [hs : fintype s] [ht : fintype t] :
fintype (s * t : set α) :=
set.fintype_image2 _ s t
@[to_additive]
lemma bdd_above_mul [ordered_comm_monoid α] {A B : set α} :
bdd_above A → bdd_above B → bdd_above (A * B) :=
begin
rintros ⟨bA, hbA⟩ ⟨bB, hbB⟩,
use bA * bB,
rintros x ⟨xa, xb, hxa, hxb, rfl⟩,
exact mul_le_mul' (hbA hxa) (hbB hxb),
end
end mul
open_locale pointwise
section big_operators
open_locale big_operators
variables {ι : Type*} [comm_monoid α]
/-- The n-ary version of `set.mem_mul`. -/
@[to_additive /-" The n-ary version of `set.mem_add`. "-/]
lemma mem_finset_prod (t : finset ι) (f : ι → set α) (a : α) :
a ∈ ∏ i in t, f i ↔ ∃ (g : ι → α) (hg : ∀ {i}, i ∈ t → g i ∈ f i), ∏ i in t, g i = a :=
begin
classical,
induction t using finset.induction_on with i is hi ih generalizing a,
{ simp_rw [finset.prod_empty, set.mem_one],
exact ⟨λ h, ⟨λ i, a, λ i, false.elim, h.symm⟩, λ ⟨f, _, hf⟩, hf.symm⟩ },
rw [finset.prod_insert hi, set.mem_mul],
simp_rw [finset.prod_insert hi],
simp_rw ih,
split,
{ rintros ⟨x, y, hx, ⟨g, hg, rfl⟩, rfl⟩,
refine ⟨function.update g i x, λ j hj, _, _⟩,
obtain rfl | hj := finset.mem_insert.mp hj,
{ rw function.update_same, exact hx },
{ rw update_noteq (ne_of_mem_of_not_mem hj hi), exact hg hj, },
rw [finset.prod_update_of_not_mem hi, function.update_same], },
{ rintros ⟨g, hg, rfl⟩,
exact ⟨g i, is.prod g, hg (is.mem_insert_self _),
⟨g, λ i hi, hg (finset.mem_insert_of_mem hi), rfl⟩, rfl⟩ },
end
/-- A version of `set.mem_finset_prod` with a simpler RHS for products over a fintype. -/
@[to_additive /-" A version of `set.mem_finset_sum` with a simpler RHS for sums over a fintype. "-/]
lemma mem_fintype_prod [fintype ι] (f : ι → set α) (a : α) :
a ∈ ∏ i, f i ↔ ∃ (g : ι → α) (hg : ∀ i, g i ∈ f i), ∏ i, g i = a :=
by { rw mem_finset_prod, simp }
/-- The n-ary version of `set.mul_mem_mul`. -/
@[to_additive /-" The n-ary version of `set.add_mem_add`. "-/]
lemma finset_prod_mem_finset_prod (t : finset ι) (f : ι → set α)
(g : ι → α) (hg : ∀ i ∈ t, g i ∈ f i) :
∏ i in t, g i ∈ ∏ i in t, f i :=
by { rw mem_finset_prod, exact ⟨g, hg, rfl⟩ }
/-- The n-ary version of `set.mul_subset_mul`. -/
@[to_additive /-" The n-ary version of `set.add_subset_add`. "-/]
lemma finset_prod_subset_finset_prod (t : finset ι) (f₁ f₂ : ι → set α)
(hf : ∀ {i}, i ∈ t → f₁ i ⊆ f₂ i) :
∏ i in t, f₁ i ⊆ ∏ i in t, f₂ i :=
begin
intro a,
rw [mem_finset_prod, mem_finset_prod],
rintro ⟨g, hg, rfl⟩,
exact ⟨g, λ i hi, hf hi $ hg hi, rfl⟩
end
@[to_additive]
lemma finset_prod_singleton {M ι : Type*} [comm_monoid M] (s : finset ι) (I : ι → M) :
∏ (i : ι) in s, ({I i} : set M) = {∏ (i : ι) in s, I i} :=
begin
letI := classical.dec_eq ι,
refine finset.induction_on s _ _,
{ simpa },
{ intros _ _ H ih,
rw [finset.prod_insert H, finset.prod_insert H, ih],
simp }
end
/-! TODO: define `decidable_mem_finset_prod` and `decidable_mem_finset_sum`. -/
end big_operators
/-! ### Properties about inversion -/
section inv
variables {s t : set α} {a : α}
/-- The set `(s⁻¹ : set α)` is defined as `{x | x⁻¹ ∈ s}` in locale `pointwise`.
It is equal to `{x⁻¹ | x ∈ s}`, see `set.image_inv`. -/
@[to_additive
/-" The set `(-s : set α)` is defined as `{x | -x ∈ s}` in locale `pointwise`.
It is equal to `{-x | x ∈ s}`, see `set.image_neg`. "-/]
protected def has_inv [has_inv α] : has_inv (set α) :=
⟨preimage has_inv.inv⟩
localized "attribute [instance] set.has_inv set.has_neg" in pointwise
@[simp, to_additive]
lemma inv_empty [has_inv α] : (∅ : set α)⁻¹ = ∅ := rfl
@[simp, to_additive]
lemma inv_univ [has_inv α] : (univ : set α)⁻¹ = univ := rfl
@[simp, to_additive]
lemma nonempty_inv [group α] {s : set α} : s⁻¹.nonempty ↔ s.nonempty :=
inv_involutive.surjective.nonempty_preimage
@[to_additive] lemma nonempty.inv [group α] {s : set α} (h : s.nonempty) : s⁻¹.nonempty :=
nonempty_inv.2 h
@[simp, to_additive]
lemma mem_inv [has_inv α] : a ∈ s⁻¹ ↔ a⁻¹ ∈ s := iff.rfl
@[to_additive]
lemma inv_mem_inv [group α] : a⁻¹ ∈ s⁻¹ ↔ a ∈ s :=
by simp only [mem_inv, inv_inv]
@[simp, to_additive]
lemma inv_preimage [has_inv α] : has_inv.inv ⁻¹' s = s⁻¹ := rfl
@[simp, to_additive]
lemma image_inv [group α] : has_inv.inv '' s = s⁻¹ :=
by { simp only [← inv_preimage], rw [image_eq_preimage_of_inverse]; intro; simp only [inv_inv] }
@[simp, to_additive]
lemma inter_inv [has_inv α] : (s ∩ t)⁻¹ = s⁻¹ ∩ t⁻¹ := preimage_inter
@[simp, to_additive]
lemma union_inv [has_inv α] : (s ∪ t)⁻¹ = s⁻¹ ∪ t⁻¹ := preimage_union
@[simp, to_additive]
lemma Inter_inv {ι : Sort*} [has_inv α] (s : ι → set α) : (⋂ i, s i)⁻¹ = ⋂ i, (s i)⁻¹ :=
preimage_Inter
@[simp, to_additive]
lemma Union_inv {ι : Sort*} [has_inv α] (s : ι → set α) : (⋃ i, s i)⁻¹ = ⋃ i, (s i)⁻¹ :=
preimage_Union
@[simp, to_additive]
lemma compl_inv [has_inv α] : (sᶜ)⁻¹ = (s⁻¹)ᶜ := preimage_compl
@[simp, to_additive]
protected lemma inv_inv [group α] : s⁻¹⁻¹ = s :=
by { simp only [← inv_preimage, preimage_preimage, inv_inv, preimage_id'] }
@[simp, to_additive]
protected lemma univ_inv [group α] : (univ : set α)⁻¹ = univ := preimage_univ
@[simp, to_additive]
lemma inv_subset_inv [group α] {s t : set α} : s⁻¹ ⊆ t⁻¹ ↔ s ⊆ t :=
(equiv.inv α).surjective.preimage_subset_preimage_iff
@[to_additive] lemma inv_subset [group α] {s t : set α} : s⁻¹ ⊆ t ↔ s ⊆ t⁻¹ :=
by { rw [← inv_subset_inv, set.inv_inv] }
@[to_additive] lemma finite.inv [group α] {s : set α} (hs : finite s) : finite s⁻¹ :=
hs.preimage $ inv_injective.inj_on _
@[to_additive] lemma inv_singleton {β : Type*} [group β] (x : β) : ({x} : set β)⁻¹ = {x⁻¹} :=
by { ext1 y, rw [mem_inv, mem_singleton_iff, mem_singleton_iff, inv_eq_iff_inv_eq, eq_comm], }
@[to_additive] protected lemma mul_inv_rev [group α] (s t : set α) : (s * t)⁻¹ = t⁻¹ * s⁻¹ :=
by simp_rw [←image_inv, ←image2_mul, image_image2, image2_image_left, image2_image_right,
mul_inv_rev, image2_swap _ s t]
end inv
/-! ### Properties about scalar multiplication -/
section smul
/-- The scaling of a set `(x • s : set β)` by a scalar `x ∶ α` is defined as `{x • y | y ∈ s}`
in locale `pointwise`. -/
@[to_additive has_vadd_set "The translation of a set `(x +ᵥ s : set β)` by a scalar `x ∶ α` is
defined as `{x +ᵥ y | y ∈ s}` in locale `pointwise`."]
protected def has_scalar_set [has_scalar α β] : has_scalar α (set β) :=
⟨λ a, image (has_scalar.smul a)⟩
/-- The pointwise scalar multiplication `(s • t : set β)` by a set of scalars `s ∶ set α`
is defined as `{x • y | x ∈ s, y ∈ t}` in locale `pointwise`. -/
@[to_additive has_vadd "The pointwise translation `(s +ᵥ t : set β)` by a set of constants
`s ∶ set α` is defined as `{x +ᵥ y | x ∈ s, y ∈ t}` in locale `pointwise`."]
protected def has_scalar [has_scalar α β] : has_scalar (set α) (set β) :=
⟨image2 has_scalar.smul⟩
localized "attribute [instance] set.has_scalar_set set.has_scalar" in pointwise
localized "attribute [instance] set.has_vadd_set set.has_vadd" in pointwise
section has_scalar
variables {ι : Sort*} {κ : ι → Sort*} [has_scalar α β] {s s₁ s₂ : set α} {t t₁ t₂ u : set β} {a : α}
{b : β}
@[simp, to_additive]
lemma image2_smul : image2 has_scalar.smul s t = s • t := rfl
@[to_additive add_image_prod]
lemma image_smul_prod : (λ x : α × β, x.fst • x.snd) '' (s ×ˢ t) = s • t := image_prod _
@[to_additive]
lemma mem_smul : b ∈ s • t ↔ ∃ x y, x ∈ s ∧ y ∈ t ∧ x • y = b := iff.rfl
@[to_additive]
lemma smul_mem_smul (ha : a ∈ s) (hb : b ∈ t) : a • b ∈ s • t := mem_image2_of_mem ha hb
@[to_additive]
lemma smul_subset_smul (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : s₁ • t₁ ⊆ s₂ • t₂ := image2_subset hs ht
@[to_additive] lemma smul_subset_iff : s • t ⊆ u ↔ ∀ (a ∈ s) (b ∈ t), a • b ∈ u := image2_subset_iff
@[simp, to_additive] lemma empty_smul : (∅ : set α) • t = ∅ := image2_empty_left
@[simp, to_additive] lemma smul_empty : s • (∅ : set β) = ∅ := image2_empty_right
@[simp, to_additive] lemma smul_singleton : s • {b} = (• b) '' s := image2_singleton_right
@[simp, to_additive] lemma singleton_smul : ({a} : set α) • t = a • t := image2_singleton_left
@[simp, to_additive]
lemma singleton_smul_singleton : ({a} : set α) • ({b} : set β) = {a • b} := image2_singleton
@[to_additive] lemma smul_subset_smul_left (h : t₁ ⊆ t₂) : s • t₁ ⊆ s • t₂ := image2_subset_left h
@[to_additive] lemma smul_subset_smul_right (h : s₁ ⊆ s₂) : s₁ • t ⊆ s₂ • t := image2_subset_right h
@[to_additive] lemma union_smul : (s₁ ∪ s₂) • t = s₁ • t ∪ s₂ • t := image2_union_left
@[to_additive] lemma smul_union : s • (t₁ ∪ t₂) = s • t₁ ∪ s • t₂ := image2_union_right
@[to_additive]
lemma inter_smul_subset : (s₁ ∩ s₂) • t ⊆ s₁ • t ∩ s₂ • t := image2_inter_subset_left
@[to_additive]
lemma smul_inter_subset : s • (t₁ ∩ t₂) ⊆ s • t₁ ∩ s • t₂ := image2_inter_subset_right
@[to_additive]
lemma Union_smul_left_image : (⋃ a ∈ s, a • t) = s • t := Union_image_left _
@[to_additive]
lemma Union_smul_right_image : (⋃ a ∈ t, (λ x, x • a) '' s) = s • t := Union_image_right _
@[to_additive]
lemma Union_smul (s : ι → set α) (t : set β) : (⋃ i, s i) • t = ⋃ i, s i • t :=
image2_Union_left _ _ _
@[to_additive]
lemma smul_Union (s : set α) (t : ι → set β) : s • (⋃ i, t i) = ⋃ i, s • t i :=
image2_Union_right _ _ _
@[to_additive]
lemma Union₂_smul (s : Π i, κ i → set α) (t : set β) : (⋃ i j, s i j) • t = ⋃ i j, s i j • t :=
image2_Union₂_left _ _ _
@[to_additive]
lemma smul_Union₂ (s : set α) (t : Π i, κ i → set β) : s • (⋃ i j, t i j) = ⋃ i j, s • t i j :=
image2_Union₂_right _ _ _
@[to_additive]
lemma Inter_smul_subset (s : ι → set α) (t : set β) : (⋂ i, s i) • t ⊆ ⋂ i, s i • t :=
image2_Inter_subset_left _ _ _
@[to_additive]
lemma smul_Inter_subset (s : set α) (t : ι → set β) : s • (⋂ i, t i) ⊆ ⋂ i, s • t i :=
image2_Inter_subset_right _ _ _
@[to_additive]
lemma Inter₂_smul_subset (s : Π i, κ i → set α) (t : set β) :
(⋂ i j, s i j) • t ⊆ ⋂ i j, s i j • t :=
image2_Inter₂_subset_left _ _ _
@[to_additive]
lemma smul_Inter₂_subset (s : set α) (t : Π i, κ i → set β) :
s • (⋂ i j, t i j) ⊆ ⋂ i j, s • t i j :=
image2_Inter₂_subset_right _ _ _
end has_scalar
section has_scalar_set
variables {ι : Sort*} {κ : ι → Sort*} [has_scalar α β] {s t t₁ t₂ : set β} {a : α} {b : β} {x y : β}
@[simp, to_additive] lemma image_smul : (λ x, a • x) '' t = a • t := rfl
@[to_additive] lemma mem_smul_set : x ∈ a • t ↔ ∃ y, y ∈ t ∧ a • y = x := iff.rfl
@[to_additive] lemma smul_mem_smul_set (hy : y ∈ t) : a • y ∈ a • t := ⟨y, hy, rfl⟩
@[to_additive]
lemma mem_smul_of_mem {s : set α} (ha : a ∈ s) (hb : b ∈ t) : a • b ∈ s • t :=
mem_image2_of_mem ha hb
@[simp, to_additive] lemma smul_set_empty : a • (∅ : set β) = ∅ := image_empty _
@[simp, to_additive] lemma smul_set_singleton : a • ({b} : set β) = {a • b} := image_singleton
@[to_additive] lemma smul_set_mono (h : s ⊆ t) : a • s ⊆ a • t := image_subset _ h
@[to_additive] lemma smul_set_union : a • (t₁ ∪ t₂) = a • t₁ ∪ a • t₂ := image_union _ _ _
@[to_additive]
lemma smul_set_inter_subset : a • (t₁ ∩ t₂) ⊆ a • t₁ ∩ (a • t₂) := image_inter_subset _ _ _
@[to_additive]
lemma smul_set_Union (a : α) (s : ι → set β) : a • (⋃ i, s i) = ⋃ i, a • s i := image_Union
@[to_additive]
lemma smul_set_Union₂ (a : α) (s : Π i, κ i → set β) : a • (⋃ i j, s i j) = ⋃ i j, a • s i j :=
image_Union₂ _ _
@[to_additive]
lemma smul_set_Inter_subset (a : α) (t : ι → set β) : a • (⋂ i, t i) ⊆ ⋂ i, a • t i :=
image_Inter_subset _ _
@[to_additive]
lemma smul_set_Inter₂_subset (a : α) (t : Π i, κ i → set β) :
a • (⋂ i j, t i j) ⊆ ⋂ i j, a • t i j :=
image_Inter₂_subset _ _
@[to_additive] lemma finite.smul_set (hs : finite s) : finite (a • s) := hs.image _
end has_scalar_set
variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} {a : α} {b : β}
@[to_additive]
lemma smul_set_inter [group α] [mul_action α β] {s t : set β} :
a • (s ∩ t) = a • s ∩ a • t :=
(image_inter $ mul_action.injective a).symm
lemma smul_set_inter₀ [group_with_zero α] [mul_action α β] {s t : set β} (ha : a ≠ 0) :
a • (s ∩ t) = a • s ∩ a • t :=
show units.mk0 a ha • _ = _, from smul_set_inter
@[simp, to_additive]
lemma smul_set_univ [group α] [mul_action α β] {a : α} : a • (univ : set β) = univ :=
eq_univ_of_forall $ λ b, ⟨a⁻¹ • b, trivial, smul_inv_smul _ _⟩
@[simp, to_additive]
lemma smul_univ [group α] [mul_action α β] {s : set α} (hs : s.nonempty) :
s • (univ : set β) = univ :=
let ⟨a, ha⟩ := hs in eq_univ_of_forall $ λ b, ⟨a, a⁻¹ • b, ha, trivial, smul_inv_smul _ _⟩
@[to_additive]
theorem range_smul_range {ι κ : Type*} [has_scalar α β] (b : ι → α) (c : κ → β) :
range b • range c = range (λ p : ι × κ, b p.1 • c p.2) :=
ext $ λ x, ⟨λ hx, let ⟨p, q, ⟨i, hi⟩, ⟨j, hj⟩, hpq⟩ := set.mem_smul.1 hx in
⟨(i, j), hpq ▸ hi ▸ hj ▸ rfl⟩,
λ ⟨⟨i, j⟩, h⟩, set.mem_smul.2 ⟨b i, c j, ⟨i, rfl⟩, ⟨j, rfl⟩, h⟩⟩
@[to_additive]
instance smul_comm_class_set [has_scalar α γ] [has_scalar β γ] [smul_comm_class α β γ] :
smul_comm_class α (set β) (set γ) :=
{ smul_comm := λ a T T',
by simp only [←image2_smul, ←image_smul, image2_image_right, image_image2, smul_comm] }
@[to_additive]
instance smul_comm_class_set' [has_scalar α γ] [has_scalar β γ] [smul_comm_class α β γ] :
smul_comm_class (set α) β (set γ) :=
by haveI := smul_comm_class.symm α β γ; exact smul_comm_class.symm _ _ _
@[to_additive]
instance smul_comm_class [has_scalar α γ] [has_scalar β γ] [smul_comm_class α β γ] :
smul_comm_class (set α) (set β) (set γ) :=
{ smul_comm := λ T T' T'', begin
simp only [←image2_smul, image2_swap _ T],
exact image2_assoc (λ b c a, smul_comm a b c),
end }
instance is_scalar_tower [has_scalar α β] [has_scalar α γ] [has_scalar β γ]
[is_scalar_tower α β γ] :
is_scalar_tower α β (set γ) :=
{ smul_assoc := λ a b T, by simp only [←image_smul, image_image, smul_assoc] }
instance is_scalar_tower' [has_scalar α β] [has_scalar α γ] [has_scalar β γ]
[is_scalar_tower α β γ] :
is_scalar_tower α (set β) (set γ) :=
{ smul_assoc := λ a T T',
by simp only [←image_smul, ←image2_smul, image_image2, image2_image_left, smul_assoc] }
instance is_scalar_tower'' [has_scalar α β] [has_scalar α γ] [has_scalar β γ]
[is_scalar_tower α β γ] :
is_scalar_tower (set α) (set β) (set γ) :=
{ smul_assoc := λ T T' T'', image2_assoc smul_assoc }
instance is_central_scalar [has_scalar α β] [has_scalar αᵐᵒᵖ β] [is_central_scalar α β] :
is_central_scalar α (set β) :=
⟨λ a S, congr_arg (λ f, f '' S) $ by exact funext (λ _, op_smul_eq_smul _ _)⟩
end smul
section vsub
variables {ι : Sort*} {κ : ι → Sort*} [has_vsub α β] {s s₁ s₂ t t₁ t₂ : set β} {a : α}
{b c : β}
include α
instance has_vsub : has_vsub (set α) (set β) := ⟨image2 (-ᵥ)⟩
@[simp] lemma image2_vsub : (image2 has_vsub.vsub s t : set α) = s -ᵥ t := rfl
lemma image_vsub_prod : (λ x : β × β, x.fst -ᵥ x.snd) '' (s ×ˢ t) = s -ᵥ t := image_prod _
lemma mem_vsub : a ∈ s -ᵥ t ↔ ∃ x y, x ∈ s ∧ y ∈ t ∧ x -ᵥ y = a := iff.rfl
lemma vsub_mem_vsub (hb : b ∈ s) (hc : c ∈ t) : b -ᵥ c ∈ s -ᵥ t := mem_image2_of_mem hb hc
lemma vsub_subset_vsub (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : s₁ -ᵥ t₁ ⊆ s₂ -ᵥ t₂ := image2_subset hs ht
lemma vsub_subset_iff {u : set α} : s -ᵥ t ⊆ u ↔ ∀ (x ∈ s) (y ∈ t), x -ᵥ y ∈ u := image2_subset_iff
@[simp] lemma empty_vsub (t : set β) : ∅ -ᵥ t = ∅ := image2_empty_left
@[simp] lemma vsub_empty (s : set β) : s -ᵥ ∅ = ∅ := image2_empty_right
@[simp] lemma vsub_singleton (s : set β) (b : β) : s -ᵥ {b} = (-ᵥ b) '' s := image2_singleton_right
@[simp] lemma singleton_vsub (t : set β) (b : β) : {b} -ᵥ t = ((-ᵥ) b) '' t := image2_singleton_left
@[simp] lemma singleton_vsub_singleton : ({b} : set β) -ᵥ {c} = {b -ᵥ c} := image2_singleton
lemma vsub_subset_vsub_left (h : t₁ ⊆ t₂) : s -ᵥ t₁ ⊆ s -ᵥ t₂ := image2_subset_left h
lemma vsub_subset_vsub_right (h : s₁ ⊆ s₂) : s₁ -ᵥ t ⊆ s₂ -ᵥ t := image2_subset_right h
lemma union_vsub : (s₁ ∪ s₂) -ᵥ t = s₁ -ᵥ t ∪ (s₂ -ᵥ t) := image2_union_left
lemma vsub_union : s -ᵥ (t₁ ∪ t₂) = s -ᵥ t₁ ∪ (s -ᵥ t₂) := image2_union_right
lemma inter_vsub_subset : s₁ ∩ s₂ -ᵥ t ⊆ (s₁ -ᵥ t) ∩ (s₂ -ᵥ t) := image2_inter_subset_left
lemma vsub_inter_subset : s -ᵥ t₁ ∩ t₂ ⊆ (s -ᵥ t₁) ∩ (s -ᵥ t₂) := image2_inter_subset_right
lemma Union_vsub_left_image : (⋃ a ∈ s, ((-ᵥ) a) '' t) = s -ᵥ t := Union_image_left _
lemma Union_vsub_right_image : (⋃ a ∈ t, (-ᵥ a) '' s) = s -ᵥ t := Union_image_right _
lemma Union_vsub (s : ι → set β) (t : set β) : (⋃ i, s i) -ᵥ t = ⋃ i, s i -ᵥ t :=
image2_Union_left _ _ _
lemma vsub_Union (s : set β) (t : ι → set β) : s -ᵥ (⋃ i, t i) = ⋃ i, s -ᵥ t i :=
image2_Union_right _ _ _
lemma Union₂_vsub (s : Π i, κ i → set β) (t : set β) : (⋃ i j, s i j) -ᵥ t = ⋃ i j, s i j -ᵥ t :=
image2_Union₂_left _ _ _
lemma vsub_Union₂ (s : set β) (t : Π i, κ i → set β) : s -ᵥ (⋃ i j, t i j) = ⋃ i j, s -ᵥ t i j :=
image2_Union₂_right _ _ _
lemma Inter_vsub_subset (s : ι → set β) (t : set β) : (⋂ i, s i) -ᵥ t ⊆ ⋂ i, s i -ᵥ t :=
image2_Inter_subset_left _ _ _
lemma vsub_Inter_subset (s : set β) (t : ι → set β) : s -ᵥ (⋂ i, t i) ⊆ ⋂ i, s -ᵥ t i :=
image2_Inter_subset_right _ _ _
lemma Inter₂_vsub_subset (s : Π i, κ i → set β) (t : set β) :
(⋂ i j, s i j) -ᵥ t ⊆ ⋂ i j, s i j -ᵥ t :=
image2_Inter₂_subset_left _ _ _
lemma vsub_Inter₂_subset (s : set β) (t : Π i, κ i → set β) :
s -ᵥ (⋂ i j, t i j) ⊆ ⋂ i j, s -ᵥ t i j :=
image2_Inter₂_subset_right _ _ _
lemma finite.vsub (hs : finite s) (ht : finite t) : finite (s -ᵥ t) := hs.image2 _ ht
lemma vsub_self_mono (h : s ⊆ t) : s -ᵥ s ⊆ t -ᵥ t := vsub_subset_vsub h h
end vsub
open_locale pointwise
section ring
variables [ring α] [add_comm_group β] [module α β] {s : set α} {t : set β} {a : α}
@[simp] lemma neg_smul_set : -a • t = -(a • t) :=
by simp_rw [←image_smul, ←image_neg, image_image, neg_smul]
@[simp] lemma smul_set_neg : a • -t = -(a • t) :=
by simp_rw [←image_smul, ←image_neg, image_image, smul_neg]
@[simp] protected lemma neg_smul : -s • t = -(s • t) :=
by simp_rw [←image2_smul, ←image_neg, image2_image_left, image_image2, neg_smul]
@[simp] protected lemma smul_neg : s • -t = -(s • t) :=
by simp_rw [←image2_smul, ←image_neg, image2_image_right, image_image2, smul_neg]
end ring
section monoid
/-! ### `set α` as a `(∪,*)`-semiring -/
/-- An alias for `set α`, which has a semiring structure given by `∪` as "addition" and pointwise
multiplication `*` as "multiplication". -/
@[derive [inhabited, partial_order, order_bot]] def set_semiring (α : Type*) : Type* := set α
/-- The identitiy function `set α → set_semiring α`. -/
protected def up (s : set α) : set_semiring α := s
/-- The identitiy function `set_semiring α → set α`. -/
protected def set_semiring.down (s : set_semiring α) : set α := s
@[simp] protected lemma down_up {s : set α} : s.up.down = s := rfl
@[simp] protected lemma up_down {s : set_semiring α} : s.down.up = s := rfl
/- This lemma is not tagged `simp`, since otherwise the linter complains. -/
lemma up_le_up {s t : set α} : s.up ≤ t.up ↔ s ⊆ t := iff.rfl
/- This lemma is not tagged `simp`, since otherwise the linter complains. -/
lemma up_lt_up {s t : set α} : s.up < t.up ↔ s ⊂ t := iff.rfl
@[simp] lemma down_subset_down {s t : set_semiring α} : s.down ⊆ t.down ↔ s ≤ t := iff.rfl
@[simp] lemma down_ssubset_down {s t : set_semiring α} : s.down ⊂ t.down ↔ s < t := iff.rfl
instance set_semiring.add_comm_monoid : add_comm_monoid (set_semiring α) :=
{ add := λ s t, (s ∪ t : set α),
zero := (∅ : set α),
add_assoc := union_assoc,
zero_add := empty_union,
add_zero := union_empty,
add_comm := union_comm, }
instance set_semiring.non_unital_non_assoc_semiring [has_mul α] :
non_unital_non_assoc_semiring (set_semiring α) :=
{ zero_mul := λ s, empty_mul,
mul_zero := λ s, mul_empty,
left_distrib := λ _ _ _, mul_union,
right_distrib := λ _ _ _, union_mul,
..set.has_mul, ..set_semiring.add_comm_monoid }
instance set_semiring.non_assoc_semiring [mul_one_class α] : non_assoc_semiring (set_semiring α) :=
{ ..set_semiring.non_unital_non_assoc_semiring, ..set.mul_one_class }
instance set_semiring.non_unital_semiring [semigroup α] : non_unital_semiring (set_semiring α) :=
{ ..set_semiring.non_unital_non_assoc_semiring, ..set.semigroup }
instance set_semiring.semiring [monoid α] : semiring (set_semiring α) :=
{ ..set_semiring.non_assoc_semiring, ..set_semiring.non_unital_semiring }
instance set_semiring.comm_semiring [comm_monoid α] : comm_semiring (set_semiring α) :=
{ ..set.comm_monoid, ..set_semiring.semiring }
/-- A multiplicative action of a monoid on a type β gives also a
multiplicative action on the subsets of β. -/
@[to_additive "An additive action of an additive monoid on a type β gives also an additive action
on the subsets of β."]
protected def mul_action_set [monoid α] [mul_action α β] : mul_action α (set β) :=
{ mul_smul := by { intros, simp only [← image_smul, image_image, ← mul_smul] },
one_smul := by { intros, simp only [← image_smul, image_eta, one_smul, image_id'] },
..set.has_scalar_set }
localized "attribute [instance] set.mul_action_set set.add_action_set" in pointwise
section mul_hom
variables [has_mul α] [has_mul β] (m : mul_hom α β) {s t : set α}
@[to_additive]
lemma image_mul : m '' (s * t) = m '' s * m '' t :=
by { simp only [← image2_mul, image_image2, image2_image_left, image2_image_right, m.map_mul] }
@[to_additive]
lemma preimage_mul_preimage_subset {s t : set β} : m ⁻¹' s * m ⁻¹' t ⊆ m ⁻¹' (s * t) :=
by { rintros _ ⟨_, _, _, _, rfl⟩, exact ⟨_, _, ‹_›, ‹_›, (m.map_mul _ _).symm ⟩ }
instance set_semiring.no_zero_divisors : no_zero_divisors (set_semiring α) :=
⟨λ a b ab, a.eq_empty_or_nonempty.imp_right $ λ ha, b.eq_empty_or_nonempty.resolve_right $
λ hb, nonempty.ne_empty ⟨_, mul_mem_mul ha.some_mem hb.some_mem⟩ ab⟩
/- Since addition on `set_semiring` is commutative (it is set union), there is no need
to also have the instance `covariant_class (set_semiring α) (set_semiring α) (swap (+)) (≤)`. -/
instance set_semiring.covariant_class_add :
covariant_class (set_semiring α) (set_semiring α) (+) (≤) :=
{ elim := λ a b c, union_subset_union_right _ }
instance set_semiring.covariant_class_mul_left :
covariant_class (set_semiring α) (set_semiring α) (*) (≤) :=
{ elim := λ a b c, mul_subset_mul_left }
instance set_semiring.covariant_class_mul_right :
covariant_class (set_semiring α) (set_semiring α) (swap (*)) (≤) :=
{ elim := λ a b c, mul_subset_mul_right }
end mul_hom
/-- The image of a set under a multiplicative homomorphism is a ring homomorphism
with respect to the pointwise operations on sets. -/
def image_hom [monoid α] [monoid β] (f : α →* β) : set_semiring α →+* set_semiring β :=
{ to_fun := image f,
map_zero' := image_empty _,
map_one' := by simp only [← singleton_one, image_singleton, f.map_one],
map_add' := image_union _,
map_mul' := λ _ _, image_mul f.to_mul_hom }
end monoid
section comm_monoid
variable [comm_monoid α]
instance : canonically_ordered_comm_semiring (set_semiring α) :=
{ add_le_add_left := λ a b, add_le_add_left,
le_iff_exists_add := λ a b, ⟨λ ab, ⟨b, (union_eq_right_iff_subset.2 ab).symm⟩,
by { rintro ⟨c, rfl⟩, exact subset_union_left _ _ }⟩,
..(infer_instance : comm_semiring (set_semiring α)),
..(infer_instance : partial_order (set_semiring α)),
..(infer_instance : order_bot (set_semiring α)),
..(infer_instance : no_zero_divisors (set_semiring α)) }
end comm_monoid
end set
open set
open_locale pointwise
section
section smul_with_zero
variables [has_zero α] [has_zero β] [smul_with_zero α β]
/-- A nonempty set is scaled by zero to the singleton set containing 0. -/
lemma zero_smul_set {s : set β} (h : s.nonempty) : (0 : α) • s = (0 : set β) :=
by simp only [← image_smul, image_eta, zero_smul, h.image_const, singleton_zero]
lemma zero_smul_subset (s : set β) : (0 : α) • s ⊆ 0 := image_subset_iff.2 $ λ x _, zero_smul α x
lemma subsingleton_zero_smul_set (s : set β) : ((0 : α) • s).subsingleton :=
subsingleton_singleton.mono (zero_smul_subset s)
lemma zero_mem_smul_set {t : set β} {a : α} (h : (0 : β) ∈ t) : (0 : β) ∈ a • t :=
⟨0, h, smul_zero' _ _⟩
variables [no_zero_smul_divisors α β] {s : set α} {t : set β} {a : α}
lemma zero_mem_smul_iff : (0 : β) ∈ s • t ↔ (0 : α) ∈ s ∧ t.nonempty ∨ (0 : β) ∈ t ∧ s.nonempty :=
begin
split,
{ rintro ⟨a, b, ha, hb, h⟩,
obtain rfl | rfl := eq_zero_or_eq_zero_of_smul_eq_zero h,
{ exact or.inl ⟨ha, b, hb⟩ },
{ exact or.inr ⟨hb, a, ha⟩ } },
{ rintro (⟨hs, b, hb⟩ | ⟨ht, a, ha⟩),
{ exact ⟨0, b, hs, hb, zero_smul _ _⟩ },
{ exact ⟨a, 0, ha, ht, smul_zero' _ _⟩ } }
end
lemma zero_mem_smul_set_iff (ha : a ≠ 0) : (0 : β) ∈ a • t ↔ (0 : β) ∈ t :=
begin
refine ⟨_, zero_mem_smul_set⟩,
rintro ⟨b, hb, h⟩,
rwa (eq_zero_or_eq_zero_of_smul_eq_zero h).resolve_left ha at hb,
end
end smul_with_zero
lemma smul_add_set [monoid α] [add_monoid β] [distrib_mul_action α β] (c : α) (s t : set β) :
c • (s + t) = c • s + c • t :=
image_add (distrib_mul_action.to_add_monoid_hom β c).to_add_hom
section group
variables [group α] [mul_action α β] {A B : set β} {a : α} {x : β}
@[simp, to_additive]
lemma smul_mem_smul_set_iff : a • x ∈ a • A ↔ x ∈ A :=
⟨λ h, begin
rw [←inv_smul_smul a x, ←inv_smul_smul a A],
exact smul_mem_smul_set h,
end, smul_mem_smul_set⟩
@[to_additive]
lemma mem_smul_set_iff_inv_smul_mem : x ∈ a • A ↔ a⁻¹ • x ∈ A :=
show x ∈ mul_action.to_perm a '' A ↔ _, from mem_image_equiv
@[to_additive]
lemma mem_inv_smul_set_iff : x ∈ a⁻¹ • A ↔ a • x ∈ A :=
by simp only [← image_smul, mem_image, inv_smul_eq_iff, exists_eq_right]
@[to_additive]
lemma preimage_smul (a : α) (t : set β) : (λ x, a • x) ⁻¹' t = a⁻¹ • t :=
((mul_action.to_perm a).symm.image_eq_preimage _).symm
@[to_additive]
lemma preimage_smul_inv (a : α) (t : set β) : (λ x, a⁻¹ • x) ⁻¹' t = a • t :=
preimage_smul (to_units a)⁻¹ t
@[simp, to_additive]
lemma set_smul_subset_set_smul_iff : a • A ⊆ a • B ↔ A ⊆ B :=
image_subset_image_iff $ mul_action.injective _
@[to_additive]
lemma set_smul_subset_iff : a • A ⊆ B ↔ A ⊆ a⁻¹ • B :=
(image_subset_iff).trans $ iff_of_eq $ congr_arg _ $
preimage_equiv_eq_image_symm _ $ mul_action.to_perm _
@[to_additive]
lemma subset_set_smul_iff : A ⊆ a • B ↔ a⁻¹ • A ⊆ B :=
iff.symm $ (image_subset_iff).trans $ iff.symm $ iff_of_eq $ congr_arg _ $
image_equiv_eq_preimage_symm _ $ mul_action.to_perm _
end group
section group_with_zero
variables [group_with_zero α] [mul_action α β] {s : set α} {a : α}
@[simp] lemma smul_mem_smul_set_iff₀ (ha : a ≠ 0) (A : set β)
(x : β) : a • x ∈ a • A ↔ x ∈ A :=
show units.mk0 a ha • _ ∈ _ ↔ _, from smul_mem_smul_set_iff
lemma mem_smul_set_iff_inv_smul_mem₀ (ha : a ≠ 0) (A : set β) (x : β) :
x ∈ a • A ↔ a⁻¹ • x ∈ A :=
show _ ∈ units.mk0 a ha • _ ↔ _, from mem_smul_set_iff_inv_smul_mem
lemma mem_inv_smul_set_iff₀ (ha : a ≠ 0) (A : set β) (x : β) : x ∈ a⁻¹ • A ↔ a • x ∈ A :=
show _ ∈ (units.mk0 a ha)⁻¹ • _ ↔ _, from mem_inv_smul_set_iff
lemma preimage_smul₀ (ha : a ≠ 0) (t : set β) : (λ x, a • x) ⁻¹' t = a⁻¹ • t :=
preimage_smul (units.mk0 a ha) t
lemma preimage_smul_inv₀ (ha : a ≠ 0) (t : set β) :
(λ x, a⁻¹ • x) ⁻¹' t = a • t :=
preimage_smul ((units.mk0 a ha)⁻¹) t
@[simp] lemma set_smul_subset_set_smul_iff₀ (ha : a ≠ 0) {A B : set β} :
a • A ⊆ a • B ↔ A ⊆ B :=
show units.mk0 a ha • _ ⊆ _ ↔ _, from set_smul_subset_set_smul_iff
lemma set_smul_subset_iff₀ (ha : a ≠ 0) {A B : set β} : a • A ⊆ B ↔ A ⊆ a⁻¹ • B :=
show units.mk0 a ha • _ ⊆ _ ↔ _, from set_smul_subset_iff
lemma subset_set_smul_iff₀ (ha : a ≠ 0) {A B : set β} : A ⊆ a • B ↔ a⁻¹ • A ⊆ B :=
show _ ⊆ units.mk0 a ha • _ ↔ _, from subset_set_smul_iff
lemma smul_univ₀ (hs : ¬ s ⊆ 0) : s • (univ : set β) = univ :=
let ⟨a, ha, ha₀⟩ := not_subset.1 hs in eq_univ_of_forall $ λ b,
⟨a, a⁻¹ • b, ha, trivial, smul_inv_smul₀ ha₀ _⟩
lemma smul_set_univ₀ (ha : a ≠ 0) : a • (univ : set β) = univ :=
eq_univ_of_forall $ λ b, ⟨a⁻¹ • b, trivial, smul_inv_smul₀ ha _⟩
end group_with_zero
end
namespace finset
variables {a : α} {s s₁ s₂ t t₁ t₂ : finset α}
/-- The finset `(1 : finset α)` is defined as `{1}` in locale `pointwise`. -/
@[to_additive /-"The finset `(0 : finset α)` is defined as `{0}` in locale `pointwise`. "-/]
protected def has_one [has_one α] : has_one (finset α) := ⟨{1}⟩
localized "attribute [instance] finset.has_one finset.has_zero" in pointwise
@[simp, to_additive]
lemma mem_one [has_one α] : a ∈ (1 : finset α) ↔ a = 1 :=
by simp [has_one.one]
@[simp, to_additive]
theorem one_subset [has_one α] : (1 : finset α) ⊆ s ↔ (1 : α) ∈ s := singleton_subset_iff
section decidable_eq
variables [decidable_eq α]
/-- The pointwise product of two finite sets `s` and `t`:
`st = s ⬝ t = s * t = { x * y | x ∈ s, y ∈ t }`. -/
@[to_additive /-"The pointwise sum of two finite sets `s` and `t`:
`s + t = { x + y | x ∈ s, y ∈ t }`. "-/]
protected def has_mul [has_mul α] : has_mul (finset α) :=
⟨λ s t, (s.product t).image (λ p : α × α, p.1 * p.2)⟩
localized "attribute [instance] finset.has_mul finset.has_add" in pointwise
section has_mul
variables [has_mul α]
@[to_additive]
lemma mul_def : s * t = (s.product t).image (λ p : α × α, p.1 * p.2) := rfl
@[to_additive]
lemma mem_mul {x : α} : x ∈ s * t ↔ ∃ y z, y ∈ s ∧ z ∈ t ∧ y * z = x :=
by { simp only [finset.mul_def, and.assoc, mem_image, exists_prop, prod.exists, mem_product] }
@[simp, norm_cast, to_additive]
lemma coe_mul : (↑(s * t) : set α) = ↑s * ↑t :=
by { ext, simp only [mem_mul, set.mem_mul, mem_coe] }
@[to_additive]
lemma mul_mem_mul {x y : α} (hx : x ∈ s) (hy : y ∈ t) : x * y ∈ s * t :=
by { simp only [finset.mem_mul], exact ⟨x, y, hx, hy, rfl⟩ }
@[to_additive]
lemma mul_card_le : (s * t).card ≤ s.card * t.card :=
by { convert finset.card_image_le, rw [finset.card_product, mul_comm] }
@[simp, to_additive] lemma empty_mul (s : finset α) : ∅ * s = ∅ :=
eq_empty_of_forall_not_mem (by simp [mem_mul])
@[simp, to_additive] lemma mul_empty (s : finset α) : s * ∅ = ∅ :=
eq_empty_of_forall_not_mem (by simp [mem_mul])
@[simp, to_additive]
lemma mul_nonempty_iff (s t : finset α) : (s * t).nonempty ↔ s.nonempty ∧ t.nonempty :=
by simp [finset.mul_def]
@[to_additive, mono] lemma mul_subset_mul (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : s₁ * t₁ ⊆ s₂ * t₂ :=
image_subset_image (product_subset_product hs ht)
attribute [mono] add_subset_add
@[simp, to_additive]
lemma mul_singleton (a : α) : s * {a} = s.image (* a) :=
by { rw [mul_def, product_singleton, map_eq_image, image_image], refl }
@[simp, to_additive]
lemma singleton_mul (a : α) : {a} * s = s.image ((*) a) :=
by { rw [mul_def, singleton_product, map_eq_image, image_image], refl }
@[simp, to_additive]
lemma singleton_mul_singleton (a b : α) : ({a} : finset α) * {b} = {a * b} :=
by rw [mul_def, singleton_product_singleton, image_singleton]
end has_mul
section mul_zero_class
variables [mul_zero_class α]
lemma mul_zero_subset (s : finset α) : s * 0 ⊆ 0 := by simp [subset_iff, mem_mul]
lemma zero_mul_subset (s : finset α) : 0 * s ⊆ 0 := by simp [subset_iff, mem_mul]
lemma nonempty.mul_zero (hs : s.nonempty) : s * 0 = 0 :=
s.mul_zero_subset.antisymm $ by simpa [finset.mem_mul] using hs
lemma nonempty.zero_mul (hs : s.nonempty) : 0 * s = 0 :=
s.zero_mul_subset.antisymm $ by simpa [finset.mem_mul] using hs
lemma singleton_zero_mul (s : finset α) :
{(0 : α)} * s ⊆ {0} :=
by simp [subset_iff, mem_mul]
end mul_zero_class
end decidable_eq
open_locale pointwise
variables {u : finset α} {b : α} {x y : β}
@[to_additive]
lemma singleton_one [has_one α] : ({1} : finset α) = 1 := rfl
@[to_additive]
lemma one_mem_one [has_one α] : (1 : α) ∈ (1 : finset α) := by simp [has_one.one]
@[to_additive]
theorem one_nonempty [has_one α] : (1 : finset α).nonempty := ⟨1, one_mem_one⟩
@[simp, to_additive]
theorem image_one [decidable_eq β] [has_one α] {f : α → β} : image f 1 = {f 1} :=
image_singleton f 1
@[to_additive add_image_prod]
lemma image_mul_prod [decidable_eq α] [has_mul α] :
image (λ x : α × α, x.fst * x.snd) (s.product t) = s * t := rfl
@[simp, to_additive]
lemma image_mul_left [decidable_eq α] [group α] :
image (λ b, a * b) t = preimage t (λ b, a⁻¹ * b) (assume x hx y hy, (mul_right_inj a⁻¹).mp) :=
coe_injective $ by simp
@[simp, to_additive]
lemma image_mul_right [decidable_eq α] [group α] :
image (* b) t = preimage t (* b⁻¹) (assume x hx y hy, (mul_left_inj b⁻¹).mp) :=
coe_injective $ by simp
@[to_additive]
lemma image_mul_left' [decidable_eq α] [group α] :
image (λ b, a⁻¹ * b) t = preimage t (λ b, a * b) (assume x hx y hy, (mul_right_inj a).mp) :=
by simp
@[to_additive]
lemma image_mul_right' [decidable_eq α] [group α] :
image (* b⁻¹) t = preimage t (* b) (assume x hx y hy, (mul_left_inj b).mp) :=
by simp
@[simp, to_additive]
lemma preimage_mul_left_singleton [group α] :
preimage {b} ((*) a) (assume x hx y hy, (mul_right_inj a).mp) = {a⁻¹ * b} :=
by { classical, rw [← image_mul_left', image_singleton] }
@[simp, to_additive]
lemma preimage_mul_right_singleton [group α] :
preimage {b} (* a) (assume x hx y hy, (mul_left_inj a).mp) = {b * a⁻¹} :=
by { classical, rw [← image_mul_right', image_singleton] }
@[simp, to_additive]
lemma preimage_mul_left_one [group α] :
preimage 1 (λ b, a * b) (assume x hx y hy, (mul_right_inj a).mp) = {a⁻¹} :=
by {classical, rw [← image_mul_left', image_one, mul_one] }
@[simp, to_additive]
lemma preimage_mul_right_one [group α] :
preimage 1 (* b) (assume x hx y hy, (mul_left_inj b).mp) = {b⁻¹} :=
by {classical, rw [← image_mul_right', image_one, one_mul] }
@[to_additive]
lemma preimage_mul_left_one' [group α] :
preimage 1 (λ b, a⁻¹ * b) (assume x hx y hy, (mul_right_inj _).mp) = {a} := by simp
@[to_additive]
lemma preimage_mul_right_one' [group α] :
preimage 1 (* b⁻¹) (assume x hx y hy, (mul_left_inj _).mp) = {b} := by simp
@[to_additive]
protected lemma mul_comm [decidable_eq α] [comm_semigroup α] : s * t = t * s :=
by exact_mod_cast @set.mul_comm _ (s : set α) t _
/-- `finset α` is a `mul_one_class` under pointwise operations if `α` is. -/
@[to_additive /-"`finset α` is an `add_zero_class` under pointwise operations if `α` is."-/]
protected def mul_one_class [decidable_eq α] [mul_one_class α] : mul_one_class (finset α) :=
function.injective.mul_one_class _ coe_injective (coe_singleton 1) (by simp)
/-- `finset α` is a `semigroup` under pointwise operations if `α` is. -/
@[to_additive /-"`finset α` is an `add_semigroup` under pointwise operations if `α` is. "-/]
protected def semigroup [decidable_eq α] [semigroup α] : semigroup (finset α) :=
function.injective.semigroup _ coe_injective (by simp)
/-- `finset α` is a `monoid` under pointwise operations if `α` is. -/
@[to_additive /-"`finset α` is an `add_monoid` under pointwise operations if `α` is. "-/]
protected def monoid [decidable_eq α] [monoid α] : monoid (finset α) :=
function.injective.monoid _ coe_injective (coe_singleton 1) (by simp)
/-- `finset α` is a `comm_monoid` under pointwise operations if `α` is. -/
@[to_additive /-"`finset α` is an `add_comm_monoid` under pointwise operations if `α` is. "-/]
protected def comm_monoid [decidable_eq α] [comm_monoid α] : comm_monoid (finset α) :=
function.injective.comm_monoid _ coe_injective (coe_singleton 1) (by simp)
localized "attribute [instance] finset.mul_one_class finset.add_zero_class finset.semigroup
finset.add_semigroup finset.monoid finset.add_monoid finset.comm_monoid finset.add_comm_monoid"
in pointwise
open_locale classical
/-- A finite set `U` contained in the product of two sets `S * S'` is also contained in the product
of two finite sets `T * T' ⊆ S * S'`. -/
@[to_additive]
lemma subset_mul {M : Type*} [monoid M] {S : set M} {S' : set M} {U : finset M} (f : ↑U ⊆ S * S') :
∃ (T T' : finset M), ↑T ⊆ S ∧ ↑T' ⊆ S' ∧ U ⊆ T * T' :=
begin
apply finset.induction_on' U,
{ use [∅, ∅], simp only [finset.empty_subset, finset.coe_empty, set.empty_subset, and_self], },
rintros a s haU hs has ⟨T, T', hS, hS', h⟩,
obtain ⟨x, y, hx, hy, ha⟩ := set.mem_mul.1 (f haU),
use [insert x T, insert y T'],
simp only [finset.coe_insert],
repeat { rw [set.insert_subset], },
use [hx, hS, hy, hS'],
refine finset.insert_subset.mpr ⟨_, _⟩,
{ rw finset.mem_mul,
use [x,y],
simpa only [true_and, true_or, eq_self_iff_true, finset.mem_insert], },
{ suffices g : (s : set M) ⊆ insert x T * insert y T', { norm_cast at g, assumption, },
transitivity ↑(T * T'),
apply h,
rw finset.coe_mul,
apply set.mul_subset_mul (set.subset_insert x T) (set.subset_insert y T'), },
end
end finset
/-! Some lemmas about pointwise multiplication and submonoids. Ideally we put these in
`group_theory.submonoid.basic`, but currently we cannot because that file is imported by this. -/
namespace submonoid
variables {M : Type*} [monoid M] {s t u : set M}
@[to_additive]
lemma mul_subset {S : submonoid M} (hs : s ⊆ S) (ht : t ⊆ S) : s * t ⊆ S :=
by { rintro _ ⟨p, q, hp, hq, rfl⟩, exact submonoid.mul_mem _ (hs hp) (ht hq) }
@[to_additive]
lemma mul_subset_closure (hs : s ⊆ u) (ht : t ⊆ u) : s * t ⊆ submonoid.closure u :=
mul_subset (subset.trans hs submonoid.subset_closure) (subset.trans ht submonoid.subset_closure)
@[to_additive]
lemma coe_mul_self_eq (s : submonoid M) : (s : set M) * s = s :=
begin
ext x,
refine ⟨_, λ h, ⟨x, 1, h, s.one_mem, mul_one x⟩⟩,
rintros ⟨a, b, ha, hb, rfl⟩,
exact s.mul_mem ha hb
end
@[to_additive]
lemma closure_mul_le (S T : set M) : closure (S * T) ≤ closure S ⊔ closure T :=
Inf_le $ λ x ⟨s, t, hs, ht, hx⟩, hx ▸ (closure S ⊔ closure T).mul_mem
(set_like.le_def.mp le_sup_left $ subset_closure hs)
(set_like.le_def.mp le_sup_right $ subset_closure ht)
@[to_additive]
lemma sup_eq_closure (H K : submonoid M) : H ⊔ K = closure (H * K) :=
le_antisymm
(sup_le
(λ h hh, subset_closure ⟨h, 1, hh, K.one_mem, mul_one h⟩)
(λ k hk, subset_closure ⟨1, k, H.one_mem, hk, one_mul k⟩))
(by conv_rhs { rw [← closure_eq H, ← closure_eq K] }; apply closure_mul_le)
lemma pow_smul_mem_closure_smul {N : Type*} [comm_monoid N] [mul_action M N]
[is_scalar_tower M N N] (r : M) (s : set N) {x : N} (hx : x ∈ closure s) :
∃ n : ℕ, r ^ n • x ∈ closure (r • s) :=
begin
apply @closure_induction N _ s
(λ (x : N), ∃ n : ℕ, r ^ n • x ∈ closure (r • s)) _ hx,
{ intros x hx,
exact ⟨1, subset_closure ⟨_, hx, by rw pow_one⟩⟩ },
{ exact ⟨0, by simpa using one_mem _⟩ },
{ rintros x y ⟨nx, hx⟩ ⟨ny, hy⟩,
use nx + ny,
convert mul_mem _ hx hy,
rw [pow_add, smul_mul_assoc, mul_smul, mul_comm, ← smul_mul_assoc, mul_comm] }
end
end submonoid
namespace group
lemma card_pow_eq_card_pow_card_univ_aux {f : ℕ → ℕ} (h1 : monotone f)
{B : ℕ} (h2 : ∀ n, f n ≤ B) (h3 : ∀ n, f n = f (n + 1) → f (n + 1) = f (n + 2)) :
∀ k, B ≤ k → f k = f B :=
begin
have key : ∃ n : ℕ, n ≤ B ∧ f n = f (n + 1),
{ contrapose! h2,
suffices : ∀ n : ℕ, n ≤ B + 1 → n ≤ f n,
{ exact ⟨B + 1, this (B + 1) (le_refl (B + 1))⟩ },
exact λ n, nat.rec (λ h, nat.zero_le (f 0)) (λ n ih h, lt_of_le_of_lt (ih (n.le_succ.trans h))
(lt_of_le_of_ne (h1 n.le_succ) (h2 n (nat.succ_le_succ_iff.mp h)))) n },
{ obtain ⟨n, hn1, hn2⟩ := key,
replace key : ∀ k : ℕ, f (n + k) = f (n + k + 1) ∧ f (n + k) = f n :=
λ k, nat.rec ⟨hn2, rfl⟩ (λ k ih, ⟨h3 _ ih.1, ih.1.symm.trans ih.2⟩) k,
replace key : ∀ k : ℕ, n ≤ k → f k = f n :=
λ k hk, (congr_arg f (add_tsub_cancel_of_le hk)).symm.trans (key (k - n)).2,
exact λ k hk, (key k (hn1.trans hk)).trans (key B hn1).symm },
end
variables {G : Type*} [group G] [fintype G] (S : set G)
@[to_additive]
lemma card_pow_eq_card_pow_card_univ [∀ (k : ℕ), decidable_pred (∈ (S ^ k))] :
∀ k, fintype.card G ≤ k → fintype.card ↥(S ^ k) = fintype.card ↥(S ^ (fintype.card G)) :=
begin
have hG : 0 < fintype.card G := fintype.card_pos_iff.mpr ⟨1⟩,
by_cases hS : S = ∅,
{ refine λ k hk, fintype.card_congr _,
rw [hS, empty_pow _ (ne_of_gt (lt_of_lt_of_le hG hk)), empty_pow _ (ne_of_gt hG)] },
obtain ⟨a, ha⟩ := set.ne_empty_iff_nonempty.mp hS,
classical,
have key : ∀ a (s t : set G), (∀ b : G, b ∈ s → a * b ∈ t) → fintype.card s ≤ fintype.card t,
{ refine λ a s t h, fintype.card_le_of_injective (λ ⟨b, hb⟩, ⟨a * b, h b hb⟩) _,
rintros ⟨b, hb⟩ ⟨c, hc⟩ hbc,
exact subtype.ext (mul_left_cancel (subtype.ext_iff.mp hbc)) },
have mono : monotone (λ n, fintype.card ↥(S ^ n) : ℕ → ℕ) :=
monotone_nat_of_le_succ (λ n, key a _ _ (λ b hb, set.mul_mem_mul ha hb)),
convert card_pow_eq_card_pow_card_univ_aux mono (λ n, set_fintype_card_le_univ (S ^ n))
(λ n h, le_antisymm (mono (n + 1).le_succ) (key a⁻¹ _ _ _)),
{ simp only [finset.filter_congr_decidable, fintype.card_of_finset] },
replace h : {a} * S ^ n = S ^ (n + 1),
{ refine set.eq_of_subset_of_card_le _ (le_trans (ge_of_eq h) _),
{ exact mul_subset_mul (set.singleton_subset_iff.mpr ha) set.subset.rfl },
{ convert key a (S ^ n) ({a} * S ^ n) (λ b hb, set.mul_mem_mul (set.mem_singleton a) hb) } },
rw [pow_succ', ←h, mul_assoc, ←pow_succ', h],
rintros _ ⟨b, c, hb, hc, rfl⟩,
rwa [set.mem_singleton_iff.mp hb, inv_mul_cancel_left],
end
end group
|
-- @@stderr --
dtrace: failed to compile script test/unittest/stack/err.D_STACK_PROTO.bad.d: [D_STACK_PROTO] line 19: stack( ) prototype mismatch: too many arguments
|
import DFA
import data.fintype.basic
import order.boolean_algebra
import data.quot
universes u v
def is_regular {α : Type u} [fintype α] (l : language α) : Prop :=
∃ (σ : Type v) [fintype σ] (A : DFA α σ), A.accepts = l
lemma is_regular_def {α : Type u} [fintype α] {l : language α} :
(is_regular.{u v}) l ↔ (∃ (σ : Type v) [fintype σ] (A : DFA α σ), A.accepts = l) :=
iff.refl _
namespace regular_language
open DFA
section basic
/--
Here we prove basic things on regular languages, such as the they form a boolean algebra
-/
variables {α : Type u} [fintype α]
variables {l l' : language α}
lemma inf_regular : (is_regular.{u v} l) → (is_regular.{u v} l') → is_regular.{u v} (l ⊓ l') :=
begin
rintros ⟨σ, hσ, A, hA⟩,
rintros ⟨τ, hτ, B, hB⟩,
resetI,
refine ⟨σ × τ, infer_instance, inter A B, _⟩,
rw [inter_accepts, hA, hB],
end
lemma compl_regular : (is_regular.{u v} l) → (is_regular.{u v} lᶜ) :=
begin
rintros ⟨Q, hQ, A, hA⟩,
refine ⟨Q, hQ, A.compl, _⟩,
rw [compl_accepts, hA]
end
lemma compl_regular_iff : (is_regular.{u v} lᶜ) ↔ (is_regular.{u v} l) :=
begin
split,
{
intro h,
rw ← compl_compl l,
exact compl_regular h
},
{ exact compl_regular },
end
lemma sup_regular : (is_regular.{u v} l) → (is_regular.{u v} l') → is_regular.{u v} (l ⊔ l') :=
begin
intros hl hl',
rw [←compl_compl (l ⊔ l'), compl_sup, compl_regular_iff],
exact inf_regular (compl_regular hl) (compl_regular hl'),
end
end basic
section relation
/-!
### Myhill-Nerode theorem
Given `l`, we define an equivalence relation on `list α`.
The main theorem is that `l` is regular iff the number of
equivalence classes of this relation is finite.
-/
parameters {α : Type u} [fintype α]
section basic
parameters (l : language α)
/--
A relation on `list α`, identifying `x, y` if for all
`z : list α`, `(x ++ z ∈ l) ↔ (y ++ z ∈ l)`.
-/
def rel : list α → list α → Prop :=
λ x y, ∀ (z : list α), (x ++ z ∈ l) ↔ (y ++ z ∈ l)
parameter {l}
lemma iff_mem_language_of_equiv {x y : list α} (Rxy : rel x y) : x ∈ l ↔ y ∈ l :=
begin
specialize Rxy [],
repeat {rwa list.append_nil at Rxy},
end
parameter (l)
lemma rel_refl : reflexive (rel) := λ _ _, by refl
lemma rel_symm : symmetric (rel) := λ _ _ hxy z, iff.symm (hxy z)
lemma rel_trans : transitive (rel) := λ _ _ _ hxy hyz z, iff.trans (hxy z) (hyz z)
lemma rel_equiv : equivalence (rel) := ⟨rel_refl, rel_symm, rel_trans⟩
instance space.setoid : setoid (list α) := setoid.mk rel rel_equiv
definition space := quotient space.setoid
parameter {l}
definition mk (x : list α) : space := @quotient.mk _ space.setoid x
@[simp] lemma mk_def (x : list α) : mk x = @quotient.mk _ space.setoid x := rfl
end basic
section finite_class_space
/-!
### Myhill-Nerode, first direction
We build an automaton accepting `l` whose states are `space l`.
As a consequence, if `space l` is finite, then `l` is regular.
-/
parameters (l : language α)
def to_DFA : DFA α (space l) :=
{
step := begin
apply quot.lift (λ (z : list α) (σ : α), (mk (z ++ [σ]) : space l)),
intros x y r,
ext σ,
simp only [regular_language.mk_def, quotient.eq],
intro z,
simp [r (σ :: z)],
end,
start := mk [],
accept := begin
apply quot.lift (∈ l),
intros x y r,
simp [iff_mem_language_of_equiv r],
end
}
@[simp] lemma to_DFA_step (w : list α) (σ : α) : to_DFA.step (mk w) σ = mk (w ++ [σ]) := rfl
@[simp] lemma to_DFA_start : to_DFA.start = mk [] := rfl
@[simp] lemma to_DFA_accept (w : list α) : (mk w) ∈ to_DFA.accept ↔ w ∈ l := by refl
@[simp] lemma to_DFA_eval_from (x y : list α) : eval_from to_DFA (mk x) y = mk (x ++ y) :=
begin
induction y with σ y generalizing x,
{
simp,
exact rel_refl l _,
},
{
specialize y_ih (x ++ [σ]),
simp at *,
exact y_ih,
}
end
lemma to_DFA_accepts : accepts to_DFA = l :=
begin
ext,
rw [mem_accepts, to_DFA_start, to_DFA_eval_from, list.nil_append, to_DFA_accept],
end
theorem regular_of_fintype_language_space [fintype (space l)] : is_regular.{u u} l :=
⟨space l, infer_instance, to_DFA, to_DFA_accepts⟩
end finite_class_space
section regular
/-!
### Myhill-Nerode, the other direction.
Now we wish to prove that if `l` is regular then `space l` is finite.
We prove this using the canonical functions `Q ↩ DFA_space ↠ space l`,
the first of which we constructed in DFA.relation.
-/
parameters {Q : Type u} (A : DFA α Q)
private def l := A.accepts
@[simp] private lemma l_def : l = A.accepts := rfl
lemma language_rel_of_DFA_rel (x y : list α) : A.rel x y → rel l x y :=
begin
intros r z,
rw rel_def at r,
rw [l_def, mem_accepts, mem_accepts, eval_from_of_append, eval_from_of_append,
← eval_def, ← eval_def, r],
end
definition language_space_of_DFA_space : A.space → space l :=
by exact quot.map id (language_rel_of_DFA_rel _)
@[simp] lemma language_space_of_DFA_space_def (w : list α) :
language_space_of_DFA_space (DFA.space.mk w) = mk w := rfl
lemma language_space_of_DFA_space_surjective : function.surjective language_space_of_DFA_space :=
begin
apply quotient.ind,
intro w,
use DFA.space.mk w,
rw language_space_of_DFA_space_def,
refl
end
open classical
local attribute [instance] prop_decidable
noncomputable instance fintype_language_space_of_regular (l : language α) (r : is_regular l) :
fintype (space l) :=
begin
choose Q fQ A hA using r,
rw ← hA,
resetI,
haveI : fintype A.space := DFA.fintype_space_of_fintype_states _,
exact fintype.of_surjective _ (language_space_of_DFA_space_surjective _),
end
end regular
end relation
end regular_language
variable (α : Type u)
|
[STATEMENT]
lemma finite_Edges[iff]: "finite(Edges xs)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. finite (Edges xs)
[PROOF STEP]
by(induct xs)(simp_all add:Edges_Cons) |
Formal statement is: proposition isometries_subspaces: fixes S :: "'a::euclidean_space set" and T :: "'b::euclidean_space set" assumes S: "subspace S" and T: "subspace T" and d: "dim S = dim T" obtains f g where "linear f" "linear g" "f ` S = T" "g ` T = S" "\<And>x. x \<in> S \<Longrightarrow> norm(f x) = norm x" "\<And>x. x \<in> T \<Longrightarrow> norm(g x) = norm x" "\<And>x. x \<in> S \<Longrightarrow> g(f x) = x" "\<And>x. x \<in> T \<Longrightarrow> f(g x) = x" Informal statement is: If two subspaces of Euclidean space have the same dimension, then there exist linear isometries between them. |
theory T144
imports Main
begin
lemma "(
(\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) &
(\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) &
(\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) &
(\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) &
(\<forall> x::nat. invo(invo(x)) = x)
) \<longrightarrow>
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z)))
"
nitpick[card nat=8,timeout=86400]
oops
end |
/-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Floris van Doorn
-/
import algebra.big_operators.basic
import algebra.smul_with_zero
import data.set.finite
import group_theory.group_action.group
import group_theory.submonoid.basic
/-!
# Pointwise addition, multiplication, and scalar multiplication of sets.
This file defines pointwise algebraic operations on sets.
* For a type `α` with multiplication, multiplication is defined on `set α` by taking
`s * t` to be the set of all `x * y` where `x ∈ s` and `y ∈ t`. Similarly for addition.
* For `α` a semigroup, `set α` is a semigroup.
* If `α` is a (commutative) monoid, we define an alias `set_semiring α` for `set α`, which then
becomes a (commutative) semiring with union as addition and pointwise multiplication as
multiplication.
* For a type `β` with scalar multiplication by another type `α`, this
file defines a scalar multiplication of `set β` by `set α` and a separate scalar
multiplication of `set β` by `α`.
* We also define pointwise multiplication on `finset`.
Appropriate definitions and results are also transported to the additive theory via `to_additive`.
## Implementation notes
* The following expressions are considered in simp-normal form in a group:
`(λ h, h * g) ⁻¹' s`, `(λ h, g * h) ⁻¹' s`, `(λ h, h * g⁻¹) ⁻¹' s`, `(λ h, g⁻¹ * h) ⁻¹' s`,
`s * t`, `s⁻¹`, `(1 : set _)` (and similarly for additive variants).
Expressions equal to one of these will be simplified.
* We put all instances in the locale `pointwise`, so that these instances are not available by
default. Note that we do not mark them as reducible (as argued by note [reducible non-instances])
since we expect the locale to be open whenever the instances are actually used (and making the
instances reducible changes the behavior of `simp`).
## Tags
set multiplication, set addition, pointwise addition, pointwise multiplication
-/
namespace set
open function
variables {α : Type*} {β : Type*} {s s₁ s₂ t t₁ t₂ u : set α} {a b : α} {x y : β}
/-! ### Properties about 1 -/
/-- The set `(1 : set α)` is defined as `{1}` in locale `pointwise`. -/
@[to_additive
/-"The set `(0 : set α)` is defined as `{0}` in locale `pointwise`. "-/]
protected def has_one [has_one α] : has_one (set α) := ⟨{1}⟩
localized "attribute [instance] set.has_one set.has_zero" in pointwise
@[to_additive]
lemma singleton_one [has_one α] : ({1} : set α) = 1 := rfl
@[simp, to_additive]
lemma mem_one [has_one α] : a ∈ (1 : set α) ↔ a = 1 := iff.rfl
@[to_additive]
lemma one_mem_one [has_one α] : (1 : α) ∈ (1 : set α) := eq.refl _
@[simp, to_additive]
theorem one_subset [has_one α] : 1 ⊆ s ↔ (1 : α) ∈ s := singleton_subset_iff
@[to_additive]
theorem one_nonempty [has_one α] : (1 : set α).nonempty := ⟨1, rfl⟩
@[simp, to_additive]
theorem image_one [has_one α] {f : α → β} : f '' 1 = {f 1} := image_singleton
/-! ### Properties about multiplication -/
/-- The set `(s * t : set α)` is defined as `{x * y | x ∈ s, y ∈ t}` in locale `pointwise`. -/
@[to_additive
/-" The set `(s + t : set α)` is defined as `{x + y | x ∈ s, y ∈ t}` in locale `pointwise`."-/]
protected def has_mul [has_mul α] : has_mul (set α) := ⟨image2 has_mul.mul⟩
localized "attribute [instance] set.has_mul set.has_add" in pointwise
@[simp, to_additive]
lemma image2_mul [has_mul α] : image2 has_mul.mul s t = s * t := rfl
@[to_additive]
lemma mem_mul [has_mul α] : a ∈ s * t ↔ ∃ x y, x ∈ s ∧ y ∈ t ∧ x * y = a := iff.rfl
@[to_additive]
lemma mul_mem_mul [has_mul α] (ha : a ∈ s) (hb : b ∈ t) : a * b ∈ s * t := mem_image2_of_mem ha hb
@[to_additive add_image_prod]
lemma image_mul_prod [has_mul α] : (λ x : α × α, x.fst * x.snd) '' s.prod t = s * t := image_prod _
@[simp, to_additive]
lemma image_mul_left [group α] : (λ b, a * b) '' t = (λ b, a⁻¹ * b) ⁻¹' t :=
by { rw image_eq_preimage_of_inverse; intro c; simp }
@[simp, to_additive]
lemma image_mul_right [group α] : (λ a, a * b) '' t = (λ a, a * b⁻¹) ⁻¹' t :=
by { rw image_eq_preimage_of_inverse; intro c; simp }
@[to_additive]
lemma image_mul_left' [group α] : (λ b, a⁻¹ * b) '' t = (λ b, a * b) ⁻¹' t := by simp
@[to_additive]
lemma image_mul_right' [group α] : (λ a, a * b⁻¹) '' t = (λ a, a * b) ⁻¹' t := by simp
@[simp, to_additive]
lemma preimage_mul_left_singleton [group α] : ((*) a) ⁻¹' {b} = {a⁻¹ * b} :=
by rw [← image_mul_left', image_singleton]
@[simp, to_additive]
lemma preimage_mul_right_singleton [group α] : (* a) ⁻¹' {b} = {b * a⁻¹} :=
by rw [← image_mul_right', image_singleton]
@[simp, to_additive]
lemma preimage_mul_left_one [group α] : (λ b, a * b) ⁻¹' 1 = {a⁻¹} :=
by rw [← image_mul_left', image_one, mul_one]
@[simp, to_additive]
lemma preimage_mul_right_one [group α] : (λ a, a * b) ⁻¹' 1 = {b⁻¹} :=
by rw [← image_mul_right', image_one, one_mul]
@[to_additive]
lemma preimage_mul_left_one' [group α] : (λ b, a⁻¹ * b) ⁻¹' 1 = {a} := by simp
@[to_additive]
lemma preimage_mul_right_one' [group α] : (λ a, a * b⁻¹) ⁻¹' 1 = {b} := by simp
@[simp, to_additive]
lemma mul_singleton [has_mul α] : s * {b} = (λ a, a * b) '' s := image2_singleton_right
@[simp, to_additive]
lemma singleton_mul [has_mul α] : {a} * t = (λ b, a * b) '' t := image2_singleton_left
@[simp, to_additive]
lemma singleton_mul_singleton [has_mul α] : ({a} : set α) * {b} = {a * b} := image2_singleton
@[to_additive]
protected lemma mul_comm [comm_semigroup α] : s * t = t * s :=
by simp only [← image2_mul, image2_swap _ s, mul_comm]
/-- `set α` is a `mul_one_class` under pointwise operations if `α` is. -/
@[to_additive /-"`set α` is an `add_zero_class` under pointwise operations if `α` is."-/]
protected def mul_one_class [mul_one_class α] : mul_one_class (set α) :=
{ mul_one := λ s, by { simp only [← singleton_one, mul_singleton, mul_one, image_id'] },
one_mul := λ s, by { simp only [← singleton_one, singleton_mul, one_mul, image_id'] },
..set.has_one, ..set.has_mul }
/-- `set α` is a `semigroup` under pointwise operations if `α` is. -/
@[to_additive /-"`set α` is an `add_semigroup` under pointwise operations if `α` is. "-/]
protected def semigroup [semigroup α] : semigroup (set α) :=
{ mul_assoc := λ _ _ _, image2_assoc mul_assoc,
..set.has_mul }
/-- `set α` is a `monoid` under pointwise operations if `α` is. -/
@[to_additive /-"`set α` is an `add_monoid` under pointwise operations if `α` is. "-/]
protected def monoid [monoid α] : monoid (set α) :=
{ ..set.semigroup,
..set.mul_one_class }
/-- `set α` is a `comm_monoid` under pointwise operations if `α` is. -/
@[to_additive /-"`set α` is an `add_comm_monoid` under pointwise operations if `α` is. "-/]
protected def comm_monoid [comm_monoid α] : comm_monoid (set α) :=
{ mul_comm := λ _ _, set.mul_comm, ..set.monoid }
localized "attribute [instance] set.mul_one_class set.add_zero_class set.semigroup set.add_semigroup
set.monoid set.add_monoid set.comm_monoid set.add_comm_monoid" in pointwise
lemma pow_mem_pow [monoid α] (ha : a ∈ s) (n : ℕ) :
a ^ n ∈ s ^ n :=
begin
induction n with n ih,
{ rw pow_zero,
exact set.mem_singleton 1 },
{ rw pow_succ,
exact set.mul_mem_mul ha ih },
end
/-- Under `[has_mul M]`, the `singleton` map from `M` to `set M` as a `mul_hom`, that is, a map
which preserves multiplication. -/
@[to_additive "Under `[has_add A]`, the `singleton` map from `A` to `set A` as an `add_hom`,
that is, a map which preserves addition.", simps]
def singleton_mul_hom [has_mul α] : mul_hom α (set α) :=
{ to_fun := singleton,
map_mul' := λ a b, singleton_mul_singleton.symm }
@[simp, to_additive]
lemma empty_mul [has_mul α] : ∅ * s = ∅ := image2_empty_left
@[simp, to_additive]
lemma mul_empty [has_mul α] : s * ∅ = ∅ := image2_empty_right
lemma empty_pow [monoid α] (n : ℕ) (hn : n ≠ 0) : (∅ : set α) ^ n = ∅ :=
by rw [← tsub_add_cancel_of_le (nat.succ_le_of_lt $ nat.pos_of_ne_zero hn), pow_succ, empty_mul]
instance decidable_mem_mul [monoid α] [fintype α] [decidable_eq α]
[decidable_pred (∈ s)] [decidable_pred (∈ t)] :
decidable_pred (∈ s * t) :=
λ _, decidable_of_iff _ mem_mul.symm
instance decidable_mem_pow [monoid α] [fintype α] [decidable_eq α]
[decidable_pred (∈ s)] (n : ℕ) :
decidable_pred (∈ (s ^ n)) :=
begin
induction n with n ih,
{ simp_rw [pow_zero, mem_one], apply_instance },
{ letI := ih, rw pow_succ, apply_instance }
end
@[to_additive]
lemma mul_subset_mul [has_mul α] (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ * s₂ ⊆ t₁ * t₂ :=
image2_subset h₁ h₂
lemma pow_subset_pow [monoid α] (hst : s ⊆ t) (n : ℕ) :
s ^ n ⊆ t ^ n :=
begin
induction n with n ih,
{ rw pow_zero,
exact subset.rfl },
{ rw [pow_succ, pow_succ],
exact mul_subset_mul hst ih },
end
@[to_additive]
lemma union_mul [has_mul α] : (s ∪ t) * u = (s * u) ∪ (t * u) := image2_union_left
@[to_additive]
lemma mul_union [has_mul α] : s * (t ∪ u) = (s * t) ∪ (s * u) := image2_union_right
@[to_additive]
lemma Union_mul_left_image [has_mul α] : (⋃ a ∈ s, (λ x, a * x) '' t) = s * t :=
Union_image_left _
@[to_additive]
lemma Union_mul_right_image [has_mul α] : (⋃ a ∈ t, (λ x, x * a) '' s) = s * t :=
Union_image_right _
@[to_additive]
lemma Union_mul {ι : Sort*} [has_mul α] (s : ι → set α) (t : set α) :
(⋃ i, s i) * t = ⋃ i, (s i * t) :=
image2_Union_left _ _ _
@[to_additive]
lemma mul_Union {ι : Sort*} [has_mul α] (t : set α) (s : ι → set α) :
t * (⋃ i, s i) = ⋃ i, (t * s i) :=
image2_Union_right _ _ _
@[simp, to_additive]
lemma univ_mul_univ [monoid α] : (univ : set α) * univ = univ :=
begin
have : ∀x, ∃a b : α, a * b = x := λx, ⟨x, ⟨1, mul_one x⟩⟩,
simpa only [mem_mul, eq_univ_iff_forall, mem_univ, true_and]
end
/-- `singleton` is a monoid hom. -/
@[to_additive singleton_add_hom "singleton is an add monoid hom"]
def singleton_hom [monoid α] : α →* set α :=
{ to_fun := singleton, map_one' := rfl, map_mul' := λ a b, singleton_mul_singleton.symm }
@[to_additive]
lemma nonempty.mul [has_mul α] : s.nonempty → t.nonempty → (s * t).nonempty := nonempty.image2
@[to_additive]
lemma finite.mul [has_mul α] (hs : finite s) (ht : finite t) : finite (s * t) :=
hs.image2 _ ht
/-- multiplication preserves finiteness -/
@[to_additive "addition preserves finiteness"]
def fintype_mul [has_mul α] [decidable_eq α] (s t : set α) [hs : fintype s] [ht : fintype t] :
fintype (s * t : set α) :=
set.fintype_image2 _ s t
@[to_additive]
lemma bdd_above_mul [ordered_comm_monoid α] {A B : set α} :
bdd_above A → bdd_above B → bdd_above (A * B) :=
begin
rintros ⟨bA, hbA⟩ ⟨bB, hbB⟩,
use bA * bB,
rintros x ⟨xa, xb, hxa, hxb, rfl⟩,
exact mul_le_mul' (hbA hxa) (hbB hxb),
end
section big_operators
open_locale big_operators
variables {ι : Type*} [comm_monoid α]
/-- The n-ary version of `set.mem_mul`. -/
@[to_additive /-" The n-ary version of `set.mem_add`. "-/]
lemma mem_finset_prod (t : finset ι) (f : ι → set α) (a : α) :
a ∈ ∏ i in t, f i ↔ ∃ (g : ι → α) (hg : ∀ {i}, i ∈ t → g i ∈ f i), ∏ i in t, g i = a :=
begin
classical,
induction t using finset.induction_on with i is hi ih generalizing a,
{ simp_rw [finset.prod_empty, set.mem_one],
exact ⟨λ h, ⟨λ i, a, λ i, false.elim, h.symm⟩, λ ⟨f, _, hf⟩, hf.symm⟩ },
rw [finset.prod_insert hi, set.mem_mul],
simp_rw [finset.prod_insert hi],
simp_rw ih,
split,
{ rintros ⟨x, y, hx, ⟨g, hg, rfl⟩, rfl⟩,
refine ⟨function.update g i x, λ j hj, _, _⟩,
obtain rfl | hj := finset.mem_insert.mp hj,
{ rw function.update_same, exact hx },
{ rw update_noteq (ne_of_mem_of_not_mem hj hi), exact hg hj, },
rw [finset.prod_update_of_not_mem hi, function.update_same], },
{ rintros ⟨g, hg, rfl⟩,
exact ⟨g i, is.prod g, hg (is.mem_insert_self _),
⟨g, λ i hi, hg (finset.mem_insert_of_mem hi), rfl⟩, rfl⟩ },
end
/-- A version of `set.mem_finset_prod` with a simpler RHS for products over a fintype. -/
@[to_additive /-" A version of `set.mem_finset_sum` with a simpler RHS for sums over a fintype. "-/]
lemma mem_fintype_prod [fintype ι] (f : ι → set α) (a : α) :
a ∈ ∏ i, f i ↔ ∃ (g : ι → α) (hg : ∀ i, g i ∈ f i), ∏ i, g i = a :=
by { rw mem_finset_prod, simp }
/-- The n-ary version of `set.mul_mem_mul`. -/
@[to_additive /-" The n-ary version of `set.add_mem_add`. "-/]
lemma finset_prod_mem_finset_prod (t : finset ι) (f : ι → set α)
(g : ι → α) (hg : ∀ i ∈ t, g i ∈ f i) :
∏ i in t, g i ∈ ∏ i in t, f i :=
by { rw mem_finset_prod, exact ⟨g, hg, rfl⟩ }
/-- The n-ary version of `set.mul_subset_mul`. -/
@[to_additive /-" The n-ary version of `set.add_subset_add`. "-/]
lemma finset_prod_subset_finset_prod (t : finset ι) (f₁ f₂ : ι → set α)
(hf : ∀ {i}, i ∈ t → f₁ i ⊆ f₂ i) :
∏ i in t, f₁ i ⊆ ∏ i in t, f₂ i :=
begin
intro a,
rw [mem_finset_prod, mem_finset_prod],
rintro ⟨g, hg, rfl⟩,
exact ⟨g, λ i hi, hf hi $ hg hi, rfl⟩
end
@[to_additive]
lemma finset_prod_singleton {M ι : Type*} [comm_monoid M] (s : finset ι) (I : ι → M) :
∏ (i : ι) in s, ({I i} : set M) = {∏ (i : ι) in s, I i} :=
begin
letI := classical.dec_eq ι,
refine finset.induction_on s _ _,
{ simpa },
{ intros _ _ H ih,
rw [finset.prod_insert H, finset.prod_insert H, ih],
simp }
end
/-! TODO: define `decidable_mem_finset_prod` and `decidable_mem_finset_sum`. -/
end big_operators
/-! ### Properties about inversion -/
/-- The set `(s⁻¹ : set α)` is defined as `{x | x⁻¹ ∈ s}` in locale `pointwise`.
It is equal to `{x⁻¹ | x ∈ s}`, see `set.image_inv`. -/
@[to_additive
/-" The set `(-s : set α)` is defined as `{x | -x ∈ s}` in locale `pointwise`.
It is equal to `{-x | x ∈ s}`, see `set.image_neg`. "-/]
protected def has_inv [has_inv α] : has_inv (set α) :=
⟨preimage has_inv.inv⟩
localized "attribute [instance] set.has_inv set.has_neg" in pointwise
@[simp, to_additive]
lemma inv_empty [has_inv α] : (∅ : set α)⁻¹ = ∅ := rfl
@[simp, to_additive]
lemma inv_univ [has_inv α] : (univ : set α)⁻¹ = univ := rfl
@[simp, to_additive]
lemma nonempty_inv [group α] {s : set α} : s⁻¹.nonempty ↔ s.nonempty :=
inv_involutive.surjective.nonempty_preimage
@[to_additive] lemma nonempty.inv [group α] {s : set α} (h : s.nonempty) : s⁻¹.nonempty :=
nonempty_inv.2 h
@[simp, to_additive]
lemma mem_inv [has_inv α] : a ∈ s⁻¹ ↔ a⁻¹ ∈ s := iff.rfl
@[to_additive]
lemma inv_mem_inv [group α] : a⁻¹ ∈ s⁻¹ ↔ a ∈ s :=
by simp only [mem_inv, inv_inv]
@[simp, to_additive]
lemma inv_preimage [has_inv α] : has_inv.inv ⁻¹' s = s⁻¹ := rfl
@[simp, to_additive]
lemma image_inv [group α] : has_inv.inv '' s = s⁻¹ :=
by { simp only [← inv_preimage], rw [image_eq_preimage_of_inverse]; intro; simp only [inv_inv] }
@[simp, to_additive]
lemma inter_inv [has_inv α] : (s ∩ t)⁻¹ = s⁻¹ ∩ t⁻¹ := preimage_inter
@[simp, to_additive]
lemma union_inv [has_inv α] : (s ∪ t)⁻¹ = s⁻¹ ∪ t⁻¹ := preimage_union
@[simp, to_additive]
lemma Inter_inv {ι : Sort*} [has_inv α] (s : ι → set α) : (⋂ i, s i)⁻¹ = ⋂ i, (s i)⁻¹ :=
preimage_Inter
@[simp, to_additive]
lemma Union_inv {ι : Sort*} [has_inv α] (s : ι → set α) : (⋃ i, s i)⁻¹ = ⋃ i, (s i)⁻¹ :=
preimage_Union
@[simp, to_additive]
lemma compl_inv [has_inv α] : (sᶜ)⁻¹ = (s⁻¹)ᶜ := preimage_compl
@[simp, to_additive]
protected lemma inv_inv [group α] : s⁻¹⁻¹ = s :=
by { simp only [← inv_preimage, preimage_preimage, inv_inv, preimage_id'] }
@[simp, to_additive]
protected lemma univ_inv [group α] : (univ : set α)⁻¹ = univ := preimage_univ
@[simp, to_additive]
lemma inv_subset_inv [group α] {s t : set α} : s⁻¹ ⊆ t⁻¹ ↔ s ⊆ t :=
(equiv.inv α).surjective.preimage_subset_preimage_iff
@[to_additive] lemma inv_subset [group α] {s t : set α} : s⁻¹ ⊆ t ↔ s ⊆ t⁻¹ :=
by { rw [← inv_subset_inv, set.inv_inv] }
@[to_additive] lemma finite.inv [group α] {s : set α} (hs : finite s) : finite s⁻¹ :=
hs.preimage $ inv_injective.inj_on _
@[to_additive] lemma inv_singleton {β : Type*} [group β] (x : β) : ({x} : set β)⁻¹ = {x⁻¹} :=
by { ext1 y, rw [mem_inv, mem_singleton_iff, mem_singleton_iff, inv_eq_iff_inv_eq, eq_comm], }
@[to_additive] protected lemma mul_inv_rev [group α] (s t : set α) : (s * t)⁻¹ = t⁻¹ * s⁻¹ :=
by simp_rw [←image_inv, ←image2_mul, image_image2, image2_image_left, image2_image_right,
mul_inv_rev, image2_swap _ s t]
/-! ### Properties about scalar multiplication -/
/-- The scaling of a set `(x • s : set β)` by a scalar `x ∶ α` is defined as `{x • y | y ∈ s}`
in locale `pointwise`. -/
@[to_additive has_vadd_set "The translation of a set `(x +ᵥ s : set β)` by a scalar `x ∶ α` is
defined as `{x +ᵥ y | y ∈ s}` in locale `pointwise`."]
protected def has_scalar_set [has_scalar α β] : has_scalar α (set β) :=
⟨λ a, image (has_scalar.smul a)⟩
/-- The pointwise scalar multiplication `(s • t : set β)` by a set of scalars `s ∶ set α`
is defined as `{x • y | x ∈ s, y ∈ t}` in locale `pointwise`. -/
@[to_additive has_vadd "The pointwise translation `(s +ᵥ t : set β)` by a set of constants
`s ∶ set α` is defined as `{x +ᵥ y | x ∈ s, y ∈ t}` in locale `pointwise`."]
protected def has_scalar [has_scalar α β] : has_scalar (set α) (set β) :=
⟨image2 has_scalar.smul⟩
localized "attribute [instance] set.has_scalar_set set.has_scalar" in pointwise
localized "attribute [instance] set.has_vadd_set set.has_vadd" in pointwise
@[simp, to_additive]
lemma image_smul [has_scalar α β] {t : set β} : (λ x, a • x) '' t = a • t := rfl
@[to_additive]
lemma mem_smul_set [has_scalar α β] {t : set β} : x ∈ a • t ↔ ∃ y, y ∈ t ∧ a • y = x := iff.rfl
@[to_additive]
lemma smul_mem_smul_set [has_scalar α β] {t : set β} (hy : y ∈ t) : a • y ∈ a • t :=
⟨y, hy, rfl⟩
@[to_additive]
lemma smul_set_union [has_scalar α β] {s t : set β} : a • (s ∪ t) = a • s ∪ a • t :=
by simp only [← image_smul, image_union]
@[to_additive]
lemma smul_set_inter [group α] [mul_action α β] {s t : set β} :
a • (s ∩ t) = a • s ∩ a • t :=
(image_inter $ mul_action.injective a).symm
lemma smul_set_inter₀ [group_with_zero α] [mul_action α β] {s t : set β} (ha : a ≠ 0) :
a • (s ∩ t) = a • s ∩ a • t :=
show units.mk0 a ha • _ = _, from smul_set_inter
@[to_additive]
lemma smul_set_inter_subset [has_scalar α β] {s t : set β} :
a • (s ∩ t) ⊆ a • s ∩ a • t := image_inter_subset _ _ _
@[simp, to_additive]
lemma smul_set_empty [has_scalar α β] (a : α) : a • (∅ : set β) = ∅ :=
by rw [← image_smul, image_empty]
@[to_additive]
lemma smul_set_mono [has_scalar α β] {s t : set β} (h : s ⊆ t) : a • s ⊆ a • t :=
by { simp only [← image_smul, image_subset, h] }
@[simp, to_additive]
lemma image2_smul [has_scalar α β] {t : set β} : image2 has_scalar.smul s t = s • t := rfl
@[to_additive]
lemma mem_smul [has_scalar α β] {t : set β} : x ∈ s • t ↔ ∃ a y, a ∈ s ∧ y ∈ t ∧ a • y = x :=
iff.rfl
lemma mem_smul_of_mem [has_scalar α β] {t : set β} {a} {b} (ha : a ∈ s) (hb : b ∈ t) :
a • b ∈ s • t :=
⟨a, b, ha, hb, rfl⟩
@[to_additive]
lemma image_smul_prod [has_scalar α β] {t : set β} :
(λ x : α × β, x.fst • x.snd) '' s.prod t = s • t :=
image_prod _
@[to_additive]
theorem range_smul_range [has_scalar α β] {ι κ : Type*} (b : ι → α) (c : κ → β) :
range b • range c = range (λ p : ι × κ, b p.1 • c p.2) :=
ext $ λ x, ⟨λ hx, let ⟨p, q, ⟨i, hi⟩, ⟨j, hj⟩, hpq⟩ := set.mem_smul.1 hx in
⟨(i, j), hpq ▸ hi ▸ hj ▸ rfl⟩,
λ ⟨⟨i, j⟩, h⟩, set.mem_smul.2 ⟨b i, c j, ⟨i, rfl⟩, ⟨j, rfl⟩, h⟩⟩
@[simp, to_additive]
lemma smul_singleton [has_scalar α β] (a : α) (b : β) : a • ({b} : set β) = {a • b} :=
image_singleton
@[simp, to_additive]
lemma singleton_smul [has_scalar α β] {t : set β} : ({a} : set α) • t = a • t :=
image2_singleton_left
@[to_additive]
instance smul_comm_class_set {γ : Type*}
[has_scalar α γ] [has_scalar β γ] [smul_comm_class α β γ] :
smul_comm_class α (set β) (set γ) :=
{ smul_comm := λ a T T',
by simp only [←image2_smul, ←image_smul, image2_image_right, image_image2, smul_comm] }
@[to_additive]
instance smul_comm_class_set' {γ : Type*}
[has_scalar α γ] [has_scalar β γ] [smul_comm_class α β γ] :
smul_comm_class (set α) β (set γ) :=
by haveI := smul_comm_class.symm α β γ; exact smul_comm_class.symm _ _ _
@[to_additive]
instance smul_comm_class {γ : Type*}
[has_scalar α γ] [has_scalar β γ] [smul_comm_class α β γ] :
smul_comm_class (set α) (set β) (set γ) :=
{ smul_comm := λ T T' T'', begin
simp only [←image2_smul, image2_swap _ T],
exact image2_assoc (λ b c a, smul_comm a b c),
end }
instance is_scalar_tower {γ : Type*}
[has_scalar α β] [has_scalar α γ] [has_scalar β γ] [is_scalar_tower α β γ] :
is_scalar_tower α β (set γ) :=
{ smul_assoc := λ a b T, by simp only [←image_smul, image_image, smul_assoc] }
instance is_scalar_tower' {γ : Type*}
[has_scalar α β] [has_scalar α γ] [has_scalar β γ] [is_scalar_tower α β γ] :
is_scalar_tower α (set β) (set γ) :=
{ smul_assoc := λ a T T',
by simp only [←image_smul, ←image2_smul, image_image2, image2_image_left, smul_assoc] }
instance is_scalar_tower'' {γ : Type*}
[has_scalar α β] [has_scalar α γ] [has_scalar β γ] [is_scalar_tower α β γ] :
is_scalar_tower (set α) (set β) (set γ) :=
{ smul_assoc := λ T T' T'', image2_assoc smul_assoc }
section monoid
/-! ### `set α` as a `(∪,*)`-semiring -/
/-- An alias for `set α`, which has a semiring structure given by `∪` as "addition" and pointwise
multiplication `*` as "multiplication". -/
@[derive inhabited] def set_semiring (α : Type*) : Type* := set α
/-- The identitiy function `set α → set_semiring α`. -/
protected def up (s : set α) : set_semiring α := s
/-- The identitiy function `set_semiring α → set α`. -/
protected def set_semiring.down (s : set_semiring α) : set α := s
@[simp] protected lemma down_up {s : set α} : s.up.down = s := rfl
@[simp] protected lemma up_down {s : set_semiring α} : s.down.up = s := rfl
instance set_semiring.add_comm_monoid : add_comm_monoid (set_semiring α) :=
{ add := λ s t, (s ∪ t : set α),
zero := (∅ : set α),
add_assoc := union_assoc,
zero_add := empty_union,
add_zero := union_empty,
add_comm := union_comm, }
instance set_semiring.non_unital_non_assoc_semiring [has_mul α] :
non_unital_non_assoc_semiring (set_semiring α) :=
{ zero_mul := λ s, empty_mul,
mul_zero := λ s, mul_empty,
left_distrib := λ _ _ _, mul_union,
right_distrib := λ _ _ _, union_mul,
..set.has_mul, ..set_semiring.add_comm_monoid }
instance set_semiring.non_assoc_semiring [mul_one_class α] : non_assoc_semiring (set_semiring α) :=
{ ..set_semiring.non_unital_non_assoc_semiring, ..set.mul_one_class }
instance set_semiring.non_unital_semiring [semigroup α] : non_unital_semiring (set_semiring α) :=
{ ..set_semiring.non_unital_non_assoc_semiring, ..set.semigroup }
instance set_semiring.semiring [monoid α] : semiring (set_semiring α) :=
{ ..set_semiring.non_assoc_semiring, ..set_semiring.non_unital_semiring }
instance set_semiring.comm_semiring [comm_monoid α] : comm_semiring (set_semiring α) :=
{ ..set.comm_monoid, ..set_semiring.semiring }
/-- A multiplicative action of a monoid on a type β gives also a
multiplicative action on the subsets of β. -/
@[to_additive "An additive action of an additive monoid on a type β gives also an additive action
on the subsets of β."]
protected def mul_action_set [monoid α] [mul_action α β] : mul_action α (set β) :=
{ mul_smul := by { intros, simp only [← image_smul, image_image, ← mul_smul] },
one_smul := by { intros, simp only [← image_smul, image_eta, one_smul, image_id'] },
..set.has_scalar_set }
localized "attribute [instance] set.mul_action_set set.add_action_set" in pointwise
section mul_hom
variables [has_mul α] [has_mul β] (m : mul_hom α β)
@[to_additive]
lemma image_mul : m '' (s * t) = m '' s * m '' t :=
by { simp only [← image2_mul, image_image2, image2_image_left, image2_image_right, m.map_mul] }
@[to_additive]
lemma preimage_mul_preimage_subset {s t : set β} : m ⁻¹' s * m ⁻¹' t ⊆ m ⁻¹' (s * t) :=
by { rintros _ ⟨_, _, _, _, rfl⟩, exact ⟨_, _, ‹_›, ‹_›, (m.map_mul _ _).symm ⟩ }
end mul_hom
/-- The image of a set under function is a ring homomorphism
with respect to the pointwise operations on sets. -/
def image_hom [monoid α] [monoid β] (f : α →* β) : set_semiring α →+* set_semiring β :=
{ to_fun := image f,
map_zero' := image_empty _,
map_one' := by simp only [← singleton_one, image_singleton, f.map_one],
map_add' := image_union _,
map_mul' := λ _ _, image_mul f.to_mul_hom }
end monoid
end set
open set
open_locale pointwise
section
variables {α : Type*} {β : Type*}
/-- A nonempty set is scaled by zero to the singleton set containing 0. -/
lemma zero_smul_set [has_zero α] [has_zero β] [smul_with_zero α β] {s : set β} (h : s.nonempty) :
(0 : α) • s = (0 : set β) :=
by simp only [← image_smul, image_eta, zero_smul, h.image_const, singleton_zero]
lemma zero_smul_subset [has_zero α] [has_zero β] [smul_with_zero α β] (s : set β) :
(0 : α) • s ⊆ 0 :=
image_subset_iff.2 $ λ x _, zero_smul α x
lemma subsingleton_zero_smul_set [has_zero α] [has_zero β] [smul_with_zero α β] (s : set β) :
((0 : α) • s).subsingleton :=
subsingleton_singleton.mono (zero_smul_subset s)
section group
variables [group α] [mul_action α β]
@[simp, to_additive]
lemma smul_mem_smul_set_iff {a : α} {A : set β} {x : β} : a • x ∈ a • A ↔ x ∈ A :=
⟨λ h, begin
rw [←inv_smul_smul a x, ←inv_smul_smul a A],
exact smul_mem_smul_set h,
end, smul_mem_smul_set⟩
@[to_additive]
lemma mem_smul_set_iff_inv_smul_mem {a : α} {A : set β} {x : β} : x ∈ a • A ↔ a⁻¹ • x ∈ A :=
show x ∈ mul_action.to_perm a '' A ↔ _, from mem_image_equiv
@[to_additive]
lemma mem_inv_smul_set_iff {a : α} {A : set β} {x : β} : x ∈ a⁻¹ • A ↔ a • x ∈ A :=
by simp only [← image_smul, mem_image, inv_smul_eq_iff, exists_eq_right]
@[to_additive]
lemma preimage_smul (a : α) (t : set β) : (λ x, a • x) ⁻¹' t = a⁻¹ • t :=
((mul_action.to_perm a).symm.image_eq_preimage _).symm
@[to_additive]
lemma preimage_smul_inv (a : α) (t : set β) : (λ x, a⁻¹ • x) ⁻¹' t = a • t :=
preimage_smul (to_units a)⁻¹ t
@[simp, to_additive]
lemma set_smul_subset_set_smul_iff {a : α} {A B : set β} : a • A ⊆ a • B ↔ A ⊆ B :=
image_subset_image_iff $ mul_action.injective _
@[to_additive]
lemma set_smul_subset_iff {a : α} {A B : set β} : a • A ⊆ B ↔ A ⊆ a⁻¹ • B :=
(image_subset_iff).trans $ iff_of_eq $ congr_arg _ $
preimage_equiv_eq_image_symm _ $ mul_action.to_perm _
@[to_additive]
lemma subset_set_smul_iff {a : α} {A B : set β} : A ⊆ a • B ↔ a⁻¹ • A ⊆ B :=
iff.symm $ (image_subset_iff).trans $ iff.symm $ iff_of_eq $ congr_arg _ $
image_equiv_eq_preimage_symm _ $ mul_action.to_perm _
end group
section group_with_zero
variables [group_with_zero α] [mul_action α β]
@[simp] lemma smul_mem_smul_set_iff₀ {a : α} (ha : a ≠ 0) (A : set β)
(x : β) : a • x ∈ a • A ↔ x ∈ A :=
show units.mk0 a ha • _ ∈ _ ↔ _, from smul_mem_smul_set_iff
lemma mem_smul_set_iff_inv_smul_mem₀ {a : α} (ha : a ≠ 0) (A : set β) (x : β) :
x ∈ a • A ↔ a⁻¹ • x ∈ A :=
show _ ∈ units.mk0 a ha • _ ↔ _, from mem_smul_set_iff_inv_smul_mem
lemma mem_inv_smul_set_iff₀ {a : α} (ha : a ≠ 0) (A : set β) (x : β) : x ∈ a⁻¹ • A ↔ a • x ∈ A :=
show _ ∈ (units.mk0 a ha)⁻¹ • _ ↔ _, from mem_inv_smul_set_iff
lemma preimage_smul₀ {a : α} (ha : a ≠ 0) (t : set β) : (λ x, a • x) ⁻¹' t = a⁻¹ • t :=
preimage_smul (units.mk0 a ha) t
lemma preimage_smul_inv₀ {a : α} (ha : a ≠ 0) (t : set β) :
(λ x, a⁻¹ • x) ⁻¹' t = a • t :=
preimage_smul ((units.mk0 a ha)⁻¹) t
@[simp] lemma set_smul_subset_set_smul_iff₀ {a : α} (ha : a ≠ 0) {A B : set β} :
a • A ⊆ a • B ↔ A ⊆ B :=
show units.mk0 a ha • _ ⊆ _ ↔ _, from set_smul_subset_set_smul_iff
lemma set_smul_subset_iff₀ {a : α} (ha : a ≠ 0) {A B : set β} : a • A ⊆ B ↔ A ⊆ a⁻¹ • B :=
show units.mk0 a ha • _ ⊆ _ ↔ _, from set_smul_subset_iff
lemma subset_set_smul_iff₀ {a : α} (ha : a ≠ 0) {A B : set β} : A ⊆ a • B ↔ a⁻¹ • A ⊆ B :=
show _ ⊆ units.mk0 a ha • _ ↔ _, from subset_set_smul_iff
end group_with_zero
end
namespace finset
variables {α : Type*} [decidable_eq α] {s t : finset α}
/-- The pointwise product of two finite sets `s` and `t`:
`st = s ⬝ t = s * t = { x * y | x ∈ s, y ∈ t }`. -/
@[to_additive /-"The pointwise sum of two finite sets `s` and `t`:
`s + t = { x + y | x ∈ s, y ∈ t }`. "-/]
protected def has_mul [has_mul α] : has_mul (finset α) :=
⟨λ s t, (s.product t).image (λ p : α × α, p.1 * p.2)⟩
localized "attribute [instance] finset.has_mul finset.has_add" in pointwise
@[to_additive]
lemma mul_def [has_mul α] :
s * t = (s.product t).image (λ p : α × α, p.1 * p.2) := rfl
@[to_additive]
lemma mem_mul [has_mul α] {x : α} :
x ∈ s * t ↔ ∃ y z, y ∈ s ∧ z ∈ t ∧ y * z = x :=
by { simp only [finset.mul_def, and.assoc, mem_image, exists_prop, prod.exists, mem_product] }
@[simp, norm_cast, to_additive]
lemma coe_mul [has_mul α] : (↑(s * t) : set α) = ↑s * ↑t :=
by { ext, simp only [mem_mul, set.mem_mul, mem_coe] }
@[to_additive]
lemma mul_mem_mul [has_mul α] {x y : α} (hx : x ∈ s) (hy : y ∈ t) :
x * y ∈ s * t :=
by { simp only [finset.mem_mul], exact ⟨x, y, hx, hy, rfl⟩ }
@[to_additive]
lemma mul_card_le [has_mul α] : (s * t).card ≤ s.card * t.card :=
by { convert finset.card_image_le, rw [finset.card_product, mul_comm] }
@[simp, to_additive] lemma empty_mul [has_mul α] (s : finset α) : ∅ * s = ∅ :=
eq_empty_of_forall_not_mem (by simp [mem_mul])
@[simp, to_additive] lemma mul_empty [has_mul α] (s : finset α) : s * ∅ = ∅ :=
eq_empty_of_forall_not_mem (by simp [mem_mul])
@[simp, to_additive] lemma mul_nonempty_iff [has_mul α] (s t : finset α):
(s * t).nonempty ↔ s.nonempty ∧ t.nonempty :=
by simp [finset.mul_def]
@[to_additive, mono] lemma mul_subset_mul [has_mul α] {s₁ s₂ t₁ t₂ : finset α}
(hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : s₁ * t₁ ⊆ s₂ * t₂ :=
image_subset_image (product_subset_product hs ht)
lemma mul_singleton_zero [mul_zero_class α] (s : finset α) :
s * {0} ⊆ {0} :=
by simp [subset_iff, mem_mul]
lemma singleton_zero_mul [mul_zero_class α] (s : finset α):
{(0 : α)} * s ⊆ {0} :=
by simp [subset_iff, mem_mul]
open_locale classical
/-- A finite set `U` contained in the product of two sets `S * S'` is also contained in the product
of two finite sets `T * T' ⊆ S * S'`. -/
@[to_additive]
lemma subset_mul {M : Type*} [monoid M] {S : set M} {S' : set M} {U : finset M} (f : ↑U ⊆ S * S') :
∃ (T T' : finset M), ↑T ⊆ S ∧ ↑T' ⊆ S' ∧ U ⊆ T * T' :=
begin
apply finset.induction_on' U,
{ use [∅, ∅], simp only [finset.empty_subset, finset.coe_empty, set.empty_subset, and_self], },
rintros a s haU hs has ⟨T, T', hS, hS', h⟩,
obtain ⟨x, y, hx, hy, ha⟩ := set.mem_mul.1 (f haU),
use [insert x T, insert y T'],
simp only [finset.coe_insert],
repeat { rw [set.insert_subset], },
use [hx, hS, hy, hS'],
refine finset.insert_subset.mpr ⟨_, _⟩,
{ rw finset.mem_mul,
use [x,y],
simpa only [true_and, true_or, eq_self_iff_true, finset.mem_insert], },
{ suffices g : (s : set M) ⊆ insert x T * insert y T', { norm_cast at g, assumption, },
transitivity ↑(T * T'),
apply h,
rw finset.coe_mul,
apply set.mul_subset_mul (set.subset_insert x T) (set.subset_insert y T'), },
end
end finset
/-! Some lemmas about pointwise multiplication and submonoids. Ideally we put these in
`group_theory.submonoid.basic`, but currently we cannot because that file is imported by this. -/
namespace submonoid
variables {M : Type*} [monoid M]
@[to_additive]
lemma mul_subset {s t : set M} {S : submonoid M} (hs : s ⊆ S) (ht : t ⊆ S) : s * t ⊆ S :=
by { rintro _ ⟨p, q, hp, hq, rfl⟩, exact submonoid.mul_mem _ (hs hp) (ht hq) }
@[to_additive]
lemma mul_subset_closure {s t u : set M} (hs : s ⊆ u) (ht : t ⊆ u) :
s * t ⊆ submonoid.closure u :=
mul_subset (subset.trans hs submonoid.subset_closure) (subset.trans ht submonoid.subset_closure)
@[to_additive]
lemma coe_mul_self_eq (s : submonoid M) : (s : set M) * s = s :=
begin
ext x,
refine ⟨_, λ h, ⟨x, 1, h, s.one_mem, mul_one x⟩⟩,
rintros ⟨a, b, ha, hb, rfl⟩,
exact s.mul_mem ha hb
end
@[to_additive]
lemma closure_mul_le (S T : set M) : closure (S * T) ≤ closure S ⊔ closure T :=
Inf_le $ λ x ⟨s, t, hs, ht, hx⟩, hx ▸ (closure S ⊔ closure T).mul_mem
(set_like.le_def.mp le_sup_left $ subset_closure hs)
(set_like.le_def.mp le_sup_right $ subset_closure ht)
@[to_additive]
lemma sup_eq_closure (H K : submonoid M) : H ⊔ K = closure (H * K) :=
le_antisymm
(sup_le
(λ h hh, subset_closure ⟨h, 1, hh, K.one_mem, mul_one h⟩)
(λ k hk, subset_closure ⟨1, k, H.one_mem, hk, one_mul k⟩))
(by conv_rhs { rw [← closure_eq H, ← closure_eq K] }; apply closure_mul_le)
end submonoid
namespace group
lemma card_pow_eq_card_pow_card_univ_aux {f : ℕ → ℕ} (h1 : monotone f)
{B : ℕ} (h2 : ∀ n, f n ≤ B) (h3 : ∀ n, f n = f (n + 1) → f (n + 1) = f (n + 2)) :
∀ k, B ≤ k → f k = f B :=
begin
have key : ∃ n : ℕ, n ≤ B ∧ f n = f (n + 1),
{ contrapose! h2,
suffices : ∀ n : ℕ, n ≤ B + 1 → n ≤ f n,
{ exact ⟨B + 1, this (B + 1) (le_refl (B + 1))⟩ },
exact λ n, nat.rec (λ h, nat.zero_le (f 0)) (λ n ih h, lt_of_le_of_lt (ih (n.le_succ.trans h))
(lt_of_le_of_ne (h1 n.le_succ) (h2 n (nat.succ_le_succ_iff.mp h)))) n },
{ obtain ⟨n, hn1, hn2⟩ := key,
replace key : ∀ k : ℕ, f (n + k) = f (n + k + 1) ∧ f (n + k) = f n :=
λ k, nat.rec ⟨hn2, rfl⟩ (λ k ih, ⟨h3 _ ih.1, ih.1.symm.trans ih.2⟩) k,
replace key : ∀ k : ℕ, n ≤ k → f k = f n :=
λ k hk, (congr_arg f (add_tsub_cancel_of_le hk)).symm.trans (key (k - n)).2,
exact λ k hk, (key k (hn1.trans hk)).trans (key B hn1).symm },
end
variables {G : Type*} [group G] [fintype G] (S : set G)
lemma card_pow_eq_card_pow_card_univ [∀ (k : ℕ), decidable_pred (∈ (S ^ k))] :
∀ k, fintype.card G ≤ k → fintype.card ↥(S ^ k) = fintype.card ↥(S ^ (fintype.card G)) :=
begin
have hG : 0 < fintype.card G := fintype.card_pos_iff.mpr ⟨1⟩,
by_cases hS : S = ∅,
{ intros k hk,
congr' 2,
rw [hS, empty_pow _ (ne_of_gt (lt_of_lt_of_le hG hk)), empty_pow _ (ne_of_gt hG)] },
obtain ⟨a, ha⟩ := set.ne_empty_iff_nonempty.mp hS,
classical,
have key : ∀ a (s t : set G), (∀ b : G, b ∈ s → a * b ∈ t) → fintype.card s ≤ fintype.card t,
{ refine λ a s t h, fintype.card_le_of_injective (λ ⟨b, hb⟩, ⟨a * b, h b hb⟩) _,
rintros ⟨b, hb⟩ ⟨c, hc⟩ hbc,
exact subtype.ext (mul_left_cancel (subtype.ext_iff.mp hbc)) },
have mono : monotone (λ n, fintype.card ↥(S ^ n) : ℕ → ℕ) :=
monotone_nat_of_le_succ (λ n, key a _ _ (λ b hb, set.mul_mem_mul ha hb)),
convert card_pow_eq_card_pow_card_univ_aux mono (λ n, set_fintype_card_le_univ (S ^ n))
(λ n h, le_antisymm (mono (n + 1).le_succ) (key a⁻¹ _ _ _)),
{ simp only [finset.filter_congr_decidable, fintype.card_of_finset] },
replace h : {a} * S ^ n = S ^ (n + 1),
{ refine set.eq_of_subset_of_card_le _ (le_trans (ge_of_eq h) _),
{ exact mul_subset_mul (set.singleton_subset_iff.mpr ha) set.subset.rfl },
{ convert key a (S ^ n) ({a} * S ^ n) (λ b hb, set.mul_mem_mul (set.mem_singleton a) hb) } },
rw [pow_succ', ←h, mul_assoc, ←pow_succ', h],
rintros _ ⟨b, c, hb, hc, rfl⟩,
rwa [set.mem_singleton_iff.mp hb, inv_mul_cancel_left],
end
end group
|
-- @@stderr --
dtrace: failed to compile script test/unittest/pragma/err.D_PRAGMA_DEPEND.main.d: [D_PRAGMA_DEPEND] line 12: main program may not explicitly depend on a library
|
Require Export Base.
Module SProdCategory.
Structure mixin_of (C: Category) := Mixin {
sprod {I}: (I -> C) -> C;
sfork {I} {X: C} {F: I -> C}: (forall i, X ~> F i) -> X ~> sprod F;
pi {I} {F: I -> C} (i: I): sprod F ~> F i;
sfork_ump {I} {X: C} {F: I -> C} (f: forall i, X ~> F i) (g: X ~> sprod F): sfork f = g <-> forall i, pi i ∘ g = f i;
}.
Notation class_of := mixin_of (only parsing).
Section ClassDef.
Structure type := Pack { sort: Category; _: class_of sort }.
Local Coercion sort: type >-> Category.
Variable T: type.
Definition class := match T return class_of T with Pack _ c => c end.
Definition Cat: Cat := T.
End ClassDef.
Module Exports.
Coercion sort: type >-> Category.
Coercion Cat: type >-> Category.obj.
Notation SProdCategory := type.
End Exports.
End SProdCategory.
Export SProdCategory.Exports.
Section SProdCategory_theory.
Context {C: SProdCategory}.
Definition sprod: forall {I}, (I -> C) -> C := @SProdCategory.sprod C (SProdCategory.class C).
Definition sfork: forall {I} {X: C} {F: I -> C}, (forall i, X ~> F i) -> X ~> sprod F := @SProdCategory.sfork C (SProdCategory.class C).
Definition pi: forall {I} {F: I -> C} (i: I), sprod F ~> F i := @SProdCategory.pi C (SProdCategory.class C).
Definition sfork_ump: forall {I} {X: C} {F: I -> C} (f: forall i, X ~> F i) (g: X ~> sprod F), sfork f = g <-> forall i, pi i ∘ g = f i := @SProdCategory.sfork_ump C (SProdCategory.class C).
Notation "∏ i .. j , x" := (sprod (fun i => .. (sprod (fun j => x)) ..)) (at level 40, i binder).
Notation "∏' i .. j , f" := (sfork (fun i => .. (sfork (fun j => f)) ..)) (at level 40, i binder).
Notation π := pi.
Lemma to_sprod_eq {I} {F: I -> C} {X: C} (f g: X ~> sprod F): f = g <-> forall i, π i ∘ f = π i ∘ g.
Proof.
split.
now intros [].
intros H.
transitivity (∏' i, (π i ∘ g)).
symmetry.
all: now apply sfork_ump.
Qed.
Definition spmap {I} {F G: I -> C} (η: forall i, F i ~> G i): sprod F ~> sprod G :=
∏' i, (η i ∘ π i).
Notation "(∏) i .. j , f" := (spmap (fun i => .. (spmap (fun j => f)) ..)) (at level 40, i binder).
Lemma pi_sfork {I} {F: I -> C} {X: C} (η: forall i, X ~> F i) (i: I): π i ∘ sfork η = η i.
Proof. now apply sfork_ump. Qed.
Lemma pi_spmap {I} {F G: I -> C} (η: forall i, F i ~> G i) (i: I): π i ∘ spmap η = η i ∘ π i.
Proof. exact (pi_sfork (fun i => η i ∘ π i) i). Qed.
Lemma sfork_comp {I} {X Y: C} {F: I -> C} (f: forall i, Y ~> F i) (g: X ~> Y): ∏' i, (f i ∘ g) = sfork f ∘ g.
Proof.
apply to_sprod_eq.
intros i.
rewrite comp_assoc.
now rewrite !pi_sfork.
Qed.
Lemma spmap_sfork {I} {F G: I -> C} {X: C} (f: forall i, F i ~> G i) (g: forall i, X ~> F i): spmap f ∘ sfork g = ∏' i, (f i ∘ g i).
Proof.
apply to_sprod_eq.
intros i.
rewrite comp_assoc.
rewrite pi_spmap.
rewrite <- comp_assoc.
now rewrite !pi_sfork.
Qed.
Lemma spmap_id {I} (F: I -> C): (∏) i, id (F i) = id (sprod F).
Proof.
apply to_sprod_eq.
intros i.
rewrite pi_spmap.
rewrite comp_id_r.
apply comp_id_l.
Qed.
Lemma spmap_comp {I} {F G H: I -> C} (η: forall i, G i ~> H i) (ϵ: forall i, F i ~> G i): (∏) i, (η i ∘ ϵ i) = spmap η ∘ spmap ϵ.
Proof.
apply to_sprod_eq.
intros i.
rewrite comp_assoc.
rewrite !pi_spmap.
rewrite <- !comp_assoc.
f_equal.
symmetry.
apply pi_spmap.
Qed.
End SProdCategory_theory.
Notation "∏ i .. j , x" := (sprod (fun i => .. (sprod (fun j => x)) ..)) (at level 40, i binder).
Notation "∏' i .. j , f" := (sfork (fun i => .. (sfork (fun j => f)) ..)) (at level 40, i binder).
Notation π := pi.
Notation "(∏) i .. j , f" := (spmap (fun i => .. (spmap (fun j => f)) ..)) (at level 40, i binder).
Instance sfork_pw C I X F: Proper (forall_relation (fun _ => eq) ==> eq) (@sfork C I X F).
Proof.
intros f g H.
f_equal.
now extensionality i.
Qed.
Instance spmap_pw C I F G: Proper (forall_relation (fun _ => eq) ==> eq) (@spmap C I F G).
Proof.
intros f g H.
f_equal.
now extensionality i.
Qed.
|
module Test.API
import Common
UserId : Type
record User where
userId : UserId
name : String
data A = A1 Int | A2 String
data B : Type where
B1 : Int -> B
B2 : String -> B
ユーザ一覧 : API UserId (Int, Double, String)
|
[STATEMENT]
lemma porder_onE:
assumes "porder_on A r"
obtains "refl_onP A r" "antisymp r" "transp r"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<lbrakk>refl_onP A r; antisymp r; transp r\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
porder_on A r
goal (1 subgoal):
1. (\<lbrakk>refl_onP A r; antisymp r; transp r\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
unfolding porder_on_def
[PROOF STATE]
proof (prove)
using this:
refl_onP A r \<and> transp r \<and> antisymp r
goal (1 subgoal):
1. (\<lbrakk>refl_onP A r; antisymp r; transp r\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by blast |
lemma adjoint_adjoint: fixes f :: "'n::euclidean_space \<Rightarrow> 'm::euclidean_space" assumes lf: "linear f" shows "adjoint (adjoint f) = f" |
module SnpParser
using LinearAlgebra;
using Plots;
include("parser.jl")
include("utils.jl")
include("plotter.jl")
export TouchstoneSnP, plot_snp
end # module
|
theory DL_Equality_Sigma_Commit imports
Abstract_Commitment
Abstract_Sigma_Protocols
Cyclic_Group_Ext
Discrete_log
GCD
Uniform_Sampling
Uniform_Sampling_Defs
begin
locale schnorr_2_base =
fixes \<G> :: "'grp cyclic_group" (structure)
and x :: nat
and g' :: 'grp
assumes finite_group: "finite (carrier \<G>)"
and order_gt_2: "order \<G> > 2"
and prime_order: "prime (order \<G>)"
and prime_field: "a < (order \<G>) \<Longrightarrow> a \<noteq> 0 \<Longrightarrow> coprime a (order \<G>)"
and g': "g' = \<^bold>g (^) x"
begin
lemma or_gt_0 [simp]:"order \<G> > 0"
using order_gt_2 by simp
lemma lossless_samp_uni_excl: "lossless_spmf (samp_uni_excl (order \<G>) p)"
proof-
have "order \<G> > 1" using order_gt_2 by simp
then show ?thesis
by (metis Diff_empty samp_uni_excl_def Diff_eq_empty_iff One_nat_def card_empty card_insert_disjoint card_lessThan equals0D finite_Diff_insert finite_lessThan lessThan_iff less_not_refl3 lossless_spmf_of_set subset_singletonD)
qed
lemma lossless_samp_uni: "lossless_spmf (sample_uniform (order \<G>))"
using order_gt_2 by simp
lemma lossless_samp_uni_units: "lossless_spmf (samp_uni_units (order \<G>))"
apply(simp add: samp_uni_units_def) using order_gt_2 by fastforce
lemma weight_samp_uni_units: "weight_spmf (samp_uni_units (order \<G>)) = 1"
using lossless_samp_uni_units
by (simp add: lossless_spmf_def)
lemma [simp]: "set_spmf (samp_uni_units_excl (order \<G>) p) = ({..< order \<G>} - {p} - {0})"
by(simp add: samp_uni_units_excl_def)
lemma lossless_samp_uni_units_excl: "lossless_spmf (samp_uni_units_excl (order \<G>) p)"
apply(simp add: samp_uni_units_excl_def) using order_gt_2
by (smt Diff_empty Diff_insert0 One_nat_def Suc_leI card.insert card_empty card_lessThan finite.intros(1) finite_insert insert_Diff insert_absorb leD nat_neq_iff prime_gt_1_nat prime_order subset_singletonD two_is_prime_nat zero_le_one)
definition "challenge = samp_uni_units (order \<G>)"
definition "snd_challenge p = samp_uni_units_excl (order \<G>) p"
definition "response r w e = return_spmf ((w*e + r) mod (order \<G>))"
type_synonym witness = "nat"
type_synonym rand = nat
type_synonym 'grp' msg = "'grp' \<times> 'grp'"
type_synonym response = nat
type_synonym challenge = nat
type_synonym 'grp' pub_in = "'grp' \<times> 'grp'"
definition init :: "'grp pub_in \<Rightarrow> witness \<Rightarrow> (rand \<times> 'grp msg) spmf"
where "init h w = do {
let (h, h') = h;
r \<leftarrow> sample_uniform (order \<G>);
return_spmf (r, \<^bold>g (^) r, g' (^) r)}"
definition check :: "'grp pub_in \<Rightarrow> 'grp msg \<Rightarrow> challenge \<Rightarrow> response \<Rightarrow> bool spmf"
where "check h a e z =
return_spmf (fst a \<otimes> (fst h (^) e) = \<^bold>g (^) z \<and> snd a \<otimes> (snd h (^) e) = g' (^) z)"
definition R :: "'grp pub_in \<Rightarrow> witness \<Rightarrow> bool"
where "R h w \<equiv> (fst h = \<^bold>g (^) w \<and> w \<noteq> 0 \<and> w < order \<G> \<and> snd h = g' (^) w)"
definition R2 :: "'grp pub_in \<Rightarrow> witness \<Rightarrow> ('grp msg, challenge, response) conv_tuple spmf"
where "R2 H w = do {
let (h, h') = H;
(r, a, a') \<leftarrow> init H w;
c \<leftarrow> samp_uni_units (order \<G>);
let z = (w*c + r) mod (order \<G>);
return_spmf ((a,a'),c, z)}"
definition S2 :: "'grp pub_in \<Rightarrow> challenge \<Rightarrow> ('grp msg, challenge, response) conv_tuple spmf"
where "S2 H c = do {
let (h, h') = H;
z \<leftarrow> (sample_uniform (order \<G>));
let a = \<^bold>g (^) z \<otimes> inv (h (^) c);
let a' = g' (^) z \<otimes> inv (h' (^) c);
return_spmf ((a,a'),c, z)}"
definition pk_adversary2 :: "'grp pub_in \<Rightarrow> ('grp msg, challenge, response) conv_tuple \<Rightarrow> ('grp msg, challenge, response) conv_tuple \<Rightarrow> nat spmf"
where "pk_adversary2 x' c1 c2 = do {
let ((a,a'), e, z) = c1;
let ((b,b'), e', z') = c2;
return_spmf (if e > e' then (nat ((int z - int z') * (fst (bezw (e - e') (order \<G>))) mod order \<G>)) else
(nat ((int z' - int z) * (fst (bezw (e' - e) (order \<G>))) mod order \<G>)))}"
sublocale epsilon_protocols_base: epsilon_protocols_base init challenge snd_challenge response check R S2 .
lemma R2_eq_R: "R2 h w = epsilon_protocols_base.R h w"
unfolding R2_def epsilon_protocols_base.R_def Let_def
by(simp add: challenge_def response_def split_def)
end
locale schnorr_2 = schnorr_2_base + cyclic_group \<G>
begin
lemma zr:
assumes z: "z = (w*c + r) mod (order \<G>)"
and x: "w < order \<G>"
and c: "c < order \<G>"
and r: "r < order \<G>"
shows "(z + (order \<G>)*(order \<G>) - w*c) mod (order \<G>) = r"
proof-
have cong: "[z + (order \<G>)*(order \<G>) = w*c + r] (mod (order \<G>))"
by(simp add: cong_nat_def z)
hence "[z + (order \<G>)*(order \<G>) - w*c = r] (mod (order \<G>))"
proof-
have "z + (order \<G>)*(order \<G>) > w*c"
using x c by (simp add: mult_strict_mono trans_less_add2)
then show ?thesis
by (metis cong add_diff_inverse_nat cong_add_lcancel_nat less_imp_le linorder_not_le)
qed
then show ?thesis
by(simp add: cong_nat_def r)
qed
lemma xr':assumes x: "w < order \<G>"
and c: "c < order \<G>"
and r: "r < order \<G>"
shows "((w*c + r) mod (order \<G>) mod (order \<G>) + (order \<G>)*(order \<G>) - w*c) mod (order \<G>) = r"
using assms zr by simp
lemma complete: assumes "h = (\<^bold>g (^) (w::nat), g' (^) w)"
shows "spmf (epsilon_protocols_base.completeness_game h w) True = 1"
proof-
have "\<^bold>g (^) y \<otimes> (\<^bold>g (^) w) (^) e = \<^bold>g (^) ((w * e + y))" for y e
by (simp add: add.commute nat_pow_pow nat_pow_mult)
also have "(\<^bold>g (^) x) (^) y \<otimes> ((\<^bold>g (^) x) (^) w) (^) e = (\<^bold>g (^) x) (^) ((w * e + y) mod (order \<G>))" for y e
by (metis add.commute nat_pow_pow nat_pow_mult pow_generator_mod generator_closed nat_pow_closed mod_mult_right_eq)
ultimately show ?thesis
unfolding epsilon_protocols_base.completeness_game_def init_def check_def
by(simp add: Let_def bind_spmf_const pow_generator_mod order_gt_2 weight_samp_uni_units lossless_weight_spmfD init_def challenge_def response_def g' assms)
qed
lemma completeness:
shows "epsilon_protocols_base.completeness h w"
apply(simp add: epsilon_protocols_base.completeness_def R_def)
by (metis prod.collapse complete)
lemma h_sub:
assumes "h = \<^bold>g (^) w" and x_not_0: "w \<noteq> 0" and w: "w < order \<G>" and z: "z < order \<G>" and c: "c < order \<G>"
shows "\<^bold>g (^) ((z + (order \<G>)*(order \<G>) - w*c)) = \<^bold>g (^) z \<otimes> inv (h (^) c)"
(is "?lhs = ?rhs")
proof-
have "(z + order \<G> * order \<G> - w * c) = (z + (order \<G> * order \<G> - w * c))"
using w c z by (simp add: less_imp_le_nat mult_le_mono)
then have lhs: "?lhs = \<^bold>g (^) z \<otimes> \<^bold>g (^) ((order \<G>)*(order \<G>) - w*c)" by(simp add: nat_pow_mult)
have " \<^bold>g (^) ((order \<G>)*(order \<G>) - w*c) = inv (h (^) c)"
proof-
have "((order \<G>)*(order \<G>) - w*c) > 0" using assms
by (simp add: mult_strict_mono)
then have " \<^bold>g (^) ((order \<G>)*(order \<G>) - w*c) = \<^bold>g (^) int ((order \<G>)*(order \<G>) - w*c)"
by (simp add: int_pow_int)
also have "... = \<^bold>g (^) int ((order \<G>)*(order \<G>)) \<otimes> inv (\<^bold>g (^) (w*c))"
using int_pow_diff[of "\<^bold>g" "order \<G> * order \<G>" "w * c"]
by (smt \<open>0 < order \<G> * order \<G> - w * c\<close> generator_closed group.int_pow_def2 group_l_invI int_minus int_pow_int l_inv_ex of_nat_less_iff zero_less_diff)
also have "... = \<^bold>g (^) ((order \<G>)*(order \<G>)) \<otimes> inv (\<^bold>g (^) (w*c))"
by (metis int_pow_int)
also have "... = \<^bold>g (^) ((order \<G>)*(order \<G>)) \<otimes> inv ((\<^bold>g (^) w) (^) c)"
by(simp add: nat_pow_pow)
also have "... = \<^bold>g (^) ((order \<G>)*(order \<G>)) \<otimes> inv (h (^) c)"
using assms by simp
also have "... = \<one> \<otimes> inv (h (^) c)"
using generator_pow_order
by (metis generator_closed mult_is_0 nat_pow_0 nat_pow_pow)
ultimately show ?thesis
by (simp add: assms(1))
qed
then show ?thesis using lhs by simp
qed
lemma h_sub2:
assumes "h' = g' (^) w" and x_not_0: "w \<noteq> 0" and w: "w < order \<G>" and z: "z < order \<G>" and c: "c < order \<G>"
shows "g' (^) ((z + (order \<G>)*(order \<G>) - w*c)) = g' (^) z \<otimes> inv (h' (^) c)"
(is "?lhs = ?rhs")
proof-
have "g' = \<^bold>g (^) x" using g' by simp
have g'_carrier: "g' \<in> carrier \<G>" using g' by simp
have 1: "g' (^) ((order \<G>)*(order \<G>) - w*c) = inv (h' (^) c)"
proof-
have "((order \<G>)*(order \<G>) - w*c) > 0" using assms
by (simp add: mult_strict_mono)
then have " g' (^) ((order \<G>)*(order \<G>) - w*c) = g' (^) int ((order \<G>)*(order \<G>) - w*c)"
by (simp add: int_pow_int)
also have "... = g' (^) int ((order \<G>)*(order \<G>)) \<otimes> inv (g' (^) (w*c))"
using int_pow_diff[of "g'" "order \<G> * order \<G>" "w * c"] g'_carrier
proof -
have "\<forall>x0 x1. int x1 - int x0 = int x1 + - 1 * int x0"
by auto
then have f1: "g' (^) int (order \<G> * order \<G> - w * c) = g' (^) nat (int (order \<G> * order \<G>) + - 1 * int (w * c))"
by (metis (no_types) int_minus int_pow_int)
have f2: "0 \<le> int (order \<G> * order \<G>) + - 1 * int (w * c)"
using \<open>(0::nat) < order \<G> * order \<G> - (w::nat) * (c::nat)\<close> by linarith
have f3: "\<forall>p a i. \<not> Group.group (p::\<lparr>carrier :: 'a set, monoid.mult :: _ \<Rightarrow> _ \<Rightarrow> _, one :: _, generator :: 'a\<rparr>) \<or> a (^)\<^bsub>p\<^esub> i = (if 0 \<le> i then a (^)\<^bsub>p\<^esub> nat i else inv\<^bsub>p\<^esub> (a (^)\<^bsub>p\<^esub> nat (- 1 * i)))"
by (simp add: group.int_pow_def2)
have f4: "\<forall>x0 x1. (x1::int) - x0 = - 1 * x0 + x1"
by auto
have "- 1 * int (w * c) + int (order \<G> * order \<G>) = int (order \<G> * order \<G>) + - 1 * int (w * c)"
by presburger
then show ?thesis
using f4 f3 f2 f1 by (metis (full_types) g'_carrier group.int_pow_diff group_l_invI int_pow_int l_inv_ex)
qed
also have "... = g' (^) ((order \<G>)*(order \<G>)) \<otimes> inv (g' (^) (w*c))"
by (metis int_pow_int)
also have "... = g' (^) ((order \<G>)*(order \<G>)) \<otimes> inv (h' (^) c)"
by(simp add: nat_pow_pow g'_carrier assms)
also have "... = \<one> \<otimes> inv (h' (^) c)"
using generator_pow_mult_order
by (metis g' generator_closed mult.commute nat_pow_one nat_pow_pow)
ultimately show ?thesis
by (simp add: assms(1) g'_carrier)
qed
have "(z + order \<G> * order \<G> - w * c) = (z + (order \<G> * order \<G> - w * c))"
using w c z by (simp add: less_imp_le_nat mult_le_mono)
then have lhs: "?lhs = g' (^) z \<otimes> g' (^) ((order \<G>)*(order \<G>) - w*c)"
by(auto simp add: nat_pow_mult g'_carrier)
then show ?thesis using 1 by simp
qed
lemma hv_zk2: assumes "H = (\<^bold>g (^) (w::nat), g' (^) w)" and "w \<noteq> 0" and "w < order \<G>"
shows "epsilon_protocols_base.R H w = bind_spmf challenge (S2 H)"
including monad_normalisation
proof-
have "R2 H w = bind_spmf challenge (S2 H)"
proof-
have g'_carrier: "g' \<in> carrier \<G>" using g' by simp
have "R2 H w = do {
let (h, h') = H;
r \<leftarrow> sample_uniform (order \<G>);
let (r, a, a') = (r, \<^bold>g (^) r, g' (^) r);
c \<leftarrow> samp_uni_units (order \<G>);
let z = (w*c + r) mod (order \<G>);
return_spmf ((a,a'),c, z)}"
by(simp add: R2_def init_def)
also have "... = do {
let (h, h') = H;
r \<leftarrow> sample_uniform (order \<G>);
c \<leftarrow> samp_uni_units (order \<G>);
let z = (w*c + r) mod (order \<G>);
let a = \<^bold>g (^) ((z + (order \<G>)*(order \<G>) - w*c) mod (order \<G>));
let a' = g' (^) ((z + (order \<G>)*(order \<G>) - w*c) mod (order \<G>));
return_spmf ((a,a'),c, z)}"
apply(simp add: Let_def R2_def init_def)
using assms xr' by(simp cong: bind_spmf_cong_simp)
also have "... = do {
let (h, h') = H;
c \<leftarrow> samp_uni_units (order \<G>);
z \<leftarrow> map_spmf (\<lambda> r. (w*c + r) mod (order \<G>)) (sample_uniform (order \<G>));
let a = \<^bold>g (^) ((z + (order \<G>)*(order \<G>) - w*c) mod (order \<G>));
let a' = g' (^) ((z + (order \<G>)*(order \<G>) - w*c) mod (order \<G>));
return_spmf ((a,a'),c, z)}"
by(simp add: bind_map_spmf Let_def o_def)
also have "... = do {
let (h, h') = H;
c \<leftarrow> samp_uni_units (order \<G>);
z \<leftarrow> (sample_uniform (order \<G>));
let a = \<^bold>g (^) ((z + (order \<G>)*(order \<G>) - w*c) mod (order \<G>));
let a' = g' (^) ((z + (order \<G>)*(order \<G>) - w*c) mod (order \<G>));
return_spmf ((a,a'),c, z)}"
by(simp add: samp_uni_plus_one_time_pad)
also have "... = do {
let (h, h') = H;
c \<leftarrow> samp_uni_units (order \<G>);
z \<leftarrow> (sample_uniform (order \<G>));
let a = \<^bold>g (^) ((z + (order \<G>)*(order \<G>) - w*c));
let a' = g' (^) ((z + (order \<G>)*(order \<G>) - w*c) mod (order \<G>));
return_spmf ((a,a'),c, z)}"
by(simp add: g' pow_generator_mod)
also have "... = do {
let (h, h') = H;
c \<leftarrow> samp_uni_units (order \<G>);
z \<leftarrow> (sample_uniform (order \<G>));
let a = \<^bold>g (^) z \<otimes> inv (h (^) c);
let a' = g' (^) ((z + (order \<G>)*(order \<G>) - w*c) mod (order \<G>));
return_spmf ((a,a'),c, z)}"
using h_sub assms by(simp cong: bind_spmf_cong_simp)
also have "... = do {
let (h, h') = H;
c \<leftarrow> samp_uni_units (order \<G>);
z \<leftarrow> (sample_uniform (order \<G>));
let a = \<^bold>g (^) z \<otimes> inv (h (^) c);
let a' = g' (^) ((z + (order \<G>)*(order \<G>) - w*c));
return_spmf ((a,a'),c, z)}"
using g'_carrier pow_carrier_mod[of "g'"] by simp
also have "... = do {
let (h, h') = H;
c \<leftarrow> samp_uni_units (order \<G>);
z \<leftarrow> (sample_uniform (order \<G>));
let a = \<^bold>g (^) z \<otimes> inv (h (^) c);
let a' = g' (^) z \<otimes> inv (h' (^) c);
return_spmf ((a,a'),c, z)}"
using h_sub2 assms by(simp cong: bind_spmf_cong_simp)
ultimately show ?thesis
unfolding challenge_def S2_def init_def
by(simp add: split_def Let_def)
qed
thus ?thesis using R2_eq_R by simp
qed
lemma inverse: assumes "gcd w (order \<G>) = 1"
shows "[w * (fst (bezw w (order \<G>))) = 1] (mod order \<G>)"
proof-
have 2: "fst (bezw w (order \<G>)) * w + snd (bezw w (order \<G>)) * int (order \<G>) = 1"
using bezw_aux assms int_minus by presburger
hence 3: "(fst (bezw w (order \<G>)) * w + snd (bezw w (order \<G>)) * int (order \<G>)) mod (order \<G>) = 1 mod (order \<G>)"
by (simp add: zmod_int)
hence 4: "(fst (bezw w (order \<G>)) * w) mod (order \<G>) = 1 mod (order \<G>)"
by simp
hence 5: "[(fst (bezw w (order \<G>))) * w = 1] (mod order \<G>)"
using 2 3 cong_int_def by auto
then show ?thesis by(simp add: mult.commute)
qed
lemma witness_find:
assumes "ya < order \<G>" and "yb < order \<G>" and "y < order \<G>" and w: "w < order \<G>" and "h = \<^bold>g (^) w" and "ya \<noteq> yb" and "w \<noteq> 0"
shows "w = (if (ya > yb) then nat ((int ((w * ya + y) mod order \<G>) - int ((w * yb + y) mod order \<G>)) * fst (bezw (ya - yb) (order \<G>)) mod int (order \<G>))
else nat ((int ((w * yb + y) mod order \<G>) - int ((w * ya + y) mod order \<G>)) * fst (bezw (yb - ya) (order \<G>)) mod int (order \<G>)))"
proof(cases "ya > yb")
case True
have gcd: "gcd (ya - yb) (order \<G>) = 1"
proof-
have "(ya - yb) < order \<G>" and "(ya - yb) \<noteq> 0"
apply(simp add: less_imp_diff_less assms True)
using True by simp
then show ?thesis using prime_field by blast
qed
have "[w*(ya - yb)*(fst (bezw (ya - yb) (order \<G>))) = (w*ya - w*yb)*(fst (bezw (ya - yb) (order \<G>)))] (mod (order \<G>))"
by (simp add: diff_mult_distrib2 assms cong_nat_def)
hence "[w*((ya - yb)*(fst (bezw (ya - yb) (order \<G>)))) = (w*ya - w*yb)*(fst (bezw (ya - yb) (order \<G>)))] (mod (order \<G>))"
by (simp add: mult.assoc)
hence "[w = (w*ya - w*yb)*(fst (bezw (ya - yb) (order \<G>)))] (mod (order \<G>))"
by (metis (no_types, hide_lams) gcd inverse[of "ya - yb"] cong_scalar_int cong_sym_int cong_trans_int mult.commute mult.left_neutral)
hence "[int w = (int w* int ya - int w* int yb)*(fst (bezw (ya - yb) (order \<G>)))] (mod (order \<G>))"
by (simp add: True less_imp_le_nat of_nat_diff)
hence "int w mod order \<G> = (int w* int ya - int w* int yb)*(fst (bezw (ya - yb) (order \<G>))) mod (order \<G>)"
using cong_int_def by blast
hence "w mod order \<G> = (int w* int ya - int w* int yb)*(fst (bezw (ya - yb) (order \<G>))) mod (order \<G>)"
by (simp add: zmod_int)
then show ?thesis using w
proof -
have f1: "\<forall>n na nb. int (nb + na) - int (nb + n) = int na - int n"
by simp
have "(int (w * ya) - int (w * yb)) * fst (bezw (ya - yb) (order \<G>)) mod int (order \<G>) = int w"
using \<open>int (w mod order \<G>) = (int w * int ya - int w * int yb) * fst (bezw (ya - yb) (order \<G>)) mod int (order \<G>)\<close> w by force
then show ?thesis
using f1
proof -
have "nat ((int ((y + w * ya) mod order \<G>) - int ((y + w * yb) mod order \<G>)) * fst (bezw (if True then ya - yb else yb - ya) (order \<G>)) mod int (order \<G>)) = w"
by (metis (no_types) \<open>(int (w * ya) - int (w * yb)) * fst (bezw (ya - yb) (order \<G>)) mod int (order \<G>) = int w\<close> \<open>\<forall>n na nb. int (nb + na) - int (nb + n) = int na - int n\<close> mod_diff_left_eq mod_diff_right_eq mod_mult_cong nat_int zmod_int)
then show ?thesis
by (simp add: True add.commute)
qed
qed
next
case False
have False': "yb > ya" using False assms
using nat_neq_iff by blast
have gcd: "gcd (yb - ya) (order \<G>) = 1"
proof-
have "(yb - ya) < order \<G>" and "(yb - ya) \<noteq> 0"
using less_imp_diff_less assms apply blast
using assms(6) zero_less_diff False' by blast
then show ?thesis using prime_field by blast
qed
have "[w*(yb - ya)*(fst (bezw (yb - ya) (order \<G>))) = (w*yb - w*ya)*(fst (bezw (yb - ya) (order \<G>)))] (mod (order \<G>))"
using assms cong_nat_def
by (simp add: diff_mult_distrib2)
then have "[w*((yb - ya)*(fst (bezw (yb - ya) (order \<G>)))) = (w*yb - w*ya)*(fst (bezw (yb - ya) (order \<G>)))] (mod (order \<G>))"
by (simp add: mult.assoc)
then have "[w = (w*yb - w*ya)*(fst (bezw (yb - ya) (order \<G>)))] (mod (order \<G>))"
using gcd inverse[of "(yb - ya)"]
by (metis (no_types, hide_lams) cong_scalar_int cong_sym_int cong_trans_int mult.commute mult.left_neutral)
then have "[int w = (int w* int yb - int w* int ya)*(fst (bezw (yb - ya) (order \<G>)))] (mod (order \<G>))"
by (simp add: False' less_imp_le_nat of_nat_diff)
then have "int w mod order \<G> = (int w* int yb - int w* int ya)*(fst (bezw (yb - ya) (order \<G>))) mod (order \<G>)"
using cong_int_def by blast
hence "w mod order \<G> = (int w* int yb - int w* int ya)*(fst (bezw (yb - ya) (order \<G>))) mod (order \<G>)"
by (simp add: zmod_int)
then show ?thesis using w
proof -
have f1: "\<forall>n na nb. int (nb + na) - int (nb + n) = int na - int n"
by simp
have "(int (w * yb) - int (w * ya)) * fst (bezw (yb - ya) (order \<G>)) mod int (order \<G>) = int w"
using \<open>int (w mod order \<G>) = (int w * int yb - int w * int ya) * fst (bezw (yb - ya) (order \<G>)) mod int (order \<G>)\<close> w by force
then show ?thesis
using f1
proof -
have "nat ((int ((y + w * yb) mod order \<G>) - int ((y + w * ya) mod order \<G>)) * fst (bezw (if True then yb - ya else ya - yb) (order \<G>)) mod int (order \<G>)) = w"
by (metis (no_types) \<open>(int (w * yb) - int (w * ya)) * fst (bezw (yb - ya) (order \<G>)) mod int (order \<G>) = int w\<close> \<open>\<forall>n na nb. int (nb + na) - int (nb + n) = int na - int n\<close> mod_diff_left_eq mod_diff_right_eq mod_mult_cong nat_int zmod_int)
then show ?thesis
by (simp add: False add.commute)
qed
qed
qed
lemma honest_verifier_ZK2:
shows "epsilon_protocols_base.honest_V_ZK H w"
unfolding epsilon_protocols_base.honest_V_ZK_def R_def
using hv_zk2[of "H" "w"]
by (metis prod.collapse)
lemma special_soundness:
shows "epsilon_protocols_base.special_soundness h w"
proof-
{assume w1: "w \<noteq> 0" and w2: "w < order \<G>"
have "local.epsilon_protocols_base.special_soundness_game h w pk_adversary2 = return_spmf True"
(is "?lhs = ?rhs")
proof-
have "?lhs = do {
y \<leftarrow> sample_uniform (order \<G>);
ya \<leftarrow> samp_uni_units (order \<G>);
yb \<leftarrow> samp_uni_units_excl (order \<G>) ya;
return_spmf (w = (if (ya > yb) then nat ((int ((w * ya + y) mod order \<G>) - int ((w * yb + y) mod order \<G>)) * fst (bezw (ya - yb) (order \<G>)) mod int (order \<G>))
else nat ((int ((w * yb + y) mod order \<G>) - int ((w * ya + y) mod order \<G>)) * fst (bezw (yb - ya) (order \<G>)) mod int (order \<G>))))}"
unfolding local.epsilon_protocols_base.special_soundness_game_def pk_adversary2_def
by(simp add: response_def challenge_def init_def snd_challenge_def)
then show ?thesis
by(simp add: lossless_samp_uni_units lossless_samp_uni_units_excl witness_find w1 w2 bind_spmf_const lossless_samp_uni_excl lossless_samp_uni lossless_weight_spmfD cong: bind_spmf_cong_simp)
qed }
then have "w \<noteq> 0 \<Longrightarrow> w < order \<G> \<Longrightarrow> spmf (local.epsilon_protocols_base.special_soundness_game h w pk_adversary2) True = 1"
by simp
then show ?thesis unfolding epsilon_protocols_base.special_soundness_def R_def by auto
qed
theorem "epsilon_protocols_base.\<Sigma>_protocol h w"
by(simp add: epsilon_protocols_base.\<Sigma>_protocol_def completeness honest_verifier_ZK2 special_soundness)
end
locale asy_schnorr_2 =
fixes \<G> :: "nat \<Rightarrow> 'grp cyclic_group"
assumes schnorr_2: "\<And>n. schnorr_2 (\<G> n) x g'"
begin
sublocale schnorr_2 "(\<G> n)" for n by(simp add: schnorr_2)
theorem "epsilon_protocols_base.\<Sigma>_protocol n g' h w"
by (simp add: completeness honest_verifier_ZK2 local.epsilon_protocols_base.\<Sigma>_protocol_def special_soundness)
end
end |
[STATEMENT]
lemma finite_hom_components: "finite (hom_components p)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. finite (hom_components p)
[PROOF STEP]
unfolding hom_components_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. finite (hom_component p ` deg_pm ` keys p)
[PROOF STEP]
using finite_keys
[PROOF STATE]
proof (prove)
using this:
finite (keys ?f)
goal (1 subgoal):
1. finite (hom_component p ` deg_pm ` keys p)
[PROOF STEP]
by (intro finite_imageI) |
State Before: α : Type u_2
β : Type u_3
ι : Type ?u.401033
mα : MeasurableSpace α
mβ : MeasurableSpace β
κ : { x // x ∈ kernel α β }
E : Type u_1
inst✝³ : NormedAddCommGroup E
inst✝² : NormedSpace ℝ E
inst✝¹ : CompleteSpace E
f : β → E
g : α → β
a : α
hg : Measurable g
inst✝ : MeasurableSingletonClass β
⊢ (∫ (x : β), f x ∂↑(deterministic g hg) a) = f (g a) State After: no goals Tactic: rw [kernel.deterministic_apply, integral_dirac _ (g a)] |
{-# OPTIONS --without-K --safe #-}
open import Categories.Category
-- the usual notion requires C to have finite limits.
-- this definition is a generalization by omitting that requirement as the definition
-- itself does not involve any limit.
module Categories.Diagram.SubobjectClassifier {o ℓ e} (C : Category o ℓ e) where
open Category C
open import Level
open import Categories.Object.Terminal C
open import Categories.Morphism C
open import Categories.Diagram.Pullback C
record SubobjectClassifier : Set (o ⊔ ℓ ⊔ e) where
field
Ω : Obj
terminal : Terminal
module terminal = Terminal terminal
open terminal
field
true : ⊤ ⇒ Ω
universal : ∀ {X Y} {f : X ⇒ Y} → Mono f → Y ⇒ Ω
pullback : ∀ {X Y} {f : X ⇒ Y} {mono : Mono f} → Pullback (universal mono) true
unique : ∀ {X Y} {f : X ⇒ Y} {g} {mono : Mono f} → Pullback g true → universal mono ≈ g
|
[STATEMENT]
lemma del_list_sorted2: "sorted1 (xs @ (a,b) # ys) \<Longrightarrow> x < a \<Longrightarrow>
del_list x (xs @ (a,b) # ys) = del_list x xs @ (a,b) # ys"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>sorted1 (xs @ (a, b) # ys); x < a\<rbrakk> \<Longrightarrow> del_list x (xs @ (a, b) # ys) = del_list x xs @ (a, b) # ys
[PROOF STEP]
by (auto simp: del_list_sorted) |
import shannon_theory
---- MUTUAL INFORMATION
open_locale big_operators
universe x
variables {ι : Type x} [fintype ι]
(X Y : ι → ℝ) [rnd_var X] [rnd_var Y]
/--
Definition (mutual information): Let X and Y be discrete random variables with
joint probability distribution pX,Y (x, y). The mutual information I(X; Y ) is the marginal
entropy H(X) less the conditional entropy H(X|Y):
I(X; Y ) ≡ H(X) − H(X|Y).
https://arxiv.org/pdf/1106.1445.pdf
-/
def mut_info : ℝ :=
Shannon_entropy(X) - (cond_entropy XY X Y)
notation `I(`X`;`Y`)` := mut_info X Y
variables {X} {Y}
/--
Lemma (symmetry in the input): mutual information is symmetric in the input.
-/
@[simp] lemma mut_info_comm : I(X;Y) = I(Y;X) :=
begin
sorry,
end
/--
Lemma (nonnegativity): The mutual information I(X;Y) is non-negative for any
random variables X and Y :
I(X; Y ) ≥ 0.
-/
lemma mut_info_nonneg : I(X;Y) ≥ 0 :=
begin
sorry,
end
/--
Lemma (mutual info zero iff independent random variable) : I(X;Y) = 0 if and
only if X and Y are independent random variables (i.e., if pX,Y (x, y) =
pX(x)pY (y)).
-/
lemma mut_info_zero_iff_independent :
I(X;Y) = 0 ↔ indpndnt_rnd_vars X Y :=
begin
sorry,
end |
/* Copyright 2016-2017 Joaquin M Lopez Munoz.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* See http://www.boost.org/libs/poly_collection for library home page.
*/
/* basic usage of boost::function_collection */
#include <boost/poly_collection/function_collection.hpp>
#include <functional>
#include <memory>
#include <random>
#include <vector>
#include "rolegame.hpp"
int main()
{
//[basic_function_1
std::vector<std::unique_ptr<sprite>> sprs;
std::vector<std::string> msgs;
std::vector<window> wnds;
//]
// populate sprs
std::mt19937 gen{92748}; // some arbitrary random seed
std::discrete_distribution<> rnd{{1,1,1}};
for(int i=0;i<4;++i){ // assign each type with 1/3 probability
switch(rnd(gen)){
case 0: sprs.push_back(std::make_unique<warrior>(i));;break;
case 1: sprs.push_back(std::make_unique<juggernaut>(i));break;
case 2: sprs.push_back(std::make_unique<goblin>(i));break;
}
}
// populate msgs
msgs.push_back("\"stamina: 10,000\"");
msgs.push_back("\"game over\"");
// populate wnds
wnds.emplace_back("pop-up 1");
wnds.emplace_back("pop-up 2");
//[basic_function_2
//= #include <boost/poly_collection/function_collection.hpp>
//= ...
//=
// function signature accepting std::ostream& and returning nothing
using render_callback=void(std::ostream&);
boost::function_collection<render_callback> c;
//]
//[basic_function_3
//<-
auto render_sprite=[](const sprite& s){
//->
//= auto render_sprite(const sprite& s){
return [&](std::ostream& os){s.render(os);};
}/*<-*/;/*->*/
//<-
auto render_message=[](const std::string& m){
//->
//= auto render_message(const std::string& m){
return [&](std::ostream& os){os<<m;};
}/*<-*/;/*->*/
//<-
auto render_window=[](const window& w){
//->
//= auto render_window(const window& w){
return [&](std::ostream& os){w.display(os);};
}/*<-*/;/*->*/
//= ...
//=
for(const auto& ps:sprs)c.insert(render_sprite(*ps));
for(const auto& m:msgs)c.insert(render_message(m));
for(const auto& w:wnds)c.insert(render_window(w));
//]
//[basic_function_4
const char* comma="";
for(const auto& cbk:c){
std::cout<<comma;
cbk(std::cout);
comma=",";
}
std::cout<<"\n";
//]
//[basic_function_5
auto cbk=*c.begin();
cbk(std::cout); // renders first element to std::cout
std::function<render_callback> f=cbk;
f(std::cout); // exactly the same
//]
//[basic_function_6
//= *c.begin()=render_message("last minute message"); // compile-time error
//]
}
|
\section{Job Monitor}
\index{Job monitor}
\index{viewing!log files}
The Condor Job Monitor is a Java application designed to allow users to view user log files.
To view a user log file, select it using the open file command in the File menu. After the file is parsed, it will be visually represented. Each horizontal line represents an individual job. The x-axis
is time. Whether a job is running at a particular time is represented by its color at that time -- white for running, black for idle. For example, a job which appears predominantly white has made
efficient progress, whereas a job which appears predominantly black has received an inordinately small proportion of computational time.
\subsection{\label{sec:transition-states}Transition States}
A transition state is the state of a job at any time. It is called a "transition" because it is defined by the two events which bookmark it. There are two basic transition states: running and idle.
An idle job typically is a job which has just been submitted into the Condor pool and is waiting to be matched with an appropriate machine or a job which has vacated from a machine and has been
returned to the pool. A running job, by contrast, is a job which is making active progress.
Advanced users may want a visual distinction between two types of running transitions: "goodput" or "badput". Goodput is the transition state preceding an eventual job completion or
checkpoint. Badput is the transition state preceding a non-checkpointed eviction event. Note that "badput" is potentially a misleading nomenclature; a job which is not checkpointed by the
Condor program may checkpoint itself or make progress in some other way. To view these two transition as distinct transitions, select the appropriate option from the "View" menu.
\subsection{\label{sec:events}Events}
There are two basic kinds of events: checkpoint events and error events. Plus advanced users can ask to see more events.
\subsection{\label{sec:job-selector}Selecting Jobs}
To view any arbitrary selection of jobs in a job file, use the job selector tool. Jobs appear visually by order of appearance within the actual text log file. For example, the log file might contain jobs
775.1, 775.2, 775.3, 775.4, and 775.5, which appear in that order. A user who wishes to see only jobs 775.2 and 775.5 can select only these two jobs in the job selector tool and click the "Ok" or
"Apply" button. The job selector supports double clicking; double
click on any single job to see it drawn in isolation.
\subsection{\label{sec:zooming}Zooming}
To view a small area of the log file, zoom in on the area which you would like to see in greater detail. You can zoom in, out and do a full zoom. A full zoom redraws the log file in its entirety. For
example, if you have zoomed in very close and would like to go all the way back out, you could do so with a succession of zoom outs or with one full zoom.
There is a difference between using the menu driven zooming and the mouse driven zooming. The menu driven zooming will recenter itself around the current center, whereas mouse driven
zooming will recenter itself (as much as possible) around the mouse click. To help you re-find the clicked area, a box will flash after the zoom. This is called the "zoom finder" and it can be turned
off in the zoom menu if you prefer.
\subsection{\label{sec:k-m-shortcuts}Keyboard and Mouse Shortcuts}
\begin{enumerate}
\item The Keyboard shortcuts:
\begin{itemize}
\item Arrows - an approximate ten percent scrollbar movement
\item PageUp and PageDown - an approximate one hundred percent scrollbar movement
\item Control + Left or Right - approximate one hundred percent scrollbar movement
\item End and Home - scrollbar movement to the vertical extreme
\item Others - as seen beside menu items
\end{itemize}
\item The mouse shortcuts:
\begin{itemize}
\item Control + Left click - zoom in
\item Control + Right click - zoom out
\item Shift + left click - re-center
\end{itemize}
\end{enumerate}
|
// Copyright (c) 2007-2012 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(HPX_TRAITS_IS_FUTURE_RANGE_HPP)
#define HPX_TRAITS_IS_FUTURE_RANGE_HPP
#include <hpx/traits/is_future.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/or.hpp>
#include <boost/range/iterator_range.hpp>
#include <vector>
namespace hpx { namespace traits
{
///////////////////////////////////////////////////////////////////////////
template <typename Range, typename Enable>
struct is_future_range
: boost::mpl::false_
{};
template <typename T>
struct is_future_range<std::vector<T> >
: is_future<T>
{};
template <typename Iterator>
struct is_future_range<boost::iterator_range<Iterator> >
: is_future<typename std::iterator_traits<Iterator>::value_type>
{};
///////////////////////////////////////////////////////////////////////////
template <typename Range, typename Enable>
struct future_range_traits;
template <typename T>
struct future_range_traits<
std::vector<T>, typename boost::enable_if<is_future<T> >::type
>
{
typedef T future_type;
};
template <typename Iterator>
struct future_range_traits<
boost::iterator_range<Iterator>,
typename boost::enable_if<
is_future<typename std::iterator_traits<Iterator>::value_type>
>::type
>
{
typedef typename std::iterator_traits<Iterator>::value_type future_type;
};
///////////////////////////////////////////////////////////////////////////
template <typename T>
struct is_future_or_future_range
: boost::mpl::or_<is_future<T>, is_future_range<T> >
{};
}}
#endif
|
/-
Copyright (c) 2022 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.group.pi
import category_theory.limits.shapes.biproducts
import algebra.category.Module.limits
import algebra.homology.short_exact.abelian
/-!
# The category of `R`-modules has finite biproducts
-/
open category_theory
open category_theory.limits
open_locale big_operators
universes w v u
namespace Module
variables {R : Type u} [ring R]
-- As `Module R` is preadditive, and has all limits, it automatically has biproducts.
instance : has_binary_biproducts (Module.{v} R) :=
has_binary_biproducts.of_has_binary_products
instance : has_finite_biproducts (Module.{v} R) :=
has_finite_biproducts.of_has_finite_products
-- We now construct explicit limit data,
-- so we can compare the biproducts to the usual unbundled constructions.
/--
Construct limit data for a binary product in `Module R`, using `Module.of R (M × N)`.
-/
@[simps cone_X is_limit_lift]
def binary_product_limit_cone (M N : Module.{v} R) : limits.limit_cone (pair M N) :=
{ cone :=
{ X := Module.of R (M × N),
π :=
{ app := λ j, discrete.cases_on j
(λ j, walking_pair.cases_on j (linear_map.fst R M N) (linear_map.snd R M N)),
naturality' := by rintros ⟨⟨⟩⟩ ⟨⟨⟩⟩ ⟨⟨⟨⟩⟩⟩; refl, }},
is_limit :=
{ lift := λ s, linear_map.prod (s.π.app ⟨walking_pair.left⟩) (s.π.app ⟨walking_pair.right⟩),
fac' := by { rintros s (⟨⟩|⟨⟩); { ext x, simp, }, },
uniq' := λ s m w,
begin
ext; [rw ← w ⟨walking_pair.left⟩, rw ← w ⟨walking_pair.right⟩]; refl,
end, } }
@[simp] lemma binary_product_limit_cone_cone_π_app_left (M N : Module.{v} R) :
(binary_product_limit_cone M N).cone.π.app ⟨walking_pair.left⟩ = linear_map.fst R M N := rfl
@[simp] lemma binary_product_limit_cone_cone_π_app_right (M N : Module.{v} R) :
(binary_product_limit_cone M N).cone.π.app ⟨walking_pair.right⟩ = linear_map.snd R M N := rfl
/--
We verify that the biproduct in `Module R` is isomorphic to
the cartesian product of the underlying types:
-/
@[simps hom_apply] noncomputable
def biprod_iso_prod (M N : Module.{v} R) : (M ⊞ N : Module.{v} R) ≅ Module.of R (M × N) :=
is_limit.cone_point_unique_up_to_iso
(binary_biproduct.is_limit M N)
(binary_product_limit_cone M N).is_limit
@[simp, elementwise] lemma biprod_iso_prod_inv_comp_fst (M N : Module.{v} R) :
(biprod_iso_prod M N).inv ≫ biprod.fst = linear_map.fst R M N :=
is_limit.cone_point_unique_up_to_iso_inv_comp _ _ (discrete.mk walking_pair.left)
@[simp, elementwise] lemma biprod_iso_prod_inv_comp_snd (M N : Module.{v} R) :
(biprod_iso_prod M N).inv ≫ biprod.snd = linear_map.snd R M N :=
is_limit.cone_point_unique_up_to_iso_inv_comp _ _ (discrete.mk walking_pair.right)
namespace has_limit
variables {J : Type w} (f : J → Module.{max w v} R)
/--
The map from an arbitrary cone over a indexed family of abelian groups
to the cartesian product of those groups.
-/
@[simps]
def lift (s : fan f) :
s.X ⟶ Module.of R (Π j, f j) :=
{ to_fun := λ x j, s.π.app ⟨j⟩ x,
map_add' := λ x y, by { ext, simp, },
map_smul' := λ r x, by { ext, simp, }, }
/--
Construct limit data for a product in `Module R`, using `Module.of R (Π j, F.obj j)`.
-/
@[simps] def product_limit_cone : limits.limit_cone (discrete.functor f) :=
{ cone :=
{ X := Module.of R (Π j, f j),
π := discrete.nat_trans (λ j, (linear_map.proj j.as : (Π j, f j) →ₗ[R] f j.as)), },
is_limit :=
{ lift := lift f,
fac' := λ s j, by { cases j, ext, simp, },
uniq' := λ s m w,
begin
ext x j,
dsimp only [has_limit.lift],
simp only [linear_map.coe_mk],
exact congr_arg (λ g : s.X ⟶ f j, (g : s.X → f j) x) (w ⟨j⟩),
end, }, }
end has_limit
open has_limit
variables {J : Type} (f : J → Module.{v} R)
/--
We verify that the biproduct we've just defined is isomorphic to the `Module R` structure
on the dependent function type
-/
@[simps hom_apply] noncomputable
def biproduct_iso_pi [fintype J] (f : J → Module.{v} R) :
(⨁ f : Module.{v} R) ≅ Module.of R (Π j, f j) :=
is_limit.cone_point_unique_up_to_iso
(biproduct.is_limit f)
(product_limit_cone f).is_limit
@[simp, elementwise] lemma biproduct_iso_pi_inv_comp_π [fintype J]
(f : J → Module.{v} R) (j : J) :
(biproduct_iso_pi f).inv ≫ biproduct.π f j = (linear_map.proj j : (Π j, f j) →ₗ[R] f j) :=
is_limit.cone_point_unique_up_to_iso_inv_comp _ _ (discrete.mk j)
end Module
section split_exact
variables {R : Type u} {A M B : Type v} [ring R] [add_comm_group A] [module R A]
[add_comm_group B] [module R B] [add_comm_group M] [module R M]
variables {j : A →ₗ[R] M} {g : M →ₗ[R] B}
open Module
/--The isomorphism `A × B ≃ₗ[R] M` coming from a right split exact sequence `0 ⟶ A ⟶ M ⟶ B ⟶ 0`
of modules.-/
noncomputable def lequiv_prod_of_right_split_exact {f : B →ₗ[R] M}
(hj : function.injective j) (exac : j.range = g.ker) (h : g.comp f = linear_map.id) :
(A × B) ≃ₗ[R] M :=
(({ right_split := ⟨as_hom f, h⟩,
mono := (Module.mono_iff_injective $ as_hom j).mpr hj,
exact := (exact_iff _ _).mpr exac } : right_split _ _).splitting.iso.trans $
biprod_iso_prod _ _).to_linear_equiv.symm
/--The isomorphism `A × B ≃ₗ[R] M` coming from a left split exact sequence `0 ⟶ A ⟶ M ⟶ B ⟶ 0`
of modules.-/
noncomputable def lequiv_prod_of_left_split_exact {f : M →ₗ[R] A}
(hg : function.surjective g) (exac : j.range = g.ker) (h : f.comp j = linear_map.id) :
(A × B) ≃ₗ[R] M :=
(({ left_split := ⟨as_hom f, h⟩,
epi := (Module.epi_iff_surjective $ as_hom g).mpr hg,
exact := (exact_iff _ _).mpr exac } : left_split _ _).splitting.iso.trans $
biprod_iso_prod _ _).to_linear_equiv.symm
end split_exact
|
%% Transient diffusion equation
%% PDE and boundary conditions
% The transient diffusion equation reads
%
% $$\alpha\frac{\partial c}{\partial t}+\nabla.\left(-D\nabla c\right)=0,$$
%
% where $c$ is the independent variable (concentration, temperature, etc)
% , $D$ is the diffusion coefficient, and $\alpha$ is a constant.
% Written by Ali A. Eftekhari
% Last checked: June 2021
clc
%% Define the domain and create a mesh structure
L = 50; % domain length
Nx = 20; % number of cells
m = createMesh3D(Nx,Nx,Nx, L,L,L);
%% Create the boundary condition structure
BC = createBC(m); % all Neumann boundary condition structure
BC.left.a(:) = 0; BC.left.b(:)=1; BC.left.c(:)=0; % left boundary
BC.right.a(:) = 0; BC.right.b(:)=1; BC.right.c(:)=0; % right boundary
BC.top.a(:) = 0; BC.top.b(:)=1; BC.top.c(:)=0; % top boundary
BC.bottom.a(:) = 0; BC.bottom.b(:)=1; BC.bottom.c(:)=0; % bottom boundary
%% define the transfer coeffs
D_val = 1;
D = createCellVariable(m, D_val);
alfa = createCellVariable(m, 1);
%% define initial values
c_init = 1;
c_old = createCellVariable(m, c_init,BC); % initial values
c = c_old; % assign the old value of the cells to the current values
%% loop
dt = 1; % time step
final_t = 50;
for t=dt:dt:final_t
[M_trans, RHS_trans] = transientTerm(c_old, dt, alfa);
Dave = harmonicMean(D);
Mdiff = diffusionTerm(Dave);
[Mbc, RHSbc] = boundaryCondition(BC);
M = M_trans-Mdiff+Mbc;
RHS = RHS_trans+RHSbc;
c = solvePDE(m,M, RHS);
c_old = c;
end
%% visualization
visualizeCells(c)
|
The ship mounted four 45 @-@ calibre quick @-@ firing ( QF ) 4 @.@ 7 @-@ inch Mk IX guns in single mounts , designated ' A ' , ' B ' , ' X ' , and ' Y ' from front to rear . For anti @-@ aircraft ( AA ) defence , Boreas had two 40 @-@ millimetre ( 1 @.@ 6 in ) QF 2 @-@ pounder Mk II AA guns mounted on a platform between her funnels . She was fitted with two above @-@ water quadruple torpedo tube mounts for 21 @-@ inch ( 533 mm ) torpedoes . One depth charge rail and two throwers were fitted ; 20 depth charges were originally carried , but this increased to 35 shortly after the war began . The ship was fitted with a Type 119 ASDIC set to detect submarines through sound waves beamed into the water that would reflect off the submarine .
|
// ***********************************************************************
// DO NOT EDIT THIS FILE !!!
// ***********************************************************************
// This file is automatically generated from the grib_api templates. All
// changes will be overridden. If you want to do permanent changes then
// you should write them into the 'AzimuthRangeImpl.*' files.
// ***********************************************************************
#include "AzimuthRange.h"
#include "../../common/GeneralDefinitions.h"
#include "../../common/GeneralFunctions.h"
#include <boost/functional/hash.hpp>
#include <iostream>
#include <macgyver/Exception.h>
namespace SmartMet {
namespace GRIB2 {
/*! \brief The constructor of the class. */
AzimuthRange::AzimuthRange() {
try {
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
/*! \brief The destructor of the class. */
AzimuthRange::~AzimuthRange() {
}
/*! \brief The method reads and initializes all data related to the current object.
\param memoryReader This object controls the access to the memory mapped file.
*/
void AzimuthRange::read(MemoryReader &memoryReader) {
try {
mNumberOfDataBinsAlongRadials = memoryReader.read_UInt32_opt();
mNumberOfRadials = memoryReader.read_UInt32_opt();
mLatitudeOfCenterPoint = memoryReader.read_Int32_opt();
mLongitudeOfCenterPoint = memoryReader.read_UInt32_opt();
mSpacingOfBinsAlongRadials = memoryReader.read_UInt32_opt();
mOffsetFromOriginToInnerBound = memoryReader.read_UInt32_opt();
mScanningMode.read(memoryReader);
mStartingAzimuth = memoryReader.read_Int16_opt();
mAzimuthalWidth = memoryReader.read_Int16_opt();
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
/*! \brief The method writes all data related to the current object.
\param dataWriter This object is used for writing the object data.
*/
void AzimuthRange::write(DataWriter &dataWriter) {
try {
dataWriter << mNumberOfDataBinsAlongRadials;
dataWriter << mNumberOfRadials;
dataWriter << mLatitudeOfCenterPoint;
dataWriter << mLongitudeOfCenterPoint;
dataWriter << mSpacingOfBinsAlongRadials;
dataWriter << mOffsetFromOriginToInnerBound;
mScanningMode.write(dataWriter);
dataWriter << mStartingAzimuth;
dataWriter << mAzimuthalWidth;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
/*! \brief The method is used for collecting the current class attributeList.
\param prefix The prefix of the each attributeList parameter.
\param attributeList The attributeList storage.
*/
void AzimuthRange::getAttributeList(const std::string &prefix, T::AttributeList &attributeList) const {
try {
char name[300];
sprintf(name, "%sAzimuthRange.NumberOfDataBinsAlongRadials", prefix.c_str());
attributeList.addAttribute(name, toString(mNumberOfDataBinsAlongRadials));
sprintf(name, "%sAzimuthRange.NumberOfRadials", prefix.c_str());
attributeList.addAttribute(name, toString(mNumberOfRadials));
sprintf(name, "%sAzimuthRange.LatitudeOfCenterPoint", prefix.c_str());
attributeList.addAttribute(name, toString(mLatitudeOfCenterPoint));
sprintf(name, "%sAzimuthRange.LongitudeOfCenterPoint", prefix.c_str());
attributeList.addAttribute(name, toString(mLongitudeOfCenterPoint));
sprintf(name, "%sAzimuthRange.SpacingOfBinsAlongRadials", prefix.c_str());
attributeList.addAttribute(name, toString(mSpacingOfBinsAlongRadials));
sprintf(name, "%sAzimuthRange.OffsetFromOriginToInnerBound", prefix.c_str());
attributeList.addAttribute(name, toString(mOffsetFromOriginToInnerBound));
sprintf(name, "%sAzimuthRange.", prefix.c_str());
mScanningMode.getAttributeList(name, attributeList);
sprintf(name, "%sAzimuthRange.StartingAzimuth", prefix.c_str());
attributeList.addAttribute(name, toString(mStartingAzimuth));
sprintf(name, "%sAzimuthRange.AzimuthalWidth", prefix.c_str());
attributeList.addAttribute(name, toString(mAzimuthalWidth));
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
/*! \brief The method is used for getting attribute values by their names.
\param attributeName The name of the attribute.
\param attributeValue The value of the attribute (string).
*/
bool AzimuthRange::getAttributeValue(const char *attributeName, std::string &attributeValue) const {
try {
if (attributeName == nullptr)
return false;
if (strcasecmp(attributeName, "NumberOfDataBinsAlongRadials") == 0) {
attributeValue = toString(mNumberOfDataBinsAlongRadials);
return true;
}
if (strcasecmp(attributeName, "NumberOfRadials") == 0) {
attributeValue = toString(mNumberOfRadials);
return true;
}
if (strcasecmp(attributeName, "LatitudeOfCenterPoint") == 0) {
attributeValue = toString(mLatitudeOfCenterPoint);
return true;
}
if (strcasecmp(attributeName, "LongitudeOfCenterPoint") == 0) {
attributeValue = toString(mLongitudeOfCenterPoint);
return true;
}
if (strcasecmp(attributeName, "SpacingOfBinsAlongRadials") == 0) {
attributeValue = toString(mSpacingOfBinsAlongRadials);
return true;
}
if (strcasecmp(attributeName, "OffsetFromOriginToInnerBound") == 0) {
attributeValue = toString(mOffsetFromOriginToInnerBound);
return true;
}
if (mScanningMode.getAttributeValue(attributeName, attributeValue))
return true;
if (strcasecmp(attributeName, "StartingAzimuth") == 0) {
attributeValue = toString(mStartingAzimuth);
return true;
}
if (strcasecmp(attributeName, "AzimuthalWidth") == 0) {
attributeValue = toString(mAzimuthalWidth);
return true;
}
return false;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
/*! \brief The method is used for checking if the attribute value matches to the given value.
\param attributeName The name of the attribute.
\param attributeValue The value of the attribute (string).
*/
bool AzimuthRange::hasAttributeValue(const char *attributeName, const char *attributeValue) const {
try {
if (attributeName == nullptr || attributeValue == nullptr)
return false;
if (strcasecmp(attributeName, "NumberOfDataBinsAlongRadials") == 0 && strcasecmp(attributeValue, toString(mNumberOfDataBinsAlongRadials).c_str()) == 0)
return true;
if (strcasecmp(attributeName, "NumberOfRadials") == 0 && strcasecmp(attributeValue, toString(mNumberOfRadials).c_str()) == 0)
return true;
if (strcasecmp(attributeName, "LatitudeOfCenterPoint") == 0 && strcasecmp(attributeValue, toString(mLatitudeOfCenterPoint).c_str()) == 0)
return true;
if (strcasecmp(attributeName, "LongitudeOfCenterPoint") == 0 && strcasecmp(attributeValue, toString(mLongitudeOfCenterPoint).c_str()) == 0)
return true;
if (strcasecmp(attributeName, "SpacingOfBinsAlongRadials") == 0 && strcasecmp(attributeValue, toString(mSpacingOfBinsAlongRadials).c_str()) == 0)
return true;
if (strcasecmp(attributeName, "OffsetFromOriginToInnerBound") == 0 && strcasecmp(attributeValue, toString(mOffsetFromOriginToInnerBound).c_str()) == 0)
return true;
if (mScanningMode.hasAttributeValue(attributeName, attributeValue))
return true;
if (strcasecmp(attributeName, "StartingAzimuth") == 0 && strcasecmp(attributeValue, toString(mStartingAzimuth).c_str()) == 0)
return true;
if (strcasecmp(attributeName, "AzimuthalWidth") == 0 && strcasecmp(attributeValue, toString(mAzimuthalWidth).c_str()) == 0)
return true;
return false;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
/*! \brief The method prints the content of the current object into the given stream.
\param ostream The output stream.
\param level The print level (used when printing multi-level structures).
\param optionFlags The printing options expressed in flag-bits.
*/
void AzimuthRange::print(std::ostream &stream, uint level, uint optionFlags) const {
try {
stream << space(level) << "AzimuthRange\n";
stream << space(level) << "- NumberOfDataBinsAlongRadials = " << toString(mNumberOfDataBinsAlongRadials) << "\n";
stream << space(level) << "- NumberOfRadials = " << toString(mNumberOfRadials) << "\n";
stream << space(level) << "- LatitudeOfCenterPoint = " << toString(mLatitudeOfCenterPoint) << "\n";
stream << space(level) << "- LongitudeOfCenterPoint = " << toString(mLongitudeOfCenterPoint) << "\n";
stream << space(level) << "- SpacingOfBinsAlongRadials = " << toString(mSpacingOfBinsAlongRadials) << "\n";
stream << space(level) << "- OffsetFromOriginToInnerBound = " << toString(mOffsetFromOriginToInnerBound) << "\n";
mScanningMode.print(stream, level + 1, optionFlags);
stream << space(level) << "- StartingAzimuth = " << toString(mStartingAzimuth) << "\n";
stream << space(level) << "- AzimuthalWidth = " << toString(mAzimuthalWidth) << "\n";
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
/*! \brief The method counts the hash value of the current object. */
T::Hash AzimuthRange::countHash() const {
try {
std::size_t seed = 0;
if (mNumberOfDataBinsAlongRadials)
boost::hash_combine(seed, *mNumberOfDataBinsAlongRadials);
if (mNumberOfRadials)
boost::hash_combine(seed, *mNumberOfRadials);
if (mLatitudeOfCenterPoint)
boost::hash_combine(seed, *mLatitudeOfCenterPoint);
if (mLongitudeOfCenterPoint)
boost::hash_combine(seed, *mLongitudeOfCenterPoint);
if (mSpacingOfBinsAlongRadials)
boost::hash_combine(seed, *mSpacingOfBinsAlongRadials);
if (mOffsetFromOriginToInnerBound)
boost::hash_combine(seed, *mOffsetFromOriginToInnerBound);
if (mStartingAzimuth)
boost::hash_combine(seed, *mStartingAzimuth);
if (mAzimuthalWidth)
boost::hash_combine(seed, *mAzimuthalWidth);
return seed;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
/*! \brief The method return the template number of the current class. */
uint AzimuthRange::getTemplateNumber() const {
return 120;
}
GridDefinition *AzimuthRange::createGridDefinition() const {
try {
return static_cast<GridDefinition *>(new AzimuthRange(*this));
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
/*! \brief The method returns the value of the {@link mNumberOfDataBinsAlongRadials} attribute. */
const T::UInt32_opt &AzimuthRange::getNumberOfDataBinsAlongRadials() const {
try {
return mNumberOfDataBinsAlongRadials;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
/*! \brief The method returns the value of the {@link mNumberOfRadials} attribute. */
const T::UInt32_opt &AzimuthRange::getNumberOfRadials() const {
try {
return mNumberOfRadials;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
/*! \brief The method returns the value of the {@link mLatitudeOfCenterPoint} attribute. */
const T::Int32_opt &AzimuthRange::getLatitudeOfCenterPoint() const {
try {
return mLatitudeOfCenterPoint;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
/*! \brief The method returns the value of the {@link mLongitudeOfCenterPoint} attribute. */
const T::UInt32_opt &AzimuthRange::getLongitudeOfCenterPoint() const {
try {
return mLongitudeOfCenterPoint;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
/*! \brief The method returns the value of the {@link mSpacingOfBinsAlongRadials} attribute. */
const T::UInt32_opt &AzimuthRange::getSpacingOfBinsAlongRadials() const {
try {
return mSpacingOfBinsAlongRadials;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
/*! \brief The method returns the value of the {@link mOffsetFromOriginToInnerBound} attribute. */
const T::UInt32_opt &AzimuthRange::getOffsetFromOriginToInnerBound() const {
try {
return mOffsetFromOriginToInnerBound;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
/*! \brief The method returns the pointer to the {@link mScanningMode} attribute. */
ScanningModeSettings *AzimuthRange::getScanningMode() const {
try {
return static_cast<ScanningModeSettings *>(&mScanningMode);
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
/*! \brief The method returns the value of the {@link mStartingAzimuth} attribute. */
const T::Int16_opt &AzimuthRange::getStartingAzimuth() const {
try {
return mStartingAzimuth;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
/*! \brief The method returns the value of the {@link mAzimuthalWidth} attribute. */
const T::Int16_opt &AzimuthRange::getAzimuthalWidth() const {
try {
return mAzimuthalWidth;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
void AzimuthRange::setNumberOfDataBinsAlongRadials(T::UInt32_opt numberOfDataBinsAlongRadials) {
try {
mNumberOfDataBinsAlongRadials = numberOfDataBinsAlongRadials;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
void AzimuthRange::setNumberOfRadials(T::UInt32_opt numberOfRadials) {
try {
mNumberOfRadials = numberOfRadials;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
void AzimuthRange::setLatitudeOfCenterPoint(T::Int32_opt latitudeOfCenterPoint) {
try {
mLatitudeOfCenterPoint = latitudeOfCenterPoint;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
void AzimuthRange::setLongitudeOfCenterPoint(T::UInt32_opt longitudeOfCenterPoint) {
try {
mLongitudeOfCenterPoint = longitudeOfCenterPoint;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
void AzimuthRange::setSpacingOfBinsAlongRadials(T::UInt32_opt spacingOfBinsAlongRadials) {
try {
mSpacingOfBinsAlongRadials = spacingOfBinsAlongRadials;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
void AzimuthRange::setOffsetFromOriginToInnerBound(T::UInt32_opt offsetFromOriginToInnerBound) {
try {
mOffsetFromOriginToInnerBound = offsetFromOriginToInnerBound;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
void AzimuthRange::setScanningMode(ScanningModeSettings &scanningMode) {
try {
mScanningMode = scanningMode;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
void AzimuthRange::setStartingAzimuth(T::Int16_opt startingAzimuth) {
try {
mStartingAzimuth = startingAzimuth;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
void AzimuthRange::setAzimuthalWidth(T::Int16_opt azimuthalWidth) {
try {
mAzimuthalWidth = azimuthalWidth;
} catch (...) {
throw Fmi::Exception(BCP, "Operation failed", nullptr);
}
}
} // namespace GRIB2
} // namespace SmartMet
|
abstract type GraphvizPoperties end
mutable struct Property{T}
key::String
value::T
end
const Properties = Vector{Property}
# return val of attribute:
function val(attributes::Properties, attribute::String)
if !isempty(attributes)
for a in attributes
if a.key == attribute
return a.value
end
end
end
return []
end
# return Tuple (bool, pos). bool=true if key exist in Attributes
import Base.haskey
function haskey(attributes::Properties, key::String)
if !isempty(attributes)
for i = 1:length(attributes)
if attributes[i].key == key
return true, i
end
end
end
return false, 0
end
# set val to attributeDict
set!(attributes::Properties, prop::Property; override=true) = set!(attributes, prop.key, prop.value; override)
function set!(attributes::Properties, key::String, value; override=true)
key_exist, idx = haskey(attributes, key)
if key_exist & (override == true)
attributes[idx].value = check_value(value)
else
push!(attributes, Property(key, check_value(value)))
end
end
# remove attribute of attributes
rm!(attributes::Properties, prop::Property) = rm!(attributes, prop.key)
function rm!(attributes::Properties, key::String)
key_exist, idx = haskey(attributes, key)
(key_exist) ? deleteat!(attributes, idx) : nothing
end |
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✝¹ : CommRing k
inst✝ : IsDomain k
f : R →+* k
x : k
hp : p ≠ 0
⊢ x ∈ roots (map f p) ↔ eval₂ f x p = 0 State After: no goals Tactic: rw [mem_roots (map_ne_zero hp), IsRoot, Polynomial.eval_map] |
Require Import Coq.Logic.Classical_Prop.
Require Import Logic.lib.Ensembles_ext.
Require Import Logic.lib.Bijection.
Require Import Logic.lib.Countable.
Require Import Logic.GeneralLogic.Base.
Require Import Logic.GeneralLogic.KripkeModel.
Require Import Logic.GeneralLogic.Complete.ContextProperty.
Require Import Logic.GeneralLogic.Complete.ContextProperty_Kripke.
Require Import Logic.GeneralLogic.Complete.Lindenbaum.
Require Import Logic.GeneralLogic.Complete.Lindenbaum_Kripke.
Require Import Logic.MinimunLogic.Syntax.
Require Import Logic.MinimunLogic.ProofTheory.Minimun.
Require Import Logic.MinimunLogic.Complete.ContextProperty_Kripke.
Require Import Logic.MinimunLogic.Complete.Lindenbaum_Kripke.
Require Import Logic.PropositionalLogic.Syntax.
Require Import Logic.PropositionalLogic.ProofTheory.Intuitionistic.
Require Import Logic.PropositionalLogic.ProofTheory.DeMorgan.
Require Import Logic.PropositionalLogic.ProofTheory.GodelDummett.
Require Import Logic.PropositionalLogic.ProofTheory.Classical.
Require Import Logic.PropositionalLogic.Semantics.Trivial.
Require Import Logic.PropositionalLogic.Complete.ContextProperty_Kripke.
Require Import Logic.PropositionalLogic.Complete.ContextProperty_Trivial.
Require Import Logic.PropositionalLogic.Complete.Lindenbaum_Kripke.
Require Import Logic.PropositionalLogic.Complete.Lindenbaum_Trivial.
Require Import Logic.PropositionalLogic.Complete.Truth_Trivial.
Require Import Logic.PropositionalLogic.Complete.Complete_Trivial.
Require Logic.PropositionalLogic.DeepEmbedded.PropositionalLanguage.
Require Logic.PropositionalLogic.DeepEmbedded.ProofTheories.
Require Logic.PropositionalLogic.DeepEmbedded.TrivialSemantics.
Local Open Scope logic_base.
Local Open Scope syntax.
Local Open Scope kripke_model.
Local Open Scope kripke_model_class.
Import PropositionalLanguageNotation.
Import KripkeModelFamilyNotation.
Import KripkeModelNotation_Intuitionistic.
Import KripkeModelClass.
Section Complete.
Context {Sigma: PropositionalLanguage.PropositionalVariables}
{CV: Countable PropositionalLanguage.Var}.
Existing Instances PropositionalLanguage.L PropositionalLanguage.minL PropositionalLanguage.pL.
Existing Instances TrivialSemantics.MD TrivialSemantics.SM TrivialSemantics.tminSM TrivialSemantics.tpSM.
Existing Instances ProofTheories.ClassicalPropositionalLogic.G ProofTheories.ClassicalPropositionalLogic.AX ProofTheories.ClassicalPropositionalLogic.minAX ProofTheories.ClassicalPropositionalLogic.ipG ProofTheories.ClassicalPropositionalLogic.cpG.
Existing Instances Axiomatization2SequentCalculus_SC Axiomatization2SequentCalculus_bSC Axiomatization2SequentCalculus_fwSC Axiomatization2SequentCalculus_minSC Axiomatization2SequentCalculus_ipSC Axiomatization2SequentCalculus_cpSC.
Definition cP: context -> Prop := maximal consistent.
Lemma AL_MC: at_least (maximal consistent) cP.
Proof. solve_at_least. Qed.
Lemma LIN_CONSI: Lindenbaum_constructable consistent cP.
Proof.
eapply Lindenbaum_constructable_Same_set.
+ rewrite Same_set_spec.
intros Phi.
apply consistent_spec.
+ apply Lindenbaum_constructable_suffice.
- apply PropositionalLanguage.formula_countable; auto.
- apply Lindenbaum_preserves_cannot_derive.
- apply Lindenbaum_cannot_derive_ensures_max_consistent.
Qed.
Definition canonical_frame: Type := sig cP.
Definition canonical_eval: PropositionalLanguage.Var -> canonical_frame -> Prop :=
fun p a => proj1_sig a (PropositionalLanguage.varp p).
Definition kMD: KripkeModel TrivialSemantics.MD :=
Build_KripkeModel TrivialSemantics.MD
unit (fun _ => canonical_frame) (fun u a v => canonical_eval v a).
Definition canonical_Kmodel: @Kmodel TrivialSemantics.MD kMD := tt.
Definition rel: bijection (Kworlds canonical_Kmodel) (sig cP) := bijection_refl.
Lemma TRUTH:
forall x: expr, forall m Phi, rel m Phi ->
(KRIPKE: canonical_Kmodel, m |= x <-> proj1_sig Phi x).
Proof.
induction x.
+ exact (truth_lemma_andp cP rel AL_MC x1 x2 IHx1 IHx2).
+ exact (truth_lemma_orp cP rel AL_MC x1 x2 IHx1 IHx2).
+ exact (truth_lemma_impp cP rel AL_MC x1 x2 IHx1 IHx2).
+ exact (truth_lemma_falsep cP rel AL_MC).
+ intros; change (m = Phi) in H; subst; reflexivity.
Qed.
Existing Instance kMD.
Theorem complete_Classical_Trivial:
strongly_complete ProofTheories.ClassicalPropositionalLogic.G TrivialSemantics.SM (AllModel _).
Proof.
assert (strongly_complete ProofTheories.ClassicalPropositionalLogic.G TrivialSemantics.SM
(KripkeModelClass _ (fun _ => True))).
Focus 2. {
hnf; intros.
apply (H Phi x).
hnf; intros.
apply H0; auto.
hnf; auto.
} Unfocus.
apply (@general_completeness PropositionalLanguage.L _ _ ProofTheories.ClassicalPropositionalLogic.G _ _ _ _
_ _ _ TrivialSemantics.SM _ _ _ _ rel LIN_CONSI TRUTH); auto.
Qed.
End Complete.
|
(* *********************************************************************)
(* *)
(* The Compcert verified compiler *)
(* *)
(* Xavier Leroy, INRIA Paris-Rocquencourt *)
(* *)
(* Copyright Institut National de Recherche en Informatique et en *)
(* Automatique. All rights reserved. This file is distributed *)
(* under the terms of the INRIA Non-Commercial License Agreement. *)
(* *)
(* *********************************************************************)
(** Compile-time evaluation of initializers for global C variables. *)
Require Import Coqlib.
Require Import Errors.
Require Import Maps.
Require Import Integers.
Require Import Floats.
Require Import Values.
Require Import AST.
Require Import Memory.
Require Import Globalenvs.
Require Import Events.
Require Import Smallstep.
Require Import Ctypes.
Require Import Cop.
Require Import Csyntax.
Require Import Csem.
Require Import Initializers.
Open Scope error_monad_scope.
Section SOUNDNESS.
Variable ge: genv.
(** * Simple expressions and their big-step semantics *)
(** An expression is simple if it contains no assignments and no
function calls. *)
Fixpoint simple (a: expr) : Prop :=
match a with
| Eloc _ _ _ => True
| Evar _ _ => True
| Ederef r _ => simple r
| Efield l1 _ _ => simple l1
| Eval _ _ => True
| Evalof l _ => simple l
| Eaddrof l _ => simple l
| Eunop _ r1 _ => simple r1
| Ebinop _ r1 r2 _ => simple r1 /\ simple r2
| Ecast r1 _ => simple r1
| Eseqand r1 r2 _ => simple r1 /\ simple r2
| Eseqor r1 r2 _ => simple r1 /\ simple r2
| Econdition r1 r2 r3 _ => simple r1 /\ simple r2 /\ simple r3
| Esizeof _ _ => True
| Ealignof _ _ => True
| Eassign _ _ _ => False
| Eassignop _ _ _ _ _ => False
| Epostincr _ _ _ => False
| Ecomma r1 r2 _ => simple r1 /\ simple r2
| Ecall _ _ _ => False
| Ebuiltin _ _ _ _ => False
| Eparen r1 _ _ => simple r1
end.
(** A big-step semantics for simple expressions. Similar to the
big-step semantics from [Cstrategy], with the addition of
conditionals, comma and paren operators. It is a pity we do not
share definitions with [Cstrategy], but such sharing raises
technical difficulties. *)
Section SIMPLE_EXPRS.
Variable e: env.
Variable m: mem.
Inductive eval_simple_lvalue: expr -> block -> int -> Prop :=
| esl_loc: forall b ofs ty,
eval_simple_lvalue (Eloc b ofs ty) b ofs
| esl_var_local: forall x ty b,
e!x = Some(b, ty) ->
eval_simple_lvalue (Evar x ty) b Int.zero
| esl_var_global: forall x ty b,
e!x = None ->
Genv.find_symbol ge x = Some b ->
eval_simple_lvalue (Evar x ty) b Int.zero
| esl_deref: forall r ty b ofs,
eval_simple_rvalue r (Vptr b ofs) ->
eval_simple_lvalue (Ederef r ty) b ofs
| esl_field_struct: forall r f ty b ofs id fList a delta,
eval_simple_rvalue r (Vptr b ofs) ->
typeof r = Tstruct id fList a -> field_offset f fList = OK delta ->
eval_simple_lvalue (Efield r f ty) b (Int.add ofs (Int.repr delta))
| esl_field_union: forall r f ty b ofs id fList a,
eval_simple_rvalue r (Vptr b ofs) ->
typeof r = Tunion id fList a ->
eval_simple_lvalue (Efield r f ty) b ofs
with eval_simple_rvalue: expr -> val -> Prop :=
| esr_val: forall v ty,
eval_simple_rvalue (Eval v ty) v
| esr_rvalof: forall b ofs l ty v,
eval_simple_lvalue l b ofs ->
ty = typeof l ->
deref_loc ge ty m b ofs E0 v ->
eval_simple_rvalue (Evalof l ty) v
| esr_addrof: forall b ofs l ty,
eval_simple_lvalue l b ofs ->
eval_simple_rvalue (Eaddrof l ty) (Vptr b ofs)
| esr_unop: forall op r1 ty v1 v,
eval_simple_rvalue r1 v1 ->
sem_unary_operation op v1 (typeof r1) = Some v ->
eval_simple_rvalue (Eunop op r1 ty) v
| esr_binop: forall op r1 r2 ty v1 v2 v,
eval_simple_rvalue r1 v1 -> eval_simple_rvalue r2 v2 ->
sem_binary_operation op v1 (typeof r1) v2 (typeof r2) m = Some v ->
eval_simple_rvalue (Ebinop op r1 r2 ty) v
| esr_cast: forall ty r1 v1 v,
eval_simple_rvalue r1 v1 ->
sem_cast v1 (typeof r1) ty = Some v ->
eval_simple_rvalue (Ecast r1 ty) v
| esr_sizeof: forall ty1 ty,
eval_simple_rvalue (Esizeof ty1 ty) (Vint (Int.repr (sizeof ty1)))
| esr_alignof: forall ty1 ty,
eval_simple_rvalue (Ealignof ty1 ty) (Vint (Int.repr (alignof ty1)))
| esr_seqand_true: forall r1 r2 ty v1 v2 v3,
eval_simple_rvalue r1 v1 -> bool_val v1 (typeof r1) = Some true ->
eval_simple_rvalue r2 v2 ->
sem_cast v2 (typeof r2) type_bool = Some v3 ->
eval_simple_rvalue (Eseqand r1 r2 ty) v3
| esr_seqand_false: forall r1 r2 ty v1,
eval_simple_rvalue r1 v1 -> bool_val v1 (typeof r1) = Some false ->
eval_simple_rvalue (Eseqand r1 r2 ty) (Vint Int.zero)
| esr_seqor_false: forall r1 r2 ty v1 v2 v3,
eval_simple_rvalue r1 v1 -> bool_val v1 (typeof r1) = Some false ->
eval_simple_rvalue r2 v2 ->
sem_cast v2 (typeof r2) type_bool = Some v3 ->
eval_simple_rvalue (Eseqor r1 r2 ty) v3
| esr_seqor_true: forall r1 r2 ty v1,
eval_simple_rvalue r1 v1 -> bool_val v1 (typeof r1) = Some true ->
eval_simple_rvalue (Eseqor r1 r2 ty) (Vint Int.one)
| esr_condition: forall r1 r2 r3 ty v v1 b v',
eval_simple_rvalue r1 v1 -> bool_val v1 (typeof r1) = Some b ->
eval_simple_rvalue (if b then r2 else r3) v' ->
sem_cast v' (typeof (if b then r2 else r3)) ty = Some v ->
eval_simple_rvalue (Econdition r1 r2 r3 ty) v
| esr_comma: forall r1 r2 ty v1 v,
eval_simple_rvalue r1 v1 -> eval_simple_rvalue r2 v ->
eval_simple_rvalue (Ecomma r1 r2 ty) v
| esr_paren: forall r tycast ty v v',
eval_simple_rvalue r v -> sem_cast v (typeof r) tycast = Some v' ->
eval_simple_rvalue (Eparen r tycast ty) v'.
End SIMPLE_EXPRS.
(** * Correctness of the big-step semantics with respect to reduction sequences *)
(** In this section, we show that if a simple expression [a] reduces to
some value (with the transition semantics from module [Csem]),
then it evaluates to this value (with the big-step semantics above). *)
Definition compat_eval (k: kind) (e: env) (a a': expr) (m: mem) : Prop :=
typeof a = typeof a' /\
match k with
| LV => forall b ofs, eval_simple_lvalue e m a' b ofs -> eval_simple_lvalue e m a b ofs
| RV => forall v, eval_simple_rvalue e m a' v -> eval_simple_rvalue e m a v
end.
Lemma lred_simple:
forall e l m l' m', lred ge e l m l' m' -> simple l -> simple l'.
Proof.
induction 1; simpl; tauto.
Qed.
Lemma lred_compat:
forall e l m l' m', lred ge e l m l' m' ->
m = m' /\ compat_eval LV e l l' m.
Proof.
induction 1; simpl; split; auto; split; auto; intros bx ofsx EV; inv EV.
apply esl_var_local; auto.
apply esl_var_global; auto.
constructor. constructor.
eapply esl_field_struct; eauto. constructor. simpl; eauto.
eapply esl_field_union; eauto. constructor. simpl; eauto.
Qed.
Lemma rred_simple:
forall r m t r' m', rred ge r m t r' m' -> simple r -> simple r'.
Proof.
induction 1; simpl; intuition. destruct b; auto.
Qed.
Lemma rred_compat:
forall e r m r' m', rred ge r m E0 r' m' ->
simple r ->
m = m' /\ compat_eval RV e r r' m.
Proof.
intros until m'; intros RED SIMP. inv RED; simpl in SIMP; try contradiction; split; auto; split; auto; intros vx EV.
inv EV. econstructor. constructor. auto. auto.
inv EV. econstructor. constructor.
inv EV. econstructor; eauto. constructor.
inv EV. econstructor; eauto. constructor. constructor.
inv EV. econstructor; eauto. constructor.
inv EV. eapply esr_seqand_true; eauto. constructor.
inv EV. eapply esr_seqand_false; eauto. constructor.
inv EV. eapply esr_seqor_true; eauto. constructor.
inv EV. eapply esr_seqor_false; eauto. constructor.
inv EV. eapply esr_condition; eauto. constructor.
inv EV. constructor.
inv EV. constructor.
econstructor; eauto. constructor.
inv EV. econstructor. constructor. auto.
Qed.
Lemma compat_eval_context:
forall e a a' m from to C,
context from to C ->
compat_eval from e a a' m ->
compat_eval to e (C a) (C a') m.
Proof.
induction 1; intros CE; auto;
try (generalize (IHcontext CE); intros [TY EV]; red; split; simpl; auto; intros).
inv H0. constructor; auto.
inv H0.
eapply esl_field_struct; eauto. rewrite TY; eauto.
eapply esl_field_union; eauto. rewrite TY; eauto.
inv H0. econstructor. eauto. auto. auto.
inv H0. econstructor; eauto.
inv H0. econstructor; eauto. congruence.
inv H0. econstructor; eauto. congruence.
inv H0. econstructor; eauto. congruence.
inv H0. econstructor; eauto. congruence.
inv H0.
eapply esr_seqand_true; eauto. rewrite TY; auto.
eapply esr_seqand_false; eauto. rewrite TY; auto.
inv H0.
eapply esr_seqor_false; eauto. rewrite TY; auto.
eapply esr_seqor_true; eauto. rewrite TY; auto.
inv H0. eapply esr_condition; eauto. congruence.
inv H0.
inv H0.
inv H0.
inv H0.
inv H0.
inv H0.
red; split; intros. auto. inv H0.
red; split; intros. auto. inv H0.
inv H0. econstructor; eauto.
inv H0. econstructor; eauto. congruence.
Qed.
Lemma simple_context_1:
forall a from to C, context from to C -> simple (C a) -> simple a.
Proof.
induction 1; simpl; tauto.
Qed.
Lemma simple_context_2:
forall a a', simple a' -> forall from to C, context from to C -> simple (C a) -> simple (C a').
Proof.
induction 2; simpl; try tauto.
Qed.
Lemma compat_eval_steps_aux f r e m r' m' s2 :
simple r ->
star (step ge) s2 nil (ExprState f r' Kstop e, m') ->
estep ge (ExprState f r Kstop e, m) nil s2 ->
exists r1,
s2 = (ExprState f r1 Kstop e, m) /\
compat_eval RV e r r1 m /\ simple r1.
Proof.
intros.
inv H1.
(* lred *)
assert (S: simple a) by (eapply simple_context_1; eauto).
exploit lred_compat; eauto. intros [A B]. subst m'0.
econstructor; split. eauto. split.
eapply compat_eval_context; eauto.
eapply simple_context_2; eauto. eapply lred_simple; eauto.
(* rred *)
assert (S: simple a) by (eapply simple_context_1; eauto).
exploit rred_compat; eauto. intros [A B]. subst m'0.
econstructor; split. eauto. split.
eapply compat_eval_context; eauto.
eapply simple_context_2; eauto. eapply rred_simple; eauto.
(* callred *)
assert (S: simple a) by (eapply simple_context_1; eauto).
inv H8; simpl in S; contradiction.
(* stuckred *)
inv H0. destruct H1; inv H0.
Qed.
Lemma compat_eval_steps:
forall f r e m r' m',
star (step ge) (ExprState f r Kstop e, m) E0 (ExprState f r' Kstop e, m') ->
simple r ->
m' = m /\ compat_eval RV e r r' m.
Proof.
intros.
remember (ExprState f r Kstop e, m) as S1.
remember E0 as t.
remember (ExprState f r' Kstop e, m') as S2.
revert S1 t S2 H r m r' m' HeqS1 Heqt HeqS2 H0.
induction 1; intros; subst.
(* base case *)
inv HeqS2. split. auto. red; auto.
(* inductive case *)
destruct (app_eq_nil t1 t2); auto. subst. inv H.
(* expression step *)
exploit compat_eval_steps_aux; eauto.
intros [r1 [A [B C]]]. subst s2.
exploit IHstar; eauto. intros [D E].
split. auto. destruct B; destruct E. split. congruence. auto.
(* statement steps *)
inv H1.
Qed.
Theorem eval_simple_steps:
forall f r e m v ty m',
star (step ge) (ExprState f r Kstop e, m) E0 (ExprState f (Eval v ty) Kstop e, m') ->
simple r ->
m' = m /\ ty = typeof r /\ eval_simple_rvalue e m r v.
Proof.
intros. exploit compat_eval_steps; eauto. intros [A [B C]].
intuition. apply C. constructor.
Qed.
(** * Soundness of the compile-time evaluator *)
(** A global environment [ge] induces a memory injection mapping
our symbolic pointers [Vptr id ofs] to run-time pointers
[Vptr b ofs] where [Genv.find_symbol ge id = Some b]. *)
Definition inj (b: block) :=
match Genv.find_symbol ge b with
| Some b' => Some (b', 0)
| None => None
end.
Lemma mem_empty_not_valid_pointer:
forall b ofs, Mem.valid_pointer Mem.empty b ofs = false.
Proof.
intros. unfold Mem.valid_pointer. destruct (Mem.perm_dec Mem.empty b ofs Cur Nonempty); auto.
eelim Mem.perm_empty; eauto.
Qed.
Lemma mem_empty_not_weak_valid_pointer:
forall b ofs, Mem.weak_valid_pointer Mem.empty b ofs = false.
Proof.
intros. unfold Mem.weak_valid_pointer.
now rewrite !mem_empty_not_valid_pointer.
Qed.
Lemma sem_cast_match:
forall v1 ty1 ty2 v2 v1' v2',
sem_cast v1 ty1 ty2 = Some v2 ->
do_cast v1' ty1 ty2 = OK v2' ->
val_inject inj v1' v1 ->
val_inject inj v2' v2.
Proof.
intros. unfold do_cast in H0. destruct (sem_cast v1' ty1 ty2) as [v2''|] eqn:E; inv H0.
exploit sem_cast_inject. eexact E. eauto.
intros [v' [A B]]. congruence.
Qed.
(** Soundness of [constval] with respect to the big-step semantics *)
Lemma constval_rvalue:
forall m a v,
eval_simple_rvalue empty_env m a v ->
forall v',
constval a = OK v' ->
val_inject inj v' v
with constval_lvalue:
forall m a b ofs,
eval_simple_lvalue empty_env m a b ofs ->
forall v',
constval a = OK v' ->
val_inject inj v' (Vptr b ofs).
Proof.
(* rvalue *)
induction 1; intros vres CV; simpl in CV; try (monadInv CV).
(* val *)
destruct v; monadInv CV; constructor.
(* rval *)
inv H1; rewrite H2 in CV; try congruence. eauto. eauto.
(* addrof *)
eauto.
(* unop *)
destruct (sem_unary_operation op x (typeof r1)) as [v1'|] eqn:E; inv EQ0.
exploit sem_unary_operation_inject. eexact E. eauto.
intros [v' [A B]]. congruence.
(* binop *)
destruct (sem_binary_operation op x (typeof r1) x0 (typeof r2) Mem.empty) as [v1'|] eqn:E; inv EQ2.
exploit (sem_binary_operation_inj inj Mem.empty m).
intros. rewrite mem_empty_not_valid_pointer in H3; discriminate.
intros. rewrite mem_empty_not_weak_valid_pointer in H3; discriminate.
intros. rewrite mem_empty_not_weak_valid_pointer in H3; discriminate.
intros. rewrite mem_empty_not_valid_pointer in H3; discriminate.
eauto. eauto. eauto.
intros [v' [A B]]. congruence.
(* cast *)
eapply sem_cast_match; eauto.
(* sizeof *)
constructor.
(* alignof *)
constructor.
(* seqand *)
destruct (bool_val x (typeof r1)) as [b|] eqn:E; inv EQ2.
exploit bool_val_inject. eexact E. eauto. intros E'.
assert (b = true) by congruence. subst b.
eapply sem_cast_match; eauto.
destruct (bool_val x (typeof r1)) as [b|] eqn:E; inv EQ2.
exploit bool_val_inject. eexact E. eauto. intros E'.
assert (b = false) by congruence. subst b. inv H2. auto.
(* seqor *)
destruct (bool_val x (typeof r1)) as [b|] eqn:E; inv EQ2.
exploit bool_val_inject. eexact E. eauto. intros E'.
assert (b = false) by congruence. subst b.
eapply sem_cast_match; eauto.
destruct (bool_val x (typeof r1)) as [b|] eqn:E; inv EQ2.
exploit bool_val_inject. eexact E. eauto. intros E'.
assert (b = true) by congruence. subst b. inv H2. auto.
(* conditional *)
destruct (bool_val x (typeof r1)) as [b'|] eqn:E; inv EQ3.
exploit bool_val_inject. eexact E. eauto. intros E'.
assert (b' = b) by congruence. subst b'.
destruct b; eapply sem_cast_match; eauto.
(* comma *)
auto.
(* paren *)
eapply sem_cast_match; eauto.
(* lvalue *)
induction 1; intros v' CV; simpl in CV; try (monadInv CV).
(* var local *)
unfold empty_env in H. rewrite PTree.gempty in H. congruence.
(* var_global *)
econstructor. unfold inj. rewrite H0. eauto. auto.
(* deref *)
eauto.
(* field struct *)
rewrite H0 in CV. monadInv CV. exploit constval_rvalue; eauto. intro MV. inv MV.
simpl. replace x with delta by congruence. econstructor; eauto.
rewrite ! Int.add_assoc. f_equal. apply Int.add_commut.
simpl. auto.
(* field union *)
rewrite H0 in CV. eauto.
Qed.
Lemma constval_simple:
forall a v, constval a = OK v -> simple a.
Proof.
induction a; simpl; intros vx CV; try (monadInv CV); eauto.
destruct (typeof a); discriminate || eauto.
monadInv CV. eauto.
destruct (access_mode ty); discriminate || eauto.
intuition eauto.
Qed.
(** Soundness of [constval] with respect to the reduction semantics. *)
Theorem constval_steps:
forall f r m v v' ty m',
star (step ge) (ExprState f r Kstop empty_env, m) E0 (ExprState f (Eval v' ty) Kstop empty_env, m') ->
constval r = OK v ->
m' = m /\ ty = typeof r /\ val_inject inj v v'.
Proof.
intros. exploit eval_simple_steps; eauto. eapply constval_simple; eauto.
intros [A [B C]]. intuition. eapply constval_rvalue; eauto.
Qed.
(** * Soundness of the translation of initializers *)
(** Soundness for single initializers. *)
Theorem transl_init_single_steps:
forall ty a data f m v1 ty1 m' v chunk b ofs m'',
transl_init_single ty a = OK data ->
star (step ge) (ExprState f a Kstop empty_env, m) E0 (ExprState f (Eval v1 ty1) Kstop empty_env, m') ->
sem_cast v1 ty1 ty = Some v ->
access_mode ty = By_value chunk ->
Mem.store chunk m' b ofs v = Some m'' ->
Genv.store_init_data ge m b ofs data = Some m''.
Proof.
intros. monadInv H.
exploit constval_steps; eauto. intros [A [B C]]. subst m' ty1.
exploit sem_cast_match; eauto. intros D.
unfold Genv.store_init_data.
inv D.
(* int *)
destruct ty; try discriminate.
destruct i0; inv EQ2.
destruct s; simpl in H2; inv H2. rewrite <- Mem.store_signed_unsigned_8; auto. auto.
destruct s; simpl in H2; inv H2. rewrite <- Mem.store_signed_unsigned_16; auto. auto.
simpl in H2; inv H2. assumption.
simpl in H2; inv H2. assumption.
inv EQ2. simpl in H2; inv H2. assumption.
(* long *)
destruct ty; inv EQ2. simpl in H2; inv H2. assumption.
(* float *)
destruct ty; try discriminate.
destruct f1; inv EQ2; simpl in H2; inv H2; assumption.
(* single *)
destruct ty; try discriminate.
destruct f1; inv EQ2; simpl in H2; inv H2; assumption.
(* pointer *)
unfold inj in H.
assert (data = Init_addrof b1 ofs1 /\ chunk = Mint32).
destruct ty; inv EQ2; inv H2.
destruct i; inv H5. intuition congruence. auto.
destruct H4; subst. destruct (Genv.find_symbol ge b1); inv H.
rewrite Int.add_zero in H3. auto.
(* undef *)
discriminate.
Qed.
(** Size properties for initializers. *)
Lemma transl_init_single_size:
forall ty a data,
transl_init_single ty a = OK data ->
Genv.init_data_size data = sizeof ty.
Proof.
intros. monadInv H. destruct x0.
- monadInv EQ2.
- destruct ty; try discriminate.
destruct i0; inv EQ2; auto.
inv EQ2; auto.
inv EQ2; auto.
- destruct ty; inv EQ2; auto.
- destruct ty; try discriminate.
destruct f0; inv EQ2; auto.
- destruct ty; try discriminate.
destruct f0; inv EQ2; auto.
- destruct ty; try discriminate.
destruct i0; inv EQ2; auto.
inv EQ2; auto.
inv EQ2; auto.
Qed.
Notation idlsize := Genv.init_data_list_size.
Remark padding_size:
forall frm to, frm <= to -> idlsize (padding frm to) = to - frm.
Proof.
unfold padding; intros. destruct (zlt frm to).
simpl. xomega.
simpl. omega.
Qed.
Remark idlsize_app:
forall d1 d2, idlsize (d1 ++ d2) = idlsize d1 + idlsize d2.
Proof.
induction d1; simpl; intros.
auto.
rewrite IHd1. omega.
Qed.
Remark union_field_size:
forall f ty fl, field_type f fl = OK ty -> sizeof ty <= sizeof_union fl.
Proof.
induction fl; simpl; intros.
- inv H.
- destruct (ident_eq f i).
+ inv H. xomega.
+ specialize (IHfl H). xomega.
Qed.
Lemma transl_init_size:
forall i ty data,
transl_init ty i = OK data ->
idlsize data = sizeof ty
with transl_init_list_size:
forall il,
(forall ty sz data,
transl_init_array ty il sz = OK data ->
idlsize data = sizeof ty * sz)
/\
(forall id ty fl pos data,
transl_init_struct id ty fl il pos = OK data ->
sizeof_struct fl pos <= sizeof ty ->
idlsize data + pos = sizeof ty).
Proof.
- induction i; intros.
+ (* single *)
monadInv H. simpl. erewrite transl_init_single_size by eauto. omega.
+ (* array *)
simpl in H. destruct ty; try discriminate.
simpl. eapply (proj1 (transl_init_list_size il)); eauto.
+ (* struct *)
simpl in H. destruct ty; try discriminate.
replace (idlsize data) with (idlsize data + 0) by omega.
eapply (proj2 (transl_init_list_size il)). eauto.
Local Opaque alignof.
simpl. apply align_le. apply alignof_pos.
+ (* union *)
simpl in H. destruct ty; try discriminate.
set (sz := sizeof (Tunion i0 f0 a)) in *.
monadInv H. rewrite idlsize_app. rewrite (IHi _ _ EQ1).
rewrite padding_size. omega. unfold sz. simpl.
apply Zle_trans with (sizeof_union f0). eapply union_field_size; eauto.
apply align_le. apply alignof_pos.
- induction il.
+ (* base cases *)
simpl. intuition.
* (* arrays *)
destruct (zeq sz 0). inv H. simpl; ring.
destruct (zle 0 sz); inv H. simpl.
rewrite Z.mul_comm.
assert (0 <= sizeof ty * sz).
{ apply Zmult_gt_0_le_0_compat. omega. generalize (sizeof_pos ty); omega. }
zify; omega.
* (* structs *)
destruct fl; inv H.
simpl in H0. rewrite padding_size by omega. omega.
+ (* inductive cases *)
destruct IHil as [A B]. split.
* (* arrays *)
intros. monadInv H.
rewrite idlsize_app.
rewrite (transl_init_size _ _ _ EQ).
rewrite (A _ _ _ EQ1).
ring.
* (* structs *)
intros. simpl in H. destruct fl; monadInv H.
rewrite ! idlsize_app.
simpl in H0.
rewrite padding_size.
rewrite (transl_init_size _ _ _ EQ).
rewrite <- (B _ _ _ _ _ EQ1). omega.
auto. apply align_le. apply alignof_pos.
Qed.
(** A semantics for general initializers *)
Definition dummy_function := mkfunction Tvoid cc_default nil nil Sskip.
Fixpoint fields_of_struct (id: ident) (ty: type) (fl: fieldlist) (pos: Z) : list (Z * type) :=
match fl with
| Fnil => nil
| Fcons id1 ty1 fl' =>
(align pos (alignof ty1), ty1) :: fields_of_struct id ty fl' (align pos (alignof ty1) + sizeof ty1)
end.
Inductive exec_init: mem -> block -> Z -> type -> initializer -> mem -> Prop :=
| exec_init_single: forall m b ofs ty a v1 ty1 chunk m' v m'',
star (step ge) (ExprState dummy_function a Kstop empty_env, m)
E0 (ExprState dummy_function (Eval v1 ty1) Kstop empty_env, m') ->
sem_cast v1 ty1 ty = Some v ->
access_mode ty = By_value chunk ->
Mem.store chunk m' b ofs v = Some m'' ->
exec_init m b ofs ty (Init_single a) m''
| exec_init_array_: forall m b ofs ty sz a il m',
exec_init_array m b ofs ty sz il m' ->
exec_init m b ofs (Tarray ty sz a) (Init_array il) m'
| exec_init_struct: forall m b ofs id fl a il m',
exec_init_list m b ofs (fields_of_struct id (Tstruct id fl a) fl 0) il m' ->
exec_init m b ofs (Tstruct id fl a) (Init_struct il) m'
| exec_init_union: forall m b ofs id fl a f i ty m',
field_type f fl = OK ty ->
exec_init m b ofs ty i m' ->
exec_init m b ofs (Tunion id fl a) (Init_union f i) m'
with exec_init_array: mem -> block -> Z -> type -> Z -> initializer_list -> mem -> Prop :=
| exec_init_array_nil: forall m b ofs ty sz,
sz >= 0 ->
exec_init_array m b ofs ty sz Init_nil m
| exec_init_array_cons: forall m b ofs ty sz i1 il m' m'',
exec_init m b ofs ty i1 m' ->
exec_init_array m' b (ofs + sizeof ty) ty (sz - 1) il m'' ->
exec_init_array m b ofs ty sz (Init_cons i1 il) m''
with exec_init_list: mem -> block -> Z -> list (Z * type) -> initializer_list -> mem -> Prop :=
| exec_init_list_nil: forall m b ofs,
exec_init_list m b ofs nil Init_nil m
| exec_init_list_cons: forall m b ofs pos ty l i1 il m' m'',
exec_init m b (ofs + pos) ty i1 m' ->
exec_init_list m' b ofs l il m'' ->
exec_init_list m b ofs ((pos, ty) :: l) (Init_cons i1 il) m''.
Scheme exec_init_ind3 := Minimality for exec_init Sort Prop
with exec_init_array_ind3 := Minimality for exec_init_array Sort Prop
with exec_init_list_ind3 := Minimality for exec_init_list Sort Prop.
Combined Scheme exec_init_scheme from exec_init_ind3, exec_init_array_ind3, exec_init_list_ind3.
Remark exec_init_array_length:
forall m b ofs ty sz il m',
exec_init_array m b ofs ty sz il m' -> sz >= 0.
Proof.
induction 1; omega.
Qed.
Lemma store_init_data_list_app:
forall data1 m b ofs m' data2 m'',
Genv.store_init_data_list ge m b ofs data1 = Some m' ->
Genv.store_init_data_list ge m' b (ofs + idlsize data1) data2 = Some m'' ->
Genv.store_init_data_list ge m b ofs (data1 ++ data2) = Some m''.
Proof.
induction data1; simpl; intros.
inv H. rewrite Zplus_0_r in H0. auto.
destruct (Genv.store_init_data ge m b ofs a); try discriminate.
rewrite Zplus_assoc in H0. eauto.
Qed.
Remark store_init_data_list_padding:
forall frm to b ofs m,
Genv.store_init_data_list ge m b ofs (padding frm to) = Some m.
Proof.
intros. unfold padding. destruct (zlt frm to); auto.
Qed.
Lemma transl_init_sound_gen:
(forall m b ofs ty i m', exec_init m b ofs ty i m' ->
forall data, transl_init ty i = OK data ->
Genv.store_init_data_list ge m b ofs data = Some m')
/\(forall m b ofs ty sz il m', exec_init_array m b ofs ty sz il m' ->
forall data, transl_init_array ty il sz = OK data ->
Genv.store_init_data_list ge m b ofs data = Some m')
/\(forall m b ofs l il m', exec_init_list m b ofs l il m' ->
forall id ty fl data pos,
l = fields_of_struct id ty fl pos ->
transl_init_struct id ty fl il pos = OK data ->
Genv.store_init_data_list ge m b (ofs + pos) data = Some m').
Proof.
Local Opaque sizeof.
apply exec_init_scheme; simpl; intros.
- (* single *)
monadInv H3. simpl. erewrite transl_init_single_steps by eauto. auto.
- (* array *)
replace (Z.max 0 sz) with sz in H1. eauto.
assert (sz >= 0) by (eapply exec_init_array_length; eauto). xomega.
- (* struct *)
replace ofs with (ofs + 0) by omega. eauto.
- (* union *)
rewrite H in H2. monadInv H2. inv EQ.
eapply store_init_data_list_app. eauto.
apply store_init_data_list_padding.
- (* array, empty *)
destruct (zeq sz 0).
inv H0. auto.
rewrite zle_true in H0 by omega. inv H0. auto.
- (* array, nonempty *)
monadInv H3.
eapply store_init_data_list_app.
eauto.
rewrite (transl_init_size _ _ _ EQ). eauto.
- (* struct, empty *)
destruct fl; simpl in H; inv H.
inv H0. apply store_init_data_list_padding.
- (* struct, nonempty *)
destruct fl; simpl in H3; inv H3.
monadInv H4.
eapply store_init_data_list_app. apply store_init_data_list_padding.
rewrite padding_size.
replace (ofs + pos0 + (align pos0 (alignof t) - pos0))
with (ofs + align pos0 (alignof t)) by omega.
eapply store_init_data_list_app.
eauto.
rewrite (transl_init_size _ _ _ EQ).
rewrite <- Zplus_assoc. eapply H2. eauto. eauto.
apply align_le. apply alignof_pos.
Qed.
Theorem transl_init_sound:
forall m b ty i m' data,
exec_init m b 0 ty i m' ->
transl_init ty i = OK data ->
Genv.store_init_data_list ge m b 0 data = Some m'.
Proof.
intros. eapply (proj1 transl_init_sound_gen); eauto.
Qed.
End SOUNDNESS.
|
(*
* Copyright 2014, General Dynamics C4 Systems
*
* SPDX-License-Identifier: GPL-2.0-only
*)
theory ArchDetSchedAux_AI
imports DetSchedAux_AI
begin
context Arch begin global_naming X64
named_theorems DetSchedAux_AI_assms
crunch exst[wp]: set_object, init_arch_objects "\<lambda>s. P (exst s)" (wp: crunch_wps unless_wp)
crunch ct[wp]: init_arch_objects "\<lambda>s. P (cur_thread s)" (wp: crunch_wps unless_wp)
crunch valid_etcbs[wp, DetSchedAux_AI_assms]: init_arch_objects valid_etcbs (wp: valid_etcbs_lift)
crunch ct[wp, DetSchedAux_AI_assms]: invoke_untyped "\<lambda>s. P (cur_thread s)"
(wp: crunch_wps dxo_wp_weak preemption_point_inv mapME_x_inv_wp
simp: crunch_simps do_machine_op_def detype_def mapM_x_defsym unless_def
ignore: freeMemory ignore: retype_region_ext)
crunch ready_queues[wp, DetSchedAux_AI_assms]: invoke_untyped "\<lambda>s. P (ready_queues s)"
(wp: crunch_wps mapME_x_inv_wp preemption_point_inv'
simp: detype_def detype_ext_def crunch_simps
wrap_ext_det_ext_ext_def mapM_x_defsym
ignore: freeMemory)
crunch scheduler_action[wp, DetSchedAux_AI_assms]: invoke_untyped "\<lambda>s. P (scheduler_action s)"
(wp: crunch_wps mapME_x_inv_wp preemption_point_inv'
simp: detype_def detype_ext_def crunch_simps
wrap_ext_det_ext_ext_def mapM_x_defsym
ignore: freeMemory)
crunch cur_domain[wp, DetSchedAux_AI_assms]: invoke_untyped "\<lambda>s. P (cur_domain s)"
(wp: crunch_wps mapME_x_inv_wp preemption_point_inv'
simp: detype_def detype_ext_def crunch_simps
wrap_ext_det_ext_ext_def mapM_x_defsym
ignore: freeMemory)
crunch idle_thread[wp, DetSchedAux_AI_assms]: invoke_untyped "\<lambda>s. P (idle_thread s)"
(wp: crunch_wps mapME_x_inv_wp preemption_point_inv dxo_wp_weak
simp: detype_def detype_ext_def crunch_simps
wrap_ext_det_ext_ext_def mapM_x_defsym
ignore: freeMemory retype_region_ext)
lemma tcb_sched_action_valid_idle_etcb:
"\<lbrace>valid_idle_etcb\<rbrace>
tcb_sched_action foo thread
\<lbrace>\<lambda>_. valid_idle_etcb\<rbrace>"
apply (rule valid_idle_etcb_lift)
apply (simp add: tcb_sched_action_def set_tcb_queue_def)
apply (wp | simp)+
done
crunch ekheap[wp]: do_machine_op "\<lambda>s. P (ekheap s)"
lemma delete_objects_etcb_at[wp, DetSchedAux_AI_assms]:
"\<lbrace>\<lambda>s::det_ext state. etcb_at P t s\<rbrace> delete_objects a b \<lbrace>\<lambda>r s. etcb_at P t s\<rbrace>"
apply (simp add: delete_objects_def)
apply (simp add: detype_def detype_ext_def wrap_ext_det_ext_ext_def etcb_at_def|wp)+
done
crunch etcb_at[wp]: reset_untyped_cap "etcb_at P t"
(wp: preemption_point_inv' mapME_x_inv_wp crunch_wps
simp: unless_def)
crunch valid_etcbs[wp]: reset_untyped_cap "valid_etcbs"
(wp: preemption_point_inv' mapME_x_inv_wp crunch_wps
simp: unless_def)
lemma invoke_untyped_etcb_at [DetSchedAux_AI_assms]:
"\<lbrace>(\<lambda>s :: det_ext state. etcb_at P t s) and valid_etcbs\<rbrace> invoke_untyped ui \<lbrace>\<lambda>r s. st_tcb_at (Not o inactive) t s \<longrightarrow> etcb_at P t s\<rbrace>"
apply (cases ui)
apply (simp add: mapM_x_def[symmetric] invoke_untyped_def whenE_def
split del: if_split)
apply (wp retype_region_etcb_at mapM_x_wp'
create_cap_no_pred_tcb_at typ_at_pred_tcb_at_lift
hoare_convert_imp[OF create_cap_no_pred_tcb_at]
hoare_convert_imp[OF _ init_arch_objects_exst]
| simp
| (wp (once) hoare_drop_impE_E))+
done
crunch valid_blocked[wp, DetSchedAux_AI_assms]: init_arch_objects valid_blocked
(wp: valid_blocked_lift set_cap_typ_at)
lemma perform_asid_control_etcb_at:"\<lbrace>(\<lambda>s. etcb_at P t s) and valid_etcbs\<rbrace>
perform_asid_control_invocation aci
\<lbrace>\<lambda>r s. st_tcb_at (Not \<circ> inactive) t s \<longrightarrow> etcb_at P t s\<rbrace>"
apply (simp add: perform_asid_control_invocation_def)
apply (rule hoare_pre)
apply (wp | wpc | simp)+
apply (wp hoare_imp_lift_something typ_at_pred_tcb_at_lift)[1]
apply (rule hoare_drop_imps)
apply (wp retype_region_etcb_at)+
apply simp
done
crunch ct[wp]: perform_asid_control_invocation "\<lambda>s. P (cur_thread s)"
crunch idle_thread[wp]: perform_asid_control_invocation "\<lambda>s. P (idle_thread s)"
crunch valid_etcbs[wp]: perform_asid_control_invocation valid_etcbs (wp: static_imp_wp)
crunch valid_blocked[wp]: perform_asid_control_invocation valid_blocked (wp: static_imp_wp)
crunch schedact[wp]: perform_asid_control_invocation "\<lambda>s :: det_ext state. P (scheduler_action s)" (wp: crunch_wps simp: detype_def detype_ext_def wrap_ext_det_ext_ext_def cap_insert_ext_def ignore: freeMemory)
crunch rqueues[wp]: perform_asid_control_invocation "\<lambda>s :: det_ext state. P (ready_queues s)" (wp: crunch_wps simp: detype_def detype_ext_def wrap_ext_det_ext_ext_def cap_insert_ext_def ignore: freeMemory)
crunch cur_domain[wp]: perform_asid_control_invocation "\<lambda>s :: det_ext state. P (cur_domain s)" (wp: crunch_wps simp: detype_def detype_ext_def wrap_ext_det_ext_ext_def cap_insert_ext_def ignore: freeMemory)
lemma perform_asid_control_invocation_valid_sched:
"\<lbrace>ct_active and invs and valid_aci aci and valid_sched and valid_idle\<rbrace>
perform_asid_control_invocation aci
\<lbrace>\<lambda>_. valid_sched\<rbrace>"
apply (rule hoare_pre)
apply (rule_tac I="invs and ct_active and valid_aci aci" in valid_sched_tcb_state_preservation)
apply (wp perform_asid_control_invocation_st_tcb_at)
apply simp
apply (wp perform_asid_control_etcb_at)+
apply (rule hoare_strengthen_post, rule aci_invs)
apply (simp add: invs_def valid_state_def)
apply (rule hoare_lift_Pf[where f="\<lambda>s. scheduler_action s"])
apply (rule hoare_lift_Pf[where f="\<lambda>s. cur_domain s"])
apply (rule hoare_lift_Pf[where f="\<lambda>s. idle_thread s"])
apply wp+
apply simp
done
crunch valid_queues[wp]: init_arch_objects valid_queues (wp: valid_queues_lift)
crunch valid_sched_action[wp]: init_arch_objects valid_sched_action (wp: valid_sched_action_lift)
crunch valid_sched[wp]: init_arch_objects valid_sched (wp: valid_sched_lift)
end
lemmas tcb_sched_action_valid_idle_etcb
= X64.tcb_sched_action_valid_idle_etcb
global_interpretation DetSchedAux_AI_det_ext?: DetSchedAux_AI_det_ext
proof goal_cases
interpret Arch .
case 1 show ?case by (unfold_locales; (fact DetSchedAux_AI_assms)?)
qed
global_interpretation DetSchedAux_AI?: DetSchedAux_AI
proof goal_cases
interpret Arch .
case 1 show ?case by (unfold_locales; (fact DetSchedAux_AI_assms)?)
qed
end
|
Seoladh Comórtas Bonn Óir Seán Ó Riada sa bhliain 2009 agus ó shin i leith tá sé ag dul ó neart go neart. Tá an comórtas oscailte d’aon duine ó aon áit ar domhan. Reachtáiltear é via an suíomh idirlínne Cuireadh Chun Ceoil agus trí RnaG. Is don ceoltóir is fearr ar uirlis áirithe an comortas. Is féidir leis an iomathóir clárú ar an suiomh idirlinne. Ansan ní mór don iomathóir 5 fuaimrian a sheinnt gan tionlacan is iad a lódáil ar an suíomh. Tá sé seo go léir saor in aisce. Craoltar píosaí ceoil gach seachtain ar Raidió na Gaeltachta, agus bíonn ceolchoirm bheo ina mbíonn na 15 iomaitheoir deireanach páirteach ar siúl, beo ar aer, ó óstán i gCorcaigh ar thús na bliana. Bronntar Bonn Óir agus Sparán a bhfuil luach €2500 orthu ar an mbuaiteóir. Níl ach uirlis i gceist in aghaidh na blaina: 2012 – An Fidil, 2011 – Feadóga, 2012 – Cláirseach nó Píob, 2013 – na uirlisí giolcaigh miotail (Boscaí ceoil, concairtín 7rl) 2014 tharnasi chun an Fidil agus mar sin de.
The Seán Riada Gold Medal competition was launched in 2009 and has been gathering strength every year since. The competition is open to anyone anywhere in the world. It is for the best Irish Traditional Musician on a particular instrument in a given year. It is organised via the internet site Cuireadh Chun Ceoil and music from the competitors is broadcast in season on RnaG and world wide vie the internet. The competitor may enter for free and must upload 5 files of themselves playing unaccompanied. The final 15 are chosen by adjudicators and they are brought, in January of the following year, to Cork city where they compete live on radio. The Gold Medal and a purse of €2,500 is awarded to the winner. One instrument is the chosen disepline every year and these are on a rota: 2010 – The fiddle, 2011 – The flutes and whistles, 2012 – The Harp and the Pipes, 2013 – The metal reed instruments (Accordian, concertina etc.) 2014 back to the fidil and so on. |
Formal statement is: lemma strict_mono_leD: "strict_mono r \<Longrightarrow> m \<le> n \<Longrightarrow> r m \<le> r n" Informal statement is: If $r$ is a strict monotone function and $m \leq n$, then $r(m) \leq r(n)$. |
-- Asociatividad_del_infimo.lean
-- Si R es un retículo y x, y, z ∈ R, entonces (x ⊓ y) ⊓ z = x ⊓ (y ⊓ z)
-- José A. Alonso Jiménez <https://jaalonso.github.io>
-- Sevilla, 18-octubre-2022
-- ---------------------------------------------------------------------
import order.lattice
variables {R : Type*} [lattice R]
variables x y z : R
-- 1ª demostración
-- ===============
example : (x ⊓ y) ⊓ z = x ⊓ (y ⊓ z) :=
begin
have h1 : (x ⊓ y) ⊓ z ≤ x ⊓ (y ⊓ z),
{ have h1a : (x ⊓ y) ⊓ z ≤ x, calc
(x ⊓ y) ⊓ z ≤ x ⊓ y : inf_le_left
... ≤ x : inf_le_left,
have h1b : (x ⊓ y) ⊓ z ≤ y ⊓ z,
{ have h1b1 : (x ⊓ y) ⊓ z ≤ y, calc
(x ⊓ y) ⊓ z ≤ x ⊓ y : inf_le_left
... ≤ y : inf_le_right,
have h1b2 : (x ⊓ y) ⊓ z ≤ z :=
inf_le_right,
show (x ⊓ y) ⊓ z ≤ y ⊓ z,
by exact le_inf h1b1 h1b2, },
show (x ⊓ y) ⊓ z ≤ x ⊓ (y ⊓ z),
by exact le_inf h1a h1b, },
have h2 : x ⊓ (y ⊓ z) ≤ (x ⊓ y) ⊓ z,
{ have h2a : x ⊓ (y ⊓ z) ≤ x ⊓ y,
{ have h2a1 : x ⊓ (y ⊓ z) ≤ x,
by exact inf_le_left,
have h2a2 : x ⊓ (y ⊓ z) ≤ y, calc
x ⊓ (y ⊓ z) ≤ y ⊓ z : inf_le_right
... ≤ y : inf_le_left,
show x ⊓ (y ⊓ z) ≤ x ⊓ y,
by exact le_inf h2a1 h2a2, },
have h2b : x ⊓ (y ⊓ z) ≤ z, calc
x ⊓ (y ⊓ z) ≤ y ⊓ z : inf_le_right
... ≤ z : inf_le_right,
show x ⊓ (y ⊓ z) ≤ (x ⊓ y) ⊓ z,
by exact le_inf h2a h2b, },
show (x ⊓ y) ⊓ z = x ⊓ (y ⊓ z),
by exact le_antisymm h1 h2,
end
-- 2ª demostración
-- ===============
example : (x ⊓ y) ⊓ z = x ⊓ (y ⊓ z) :=
begin
apply le_antisymm,
{ apply le_inf,
{ apply inf_le_of_left_le inf_le_left, },
{ apply le_inf (inf_le_of_left_le inf_le_right) inf_le_right}},
{apply le_inf,
{ apply le_inf inf_le_left (inf_le_of_right_le inf_le_left), },
{ apply inf_le_of_right_le inf_le_right, },},
end
-- 3ª demostración
-- ===============
example : (x ⊓ y) ⊓ z = x ⊓ (y ⊓ z) :=
le_antisymm
(le_inf
(inf_le_of_left_le inf_le_left)
(le_inf (inf_le_of_left_le inf_le_right) inf_le_right))
(le_inf
(le_inf inf_le_left (inf_le_of_right_le inf_le_left))
(inf_le_of_right_le inf_le_right))
-- 4ª demostración
-- ===============
example : (x ⊓ y) ⊓ z = x ⊓ (y ⊓ z) :=
-- by library_search
inf_assoc
-- 5ª demostración
-- ===============
example : (x ⊓ y) ⊓ z = x ⊓ (y ⊓ z) :=
-- by hint
by finish
|
module Core.Case.Util
import Core.Case.CaseTree
import Core.Context
import Core.Value
public export
record DataCon where
constructor MkDataCon
name : Name
tag : Int
arity : Nat
||| Given a normalised type, get all the possible constructors for that
||| type family, with their type, name, tag, and arity.
export
getCons : {auto c : Ref Ctxt Defs} ->
{vars : _} ->
Defs -> NF vars -> Core (List DataCon)
getCons defs (NTCon _ tn _ _ _)
= case !(lookupDefExact tn (gamma defs)) of
Just (TCon _ _ _ _ _ _ cons _) =>
do cs' <- traverse addTy cons
pure (catMaybes cs')
_ => throw (InternalError "Called `getCons` on something that is not a Type constructor")
where
addTy : Name -> Core (Maybe DataCon)
addTy cn
= do Just gdef <- lookupCtxtExact cn (gamma defs)
| _ => pure Nothing
case (gdef.definition, gdef.type) of
(DCon t arity _, ty) =>
pure . Just $ MkDataCon cn t arity
_ => pure Nothing
getCons defs _ = pure []
emptyRHS : FC -> CaseTree vars -> CaseTree vars
emptyRHS fc (Case idx el sc alts) = Case idx el sc (map emptyRHSalt alts)
where
emptyRHSalt : CaseAlt vars -> CaseAlt vars
emptyRHSalt (ConCase n t args sc) = ConCase n t args (emptyRHS fc sc)
emptyRHSalt (DelayCase c arg sc) = DelayCase c arg (emptyRHS fc sc)
emptyRHSalt (ConstCase c sc) = ConstCase c (emptyRHS fc sc)
emptyRHSalt (DefaultCase sc) = DefaultCase (emptyRHS fc sc)
emptyRHS fc (STerm i s) = STerm i (Erased fc False)
emptyRHS fc sc = sc
export
mkAlt : {vars : _} ->
FC -> CaseTree vars -> DataCon -> CaseAlt vars
mkAlt fc sc (MkDataCon cn t ar)
= ConCase cn t (map (MN "m") (take ar [0..]))
(weakenNs (map take) (emptyRHS fc sc))
export
tagIs : Int -> CaseAlt vars -> Bool
tagIs t (ConCase _ t' _ _) = t == t'
tagIs t (ConstCase _ _) = False
tagIs t (DelayCase _ _ _) = False
tagIs t (DefaultCase _) = True
|
Formal statement is: lemma sigma_sets_top: "sp \<in> sigma_sets sp A" Informal statement is: The topology on a space is a $\sigma$-algebra. |
module Rationals
--Type for divisibility
data isDivisor : Integer -> Integer -> Type where
AllDivZ : (m : Integer) -> isDivisor m 0
OneDivAll : (m : Integer) -> isDivisor 1 m
MulDiv : (c : Integer) -> isDivisor n m -> isDivisor ((\l => l*c) n) ((\l => l*c) m)
isNotZero : Nat -> Bool
isNotZero Z = False
isNotZero (S k) = True
isFactorInt : Integer -> Integer -> Type --Needed for defining Integer division
isFactorInt m n = (k : Integer ** (m * k = n))
divides : (m: Integer) -> (n: Integer) -> (k: Integer ** (m * k = n)) -> Integer
divides m n k = (fst k)
Pair : Type
Pair = (Integer, Integer)
Eucl: (a: Nat) -> (b: Nat) -> (Nat, Nat) --Euclidean algorithm implemented by Chinmaya
Eucl Z b = (0,0)
Eucl (S k) b = case (lte (S (S k)) b) of
False => (S(fst(Eucl (minus (S k) b) b)), snd(Eucl (minus (S k) b) b))
True => (0, S k)
{-
gcdab : Nat -> Nat -> Nat -- Produces the GCD of two numbers. This will be useful to produce the simplified form of a rational number.
gcdab b Z = b
gcdab a b = gcdab b (snd (Eucl a b))
-}
--Integer implemetation of gcd
gccd : (Integer, Integer) -> Integer
gccd (a, b) = if (isNotZero (toNat b)) then next else a where
next = gccd (b, toIntegerNat (modNat (toNat a) (toNat b)))
data NotZero : Integer -> Type where --Proof that a number is not zero, needed to construct Q
OneNotZero : NotZero 1
NegativeNotZero : ( n: Integer ) -> NotZero n -> NotZero (-n)
PositiveNotZero : ( m: Integer ) -> LTE 1 (fromIntegerNat m) -> NotZero m
--Type for equality of two Rationals
data EqRat : Pair -> Pair -> Type where
IdEq : (m : Pair) -> EqRat m m
MulEq : (c : Integer) -> EqRat n m -> EqRat ((fst n)*c,(snd n)*c) m
make_rational : (p: Nat) -> (q: Integer) -> NotZero q -> Pair
make_rational p q x = (toIntegerNat(p), q)
InclusionMap : (n : Nat) -> Pair --Includes the naturals in Q
InclusionMap n = make_rational n 1 OneNotZero
AddRationals : (x: Pair) -> NotZero (snd x) -> (y: Pair) -> NotZero (snd y) -> Pair
AddRationals x a y b = ((fst x)*(snd y) + (snd x)*(fst y), (snd x)*(snd y))
MultiplyRationals : (x: Pair) -> NotZero (snd x) -> (y: Pair) -> NotZero (snd y) -> Pair
MultiplyRationals x a y b =((fst x)*(fst y), (snd x)*(snd y))
--Need proof that MultInverse x * x = 1
MultInverse : (x: Pair) -> NotZero (fst x) -> NotZero (snd x) -> Pair
MultInverse x y z = ((snd x), (fst x))
AddInverse : (x: Pair) -> NotZero (snd x) -> Pair
AddInverse x a = (-(fst x), (snd x))
Subtraction : (x: Pair) -> NotZero (snd x) -> (y: Pair) -> NotZero (snd y) -> Pair
Subtraction x a y b = AddRationals x a (AddInverse y b) b
Division : (x: Pair) -> NotZero (snd x) -> (y: Pair) -> NotZero (fst y) -> NotZero (snd y) -> Pair
Division x a y b c = MultiplyRationals x a (MultInverse y b c) b
--SimplifyRational : (x: Pair) -> NotZero (snd x) -> Pair
--SimplifyRational x a = (divides (gcdab fromIntegerNat((fst x)) fromIntegerNat((snd x))) ___ (fst x), divides (gcdab fromIntegerNat((fst x)) fromIntegerNat((snd x)) __ (snd x))
--To prove that the SimplifyRational works, we can just check if the output is equal to the input
-- To be done
simplifyRational : (x : Pair) -> Pair
simplifyRational (a, b) = (sa, sb) where
sa = cast {from=Double} {to=Integer} (da / g) where
da = cast {from=Integer} {to=Double} a
g = cast {from=Integer} {to=Double} (gccd (a,b))
sb = cast {from=Double} {to=Integer} (db / g) where
db = cast {from=Integer} {to=Double} b
g = cast {from=Integer} {to=Double} (gccd (a,b))
--Above, I will need to supply a proof that the GCD divides the two numbers. Then, the function defined above will produce the rational in simplified form.
|
module Main
import Data.Vect
-- Enumerated types - Types defined by giving the possible values directly.
data Direction = North | East | South | West
turnClockwise : Direction -> Direction
turnClockwise North = East
turnClockwise East = South
turnClockwise South = West
turnClockwise West = North
-- Union types - Enumerated types that carries additional data at each values.
||| Shape represent objects from trigonometry.
data Shape = ||| A triangle, with its base length and height
Triangle Double Double
| ||| A rectabgle, with its length and height
Rectangle Double Double
| ||| A circle, with its radius
Circle Double
%name Shape shape, shape1, shape2
area : Shape -> Double
area (Triangle base height) = 0.5 * base * height
area (Rectangle length height) = length * height
area (Circle radius) = pi * radius * radius
data Shape2 : Type where
Triangle2 : Double -> Double -> Shape2
Rectagle2 : Double -> Double -> Shape2
Circle2 : Double -> Shape2
-- Recursive types - Union types that defined on terms of themselves.
data Picture : Type where
Primitive : Shape -> Picture
Combine : Picture -> Picture -> Picture
Rotate : Double -> Picture -> Picture
Translate : Double -> Double -> Picture -> Picture
%name Picture pic, pic1, pic2
rectangle : Picture
rectangle = Primitive (Rectangle 20 10)
circle : Picture
circle = Primitive (Circle 5)
triangle : Picture
triangle = Primitive (Triangle 10 10)
testPicture : Picture
testPicture =
Combine (Translate 5 5 rectangle)
(Combine (Translate 35 5 circle)
(Translate 15 25 triangle))
pictureArea : Picture -> Double
pictureArea (Primitive shape) = area shape
pictureArea (Combine pic pic1) = pictureArea pic + pictureArea pic1
pictureArea (Rotate x pic) = pictureArea pic
pictureArea (Translate x y pic) = pictureArea pic
-- Generic types - Types that are parametrized over some type
data Tree e
= Empty
| Node (Tree e) e (Tree e)
%name Tree tree, tree1
insert : Ord elem => elem -> Tree elem -> Tree elem
insert x Empty = Node Empty x Empty
insert x node@(Node left val right) = case compare x val of
LT => Node (insert x left) val right
EQ => node
GT => Node left val (insert x right)
data STree : Type -> Type where
SEmpty : Ord elem => STree elem
SNode : Ord elem
=> (left : STree elem)
-> (val : elem)
-> (right : STree elem)
-> STree elem
insertS : elem -> STree elem -> STree elem
insertS x SEmpty = SNode SEmpty x SEmpty
insertS x node@(SNode left val right)
= case compare x val of
LT => SNode (insertS x left) val right
EQ => node
GT => SNode left val (insertS x right)
listTree : Ord a => List a -> Tree a
listTree [] = Empty
listTree (x :: xs) = insert x $ listTree xs
treeToList : Tree a -> List a
treeToList Empty = []
treeToList (Node left val right) = treeToList left ++ [val] ++ treeToList right
-- Dependent types - Types are computed from some other values
data PowerSource = Petrol | Pedal
data Vehicle : PowerSource -> Type where
Bicycle : Vehicle Pedal
Car : (fuel : Nat) -> Vehicle Petrol
Bus : (fuel : Nat) -> Vehicle Petrol
renderVehicle : Vehicle power -> String
renderVehicle Bicycle = "Bicycle"
renderVehicle (Car fuel) = "Car " ++ show fuel
renderVehicle (Bus fuel) = "Bus " ++ show fuel
wheels : Vehicle power -> Nat
wheels Bicycle = 2
wheels (Car fuel) = 4
wheels (Bus fuel) = 4
refuel : Vehicle Petrol -> Vehicle Petrol
refuel (Car fuel) = Car 100
refuel (Bus fuel) = Bus 200
refuel Bicycle impossible
zip2 : Vect n a -> Vect n b -> Vect n (a,b)
zip2 [] [] = []
zip2 (x :: xs) (y :: ys) = (x, y) :: zip2 xs ys
tryIndex : Integer -> Vect n a -> Maybe a
tryIndex {n} i xs = case integerToFin i n of
Nothing => Nothing
Just idx => Just (index idx xs)
fin : Fin n -> Nat
fin FZ = 0
fin (FS x) = 1 + fin x
total
vectTake : (fn : Fin n) -> Vect n a -> Vect (fin fn) a
vectTake FZ xs = []
vectTake (FS n) (x :: xs) = x :: vectTake n xs
sumEntries : Num a => (pos : Integer) -> Vect n a -> Vect n a -> Maybe a
sumEntries {n} i xs ys = case integerToFin i n of
Nothing => Nothing
Just idx => Just $ (index idx xs) + (index idx ys)
main : IO ()
main = do
printLn "Data types"
printLn $ pictureArea testPicture
printLn $ treeToList $ listTree [1,4,3,5,2]
printLn $ wheels Bicycle
printLn $ renderVehicle (Bus 10)
printLn $ zip2 [1,2,3] ['a', 'b', 'c']
printLn $ Vect.index 3 [1,2,3,4,5]
printLn $ tryIndex 3 [1,2,3,4,5]
printLn $ sumEntries 2 [1,2,3,4] [5,6,7,8]
|
theory T87
imports Main
begin
lemma "(
(\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) &
(\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) &
(\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) &
(\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) &
(\<forall> x::nat. invo(invo(x)) = x)
) \<longrightarrow>
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z)))
"
nitpick[card nat=4,timeout=86400]
oops
end |
State Before: R : Type u_1
inst✝ : Semiring R
f✝ : R[X]
N : ℕ
f : R[X]
⊢ reflect N f = 0 ↔ f = 0 State After: no goals Tactic: rw [ofFinsupp_eq_zero, reflect, embDomain_eq_zero, ofFinsupp_eq_zero] |
(* *********************************************************************)
(* *)
(* The Compcert verified compiler *)
(* *)
(* Xavier Leroy, INRIA Paris-Rocquencourt *)
(* *)
(* Copyright Institut National de Recherche en Informatique et en *)
(* Automatique. All rights reserved. This file is distributed *)
(* under the terms of the INRIA Non-Commercial License Agreement. *)
(* *)
(* *********************************************************************)
(** Computation of resource bounds for Linear code. *)
Require Import FSets FSetAVL.
Require Import Coqlib Ordered.
Require Intv.
Require Import AST.
Require Import Op.
Require Import Machregs Locations.
Require Import Linear.
Require Import Conventions.
Module RegOrd := OrderedIndexed (IndexedMreg).
Module RegSet := FSetAVL.Make (RegOrd).
(** * Resource bounds for a function *)
(** The [bounds] record capture how many local and outgoing stack slots
and callee-save registers are used by a function. *)
(** We demand that all bounds are positive or null.
These properties are used later to reason about the layout of
the activation record. *)
Record bounds : Type := mkbounds {
used_callee_save: list mreg;
bound_local: Z;
bound_outgoing: Z;
bound_stack_data: Z;
bound_local_pos: bound_local >= 0;
bound_outgoing_pos: bound_outgoing >= 0;
bound_stack_data_pos: bound_stack_data >= 0;
used_callee_save_norepet: list_norepet used_callee_save;
used_callee_save_prop: forall r, In r used_callee_save -> is_callee_save r = true
}.
(** The following predicates define the correctness of a set of bounds
for the code of a function. *)
Section WITHIN_BOUNDS.
Variable b: bounds.
Definition mreg_within_bounds (r: mreg) :=
is_callee_save r = true -> In r (used_callee_save b).
Definition slot_within_bounds (sl: slot) (ofs: Z) (ty: typ) :=
match sl with
| Local => ofs + typesize ty <= bound_local b
| Outgoing => ofs + typesize ty <= bound_outgoing b
| Incoming => True
end.
Definition instr_within_bounds (i: instruction) :=
match i with
| Lgetstack sl ofs ty r => slot_within_bounds sl ofs ty /\ mreg_within_bounds r
| Lsetstack r sl ofs ty => slot_within_bounds sl ofs ty
| Lop op args res => mreg_within_bounds res
| Lload chunk addr args dst => mreg_within_bounds dst
| Lcall sig ros => size_arguments sig <= bound_outgoing b
| Lbuiltin ef args res =>
(forall r, In r (params_of_builtin_res res) \/ In r (destroyed_by_builtin ef) -> mreg_within_bounds r)
/\ (forall sl ofs ty, In (S sl ofs ty) (params_of_builtin_args args) -> slot_within_bounds sl ofs ty)
| _ => True
end.
End WITHIN_BOUNDS.
Definition function_within_bounds (f: function) (b: bounds) : Prop :=
forall instr, In instr f.(fn_code) -> instr_within_bounds b instr.
(** * Inference of resource bounds for a function *)
(** The resource bounds for a function are computed by a linear scan
of its instructions. *)
Section BOUNDS.
Variable f: function.
Definition record_reg (u: RegSet.t) (r: mreg) : RegSet.t :=
if is_callee_save r then RegSet.add r u else u.
Definition record_regs (u: RegSet.t) (rl: list mreg) : RegSet.t :=
fold_left record_reg rl u.
(** In the proof of the [Stacking] pass, we only need to bound the
registers written by an instruction. Therefore, we examine the
result registers only, not the argument registers. *)
Definition record_regs_of_instr (u: RegSet.t) (i: instruction) : RegSet.t :=
match i with
| Lgetstack sl ofs ty r => record_reg u r
| Lsetstack r sl ofs ty => record_reg u r
| Lop op args res => record_reg u res
| Lload chunk addr args dst => record_reg u dst
| Lstore chunk addr args src => u
| Lcall sig ros => u
| Ltailcall sig ros => u
| Lbuiltin ef args res =>
record_regs (record_regs u (params_of_builtin_res res)) (destroyed_by_builtin ef)
| Llabel lbl => u
| Lgoto lbl => u
| Lcond cond args lbl => u
| Ljumptable arg tbl => u
| Lreturn => u
end.
Definition record_regs_of_function : RegSet.t :=
fold_left record_regs_of_instr f.(fn_code) RegSet.empty.
Fixpoint slots_of_locs (l: list loc) : list (slot * Z * typ) :=
match l with
| nil => nil
| S sl ofs ty :: l' => (sl, ofs, ty) :: slots_of_locs l'
| R r :: l' => slots_of_locs l'
end.
Definition slots_of_instr (i: instruction) : list (slot * Z * typ) :=
match i with
| Lgetstack sl ofs ty r => (sl, ofs, ty) :: nil
| Lsetstack r sl ofs ty => (sl, ofs, ty) :: nil
| Lbuiltin ef args res => slots_of_locs (params_of_builtin_args args)
| _ => nil
end.
Definition max_over_list {A: Type} (valu: A -> Z) (l: list A) : Z :=
List.fold_left (fun m l => Z.max m (valu l)) l 0.
Definition max_over_instrs (valu: instruction -> Z) : Z :=
max_over_list valu f.(fn_code).
Definition max_over_slots_of_instr (valu: slot * Z * typ -> Z) (i: instruction) : Z :=
max_over_list valu (slots_of_instr i).
Definition max_over_slots_of_funct (valu: slot * Z * typ -> Z) : Z :=
max_over_instrs (max_over_slots_of_instr valu).
Definition local_slot (s: slot * Z * typ) :=
match s with (Local, ofs, ty) => ofs + typesize ty | _ => 0 end.
Definition outgoing_slot (s: slot * Z * typ) :=
match s with (Outgoing, ofs, ty) => ofs + typesize ty | _ => 0 end.
Definition outgoing_space (i: instruction) :=
match i with Lcall sig _ => size_arguments sig | _ => 0 end.
Lemma max_over_list_pos:
forall (A: Type) (valu: A -> Z) (l: list A),
max_over_list valu l >= 0.
Proof.
intros until valu. unfold max_over_list.
assert (forall l z, fold_left (fun x y => Z.max x (valu y)) l z >= z).
induction l; simpl; intros.
lia. apply Zge_trans with (Z.max z (valu a)).
auto. apply Z.le_ge. apply Z.le_max_l. auto.
Qed.
Lemma max_over_slots_of_funct_pos:
forall (valu: slot * Z * typ -> Z), max_over_slots_of_funct valu >= 0.
Proof.
intros. unfold max_over_slots_of_funct.
unfold max_over_instrs. apply max_over_list_pos.
Qed.
(* Move elsewhere? *)
Remark fold_left_preserves:
forall (A B: Type) (f: A -> B -> A) (P: A -> Prop),
(forall a b, P a -> P (f a b)) ->
forall l a, P a -> P (fold_left f l a).
Proof.
induction l; simpl; auto.
Qed.
Remark fold_left_ensures:
forall (A B: Type) (f: A -> B -> A) (P: A -> Prop) b0,
(forall a b, P a -> P (f a b)) ->
(forall a, P (f a b0)) ->
forall l a, In b0 l -> P (fold_left f l a).
Proof.
induction l; simpl; intros. contradiction.
destruct H1. subst a. apply fold_left_preserves; auto. apply IHl; auto.
Qed.
Definition only_callee_saves (u: RegSet.t) : Prop :=
forall r, RegSet.In r u -> is_callee_save r = true.
Lemma record_reg_only: forall u r, only_callee_saves u -> only_callee_saves (record_reg u r).
Proof.
unfold only_callee_saves, record_reg; intros.
destruct (is_callee_save r) eqn:CS; auto.
destruct (mreg_eq r r0). congruence. apply H; eapply RegSet.add_3; eauto.
Qed.
Lemma record_regs_only: forall rl u, only_callee_saves u -> only_callee_saves (record_regs u rl).
Proof.
intros. unfold record_regs. apply fold_left_preserves; auto using record_reg_only.
Qed.
Lemma record_regs_of_instr_only: forall u i, only_callee_saves u -> only_callee_saves (record_regs_of_instr u i).
Proof.
intros. destruct i; simpl; auto using record_reg_only, record_regs_only.
Qed.
Lemma record_regs_of_function_only:
only_callee_saves record_regs_of_function.
Proof.
intros. unfold record_regs_of_function.
apply fold_left_preserves. apply record_regs_of_instr_only.
red; intros. eelim RegSet.empty_1; eauto.
Qed.
Program Definition function_bounds := {|
used_callee_save := RegSet.elements record_regs_of_function;
bound_local := max_over_slots_of_funct local_slot;
bound_outgoing := Z.max (max_over_instrs outgoing_space) (max_over_slots_of_funct outgoing_slot);
bound_stack_data := Z.max f.(fn_stacksize) 0
|}.
Next Obligation.
apply max_over_slots_of_funct_pos.
Qed.
Next Obligation.
apply Z.le_ge. eapply Z.le_trans. 2: apply Z.le_max_r.
apply Z.ge_le. apply max_over_slots_of_funct_pos.
Qed.
Next Obligation.
apply Z.le_ge. apply Z.le_max_r.
Qed.
Next Obligation.
generalize (RegSet.elements_3w record_regs_of_function).
generalize (RegSet.elements record_regs_of_function).
induction 1. constructor. constructor; auto.
red; intros; elim H. apply InA_alt. exists x; auto.
Qed.
Next Obligation.
apply record_regs_of_function_only. apply RegSet.elements_2.
apply InA_alt. exists r; auto.
Qed.
(** We now show the correctness of the inferred bounds. *)
Lemma record_reg_incr: forall u r r', RegSet.In r' u -> RegSet.In r' (record_reg u r).
Proof.
unfold record_reg; intros. destruct (is_callee_save r); auto. apply RegSet.add_2; auto.
Qed.
Lemma record_reg_ok: forall u r, is_callee_save r = true -> RegSet.In r (record_reg u r).
Proof.
unfold record_reg; intros. rewrite H. apply RegSet.add_1; auto.
Qed.
Lemma record_regs_incr: forall r' rl u, RegSet.In r' u -> RegSet.In r' (record_regs u rl).
Proof.
intros. unfold record_regs. apply fold_left_preserves; auto using record_reg_incr.
Qed.
Lemma record_regs_ok: forall r rl u, In r rl -> is_callee_save r = true -> RegSet.In r (record_regs u rl).
Proof.
intros. unfold record_regs. eapply fold_left_ensures; eauto using record_reg_incr, record_reg_ok.
Qed.
Lemma record_regs_of_instr_incr: forall r' u i, RegSet.In r' u -> RegSet.In r' (record_regs_of_instr u i).
Proof.
intros. destruct i; simpl; auto using record_reg_incr, record_regs_incr.
Qed.
Definition defined_by_instr (r': mreg) (i: instruction) :=
match i with
| Lgetstack sl ofs ty r => r' = r
| Lop op args res => r' = res
| Lload chunk addr args dst => r' = dst
| Lbuiltin ef args res => In r' (params_of_builtin_res res) \/ In r' (destroyed_by_builtin ef)
| _ => False
end.
Lemma record_regs_of_instr_ok: forall r' u i, defined_by_instr r' i -> is_callee_save r' = true -> RegSet.In r' (record_regs_of_instr u i).
Proof.
intros. destruct i; simpl in *; try contradiction; subst; auto using record_reg_ok.
destruct H; auto using record_regs_incr, record_regs_ok.
Qed.
Lemma record_regs_of_function_ok:
forall r i, In i f.(fn_code) -> defined_by_instr r i -> is_callee_save r = true -> RegSet.In r record_regs_of_function.
Proof.
intros. unfold record_regs_of_function.
eapply fold_left_ensures; eauto using record_regs_of_instr_incr, record_regs_of_instr_ok.
Qed.
Lemma max_over_list_bound:
forall (A: Type) (valu: A -> Z) (l: list A) (x: A),
In x l -> valu x <= max_over_list valu l.
Proof.
intros until x. unfold max_over_list.
assert (forall c z,
let f := fold_left (fun x y => Z.max x (valu y)) c z in
z <= f /\ (In x c -> valu x <= f)).
induction c; simpl; intros.
split. lia. tauto.
elim (IHc (Z.max z (valu a))); intros.
split. apply Z.le_trans with (Z.max z (valu a)). apply Z.le_max_l. auto.
intro H1; elim H1; intro.
subst a. apply Z.le_trans with (Z.max z (valu x)).
apply Z.le_max_r. auto. auto.
intro. elim (H l 0); intros. auto.
Qed.
Lemma max_over_instrs_bound:
forall (valu: instruction -> Z) i,
In i f.(fn_code) -> valu i <= max_over_instrs valu.
Proof.
intros. unfold max_over_instrs. apply max_over_list_bound; auto.
Qed.
Lemma max_over_slots_of_funct_bound:
forall (valu: slot * Z * typ -> Z) i s,
In i f.(fn_code) -> In s (slots_of_instr i) ->
valu s <= max_over_slots_of_funct valu.
Proof.
intros. unfold max_over_slots_of_funct.
apply Z.le_trans with (max_over_slots_of_instr valu i).
unfold max_over_slots_of_instr. apply max_over_list_bound. auto.
apply max_over_instrs_bound. auto.
Qed.
Lemma local_slot_bound:
forall i ofs ty,
In i f.(fn_code) -> In (Local, ofs, ty) (slots_of_instr i) ->
ofs + typesize ty <= bound_local function_bounds.
Proof.
intros.
unfold function_bounds, bound_local.
change (ofs + typesize ty) with (local_slot (Local, ofs, ty)).
eapply max_over_slots_of_funct_bound; eauto.
Qed.
Lemma outgoing_slot_bound:
forall i ofs ty,
In i f.(fn_code) -> In (Outgoing, ofs, ty) (slots_of_instr i) ->
ofs + typesize ty <= bound_outgoing function_bounds.
Proof.
intros. change (ofs + typesize ty) with (outgoing_slot (Outgoing, ofs, ty)).
unfold function_bounds, bound_outgoing.
apply Zmax_bound_r. eapply max_over_slots_of_funct_bound; eauto.
Qed.
Lemma size_arguments_bound:
forall sig ros,
In (Lcall sig ros) f.(fn_code) ->
size_arguments sig <= bound_outgoing function_bounds.
Proof.
intros. change (size_arguments sig) with (outgoing_space (Lcall sig ros)).
unfold function_bounds, bound_outgoing.
apply Zmax_bound_l. apply max_over_instrs_bound; auto.
Qed.
(** Consequently, all machine registers or stack slots mentioned by one
of the instructions of function [f] are within bounds. *)
Lemma mreg_is_within_bounds:
forall i, In i f.(fn_code) ->
forall r, defined_by_instr r i ->
mreg_within_bounds function_bounds r.
Proof.
intros. unfold mreg_within_bounds. intros.
exploit record_regs_of_function_ok; eauto. intros.
apply RegSet.elements_1 in H2. rewrite InA_alt in H2. destruct H2 as (r' & A & B).
subst r'; auto.
Qed.
Lemma slot_is_within_bounds:
forall i, In i f.(fn_code) ->
forall sl ty ofs, In (sl, ofs, ty) (slots_of_instr i) ->
slot_within_bounds function_bounds sl ofs ty.
Proof.
intros. unfold slot_within_bounds.
destruct sl.
eapply local_slot_bound; eauto.
auto.
eapply outgoing_slot_bound; eauto.
Qed.
Lemma slots_of_locs_charact:
forall sl ofs ty l, In (sl, ofs, ty) (slots_of_locs l) <-> In (S sl ofs ty) l.
Proof.
induction l; simpl; intros.
tauto.
destruct a; simpl; intuition congruence.
Qed.
(** It follows that every instruction in the function is within bounds,
in the sense of the [instr_within_bounds] predicate. *)
Lemma instr_is_within_bounds:
forall i,
In i f.(fn_code) ->
instr_within_bounds function_bounds i.
Proof.
intros;
destruct i;
generalize (mreg_is_within_bounds _ H); generalize (slot_is_within_bounds _ H);
simpl; intros; auto.
(* call *)
eapply size_arguments_bound; eauto.
(* builtin *)
split; intros.
apply H1; auto.
apply H0. rewrite slots_of_locs_charact; auto.
Qed.
Lemma function_is_within_bounds:
function_within_bounds f function_bounds.
Proof.
intros; red; intros. apply instr_is_within_bounds; auto.
Qed.
End BOUNDS.
(** Helper to determine the size of the frame area that holds the contents of saved registers. *)
Fixpoint size_callee_save_area_rec (l: list mreg) (ofs: Z) : Z :=
match l with
| nil => ofs
| r :: l =>
let ty := mreg_type r in
let sz := AST.typesize ty in
size_callee_save_area_rec l (align ofs sz + sz)
end.
Definition size_callee_save_area (b: bounds) (ofs: Z) : Z :=
size_callee_save_area_rec (used_callee_save b) ofs.
Lemma size_callee_save_area_rec_incr:
forall l ofs, ofs <= size_callee_save_area_rec l ofs.
Proof.
Local Opaque mreg_type.
induction l as [ | r l]; intros; simpl.
- lia.
- eapply Z.le_trans. 2: apply IHl.
generalize (AST.typesize_pos (mreg_type r)); intros.
apply Z.le_trans with (align ofs (AST.typesize (mreg_type r))).
apply align_le; auto.
lia.
Qed.
Lemma size_callee_save_area_incr:
forall b ofs, ofs <= size_callee_save_area b ofs.
Proof.
intros. apply size_callee_save_area_rec_incr.
Qed.
(** Layout of the stack frame and its properties. These definitions
are used in the machine-dependent [Stacklayout] module and in the
[Stacking] pass. *)
Record frame_env : Type := mk_frame_env {
fe_size: Z;
fe_ofs_link: Z;
fe_ofs_retaddr: Z;
fe_ofs_local: Z;
fe_ofs_callee_save: Z;
fe_stack_data: Z;
fe_used_callee_save: list mreg
}.
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.