text
stringlengths 0
3.34M
|
---|
program t
integer::a
DATA a/x'1f7'/
print *,a
endprogram t
|
[STATEMENT]
lemma polynomial_of_mset_Cons[simp]:
\<open>polynomial_of_mset (add_mset x ys) = Const (snd x) * poly_of_vars (fst x) + polynomial_of_mset ys\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. polynomial_of_mset (add_mset x ys) = Const (snd x) * poly_of_vars (fst x) + polynomial_of_mset ys
[PROOF STEP]
by (cases x)
(auto simp: ac_simps polynomial_of_mset_def mononom_of_vars_def) |
import algebra.pi_instances algebra.half_ring data.finset
/-- A function which is defined everywhere, but only has "interesting" values in
a finite set of locations.
This is used to define a basic vector space, where every defined basis is
known. -/
structure fin_fn (α : Type*) (β : Type*) [has_zero β] :=
(space : α → β)
(support : finset α)
(support_iff : ∀ x, space x ≠ 0 ↔ x ∈ support)
namespace fin_fn
section helpers
variables {α : Type*} {β₁ : Type*} {β₂ : Type*} {β : Type*} [has_zero β₁] [has_zero β₂] [has_zero β]
/-- Map over a finite set, assuming the support set doesn't grow. -/
def on_finset [decidable_eq β] (s : finset α) (f : α → β) (hf : ∀a, f a ≠ 0 → a ∈ s) : fin_fn α β :=
⟨ f,
s.filter (λa, f a ≠ 0),
λ x, ⟨ λ h, finset.mem_filter.mpr ⟨ hf x h, h ⟩, λ h, (finset.mem_filter.mp h).2 ⟩ ⟩
/-- Zip over two support sets, assuming the operation preserves 0. -/
def zip_with [decidable_eq α] [decidable_eq β₁] [decidable_eq β]
(f : β₁ → β₂ → β) (zero : f 0 0 = 0) (g₁ : fin_fn α β₁) (g₂ : fin_fn α β₂) : (fin_fn α β) :=
on_finset (g₁.support ∪ g₂.support) (λa, f (g₁.space a) (g₂.space a)) (λ a not_zero, begin
rw [finset.mem_union, (g₁.support_iff _).symm, (g₂.support_iff _).symm, ne, ← not_and_distrib],
rintro ⟨ h₁, h₂ ⟩, rw [h₁, h₂] at not_zero, from not_zero zero,
end)
/-- Function extensionality lifted to fin_fns. -/
@[ext]
lemma ext : ∀ {f g : fin_fn α β}, (∀ a, f.space a = g.space a) → f = g
| ⟨ f, sf, iff_f ⟩ ⟨ g, sg, iff_g ⟩ lift := begin
have : f = g := funext lift, subst this,
have : sf = sg := finset.ext' (λ a, (iff_f a).symm.trans (iff_g a)), subst this,
end
/-- Apply a 0-preserving function over the range of our fin_fn. -/
def map_range [decidable_eq β] (f : β₁ → β) (zero : f 0 = 0) (g : fin_fn α β₁) : fin_fn α β :=
on_finset g.support (f ∘ g.space) (λ a not_zero, begin
rw [(g.support_iff _).symm],
assume is_zero, rw [function.comp_app, is_zero] at not_zero, from not_zero zero,
end)
lemma unsupported_zero [decidable_eq β] {x : α} {f : fin_fn α β} : x ∉ f.support ↔ f.space x = 0
:= ⟨ λ nmem, by_contradiction (λ h, nmem ((f.support_iff x).mp h)),
λ zero mem, (f.support_iff x).mpr mem zero ⟩
/-- Function extensionality lifted to fin_fns. -/
lemma ext' [decidable_eq β] : ∀ {f g : fin_fn α β}, f.support = g.support → (∀ a ∈ f.support, f.space a = g.space a) → f = g
| ⟨ f, sf, iff_f ⟩ ⟨ g, _, iff_g ⟩ eql lift := begin
simp only [] at eql, subst eql,
suffices : ∀ a, f a = g a, from ext this,
assume a,
cases classical.prop_decidable (a ∈ sf),
case is_true { from lift a h },
case is_false {
have : f a = 0,
{ have : a ∉ (fin_fn.mk f sf iff_f).support := h,
from (unsupported_zero.mp this) },
have : g a = 0,
{ have : a ∉ (fin_fn.mk g sf iff_g).support := h,
from (unsupported_zero.mp this) },
rw [‹f a = 0›, ‹g a = 0›],
}
end
/-- Convert this fin_fn to a string, using a specific separator (such as "+"). -/
protected def to_string [has_repr α] [has_repr β] : string → fin_fn α β → string
| sep x := string.intercalate sep ((x.support.val.map (λ a, repr (x.space a) ++ " • " ++ repr a)).sort (≤))
end helpers
section monoid_instances
variables (α : Type*) (β : Type*)
instance [has_repr α] [has_repr β] [has_zero β] : has_repr (fin_fn α β) := ⟨ fin_fn.to_string "+" ⟩
instance [has_zero β] : has_zero (fin_fn α β)
:= ⟨ { space := λ _, 0,
support := finset.empty,
support_iff := λ x, ⟨ λ nZero, by contradiction, λ x, by cases x ⟩ } ⟩
instance [has_zero β] : inhabited (fin_fn α β) := ⟨ 0 ⟩
instance [add_monoid β] [decidable_eq α] [decidable_eq β] : has_add (fin_fn α β) :=
{ add := zip_with (+) (add_zero 0) }
instance [add_monoid β] [decidable_eq α] [decidable_eq β] : add_monoid (fin_fn α β) :=
{ add_assoc := λ a b c, ext (λ x, add_assoc _ _ _),
zero_add := λ a, ext (λ x, zero_add _),
add_zero := λ a, ext (λ x, add_zero _),
..fin_fn.has_add α β,
..fin_fn.has_zero α β }
instance [add_comm_monoid β] [decidable_eq α] [decidable_eq β]
: add_comm_monoid (fin_fn α β) :=
{ add_comm := λ a b, ext (λ x, add_comm _ _),
..fin_fn.add_monoid α β }
instance [add_group β] [decidable_eq β] : has_neg (fin_fn α β) :=
{ neg := map_range has_neg.neg neg_zero }
instance [add_comm_group β] [decidable_eq α] [decidable_eq β] : add_comm_group (fin_fn α β) :=
{ add_left_neg := λ f, ext (λ a, add_left_neg _),
..fin_fn.add_comm_monoid α β,
..fin_fn.has_neg α β }
instance [semiring β] [decidable_eq β]
: has_scalar β (fin_fn α β)
:= { smul := λ a, map_range ((•) a) (smul_zero _) }
instance [comm_ring β] [decidable_eq β]
: mul_action β (fin_fn α β) :=
{ one_smul := λ f, ext (λ a, one_smul _ _),
mul_smul := λ x y f, ext (λ a, mul_smul _ _ _),
..fin_fn.has_scalar α β }
instance [comm_ring β] [decidable_eq α] [decidable_eq β]
: distrib_mul_action β (fin_fn α β) :=
{ smul_add := λ r x y, ext (λ a, smul_add _ _ _),
smul_zero := λ r, ext (λ a, smul_zero _),
..fin_fn.mul_action α β }
instance [comm_ring β] [decidable_eq α] [decidable_eq β]
: semimodule β (fin_fn α β) :=
{ add_smul := λ r s f, ext (λ a, right_distrib _ _ _),
zero_smul := λ f, ext (λ a, zero_mul _),
..fin_fn.distrib_mul_action α β,
}
instance [has_zero β] [decidable_eq α] [decidable_eq β] : decidable_eq (fin_fn α β)
| ⟨ a_f, a_space, a_iff ⟩ ⟨ b_f, b_space, b_iff ⟩ :=
if eq_space : a_space = b_space then
if eq_f : ∀ a ∈ a_space, a_f a = b_f a then
is_true (ext' eq_space eq_f)
else is_false (λ x, begin
have h := (fin_fn.mk.inj x).1, subst h,
from eq_f (λ x mem, rfl),
end)
else is_false (λ x, eq_space (fin_fn.mk.inj x).2)
instance [add_monoid β] [decidable_eq α] [decidable_eq β] (a : α) : is_add_monoid_hom (λ f : fin_fn α β, f.space a)
:= { map_add := λ a b, rfl, map_zero := rfl }
end monoid_instances
section bulk_operations
variables {α : Type*} {β : Type*}
/-- Construct a fin_fn from a single value A. This returns a unit vector in the
basis of 'A'. -/
def single [has_zero β] [decidable_eq α] [decidable_eq β] (A : α) (b : β) : fin_fn α β :=
{ space := λ B, if A = B then b else 0,
support := if 0 = b then ∅ else finset.singleton A,
support_iff := λ B, begin
by_cases is_zero : 0 = b; by_cases is_eq : A = B; simp only [is_zero, is_eq, if_pos, if_false],
{ from ⟨ λ x, by contradiction, false.elim ⟩ },
{ from ⟨ λ x, by contradiction, false.elim ⟩ },
{ from ⟨ λ _, finset.mem_singleton.mpr rfl, λ _, ne.symm is_zero ⟩ },
{ from ⟨ λ x, by contradiction, λ mem, absurd (finset.mem_singleton.mp mem).symm is_eq ⟩ },
end }
lemma single.inj [has_zero β] [decidable_eq α] [decidable_eq β] (A : α)
: function.injective (@single α β _ _ _ A)
| b₁ b₂ eql := begin
have : (single A b₁).space A = (single A b₂).space A, rw eql,
simpa only [single, if_pos] using this,
end
@[simp]
lemma single_zero [has_zero β] [decidable_eq α] [decidable_eq β] (a : α) : single a (0 : β) = 0
:= by { simp only [single, if_pos, if_t_t], from rfl }
@[simp]
lemma single_add [add_monoid β] [decidable_eq α] [decidable_eq β] (a : α) (b₁ b₂ : β) :
single a (b₁ + b₂) = single a b₁ + single a b₂
:= ext (λ x, begin
show ite (a = x) (b₁ + b₂) 0 = ite (a = x) b₁ 0 + ite (a = x) b₂ 0,
by_cases a = x; simp only [h, if_pos, if_false, add_zero],
end)
/-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/
def sum {γ : Type*} [has_zero β] [add_comm_monoid γ] (f : fin_fn α β) (g : α → β → γ) : γ
:= f.support.sum (λa, g a (f.space a))
@[simp]
lemma sum_single_index {γ : Type*} [add_comm_monoid γ] [comm_ring β] [decidable_eq α] [decidable_eq β]
(a : α) (b : β) (f : α → β → γ) (zero : ∀ x, f x 0 = 0): (single a b).sum f = f a b := begin
by_cases 0 = b; simp only [sum, single, if_pos, if_false, h],
{ simp only [finset.sum_empty, h.symm, zero] },
{ simp only [finset.sum_singleton, if_pos] },
end
lemma sum_distrib {γ : Type*} [decidable_eq α] [decidable_eq β] [add_comm_monoid β] [add_comm_monoid γ] {x y : fin_fn α β}
{h : α → β → γ} (h_zero : ∀ a, h a 0 = 0) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ + h a b₂) :
(x + y).sum h = x.sum h + y.sum h := begin
show finset.sum (finset.filter (λ a, x.space a + y.space a ≠ 0) (x.support ∪ y.support))
(λ a, h a (x.space a + y.space a))
= x.sum h + y.sum h,
have : finset.sum (finset.filter (λ a, x.space a + y.space a ≠ 0) (x.support ∪ y.support))
(λ a, h a (x.space a + y.space a))
= finset.sum (x.support ∪ y.support) (λ a, h a (x.space a + y.space a))
:= finset.sum_subset (finset.filter_subset (x.support ∪ y.support)) (λ a mem not_mem, begin
suffices : x.space a + y.space a = 0, simp only [h_zero, this],
by_contradiction not_zero,
have h := finset.mem_sdiff.mpr ⟨ mem, not_mem ⟩,
rw ← finset.filter_not at h,
from (finset.mem_filter.mp h).2 not_zero,
end),
rw this,
have hx : x.sum h = finset.sum (x.support ∪ y.support) (λ a, h a (x.space a))
:= finset.sum_subset (finset.subset_union_left x.support y.support)
(λ a mem not_x, by simp only [unsupported_zero.mp not_x, h_zero]),
have hy : y.sum h = finset.sum (x.support ∪ y.support) (λ a, h a (y.space a))
:= finset.sum_subset (finset.subset_union_right x.support y.support)
(λ a mem not_y, by simp only [unsupported_zero.mp not_y, h_zero]),
simp only [hx, hy, h_add, finset.sum_add_distrib],
end
@[simp]
lemma sum_zero {γ : Type*} [has_zero β] [add_comm_monoid γ] (f : α → β → γ) : sum 0 f = 0 := rfl
@[simp]
lemma sum_const_zero {γ : Type*} [has_zero β] [add_comm_monoid γ] (f : fin_fn α β): sum f (λ _ _, (0 : γ)) = 0
:= finset.sum_const_zero
/-- Map every basis in the fin_fn to another fin_fn, accumulating them together. -/
def bind {γ : Type*} [decidable_eq γ] [decidable_eq β] [semiring β] (f : fin_fn α β) (g : α → fin_fn γ β) : fin_fn γ β
:= sum f (λ x c, c • g x)
@[simp]
lemma bind_zero {γ : Type} [decidable_eq γ] [decidable_eq β] [semiring β] (f : α → fin_fn γ β) : bind 0 f = 0 := sum_zero _
lemma empty_zero [has_zero β] [decidable_eq β] : ∀ (f : fin_fn α β), f.support = ∅ → f = 0
| ⟨ f, _, iff ⟩ ⟨ _ ⟩ := ext (λ x, by_contradiction (iff x).mp)
@[simp]
lemma sum_sum_index {γ : Type*} {α₁: Type*} {β₁ : Type*} [decidable_eq α] [decidable_eq α₁] [decidable_eq β]
[add_comm_monoid β₁] [add_comm_monoid β] [add_comm_monoid γ]
{f : fin_fn α₁ β₁} {g : α₁ → β₁ → fin_fn α β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 0) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ + h a b₂) :
(f.sum g).sum h = f.sum (λa b, (g a b).sum h) := begin
show (finset.sum f.support (λ (a : α₁), g a (f.space a))).sum h
= finset.sum f.support _,
induction f.support using finset.induction_on with a s not_mem ih,
from rfl,
{ rw [finset.sum_insert not_mem, finset.sum_insert not_mem, ← ih, sum_distrib h_zero h_add], },
end
lemma bind_distrib {γ : Type} [comm_ring β] [decidable_eq α] [decidable_eq γ] [decidable_eq β] :
∀ (x y : fin_fn α β) (f : α → fin_fn γ β)
, bind (x + y) f = bind x f + bind y f
| x y f := begin
have zero : ∀ a, (λ (x : α) (c : β), c • f x) a 0 = 0 := λ _, by simp only [zero_smul],
have add : ∀ (a : α) (b₁ b₂ : β)
, (λ (x : α) (c : β), c • f x) a (b₁ + b₂)
= (λ (x : α) (c : β), c • f x) a b₁ + (λ (x : α) (c : β), c • f x) a b₂
:= λ _ _ _, by simp only [add_smul],
simp only [sum_distrib zero add, bind],
end
lemma bind_smul {γ : Type} [comm_ring β] [decidable_eq α] [decidable_eq γ] [decidable_eq β] :
∀ (c : β) (x : fin_fn α β) (f : α → fin_fn γ β)
, c • bind x f = bind (c • x) f
| c x f := begin
simp only [bind, sum],
have : (c • x).support ⊆ x.support := finset.filter_subset _,
rw finset.sum_subset this (λ a mem not_mem, begin
show (λ a, (c • x).space a • f a) a = 0,
simp only [],
rw [unsupported_zero.mp not_mem, zero_smul],
end), simp only [], clear this,
-- Then follow the same proof as prod_pow.
induction x.support using finset.induction_on with a f not_mem ih,
{ simp only [finset.sum_empty, smul_zero] },
{
simp only [finset.sum_insert not_mem],
rw [smul_add, ← mul_smul, ih],
from rfl,
},
end
/-- `bind`, lifted to two `fin_fn`s. -/
def bind₂ {γ η : Type} [decidable_eq η] [decidable_eq β] [semiring β]
: fin_fn α β → fin_fn γ β → (α → γ → fin_fn η β) → fin_fn η β
| x y f := bind x (λ a, bind y (f a))
lemma bind₂_zero {γ η : Type} [decidable_eq η] [decidable_eq β] [semiring β] (f : α → γ → fin_fn η β) :
bind₂ 0 0 f = 0 := rfl
lemma bind₂_zero_right {γ η : Type} [decidable_eq η] [decidable_eq β] [semiring β]
(x : fin_fn γ β) (f : α → γ → fin_fn η β) :
bind₂ 0 x f = 0 := rfl
/-- It doesn't matter which order we do our bind in! -/
lemma bind₂_swap {α β γ η : Type*} [decidable_eq η] [decidable_eq β] [comm_ring β] :
∀ (x : fin_fn α β) (y : fin_fn γ β) (f : (α → γ → fin_fn η β))
, bind₂ x y f = bind₂ y x (λ x y, f y x)
| x y f := begin
show finset.sum x.support (λ a, x.space a • finset.sum y.support (λ b, y.space b • f a b))
= finset.sum y.support (λ a, y.space a • finset.sum x.support (λ b, x.space b • f b a)),
have : ∀ a b, y.space a • x.space b • f b a = x.space b • y.space a • f b a
:= λ a b, smul_comm (y.space a) _ _,
simp only [finset.smul_sum, this],
simp only [finset.sum_eq_multiset_sum],
from multiset.sum_map_sum_map x.support.val y.support.val,
end
lemma bind₂_zero_left {α β γ η : Type} [decidable_eq β] [decidable_eq η] [comm_ring β]
(x : fin_fn α β) (f : α → γ → fin_fn η β) :
bind₂ x 0 f = 0 := by { rw (bind₂_swap x 0 f), from rfl }
@[simp]
lemma bind_single {γ : Type} [comm_ring β] [decidable_eq α] [decidable_eq γ] [decidable_eq β] :
∀ (a : α) (b : β) (f : α → fin_fn γ β)
, bind (single a b) f = b • f a
| a b f := sum_single_index a b _ (λ x, zero_smul _ _)
@[simp]
lemma sum_single [decidable_eq α] [decidable_eq β] [add_comm_monoid β] (f : fin_fn α β)
: f.sum single = f := begin
suffices : ∀ (a : α), (sum f single).space a = f.space a, from ext this,
assume a,
suffices : finset.sum f.support (λ (x : α), ite (x = a) (f.space x) 0) = f.space a,
{ have h := (f.support.sum_hom (λ f : fin_fn α β, f.space a)).symm,
refine trans h _,
simp only [single, this] },
by_cases h : a ∈ f.support,
{ have : (finset.singleton a : finset α) ⊆ f.support,
{ simpa only [finset.subset_iff, finset.mem_singleton, forall_eq] },
rw ← finset.sum_subset this (λ b mem not_mem, begin
show ite (b = a) (f.space b) 0 = 0,
simp only [if_neg (finset.not_mem_singleton.mp not_mem)],
end),
simp only [finset.sum_singleton, if_pos (eq.refl a)],
},
{
calc finset.sum f.support (λ (x : α), ite (x = a) (f.space x) 0)
= f.support.sum (λ a, (0 : β)) : finset.sum_congr rfl (λ b mem, begin
by_cases (b = a), { subst h, contradiction },
simp only [if_neg h],
end)
... = 0 : finset.sum_const_zero
... = f.space a : (unsupported_zero.mp h).symm
},
end
end bulk_operations
section group_instances
variables (α : Type*) (β : Type*)
instance [decidable_eq α] [decidable_eq β] [has_zero α] [has_zero β] [has_one β] : has_one (fin_fn α β) :=
{ one := single 0 1 }
instance [decidable_eq α] [decidable_eq β] [has_add α] [semiring β] : has_mul (fin_fn α β) :=
{ mul := λ f g, f.sum $ λ a₁ b₁, g.sum $ λ a₂ b₂, single (a₁ + a₂) (b₁ * b₂) }
instance [decidable_eq α] [decidable_eq β] [add_semigroup α] [comm_ring β] : semigroup (fin_fn α β)
:= { mul_assoc := λ a b c, begin
show sum
(sum a (λ (a₁ : α) (b₁ : β), sum b (λ (a₂ : α) (b₂ : β), single (a₁ + a₂) (b₁ * b₂))))
(λ (a₁ : α) (b₁ : β), sum c (λ (a₂ : α) (b₂ : β), single (a₁ + a₂) (b₁ * b₂)))
= sum a (λ (a₁ : α) (b₁ : β)
, sum (sum b (λ (a₁ : α) (b₁ : β), sum c (λ (a₂ : α) (b₂ : β), single (a₁ + a₂) (b₁ * b₂))))
(λ (a₂ : α) (b₂ : β), single (a₁ + a₂) (b₁ * b₂))),
have zero : ∀ (a' : α) (b' : β) a, (λ a b, single (a' + a) (b' * b)) a 0 = 0
:= λ _ _ a, by simp only [mul_zero, single_zero, sum_const_zero],
have add : ∀ (a' : α) (b' : β) (a : α) (b₁ b₂ : β)
, single (a' + a) (b' * (b₁ + b₂))
= single (a' + a) (b' * b₁) + single (a' + a) (b' * b₂)
:= λ _ _ a b₁ b₂, by simp only [left_distrib, single_add],
have this :
∀ (a : fin_fn α β) (f : α → β → fin_fn α β)
, sum (sum a f) (λ a₁ b₁, sum c (λ a₂ b₂, single (a₁ + a₂) (b₁ * b₂)))
= sum a (λ a b, sum (f a b) (λ a₁ b₁, sum c (λ a₂ b₂, single (a₁ + a₂) (b₁ * b₂))))
:= λ a f, sum_sum_index
(λ a, by { simp only [zero_mul, single_zero, sum_const_zero] })
(λ a b₁ b₂, by simp only [sum, right_distrib, single_add, finset.sum_add_distrib]),
simp only [this], clear this,
simp [sum_single_index, sum_sum_index (zero _ _) (add _ _), mul_assoc],
end,
..fin_fn.has_mul α β }
instance [decidable_eq α] [decidable_eq β] [add_monoid α] [comm_ring β] : monoid (fin_fn α β) :=
{ one_mul := λ a, begin
show sum (single 0 1) (λ a₁ b₁, sum a (λ a₂ b₂, single (a₁ + a₂) (b₁ * b₂))) = a,
simp,
end,
mul_one := λ a, begin
show sum a (λ a₁ b₁, sum (single (0 : α) (1 : β)) (λ a₂ b₂, single (a₁ + a₂) (b₁ * b₂))) = a,
simp,
end,
..fin_fn.has_one α β,
..fin_fn.semigroup α β }
instance [decidable_eq α] [decidable_eq β] [add_comm_monoid α] [comm_ring β] : comm_monoid (fin_fn α β) :=
{ mul_comm := λ a b, begin
show sum a (λ a₁ b₁, sum b (λ a₂ b₂, single (a₁ + a₂) (b₁ * b₂)))
= sum b (λ a₁ b₁, sum a (λ a₂ b₂, single (a₁ + a₂) (b₁ * b₂))),
suffices : sum a (λ a₁ b₁, sum b (λ a₂ b₂, single (a₁ + a₂) (b₁ * b₂)))
= sum b (λ a₁ b₁, sum a (λ a₂ b₂, single (a₂ + a₁) (b₂ * b₁))),
{ simpa only [add_comm, mul_comm] using this },
simp only [sum, finset.sum_eq_multiset_sum],
from multiset.sum_map_sum_map a.support.val b.support.val,
end
..fin_fn.monoid α β }
instance [decidable_eq α] [decidable_eq β] [has_add α] [semiring β] : mul_zero_class (fin_fn α β) :=
{ zero_mul := λ x, by simp only [has_mul.mul, sum_zero],
mul_zero := λ x, by simp only [has_mul.mul, sum_zero, sum_const_zero],
..fin_fn.has_zero α β,
..fin_fn.has_mul α β }
instance [decidable_eq α] [decidable_eq β] [has_add α] [semiring β] : distrib (fin_fn α β) :=
{ left_distrib := λ a b c, begin
show sum a (λ a₁ b₁, sum (b + c) (λ a₂ b₂, single (a₁ + a₂) (b₁ * b₂)))
= sum a (λ a₁ b₁, sum b (λ a₂ b₂, single (a₁ + a₂) (b₁ * b₂)))
+ sum a (λ a₁ b₁, sum c (λ a₂ b₂, single (a₁ + a₂) (b₁ * b₂))),
have zero : ∀ (a' : α) (b' : β) a, (λ a b, single (a' + a) (b' * b)) a 0 = 0
:= λ _ _ a, by simp only [mul_zero, single_zero, sum_const_zero],
have add : ∀ (a' : α) (b' : β) (a : α) (b₁ b₂ : β)
, single (a' + a) (b' * (b₁ + b₂))
= single (a' + a) (b' * b₁) + single (a' + a) (b' * b₂)
:= λ _ _ a b₁ b₂, by simp only [left_distrib, single_add],
simp only [sum_distrib (zero _ _) (add _ _)],
from finset.sum_add_distrib,
end,
right_distrib := λ a b c, sum_distrib
(λ a, by { simp only [zero_mul, single_zero, sum_const_zero] })
(λ a b₁ b₂, by simp only [sum, right_distrib, single_add, finset.sum_add_distrib]),
..fin_fn.has_add α β,
..fin_fn.has_mul α β }
instance [decidable_eq α] [decidable_eq β] [add_comm_monoid α] [comm_ring β] : comm_ring (fin_fn α β) :=
{ ..fin_fn.add_comm_group α β,
..fin_fn.comm_monoid α β,
..fin_fn.distrib α β }
instance [decidable_eq α] [decidable_eq β] [add_comm_monoid α] [half_ring β] : half_ring (fin_fn α β) :=
{ half := fin_fn.single 0 ½,
one_is_two_halves := ext (λ a, begin
show ite (0 = a) (1 : β) 0 = ite (0 = a) ½ 0 + ite (0 = a) ½ 0,
by_cases h : 0 = a; simp only [if_pos, if_false, h],
from half_ring.one_is_two_halves _,
from (add_zero 0).symm,
end),
..fin_fn.comm_ring _ β }
end group_instances
end fin_fn
#lint-
|
#=
Methods to simplify the plotting functionality for TS objects.
=#
const DEFAULT_COLORS = [:black, :red, :green, :blue, :cyan, :magenta, :orange, :pink]
import RecipesBase: @recipe
function beautify_string(s::String;
preserve_acronyms::Bool=true,
space_before_nums::Bool=true,
rm_underscores::Bool=true)
idx_upper = findall(isuppercase, s)
out_arr = String[string(s[1])]
@inbounds for i in 2:length(s)
if isuppercase(s[i]) && preserve_acronyms && !isuppercase(s[i-1])
push!(out_arr, " $(s[i])")
elseif isnumeric(s[i]) && space_before_nums && !isnumeric(s[i-1])
push!(out_arr, " $(s[i])")
else
push!(out_arr, string(s[i]))
end
end
return rm_underscores ? replace(join(out_arr), "_" => "") : join(out_arr)
end
function tslab(flds::Vector{Symbol}; beautify=true, args...)
arr::Vector{String} = beautify ? beautify_string.(string.(flds); args...) : string.(flds)
out::Matrix{String} = repeat([""], 1, length(flds))
@inbounds for i in 1:length(flds)
out[1,i] = arr[i]
end
return out
end
function get_xticks(t::Vector{T};
nticks::Int=5,
fmt_str::String=(T==Date ? "yyyy-mm-dd" : "yyyy-mm-ddTHH:MM:SS")) where T<:Dates.TimeType
xticks_idx::Vector{Int} = round.(Int, range(1, stop=size(t,1), length=nticks))
xticks_lab::Vector{String} = Dates.format.(t[xticks_idx], fmt_str)
return xticks_idx, xticks_lab
end
@recipe function f(X::TS)
#x = 1:size(X,1)
xticks --> get_xticks(X.index)
lab --> tslab(X.fields)
X.values
end
|
#ifndef _OPENMP
function omp_get_thread_num()
integer :: omp_get_thread_num
omp_get_thread_num = 0
end function omp_get_thread_num
#endif
module common
implicit none
double precision, parameter :: pi=3.14159265358979d0
double precision, parameter :: twopi=6.28318530717958d0
double precision, parameter :: c=2.9979d10
double precision, parameter :: e_charge=4.8032d-10
double precision, parameter :: e_mass=9.1094d-28
double precision, parameter :: p_mass=1.6726d-24
double precision, parameter :: ev=1.6022d-12
contains
! From: http://fortranwiki.org/fortran/show/newunit
! This is a simple function to search for an available unit.
! LUN_MIN and LUN_MAX define the range of possible LUNs to check.
! The UNIT value is returned by the function, and also by the optional
! argument. This allows the function to be used directly in an OPEN
! statement, and optionally save the result in a local variable.
! If no units are available, -1 is returned.
integer function newunit(unit)
integer, intent(out), optional :: unit
! local
integer, parameter :: LUN_MIN=10, LUN_MAX=1000
logical :: opened
integer :: lun
! begin
newunit=-1
do lun=LUN_MIN,LUN_MAX
inquire(unit=lun,opened=opened)
if (.not. opened) then
newunit=lun
exit
end if
end do
if (present(unit)) unit=newunit
end function newunit
end module common
|
#include "client.h"
#include <boost/asio/ssl.hpp>
#include <range/v3/all.hpp>
#include <boost/beast.hpp>
#include <utility>
namespace cacheless {
client::client(int threads, intents intents) :
m_intents(intents) ,
m_threads(std::max(threads - 1, 0)),
m_ioc(std::in_place_type<boost::asio::io_context>, threads){}
client::client(boost::asio::io_context& ioc, intents intents) :
m_intents(intents),
m_ioc(std::in_place_type<boost::asio::io_context*>, &ioc){}
void client::run() {
do_gateway_stuff();
//m_th
boost::asio::executor_work_guard work_guard(context().get_executor());
ranges::generate(m_threads, [&]() {
return std::thread([&]() {
context().run();
});
});
context().run();
int u = 0;
}
void client::stop() {
context().stop();
}
void client::set_token(std::string token, const token_type type) {
m_token = token;
switch (type) {
case token_type::BOT: m_authToken = "Bot " + std::move(token);
break;
case token_type::BEARER: m_authToken = "Bearer " + std::move(token);
break;
default: break;
}
}
void client::rate_limit_global(const std::chrono::system_clock::time_point tp) {
std::unique_lock<std::mutex> locky(m_global_rate_limit_mut, std::try_to_lock);
//only 1 shard needs to call this to rate limit every shard
if (!locky) {
return;
}
const auto now = std::chrono::system_clock::now();
if (m_last_global_rate_limit - now < std::chrono::seconds(3)) {//so i don't rate_limit myself twice
m_last_global_rate_limit = now;
//for (auto& shard : m_shards) {
// shard->rate_limit(tp);
//}
}
}
void client::do_gateway_stuff() {
m_getGateway();
for (int i = 0; i < m_num_shards; ++i) {
m_shards.emplace_back(std::make_unique<internal_shard>(i, this, context(), m_gateway, m_intents));
}
}
void client::m_getGateway() {
boost::asio::io_context ioc;//m_ioc.run is called after this finishes, so need a different ioc
boost::asio::ip::tcp::resolver resolver{ ioc };
boost::asio::ssl::context ssl_context{ boost::asio::ssl::context::tlsv12_client };
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> ssl_socket{ ioc, ssl_context };
boost::beast::flat_buffer buffer;
boost::asio::connect(ssl_socket.next_layer(), resolver.resolve("discord.com", "https"));
ssl_socket.handshake(boost::asio::ssl::stream_base::client);
boost::beast::http::request<boost::beast::http::string_body> request(boost::beast::http::verb::get, "/api/v8/gateway/bot", 11);
request.set("Application", "cerwy");
request.set(boost::beast::http::field::authorization, m_authToken);
request.set("Host", "discord.com"s);
request.set("Upgrade-Insecure-Requests", "1");
request.set(boost::beast::http::field::user_agent, "potato_world");
request.keep_alive(true);
request.set(boost::beast::http::field::accept, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
//request.set(boost::beast::http::field::accept_encoding, "gzip,deflate,br");
request.set(boost::beast::http::field::accept_language, "en-US,en;q=0.5");
request.prepare_payload();
boost::beast::http::write(ssl_socket, request);
boost::beast::http::response<boost::beast::http::string_body> response;
boost::beast::http::read(ssl_socket, buffer, response);
if (response.result_int() == 401) {
throw std::runtime_error("unauthorized. bad token?");
}
nlohmann::json yay = nlohmann::json::parse(response.body());
m_gateway = yay["url"].get<std::string>() + "/?v=8&encoding=json";
if (m_num_shards == 0) {
m_num_shards = yay["shards"].get<int>();
}
//m_num_shards = 2;
//std::cout << m_gateway << std::endl;
fmt::print(m_gateway);
fmt::print("\n");
}
}
|
Macy's, Inc. announced that its comparable sales on an owned plus licensed basis declined by 4.7% in November/December 2015 combined, compared with the same period last year.
Macy's is not expecting a major change in sales trend in January and expects a comparable sales decline on an owned plus licensed basis in the fourth quarter of 2015 to approximate the 4.7% decline in November/December. Macy's is scheduled to report fourth quarter sales and earnings on Tuesday, February 23, 2016.
In addition to their sales report, the company also outlined the cost efficiency initiatives that will take place in early 2016 and will reduce SG&A expense by approximately $400 million while still investing in growth strategies, particularly in omnichannel capabilities at Macy's and Bloomingdale's.
Implementing a voluntary separation opportunity for about 165 senior executives in Macy’s and Bloomingdale’s central stores, office and support functions who meet certain age and service requirements and chose to leave the company beginning in spring 2016. Approximately 35 percent of these executive positions will not be replaced.
Reducing an additional 600 positions in back-office organizations by eliminating tasks, simplifying processes and combining positions, with about 150 of these associates reassigned to other positions.
Consolidating the four existing Macy’s, Inc. credit and customer services center facilities into three. The call center in St. Louis will be closed in spring 2016, affecting approximately 750 employees. Work currently performed in St. Louis will be divided among existing credit and customer services centers in Tempe, AZ, Clearwater, FL, and Mason, OH, where a total of about 640 positions will be added.
Decreasing non-payroll budgets companywide in areas such as travel, meetings and consulting services. |
(* Title: HOL/HOLCF/ex/Dnat.thy
Author: Franz Regensburger
Theory for the domain of natural numbers dnat = one ++ dnat
*)
theory Dnat
imports HOLCF
begin
domain dnat = dzero | dsucc (dpred :: dnat)
definition
iterator :: "dnat \<rightarrow> ('a \<rightarrow> 'a) \<rightarrow> 'a \<rightarrow> 'a" where
"iterator = fix\<cdot>(LAM h n f x.
case n of dzero \<Rightarrow> x
| dsucc\<cdot>m \<Rightarrow> f\<cdot>(h\<cdot>m\<cdot>f\<cdot>x))"
text \<open>
\medskip Expand fixed point properties.
\<close>
lemma iterator_def2:
"iterator = (LAM n f x. case n of dzero \<Rightarrow> x | dsucc\<cdot>m \<Rightarrow> f\<cdot>(iterator\<cdot>m\<cdot>f\<cdot>x))"
apply (rule trans)
apply (rule fix_eq2)
apply (rule iterator_def [THEN eq_reflection])
apply (rule beta_cfun)
apply simp
done
text \<open>\medskip Recursive properties.\<close>
lemma iterator1: "iterator\<cdot>UU\<cdot>f\<cdot>x = UU"
apply (subst iterator_def2)
apply simp
done
lemma iterator2: "iterator\<cdot>dzero\<cdot>f\<cdot>x = x"
apply (subst iterator_def2)
apply simp
done
lemma iterator3: "n \<noteq> UU \<Longrightarrow> iterator\<cdot>(dsucc\<cdot>n)\<cdot>f\<cdot>x = f\<cdot>(iterator\<cdot>n\<cdot>f\<cdot>x)"
apply (rule trans)
apply (subst iterator_def2)
apply simp
apply (rule refl)
done
lemmas iterator_rews = iterator1 iterator2 iterator3
lemma dnat_flat: "\<forall>x y::dnat. x \<sqsubseteq> y \<longrightarrow> x = UU \<or> x = y"
apply (rule allI)
apply (induct_tac x)
apply fast
apply (rule allI)
apply (case_tac y)
apply simp
apply simp
apply simp
apply (rule allI)
apply (case_tac y)
apply (fast intro!: bottomI)
apply (thin_tac "\<forall>y. dnat \<sqsubseteq> y \<longrightarrow> dnat = UU \<or> dnat = y")
apply simp
apply (simp (no_asm_simp))
apply (drule_tac x="dnata" in spec)
apply simp
done
end
|
## Surfinpy
#### Tutorial 1 - Bulk Phase diagrams
In this tutorial we learn how to generate a basic bulk phase diagram from DFT energies. This enables the comparison of the thermodynamic stability of various different bulk phases under different chemical potentials giving valuable insight in to the syntheis of solid phases. This example will consider a series of bulk phases which can be defined through a reaction scheme across all phases, thus for this example including an example bulk phase, H<sub>2</sub>O and CO<sub>2</sub> as reactions and A as a generic product.
\begin{align}
x\text{Bulk} + y\text{H}_2\text{O} + z\text{CO}_2 \rightarrow \text{A}
\end{align}
##### Methodology
The system is in equilibrium when the chemical potentials of the reactants and product are equal; <i>i.e.</i> the change in Gibbs free energy is $\delta G_{T,p} = 0$.
\begin{align}
\delta G_{T,p} = \mu_A - x\mu_{\text{Bulk}} - y\mu_{\text{H}_2\text{O}} - z\mu_{\text{CO}_2} = 0
\end{align}
Assuming that H<sub>2</sub>O and CO<sub>2</sub> are gaseous species, $\mu_{CO_2}$ and $\mu_{H_2O}$ can be written as
\begin{align}
\mu_{\text{H}_2\text{O}} = \mu^0_{\text{H}_2\text{O}} + \Delta\mu_{\text{H}_2\text{O}}
\end{align}
and
\begin{align}
\mu_{\text{CO}_2} = \mu^0_{\text{CO}_2} + \Delta\mu_{\text{CO}_2}
\end{align}
The chemical potential $\mu^0_x$ is the partial molar free energy of any reactants or products (x) in their standard states, in this example we assume all solid components can be expressed as
\begin{align}
\mu_{\text{component}} = \mu^0_{\text{component}}
\end{align}
Hence, we can now rearrange the equations to produce;
\begin{align}
\mu^0_A - x\mu^0_{\text{Bulk}} - y\mu^0_{\text{H}_2\text{O}} - z\mu^0_{\text{CO}_2} = y\Delta\mu_{\text{H}_2\text{O}} + z\Delta\mu_{\text{CO}_2}
\end{align}
As $\mu^0_A$ corresponds to the partial molar free energy of product A, we can replace the left side with the Gibbs free energy ($\Delta G_{\text{f}}^0$).
\begin{align}
\delta G_{T,p} = \Delta G_{\text{f}}^0 - y\Delta\mu_{\text{H}_2\text{O}} - z\Delta\mu_{\text{CO}_2}
\end{align}
At equilibrium $\delta G_{T,p} = 0$, and hence
\begin{align}
\Delta G_{\text{f}}^0 = y\Delta\mu_{\text{H}_2\text{O}} + z\Delta\mu_{\text{CO}_2}
\end{align}
Thus, we can find the values of $\Delta\mu_{\text{H}_2\text{O}}$ and $\Delta\mu_{\text{CO}_2}$ (or $(p_{\text{H}_2\text{O}})^y$ and $(p_{\text{CO}_2})^z$) when solid phases are in thermodynamic equilibrium; <i>i.e.</i> they are more or less stable than bulk. This procedure can then be applied to all phases to identify which is the most stable, provided that the free energy $\Delta G_f^0$ is known for each phase.
The free energy can be calculated using
\begin{align}
\Delta G^{0}_{f} = \sum\Delta G_{f}^{0,\text{products}} - \sum\Delta G_{f}^{0,\text{reactants}}
\end{align}
Where for this tutorial the free energy (G) is equal to the calculated DFT energy (U<sub>0</sub>).
```python
import matplotlib.pyplot as plt
from surfinpy import bulk_mu_vs_mu as bmvm
from surfinpy import utils as ut
from surfinpy import data
```
The first thing to do is input the data that we have generated from our DFT simulations. The input data needs to be contained within a `surfinpy.data` object. First we have created a `surfinpy.data.ReferenceDataSet` object for the bulk data (reference data), where `cation` is the number of cations, `anion` is the number of anions, `energy` is the DFT energy and `funits` is the number of formula units.
```python
bulk = data.ReferenceDataSet(cation = 1, anion = 1, energy = -92.0, funits = 10)
```
Next we create the bulk `surfinpy.data.DataSet` objects - one for each surface or "phase". `cation` is the number of cations, `x` is in this case the number of oxygen species (corresponding to the X axis of the phase diagram), `y` is the number of in this case water molecules (corresponding to the Y axis of our phase diagram), `energy` is the DFT energy, `label` is the label for the phase (appears on the phase diagram) and finally `nSpecies` is the number of adsorbin species.
```python
Bulk = data.DataSet(cation = 10, x = 0, y = 0, energy = -92.0, label = "Bulk")
A = data.DataSet(cation = 10, x = 5, y = 20, energy = -468.0, label = "A")
B = data.DataSet(cation = 10, x = 0, y = 10, energy = -228.0, label = "B")
C = data.DataSet(cation = 10, x = 10, y = 30, energy = -706.0, label = "C")
D = data.DataSet(cation = 10, x = 10, y = 0, energy = -310.0, label = "D")
E = data.DataSet(cation = 10, x = 10, y = 50, energy = -972.0, label = "E")
F = data.DataSet(cation = 10, x = 8, y = 10, energy = -398.0, label = "F")
```
Next we need to create a list of our data. Don't worry about the order, surfinpy will sort that out for you.
```python
data = [Bulk, A, B, C, D, E, F]
```
We now need to generate our X and Y axis, or more appropriately, our chemical potential values. These exist in a dictionary. 'Range' corresponds to the range of chemcial potential values to be considered and 'Label' is the axis label. Additionally, the x and y energy need to be specified.
```
deltaX = {'Range': Range of Chemical Potential,
'Label': Species Label}
```
```python
deltaX = {'Range': [ -3, 2], 'Label': 'CO_2'}
deltaY = {'Range': [ -3, 2], 'Label': 'H_2O'}
x_energy=-20.53412969
y_energy=-12.83725889
```
And finally we can generate our plot using these 6 variables of data.
```python
system = bmvm.calculate(data, bulk, deltaX, deltaY, x_energy, y_energy)
ax = system.plot_phase(figsize=(6, 4.5))
plt.show()
```
```python
```
|
# SDE state
"""
Probabilistic SDE State
$FIELDS
"""
struct State{T<:Number}
"mean z"
μ::Vector{T}
"covariance matrix"
Σ::Matrix{T}
function State(μ::Vector{T},Σ::Matrix{T}) where {T}
p = length(μ)
LinearAlgebra.checksquare(Σ)==p || error("Σ must be $p-by-$p")
new{T}(μ,Σ)
end
end
State(μ::Vector,Σ::Matrix) = State(promote(μ,Σ)...)
function Base.show(io::IO,ss::State{T}) where {T}
elstr = if T<:Complex
x->@sprintf("%0.3g+%0.3gim",real(x),imag(x))
else
x->@sprintf("%0.3g",x)
end
μs = elstr.(ss.μ)
μstr = join(μs," ")
Σstr = if iszero(ss.Σ)
0
else
Σs = elstr.(ss.Σ)
rows = join.(eachrow(Σs)," ")
Σstr = join(rows,"; ")
"["*Σstr*"]"
end
print(io,"μ = [",μstr,"] | Σ ",Σstr)
end
function Base.convert(::Type{State{T}},x::State) where {T}
return State(convert(AbstractVector{T},x.μ),convert(AbstractMatrix{T},x.Σ))
end
Distributions.dim(state::State) = length(state.μ)
function Statistics.mean(states::Vector{<:State})
μ = mean(getproperty.(states,:μ))
Σ = mean(getproperty.(states,:Σ))
return State(μ,Σ)
end
Base.rand(rng::AbstractRNG,state::State) = semiposdef_mvrand(rng,state.μ,state.Σ)
function State(Σ::AbstractMatrix{T}) where {T}
p = size(Σ,1)
μ = zeros(T,p)
return State(μ,Σ)
end
function State(μ::AbstractVector{T}) where {T}
p = length(μ)
Σ = zeros(T,p,p)
return State(μ,Σ)
end
import Base.:(==)
x::State==y::State = x.μ==y.μ && x.Σ==y.Σ
Base.hash(x::State, h::UInt) = hash(x.μ, hash(x.Σ, h))
Base.isapprox(x::State,y::State;kwargs...) = isapprox(x.μ,y.μ;kwargs...) && isapprox(x.Σ,y.Σ;kwargs...)
# """
# $SIGNATURES
# State of order `p`and compatible with data `y` and zero elsewhere
# """
# function compatiblestate(p,y)
# z = similar(y,p)
# z[:] .= 0
# z[1] = y[1]
# return State(z)
# end
# iscompatible(state::State,y) = !iszero(state.Σ) || state.μ[1]==y[1]
# function checkcompatible(state::State,y)
# iscompatible(state,y) || error("state $state incompatible with data")
# return state
# end
"
$(SIGNATURES)
Return deterministic state value. Throws an error if the state is not deterministic
"
function detstate(ss::State)
if !iszero(ss.Σ) error("Not a deterministic state") end
return ss.μ
end
|
# --------------
#Importing header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Code starts here
data = pd.read_csv(path)
loan_status= data['Loan_Status'].value_counts()
print(loan_status)
loan_status.plot(kind='bar')
# --------------
#Code starts here
property_and_loan=data.groupby(['Property_Area','Loan_Status']).size().unstack()
print(property_and_loan)
property_and_loan.plot(kind='bar',stacked=False,figsize=(15,10))
plt.xticks(rotation=45)
# --------------
#Code starts here
education_and_loan=data.groupby(['Education','Loan_Status']).size().unstack()
education_and_loan.plot(stacked=True,kind='bar',figsize=(15,10))
plt.xticks(rotation=45)
# --------------
#Code starts here
graduate=data[data['Education']=='Graduate']
not_graduate=data[data['Education'] == 'Not Graduate']
graduate['LoanAmount'].plot(kind='density',label='Graduate')
not_graduate['LoanAmount'].plot(kind='density',label='Not Graduate')
#Code ends here
#For automatic legend display
plt.legend()
# --------------
#Code starts here
fig ,(ax_1,ax_2,ax_3)=plt.subplots(1,3, figsize=(20,10))
data.plot.scatter(x='ApplicantIncome',y='LoanAmount',ax=ax_1)
data.plot.scatter(x='CoapplicantIncome',y='LoanAmount',ax=ax_2)
data['TotalIncome']=data['ApplicantIncome']+data['CoapplicantIncome']
data.plot.scatter(x='TotalIncome',y='LoanAmount',ax=ax_3)
|
[STATEMENT]
lemma lfilter_unique:
assumes "\<And>xs. f xs = (if \<forall>x\<in>lset xs. \<not> P x then LNil
else if P (lhd xs) then LCons (lhd xs) (f (ltl xs))
else f (ltl xs))"
shows "f = lfilter P"
\<comment> \<open>It seems as if we cannot use @{thm lfilter_unique_weak} for showing this as the induction and the coinduction must be nested\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. f = lfilter P
[PROOF STEP]
proof(rule ext)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. f x = lfilter P x
[PROOF STEP]
show "f xs = lfilter P xs" for xs
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. f xs = lfilter P xs
[PROOF STEP]
proof(coinduction arbitrary: xs)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>xs. (f xs = LNil) = (lfilter P xs = LNil) \<and> (f xs \<noteq> LNil \<longrightarrow> lfilter P xs \<noteq> LNil \<longrightarrow> lhd (f xs) = lhd (lfilter P xs) \<and> (\<exists>xsa. ltl (f xs) = f xsa \<and> ltl (lfilter P xs) = lfilter P xsa))
[PROOF STEP]
case (Eq_llist xs)
[PROOF STATE]
proof (state)
this:
goal (1 subgoal):
1. \<And>xs. (f xs = LNil) = (lfilter P xs = LNil) \<and> (f xs \<noteq> LNil \<longrightarrow> lfilter P xs \<noteq> LNil \<longrightarrow> lhd (f xs) = lhd (lfilter P xs) \<and> (\<exists>xsa. ltl (f xs) = f xsa \<and> ltl (lfilter P xs) = lfilter P xsa))
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (f xs = LNil) = (lfilter P xs = LNil) \<and> (f xs \<noteq> LNil \<longrightarrow> lfilter P xs \<noteq> LNil \<longrightarrow> lhd (f xs) = lhd (lfilter P xs) \<and> (\<exists>xs. ltl (f xs) = f xs \<and> ltl (lfilter P xs) = lfilter P xs))
[PROOF STEP]
apply(induction arg\<equiv>"(P, xs)" arbitrary: xs rule: lfilter.inner_induct)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>xs. (\<And>y. \<lbrakk>(P, y) = (P, xs); \<not> (\<forall>x\<in>lset y. \<not> P x); \<not> P (lhd y)\<rbrakk> \<Longrightarrow> (f (ltl y) = LNil) = (lfilter P (ltl y) = LNil) \<and> (f (ltl y) \<noteq> LNil \<longrightarrow> lfilter P (ltl y) \<noteq> LNil \<longrightarrow> lhd (f (ltl y)) = lhd (lfilter P (ltl y)) \<and> (\<exists>xs. ltl (f (ltl y)) = f xs \<and> ltl (lfilter P (ltl y)) = lfilter P xs))) \<Longrightarrow> (f xs = LNil) = (lfilter P xs = LNil) \<and> (f xs \<noteq> LNil \<longrightarrow> lfilter P xs \<noteq> LNil \<longrightarrow> lhd (f xs) = lhd (lfilter P xs) \<and> (\<exists>xsa. ltl (f xs) = f xsa \<and> ltl (lfilter P xs) = lfilter P xsa))
[PROOF STEP]
apply(subst (1 2 3 4) assms)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>xs. (\<And>y. \<lbrakk>(P, y) = (P, xs); \<not> (\<forall>x\<in>lset y. \<not> P x); \<not> P (lhd y)\<rbrakk> \<Longrightarrow> (f (ltl y) = LNil) = (lfilter P (ltl y) = LNil) \<and> (f (ltl y) \<noteq> LNil \<longrightarrow> lfilter P (ltl y) \<noteq> LNil \<longrightarrow> lhd (f (ltl y)) = lhd (lfilter P (ltl y)) \<and> (\<exists>xs. ltl (f (ltl y)) = f xs \<and> ltl (lfilter P (ltl y)) = lfilter P xs))) \<Longrightarrow> ((if \<forall>x\<in>lset xs. \<not> P x then LNil else if P (lhd xs) then LCons (lhd xs) (f (ltl xs)) else f (ltl xs)) = LNil) = (lfilter P xs = LNil) \<and> ((if \<forall>x\<in>lset xs. \<not> P x then LNil else if P (lhd xs) then LCons (lhd xs) (f (ltl xs)) else f (ltl xs)) \<noteq> LNil \<longrightarrow> lfilter P xs \<noteq> LNil \<longrightarrow> lhd (if \<forall>x\<in>lset xs. \<not> P x then LNil else if P (lhd xs) then LCons (lhd xs) (f (ltl xs)) else f (ltl xs)) = lhd (lfilter P xs) \<and> (\<exists>xsa. ltl (if \<forall>x\<in>lset xs. \<not> P x then LNil else if P (lhd xs) then LCons (lhd xs) (f (ltl xs)) else f (ltl xs)) = f xsa \<and> ltl (lfilter P xs) = lfilter P xsa))
[PROOF STEP]
apply(subst (1 2 3 4) lfilter.code)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>xs. (\<And>y. \<lbrakk>(P, y) = (P, xs); \<not> (\<forall>x\<in>lset y. \<not> P x); \<not> P (lhd y)\<rbrakk> \<Longrightarrow> (f (ltl y) = LNil) = (lfilter P (ltl y) = LNil) \<and> (f (ltl y) \<noteq> LNil \<longrightarrow> lfilter P (ltl y) \<noteq> LNil \<longrightarrow> lhd (f (ltl y)) = lhd (lfilter P (ltl y)) \<and> (\<exists>xs. ltl (f (ltl y)) = f xs \<and> ltl (lfilter P (ltl y)) = lfilter P xs))) \<Longrightarrow> ((if \<forall>x\<in>lset xs. \<not> P x then LNil else if P (lhd xs) then LCons (lhd xs) (f (ltl xs)) else f (ltl xs)) = LNil) = ((if \<forall>x\<in>lset xs. \<not> P x then LNil else if P (lhd xs) then LCons (lhd xs) (lfilter P (ltl xs)) else lfilter P (ltl xs)) = LNil) \<and> ((if \<forall>x\<in>lset xs. \<not> P x then LNil else if P (lhd xs) then LCons (lhd xs) (f (ltl xs)) else f (ltl xs)) \<noteq> LNil \<longrightarrow> (if \<forall>x\<in>lset xs. \<not> P x then LNil else if P (lhd xs) then LCons (lhd xs) (lfilter P (ltl xs)) else lfilter P (ltl xs)) \<noteq> LNil \<longrightarrow> lhd (if \<forall>x\<in>lset xs. \<not> P x then LNil else if P (lhd xs) then LCons (lhd xs) (f (ltl xs)) else f (ltl xs)) = lhd (if \<forall>x\<in>lset xs. \<not> P x then LNil else if P (lhd xs) then LCons (lhd xs) (lfilter P (ltl xs)) else lfilter P (ltl xs)) \<and> (\<exists>xsa. ltl (if \<forall>x\<in>lset xs. \<not> P x then LNil else if P (lhd xs) then LCons (lhd xs) (f (ltl xs)) else f (ltl xs)) = f xsa \<and> ltl (if \<forall>x\<in>lset xs. \<not> P x then LNil else if P (lhd xs) then LCons (lhd xs) (lfilter P (ltl xs)) else lfilter P (ltl xs)) = lfilter P xsa))
[PROOF STEP]
apply auto
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
[PROOF STATE]
proof (state)
this:
(f xs = LNil) = (lfilter P xs = LNil) \<and> (f xs \<noteq> LNil \<longrightarrow> lfilter P xs \<noteq> LNil \<longrightarrow> lhd (f xs) = lhd (lfilter P xs) \<and> (\<exists>xs. ltl (f xs) = f xs \<and> ltl (lfilter P xs) = lfilter P xs))
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
f ?xs = lfilter P ?xs
goal:
No subgoals!
[PROOF STEP]
qed |
program t
do i=1,3
print *,i
end do
end program t
|
# Bayes' Theorem
## Motivating Examples - Limitations of Machine Learning and (frequentist) Statistics
(1) Consider a model for detection of fraud in financial transactions. We trained and validated such a model using (labelled) data from the past. The model is deployed in production and predicts a given transaction to be fraud. Knowing our model's True and False Positive Rates, and having an estimate of the frequency of fraud, what is the _probability_ that this transaction is actually fraudulent?
(2) Consider we observe a few thousand heart rate measurements from a person's last running activity. What is the _probability_ (interval) that the observed mean and variance in this sample represent this person's true distribution of exercise intensity? How does this inference change if we have prior knowledge (e.g. population data)?
ML and stats tools lack common ways to:
- Express uncertainty about inference of parameters,
- Express uncertainty about predictions,
- Use **and make explicit** (subjective) prior knowledge for inference
## The basics: Probability Mass/Density Functions
A **random variable** $X$ can be:
### Discrete:
$X \in \{Red, Black\}$, with **probability mass function (PMF)**
<div style="font-size: 2em">
$$
p(x) =
\begin{cases}
0.8,&x = Red\\
0.2,&x = Black\\
0,&otherwise
\end{cases}
$$
</div
```python
def pmf(x):
return {
'Red': 0.8,
'Black': 0.2
}.get(x, 0.0)
```
### Continuous:
$X \in [30, 230]$, with probability **density** function **(PDF)**, assuming a normal distribution with:
* mean $\bbox[1pt,border:2px solid red]{\mu} = 120$,
* variance $\bbox[1pt,border:2px solid blue]{\sigma^2} = 400$
<div style="font-size: 2em">
$$p(x) = \frac{1}{\sqrt{2\pi\bbox[1pt,border:2px solid blue]{400}}}e^{-\frac{(x - \bbox[1pt,border:2px solid red]{120})^2}{2*\bbox[1pt,border:2px solid blue]{400}}}$$
</div>
Be aware there are [many more](https://en.wikipedia.org/wiki/List_of_probability_distributions) types of probability distributions.
```python
# No need to implement these PDFs yourselves, see scipy.stats
import numpy as np
from scipy.stats import norm
heart_rate_mean = 120
heart_rate_std = 20
norm.pdf(130, loc=heart_rate_mean, scale=heart_rate_std)
```
```python
# For reuse of the same distribution params, a distribution can be _frozen_:
norm_hr = norm(loc=heart_rate_mean, scale=heart_rate_std)
norm_hr.pdf(130)
```
- What does this value mean?
- Is it a probability?
- What is the probability $Pr(X = 120)$, where $X$ is _exactly_ 120?
---
```python
import plotly.graph_objs as go
x=np.linspace(30, 230, 100)
go.FigureWidget(
data=[
go.Scatter(x=x, y=norm_hr.pdf(x), mode='lines', line={'shape': 'spline', 'width': 4}, showlegend=False),
go.Scatter(x=[130, 155], y=norm_hr.pdf([130, 155]), mode='markers', marker={'size': 8}, showlegend=False)
],
layout={
'width': 800,
'title': 'p(X), for μ=120, σ=20',
'xaxis': {'title': 'X'},
'yaxis': {'title': 'p(X)'}
}
)
```
A PDF gives the **relative likelihood** of $X$ having a given value:
```python
norm_hr.pdf(130) / norm_hr.pdf(155)
```
meaning that with $\mu=120$ and $\sigma=20$, a heart rate of 130 is around 4 times more likely than a heart rate of 155.
### Probabilities from PDF's
You can derive probabilities from PDFs by integration:
$$Pr(100 \le X \le 120) = \int_{100}^{120}p(x)$$
And for a valid PDF:
$$ \int_{-\infty}^{\infty}p(x) = 1$$
The integral of a PDF is called a **Cumulative Distribution Function (CDF)**.
## Adding 1 Dimension: Joint and Conditional Probability
The joint probability density of 2 random variables $A$ and $B$ is given as
<div style="font-size: 2em">
$$
p(A, B) = p(A|B)p(B)
$$
</div>
where $p(A|B)$ represents the density of $A$, **given** $B$, or **conditioned on** $B$.
How should $p(A, B)$, or $p(A|B)$ be interpreted?
Let's use maximum heart rates as an example. A person's maximum heart rate usually decreases with age. A commonly mentioned formula to estimate maximum heart rate is 220 - age, (see [wikipedia](https://en.wikipedia.org/wiki/Heart_rate#Haskell_&_Fox)).
```python
def to_max_heart_rate(age):
return 220 - age
```
This method is a gross oversimplification and shouldn't be used in practice, but serves well for this example.
```python
ages = np.linspace(15, 85, 100) # simulate 100 users of some fitness app, ages "uniformly" distributed between 15 and 85
max_heart_rate_means = to_max_heart_rate(ages)
```
```python
y = np.linspace(130, 250, 100)
max_heart_rate_densities = np.array([norm.pdf(y, loc=age_hr, scale=10) for age_hr in max_heart_rate_means])
```
```python
go.FigureWidget(
data=[
go.Surface(x=ages, y=y, z=max_heart_rate_densities)
],
layout=go.Layout(
width=600,
height=600,
xaxis=dict(title='age'),
yaxis=dict(title='hr max')
)
)
```
$p(H,A)$ represents the relative likelihood that age ($A$) and heart rate ($H$) have some values **simultaneously**. For discrete random variables, the joint PMF is a 2-d lookup table.
$p(H|A=a)$ represents the relative likelihood of a heart rate for a fixed age (imagine a slice cutting through the sphere above, going through x=a). This results in a single-variable PDF.
Similar to 1-d PDFs, probabilities can be obtained by (double) integration.
If $A$ and $B$ are **independent**, $p(A|B) = p(A)$. Most often, this is _not_ the case, so don't interpret $p(A,B)$ as being as simple as $p(A) \times p(B)$
## Since Variable Order Doesn't Matter...
<div style="font-size: 2em">
$$
\begin{align}
p(A,B) &= p(B,A)\Leftrightarrow\\
p(A|B)p(B) &= p(B|A)p(A)\Leftrightarrow
\end{align}
$$
</div>
<div style="font-size: 3em">
$$
p(A|B) = \frac{p(B|A)p(A)}{p(B)}
$$
</div>
a.k.a. **Bayes' Theorem**, or **Bayes' Rule**.
## That Fraud Detection Model
Let's try to plug our initial question about our fraud detection model into this formula. There are 2 (discrete) random variables involved:
- Transaction Fraud ($F \in \{Fraud, OK\}$)
- Model Alert ($A \in \{Alert, OK\}$)
Having trained and validated our model using historical data, we obtained a confusion matrix that looks as follows:
| predicted\true| fraud | ok |
|---------------|-------|--------|
| predict_fraud | 0.95 | 0.0001 |
| predict_ok | 0.05 | 0.9999 |
Further, we know from past experience, that roughly 1 in a million transactions are fraudulent, i.e. $p(F=Fraud) = 0.000001$
We are interested in the probability $p(F=Fraud|A=Alert)$
According to Bayes' Theorem, this is equal to:
$$
\frac{\bbox[1pt,border:2px solid red]{p(A=Alert|F=Fraud)}\times\bbox[1pt,border:2px solid yellow]{p(F=Fraud)}}{\bbox[1pt,border:2px solid blue]{p(A=Alert)}}
$$
with
$$
\begin{align}
p(A=Alert) & = \sum_{f \in F}p(A=Alert|f).p(f)\\
& = 0.95\times0.000001 + 0.0001\times0.999999\\
& \approx 0.0001 \\
\end{align}
$$
which leads to
$$
p(F=Fraud|A=Alert) = \frac{\bbox[1pt,border:2px solid red]{0.95}\times\bbox[1pt,border:2px solid yellow]{0.000001}}{\bbox[1pt,border:2px solid blue]{0.0001}} \approx 0.01
$$
```python
def p_fraud_given_alert(p_fraud, true_positive_rate, false_positive_rate):
return true_positive_rate * p_fraud / (true_positive_rate * p_fraud + false_positive_rate * (1 - p_fraud))
p_fraud_given_alert(0.001, 0.95, 0.0001)
```
```python
p_fraud_given_alert(0.0001, 0.95, 0.0001)
```
```python
p_fraud_given_alert(0.00001, 0.95, 0.0001)
```
To conclude, the first application of Bayes' Rule is for cases where (for discrete events) we can directly measure some conditional probability $p(B|A)$, and prior probabilities $p(A)$ and $p(B)$, but our probability of interest $p(A|B)$ is less straightforward.
## (Social) Sience, Null Hypothesis Significance Tests, and that P Value
- What's the meaning of the P value in a significance test? (I dare you!)
- Given some P value, can we infer anything about the **probability** of the Null Hypothesis (or Alternative Hypothesis) being true?
- Can we express statements about P values in terms of $p(\text{Hypothesis}\mid\text{Data})$, or $p(\text{Data}\mid\text{Hypothesis})$
|
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝¹ : DecidableEq M
inst✝ : CommSemiring R
f : M → ι
i : ι
m : M
h : m ∈ 0.support
⊢ f m = i
[PROOFSTEP]
cases h
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝¹ : DecidableEq M
inst✝ : CommSemiring R
⊢ gradeBy R id = grade R
[PROOFSTEP]
rfl
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝¹ : DecidableEq M
inst✝ : CommSemiring R
f : M → ι
i : ι
a : AddMonoidAlgebra R M
⊢ a ∈ gradeBy R f i ↔ ↑a.support ⊆ f ⁻¹' {i}
[PROOFSTEP]
rfl
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝¹ : DecidableEq M
inst✝ : CommSemiring R
m : M
a : AddMonoidAlgebra R M
⊢ a ∈ grade R m ↔ a.support ⊆ {m}
[PROOFSTEP]
rw [← Finset.coe_subset, Finset.coe_singleton]
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝¹ : DecidableEq M
inst✝ : CommSemiring R
m : M
a : AddMonoidAlgebra R M
⊢ a ∈ grade R m ↔ ↑a.support ⊆ {m}
[PROOFSTEP]
rfl
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝¹ : DecidableEq M
inst✝ : CommSemiring R
m : M
a : AddMonoidAlgebra R M
⊢ a ∈ grade R m ↔ a ∈ LinearMap.range (Finsupp.lsingle m)
[PROOFSTEP]
rw [mem_grade_iff, Finsupp.support_subset_singleton']
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝¹ : DecidableEq M
inst✝ : CommSemiring R
m : M
a : AddMonoidAlgebra R M
⊢ (∃ b, a = Finsupp.single m b) ↔ a ∈ LinearMap.range (Finsupp.lsingle m)
[PROOFSTEP]
apply exists_congr
[GOAL]
case h
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝¹ : DecidableEq M
inst✝ : CommSemiring R
m : M
a : AddMonoidAlgebra R M
⊢ ∀ (a_1 : R), a = Finsupp.single m a_1 ↔ ↑(Finsupp.lsingle m) a_1 = a
[PROOFSTEP]
intro r
[GOAL]
case h
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝¹ : DecidableEq M
inst✝ : CommSemiring R
m : M
a : AddMonoidAlgebra R M
r : R
⊢ a = Finsupp.single m r ↔ ↑(Finsupp.lsingle m) r = a
[PROOFSTEP]
constructor
[GOAL]
case h.mp
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝¹ : DecidableEq M
inst✝ : CommSemiring R
m : M
a : AddMonoidAlgebra R M
r : R
⊢ a = Finsupp.single m r → ↑(Finsupp.lsingle m) r = a
[PROOFSTEP]
exact Eq.symm
[GOAL]
case h.mpr
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝¹ : DecidableEq M
inst✝ : CommSemiring R
m : M
a : AddMonoidAlgebra R M
r : R
⊢ ↑(Finsupp.lsingle m) r = a → a = Finsupp.single m r
[PROOFSTEP]
exact Eq.symm
[GOAL]
M : Type u_1
ι : Type u_2
R✝ : Type u_3
inst✝² : DecidableEq M
inst✝¹ : CommSemiring R✝
R : Type u_4
inst✝ : CommSemiring R
f : M → ι
m : M
r : R
⊢ Finsupp.single m r ∈ gradeBy R f (f m)
[PROOFSTEP]
intro x hx
[GOAL]
M : Type u_1
ι : Type u_2
R✝ : Type u_3
inst✝² : DecidableEq M
inst✝¹ : CommSemiring R✝
R : Type u_4
inst✝ : CommSemiring R
f : M → ι
m : M
r : R
x : M
hx : x ∈ (Finsupp.single m r).support
⊢ f x = f m
[PROOFSTEP]
rw [Finset.mem_singleton.mp (Finsupp.support_single_subset hx)]
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝³ : DecidableEq M
inst✝² : AddMonoid M
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
m : M
h : m ∈ 1.support
⊢ ↑f m = 0
[PROOFSTEP]
rw [one_def] at h
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝³ : DecidableEq M
inst✝² : AddMonoid M
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
m : M
h : m ∈ (single 0 1).support
⊢ ↑f m = 0
[PROOFSTEP]
by_cases H : (1 : R) = (0 : R)
[GOAL]
case pos
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝³ : DecidableEq M
inst✝² : AddMonoid M
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
m : M
h : m ∈ (single 0 1).support
H : 1 = 0
⊢ ↑f m = 0
[PROOFSTEP]
rw [H, single, Finsupp.single_zero] at h
[GOAL]
case pos
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝³ : DecidableEq M
inst✝² : AddMonoid M
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
m : M
h : m ∈ 0.support
H : 1 = 0
⊢ ↑f m = 0
[PROOFSTEP]
cases h
[GOAL]
case neg
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝³ : DecidableEq M
inst✝² : AddMonoid M
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
m : M
h : m ∈ (single 0 1).support
H : ¬1 = 0
⊢ ↑f m = 0
[PROOFSTEP]
rw [Finsupp.support_single_ne_zero _ H, Finset.mem_singleton] at h
[GOAL]
case neg
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝³ : DecidableEq M
inst✝² : AddMonoid M
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
m : M
h : m = 0
H : ¬1 = 0
⊢ ↑f m = 0
[PROOFSTEP]
rw [h, AddMonoidHom.map_zero]
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝³ : DecidableEq M
inst✝² : AddMonoid M
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : ι
a b : AddMonoidAlgebra R M
ha : a ∈ gradeBy R (↑f) i
hb : b ∈ gradeBy R (↑f) j
c : M
hc : c ∈ (a * b).support
⊢ ↑f c = i + j
[PROOFSTEP]
set h := support_mul a b hc
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝³ : DecidableEq M
inst✝² : AddMonoid M
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : ι
a b : AddMonoidAlgebra R M
ha : a ∈ gradeBy R (↑f) i
hb : b ∈ gradeBy R (↑f) j
c : M
hc : c ∈ (a * b).support
h : c ∈ Finset.biUnion a.support fun a₁ => Finset.biUnion b.support fun a₂ => {a₁ + a₂} := support_mul a b hc
⊢ ↑f c = i + j
[PROOFSTEP]
simp only [Finset.mem_biUnion] at h
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝³ : DecidableEq M
inst✝² : AddMonoid M
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : ι
a b : AddMonoidAlgebra R M
ha : a ∈ gradeBy R (↑f) i
hb : b ∈ gradeBy R (↑f) j
c : M
hc : c ∈ (a * b).support
h : ∃ a_1, a_1 ∈ a.support ∧ ∃ a, a ∈ b.support ∧ c ∈ {a_1 + a}
⊢ ↑f c = i + j
[PROOFSTEP]
rcases h with ⟨ma, ⟨hma, ⟨mb, ⟨hmb, hmc⟩⟩⟩⟩
[GOAL]
case intro.intro.intro.intro
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝³ : DecidableEq M
inst✝² : AddMonoid M
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : ι
a b : AddMonoidAlgebra R M
ha : a ∈ gradeBy R (↑f) i
hb : b ∈ gradeBy R (↑f) j
c : M
hc : c ∈ (a * b).support
ma : M
hma : ma ∈ a.support
mb : M
hmb : mb ∈ b.support
hmc : c ∈ {ma + mb}
⊢ ↑f c = i + j
[PROOFSTEP]
rw [← ha ma hma, ← hb mb hmb, Finset.mem_singleton.mp hmc]
[GOAL]
case intro.intro.intro.intro
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝³ : DecidableEq M
inst✝² : AddMonoid M
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : ι
a b : AddMonoidAlgebra R M
ha : a ∈ gradeBy R (↑f) i
hb : b ∈ gradeBy R (↑f) j
c : M
hc : c ∈ (a * b).support
ma : M
hma : ma ∈ a.support
mb : M
hmb : mb ∈ b.support
hmc : c ∈ {ma + mb}
⊢ ↑f (ma + mb) = ↑f ma + ↑f mb
[PROOFSTEP]
apply AddMonoidHom.map_add
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝² : DecidableEq M
inst✝¹ : AddMonoid M
inst✝ : CommSemiring R
⊢ SetLike.GradedMonoid (grade R)
[PROOFSTEP]
apply gradeBy.gradedMonoid (AddMonoidHom.id _)
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
⊢ GradedMonoid.mk (↑f (↑Multiplicative.toAdd 1))
{ val := Finsupp.single (↑Multiplicative.toAdd 1) 1,
property := (_ : Finsupp.single (↑Multiplicative.toAdd 1) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd 1))) } =
GradedMonoid.mk 0 GradedMonoid.GOne.one
[PROOFSTEP]
congr 2
[GOAL]
case h.e_3.h
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
⊢ ↑f (↑Multiplicative.toAdd 1) = 0
[PROOFSTEP]
simp
[GOAL]
case h.e_4.e_2.h
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
⊢ (fun x => x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd 1))) = fun x => x ∈ (fun i => gradeBy R (↑f) i) 0
[PROOFSTEP]
simp
[GOAL]
case h.e_4.e_4
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
⊢ HEq (_ : Finsupp.single (↑Multiplicative.toAdd 1) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd 1)))
(_ : 1 ∈ gradeBy R (↑f) 0)
[PROOFSTEP]
simp
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
⊢ OneHom.toFun
{
toFun := fun m =>
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd m)))
{ val := Finsupp.single (↑Multiplicative.toAdd m) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd m) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd m))) },
map_one' :=
(_ :
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd 1)))
{ val := Finsupp.single (↑Multiplicative.toAdd 1) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd 1) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd 1))) } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) 0) GradedMonoid.GOne.one) }
(i * j) =
OneHom.toFun
{
toFun := fun m =>
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd m)))
{ val := Finsupp.single (↑Multiplicative.toAdd m) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd m) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd m))) },
map_one' :=
(_ :
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd 1)))
{ val := Finsupp.single (↑Multiplicative.toAdd 1) 1,
property :=
(_ :
Finsupp.single (↑Multiplicative.toAdd 1) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd 1))) } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) 0) GradedMonoid.GOne.one) }
i *
OneHom.toFun
{
toFun := fun m =>
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd m)))
{ val := Finsupp.single (↑Multiplicative.toAdd m) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd m) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd m))) },
map_one' :=
(_ :
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd 1)))
{ val := Finsupp.single (↑Multiplicative.toAdd 1) 1,
property :=
(_ :
Finsupp.single (↑Multiplicative.toAdd 1) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd 1))) } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) 0) GradedMonoid.GOne.one) }
j
[PROOFSTEP]
symm
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
⊢ OneHom.toFun
{
toFun := fun m =>
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd m)))
{ val := Finsupp.single (↑Multiplicative.toAdd m) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd m) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd m))) },
map_one' :=
(_ :
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd 1)))
{ val := Finsupp.single (↑Multiplicative.toAdd 1) 1,
property :=
(_ :
Finsupp.single (↑Multiplicative.toAdd 1) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd 1))) } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) 0) GradedMonoid.GOne.one) }
i *
OneHom.toFun
{
toFun := fun m =>
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd m)))
{ val := Finsupp.single (↑Multiplicative.toAdd m) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd m) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd m))) },
map_one' :=
(_ :
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd 1)))
{ val := Finsupp.single (↑Multiplicative.toAdd 1) 1,
property :=
(_ :
Finsupp.single (↑Multiplicative.toAdd 1) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd 1))) } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) 0) GradedMonoid.GOne.one) }
j =
OneHom.toFun
{
toFun := fun m =>
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd m)))
{ val := Finsupp.single (↑Multiplicative.toAdd m) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd m) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd m))) },
map_one' :=
(_ :
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd 1)))
{ val := Finsupp.single (↑Multiplicative.toAdd 1) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd 1) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd 1))) } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) 0) GradedMonoid.GOne.one) }
(i * j)
[PROOFSTEP]
dsimp only [toAdd_one, Eq.ndrec, Set.mem_setOf_eq, ne_eq, OneHom.toFun_eq_coe, OneHom.coe_mk, toAdd_mul]
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
⊢ ↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd i)))
{ val := Finsupp.single (↑Multiplicative.toAdd i) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd i) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i))) } *
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd j)))
{ val := Finsupp.single (↑Multiplicative.toAdd j) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd j) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd j))) } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)))
{ val := Finsupp.single (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) 1,
property :=
(_ :
Finsupp.single (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) 1 ∈
gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j))) }
[PROOFSTEP]
convert DirectSum.of_mul_of (A := (fun i : ι => gradeBy R f i)) _ _
[GOAL]
case h.e'_3.h.e'_1.h.e'_1.h.e'_2.h.h.e'_5.h.e'_7
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
x✝ : AddMonoidAlgebra R M
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_1.h.e'_3.e'_2.e'_2.e'_8
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_2.h.e'_2.h.h.e'_5.h.e'_7
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
x✝ : AddMonoidAlgebra R M
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_4.e'_4.e'_2.e'_2.e'_2.e'_8
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝¹ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝¹ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_3✝ : HEq (fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_1✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_4.e'_6.e'_4.e'_2.e'_2.e'_8
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝² :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝¹ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_3✝ : HEq (fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }
e_1✝¹ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_4✝ : HEq AddZeroClass.toAdd AddZeroClass.toAdd
e_1✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_5.e'_5
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_6.e'_2.h.h.e'_5.h.e'_7
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
x✝ : AddMonoidAlgebra R M
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_6.e'_3
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ Finsupp.single (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) 1 =
↑(GradedMonoid.GMul.mul
{ val := Finsupp.single (↑Multiplicative.toAdd i) 1,
property := (_ : Finsupp.single (↑Multiplicative.toAdd i) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i))) }
{ val := Finsupp.single (↑Multiplicative.toAdd j) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd j) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd j))) })
[PROOFSTEP]
repeat {rw [AddMonoidHom.map_add]
}
[GOAL]
case h.e'_3.h.e'_1.h.e'_1.h.e'_2.h.h.e'_5.h.e'_7
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
x✝ : AddMonoidAlgebra R M
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_1.h.e'_3.e'_2.e'_2.e'_8
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_2.h.e'_2.h.h.e'_5.h.e'_7
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
x✝ : AddMonoidAlgebra R M
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_4.e'_4.e'_2.e'_2.e'_2.e'_8
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝¹ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝¹ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_3✝ : HEq (fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_1✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_4.e'_6.e'_4.e'_2.e'_2.e'_8
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝² :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝¹ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_3✝ : HEq (fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }
e_1✝¹ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_4✝ : HEq AddZeroClass.toAdd AddZeroClass.toAdd
e_1✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_5.e'_5
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_6.e'_2.h.h.e'_5.h.e'_7
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
x✝ : AddMonoidAlgebra R M
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_6.e'_3
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ Finsupp.single (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) 1 =
↑(GradedMonoid.GMul.mul
{ val := Finsupp.single (↑Multiplicative.toAdd i) 1,
property := (_ : Finsupp.single (↑Multiplicative.toAdd i) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i))) }
{ val := Finsupp.single (↑Multiplicative.toAdd j) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd j) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd j))) })
[PROOFSTEP]
{rw [AddMonoidHom.map_add]
}
[GOAL]
case h.e'_3.h.e'_1.h.e'_1.h.e'_2.h.h.e'_5.h.e'_7
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
x✝ : AddMonoidAlgebra R M
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
[PROOFSTEP]
rw [AddMonoidHom.map_add]
[GOAL]
case h.e'_3.h.e'_1.h.e'_3.e'_2.e'_2.e'_8
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_2.h.e'_2.h.h.e'_5.h.e'_7
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
x✝ : AddMonoidAlgebra R M
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_4.e'_4.e'_2.e'_2.e'_2.e'_8
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝¹ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝¹ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_3✝ : HEq (fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_1✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_4.e'_6.e'_4.e'_2.e'_2.e'_8
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝² :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝¹ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_3✝ : HEq (fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }
e_1✝¹ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_4✝ : HEq AddZeroClass.toAdd AddZeroClass.toAdd
e_1✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_5.e'_5
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_6.e'_2.h.h.e'_5.h.e'_7
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
x✝ : AddMonoidAlgebra R M
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_6.e'_3
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ Finsupp.single (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) 1 =
↑(GradedMonoid.GMul.mul
{ val := Finsupp.single (↑Multiplicative.toAdd i) 1,
property := (_ : Finsupp.single (↑Multiplicative.toAdd i) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i))) }
{ val := Finsupp.single (↑Multiplicative.toAdd j) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd j) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd j))) })
[PROOFSTEP]
{rw [AddMonoidHom.map_add]
}
[GOAL]
case h.e'_3.h.e'_1.h.e'_3.e'_2.e'_2.e'_8
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
[PROOFSTEP]
rw [AddMonoidHom.map_add]
[GOAL]
case h.e'_3.h.e'_2.h.e'_2.h.h.e'_5.h.e'_7
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
x✝ : AddMonoidAlgebra R M
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_4.e'_4.e'_2.e'_2.e'_2.e'_8
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝¹ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝¹ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_3✝ : HEq (fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_1✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_4.e'_6.e'_4.e'_2.e'_2.e'_8
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝² :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝¹ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_3✝ : HEq (fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }
e_1✝¹ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_4✝ : HEq AddZeroClass.toAdd AddZeroClass.toAdd
e_1✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_5.e'_5
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_6.e'_2.h.h.e'_5.h.e'_7
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
x✝ : AddMonoidAlgebra R M
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_6.e'_3
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ Finsupp.single (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) 1 =
↑(GradedMonoid.GMul.mul
{ val := Finsupp.single (↑Multiplicative.toAdd i) 1,
property := (_ : Finsupp.single (↑Multiplicative.toAdd i) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i))) }
{ val := Finsupp.single (↑Multiplicative.toAdd j) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd j) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd j))) })
[PROOFSTEP]
{rw [AddMonoidHom.map_add]
}
[GOAL]
case h.e'_3.h.e'_2.h.e'_2.h.h.e'_5.h.e'_7
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
x✝ : AddMonoidAlgebra R M
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
[PROOFSTEP]
rw [AddMonoidHom.map_add]
[GOAL]
case h.e'_3.h.e'_4.e'_4.e'_2.e'_2.e'_2.e'_8
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝¹ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝¹ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_3✝ : HEq (fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_1✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_4.e'_6.e'_4.e'_2.e'_2.e'_8
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝² :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝¹ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_3✝ : HEq (fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }
e_1✝¹ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_4✝ : HEq AddZeroClass.toAdd AddZeroClass.toAdd
e_1✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_5.e'_5
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_6.e'_2.h.h.e'_5.h.e'_7
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
x✝ : AddMonoidAlgebra R M
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_6.e'_3
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ Finsupp.single (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) 1 =
↑(GradedMonoid.GMul.mul
{ val := Finsupp.single (↑Multiplicative.toAdd i) 1,
property := (_ : Finsupp.single (↑Multiplicative.toAdd i) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i))) }
{ val := Finsupp.single (↑Multiplicative.toAdd j) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd j) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd j))) })
[PROOFSTEP]
{rw [AddMonoidHom.map_add]
}
[GOAL]
case h.e'_3.h.e'_4.e'_4.e'_2.e'_2.e'_2.e'_8
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝¹ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝¹ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_3✝ : HEq (fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_1✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
[PROOFSTEP]
rw [AddMonoidHom.map_add]
[GOAL]
case h.e'_3.h.e'_4.e'_6.e'_4.e'_2.e'_2.e'_8
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝² :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝¹ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_3✝ : HEq (fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }
e_1✝¹ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_4✝ : HEq AddZeroClass.toAdd AddZeroClass.toAdd
e_1✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_5.e'_5
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_6.e'_2.h.h.e'_5.h.e'_7
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
x✝ : AddMonoidAlgebra R M
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_6.e'_3
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ Finsupp.single (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) 1 =
↑(GradedMonoid.GMul.mul
{ val := Finsupp.single (↑Multiplicative.toAdd i) 1,
property := (_ : Finsupp.single (↑Multiplicative.toAdd i) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i))) }
{ val := Finsupp.single (↑Multiplicative.toAdd j) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd j) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd j))) })
[PROOFSTEP]
{rw [AddMonoidHom.map_add]
}
[GOAL]
case h.e'_3.h.e'_4.e'_6.e'_4.e'_2.e'_2.e'_8
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝² :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝¹ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_3✝ : HEq (fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) fun x => ⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }
e_1✝¹ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
e_4✝ : HEq AddZeroClass.toAdd AddZeroClass.toAdd
e_1✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
[PROOFSTEP]
rw [AddMonoidHom.map_add]
[GOAL]
case h.e'_3.h.e'_5.e'_5
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_6.e'_2.h.h.e'_5.h.e'_7
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
x✝ : AddMonoidAlgebra R M
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_6.e'_3
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ Finsupp.single (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) 1 =
↑(GradedMonoid.GMul.mul
{ val := Finsupp.single (↑Multiplicative.toAdd i) 1,
property := (_ : Finsupp.single (↑Multiplicative.toAdd i) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i))) }
{ val := Finsupp.single (↑Multiplicative.toAdd j) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd j) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd j))) })
[PROOFSTEP]
{rw [AddMonoidHom.map_add]
}
[GOAL]
case h.e'_3.h.e'_5.e'_5
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_1✝ :
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i }) =
({ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) } →+
⨁ (i : ι), { x // x ∈ gradeBy R (↑f) i })
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
[PROOFSTEP]
rw [AddMonoidHom.map_add]
[GOAL]
case h.e'_3.h.e'_6.e'_2.h.h.e'_5.h.e'_7
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
x✝ : AddMonoidAlgebra R M
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
case h.e'_3.h.e'_6.e'_3
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ Finsupp.single (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) 1 =
↑(GradedMonoid.GMul.mul
{ val := Finsupp.single (↑Multiplicative.toAdd i) 1,
property := (_ : Finsupp.single (↑Multiplicative.toAdd i) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i))) }
{ val := Finsupp.single (↑Multiplicative.toAdd j) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd j) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd j))) })
[PROOFSTEP]
{rw [AddMonoidHom.map_add]
}
[GOAL]
case h.e'_3.h.e'_6.e'_2.h.h.e'_5.h.e'_7
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
x✝ : AddMonoidAlgebra R M
⊢ ↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) = ↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)
[PROOFSTEP]
rw [AddMonoidHom.map_add]
[GOAL]
case h.e'_3.h.e'_6.e'_3
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ Finsupp.single (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) 1 =
↑(GradedMonoid.GMul.mul
{ val := Finsupp.single (↑Multiplicative.toAdd i) 1,
property := (_ : Finsupp.single (↑Multiplicative.toAdd i) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i))) }
{ val := Finsupp.single (↑Multiplicative.toAdd j) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd j) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd j))) })
[PROOFSTEP]
{rw [AddMonoidHom.map_add]
}
[GOAL]
case h.e'_3.h.e'_6.e'_3
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ Finsupp.single (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) 1 =
↑(GradedMonoid.GMul.mul
{ val := Finsupp.single (↑Multiplicative.toAdd i) 1,
property := (_ : Finsupp.single (↑Multiplicative.toAdd i) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i))) }
{ val := Finsupp.single (↑Multiplicative.toAdd j) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd j) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd j))) })
[PROOFSTEP]
rw [AddMonoidHom.map_add]
[GOAL]
case h.e'_3.h.e'_6.e'_3
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ Finsupp.single (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) 1 =
↑(GradedMonoid.GMul.mul
{ val := Finsupp.single (↑Multiplicative.toAdd i) 1,
property := (_ : Finsupp.single (↑Multiplicative.toAdd i) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i))) }
{ val := Finsupp.single (↑Multiplicative.toAdd j) 1,
property :=
(_ : Finsupp.single (↑Multiplicative.toAdd j) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd j))) })
[PROOFSTEP]
simp only [SetLike.coe_gMul]
[GOAL]
case h.e'_3.h.e'_6.e'_3
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ Finsupp.single (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) 1 =
Finsupp.single (↑Multiplicative.toAdd i) 1 * Finsupp.single (↑Multiplicative.toAdd j) 1
[PROOFSTEP]
refine Eq.trans (by rw [one_mul]) single_mul_single.symm
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i j : Multiplicative M
e_2✝ :
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j)) } =
{ x // x ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd i) + ↑f (↑Multiplicative.toAdd j)) }
⊢ Finsupp.single (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) 1 =
single (↑Multiplicative.toAdd i + ↑Multiplicative.toAdd j) (1 * 1)
[PROOFSTEP]
rw [one_mul]
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
m : M
r : R
⊢ ↑(decomposeAux f) (Finsupp.single m r) =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m))
{ val := Finsupp.single m r, property := (_ : Finsupp.single m r ∈ gradeBy R (↑f) (↑f m)) }
[PROOFSTEP]
refine' (lift_single _ _ _).trans _
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
m : M
r : R
⊢ r •
↑{
toOneHom :=
{
toFun := fun m =>
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd m)))
{ val := Finsupp.single (↑Multiplicative.toAdd m) 1,
property :=
(_ :
Finsupp.single (↑Multiplicative.toAdd m) 1 ∈ gradeBy R (↑f) (↑f (↑Multiplicative.toAdd m))) },
map_one' :=
(_ :
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd 1)))
{ val := Finsupp.single (↑Multiplicative.toAdd 1) 1,
property :=
(_ :
Finsupp.single (↑Multiplicative.toAdd 1) 1 ∈
gradeBy R (↑f) (↑f (↑Multiplicative.toAdd 1))) } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) 0) GradedMonoid.GOne.one) },
map_mul' :=
(_ :
∀ (i j : Multiplicative M),
OneHom.toFun
{
toFun := fun m =>
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd m)))
{ val := Finsupp.single (↑Multiplicative.toAdd m) 1,
property :=
(_ :
Finsupp.single (↑Multiplicative.toAdd m) 1 ∈
gradeBy R (↑f) (↑f (↑Multiplicative.toAdd m))) },
map_one' :=
(_ :
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd 1)))
{ val := Finsupp.single (↑Multiplicative.toAdd 1) 1,
property :=
(_ :
Finsupp.single (↑Multiplicative.toAdd 1) 1 ∈
gradeBy R (↑f) (↑f (↑Multiplicative.toAdd 1))) } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) 0) GradedMonoid.GOne.one) }
(i * j) =
OneHom.toFun
{
toFun := fun m =>
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd m)))
{ val := Finsupp.single (↑Multiplicative.toAdd m) 1,
property :=
(_ :
Finsupp.single (↑Multiplicative.toAdd m) 1 ∈
gradeBy R (↑f) (↑f (↑Multiplicative.toAdd m))) },
map_one' :=
(_ :
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd 1)))
{ val := Finsupp.single (↑Multiplicative.toAdd 1) 1,
property :=
(_ :
Finsupp.single (↑Multiplicative.toAdd 1) 1 ∈
gradeBy R (↑f) (↑f (↑Multiplicative.toAdd 1))) } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) 0) GradedMonoid.GOne.one) }
i *
OneHom.toFun
{
toFun := fun m =>
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd m)))
{ val := Finsupp.single (↑Multiplicative.toAdd m) 1,
property :=
(_ :
Finsupp.single (↑Multiplicative.toAdd m) 1 ∈
gradeBy R (↑f) (↑f (↑Multiplicative.toAdd m))) },
map_one' :=
(_ :
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f (↑Multiplicative.toAdd 1)))
{ val := Finsupp.single (↑Multiplicative.toAdd 1) 1,
property :=
(_ :
Finsupp.single (↑Multiplicative.toAdd 1) 1 ∈
gradeBy R (↑f) (↑f (↑Multiplicative.toAdd 1))) } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) 0) GradedMonoid.GOne.one) }
j) }
(↑Multiplicative.ofAdd m) =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m))
{ val := Finsupp.single m r, property := (_ : Finsupp.single m r ∈ gradeBy R (↑f) (↑f m)) }
[PROOFSTEP]
refine' (DirectSum.of_smul R _ _ _).symm.trans _
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
m : M
r : R
⊢ ↑(DirectSum.of (fun i => (fun i => { x // x ∈ gradeBy R (↑f) i }) i)
(↑f (↑Multiplicative.toAdd (↑Multiplicative.ofAdd m))))
(r •
{ val := Finsupp.single (↑Multiplicative.toAdd (↑Multiplicative.ofAdd m)) 1,
property :=
(_ :
Finsupp.single (↑Multiplicative.toAdd (↑Multiplicative.ofAdd m)) 1 ∈
gradeBy R (↑f) (↑f (↑Multiplicative.toAdd (↑Multiplicative.ofAdd m)))) }) =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m))
{ val := Finsupp.single m r, property := (_ : Finsupp.single m r ∈ gradeBy R (↑f) (↑f m)) }
[PROOFSTEP]
apply DirectSum.of_eq_of_gradedMonoid_eq
[GOAL]
case h
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
m : M
r : R
⊢ GradedMonoid.mk (↑f (↑Multiplicative.toAdd (↑Multiplicative.ofAdd m)))
(r •
{ val := Finsupp.single (↑Multiplicative.toAdd (↑Multiplicative.ofAdd m)) 1,
property :=
(_ :
Finsupp.single (↑Multiplicative.toAdd (↑Multiplicative.ofAdd m)) 1 ∈
gradeBy R (↑f) (↑f (↑Multiplicative.toAdd (↑Multiplicative.ofAdd m)))) }) =
GradedMonoid.mk (↑f m) { val := Finsupp.single m r, property := (_ : Finsupp.single m r ∈ gradeBy R (↑f) (↑f m)) }
[PROOFSTEP]
refine' Sigma.subtype_ext rfl _
[GOAL]
case h
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
m : M
r : R
⊢ ↑(GradedMonoid.mk (↑f (↑Multiplicative.toAdd (↑Multiplicative.ofAdd m)))
(r •
{ val := Finsupp.single (↑Multiplicative.toAdd (↑Multiplicative.ofAdd m)) 1,
property :=
(_ :
Finsupp.single (↑Multiplicative.toAdd (↑Multiplicative.ofAdd m)) 1 ∈
gradeBy R (↑f) (↑f (↑Multiplicative.toAdd (↑Multiplicative.ofAdd m)))) })).snd =
↑(GradedMonoid.mk (↑f m)
{ val := Finsupp.single m r, property := (_ : Finsupp.single m r ∈ gradeBy R (↑f) (↑f m)) }).snd
[PROOFSTEP]
refine' (Finsupp.smul_single' _ _ _).trans _
[GOAL]
case h
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
m : M
r : R
⊢ Finsupp.single (↑Multiplicative.toAdd (↑Multiplicative.ofAdd m)) (r * 1) =
↑(GradedMonoid.mk (↑f m)
{ val := Finsupp.single m r, property := (_ : Finsupp.single m r ∈ gradeBy R (↑f) (↑f m)) }).snd
[PROOFSTEP]
rw [mul_one]
[GOAL]
case h
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
m : M
r : R
⊢ Finsupp.single (↑Multiplicative.toAdd (↑Multiplicative.ofAdd m)) r =
↑(GradedMonoid.mk (↑f m)
{ val := Finsupp.single m r, property := (_ : Finsupp.single m r ∈ gradeBy R (↑f) (↑f m)) }).snd
[PROOFSTEP]
rfl
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i : ι
x : { x // x ∈ gradeBy R (↑f) i }
⊢ ↑(decomposeAux f) ↑x = ↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) x
[PROOFSTEP]
obtain ⟨x, hx⟩ := x
[GOAL]
case mk
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i : ι
x : AddMonoidAlgebra R M
hx : x ∈ gradeBy R (↑f) i
⊢ ↑(decomposeAux f) ↑{ val := x, property := hx } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) { val := x, property := hx }
[PROOFSTEP]
revert hx
[GOAL]
case mk
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i : ι
x : AddMonoidAlgebra R M
⊢ ∀ (hx : x ∈ gradeBy R (↑f) i),
↑(decomposeAux f) ↑{ val := x, property := hx } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) { val := x, property := hx }
[PROOFSTEP]
refine' Finsupp.induction x _ _
[GOAL]
case mk.refine'_1
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i : ι
x : AddMonoidAlgebra R M
⊢ ∀ (hx : 0 ∈ gradeBy R (↑f) i),
↑(decomposeAux f) ↑{ val := 0, property := hx } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) { val := 0, property := hx }
[PROOFSTEP]
intro hx
[GOAL]
case mk.refine'_1
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i : ι
x : AddMonoidAlgebra R M
hx : 0 ∈ gradeBy R (↑f) i
⊢ ↑(decomposeAux f) ↑{ val := 0, property := hx } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) { val := 0, property := hx }
[PROOFSTEP]
symm
[GOAL]
case mk.refine'_1
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i : ι
x : AddMonoidAlgebra R M
hx : 0 ∈ gradeBy R (↑f) i
⊢ ↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) { val := 0, property := hx } =
↑(decomposeAux f) ↑{ val := 0, property := hx }
[PROOFSTEP]
exact AddMonoidHom.map_zero _
[GOAL]
case mk.refine'_2
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i : ι
x : AddMonoidAlgebra R M
⊢ ∀ (a : M) (b : R) (f_1 : M →₀ R),
¬a ∈ f_1.support →
b ≠ 0 →
(∀ (hx : f_1 ∈ gradeBy R (↑f) i),
↑(decomposeAux f) ↑{ val := f_1, property := hx } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) { val := f_1, property := hx }) →
∀ (hx : Finsupp.single a b + f_1 ∈ gradeBy R (↑f) i),
↑(decomposeAux f) ↑{ val := Finsupp.single a b + f_1, property := hx } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i)
{ val := Finsupp.single a b + f_1, property := hx }
[PROOFSTEP]
intro m b y hmy hb ih hmby
[GOAL]
case mk.refine'_2
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i : ι
x : AddMonoidAlgebra R M
m : M
b : R
y : M →₀ R
hmy : ¬m ∈ y.support
hb : b ≠ 0
ih :
∀ (hx : y ∈ gradeBy R (↑f) i),
↑(decomposeAux f) ↑{ val := y, property := hx } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) { val := y, property := hx }
hmby : Finsupp.single m b + y ∈ gradeBy R (↑f) i
⊢ ↑(decomposeAux f) ↑{ val := Finsupp.single m b + y, property := hmby } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) { val := Finsupp.single m b + y, property := hmby }
[PROOFSTEP]
have : Disjoint (Finsupp.single m b).support y.support := by
simpa only [Finsupp.support_single_ne_zero _ hb, Finset.disjoint_singleton_left]
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i : ι
x : AddMonoidAlgebra R M
m : M
b : R
y : M →₀ R
hmy : ¬m ∈ y.support
hb : b ≠ 0
ih :
∀ (hx : y ∈ gradeBy R (↑f) i),
↑(decomposeAux f) ↑{ val := y, property := hx } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) { val := y, property := hx }
hmby : Finsupp.single m b + y ∈ gradeBy R (↑f) i
⊢ Disjoint (Finsupp.single m b).support y.support
[PROOFSTEP]
simpa only [Finsupp.support_single_ne_zero _ hb, Finset.disjoint_singleton_left]
[GOAL]
case mk.refine'_2
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i : ι
x : AddMonoidAlgebra R M
m : M
b : R
y : M →₀ R
hmy : ¬m ∈ y.support
hb : b ≠ 0
ih :
∀ (hx : y ∈ gradeBy R (↑f) i),
↑(decomposeAux f) ↑{ val := y, property := hx } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) { val := y, property := hx }
hmby : Finsupp.single m b + y ∈ gradeBy R (↑f) i
this : Disjoint (Finsupp.single m b).support y.support
⊢ ↑(decomposeAux f) ↑{ val := Finsupp.single m b + y, property := hmby } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) { val := Finsupp.single m b + y, property := hmby }
[PROOFSTEP]
rw [mem_gradeBy_iff, Finsupp.support_add_eq this, Finset.coe_union, Set.union_subset_iff] at hmby
[GOAL]
case mk.refine'_2
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i : ι
x : AddMonoidAlgebra R M
m : M
b : R
y : M →₀ R
hmy : ¬m ∈ y.support
hb : b ≠ 0
ih :
∀ (hx : y ∈ gradeBy R (↑f) i),
↑(decomposeAux f) ↑{ val := y, property := hx } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) { val := y, property := hx }
hmby✝ : Finsupp.single m b + y ∈ gradeBy R (↑f) i
hmby : ↑(Finsupp.single m b).support ⊆ ↑f ⁻¹' {i} ∧ ↑y.support ⊆ ↑f ⁻¹' {i}
this : Disjoint (Finsupp.single m b).support y.support
⊢ ↑(decomposeAux f) ↑{ val := Finsupp.single m b + y, property := hmby✝ } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) { val := Finsupp.single m b + y, property := hmby✝ }
[PROOFSTEP]
cases' hmby with h1 h2
[GOAL]
case mk.refine'_2.intro
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i : ι
x : AddMonoidAlgebra R M
m : M
b : R
y : M →₀ R
hmy : ¬m ∈ y.support
hb : b ≠ 0
ih :
∀ (hx : y ∈ gradeBy R (↑f) i),
↑(decomposeAux f) ↑{ val := y, property := hx } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) { val := y, property := hx }
hmby : Finsupp.single m b + y ∈ gradeBy R (↑f) i
this : Disjoint (Finsupp.single m b).support y.support
h1 : ↑(Finsupp.single m b).support ⊆ ↑f ⁻¹' {i}
h2 : ↑y.support ⊆ ↑f ⁻¹' {i}
⊢ ↑(decomposeAux f) ↑{ val := Finsupp.single m b + y, property := hmby } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) { val := Finsupp.single m b + y, property := hmby }
[PROOFSTEP]
have : f m = i := by rwa [Finsupp.support_single_ne_zero _ hb, Finset.coe_singleton, Set.singleton_subset_iff] at h1
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i : ι
x : AddMonoidAlgebra R M
m : M
b : R
y : M →₀ R
hmy : ¬m ∈ y.support
hb : b ≠ 0
ih :
∀ (hx : y ∈ gradeBy R (↑f) i),
↑(decomposeAux f) ↑{ val := y, property := hx } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) { val := y, property := hx }
hmby : Finsupp.single m b + y ∈ gradeBy R (↑f) i
this : Disjoint (Finsupp.single m b).support y.support
h1 : ↑(Finsupp.single m b).support ⊆ ↑f ⁻¹' {i}
h2 : ↑y.support ⊆ ↑f ⁻¹' {i}
⊢ ↑f m = i
[PROOFSTEP]
rwa [Finsupp.support_single_ne_zero _ hb, Finset.coe_singleton, Set.singleton_subset_iff] at h1
[GOAL]
case mk.refine'_2.intro
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i : ι
x : AddMonoidAlgebra R M
m : M
b : R
y : M →₀ R
hmy : ¬m ∈ y.support
hb : b ≠ 0
ih :
∀ (hx : y ∈ gradeBy R (↑f) i),
↑(decomposeAux f) ↑{ val := y, property := hx } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) { val := y, property := hx }
hmby : Finsupp.single m b + y ∈ gradeBy R (↑f) i
this✝ : Disjoint (Finsupp.single m b).support y.support
h1 : ↑(Finsupp.single m b).support ⊆ ↑f ⁻¹' {i}
h2 : ↑y.support ⊆ ↑f ⁻¹' {i}
this : ↑f m = i
⊢ ↑(decomposeAux f) ↑{ val := Finsupp.single m b + y, property := hmby } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) { val := Finsupp.single m b + y, property := hmby }
[PROOFSTEP]
subst this
[GOAL]
case mk.refine'_2.intro
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
x : AddMonoidAlgebra R M
m : M
b : R
y : M →₀ R
hmy : ¬m ∈ y.support
hb : b ≠ 0
this : Disjoint (Finsupp.single m b).support y.support
ih :
∀ (hx : y ∈ gradeBy R (↑f) (↑f m)),
↑(decomposeAux f) ↑{ val := y, property := hx } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m)) { val := y, property := hx }
hmby : Finsupp.single m b + y ∈ gradeBy R (↑f) (↑f m)
h1 : ↑(Finsupp.single m b).support ⊆ ↑f ⁻¹' {↑f m}
h2 : ↑y.support ⊆ ↑f ⁻¹' {↑f m}
⊢ ↑(decomposeAux f) ↑{ val := Finsupp.single m b + y, property := hmby } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m)) { val := Finsupp.single m b + y, property := hmby }
[PROOFSTEP]
simp only [AlgHom.map_add, Submodule.coe_mk, decomposeAux_single f m]
[GOAL]
case mk.refine'_2.intro
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
x : AddMonoidAlgebra R M
m : M
b : R
y : M →₀ R
hmy : ¬m ∈ y.support
hb : b ≠ 0
this : Disjoint (Finsupp.single m b).support y.support
ih :
∀ (hx : y ∈ gradeBy R (↑f) (↑f m)),
↑(decomposeAux f) ↑{ val := y, property := hx } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m)) { val := y, property := hx }
hmby : Finsupp.single m b + y ∈ gradeBy R (↑f) (↑f m)
h1 : ↑(Finsupp.single m b).support ⊆ ↑f ⁻¹' {↑f m}
h2 : ↑y.support ⊆ ↑f ⁻¹' {↑f m}
⊢ ↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m))
{ val := Finsupp.single m b, property := (_ : Finsupp.single m b ∈ gradeBy R (↑f) (↑f m)) } +
↑(decomposeAux f) y =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m)) { val := Finsupp.single m b + y, property := hmby }
[PROOFSTEP]
let ih' := ih h2
[GOAL]
case mk.refine'_2.intro
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
x : AddMonoidAlgebra R M
m : M
b : R
y : M →₀ R
hmy : ¬m ∈ y.support
hb : b ≠ 0
this : Disjoint (Finsupp.single m b).support y.support
ih :
∀ (hx : y ∈ gradeBy R (↑f) (↑f m)),
↑(decomposeAux f) ↑{ val := y, property := hx } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m)) { val := y, property := hx }
hmby : Finsupp.single m b + y ∈ gradeBy R (↑f) (↑f m)
h1 : ↑(Finsupp.single m b).support ⊆ ↑f ⁻¹' {↑f m}
h2 : ↑y.support ⊆ ↑f ⁻¹' {↑f m}
ih' : ↑(decomposeAux f) ↑{ val := y, property := h2 } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m)) { val := y, property := h2 } :=
ih h2
⊢ ↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m))
{ val := Finsupp.single m b, property := (_ : Finsupp.single m b ∈ gradeBy R (↑f) (↑f m)) } +
↑(decomposeAux f) y =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m)) { val := Finsupp.single m b + y, property := hmby }
[PROOFSTEP]
dsimp at ih'
[GOAL]
case mk.refine'_2.intro
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
x : AddMonoidAlgebra R M
m : M
b : R
y : M →₀ R
hmy : ¬m ∈ y.support
hb : b ≠ 0
this : Disjoint (Finsupp.single m b).support y.support
ih :
∀ (hx : y ∈ gradeBy R (↑f) (↑f m)),
↑(decomposeAux f) ↑{ val := y, property := hx } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m)) { val := y, property := hx }
hmby : Finsupp.single m b + y ∈ gradeBy R (↑f) (↑f m)
h1 : ↑(Finsupp.single m b).support ⊆ ↑f ⁻¹' {↑f m}
h2 : ↑y.support ⊆ ↑f ⁻¹' {↑f m}
ih' : ↑(decomposeAux f) y =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m)) { val := y, property := h2 } :=
ih h2
⊢ ↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m))
{ val := Finsupp.single m b, property := (_ : Finsupp.single m b ∈ gradeBy R (↑f) (↑f m)) } +
↑(decomposeAux f) y =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m)) { val := Finsupp.single m b + y, property := hmby }
[PROOFSTEP]
rw [ih', ← AddMonoidHom.map_add]
[GOAL]
case mk.refine'_2.intro
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
x : AddMonoidAlgebra R M
m : M
b : R
y : M →₀ R
hmy : ¬m ∈ y.support
hb : b ≠ 0
this : Disjoint (Finsupp.single m b).support y.support
ih :
∀ (hx : y ∈ gradeBy R (↑f) (↑f m)),
↑(decomposeAux f) ↑{ val := y, property := hx } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m)) { val := y, property := hx }
hmby : Finsupp.single m b + y ∈ gradeBy R (↑f) (↑f m)
h1 : ↑(Finsupp.single m b).support ⊆ ↑f ⁻¹' {↑f m}
h2 : ↑y.support ⊆ ↑f ⁻¹' {↑f m}
ih' : ↑(decomposeAux f) y =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m)) { val := y, property := h2 } :=
ih h2
⊢ ↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m))
({ val := Finsupp.single m b, property := (_ : Finsupp.single m b ∈ gradeBy R (↑f) (↑f m)) } +
{ val := y, property := h2 }) =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m)) { val := Finsupp.single m b + y, property := hmby }
[PROOFSTEP]
apply DirectSum.of_eq_of_gradedMonoid_eq
[GOAL]
case mk.refine'_2.intro.h
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
x : AddMonoidAlgebra R M
m : M
b : R
y : M →₀ R
hmy : ¬m ∈ y.support
hb : b ≠ 0
this : Disjoint (Finsupp.single m b).support y.support
ih :
∀ (hx : y ∈ gradeBy R (↑f) (↑f m)),
↑(decomposeAux f) ↑{ val := y, property := hx } =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m)) { val := y, property := hx }
hmby : Finsupp.single m b + y ∈ gradeBy R (↑f) (↑f m)
h1 : ↑(Finsupp.single m b).support ⊆ ↑f ⁻¹' {↑f m}
h2 : ↑y.support ⊆ ↑f ⁻¹' {↑f m}
ih' : ↑(decomposeAux f) y =
↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) (↑f m)) { val := y, property := h2 } :=
ih h2
⊢ GradedMonoid.mk (↑f m)
({ val := Finsupp.single m b, property := (_ : Finsupp.single m b ∈ gradeBy R (↑f) (↑f m)) } +
{ val := y, property := h2 }) =
GradedMonoid.mk (↑f m) { val := Finsupp.single m b + y, property := hmby }
[PROOFSTEP]
congr 2
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
⊢ AlgHom.comp (coeAlgHom (gradeBy R ↑f)) (decomposeAux f) = AlgHom.id R (AddMonoidAlgebra R M)
[PROOFSTEP]
ext : 2
[GOAL]
case h.h
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
x✝ : Multiplicative M
⊢ ↑(MonoidHom.comp (↑(AlgHom.comp (coeAlgHom (gradeBy R ↑f)) (decomposeAux f))) (of R M)) x✝ =
↑(MonoidHom.comp (↑(AlgHom.id R (AddMonoidAlgebra R M))) (of R M)) x✝
[PROOFSTEP]
simp only [MonoidHom.coe_comp, MonoidHom.coe_coe, AlgHom.coe_comp, Function.comp_apply, of_apply, AlgHom.coe_id, id_eq]
[GOAL]
case h.h
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
x✝ : Multiplicative M
⊢ ↑(coeAlgHom (gradeBy R ↑f)) (↑(decomposeAux f) (single (↑Multiplicative.toAdd x✝) 1)) =
single (↑Multiplicative.toAdd x✝) 1
[PROOFSTEP]
rw [decomposeAux_single, DirectSum.coeAlgHom_of, Subtype.coe_mk]
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
i : ι
x : { x // x ∈ gradeBy R (↑f) i }
⊢ ↑(decomposeAux f) ↑x = ↑(DirectSum.of (fun i => { x // x ∈ gradeBy R (↑f) i }) i) x
[PROOFSTEP]
rw [decomposeAux_coe f x]
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
⊢ Decomposition (gradeBy R ↑f)
[PROOFSTEP]
infer_instance
[GOAL]
M : Type u_1
ι : Type u_2
R : Type u_3
inst✝⁴ : DecidableEq M
inst✝³ : AddMonoid M
inst✝² : DecidableEq ι
inst✝¹ : AddMonoid ι
inst✝ : CommSemiring R
f : M →+ ι
⊢ Decomposition (grade R)
[PROOFSTEP]
infer_instance
|
#include <boost/graph/parallel/basic_reduce.hpp>
|
# under-sampling and bagging make prediction models
# setting
```{r}
########################## Data setting
### Setting
rm(list=ls(all=TRUE))
library(data.table)
library(dplyr)
library(ggplot2)
library(car)
library(psych)
library(pROC)
library(epitools)
library(tableone)
library(caret)
library(tictoc)
library(Boruta)
library(doParallel)
cl <- makePSOCKcluster(detectCores(all.tests = FALSE, logical = TRUE) - 1)
registerDoParallel(cl)
set.seed(1234)
######################### Input data
Data <- fread("Data_demo.csv", encoding = "UTF-8" )
Data$V1 <- NULL
colnames(Data)
dim(Data)
Data[, table(TrainTest), ]
Data_train <- Data[TrainTest == "Train", , ] #*eligible
Data_test <- Data[TrainTest == "Test", , ] #*eligible
Noise <- function(Var, Data){
Var + rnorm(mean = 0, sd = sd(Var)/5, n = nrow(Data))
}
RMSE <- function(Obs, Pred){
Dif <- Pred - Obs
RMSE <- round(sqrt(mean(Dif**2)), 2)
return(RMSE)
}
MAE <- function(Obs, Pred){
Dif <- Pred - Obs
MAE <- Dif %>% abs() %>% mean() %>% round(., 2)
return(MAE)
}
MAPE <- function(Obs, Pred){
Dif <- Pred - Obs
MAPE <- mean(abs(Dif/Obs)*100) %>% round(., 2)
return(MAPE)
}
```
#
```{r}
# CV methods
CV_method <- "cv"
CV_number <- 5
Repeated_number <- 1
Tune_number <- 1
# under-sampling parameters
Data_train_original <- data.frame(Data_train)
Parameter_grid <- expand.grid(
iii_Top_x_percentile = seq(0.90, 0.98, 0.01),
iii_N_down = seq(100, 200, 100)
) %>% as.data.frame
Population_cut <- Data_train[AMPM == "PM" & Population100000 >= 5, ID, ] %>% unique()
Population_cut
```
# Under sampling setting
```{r}
# using variables
Var_use <- c(
"Cluster_pred",
"ID",
"Date",
"Population100000",
"LogPopulation100000",
"Mean_income_city_2015",
"Green_area_percent",
"Age_median_city",
"Population_over_65_100000",
"SexRatioF",
"SeverityAll",
"RainySeason",
"DifDateRain",
"holiday_flag",
"Hour",
"Month",
"precip1Hour",
"windSpeed_ms",
"DownwardSolarRadiation_kwm2",
"relativeHumidity",
"temperature",
"temperature_past1d_max_diff",
"temperature_past1d_mean_diff",
"temperature_past1d_min_diff"
)
# formula
Form_temp <- formula(
SeverityAll ~
Population100000 +
Mean_income_city_2015 +
Green_area_percent +
Age_median_city +
Population_over_65_100000 +
SexRatioF +
RainySeason +
DifDateRain +
holiday_flag +
Hour +
Month +
precip1Hour +
windSpeed_ms +
DownwardSolarRadiation_kwm2 +
relativeHumidity +
temperature +
temperature_past1d_max_diff +
temperature_past1d_mean_diff +
temperature_past1d_min_diff
)
# set seed
Size_n <- 36
Seeds_fix <- vector(mode = "list", length = CV_number * Repeated_number + 1)
for(i in 1:(CV_number * Repeated_number)) Seeds_fix[[i]] <- sample.int(n = 10000, size = Size_n )
Seeds_fix[[(CV_number * Repeated_number + 1)]] <- sample.int(10000, 1)
Seeds_fix
# construct rfeControl object
rfe_control = rfeControl(
functions = caretFuncs,
allowParallel = TRUE,
method = CV_method,
number = CV_number,
returnResamp = "final",
seeds = Seeds_fix
)
# construct trainControl object for train method
fit_control = trainControl(
allowParallel = TRUE,
method = CV_method,
number = CV_number,
seeds = Seeds_fix
)
```
# Under sampling
```{r}
tic(4)
# Under sampling
HogeRMSE <- c()
HogeMAPE <- c()
for(iii in 1:nrow(Parameter_grid)){
# read classifiers
Classifier <- readRDS(
paste("Classifier",
"_top_",
Parameter_grid[iii, "iii_Top_x_percentile"],
"_percent.rds",
sep = ""
)
)
# predict classess
Data_train_cluster <- Data_train[ID %in% Population_cut, , ]
Data_train_cluster$Cluster_pred <- predict(Classifier, Data_train_cluster, pe = "raw")
Data_train_cluster_no <- Data_train[(ID %in% Population_cut) == FALSE, , ]
Data_train_cluster_no[, Cluster_pred := "99", ]
Data_train_cluster <- rbind(Data_train_cluster, Data_train_cluster_no)
Data_train_cluster <- Data_train_cluster[, Var_use, with = F]
# Under sampling b1-5
Temp_train <- c()
Temp_test <- c()
for(bbb in 1:10){
set.seed(bbb)
Data_train_cluster_auged <- sample_n(
tbl = Data_train_cluster[Cluster_pred == "99", , ],
size = Parameter_grid[iii, "iii_N_down"],
replace = F
)
Data_train_cluster_auged_bag <- rbind(Data_train_cluster_auged, Data_train_cluster[Cluster_pred != "99", , ])
### Save data
fwrite(
Data_train_cluster_auged_bag,
paste(
"Data_train_top_",
Parameter_grid[iii, "iii_Top_x_percentile"],
"_percent_",
Parameter_grid[iii, "iii_N_down"],
"_under_",
bbb,
".csv", sep = "")
)
# xgbTree
tic(6)
xgbTree_temp <- train(
form = Form_temp,
data = Data_train_cluster_auged_bag,
method = "xgbTree",
objective="reg:squarederror",
trControl = fit_control,
metric = "RMSE",
preProcess = c("center", "scale"),
tuneLength = 3
#tuneGrid = tune_params
)
summary(xgbTree_temp)
xgbTree_temp
toc(6)
# save models
saveRDS(xgbTree_temp,
paste(
"xgbTree_temp_model_",
Parameter_grid[iii, "iii_Top_x_percentile"],
"_percent_",
Parameter_grid[iii, "iii_N_down"],
"_under_",
bbb,
".rds", sep = ""
)
)
# Store
Temp_train <- cbind(Temp_train, predict(xgbTree_temp, Data_train, pe = "raw"))
Temp_test <- cbind(Temp_test, predict(xgbTree_temp, Data_test, pe = "raw"))
}
Temp_train <- data.table(Temp_train)
Temp_train[, Pred := rowMeans(Temp_train), ]
Temp_train[, Pred := ifelse(Pred < 0, 0, Pred), ]
Temp_test <- data.table(Temp_test)
Temp_test[, Pred := rowMeans(Temp_test), ]
Temp_test[, Pred := ifelse(Pred < 0, 0, Pred), ]
# get performance
Data_train[, Pred := Temp_train$Pred, ]
Data_test[, Pred := Temp_test$Pred, ]
RMSE_train <- RMSE(Obs = Data_train$SeverityAll, Pred = Data_train$Pred)
MAE_train <- MAE(Obs = Data_train$SeverityAll, Pred = Data_train$Pred)
Cor_train <- paste(
cor.test(Data_train$SeverityAll, Data_train$Pred)$estimate %>% round(., 2),
" (",
cor.test(Data_train$SeverityAll, Data_train$Pred)$conf.int[1] %>% round(., 2),
" to ",
cor.test(Data_train$SeverityAll, Data_train$Pred)$conf.int[2] %>% round(., 2),
")",
sep = ""
)
# get performance
RMSE_test <- RMSE(Obs = Data_test$SeverityAll, Pred = Data_test$Pred)
MAE_test <- MAE(Obs = Data_test$SeverityAll, Pred = Data_test$Pred)
Cor_test <- paste(
cor.test(Data_test$SeverityAll, Data_test$Pred)$estimate %>% round(., 2),
" (",
cor.test(Data_test$SeverityAll, Data_test$Pred)$conf.int[1] %>% round(., 2),
" to ",
cor.test(Data_test$SeverityAll, Data_test$Pred)$conf.int[2] %>% round(., 2),
")",
sep = ""
)
# Summarize
Performance <- c(
paste(
"xgbTree_temp_model_",
Parameter_grid[iii, "iii_Top_x_percentile"],
"_percent_",
Parameter_grid[iii, "iii_N_down"],
"_under", sep = ""
),
RMSE_train
, RMSE_test
, Cor_train
, Cor_test
)
HogeRMSE <- rbind(HogeRMSE, Performance)
# Organized dataset
Data_train_MAPE <- Data_train %>%
group_by(Date) %>%
summarise(
Obs = sum(SeverityAll),
Pred = sum(Pred)
) %>% data.table()
Data_train_MAPE[, Year := year(Date), ]
Data_train_MAPE[, Spike :=
ifelse(Year == 2015 & Obs >= Data_train_MAPE[Year == 2015, quantile(Obs, 0.8), ], 1,
ifelse(Year == 2016 & Obs >= Data_train_MAPE[Year == 2016, quantile(Obs, 0.8), ], 1,
ifelse(Year == 2017 & Obs >= Data_train_MAPE[Year == 2017, quantile(Obs, 0.8), ], 1, 0)))
, ]
Data_train_MAPE[, table(Spike), ]
Data_train_MAPE[, table(Spike), ] / nrow(Data_train_MAPE)
# get performance
MAPE_train <- MAPE(
Obs = Data_train_MAPE[Spike == 1, Obs, ],
Pred = Data_train_MAPE[Spike == 1, Pred, ]
)
PE_train <- Data_train_MAPE[Spike == 1, round( (abs(sum(Pred) - sum(Obs)) / sum(Obs) ) * 100, 2), ]
# Organized dataset
Data_test_MAPE <- Data_test %>%
group_by(Date) %>%
summarise(
Obs = sum(SeverityAll),
Pred = sum(Pred)
) %>% data.table()
Data_test_MAPE[, Year := year(Date), ]
Data_test_MAPE[, Spike :=
ifelse(Year == 2018 & Obs >= Data_test_MAPE[Year == 2018, quantile(Obs, 0.8), ], 1, 0)
, ]
Data_test_MAPE[, table(Spike), ]
Data_test_MAPE[, table(Spike), ] / nrow(Data_test_MAPE)
# get performance
MAPE_test <- MAPE(
Obs = Data_test_MAPE[Spike == 1, Obs, ],
Pred = Data_test_MAPE[Spike == 1, Pred, ]
)
PE_est <- Data_test_MAPE[Spike == 1, round( (abs(sum(Pred) - sum(Obs)) / sum(Obs) ) * 100, 2), ]
# Summarize
Performance <- c(
paste(
"xgbTree_temp_model_",
Parameter_grid[iii, "iii_Top_x_percentile"],
"_percent_",
Parameter_grid[iii, "iii_N_down"],
"_under", sep = ""
),
MAPE_train
, MAPE_test
, PE_train
, PE_est
)
HogeMAPE <- rbind(HogeMAPE, Performance)
# get predicted values
Data_train$Predicted <- Data_train$Pred
Data_train$Obserbved <- Data_train$SeverityAll
# get predicted values
Data_test$Predicted <- Data_test$Pred
Data_test$Obserbved <- Data_test$SeverityAll
## Make figures
ggplot(data = Data_train, aes(x = Predicted, y = Obserbved)) +
geom_point() +
geom_smooth(method = lm) +
scale_x_continuous(limits = c(0, 100), breaks = seq(0, 100, 10)) +
scale_y_continuous(limits = c(0, 100), breaks = seq(0, 100, 10)) +
xlab("") +
ylab("") +
theme_classic()
ggsave(
paste(
"Out_plot_",
"xgbTree_temp_model_",
Parameter_grid[iii, "iii_Top_x_percentile"],
"_percent_",
Parameter_grid[iii, "iii_N_down"],
"_under",
"_train.png", sep = ""),
width = 4.2, height = 3.2
) #*action
### Make figures taest
ggplot(data = Data_test, aes(x = Predicted, y = Obserbved)) +
geom_point() +
geom_smooth(method = lm) +
scale_x_continuous(limits = c(0, 100), breaks = seq(0, 100, 10)) +
scale_y_continuous(limits = c(0, 100), breaks = seq(0, 100, 10)) +
xlab("") +
ylab("") +
theme_classic()
ggsave(
paste(
"Out_plot_",
"xgbTree_temp_model_",
Parameter_grid[iii, "iii_Top_x_percentile"],
"_percent_",
Parameter_grid[iii, "iii_N_down"],
"_under",
"_test.png", sep = ""),
width = 4.2, height = 3.2
) #*action
### Make Fig train
DataSum_train <- Data_train %>%
group_by(Date) %>%
summarise(
Obserbved = sum(Obserbved),
Predicted = sum(Predicted)
) %>%
data.table()
DataSum_test <- Data_test %>%
group_by(Date) %>%
summarise(
Obserbved = sum(Obserbved),
Predicted = sum(Predicted)
) %>%
data.table()
DataSum <- rbind(DataSum_train, DataSum_test)
DataSum[, Date:=as.Date(Date), ]
DataSum[, YearUse:=year(Date), ]
DataSum <- DataSum[order(Date), , ]
DataSum[, Day:=1:length(Obserbved), by = YearUse]
DataSum[Date == as.Date("2015-06-01"), , ]
DataSum[Date == as.Date("2015-07-01"), , ]
DataSum[Date == as.Date("2015-08-01"), , ]
DataSum[Date == as.Date("2015-09-01"), , ]
ggplot(data = DataSum, aes(x = Day), group=factor(YearUse)) +
geom_line(aes(y = Obserbved, x=Day), colour = "Black", size = 0.4) +
geom_line(aes(y = Predicted, x=Day), colour = "Red", size = 0.4) +
xlab("") +
ylab("") +
scale_y_continuous(
limits = c(0, 450),
breaks = seq(0, 450, 50)
) +
scale_x_continuous(
label = c("Jun.", "Jul.", "Aug.", "Sep."),
breaks = c(1, 31, 62, 93)
) +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
facet_grid(~YearUse) +
theme_classic()
ggsave(
paste(
"Out_time_24_",
"xgbTree_temp_model_",
Parameter_grid[iii, "iii_Top_x_percentile"],
"_percent_",
Parameter_grid[iii, "iii_N_down"],
"_under",
".png", sep = ""),
width = 6.7 * 1.5, height = 3.5 * 0.66
) #*action
}
fwrite(HogeRMSE, "Out_RMSE_under.csv")
fwrite(HogeMAPE, "Out_MAPE_under.csv")
toc(4)
toc(1)
```
|
function [q] = rotMatToQuat(R)
[r,c] = size( R );
R=R';
if( r ~= 3 | c ~= 3 )
fprintf( 'R must be a 3x3 matrix\n\r' );
return;
end
Rxx = R(1,1); Rxy = R(1,2); Rxz = R(1,3);
Ryx = R(2,1); Ryy = R(2,2); Ryz = R(2,3);
Rzx = R(3,1); Rzy = R(3,2); Rzz = R(3,3);
w = sqrt( trace( R ) + 1 ) / 2;
% check if w is real. Otherwise, zero it.
if( imag( w ) > 0 )
w = 0;
end
x = sqrt( 1 + Rxx - Ryy - Rzz ) / 2;
y = sqrt( 1 + Ryy - Rxx - Rzz ) / 2;
z = sqrt( 1 + Rzz - Ryy - Rxx ) / 2;
[~, i ] = max( [w,x,y,z] );
if( i == 1 )
x = ( Rzy - Ryz ) / (4*w);
y = ( Rxz - Rzx ) / (4*w);
z = ( Ryx - Rxy ) / (4*w);
end
if( i == 2 )
w = ( Rzy - Ryz ) / (4*x);
y = ( Rxy + Ryx ) / (4*x);
z = ( Rzx + Rxz ) / (4*x);
end
if( i == 3 )
w = ( Rxz - Rzx ) / (4*y);
x = ( Rxy + Ryx ) / (4*y);
z = ( Ryz + Rzy ) / (4*y);
end
if( i == 4 )
w = ( Ryx - Rxy ) / (4*z);
x = ( Rzx + Rxz ) / (4*z);
y = ( Ryz + Rzy ) / (4*z);
end
q = [x; y; z; w];
end |
context("data_dredge_regression")
library(magrittr)
library(mnmacros)
#library(testthat)
rm(list = ls())
set.seed(0)
# not enough columns
y1 <- rep(c("a", "b"), c(10,10))
expect_error(
data.frame(y1, stringsAsFactors = F) %>% data_dredge_regression(),
"data %>% ncol() >= 2 is not TRUE",
fixed = T)
# not enough response columns
expect_error(
data.frame(y1, y1, stringsAsFactors = F) %>% data_dredge_regression(),
"response_column_count >= 1 is not TRUE",
fixed = T)
# categorical predicts continuous
y2 <- c(rnorm(10), rnorm(10, mean = 2))
actual <- data.frame(y1, y2, stringsAsFactors = F) %>% data_dredge_regression()
expected <- data.frame(
formula = c("y2 ~ y1"),
best_pvalue = c(0.01135),
adjusted_r_squared = c(0.26782),
stringsAsFactors = F)
expect_equal(actual, expected, tolerance = 0.001)
# continuous predicts continuous
y3 <- c(rnorm(10, mean = 2), rnorm(10, mean = 4))
actual <- data.frame(y2, y3, stringsAsFactors = F) %>% data_dredge_regression()
expected <- data.frame(
formula = c("y3 ~ y2", "y2 ~ y3"),
best_pvalue = c(0.01400, 0.01400),
adjusted_r_squared = c(0.25210, 0.25210),
stringsAsFactors = F)
expect_equal(actual, expected, tolerance = 0.001)
# mixed case test
actual <-
data.frame(y1, y2, y3, stringsAsFactors = F) %>%
data_dredge_regression()
expected <- data.frame(
formula = c("y2 ~ y1", "y3 ~ y1", "y3 ~ y2", "y2 ~ y3", "y3 ~ y1*y2"),
best_pvalue = c(0.01135, 0, 0.01400, 0.01400, 0.00029),
adjusted_r_squared = c(0.26782, 0.67155, 0.25210, 0.25210, 0.67321),
stringsAsFactors = F)
expect_equal(actual, expected, tolerance = 0.001)
# perfect numeric continuous regression
y4 <- y3 + 1
actual <-
data.frame(y3, y4, stringsAsFactors = F) %>%
data_dredge_regression()
expect_equal(actual %>% nrow(), 0)
# perfect integer continuous regression
y5 <- 1:10
y6 <- 1:10 + 1 %>% as.integer()
actual <-
data.frame(y5, y6, stringsAsFactors = F) %>%
data_dredge_regression()
expect_equal(actual %>% nrow(), 0)
# perfect numeric ~ categorical regression
y7 <- c("q", "w", "e", "r", "t", "y", "u", "i", "o", "p")
actual <-
data.frame(y5, y7, stringsAsFactors = F) %>%
data_dredge_regression()
expect_equal(actual %>% nrow(), 0)
# perfect integer ~ categorical regression
actual <-
data.frame(y6, y7, stringsAsFactors = F) %>%
data_dredge_regression()
expect_equal(actual %>% nrow(), 0)
|
-- |
-- Module : Application
-- Description : Utilties for creating GUI applications
-- Copyright : (c) Jonatan H Sundqvist, year
-- License : MIT
-- Maintainer : Jonatan H Sundqvist
-- Stability : experimental|stable
-- Portability : POSIX (not sure)
--
-- Created date year
-- TODO | - Refactor (move types to separate module, add lenses)
-- - Input queries, composite events (InputState type?)
-- - Redesign API (less fragile and add-hoc) (divide into app types, eg. full screen canvas, etc.)
-- - Optional event wrappers
-- - Printf-style event coupling (with a Listener class (?))
-- SPEC | -
-- -
--------------------------------------------------------------------------------------------------------------------------------------------
-- GHC directives
--------------------------------------------------------------------------------------------------------------------------------------------
{-# LANGUAGE RankNTypes #-}
--------------------------------------------------------------------------------------------------------------------------------------------
-- API
--------------------------------------------------------------------------------------------------------------------------------------------
module Southpaw.Interactive.Application where
--------------------------------------------------------------------------------------------------------------------------------------------
-- We'll need these
--------------------------------------------------------------------------------------------------------------------------------------------
import Data.Complex --
import Data.Functor --
import Data.IORef --
import Data.Maybe --
import Control.Lens hiding (set)
import Control.Monad (liftM, when, void, forM) --
import Control.Applicative (pure, (<*>))
import Graphics.UI.Gtk --
import qualified Graphics.Rendering.Cairo as Cairo --
import Southpaw.Interactive.Types
import Southpaw.Interactive.Lenses
--------------------------------------------------------------------------------------------------------------------------------------------
-- Data
--------------------------------------------------------------------------------------------------------------------------------------------
-- |
-- TODO: Rename (eg. no-listeners), create a separate default value (?)
nolisteners :: EventMap self s
nolisteners = EventMap Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- |
-- TODO: Rename (eg. no-listeners), create a separate default value (?)
-- defaultListeners :: EventMap s
-- defaultListeners = nolisteners { }
--------------------------------------------------------------------------------------------------------------------------------------------
-- Functions
--------------------------------------------------------------------------------------------------------------------------------------------
-- Master listeners ------------------------------------------------------------------------------------------------------------------------
-- TODO: Hoogle section
-- |
masterdraw :: (s -> Cairo.Render ()) -> IORef s -> Cairo.Render ()
masterdraw draw stateref = do
state <- Cairo.liftIO $ readIORef stateref
draw state
-- General utilities -----------------------------------------------------------------------------------------------------------------------
-- |
-- TODO: Make polymorphic
widgetSize :: WidgetClass self => self -> IO (Complex Int)
widgetSize widget = (:+) <$> widgetGetAllocatedWidth widget <*> widgetGetAllocatedHeight widget
--------------------------------------------------------------------------------------------------------------------------------------------
-- |
-- TODO: Rename (duh)
-- TODO: Refactor
-- TODO: Factor out default event handlers
-- TODO: Use state value from the App (?)
wholecanvas :: WidgetSettings Window state -> WidgetSettings DrawingArea state -> state -> IO (App FullCanvasLayout state)
wholecanvas windowSettings canvasSettings appstate = do
initGUI
stateref <- newIORef appstate
window' <- makeWidget windowNew stateref $ windowSettings
frame' <- frameNew
canvas' <- makeWidget drawingAreaNew stateref $ canvasSettings
containerAdd frame' canvas'
set window' [ containerChild := frame' ]
widgetShowAll window'
return $ App { _window=window', _layout=FullCanvasLayout { _canvas=canvas' }, _appsize=_settingsize windowSettings, _state=stateref }
-- |
-- TODO: Use readstate for everything, or remove it (?)
-- TODO: Find out how to deal with 'onanimate'
-- TODO: Event wrappers (eg. draw)
attachListeners :: WidgetClass self => self -> IORef state -> EventMap self state -> IO ()
attachListeners self stateref eventmap = do
simpleBind buttonPressEvent onmousedown
simpleBind buttonReleaseEvent onmouseup
simpleBind motionNotifyEvent onmousemotion
simpleBind keyPressEvent onkeydown
simpleBind keyReleaseEvent onkeyup
simpleBind deleteEvent ondelete
-- simpleBind draw (\emap -> maybe Nothing (void . Just . masterdraw dr) (ondraw emap))
maybe pass (\ondr -> void $ (self `on` draw $ masterdraw ondr stateref)) (ondraw eventmap)
maybe pass (\(fps, ona) -> void $ timeoutAdd (ona self stateref) fps) (onanimate eventmap)
pass
-- perhapsBind self key onanimate
-- onresize, -- configureEvent
-- ondrawIO
-- perhapsBind self onquit
-- forM [(self `on` motionNotifyEvent, onmousemotion),
-- (self `on` buttonPressEvent, onmousedown),
-- (self `on` buttonReleaseEvent, onmouseup)] $ \(signal, prop) -> perhaps (prop eventmap) (\listener -> signal $ listener stateref)
where
simpleBind = maybeBind self eventmap stateref
-- |
pass :: Monad m => m ()
pass = return ()
-- |
-- bind :: WidgetClass self => self -> Signal ->
bind :: WidgetClass self => self -> Signal self callback -> IORef s -> (IORef s -> callback) -> IO (ConnectId self)
bind self event stateref action = self `on` event $ action stateref
-- |
maybeBind :: WidgetClass self => self -> EventMap self s -> IORef s -> Signal self callback -> (EventMap self s -> Maybe (IORef s -> callback)) -> IO ()
maybeBind self eventmap state event find = maybe pass (void . bind self event state) (find eventmap)
-- |
makeWidget :: WidgetClass self => IO self -> IORef s -> WidgetSettings self s -> IO self
makeWidget make stateref settings = do
widget <- make
applySettings widget stateref settings
-- |
applySettings :: WidgetClass self => self -> IORef s -> WidgetSettings self s -> IO self
applySettings self stateref settings = do
widgetSetSizeRequest self dx dy -- TODO: Use windowSetDefaultSize instead (?)
widgetAddEvents self eventmasks
attachListeners self stateref (_settinglisteners settings)
return self
where
(dx:+dy) = _settingsize settings
eventmasks = _settingeventmasks settings
--------------------------------------------------------------------------------------------------------------------------------------------
-- |
-- TODO: Add setup argument (?)
-- TODO: Use 'IO (App s)' or 'App s' directly (?)
run :: IO (App layout state) -> IO ()
run makeApp = makeApp >> mainGUI
|
\BoSSSopen{tutorial9-SIP/sip}
\graphicspath{{tutorial9-SIP/sip.texbatch/}}
\BoSSScmd{
/// \section*{What's new}
/// \begin{itemize}
/// \item Symmetric Interior Penalty method (SIP)
/// \item investigating matrix properties
/// \end{itemize}
/// \section*{Prerequisites}
/// \begin{itemize}
/// \item basics SIP method
/// \item spatial operator, chapter \ref{SpatialOperator}
/// \item implementing numerical fluxes and convergence study, chapter \ref{NumFlux}
/// \end{itemize}
///
///%_______________________________________________________
/// \section{Problem statement}
/// We consider the 2D Poisson problem:
/// \begin{equation*}
/// \Delta u = f(x,y)
/// \end{equation*}
/// with $f(x,y)\neq 0$ is an arbitrary function of $x$ and/or $y$ or constant.
/// Within this exercise, we are going to investigate the Symmetric Interior Penalty discretization method (SIP) for the Laplace operator:
/// \begin{equation*}
/// a_{\text{sip}}(u,v)
/// = \int_{\domain} \underbrace{\nabla u \cdot \nabla v}_{\text{Volume\ term}}\dV
/// - \oint_{\Gamma \setminus \Gamma_{N }} \underbrace{
/// \mean {\nabla u} \cdot n_{\Gamma}\jump{v}
/// }_{\text{consistency\ term}} + \underbrace{
/// \mean{\nabla v} \cdot \vec{n}_{\Gamma} \jump{u}
/// }_{\text{symmetry\ term}} \dA
/// + \oint_{\Gamma \setminus \Gamma_{N}} \underbrace{
/// \eta \jump{u}\jump{v}
/// }_{\text{penalty\ term}} \dA
/// \end{equation*}
/// The use of these fluxes including a penalty term stabilizes the DG-discretization for the Laplace operator.
///
///%____________________________________________
/// \section{Solution within the \BoSSS{} framework}
/// First, we initialize the new worksheet:
}
\BoSSSexeSilent
\BoSSScmd{
restart;
}
\BoSSSexeSilent
\BoSSScmd{
/// We need the following packages:
using ilPSP.LinSolvers;\newline
using ilPSP.Connectors.Matlab;
}
\BoSSSexe
\BoSSScmdSilent{
/// BoSSScmdSilent BoSSSexeSilent
using NUnit.Framework;
}
\BoSSSexeSilent
\BoSSScmd{
/// \subsection{Implementation of the SIP fluxes}
/// We are going to implement the SIP-form
/// \begin{equation*}
/// a_{\text{sip}}(u,v)
/// = \int_{\domain} \underbrace{\nabla u \cdot \nabla v}_{\text{volume\ term}}\dV
/// - \oint_{\Gamma \setminus \Gamma_{N }} \underbrace{
/// \mean {\nabla u} \cdot n_{\Gamma}\jump{v}
/// }_{\text{consistency\ term}} + \underbrace{
/// \mean{\nabla v} \cdot \vec{n}_{\Gamma} \jump{u}
/// }_{\text{symmetry\ term}} \dA
/// + \oint_{\Gamma \setminus \Gamma_{N}} \underbrace{
/// \eta \jump{u}\jump{v}
/// }_{\text{penalty\ term}} \dA
/// \end{equation*}
/// First, we need a class in which the integrands are defined.
/// This also includes some technical aspects like the \code{TermActivationFlags}.
public class SipLaplace :\newline
\btab \btab BoSSS.Foundation.IEdgeForm, // edge integrals\newline
\btab \btab BoSSS.Foundation.IVolumeForm // volume integrals\newline
\{\newline
/// We do not use parameters (e.g. variable viscosity, ...)
/// at this point: so this can be null
\btab public IList<string> ParameterOrdering \{ \newline
\btab \btab get \{ return new string[0]; \} \newline
\btab \} \newline
/// but we have one argument variable, $u$ (our trial function)
\btab public IList<String> ArgumentOrdering \{ \newline
\btab \btab get \{ return new string[] \{ "u" \}; \} \newline
\btab \}\newline
/// The \code{TermActivationFlags} tell \BoSSS\ which kind of terms,
/// i.e. products of $u$, $v$, $\nabla u$, and $\nabla v$
/// the \code{VolumeForm(...)} actually contains.
/// This additional information helps to improve the performance.
\btab public TermActivationFlags VolTerms \{\newline
\btab \btab get \{\newline
\btab \btab \btab return TermActivationFlags.GradUxGradV;\newline
\btab \btab \}\newline
\btab \}\newline
/// activation flags for the 'InnerEdgeForm(...)'
\btab public TermActivationFlags InnerEdgeTerms \{\newline
\btab \btab get \{\newline
\btab \btab \btab return (TermActivationFlags.AllOn);\newline
\btab \btab \btab // if we do not care about performance, we can activate all terms.\newline
\btab \btab \}\newline
\btab \}\newline
\btab public TermActivationFlags BoundaryEdgeTerms \{\newline
\btab get \{\newline
\btab \btab return TermActivationFlags.AllOn;\newline
\btab \btab \}\newline
\btab \}\newline
/// For the computation of the penalty factor $\eta$,
/// we require
/// some length scale for each cell and
/// the polynomial degree of the DG approximation.
\btab public MultidimensionalArray cj;\newline
\btab public int PolynomialDegree;\newline
/// The safety factor for the penalty factor should be in the order of 1.
/// A very large penalty factor increases the condition number of the
/// system, but without affecting stability.
/// A very small penalty factor yields to an unstable discretization.
\btab public double PenaltySafety = 2.2; \newline
/// The actual computation of the penalty factor, which should be
/// used in the \code{InnerEdgeForm} and \code{BoundaryEdgeForm} functions.
/// Hint: for the parameters \code{jCellIn}, \code{jCellOut} and \code{g},
/// take a look at
/// \code{CommonParams} and \code{CommonParamsBnd}.
\btab double PenaltyFactor(int jCellIn, int jCellOut) \{\newline
\btab \btab double cj\_in = cj[jCellIn];\newline
\btab \btab double penalty\_base = PenaltySafety*PolynomialDegree*PolynomialDegree;\newline
\btab \btab double eta = penalty\_base * cj\_in;\newline
\btab \btab if(jCellOut >= 0) \{\newline
\btab \btab \btab double cj\_out = cj[jCellOut];\newline
\btab \btab \btab eta = Math.Max(eta, penalty\_base * cj\_out);\newline
\btab \btab \}\newline
\btab \btab return eta;\newline
\btab \}\newline
/// The following functions cover the actual math.
/// For any discretization of the Laplace operator, we have to specify:
/// \begin{itemize}
/// \item a volume integrand,
/// \item an edge integrand for inner edges, i.e. on $\Gamma_i$,
/// \item an edge integrand for boundary edges, i.e. on $\partial \Omega$.
/// \end{itemize}
/// The integrand for the volume integral:
\btab public double VolumeForm(ref CommonParamsVol cpv, \newline
\btab \btab double[] U, double[,] GradU, // the trial-function u \newline
\btab \btab // (i.e. the function we search for) and its gradient\newline
\btab \btab double V, double[] GradV // the test function; \newline
\btab \btab ) \{\newline
\newline
\btab \btab double acc = 0;\newline
\btab \btab for(int d = 0; d < cpv.D; d++)\newline
\btab \btab \btab acc += GradU[0, d] * GradV[d];\newline
\btab \btab return acc;\newline
\btab \}\newline
/// The integrand for the integral on the inner edges,
/// \[
/// -( \mean{ \nabla u } \jump{ v }) \cdot \vec{n}_{\Gamma}
/// -( \mean{ \nabla v } \jump{ u }) \cdot \vec{n}_{\Gamma}
/// + \eta \jump{ u } \jump{v} :
/// \]
\btab public double InnerEdgeForm(ref CommonParams inp, \newline
\btab \btab double[] U\_IN, double[] U\_OT, double[,] GradU\_IN, double[,] GradU\_OT, \newline
\btab \btab double V\_IN, double V\_OT, double[] GradV\_IN, double[] GradV\_OT) \{\newline
\newline
\btab \btab double eta = PenaltyFactor(inp.jCellIn, inp.jCellOut);\newline
\newline
\btab \btab double Acc = 0.0;\newline
\btab \btab for(int d = 0; d < inp.D; d++) \{ // loop over vector components \newline
\btab \btab \btab // consistency term: -(\{\{ \textbackslash /u \}\} [[ v ]])*Normale\newline
\btab \btab \btab // index d: spatial direction\newline
\btab \btab \btab Acc -= 0.5 * (GradU\_IN[0, d] + GradU\_OT[0, d])*(V\_IN - V\_OT)\newline
\btab \btab \btab \btab \btab * inp.Normale[d];\newline
\newline
\btab \btab \btab // symmetry term: -(\{\{ \textbackslash /v \}\} [[ u ]])*Normale\newline
\btab \btab \btab Acc -= 0.5 * (GradV\_IN[d] + GradV\_OT[d])*(U\_IN[0] - U\_OT[0])\newline
\btab \btab \btab \btab \btab * inp.Normale[d];;\newline
\btab \btab \}\newline
\newline
\btab \btab // penalty term: eta*[[u]]*[[v]]\newline
\btab \btab Acc += eta*(U\_IN[0] - U\_OT[0])*(V\_IN - V\_OT);\newline
\btab \btab return Acc;\newline
\btab \} \newline
/// The integrand on boundary edges, i.e. on $\partial \Omega$, is
/// \[
/// -( \mean{ \nabla u } \jump{ v }) \cdot \vec{n}_{\Gamma}
/// -( \mean{ \nabla v } \jump{ u }) \cdot \vec{n}_{\Gamma}
/// + \eta \jump{ u } \jump{v} .
/// \]
/// For the boundary we have to consider the special definition for
/// the mean-value operator $\mean{-}$ and the jump operator
/// $\jump{-}$ on the boundary.
\btab public double BoundaryEdgeForm(ref CommonParamsBnd inp, \newline
\btab \btab double[] U\_IN, double[,] GradU\_IN, double V\_IN, double[] GradV\_IN) \{\newline
\newline
\btab \btab double eta = PenaltyFactor(inp.jCellIn, -1);\newline
\btab \btab double Acc = 0.0;\newline
\btab \btab for(int d = 0; d < inp.D; d++) \{ // loop over vector components \newline
\btab \btab \btab // consistency term: -(\{\{ \textbackslash /u \}\} [[ v ]])*Normale\newline
\btab \btab \btab // index d: spatial direction\newline
\btab \btab \btab Acc -= (GradU\_IN[0, d])*(V\_IN) * inp.Normale[d];\newline
\newline
\btab \btab \btab // symmetry term: -(\{\{ \textbackslash /v \}\} [[ u ]])*Normale\newline
\btab \btab \btab Acc -= (GradV\_IN[d])*(U\_IN[0]) * inp.Normale[d];;\newline
\btab \btab \}\newline
\newline
\btab \btab // penalty term: eta*[[u]]*[[v]]\newline
\btab \btab Acc += eta*(U\_IN[0])*(V\_IN);\newline
\newline
\newline
\btab \btab return Acc;\newline
\btab \}\newline
\}
}
\BoSSSexe
\BoSSScmd{
/// \subsection{Evaluation of the poisson operator in 1D}
/// We consider the following problem:
/// \begin{equation*}
/// \Delta u = 2,\quad -1<x<1,\quad u(-1)=u(1)=0.
/// \end{equation*}
/// The solution is $u_{ex}(x) = 1 - x^2$. Since this is quadratic, we can represent it \emph{exactly} in a DG space of order 2.
/// As usual, we have to set up a grid and a basis:
var grd1D = Grid1D.LineGrid(GenericBlas.Linspace(-1,1,10));\newline
var gdata1D = new GridData(grd1D);\newline
var DGBasisOn1D = new Basis(gdata1D,2);\newline
/// and a right-hand-side:
var RHS = new SinglePhaseField(DGBasisOn1D, "RHS");\newline
RHS.ProjectField((double x) => 2);\newline
/// We have to ensure to set the \code{PolynomialDegree} in the \emph{SipLaplace}-object.
var i\_SipLaplace = new SipLaplace();\newline
i\_SipLaplace.PolynomialDegree = DGBasisOn1D.Degree;\newline
i\_SipLaplace.cj = gdata1D.Cells.cj;\newline
var Operator\_SipLaplace = i\_SipLaplace.Operator();\newline
/// We now want to calculate the residual after inserting the exact solution as well as a wrong solution.
/// The implementation of the exact solution:
var u\_ex = new SinglePhaseField(DGBasisOn1D, "$u\_\{ex\}$");\newline
u\_ex.ProjectField((double x) => 1.0 - x*x);\newline
/// The implementation of a spurious, i.e. a wrong solution; we take the exact solution and add random values in each cell:
var u\_wrong = new SinglePhaseField(DGBasisOn1D, "$u\_\{wrong\}$");\newline
u\_wrong.ProjectField((double x) => 1.0 - x*x);\newline
Random R = new Random();\newline
for(int j = 0; j < gdata1D.Cells.NoOfLocalUpdatedCells; j++)\{\newline
\btab double ujMean = u\_wrong.GetMeanValue(j);\newline
\btab ujMean += R.NextDouble();\newline
\btab u\_wrong.SetMeanValue(j, ujMean);\newline
\btab \}\newline
/// Evaluating the Laplace operator using the different solutions:
var Residual = new SinglePhaseField(DGBasisOn1D,"Resi1");\newline
var ResidualNorm = new List<double>();\newline
foreach(var u in new DGField[] \{u\_ex, u\_wrong\}) \{\newline
\btab Residual.Clear();\newline
\btab Operator\_SipLaplace.Evaluate(u, Residual); // evaluate\newline
\btab Residual.Acc(-1.0, RHS); \newline
\btab double ResiNorm = Residual.L2Norm();\newline
\btab ResidualNorm.Add(ResiNorm);\newline
\btab Console.WriteLine("Residual for " + u.Identification + " = " + ResiNorm); \newline
\}
}
\BoSSSexe
\BoSSScmdSilent{
/// tests BoSSScmdSilent
Assert.LessOrEqual(ResidualNorm[0], 1e-10);\newline
Assert.GreaterOrEqual(ResidualNorm[1], 1e-1);
}
\BoSSSexe
\BoSSScmd{
/// \subsection{The matrix of the Poisson Operator}
/// If we do not know the exact solution, we have to solve a linear system.
/// Therefore, we not only need to evaluate the operator,
/// but we need its matrix.
/// The \emph{Mapping} controls which degree-of-freedom of the DG approximation
/// is mapped to which row, resp. column of the matrix.
var Mapping = new UnsetteledCoordinateMapping(DGBasisOn1D);\newline
var Matrix\_SipLaplace = Operator\_SipLaplace.ComputeMatrix(Mapping,null,Mapping);
}
\BoSSSexe
\BoSSScmd{
Matrix\_SipLaplace.NoOfCols;
}
\BoSSSexe
\BoSSScmd{
Matrix\_SipLaplace.NoOfRows;
}
\BoSSSexe
\BoSSScmd{
/// We see that the matrix has 27 rows and columns.
}
\BoSSSexe
\BoSSScmd{
/// \paragraph{Matrix rank and determinant of the matrix
/// \code{Matrix\_SipLaplace}:}
/// Use the functions \emph{rank} and \emph{det} to analyze the matrix (warning: this can get costly
/// for larger matrices!).\\
///Interpret the results:
/// \begin{itemize}
/// \item What does it mean, when a matrix has full rank?
/// \item How many solutions can a linear system have?
/// \end{itemize}
double rank = Matrix\_SipLaplace.rank(); \newline
Console.WriteLine("Matrix rank = " + rank);\newline
\newline
double det = Matrix\_SipLaplace.det(); \newline
Console.WriteLine("Determinante = " + det);\newline
/// So the matrix of the SIP discretization has a unique solution.
}
\BoSSSexe
\BoSSScmdSilent{
/// tests BoSSScmdSilent
Assert.AreEqual(rank, Matrix\_SipLaplace.NoOfCols);\newline
Assert.Greater(det, 1.0);
}
\BoSSSexe
\BoSSScmd{
%
}
\BoSSSexe
\BoSSScmd{
/// \section{Advanced topics}
}
\BoSSSexe
\BoSSScmd{
/// %========================================================
/// %========================================================
/// \subsection{The penalty parameter of the SIP and stability in 2D}
/// %========================================================
/// %========================================================
}
\BoSSSexe
\BoSSScmd{
/// We define a two-dimensional grid:
var grd2D = Grid2D.Cartesian2DGrid(GenericBlas.Linspace(-1,1,21), \newline
\btab \btab \btab \btab \btab \btab \btab \btab \btab \btab GenericBlas.Linspace(-1,1,16));\newline
var gdata2D = new GridData(grd2D);\newline
var DGBasisOn2D = new Basis(gdata2D, 5);\newline
var Mapping2D = new UnsetteledCoordinateMapping(DGBasisOn2D);
}
\BoSSSexe
\BoSSScmd{
/// We are going to choose the \code{PenaltySafety} for the \code{SipLaplace}
/// from the following list
double[] SFs = new double[] \newline
\btab \{0.001, 0.002, 0.01, 0.02, 0.1, 0.2, 1, 2, 10, 20, 100\};\newline
/// and compute the condition number as well as the determinate.
}
\BoSSSexe
\BoSSScmd{
/// We consider the example
/// \[
/// -\Delta u = \pi^2 0.5 \cos(x/2) \cos(y/2)
/// \text{ with }
/// (x,y) \in (-1,1)^2
/// \]
/// and $u = 0$ on the boundary.
/// The exact solution is $u_{Ex}(x,y) = \cos(x/2) \cos(y/2)$.
Func<double[], double> exSol = \newline
\btab \btab (X => Math.Cos(X[0]*Math.PI*0.5)*Math.Cos(X[1]*Math.PI*0.5));\newline
Func<double[], double> exRhs = \newline
\btab \btab (X => (Math.PI*Math.PI*0.5*Math.Cos(X[0]*Math.PI*0.5)\newline
\btab \btab \btab \btab \btab *Math.Cos(X[1]*Math.PI*0.5))); // == - /\textbackslash exSol\newline
SinglePhaseField RHS = new SinglePhaseField(DGBasisOn2D, "RHS");\newline
RHS.ProjectField(exRhs);\newline
double[] RHSvec = RHS.CoordinateVector.ToArray();
}
\BoSSSexe
\BoSSScmd{
/// We check our discretization once more in 2D; the residual should be low,
/// but not exactly (resp. up to $10^{-12}$) since the solution is not
/// polynomial and cannot be fulfilled exactly.
SinglePhaseField u = new SinglePhaseField(DGBasisOn2D,"u");\newline
u.ProjectField(exSol);\newline
i\_SipLaplace.PolynomialDegree = DGBasisOn2D.Degree;\newline
i\_SipLaplace.cj = gdata2D.Cells.cj;\newline
var Matrix\_SIP\_sf = Operator\_SipLaplace.ComputeMatrix(Mapping2D,\newline
\btab \btab \btab \btab \btab \btab \btab \btab \btab \btab \btab \btab \btab \btab null,\newline
\btab \btab \btab \btab \btab \btab \btab \btab \btab \btab \btab \btab \btab \btab Mapping2D);\newline
SinglePhaseField Residual = new SinglePhaseField(DGBasisOn2D,"Residual");\newline
Residual.Acc(1.0, RHS);\newline
Matrix\_SIP\_sf.SpMV(-1.0, u.CoordinateVector, 1.0, Residual.CoordinateVector);\newline
Console.WriteLine("Residual L2 norm: " + Residual.L2Norm());
}
\BoSSSexe
\BoSSScmd{
/// We also check that the matrix is symmetric:
var checkMatrix = Matrix\_SIP\_sf - Matrix\_SIP\_sf.Transpose();\newline
checkMatrix.InfNorm();
}
\BoSSSexe
\BoSSScmdSilent{
/// tests BoSSScmdSilent
Assert.LessOrEqual(checkMatrix.InfNorm(), 1e-8);
}
\BoSSSexe
\BoSSScmd{
/// \paragraph{Matrix properties for different penalty factors.}
/// Now, we assemble the matrix of the SIP for different
/// \code{PenaltySafety}-factors. We also try to solve the linear system
/// using an iterative method. As Matlab is called multiple times during this
/// command, it can take some minutes until it is done.
int cnt = 0;\newline
var Results = new List<Tuple<double,double,int,double,bool>>();\newline
foreach(double sf in SFs) \{\newline
\btab cnt++;\newline
\btab i\_SipLaplace.PenaltySafety = sf;\newline
\btab i\_SipLaplace.PolynomialDegree = DGBasisOn2D.Degree;\newline
\btab var Matrix\_SIP\_sf = Operator\_SipLaplace.ComputeMatrix(\newline
\btab \btab \btab \btab \btab \btab \btab \btab \btab Mapping2D,null,Mapping2D);\newline
\btab double condNo1 = Matrix\_SIP\_sf.condest(); \newline
\btab bool definite = Matrix\_SIP\_sf.IsDefinite();\newline
\newline
/// We solve the system
/// \[
/// \text{\tt Matrix\_SIP\_sf} \cdot u = \text{\tt RHS}
/// \]
/// using a an iterative solver, the so-called
/// conjugate gradient (CG) method.
/// CG requires a positive definite matrix.
/// The function \code{Solve\_CG} returns the number of iterations.
\btab SinglePhaseField u = new SinglePhaseField(DGBasisOn2D,"u");\newline
\btab u.InitRandom();\newline
\btab int NoOfIter = Matrix\_SIP\_sf.Solve\_CG(u.CoordinateVector, RHSvec);\newline
\newline
\btab SinglePhaseField Error = new SinglePhaseField(DGBasisOn2D,"Error");\newline
\btab Error.ProjectField(exSol);\newline
\btab Error.Acc(-1.0, u);\newline
\newline
\btab double L2err = u.L2Error(exSol);\newline
\newline
\btab Console.WriteLine(sf + "\textbackslash t" + condNo1.ToString("0.#E-00") \newline
\btab \btab \btab \btab \btab \btab + "\textbackslash t" + NoOfIter \newline
\btab \btab \btab \btab \btab \btab + "\textbackslash t" + L2err.ToString("0.#E-00") \newline
\btab \btab \btab \btab \btab \btab + "\textbackslash t" + definite);\newline
\btab Results.Add(new Tuple<double,double,int,double,bool>(sf, condNo1, NoOfIter,\newline
\btab \btab \btab \btab \btab \btab \btab \btab L2err, definite));\newline
\}
}
\BoSSSexe
\BoSSScmdSilent{
/// tests BoSSScmdSilent
foreach(var r in Results) \{\newline
\btab if(r.Item1 >= 1 && r.Item1 <= 20) \{\newline
\btab \btab Assert.LessOrEqual(r.Item2, 1e7); // cond No.\newline
\btab \btab Assert.LessOrEqual(r.Item3, 6000); // iter\newline
\btab \btab Assert.LessOrEqual(r.Item4, 1e-4); // L2 err\newline
\btab \btab Assert.IsTrue(r.Item5); // definite \newline
\btab \}\newline
\btab if(r.Item1 <= 0.1) \{\newline
\btab \btab Assert.IsFalse(r.Item5); // indefinite \newline
\btab \}\newline
\}
}
\BoSSSexe
\BoSSScmd{
/// \paragraph{Plotting:}
/// Plot the number of conjugate gradient iterations versus the
/// \code{PenaltySafety}.
/// A logarithmic scale is used for the horizontal axis.
var format = new PlotFormat(lineColor: LineColors.Blue, \newline
\btab \btab \btab \btab \btab \btab \btab pointSize: 2, \newline
\btab \btab \btab \btab \btab \btab \btab dashType: DashTypes.DotDashed, \newline
\btab \btab \btab \btab \btab \btab \btab Style: Styles.LinesPoints, \newline
\btab \btab \btab \btab \btab \btab \btab pointType:PointTypes.OpenCircle);\newline
Gnuplot gp = new Gnuplot(baseLineFormat:format);\newline
gp.PlotLogXY(Results.Select(r => r.Item1), \newline
\btab \btab \btab Results.Select(r => ((double)(r.Item3))));\newline
gp.PlotNow();
}
\BoSSSexe
\BoSSScmd{
/// \paragraph{Convergence study, indefinite vs. definite.}
/// We are going to solve the SIP-system for different grid resolutions,
/// comparing an insufficient penalty to a penalty which is large enough.
double[] Resolution = new double[] \{ 8, 16, 32, 64, 128, 256 \};\newline
List<double> L2Error\_indef = new List<double>();\newline
List<double> L2Error\_posdef = new List<double>();\newline
foreach(int Res in Resolution) \{\newline
\btab var grd2D = Grid2D.Cartesian2DGrid(GenericBlas.Linspace(-1,1,(int)Res + 1), \newline
\btab \btab \btab \btab \btab \btab \btab \btab \btab GenericBlas.Linspace(-1,1,(int)Res + 1));\newline
\btab var gdata2D = new GridData(grd2D);\newline
\btab var DGBasisOn2D = new Basis(gdata2D, 2);\newline
\btab var Mapping2D = new UnsetteledCoordinateMapping(DGBasisOn2D);\newline
\newline
\btab SinglePhaseField RHS = new SinglePhaseField(DGBasisOn2D, "RHS");\newline
\btab RHS.ProjectField(exRhs);\newline
\btab SinglePhaseField uEx = new SinglePhaseField(\newline
\btab \btab new Basis(gdata2D, DGBasisOn2D.Degree*2),\newline
\btab \btab "Error");\newline
\btab uEx.ProjectField(exSol);\newline
\newline
\btab i\_SipLaplace.PolynomialDegree = DGBasisOn2D.Degree;\newline
\btab i\_SipLaplace.cj = gdata2D.Cells.cj;\newline
\newline
\btab i\_SipLaplace.PenaltySafety = 0.01;\newline
\btab var Matrix\_SIP\_indef = Operator\_SipLaplace.ComputeMatrix(\newline
\btab \btab \btab \btab \btab \btab \btab \btab \btab Mapping2D,null,Mapping2D);\newline
\newline
\btab SinglePhaseField u\_indef = new SinglePhaseField(DGBasisOn2D,"u");\newline
\btab Matrix\_SIP\_indef.Solve\_Direct(u\_indef.CoordinateVector, \newline
\btab \btab \btab \btab \btab \btab \btab \btab RHS.CoordinateVector);\newline
\btab var Error\_indef = uEx.CloneAs();\newline
\btab Error\_indef.AccLaidBack(-1.0, u\_indef);\newline
\btab L2Error\_indef.Add(Error\_indef.L2Norm());\newline
\newline
/// In order to have a positive definite system, we are
/// using $\text{\tt PenaltySafety} = 2$!
\btab i\_SipLaplace.PenaltySafety = 2.0;\newline
\btab var Matrix\_SIP\_posdef = Operator\_SipLaplace.ComputeMatrix(\newline
\btab \btab \btab \btab \btab \btab \btab \btab \btab Mapping2D,null,Mapping2D);\newline
\newline
\btab SinglePhaseField u\_posdef = new SinglePhaseField(DGBasisOn2D,"u");\newline
\btab Matrix\_SIP\_posdef.Solve\_Direct(u\_posdef.CoordinateVector, \newline
\btab \btab \btab \btab \btab \btab \btab \btab RHS.CoordinateVector);\newline
\btab var Error\_posdef = uEx.CloneAs();\newline
\btab Error\_posdef.AccLaidBack(-1.0, u\_posdef);\newline
\btab L2Error\_posdef.Add(Error\_posdef.L2Norm());\newline
\newline
\btab Console.WriteLine(L2Error\_indef.Last().ToString("0.#E-00") \newline
\btab \btab \btab \btab \btab + "\textbackslash t" + L2Error\_posdef.Last().ToString("0.#E-00"));\newline
\}
}
\BoSSSexe
\BoSSScmd{
/// \paragraph{Convergence plot:}
/// The convergence plot unveils that there is something wrong if the
/// penalty factor is set too low.
/// While the solution of the indefinite system may look right at the first
/// glance, we see that we do not obtain grid convergence for
/// \code{Error\_indef}.
/// The error of the positive definite system, \code{Error\_posdef}, where the
/// penalty is chosen sufficiently large converges with the expected
/// rate.
var format = new PlotFormat(lineColor: LineColors.Blue, \newline
\btab \btab \btab \btab \btab \btab \btab pointSize: 2, \newline
\btab \btab \btab \btab \btab \btab \btab dashType: DashTypes.DotDashed, \newline
\btab \btab \btab \btab \btab \btab \btab Style: Styles.LinesPoints, \newline
\btab \btab \btab \btab \btab \btab \btab pointType:PointTypes.OpenCircle);\newline
Gnuplot gp = new Gnuplot(baseLineFormat:format);\newline
gp.PlotLogXLogY(Resolution, L2Error\_indef);\newline
gp.PlotLogXLogY(Resolution, L2Error\_posdef);\newline
gp.PlotNow();
}
\BoSSSexe
\BoSSScmd{
/// Finally, we are going to compute the convergence rate of the SIP
/// discretization: we take the logarithm of the resolution and the error:
}
\BoSSSexe
\BoSSScmd{
var log\_h = Resolution.Select(h => Math.Log10(h)).ToArray();\newline
var log\_Err = L2Error\_posdef.Select(h => Math.Log10(h)).ToArray();
}
\BoSSSexe
\BoSSScmd{
var LeastSquaresSys = MultidimensionalArray.Create(log\_h.Length,2);\newline
LeastSquaresSys.SetColumn(0, log\_h.Length.ForLoop(i => 1.0));\newline
LeastSquaresSys.SetColumn(1, log\_h);\newline
double[] dk = new double[2]; // intercept and slope of best-fit line\newline
LeastSquaresSys.LeastSquareSolve(dk, log\_Err);
}
\BoSSSexe
\BoSSScmd{
dk;
}
\BoSSSexe
\BoSSScmdSilent{
/// tests BoSSScmdSilent
Assert.LessOrEqual(dk[1], -2.9);
}
\BoSSSexe
\BoSSScmd{
/// \section{Further reading}
/// \begin{itemize}
/// \item
/// \bibentry{DiPietroErn2011}
/// \item
/// \bibentry{Arnold_1982}
/// \end{itemize}
}
\BoSSSexe
|
/*
* Copyright 2019 GridGain Systems, Inc. and Contributors.
*
* Licensed under the GridGain Community Edition License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <boost/test/unit_test.hpp>
#include "sql_test_suite_fixture.h"
using namespace ignite;
using namespace boost::unit_test;
BOOST_FIXTURE_TEST_SUITE(SqlSystemFunctionTestSuite, ignite::SqlTestSuiteFixture)
BOOST_AUTO_TEST_CASE(TestSystemFunctionDatabase)
{
CheckSingleResult<std::string>("SELECT {fn DATABASE()}");
}
BOOST_AUTO_TEST_CASE(TestSystemFunctionUser)
{
CheckSingleResult<std::string>("SELECT {fn USER()}");
}
BOOST_AUTO_TEST_CASE(TestSystemFunctionIfnull)
{
CheckSingleResult<SQLINTEGER>("SELECT {fn IFNULL(NULL, 42)}", 42);
}
BOOST_AUTO_TEST_SUITE_END()
|
// Copyright (C) 2016 Gideon May ([email protected])
//
// Permission to copy, use, sell and distribute this software is granted
// provided this copyright notice appears in all copies.
// Permission to modify the code and to distribute modified code is granted
// provided this copyright notice appears in all copies, and a notice
// that the code was modified is included with the copyright notice.
//
// This software is provided "as is" without express or implied warranty,
// and with no claim as to its suitability for any purpose.
// TODO missing docs and functors (partially implemented)
#include <boost/python.hpp>
#include <boost/ref.hpp>
#include <osg/Drawable>
#include <osg/NodeVisitor>
#include <osg/TriangleFunctor>
#include <string>
#include <iostream>
#include "Drawable.hpp"
#include "held_ptr.hpp"
#include "Math.hpp"
using namespace boost::python;
namespace {
// Reference http://www.boost.org/libs/python/doc/tutorial/doc/class_virtual_functions.html
// free caller functions
/** Clone the type of an object, with Object* return type. Must be defined by derived classes.*/
osg::Object* call_cloneType(osg::Object& obj) { return obj.cloneType(); }
/** Clone the an object, with Object* return type. Must be defined by derived classes.*/
osg::Object* call_clone(osg::Object& obj, const osg::CopyOp& copyop) { return obj.clone(copyop); }
void call_drawImplementation(osg::Drawable& obj, osg::RenderInfo& info) { obj.drawImplementation(info); }
class DrawableWrapper : public osg::Drawable {
public:
DrawableWrapper(PyObject* self_)
: self(self_) {}
osg::Object* cloneType() const { return call_method<osg::Object*>(self, "cloneType"); }
osg::Object* clone(const osg::CopyOp& copyop) const { return call_method<osg::Object*>(self, "clone", copyop); }
void drawImplementation(osg::State& state) const { return call_method<void>(self, "drawImplementation", state); }
PyObject* self;
};
} // namespace
namespace PyOSG {
class UpdateCallback : public osg::Drawable::UpdateCallback
{
public:
UpdateCallback(PyObject * p) : _self(p) {
// std::cerr << "UpdateCallback:ctor\n";
Py_XINCREF(_self);
}
~UpdateCallback()
{
Py_XDECREF(_self);
}
virtual void update(osg::NodeVisitor *visitor, osg::Drawable* drawable)
{
// std::cerr << "UpdateCallback:update\n";
try {
call_method<void>(_self, "update", ptr(visitor), ptr(drawable));
} catch(...) {
handle_exception();
PyErr_Print();
throw_error_already_set();
}
}
virtual void update_imp(osg::NodeVisitor *visitor, osg::Drawable* drawable)
{
// is a pure virtual function
// this->osg::Drawable::UpdateCallback::update(node, nv);
}
private:
PyObject * _self;
};
class CullCallback : public osg::Drawable::CullCallback
{
public:
CullCallback(PyObject * p) : _self(p) {
Py_XINCREF(_self);
}
~CullCallback()
{
Py_XDECREF(_self);
}
virtual bool cull(osg::NodeVisitor *visitor, osg::Drawable* drawable, osg::State * state) const
{
try {
return (bool) call_method<int>(_self, "cull", ptr(visitor), ptr(drawable), ptr(state));
} catch(...) {
handle_exception();
PyErr_Print();
throw_error_already_set();
return false;
}
}
virtual void cull_imp(osg::NodeVisitor *visitor, osg::Drawable* drawable)
{
// is a pure virtual function
// this->osg::Drawable::CullCallback::cull(node, nv);
}
private:
PyObject * _self;
};
class DrawCallback : public osg::Drawable::DrawCallback
{
public:
DrawCallback(PyObject * p) : _self(p) {
Py_XINCREF(_self);
}
~DrawCallback() {
Py_XDECREF(_self);
}
/** do customized draw code.*/
virtual void drawImplementation(osg::State& state,const osg::Drawable* drawable) const
{
try {
call_method<void>(_self, "drawImplementation", ptr(&state), ptr(drawable));
return;
} catch(...) {
handle_exception();
PyErr_Print();
throw_error_already_set();
return;
}
}
virtual void drawImplementation_imp(osg::RenderInfo& info, const osg::Drawable* drawable) const
{
// FIXME!
this->osg::Drawable::DrawCallback::drawImplementation(info, drawable);
}
private:
PyObject * _self;
};
tuple getParents(osg::Drawable& self)
{
list plist;
osg::Drawable::ParentList::const_iterator piter;
// FIXME
#if 0
for(piter = self.getParents().begin(); piter < self.getParents().end(); piter++) {
plist.append(object(const_cast<osg::Node *>(* piter)));
}
#endif
return tuple(piter);
}
} // namespace
namespace PyOSG {
class_Drawable * DrawableClass = NULL;
void init_Drawable()
{
DrawableClass = new class_Drawable("Drawable",
"Pure virtual base class for drawable Geometry. Contains no drawing primitives\n"
"directly, these are provided by subclasses such as osg::Geometry. State attributes \n"
"for a Drawable are maintained in StateSet which the Drawable maintains\n"
"a referenced counted pointer to. Both Drawable's and StateSet's can \n"
"be shared for optimal memory usage and graphics performance.\n",
no_init);
scope drawable_class(*DrawableClass);
(*DrawableClass)
.def("cloneType", &call_cloneType, return_internal_reference<>())
.def("clone", &call_clone, return_internal_reference<>())
.def("getParents",
&getParents,
"Get the parent list of drawable.\n")
// FIXME
#if 0
.def("getParent",
(osg::Node *(osg::Drawable::*)(unsigned int))
&osg::Drawable::getParent,
return_value_policy<manage_osg_object>())
#endif
.def("getNumParents",
&osg::Drawable::getNumParents)
.def("setStateSet",
&osg::Drawable::setStateSet)
.def("getStateSet",
(osg::StateSet * ( osg::Drawable::*)())
&osg::Drawable::getStateSet,
return_value_policy<manage_osg_object>())
.def("getOrCreateStateSet",
(osg::StateSet * ( osg::Drawable::*)())
&osg::Drawable::getOrCreateStateSet,
return_value_policy<manage_osg_object>())
.def("dirtyBound", &osg::Drawable::dirtyBound)
.def("getBound",
&osg::Drawable::getBound,
return_value_policy<copy_const_reference>())
.def("setShape",
&osg::Drawable::setShape)
.def("getShape",
(osg::Shape *(osg::Drawable::*)())
&osg::Drawable::getShape,
return_value_policy<manage_osg_object>())
.def("setSupportsDisplayList",
&osg::Drawable::setSupportsDisplayList)
.def("getSupportsDisplayList",
&osg::Drawable::getSupportsDisplayList)
.def("setUseDisplayList",
&osg::Drawable::setUseDisplayList)
.def("getUseDisplayList",
&osg::Drawable::getUseDisplayList)
.def("setUseVertexBufferObjects", &osg::Drawable::setUseVertexBufferObjects)
.def("getUseVertexBufferObjects", &osg::Drawable::getUseVertexBufferObjects)
.def("dirtyDisplayList",
&osg::Drawable::dirtyDisplayList)
.def("draw", &osg::Drawable::draw)
.def("compileGLObjects", &osg::Drawable::compileGLObjects)
.def("setUpdateCallback", &osg::Drawable::setUpdateCallback)
.def("setCullCallback", &osg::Drawable::setCullCallback)
.def("setDrawCallback", &osg::Drawable::setDrawCallback)
// &osg::Drawable::getDrawCallback, return_internal_reference<>())
.def("drawImplementation", &osg::Drawable::drawImplementation)
.def("drawImplementation", &call_drawImplementation)
.def("deleteDisplayList", &osg::Drawable::deleteDisplayList)
.def("flushDeletedDisplayLists", &osg::Drawable::flushDeletedDisplayLists)
// FIXME
#if 0
.def("deleteVertexBufferObject", &osg::Drawable::deleteVertexBufferObject)
.def("flushDeletedVertexBufferObjects", &osg::Drawable::flushDeletedVertexBufferObjects)
.def("getExtensions", &osg::Drawable::getExtensions, return_internal_reference<>())
.def("setExtensions", &osg::Drawable::setExtensions)
#endif
;
class_<osg::Drawable::UpdateCallback, osg::ref_ptr<UpdateCallback>, bases<osg::Referenced>, boost::noncopyable>("UpdateCallback", no_init)
.def(init<>()) // calls the derived init function
.def("update", &UpdateCallback::update_imp)
;
class_<osg::Drawable::CullCallback, osg::ref_ptr<CullCallback>, bases<osg::Referenced>, boost::noncopyable>("CullCallback", no_init)
.def(init<>()) // calls the derived init function
.def("cull", &CullCallback::cull_imp)
;
class_<osg::Drawable::DrawCallback, osg::ref_ptr<DrawCallback>, bases<osg::Referenced>, boost::noncopyable>("DrawCallback", no_init)
.def(init<>()) // calls the derived init function
.def("drawImplementation", &DrawCallback::drawImplementation_imp)
;
class_<osg::Drawable::AttributeFunctor> attrFunctor("AttributeFunctor");
attrFunctor
.def(init<>())
// .def("apply", &osg::Drawable::AttributeFunctor::apply)
;
// FIXME !!!
#if 0
class_<osg::Drawable::Extensions, osg::ref_ptr<osg::Drawable::Extensions>, bases<osg::Referenced>, boost::noncopyable> extensions("Extensions", no_init);
extensions
.def(init<unsigned int>())
//.def("lowestCommonDenominator", &osg::Drawable::Extensions::lowestCommonDenominator)
.def("setupGLExtenions", &osg::Drawable::Extensions::setupGLExtenions)
.def("setVertexProgramSupported", &osg::Drawable::Extensions::setVertexProgramSupported)
.def("isVertexProgramSupported", &osg::Drawable::Extensions::isVertexProgramSupported)
.def("setSecondaryColorSupported", &osg::Drawable::Extensions::setSecondaryColorSupported)
.def("isSecondaryColorSupported", &osg::Drawable::Extensions::isSecondaryColorSupported)
.def("setFogCoordSupported", &osg::Drawable::Extensions::setFogCoordSupported)
.def("isFogCoordSupported", &osg::Drawable::Extensions::isFogCoordSupported)
.def("setMultiTexSupported", &osg::Drawable::Extensions::setMultiTexSupported)
.def("isMultiTexSupported", &osg::Drawable::Extensions::isMultiTexSupported)
.def("setOcclusionQuerySupported", &osg::Drawable::Extensions::setOcclusionQuerySupported)
.def("isOcclusionQuerySupported", &osg::Drawable::Extensions::isOcclusionQuerySupported)
.def("setARBOcclusionQuerySupported", &osg::Drawable::Extensions::setARBOcclusionQuerySupported)
.def("isARBOcclusionQuerySupported", &osg::Drawable::Extensions::isARBOcclusionQuerySupported)
.def("glSecondaryColor3ubv", &osg::Drawable::Extensions::glSecondaryColor3ubv)
.def("glSecondaryColor3fv", &osg::Drawable::Extensions::glSecondaryColor3fv)
.def("glFogCoordfv", &osg::Drawable::Extensions::glFogCoordfv)
.def("glMultiTexCoord1f", &osg::Drawable::Extensions::glMultiTexCoord1f)
.def("glMultiTexCoord2fv", &osg::Drawable::Extensions::glMultiTexCoord2fv)
.def("glMultiTexCoord3fv", &osg::Drawable::Extensions::glMultiTexCoord3fv)
.def("glMultiTexCoord4fv", &osg::Drawable::Extensions::glMultiTexCoord4fv)
.def("glVertexAttrib1s", &osg::Drawable::Extensions::glVertexAttrib1s)
.def("glVertexAttrib1f", &osg::Drawable::Extensions::glVertexAttrib1f)
.def("glVertexAttrib2fv", &osg::Drawable::Extensions::glVertexAttrib2fv)
.def("glVertexAttrib3fv", &osg::Drawable::Extensions::glVertexAttrib3fv)
.def("glVertexAttrib4fv", &osg::Drawable::Extensions::glVertexAttrib4fv)
.def("glVertexAttrib4ubv", &osg::Drawable::Extensions::glVertexAttrib4ubv)
.def("glVertexAttrib4Nubv", &osg::Drawable::Extensions::glVertexAttrib4Nubv)
.def("glGenBuffers", &osg::Drawable::Extensions::glGenBuffers)
.def("glBindBuffer", &osg::Drawable::Extensions::glBindBuffer)
// XXX .def("glBufferData", &osg::Drawable::Extensions::glBufferData)
// XXX .def("glBufferSubData", &osg::Drawable::Extensions::glBufferSubData)
.def("glDeleteBuffers", &osg::Drawable::Extensions::glDeleteBuffers)
.def("glGenOcclusionQueries", &osg::Drawable::Extensions::glGenOcclusionQueries)
.def("glDeleteOcclusionQueries", &osg::Drawable::Extensions::glDeleteOcclusionQueries)
.def("glIsOcclusionQuery", &osg::Drawable::Extensions::glIsOcclusionQuery) //returns a GLboolean
.def("glBeginOcclusionQuery", &osg::Drawable::Extensions::glBeginOcclusionQuery)
.def("glEndOcclusionQuery", &osg::Drawable::Extensions::glEndOcclusionQuery)
.def("glGetOcclusionQueryiv", &osg::Drawable::Extensions::glGetOcclusionQueryiv)
.def("glGetOcclusionQueryuiv", &osg::Drawable::Extensions::glGetOcclusionQueryuiv)
.def("glGetQueryiv", &osg::Drawable::Extensions::glGetQueryiv)
.def("glGenQueries", &osg::Drawable::Extensions::glGenQueries)
.def("glBeginQuery", &osg::Drawable::Extensions::glBeginQuery)
.def("glEndQuery", &osg::Drawable::Extensions::glEndQuery)
.def("glIsQuery", &osg::Drawable::Extensions::glIsQuery) // returns GLboolean
.def("glGetQueryObjectiv", &osg::Drawable::Extensions::glGetQueryObjectiv)
.def("glGetQueryObjectuiv", &osg::Drawable::Extensions::glGetQueryObjectuiv)
;
#endif
# define OSG_ENUM_TYPE(VALUE) type.value(#VALUE, osg::Drawable::VALUE)
enum_<osg::Drawable::AttributeTypes> type("AttributeTypes");
OSG_ENUM_TYPE(VERTICES);
OSG_ENUM_TYPE(WEIGHTS);
OSG_ENUM_TYPE(NORMALS);
OSG_ENUM_TYPE(COLORS);
OSG_ENUM_TYPE(SECONDARY_COLORS);
OSG_ENUM_TYPE(FOG_COORDS);
OSG_ENUM_TYPE(ATTRIBUTE_6);
OSG_ENUM_TYPE(ATTRIBUTE_7);
OSG_ENUM_TYPE(TEXTURE_COORDS);
OSG_ENUM_TYPE(TEXTURE_COORDS_0);
OSG_ENUM_TYPE(TEXTURE_COORDS_1);
OSG_ENUM_TYPE(TEXTURE_COORDS_2);
OSG_ENUM_TYPE(TEXTURE_COORDS_3);
OSG_ENUM_TYPE(TEXTURE_COORDS_4);
OSG_ENUM_TYPE(TEXTURE_COORDS_5);
OSG_ENUM_TYPE(TEXTURE_COORDS_6);
OSG_ENUM_TYPE(TEXTURE_COORDS_7);
type.export_values();
}
} // namespace PyOSG
|
/-
Copyright (c) 2020 Jujian Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jujian Zhang, Johan Commelin
From: https://github.com/leanprover-community/mathlib/blob/ae10dceda978370b312f93a53a0e93fd2157d5bf/src/algebraic_geometry/projective_spectrum/topology.lean
-/
import topology.category.Top
import .homogeneous_ideal
/-!
# Projective spectrum of a graded ring
The projective spectrum of a graded commutative ring is the subtype of all homogenous ideals that
are prime and do not contain the irrelevant ideal.
It is naturally endowed with a topology: the Zariski topology.
## Notation
- `R` is a commutative semiring;
- `A` is a commutative ring and an `R`-algebra;
- `𝒜 : ℕ → submodule R A` is the grading of `A`;
## Main definitions
* `projective_spectrum 𝒜`: The projective spectrum of a graded ring `A`, or equivalently, the set of
all homogeneous ideals of `A` that is both prime and relevant i.e. not containing irrelevant
ideal. Henceforth, we call elements of projective spectrum *relevant homogeneous prime ideals*.
* `projective_spectrum.zero_locus 𝒜 s`: The zero locus of a subset `s` of `A`
is the subset of `projective_spectrum 𝒜` consisting of all relevant homogeneous prime ideals that
contain `s`.
* `projective_spectrum.vanishing_ideal t`: The vanishing ideal of a subset `t` of
`projective_spectrum 𝒜` is the intersection of points in `t` (viewed as relevant homogeneous prime
ideals).
* `projective_spectrum.Top`: the topological space of `projective_spectrum 𝒜` endowed with the
Zariski topology
-/
noncomputable theory
open_locale direct_sum big_operators pointwise
open direct_sum set_like Top topological_space category_theory opposite
variables {R A: Type*}
variables [comm_semiring R] [comm_ring A] [algebra R A]
variables (𝒜 : ℕ → submodule R A) [graded_algebra 𝒜]
/--
The projective spectrum of a graded commutative ring is the subtype of all homogenous ideals that
are prime and do not contain the irrelevant ideal.
-/
@[nolint has_inhabited_instance]
def projective_spectrum :=
{I : homogeneous_ideal 𝒜 // I.to_ideal.is_prime ∧ ¬(homogeneous_ideal.irrelevant 𝒜 ≤ I)}
namespace projective_spectrum
variable {𝒜}
/-- A method to view a point in the projective spectrum of a graded ring
as a homogeneous ideal of that ring. -/
abbreviation as_homogeneous_ideal (x : projective_spectrum 𝒜) : homogeneous_ideal 𝒜 := x.1
lemma as_homogeneous_ideal_def (x : projective_spectrum 𝒜) :
x.as_homogeneous_ideal = x.1 := rfl
instance is_prime (x : projective_spectrum 𝒜) :
x.as_homogeneous_ideal.to_ideal.is_prime := x.2.1
@[ext] lemma ext {x y : projective_spectrum 𝒜} :
x = y ↔ x.as_homogeneous_ideal = y.as_homogeneous_ideal :=
subtype.ext_iff_val
variable (𝒜)
/-- The zero locus of a set `s` of elements of a commutative ring `A`
is the set of all relevant homogeneous prime ideals of the ring that contain the set `s`.
An element `f` of `A` can be thought of as a dependent function on the projective spectrum of `𝒜`.
At a point `x` (a homogeneous prime ideal)
the function (i.e., element) `f` takes values in the quotient ring `A` modulo the prime ideal `x`.
In this manner, `zero_locus s` is exactly the subset of `projective_spectrum 𝒜`
where all "functions" in `s` vanish simultaneously. -/
def zero_locus (s : set A) : set (projective_spectrum 𝒜) :=
{x | s ⊆ x.as_homogeneous_ideal}
@[simp] lemma mem_zero_locus (x : projective_spectrum 𝒜) (s : set A) :
x ∈ zero_locus 𝒜 s ↔ s ⊆ x.as_homogeneous_ideal := iff.rfl
@[simp] lemma zero_locus_span (s : set A) :
zero_locus 𝒜 (ideal.span s) = zero_locus 𝒜 s :=
by { ext x, exact (submodule.gi _ _).gc s x.as_homogeneous_ideal.to_ideal }
variable {𝒜}
/-- The vanishing ideal of a set `t` of points
of the prime spectrum of a commutative ring `R`
is the intersection of all the prime ideals in the set `t`.
An element `f` of `A` can be thought of as a dependent function on the projective spectrum of `𝒜`.
At a point `x` (a homogeneous prime ideal)
the function (i.e., element) `f` takes values in the quotient ring `A` modulo the prime ideal `x`.
In this manner, `vanishing_ideal t` is exactly the ideal of `A`
consisting of all "functions" that vanish on all of `t`. -/
def vanishing_ideal (t : set (projective_spectrum 𝒜)) : homogeneous_ideal 𝒜 :=
⨅ (x : projective_spectrum 𝒜) (h : x ∈ t), x.as_homogeneous_ideal
lemma coe_vanishing_ideal (t : set (projective_spectrum 𝒜)) :
(vanishing_ideal t : set A) =
{f | ∀ x : projective_spectrum 𝒜, x ∈ t → f ∈ x.as_homogeneous_ideal} :=
begin
ext f,
rw [vanishing_ideal, set_like.mem_coe, ← homogeneous_ideal.mem_iff,
homogeneous_ideal.to_ideal_infi, submodule.mem_infi],
apply forall_congr (λ x, _),
rw [homogeneous_ideal.to_ideal_infi, submodule.mem_infi, homogeneous_ideal.mem_iff],
end
lemma mem_vanishing_ideal (t : set (projective_spectrum 𝒜)) (f : A) :
f ∈ vanishing_ideal t ↔
∀ x : projective_spectrum 𝒜, x ∈ t → f ∈ x.as_homogeneous_ideal :=
by rw [← set_like.mem_coe, coe_vanishing_ideal, set.mem_set_of_eq]
@[simp] lemma vanishing_ideal_singleton (x : projective_spectrum 𝒜) :
vanishing_ideal ({x} : set (projective_spectrum 𝒜)) = x.as_homogeneous_ideal :=
by simp [vanishing_ideal]
lemma subset_zero_locus_iff_le_vanishing_ideal (t : set (projective_spectrum 𝒜))
(I : ideal A) :
t ⊆ zero_locus 𝒜 I ↔ I ≤ (vanishing_ideal t).to_ideal :=
⟨λ h f k, (mem_vanishing_ideal _ _).mpr (λ x j, (mem_zero_locus _ _ _).mpr (h j) k), λ h,
λ x j, (mem_zero_locus _ _ _).mpr (le_trans h (λ f h, ((mem_vanishing_ideal _ _).mp h) x j))⟩
variable (𝒜)
/-- `zero_locus` and `vanishing_ideal` form a galois connection. -/
lemma gc_ideal : @galois_connection
(ideal A) (set (projective_spectrum 𝒜))ᵒᵈ _ _
(λ I, zero_locus 𝒜 I) (λ t, (vanishing_ideal t).to_ideal) :=
λ I t, subset_zero_locus_iff_le_vanishing_ideal t I
/-- `zero_locus` and `vanishing_ideal` form a galois connection. -/
lemma gc_set : @galois_connection
(set A) (set (projective_spectrum 𝒜))ᵒᵈ _ _
(λ s, zero_locus 𝒜 s) (λ t, vanishing_ideal t) :=
have ideal_gc : galois_connection (ideal.span) coe := (submodule.gi A _).gc,
by simpa [zero_locus_span, function.comp] using galois_connection.compose ideal_gc (gc_ideal 𝒜)
lemma gc_homogeneous_ideal : @galois_connection
(homogeneous_ideal 𝒜) (set (projective_spectrum 𝒜))ᵒᵈ _ _
(λ I, zero_locus 𝒜 I) (λ t, (vanishing_ideal t)) :=
λ I t, by simpa [show I.to_ideal ≤ (vanishing_ideal t).to_ideal ↔ I ≤ (vanishing_ideal t),
from iff.rfl] using subset_zero_locus_iff_le_vanishing_ideal t I.to_ideal
lemma subset_zero_locus_iff_subset_vanishing_ideal (t : set (projective_spectrum 𝒜))
(s : set A) :
t ⊆ zero_locus 𝒜 s ↔ s ⊆ vanishing_ideal t :=
(gc_set _) s t
lemma subset_vanishing_ideal_zero_locus (s : set A) :
s ⊆ vanishing_ideal (zero_locus 𝒜 s) :=
(gc_set _).le_u_l s
lemma ideal_le_vanishing_ideal_zero_locus (I : ideal A) :
I ≤ (vanishing_ideal (zero_locus 𝒜 I)).to_ideal :=
(gc_ideal _).le_u_l I
lemma homogeneous_ideal_le_vanishing_ideal_zero_locus (I : homogeneous_ideal 𝒜) :
I ≤ vanishing_ideal (zero_locus 𝒜 I) :=
(gc_homogeneous_ideal _).le_u_l I
lemma subset_zero_locus_vanishing_ideal (t : set (projective_spectrum 𝒜)) :
t ⊆ zero_locus 𝒜 (vanishing_ideal t) :=
(gc_ideal _).l_u_le t
lemma zero_locus_anti_mono {s t : set A} (h : s ⊆ t) : zero_locus 𝒜 t ⊆ zero_locus 𝒜 s :=
(gc_set _).monotone_l h
lemma zero_locus_anti_mono_ideal {s t : ideal A} (h : s ≤ t) :
zero_locus 𝒜 (t : set A) ⊆ zero_locus 𝒜 (s : set A) :=
(gc_ideal _).monotone_l h
lemma zero_locus_anti_mono_homogeneous_ideal {s t : homogeneous_ideal 𝒜} (h : s ≤ t) :
zero_locus 𝒜 (t : set A) ⊆ zero_locus 𝒜 (s : set A) :=
(gc_homogeneous_ideal _).monotone_l h
lemma vanishing_ideal_anti_mono {s t : set (projective_spectrum 𝒜)} (h : s ⊆ t) :
vanishing_ideal t ≤ vanishing_ideal s :=
(gc_ideal _).monotone_u h
lemma zero_locus_bot :
zero_locus 𝒜 ((⊥ : ideal A) : set A) = set.univ :=
(gc_ideal 𝒜).l_bot
@[simp] lemma zero_locus_singleton_zero :
zero_locus 𝒜 ({0} : set A) = set.univ :=
zero_locus_bot _
@[simp] lemma zero_locus_empty :
zero_locus 𝒜 (∅ : set A) = set.univ :=
(gc_set 𝒜).l_bot
@[simp] lemma vanishing_ideal_univ :
vanishing_ideal (∅ : set (projective_spectrum 𝒜)) = ⊤ :=
by simpa using (gc_ideal _).u_top
lemma zero_locus_empty_of_one_mem {s : set A} (h : (1:A) ∈ s) :
zero_locus 𝒜 s = ∅ :=
set.eq_empty_iff_forall_not_mem.mpr $ λ x hx,
(infer_instance : x.as_homogeneous_ideal.to_ideal.is_prime).ne_top $
x.as_homogeneous_ideal.to_ideal.eq_top_iff_one.mpr $ hx h
@[simp] lemma zero_locus_singleton_one :
zero_locus 𝒜 ({1} : set A) = ∅ :=
zero_locus_empty_of_one_mem 𝒜 (set.mem_singleton (1 : A))
@[simp] lemma zero_locus_univ :
zero_locus 𝒜 (set.univ : set A) = ∅ :=
zero_locus_empty_of_one_mem _ (set.mem_univ 1)
lemma zero_locus_sup_ideal (I J : ideal A) :
zero_locus 𝒜 ((I ⊔ J : ideal A) : set A) = zero_locus _ I ∩ zero_locus _ J :=
(gc_ideal 𝒜).l_sup
lemma zero_locus_sup_homogeneous_ideal (I J : homogeneous_ideal 𝒜) :
zero_locus 𝒜 ((I ⊔ J : homogeneous_ideal 𝒜) : set A) = zero_locus _ I ∩ zero_locus _ J :=
(gc_homogeneous_ideal 𝒜).l_sup
lemma zero_locus_union (s s' : set A) :
zero_locus 𝒜 (s ∪ s') = zero_locus _ s ∩ zero_locus _ s' :=
(gc_set 𝒜).l_sup
lemma vanishing_ideal_union (t t' : set (projective_spectrum 𝒜)) :
vanishing_ideal (t ∪ t') = vanishing_ideal t ⊓ vanishing_ideal t' :=
by ext1; convert (gc_ideal 𝒜).u_inf
lemma zero_locus_supr_ideal {γ : Sort*} (I : γ → ideal A) :
zero_locus _ ((⨆ i, I i : ideal A) : set A) = (⋂ i, zero_locus 𝒜 (I i)) :=
(gc_ideal 𝒜).l_supr
lemma zero_locus_supr_homogeneous_ideal {γ : Sort*} (I : γ → homogeneous_ideal 𝒜) :
zero_locus _ ((⨆ i, I i : homogeneous_ideal 𝒜) : set A) = (⋂ i, zero_locus 𝒜 (I i)) :=
(gc_homogeneous_ideal 𝒜).l_supr
lemma zero_locus_Union {γ : Sort*} (s : γ → set A) :
zero_locus 𝒜 (⋃ i, s i) = (⋂ i, zero_locus 𝒜 (s i)) :=
(gc_set 𝒜).l_supr
lemma zero_locus_bUnion (s : set (set A)) :
zero_locus 𝒜 (⋃ s' ∈ s, s' : set A) = ⋂ s' ∈ s, zero_locus 𝒜 s' :=
by simp only [zero_locus_Union]
lemma vanishing_ideal_Union {γ : Sort*} (t : γ → set (projective_spectrum 𝒜)) :
vanishing_ideal (⋃ i, t i) = (⨅ i, vanishing_ideal (t i)) :=
homogeneous_ideal.to_ideal_injective $
by convert (gc_ideal 𝒜).u_infi; exact homogeneous_ideal.to_ideal_infi _
lemma zero_locus_inf (I J : ideal A) :
zero_locus 𝒜 ((I ⊓ J : ideal A) : set A) = zero_locus 𝒜 I ∪ zero_locus 𝒜 J :=
set.ext $ λ x, by simpa using x.2.1.inf_le
lemma union_zero_locus (s s' : set A) :
zero_locus 𝒜 s ∪ zero_locus 𝒜 s' = zero_locus 𝒜 ((ideal.span s) ⊓ (ideal.span s'): ideal A) :=
by { rw zero_locus_inf, simp }
lemma zero_locus_mul_ideal (I J : ideal A) :
zero_locus 𝒜 ((I * J : ideal A) : set A) = zero_locus 𝒜 I ∪ zero_locus 𝒜 J :=
set.ext $ λ x, by simpa using x.2.1.mul_le
lemma zero_locus_mul_homogeneous_ideal (I J : homogeneous_ideal 𝒜) :
zero_locus 𝒜 ((I * J : homogeneous_ideal 𝒜) : set A) = zero_locus 𝒜 I ∪ zero_locus 𝒜 J :=
set.ext $ λ x, by simpa using x.2.1.mul_le
lemma zero_locus_singleton_mul (f g : A) :
zero_locus 𝒜 ({f * g} : set A) = zero_locus 𝒜 {f} ∪ zero_locus 𝒜 {g} :=
set.ext $ λ x, by simpa using x.2.1.mul_mem_iff_mem_or_mem
@[simp] lemma zero_locus_singleton_pow (f : A) (n : ℕ) (hn : 0 < n) :
zero_locus 𝒜 ({f ^ n} : set A) = zero_locus 𝒜 {f} :=
set.ext $ λ x, by simpa using x.2.1.pow_mem_iff_mem n hn
lemma sup_vanishing_ideal_le (t t' : set (projective_spectrum 𝒜)) :
vanishing_ideal t ⊔ vanishing_ideal t' ≤ vanishing_ideal (t ∩ t') :=
begin
intros r,
rw [← homogeneous_ideal.mem_iff, homogeneous_ideal.to_ideal_sup, mem_vanishing_ideal,
submodule.mem_sup],
rintro ⟨f, hf, g, hg, rfl⟩ x ⟨hxt, hxt'⟩,
erw mem_vanishing_ideal at hf hg,
apply submodule.add_mem; solve_by_elim
end
lemma mem_compl_zero_locus_iff_not_mem {f : A} {I : projective_spectrum 𝒜} :
I ∈ (zero_locus 𝒜 {f} : set (projective_spectrum 𝒜))ᶜ ↔ f ∉ I.as_homogeneous_ideal :=
by rw [set.mem_compl_eq, mem_zero_locus, set.singleton_subset_iff]; refl
/-- The Zariski topology on the prime spectrum of a commutative ring
is defined via the closed sets of the topology:
they are exactly those sets that are the zero locus of a subset of the ring. -/
instance zariski_topology : topological_space (projective_spectrum 𝒜) :=
topological_space.of_closed (set.range (projective_spectrum.zero_locus 𝒜))
(⟨set.univ, by simp⟩)
begin
intros Zs h,
rw set.sInter_eq_Inter,
let f : Zs → set _ := λ i, classical.some (h i.2),
have hf : ∀ i : Zs, ↑i = zero_locus 𝒜 (f i) := λ i, (classical.some_spec (h i.2)).symm,
simp only [hf],
exact ⟨_, zero_locus_Union 𝒜 _⟩
end
(by { rintros _ ⟨s, rfl⟩ _ ⟨t, rfl⟩, exact ⟨_, (union_zero_locus 𝒜 s t).symm⟩ })
/--
The underlying topology of `Proj` is the projective spectrum of graded ring `A`.
-/
def Top : Top := Top.of (projective_spectrum 𝒜)
lemma is_open_iff (U : set (projective_spectrum 𝒜)) :
is_open U ↔ ∃ s, Uᶜ = zero_locus 𝒜 s :=
by simp only [@eq_comm _ Uᶜ]; refl
lemma is_closed_iff_zero_locus (Z : set (projective_spectrum 𝒜)) :
is_closed Z ↔ ∃ s, Z = zero_locus 𝒜 s :=
by rw [← is_open_compl_iff, is_open_iff, compl_compl]
lemma is_closed_zero_locus (s : set A) :
is_closed (zero_locus 𝒜 s) :=
by { rw [is_closed_iff_zero_locus], exact ⟨s, rfl⟩ }
lemma zero_locus_vanishing_ideal_eq_closure (t : set (projective_spectrum 𝒜)) :
zero_locus 𝒜 (vanishing_ideal t : set A) = closure t :=
begin
apply set.subset.antisymm,
{ rintro x hx t' ⟨ht', ht⟩,
obtain ⟨fs, rfl⟩ : ∃ s, t' = zero_locus 𝒜 s,
by rwa [is_closed_iff_zero_locus] at ht',
rw [subset_zero_locus_iff_subset_vanishing_ideal] at ht,
exact set.subset.trans ht hx },
{ rw (is_closed_zero_locus _ _).closure_subset_iff,
exact subset_zero_locus_vanishing_ideal 𝒜 t }
end
lemma vanishing_ideal_closure (t : set (projective_spectrum 𝒜)) :
vanishing_ideal (closure t) = vanishing_ideal t :=
begin
have := (gc_ideal 𝒜).u_l_u_eq_u t,
dsimp only at this,
ext1,
erw zero_locus_vanishing_ideal_eq_closure 𝒜 t at this,
exact this,
end
section basic_open
/-- `basic_open r` is the open subset containing all prime ideals not containing `r`. -/
def basic_open (r : A) : topological_space.opens (projective_spectrum 𝒜) :=
{ val := { x | r ∉ x.as_homogeneous_ideal },
property := ⟨{r}, set.ext $ λ x, set.singleton_subset_iff.trans $ not_not.symm⟩ }
@[simp] lemma mem_basic_open (f : A) (x : projective_spectrum 𝒜) :
x ∈ basic_open 𝒜 f ↔ f ∉ x.as_homogeneous_ideal := iff.rfl
lemma mem_coe_basic_open (f : A) (x : projective_spectrum 𝒜) :
x ∈ (↑(basic_open 𝒜 f): set (projective_spectrum 𝒜)) ↔ f ∉ x.as_homogeneous_ideal := iff.rfl
lemma is_open_basic_open {a : A} : is_open ((basic_open 𝒜 a) :
set (projective_spectrum 𝒜)) :=
(basic_open 𝒜 a).property
@[simp] lemma basic_open_eq_zero_locus_compl (r : A) :
(basic_open 𝒜 r : set (projective_spectrum 𝒜)) = (zero_locus 𝒜 {r})ᶜ :=
set.ext $ λ x, by simpa only [set.mem_compl_eq, mem_zero_locus, set.singleton_subset_iff]
@[simp] lemma basic_open_one : basic_open 𝒜 (1 : A) = ⊤ :=
topological_space.opens.ext $ by simp
@[simp] lemma basic_open_zero : basic_open 𝒜 (0 : A) = ⊥ :=
topological_space.opens.ext $ by simp
lemma basic_open_mul (f g : A) : basic_open 𝒜 (f * g) = basic_open 𝒜 f ⊓ basic_open 𝒜 g :=
topological_space.opens.ext $ by {simp [zero_locus_singleton_mul]}
lemma basic_open_mul_le_left (f g : A) : basic_open 𝒜 (f * g) ≤ basic_open 𝒜 f :=
by { rw basic_open_mul 𝒜 f g, exact inf_le_left }
lemma basic_open_mul_le_right (f g : A) : basic_open 𝒜 (f * g) ≤ basic_open 𝒜 g :=
by { rw basic_open_mul 𝒜 f g, exact inf_le_right }
@[simp] lemma basic_open_pow (f : A) (n : ℕ) (hn : 0 < n) :
basic_open 𝒜 (f ^ n) = basic_open 𝒜 f :=
topological_space.opens.ext $ by simpa using zero_locus_singleton_pow 𝒜 f n hn
lemma basic_open_eq_union_of_projection (f : A) :
basic_open 𝒜 f = ⨆ (i : ℕ), basic_open 𝒜 (graded_algebra.proj 𝒜 i f) :=
topological_space.opens.ext $ set.ext $ λ z, begin
erw [mem_coe_basic_open, topological_space.opens.mem_Sup],
split; intros hz,
{ rcases show ∃ i, graded_algebra.proj 𝒜 i f ∉ z.as_homogeneous_ideal, begin
contrapose! hz with H,
classical,
rw ←direct_sum.sum_support_decompose 𝒜 f,
apply ideal.sum_mem _ (λ i hi, H i)
end with ⟨i, hi⟩,
exact ⟨basic_open 𝒜 (graded_algebra.proj 𝒜 i f), ⟨i, rfl⟩, by rwa mem_basic_open⟩ },
{ obtain ⟨_, ⟨i, rfl⟩, hz⟩ := hz,
exact λ rid, hz (z.1.2 i rid) },
end
lemma is_topological_basis_basic_opens : topological_space.is_topological_basis
(set.range (λ (r : A), (basic_open 𝒜 r : set (projective_spectrum 𝒜)))) :=
begin
apply topological_space.is_topological_basis_of_open_of_nhds,
{ rintros _ ⟨r, rfl⟩,
exact is_open_basic_open 𝒜 },
{ rintros p U hp ⟨s, hs⟩,
rw [← compl_compl U, set.mem_compl_eq, ← hs, mem_zero_locus, set.not_subset] at hp,
obtain ⟨f, hfs, hfp⟩ := hp,
refine ⟨basic_open 𝒜 f, ⟨f, rfl⟩, hfp, _⟩,
rw [← set.compl_subset_compl, ← hs, basic_open_eq_zero_locus_compl, compl_compl],
exact zero_locus_anti_mono 𝒜 (set.singleton_subset_iff.mpr hfs) }
end
end basic_open
section order
/-!
## The specialization order
We endow `projective_spectrum 𝒜` with a partial order,
where `x ≤ y` if and only if `y ∈ closure {x}`.
-/
instance : partial_order (projective_spectrum 𝒜) :=
subtype.partial_order _
@[simp] lemma as_ideal_le_as_ideal (x y : projective_spectrum 𝒜) :
x.as_homogeneous_ideal ≤ y.as_homogeneous_ideal ↔ x ≤ y :=
subtype.coe_le_coe
@[simp] lemma as_ideal_lt_as_ideal (x y : projective_spectrum 𝒜) :
x.as_homogeneous_ideal < y.as_homogeneous_ideal ↔ x < y :=
subtype.coe_lt_coe
lemma le_iff_mem_closure (x y : projective_spectrum 𝒜) :
x ≤ y ↔ y ∈ closure ({x} : set (projective_spectrum 𝒜)) :=
begin
rw [← as_ideal_le_as_ideal, ← zero_locus_vanishing_ideal_eq_closure,
mem_zero_locus, vanishing_ideal_singleton],
simp only [coe_subset_coe, subtype.coe_le_coe, coe_coe],
end
end order
end projective_spectrum
|
{- Byzantine Fault Tolerant Consensus Verification in Agda, version 0.9.
Copyright (c) 2021, Oracle and/or its affiliates.
Licensed under the Universal Permissive License v 1.0 as shown at https://opensource.oracle.com/licenses/upl
-}
open import LibraBFT.Base.Types
open import LibraBFT.Impl.Consensus.PersistentLivenessStorage
open import LibraBFT.Impl.Properties.Util
open import LibraBFT.ImplShared.Base.Types
open import LibraBFT.ImplShared.Consensus.Types
open import LibraBFT.ImplShared.Util.Dijkstra.All
open import Optics.All
open import Util.Prelude
module LibraBFT.Impl.Consensus.PersistentLivenessStorage.Properties where
module saveVoteMSpec (vote : Vote) where
open OutputProps
postulate -- TODO-2: refine and prove
contract
: ∀ P pre
→ (∀ outs → NoMsgs outs → NoErrors outs → P (inj₁ fakeErr) pre outs)
→ (∀ outs → NoMsgs outs → NoErrors outs
→ P (inj₂ unit) pre outs)
→ RWS-weakestPre (saveVoteM vote) P unit pre
|
The quake affected the three Médecins Sans Frontières ( Doctors Without Borders ) medical facilities around Port @-@ au @-@ Prince , causing one to collapse completely . A hospital in <unk> , a wealthy suburb of Port @-@ au @-@ Prince , also collapsed , as did the St. Michel District Hospital in the southern town of Jacmel , which was the largest referral hospital in south @-@ east Haiti .
|
its name. I just open a foo.gpg file and things "just work".
There's an "Encryption/Decryption" submenu which seems "discoverable".
In what sense does it need to be more "discoverable"?
I never tried doing encryption by visiting a file named .gpg. |
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright 2005-2016 Brian Roark and Google, Inc.
// Classes to generate random sentences from an LM or more generally
// paths through any FST where epsilons are treated as failure transitions.
#ifndef NGRAM_NGRAM_RANDGEN_H_
#define NGRAM_NGRAM_RANDGEN_H_
#include <sys/types.h>
#include <unistd.h>
#include <vector>
// Faster multinomial sampling possible if Gnu Scientific Library available.
#ifdef HAVE_GSL
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#endif // HAVE_GSL
#include <fst/fst.h>
#include <fst/randgen.h>
#include <ngram/util.h>
namespace ngram {
using fst::Fst;
using fst::ArcIterator;
using fst::LogWeight;
using fst::Log64Weight;
// Same as FastLogProbArcSelector but treats *all* epsilons as
// failure transitions that have a backoff weight. The LM must
// be fully normalized.
template <class A>
class NGramArcSelector {
public:
typedef typename A::StateId StateId;
typedef typename A::Weight Weight;
explicit NGramArcSelector(int seed = time(0) + getpid()) : seed_(seed) {
srand(seed);
}
// Samples one transition.
size_t operator()(const Fst<A> &fst, StateId s, double total_prob,
fst::CacheLogAccumulator<A> *accumulator) const {
double r = rand() / (RAND_MAX + 1.0);
// In effect, subtract out excess mass from the cumulative distribution.
// Requires the backoff epsilon be the initial transition.
double z = r + total_prob - 1.0;
if (z <= 0.0) return 0;
ArcIterator<Fst<A> > aiter(fst, s);
return accumulator->LowerBound(-log(z), &aiter);
}
int Seed() const { return seed_; }
private:
int seed_;
fst::WeightConvert<Weight, LogWeight> to_log_weight_;
};
} // namespace ngram
namespace fst {
// Specialization for NGramArcSelector.
template <class A>
class ArcSampler<A, ngram::NGramArcSelector<A> > {
public:
typedef ngram::NGramArcSelector<A> S;
typedef typename A::StateId StateId;
typedef typename A::Weight Weight;
typedef typename A::Label Label;
typedef CacheLogAccumulator<A> C;
ArcSampler(const Fst<A> &fst, const S &arc_selector, int max_length = INT_MAX)
: fst_(fst),
arc_selector_(arc_selector),
max_length_(max_length),
matcher_(fst_, MATCH_INPUT) {
// Ensure the input FST has any epsilons as the initial transitions.
if (!fst_.Properties(kILabelSorted, true))
NGRAMERROR() << "ArcSampler: is not input-label sorted";
accumulator_.reset(new C());
accumulator_->Init(fst);
#ifdef HAVE_GSL
rng_ = gsl_rng_alloc(gsl_rng_taus);
gsl_rng_set(rng_, arc_selector.Seed());
#endif // HAVE_GSL
}
ArcSampler(const ArcSampler<A, S> &sampler, const Fst<A> *fst = 0)
: fst_(fst ? *fst : sampler.fst_),
arc_selector_(sampler.arc_selector_),
max_length_(sampler.max_length_),
matcher_(fst_, MATCH_INPUT) {
if (fst) {
accumulator_.reset(new C());
accumulator_->Init(*fst);
} else { // shallow copy
accumulator_.reset(new C(*sampler.accumulator_));
}
}
~ArcSampler() {
#ifdef HAVE_GSL
gsl_rng_free(rng_);
#endif // HAVE_GSL
}
bool Sample(const RandState<A> &rstate) {
sample_map_.clear();
forbidden_labels_.clear();
if ((fst_.NumArcs(rstate.state_id) == 0 &&
fst_.Final(rstate.state_id) == Weight::Zero()) ||
rstate.length == max_length_) {
Reset();
return false;
}
double total_prob = TotalProb(rstate.state_id);
#ifdef HAVE_GSL
if (fst_.NumArcs(rstate.state_id) + 1 < rstate.nsamples) {
Weight numer_weight, denom_weight;
BackoffWeight(rstate.state_id, total_prob, &numer_weight, &denom_weight);
MultinomialSample(rstate, numer_weight);
Reset();
return true;
}
#endif // HAVE_GSL
ArcIterator<Fst<A> > aiter(fst_, rstate.state_id);
for (size_t i = 0; i < rstate.nsamples; ++i) {
size_t pos = 0;
Label label = kNoLabel;
do {
pos = arc_selector_(fst_, rstate.state_id, total_prob,
accumulator_.get());
if (pos < fst_.NumArcs(rstate.state_id)) {
aiter.Seek(pos);
label = aiter.Value().ilabel;
} else {
label = kNoLabel;
}
} while (ForbiddenLabel(label, rstate));
++sample_map_[pos];
}
Reset();
return true;
}
bool Done() const { return sample_iter_ == sample_map_.end(); }
void Next() { ++sample_iter_; }
std::pair<size_t, size_t> Value() const { return *sample_iter_; }
void Reset() { sample_iter_ = sample_map_.begin(); }
bool Error() const { return false; }
private:
double TotalProb(StateId s) {
// Get cumulative weight at the state.
ArcIterator<Fst<A> > aiter(fst_, s);
accumulator_->SetState(s);
Weight total_weight =
accumulator_->Sum(fst_.Final(s), &aiter, 0, fst_.NumArcs(s));
return exp(-to_log_weight_(total_weight).Value());
}
void BackoffWeight(StateId s, double total_prob, Weight *numer_weight,
Weight *denom_weight);
#ifdef HAVE_GSL
void MultinomialSample(const RandState<A> &rstate, Weight fail_weight);
#endif // HAVE_GSL
bool ForbiddenLabel(Label l, const RandState<A> &rstate);
const Fst<A> &fst_;
const S &arc_selector_;
int max_length_;
// Stores (N, K) as described for Value().
std::map<size_t, size_t> sample_map_;
std::map<size_t, size_t>::const_iterator sample_iter_;
std::unique_ptr<C> accumulator_;
#ifdef HAVE_GSL
gsl_rng *rng_; // GNU Sci Lib random number generator
vector<double> pr_; // multinomial parameters
vector<unsigned int> pos_; // sample positions
vector<unsigned int> n_; // sample counts
#endif // HAVE_GSL
WeightConvert<Log64Weight, Weight> to_weight_;
WeightConvert<Weight, Log64Weight> to_log_weight_;
std::set<Label>
forbidden_labels_; // labels forbidden for failure transitions
Matcher<Fst<A> > matcher_;
};
// Finds and decomposes the backoff probability into its numerator and
// denominator.
template <class A>
void ArcSampler<A, ngram::NGramArcSelector<A> >::BackoffWeight(
StateId s, double total, Weight *numer_weight, Weight *denom_weight) {
// Get backoff prob.
double backoff = 0.0;
matcher_.SetState(s);
matcher_.Find(0);
for (; !matcher_.Done(); matcher_.Next()) {
const A &arc = matcher_.Value();
if (arc.ilabel != kNoLabel) { // not an implicit epsilon loop
backoff = exp(-to_log_weight_(arc.weight).Value());
break;
}
}
if (backoff == 0.0) { // no backoff transition
*numer_weight = Weight::Zero();
*denom_weight = Weight::Zero();
return;
}
// total = 1 - numer + backoff
double numer = 1.0 + backoff - total;
*numer_weight = to_weight_(-log(numer));
// backoff = numer/denom
double denom = numer / backoff;
*denom_weight = to_weight_(-log(denom));
}
#ifdef HAVE_GSL
template <class A>
void ArcSampler<A, ngram::NGramArcSelector<A> >::MultinomialSample(
const RandState<A> &rstate, Weight fail_weight) {
pr_.clear();
pos_.clear();
n_.clear();
size_t pos = 0;
for (ArcIterator<Fst<A> > aiter(fst_, rstate.state_id); !aiter.Done();
aiter.Next(), ++pos) {
const A &arc = aiter.Value();
if (!ForbiddenLabel(arc.ilabel, rstate)) {
pos_.push_back(pos);
Weight weight = arc.ilabel == 0 ? fail_weight : arc.weight;
pr_.push_back(exp(-to_log_weight_(weight).Value()));
}
}
if (fst_.Final(rstate.state_id) != Weight::Zero() &&
!ForbiddenLabel(kNoLabel, rstate)) {
pos_.push_back(pos);
pr_.push_back(exp(-to_log_weight_(fst_.Final(rstate.state_id)).Value()));
}
if (rstate.nsamples < UINT_MAX) {
n_.resize(pr_.size());
gsl_ran_multinomial(rng_, pr_.size(), rstate.nsamples, &(pr_[0]), &(n_[0]));
for (size_t i = 0; i < n_.size(); ++i)
if (n_[i] != 0) sample_map_[pos_[i]] = n_[i];
} else {
for (size_t i = 0; i < pr_.size(); ++i)
sample_map_[pos_[i]] = ceil(pr_[i] * rstate.nsamples);
}
}
#endif // HAVE_GSL
template <class A>
bool ArcSampler<A, ngram::NGramArcSelector<A> >::ForbiddenLabel(
Label l, const RandState<A> &rstate) {
if (l == 0) return false;
if (fst_.NumArcs(rstate.state_id) > rstate.nsamples) {
for (const RandState<A> *rs = &rstate; rs->parent != 0; rs = rs->parent) {
StateId parent_id = rs->parent->state_id;
ArcIterator<Fst<A> > aiter(fst_, parent_id);
aiter.Seek(rs->select);
if (aiter.Value().ilabel != 0) // not backoff transition
return false;
if (l == kNoLabel) { // super-final label
return fst_.Final(parent_id) != Weight::Zero();
} else {
matcher_.SetState(parent_id);
if (matcher_.Find(l)) return true;
}
}
return false;
} else {
if (forbidden_labels_.empty()) {
for (const RandState<A> *rs = &rstate; rs->parent != 0; rs = rs->parent) {
StateId parent_id = rs->parent->state_id;
ArcIterator<Fst<A> > aiter(fst_, parent_id);
aiter.Seek(rs->select);
if (aiter.Value().ilabel != 0) // not backoff transition
break;
for (aiter.Reset(); !aiter.Done(); aiter.Next()) {
Label l = aiter.Value().ilabel;
if (l != 0) forbidden_labels_.insert(l);
}
if (fst_.Final(parent_id) != Weight::Zero())
forbidden_labels_.insert(kNoLabel);
}
}
return forbidden_labels_.count(l) > 0;
}
}
} // namespace fst
#endif // NGRAM_NGRAM_RANDGEN_H_
|
Yet another sunny day here in Brussels and I really wanted to take advantage of this Sunday afternoon and take a feel trip to Hollande; well, actually a small city right across the border from Belgium. It’s nice from time to time to change the usual place that you visit and just try something new. Of course that I went to KFC as well, Belgium not having one unfortunately.
Anyway, back to the fashionable part of the day, I wanted to share with you guys the dress I wore this afternoon. I believe that all these dresses from Udobuy have a mix of glamour and elegance, but at the same time they make you look so chic ^^. What do you think?
The great surprise was that this dress is inspired by one of Katy Perry’s.
you like today’s look. Can’t wait to read all your wonderful comments.
omg. just wow. you are so stunning. |
#this script is used to add rBC mass to the database
import sys
import os
import datetime
import pickle
import numpy as np
import matplotlib.pyplot as plt
from pprint import pprint
from scipy.optimize import curve_fit
from scipy import stats
from SP2_particle_record_UTC import ParticleRecord
from struct import *
import hk_new
import hk_new_no_ts_LEO
from scipy import linspace, polyval, polyfit, sqrt, stats
import math
import mysql.connector
from datetime import datetime
import calendar
dir_c = 'C:/Users/Sarah Hanna/Documents/Data/Alert Data/Jasons analysis/Raw/2011/'
os.chdir(dir_c)
file_list = []
file_name_list = []
for file in os.listdir('.'):
file_list.append([file,os.path.getsize('C:/Users/Sarah Hanna/Documents/Data/Alert Data/Jasons analysis/Raw/2011/' + file)/1000])
file_name_list.append(file)
#setup
data_dir = 'F:/Alert/2011/SP2B_files/'
count = 0
os.chdir(data_dir)
for directory in os.listdir(data_dir):
if os.path.isdir(directory) == True and directory.startswith('20'):
folder_date = datetime.strptime(directory, '%Y%m%d')
if folder_date >= datetime(2011,1,1) and folder_date < datetime(2011,8,13):
directory_path =os.path.abspath(directory)
os.chdir(directory_path)
for file in os.listdir('.'):
if file.endswith('.sp2b') and (file.endswith('gnd.sp2b')==False) and os.path.getsize(directory_path + '/'+ file) !=0:
for j_file_data in file_list:
if file == j_file_data[0]:
if j_file_data[1] != os.path.getsize(directory_path + '/'+ file)/1000:
print j_file_data[0], j_file_data[1] , file,os.path.getsize(directory_path + '/'+ file)/1000
break
if file not in file_name_list:
print file
print os.path.getsize(directory_path + '/'+ file)/1000
count +=1
os.chdir(data_dir)
print count |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdint.h>
#include <vector>
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable : 4355)
#endif //_MSC_VER
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0601
#endif // _WIN32_WINNT
#include <boost/asio.hpp>
#include <boost/bind/bind.hpp>
#include <boost/make_shared.hpp>
#ifdef _MSC_VER
# pragma warning(pop)
#endif //_MSC_VER
#include <ignite/binary/binary.h>
#include <ignite/impl/binary/binary_utils.h>
#include "test_server.h"
namespace ignite
{
TestServerSession::TestServerSession(boost::asio::io_service& service, const std::vector< std::vector<int8_t> >& responses) :
socket(service),
responses(responses),
requestsResponded(0)
{
// No-op.
}
void TestServerSession::Start()
{
ReadNextRequest();
}
void TestServerSession::ReadNextRequest()
{
requests.push_back(std::vector<int8_t>());
std::vector<int8_t>& newRequest = requests.back();
newRequest.resize(4);
async_read(socket, boost::asio::buffer(newRequest.data(), newRequest.size()),
boost::bind(&TestServerSession::HandleRequestSizeReceived, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void TestServerSession::HandleRequestSizeReceived(const boost::system::error_code& error, size_t bytesTransferred)
{
if (error || bytesTransferred != 4)
{
socket.close();
return;
}
std::vector<int8_t>& newRequest = requests.back();
impl::interop::InteropUnpooledMemory mem(4);
mem.Length(4);
memcpy(mem.Data(), newRequest.data(), newRequest.size());
int32_t size = impl::binary::BinaryUtils::ReadInt32(mem, 0);
newRequest.resize(4 + size);
async_read(socket, boost::asio::buffer(newRequest.data() + 4, size),
boost::bind(&TestServerSession::HandleRequestReceived, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void TestServerSession::HandleRequestReceived(const boost::system::error_code& error, size_t bytesTransferred)
{
if (error || !bytesTransferred || requestsResponded == responses.size())
{
std::cout << requestsResponded << std::endl;
std::cout << responses.size() << std::endl;
socket.close();
return;
}
const std::vector<int8_t>& response = responses.at(requestsResponded);
async_write(socket, boost::asio::buffer(response.data(), response.size()),
boost::bind(&TestServerSession::HandleResponseSent, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
++requestsResponded;
}
void TestServerSession::HandleResponseSent(const boost::system::error_code& error, size_t bytesTransferred)
{
if (error || !bytesTransferred)
{
socket.close();
return;
}
ReadNextRequest();
}
TestServer::TestServer(uint16_t port) :
acceptor(service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port))
{
// No-op.
}
TestServer::~TestServer()
{
Stop();
}
void TestServer::Start()
{
if (!serverThread)
{
StartAccept();
serverThread.reset(new boost::thread(boost::bind(&boost::asio::io_service::run, &service)));
}
}
void TestServer::Stop()
{
if (serverThread)
{
service.stop();
serverThread->join();
serverThread.reset();
}
}
void TestServer::StartAccept()
{
using namespace boost::asio;
boost::shared_ptr<TestServerSession> newSession;
newSession.reset(new TestServerSession(service, responses));
acceptor.async_accept(newSession->GetSocket(),
boost::bind(&TestServer::HandleAccept, this, newSession, placeholders::error));
}
void TestServer::HandleAccept(boost::shared_ptr<TestServerSession> session, const boost::system::error_code& error)
{
if (!error)
{
session->Start();
sessions.push_back(session);
}
StartAccept();
}
} // namespace ignite
|
lemma independent_Basis: "independent Basis" |
open import Agda.Builtin.Unit
open import Agda.Builtin.List
open import Agda.Builtin.Reflection
id : {A : Set} → A → A
id x = x
macro
tac : Term → TC ⊤
tac hole = unify hole (def (quote id) (arg (arg-info visible relevant) (var 0 []) ∷ []))
test : {A : Set} → A → A
test x = {!tac!}
|
function smallest_prime_factor(n::Int64)
i=2;
while i*i<=n
if( n%i==0)
return i
end
i=i+1
end
return n
end
function compute()
n=600851475143
while true
p=smallest_prime_factor(n)
if p<n
n/=p
n=Int64(n)
else return n
end
end
end
print(compute())
|
module Example.Qtt.N
import Data.Vect
namespace Repetition
-- repN 0 f x ~ x
-- repN 1 f x ~ f x
-- repN 2 f x ~ f . f $ x
-- repN 3 f x ~ f . f . f $ x
namespace BadRepetitionS
public export
repN : Nat -> (a -> a) -> (a -> a)
repN Z f = id
repN (S n) f = BadRepetitionS.repN n (f . f)
namespace BadRepetitionX
public export
repN : Nat -> (a -> a) -> (a -> a)
repN Z f = f
repN (S n) f = BadRepetitionX.repN n (f . f)
namespace BadRepetitionZ
public export
repN : Nat -> (a -> a) -> (a -> a)
repN Z f = f
repN (S n) f = BadRepetitionZ.repN n f . f
namespace NiceRepetition
public export
repN : Nat -> (a -> a) -> (a -> a)
repN Z f = id
repN (S n) f = NiceRepetition.repN n f . f
namespace NRepetition
--public export
--repN : (n : Nat) -> (n _ : a -> a) -> (a -> a)
--repN Z f = id
--repN (S n) f = NiceRepetition.repN n f . f
namespace Folding
foldr : (op : a -> b -> b) -> (init : b) -> Vect n a -> b
--foldr : ((n) op : a -> b -> b) -> (init : b) -> Vect n a -> b
-- Меру надо знать
--foldr : ((n) op : a -> (k _ : b) -> b) -> ((k * n) init : b) -> Vect n a -> b
|
func $foo (
var %i i32
#var %i1 i32, var %j1 i32, var %k1 i32
) i32 {
return (
add i32(dread i32 %i,
constval i32 -998))}
func $foo1 (
var %i i32, var %j i32, var %k i32,
var %i1 i32, var %j1 i32, var %k1 i32
) i32 {
return (
add i32(dread i32 %i, dread i32 %j))}
func $foo2 (
var %i i32, var %j i32, var %k i32
) i32 {
return (
add i32(dread i32 %i, constval i32 0x111111111))}
func $foo3 (
var %i i64, var %j i64, var %k i32
) i64 {
return (
add i64(dread i64 %i, constval i64 0x111111111))}
func $foo4 (
var %i i64, var %j i64, var %k i32
)i64 {
return (
add i64(dread i64 %i, dread i64 %j))}
func $foo5 (
var %i i64, var %j i64, var %k i32
) i64 {
return (
add i64(dread i64 %i, constval i64 0x11111))}
func $foo6 (
var %i f64, var %j f64, var %k i32
) f64 {
return (
add f64(dread f64 %i, constval f64 2.237))}
func $foo66 (
var %i f64, var %j f64, var %k i32
) f64 {
return (
add f64(dread f64 %i, constval f64 2.237))}
func $foo7 (
var %i f32, var %j f32, var %k i32
) f32 {
return (
add f32(dread f32 %i, dread f32 %j))}
func $foo8 (
var %i f32, var %j f32, var %k i32
) f32 {
return (
add f32(dread f32 %i, constval f32 2.237f))}
func $foo9 (
var %i i8, var %j u8, var %k i32) i32 {
return (
add i32(dread i32 %i, dread u32 %j))}
# EXEC: %irbuild Main.mpl
# EXEC: %irbuild Main.irb.mpl
# EXEC: %cmp Main.irb.mpl Main.irb.irb.mpl
|
Do you have a Family Project?
When was the last occasion you and your family spent time together?
Don’t tell me that you watched a movie at the PVR Cinemas and shared popcorns, only last week.
Or you had a gala dinner at the Barbeque Nation, a month ago on a Friday night.
Hold on. I am asking whether you did something together like a project. A family project I mean.
The project could be trivial and simple but with a cause. The idea is to be together and enjoy – and cherish the moments that you will remember later.
Given the machine life in the cities we live, we as a family seldom spend time together. We don’t think about or aspire to do something meaningful, exiting, creative and demonstrative for a cause. Life we live does not have a family fizz.
Today each member of the family is busy with something – everybody is stressed out and lives a siloed life.
We don’t have that family bond anymore that was perhaps there a generation before. Is this one of the reasons why we see growing frustration, leading to depression and disorders like schizophrenia?
Few of my friends have recognized the need of a “family project”.
I know a friend who takes his family to the mountains around Karjat. They spend two weeks in the tribal villages twice a year. His wife is a gynecologist, son is studying agriculture engineering and daughter is into development work at the TISS. Over the past five years, the family has supported a school, provided medical advice, improved farming practices and helped in building a market for the honey and handicrafts. When I visit their place and the topic comes about Karjat, everyone gets excited to talk and tell me their experience, the challenges they faced and how they resolved them collectively. And when there is a slide show in the drawing room, showing me the “project”, on every slide there is fight who would tell the “story” first. I see there a resonance of emotions with all the enthusiasm.
But as I said before, the “family project” can be even short and sweet.
I remember when our children were young, we decided to spend an afternoon at a hobby pottery shop at the Atria Mall in Worli. We four (my wife Kiran, daughter Devika and son Pranav) walked into the pottery shop in the mall in the afternoon and decided to make a house with clay.
We were given clay, the “tools” and some glazing materials with bright colors. It took for us neat 3 hours to visualize and make a toy house with a roof that could be lifted to store the “secrets”. We discussed, shared the tasks, added value to each other’s work. Finally, the clay house was taken to the oven to bake. And when done, we were so thrilled to see that we could create something together – a lovely toy house (actually a storage box) with bright colors!
We have preserved this work even today as a mark of us working together reminding us of all the joy and happiness. I think I understood my wife, son and daughter that afternoon much better.
I spoke about the house that we “built”, and this reminds me of the wonderful visit me and my colleagues recently made to the Eco House of Dr Anjali Parasnis.
Dr Anjali is Associate Director at TERI Western Zone office in New Mumbai.
Few years ago, Anjali, her two sons and parents took up a “Family project” of building a Eco House near Khalapur, at the foothills of the mountains of Khandala near Mumbai. The family worked with all the passion, creativity and all the perseverance on this project. We were simply amazed to witness sustainability put into practice.
The Eco House is a framed structure and for portion of the walls, it makes use of abandoned PET and beer bottles. The Jambha stone (laterite) is otherwise used that is porous. The foyer has lovely tile work made out of broken tiles what would have been otherwise thrown as waste. The kitchen has two sinks and a dual plumbing system is used that takes the sullage through a root zone treatment and then to a recharge pit to replenish the groundwater aquifer. Rainwater is tapped and channeled through to percolation area to charge the aquifer. Broken chassis of the vehicles are used for the lintels after cutting. Natural ducts through hollow walls are provided with options of forced circulation for cooling, cutting down the air conditioning requirements. I was impressed with the garden and the “healthy” vegetables that were grown. Watering in the garden was done with drip irrigation.
But obtaining a loan for such an unconventional house was not easy. Anjali faced major difficulties. The Bank wanted not an Eco House, but a house built with concrete and the “usual” stuff.
Anjali told us that the house was built such that it would produce least amount of the waste, in the event the house was to be demolished and rebuilt! I was amazed that so much thought was given considering the life cycle.
Everybody in the family spoke about the house and had something interesting to tell. I was impressed to experience this “family project”. We had a good fortune to meet the construction contractor and two young architects from Khalapur. I could see that building Anjali’s house had transformed them – they not only could visualize the importance of sustainability but learnt how to implement the elements into a form with functionality by making a wise choice of materials. I was happy to know that Anjali and her architect friends are now documenting the project’s story.
Anjali’s parents live in this Eco House. Indeed, they were practicing science with traditions, using less resources and making least waste possible with all the humility and simplicity that nature wants one to be. The silence around told us that this was sustainable living. I felt envious. Anjali’s mother read out a few poems in Marathi that expressed her love towards nature and her deep understanding of sustainability.
When I returned home, I took out the toy clay house from the chest of drawers. This was the toy house that we made as an afternoon family project years ago.
“Wish we build a real house together one day” I sighed. I was inspired by Anjali’s family project of the Eco House.
I decided to call for a Skype session for this Family project.
As usual, I thought I will advise – because I knew that was the only thing I could possibly do!
This article was so wonderful and inspiring. It has been appreciated across my network. Thanks Dr Modak. |
Out of Great Tribulation ; memorial chapel , Norbury <unk> church , 1948
|
submodule(Mod_CauchyElement) SUPCauchyElementSGS
!-----------------------------------------------------------------------
!
! This routine computes the elemental stabilization for
! the three field linear formulation.
! Taken from 'A mixed three-field FE formulation for stress accurate
! analysis including the incompressible limit'
! Authors: Chiumenti, Cervera, Codina
! doi : 10.1016/j.cma.2014.08.004
!
!-----------------------------------------------------------------------
implicit none
contains
!-------------------Tau_u matrix calculation----------
module subroutine sup_elm_usgs_ES(e,ndime,tn,dvol,elmat)
!-----------------------------------------------------------------------
!
! This routine computes the elemental material matrix
! B*B_t, (div y,div s)
!
!-----------------------------------------------------------------------
implicit none
class(FiniteElement), intent(in) :: e
integer(ip), intent(in) :: ndime,tn
real(rp), intent(in) :: dvol
real(rp), intent(inout) :: elmat(tn,e%pnode,tn,e%pnode)
integer(ip) :: idime,jdime,inode,jnode,i,j
real(rp) :: B_i(tn,ndime),B_j(ndime,tn)
real(rp) :: B_aux(tn,ndime)
real(rp) :: BB(tn,tn)
do inode=1,e%pnode
do jnode=1,e%pnode
BB = 0.0_rp
call sld_calculate_FdN_tensor_lin(e,ndime,tn,inode,jnode,BB)
elmat(1:tn,inode,1:tn,jnode) = elmat(1:tn,inode,1:tn,jnode)+BB(:,:)*dvol
end do
end do
end subroutine sup_elm_usgs_ES
module subroutine sup_elm_usgs_EP(e,ndime,tn,dvol,elmat)
!-----------------------------------------------------------------------
!
! This routine computes the elemental material matrix
! B*G, (div y, grad p)
!
!-----------------------------------------------------------------------
implicit none
class(FiniteElement), intent(in) :: e
integer(ip), intent(in) :: ndime,tn
real(rp), intent(in) :: dvol
real(rp), intent(inout) :: elmat(tn,e%pnode,1,e%pnode)
integer(ip) :: idime,jdime,inode,jnode
real(rp) :: B(tn,ndime),G(ndime)
real(rp) :: BG(tn)
do inode=1,e%pnode
call sld_calculateB(e,ndime,tn,inode,B)
do jnode=1,e%pnode
call sld_calculateB_inditial(e,ndime,jnode,G)
BG = matmul(B,G)
elmat(1:tn,inode,1,jnode) = elmat(1:tn,inode,1,jnode) + BG(:)*dvol
end do
end do
end subroutine sup_elm_usgs_EP
module subroutine sup_elm_usgs_QS(e,ndime,tn,dvol,elmat)
!-----------------------------------------------------------------------
!
! This routine computes the elemental material matrix
! G*B
!
!-----------------------------------------------------------------------
implicit none
class(FiniteElement), intent(in) :: e
integer(ip), intent(in) :: ndime,tn
real(rp), intent(in) :: dvol
real(rp), intent(inout) :: elmat(1,e%pnode,tn,e%pnode)
integer(ip) :: idime,jdime,inode,jnode
real(rp) :: G(ndime),B(ndime,tn)
real(rp) :: GB(tn)
do inode=1,e%pnode
do jnode=1,e%pnode
GB = 0.0_rp
!d/dX_i(q_h)
call sld_calculate_dqFinv_vector_lin(e,ndime,tn,inode,jnode,GB)
!Negative sign because of -div(S_ij)
elmat(1,inode,1:tn,jnode) = elmat(1,inode,1:tn,jnode) - GB*dvol
end do
end do
end subroutine sup_elm_usgs_QS
module subroutine sup_elm_usgs_QP(e,ndime,tn,dvol,elmat)
!-----------------------------------------------------------------------
!
! This routine computes the elemental material matrix
! G_t*G
!
!-----------------------------------------------------------------------
implicit none
class(FiniteElement), intent(in) :: e
integer(ip), intent(in) :: ndime,tn
real(rp), intent(in) :: dvol
real(rp), intent(inout) :: elmat(1,e%pnode,1,e%pnode)
integer(ip) :: idime,jdime,inode,jnode
real(rp) :: GG,G_i(ndime),G_j(ndime)
do inode=1,e%pnode
call sld_calculateB_inditial(e,ndime,inode,G_i)
do jnode=1,e%pnode
call sld_calculateB_inditial(e,ndime,jnode,G_j)
GG = dot_product(G_i,G_j)*dvol
elmat(1,inode,1,jnode) = elmat(1,inode,1,jnode) + GG
end do
end do
end subroutine sup_elm_usgs_QP
!-------------------Tau_s matrix calculation----------
module subroutine sup_elm_ssgs_VU(e,ndime,tn,dvol,c_dev,elmat)
!-----------------------------------------------------------------------
!
! This routine computes the elemental material matrix
! B_t*P*Ñ_s
!
!-----------------------------------------------------------------------
implicit none
class(FiniteElement), intent(in) :: e
integer(ip), intent(in) :: ndime,tn
real(rp), intent(in) :: dvol
real(rp), intent(in) :: c_dev(tn,tn)
real(rp), intent(inout) :: elmat(ndime,e%pnode,ndime,e%pnode)
integer(ip) :: idime,jdime,inode,jnode
real(rp) :: CB(tn,ndime)
real(rp) :: B_j(tn,ndime),B_i(ndime,tn)
real(rp) :: B_aux(tn,ndime)
real(rp) :: BCB(ndime,ndime)
do inode=1,e%pnode
call sld_calculateB(e,ndime,tn,inode,B_aux)
B_i = transpose(B_aux)
do jnode=1,e%pnode
call sld_calculateB(e,ndime,tn,jnode,B_j)
CB = matmul(c_dev,B_j)
BCB = matmul(B_i,CB)*dvol
!Notice the minus sign
elmat(1:ndime,inode,1:ndime,jnode) = elmat(1:ndime,inode,1:ndime,jnode) - BCB(:,:)
end do
end do
end subroutine sup_elm_ssgs_VU
module subroutine sup_elm_ssgs_VS(e,ndime,tn,dvol,P,elmat)
!-----------------------------------------------------------------------
!
! This routine computes the elemental material matrix
! B_t*P*Ñ_s
!
!-----------------------------------------------------------------------
implicit none
class(FiniteElement), intent(in) :: e
integer(ip), intent(in) :: ndime,tn
real(rp), intent(in) :: P(tn,tn),dvol
real(rp), intent(inout) :: elmat(ndime,e%pnode,tn,e%pnode)
integer(ip) :: idime,jdime,inode,jnode
real(rp) :: B(ndime,tn)
real(rp) :: auxB(tn,ndime)
real(rp) :: BPN(ndime,tn)
real(rp) :: ii(tn,tn),N(tn,tn)
real(rp) :: PN(tn,tn)
call getDiagTensor(ndime,tn,ii)
do inode=1,e%pnode
call sld_calculateB(e,ndime,tn,inode,auxB)
B = transpose(auxB)
do jnode=1,e%pnode
N = e%shape(jnode,e%igaus)*ii
PN = matmul(P,N)
BPN = matmul(B,PN)*dvol
elmat(1:ndime,inode,1:tn,jnode) = elmat(1:ndime,inode,1:tn,jnode) + BPN(1:ndime,1:tn)
end do
end do
end subroutine sup_elm_ssgs_VS
module subroutine sup_elm_ssgs_EU(e,ndime,tn,dvol,P,elmat)
!-----------------------------------------------------------------------
!
! This routine computes the elemental material matrix
! N_t*P*B, (y,P:grad_s u)
!
!-----------------------------------------------------------------------
implicit none
class(FiniteElement), intent(in) :: e
integer(ip), intent(in) :: ndime,tn
real(rp), intent(in) :: P(tn,tn),dvol
real(rp), intent(inout) :: elmat(tn,e%pnode,ndime,e%pnode)
integer(ip) :: idime,jdime,inode,jnode
real(rp) :: ii(tn,tn)
real(rp) :: N(tn,tn)
real(rp) :: B(tn,ndime)
real(rp) :: PB(tn,ndime)
real(rp) :: NPB(tn,ndime)
call getDiagTensor(ndime,tn,ii)
do inode=1,e%pnode
N = e%shape(inode,e%igaus)*(ii)
do jnode=1,e%pnode
call sld_calculateB(e,ndime,tn,jnode,B)
PB = matmul(P,B)
NPB = matmul(N,PB)*dvol
elmat(1:tn,inode,1:ndime,jnode) = elmat(1:tn,inode,1:ndime,jnode) + NPB(:,:)
end do
end do
end subroutine sup_elm_ssgs_EU
module subroutine sup_elm_ssgs_ES(e,ndime,tn,dvol,D,elmat)
!-----------------------------------------------------------------------
!
! This routine computes the elemental material matrix
! -Ñ_s_t*D*Ñ_s , (y,D:s)
!
!-----------------------------------------------------------------------
implicit none
class(FiniteElement), intent(in) :: e
integer(ip), intent(in) :: ndime,tn
real(rp), intent(in) :: D(tn,tn),dvol
real(rp), intent(inout) :: elmat(tn,e%pnode,tn,e%pnode)
integer(ip) :: idime,jdime,inode,jnode
real(rp) :: ii(tn,tn)
real(rp) :: N_i(tn,tn) ,N_j(tn,tn)
real(rp) :: B(tn,ndime)
real(rp) :: NN(tn,tn)
!call getDiagTensor(ndime,tn,ii)
!do inode=1,e%pnode
! N_i = e%shape(inode,e%igaus)*(ii)
! do jnode=1,e%pnode
! N_j = e%shape(jnode,e%igaus)*ii
! DN = matmul(D,N_j)
! NDN = matmul(N_i,DN)*dvol
! !Notice the minus sign
! elmat(1:tn,inode,1:tn,jnode) = elmat(1:tn,inode,1:tn,jnode) - NDN(1:tn,1:tn)
! end do
!end do
call getDiagTensor(ndime,tn,ii)
do inode=1,e%pnode
! xi_ij
N_i = e%shape(inode,e%igaus)*ii
do jnode=1,e%pnode
N_j = e%shape(jnode,e%igaus)*ii
! (xi_ij,S_ij)
NN = matmul(D,N_j)
NN = matmul(N_i,NN)*dvol
elmat(1:tn,inode,1:tn,jnode) = elmat(1:tn,inode,1:tn,jnode) - NN(1:tn,1:tn)
end do
end do
end subroutine sup_elm_ssgs_ES
!-------------------Tau_p matrix calculation----------
module subroutine sup_elm_psgs_VU(e,ndime,dvol,K,G,elmat)
!-----------------------------------------------------------------------
!
! This routine computes the elemental material matrix
! G_t*G
!
!-----------------------------------------------------------------------
implicit none
class(FiniteElement), intent(in) :: e
integer(ip), intent(in) :: ndime
real(rp), intent(in) :: dvol,K,G
real(rp), intent(inout) :: elmat(ndime,e%pnode,ndime,e%pnode)
integer(ip) :: idime,jdime,inode,jnode,i,j
real(rp) :: GG(ndime,ndime),G_i(ndime),G_j(ndime),C_vol
C_vol=min(K,(2.0_rp/3.0_rp)*G)
do inode=1,e%pnode
call sld_calculateB_inditial(e,ndime,inode,G_i)
do jnode=1,e%pnode
call sld_calculateB_inditial(e,ndime,jnode,G_j)
GG = 0.0_rp
do i=1,ndime
do j=1,ndime
GG(i,j) = G_i(i)*G_j(j)
end do
end do
elmat(1:ndime,inode,1:ndime,jnode) = elmat(1:ndime,inode,1:ndime,jnode) - C_vol*GG*dvol
end do
end do
end subroutine sup_elm_psgs_VU
module subroutine sup_elm_psgs_VP(e,ndime,dvol,elmat)
!-----------------------------------------------------------------------
!
! This routine computes the elemental material matrix
! GN_p
!
!-----------------------------------------------------------------------
implicit none
class(FiniteElement), intent(in) :: e
integer(ip), intent(in) :: ndime
real(rp), intent(in) :: dvol
real(rp), intent(inout) :: elmat(ndime,e%pnode,1,e%pnode)
integer(ip) :: idime,jdime,inode,jnode
real(rp) :: G(ndime),GN(ndime)
G = 0.0_rp
GN = 0.0_rp
do inode=1,e%pnode
call sld_calculateB_inditial(e,ndime,inode,G)
do jnode=1,e%pnode
GN = G*e%shape(jnode,e%igaus)*dvol
elmat(1:ndime,inode,1,jnode) = elmat(1:ndime,inode,1,jnode) + GN(1:ndime)
end do
end do
end subroutine sup_elm_psgs_VP
module subroutine sup_elm_psgs_QU(e,ndime,dvol,elmat)
!-----------------------------------------------------------------------
!
! This routine computes the elemental material matrix
! N_iG_j
!
!-----------------------------------------------------------------------
implicit none
class(FiniteElement), intent(in) :: e
integer(ip), intent(in) :: ndime
real(rp), intent(in) :: dvol
real(rp), intent(inout) :: elmat(1,e%pnode,ndime,e%pnode)
integer(ip) :: idime,jdime,inode,jnode
real(rp) :: G(ndime),NG(ndime),N
G = 0.0_rp
NG = 0.0_rp
N = 0.0_rp
do inode=1,e%pnode
N = e%shape(inode,e%igaus)
do jnode=1,e%pnode
call sld_calculateB_inditial(e,ndime,jnode,G)
NG = N*G*dvol
elmat(1,inode,1:ndime,jnode) = elmat(1,inode,1:ndime,jnode) + NG(1:ndime)
end do
end do
end subroutine sup_elm_psgs_QU
module subroutine sup_elm_psgs_QP(e,ndime,dvol,D_vol,elmat)
!-----------------------------------------------------------------------
!
! This routine computes the elemental material matrix
! -D_vol*N_j_t*N_i
!
!-----------------------------------------------------------------------
implicit none
class(FiniteElement), intent(in) :: e
integer(ip), intent(in) :: ndime
real(rp), intent(in) :: dvol,D_vol
real(rp), intent(inout) :: elmat(1,e%pnode,1,e%pnode)
integer(ip) :: idime,jdime,inode,jnode
real(rp) :: DNN,N_i,N_j
do inode=1,e%pnode
N_i = e%shape(inode,e%igaus)
do jnode=1,e%pnode
N_j = e%shape(jnode,e%igaus)
!Notice the minus sign
DNN = -D_vol*N_i*N_j*dvol
elmat(1,inode,1,jnode) = elmat(1,inode,1,jnode) + DNN
end do
end do
end subroutine sup_elm_psgs_QP
end submodule SUPCauchyElementSGS
|
(** Extension of Coq language with some IO and exception-handling operators.
TODO: integration with http://coq.io/ ?
*)
Require Export ImpPrelude.
Import Notations.
Local Open Scope impure.
(** Printing functions *)
Axiom print: pstring -> ?? unit.
Extract Constant print => "ImpIOOracles.print".
Axiom println: pstring -> ?? unit.
Extract Constant println => "ImpIOOracles.println".
Axiom read_line: unit -> ?? pstring.
Extract Constant read_line => "ImpIOOracles.read_line".
Require Import ZArith.
Axiom string_of_Z: Z -> ?? pstring.
Extract Constant string_of_Z => "ImpIOOracles.string_of_Z".
(** timer *)
Axiom timer: forall {A B}, (A -> ?? B)*A -> ?? B.
Extract Constant timer => "ImpIOOracles.timer".
(** Exception Handling *)
Axiom exit_observer: Type.
Extract Constant exit_observer => "((unit -> unit) ref)".
Axiom new_exit_observer: (unit -> ??unit) -> ??exit_observer.
Extract Constant new_exit_observer => "ImpIOOracles.new_exit_observer".
Axiom set_exit_observer: exit_observer * (unit -> ??unit) -> ??unit.
Extract Constant set_exit_observer => "ImpIOOracles.set_exit_observer".
Axiom exn: Type.
Extract Inlined Constant exn => "exn".
Axiom raise: forall {A}, exn -> ?? A.
Extract Constant raise => "raise".
Axiom exn2string: exn -> ?? pstring.
Extract Constant exn2string => "ImpIOOracles.exn2string".
Axiom fail: forall {A}, pstring -> ?? A.
Extract Constant fail => "ImpIOOracles.fail".
Axiom try_with_fail: forall {A}, (unit -> ?? A) * (pstring -> exn -> ??A) -> ??A.
Extract Constant try_with_fail => "ImpIOOracles.try_with_fail".
Axiom try_with_any: forall {A}, (unit -> ?? A) * (exn -> ??A) -> ??A.
Extract Constant try_with_any => "ImpIOOracles.try_with_any".
Notation "'RAISE' e" := (DO r <~ raise (A:=False) e ;; RET (match r with end)) (at level 0): impure_scope.
Notation "'FAILWITH' msg" := (DO r <~ fail (A:=False) msg ;; RET (match r with end)) (at level 0): impure_scope.
Definition _FAILWITH {A:Type} msg: ?? A := FAILWITH msg.
Example _FAILWITH_correct A msg (P: A -> Prop):
WHEN _FAILWITH msg ~> r THEN P r.
Proof.
wlp_simplify.
Qed.
Notation "'TRY' k1 'WITH_FAIL' s ',' e '=>' k2" := (try_with_fail (fun _ => k1, fun s e => k2))
(at level 55, k1 at level 53, right associativity): impure_scope.
Notation "'TRY' k1 'WITH_ANY' e '=>' k2" := (try_with_any (fun _ => k1, fun e => k2))
(at level 55, k1 at level 53, right associativity): impure_scope.
Program Definition assert_b (b: bool) (msg: pstring): ?? b=true :=
match b with
| true => RET _
| false => FAILWITH msg
end.
Lemma assert_wlp_true msg b: WHEN assert_b b msg ~> _ THEN b=true.
Proof.
wlp_simplify.
Qed.
Lemma assert_false_wlp msg (P: Prop): WHEN assert_b false msg ~> _ THEN P.
Proof.
simpl; wlp_simplify.
Qed.
Program Definition try_catch_fail_ensure {A} (k1: unit -> ?? A) (k2: pstring -> exn -> ??A) (P: A -> Prop | wlp (k1 tt) P /\ (forall s e, wlp (k2 s e) P)): ?? { r | P r }
:= TRY
DO r <~ mk_annot (k1 tt);;
RET (exist P r _)
WITH_FAIL s, e =>
DO r <~ mk_annot (k2 s e);;
RET (exist P r _).
Obligation 2.
unfold wlp in * |- *; eauto.
Qed.
Notation "'TRY' k1 'CATCH_FAIL' s ',' e '=>' k2 'ENSURE' P" := (try_catch_fail_ensure (fun _ => k1) (fun s e => k2) (exist _ P _))
(at level 55, k1 at level 53, right associativity): impure_scope.
Definition is_try_post {A} (P: A -> Prop) k1 k2 : Prop :=
wlp (k1 ()) P /\ forall (e:exn), wlp (k2 e) P.
Program Definition try_catch_ensure {A} k1 k2 (P:A->Prop|is_try_post P k1 k2): ?? { r | P r }
:= TRY
DO r <~ mk_annot (k1 ());;
RET (exist P r _)
WITH_ANY e =>
DO r <~ mk_annot (k2 e);;
RET (exist P r _).
Obligation 1.
unfold is_try_post, wlp in * |- *; intuition eauto.
Qed.
Obligation 2.
unfold is_try_post, wlp in * |- *; intuition eauto.
Qed.
Notation "'TRY' k1 'CATCH' e '=>' k2 'ENSURE' P" := (try_catch_ensure (fun _ => k1) (fun e => k2) (exist _ P _))
(at level 55, k1 at level 53, right associativity): impure_scope.
Program Example tryex {A} (x y:A) :=
TRY (RET x)
CATCH _ => (RET y)
ENSURE (fun r => r = x \/ r = y).
Obligation 1.
split; wlp_simplify.
Qed.
Program Example tryex_test {A} (x y:A):
WHEN tryex x y ~> r THEN `r <> x -> `r = y.
Proof.
wlp_simplify. destruct exta as [r [X|X]]; intuition.
Qed.
Program Example try_branch1 {A} (x:A): ?? { r | r = x} :=
TRY (RET x)
CATCH e => (FAILWITH "!")
ENSURE _.
Obligation 1.
split; wlp_simplify.
Qed.
Program Example try_branch2 {A} (x:A): ?? { r | r = x} :=
TRY (FAILWITH "!")
CATCH e => (RET x)
ENSURE _.
Obligation 1.
split; wlp_simplify.
Qed.
|
lemma has_vector_derivative_complex_iff: "(f has_vector_derivative x) F \<longleftrightarrow> ((\<lambda>x. Re (f x)) has_field_derivative (Re x)) F \<and> ((\<lambda>x. Im (f x)) has_field_derivative (Im x)) F" |
SUBROUTINE UPQRQF(N,ETA,S,F0,F1,QT,R,W,T)
C
C SUBROUTINE UPQRQF PERFORMS A BROYDEN UPDATE ON THE Q R
C FACTORIZATION OF A MATRIX A, (AN APPROXIMATION TO J(X0)),
C RESULTING IN THE FACTORIZATION Q+ R+ OF
C
C A+ = A + (Y - A*S) (ST)/(ST * S),
C
C (AN APPROXIMATION TO J(X1))
C WHERE S = X1 - X0, ST = S TRANSPOSE, Y = F(X1) - F(X0).
C
C THE ENTRY POINT R1UPQF PERFORMS THE RANK ONE UPDATE ON THE QR
C FACTORIZATION OF
C
C A+ = A + Q*(T*ST).
C
C
C ON INPUT:
C
C N IS THE DIMENSION OF X AND F(X).
C
C ETA IS A NOISE PARAMETER. IF (Y-A*S)(I) .LE. ETA*(|F1(I)|+|F0(I)|)
C FOR 1 .LE. I .LE. N, THEN NO UPDATE IS PERFORMED.
C
C S(1:N) = X1 - X0 (OR S FOR THE ENTRY POINT R1UPQF).
C
C F0(1:N) = F(X0).
C
C F1(1:N) = F(X1).
C
C QT(1:N,1:N) CONTAINS THE OLD Q TRANSPOSE, WHERE A = Q*R .
C
C R(1:N*(N+1)/2) CONTAINS THE OLD R, STORED BY ROWS.
C
C W(1:N), T(1:N) ARE WORK ARRAYS ( T CONTAINS THE VECTOR T FOR THE
C ENTRY POINT R1UPQF ).
C
C
C ON OUTPUT:
C
C N AND ETA ARE UNCHANGED.
C
C QT CONTAINS Q+ TRANSPOSE.
C
C R CONTAINS R+, STORED BY ROWS.
C
C S, F0, F1, W, AND T HAVE ALL BEEN CHANGED.
C
C
C CALLS DAXPY, DDOT, AND DNRM2.
C
C ***** DECLARATIONS *****
C
C FUNCTION DECLARATIONS
C
DOUBLE PRECISION DDOT, DNRM2
C
C LOCAL VARIABLES
C
DOUBLE PRECISION C, DEN, ONE, SS, WW, YY
INTEGER I, INDEXR, INDXR2, J, K
LOGICAL SKIPUP
C
C SCALAR ARGUMENTS
C
DOUBLE PRECISION ETA
INTEGER N
C
C ARRAY DECLARATIONS
C
DOUBLE PRECISION S(N), F0(N), F1(N), QT(N,N), R(N*(N+1)/2),
$ W(N), T(N), TT(2)
C
C ***** END OF DECLARATIONS *****
C
C ***** FIRST EXECUTABLE STATEMENT *****
C
ONE = 1.0
SKIPUP = .TRUE.
C
C ***** DEFINE T AND S SUCH THAT *****
C
C A+ = Q*(R + T*ST).
C
C T = R*S.
C
INDEXR = 1
DO 10 I=1,N
T(I) = DDOT(N-I+1,R(INDEXR),1,S(I),1)
INDEXR = INDEXR + N - I + 1
10 CONTINUE
C
C W = Y - Q*T = Y - A*S.
C
DO 20 I=1,N
W(I) = F1(I) - F0(I) - DDOT(N,QT(1,I),1,T,1)
C
C IF W(I) IS NOT SMALL, THEN UPDATE MUST BE PERFORMED,
C OTHERWISE SET W(I) TO 0.
C
IF (ABS(W(I)) .GT. ETA*(ABS(F1(I)) + ABS(F0(I)))) THEN
SKIPUP = .FALSE.
ELSE
W(I) = 0.0
END IF
20 CONTINUE
C
C IF NO UPDATE IS NECESSARY, THEN RETURN.
C
IF (SKIPUP) RETURN
C
C T = QT*W = QT*Y - R*S.
C
DO 30 I=1,N
T(I) = DDOT(N,QT(I,1),N,W,1)
30 CONTINUE
C
C S = S/(ST*S).
C
DEN = 1.0/DDOT(N,S,1,S,1)
CALL DSCAL(N,DEN,S,1)
C
C ***** END OF COMPUTATION OF T & S *****
C AT THIS POINT, A+ = Q*(R + T*ST).
C
CALL r1upqf(n, s, t, qt, r, w)
RETURN
END
|
Set Universe Polymorphism.
Require Import GHC.Base.
(** * Deriving from applicative functors *)
Definition apdict_fmap {I : Type -> Type} `{D : Applicative__Dict I}
{A B : Type} (f : A -> B) (a : I A) : I B :=
@liftA2__ I D _ _ _ id (@pure__ I D _ f) a.
#[global] Instance apdict_functor (I : Type -> Type) (D : Applicative__Dict I) : Functor I :=
fun r k => k {| fmap__ := fun {a} {b} => apdict_fmap (D := D) ;
op_zlzd____ := fun {a} {b} => apdict_fmap (D := D) ∘ const |}.
#[global] Instance apdict_applicative (I : Type -> Type) (D : Applicative__Dict I) :
@Applicative I (apdict_functor I D) :=
fun r k => k D.
(** * Deriving from monads *)
Definition monaddict_fmap {I : Type -> Type} `{D : Monad__Dict I}
{A B : Type} (f : A -> B) (a : I A) : I B :=
@op_zgzgze____ I D _ _ a (@return___ I D _ ∘ f).
#[global] Instance monaddict_functor (I : Type -> Type) (D : Monad__Dict I) : Functor I :=
fun r k => k {| fmap__ := fun {a} {b} => monaddict_fmap (D := D) ;
op_zlzd____ := fun {a} {b} => monaddict_fmap (D := D) ∘ const |}.
Definition monaddict_ap {I : Type -> Type} `{D : Monad__Dict I}
{A B : Type} (f : I (A -> B)) (a : I A) : I B :=
@op_zgzgze____ I D _ _ a
(fun a => @op_zgzgze____ I D _ _ f
(fun f => @return___ I D _ (f a))).
#[global] Instance monaddict_applicative (I : Type -> Type) (D : Monad__Dict I) :
@Applicative I (monaddict_functor I D) :=
fun r k => k {| liftA2__ := fun {a b c} g fa fb =>
monaddict_ap (D := D)
(monaddict_fmap (D := D) g fa) fb ;
op_zlztzg____ := fun {a b} => monaddict_ap (D := D) ;
op_ztzg____ := fun {a b} fa => monaddict_ap (D := D) (op_zlzd__
(g__0__ := monaddict_functor I D) id fa) ;
pure__ := fun {a} => @return___ I D _ |}.
#[global] Instance monaddict_monad (I : Type -> Type) (D : Monad__Dict I) :
@Monad I (monaddict_functor I D) (monaddict_applicative I D) :=
fun r k => k D.
|
Developed exclusively for Coach, Coach Leather Cleaner is an allover leather cleaner tested to ensure gentle yet effective cleaning and the optimal care for Coach leather products.
We recommend that you use only Coach Leather Cleaner on your Coach leather products, as other cleaners may contain solvents that can discolor or damage our leathers.
Coach Leather Cleaner is safe for use on almost all Coach leathers. Please expand the details section for more information.
Coach Leather Cleaner may be used on the following leathers: Crossgrain, Glovetanned, Metallic Pebble, Natural Calf, Pebble, Polished Pebble, Refined Pebble, Signature Calf, Smooth Calf, Soft Calf, Stamped/Glazed Crocodile, Stamped Snakeskin.
Please DO NOT use this product on Sport Calf Leather, Calf Suede or Haircalf. For other leathers not on this list, test in an inconspicuous spot and let dry for at least one hour to ensure no negative reaction before proceeding. |
State Before: α : Type ?u.61226
β : Type ?u.61229
G₀ : Type u_1
inst✝² : TopologicalSpace G₀
inst✝¹ : GroupWithZero G₀
inst✝ : ContinuousMul G₀
a : G₀
h : Tendsto Inv.inv (𝓝 1) (𝓝 1)
x : G₀
hx : x ≠ 0
⊢ ContinuousAt Inv.inv x State After: α : Type ?u.61226
β : Type ?u.61229
G₀ : Type u_1
inst✝² : TopologicalSpace G₀
inst✝¹ : GroupWithZero G₀
inst✝ : ContinuousMul G₀
a : G₀
h : Tendsto Inv.inv (𝓝 1) (𝓝 1)
x : G₀
hx : x ≠ 0
hx' : x⁻¹ ≠ 0
⊢ ContinuousAt Inv.inv x Tactic: have hx' := inv_ne_zero hx State Before: α : Type ?u.61226
β : Type ?u.61229
G₀ : Type u_1
inst✝² : TopologicalSpace G₀
inst✝¹ : GroupWithZero G₀
inst✝ : ContinuousMul G₀
a : G₀
h : Tendsto Inv.inv (𝓝 1) (𝓝 1)
x : G₀
hx : x ≠ 0
hx' : x⁻¹ ≠ 0
⊢ ContinuousAt Inv.inv x State After: α : Type ?u.61226
β : Type ?u.61229
G₀ : Type u_1
inst✝² : TopologicalSpace G₀
inst✝¹ : GroupWithZero G₀
inst✝ : ContinuousMul G₀
a : G₀
h : Tendsto Inv.inv (𝓝 1) (𝓝 1)
x : G₀
hx : x ≠ 0
hx' : x⁻¹ ≠ 0
⊢ Tendsto ((fun x_1 => x_1 * x⁻¹⁻¹) ∘ Inv.inv ∘ fun x_1 => x * x_1) (𝓝 1) (𝓝 1) Tactic: rw [ContinuousAt, ← map_mul_left_nhds_one₀ hx, ← nhds_translation_mul_inv₀ hx',
tendsto_map'_iff, tendsto_comap_iff] |
State Before: α : Type u
β : Type v
X : Type ?u.304312
ι : Type ?u.304315
inst✝ : PseudoMetricSpace α
x y z : α
ε ε₁ ε₂ : ℝ
s : Set α
e : β → α
a : α
⊢ (∀ (i : ℕ), True → ∃ y, y ∈ range e ∧ y ∈ ball a (1 / (↑i + 1))) ↔ ∀ (n : ℕ), ∃ k, dist a (e k) < 1 / (↑n + 1) State After: no goals Tactic: simp only [mem_ball, dist_comm, exists_range_iff, forall_const] |
{-# OPTIONS --cubical #-}
module PathWith where
open import Agda.Builtin.Cubical.Path
open import Agda.Primitive.Cubical
open import Agda.Builtin.Nat
pred : Nat → Nat
pred (suc n) = n
pred 0 = 0
f : Nat → Nat
f n with pred n
... | zero = zero
... | suc m = suc m
module _ (qqq : Nat) where
test1 : f ≡ pred
test1 i n with pred n
... | zero = zero
... | suc q = suc q
test2 : test1 ≡ test1
test2 i n j x with pred x
... | zero = zero
... | suc q = suc q
|
If $A_1, \ldots, A_n$ are finite sets, then $\sum_{i=1}^n |A_i| \geq |\bigcup_{i=1}^n A_i|$. |
"""
$(TYPEDEF)
Structures to contain the volumes obtained from calculations.
$(TYPEDFIELDS)
"""
@with_kw mutable struct Volume
total::Float64
bulk::Float64
domain::Float64
shell::Vector{Float64}
end
Volume(nbins::Int) = Volume(0.0, 0.0, 0.0, zeros(Float64, nbins))
function reset!(v::Volume)
v.total = 0.0
v.bulk = 0.0
v.domain = 0.0
@. v.shell = 0.0
return nothing
end
#function Base.show(io::IO, v::Volume)
# n = length(v.shell)
# println(" Mean total box volume: $(v.total) ")
# println(" Mean bulk volume: $(v.bulk) ")
# println(" Mean solute domain volume: $(v.domain) ")
# println(" Volumes of first, medium, and last solvation shells: $(v.shell[1]), $(v.shell[round(Int,n/2)]), $(v.shell[n])")
#end
|
(* *********************************************************************)
(* *)
(* The CertiKOS Certified Kit Operating System *)
(* *)
(* The FLINT Group, Yale University *)
(* *)
(* Copyright The FLINT Group, Yale University. All rights reserved. *)
(* This file is distributed under the terms of the Yale University *)
(* Non-Commercial License Agreement. *)
(* *)
(* *********************************************************************)
(* *********************************************************************)
(* *)
(* Low Level Specification *)
(* *)
(* Ronghui Gu <[email protected]> *)
(* *)
(* Yale Flint Group *)
(* *)
(* *********************************************************************)
(** This file provide the contextual refinement proof between MBoot layer and MALInit layer*)
Require Import Coqlib.
Require Import Errors.
Require Import AST.
Require Import Integers.
Require Import Floats.
Require Import Op.
Require Import Asm.
Require Import Events.
Require Import Globalenvs.
Require Import Smallstep.
Require Import Values.
Require Import Memory.
Require Import Maps.
Require Import AuxLemma.
Require Import FlatMemory.
Require Import AuxStateDataType.
Require Import Constant.
Require Import GlobIdent.
Require Import RealParams.
Require Import AsmImplLemma.
Require Import GenSem.
Require Import PrimSemantics.
Require Import Conventions.
Require Import liblayers.logic.PTreeModules.
Require Import liblayers.logic.LayerLogicImpl.
Require Import liblayers.compcertx.Stencil.
Require Import liblayers.compcertx.MakeProgram.
Require Import liblayers.compat.CompatLayers.
Require Import liblayers.compat.CompatGenSem.
Require Import compcert.cfrontend.Ctypes.
Require Import AbstractDataType.
Require Import PIPC.
Local Open Scope string_scope.
Local Open Scope error_monad_scope.
Local Open Scope Z_scope.
(** * Definition of the refinement relation*)
Section Refinement.
Context `{real_params: RealParams}.
Notation LDATA := RData.
Notation LDATAOps := (cdata LDATA).
Inductive elf_load_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:
sprimcall_sem (mem := mwd LDATAOps):=
| elf_load_spec_low_intro s (m'0: mwd LDATAOps) n be ofse sig rs b:
find_symbol s elf_load = Some b ->
rs PC = Vptr b Int.zero ->
(exists elf_id, find_symbol s elf_id = Some be) ->
sig = mksignature (AST.Tint::AST.Tint::nil) None cc_default ->
extcall_arguments rs m'0 sig (Vptr be ofse :: Vint n :: nil) ->
asm_invariant (mem := mwd LDATAOps) s rs m'0 ->
elf_load_spec_low_step s rs m'0 (rs#RA<- Vundef#PC <- (rs#RA)) m'0.
Inductive uctx_get_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:
sextcall_sem (mem := mwd LDATAOps) :=
uctx_get_spec_low_intro s (WB: _ -> Prop) (m'0: mwd LDATAOps) b0 n ofs v:
find_symbol s UCTX_LOC = Some b0 ->
Mem.load Mint32 m'0 b0 ((Int.unsigned n) * UCTXT_SIZE * 4 + Int.unsigned ofs * 4) = Some (Vint v) ->
0 <= (Int.unsigned n) < num_proc ->
is_UCTXT_ptr (Int.unsigned ofs) = false ->
kernel_mode (snd m'0) ->
uctx_get_spec_low_step s WB (Vint n :: Vint ofs :: nil) m'0 (Vint v) m'0.
Inductive uctx_set_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:
sextcall_sem (mem := mwd LDATAOps) :=
uctx_set_spec_low_intro s (WB: _ -> Prop) (m'0 m0: mwd LDATAOps) b0 n ofs v:
find_symbol s UCTX_LOC = Some b0 ->
Mem.store Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + Int.unsigned ofs * 4) (Vint v) = Some m0 ->
0 <= (Int.unsigned n) < num_proc ->
is_UCTXT_ptr (Int.unsigned ofs) = false ->
kernel_mode (snd m'0) ->
uctx_set_spec_low_step s WB (Vint n :: Vint ofs :: Vint v :: nil) m'0 Vundef m0.
Inductive uctx_set_eip_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:
sextcall_sem (mem := mwd LDATAOps) :=
uctx_set_eip_spec_low_intro s (WB: _ -> Prop) (m'0 m0: mwd LDATAOps) b0 n bf ofs:
find_symbol s UCTX_LOC = Some b0 ->
Mem.store Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_EIP * 4) (Vptr bf ofs) = Some m0 ->
0 <= (Int.unsigned n) < num_proc ->
(exists fun_id, find_symbol s fun_id = Some bf) ->
kernel_mode (snd m'0) ->
uctx_set_eip_spec_low_step s WB (Vint n :: Vptr bf ofs :: nil) m'0 Vundef m0.
Inductive save_uctx_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:
sextcall_sem (mem := mwd LDATAOps) :=
save_uctx_spec_low_intro s (WB: _ -> Prop)
(m0 m1 m2 m3 m4 m5 m6 m7 m8 m9 m10 m11 m12 m13 m14
m15 m16 m17: mwd LDATAOps)
u0 u1 u2 u3 u4 u5 u6 u7 u8 u9 u10 u11 u12 u13 u14 u15 u16 b1 n:
find_symbol s UCTX_LOC = Some b1 ->
Mem.store Mint32 m0 b1 (UCTXT_SIZE * 4 * n + 4 * U_EDI) (Vint u0) = Some m1 ->
Mem.store Mint32 m1 b1 (UCTXT_SIZE * 4 * n + 4 * U_ESI) (Vint u1) = Some m2 ->
Mem.store Mint32 m2 b1 (UCTXT_SIZE * 4 * n + 4 * U_EBP) (Vint u2) = Some m3 ->
Mem.store Mint32 m3 b1 (UCTXT_SIZE * 4 * n + 4 * U_OESP) (Vint u3) = Some m4 ->
Mem.store Mint32 m4 b1 (UCTXT_SIZE * 4 * n + 4 * U_EBX) (Vint u4) = Some m5 ->
Mem.store Mint32 m5 b1 (UCTXT_SIZE * 4 * n + 4 * U_EDX) (Vint u5) = Some m6 ->
Mem.store Mint32 m6 b1 (UCTXT_SIZE * 4 * n + 4 * U_ECX) (Vint u6) = Some m7 ->
Mem.store Mint32 m7 b1 (UCTXT_SIZE * 4 * n + 4 * U_EAX) (Vint u7) = Some m8 ->
Mem.store Mint32 m8 b1 (UCTXT_SIZE * 4 * n + 4 * U_ES) (Vint u8) = Some m9 ->
Mem.store Mint32 m9 b1 (UCTXT_SIZE * 4 * n + 4 * U_DS) (Vint u9) = Some m10 ->
Mem.store Mint32 m10 b1 (UCTXT_SIZE * 4 * n + 4 * U_TRAPNO) (Vint u10) = Some m11 ->
Mem.store Mint32 m11 b1 (UCTXT_SIZE * 4 * n + 4 * U_ERR) (Vint u11) = Some m12 ->
Mem.store Mint32 m12 b1 (UCTXT_SIZE * 4 * n + 4 * U_EIP) (Vint u12) = Some m13 ->
Mem.store Mint32 m13 b1 (UCTXT_SIZE * 4 * n + 4 * U_CS) (Vint u13) = Some m14 ->
Mem.store Mint32 m14 b1 (UCTXT_SIZE * 4 * n + 4 * U_EFLAGS) (Vint u14) = Some m15 ->
Mem.store Mint32 m15 b1 (UCTXT_SIZE * 4 * n + 4 * U_ESP) (Vint u15) = Some m16 ->
Mem.store Mint32 m16 b1 (UCTXT_SIZE * 4 * n + 4 * U_SS) (Vint u16) = Some m17 ->
cid (snd m0) = n ->
kernel_mode (snd m0) ->
pg (snd m0) = true ->
save_uctx_spec_low_step s WB (Vint u0::Vint u1::Vint u2::Vint u3::Vint u4::Vint u5::Vint u6::
Vint u7::Vint u8::Vint u9::Vint u10::Vint u11::Vint u12::Vint u13
::Vint u14::Vint u15::Vint u16::nil) m0 Vundef m17.
Inductive restore_uctx_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:
sprimcall_sem (mem := mwd LDATAOps):=
restore_uctx_spec_low_intro s v0 v1 v2 v4 v5 v6 v7 v8 v9
(m'0: mem) b0 n rs rs' labd labd' sig b:
find_symbol s restore_uctx = Some b ->
rs PC = Vptr b Int.zero ->
find_symbol s UCTX_LOC = Some b0 ->
Mem.load Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_EDI) = Some v0 ->
Mem.load Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_ESI * 4) = Some v1 ->
Mem.load Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_EBP * 4) = Some v2 ->
Mem.load Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_EBX * 4) = Some v4 ->
Mem.load Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_EDX * 4) = Some v5 ->
Mem.load Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_ECX * 4) = Some v6 ->
Mem.load Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_EAX * 4) = Some v7 ->
Mem.load Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_ESP * 4) = Some v8 ->
Mem.load Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_EIP * 4) = Some v9 ->
rs' = (undef_regs (CR ZF :: CR CF :: CR PF :: CR SF :: CR OF
:: IR ECX :: IR EAX :: RA :: nil)
(undef_regs (List.map preg_of destroyed_at_call) rs)) ->
trapout_spec labd = Some labd' ->
cid labd = Int.unsigned n ->
kernel_mode labd ->
asm_invariant (mem := mwd LDATAOps) s rs (m'0, labd) ->
high_level_invariant labd ->
sig = mksignature (AST.Tint::nil) None cc_default ->
extcall_arguments rs m'0 sig (Vint n ::nil) ->
restore_uctx_spec_low_step s rs (m'0, labd)
(rs'#Asm.EDI <- v0 #Asm.ESI <- v1 #Asm.EBP <- v2 #Asm.ESP<- v8#Asm.EBX <- v4
#EDX<- v5 #ECX<-v6 #EAX <- v7# PC <- v9) (m'0, labd').
Section WITHMEM.
Context `{Hstencil: Stencil}.
Context `{Hmem: Mem.MemoryModel}.
Context `{Hmwd: UseMemWithData mem}.
Definition uctx_get_spec_low: compatsem LDATAOps :=
csem uctx_get_spec_low_step (type_of_list_type (Tint32::Tint32::nil)) Tint32.
Definition uctx_set_spec_low: compatsem LDATAOps :=
csem uctx_set_spec_low_step (type_of_list_type (Tint32::Tint32::Tint32::nil)) Tvoid.
Definition uctx_set_eip_spec_low: compatsem LDATAOps :=
csem uctx_set_eip_spec_low_step (type_of_list_type (Tint32::Tpointer Tvoid noattr::nil)) Tvoid.
Definition elf_load_spec_low: compatsem LDATAOps :=
asmsem_withsig elf_load elf_load_spec_low_step (mksignature (AST.Tint::AST.Tint::nil) None cc_default).
Definition save_uctx_spec_low: compatsem LDATAOps :=
csem save_uctx_spec_low_step (type_of_list_type
(Tint32::Tint32::Tint32::Tint32::
Tint32::Tint32::Tint32::Tint32::
Tint32::Tint32::Tint32::Tint32::
Tint32::Tint32::Tint32::Tint32::
Tint32::nil)) Tvoid.
Definition restore_uctx_spec_low: compatsem LDATAOps :=
asmsem_withsig restore_uctx restore_uctx_spec_low_step (mksignature (AST.Tint::nil) None cc_default).
(*Definition MSpec : compatlayer LDATAOps :=
uctx_get ↦ uctx_get_spec_low
⊕ uctx_set ↦ uctx_set_spec_low
⊕ uctx_set_eip ↦ uctx_set_eip_spec_low
⊕ restore_uctx ↦ restore_uctx_spec_low
⊕ save_uctx ↦ save_uctx_spec_low
⊕ elf_load ↦ elf_load_spec_low.
Definition MVar : compatlayer LDATAOps :=
UCTX_LOC ↦ mkglobvar (Tarray Tint32 (num_proc * UCTXT_SIZE * 4) (mk_attr false None))
(Init_space (num_proc * UCTXT_SIZE * 4) :: nil) false false.*)
End WITHMEM.
End Refinement.
|
lemma (in finite_measure) bounded_measure: "measure M A \<le> measure M (space M)" |
## Author: Sergio García Prado
## Title: Statistical Inference - Goodness of Fit - Exercise 09
rm(list = ls())
observed <- c(8, 46, 55, 40, 11)
(k <- length(observed))
# 5
(n <- sum(observed))
# 160
(p.hat <- sum(observed * 0:(k-1)) / (n * (k - 1)))
# 0.5
(expected <- n * dbinom(0:(k - 1), size = k - 1, prob = p.hat))
# 10 40 60 40 10
(Q <- sum((observed - expected ) ^ 2 / expected))
# 1.81666666666666
(pvalue <- 1 - pchisq(Q, df = (k - 1) - 1))
# 0.611314815940897
|
section {*FUNCTION\_\_CFG\_AUGMENT*}
theory
FUNCTION__CFG_AUGMENT
imports
PRJ_12_06_02__ENTRY
begin
definition F_CFG_AUGMENT__input :: "
('nonterminal DT_symbol, 'event DT_symbol) cfg
\<Rightarrow> 'event DT_symbol
\<Rightarrow> 'nonterminal DT_symbol
\<Rightarrow> ('nonterminal DT_symbol, 'event DT_symbol) cfg
\<Rightarrow> bool"
where
"F_CFG_AUGMENT__input G Do S' G' \<equiv>
valid_cfg G
\<and> Do = F_FRESH (cfg_events G)
\<and> S' = F_FRESH (cfg_nonterminals G)
\<and> G' = F_CFG_AUGMENT G S' Do"
theorem F_CFG_AUGMENT__makes_CFG: "
F_CFG_AUGMENT__input G Do S' G'
\<Longrightarrow> valid_cfg G'"
apply(simp add: F_CFG_AUGMENT__input_def F_CFG_AUGMENT_def)
apply(simp add: valid_cfg_def)
apply(clarsimp)
apply(rename_tac e)(*strict*)
apply(erule_tac
x="e"
in ballE)
apply(rename_tac e)(*strict*)
apply(auto)
done
lemma F_CFG_AUGMENT__FirstStep: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> valid_cfg G'
\<Longrightarrow> cfgSTD.derivation G' d
\<Longrightarrow> d 0 = Some (pair None \<lparr>cfg_conf = [teA (cfg_initial G')]\<rparr>)
\<Longrightarrow> d (Suc n) \<noteq> None
\<Longrightarrow> d (Suc 0) = Some (pair (Some \<lparr>prod_lhs = cfg_initial G', prod_rhs = [teB Do, teA (cfg_initial G), teB Do]\<rparr>) \<lparr>cfg_conf = [teB Do, teA (cfg_initial G), teB Do]\<rparr>)"
apply(subgoal_tac "\<exists>e c. d (Suc 0) = Some (pair (Some e) c)")
prefer 2
apply(case_tac "d (Suc 0)")
apply(case_tac n)
apply(force)
apply(rename_tac nat)(*strict*)
apply(rule_tac
n="Suc n"
and i="Suc 0"
in cfgSTD.derivationNoFromNone2)
apply(rename_tac nat)(*strict*)
apply(force)
apply(rename_tac nat)(*strict*)
apply(force)
apply(rename_tac nat)(*strict*)
apply(force)
apply(rename_tac nat)(*strict*)
apply(force)
apply(rename_tac a)(*strict*)
apply(case_tac a)
apply(rename_tac a option b)(*strict*)
apply(clarsimp)
apply(rename_tac option b y)(*strict*)
apply(case_tac option)
apply(rename_tac option b y)(*strict*)
apply(clarsimp)
apply(rename_tac b y)(*strict*)
apply(rule cfgSTD.derivation_Always_PreEdge_prime)
apply(rename_tac b y)(*strict*)
apply(force)
apply(rename_tac b y)(*strict*)
apply(force)
apply(rename_tac option b y a)(*strict*)
apply(force)
apply(erule exE)+
apply(rename_tac e c)(*strict*)
apply(subgoal_tac "cfgSTD_step_relation G' \<lparr>cfg_conf = [teA (cfg_initial G')]\<rparr> e c")
apply(rename_tac e c)(*strict*)
prefer 2
apply(rule cfgSTD.position_change_due_to_step_relation)
apply(rename_tac e c)(*strict*)
apply(force)
apply(rename_tac e c)(*strict*)
apply(force)
apply(rename_tac e c)(*strict*)
apply(force)
apply(rename_tac e c)(*strict*)
apply(case_tac e)
apply(rename_tac e c prod_lhs prod_rhs)(*strict*)
apply(case_tac c)
apply(rename_tac e c prod_lhs prod_rhs cfg_conf)(*strict*)
apply(rename_tac A w s)
apply(rename_tac e c A w s)(*strict*)
apply(subgoal_tac "A=cfg_initial G' \<and> w=[teB Do, teA (cfg_initial G), teB Do] \<and> s=[teB Do, teA (cfg_initial G), teB Do]")
apply(rename_tac e c A w s)(*strict*)
apply(force)
apply(rename_tac e c A w s)(*strict*)
apply(simp add: cfgSTD_step_relation_def)
apply(erule conjE)+
apply(erule exE)+
apply(rename_tac e c A w s y l r)(*strict*)
apply(case_tac l)
apply(rename_tac e c A w s y l r)(*strict*)
apply(clarsimp)
apply(rename_tac w y)(*strict*)
apply(simp add: F_CFG_AUGMENT_def)
apply(clarsimp)
apply(simp add: valid_cfg_def)
apply(clarsimp)
apply(erule_tac
x="\<lparr>prod_lhs = F_FRESH (cfg_nonterminals G), prod_rhs = w\<rparr>"
and P="\<lambda>x. prod_lhs x \<in> cfg_nonterminals G \<and> setA (prod_rhs x) \<subseteq> cfg_nonterminals G \<and> setB (prod_rhs x) \<subseteq> cfg_events G"
in ballE)
apply(rename_tac w y)(*strict*)
apply(clarsimp)
apply(subgoal_tac "F_FRESH (cfg_nonterminals G) \<notin> cfg_nonterminals G")
apply(rename_tac w y)(*strict*)
apply(force)
apply(rename_tac w y)(*strict*)
apply(rule F_FRESH_is_fresh)
apply(force)
apply(rename_tac w y)(*strict*)
apply(force)
apply(rename_tac e c A w s y l r a list)(*strict*)
apply(force)
done
lemma F_CFG_AUGMENT__later_at_old_grammar: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> valid_cfg G'
\<Longrightarrow> cfgRM.derivation G' d
\<Longrightarrow> d 0 = Some (pair None \<lparr>cfg_conf = [teA (cfg_initial G')]\<rparr>)
\<Longrightarrow> d (Suc n) = Some (pair e \<lparr>cfg_conf = w\<rparr>)
\<Longrightarrow> setA w \<subseteq> cfg_nonterminals G"
apply(subgoal_tac "d (Suc 0)= Some (pair (Some \<lparr>prod_lhs=cfg_initial G',prod_rhs=[teB Do,teA (cfg_initial G),teB Do]\<rparr>) \<lparr>cfg_conf=[teB Do,teA (cfg_initial G),teB Do]\<rparr>)")
prefer 2
apply(rule F_CFG_AUGMENT__FirstStep)
apply(force)
apply(force)
apply(force)
apply(force)
apply(force)
apply(rule cfgRM_derivations_are_cfg_derivations)
apply(force)
apply(force)
apply(blast)
apply(subgoal_tac "\<forall>n. (case d (Suc n) of None \<Rightarrow> True | Some (pair e c) \<Rightarrow> setA (cfg_conf c) \<subseteq> cfg_nonterminals G)")
apply(erule_tac
x="n"
in allE)
apply(clarsimp)
apply(rule allI)
apply(rename_tac na)(*strict*)
apply(rule_tac
m="Suc 0"
and n="na"
in cfgRM.property_preseved_under_steps_is_invariant2)
apply(rename_tac na)(*strict*)
apply(force)
apply(rename_tac na)(*strict*)
apply(clarsimp)
apply(simp add: valid_cfg_def)
apply(rename_tac na)(*strict*)
apply(force)
apply(rename_tac na)(*strict*)
apply(force)
apply(rename_tac na)(*strict*)
apply(rule allI)
apply(rename_tac na i)(*strict*)
apply(rule impI)
apply(erule conjE)+
apply(case_tac "d (Suc i)")
apply(rename_tac na i)(*strict*)
apply(clarsimp)
apply(rename_tac na i a)(*strict*)
apply(subgoal_tac "\<exists>e c. a = pair (Some e) c")
apply(rename_tac na i a)(*strict*)
prefer 2
apply(rule cfgRM.some_position_has_details_after_0)
apply(rename_tac na i a)(*strict*)
apply(force)
apply(rename_tac na i a)(*strict*)
apply(force)
apply(rename_tac na i a)(*strict*)
apply(erule exE)+
apply(rename_tac na i a ea c)(*strict*)
apply(subgoal_tac "setA (cfg_conf c) \<subseteq> cfg_nonterminals G")
apply(rename_tac na i a ea c)(*strict*)
apply(force)
apply(rename_tac na i a ea c)(*strict*)
apply(subgoal_tac "\<exists>e c. d i = Some (pair e c)")
apply(rename_tac na i a ea c)(*strict*)
prefer 2
apply(rule_tac
m="Suc i"
in cfgRM.pre_some_position_is_some_position)
apply(rename_tac na i a ea c)(*strict*)
apply(force)
apply(rename_tac na i a ea c)(*strict*)
apply(force)
apply(rename_tac na i a ea c)(*strict*)
apply(force)
apply(rename_tac na i a ea c)(*strict*)
apply(erule exE)+
apply(rename_tac na i a ea c eaa ca)(*strict*)
apply(subgoal_tac "cfgRM_step_relation G' ca ea c")
apply(rename_tac na i a ea c eaa ca)(*strict*)
prefer 2
apply(rule cfgRM.position_change_due_to_step_relation)
apply(rename_tac na i a ea c eaa ca)(*strict*)
apply(force)
apply(rename_tac na i a ea c eaa ca)(*strict*)
apply(force)
apply(rename_tac na i a ea c eaa ca)(*strict*)
apply(force)
apply(rename_tac na i a ea c eaa ca)(*strict*)
apply(case_tac c)
apply(rename_tac na i a ea c eaa ca cfg_confa)(*strict*)
apply(case_tac ca)
apply(rename_tac na i a ea c eaa ca cfg_confa cfg_confaa)(*strict*)
apply(case_tac ea)
apply(rename_tac na i a ea c eaa ca cfg_confa cfg_confaa prod_lhs prod_rhs)(*strict*)
apply(simp add: cfgRM_step_relation_def)
apply(rename_tac na i a ea c eaa ca cfg_conf cfg_confa prod_lhs prod_rhs)(*strict*)
apply(clarsimp)
apply(rename_tac na i ea prod_lhs prod_rhs x l r)(*strict*)
apply(simp only: setAConcat concat_asso)
apply(clarsimp)
apply(erule disjE)
apply(rename_tac na i ea prod_lhs prod_rhs x l r)(*strict*)
apply(force)
apply(rename_tac na i ea prod_lhs prod_rhs x l r)(*strict*)
apply(simp add: F_CFG_AUGMENT_def)
apply(erule disjE)
apply(rename_tac na i ea prod_lhs prod_rhs x l r)(*strict*)
apply(clarsimp)
apply(rename_tac na i ea l r)(*strict*)
apply(simp add: valid_cfg_def)
apply(rename_tac na i ea prod_lhs prod_rhs x l r)(*strict*)
apply(simp add: valid_cfg_def)
apply(rename_tac na i ea prod_lhsa prod_rhsa x l r)(*strict*)
apply(clarsimp)
apply(erule_tac
x="\<lparr>prod_lhs = prod_lhsa, prod_rhs = prod_rhsa\<rparr>"
and P="\<lambda>x. prod_lhs x \<in> cfg_nonterminals G \<and> setA (prod_rhs x) \<subseteq> cfg_nonterminals G \<and> setB (prod_rhs x) \<subseteq> cfg_events G"
in ballE)
apply(rename_tac na i ea prod_lhsa prod_rhsa x l r)(*strict*)
apply(clarsimp)
apply(rename_tac na i ea prod_lhs prod_rhsa x l r)(*strict*)
apply(force)
apply(rename_tac na i ea prod_lhs prod_rhsa x l r)(*strict*)
apply(clarsimp)
done
lemma F_CFG_AUGMENT__initial_not_in_nonterms: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> cfg_initial G' \<notin> cfg_nonterminals G"
apply(rule_tac
t="cfg_initial G'"
and s="F_FRESH (cfg_nonterminals G)"
in ssubst)
apply(simp add: F_CFG_AUGMENT_def)
apply(rule F_FRESH_is_fresh)
apply(simp add: valid_cfg_def)
done
lemma F_CFG_AUGMENT__preserves_derivation: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> cfgSTD.derivation G d
\<Longrightarrow> cfgSTD.derivation G' d"
apply(simp add: cfgSTD.derivation_def)
apply(auto)
apply(rename_tac i)(*strict*)
apply(erule_tac
x="i"
in allE)
apply(case_tac i)
apply(rename_tac i)(*strict*)
apply(auto)
apply(rename_tac nat)(*strict*)
apply(case_tac "d (Suc nat)")
apply(rename_tac nat)(*strict*)
apply(auto)
apply(rename_tac nat a)(*strict*)
apply(case_tac a)
apply(rename_tac nat a option b)(*strict*)
apply(auto)
apply(rename_tac nat option b)(*strict*)
apply(case_tac "d nat")
apply(rename_tac nat option b)(*strict*)
apply(auto)
apply(rename_tac nat option b a)(*strict*)
apply(case_tac a)
apply(rename_tac nat option b a optiona ba)(*strict*)
apply(auto)
apply(rename_tac nat option b optiona ba)(*strict*)
apply(case_tac option)
apply(rename_tac nat option b optiona ba)(*strict*)
apply(auto)
apply(rename_tac nat b optiona ba a)(*strict*)
apply(simp add: cfgSTD_step_relation_def)
apply(auto)
apply(rename_tac nat b optiona ba a l r)(*strict*)
apply(simp add: F_CFG_AUGMENT_def)
done
lemma F_CFG_AUGMENT__preserves_RMderivation: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> cfgRM.derivation G d
\<Longrightarrow> cfgRM.derivation G' d"
apply(simp add: cfgRM.derivation_def)
apply(auto)
apply(rename_tac i)(*strict*)
apply(erule_tac
x="i"
in allE)
apply(case_tac i)
apply(rename_tac i)(*strict*)
apply(auto)
apply(rename_tac nat)(*strict*)
apply(case_tac "d (Suc nat)")
apply(rename_tac nat)(*strict*)
apply(auto)
apply(rename_tac nat a)(*strict*)
apply(case_tac a)
apply(rename_tac nat a option b)(*strict*)
apply(auto)
apply(rename_tac nat option b)(*strict*)
apply(case_tac "d nat")
apply(rename_tac nat option b)(*strict*)
apply(auto)
apply(rename_tac nat option b a)(*strict*)
apply(case_tac a)
apply(rename_tac nat option b a optiona ba)(*strict*)
apply(auto)
apply(rename_tac nat option b optiona ba)(*strict*)
apply(case_tac option)
apply(rename_tac nat option b optiona ba)(*strict*)
apply(auto)
apply(rename_tac nat b optiona ba a)(*strict*)
apply(simp add: cfgRM_step_relation_def)
apply(auto)
apply(rename_tac nat b optiona ba a l r)(*strict*)
apply(simp add: F_CFG_AUGMENT_def)
done
lemma F_CFG_AUGMENT__reflects_derivation_hlp: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> d i = Some (pair e1 \<lparr>cfg_conf = w\<rparr>)
\<Longrightarrow> setA w \<subseteq> cfg_nonterminals G
\<Longrightarrow> setB w \<subseteq> cfg_events G
\<Longrightarrow> cfgSTD.derivation G' d
\<Longrightarrow> d (i + j) = Some (pair e2 \<lparr>cfg_conf = w'\<rparr>)
\<Longrightarrow> setB w' \<subseteq> cfg_events G \<and> setA w' \<subseteq> cfg_nonterminals G"
apply(subgoal_tac " \<forall>e2 w'. d (i+j)=Some (pair e2 \<lparr>cfg_conf=w'\<rparr>) \<longrightarrow> (setA w' \<subseteq> cfg_nonterminals G \<and> setB w' \<subseteq> cfg_events G) ")
apply(clarsimp)
apply(rule_tac
m="i"
and n="j"
in cfgSTD.property_preseved_under_steps_is_invariant2)
apply(blast)+
apply(clarsimp)
apply(arith)
apply(arith)
apply(rule allI)
apply(rename_tac ia)(*strict*)
apply(rule impI)
apply(erule conjE)+
apply(rule allI)+
apply(rename_tac ia e2a w'nonterminal)(*strict*)
apply(rule impI)
apply(subgoal_tac "\<exists>e. Some e=e2a")
apply(rename_tac ia e2a w'nonterminal)(*strict*)
prefer 2
apply(case_tac e2a)
apply(rename_tac ia e2a w'nonterminal)(*strict*)
apply(rule cfgSTD.derivation_Always_PreEdge_prime)
apply(rename_tac ia e2a w'nonterminal)(*strict*)
apply(blast)+
apply(rename_tac ia e2a w'nonterminal)(*strict*)
apply(erule exE)+
apply(rename_tac ia e2a w'nonterminal e)(*strict*)
apply(subgoal_tac "\<exists>e c. d ia = Some (pair e c)")
apply(rename_tac ia e2a w'nonterminal e)(*strict*)
prefer 2
apply(rule_tac
m="Suc ia"
in cfgSTD.pre_some_position_is_some_position)
apply(rename_tac ia e2a w'nonterminal e)(*strict*)
apply(blast)
apply(rename_tac ia e2a w'nonterminal e)(*strict*)
apply(blast)
apply(rename_tac ia e2a w'nonterminal e)(*strict*)
apply(force)
apply(rename_tac ia e2a w'nonterminal e)(*strict*)
apply(erule exE)+
apply(rename_tac ia e2a w'nonterminal e ea c)(*strict*)
apply(case_tac c)
apply(rename_tac ia e2a w'nonterminal e ea c cfg_conf)(*strict*)
apply(rename_tac cw)
apply(rename_tac ia e2a w'nonterminal e ea c cw)(*strict*)
apply(erule_tac
x="ea"
in allE)
apply(erule_tac
x="cw"
in allE)
apply(erule impE)
apply(rename_tac ia e2a w'nonterminal e ea c cw)(*strict*)
apply(blast)
apply(rename_tac ia e2a w'nonterminal e ea c cw)(*strict*)
apply(erule conjE)+
apply(subgoal_tac "cfgSTD_step_relation G' \<lparr>cfg_conf = cw\<rparr> e \<lparr>cfg_conf = w'nonterminal\<rparr>")
apply(rename_tac ia e2a w'nonterminal e ea c cw)(*strict*)
prefer 2
apply(rule cfgSTD.position_change_due_to_step_relation)
apply(rename_tac ia e2a w'nonterminal e ea c cw)(*strict*)
apply(blast)+
apply(rename_tac ia e2a w'nonterminal e ea c cw)(*strict*)
apply(subgoal_tac "cfgSTD_step_relation G \<lparr>cfg_conf = cw\<rparr> e \<lparr>cfg_conf = w'nonterminal\<rparr>")
apply(rename_tac ia e2a w'nonterminal e ea c cw)(*strict*)
prefer 2
apply(simp add: cfgSTD_step_relation_def)
apply(clarsimp)
apply(rename_tac ia e ea l r)(*strict*)
apply(simp add: F_CFG_AUGMENT_def)
apply(clarsimp)
apply(rename_tac ia ea l r)(*strict*)
apply(subgoal_tac "False")
apply(rename_tac ia ea l r)(*strict*)
apply(force)
apply(rename_tac ia ea l r)(*strict*)
apply(subgoal_tac "F_FRESH (cfg_nonterminals G) \<in> cfg_nonterminals G")
apply(rename_tac ia ea l r)(*strict*)
apply(subgoal_tac "F_FRESH (cfg_nonterminals G) \<notin> cfg_nonterminals G")
apply(rename_tac ia ea l r)(*strict*)
apply(force)
apply(rename_tac ia ea l r)(*strict*)
apply(rule F_FRESH_is_fresh)
apply(simp add: valid_cfg_def)
apply(rename_tac ia ea l r)(*strict*)
apply(simp only: setAConcat concat_asso)
apply(clarsimp)
apply(rename_tac ia e2a w'nonterminal e ea c cw)(*strict*)
apply(simp add: cfgSTD_step_relation_def)
apply(clarsimp)
apply(rename_tac ia e ea l r)(*strict*)
apply(simp only: setAConcat concat_asso setBConcat)
apply(simp add: valid_cfg_def)
done
lemma F_CFG_AUGMENT__reflects_derivation: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> d 0 = Some (pair None \<lparr>cfg_conf = w\<rparr>)
\<Longrightarrow> setA w \<subseteq> cfg_nonterminals G
\<Longrightarrow> setB w \<subseteq> cfg_events G
\<Longrightarrow> cfgSTD.derivation G' d
\<Longrightarrow> cfgSTD.derivation G d"
apply(subgoal_tac "\<forall>i e2 w'. d i = Some (pair e2 \<lparr>cfg_conf=w'\<rparr>) \<longrightarrow> setB w' \<subseteq> cfg_events G \<and> setA w' \<subseteq> cfg_nonterminals G")
prefer 2
apply(rule allI)+
apply(rename_tac i e2 w')(*strict*)
apply(rule impI)
apply(rule_tac
d="d"
in F_CFG_AUGMENT__reflects_derivation_hlp)
apply(rename_tac i e2 w')(*strict*)
apply(force)
apply(rename_tac i e2 w')(*strict*)
apply(force)
apply(rename_tac i e2 w')(*strict*)
apply(force)
apply(rename_tac i e2 w')(*strict*)
apply(force)
apply(rename_tac i e2 w')(*strict*)
apply(force)
apply(rename_tac i e2 w')(*strict*)
apply(force)
apply(rename_tac i e2 w')(*strict*)
apply(force)
apply(rename_tac i e2 w')(*strict*)
apply(force)
apply(rename_tac i e2 w')(*strict*)
apply(force)
apply(simp add: cfgSTD.derivation_def)
apply(auto)
apply(rename_tac i)(*strict*)
apply(erule_tac
x="i"
and P="\<lambda>i. case i of 0 \<Rightarrow> case_option False (case_derivation_configuration (\<lambda>a c. case a of None \<Rightarrow> True | Some e \<Rightarrow> False)) (d 0) | Suc i' \<Rightarrow> case_option True (case_derivation_configuration (\<lambda>i1 i2. case_option False (case_derivation_configuration (\<lambda>i'1 i'2. case i1 of None \<Rightarrow> False | Some i1v \<Rightarrow> cfgSTD_step_relation (F_CFG_AUGMENT G (F_FRESH (cfg_nonterminals G)) (F_FRESH (cfg_events G))) i'2 i1v i2)) (d i'))) (d i)"
in allE)
apply(rename_tac i)(*strict*)
apply(case_tac i)
apply(rename_tac i)(*strict*)
apply(auto)
apply(rename_tac nat)(*strict*)
apply(case_tac "d (Suc nat)")
apply(rename_tac nat)(*strict*)
apply(auto)
apply(rename_tac nat a)(*strict*)
apply(case_tac a)
apply(rename_tac nat a option b)(*strict*)
apply(auto)
apply(rename_tac nat option b)(*strict*)
apply(case_tac "d nat")
apply(rename_tac nat option b)(*strict*)
apply(auto)
apply(rename_tac nat option b a)(*strict*)
apply(case_tac a)
apply(rename_tac nat option b a optiona ba)(*strict*)
apply(auto)
apply(rename_tac nat option b optiona ba)(*strict*)
apply(case_tac option)
apply(rename_tac nat option b optiona ba)(*strict*)
apply(auto)
apply(rename_tac nat b optiona ba a)(*strict*)
apply(simp add: cfgSTD_step_relation_def)
apply(auto)
apply(rename_tac nat b optiona ba a l r)(*strict*)
apply(simp add: F_CFG_AUGMENT_def)
apply(erule disjE)
apply(rename_tac nat b optiona ba a l r)(*strict*)
prefer 2
apply(clarsimp)
apply(rename_tac nat b optiona ba a l r)(*strict*)
apply(clarsimp)
apply(rename_tac nat b optiona ba l r)(*strict*)
apply(subgoal_tac "False")
apply(rename_tac nat b optiona ba l r)(*strict*)
apply(force)
apply(rename_tac nat b optiona ba l r)(*strict*)
apply(erule_tac
x="nat"
in allE)
apply(clarsimp)
apply(case_tac ba)
apply(rename_tac nat b optiona ba l r cfg_confa)(*strict*)
apply(auto)
apply(rename_tac nat b optiona l r)(*strict*)
apply(subgoal_tac "F_FRESH (cfg_nonterminals G) \<in> cfg_nonterminals G")
apply(rename_tac nat b optiona l r)(*strict*)
apply(subgoal_tac "F_FRESH (cfg_nonterminals G) \<notin> cfg_nonterminals G")
apply(rename_tac nat b optiona l r)(*strict*)
apply(force)
apply(rename_tac nat b optiona l r)(*strict*)
apply(rule F_FRESH_is_fresh)
apply(simp add: valid_cfg_def)
apply(rename_tac nat b optiona l r)(*strict*)
apply(simp only: setAConcat concat_asso)
apply(clarsimp)
done
lemma cfgSTD_first_F_CFG_AUGMENT__no_change_on_old_input: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> valid_cfg G'
\<Longrightarrow> setA w \<subseteq> cfg_nonterminals G
\<Longrightarrow> setB w \<subseteq> cfg_events G
\<Longrightarrow> cfgSTD_first G k w = cfgSTD_first G' k w"
apply(rule_tac
t="cfgSTD_first G k w"
and s="(\<lambda>x. take k x) ` {r. \<exists>d e1 n. cfgSTD.derivation G d \<and> maximum_of_domain d n \<and> d 0 = Some (pair None \<lparr>cfg_conf=w\<rparr>) \<and> d n = Some (pair e1 \<lparr>cfg_conf=liftB r\<rparr>) }"
in ssubst)
apply(rule cfgSTD_first_sound)
apply(rule_tac
t="cfgSTD_first G' k w"
and s="(\<lambda>x. take k x) ` {r. \<exists>d e1 n. cfgSTD.derivation G' d \<and> maximum_of_domain d n \<and> d 0 = Some (pair None \<lparr>cfg_conf=w\<rparr>) \<and> d n = Some (pair e1 \<lparr>cfg_conf=liftB r\<rparr>) }"
in ssubst)
apply(rule cfgSTD_first_sound)
apply(clarsimp)
apply(rule order_antisym)
apply(clarsimp)
apply(rename_tac xa d e1 n)(*strict*)
apply(rule inMap)
apply(clarsimp)
apply(rule_tac
x="xa"
in exI)
apply(clarsimp)
apply(rule_tac
x="d"
in exI)
apply(clarsimp)
apply(rule conjI)
apply(rename_tac xa d e1 n)(*strict*)
apply(rule F_CFG_AUGMENT__preserves_derivation)
apply(rename_tac xa d e1 n)(*strict*)
apply(force)
apply(rename_tac xa d e1 n)(*strict*)
apply(force)
apply(rename_tac xa d e1 n)(*strict*)
apply(force)
apply(rename_tac xa d e1 n)(*strict*)
apply(force)
apply(rename_tac xa d e1 n)(*strict*)
apply(force)
apply(rename_tac xa d e1 n)(*strict*)
apply(rule_tac
x="e1"
in exI)
apply(rule_tac
x="n"
in exI)
apply(auto)
apply(rename_tac xa d e1 n)(*strict*)
apply(rule inMap)
apply(auto)
apply(rule_tac
x="xa"
in exI)
apply(clarsimp)
apply(rule_tac
x="d"
in exI)
apply(clarsimp)
apply(rule conjI)
apply(rename_tac xa d e1 n)(*strict*)
prefer 2
apply(rule_tac
x="e1"
in exI)
apply(rule_tac
x="n"
in exI)
apply(auto)
apply(rename_tac xa d e1 n)(*strict*)
apply(rule F_CFG_AUGMENT__reflects_derivation)
apply(rename_tac xa d e1 n)(*strict*)
apply(force)
apply(rename_tac xa d e1 n)(*strict*)
apply(force)
apply(rename_tac xa d e1 n)(*strict*)
apply(force)
apply(rename_tac xa d e1 n)(*strict*)
apply(force)
apply(rename_tac xa d e1 n)(*strict*)
apply(force)
apply(rename_tac xa d e1 n)(*strict*)
apply(force)
apply(rename_tac xa d e1 n)(*strict*)
apply(force)
apply(rename_tac xa d e1 n)(*strict*)
apply(force)
done
lemma F_CFG_AUGMENT__two_elements_construct_domain_subset: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> two_elements_construct_domain (cfg_nonterminals G) (cfg_events G) \<subseteq> two_elements_construct_domain (cfg_nonterminals G') (cfg_events G')"
apply(simp add: F_CFG_AUGMENT_def two_elements_construct_domain_def)
apply(force)
done
lemma F_CFG_AUGMENT__cfg_events: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> cfg_events G' - {Do} = cfg_events G"
apply(simp add: F_CFG_AUGMENT_def)
apply(rule order_antisym)
apply(clarsimp)
apply(clarsimp)
apply(subgoal_tac "F_FRESH (cfg_events G) \<notin> cfg_events G")
apply(force)
apply(rule F_FRESH_is_fresh)
apply(simp add: valid_cfg_def)
done
lemma F_CFG_AUGMENT__on_old_grammar_basically: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> valid_cfg G'
\<Longrightarrow> cfgSTD.derivation G' d
\<Longrightarrow> d 0 = Some (pair None \<lparr>cfg_conf = [teA (cfg_initial G')]\<rparr>)
\<Longrightarrow> d (Suc n) \<noteq> None
\<Longrightarrow> maximum_of_domain d x
\<Longrightarrow> \<exists>e w. teB Do \<notin> set w \<and> (teA S') \<notin> set w \<and> d (Suc n) = Some (pair e \<lparr>cfg_conf = teB Do # w @ [teB Do]\<rparr>)"
apply(subgoal_tac "d (Suc 0)= Some (pair (Some \<lparr>prod_lhs=cfg_initial G',prod_rhs=[teB Do,teA (cfg_initial G),teB Do]\<rparr>) \<lparr>cfg_conf=[teB Do,teA (cfg_initial G),teB Do]\<rparr>)")
prefer 2
apply(rule F_CFG_AUGMENT__FirstStep)
apply(force)+
apply(subgoal_tac "x\<ge>Suc 0")
prefer 2
apply(rule cfgSTD.allPreMaxDomSome_prime)
apply(force)
apply(force)
apply(force)
apply(subgoal_tac "x\<ge>Suc n")
prefer 2
apply(rule cfgSTD.allPreMaxDomSome_prime)
apply(force)
apply(force)
apply(force)
apply(rule_tac
x="Suc n"
and m="Suc 0"
and n="x-Suc 0"
in cfgSTD.property_preseved_under_steps_is_invariant2)
apply(force)
apply(rule_tac
x="Some \<lparr>prod_lhs = cfg_initial G', prod_rhs = [teB Do, teA (cfg_initial G), teB Do]\<rparr>"
in exI)
apply(rule_tac
x="[teA (cfg_initial G)]"
in exI)
apply(clarsimp)
apply(rename_tac y)(*strict*)
apply(subgoal_tac "cfg_initial G \<in> cfg_nonterminals G")
apply(rename_tac y)(*strict*)
apply(subgoal_tac "F_FRESH (cfg_nonterminals G) \<notin> cfg_nonterminals G")
apply(rename_tac y)(*strict*)
apply(force)
apply(rename_tac y)(*strict*)
apply(rule F_FRESH_is_fresh)
apply(simp add: valid_cfg_def)
apply(rename_tac y)(*strict*)
apply(simp add: valid_cfg_def)
apply(force)
apply(force)
apply(rule allI)
apply(rename_tac i)(*strict*)
apply(rule impI)
apply(subgoal_tac "\<exists>e c. d (Suc i) = Some (pair (Some e) c)")
apply(rename_tac i)(*strict*)
prefer 2
apply(rule cfgSTD.some_position_has_details_before_max_dom_after_0)
apply(rename_tac i)(*strict*)
apply(blast)
apply(rename_tac i)(*strict*)
apply(blast)
apply(rename_tac i)(*strict*)
apply(arith)
apply(rename_tac i)(*strict*)
apply(erule exE)+
apply(rename_tac i e c)(*strict*)
apply(erule conjE)+
apply(erule exE)+
apply(rename_tac i e c ea w)(*strict*)
apply(erule conjE)+
apply(subgoal_tac "cfgSTD_step_relation G' \<lparr>cfg_conf = teB Do # w @ [teB Do]\<rparr> e c")
apply(rename_tac i e c ea w)(*strict*)
prefer 2
apply(rule cfgSTD.position_change_due_to_step_relation)
apply(rename_tac i e c ea w)(*strict*)
apply(blast)
apply(rename_tac i e c ea w)(*strict*)
apply(blast)
apply(rename_tac i e c ea w)(*strict*)
apply(blast)
apply(rename_tac i e c ea w)(*strict*)
apply(case_tac c)
apply(rename_tac i e c ea w cfg_conf)(*strict*)
apply(simp add: cfgSTD_step_relation_def)
apply(clarsimp)
apply(rename_tac i e ea w y l r)(*strict*)
apply(case_tac l)
apply(rename_tac i e ea w y l r)(*strict*)
apply(clarsimp)
apply(rename_tac i e ea w y l r a list)(*strict*)
apply(clarsimp)
apply(rename_tac i e ea w y r list)(*strict*)
apply(case_tac r)
apply(rename_tac i e ea w y r list)(*strict*)
apply(clarsimp)
apply(rename_tac i e ea w y r list a lista)(*strict*)
apply(subgoal_tac "\<exists>w' x'. r = w' @ [x']")
apply(rename_tac i e ea w y r list a lista)(*strict*)
prefer 2
apply(rule NonEmptyListHasTailElem)
apply(force)
apply(rename_tac i e ea w y r list a lista)(*strict*)
apply(thin_tac "r=a#lista")
apply(clarsimp)
apply(rename_tac i e ea y list w')(*strict*)
apply(subgoal_tac "e \<in> cfg_productions G")
apply(rename_tac i e ea y list w')(*strict*)
prefer 2
apply(subgoal_tac "e \<noteq> \<lparr>prod_lhs=cfg_initial (F_CFG_AUGMENT G (F_FRESH (cfg_nonterminals G)) (F_FRESH (cfg_events G))),prod_rhs=[teB (F_FRESH (cfg_events G)),teA (cfg_initial G),teB (F_FRESH (cfg_events G))]\<rparr>")
apply(rename_tac i e ea y list w')(*strict*)
apply(simp add: F_CFG_AUGMENT_def)
apply(rename_tac i e ea y list w')(*strict*)
apply(clarsimp)
apply(rename_tac i ea y list w')(*strict*)
apply(simp add: F_CFG_AUGMENT_def)
apply(rename_tac i e ea y list w')(*strict*)
apply(simp add: valid_cfg_def)
apply(clarsimp)
apply(erule_tac
x="e"
and P="\<lambda>e. prod_lhs e \<in> cfg_nonterminals G \<and> setA (prod_rhs e) \<subseteq> cfg_nonterminals G \<and> setB (prod_rhs e) \<subseteq> cfg_events G"
in ballE)
apply(rename_tac i e ea y list w')(*strict*)
prefer 2
apply(force)
apply(rename_tac i e ea y list w')(*strict*)
apply(clarsimp)
apply(rule conjI)
apply(rename_tac i e ea y list w')(*strict*)
apply(rule setB_set_not)
apply(rule_tac
B="cfg_events G"
in nset_mp)
apply(rename_tac i e ea y list w')(*strict*)
apply(force)
apply(rename_tac i e ea y list w')(*strict*)
apply(rule F_FRESH_is_fresh)
apply(force)
apply(rename_tac i e ea y list w')(*strict*)
apply(rule setA_set_not)
apply(rule_tac
B="cfg_nonterminals G"
in nset_mp)
apply(rename_tac i e ea y list w')(*strict*)
apply(force)
apply(rename_tac i e ea y list w')(*strict*)
apply(rule F_FRESH_is_fresh)
apply(force)
done
lemma F_CFG_AUGMENT__cfg_nonterminals: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> A \<subseteq> cfg_nonterminals G
\<Longrightarrow> A \<subseteq> cfg_nonterminals G'"
apply(simp add: F_CFG_AUGMENT_def)
apply(force)
done
lemma F_CFG_AUGMENT__cfg_events2: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> A \<subseteq> cfg_events G
\<Longrightarrow> A \<subseteq> cfg_events G'"
apply(simp add: F_CFG_AUGMENT_def)
apply(force)
done
lemma F_CFG_AUGMENT__preserves_belongs: "
F_CFG_AUGMENT__input G Do S' G'
\<Longrightarrow> valid_cfg G'
\<Longrightarrow> cfgSTD.derivation G d
\<Longrightarrow> cfgSTD.belongs G d
\<Longrightarrow> cfgSTD.belongs G' d"
apply(subgoal_tac "\<exists>c. d 0 = Some (pair None c)")
prefer 2
apply(rule cfgSTD.some_position_has_details_at_0)
apply(force)
apply(clarsimp)
apply(rename_tac c)(*strict*)
apply(rule cfgSTD.derivation_belongs)
apply(rename_tac c)(*strict*)
apply(force)
apply(rename_tac c)(*strict*)
apply(force)
apply(rename_tac c)(*strict*)
prefer 2
apply(rule_tac
G="G"
in F_CFG_AUGMENT__preserves_derivation)
apply(rename_tac c)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac c)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac c)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac c)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac c)(*strict*)
apply(force)
apply(rename_tac c)(*strict*)
apply(subgoal_tac "c \<in> cfg_configurations G")
apply(rename_tac c)(*strict*)
prefer 2
apply(rule cfgSTD.belongs_configurations)
apply(rename_tac c)(*strict*)
apply(force)
apply(rename_tac c)(*strict*)
apply(force)
apply(rename_tac c)(*strict*)
apply(simp add: cfg_configurations_def)
apply(clarsimp)
apply(rename_tac ca)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def F_CFG_AUGMENT_def)
apply(clarsimp)
apply(force)
done
lemma F_CFG_AUGMENT__preserves_belongsRM: "
F_CFG_AUGMENT__input G Do S' G'
\<Longrightarrow> valid_cfg G'
\<Longrightarrow> cfgRM.derivation G d
\<Longrightarrow> cfgRM.belongs G d
\<Longrightarrow> cfgRM.belongs G' d"
apply(subgoal_tac "\<exists>c. d 0 = Some (pair None c)")
prefer 2
apply(rule cfgRM.some_position_has_details_at_0)
apply(force)
apply(clarsimp)
apply(rename_tac c)(*strict*)
apply(rule cfgRM.derivation_belongs)
apply(rename_tac c)(*strict*)
apply(force)
apply(rename_tac c)(*strict*)
apply(force)
apply(rename_tac c)(*strict*)
prefer 2
apply(rule_tac
G="G"
in F_CFG_AUGMENT__preserves_RMderivation)
apply(rename_tac c)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac c)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac c)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac c)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac c)(*strict*)
apply(force)
apply(rename_tac c)(*strict*)
apply(subgoal_tac "c \<in> cfg_configurations G")
apply(rename_tac c)(*strict*)
prefer 2
apply(rule cfgSTD.belongs_configurations)
apply(rename_tac c)(*strict*)
apply(force)
apply(rename_tac c)(*strict*)
apply(force)
apply(rename_tac c)(*strict*)
apply(simp add: cfg_configurations_def)
apply(clarsimp)
apply(rename_tac ca)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def F_CFG_AUGMENT_def)
apply(clarsimp)
apply(force)
done
lemma F_CFG_AUGMENT__derivation_of_input_from_effect_prime: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> cfgRM.derivation G' d
\<Longrightarrow> cfgRM.belongs G d
\<Longrightarrow> cfgRM.derivation G d"
apply(simp (no_asm) add: cfgRM.derivation_def)
apply(clarsimp)
apply(rename_tac i)(*strict*)
apply(induct_tac i rule: nat_induct)
apply(rename_tac i)(*strict*)
apply(clarsimp)
apply(simp add: cfgRM.derivation_def)
apply(erule_tac
x="0"
in allE)
apply(clarsimp)
apply(rename_tac i n)(*strict*)
apply(clarsimp)
apply(rename_tac n)(*strict*)
apply(case_tac "d(Suc n)")
apply(rename_tac n)(*strict*)
apply(clarsimp)
apply(rename_tac n a)(*strict*)
apply(subgoal_tac "\<exists>e1 e2 c1 c2. d n = Some (pair e1 c1) \<and> d (Suc n) = Some (pair (Some e2) c2) \<and> cfgRM_step_relation (F_CFG_AUGMENT G (F_FRESH (cfg_nonterminals G)) (F_FRESH (cfg_events G))) c1 e2 c2")
apply(rename_tac n a)(*strict*)
prefer 2
apply(rule_tac
m="Suc n"
in cfgRM.step_detail_before_some_position)
apply(rename_tac n a)(*strict*)
apply(force)
apply(rename_tac n a)(*strict*)
apply(force)
apply(rename_tac n a)(*strict*)
apply(force)
apply(rename_tac n a)(*strict*)
apply(clarsimp)
apply(rename_tac n e1 e2 c1 c2)(*strict*)
apply(simp add: cfgRM_step_relation_def)
apply(clarsimp)
apply(rename_tac n e1 e2 c1 c2 l r)(*strict*)
apply(simp add: cfgRM.belongs_def)
apply(erule_tac
x="Suc n"
in allE)
apply(clarsimp)
apply(simp add: cfg_step_labels_def)
done
lemma F_CFG_AUGMENT__reflects_derivationRM_hlp: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> d i = Some (pair e1 \<lparr>cfg_conf = w\<rparr>)
\<Longrightarrow> setA w \<subseteq> cfg_nonterminals G
\<Longrightarrow> setB w \<subseteq> cfg_events G
\<Longrightarrow> cfgRM.derivation G' d
\<Longrightarrow> d (i + j) = Some (pair e2 \<lparr>cfg_conf = w'\<rparr>)
\<Longrightarrow> setB w' \<subseteq> cfg_events G \<and> setA w' \<subseteq> cfg_nonterminals G"
apply(subgoal_tac " \<forall>e2 w'. d (i+j)=Some (pair e2 \<lparr>cfg_conf=w'\<rparr>) \<longrightarrow> (setA w' \<subseteq> cfg_nonterminals G \<and> setB w' \<subseteq> cfg_events G) ")
apply(clarsimp)
apply(rule_tac
m="i"
and n="j"
in cfgRM.property_preseved_under_steps_is_invariant2)
apply(blast)+
apply(clarsimp)
apply(arith)
apply(arith)
apply(rule allI)
apply(rename_tac ia)(*strict*)
apply(rule impI)
apply(erule conjE)+
apply(rule allI)+
apply(rename_tac ia e2a w'nonterminal)(*strict*)
apply(rule impI)
apply(subgoal_tac "\<exists>e. Some e=e2a")
apply(rename_tac ia e2a w'nonterminal)(*strict*)
prefer 2
apply(case_tac e2a)
apply(rename_tac ia e2a w'nonterminal)(*strict*)
apply(rule cfgRM.derivation_Always_PreEdge_prime)
apply(rename_tac ia e2a w'nonterminal)(*strict*)
apply(blast)+
apply(rename_tac ia e2a w'nonterminal)(*strict*)
apply(erule exE)+
apply(rename_tac ia e2a w'nonterminal e)(*strict*)
apply(subgoal_tac "\<exists>e c. d ia = Some (pair e c)")
apply(rename_tac ia e2a w'nonterminal e)(*strict*)
prefer 2
apply(rule_tac
m="Suc ia"
in cfgRM.pre_some_position_is_some_position)
apply(rename_tac ia e2a w'nonterminal e)(*strict*)
apply(blast)
apply(rename_tac ia e2a w'nonterminal e)(*strict*)
apply(blast)
apply(rename_tac ia e2a w'nonterminal e)(*strict*)
apply(force)
apply(rename_tac ia e2a w'nonterminal e)(*strict*)
apply(erule exE)+
apply(rename_tac ia e2a w'nonterminal e ea c)(*strict*)
apply(case_tac c)
apply(rename_tac ia e2a w'nonterminal e ea c cfg_conf)(*strict*)
apply(rename_tac cw)
apply(rename_tac ia e2a w'nonterminal e ea c cw)(*strict*)
apply(erule_tac
x="ea"
in allE)
apply(erule_tac
x="cw"
in allE)
apply(erule impE)
apply(rename_tac ia e2a w'nonterminal e ea c cw)(*strict*)
apply(blast)
apply(rename_tac ia e2a w'nonterminal e ea c cw)(*strict*)
apply(erule conjE)+
apply(subgoal_tac "cfgRM_step_relation G' \<lparr>cfg_conf = cw\<rparr> e \<lparr>cfg_conf = w'nonterminal\<rparr>")
apply(rename_tac ia e2a w'nonterminal e ea c cw)(*strict*)
prefer 2
apply(rule cfgRM.position_change_due_to_step_relation)
apply(rename_tac ia e2a w'nonterminal e ea c cw)(*strict*)
apply(blast)+
apply(rename_tac ia e2a w'nonterminal e ea c cw)(*strict*)
apply(subgoal_tac "cfgRM_step_relation G \<lparr>cfg_conf = cw\<rparr> e \<lparr>cfg_conf = w'nonterminal\<rparr>")
apply(rename_tac ia e2a w'nonterminal e ea c cw)(*strict*)
prefer 2
apply(simp add: cfgRM_step_relation_def)
apply(clarsimp)
apply(rename_tac ia e ea l r)(*strict*)
apply(simp add: F_CFG_AUGMENT_def)
apply(clarsimp)
apply(rename_tac ia ea l r)(*strict*)
apply(subgoal_tac "False")
apply(rename_tac ia ea l r)(*strict*)
apply(force)
apply(rename_tac ia ea l r)(*strict*)
apply(subgoal_tac "F_FRESH (cfg_nonterminals G) \<in> cfg_nonterminals G")
apply(rename_tac ia ea l r)(*strict*)
apply(subgoal_tac "F_FRESH (cfg_nonterminals G) \<notin> cfg_nonterminals G")
apply(rename_tac ia ea l r)(*strict*)
apply(force)
apply(rename_tac ia ea l r)(*strict*)
apply(rule F_FRESH_is_fresh)
apply(simp add: valid_cfg_def)
apply(rename_tac ia ea l r)(*strict*)
apply(simp only: setAConcat concat_asso)
apply(clarsimp)
apply(rename_tac ia e2a w'nonterminal e ea c cw)(*strict*)
apply(simp add: cfgRM_step_relation_def)
apply(clarsimp)
apply(rename_tac ia e ea l r)(*strict*)
apply(simp only: setAConcat concat_asso setBConcat)
apply(simp add: valid_cfg_def)
done
lemma F_CFG_AUGMENT__reflects_derivationRM: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> d 0 = Some (pair None \<lparr>cfg_conf = w\<rparr>)
\<Longrightarrow> setA w \<subseteq> cfg_nonterminals G
\<Longrightarrow> setB w \<subseteq> cfg_events G
\<Longrightarrow> cfgRM.derivation G' d
\<Longrightarrow> cfgRM.derivation G d"
apply(subgoal_tac "\<forall>i e2 w'. d i = Some (pair e2 \<lparr>cfg_conf=w'\<rparr>) \<longrightarrow> setB w' \<subseteq> cfg_events G \<and> setA w' \<subseteq> cfg_nonterminals G")
prefer 2
apply(rule allI)+
apply(rename_tac i e2 w')(*strict*)
apply(rule impI)
apply(rule_tac
d="d"
in F_CFG_AUGMENT__reflects_derivationRM_hlp)
apply(rename_tac i e2 w')(*strict*)
apply(force)
apply(rename_tac i e2 w')(*strict*)
apply(force)
apply(rename_tac i e2 w')(*strict*)
apply(force)
apply(rename_tac i e2 w')(*strict*)
apply(force)
apply(rename_tac i e2 w')(*strict*)
apply(force)
apply(rename_tac i e2 w')(*strict*)
apply(force)
apply(rename_tac i e2 w')(*strict*)
apply(force)
apply(rename_tac i e2 w')(*strict*)
apply(force)
apply(rename_tac i e2 w')(*strict*)
apply(force)
apply(simp add: cfgRM.derivation_def)
apply(auto)
apply(rename_tac i)(*strict*)
apply(erule_tac
x="i"
and P="\<lambda>i. case i of 0 \<Rightarrow> case_option False (case_derivation_configuration (\<lambda>a c. case a of None \<Rightarrow> True | Some e \<Rightarrow> False)) (d 0) | Suc i' \<Rightarrow> case_option True (case_derivation_configuration (\<lambda>i1 i2. case_option False (case_derivation_configuration (\<lambda>i'1 i'2. case i1 of None \<Rightarrow> False | Some i1v \<Rightarrow> cfgRM_step_relation (F_CFG_AUGMENT G (F_FRESH (cfg_nonterminals G)) (F_FRESH (cfg_events G))) i'2 i1v i2)) (d i'))) (d i)"
in allE)
apply(rename_tac i)(*strict*)
apply(case_tac i)
apply(rename_tac i)(*strict*)
apply(auto)
apply(rename_tac nat)(*strict*)
apply(case_tac "d (Suc nat)")
apply(rename_tac nat)(*strict*)
apply(auto)
apply(rename_tac nat a)(*strict*)
apply(case_tac a)
apply(rename_tac nat a option b)(*strict*)
apply(auto)
apply(rename_tac nat option b)(*strict*)
apply(case_tac "d nat")
apply(rename_tac nat option b)(*strict*)
apply(auto)
apply(rename_tac nat option b a)(*strict*)
apply(case_tac a)
apply(rename_tac nat option b a optiona ba)(*strict*)
apply(auto)
apply(rename_tac nat option b optiona ba)(*strict*)
apply(case_tac option)
apply(rename_tac nat option b optiona ba)(*strict*)
apply(auto)
apply(rename_tac nat b optiona ba a)(*strict*)
apply(simp add: cfgRM_step_relation_def)
apply(auto)
apply(rename_tac nat b optiona ba a l r)(*strict*)
apply(simp add: F_CFG_AUGMENT_def)
apply(erule disjE)
apply(rename_tac nat b optiona ba a l r)(*strict*)
prefer 2
apply(clarsimp)
apply(rename_tac nat b optiona ba a l r)(*strict*)
apply(clarsimp)
apply(rename_tac nat b optiona ba l r)(*strict*)
apply(subgoal_tac "False")
apply(rename_tac nat b optiona ba l r)(*strict*)
apply(force)
apply(rename_tac nat b optiona ba l r)(*strict*)
apply(erule_tac
x="nat"
in allE)
apply(clarsimp)
apply(case_tac ba)
apply(rename_tac nat b optiona ba l r cfg_confa)(*strict*)
apply(auto)
apply(rename_tac nat b optiona l r)(*strict*)
apply(subgoal_tac "F_FRESH (cfg_nonterminals G) \<in> cfg_nonterminals G")
apply(rename_tac nat b optiona l r)(*strict*)
apply(subgoal_tac "F_FRESH (cfg_nonterminals G) \<notin> cfg_nonterminals G")
apply(rename_tac nat b optiona l r)(*strict*)
apply(force)
apply(rename_tac nat b optiona l r)(*strict*)
apply(rule F_FRESH_is_fresh)
apply(simp add: valid_cfg_def)
apply(rename_tac nat b optiona l r)(*strict*)
apply(simp only: setAConcat concat_asso)
apply(clarsimp)
done
lemma F_CFG_AUGMENT__in_nonterms_of_G: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> setA w \<subseteq> cfg_nonterminals G'
\<Longrightarrow> teA S' \<notin> set w
\<Longrightarrow> setA w \<subseteq> cfg_nonterminals G"
apply(simp add: F_CFG_AUGMENT_def)
apply(clarsimp)
apply(rename_tac x)(*strict*)
apply(subgoal_tac "x \<in> insert (F_FRESH (cfg_nonterminals G)) (cfg_nonterminals G)")
apply(rename_tac x)(*strict*)
prefer 2
apply(force)
apply(rename_tac x)(*strict*)
apply(thin_tac "setA w \<subseteq> insert (F_FRESH (cfg_nonterminals G)) (cfg_nonterminals G)")
apply(rename_tac x)(*strict*)
apply(clarsimp)
apply(subgoal_tac "False")
apply(force)
apply(induct w)
apply(force)
apply(rename_tac a w)(*strict*)
apply(clarsimp)
apply(erule disjE)
apply(rename_tac a w)(*strict*)
apply(force)
apply(rename_tac a w)(*strict*)
apply(case_tac a)
apply(rename_tac a w aa)(*strict*)
apply(clarsimp)
apply(rename_tac a w b)(*strict*)
apply(clarsimp)
done
lemma F_CFG_AUGMENT__in_cfg_events_of_G: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> setB w \<subseteq> cfg_events G'
\<Longrightarrow> teB Do \<notin> set w
\<Longrightarrow> setB w \<subseteq> cfg_events G"
apply(simp add: F_CFG_AUGMENT_def)
apply(clarsimp)
apply(rename_tac x)(*strict*)
apply(subgoal_tac "x \<in> insert (F_FRESH (cfg_events G)) (cfg_events G)")
apply(rename_tac x)(*strict*)
prefer 2
apply(force)
apply(rename_tac x)(*strict*)
apply(thin_tac "setB w \<subseteq> insert (F_FRESH (cfg_events G)) (cfg_events G)")
apply(rename_tac x)(*strict*)
apply(clarsimp)
apply(subgoal_tac "False")
apply(force)
apply(induct w)
apply(force)
apply(rename_tac a w)(*strict*)
apply(clarsimp)
apply(erule disjE)
apply(rename_tac a w)(*strict*)
apply(force)
apply(rename_tac a w)(*strict*)
apply(case_tac a)
apply(rename_tac a w aa)(*strict*)
apply(clarsimp)
apply(rename_tac a w b)(*strict*)
apply(clarsimp)
done
lemma F_CFG_AUGMENT__lang_incl1: "
F_CFG_AUGMENT__input G Do S' G'
\<Longrightarrow> (\<lambda>w. Do # w @ [Do]) ` cfgSTD.marked_language G \<subseteq> cfgSTD.marked_language G'"
apply(subgoal_tac "valid_cfg G'")
prefer 2
apply(rule_tac
G="G"
in F_CFG_AUGMENT__makes_CFG)
apply(force)
apply(simp add: cfgSTD.marked_language_def)
apply(clarsimp)
apply(rename_tac w d)(*strict*)
apply(rule_tac
x = "derivation_append (der2 \<lparr>cfg_conf = [teA (cfg_initial G')]\<rparr> \<lparr>prod_lhs=cfg_initial G',prod_rhs=[teB Do,teA (cfg_initial G),teB Do]\<rparr> \<lparr>cfg_conf=[teB Do,teA (cfg_initial G),teB Do]\<rparr>) (derivation_map d (\<lambda>v. \<lparr>cfg_conf = teB Do#(cfg_conf v)@[teB Do]\<rparr>)) (Suc 0)"
in exI)
apply(rule context_conjI)
apply(rename_tac w d)(*strict*)
apply(simp add: cfgSTD.derivation_initial_def)
apply(rule conjI)
apply(rename_tac w d)(*strict*)
apply(rule cfgSTD.derivation_concat2)
apply(rename_tac w d)(*strict*)
apply(rule cfgSTD.der2_is_derivation)
apply(simp add: cfgSTD_step_relation_def)
apply(rule conjI)
apply(rename_tac w d)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def F_CFG_AUGMENT_def)
apply(rename_tac w d)(*strict*)
apply(rule_tac
x="[]"
in exI)
apply(rule_tac
x="[]"
in exI)
apply(clarsimp)
apply(rename_tac w d)(*strict*)
apply(rule der2_maximum_of_domain)
apply(rename_tac w d)(*strict*)
apply(rule cfgSTD.derivation_map_preserves_derivation2)
apply(rename_tac w d)(*strict*)
apply(rule_tac
G="G"
in F_CFG_AUGMENT__preserves_derivation)
apply(rename_tac w d)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac w d)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac w d)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac w d)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac w d)(*strict*)
apply(force)
apply(rename_tac w d)(*strict*)
apply(clarsimp)
apply(rename_tac w d a e b)(*strict*)
apply(simp add: cfgSTD_step_relation_def)
apply(clarsimp)
apply(rename_tac w d a e b l r)(*strict*)
apply(rule_tac
x="teB Do#l"
in exI)
apply(rule_tac
x="r@[teB Do]"
in exI)
apply(clarsimp)
apply(rename_tac w d)(*strict*)
apply(simp add: der2_def)
apply(simp add: derivation_map_def)
apply(case_tac "d 0")
apply(rename_tac w d)(*strict*)
apply(clarsimp)
apply(rename_tac w d a)(*strict*)
apply(clarsimp)
apply(case_tac a)
apply(rename_tac w d a option b)(*strict*)
apply(clarsimp)
apply(rename_tac w d b)(*strict*)
apply(simp add: cfg_initial_configurations_def)
apply(rename_tac w d)(*strict*)
apply(simp add: derivation_append_def der2_def)
apply(simp add: cfg_initial_configurations_def)
apply(case_tac "d 0")
apply(rename_tac w d)(*strict*)
apply(clarsimp)
apply(rename_tac w d a)(*strict*)
apply(clarsimp)
apply(case_tac a)
apply(rename_tac w d a option b)(*strict*)
apply(clarsimp)
apply(rename_tac w d b)(*strict*)
apply(simp add: cfg_configurations_def)
apply(rule cfg_initial_in_nonterms)
apply(force)
apply(rename_tac w d)(*strict*)
apply(rule conjI)
apply(rename_tac w d)(*strict*)
apply(simp add: cfg_marked_effect_def)
apply(clarsimp)
apply(rename_tac w d e c i)(*strict*)
apply(case_tac i)
apply(rename_tac w d e c i)(*strict*)
apply(clarsimp)
apply(rename_tac w d e c)(*strict*)
apply(simp add: cfgSTD.derivation_initial_def)
apply(clarsimp)
apply(rename_tac w d c)(*strict*)
apply(simp add: cfg_initial_configurations_def)
apply(rename_tac w d e c i nat)(*strict*)
apply(simp add: cfg_initial_configurations_def)
apply(clarsimp)
apply(rename_tac w d e c nat)(*strict*)
apply(rule_tac
x="e"
in exI)
apply(simp add: cfgSTD.derivation_initial_def)
apply(case_tac "d 0")
apply(rename_tac w d e c nat)(*strict*)
apply(clarsimp)
apply(rename_tac w d e c nat a)(*strict*)
apply(clarsimp)
apply(case_tac a)
apply(rename_tac w d e c nat a option b)(*strict*)
apply(clarsimp)
apply(rename_tac w d e c nat b)(*strict*)
apply(simp add: cfg_initial_configurations_def)
apply(clarsimp)
apply(rename_tac w d e c nat)(*strict*)
apply(rule_tac
x="\<lparr>cfg_conf=teB Do # cfg_conf c @ [teB Do]\<rparr>"
in exI)
apply(clarsimp)
apply(rule conjI)
apply(rename_tac w d e c nat)(*strict*)
apply(rule_tac
x="Suc (Suc nat)"
in exI)
apply(simp add: derivation_append_def)
apply(simp add: derivation_map_def)
apply(rename_tac w d e c nat)(*strict*)
apply(simp (no_asm) only: setAConcat concat_asso)
apply(rule conjI)
apply(rename_tac w d e c nat)(*strict*)
apply(force)
apply(rename_tac w d e c nat)(*strict*)
apply(rule_tac
t="cfg_conf c"
and s="liftB w"
in ssubst)
apply(rename_tac w d e c nat)(*strict*)
apply(force)
apply(rename_tac w d e c nat)(*strict*)
apply(rule liftB_commute_one_elem_app)
apply(rename_tac w d)(*strict*)
apply(rule conjI)
apply(rename_tac w d)(*strict*)
apply(simp add: cfgSTD.derivation_initial_def)
apply(rename_tac w d)(*strict*)
apply(simp add: cfg_marked_effect_def)
apply(clarsimp)
apply(rename_tac w d e c i)(*strict*)
apply(simp add: cfg_marking_condition_def)
apply(clarsimp)
apply(rename_tac w d e c i ia ea ca)(*strict*)
apply(rule_tac
x="Suc ia"
in exI)
apply(rule_tac
x="ea"
in exI)
apply(rule_tac
x="\<lparr>cfg_conf=teB Do # cfg_conf ca @ [teB Do]\<rparr>"
in exI)
apply(simp add: derivation_append_def)
apply(simp add: derivation_map_def)
apply(case_tac ia)
apply(rename_tac w d e c i ia ea ca)(*strict*)
apply(clarsimp)
apply(rename_tac w d e c i ea ca)(*strict*)
apply(simp add: cfgSTD.derivation_initial_def)
apply(clarsimp)
apply(rename_tac w d e c i ca)(*strict*)
apply(simp add: cfg_initial_configurations_def)
apply(clarsimp)
apply(rename_tac w d e c i)(*strict*)
apply(simp add: cfg_marking_configuration_def)
apply(rename_tac w d e c i ia ea ca nat)(*strict*)
apply(clarsimp)
apply(rename_tac w d e c i ea ca nat)(*strict*)
apply(simp add: cfg_marking_configuration_def)
apply(clarsimp)
apply(simp add: cfg_configurations_def)
apply(simp (no_asm) only: setAConcat concat_asso)
apply(clarsimp)
apply(rename_tac w d e c i ea nat cb)(*strict*)
apply(simp (no_asm) only: setBConcat concat_asso)
apply(clarsimp)
apply(simp add: F_CFG_AUGMENT__input_def F_CFG_AUGMENT_def)
apply(clarsimp)
apply(rename_tac w d e c i ea nat cb x)(*strict*)
apply(subgoal_tac "x \<in> cfg_events G")
apply(rename_tac w d e c i ea nat cb x)(*strict*)
apply(force)
apply(rename_tac w d e c i ea nat cb x)(*strict*)
apply(force)
done
lemma F_CFG_AUGMENT__lang_incl2: "
F_CFG_AUGMENT__input G Do S' G'
\<Longrightarrow> (\<lambda>w. Do # w @ [Do]) ` cfgSTD.marked_language G \<supseteq> cfgSTD.marked_language G'"
apply(subgoal_tac "valid_cfg G'")
prefer 2
apply(rule_tac
G="G"
in F_CFG_AUGMENT__makes_CFG)
apply(force)
apply(simp add: cfgSTD.marked_language_def)
apply(clarsimp)
apply(rename_tac x d)(*strict*)
apply(rule inMap)
apply(simp add: cfg_marking_condition_def)
apply(clarsimp)
apply(rename_tac x d i e c)(*strict*)
apply(simp add: cfgSTD.derivation_initial_def)
apply(case_tac "d 0")
apply(rename_tac x d i e c)(*strict*)
apply(clarsimp)
apply(rename_tac x d i e c a)(*strict*)
apply(clarsimp)
apply(case_tac a)
apply(rename_tac x d i e c a option b)(*strict*)
apply(clarsimp)
apply(rename_tac x d i e c b)(*strict*)
apply(case_tac i)
apply(rename_tac x d i e c b)(*strict*)
apply(clarsimp)
apply(rename_tac x d c)(*strict*)
apply(simp add: cfg_marking_configuration_def)
apply(simp add: cfg_configurations_def)
apply(simp add: cfg_initial_configurations_def)
apply(rename_tac x d i e c b nat)(*strict*)
apply(clarsimp)
apply(rename_tac x d e c b nat)(*strict*)
apply(subgoal_tac "\<exists>d. d 0 = Some (pair None b) \<and> x \<in> cfg_marked_effect G' d \<and> d (Suc nat) = Some (pair e c) \<and> cfgSTD.derivation G' d \<and> maximum_of_domain d (Suc nat) ")
apply(rename_tac x d e c b nat)(*strict*)
prefer 2
apply(rule_tac
x="derivation_take d (Suc nat)"
in exI)
apply(rule conjI)
apply(rename_tac x d e c b nat)(*strict*)
apply(simp add: derivation_take_def)
apply(rename_tac x d e c b nat)(*strict*)
apply(rule conjI)
apply(rename_tac x d e c b nat)(*strict*)
apply(simp add: cfg_marked_effect_def derivation_take_def)
apply(clarsimp)
apply(rename_tac x d e c b nat ea ca i)(*strict*)
apply(rule_tac
x="ea"
in exI)
apply(rule_tac
x="ca"
in exI)
apply(clarsimp)
apply(rule_tac
x="i"
in exI)
apply(clarsimp)
apply(simp add: cfg_marking_configuration_def)
apply(clarsimp)
apply(rule cfgSTD.dead_end_at_some_is_max_dom_prime)
apply(rename_tac x d e c b nat ea ca i)(*strict*)
apply(force)
apply(rename_tac x d e c b nat ea ca i)(*strict*)
apply(force)
apply(rename_tac x d e c b nat ea ca i)(*strict*)
apply(force)
apply(rename_tac x d e c b nat ea ca i)(*strict*)
apply(rule cfgSTD_no_step_without_nonterms)
apply(force)
apply(rename_tac x d e c b nat ea ca i)(*strict*)
apply(rule cfgSTD_no_step_without_nonterms)
apply(force)
apply(rename_tac x d e c b nat)(*strict*)
apply(rule conjI)
apply(rename_tac x d e c b nat)(*strict*)
apply(simp add: derivation_take_def)
apply(rename_tac x d e c b nat)(*strict*)
apply(rule conjI)
apply(rename_tac x d e c b nat)(*strict*)
apply(rule cfgSTD.derivation_take_preserves_derivation)
apply(force)
apply(rename_tac x d e c b nat)(*strict*)
apply(rule maximum_of_domain_derivation_take)
apply(force)
apply(rename_tac x d e c b nat)(*strict*)
apply(thin_tac "x \<in> cfg_marked_effect G' d")
apply(thin_tac "cfgSTD.derivation G' d")
apply(thin_tac "d (Suc nat) = Some (pair e c)")
apply(thin_tac "d 0 = Some (pair None b)")
apply(clarsimp)
apply(rename_tac x e c b nat d)(*strict*)
apply(subgoal_tac "\<exists>e w. teB Do \<notin> set w \<and> (teA S') \<notin> set w \<and> d (Suc nat) = Some (pair e \<lparr>cfg_conf=teB Do#w@[teB Do]\<rparr>)")
apply(rename_tac x e c b nat d)(*strict*)
prefer 2
apply(rule_tac
G="G"
in F_CFG_AUGMENT__on_old_grammar_basically)
apply(rename_tac x e c b nat d)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x e c b nat d)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x e c b nat d)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x e c b nat d)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x e c b nat d)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x e c b nat d)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x e c b nat d)(*strict*)
apply(simp add: cfg_initial_configurations_def)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x e c b nat d)(*strict*)
apply(force)
apply(rename_tac x e c b nat d)(*strict*)
apply(force)
apply(rename_tac x e c b nat d)(*strict*)
apply(clarsimp)
apply(rename_tac x e b nat d w)(*strict*)
apply(simp add: cfg_marked_effect_def)
apply(clarsimp)
apply(rename_tac x e b nat d w ea c i)(*strict*)
apply(subgoal_tac "i=Suc nat")
apply(rename_tac x e b nat d w ea c i)(*strict*)
prefer 2
apply(rule cfgSTD.dead_end_at_some_is_max_dom)
apply(rename_tac x e b nat d w ea c i)(*strict*)
apply(force)
apply(rename_tac x e b nat d w ea c i)(*strict*)
apply(force)
apply(rename_tac x e b nat d w ea c i)(*strict*)
apply(force)
apply(rename_tac x e b nat d w ea c i)(*strict*)
apply(rule cfgSTD_no_step_without_nonterms)
apply(force)
apply(rename_tac x e b nat d w ea c i)(*strict*)
apply(clarsimp)
apply(rename_tac x b nat d w ea)(*strict*)
apply(subgoal_tac "d (Suc 0)= Some (pair (Some \<lparr>prod_lhs=cfg_initial G',prod_rhs=[teB Do,teA (cfg_initial G),teB Do]\<rparr>) \<lparr>cfg_conf=[teB Do,teA (cfg_initial G),teB Do]\<rparr>)")
apply(rename_tac x b nat d w ea)(*strict*)
prefer 2
apply(rule F_CFG_AUGMENT__FirstStep)
apply(rename_tac x b nat d w ea)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x b nat d w ea)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x b nat d w ea)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x b nat d w ea)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x b nat d w ea)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x b nat d w ea)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x b nat d w ea)(*strict*)
apply(simp add: cfg_initial_configurations_def)
apply(rename_tac x b nat d w ea)(*strict*)
apply(force)
apply(rename_tac x b nat d w ea)(*strict*)
apply(rule_tac
x="filterB w"
in exI)
apply(rule conjI)
apply(rename_tac x b nat d w ea)(*strict*)
prefer 2
apply(rule liftB_inj)
apply(rule_tac
t="liftB x"
and s="teB Do # w @ [teB Do]"
in ssubst)
apply(rename_tac x b nat d w ea)(*strict*)
apply(force)
apply(rename_tac x b nat d w ea)(*strict*)
apply(clarsimp)
apply(rule_tac
t="w@[teB Do]"
and s="(liftB (filterB w)) @ [teB Do]"
in ssubst)
apply(rename_tac x b nat d w ea)(*strict*)
apply(clarsimp)
apply(rule sym)
apply(rule liftBDeConv2)
apply(simp only: setAConcat concat_asso)
apply(force)
apply(rename_tac x b nat d w ea)(*strict*)
apply(rule liftB_commute_one_elem_app)
apply(rename_tac x b nat d w ea)(*strict*)
apply(rule_tac
x="derivation_drop (derivation_map d (\<lambda>c. c\<lparr>cfg_conf:=drop(Suc 0)(butlast(cfg_conf c))\<rparr>)) (Suc 0)"
in exI)
apply(rule context_conjI)
apply(rename_tac x b nat d w ea)(*strict*)
apply(simp (no_asm_simp) add: cfgSTD.derivation_def)
apply(clarsimp)
apply(rename_tac x b nat d w ea i)(*strict*)
apply(case_tac i)
apply(rename_tac x b nat d w ea i)(*strict*)
apply(clarsimp)
apply(rename_tac x b nat d w ea)(*strict*)
apply(simp add: derivation_drop_def derivation_map_def)
apply(rename_tac x b nat d w ea i nata)(*strict*)
apply(clarsimp)
apply(rename_tac x b nat d w ea nata)(*strict*)
apply(simp add: derivation_drop_def derivation_map_def)
apply(case_tac "d (Suc (Suc nata))")
apply(rename_tac x b nat d w ea nata)(*strict*)
apply(clarsimp)
apply(rename_tac x b nat d w ea nata a)(*strict*)
apply(subgoal_tac "\<exists>e w. teB Do \<notin> set w \<and> (teA S') \<notin> set w \<and> d (Suc (Suc nata)) = Some (pair e \<lparr>cfg_conf=teB Do#w@[teB Do]\<rparr>)")
apply(rename_tac x b nat d w ea nata a)(*strict*)
prefer 2
apply(rule_tac
G="G"
in F_CFG_AUGMENT__on_old_grammar_basically)
apply(rename_tac x b nat d w ea nata a)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x b nat d w ea nata a)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x b nat d w ea nata a)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x b nat d w ea nata a)(*strict*)
apply(force)
apply(rename_tac x b nat d w ea nata a)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x b nat d w ea nata a)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x b nat d w ea nata a)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(simp add: cfg_initial_configurations_def)
apply(rename_tac x b nat d w ea nata a)(*strict*)
apply(force)
apply(rename_tac x b nat d w ea nata a)(*strict*)
apply(force)
apply(rename_tac x b nat d w ea nata a)(*strict*)
apply(clarsimp)
apply(rename_tac x b nat d w ea nata e wa)(*strict*)
apply(case_tac "d (Suc nata)")
apply(rename_tac x b nat d w ea nata e wa)(*strict*)
apply(rule_tac
n="Suc nata"
in cfgSTD.derivationNoFromNone)
apply(rename_tac x b nat d w ea nata e wa)(*strict*)
apply(force)
apply(rename_tac x b nat d w ea nata e wa)(*strict*)
apply(force)
apply(rename_tac x b nat d w ea nata e wa)(*strict*)
apply(force)
apply(rename_tac x b nat d w ea nata e wa a)(*strict*)
apply(subgoal_tac "\<exists>e w. teB Do \<notin> set w \<and> (teA S') \<notin> set w \<and> d (Suc nata) = Some (pair e \<lparr>cfg_conf=teB Do#w@[teB Do]\<rparr>)")
apply(rename_tac x b nat d w ea nata e wa a)(*strict*)
prefer 2
apply(rule_tac
G="G"
in F_CFG_AUGMENT__on_old_grammar_basically)
apply(rename_tac x b nat d w ea nata e wa a)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x b nat d w ea nata e wa a)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x b nat d w ea nata e wa a)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x b nat d w ea nata e wa a)(*strict*)
apply(force)
apply(rename_tac x b nat d w ea nata e wa a)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x b nat d w ea nata e wa a)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x b nat d w ea nata e wa a)(*strict*)
apply(simp add: cfg_initial_configurations_def)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x b nat d w ea nata e wa a)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x b nat d w ea nata e wa a)(*strict*)
apply(force)
apply(rename_tac x b nat d w ea nata e wa a)(*strict*)
apply(clarsimp)
apply(rename_tac x b nat d w ea nata e wa eb wb)(*strict*)
apply(simp add: derivation_drop_def derivation_map_def)
apply(subgoal_tac "Suc (Suc nata) \<le> Suc nat")
apply(rename_tac x b nat d w ea nata e wa eb wb)(*strict*)
prefer 2
apply(rule cfgSTD.allPreMaxDomSome_prime)
apply(rename_tac x b nat d w ea nata e wa eb wb)(*strict*)
apply(force)
apply(rename_tac x b nat d w ea nata e wa eb wb)(*strict*)
apply(force)
apply(rename_tac x b nat d w ea nata e wa eb wb)(*strict*)
apply(force)
apply(rename_tac x b nat d w ea nata e wa eb wb)(*strict*)
apply(subgoal_tac "\<exists>e c. d (Suc (Suc nata)) = Some (pair (Some e) c)")
apply(rename_tac x b nat d w ea nata e wa eb wb)(*strict*)
prefer 2
apply(rule cfgSTD.some_position_has_details_before_max_dom_after_0)
apply(rename_tac x b nat d w ea nata e wa eb wb)(*strict*)
apply(blast)
apply(rename_tac x b nat d w ea nata e wa eb wb)(*strict*)
apply(blast)
apply(rename_tac x b nat d w ea nata e wa eb wb)(*strict*)
apply(arith)
apply(rename_tac x b nat d w ea nata e wa eb wb)(*strict*)
apply(clarsimp)
apply(rename_tac x b nat d w ea nata wa eb wb ec)(*strict*)
apply(subgoal_tac "cfgSTD_step_relation G \<lparr>cfg_conf = wb\<rparr> ec \<lparr>cfg_conf = wa\<rparr>")
apply(rename_tac x b nat d w ea nata wa eb wb ec)(*strict*)
apply(force)
apply(rename_tac x b nat d w ea nata wa eb wb ec)(*strict*)
apply(subgoal_tac "cfgSTD_step_relation G' \<lparr>cfg_conf = teB Do # wb @ [teB Do]\<rparr> ec \<lparr>cfg_conf = teB Do # wa @ [teB Do]\<rparr>")
apply(rename_tac x b nat d w ea nata wa eb wb ec)(*strict*)
prefer 2
apply(rule_tac
n="Suc nata"
in cfgSTD.position_change_due_to_step_relation)
apply(rename_tac x b nat d w ea nata wa eb wb ec)(*strict*)
apply(blast)
apply(rename_tac x b nat d w ea nata wa eb wb ec)(*strict*)
apply(blast)
apply(rename_tac x b nat d w ea nata wa eb wb ec)(*strict*)
apply(blast)
apply(rename_tac x b nat d w ea nata wa eb wb ec)(*strict*)
apply(simp add: cfgSTD_step_relation_def)
apply(clarsimp)
apply(rename_tac x b nat d w ea nata wa eb wb ec l r)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def F_CFG_AUGMENT_def)
apply(clarsimp)
apply(case_tac l)
apply(rename_tac x b nat d w ea nata wa eb wb ec l r)(*strict*)
apply(clarsimp)
apply(rename_tac x b nat d w ea nata wa eb wb ec l r a list)(*strict*)
apply(clarsimp)
apply(rename_tac x b nat d w ea nata wa eb wb ec r list)(*strict*)
apply(case_tac r)
apply(rename_tac x b nat d w ea nata wa eb wb ec r list)(*strict*)
apply(clarsimp)
apply(rename_tac x b nat d w ea nata wa eb wb ec r list a lista)(*strict*)
apply(subgoal_tac "\<exists>w' x'. r = w' @ [x']")
apply(rename_tac x b nat d w ea nata wa eb wb ec r list a lista)(*strict*)
prefer 2
apply(rule NonEmptyListHasTailElem)
apply(force)
apply(rename_tac x b nat d w ea nata wa eb wb ec r list a lista)(*strict*)
apply(thin_tac "r=a#lista")
apply(clarsimp)
apply(rename_tac x b nat d w ea nata eb ec list w')(*strict*)
apply(rule conjI)
apply(rename_tac x b nat d w ea nata eb ec list w')(*strict*)
apply(clarsimp)
apply(rename_tac x b nat d w ea nata eb ec list w')(*strict*)
apply(rule_tac
x="list"
in exI)
apply(rule_tac
x="w'"
in exI)
apply(clarsimp)
apply(rename_tac x b nat d w ea)(*strict*)
apply(rule conjI)
apply(rename_tac x b nat d w ea)(*strict*)
apply(simp add: derivation_drop_def derivation_map_def)
apply(simp add: cfg_initial_configurations_def)
apply(clarsimp)
apply(rename_tac x nat d w ea)(*strict*)
apply(simp add: cfg_configurations_def)
apply(rule cfg_initial_in_nonterms)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac x b nat d w ea)(*strict*)
apply(rule conjI)
apply(rename_tac x b nat d w ea)(*strict*)
apply(rule_tac
x="if nat=0 then None else ea"
in exI)
apply(rule_tac
x="\<lparr>cfg_conf = w\<rparr>"
in exI)
apply(clarsimp)
apply(rule conjI)
apply(rename_tac x b nat d w ea)(*strict*)
apply(clarsimp)
apply(rename_tac x b nat d w ea)(*strict*)
apply(clarsimp)
apply(rule conjI)
apply(rename_tac x b nat d w ea)(*strict*)
apply(rule_tac
x="nat"
in exI)
apply(simp add: derivation_drop_def derivation_map_def)
apply(rename_tac x b nat d w ea)(*strict*)
apply(simp only: setAConcat concat_asso)
apply(rule conjI)
apply(rename_tac x b nat d w ea)(*strict*)
apply(force)
apply(rename_tac x b nat d w ea)(*strict*)
apply(rule liftBDeConv2)
apply(force)
apply(rename_tac x b nat d w ea)(*strict*)
apply(rule conjI)
apply(rename_tac x b nat d w ea)(*strict*)
apply(simp add: derivation_drop_def derivation_map_def)
apply(rename_tac x b nat d w ea)(*strict*)
apply(simp add: cfg_initial_configurations_def)
apply(clarsimp)
apply(rename_tac x nat d w ea)(*strict*)
apply(rule_tac
x="nat"
in exI)
apply(rule_tac
x="if nat =0 then None else ea"
in exI)
apply(rule_tac
x="\<lparr>cfg_conf = w\<rparr>"
in exI)
apply(simp add: derivation_drop_def derivation_map_def)
apply(subgoal_tac "\<lparr>cfg_conf = w\<rparr> \<in> cfg_marking_configuration G")
apply(rename_tac x nat d w ea)(*strict*)
apply(clarsimp)
apply(rename_tac x nat d w ea)(*strict*)
apply(simp add: cfg_marking_configuration_def)
apply(simp add: cfg_configurations_def)
apply(clarsimp)
apply(simp only: setAConcat concat_asso)
apply(simp only: setBConcat concat_asso)
apply(rule conjI)
apply(rename_tac x nat d w ea)(*strict*)
apply(force)
apply(rename_tac x nat d w ea)(*strict*)
apply(rule conjI)
apply(rename_tac x nat d w ea)(*strict*)
apply(force)
apply(rename_tac x nat d w ea)(*strict*)
apply(subgoal_tac "Do \<notin> setB w")
apply(rename_tac x nat d w ea)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def F_CFG_AUGMENT_def)
apply(force)
apply(rename_tac x nat d w ea)(*strict*)
apply(rule not_in_setBI)
apply(force)
done
theorem F_CFG_AUGMENT__lang: "
F_CFG_AUGMENT__input G Do S' G'
\<Longrightarrow> (\<lambda>w. Do # w @ [Do]) ` cfgSTD.marked_language G = cfgSTD.marked_language G'"
apply(rule order_antisym)
apply(rule F_CFG_AUGMENT__lang_incl1)
apply(force)
apply(rule F_CFG_AUGMENT__lang_incl2)
apply(force)
done
lemma F_CFG_AUGMENT__lang_prime: "
F_CFG_AUGMENT__input G Do S' G'
\<Longrightarrow> (\<lambda>w. Do # w @ [Do]) w \<in> cfgSTD.marked_language G'
\<Longrightarrow> w \<in> cfgSTD.marked_language G"
apply(subgoal_tac "(\<lambda>w. Do#w@[Do]) w \<in> ((\<lambda>w. Do#w@[ Do]) ` cfgSTD.marked_language G)")
prefer 2
apply(rule_tac
s="cfgSTD.marked_language G'"
and t="(\<lambda>w. Do#w@[Do]) ` cfgSTD.marked_language G"
in ssubst)
apply(rule F_CFG_AUGMENT__lang)
apply(force)
apply(force)
apply(force)
done
lemma F_CFG_AUGMENT__derivation_of_input_from_effect: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> cfgRM.derivation G' d
\<Longrightarrow> cfgRM.belongs G' d
\<Longrightarrow> d 0 = Some (pair None c)
\<Longrightarrow> set (cfg_conf c) \<subseteq> two_elements_construct_domain (cfg_nonterminals G) (cfg_events G)
\<Longrightarrow> cfgRM.belongs G d"
apply(simp (no_asm) add: cfgRM.belongs_def)
apply(clarsimp)
apply(rename_tac i)(*strict*)
apply(induct_tac i rule: nat_induct)
apply(rename_tac i)(*strict*)
apply(clarsimp)
apply(simp add: cfg_configurations_def)
apply(case_tac c)
apply(rename_tac cfg_confa)(*strict*)
apply(clarsimp)
apply(rename_tac cfg_conf)(*strict*)
apply(rule conjI)
apply(rename_tac cfg_conf)(*strict*)
apply(rule two_elements_construct_domain_setA)
apply(force)
apply(rename_tac cfg_conf)(*strict*)
apply(rule two_elements_construct_domain_setB)
apply(force)
apply(rename_tac i n)(*strict*)
apply(clarsimp)
apply(rename_tac n)(*strict*)
apply(rename_tac n)
apply(case_tac "d(Suc n)")
apply(rename_tac n)(*strict*)
apply(clarsimp)
apply(rename_tac n a)(*strict*)
apply(subgoal_tac "\<exists>e1 e2 c1 c2. d n = Some (pair e1 c1) \<and> d (Suc n) = Some (pair (Some e2) c2) \<and> cfgRM_step_relation (F_CFG_AUGMENT G (F_FRESH (cfg_nonterminals G)) (F_FRESH (cfg_events G))) c1 e2 c2")
apply(rename_tac n a)(*strict*)
prefer 2
apply(rule_tac
m="Suc n"
in cfgRM.step_detail_before_some_position)
apply(rename_tac n a)(*strict*)
apply(force)
apply(rename_tac n a)(*strict*)
apply(force)
apply(rename_tac n a)(*strict*)
apply(force)
apply(rename_tac n a)(*strict*)
apply(clarsimp)
apply(rename_tac n e1 e2 c1 c2)(*strict*)
apply(simp add: cfgRM_step_relation_def)
apply(clarsimp)
apply(rename_tac n e1 e2 c1 c2 l r)(*strict*)
apply(simp add: cfg_step_labels_def cfg_configurations_def)
apply(clarsimp)
apply(rename_tac n e1 e2 c2 l r)(*strict*)
apply(case_tac c2)
apply(rename_tac n e1 e2 c2 l r cfg_confa)(*strict*)
apply(clarsimp)
apply(rename_tac n e1 e2 l r)(*strict*)
apply(simp only: setBConcat setAConcat concat_asso)
apply(clarsimp)
apply(rule context_conjI)
apply(rename_tac n e1 e2 l r)(*strict*)
prefer 2
apply(simp add: valid_cfg_def)
apply(rename_tac n e1 e2 l r)(*strict*)
apply(simp add: F_CFG_AUGMENT_def)
apply(clarsimp)
apply(rename_tac n e1 l r)(*strict*)
apply(subgoal_tac "F_FRESH (cfg_nonterminals G) \<notin> cfg_nonterminals G")
apply(rename_tac n e1 l r)(*strict*)
apply(force)
apply(rename_tac n e1 l r)(*strict*)
apply(rule F_FRESH_is_fresh)
apply(simp add: valid_cfg_def)
done
theorem F_CFG_AUGMENT__preserves_Nonblockingness: "
F_CFG_AUGMENT__input G Do S' G'
\<Longrightarrow> valid_cfg G
\<Longrightarrow> cfgRM.Nonblockingness_branching G
\<Longrightarrow> cfgRM.Nonblockingness_branching G'"
apply(rule_tac
GL="G"
and R="{(\<lparr>cfg_conf=[teA (cfg_initial G)]\<rparr>,\<lparr>cfg_conf=[teA (cfg_initial G')]\<rparr>)}\<union>{(\<lparr>cfg_conf=wl\<rparr>,\<lparr>cfg_conf=wr\<rparr>)| wl wr. wr=[teB Do]@wl@[teB Do] \<and> set wl \<subseteq> two_elements_construct_domain (cfg_nonterminals G) (cfg_events G) }"
in cfgRM_cfgRM_ATS_Bisimulation_Configuration_Weak.preserve_Nonblockingness)
apply(force)
apply(rule F_CFG_AUGMENT__makes_CFG)
apply(force)
apply(simp add: F_CFG_AUGMENT__input_def)
prefer 5
apply(force)
apply(simp add: cfgRM_cfgRM_ATS_Bisimulation_Configuration_Weak.bisimulation_initial_def)
apply(clarsimp)
apply(rename_tac i2)(*strict*)
apply(simp add: cfg_initial_configurations_def)
apply(simp add: cfg_configurations_def)
apply(clarsimp)
apply(rule cfg_initial_in_nonterms)
apply(force)
apply(simp add: cfgRM_cfgRM_ATS_Bisimulation_Configuration_Weak.bisimulation_preserves_steps1_def)
apply(rule conjI)
apply(clarsimp)
apply(rename_tac e2 s2')(*strict*)
apply(simp add: cfgRM_step_relation_def)
apply(clarsimp)
apply(rename_tac e2 s2' l r)(*strict*)
apply(case_tac l)
apply(rename_tac e2 s2' l r)(*strict*)
prefer 2
apply(rename_tac e2 s2' l r a list)(*strict*)
apply(clarsimp)
apply(rename_tac e2 s2' l r)(*strict*)
apply(clarsimp)
apply(rename_tac e2 s2')(*strict*)
apply(rule_tac
x="\<lparr>cfg_conf = [teA (cfg_initial G)]\<rparr>"
in exI)
apply(clarsimp)
apply(rule_tac
x="der1 \<lparr>cfg_conf = [teA (cfg_initial G)]\<rparr>"
in exI)
apply(rule conjI)
apply(rename_tac e2 s2')(*strict*)
apply(rule cfgRM.der1_is_derivation)
apply(rename_tac e2 s2')(*strict*)
apply(rule_tac
x="0"
in exI)
apply(clarsimp)
apply(rule conjI)
apply(rename_tac e2 s2')(*strict*)
apply(rule der1_maximum_of_domain)
apply(rename_tac e2 s2')(*strict*)
apply(rule conjI)
apply(rename_tac e2 s2')(*strict*)
apply(simp add: get_configuration_def der1_def)
apply(rename_tac e2 s2')(*strict*)
apply(case_tac s2')
apply(rename_tac e2 s2' cfg_confa)(*strict*)
apply(clarsimp)
apply(rename_tac e2)(*strict*)
apply(case_tac e2)
apply(rename_tac e2 prod_lhsa prod_rhsa)(*strict*)
apply(clarsimp)
apply(rename_tac prod_rhs)(*strict*)
apply(rename_tac w)
apply(rename_tac w)(*strict*)
apply(erule impE)
apply(rename_tac w)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def F_CFG_AUGMENT_def)
apply(erule disjE)
apply(rename_tac w)(*strict*)
apply(clarsimp)
apply(rename_tac w)(*strict*)
apply(simp add: valid_cfg_def)
apply(clarsimp)
apply(erule_tac
x="\<lparr>prod_lhs = F_FRESH (cfg_nonterminals G), prod_rhs = w\<rparr>"
in ballE)
apply(rename_tac w)(*strict*)
prefer 2
apply(force)
apply(rename_tac w)(*strict*)
apply(clarsimp)
apply(subgoal_tac "F_FRESH (cfg_nonterminals G) \<notin> cfg_nonterminals G")
apply(rename_tac w)(*strict*)
apply(force)
apply(rename_tac w)(*strict*)
apply(rule F_FRESH_is_fresh)
apply(force)
apply(rename_tac w)(*strict*)
apply(simp add: two_elements_construct_domain_def)
apply(clarsimp)
apply(simp add: valid_cfg_def)
apply(clarsimp)
apply(rename_tac wl e2 s2')(*strict*)
apply(simp add: cfgRM_step_relation_def)
apply(clarsimp)
apply(rename_tac wl e2 s2' l r)(*strict*)
apply(case_tac l)
apply(rename_tac wl e2 s2' l r)(*strict*)
apply(clarsimp)
apply(rename_tac wl e2 s2' l r a list)(*strict*)
apply(clarsimp)
apply(rename_tac wl e2 s2' r list)(*strict*)
apply(case_tac r)
apply(rename_tac wl e2 s2' r list)(*strict*)
apply(clarsimp)
apply(rename_tac wl e2 s2' r list a lista)(*strict*)
apply(subgoal_tac "\<exists>w' x'. r = w' @ [x']")
apply(rename_tac wl e2 s2' r list a lista)(*strict*)
prefer 2
apply(rule NonEmptyListHasTailElem)
apply(force)
apply(rename_tac wl e2 s2' r list a lista)(*strict*)
apply(thin_tac "r=a#lista")
apply(clarsimp)
apply(rename_tac e2 s2' list w')(*strict*)
apply(rename_tac wl wr)
apply(rename_tac e2 s2' wl wr)(*strict*)
apply(case_tac s2')
apply(rename_tac e2 s2' wl wr cfg_confa)(*strict*)
apply(clarsimp)
apply(rename_tac e2 wl wr)(*strict*)
apply(rule_tac
x="\<lparr>cfg_conf = wl @ prod_rhs e2 @ wr\<rparr>"
in exI)
apply(rule_tac
x="der2 \<lparr>cfg_conf = wl @ teA (prod_lhs e2) # wr\<rparr> e2 \<lparr>cfg_conf = wl @ (prod_rhs e2) @ wr\<rparr>"
in exI)
apply(clarsimp)
apply(subgoal_tac "e2 \<in> cfg_productions G")
apply(rename_tac e2 wl wr)(*strict*)
prefer 2
apply(simp add: F_CFG_AUGMENT__input_def F_CFG_AUGMENT_def)
apply(erule disjE)
apply(rename_tac e2 wl wr)(*strict*)
apply(clarsimp)
apply(rename_tac wl wr)(*strict*)
apply(simp add: two_elements_construct_domain_def)
apply(erule disjE)
apply(rename_tac wl wr)(*strict*)
apply(clarsimp)
apply(subgoal_tac "F_FRESH (cfg_nonterminals G) \<notin> cfg_nonterminals G")
apply(rename_tac wl wr)(*strict*)
apply(force)
apply(rename_tac wl wr)(*strict*)
apply(rule F_FRESH_is_fresh)
apply(simp add: valid_cfg_def)
apply(rename_tac wl wr)(*strict*)
apply(clarsimp)
apply(rename_tac e2 wl wr)(*strict*)
apply(clarsimp)
apply(rename_tac e2 wl wr)(*strict*)
apply(rule conjI)
apply(rename_tac e2 wl wr)(*strict*)
apply(rule cfgRM.der2_is_derivation)
apply(simp add: cfgRM_step_relation_def)
apply(rule_tac
x="wl"
in exI)
apply(rule_tac
x="wr"
in exI)
apply(clarsimp)
apply(simp only: setAConcat concat_asso)
apply(force)
apply(rename_tac e2 wl wr)(*strict*)
apply(rule_tac
x="Suc 0"
in exI)
apply(rule conjI)
apply(rename_tac e2 wl wr)(*strict*)
apply(rule der2_maximum_of_domain)
apply(rename_tac e2 wl wr)(*strict*)
apply(simp add: get_configuration_def der2_def)
apply(case_tac e2)
apply(rename_tac e2 wl wr prod_lhsa prod_rhsa)(*strict*)
apply(rule SetxBiElem_check_vs_set_two_elements_construct_domain_check)
apply(rename_tac e2 wl wr prod_lhsa prod_rhsa)(*strict*)
apply(rule prod_rhs_in_cfg_events)
apply(rename_tac e2 wl wr prod_lhsa prod_rhs)(*strict*)
apply(force)
apply(rename_tac e2 wl wr prod_lhsa prod_rhsa)(*strict*)
apply(force)
apply(rename_tac e2 wl wr prod_lhsa prod_rhsa)(*strict*)
apply(rule prod_rhs_in_nonterms)
apply(rename_tac e2 wl wr prod_lhsa prod_rhs)(*strict*)
apply(force)
apply(rename_tac e2 wl wr prod_lhsa prod_rhsa)(*strict*)
apply(force)
apply(subgoal_tac "valid_cfg G'")
prefer 2
apply(rule_tac
G="G"
in F_CFG_AUGMENT__makes_CFG)
apply(force)
apply(simp add: cfgRM_cfgRM_ATS_Bisimulation_Configuration_Weak.bisimulation_preserves_steps2_def)
apply(rule conjI)
apply(clarsimp)
apply(rename_tac e1 s1')(*strict*)
apply(case_tac s1')
apply(rename_tac e1 s1' cfg_conf)(*strict*)
apply(clarsimp)
apply(rename_tac e1 cfg_conf)(*strict*)
apply(rename_tac w)
apply(rename_tac e1 w)(*strict*)
apply(rule_tac
x="\<lparr>cfg_conf = teB Do # w @ [teB Do]\<rparr>"
in exI)
apply(clarsimp)
apply(rule_tac
x="der3 \<lparr>cfg_conf = [teA (cfg_initial G')]\<rparr> \<lparr>prod_lhs=cfg_initial G',prod_rhs= teB Do # [teA (cfg_initial G)] @ [teB Do]\<rparr> \<lparr>cfg_conf = teB Do # [teA (cfg_initial G)] @ [teB Do]\<rparr> e1 \<lparr>cfg_conf = teB Do # w @ [teB Do]\<rparr>"
in exI)
apply(rename_tac e1 w)(*strict*)
apply(rule conjI)
apply(rename_tac e1 w)(*strict*)
apply(rule cfgRM.der3_is_derivation)
apply(rename_tac e1 w)(*strict*)
apply(force)
apply(rename_tac e1 w)(*strict*)
apply(simp add: cfgRM_step_relation_def)
apply(clarsimp)
apply(rename_tac e1 l r)(*strict*)
apply(rule conjI)
apply(rename_tac e1 l r)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(simp add: F_CFG_AUGMENT_def)
apply(rename_tac e1 l r)(*strict*)
apply(rule_tac
x="[]"
in exI)
apply(rule_tac
x="[]"
in exI)
apply(clarsimp)
apply(rename_tac e1 w)(*strict*)
apply(simp add: cfgRM_step_relation_def)
apply(clarsimp)
apply(rename_tac e1 l r)(*strict*)
apply(case_tac l)
apply(rename_tac e1 l r)(*strict*)
prefer 2
apply(rename_tac e1 l r a list)(*strict*)
apply(force)
apply(rename_tac e1 l r)(*strict*)
apply(clarsimp)
apply(rename_tac e1)(*strict*)
apply(rule conjI)
apply(rename_tac e1)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(simp add: F_CFG_AUGMENT_def)
apply(rename_tac e1)(*strict*)
apply(rule_tac
x="[teB Do]"
in exI)
apply(rule_tac
x="[teB Do]"
in exI)
apply(clarsimp)
apply(rename_tac e1 w)(*strict*)
apply(rule_tac
x="Suc (Suc 0)"
in exI)
apply(rule conjI)
apply(rename_tac e1 w)(*strict*)
apply(rule der3_maximum_of_domain)
apply(rename_tac e1 w)(*strict*)
apply(simp add: get_configuration_def der3_def)
apply(simp add: cfgRM_step_relation_def)
apply(erule conjE)
apply(erule exE)+
apply(rename_tac e1 w l r)(*strict*)
apply(erule conjE)+
apply(case_tac l)
apply(rename_tac e1 w l r)(*strict*)
prefer 2
apply(rename_tac e1 w l r a list)(*strict*)
apply(force)
apply(rename_tac e1 w l r)(*strict*)
apply(rule SetxBiElem_check_vs_set_two_elements_construct_domain_check)
apply(rename_tac e1 w l r)(*strict*)
apply(case_tac e1)
apply(rename_tac e1 w l r prod_lhsa prod_rhsa)(*strict*)
apply(rule_tac
t="w"
and s="prod_rhs e1"
in ssubst)
apply(rename_tac e1 w l r prod_lhsa prod_rhsa)(*strict*)
apply(force)
apply(rename_tac e1 w l r prod_lhsa prod_rhsa)(*strict*)
apply(rule prod_rhs_in_cfg_events)
apply(rename_tac e1 w l r prod_lhsa prod_rhsa)(*strict*)
apply(force)
apply(rename_tac e1 w l r prod_lhsa prod_rhsa)(*strict*)
apply(force)
apply(rename_tac e1 w l r)(*strict*)
apply(case_tac e1)
apply(rename_tac e1 w l r prod_lhsa prod_rhsa)(*strict*)
apply(rule prod_rhs_in_nonterms)
apply(rename_tac e1 w l r prod_lhsa prod_rhsa)(*strict*)
apply(force)
apply(rename_tac e1 w l r prod_lhsa prod_rhsa)(*strict*)
apply(force)
apply(clarsimp)
apply(rename_tac wl e1 s1')(*strict*)
apply(case_tac s1')
apply(rename_tac wl e1 s1' cfg_conf)(*strict*)
apply(clarsimp)
apply(rename_tac wl e1 cfg_conf)(*strict*)
apply(rename_tac w)
apply(rename_tac wl e1 w)(*strict*)
apply(rule_tac
x="\<lparr>cfg_conf = teB Do # w @ [teB Do]\<rparr>"
in exI)
apply(clarsimp)
apply(rule_tac
x="der2 \<lparr>cfg_conf = teB Do # wl @ [teB Do]\<rparr> e1 \<lparr>cfg_conf = teB Do # w @ [teB Do]\<rparr>"
in exI)
apply(rule conjI)
apply(rename_tac wl e1 w)(*strict*)
apply(rule cfgRM.der2_is_derivation)
apply(simp add: cfgRM_step_relation_def)
apply(clarsimp)
apply(rename_tac e1 l r)(*strict*)
apply(rule conjI)
apply(rename_tac e1 l r)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(simp add: F_CFG_AUGMENT_def)
apply(rename_tac e1 l r)(*strict*)
apply(rule_tac
x="[teB Do]@l"
in exI)
apply(rule_tac
x="r@[teB Do]"
in exI)
apply(clarsimp)
apply(simp only: setAConcat concat_asso)
apply(clarsimp)
apply(rename_tac wl e1 w)(*strict*)
apply(rule_tac
x="Suc 0"
in exI)
apply(rule conjI)
apply(rename_tac wl e1 w)(*strict*)
apply(rule der2_maximum_of_domain)
apply(rename_tac wl e1 w)(*strict*)
apply(simp add: get_configuration_def der2_def)
apply(simp add: cfgRM_step_relation_def)
apply(clarsimp)
apply(rename_tac e1 x l r)(*strict*)
apply(erule disjE)
apply(rename_tac e1 x l r)(*strict*)
apply(force)
apply(rename_tac e1 x l r)(*strict*)
apply(erule disjE)
apply(rename_tac e1 x l r)(*strict*)
prefer 2
apply(force)
apply(rename_tac e1 x l r)(*strict*)
apply(rule_tac
A="set (prod_rhs e1)"
in set_mp)
apply(rename_tac e1 x l r)(*strict*)
apply(case_tac e1)
apply(rename_tac e1 x l r prod_lhsa prod_rhsa)(*strict*)
apply(rule SetxBiElem_check_vs_set_two_elements_construct_domain_check)
apply(rename_tac e1 x l r prod_lhsa prod_rhsa)(*strict*)
apply(rule prod_rhs_in_cfg_events)
apply(rename_tac e1 x l r prod_lhsa prod_rhsa)(*strict*)
apply(force)
apply(rename_tac e1 x l r prod_lhsa prod_rhsa)(*strict*)
apply(force)
apply(rename_tac e1 x l r prod_lhsa prod_rhsa)(*strict*)
apply(rule prod_rhs_in_nonterms)
apply(rename_tac e1 x l r prod_lhsa prod_rhsa)(*strict*)
apply(force)
apply(rename_tac e1 x l r prod_lhsa prod_rhsa)(*strict*)
apply(force)
apply(rename_tac e1 x l r)(*strict*)
apply(force)
apply(clarsimp)
apply(simp add: cfgRM_cfgRM_ATS_Bisimulation_Configuration_Weak.bisimulation_preserves_marking_condition_def)
apply(rule conjI)
apply(clarsimp)
apply(rename_tac dh n dha na)(*strict*)
apply(simp add: cfg_marking_condition_def)
apply(clarsimp)
apply(rename_tac dh n dha na i e c)(*strict*)
apply(rule_tac
x="na"
in exI)
apply(subgoal_tac "\<exists>e c. dha na = Some (pair e c)")
apply(rename_tac dh n dha na i e c)(*strict*)
prefer 2
apply(simp add: maximum_of_domain_def)
apply(clarsimp)
apply(rename_tac dh n dha na i e c y ya)(*strict*)
apply(case_tac ya)
apply(rename_tac dh n dha na i e c y ya option b)(*strict*)
apply(force)
apply(rename_tac dh n dha na i e c)(*strict*)
apply(clarsimp)
apply(rename_tac dh n dha na i e c ea ca)(*strict*)
apply(simp add: cfg_marking_configuration_def cfg_configurations_def)
apply(clarsimp)
apply(rename_tac dh n dha na i e ea ca cb)(*strict*)
apply(case_tac ca)
apply(rename_tac dh n dha na i e ea ca cb cfg_confa)(*strict*)
apply(clarsimp)
apply(rename_tac dh n dha na i e ea cb cfg_conf)(*strict*)
apply(rename_tac w)
apply(rename_tac dh n dha na i e ea cb w)(*strict*)
apply(simp add: derivation_append_fit_def der1_def)
apply(clarsimp)
apply(rename_tac dh n dha na i e ea cb)(*strict*)
apply(case_tac "dh n")
apply(rename_tac dh n dha na i e ea cb)(*strict*)
apply(clarsimp)
apply(rename_tac dh n dha na i e ea cb a)(*strict*)
apply(clarsimp)
apply(case_tac a)
apply(rename_tac dh n dha na i e ea cb a option b)(*strict*)
apply(clarsimp)
apply(rename_tac dh n dha na i e ea cb option)(*strict*)
apply(subgoal_tac "i=n")
apply(rename_tac dh n dha na i e ea cb option)(*strict*)
apply(clarsimp)
apply(rename_tac dh n dha na i e ea cb option)(*strict*)
apply(rule cfgRM.maximum_of_domainUnique)
apply(rename_tac dh n dha na i e ea cb option)(*strict*)
apply(force)
apply(rename_tac dh n dha na i e ea cb option)(*strict*)
apply(force)
apply(rename_tac dh n dha na i e ea cb option)(*strict*)
apply(simp add: maximum_of_domain_def)
apply(rule cfgRM_no_step_without_nonterms)
apply(rename_tac dh n dha na i e ea cb option)(*strict*)
apply(force)
apply(rename_tac dh n dha na i e ea cb option)(*strict*)
apply(force)
apply(rename_tac dh n dha na i e ea cb option)(*strict*)
apply(force)
apply(rename_tac dh n dha na i e ea cb option)(*strict*)
apply(force)
apply(clarsimp)
apply(rename_tac wl dh n dha na)(*strict*)
apply(simp add: cfg_marking_condition_def)
apply(clarsimp)
apply(rename_tac wl dh n dha na i e c)(*strict*)
apply(simp add: cfg_marking_configuration_def cfg_configurations_def)
apply(clarsimp)
apply(rename_tac wl dh n dha na i e ca)(*strict*)
apply(rule_tac
x="na"
in exI)
apply(subgoal_tac "\<exists>e c. dha na = Some (pair e c)")
apply(rename_tac wl dh n dha na i e ca)(*strict*)
prefer 2
apply(simp add: maximum_of_domain_def)
apply(clarsimp)
apply(rename_tac wl dh n dha na i e ca y ya)(*strict*)
apply(case_tac ya)
apply(rename_tac wl dh n dha na i e ca y ya option b)(*strict*)
apply(force)
apply(rename_tac wl dh n dha na i e ca)(*strict*)
apply(clarsimp)
apply(rename_tac wl dh n dha na i e ca ea c)(*strict*)
apply(case_tac c)
apply(rename_tac wl dh n dha na i e ca ea c cfg_confa)(*strict*)
apply(clarsimp)
apply(rename_tac wl dh n dha na i e ca ea cfg_conf)(*strict*)
apply(rename_tac w)
apply(rename_tac wl dh n dha na i e ca ea w)(*strict*)
apply(simp add: derivation_append_fit_def der1_def)
apply(clarsimp)
apply(rename_tac wl dh n dha na i e ca ea)(*strict*)
apply(case_tac "dh n")
apply(rename_tac wl dh n dha na i e ca ea)(*strict*)
apply(clarsimp)
apply(rename_tac wl dh n dha na i e ca ea a)(*strict*)
apply(clarsimp)
apply(case_tac a)
apply(rename_tac wl dh n dha na i e ca ea a option b)(*strict*)
apply(clarsimp)
apply(rename_tac wl dh n dha na i e ca ea option)(*strict*)
apply(subgoal_tac "i=n")
apply(rename_tac wl dh n dha na i e ca ea option)(*strict*)
prefer 2
apply(rule cfgRM.maximum_of_domainUnique)
apply(rename_tac wl dh n dha na i e ca ea option)(*strict*)
apply(force)
apply(rename_tac wl dh n dha na i e ca ea option)(*strict*)
apply(force)
apply(rename_tac wl dh n dha na i e ca ea option)(*strict*)
apply(simp add: maximum_of_domain_def)
apply(rule cfgRM_no_step_without_nonterms)
apply(rename_tac wl dh n dha na i e ca ea option)(*strict*)
apply(force)
apply(rename_tac wl dh n dha na i e ca ea option)(*strict*)
apply(force)
apply(rename_tac wl dh n dha na i e ca ea option)(*strict*)
apply(force)
apply(rename_tac wl dh n dha na i e ca ea option)(*strict*)
apply(force)
apply(rename_tac wl dh n dha na i e ca ea option)(*strict*)
apply(clarsimp)
apply(rename_tac dh n dha na e ca ea)(*strict*)
apply(simp only: setBConcat setAConcat concat_asso)
apply(clarsimp)
apply(simp add: F_CFG_AUGMENT__input_def F_CFG_AUGMENT_def)
apply(clarsimp)
apply(rename_tac dh n dha na e ca ea x)(*strict*)
apply(force)
done
lemma F_CFG_AUGMENT__reachableConf_of_certain_form: "
F_CFG_AUGMENT__input G Do S' G'
\<Longrightarrow> cfgSTD.derivation_initial G' d
\<Longrightarrow> d (Suc i) = Some (pair e c)
\<Longrightarrow> \<exists>w. set w \<subseteq> two_elements_construct_domain (cfg_nonterminals G) (cfg_events G) \<and> cfg_conf c = [teB Do] @ w @ [teB Do]"
apply(subgoal_tac "valid_cfg G'")
prefer 2
apply(rule F_CFG_AUGMENT__makes_CFG)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(force)
apply(induct i arbitrary: e c)
apply(rename_tac e c)(*strict*)
apply(clarsimp)
apply(subgoal_tac "d (Suc 0)= Some (pair (Some \<lparr>prod_lhs=cfg_initial G',prod_rhs=[teB Do,teA (cfg_initial G),teB Do]\<rparr>) \<lparr>cfg_conf=[teB Do,teA (cfg_initial G),teB Do]\<rparr>)")
apply(rename_tac e c)(*strict*)
prefer 2
apply(rule F_CFG_AUGMENT__FirstStep)
apply(rename_tac e c)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac e c)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac e c)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac e c)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(rename_tac e c)(*strict*)
apply(force)
apply(rename_tac e c)(*strict*)
apply(rule cfgSTD.derivation_initial_is_derivation)
apply(force)
apply(rename_tac e c)(*strict*)
apply(simp add: cfgSTD.derivation_initial_def cfg_initial_configurations_def)
apply(clarsimp)
apply(case_tac "d 0")
apply(rename_tac e c)(*strict*)
apply(clarsimp)
apply(rename_tac e c a)(*strict*)
apply(clarsimp)
apply(case_tac a)
apply(rename_tac e c a option b)(*strict*)
apply(clarsimp)
apply(rename_tac e c b)(*strict*)
apply(simp add: cfg_initial_configurations_def)
apply(rename_tac e c)(*strict*)
apply(force)
apply(rename_tac e c)(*strict*)
apply(clarsimp)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(simp add: two_elements_construct_domain_def valid_cfg_def)
apply(rename_tac i e c)(*strict*)
apply(clarsimp)
apply(subgoal_tac "\<exists>e1 e2 c1 c2. d (Suc i) = Some (pair e1 c1) \<and> d (Suc (Suc i)) = Some (pair (Some e2) c2) \<and> cfgSTD_step_relation G' c1 e2 c2")
apply(rename_tac i e c)(*strict*)
prefer 2
apply(rule_tac
m="Suc (Suc i)"
in cfgSTD.step_detail_before_some_position)
apply(rename_tac i e c)(*strict*)
apply(rule cfgSTD.derivation_initial_is_derivation)
apply(force)
apply(rename_tac i e c)(*strict*)
apply(force)
apply(rename_tac i e c)(*strict*)
apply(force)
apply(rename_tac i e c)(*strict*)
apply(clarsimp)
apply(rename_tac i c e1 e2 c1)(*strict*)
apply(erule_tac
x="e1"
in meta_allE)
apply(erule_tac
x="c1"
in meta_allE)
apply(clarsimp)
apply(rename_tac i c e1 e2 c1 w)(*strict*)
apply(simp add: cfgSTD_step_relation_def)
apply(clarsimp)
apply(rename_tac i c e1 e2 c1 w l r)(*strict*)
apply(case_tac l)
apply(rename_tac i c e1 e2 c1 w l r)(*strict*)
apply(force)
apply(rename_tac i c e1 e2 c1 w l r a list)(*strict*)
apply(clarsimp)
apply(rename_tac i c e1 e2 c1 w r list)(*strict*)
apply(case_tac r)
apply(rename_tac i c e1 e2 c1 w r list)(*strict*)
apply(clarsimp)
apply(rename_tac i c e1 e2 c1 w r list a lista)(*strict*)
apply(subgoal_tac "\<exists>w' x'. r = w' @ [x']")
apply(rename_tac i c e1 e2 c1 w r list a lista)(*strict*)
prefer 2
apply(rule NonEmptyListHasTailElem)
apply(force)
apply(rename_tac i c e1 e2 c1 w r list a lista)(*strict*)
apply(thin_tac "r=a#lista")
apply(clarsimp)
apply(rename_tac i c e1 e2 c1 list w' x)(*strict*)
apply(subgoal_tac "e2 \<in> cfg_productions G")
apply(rename_tac i c e1 e2 c1 list w' x)(*strict*)
apply(simp add: valid_cfg_def F_CFG_AUGMENT__input_def two_elements_construct_domain_def)
apply(clarsimp)
apply(erule_tac
x="e2"
and P="\<lambda>e2. prod_lhs e2 \<in> cfg_nonterminals G \<and> setA (prod_rhs e2) \<subseteq> cfg_nonterminals G \<and> setB (prod_rhs e2) \<subseteq> cfg_events G"
in ballE)
apply(rename_tac i c e1 e2 c1 list w' x)(*strict*)
prefer 2
apply(force)
apply(rename_tac i c e1 e2 c1 list w' x)(*strict*)
apply(clarsimp)
apply(case_tac x)
apply(rename_tac i c e1 e2 c1 list w' x a)(*strict*)
apply(clarsimp)
apply(rename_tac i c e1 e2 c1 list w' a)(*strict*)
apply(rule inMap)
apply(clarsimp)
apply(rule_tac
A="setA (prod_rhs e2)"
in set_mp)
apply(rename_tac i c e1 e2 c1 list w' a)(*strict*)
apply(force)
apply(rename_tac i c e1 e2 c1 list w' a)(*strict*)
apply(rule set_setA)
apply(force)
apply(rename_tac i c e1 e2 c1 list w' x b)(*strict*)
apply(clarsimp)
apply(rename_tac i c e1 e2 c1 list w' b)(*strict*)
apply(subgoal_tac "teB b \<in> teB ` cfg_events G")
apply(rename_tac i c e1 e2 c1 list w' b)(*strict*)
apply(force)
apply(rename_tac i c e1 e2 c1 list w' b)(*strict*)
apply(rule inMap)
apply(clarsimp)
apply(rule_tac
A="setB (prod_rhs e2)"
in set_mp)
apply(rename_tac i c e1 e2 c1 list w' b)(*strict*)
apply(force)
apply(rename_tac i c e1 e2 c1 list w' b)(*strict*)
apply(rule set_setB)
apply(force)
apply(rename_tac i c e1 e2 c1 list w' x)(*strict*)
apply(subgoal_tac "prod_lhs e2 \<in> cfg_nonterminals G")
apply(rename_tac i c e1 e2 c1 list w' x)(*strict*)
apply(subgoal_tac "e2 \<in> cfg_productions G'")
apply(rename_tac i c e1 e2 c1 list w' x)(*strict*)
apply(simp add: F_CFG_AUGMENT__input_def)
apply(clarsimp)
apply(simp add: F_CFG_AUGMENT_def)
apply(clarsimp)
apply(rename_tac i c e1 c1 list w' x)(*strict*)
apply(case_tac c1)
apply(rename_tac i c e1 c1 list w' x cfg_confa)(*strict*)
apply(clarsimp)
apply(rename_tac i c e1 list w' x)(*strict*)
apply(case_tac c)
apply(rename_tac i c e1 list w' x cfg_confa)(*strict*)
apply(clarsimp)
apply(rename_tac i e1 list w' x)(*strict*)
apply(simp add: two_elements_construct_domain_def)
apply(subgoal_tac "F_FRESH (cfg_nonterminals G) \<notin> cfg_nonterminals G")
apply(rename_tac i e1 list w' x)(*strict*)
apply(force)
apply(rename_tac i e1 list w' x)(*strict*)
apply(rule F_FRESH_is_fresh)
apply(simp add: F_CFG_AUGMENT__input_def valid_cfg_def)
apply(rename_tac i c e1 e2 c1 list w' x)(*strict*)
apply(rule_tac
t="cfg_productions G'"
and s="cfg_step_labels G'"
in ssubst)
apply(rename_tac i c e1 e2 c1 list w' x)(*strict*)
apply(simp add: cfg_step_labels_def)
apply(rename_tac i c e1 e2 c1 list w' x)(*strict*)
apply(rule cfgSTD.belongs_step_labels)
apply(rename_tac i c e1 e2 c1 list w' x)(*strict*)
apply(rule cfgSTD.derivation_initial_belongs)
apply(rename_tac i c e1 e2 c1 list w' x)(*strict*)
apply(force)
apply(rename_tac i c e1 e2 c1 list w' x)(*strict*)
apply(force)
apply(rename_tac i c e1 e2 c1 list w' x)(*strict*)
apply(force)
apply(rename_tac i c e1 e2 c1 list w' x)(*strict*)
apply(simp add: two_elements_construct_domain_def)
apply(erule disjE)
apply(rename_tac i c e1 e2 c1 list w' x)(*strict*)
apply(clarsimp)
apply(rename_tac i c e1 e2 c1 list w' x)(*strict*)
apply(clarsimp)
done
lemma F_CFG_AUGMENT__prod_subset: "
valid_cfg G
\<Longrightarrow> Do = F_FRESH (cfg_events G)
\<Longrightarrow> S' = F_FRESH (cfg_nonterminals G)
\<Longrightarrow> G' = F_CFG_AUGMENT G S' Do
\<Longrightarrow> cfg_productions G \<subseteq> cfg_productions G'"
apply(simp add: F_CFG_AUGMENT_def)
apply(force)
done
end
|
If $T$ is a connected subset of $S$ containing $x$, then $T$ is contained in the connected component of $S$ containing $x$. |
theory PF_Ok_Transformation
imports PF_PF
begin
(* this is currently unused *)
(* definitions without packet type 'p *)
definition filter'' :: "'a ruleset \<Rightarrow> ('a \<Rightarrow> bool) \<Rightarrow> decision_wrap \<Rightarrow> decision_wrap" where
"filter'' rules \<gamma> d = filter' rules (\<lambda>a p. \<gamma> a) () d"
lemma matches_equiv[simp]: "matches (\<lambda>a p. \<gamma> a packet) me () = matches \<gamma> me packet"
by (induction me, auto)
lemma filter_filter''_eq[simp]: "filter'' rules (\<lambda>a. \<gamma> a packet) d = filter' rules \<gamma> packet d"
unfolding filter''_def
by (induction rules \<gamma> packet d rule: filter'.induct) (auto split: line.splits)
(* default behavior is Accept *)
definition pf' :: "'a ruleset \<Rightarrow> ('a \<Rightarrow> bool) \<Rightarrow> decision" where
"pf' rules \<gamma> = unwrap_decision (filter'' rules \<gamma> (Preliminary Accept))"
lemma "pf rules \<gamma> packet = pf' rules (\<lambda>a. \<gamma> a packet)"
unfolding pf_def pf'_def
by simp
(* ruleset transformations *)
definition ruleset_equiv :: "'a ruleset \<Rightarrow> 'a ruleset \<Rightarrow> bool" ("_ \<simeq> _") where
"(l1 \<simeq> l2) \<longleftrightarrow> (pf' l1 = pf' l2)"
lemma ruleset_equivI[intro]: "(\<And>\<gamma>. pf' l1 \<gamma> = pf' l2 \<gamma>) \<Longrightarrow> l1 \<simeq> l2"
unfolding ruleset_equiv_def by auto
lemma ruleset_equiv_refl[intro, simp]: "l \<simeq> l" by auto
definition ok_transformation ::"('a ruleset \<Rightarrow> 'a ruleset) \<Rightarrow> bool" where
"ok_transformation f \<longleftrightarrow> (\<forall> rules. (rules \<simeq> (f rules)))"
lemma ok_transformationI[intro]: "(\<And>rules. (rules \<simeq> (f rules))) \<Longrightarrow> ok_transformation f"
unfolding ok_transformation_def by auto
lemma id_transformation[intro, simp]: "ok_transformation id" by auto
end |
If $f$ is a bounded bilinear function, then $f(x, y) \to 0$ as $y \to 0$. |
\documentclass[12pt]{article}
% Pacotes para o português.
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{graphicx} % Comando \includegraphics
\usepackage{xcolor} % Comando de cores \textcolor
\usepackage{indentfirst} % Indenta o primeiro parágrafo de cada seção
\usepackage{url} % Comandos \url e \href
\usepackage[top=2cm, bottom=2cm, left=2cm, right=2cm]{geometry} % Define as margens do documento
\usepackage{multirow} % Permite criar tabelas com uma célula ocupando várias linhas
\usepackage{amssymb} % Símbolos matemáticos
\usepackage{amsmath}
\usepackage{gensymb}
\usepackage{caption} % Para definir o estilo das legendas de figuras e tabelas.
\usepackage{setspace} % Para definir espaçamento entre linhas. (\onehalfspacing, \singlespacing, \doublespacing)
\usepackage{breakcites} % Para permitir quebra de linha no meio de citações.
\usepackage{times} % Fonte Times New Roman
\usepackage{caption}
\usepackage{subcaption}
\usepackage{csvsimple}
% Comando para marcar o texto para revisão.
% \newcommand{\rev}[1]{\textcolor{red}{#1}}
\graphicspath{{./images/}}
\begin{document}
\doublespacing
\begin{titlepage}
\begin{center}
{\large \sc University of Toronto} \\
{\large \sc Faculty of Applied Siences and Engineering}\\[0.7cm]
{\small \sc Division of Engineering Science}
\vspace{4cm}
% Título.
{\large \sc PHY180F}\\
\rule{\linewidth}{2pt}
\vspace{0.9em} % Ajuste ao seu gosto
{\Large \bfseries Pendulum Lab - Final Report}
\vspace{0.2em} % Ajuste ao seu gosto
\rule{\linewidth}{2pt} \\
{\small \sc December 9th, 2020}
\end{center}
\vspace{4cm}
% Assinaturas
\begin{minipage}{0.43\textwidth}
\emph{Author:}
Jayden Lefebvre\\
UTorID:
lefebv69
\end{minipage}
\hspace{1cm}
\begin{minipage}{0.43\textwidth}
\emph{Professor:}
\hspace{1.5cm} Dr. Joseph Thywissen\\
\emph{Teaching Assistant: }
Mr. Saeed Oghbaey
\end{minipage}
\vfill
\end{titlepage}
\pagestyle{empty}
\tableofcontents
\newpage
\setcounter{page}{1}
\pagestyle{plain}
\singlespacing
\section{Introduction}
\label{section:intro}
The purpose of this lab is to investigate the factors that contribute to a pendulum's behaviour, with a specific focus on \emph{simple harmonic motion} (see Section \ref{section:motion}).
In order to determine the fitness of a pendulum to the simple harmonic motion model, I will be investigating the relationships between period of oscillation and initial amplitude (\ref{section:q3}), string length (\ref{section:q4a}), and bob mass (\ref{section:q4b}).
In addition, I will be investigating the $Q$ factor or 'quality' of my pendulum (\ref{section:q2}).
\section{Background}
\label{section:background}
When released from some initial amplitude - angular displacement from equilibrium -
the pendulum is acted upon by the component of gravity \emph{tangential} to the string.
As it overshoots the equilibrium point and continues its oscillation, the tangential
component of gravity continues to act as a \emph{restorative force}, attempting to bring the
pendulum to rest at equilibrium. This continues until all energy in the system is dissipated, either via friction about the pin, or air resistance.
\subsection{Simple Harmonic Motion and Q Factor}
\label{section:motion}
Pendulums operate on the principle of \emph{simple harmonic motion}.
In non-ideal pendulum, the amplitude of oscillation decreases over time. This energy dissipation is due to a \emph{damping force} (friction and air resistance).
A \emph{damped oscillator}, as it is called, that has a large \emph{quality factor} $Q$ retains its energy for a longer time, and as such oscillates for more periods. The amplitude of a damped oscillator over time is described by:\\
\begin{equation}
\label{eqn:motion}
\theta(t) = \theta_0e^{t/\tau}\cos(2\pi\frac tT + \phi_0)
\end{equation}
\noindent
where $t$ is the time elapsed, $\theta_0$ is the initial amplitude, $\tau$ is the damping factor, $T$ is the period, $\phi_0$ is the phase offset.
There are two ways in which to calculate $Q$ factor:
\begin{equation}
Q_1=\pi \frac \tau T \text{ where $\tau$ and $T$ are the decay constant and period, respectively;}
\label{eqn:Q1}
\end{equation}
\begin{equation}
Q_2=2N\text{ where $N$ is the number of oscillations before }\theta(t)=\theta_Q=e^{-\pi/2}\theta_0 \approx 20\%\text{ of }\theta_0
\label{eqn:Q2}
\end{equation}
\subsection{Amplitude vs Period}
\label{powerseries}
Theoretically, if a pendulum operates in accordance with simple harmonic motion (Section \ref{section:motion}) and is symmetrical, the oscillation \emph{should} have the following properties:
\begin{enumerate}
\item There should be \textbf{no} relationship between \emph{sign} of initial amplitude and period length (symmetry);
\item There should be negligible relationship between \emph{magnitude} of initial amplitude and period.
\end{enumerate}
Thus, if period and initial amplitude are fit to the power series:
\begin{equation}
\label{eqn:powerseries}
T = A + B\theta_0 + C \theta_0^2 + \cdots
\end{equation}
\noindent
B should be equal to experimental zero, and C should be reasonably zero for small initial amplitudes. \textbf{Note:} degrees higher than 2 are not used for the purposes of this lab.
\pagebreak
\subsection{Length vs Period}
\label{powerlaw}
If a pendulum operates in accordance with simple harmonic motion (Section \ref{section:motion}), the period of oscillation \emph{should} be proportional to the square root of the length (the distance from the axis of rotation to the center of mass, or COM):
$$
T \approx 2\sqrt{L}
$$
Expressed as an exponential function:
\begin{equation}
\label{eqn:powerlaw}
T = k(L_0 + L)^n
\end{equation}
\noindent
where $T$ is the period, $k$ is the coefficient (related to the restorative force, gravity), $n$ is the exponent, and $L_0$ is the "error" of our estimation for length (should be experimentally zero).
\section{Method}
\label{section:method}
\subsection{Apparatus Details}
\label{section:materials}
Despite the report requirement for \textbf{no materials list}, there is a general understanding of certain components of the pendulum apparatus that are vital to understanding the method:
\begin{itemize}
\item The bob used is a container of small removable masses with a sturdy lid to which the string can be affixed;
\item The string used is not stretchy, and is made of wound plastic fibers;
\end{itemize}
\subsection{Setup}
\label{section:setup}
\noindent
The apparatus setup is as follows:
\begin{enumerate}
\item A mounting screw is installed at a fixed, sturdy mounting location;
\item The bob is configured for the test (see below) and attached to string via self-tightening slipknot (see Appendix Figure \ref{appendix:setup} for a closer look);
\item Non-slipping bowline knots are made in the string at fixed distances from the bob COM: 44.75", 39", 34.25", 29", and 25.25";
\item Horizontal reference is placed \emph{in plane} with the pendulum oscillation (see Appendix Figure \ref{appendix:table});
\item Tape marks are made at center (aka. pendulum equilibrium) on the horizontal reference, as well as 2ft (0.610m) in either direction (see Appendix Figure \ref{appendix:table});
\item Camera is set up on camera stand, in plane with pendulum oscillation, with the bottom of the camera viewport calibrated to the horizontal reference (see Appendix Figure \ref{appendix:table});
\end{enumerate}
\pagebreak
\noindent
The pendulum is configured on a \emph{per-test basis}.\\
If the test requires the \emph{mass} be adjusted:
\begin{enumerate}
\item Remove the cap from the bob;
\item Pour some of the pendulum's mass into a sturdy container;
\item Place the bob on the scale, and record the bob mass, adjust mass again if necessary;
\item Replace the cap and ensure the bob is tied to the string (as described above);
\end{enumerate}
\noindent
If the test requires the \emph{length} be adjusted, loop the selected bowline around the fixed mounting screw.
\subsection{Video Capture}
\label{section:videocapture}
\noindent
3 sets of videos were taken:
\begin{enumerate}
\item \textbf{Full Period} - Pendulum (mass 2032g, length 34.25") released at 90$\deg$, allowed to decay to <15$\deg$;
\item \textbf{String Length Trials} - Pendulum (mass 2032g) released at a moderate angle (think 30$\deg$-50$\deg$) with varying string length (44.75", 39", 34.25", 29", 25.25"), allowed to oscillate for 4-6 periods;
\item \textbf{Bob Mass Trials} - Pendulum (length 34.25") released at a moderate angle (think 30$\deg$-50$\deg$) with varying bob mass (2032g, 1784g, 1607g, 1366g, 1012g), allowed to oscillate for 4-6 periods;
\end{enumerate}
\subsection{Tracker Video Analysis}
\label{section:trackeranalysis}
The Tracker Video Analysis and Modelling Tool\cite{tracker} was used to track the position of the pendulum in the video captures across time.\\
\noindent
Preparing the video capture for Tracker software:
\begin{enumerate}
\item In VLC, select "File > Convert / Stream" and open the video capture;
\item Select "Custom" profile, customize with no audio track (minimize file size) and FLV encapsulation (Tracker compatibility);
\item Save as a file with appropriate name;
\end{enumerate}
\noindent
Opening the video in Tracker software:
\begin{enumerate}
\item In Tracker, select "File > Open File" and open the FLV video capture;
\item Wait for all frames to be loaded;
\end{enumerate}
\pagebreak
\noindent
Calibrating the Tracker environment:
\begin{enumerate}
\item Select "Track > New > Calibration Tools > Calibration Stick" and follow the Tracker's instructions to calibrate the ends of the stick to the center and 2ft marking on the horizontal reference in the video;
\item Toggle "Track > Axes > Visible" \textbf{ON}, and drag the origin of the axes to the pendulum axis;
\end{enumerate}
\noindent
Tracking the pendulum:
\begin{enumerate}
\item Select "Track > New > Point Mass";
\item On the "Track Control" panel, select the new point mass (should be named "mass A") and select "Autotracker";
\item Ensure the frame advance number in the bottom right of the screen is set to 5 (reduce total frames);
\item Depending on the speed of the pendulum, you will have to switch between \emph{manually} tracking the pendulum frame-by-frame (Shift+LClick) or using the \emph{autotracker} (set keyframe position, template region, search region, and evolution rate, I used 60\%) and allowing it to search for you;
\item Track the pendulum across all frames.
\end{enumerate}
\noindent
Exporting data for analysis:
\begin{enumerate}
\item In the table panel (right side, bottom panel), click the table button and ensure x, y, theta r, and v are toggled on
\item Right click inside the table, select "Numbers > Units..." and ensure that "Angle Units" is set to radians
\item Left click inside the table, press "CMD+A" on Mac (or "CTRL+A" on Windows) to select the entire table
\item Press "CMD+C" on Mac (or "CTRL+C" on Windows) to copy the entire table
\item Paste the data into Google Sheets. You can now perform analysis on the data.
\end{enumerate}
\subsection{Python Data Analysis}
Scripts were written in the \emph{Python} programming language\cite{python} to calculate and plot the fits and residuals for each test. The \emph{SciPy}\cite{scipy} and \emph{matplotlib}\cite{matplotlib} libraries were used. Scripts can be found in Appendix Section \ref{appendix:scripts}.
\pagebreak
\subsection{Uncertainty}
\label{section:uncertainty}
\subsubsection{Measurement Uncertainties}
\noindent
There were numerous sources of measurement uncertainty, examined here:
\begin{itemize}
\item Time - 60fps, assume $\pm$1 frame, $\pm$0.01667s
\item Position (Reference Frame) - 2ft markers on table used as reference (Fig), my standard imperial measuring tape has $\pm$1/16in uncertainty, or 0.2\% positional uncertainty. This distance is used as the reference length when analyzing the footage in Tracker. Since all positions are measured as distances, all positional data would have this uncertainty.
\item Position (Motion Blur) - Speed at apex when 2030g pendulum released from $\pi/2$rad is 4.042 m/s, which produced a motion blur in the video (Fig). The circular cross-section of the bob has a circumference of 10 5/8" = 26.988cm, or an actual diameter of 8.59cm which, due to motion blur, appeared to be 10.4cm on camera, corresponding to (10.4-8.59)/2 = 0.905cm of positional uncertainty. $v/v_0 * 0.905 / 100$
\item Mass Uncertainty - $\pm$1g kitchen scale
\end{itemize}
The maximum of the two positional uncertainties are used per datum, per the uncertianty propagation conventions outlined in the Pendulum Lab Handout.
\subsubsection{Calculated Uncertainties}
Measurement uncertainty was propagated per the uncertianty propagation conventions outlined in the Pendulum Lab Handout.\\
In order to calculate uncertainty for angle measurements generated from positional data, the difference between the maximum and minimum angles for position $(x,y)$ - given uncertainties $x'$ and $y'$ is used. For example, consider the set of all 4 possible combinations:
$$ S = \{\arctan(\frac{y\pm y'}{x \pm x'} \cdots)\}$$
The numerical difference between the maximum and minimum possible angles for a given position is used as the angular uncertainty:
$$ \theta' = \max\{S\} - \min\{S\}$$
\subsubsection{General Limitations}
\noindent
There were several sources of uncalulable or irreducable uncertainties, here viewed as limitations:
\begin{itemize}
\item Video pixellation leads to innacuracy in tracking;
\item Autotracker has limited accuracy when estimating bob mass position;
\item Video framerate (as well as Tracker frame step multiplier) limit time accuracy;
\end{itemize}
\newpage
\section{Results and Analysis}
\subsection{Q Factor}
\label{section:q2}
\subsubsection{Graphs}
\begin{figure}[h]
\centering
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{q2_fit.png}
\caption{Fit of data to decaying sinusoid (see Section \ref{section:q2fit}).}
\label{fig:q2fit}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{q2_residuals.png}
\caption{Residuals of fit.}
\label{fig:q2residuals}
\end{subfigure}
\hfill
\caption{Pendulum swing data (2030g, 34.25"). \\Note that error bars are \emph{very} small.}
\label{fig:q2fig}
\end{figure}
\subsubsection{Decaying Sinusoid Fit}
\label{section:q2fit}
The pendulum's amplitude over time bounded by $t \approx [80,130]$sec is shown in Figure \ref{fig:q2fit}, along with the fit of a decaying sinusoid as described in Equation \ref{eqn:motion}.
The specific values found by the curve fit function are as follows:
\begin{center}
$
\theta_0= 1.28 \pm 0.04\text{rad}$\\$
\tau= 240 \pm 20\text{sec}^{-1}$\\$
T= 2.1577 \pm 0.0002\text{sec}$\\$
\phi_0= 21.98 \pm 0.03\text{rad}
$
\end{center}
The specific equation for this fit is thus:
\begin{equation}
\theta(t) = 1.28e^{t/240}\cos(2\pi\frac t{2.1577} + 21.98)
\end{equation}
\subsubsection{Calculating Q Factor}
\begin{equation}
\label{eqn:Q1calc}
Q1 = \pi \frac \tau T =\pi*\frac{242.01}{2.1577} = 350 \pm 30
\end{equation}
\begin{equation}
\label{eqn:Q2calc}
\theta_Q = \theta_0*e^{-\pi/2} = 0.295\pm0.009\text{rad}
\end{equation}
The above amplitude occurs after 126 full oscillations, meaning that according to Equation \ref{eqn:Q2}, $Q2 = 352$.\medskip\\
Given that $Q2$ is well within the uncertainty of $Q1$, I am \emph{very} confident about the accuracy of this number.
\pagebreak
\subsection{Amplitude vs Period}
\label{section:q3}
\subsubsection{Graphs}
\begin{figure}[h]
\centering
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{q3_fit.png}
\caption{Fit of amplitude vs period to power series (see Section \ref{section:q3fit}).}
\label{fig:q3fit}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{q3_residuals.png}
\caption{Residuals of fit.}
\label{fig:q3residuals}
\end{subfigure}
\hfill
\caption{Pendulum swing data (2030g, 34.25"). \\Note that error bars are visible, but again \emph{very} small.}
\label{fig:q3fig}
\end{figure}
\subsubsection{Power Series Fit}
\label{section:q3fit}
The pendulum's period over varying initial amplitude bounded by $\theta_0 \approx [-\pi/2,\pi/2]$rad is shown in Figure \ref{fig:q3fit}, along with the fit of a power series as described in Equation \ref{eqn:powerseries}.
The specific values found by the curve fitting function are as follows:
\begin{center}
$
A= 2.05 \pm 0.01\text{sec}
$\\
$
B= 0.006 \pm 0.01 \frac {\text{sec}}{\text{rad}}\approx 0$\\
$
C= 0.11 \pm 0.02\frac {\text{sec}}{\text{rad}^2}
$
\end{center}
The specific equation for this fit is thus:
\begin{equation}
T = 2.05 + 0.11\theta_0^2
\end{equation}
\subsubsection{Symmetry Test}
Given that the value of $B$ is less than its uncertainty, it can be said to be "experimentally zero".
As such, my pendulum passes the "asymmetry test", and is sufficiently symmetrical for further experimentation.\medskip\\
\pagebreak
\subsection{Length vs Period}
\label{section:q4a}
\subsubsection{Graphs}
\begin{figure}[h]
\centering
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{q4a_fit.png}
\caption{Fit of length vs period to power series (see Section \ref{section:q4afit}).}
\label{fig:q4afit}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{q4a_residuals.png}
\caption{Residuals of fit.}
\label{fig:q4aresiduals}
\end{subfigure}
\label{fig:q4afig}
\end{figure}
\begin{figure}[h]
\centering
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{q4a_logfit.png}
\caption{Fit of data to power law (see Section \ref{section:q4afit}, logarithmic axes).}
\label{fig:q4alogfit}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{q4a_logresiduals.png}
\caption{Residuals of fit (logarithmic axes).}
\label{fig:q4alogresiduals}
\end{subfigure}
\hfill
\caption{Pendulum swing data (2030g) for varying lengths (44.75", 39", 34.25", 29", 25.25"). Note that residuals are far smaller than uncertainties.}
\label{fig:q4alogfig}
\end{figure}
\subsubsection{Power Law Fit}
\label{section:q4afit}
The pendulum's period over varying length bounded by $L = [44.75, 39, 34.25, 29, 25.25]$ inches, or\\
$L=[1.137, 0.991, 0.870, 0.737, 0.641]$ meters is shown in Figure \ref{fig:q4afit}, along with the fit of a power law function as described in Equation \ref{eqn:powerlaw}.
The specific values found by the curve fitting function are as follows:
\begin{center}
$
k= 1.12 \pm 0.09
$\\
$
L_0= -0.2 \pm 0.2 \text{m}\approx 0$\\
$
n= 0.4 \pm 0.1
$
\end{center}
The specific equation for this fit is thus:
\begin{equation}
T = 1.12L^{0.4}
\end{equation}
\subsubsection{Accuracy}
The exponent $n$ seems to be farther from $1/2$ than anticipated. When k is removed from the curve fitting parameters and fixed to 1:\\
$L_0: 0.06940995886640021$
$n: 0.5304151670699991$
$n$ is much closer to $1/2$, and $L_0$ is actually \emph{smaller} in magnitude. Since the addition of a coefficient makes the results less accurate to theory, perhaps more data points would have made the fit better.
\subsection{Period vs Mass}
\label{section:q4b}
\subsubsection{Graphs - Motion for Varying Mass}
\begin{figure}[h]
\centering
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=6cm,height=6cm, keepaspectratio]{q4b_fit1.png}
\caption{Fit of pendulum motion with mass \textbf{2032g} to decaying sinusoid (see Section \ref{section:q2fit}).}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=6cm,height=6cm, keepaspectratio]{q4b_residuals1.png}
\caption{Residuals of fit.}
\end{subfigure}
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=6cm,height=6cm, keepaspectratio]{q4b_fit2.png}
\caption{Fit of pendulum motion with mass \textbf{1784g} to decaying sinusoid (see Section \ref{section:q2fit}).}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=6cm,height=6cm, keepaspectratio]{q4b_residuals2.png}
\caption{Residuals of fit.}
\end{subfigure}
\label{fig:q4bfig1}
\caption{Pendulum motion for varying mass, group 1.}
\end{figure}
\pagebreak
\begin{figure}[h]
\centering
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{q4b_fit3.png}
\caption{Fit of pendulum motion with mass \textbf{1607g} to decaying sinusoid (see Section \ref{section:q2fit}).}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{q4b_residuals3.png}
\caption{Residuals of fit.}
\end{subfigure}
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=6cm,height=6cm, keepaspectratio]{q4b_fit4.png}
\caption{Fit of pendulum motion with mass \textbf{1366g} to decaying sinusoid (see Section \ref{section:q2fit}).}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=6cm,height=6cm, keepaspectratio]{q4b_residuals4.png}
\caption{Residuals of fit.}
\end{subfigure}
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=6cm,height=6cm, keepaspectratio]{q4b_fit5.png}
\caption{Fit of pendulum motion with mass \textbf{1012g} to decaying sinusoid (see Section \ref{section:q2fit}).}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=6cm,height=6cm, keepaspectratio]{q4b_residuals5.png}
\caption{Residuals of fit.}
\end{subfigure}
\hfill
\caption{Pendulum motion for varying mass, group 2.}
\label{fig:q4bfig2}
\end{figure}
\pagebreak
\subsubsection{Period for Varying Mass}
\label{section:q4bsummary}
When the period is found for the pendulum with varying mass, values for $~\tau$ and $T$ are found, and are displayed in the following table:
\begin{center}
\begin{tabular}{||c c c c c c||}
\hline
Trial \# & Mass (g) & T (sec) & T' ($\pm$sec) & $\tau$ (sec$^{-1}$) & $\tau'$ ($\pm$sec$^{-1}$) \\ [0.5ex]
\hline\hline
1 & 2032 & 1.939 & 0.001 & 150 & 40 \\
\hline
2 & 1784 & 1.945 & 0.001 & 200 & 100 \\
\hline
3 & 1607 & 1.9360 & 0.0006 & 200 & 40 \\
\hline
4 & 1366 & 1.9641 & 0.0009 & 300 & 100 \\
\hline
5 & 1012 & 1.9625 & 0.0009 & 130 & 30 \\ [1ex]
\hline
\end{tabular}
\end{center}
\noindent
Values for $\theta_0$ and $\phi_0$ are ignored, as they relate more to where in the oscillation the recording starts, rather than the properties of the oscillator.\\
\noindent
A fit for period vs mass can be found below.
\begin{figure}[h]
\centering
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{q4b_summaryfit.png}
\caption{Fit of period vs varying mass to power series (See Equation \ref{eqn:powerseries}).}
\label{fig:q4bfitsummary}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{q4b_summaryresiduals.png}
\caption{Residuals of fit.}
\label{fig:q4bresidualssummary}
\end{subfigure}
\label{fig:q4bfigsummary}
\end{figure}
\pagebreak
\subsubsection{Analysis}
\noindent
The power series fit (Equation \ref{eqn:powerseries}) for mass vs period in Section \ref{section:q4bsummary} produced the following values:
\begin{center}
$A= 2.01 \pm 0.10$\\
$B= -0.00005 \pm 0.0001 \approx 0$\\
$C= 6\times 10^{-9} \pm 4\times 10^{-8}\approx 0$
\end{center}
Both $B$ and $C$ are experimentally zero. In addition, the magnitudes of $C$ and $B$ are \emph{tiny} in comparison to the values being examined ($1.935\leq T \leq 1.985$), and the uncertainties for the data points lie far from the line of best fit.\\
\noindent
For these reasons, seems to be \emph{no correlation} (linear or quadratic) between bob mass and period of oscillation.
\section{Conclusion}
\label{section:conclusion}
In Section \ref{section:q2}, I found that the Q factor of this pendulum is $Q=350$. This speaks to a high quality pendulum, meaning that it does not dissipate energy very quickly, and is able to oscillate for a long period of time.
In Section \ref{section:q3}, I found that my pendulum is symmetrical. I also found that at amplitudes exceeding $\pm1.0$rad, the period begins to increase drastically.
In Section \ref{section:q4a}, I found that my pendulum obeys similar laws to those expected, with a periodicity proportional to the root of the string length.
In Section \ref{section:q4b}, I found that the period of my pendulum is not correlated to the bob mass.\\
Overall, the pendulum I have constructed seems to closely match the "ideal" pendulum.
\pagebreak
\appendix
\section{Supplementary Photos}
\label{section:setup}
\begin{figure}[h]
\centering
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=6cm,height=6cm,keepaspectratio]{camera.png}
\caption{View from the camera's perspective, showing the table as horizontal reference in the bottom of the camera viewport.}
\label{appendix:camera}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=6cm,height=6cm,keepaspectratio]{camerastand.png}
\caption{View from behind the camera stand, showing the orientation and placement of the entire setup.}
\label{appendix:camerastand}
\end{subfigure}
\newline
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=6cm,height=6cm,keepaspectratio,angle=270,origin=c]{setup.jpeg}
\caption{View showing the entire pendulum in equilibrium position. Note that this photo was taken \emph{before} additional length knots were added for Section \ref{section:q4a}.}
\label{appendix:setup}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=6cm,height=6cm,keepaspectratio]{table.jpeg}
\caption{View showing the pendulum in equilibrium position above the table marked with tape at 2ft intervals. Note that the equilibrium position lines up with the center of the table.}
\label{appendix:table}
\end{subfigure}
\hfill
\caption{Photos, group 1.}
\end{figure}
\pagebreak
\begin{figure}[h]
\centering
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=6cm,height=6cm,keepaspectratio,angle=270,origin=c]{scale.jpeg}
\caption{View showing the scale used to mass the bob for Section \ref{section:q4b}.}
\label{appendix:scale}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.48\textwidth}
\centering
\includegraphics[width=6cm,height=6cm,keepaspectratio]{motionblur.png}
\caption{View showing the motion blur induced by pendulum velocity at the apex when released from $\theta_0=\pi/2$. Note the length marking.}
\label{appendix:motionblur}
\end{subfigure}
\hfill
\caption{Photos, group 2.}
\end{figure}
\section{Python Scripts}
\label{appendix:scripts}
\noindent
All scripts have been moved to this project's GitHub repository, at \emph{https://github.com/JLefebvre55/PHY180-Pendulum}. You can find them named appropriately under the "scripts" folder.
\section{Data}
\noindent
On the next page is an example dataset for Section \ref{section:q2} on Q factor. It is abridged and precision-limited for demonstration. Full datasets can be found in the project repository, at \emph{https://github.com/JLefebvre55/PHY180-Pendulum}. You can find them named appropriately under the "data" folder.\medskip\\
\csvautotabular{abridged.csv}
\bibliographystyle{ieeetr}
\bibliography{references.bib}
\end{document} |
/-
Copyright (c) Ian Riley. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ian Riley
-/
constant Ill : Prop -- indeterminate "ill-defined" proposition
constant Nil : Prop -- null proposition
constant Undfn : Prop -- undefined proposition ; not within scope
notation `γ₀` := Ill -- γ₀ \gamma\zero
notation `ω₀` := Nil -- ω₀ \omega\zero
notation `Υ₀` := Undfn -- Υ₀ \Upsilon\zero
/-
Mapping of a variable name to an assertion about that variable.
The Prop type has been selected for a few reasons :
(a) Most efficient Type (Sort 0) to generalize over program data types. An
inductive type can't be eliminated without multiple intermediate steps,
which inflates the resulting proof.
(b) Using a Prop types lifts program data types to the level of a
proposition, so that we can better employ existing Lean libraries as well
as define new libraries over a single Prop type.
(c) In addition, using a Prop type retains variables as propositional
variables in both hypotheses and goals for later analysis.
The term 'scope' is used rather than the traditional term 'state'. There is
an existing 'state' type in Lean core. In addition, the use of 'scope' implies
a distinction about its propositions that is not commonly emphasized. The
propositions are not assertions about the state of the program but about the
state of the currently accessible scope.
-/
def scope := Π (name : string), Prop -- Π \Pi
@[simp] def scope.update (name : string) (val : Prop) (s : scope) : scope :=
λ (name' : string), if name' = name then val else s name' -- λ \lam
@[simp] def empty.scope := (λ (_ : string), Υ₀)
notation s `{` name ` ↦ ` val `}` := scope.update name val s -- ↦ \mapsto
notation `[∅]` := empty.scope -- ∅ \empty
notation `[` name ` ↦ ` val `]` := scope.update name val [∅]
/-
Instructions for how to use scope and its notation
The type of scope is string → Prop . It is defined as Π (name : string), Prop
to emphasize that instances of scope are defined using λ-expressions. We use
the informal notation [x ↦ 0, y ↦ 8] to refer to the scope where the
program variable x has value 0 and the program variable y has value 8.
This same scope can be implemented in Lean using the following λ-expression.
CORRECT
(λ {x y : ℕ} (name : string), if name = "x" then (x = 0) else
if name = "y" then (y = 8) else Υ₀)
Since the type of scope is string → Prop , we must take extra care when
inserting data types such as ℕ, ℤ, ℝ, bool, char, and string into a scope. The
following λ-expression is incorrect for the scope [x ↦ 0, y ↦ 8].
INCORRECT
(λ {x y : ℕ} (name : string), if name = "x" then 0 else
if name = "y" then 8 else 0)
The values of x and y returned by the above λ-expression are not Prop; they are
ℕ. In Lean, Prop is of type Sort 0, while ℕ is of type Type. These types,
Sort 0 and Type, are not compatible. Therefore, to include the value of x
into a scope, rather than including its value into the scope, we must include
an assertion about its value. Thus, we must use (x = 0) rather than 0 when
asserting that the value of program variable x is 0 in the current scope.
By constructing scopes this way, we have mapped the common understanding of a
scope (a mapping of variables to values) to a more formal understanding of a
scope (a mapping of propositional variables to propositions). Thus, the scope
[x ↦ 0, y ↦ 8] becomes [Px ↦ (x = 0), Py ↦ (y = 8)], where Px and Py are the
propositional variables related to program variables x and y, respectively.
Our motivation for using this construction is to define a scope that can
include assertions about program variables of different types. In Lean,
the following λ-expression is prohibited.
INVALID
(λ {x y : ℕ} (name : string), if name = "x" then 0 else
if name = "y" then "hello" else Υ₀)
This λ-expression is prohibited because it has three distinct types depending
on the value of name. If name = "x", then the λ-expression has type string → ℕ.
If name = "y", then the λ-expression has type string → string. Otherwise,
it has type string → Prop. Lean's type checker cannot determine the type of
this λ-expression without knowing the value of the input parameter name, so
this expression has been prohibited.
The most basic scope provided by this library is the empty scope, defined as
[∅], which is a scope where every propositional variable is mapped to the
proposition Υ₀ (undefined). The proposition Υ₀ is used to indicate that a
propositional variable has no corresponding proposition. Seeing Υ₀ in a proof
is generally considered to be an indication that the proof state is incorrect
and that any resulting proof would be invalid.
Note: Propositions γ₀ (ill-defined) and ω₀ (null) are also provided. γ₀ is used
to indicate a propositional variable that has an indeterminate proposition.
This occurs when a program variable is modified non-deterministically. In such
cases, γ₀ should be used when the propositional variable can be any proposition
of an infinite set of propositions or a finite set of unknown propositions. If
there is a finite set of known propositions, then a disjunction can be used
rather γ₀. The ω₀ proposition is provided to represent program variables that
can be assigned the null value or its equivalent (nil, option.none, etc.).
A scope, such as [x ↦ 8] (which we know to be [Px ↦ (x = 8)]), can be defined
in Lean using the following notation, ["x" ↦ (x = 8)]. This notation applies
to the scope.update definition to the empty scope using "x" and (x = 8) as
its other inputs. By doing so, the propositional variable Px, denoted "x", maps
to the proposition (x = 8), while all other propositional variables are
undefined. Note that the left-hand side of ↦ (\mapsto) must be a string.
Given a scope s with propositional variable "x", the proposition of "x" can be
updated using the following notation, s{"x" ↦ (x = 0)}. This updates the
proposition of "x" to be the proposition (x = 0). Thus, we can represent
changes to program variables using this notation.
Given a scope s with only propositional variable "x", we can include a new
proposition for propositional variable "y" in s using the same notation
as before, s{"y" ↦ (y = 5)}. This, in essence, updates the proposition of
propositional variable "y" from Υ₀ to (y = 5), which asserts that the program
variable y has a value of 5. This notation can be used to insert a new
propositional variable into any scope.
As a final important note, it should be stressed that, since we are utilizing
Prop as the implied type of scope, we must approach lemmas and theorems
differently than we would otherwise. For example, the following lemmas would
be, at worst, invalid and, at best, illicit.
INVALID
example {x : ℕ} (s : ["x" ↦ (x = 0)]) : (x = 0)
example {x : ℕ} (s : ["x" ↦ (x = 0)]) : (s "x")
Each lemma presented above is, by equivalence, an assertion about the value of
program variable x given the scope s. While we can clearly see that the goals
are each a proposition within the stated scope, we cannot make such claims
about a scope.
In Lean terms, scope is defined as a proof of propositions of the
form string → Prop. The goals of the above examples are each of type Prop
and the stated hypothesis in each example is a particular proof of
one string → Prop. If we are attempting to construct a proof that a
particular Prop follows from a particular proof of string → Prop, then we
should rightfully inquire what string justifies such a proof. We can easily
tell that the string "x" justifies the proof. However, given the proof
construction, can we be justified in saying that there is such a string "x"? No.
That a string "x" could exist is not the same as stating that the string "x"
does exist in the current proof context. The following constructions would
be more appropriate.
example {x : ℕ} (s : ["x" ↦ (x = 0)]) : ∃ name, name → (x = 0)
example {x : ℕ} (s : ["x" ↦ (x = 0)]) : ∀ name, (name = "x") → (x = 0)
Once we have incorporated this understanding into our proof construction, there
is one last hiccup that we must avoid. The following construction would also
be invalid.
INVALID
example {x : ℕ} (s : ["x" ↦ (x = 0)]) (name : string) : (name = "x") → 0
The example above is invalid because it's a claim about a particular value of
the program variable x. In this case, the value 0, which is a ℕ. However,
for x to have the value 0, there must a program variable x. While the
construction above asserts the existence of a name with value "x", it does
not assert the existence of a program variable x. As such, while we can
assert (x = 0), 0 does not follow from (x = 0) unless we can also assert the
existence of x. We must continue to remember that the definition of scope
asserts propositions about program variables rather than their exact value.
The following construction would be more appropriate.
example {x : ℕ} (s : ["x" ↦ (x = 0)]) (name : _) (x' : x): (name = "x") → 0
The primary lesson that we can take away from these examples is that a scope
does not imply the existence of its constituent propositional variables or the
existence of program variables. This error in thinking will often arise if
scope is treated as a data structure, as a map/dictionary or as a list.
It is neither. In Lean, a scope is a family of proofs.
The following examples illustrate the suggested approach to verify assertions
about program variables.
CORRECT
example {x : ℕ} : (∃ s, s "x" → (x = 0))
example {x : ℕ} : (∃ s, s "x" = (x = 0))
example {x : ℕ} : (∀ s, (s = ["x" ↦ (x = 0)]) → (s "x" → (x = 0)))
example {x : ℕ} : (∀ s, (s = ["x" ↦ (x = 0)]) → (s "x" = (x = 0)))
The above examples are an assertion about a particular propositional variable
in a scope. They are essentially asking whether the particular
proof ["x" ↦ (x = 0)] in the family of proofs (represented by scope) is
the proof s "x" = (x = 0), which is a valid and licit inquiry.
-/
namespace scope
meta def tactic.dec_trivial := `[exact dec_trivial]
@[simp] lemma update_apply (name : string) (val : Prop) (s : scope) :
s{name ↦ val} name = val := if_pos rfl
@[simp] lemma update_apply_ne (name name' : string) (val : Prop)
(s : scope) (hname : name' ≠ name . tactic.dec_trivial) :
s{name ↦ val} name' = s name' := if_neg hname
@[simp] lemma update_id (name : string) (s : scope) :
s{name ↦ s name} = s :=
begin
apply funext,
intro name',
by_cases name' = name,
{
rw h,
exact update_apply name (s name) s,
},
{
apply update_apply_ne,
exact h,
}
end
@[simp] lemma update_squash (name : string) (val₁ val₂ : Prop)
(s : scope) : s{name ↦ val₂}{name ↦ val₁} = s{name ↦ val₁} :=
begin
apply funext,
intro name',
by_cases name' = name,
{
rw h,
repeat {rw update_apply},
},
{
repeat {rw update_apply_ne name name' _ _ h},
}
end
@[simp] lemma update_swap (name₁ name₂ : string) (val₁ val₂ : Prop)
(s: scope) (hname : name₁ ≠ name₂ . tactic.dec_trivial) :
s{name₂ ↦ val₂}{name₁ ↦ val₁} = s{name₁ ↦ val₁}{name₂ ↦ val₂} :=
begin
apply funext,
intro name',
by_cases name' = name₁; have h₁ := h;
by_cases name' = name₂; have h₂ := h,
{
exfalso,
apply hname,
rw h₁ at h₂,
exact h₂,
},
{
rw h₁,
rw update_apply,
rw update_apply_ne _ _ _ _ hname,
rw update_apply,
},
{
rw h₂,
rw update_apply,
have hname := ne.symm hname,
rw update_apply_ne _ _ _ _ hname,
rw update_apply,
},
{
rw update_apply_ne _ _ _ _ h₁,
rw update_apply_ne _ _ _ _ h₂,
rw update_apply_ne _ _ _ _ h₂,
rw update_apply_ne _ _ _ _ h₁,
}
end
end scope
|
{-# OPTIONS --safe --warning=error --without-K #-}
open import Setoids.Setoids
open import Sets.EquivalenceRelations
open import Rings.Definition
module Rings.Ideals.Principal.Lemmas {a b : _} {A : Set a} {S : Setoid {a} {b} A} {_+_ _*_ : A → A → A} (R : Ring S _+_ _*_) where
open Setoid S
open Ring R
open Equivalence eq
open import Rings.Ideals.Principal.Definition R
open import Rings.Ideals.Definition R
open import Rings.Ideals.Lemmas R
open import Rings.Divisible.Definition R
generatorZeroImpliesAllZero : {c : _} {pred : A → Set c} → {i : Ideal pred} → (princ : PrincipalIdeal i) → PrincipalIdeal.generator princ ∼ 0R → {x : A} → pred x → x ∼ 0R
generatorZeroImpliesAllZero record { generator = gen ; genIsInIdeal = genIsInIdeal ; genGenerates = genGenerates } gen=0 {x} predX = generatorZeroImpliesMembersZero {x} (divisibleWellDefined gen=0 reflexive (genGenerates predX))
|
[STATEMENT]
lemma subst_fm_UnionP [simp]:
"(UnionP x y z)(i::=u) = UnionP (subst i u x) (subst i u y) (subst i u z)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (UnionP x y z)(i::=u) = UnionP (subst i u x) (subst i u y) (subst i u z)
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. (UnionP x y z)(i::=u) = UnionP (subst i u x) (subst i u y) (subst i u z)
[PROOF STEP]
obtain j::name where "atom j \<sharp> (x,y,z,i,u)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>j. atom j \<sharp> (x, y, z, i, u) \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (metis obtain_fresh)
[PROOF STATE]
proof (state)
this:
atom j \<sharp> (x, y, z, i, u)
goal (1 subgoal):
1. (UnionP x y z)(i::=u) = UnionP (subst i u x) (subst i u y) (subst i u z)
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
atom j \<sharp> (x, y, z, i, u)
goal (1 subgoal):
1. (UnionP x y z)(i::=u) = UnionP (subst i u x) (subst i u y) (subst i u z)
[PROOF STEP]
by (auto simp: UnionP.simps [of j])
[PROOF STATE]
proof (state)
this:
(UnionP x y z)(i::=u) = UnionP (subst i u x) (subst i u y) (subst i u z)
goal:
No subgoals!
[PROOF STEP]
qed |
% !TeX root = 00Book.tex
\subsection{July: Honey Production}
|
module TakeDropDec where
import Relation.Binary.PropositionalEquality as Eq
open Eq using (_≡_; refl; sym; trans; cong; cong₂; _≢_)
open import Data.Empty using (⊥; ⊥-elim)
open import Data.List using (List; []; _∷_)
open import Data.List.All using (All; []; _∷_)
open import Data.Bool using (Bool; true; false; T)
open import Data.Unit using (⊤; tt)
open import Relation.Nullary using (¬_; Dec; yes; no)
open import Relation.Nullary.Decidable using ()
open import Function using (_∘_)
module TakeDrop {A : Set} {P : A → Set} (P? : ∀ (x : A) → Dec (P x)) where
takeWhile : List A → List A
takeWhile [] = []
takeWhile (x ∷ xs) with P? x
... | yes _ = x ∷ takeWhile xs
... | no _ = []
dropWhile : List A → List A
dropWhile [] = []
dropWhile (x ∷ xs) with P? x
... | yes _ = dropWhile xs
... | no _ = x ∷ xs
Head : (A → Set) → List A → Set
Head P [] = ⊥
Head P (x ∷ xs) = P x
takeWhile-lemma : ∀ (xs : List A) → All P (takeWhile xs)
takeWhile-lemma [] = []
takeWhile-lemma (x ∷ xs) with P? x
... | yes px = px ∷ takeWhile-lemma xs
... | no _ = []
dropWhile-lemma : ∀ (xs : List A) → ¬ Head P (dropWhile xs)
dropWhile-lemma [] = λ()
dropWhile-lemma (x ∷ xs) with P? x
... | yes _ = dropWhile-lemma xs
... | no ¬px = ¬px
open TakeDrop
open import Data.Nat using (ℕ; zero; suc; _≟_)
_ : takeWhile (0 ≟_) (0 ∷ 0 ∷ 1 ∷ []) ≡ (0 ∷ 0 ∷ [])
_ = refl
_ : dropWhile (0 ≟_) (0 ∷ 0 ∷ 1 ∷ []) ≡ (1 ∷ [])
_ = refl
|
# This file is a part of Julia. License is MIT: https://julialang.org/license
module API
using UUIDs
using Printf
import Random
import Dates
import LibGit2
import ..depots, ..depots1, ..logdir, ..devdir
import ..Operations, ..Display, ..GitTools, ..Pkg, ..UPDATED_REGISTRY_THIS_SESSION
using ..Types, ..TOML
using Pkg.Types: VersionTypes
preview_info() = printstyled("───── Preview mode ─────\n"; color=Base.info_color(), bold=true)
include("generate.jl")
function check_package_name(x::AbstractString, mode=nothing)
if !(occursin(Pkg.REPLMode.name_re, x))
message = "$x is not a valid packagename."
if mode !== nothing && any(occursin.(['\\','/'], x)) # maybe a url or a path
message *= "\nThe argument appears to be a URL or path, perhaps you meant " *
"`Pkg.$mode(PackageSpec(url=\"...\"))` or `Pkg.$mode(PackageSpec(path=\"...\"))`."
end
pkgerror(message)
end
return PackageSpec(x)
end
develop(pkg::Union{AbstractString, PackageSpec}; kwargs...) = develop([pkg]; kwargs...)
develop(pkgs::Vector{<:AbstractString}; kwargs...) =
develop([check_package_name(pkg, :develop) for pkg in pkgs]; kwargs...)
develop(pkgs::Vector{PackageSpec}; kwargs...) = develop(Context(), pkgs; kwargs...)
function develop(ctx::Context, pkgs::Vector{PackageSpec};
shared::Bool=true, strict::Bool=false, kwargs...)
pkgs = deepcopy(pkgs) # deepcopy for avoid mutating PackageSpec members
Context!(ctx; kwargs...)
for pkg in pkgs
# if julia is passed as a package the solver gets tricked
pkg.name != "julia" || pkgerror("Trying to develop julia as a package")
pkg.repo.rev === nothing || pkgerror("git revision can not be given to `develop`")
pkg.name !== nothing || pkg.uuid !== nothing || pkg.repo.url !== nothing ||
pkgerror("A package must be specified by `name`, `uuid`, `url`, or `path`.")
pkg.version == VersionSpec() ||
pkgerror("Can not specify version when tracking a repo.")
end
ctx.preview && preview_info()
new_git = handle_repos_develop!(ctx, pkgs, shared)
any(pkg -> Types.collides_with_project(ctx.env, pkg), pkgs) &&
pkgerror("Cannot `develop` package with the same name or uuid as the project")
Operations.develop(ctx, pkgs, new_git; strict=strict)
ctx.preview && preview_info()
return
end
add(pkg::Union{AbstractString, PackageSpec}; kwargs...) = add([pkg]; kwargs...)
add(pkgs::Vector{<:AbstractString}; kwargs...) =
add([check_package_name(pkg, :add) for pkg in pkgs]; kwargs...)
add(pkgs::Vector{PackageSpec}; kwargs...) = add(Context(), pkgs; kwargs...)
function add(ctx::Context, pkgs::Vector{PackageSpec}; strict::Bool=false, kwargs...)
pkgs = deepcopy(pkgs) # deepcopy for avoid mutating PackageSpec members
Context!(ctx; kwargs...)
for pkg in pkgs
# if julia is passed as a package the solver gets tricked; this catches the error early on
pkg.name == "julia" && pkgerror("Trying to add julia as a package")
pkg.name !== nothing || pkg.uuid !== nothing || pkg.repo.url !== nothing ||
pkgerror("A package must be specified by `name`, `uuid`, `url`, or `path`.")
if (pkg.repo.url !== nothing || pkg.repo.rev !== nothing)
pkg.version == VersionSpec() ||
pkgerror("Can not specify version when tracking a repo.")
end
end
ctx.preview && preview_info()
Types.update_registries(ctx)
repo_pkgs = [pkg for pkg in pkgs if (pkg.repo.url !== nothing || pkg.repo.rev !== nothing)]
new_git = handle_repos_add!(ctx, repo_pkgs)
# repo + unpinned -> name, uuid, repo.rev, repo.url, tree_hash
# repo + pinned -> name, uuid, tree_hash
project_deps_resolve!(ctx.env, pkgs)
registry_resolve!(ctx.env, pkgs)
stdlib_resolve!(ctx, pkgs)
ensure_resolved(ctx.env, pkgs, registry=true)
any(pkg -> Types.collides_with_project(ctx.env, pkg), pkgs) &&
pkgerror("Cannot add package with the same name or uuid as the project")
Operations.add(ctx, pkgs, new_git; strict=strict)
ctx.preview && preview_info()
return
end
rm(pkg::Union{AbstractString, PackageSpec}; kwargs...) = rm([pkg]; kwargs...)
rm(pkgs::Vector{<:AbstractString}; kwargs...) = rm([PackageSpec(pkg) for pkg in pkgs]; kwargs...)
rm(pkgs::Vector{PackageSpec}; kwargs...) = rm(Context(), pkgs; kwargs...)
function rm(ctx::Context, pkgs::Vector{PackageSpec}; mode=PKGMODE_PROJECT, kwargs...)
pkgs = deepcopy(pkgs) # deepcopy for avoid mutating PackageSpec members
foreach(pkg -> pkg.mode = mode, pkgs)
for pkg in pkgs
pkg.name !== nothing || pkg.uuid !== nothing ||
pkgerror("Must specify package by either `name` or `uuid`.")
if !(pkg.version == VersionSpec() && pkg.pinned == false &&
pkg.tree_hash === nothing && pkg.repo.url === nothing &&
pkg.repo.rev === nothing && pkg.path === nothing)
pkgerror("Package may only be specified by either `name` or `uuid`")
end
end
Context!(ctx; kwargs...)
ctx.preview && preview_info()
project_deps_resolve!(ctx.env, pkgs)
manifest_resolve!(ctx.env, pkgs)
ensure_resolved(ctx.env, pkgs)
Operations.rm(ctx, pkgs)
ctx.preview && preview_info()
return
end
up(ctx::Context; kwargs...) = up(ctx, PackageSpec[]; kwargs...)
up(; kwargs...) = up(PackageSpec[]; kwargs...)
up(pkg::Union{AbstractString, PackageSpec}; kwargs...) = up([pkg]; kwargs...)
up(pkgs::Vector{<:AbstractString}; kwargs...) = up([PackageSpec(pkg) for pkg in pkgs]; kwargs...)
up(pkgs::Vector{PackageSpec}; kwargs...) = up(Context(), pkgs; kwargs...)
function up(ctx::Context, pkgs::Vector{PackageSpec};
level::UpgradeLevel=UPLEVEL_MAJOR, mode::PackageMode=PKGMODE_PROJECT,
update_registry::Bool=true, kwargs...)
pkgs = deepcopy(pkgs) # deepcopy for avoid mutating PackageSpec members
foreach(pkg -> pkg.mode = mode, pkgs)
Context!(ctx; kwargs...)
ctx.preview && preview_info()
if update_registry
Types.clone_default_registries()
Types.update_registries(ctx; force=true)
end
if isempty(pkgs)
if mode == PKGMODE_PROJECT
for (name::String, uuid::UUID) in ctx.env.project.deps
push!(pkgs, PackageSpec(name=name, uuid=uuid))
end
elseif mode == PKGMODE_MANIFEST
for (uuid, entry) in ctx.env.manifest
push!(pkgs, PackageSpec(name=entry.name, uuid=uuid))
end
end
else
project_deps_resolve!(ctx.env, pkgs)
manifest_resolve!(ctx.env, pkgs)
ensure_resolved(ctx.env, pkgs)
end
Operations.up(ctx, pkgs, level)
ctx.preview && preview_info()
return
end
resolve(ctx::Context=Context()) =
up(ctx, level=UPLEVEL_FIXED, mode=PKGMODE_MANIFEST, update_registry=false)
pin(pkg::Union{AbstractString, PackageSpec}; kwargs...) = pin([pkg]; kwargs...)
pin(pkgs::Vector{<:AbstractString}; kwargs...) = pin([PackageSpec(pkg) for pkg in pkgs]; kwargs...)
pin(pkgs::Vector{PackageSpec}; kwargs...) = pin(Context(), pkgs; kwargs...)
function pin(ctx::Context, pkgs::Vector{PackageSpec}; kwargs...)
pkgs = deepcopy(pkgs) # deepcopy for avoid mutating PackageSpec members
Context!(ctx; kwargs...)
ctx.preview && preview_info()
for pkg in pkgs
pkg.name !== nothing || pkg.uuid !== nothing ||
pkgerror("Must specify package by either `name` or `uuid`.")
pkg.repo.url === nothing || pkgerror("Can not specify `repo` url")
pkg.repo.rev === nothing || pkgerror("Can not specify `repo` rev")
end
foreach(pkg -> pkg.mode = PKGMODE_PROJECT, pkgs)
project_deps_resolve!(ctx.env, pkgs)
ensure_resolved(ctx.env, pkgs)
Operations.pin(ctx, pkgs)
return
end
free(pkg::Union{AbstractString, PackageSpec}; kwargs...) = free([pkg]; kwargs...)
free(pkgs::Vector{<:AbstractString}; kwargs...) = free([PackageSpec(pkg) for pkg in pkgs]; kwargs...)
free(pkgs::Vector{PackageSpec}; kwargs...) = free(Context(), pkgs; kwargs...)
function free(ctx::Context, pkgs::Vector{PackageSpec}; kwargs...)
pkgs = deepcopy(pkgs) # deepcopy for avoid mutating PackageSpec members
Context!(ctx; kwargs...)
ctx.preview && preview_info()
for pkg in pkgs
pkg.name !== nothing || pkg.uuid !== nothing ||
pkgerror("Must specify package by either `name` or `uuid`.")
if !(pkg.version == VersionSpec() && pkg.pinned == false &&
pkg.tree_hash === nothing && pkg.repo.url === nothing &&
pkg.repo.rev === nothing && pkg.path === nothing)
pkgerror("Package may only be specified by either `name` or `uuid`")
end
end
foreach(pkg -> pkg.mode = PKGMODE_MANIFEST, pkgs)
manifest_resolve!(ctx.env, pkgs)
ensure_resolved(ctx.env, pkgs)
find_registered!(ctx.env, UUID[pkg.uuid for pkg in pkgs])
Operations.free(ctx, pkgs)
return
end
test(;kwargs...) = test(PackageSpec[]; kwargs...)
test(pkg::Union{AbstractString, PackageSpec}; kwargs...) = test([pkg]; kwargs...)
test(pkgs::Vector{<:AbstractString}; kwargs...) = test([PackageSpec(pkg) for pkg in pkgs]; kwargs...)
test(pkgs::Vector{PackageSpec}; kwargs...) = test(Context(), pkgs; kwargs...)
function test(ctx::Context, pkgs::Vector{PackageSpec};
coverage=false, test_fn=nothing,
julia_args::Cmd=``,
test_args::Cmd=``, kwargs...)
pkgs = deepcopy(pkgs) # deepcopy for avoid mutating PackageSpec members
Context!(ctx; kwargs...)
ctx.preview && preview_info()
if isempty(pkgs)
ctx.env.pkg === nothing && pkgerror("trying to test unnamed project") #TODO Allow this?
push!(pkgs, ctx.env.pkg)
else
project_resolve!(ctx.env, pkgs)
project_deps_resolve!(ctx.env, pkgs)
manifest_resolve!(ctx.env, pkgs)
ensure_resolved(ctx.env, pkgs)
end
Operations.test(ctx, pkgs; coverage=coverage, test_fn=test_fn, julia_args=julia_args, test_args=test_args)
return
end
installed() = __installed(PKGMODE_PROJECT)
function __installed(mode::PackageMode=PKGMODE_MANIFEST)
diffs = Display.status(Context(), PackageSpec[], mode=mode, use_as_api=true)
version_status = Dict{String, Union{VersionNumber,Nothing}}()
diffs == nothing && return version_status
for entry in diffs
version_status[entry.name] = entry.new.ver
end
return version_status
end
function gc(ctx::Context=Context(); kwargs...)
Context!(ctx; kwargs...)
ctx.preview && preview_info()
env = ctx.env
# If the manifest was not used
usage_file = joinpath(logdir(), "manifest_usage.toml")
# Collect only the manifest that is least recently used
manifest_date = Dict{String, Dates.DateTime}()
for (manifest_file, infos) in TOML.parse(String(read(usage_file)))
for info in infos
date = info["time"]
manifest_date[manifest_file] = haskey(manifest_date, date) ? max(manifest_date[date], date) : date
end
end
# Find all reachable packages through manifests recently used
new_usage = Dict{String, Any}()
paths_to_keep = String[]
printpkgstyle(ctx, :Active, "manifests:")
for (manifestfile, date) in manifest_date
!isfile(manifestfile) && continue
println(" $(Types.pathrepr(manifestfile))")
manifest = try
read_manifest(manifestfile)
catch e
@warn "Reading manifest file at $manifestfile failed with error" exception = e
nothing
end
manifest == nothing && continue
new_usage[manifestfile] = [Dict("time" => date)]
for (uuid, entry) in manifest
if entry.tree_hash !== nothing
push!(paths_to_keep,
Operations.find_installed(entry.name, uuid, entry.tree_hash))
end
end
end
# Collect the paths to delete (everything that is not reachable)
paths_to_delete = String[]
for depot in depots()
packagedir = abspath(depot, "packages")
if isdir(packagedir)
for name in readdir(packagedir)
if isdir(joinpath(packagedir, name))
for slug in readdir(joinpath(packagedir, name))
versiondir = joinpath(packagedir, name, slug)
if !(versiondir in paths_to_keep) && isdir(versiondir)
push!(paths_to_delete, versiondir)
end
end
end
end
end
end
pretty_byte_str = (size) -> begin
bytes, mb = Base.prettyprint_getunits(size, length(Base._mem_units), Int64(1024))
return @sprintf("%.3f %s", bytes, Base._mem_units[mb])
end
# Delete paths for noreachable package versions and compute size saved
function recursive_dir_size(path)
size = 0
for (root, dirs, files) in walkdir(path)
for file in files
size += lstat(joinpath(root, file)).size
end
end
return size
end
sz = 0
for path in paths_to_delete
sz_pkg = recursive_dir_size(path)
if !ctx.preview
try
Base.rm(path; recursive=true)
catch
@warn "Failed to delete $path"
end
end
printpkgstyle(ctx, :Deleted, Types.pathrepr(path) * " (" * pretty_byte_str(sz_pkg) * ")")
sz += sz_pkg
end
# Delete package paths that are now empty
for depot in depots()
packagedir = abspath(depot, "packages")
if isdir(packagedir)
for name in readdir(packagedir)
name_path = joinpath(packagedir, name)
if isdir(name_path)
if isempty(readdir(name_path))
!ctx.preview && Base.rm(name_path)
end
end
end
end
end
# Write the new condensed usage file
if !ctx.preview
open(usage_file, "w") do io
TOML.print(io, new_usage, sorted=true)
end
end
ndel = length(paths_to_delete)
byte_save_str = ndel == 0 ? "" : (" (" * pretty_byte_str(sz) * ")")
printpkgstyle(ctx, :Deleted, "$(ndel) package installation$(ndel == 1 ? "" : "s")$byte_save_str")
ctx.preview && preview_info()
return
end
build(pkgs...; kwargs...) = build([PackageSpec(pkg) for pkg in pkgs]; kwargs...)
build(pkg::Array{Union{}, 1}; kwargs...) = build(PackageSpec[]; kwargs...)
build(pkg::PackageSpec; kwargs...) = build([pkg]; kwargs...)
build(pkgs::Vector{PackageSpec}; kwargs...) = build(Context(), pkgs; kwargs...)
function build(ctx::Context, pkgs::Vector{PackageSpec}; verbose=false, kwargs...)
pkgs = deepcopy(pkgs) # deepcopy for avoid mutating PackageSpec members
Context!(ctx; kwargs...)
ctx.preview && preview_info()
if isempty(pkgs)
if ctx.env.pkg !== nothing
push!(pkgs, ctx.env.pkg)
else
for (uuid, entry) in ctx.env.manifest
push!(pkgs, PackageSpec(entry.name, uuid))
end
end
end
project_resolve!(ctx.env, pkgs)
foreach(pkg -> pkg.mode = PKGMODE_MANIFEST, pkgs)
manifest_resolve!(ctx.env, pkgs)
ensure_resolved(ctx.env, pkgs)
Operations.build(ctx, pkgs, verbose)
end
#####################################
# Backwards compatibility with Pkg2 #
#####################################
function clone(url::String, name::String = "")
@warn "Pkg.clone is only kept for legacy CI script reasons, please use `add`" maxlog=1
ctx = Context()
if !isempty(name)
ctx.old_pkg2_clone_name = name
end
develop(ctx, [Pkg.REPLMode.parse_package_identifier(url; add_or_develop=true)])
end
function dir(pkg::String, paths::AbstractString...)
@warn "`Pkg.dir(pkgname, paths...)` is deprecated; instead, do `import $pkg; joinpath(dirname(pathof($pkg)), \"..\", paths...)`." maxlog=1
pkgid = Base.identify_package(pkg)
pkgid === nothing && return nothing
path = Base.locate_package(pkgid)
path === nothing && return nothing
return abspath(path, "..", "..", paths...)
end
precompile() = precompile(Context())
function precompile(ctx::Context)
printpkgstyle(ctx, :Precompiling, "project...")
pkgids = [Base.PkgId(uuid, name) for (name, uuid) in ctx.env.project.deps if !(uuid in keys(ctx.stdlibs))]
if ctx.env.pkg !== nothing && isfile( joinpath( dirname(ctx.env.project_file), "src", ctx.env.pkg.name * ".jl") )
push!(pkgids, Base.PkgId(ctx.env.pkg.uuid, ctx.env.pkg.name))
end
# TODO: since we are a complete list, but not topologically sorted, handling of recursion will be completely at random
for pkg in pkgids
paths = Base.find_all_in_cache_path(pkg)
sourcepath = Base.locate_package(pkg)
sourcepath == nothing && continue
# Heuristic for when precompilation is disabled
occursin(r"\b__precompile__\(\s*false\s*\)", read(sourcepath, String)) && continue
stale = true
for path_to_try in paths::Vector{String}
staledeps = Base.stale_cachefile(sourcepath, path_to_try)
staledeps === true && continue
# TODO: else, this returns a list of packages that may be loaded to make this valid (the topological list)
stale = false
break
end
if stale
printpkgstyle(ctx, :Precompiling, pkg.name)
try
Base.compilecache(pkg, sourcepath)
catch
end
end
end
nothing
end
instantiate(; kwargs...) = instantiate(Context(); kwargs...)
function instantiate(ctx::Context; manifest::Union{Bool, Nothing}=nothing,
update_registry::Bool=true, kwargs...)
Context!(ctx; kwargs...)
if (!isfile(ctx.env.manifest_file) && manifest == nothing) || manifest == false
up(ctx; update_registry=update_registry)
return
end
if !isfile(ctx.env.manifest_file) && manifest == true
pkgerror("manifest at $(ctx.env.manifest_file) does not exist")
end
Operations.prune_manifest(ctx.env)
for (name, uuid) in ctx.env.project.deps
get(ctx.env.manifest, uuid, nothing) === nothing || continue
pkgerror("`$name` is a direct dependency, but does not appear in the manifest.",
" If you intend `$name` to be a direct dependency, run `Pkg.resolve()` to populate the manifest.",
" Otherwise, remove `$name` with `Pkg.rm(\"$name\")`.",
" Finally, run `Pkg.instantiate()` again.")
end
Operations.is_instanitated(ctx) && return
Types.update_registries(ctx)
pkgs = PackageSpec[]
Operations.load_all_deps!(ctx, pkgs)
Operations.check_registered(ctx, pkgs)
new_git = UUID[]
for pkg in pkgs
pkg.repo.url !== nothing || continue
sourcepath = Operations.source_path(pkg)
isdir(sourcepath) && continue
# download repo at tree hash
push!(new_git, pkg.uuid)
clonepath = Types.clone_path!(pkg.repo.url)
tmp_source = Types.repo_checkout(clonepath, string(pkg.tree_hash))
mkpath(sourcepath)
mv(tmp_source, sourcepath; force=true)
end
new_apply = Operations.download_source(ctx, pkgs)
Operations.build_versions(ctx, union(new_apply, new_git))
end
@deprecate status(mode::PackageMode) status(mode=mode)
status(; kwargs...) = status(PackageSpec[]; kwargs...)
status(pkg::Union{AbstractString,PackageSpec}; kwargs...) = status([pkg]; kwargs...)
status(pkgs::Vector{<:AbstractString}; kwargs...) =
status([check_package_name(pkg) for pkg in pkgs]; kwargs...)
status(pkgs::Vector{PackageSpec}; kwargs...) = status(Context(), pkgs; kwargs...)
function status(ctx::Context, pkgs::Vector{PackageSpec}; diff::Bool=false, mode=PKGMODE_PROJECT)
project_resolve!(ctx.env, pkgs)
project_deps_resolve!(ctx.env, pkgs)
if mode === PKGMODE_MANIFEST
foreach(pkg -> pkg.mode = PKGMODE_MANIFEST, pkgs)
end
manifest_resolve!(ctx.env, pkgs)
ensure_resolved(ctx.env, pkgs)
Pkg.Display.status(ctx, pkgs, diff=diff, mode=mode)
return nothing
end
function activate()
Base.ACTIVE_PROJECT[] = nothing
p = Base.active_project()
p === nothing || printpkgstyle(Context(), :Activating, "environment at $(pathrepr(p))")
return nothing
end
function _activate_dep(dep_name::AbstractString)
Base.active_project() === nothing && return
env = nothing
try
env = EnvCache()
catch err
err isa PkgError || rethrow()
return
end
uuid = get(env.project.deps, dep_name, nothing)
if uuid !== nothing
entry = manifest_info(env, uuid)
if entry.path !== nothing
return joinpath(dirname(env.project_file), entry.path)
end
end
end
function activate(path::AbstractString; shared::Bool=false)
if !shared
# `pkg> activate path`/`Pkg.activate(path)` does the following
# 1. if path exists, activate that
# 2. if path exists in deps, and the dep is deved, activate that path (`devpath` above)
# 3. activate the non-existing directory (e.g. as in `pkg> activate .` for initing a new env)
if Types.isdir_windows_workaround(path)
fullpath = abspath(path)
else
fullpath = _activate_dep(path)
if fullpath === nothing
fullpath = abspath(path)
end
end
else
# initialize `fullpath` in case of empty `Pkg.depots()`
fullpath = ""
# loop over all depots to check if the shared environment already exists
for depot in Pkg.depots()
fullpath = joinpath(Pkg.envdir(depot), path)
isdir(fullpath) && break
end
# this disallows names such as "Foo/bar", ".", "..", etc
if basename(abspath(fullpath)) != path
pkgerror("not a valid name for a shared environment: $(path)")
end
# unless the shared environment already exists, place it in the first depots
if !isdir(fullpath)
fullpath = joinpath(Pkg.envdir(Pkg.depots1()), path)
end
end
Base.ACTIVE_PROJECT[] = Base.load_path_expand(fullpath)
p = Base.active_project()
if p !== nothing
n = ispath(p) ? "" : "new "
printpkgstyle(Context(), :Activating, "$(n)environment at $(pathrepr(p))")
end
return nothing
end
function setprotocol!(;
domain::AbstractString="github.com",
protocol::Union{Nothing, AbstractString}=nothing
)
GitTools.setprotocol!(domain=domain, protocol=protocol)
return nothing
end
@deprecate setprotocol!(proto::Union{Nothing, AbstractString}) setprotocol!(protocol = proto) false
# API constructor
function Package(;name::Union{Nothing,AbstractString} = nothing,
uuid::Union{Nothing,String,UUID} = nothing,
version::Union{VersionNumber, String, VersionSpec, Nothing} = nothing,
url = nothing, rev = nothing, path=nothing, mode::PackageMode = PKGMODE_PROJECT)
path !== nothing && url !== nothing &&
pkgerror("cannot specify both a path and url")
url !== nothing && version !== nothing &&
pkgerror("`version` can not be given with `url`, use `rev` instead")
repo = Types.GitRepo(rev = rev, url = url !== nothing ? url : path)
version = version === nothing ? VersionSpec() : VersionSpec(version)
uuid isa String && (uuid = UUID(uuid))
PackageSpec(;name=name, uuid=uuid, version=version, mode=mode, path=nothing,
special_action=PKGSPEC_NOTHING, repo=repo, tree_hash=nothing)
end
Package(name::AbstractString) = PackageSpec(name)
Package(name::AbstractString, uuid::UUID) = PackageSpec(name, uuid)
Package(name::AbstractString, uuid::UUID, version::VersionTypes) = PackageSpec(name, uuid, version)
end # module
|
The Parable of the Great Supper ; triptych , St. George 's chapel , Waddon
|
(* Title: HOL/Auth/n_germanish.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_germanish Protocol Case Study*}
theory n_germanish imports n_germanish_lemma_invs_on_rules n_germanish_on_inis
begin
lemma main:
assumes a1: "s \<in> reachableSet {andList (allInitSpecs N)} (rules N)"
and a2: "0 < N"
shows "\<forall> f. f \<in> (invariants N) --> formEval f s"
proof (rule consistentLemma)
show "consistent (invariants N) {andList (allInitSpecs N)} (rules N)"
proof (cut_tac a1, unfold consistent_def, rule conjI)
show "\<forall> f ini s. f \<in> (invariants N) --> ini \<in> {andList (allInitSpecs N)} --> formEval ini s --> formEval f s"
proof ((rule allI)+, (rule impI)+)
fix f ini s
assume b1: "f \<in> (invariants N)" and b2: "ini \<in> {andList (allInitSpecs N)}" and b3: "formEval ini s"
have b4: "formEval (andList (allInitSpecs N)) s"
apply (cut_tac b2 b3, simp) done
show "formEval f s"
apply (rule on_inis, cut_tac b1, assumption, cut_tac b2, assumption, cut_tac b3, assumption) done
qed
next show "\<forall> f r s. f \<in> invariants N --> r \<in> rules N --> invHoldForRule s f r (invariants N)"
proof ((rule allI)+, (rule impI)+)
fix f r s
assume b1: "f \<in> invariants N" and b2: "r \<in> rules N"
show "invHoldForRule s f r (invariants N)"
apply (rule invs_on_rules, cut_tac b1, assumption, cut_tac b2, assumption) done
qed
qed
next show "s \<in> reachableSet {andList (allInitSpecs N)} (rules N)"
apply (metis a1) done
qed
end
|
function rs = gmi(s, D, eps, NNR, len, Nref)
%tstoolbox/@signal/gmi
% Syntax:
% * gmi(s, D, eps, NNR, len, Nref)
%
% Input arguments:
% * D -
% * eps -
% * NNR -
% * len -
% * Nref -
%
% Generalized mutual information function for a scalar time series
%
% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt
narginchk(6,6);
if (ndim(s) > 1) | (~isreal(data(s)))
help(mfilename)
return
end
L = dlens(s, 1);
[y,i] = sort(data(s));
ra(i) = 0:(1/L):(1-1/L); % create rank values
e = embed(signal(ra'), D, 1); %'
c = core(gmi(data(e), ceil(rand(Nref,1)*(L-len-D-3))+2, eps, NNR, len));
rs = signal(c, s); % special constructor calling syntax for working routines
a = getaxis(s, 1);
dl = delta(a);
a = setfirst(a, 0);
rs = setaxis(rs, 1, a);
rs = setyunit(rs, unit); % gmi values are scalars without unit
rs = addhistory(rs, 'Generalized mutual information function');
rs = addcommandlines(rs, 's = gmi(s', D, eps, NNR, len, Nref);
|
Formal statement is: lemma real_polynomial_function_power [intro]: "real_polynomial_function f \<Longrightarrow> real_polynomial_function (\<lambda>x. f x^n)" Informal statement is: If $f$ is a real polynomial function, then $f^n$ is a real polynomial function. |
import numpy as np
import matplotlib.pyplot as plt
def get_data(data):
"""
Turn the raw string into a set of instructions and the 'paper'.
"""
dots, instrux = data.strip().split('\n\n')
instrux = [i.split('along ')[-1] for i in instrux.split('\n')]
instrux = [i.split('=') for i in instrux]
coords = np.array([list(map(int, i.split(','))) for i in dots.split('\n')])
min_x, max_x = np.min(coords[:, 0]), np.max(coords[:, 0])
min_y, max_y = np.min(coords[:, 1]), np.max(coords[:, 1])
paper = np.zeros((max_y+1, max_x+1), dtype=int)
paper[coords[:, 1], coords[:, 0]] = 1
return paper, instrux
def fold(paper, axis, pos):
"""
Make a fold.
"""
if axis == 'y':
top, bottom = np.array_split(paper, [pos,], axis=0)
bottom = bottom[1:]
if top.size > bottom.size:
bottom = np.pad(bottom, ((0, len(top)-len(bottom)), (0, 0)), 'constant')
else:
top = np.pad(top, ((len(bottom)-len(top), 0), (0, 0)), 'constant')
return top | np.flipud(bottom)
elif axis == 'x':
left, right = np.array_split(paper, [pos,], axis=1)
right = right[:, 1:]
if left.size > right.size:
right = np.pad(right, ((0, 0), (0, len(left.T)-len(right.T))), 'constant')
else:
left = np.pad(left, ((0, 0), (len(right.T)-len(left.T), 0)), 'constant')
return left | np.fliplr(right)
if __name__ == '__main__':
with open('day13.txt') as f:
data = f.read()
paper, instrux = get_data(data)
for instruction in instrux:
axis, pos = instruction
paper = fold(paper, axis, int(pos))
plt.imshow(paper)
plt.show()
|
************************************************************************
*
* Function PTILE Called by: PCTL
*
* calculate the requested percentile from a sorted vector
* (Beyer, 1987 p. 518.)
*
* local variables
* ---------------
* NP index corresponding to the desired percentile
* WGHT weight factor used to interpolate between the two
* closest values when the vector index of the desired
* percentile is not an integer
*
************************************************************************
DOUBLE PRECISION FUNCTION PTILE(X2,NUM,PCTILE)
*
* subroutine arguments
*
INTEGER*4 NUM
DOUBLE PRECISION PCTILE,X2(*)
*
* local vars
*
INTEGER*4 I
DOUBLE PRECISION NP,WGHT
*
* For data sorted in ascending order, the Jth percentile is
* defined as the ((N+1)J/100)th value. When this quantity is not
* an integer, the Jth percentile is interpolated from the two
* closest values. The weighting factor for interpolation, WGHT,
* is equal to the noninteger fractional portion of NP. IF statement
* is required to prevent interpolation past the end of the data set
* (e.g. the 99 percentile of some small data sets may
*
NP = DBLE(NUM+1)*PCTILE
I = INT(NP)
WGHT = NP-INT(NP)
IF (I+1 .LE. NUM) THEN
PTILE = (1.0D0-WGHT)*X2(I)+WGHT*X2(I+1)
ELSE
PTILE = X2(I)
ENDIF
RETURN
END
|
(* A depth-first search algorithm. *)
Require Import PeanoNat.
From larith Require Import A_setup B1_utils.
Section Stateful_search.
Variable X state solution : Type.
Variable check : state -> X -> state + solution.
Fixpoint search s l : state + (X × solution) :=
match l with
| [] => inl s
| x :: l' =>
match check s x with
| inl t => search t l'
| inr y => inr (x, y)
end
end.
Theorem search_app s l1 l2 :
search s (l1 ++ l2) =
match search s l1 with
| inl t => search t l2
| _ => search s l1
end.
Proof.
revert s; induction l1; simpl; intros. easy.
destruct (check s a); [apply IHl1|easy].
Qed.
Theorem search_inr_inv s l x y :
search s l = inr (x, y) -> In x l /\ ∃t, check t x = inr y.
Proof.
revert s; induction l; simpl; intros. easy.
destruct (check s a) as [t|y'] eqn:Ha.
apply IHl in H; split; [now right|apply H].
inv H; split; [now left|exists s; apply Ha].
Qed.
End Stateful_search.
Arguments search {_ _ _}.
Section Depth_first_search.
Variable node : Type.
Variable adj : node -> list node.
Variable accept : node -> bool.
Hypothesis dec : ∀v w : node, {v = w} + {v ≠ w}.
Notation diff x y := (subtract dec x y).
Notation next v := (remove dec v (adj v)).
Notation Path := (RTC (λ v w, In w (next v))).
Notation Notin l := (λ x, ¬In x l).
Notation Inr x := (∃r, x = inr r).
Fixpoint dfs depth visited v : list node + list node :=
match depth with
| 0 => inl visited
| S n =>
if in_dec dec v visited then inl visited
else if accept v then inr []
else match search (dfs n) (v :: visited) (next v)
with
| inl visited' => inl visited'
| inr (w, path) => inr (w :: path)
end
end.
Definition DFS_path visited path :=
Path path /\ Forall (Notin visited) path.
Definition DFS_solution visited v path :=
DFS_path visited (v :: path) /\ accept (last path v) = true.
Section Utilities.
Theorem Inr_inr {X Y} y :
Inr (@inr X Y y).
Proof.
exists y; reflexivity.
Qed.
Theorem DFS_solution_refl visited v :
¬In v visited /\ accept v = true <-> DFS_solution visited v [].
Proof.
split.
- repeat split. apply RTC_refl.
apply Forall_cons; easy. simpl; apply H.
- intros [[]]; inv H0.
Qed.
Theorem DFS_path_cons visited v w path :
DFS_path visited (w :: path) /\ ¬In v visited /\ In w (next v) <->
DFS_path visited (v :: w :: path).
Proof.
split.
- intros [[] []]; repeat split.
apply RTC_cons; easy. apply Forall_cons; easy.
- intros []; inv H; inv H0.
Qed.
Theorem DFS_path_incl vis_a vis_b path :
(∀v, In v vis_a -> In v vis_b) ->
DFS_path vis_b path -> DFS_path vis_a path.
Proof.
split. apply H0.
eapply Forall_impl. 2: apply H0.
intros v; apply contra, H.
Qed.
Corollary DFS_solution_cons visited v w path :
DFS_solution visited w path /\ ¬In v visited /\ In w (next v) <->
DFS_solution visited v (w :: path).
Proof.
unfold DFS_solution; rewrite <-DFS_path_cons, last_cons; easy.
Qed.
Corollary DFS_global_solution_refl v :
accept v = true <-> DFS_solution [] v [].
Proof.
rewrite <-DFS_solution_refl; easy.
Qed.
Corollary DFS_global_solution_cons v w path :
DFS_solution [] w path /\ In w (next v) <->
DFS_solution [] v (w :: path).
Proof.
rewrite <-DFS_solution_cons; easy.
Qed.
End Utilities.
Section Soundness.
(* Visited nodes are remembered. *)
Lemma dfs_inl_incl n vis_a v vis_z z :
dfs n vis_a v = inl vis_z -> In z vis_a -> In z vis_z.
Proof.
revert vis_a v vis_z; induction n; simpl; intros. inv H.
destruct (in_dec _); [inv H|].
destruct (accept v); [easy|].
destruct (search _) as [vis_z'|[]] eqn:Hs; [inv H|easy].
remember (v :: vis_a) as vis_b.
assert(In z vis_b) by (subst; apply in_cons, H0).
clear H0 Heqvis_b; revert H Hs; revert vis_b.
induction (next v) as [|w ws]; simpl; intros.
inv Hs. destruct (dfs _) as [vis_c|] eqn:Hw; [|easy].
(* The inclusion relation is preserved over the induction. *)
destruct (in_dec dec z vis_c); [|exfalso].
apply IHws with (vis_b:=vis_c); easy.
apply IHn in Hw; easy.
Qed.
(* Solutions given by dfs are correct. *)
Theorem dfs_sound n vis_a v path :
dfs n vis_a v = inr path -> DFS_solution vis_a v path.
Proof.
revert vis_a v path; induction n; simpl; intros. easy.
destruct (in_dec _); [easy|].
destruct (accept v) eqn:Hv. inv H.
repeat split; [apply RTC_refl|apply Forall_cons; easy|apply Hv].
destruct (search _) as [|[z from_z]] eqn:Hs; [easy|inv H].
(* Abstract over (v :: vis_a) and (next v). *)
remember (v :: vis_a) as vis_b; remember (next v) as nextv.
assert(∀x, In x vis_a -> In x vis_b) by (intros; subst; apply in_cons, H).
assert(∀x, In x nextv -> In x (next v)) by (subst; easy).
clear Hv Heqvis_b Heqnextv; revert Hs H H0; revert vis_b.
(* Do induction over nextv. *)
induction nextv as [|w ws]; simpl; intros.
easy. destruct (dfs _) as [vis_c|] eqn:Hw.
- apply IHws in Hs. apply Hs.
intros; eapply dfs_inl_incl. apply Hw. apply H, H1.
intros; apply H0; right; apply H1.
- inv Hs; apply IHn in Hw.
apply DFS_solution_cons; split; split.
eapply DFS_path_incl; [apply H|apply Hw].
apply Hw. apply n0. apply H0; left; easy.
Qed.
End Soundness.
Section Completeness.
Variable graph : list node.
Hypothesis graph_spec : ∀v, In v graph.
(* Two DFS paths can be appended. *)
Lemma DFS_path_trans visited v path1 path2 :
DFS_path visited (v :: path1) ->
DFS_path visited (last path1 v :: path2) ->
DFS_path visited (v :: path1 ++ path2).
Proof.
intros [H1a H1b] [H2a H2b].
rewrite app_comm_cons; split. eapply RTC_trans with (d:=v).
apply H1a. rewrite last_cons; apply H2a.
apply Forall_app; split; [apply H1b|inv H2b].
Qed.
(* Each new visited node can be reached by a path. *)
Lemma path_to_visited n vis_a v vis_z z :
dfs n vis_a v = inl vis_z -> ¬In z vis_a -> In z vis_z ->
∃path, DFS_path vis_a (v :: path) /\ last path v = z.
Proof.
revert vis_a v vis_z; induction n; simpl; intros. inv H.
destruct (in_dec _); [inv H|].
destruct (accept v); [easy|].
destruct (search _) as [vis_z'|[]] eqn:Hs; [inv H|easy].
(* Discard the case z = v. *)
destruct (dec z v). exists []; subst; repeat split.
apply RTC_refl. apply Forall_cons; easy.
(* Abstract over (v :: vis_a) and (next v). *)
remember (v :: vis_a) as vis_b; remember (next v) as nextv.
assert(¬In z vis_b) by (subst; apply not_in_cons; easy).
assert(∀x, In x vis_a -> In x vis_b) by (intros; subst; apply in_cons, H2).
assert(∀x, In x nextv -> In x (next v)) by (subst; easy).
clear H0 n1 Heqvis_b Heqnextv; revert Hs H H2; revert vis_b.
induction nextv as [|w ws]; simpl; intros. inv Hs.
(* Destruct the recursive call, and check if it visits z. *)
destruct (dfs _) as [vis_c|] eqn:Hw; [|easy].
destruct (in_dec dec z vis_c).
- (* If the recursive call visits z; use IHn. *)
apply IHn in Hw as [path []]; try easy.
exists (w :: path); split; [|rewrite last_cons; apply H4].
apply DFS_path_cons; split. eapply DFS_path_incl; [apply H2|apply H0].
split. apply n0. apply H3, in_eq.
- (* If it doesn't; use IHnextv. *)
apply IHws with (vis_b:=vis_c); try easy.
intros; apply H3; apply in_cons, H0.
intros; eapply dfs_inl_incl. apply Hw. apply H2, H0.
Qed.
(* If a solution exists, then, given enough fuel, dfs will also find one. *)
Theorem dfs_complete vis_a n :
length (diff graph vis_a) <= n ->
∀v path, DFS_solution vis_a v path -> Inr (dfs n vis_a v).
Proof.
revert vis_a; induction n; intros vis_a Hn; intros.
(* Zero case. Contradition since v ∈ graph \ visited. *)
destruct H as [[_ H]]; inv H.
exfalso; apply in_nil with (a:=v).
apply Nat.le_0_r, length_zero_iff_nil in Hn.
rewrite <-Hn; apply subtract_spec; easy.
(* Successor case. *)
destruct H as [[]]; inv H0; simpl.
destruct (in_dec _); [easy|]; clear n0.
destruct (accept v) eqn:Hv; [apply Inr_inr|].
(* Get a sub-path without v. *)
destruct split_at_last_instance with (x:=v)(l:=v::path)
as [pre [path' []]]. apply dec. apply in_eq.
rewrite <-last_cons with (d:=v) in H1; rewrite H0 in H, H1.
apply RTC_app_inv in H as [_ H]; rewrite last_app in H1.
assert(Forall (Notin vis_a) path'). {
destruct pre; inv H0. apply Forall_app in H5 as [_ H5]; inv H5. }
clear H0 H5 path pre.
(* The given path cannot be empty; obtain the next node. *)
inv H3; [simpl in H1; rewrite H1 in Hv; easy|].
inv H; rewrite last_cons in H1; apply in_remove in H9 as ?.
rename x into w, l into path.
(* Wrap hypotheses back together and clean up. *)
assert(H' : DFS_solution (v :: vis_a) w path). {
repeat split; try easy. apply Forall_cons.
apply not_in_cons; easy. apply not_in_cons in H2.
apply Forall_forall; intros u Hu [F|F]; subst. easy.
eapply Forall_forall with (x:=u) in H5; easy. }
assert(Hn' : length (diff graph (v :: vis_a)) <= n). {
simpl; eapply Nat.lt_succ_r, Nat.lt_le_trans.
apply subtract_length_lt_cons_r; [apply graph_spec|apply H4]. apply Hn. }
clear H H0 H1 H2 H4 H5 H7 Hv Hn.
remember (v :: vis_a) as vis_b; clear Heqvis_b vis_a.
(* Split (next v) into (next1 ++ w :: next2). *)
apply split_list in H9 as [next1 [next2 H9]]; rewrite H9.
cut(Inr (search (dfs n) vis_b (next1 ++ [w]))). intros [[w' path']].
rewrite cons_app, app_assoc, search_app, H; apply Inr_inr.
clear H9 v; revert H' Hn'; revert vis_b.
(* Do induction on the nodes that are checked before w. *)
induction next1 as [|u]; simpl; intros.
- (* At w the previous induction hypothesis guarantees a solution. *)
apply IHn in H' as [path' H']. rewrite H'; apply Inr_inr. easy.
- (* Check if the search terminates before w. *)
destruct (dfs _) as [vis_c|] eqn:Hu; [|apply Inr_inr].
(* If not, then we can use IHnext1. *)
apply IHnext1; clear IHnext1 next1.
+ (* Show that the path does not go through visited nodes. *)
destruct H' as [[]]; repeat split; try easy.
rewrite Forall_Exists_neg, Exists_exists; intros [e [H1e H2e]].
apply Forall_forall with (x:=e) in H0 as H3e; [|apply H1e].
(* If it does, then there exists a contradictory solution for v. *)
eapply path_to_visited in H2e as [to_e ?]; [|apply Hu|apply H3e].
destruct H2; subst. apply split_list in H1e as [path1 [path2 H1e]].
rewrite <-last_cons with (d:=w) in H1; rewrite H1e in H, H0, H1.
apply RTC_app_inv in H as [_ H]; apply Forall_app in H0 as [_ H0];
rewrite last_app in H1.
(* to_e ++ path2 is now a solution for u. *)
assert(DFS_solution vis_b u (to_e ++ path2)).
* split. apply DFS_path_trans; easy.
destruct path2. rewrite app_nil_r; apply H1.
rewrite last_app; rewrite last_cons in H1; apply H1.
* apply IHn in H3. rewrite Hu in H3; destruct H3; easy. easy.
+ (* Show that n is big enough. *)
etransitivity; [|apply Hn'].
apply length_subtract_le_incl_r.
intros; eapply dfs_inl_incl; [apply Hu|apply H].
Qed.
End Completeness.
Variable upper_bound : nat.
Hypothesis finite_graph : ∃l, length l <= upper_bound /\ ∀v : node, In v l.
Theorem depth_first_search visited v :
(Σ path, DFS_solution visited v path) +
{∀path, ¬DFS_solution visited v path}.
Proof.
destruct (dfs upper_bound visited v) as [visited'|path] eqn:H.
- right; intros path Hpath.
destruct finite_graph as [graph [graph_len graph_spec]].
assert(Hlen : length (diff graph visited) <= upper_bound).
+ rewrite subtract_length; etransitivity.
apply Nat.le_sub_l. apply graph_len.
+ eapply dfs_complete with (v:=v) in Hlen as [path' H'].
congruence. apply graph_spec. apply Hpath.
- left; exists path. eapply dfs_sound, H.
Defined.
End Depth_first_search.
Arguments dfs {_}.
Arguments DFS_path {_}.
Arguments DFS_solution {_}.
|
lemma ne_succ_self (n : mynat) : n ≠ succ n :=
begin
cases n with k,
exact zero_ne_succ 0,
intro x,
have h := succ_eq_succ_iff k (succ k),
rw h at x,
symmetry at x,
rw succ_eq_add_one at x,
have h2 := eq_zero_of_add_right_eq_self x,
rw one_eq_succ_zero at h2,
symmetry at h2,
apply zero_ne_succ 0,
exact h2,
end |
program ifst;
var ch : char;
begin
readln(ch);
if ch = 'a' then
writeln('It is ''a'' ');
|
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <string.h>
//** Init Multinomial
gsl_rng* init_gsl_rng(){
gsl_rng* r;
const gsl_rng_type* T2;
srand(time(NULL));
unsigned int seed;
seed= rand();
gsl_rng_env_setup();
T2 = gsl_rng_default;
r = gsl_rng_alloc (T2);
gsl_rng_set (r, seed);
return r;
}
unsigned int substract(unsigned int val){
if(val>0)
return val-1;
else
return 0;
}
//** Data must be dictionated
//** Doc-Word-topic
void dt2b_inference(int** data , unsigned int** uKu, unsigned int** pKp, unsigned int** KuKp, const int it, const int Ku,const int Kp, const int nusers, const int nplaces, const int nrecs){
float l,prev_l,prob=0;
//** Allocate Dynamic Tables
unsigned int zu[Ku];
memset( zu, 0, Ku*sizeof(unsigned int) );
unsigned int zp[Kp];
memset( zp, 0, Kp*sizeof(unsigned int) );
double p_zuzp[Ku][Kp];
//** Initialization
gsl_rng * r;
r=init_gsl_rng();
//** Initialize Dynamic Tables
unsigned int oneutopic,oneptopic;
size_t rowid;
for(rowid=0;rowid<nrecs;rowid++){
oneutopic=data[rowid][2];
oneptopic=data[rowid][3];
zu[(size_t)oneutopic]++;
zp[(size_t)oneptopic]++;
}
//** Iterate
size_t i,s,kp,ku;
int curr_u,curr_p,curr_ku,curr_kp;
for(i=0;i<it;i++){
l=0;
//printf("iteration %zu\n",i);
for(rowid=0;rowid<nrecs;rowid++){
//** Discount
curr_u=data[rowid][0];
curr_p=data[rowid][1];
curr_ku=data[rowid][2];
curr_kp=data[rowid][3];
uKu[curr_u][curr_ku]=substract(uKu[curr_u][curr_ku]);
pKp[curr_p][curr_kp]=substract(pKp[curr_p][curr_kp]);
KuKp[curr_ku][curr_kp]=substract(KuKp[curr_ku][curr_kp]);
zu[curr_ku]=substract(zu[curr_ku]);
zp[curr_kp]=substract(zp[curr_kp]);
//** Obtain Posterior
prob=0;
for(ku=0;ku<Ku;ku++){
for(kp=0;kp<Kp;kp++){
p_zuzp[ku][kp]=((KuKp[ku][kp]+0.5)*(uKu[curr_u][ku]+0.5)*(pKp[curr_p][kp]+0.5))/((zu[ku]+0.5*nusers)*(zp[kp]+0.5*nplaces));
prob+=p_zuzp[ku][kp];
}
}
l+=log(prob);
//** Obtain one sample
unsigned int samples[Ku*Kp];
double* p_z = (double*) p_zuzp;
gsl_ran_multinomial(r, Ku*Kp, 1, p_z, samples);
size_t chosen_ku,chosen_kp;
for(s=0;s<Ku*Kp;s++){
if (samples[s]>0){
//get two indexes from one
chosen_ku=(unsigned int) (s/Kp);
chosen_kp=(unsigned int) (s%Kp);
break;
}
}
//** Update
data[rowid][2]=chosen_ku;
data[rowid][3]=chosen_kp;
uKu[curr_u][chosen_ku]+=1;
pKp[curr_p][chosen_kp]+=1;
KuKp[chosen_ku][chosen_kp]+=1;
zu[chosen_ku]+=1;
zp[chosen_kp]+=1;
}
if (i==0)
prev_l=l;
//** Check convergence
if (l<prev_l && i>50){
printf("Stopped at iteration %zu",i);
break;
}
printf("Likelihood at iteration %zu: %f \n",i,l);
}
gsl_rng_free (r);
}
|
function set_label_fontsize(hax, size)
for i=1:length(hax)
h_xlabel = get(hax(i),'XLabel');
set(h_xlabel,'FontSize',size);
h_ylabel = get(hax(i),'YLabel');
set(h_ylabel,'FontSize',size);
end
|
#= This module is based on Numerical Recipes. =#
module orderedTableSearch
@inline function locate(x, grid, btm=0, up=0)
# result is same as searchsortedlast
#grid must be monotonically increasing.
if up == 0
up = length(grid) + 1
end
N = length(grid)
ascnd = (grid[end] > grid[1])
# evaluation is out of range
if x < grid[1]
return 0
elseif x > grid[end]
return N
end
mid = 0
@inbounds while up - btm > 1
mid = div((up+btm),2)#floor(Int, (up + btm) / 2)
if ascnd == (x >= grid[mid])
btm = mid
else
up = mid
end
end
return btm
end
@inline function hunt(x, grid, init_btm::Int)
N = length(grid)
ascnd = (grid[end] > grid[1])
btm = init_btm
up = 0
if init_btm < 1 || btm > N
return locate(x, grid)
else
inc = 1 # increment
if (x > grid[btm]) == ascnd
@inbounds while true
up = btm + inc
if up > N - 1
up = N
break
elseif (x > grid[up]) == ascnd
btm = up
inc += inc
else
break
end
end
else
up = btm
@inbounds while true
btm = up - inc
if btm < 1
btm = 1
break
elseif (x < grid[btm]) == ascnd
up = btm
inc += inc
else
break
end
end
end
end
return locate(x, grid, btm, up)
end
end
|
theory SDL imports Main (* Christoph Benzmüller & Xavier Parent, 2018 *)
begin (* SDL: Standard Deontic Logic (Modal Logic D) *)
typedecl i (*type for possible worlds*) type_synonym \<sigma> = "(i\<Rightarrow>bool)"
consts r::"i\<Rightarrow>i\<Rightarrow>bool" (infixr"r"70) (*Accessibility relation.*) cw::i (*Current world.*)
abbreviation mtop ("\<^bold>\<top>") where "\<^bold>\<top> \<equiv> \<lambda>w. True"
abbreviation mbot ("\<^bold>\<bottom>") where "\<^bold>\<bottom> \<equiv> \<lambda>w. False"
abbreviation mnot ("\<^bold>\<not>_"[52]53) where "\<^bold>\<not>\<phi> \<equiv> \<lambda>w. \<not>\<phi>(w)"
abbreviation mand (infixr"\<^bold>\<and>"51) where "\<phi>\<^bold>\<and>\<psi> \<equiv> \<lambda>w. \<phi>(w)\<and>\<psi>(w)"
abbreviation mor (infixr"\<^bold>\<or>"50) where "\<phi>\<^bold>\<or>\<psi> \<equiv> \<lambda>w. \<phi>(w)\<or>\<psi>(w)"
abbreviation mimp (infixr"\<^bold>\<rightarrow>"49) where "\<phi>\<^bold>\<rightarrow>\<psi> \<equiv> \<lambda>w. \<phi>(w)\<longrightarrow>\<psi>(w)"
abbreviation mequ (infixr"\<^bold>\<leftrightarrow>"48) where "\<phi>\<^bold>\<leftrightarrow>\<psi> \<equiv> \<lambda>w. \<phi>(w)\<longleftrightarrow>\<psi>(w)"
abbreviation mobligatory ("OB") where "OB \<phi> \<equiv> \<lambda>w. \<forall>v. w r v \<longrightarrow> \<phi>(v)" (*obligatory*)
abbreviation mpermissible ("PE") where "PE \<phi> \<equiv> \<^bold>\<not>(OB(\<^bold>\<not>\<phi>))" (*permissible*)
abbreviation mimpermissible ("IM") where "IM \<phi> \<equiv> OB(\<^bold>\<not>\<phi>)" (*impermissible*)
abbreviation omissible ("OM") where "OM \<phi> \<equiv> \<^bold>\<not>(OB \<phi>)" (*omissible*)
abbreviation moptional ("OP") where "OP \<phi> \<equiv> (\<^bold>\<not>(OB \<phi>) \<^bold>\<and> \<^bold>\<not>(OB(\<^bold>\<not>\<phi>)))" (*optional*)
abbreviation ddlvalid::"\<sigma> \<Rightarrow> bool" ("\<lfloor>_\<rfloor>"[7]105) (*Global Validity*)
where "\<lfloor>A\<rfloor> \<equiv> \<forall>w. A w"
abbreviation ddlvalidcw::"\<sigma> \<Rightarrow> bool" ("\<lfloor>_\<rfloor>\<^sub>c\<^sub>w"[7]105) (*Local Validity (in cw)*)
where "\<lfloor>A\<rfloor>\<^sub>c\<^sub>w \<equiv> A cw"
(* The D axiom is postulated *)
axiomatization where D: "\<lfloor>\<^bold>\<not> ((OB \<phi>) \<^bold>\<and> (OB (\<^bold>\<not> \<phi>)))\<rfloor>"
(* Meta-level study: D corresponds to seriality *)
lemma "\<lfloor>\<^bold>\<not> ((OB \<phi>) \<^bold>\<and> (OB (\<^bold>\<not> \<phi>)))\<rfloor> \<longleftrightarrow> (\<forall>w. \<exists>v. w r v)" by auto
(* Standardised syntax: unary operator for obligation in SDL *)
abbreviation obligatorySDL::"\<sigma>\<Rightarrow>\<sigma>" ("\<^bold>O\<^bold>\<langle>_\<^bold>\<rangle>") where "\<^bold>O\<^bold>\<langle>A\<^bold>\<rangle> \<equiv> OB A"
(* Consistency *)
lemma True nitpick [satisfy] oops
(* Unimportant *)
sledgehammer_params [max_facts=20,timeout=20] (* Sets parameters for theorem provers *)
nitpick_params [user_axioms,expect=genuine,show_all,format=2] (* ... and model finder. *)
end
|
module Language.Reflection.TTImp
import public Language.Reflection.TT
%default total
-- Unchecked terms and declarations in the intermediate language
mutual
public export
data BindMode = PI Count | PATTERN | NONE
-- For as patterns matching linear arguments, select which side is
-- consumed
public export
data UseSide = UseLeft | UseRight
public export
data DotReason = NonLinearVar
| VarApplied
| NotConstructor
| ErasedArg
| UserDotted
| UnknownDot
| UnderAppliedCon
public export
data TTImp : Type where
IVar : FC -> Name -> TTImp
IPi : FC -> Count -> PiInfo TTImp -> Maybe Name ->
(argTy : TTImp) -> (retTy : TTImp) -> TTImp
ILam : FC -> Count -> PiInfo TTImp -> Maybe Name ->
(argTy : TTImp) -> (lamTy : TTImp) -> TTImp
ILet : FC -> (lhsFC : FC) -> Count -> Name ->
(nTy : TTImp) -> (nVal : TTImp) ->
(scope : TTImp) -> TTImp
ICase : FC -> TTImp -> (ty : TTImp) ->
List Clause -> TTImp
ILocal : FC -> List Decl -> TTImp -> TTImp
IUpdate : FC -> List IFieldUpdate -> TTImp -> TTImp
IApp : FC -> TTImp -> TTImp -> TTImp
INamedApp : FC -> TTImp -> Name -> TTImp -> TTImp
IAutoApp : FC -> TTImp -> TTImp -> TTImp
IWithApp : FC -> TTImp -> TTImp -> TTImp
ISearch : FC -> (depth : Nat) -> TTImp
IAlternative : FC -> AltType -> List TTImp -> TTImp
IRewrite : FC -> TTImp -> TTImp -> TTImp
-- Any implicit bindings in the scope should be bound here, using
-- the given binder
IBindHere : FC -> BindMode -> TTImp -> TTImp
-- A name which should be implicitly bound
IBindVar : FC -> String -> TTImp
-- An 'as' pattern, valid on the LHS of a clause only
IAs : FC -> (nameFC : FC) -> UseSide -> Name -> TTImp -> TTImp
-- A 'dot' pattern, i.e. one which must also have the given value
-- by unification
IMustUnify : FC -> DotReason -> TTImp -> TTImp
-- Laziness annotations
IDelayed : FC -> LazyReason -> TTImp -> TTImp -- the type
IDelay : FC -> TTImp -> TTImp -- delay constructor
IForce : FC -> TTImp -> TTImp
-- Quasiquotation
IQuote : FC -> TTImp -> TTImp
IQuoteName : FC -> Name -> TTImp
IQuoteDecl : FC -> List Decl -> TTImp
IUnquote : FC -> TTImp -> TTImp
IPrimVal : FC -> (c : Constant) -> TTImp
IType : FC -> TTImp
IHole : FC -> String -> TTImp
-- An implicit value, solved by unification, but which will also be
-- bound (either as a pattern variable or a type variable) if unsolved
-- at the end of elaborator
Implicit : FC -> (bindIfUnsolved : Bool) -> TTImp
IWithUnambigNames : FC -> List Name -> TTImp -> TTImp
public export
data IFieldUpdate : Type where
ISetField : (path : List String) -> TTImp -> IFieldUpdate
ISetFieldApp : (path : List String) -> TTImp -> IFieldUpdate
public export
data AltType : Type where
FirstSuccess : AltType
Unique : AltType
UniqueDefault : TTImp -> AltType
public export
data FnOpt : Type where
Inline : FnOpt
TCInline : FnOpt
-- Flag means the hint is a direct hint, not a function which might
-- find the result (e.g. chasing parent interface dictionaries)
Hint : Bool -> FnOpt
-- Flag means to use as a default if all else fails
GlobalHint : Bool -> FnOpt
ExternFn : FnOpt
-- Defined externally, list calling conventions
ForeignFn : List TTImp -> FnOpt
-- assume safe to cancel arguments in unification
Invertible : FnOpt
Totality : TotalReq -> FnOpt
Macro : FnOpt
SpecArgs : List Name -> FnOpt
public export
data ITy : Type where
MkTy : FC -> (nameFC : FC) -> (n : Name) -> (ty : TTImp) -> ITy
public export
data DataOpt : Type where
SearchBy : List Name -> DataOpt -- determining arguments
NoHints : DataOpt -- Don't generate search hints for constructors
UniqueSearch : DataOpt -- auto implicit search must check result is unique
External : DataOpt -- implemented externally
NoNewtype : DataOpt -- don't apply newtype optimisation
public export
data Data : Type where
MkData : FC -> (n : Name) -> (tycon : TTImp) ->
(opts : List DataOpt) ->
(datacons : List ITy) -> Data
MkLater : FC -> (n : Name) -> (tycon : TTImp) -> Data
public export
data IField : Type where
MkIField : FC -> Count -> PiInfo TTImp -> Name -> TTImp ->
IField
public export
data Record : Type where
MkRecord : FC -> (n : Name) ->
(params : List (Name, Count, PiInfo TTImp, TTImp)) ->
(conName : Name) ->
(fields : List IField) ->
Record
public export
data WithFlag = Syntactic
public export
data Clause : Type where
PatClause : FC -> (lhs : TTImp) -> (rhs : TTImp) -> Clause
WithClause : FC -> (lhs : TTImp) -> (wval : TTImp) ->
(prf : Maybe Name) -> (flags : List WithFlag) ->
List Clause -> Clause
ImpossibleClause : FC -> (lhs : TTImp) -> Clause
public export
data Decl : Type where
IClaim : FC -> Count -> Visibility -> List FnOpt ->
ITy -> Decl
IData : FC -> Visibility -> Data -> Decl
IDef : FC -> Name -> List Clause -> Decl
IParameters : FC -> List (Name, Count, PiInfo TTImp, TTImp) ->
List Decl -> Decl
IRecord : FC ->
Maybe String -> -- nested namespace
Visibility -> Record -> Decl
INamespace : FC -> Namespace -> List Decl -> Decl
ITransform : FC -> Name -> TTImp -> TTImp -> Decl
IRunElabDecl : FC -> TTImp -> Decl
ILog : Maybe (List String, Nat) -> Decl
IBuiltin : FC -> BuiltinType -> Name -> Decl
public export
getFC : TTImp -> FC
getFC (IVar fc y) = fc
getFC (IPi fc _ _ _ _ _) = fc
getFC (ILam fc _ _ _ _ _) = fc
getFC (ILet fc _ _ _ _ _ _) = fc
getFC (ICase fc _ _ _) = fc
getFC (ILocal fc _ _) = fc
getFC (IUpdate fc _ _) = fc
getFC (IApp fc _ _) = fc
getFC (INamedApp fc _ _ _) = fc
getFC (IAutoApp fc _ _) = fc
getFC (IWithApp fc _ _) = fc
getFC (ISearch fc _) = fc
getFC (IAlternative fc _ _) = fc
getFC (IRewrite fc _ _) = fc
getFC (IBindHere fc _ _) = fc
getFC (IBindVar fc _) = fc
getFC (IAs fc _ _ _ _) = fc
getFC (IMustUnify fc _ _) = fc
getFC (IDelayed fc _ _) = fc
getFC (IDelay fc _) = fc
getFC (IForce fc _) = fc
getFC (IQuote fc _) = fc
getFC (IQuoteName fc _) = fc
getFC (IQuoteDecl fc _) = fc
getFC (IUnquote fc _) = fc
getFC (IPrimVal fc _) = fc
getFC (IType fc) = fc
getFC (IHole fc _) = fc
getFC (Implicit fc _) = fc
getFC (IWithUnambigNames fc _ _) = fc
|
C Copyright(C) 2009-2017 National Technology & Engineering Solutions of
C Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
C NTESS, the U.S. Government retains certain rights in this software.
C
C Redistribution and use in source and binary forms, with or without
C modification, are permitted provided that the following conditions are
C met:
C
C * Redistributions of source code must retain the above copyright
C notice, this list of conditions and the following disclaimer.
C
C * Redistributions in binary form must reproduce the above
C copyright notice, this list of conditions and the following
C disclaimer in the documentation and/or other materials provided
C with the distribution.
C * Neither the name of NTESS nor the names of its
C contributors may be used to endorse or promote products derived
C from this software without specific prior written permission.
C
C THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
C "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
C LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
C A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
C OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
C SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
C LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
C DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
C THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
C (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
C OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
C $Log: filhnd.f,v $
C Revision 1.4 2009/03/25 12:36:44 gdsjaar
C Add copyright and license notice to all files.
C Permission to assert copyright has been granted; blot is now open source, BSD
C
C Revision 1.3 2002/11/27 16:19:09 gdsjaar
C Fix filhnd calls to not pass partially uninitialized character strings to upcase.
C
C Revision 1.2 1997/11/11 14:55:55 gdsjaar
C Added 'external blkdat' to main program to ensure that the block data
C gets linked into the executable. Wasn't happening on dec alpha
C systems.
C
C Removed unreachable lines in several routines
C
C Fixed variable name spelling in contor.f
C
C Unsplit strings that were split across lines
C
C Removed old error variables left over from exodusIIv1
C
C Upped version number
C
C Revision 1.1 1994/04/07 20:00:47 gdsjaar
C Initial checkin of ACCESS/graphics/blotII2
C
c Revision 1.2 1990/12/14 08:50:32 gdsjaar
c Added RCS Id and Log to all files
c
c ======================================================================
c ======================================================================
c ======================================================================
c ======================================================================
c
c ROUTINE: filhnd
c
c DESCRIPTION: Opens and closes files.
c
c AUTHOR: John H. Glick
c Sandia-2017 National Laboratories
c Division 1511
c
c DATE: December 20, 1988
c
c TYPE OF SUBPROGRAM: subroutine
c
c USEAGE: call filhnd (unit , fil1, ecodei, ecodeo,
c type, fform, facces, frecl, *)
c
c PARAMETERS:
c
c integer unit -- (INPUT)
c If > 0, specifies the logical unit to be
c opened.
c If < 0, -unit specifies the logical unit to
c close.
c If = 0, all open logical units are to be
c closed.
c
c character type -- (INPUT)
c 'I' if input file (status = 'old')
c 'O' if output file (status = 'new')
c 'U' if unknown file type (status = 'unknown')
c 'S' if scratch file (status = 'scratch')
c
c character fform -- (INPUT)
c 'F' if formatted file
c 'U' if unformatted file
c
c CALLS:
c
c prterr (BLOT) -- Prints an error message if one occurred
c during the execution of filhnd.
c exname (SUPES) -- Gets the filename associated with a unit
c number.
c lenstr (strlib) -- Gets the length of a string (excluding
c trailing blanks).
c
c GLOBAL VARIABLES REFERENCED:
c
c CALLING ROUTINE(S): getins (BLOT)
c
c SYSTEM DEPENDENCIES: none
c
c ======================================================================
c ======================================================================
c
subroutine filhnd (unit, filn, ecodei, ecodeo, type, fform,
& facces, frecl, *)
c
c
c parameters
c
integer unit
c if > 0, the logical unit of the file to open.
c if < 0, the logical unit of the file to close.
c if = 0, close all files
logical ecodei
c On input, .TRUE., if program should abort
c if an error on opening the file occurred.
c .FALSE. otherwise.
logical ecodeo
c On output, .TRUE. if the file opening occurred successfully.
c .FALSE. otherwise.
integer frecl
c If a file is to be opened and it is a direct access file,
c the file's record length.
c If a single file ( not all files ) is to be closed,
c this parameter = 1 to delete the file on closing.
c Otherwise, the default status parameter is used on the close
c call.
character type
c 'o' if an old file,
c 'n' if a new file,
c 's' if a scratch file
c 'u' if unknown
character fform
c 'u' if unformatted
c 'f' if formatted
character facces
c 'd' if direct
c s' if sequential
character * (*) filn
c Name of the file to open. If ! = ' ', then filhnd calls
c the SUPES routine EXNAME to get the filename associated
c with the specified unit number.
c
c if unit <= 0, then all other paramaters are ignored.
c
c
c declarations
c
character*132 filnam
c filename associated with unit
integer lname
c length of string filnam (less trailing blanks)
character*11 form
c value of form keyword in open statement
character*10 access
c value of access keyword in open statement
character*7 status
c value of status keyword in open statement
integer lform,lstat
c length of form and status keywords (less trailing blanks)
integer lacces
c length of access keyword (less trailing blanks)
integer ios
c integer indicating error status of the open call.
c = 0 no error,
c = error code otherwise.
character*1 cparm
c dummy argument for call to exparm
character tform, ttype, tacces
c Temporary variables for storing modified values of fform,
c type, and facces
c
c *****************************************************************
c *****************************************************************
c
c static declarations
c
logical first
save first
integer maxunits
parameter (maxunits=25)
c maximum number of units that may be open at once.
integer numopn
c number of currently open files
integer opnlst(maxunits)
c array of currently open unit
c numbers
save numopn, opnlst
data first / .TRUE. /
c *********************************************************************
c *********************************************************************
if (first) then
numopn = 0
first = .FALSE.
end if
c print *, 'numopen = ',numopn
c if ( numopn .gt. 0 )
c & print *, 'list is ',(opnlst(i),i=1,numopn)
if ( unit .gt. 0 ) then
c
c open file associated with unit
c
c set open keywords
c
cparm = fform
call upcase_bl ( cparm )
tform = cparm(1:1)
if ( tform .eq. 'U' ) then
form = 'unformatted'
else if (tform .eq. 'F' ) then
form = 'formatted'
else
call prterr ('PROGRAM',
& 'Bad value for fform parameter in filhnd routine.')
return 1
endif
lform = lenstr ( form )
cparm = type
call upcase_bl ( cparm )
ttype = cparm(1:1)
if ( ttype .eq. 'O' ) then
status = 'old'
else if ( ttype .eq. 'N' ) then
status = 'new'
else if ( ttype .eq. 'U' ) then
status = 'unknown'
else if ( ttype .eq. 'S' ) then
status = 'scratch'
else
call prterr ('PROGRAM',
& 'Bad value for type parameter in filhnd.')
return 1
endif
lstat = lenstr ( status )
c
c
cparm = facces
call upcase_bl ( cparm )
tacces = cparm(1:1)
if ( tacces .eq. 'D' ) then
access = 'direct'
else if ( tacces .eq. 'S' ) then
access = 'sequential'
else
call prterr ('PROGRAM',
& 'Bad value for access parameter in filhnd.')
return 1
endif
lacces = lenstr ( access )
c
c
c open file
c
if ( status .ne. 'scratch' ) then
c
c get file associated with unit
c
filnam = filn
call pack ( filnam, lname )
if ( lname .eq. 0 ) then
call exname ( unit, filnam, lname )
endif
c
if ( access .eq. 'direct' ) then
open ( unit=unit, file=filnam(:lname),
& form=form(:lform),
& status=status(:lstat), access=access(:lacces),
& recl=frecl, iostat=ios )
else
c print *,'filename=',filnam(:lname),'='
c print *,'form=',form(:lform),'='
c print *,'status=',status(:lstat),'='
open ( unit=unit, file=filnam(:lname),
& form=form(:lform),
& status=status(:lstat), iostat=ios)
endif
if ( ios .ne. 0 ) then
if ( ecodei ) then
call prterr ('FATAL',
& 'Error opening file in filhnd')
return 1
else
call prterr ('ERROR',
& 'Error opening file in filhnd')
ecodeo = .FALSE.
endif
else
ecodeo = .TRUE.
endif
else
if ( access .eq. 'direct' ) then
open ( unit=unit, form=form(:lform),
& status=status(:lstat), access=access(:lacces),
& recl=frecl, iostat=ios )
else
open ( unit=unit, form=form(:lform),
& status=status(:lstat), iostat=ios)
endif
if ( ios .ne. 0 ) then
if ( ecodei ) then
call prterr ('FATAL',
& 'Error opening file in filhnd')
return 1
else
call prterr ('ERROR',
& 'Error opening file in filhnd')
ecodeo = .FALSE.
endif
else
ecodeo = .TRUE.
endif
endif
c
c
c update list of open files
c
if ( ecodeo ) then
numopn = numopn + 1
opnlst(numopn) = unit
endif
c
c
else if ( unit .lt. 0 ) then
c
c
c close file
unit = -unit
if ( frecl .eq. 1 ) then
close ( unit=unit, status='delete', iostat=ios )
else
close ( unit=unit, iostat=ios )
endif
if ( ios .ne. 0 ) then
call exname ( unit, filnam, lname )
if ( ecodei ) then
call prterr ('PROGRAM',
& 'Error closing file in filhnd')
return 1
else
call prterr ('PROGRAM',
& 'Error closing file in filhnd')
ecodeo = .FALSE.
endif
else
ecodeo = .TRUE.
endif
c
c update list of open files
c
if ( ecodeo ) then
i = 1
100 continue
if ( (i .le. numopn) .and. (unit .ne. opnlst(i)) ) then
i = i + 1
go to 100
endif
if ( i .gt. numopn ) then
call prterr ('PROGRAM',
&'Closed a file in filhnd that was not on the list of open files')
return 1
else
numopn = numopn - 1
do 110 j = i, numopn
opnlst(j) = opnlst(j+1)
110 continue
endif
endif
else
c close all open files
c
ecodeo = .TRUE.
do 120 i = 1, numopn
close ( unit=opnlst(i), iostat=ios )
if ( ios .ne. 0 ) then
call exname ( opnlst(i), filnam, lname )
if ( ecodei ) then
call prterr ('PROGRAM',
& 'Error closing file in filhnd')
return 1
else
call prterr ('PROGRAM',
& 'Error closing file in filhnd')
ecodeo = .FALSE.
endif
endif
120 continue
endif
c print *, 'about to exit filhnd'
c print *, 'numopen = ',numopn
c if ( numopn .gt. 0 )
c & print *, 'list is ',(opnlst(i),i=1,numopn)
return
end
|
chapter \<open>Array-Based Queuing Lock\<close>
section \<open>Challenge\<close>
text_raw \<open>{\upshape
Array-Based Queuing Lock (ABQL)
is a variation of the Ticket Lock algorithm with a bounded number
of concurrent threads and improved scalability due to better cache
behaviour.
%(\url{https://en.wikipedia.org/wiki/Array_Based_Queuing_Locks})
We assume that there are \texttt{N} threads and we
allocate a shared Boolean array \texttt{pass[]} of length \texttt{N}.
We also allocate a shared integer value \texttt{next}.
In practice, \texttt{next} is an unsigned bounded
integer that wraps to 0 on overflow, and
we assume that the maximal value of \texttt{next} is
of the form $k\mathtt{N} - 1$.
Finally, we assume at our disposal
an atomic \texttt{fetch\_and\_add} instruction,
such that \texttt{fetch\_and\_add(next,1)} increments the value
of \texttt{next} by 1 and returns the original value of \texttt{next}.
The elements of \texttt{pass[]} are spinlocks, assigned
individually to each thread in the waiting queue.
Initially, each element of \texttt{pass[]} is set to
\texttt{false}, except \texttt{pass[0]} which is set to
\texttt{true}, allowing the first coming thread to acquire
the lock.
Variable \texttt{next} contains the number of the first available
place in the waiting queue and is initialized to 0.
Here is an implementation of the locking algorithm in pseudocode:
\begin{lstlisting}[language=C,morekeywords={procedure,function,end,to,in,var,then,not,mod}]
procedure abql_init()
for i = 1 to N - 1 do
pass[i] := false
end-for
pass[0] := true
next := 0
end-procedure
function abql_acquire()
var my_ticket := fetch_and_add(next,1) mod N
while not pass[my_ticket] do
end-while
return my_ticket
end-function
procedure abql_release(my_ticket)
pass[my_ticket] := false
pass[(my_ticket + 1) mod N] := true
end-procedure
\end{lstlisting}
Each thread that acquires the lock must eventually release it
by calling \texttt{abql\_release(my\_ticket)}, where \texttt{my\_ticket}
is the return value of the earlier call of \texttt{abql\_acquire()}.
We assume that no thread tries to re-acquire the lock while already
holding it, neither it attempts to release the lock which it does not possess.
Notice that the first
assignment in \texttt{abql\_release()} can be moved at the end
of \texttt{abql\_acquire()}.
\bigskip
\noindent\textbf{Verification task~1.}~Verify
the safety of ABQL
under the given assumptions. Specifically, you should prove that no two
threads can hold the lock at any given time.
\bigskip
\noindent\textbf{Verification task~2.}~Verify
the fairness, namely that the threads acquire the lock
in order of request.
\bigskip
\noindent\textbf{Verification task~3.}~Verify
the liveness under a fair scheduler, namely that
each thread requesting the lock will eventually acquire it.
\bigskip
You have liberty of adapting the implementation and specification
of the concurrent setting as best suited for your verification tool.
In particular, solutions with a fixed value of \texttt{N} are acceptable.
We expect, however, that the general idea of the algorithm and
the non-deterministic behaviour of the scheduler shall be preserved.
}
\clearpage
\<close>
section \<open>Solution\<close>
theory Challenge3
imports "lib/VTcomp" "lib/DF_System"
begin
text \<open>The Isabelle Refinement Framework does not support concurrency.
However, Isabelle is a general purpose theorem prover, thus we can model
the problem as a state machine, and prove properties over runs.
For this polished solution, we make use of a small library for
transition systems and simulations: @{theory VerifyThis2018.DF_System}.
Note, however, that our definitions are still quite ad-hoc,
and there are lots of opportunities to define libraries that make similar
proofs simpler and more canonical.
We approach the final ABQL with three refinement steps:
\<^enum> We model a ticket lock with unbounded counters, and prove safety, fairness, and liveness.
\<^enum> We bound the counters by \<open>mod N\<close> and \<open>mod (k*N) respectively\<close>
\<^enum> We implement the current counter by an array,
yielding exactly the algorithm described in the challenge.
With a simulation argument, we transfer the properties of the abstract
system over the refinements.
The final theorems proving safety, fairness, and liveness can be found at
the end of this chapter, in Subsection~\ref{sec:main_theorems}.
\<close>
subsection \<open>General Definitions\<close>
text \<open>We fix a positive number \<open>N\<close> of threads\<close>
consts N :: nat
specification (N) N_not0[simp, intro!]: "N\<noteq>0" by auto
lemma N_gt0[simp, intro!]: "0<N" by (cases N) auto
text \<open>A thread's state, representing the sequence points in the given algorithm.
This will not change over the refinements.\<close>
datatype thread =
INIT
| is_WAIT: WAIT (ticket: nat)
| is_HOLD: HOLD (ticket: nat)
| is_REL: REL (ticket: nat)
subsection \<open>Refinement 1: Ticket Lock with Unbounded Counters\<close>
text \<open>System's state: Current ticket, next ticket, thread states\<close>
type_synonym astate = "nat \<times> nat \<times> (nat \<Rightarrow> thread)"
abbreviation "cc \<equiv> fst"
abbreviation "nn s \<equiv> fst (snd s)"
abbreviation "tts s \<equiv> snd (snd s)"
text \<open>The step relation of a single thread\<close>
inductive astep_sng where
enter_wait: "astep_sng (c,n,INIT) (c,(n+1),WAIT n)"
| loop_wait: "c\<noteq>k \<Longrightarrow> astep_sng (c,n,WAIT k) (c,n,WAIT k)"
| exit_wait: "astep_sng (c,n,WAIT c) (c,n,HOLD c)"
| start_release: "astep_sng (c,n,HOLD k) (c,n,REL k)"
| release: "astep_sng (c,n,REL k) (k+1,n,INIT)"
text \<open>The step relation of the system\<close>
inductive alstep for t where
"\<lbrakk> t<N; astep_sng (c,n,ts t) (c',n',s') \<rbrakk>
\<Longrightarrow> alstep t (c,n,ts) (c',n',ts(t:=s'))"
text \<open>Initial state of the system\<close>
definition "as\<^sub>0 \<equiv> (0, 0, \<lambda>_. INIT)"
interpretation A: system as\<^sub>0 alstep .
text \<open>In our system, each thread can always perform a step\<close>
lemma never_blocked: "A.can_step l s \<longleftrightarrow> l<N"
apply (cases s; cases "tts s l"; simp)
unfolding A.can_step_def
apply (clarsimp simp: alstep.simps astep_sng.simps; blast)+
done
text \<open>Thus, our system is in particular deadlock free\<close>
interpretation A: df_system as\<^sub>0 alstep
apply unfold_locales
subgoal for s
using never_blocked[of 0 s]
unfolding A.can_step_def
by auto
done
subsubsection \<open>Safety: Mutual Exclusion\<close>
text \<open>Predicates to express that a thread uses or holds a ticket\<close>
definition "has_ticket s k \<equiv> s=WAIT k \<or> s=HOLD k \<or> s=REL k"
lemma has_ticket_simps[simp]:
"\<not>has_ticket INIT k"
"has_ticket (WAIT k) k'\<longleftrightarrow> k'=k"
"has_ticket (HOLD k) k'\<longleftrightarrow> k'=k"
"has_ticket (REL k) k'\<longleftrightarrow> k'=k"
unfolding has_ticket_def by auto
definition "locks_ticket s k \<equiv> s=HOLD k \<or> s=REL k"
lemma locks_ticket_simps[simp]:
"\<not>locks_ticket INIT k"
"\<not>locks_ticket (WAIT k) k'"
"locks_ticket (HOLD k) k'\<longleftrightarrow> k'=k"
"locks_ticket (REL k) k'\<longleftrightarrow> k'=k"
unfolding locks_ticket_def by auto
lemma holds_imp_uses: "locks_ticket s k \<Longrightarrow> has_ticket s k"
unfolding locks_ticket_def by auto
text \<open>We show the following invariant.
Intuitively, it can be read as follows:
\<^item> Current lock is less than or equal next lock
\<^item> For all threads that use a ticket (i.e., are waiting, holding, or releasing):
\<^item> The ticket is in between current and next
\<^item> No other thread has the same ticket
\<^item> Only the current ticket can be held (or released)
\<close>
definition "invar1 \<equiv> \<lambda>(c,n,ts).
c \<le> n
\<and> (\<forall>t k. t<N \<and> has_ticket (ts t) k \<longrightarrow>
c \<le> k \<and> k < n
\<and> (\<forall>t' k'. t'<N \<and> has_ticket (ts t') k' \<and> t\<noteq>t' \<longrightarrow> k\<noteq>k')
\<and> (\<forall>k. k\<noteq>c \<longrightarrow> \<not>locks_ticket (ts t) k)
)
"
lemma is_invar1: "A.is_invar invar1"
apply rule
subgoal by (auto simp: invar1_def as\<^sub>0_def)
subgoal for s s'
apply (clarify)
apply (erule alstep.cases)
apply (erule astep_sng.cases)
apply (clarsimp_all simp: invar1_def)
apply fastforce
apply fastforce
apply fastforce
apply fastforce
by (metis Suc_le_eq holds_imp_uses locks_ticket_def le_neq_implies_less)
done
text \<open>From the above invariant, it's straightforward to show mutual exclusion\<close>
theorem mutual_exclusion: "\<lbrakk>A.reachable s;
t<N; t'<N; t\<noteq>t'; is_HOLD (tts s t); is_HOLD (tts s t')
\<rbrakk> \<Longrightarrow> False"
apply (cases "tts s t"; simp)
apply (cases "tts s t'"; simp)
using A.invar_reachable[OF is_invar1, of s]
apply (auto simp: invar1_def)
by (metis locks_ticket_simps(3) has_ticket_simps(3))
lemma mutual_exclusion': "\<lbrakk>A.reachable s;
t<N; t'<N; t\<noteq>t';
locks_ticket (tts s t) tk; locks_ticket (tts s t') tk'
\<rbrakk> \<Longrightarrow> False"
apply (cases "tts s t"; simp; cases "tts s t'"; simp)
apply (cases "tts s t'"; simp)
using A.invar_reachable[OF is_invar1, of s]
apply (clarsimp_all simp: invar1_def)
unfolding locks_ticket_def has_ticket_def
apply metis+
done
subsubsection \<open>Fairness: Ordered Lock Acquisition\<close>
text \<open>We first show an auxiliary lemma:
Consider a segment of a run from \<open>i\<close> to \<open>j\<close>. Every thread that waits for
a ticket in between the current ticket at \<open>i\<close> and the current ticket at \<open>j\<close>
will be granted the lock in between \<open>i\<close> and \<open>j\<close>.
\<close>
lemma fair_aux:
assumes R: "A.is_run s"
assumes A: "i<j" "cc (s i) \<le> k" "k < cc (s j)" "t<N" "tts (s i) t=WAIT k"
shows "\<exists>l. i\<le>l \<and> l<j \<and> tts (s l) t = HOLD k"
proof -
interpret A: run as\<^sub>0 alstep s by unfold_locales fact
from A show ?thesis
proof (induction "j-i" arbitrary: i)
case 0
then show ?case by auto
next
case (Suc i')
hence [simp]: "i'=j - Suc i" by auto
note IH=Suc.hyps(1)[OF this]
obtain t' where "alstep t' (s i) (s (Suc i))" by (rule A.stepE)
then show ?case using Suc.prems
proof cases
case (1 c n ts c' n' s')
note [simp] = "1"(1,2,3)
from A.run_invar[OF is_invar1, of i] have "invar1 (c,n,ts)" by auto
note I1 = this[unfolded invar1_def, simplified]
from "1"(4) show ?thesis
proof (cases rule: astep_sng.cases)
case enter_wait
then show ?thesis
using IH Suc.prems apply (auto)
by (metis "1"(2) Suc_leD Suc_lessI fst_conv leD thread.distinct(1))
next
case (loop_wait k)
then show ?thesis
using IH Suc.prems apply (auto)
by (metis "1"(2) Suc_leD Suc_lessI fst_conv leD)
next
case exit_wait
then show ?thesis
apply (cases "t'=t")
subgoal
using Suc.prems apply clarsimp
by (metis "1"(2) Suc_leD Suc_lessI fst_conv fun_upd_same leD
less_or_eq_imp_le snd_conv)
subgoal
using Suc.prems IH
apply auto
by (metis "1"(2) Suc_leD Suc_lessI fst_conv leD)
done
next
case (start_release k)
then show ?thesis
using IH Suc.prems apply (auto)
by (metis "1"(2) Suc_leD Suc_lessI fst_conv leD thread.distinct(7))
next
case (release k)
then show ?thesis
apply (cases "t'=t")
using I1 IH Suc.prems apply (auto)
by (metis "1"(2) "1"(3) Suc_leD Suc_leI Suc_lessI fst_conv
locks_ticket_simps(4) le_antisym not_less_eq_eq
has_ticket_simps(2) has_ticket_simps(4))
qed
qed
qed
qed
lemma s_case_expand:
"(case s of (c, n, ts) \<Rightarrow> P c n ts) = P (cc s) (nn s) (tts s)"
by (auto split: prod.splits)
text \<open>
A version of the fairness lemma which is very detailed on the
actual ticket numbers. We will weaken this later.
\<close>
lemma fair_aux2:
assumes RUN: "A.is_run s"
assumes ACQ: "t<N" "tts (s i) t=INIT" "tts (s (Suc i)) t=WAIT k"
assumes HOLD: "i<j" "tts (s j) t = HOLD k"
assumes WAIT: "t'<N" "tts (s i) t' = WAIT k'"
obtains l where "i<l" "l<j" "tts (s l) t' = HOLD k'"
proof -
interpret A: run as\<^sub>0 alstep s by unfold_locales fact
from ACQ WAIT have [simp]: "t\<noteq>t'" "t'\<noteq>t" by auto
from ACQ have [simp]:
"nn (s i) = k \<and> nn (s (Suc i)) = Suc k
\<and> cc (s (Suc i)) = cc (s i) \<and> tts (s (Suc i)) = (tts (s i))(t:=WAIT k)"
apply (rule_tac A.stepE[of i])
apply (erule alstep.cases)
apply (erule astep_sng.cases)
by (auto simp: nth_list_update split: if_splits)
from A.run_invar[OF is_invar1, of i] have "invar1 (s i)" by auto
note I1 = this[unfolded invar1_def, unfolded s_case_expand, simplified]
from WAIT I1 have "k' < k" by fastforce
from ACQ HOLD have "Suc i \<noteq> j" by auto with HOLD have "Suc i < j" by auto
have X1: "cc (s i) \<le> k'" using I1 WAIT by fastforce
have X2: "k' < cc (s j)"
using A.run_invar[OF is_invar1, of j, unfolded invar1_def s_case_expand]
using \<open>k' < k\<close> \<open>t<N\<close> HOLD(2)
apply clarsimp
by (metis locks_ticket_simps(3) has_ticket_simps(3))
from fair_aux[OF RUN \<open>Suc i < j\<close>, of k' t', simplified] obtain l where
"l\<ge>Suc i" "l<j" "tts (s l) t' = HOLD k'"
using WAIT X1 X2 by auto
thus ?thesis
apply (rule_tac that[of l])
by auto
qed
lemma find_hold_position:
assumes RUN: "A.is_run s"
assumes WAIT: "t<N" "tts (s i) t = WAIT tk"
assumes NWAIT: "i<j" "tts (s j) t \<noteq> WAIT tk"
obtains l where "i<l" "l\<le>j" "tts (s l) t = HOLD tk"
proof -
interpret A: run as\<^sub>0 alstep s by unfold_locales fact
from WAIT(2) NWAIT have "\<exists>l. i<l \<and> l\<le>j \<and> tts (s l) t = HOLD tk"
proof (induction "j-i" arbitrary: i)
case 0
then show ?case by auto
next
case (Suc i')
hence [simp]: "i'=j - Suc i" by auto
note IH=Suc.hyps(1)[OF this]
obtain t' where "alstep t' (s i) (s (Suc i))" by (rule A.stepE)
then show ?case
apply -
apply (cases "t=t'";erule alstep.cases; erule astep_sng.cases)
apply auto
using IH Suc.prems Suc.hyps(2)
apply (auto)
apply (metis Suc_lessD Suc_lessI fun_upd_same snd_conv)
apply (metis Suc_lessD Suc_lessI fun_upd_other snd_conv)
apply (metis Suc.prems(1) Suc_lessD Suc_lessI fun_upd_triv)
apply (metis Suc_lessD Suc_lessI fun_upd_other snd_conv)
apply (metis Suc_lessD Suc_lessI fun_upd_other snd_conv)
apply (metis Suc_lessD Suc_lessI fun_upd_other snd_conv)
done
qed
thus ?thesis using that by blast
qed
text \<open>
Finally we can show fairness, which we state as follows:
Whenever a thread \<open>t\<close> gets a ticket, all other threads \<open>t'\<close> waiting for the lock
will be granted the lock before \<open>t\<close>.
\<close>
theorem fair:
assumes RUN: "A.is_run s"
assumes ACQ: "t<N" "tts (s i) t=INIT" "is_WAIT (tts (s (Suc i)) t)"
\<comment> \<open>Thread \<open>t\<close> calls \<open>acquire\<close> in step \<open>i\<close>\<close>
assumes HOLD: "i<j" "is_HOLD (tts (s j) t)"
\<comment> \<open>Thread \<open>t\<close> holds lock in step \<open>j\<close>\<close>
assumes WAIT: "t'<N" "is_WAIT (tts (s i) t')"
\<comment> \<open>Thread \<open>t'\<close> waits for lock at step \<open>i\<close>\<close>
obtains l where "i<l" "l<j" "is_HOLD (tts (s l) t')"
\<comment> \<open>Then, \<open>t'\<close> gets lock earlier\<close>
proof -
obtain k where Wk: "tts (s (Suc i)) t = WAIT k" using ACQ
by (cases "tts (s (Suc i)) t") auto
obtain k' where Wk': "tts (s i) t' = WAIT k'" using WAIT
by (cases "tts (s i) t'") auto
from ACQ HOLD have "Suc i \<noteq> j" by auto with HOLD have "Suc i < j" by auto
obtain j' where H': "Suc i < j'" "j' \<le> j" "tts (s j') t = HOLD k"
apply (rule find_hold_position[OF RUN \<open>t<N\<close> Wk \<open>Suc i < j\<close>])
using HOLD(2) by auto
show ?thesis
apply (rule fair_aux2[OF RUN ACQ(1,2) Wk _ H'(3) WAIT(1) Wk'])
subgoal using H'(1) by simp
subgoal apply (erule that) using H'(2) by auto
done
qed
subsubsection \<open>Liveness\<close>
text \<open>For all tickets in between the current and the next ticket,
there is a thread that has this ticket\<close>
definition "invar2
\<equiv> \<lambda>(c,n,ts). \<forall>k. c\<le>k \<and> k<n \<longrightarrow> (\<exists>t<N. has_ticket (ts t) k)"
lemma is_invar2: "A.is_invar invar2"
apply rule
subgoal by (auto simp: invar2_def as\<^sub>0_def)
subgoal for s s'
apply (clarsimp simp: invar2_def)
apply (erule alstep.cases; erule astep_sng.cases; clarsimp)
apply (metis less_antisym has_ticket_simps(1))
subgoal by (metis has_ticket_simps(2))
subgoal by (metis has_ticket_simps(2))
subgoal by (metis has_ticket_simps(3))
subgoal
apply (frule A.invar_reachable[OF is_invar1])
unfolding invar1_def
apply clarsimp
by (metis Suc_leD locks_ticket_simps(4)
not_less_eq_eq has_ticket_simps(4))
done
done
text \<open>If a thread t is waiting for a lock, the current lock is also used by a thread\<close>
corollary current_lock_used:
assumes R: "A.reachable (c,n,ts)"
assumes WAIT: "t<N" "ts t = WAIT k"
obtains t' where "t'<N" "has_ticket (ts t') c"
using A.invar_reachable[OF is_invar2 R]
and A.invar_reachable[OF is_invar1 R] WAIT
unfolding invar1_def invar2_def apply auto
by (metis (full_types) le_neq_implies_less not_le order_mono_setup.refl
has_ticket_simps(2))
text \<open>Used tickets are unique (Corollary from invariant 1)\<close>
lemma has_ticket_unique: "\<lbrakk>A.reachable (c,n,ts);
t<N; has_ticket (ts t) k; t'<N; has_ticket (ts t') k
\<rbrakk> \<Longrightarrow> t'=t"
apply (drule A.invar_reachable[OF is_invar1])
by (auto simp: invar1_def)
text \<open>We define the thread that holds a specified ticket\<close>
definition "tkt_thread \<equiv> \<lambda>ts k. THE t. t<N \<and> has_ticket (ts t) k"
lemma tkt_thread_eq:
assumes R: "A.reachable (c,n,ts)"
assumes A: "t<N" "has_ticket (ts t) k"
shows "tkt_thread ts k = t"
using has_ticket_unique[OF R]
unfolding tkt_thread_def
using A by auto
lemma holds_only_current:
assumes R: "A.reachable (c,n,ts)"
assumes A: "t<N" "locks_ticket (ts t) k"
shows "k=c"
using A.invar_reachable[OF is_invar1 R] A unfolding invar1_def
using holds_imp_uses by blast
text \<open>For the inductive argument, we will use this measure, that decreases as a
single thread progresses through its phases.
\<close>
definition "tweight s \<equiv>
case s of WAIT _ \<Rightarrow> 3::nat | HOLD _ \<Rightarrow> 2 | REL _ \<Rightarrow> 1 | INIT \<Rightarrow> 0"
text \<open>We show progress: Every thread that waits for the lock
will eventually hold the lock.\<close>
theorem progress:
assumes FRUN: "A.is_fair_run s"
assumes A: "t<N" "is_WAIT (tts (s i) t)"
shows "\<exists>j>i. is_HOLD (tts (s j) t)"
proof -
interpret A: fair_run as\<^sub>0 alstep s by unfold_locales fact
from A obtain k where Wk: "tts (s i) t = WAIT k"
by (cases "tts (s i) t") auto
text \<open>We use the following induction scheme:
\<^item> Either the current thread increases (if we reach \<open>k\<close>, we are done)
\<^item> (lex) the thread using the current ticket makes a step
\<^item> (lex) another thread makes a step
\<close>
define lrel where "lrel \<equiv>
inv_image (measure id <*lex*> measure id <*lex*> measure id) (\<lambda>i. (
k-cc (s i),
tweight (tts (s i) (tkt_thread (tts (s i)) (cc (s i)))),
A.dist_step (tkt_thread (tts (s i)) (cc (s i))) i
))"
have "wf lrel" unfolding lrel_def by auto
then show ?thesis using A(1) Wk
proof (induction i)
case (less i)
text \<open>We name the components of this and the next state\<close>
obtain c n ts where [simp]: "s i = (c,n,ts)" by (cases "s i")
from A.run_reachable[of i] have R: "A.reachable (c,n,ts)" by simp
obtain c' n' ts' where [simp]: "s (Suc i) = (c',n',ts')"
by (cases "s (Suc i)")
from A.run_reachable[of "Suc i"] have R': "A.reachable (c',n',ts')"
by simp
from less.prems have WAIT[simp]: "ts t = WAIT k" by simp
{
text \<open>If thread \<open>t\<close> left waiting state, we are done\<close>
assume "ts' t \<noteq> WAIT k"
hence "ts' t = HOLD k" using less.prems
apply (rule_tac A.stepE[of i])
apply (auto elim!: alstep.cases astep_sng.cases split: if_splits)
done
hence ?case by auto
} moreover {
assume [simp]: "ts' t = WAIT k"
text \<open>Otherwise, we obtain the thread \<open>tt\<close> that holds the current lock\<close>
obtain tt where UTT: "tt<N" "has_ticket (ts tt) c"
using current_lock_used[of c n ts t k]
and less.prems A.run_reachable[of i]
by auto
have [simp]: "tkt_thread ts c = tt" using tkt_thread_eq[OF R UTT] .
note [simp] = \<open>tt<N\<close>
have "A.can_step tt (s i)" by (simp add: never_blocked)
hence ?case proof (cases rule: A.rstep_cases)
case (other t') \<comment> \<open>Another thread than \<open>tt\<close> makes a step.\<close>
text \<open>The current ticket and \<open>tt\<close>'s state remain the same\<close>
hence [simp]: "c' = c \<and> ts' tt = ts tt"
using has_ticket_unique[OF R UTT, of t']
unfolding A.rstep_def
using holds_only_current[OF R, of t']
by (force elim!: alstep.cases astep_sng.cases)
text \<open>Thus, \<open>tt\<close> is still using the current ticket\<close>
have [simp]: "tkt_thread ts' c = tt"
using UTT tkt_thread_eq[OF R', of tt c] by auto
text \<open>Only the distance to \<open>tt\<close>'s next step has decreased\<close>
have "(Suc i, i) \<in> lrel"
unfolding lrel_def tweight_def by (simp add: other)
text \<open>And we can apply the induction hypothesis\<close>
with less.IH[of "Suc i"] \<open>t<N\<close> show ?thesis
apply (auto) using Suc_lessD by blast
next
case THIS: this \<comment> \<open>The thread \<open>tt\<close> that uses the current ticket makes a step\<close>
show ?thesis
proof (cases "\<exists>k'. ts tt = REL k'")
case True \<comment> \<open>\<open>tt\<close> has finished releasing the lock \<close>
then have [simp]: "ts tt = REL c"
using UTT by auto
text \<open>Thus, current increases\<close>
have [simp]: "c' = Suc c"
using THIS apply -
unfolding A.rstep_def
apply (erule alstep.cases, erule astep_sng.cases)
by auto
text \<open>But is still less than \<open>k\<close>\<close>
from A.invar_reachable[OF is_invar1 R] have "k>c"
apply (auto simp: invar1_def)
by (metis UTT WAIT \<open>ts tt = REL c\<close> le_neq_implies_less
less.prems(1) thread.distinct(9) has_ticket_simps(2))
text \<open>And we can apply the induction hypothesis\<close>
hence "(Suc i, i) \<in> lrel"
unfolding lrel_def by auto
with less.IH[of "Suc i"] \<open>t<N\<close> show ?thesis
apply (auto) using Suc_lessD by blast
next
case False \<comment> \<open>\<open>tt\<close> has acquired the lock, or started releasing it\<close>
text \<open>Hence, current remains the same, but the weight of \<open>tt\<close> decreases\<close>
hence [simp]: "
c' = c
\<and> tweight (ts tt) > tweight (ts' tt)
\<and> has_ticket (ts' tt) c"
using THIS UTT apply -
unfolding A.rstep_def
apply (erule alstep.cases, erule astep_sng.cases)
by (auto simp: has_ticket_def tweight_def)
text \<open>\<open>tt\<close> still holds the current lock\<close>
have [simp]: "tkt_thread ts' c = tt"
using tkt_thread_eq[OF R' \<open>tt<N\<close>, of c] by simp
text \<open>And we can apply the IH\<close>
have "(Suc i, i) \<in> lrel" unfolding lrel_def by auto
with less.IH[of "Suc i"] \<open>t<N\<close> show ?thesis
apply (auto) using Suc_lessD by blast
qed
qed
}
ultimately show ?case by blast
qed
qed
subsection \<open>Refinement 2: Bounding the Counters\<close>
text \<open>We fix the \<open>k\<close> from the task description, which must be positive\<close>
consts k::nat
specification (k) k_not0[simp]: "k\<noteq>0" by auto
lemma k_gt0[simp]: "0<k" by (cases k) auto
text \<open>System's state: Current ticket, next ticket, thread states\<close>
type_synonym bstate = "nat \<times> nat \<times> (nat \<Rightarrow> thread)"
text \<open>The step relation of a single thread\<close>
inductive bstep_sng where
enter_wait: "bstep_sng (c,n,INIT) (c,(n+1) mod (k*N),WAIT (n mod N))"
| loop_wait: "c\<noteq>tk \<Longrightarrow> bstep_sng (c,n,WAIT tk) (c,n,WAIT tk)"
| exit_wait: "bstep_sng (c,n,WAIT c) (c,n,HOLD c)"
| start_release: "bstep_sng (c,n,HOLD tk) (c,n,REL tk)"
| release: "bstep_sng (c,n,REL tk) ((tk+1) mod N,n,INIT)"
text \<open>The step relation of the system, labeled with the thread \<open>t\<close> that performs the step\<close>
inductive blstep for t where
"\<lbrakk> t<N; bstep_sng (c,n,ts t) (c',n',s') \<rbrakk>
\<Longrightarrow> blstep t (c,n,ts) (c',n',ts(t:=s'))"
text \<open>Initial state of the system\<close>
definition "bs\<^sub>0 \<equiv> (0, 0, \<lambda>_. INIT)"
interpretation B: system bs\<^sub>0 blstep .
lemma b_never_blocked: "B.can_step l s \<longleftrightarrow> l<N"
apply (cases s; cases "tts s l"; simp)
unfolding B.can_step_def
apply (clarsimp simp: blstep.simps bstep_sng.simps; blast)+
done
interpretation B: df_system bs\<^sub>0 blstep
apply unfold_locales
subgoal for s
using b_never_blocked[of 0 s]
unfolding B.can_step_def
by auto
done
subsubsection \<open>Simulation\<close>
text \<open>We show that the abstract system simulates the concrete one.\<close>
text \<open>A few lemmas to ease the automation further below\<close>
lemma nat_sum_gtZ_iff[simp]:
"finite s \<Longrightarrow> sum f s \<noteq> (0::nat) \<longleftrightarrow> (\<exists>x\<in>s. f x \<noteq> 0)"
by simp
lemma n_eq_Suc_sub1_conv[simp]: "n = Suc (n - Suc 0) \<longleftrightarrow> n\<noteq>0" by auto
lemma mod_mult_mod_eq[mod_simps]: "x mod (k * N) mod N = x mod N"
by (meson dvd_eq_mod_eq_0 mod_mod_cancel mod_mult_self2_is_0)
lemma mod_eq_imp_eq_aux: "b mod N = (a::nat) mod N \<Longrightarrow> a\<le>b \<Longrightarrow> b<a+N \<Longrightarrow> b=a"
by (metis Groups.add_ac add_0_right
le_add_diff_inverse less_diff_conv2 nat_minus_mod
nat_minus_mod_plus_right mod_if)
lemma mod_eq_imp_eq:
"\<lbrakk>b \<le> x; x < b + N; b \<le> y; y < b + N; x mod N = y mod N \<rbrakk> \<Longrightarrow> x=y"
proof -
assume a1: "b \<le> y"
assume a2: "y < b + N"
assume a3: "b \<le> x"
assume a4: "x < b + N"
assume a5: "x mod N = y mod N"
have f6: "x < y + N"
using a4 a1 by linarith
have "y < x + N"
using a3 a2 by linarith
then show ?thesis
using f6 a5 by (metis (no_types) mod_eq_imp_eq_aux nat_le_linear)
qed
text \<open>Map the ticket of a thread\<close>
fun map_ticket where
"map_ticket f INIT = INIT"
| "map_ticket f (WAIT tk) = WAIT (f tk)"
| "map_ticket f (HOLD tk) = HOLD (f tk)"
| "map_ticket f (REL tk) = REL (f tk)"
lemma map_ticket_addsimps[simp]:
"map_ticket f t = INIT \<longleftrightarrow> t=INIT"
"map_ticket f t = WAIT tk \<longleftrightarrow> (\<exists>tk'. tk=f tk' \<and> t=WAIT tk')"
"map_ticket f t = HOLD tk \<longleftrightarrow> (\<exists>tk'. tk=f tk' \<and> t=HOLD tk')"
"map_ticket f t = REL tk \<longleftrightarrow> (\<exists>tk'. tk=f tk' \<and> t=REL tk')"
by (cases t; auto)+
text \<open>We define the number of threads that use a ticket\<close>
fun ni_weight :: "thread \<Rightarrow> nat" where
"ni_weight INIT = 0" | "ni_weight _ = 1"
lemma ni_weight_le1[simp]: "ni_weight s \<le> Suc 0"
by (cases s) auto
definition "num_ni ts \<equiv> \<Sum> i=0..<N. ni_weight (ts i)"
lemma num_ni_init[simp]: "num_ni (\<lambda>_. INIT) = 0" by (auto simp: num_ni_def)
lemma num_ni_upd:
"t<N \<Longrightarrow> num_ni (ts(t:=s)) = num_ni ts - ni_weight (ts t) + ni_weight s"
by (auto
simp: num_ni_def if_distrib[of ni_weight] sum.If_cases algebra_simps
simp: sum_diff1_nat
)
lemma num_ni_nz_if[simp]: "\<lbrakk>t < N; ts t \<noteq> INIT\<rbrakk> \<Longrightarrow> num_ni ts \<noteq> 0"
apply (cases "ts t")
by (simp_all add: num_ni_def) force+
lemma num_ni_leN: "num_ni ts \<le> N"
apply (clarsimp simp: num_ni_def)
apply (rule order_trans)
apply (rule sum_bounded_above[where K=1])
apply auto
done
text \<open>We provide an additional invariant, considering the distance of
\<open>c\<close> and \<open>n\<close>. Although we could probably get this from the previous
invariants, it is easy enough to prove directly.
\<close>
definition "invar3 \<equiv> \<lambda>(c,n,ts). n = c + num_ni ts"
lemma is_invar3: "A.is_invar invar3"
apply (rule)
subgoal by (auto simp: invar3_def as\<^sub>0_def)
subgoal for s s'
apply clarify
apply (erule alstep.cases, erule astep_sng.cases)
apply (auto simp: invar3_def num_ni_upd)
using holds_only_current by fastforce
done
text \<open>We establish a simulation relation: The concrete counters are
the abstract ones, wrapped around.
\<close>
definition "sim_rel1 \<equiv> \<lambda>(c,n,ts) (ci,ni,tsi).
ci = c mod N
\<and> ni = n mod (k*N)
\<and> tsi = (map_ticket (\<lambda>t. t mod N)) o ts
"
lemma sraux:
"sim_rel1 (c,n,ts) (ci,ni,tsi) \<Longrightarrow> ci = c mod N \<and> ni = n mod (k*N)"
by (auto simp: sim_rel1_def Let_def)
lemma sraux2: "\<lbrakk>sim_rel1 (c,n,ts) (ci,ni,tsi); t<N\<rbrakk>
\<Longrightarrow> tsi t = map_ticket (\<lambda>x. x mod N) (ts t)"
by (auto simp: sim_rel1_def Let_def)
interpretation sim1: simulationI as\<^sub>0 alstep bs\<^sub>0 blstep sim_rel1
proof unfold_locales
show "sim_rel1 as\<^sub>0 bs\<^sub>0"
by (auto simp: sim_rel1_def as\<^sub>0_def bs\<^sub>0_def)
next
fix as bs t bs'
assume Ra_aux: "A.reachable as"
and Rc_aux: "B.reachable bs"
and SIM: "sim_rel1 as bs"
and CS: "blstep t bs bs'"
obtain c n ts where [simp]: "as=(c,n,ts)" by (cases as)
obtain ci ni tsi where [simp]: "bs=(ci,ni,tsi)" by (cases bs)
obtain ci' ni' tsi' where [simp]: "bs'=(ci',ni',tsi')" by (cases bs')
from Ra_aux have Ra: "A.reachable (c,n,ts)" by simp
from Rc_aux have Rc: "B.reachable (ci,ni,tsi)" by simp
from CS have "t<N" by cases auto
have [simp]: "n = c + num_ni ts"
using A.invar_reachable[OF is_invar3 Ra, unfolded invar3_def] by simp
have AUX1: "c\<le>tk" "tk<c+N" if "ts t = WAIT tk" for tk
using that A.invar_reachable[OF is_invar1 Ra]
apply (auto simp: invar1_def)
using \<open>t<N\<close> apply fastforce
using \<open>t<N\<close> num_ni_leN[of ts] by fastforce
from SIM CS have "\<exists>as'. alstep t as as' \<and> sim_rel1 as' bs'"
apply simp
apply (erule blstep.cases)
apply (erule bstep_sng.cases)
apply clarsimp_all
subgoal
apply (intro exI conjI)
apply (rule alstep.intros)
apply (simp add: sim_rel1_def Let_def)
apply (simp add: sraux sraux2)
apply (rule astep_sng.enter_wait)
apply (simp add: sim_rel1_def; intro conjI ext)
apply (auto simp: sim_rel1_def Let_def mod_simps)
done
subgoal
apply (clarsimp simp: sraux sraux2)
apply (intro exI conjI)
apply (rule alstep.intros)
apply (simp add: sim_rel1_def Let_def)
apply clarsimp
apply (rule astep_sng.loop_wait)
apply (auto simp: sim_rel1_def Let_def mod_simps)
done
subgoal
apply (clarsimp simp: sraux sraux2)
subgoal for tk'
apply (subgoal_tac "tk'=c")
apply (intro exI conjI)
apply (rule alstep.intros)
apply (simp add: sim_rel1_def Let_def)
apply clarsimp
apply (rule astep_sng.exit_wait)
apply (auto simp: sim_rel1_def Let_def mod_simps) []
apply (clarsimp simp: sim_rel1_def)
apply (erule mod_eq_imp_eq_aux)
apply (auto simp: AUX1)
done
done
subgoal
apply (clarsimp simp: sraux sraux2)
apply (intro exI conjI)
apply (rule alstep.intros)
apply (simp add: sim_rel1_def Let_def)
apply clarsimp
apply (rule astep_sng.start_release)
apply (auto simp: sim_rel1_def Let_def mod_simps)
done
subgoal
apply (clarsimp simp: sraux sraux2)
apply (intro exI conjI)
apply (rule alstep.intros)
apply (simp add: sim_rel1_def Let_def)
apply clarsimp
apply (rule astep_sng.release)
apply (auto simp: sim_rel1_def Let_def mod_simps)
done
done
then show "\<exists>as'. sim_rel1 as' bs' \<and> alstep t as as'" by blast
next
fix as bs l
assume "A.reachable as" "B.reachable bs" "sim_rel1 as bs" "A.can_step l as"
then show "B.can_step l bs" using b_never_blocked never_blocked by simp
qed
subsubsection \<open>Transfer of Properties\<close>
text \<open>We transfer a few properties over the simulation,
which we need for the next refinement step.
\<close>
lemma xfer_locks_ticket:
assumes "locks_ticket (map_ticket (\<lambda>t. t mod N) (ts t)) tki"
obtains tk where "tki=tk mod N" "locks_ticket (ts t) tk"
using assms unfolding locks_ticket_def
by auto
lemma b_holds_only_current:
"\<lbrakk>B.reachable (c, n, ts); t < N; locks_ticket (ts t) tk\<rbrakk> \<Longrightarrow> tk = c"
apply (rule sim1.xfer_reachable, assumption)
apply (clarsimp simp: sim_rel1_def)
apply (erule xfer_locks_ticket)+
using holds_only_current
by blast
lemma b_mutual_exclusion': "\<lbrakk>B.reachable s;
t<N; t'<N; t\<noteq>t'; locks_ticket (tts s t) tk; locks_ticket (tts s t') tk'
\<rbrakk> \<Longrightarrow> False"
apply (rule sim1.xfer_reachable, assumption)
apply (clarsimp simp: sim_rel1_def)
apply (erule xfer_locks_ticket)+
apply (drule (3) mutual_exclusion'; simp)
done
lemma xfer_has_ticket:
assumes "has_ticket (map_ticket (\<lambda>t. t mod N) (ts t)) tki"
obtains tk where "tki=tk mod N" "has_ticket (ts t) tk"
using assms unfolding has_ticket_def
by auto
lemma has_ticket_in_range:
assumes Ra: "A.reachable (c,n,ts)" and "t<N" and U: "has_ticket (ts t) tk"
shows "c\<le>tk \<and> tk<c+N"
proof -
have [simp]: "n=c + num_ni ts"
using A.invar_reachable[OF is_invar3 Ra, unfolded invar3_def] by simp
show "c\<le>tk \<and> tk<c+N"
using A.invar_reachable[OF is_invar1 Ra] U
apply (auto simp: invar1_def)
using \<open>t<N\<close> apply fastforce
using \<open>t<N\<close> num_ni_leN[of ts] by fastforce
qed
lemma b_has_ticket_unique: "\<lbrakk>B.reachable (ci,ni,tsi);
t<N; has_ticket (tsi t) tki; t'<N; has_ticket (tsi t') tki
\<rbrakk> \<Longrightarrow> t'=t"
apply (rule sim1.xfer_reachable, assumption)
apply (auto simp: sim_rel1_def)
subgoal for c n ts
apply (erule xfer_has_ticket)+
apply simp
subgoal for tk tk'
apply (subgoal_tac "tk=tk'")
apply simp
apply (frule (4) has_ticket_unique, assumption)
apply (frule (2) has_ticket_in_range[where tk=tk])
apply (frule (2) has_ticket_in_range[where tk=tk'])
apply (auto simp: mod_simps)
apply (rule mod_eq_imp_eq; (assumption|simp))
done
done
done
subsection \<open>Refinement 3: Using an Array\<close>text_raw \<open>\label{sec:refine3}\<close>
text \<open>Finally, we use an array instead of a counter, thus obtaining
the exact data structures from the challenge assignment.
Note that we model the array by a list of Booleans here.
\<close>
text \<open>System's state: Current ticket array, next ticket, thread states\<close>
type_synonym cstate = "bool list \<times> nat \<times> (nat \<Rightarrow> thread)"
text \<open>The step relation of a single thread\<close>
inductive cstep_sng where
enter_wait: "cstep_sng (p,n,INIT) (p,(n+1) mod (k*N),WAIT (n mod N))"
| loop_wait: "\<not>p!tk \<Longrightarrow> cstep_sng (p,n,WAIT tk) (p,n,WAIT tk)"
| exit_wait: "p!tk \<Longrightarrow> cstep_sng (p,n,WAIT tk) (p,n,HOLD tk)"
| start_release: "cstep_sng (p,n,HOLD tk) (p[tk:=False],n,REL tk)"
| release: "cstep_sng (p,n,REL tk) (p[(tk+1) mod N := True],n,INIT)"
text \<open>The step relation of the system, labeled with the thread \<open>t\<close> that performs the step\<close>
inductive clstep for t where
"\<lbrakk> t<N; cstep_sng (c,n,ts t) (c',n',s') \<rbrakk>
\<Longrightarrow> clstep t (c,n,ts) (c',n',ts(t:=s'))"
text \<open>Initial state of the system\<close>
definition "cs\<^sub>0 \<equiv> ((replicate N False)[0:=True], 0, \<lambda>_. INIT)"
interpretation C: system cs\<^sub>0 clstep .
lemma c_never_blocked: "C.can_step l s \<longleftrightarrow> l<N"
apply (cases s; cases "tts s l"; simp)
unfolding C.can_step_def
apply (clarsimp_all simp: clstep.simps cstep_sng.simps)
by metis
interpretation C: df_system cs\<^sub>0 clstep
apply unfold_locales
subgoal for s
using c_never_blocked[of 0 s]
unfolding C.can_step_def
by auto
done
text \<open>We establish another invariant that states that the ticket numbers are bounded.\<close>
definition "invar4
\<equiv> \<lambda>(c,n,ts). c<N \<and> (\<forall>t<N. \<forall>tk. has_ticket (ts t) tk \<longrightarrow> tk<N)"
lemma is_invar4: "B.is_invar invar4"
apply (rule)
subgoal by (auto simp: invar4_def bs\<^sub>0_def)
subgoal for s s'
apply clarify
apply (erule blstep.cases, erule bstep_sng.cases)
unfolding invar4_def
apply safe
apply (metis N_gt0 fun_upd_other fun_upd_same mod_mod_trivial
nat_mod_lem has_ticket_simps(2))
apply (metis fun_upd_triv)
apply (metis fun_upd_other fun_upd_same has_ticket_simps(3))
apply (metis fun_upd_other fun_upd_same has_ticket_def has_ticket_simps(4))
using mod_less_divisor apply blast
apply (metis fun_upd_apply thread.distinct(1) thread.distinct(3)
thread.distinct(5) has_ticket_def)
done
done
text \<open>We define a predicate that describes that
a thread of the system is at the release sequence point --- in this case,
the array does not have a set bit, otherwise, the set bit corresponds to the
current ticket.\<close>
definition "is_REL_state \<equiv> \<lambda>ts. \<exists>t<N. \<exists>tk. ts t = REL tk"
lemma is_REL_state_simps[simp]:
"t<N \<Longrightarrow> is_REL_state (ts(t:=REL tk))"
"t<N \<Longrightarrow> \<not>is_REL (ts t) \<Longrightarrow> \<not>is_REL s'
\<Longrightarrow> is_REL_state (ts(t:=s')) \<longleftrightarrow> is_REL_state ts"
unfolding is_REL_state_def
apply (auto; fail) []
apply auto []
by (metis thread.disc(12))
lemma is_REL_state_aux1:
assumes R: "B.reachable (c,n,ts)"
assumes REL: "is_REL_state ts"
assumes "t<N" and [simp]: "ts t = WAIT tk"
shows "tk\<noteq>c"
using REL unfolding is_REL_state_def
apply clarify
subgoal for t' tk'
using b_has_ticket_unique[OF R \<open>t<N\<close>, of tk t']
using b_holds_only_current[OF R, of t' tk']
by (auto)
done
lemma is_REL_state_aux2:
assumes R: "B.reachable (c,n,ts)"
assumes A: "t<N" "ts t = REL tk"
shows "\<not>is_REL_state (ts(t:=INIT))"
using b_holds_only_current[OF R] A
using b_mutual_exclusion'[OF R]
apply (clarsimp simp: is_REL_state_def)
by fastforce
text \<open>Simulation relation that implements current ticket by array\<close>
definition "sim_rel2 \<equiv> \<lambda>(c,n,ts) (ci,ni,tsi).
(if is_REL_state ts then
ci = replicate N False
else
ci = (replicate N False)[c:=True]
)
\<and> ni = n
\<and> tsi = ts
"
interpretation sim2: simulationI bs\<^sub>0 blstep cs\<^sub>0 clstep sim_rel2
proof unfold_locales
show "sim_rel2 bs\<^sub>0 cs\<^sub>0"
by (auto simp: sim_rel2_def bs\<^sub>0_def cs\<^sub>0_def is_REL_state_def)
next
fix bs cs t cs'
assume Rc_aux: "B.reachable bs"
and Rd_aux: "C.reachable cs"
and SIM: "sim_rel2 bs cs"
and CS: "clstep t cs cs'"
obtain c n ts where [simp]: "bs=(c,n,ts)" by (cases bs)
obtain ci ni tsi where [simp]: "cs=(ci,ni,tsi)" by (cases cs)
obtain ci' ni' tsi' where [simp]: "cs'=(ci',ni',tsi')" by (cases cs')
from Rc_aux have Rc: "B.reachable (c,n,ts)" by simp
from Rd_aux have Rd: "C.reachable (ci,ni,tsi)" by simp
from CS have "t<N" by cases auto
have [simp]: "tk<N" if "ts t = WAIT tk" for tk
using B.invar_reachable[OF is_invar4 Rc] that \<open>t<N\<close>
by (auto simp: invar4_def)
have HOLD_AUX: "tk=c" if "ts t = HOLD tk" for tk
using b_holds_only_current[OF Rc \<open>t<N\<close>, of tk] that by auto
have REL_AUX: "tk=c" if "ts t = REL tk" "t<N" for t tk
using b_holds_only_current[OF Rc \<open>t<N\<close>, of tk] that by auto
have [simp]: "c<N" using B.invar_reachable[OF is_invar4 Rc]
by (auto simp: invar4_def)
have [simp]:
"replicate N False \<noteq> (replicate N False)[c := True]"
"(replicate N False)[c := True] \<noteq> replicate N False"
apply (auto simp: list_eq_iff_nth_eq nth_list_update)
using \<open>c < N\<close> by blast+
have [simp]:
"(replicate N False)[c := True] ! d \<longleftrightarrow> d=c" if "d<N" for d
using that
by (auto simp: list_eq_iff_nth_eq nth_list_update)
have [simp]: "(replicate N False)[tk := False] = replicate N False" for tk
by (auto simp: list_eq_iff_nth_eq nth_list_update')
from SIM CS have "\<exists>bs'. blstep t bs bs' \<and> sim_rel2 bs' cs'"
apply simp
apply (subst (asm) sim_rel2_def)
apply (erule clstep.cases)
apply (erule cstep_sng.cases)
apply clarsimp_all
subgoal
apply (intro exI conjI)
apply (rule blstep.intros)
apply (simp)
apply clarsimp
apply (rule bstep_sng.enter_wait)
apply (auto simp: sim_rel2_def split: if_splits)
done
subgoal for tk'
apply (intro exI conjI)
apply (rule blstep.intros)
apply (simp)
apply clarsimp
apply (rule bstep_sng.loop_wait)
subgoal
apply (clarsimp simp: sim_rel2_def split: if_splits)
apply (frule (2) is_REL_state_aux1[OF Rc])
by simp
subgoal by (auto simp: sim_rel2_def split: if_splits)
done
subgoal
apply (intro exI conjI)
apply (rule blstep.intros)
apply (simp)
apply (clarsimp split: if_splits)
apply (rule bstep_sng.exit_wait)
apply (auto simp: sim_rel2_def split: if_splits)
done
subgoal
apply (intro exI conjI)
apply (rule blstep.intros)
apply (simp)
apply clarsimp
apply (rule bstep_sng.start_release)
apply (auto simp: sim_rel2_def dest: HOLD_AUX split: if_splits)
done
subgoal
apply (intro exI conjI)
apply (rule blstep.intros)
apply (simp)
apply clarsimp
apply (rule bstep_sng.release)
apply (auto
simp: sim_rel2_def
dest: is_REL_state_aux2[OF Rc]
split: if_splits)
by (metis fun_upd_triv is_REL_state_simps(1))
done
then show "\<exists>bs'. sim_rel2 bs' cs' \<and> blstep t bs bs'" by blast
next
fix bs cs l
assume "B.reachable bs" "C.reachable cs" "sim_rel2 bs cs" "B.can_step l bs"
then show "C.can_step l cs" using c_never_blocked b_never_blocked by simp
qed
subsection \<open>Transfer Setup\<close>
text \<open>We set up the final simulation relation, and the transfer of the
concepts used in the correctness statements. \<close>
definition "sim_rel \<equiv> sim_rel1 OO sim_rel2"
interpretation sim: simulation as\<^sub>0 alstep cs\<^sub>0 clstep sim_rel
unfolding sim_rel_def
by (rule sim_trans) unfold_locales
lemma xfer_holds:
assumes "sim_rel s cs"
shows "is_HOLD (tts cs t) \<longleftrightarrow> is_HOLD (tts s t)"
using assms unfolding sim_rel_def sim_rel1_def sim_rel2_def
by (cases "tts cs t") auto
lemma xfer_waits:
assumes "sim_rel s cs"
shows "is_WAIT (tts cs t) \<longleftrightarrow> is_WAIT (tts s t)"
using assms unfolding sim_rel_def sim_rel1_def sim_rel2_def
by (cases "tts cs t") auto
lemma xfer_init:
assumes "sim_rel s cs"
shows "tts cs t = INIT \<longleftrightarrow> tts s t = INIT"
using assms unfolding sim_rel_def sim_rel1_def sim_rel2_def
by auto
subsection \<open>Main Theorems\<close> text_raw \<open>\label{sec:main_theorems}\<close>
subsubsection \<open>Trusted Code Base\<close>
text \<open>
Note that the trusted code base for these theorems is only the
formalization of the concrete system as defined in Section~\ref{sec:refine3}.
The simulation setup and the
abstract systems are only auxiliary constructions for the proof.
For completeness, we display the relevant definitions of
reachability, runs, and fairness here:
@{lemma [display, source] "C.step s s' = (\<exists>l. clstep l s s')" by simp}
@{thm [display] C.reachable_def[no_vars] C.run_definitions[no_vars]}
\<close>
subsubsection \<open>Safety\<close>
text \<open>We show that there is no reachable state in which two different
threads hold the lock.\<close>
(* ALWAYS (NOT (HOLD ** HOLD)) *)
theorem final_mutual_exclusion: "\<lbrakk>C.reachable s;
t<N; t'<N; t\<noteq>t'; is_HOLD (tts s t); is_HOLD (tts s t')
\<rbrakk> \<Longrightarrow> False"
apply (erule sim.xfer_reachable)
apply (simp add: xfer_holds)
by (erule (5) mutual_exclusion)
subsubsection \<open>Fairness\<close>
text \<open>We show that, whenever a thread \<open>t\<close> draws a ticket, all other
threads \<open>t'\<close> waiting for the lock will be granted the lock before \<open>t\<close>. \<close>
(* ALWAYS (INIT t\<^sub>1 \<and> WAIT t\<^sub>2 \<and> X (WAIT t\<^sub>1) \<longrightarrow> HOLD t\<^sub>2 BEFORE HOLD t\<^sub>1 ) *)
theorem final_fair:
assumes RUN: "C.is_run s"
assumes ACQ: "t<N" and "tts (s i) t=INIT" and "is_WAIT (tts (s (Suc i)) t)"
\<comment> \<open>Thread \<open>t\<close> draws ticket in step \<open>i\<close>\<close>
assumes HOLD: "i<j" and "is_HOLD (tts (s j) t)"
\<comment> \<open>Thread \<open>t\<close> holds lock in step \<open>j\<close>\<close>
assumes WAIT: "t'<N" and "is_WAIT (tts (s i) t')"
\<comment> \<open>Thread \<open>t'\<close> waits for lock at step \<open>i\<close>\<close>
obtains l where "i<l" and "l<j" and "is_HOLD (tts (s l) t')"
\<comment> \<open>Then, \<open>t'\<close> gets lock earlier\<close>
using RUN
proof (rule sim.xfer_run)
fix as
assume Ra: "A.is_run as" and SIM[rule_format]: "\<forall>i. sim_rel (as i) (s i)"
note XFER = xfer_init[OF SIM] xfer_holds[OF SIM] xfer_waits[OF SIM]
show ?thesis
using assms
apply (simp add: XFER)
apply (erule (6) fair[OF Ra])
apply (erule (1) that)
apply (simp add: XFER)
done
qed
subsubsection \<open>Liveness\<close>
text \<open>We show that, for a fair run, every thread that waits for the lock
will eventually hold the lock.\<close>
(* ALWAYS (WAIT \<longrightarrow> EVENTUALLY HOLD) *)
theorem final_progress:
assumes FRUN: "C.is_fair_run s"
assumes WAIT: "t<N" and "is_WAIT (tts (s i) t)"
shows "\<exists>j>i. is_HOLD (tts (s j) t)"
using FRUN
proof (rule sim.xfer_fair_run)
fix as
assume Ra: "A.is_fair_run as"
and SIM[rule_format]: "\<forall>i. sim_rel (as i) (s i)"
note XFER = xfer_init[OF SIM] xfer_holds[OF SIM] xfer_waits[OF SIM]
show ?thesis
using assms
apply (simp add: XFER)
apply (erule (1) progress[OF Ra])
done
qed
end
|
theory Heap
imports Main
begin
subsection "References"
definition "ref = (UNIV::nat set)"
typedef ref = ref by (simp add: ref_def)
code_datatype Abs_ref
lemma finite_nat_ex_max:
assumes fin: "finite (N::nat set)"
shows "\<exists>m. \<forall>n\<in>N. n < m"
using fin
proof (induct)
case empty
show ?case by auto
next
case (insert k N)
have "\<exists>m. \<forall>n\<in>N. n < m" by fact
then obtain m where m_max: "\<forall>n\<in>N. n < m"..
show "\<exists>m. \<forall>n\<in>insert k N. n < m"
proof (rule exI [where x="Suc (max k m)"])
qed (insert m_max, auto simp add: max_def)
qed
lemma infinite_nat: "\<not>finite (UNIV::nat set)"
proof
assume fin: "finite (UNIV::nat set)"
then obtain m::nat where "\<forall>n\<in>UNIV. n < m"
by (rule finite_nat_ex_max [elim_format] ) auto
moreover have "m\<in>UNIV"..
ultimately show False by blast
qed
lemma infinite_ref [simp,intro]: "\<not>finite (UNIV::ref set)"
proof
assume "finite (UNIV::ref set)"
hence "finite (range Rep_ref)"
by simp
moreover
have "range Rep_ref = ref"
proof
show "range Rep_ref \<subseteq> ref"
by (simp add: ref_def)
next
show "ref \<subseteq> range Rep_ref"
proof
fix x
assume x: "x \<in> ref"
show "x \<in> range Rep_ref"
by (rule Rep_ref_induct) (auto simp add: ref_def)
qed
qed
ultimately have "finite ref"
by simp
thus False
by (simp add: ref_def infinite_nat)
qed
consts Null :: ref
definition new :: "ref set \<Rightarrow> ref" where
"new A = (SOME a. a \<notin> {Null} \<union> A)"
text \<open>
Constant @{const "Null"} can be defined later on. Conceptually
@{const "Null"} and @{const "new"} are \<open>fixes\<close> of a locale
with @{prop "finite A \<Longrightarrow> new A \<notin> A \<union> {Null}"}. But since definitions
relative to a locale do not yet work in Isabelle2005 we use this
workaround to avoid lots of parameters in definitions.
\<close>
lemma new_notin [simp,intro]:
"finite A \<Longrightarrow> new (A) \<notin> A"
apply (unfold new_def)
apply (rule someI2_ex)
apply (fastforce intro: ex_new_if_finite)
apply simp
done
lemma new_not_Null [simp,intro]:
"finite A \<Longrightarrow> new (A) \<noteq> Null"
apply (unfold new_def)
apply (rule someI2_ex)
apply (fastforce intro: ex_new_if_finite)
apply simp
done
end |
#' Get citations in various formats from CrossRef.
#'
#' @export
#'
#' @param dois Search by a single DOI or many DOIs.
#' @param format Name of the format. One of "rdf-xml", "turtle",
#' "citeproc-json", "citeproc-json-ish", "text", "ris", "bibtex" (default),
#' "crossref-xml", "datacite-xml","bibentry", or "crossref-tdm". The format
#' "citeproc-json-ish" is a format that is not quite proper citeproc-json.
#' Note that the package bibtex is required when `format="bibtex"`; the
#' package is in Suggests so is not required when installing rcrossref
#' @param style a CSL style (for text format only). See [get_styles()]
#' for options. Default: 'apa'. If there's a style that CrossRef doesn't support
#' you'll get a `(500) Internal Server Error`
#' @param locale Language locale. See `?Sys.getlocale`
#' @param raw (logical) Return raw text in the format given by `format`
#' parameter. Default: `FALSE`
#' @param url (character) Base URL for the content negotiation request.
#' Default: "https://doi.org"
#'
#' @template moreargs
#' @details See http://citation.crosscite.org/docs.html for more info
#' on the Crossref Content Negotiation API service.
#'
#' DataCite DOIs: Some values of the `format` parameter won't work with
#' DataCite DOIs, i.e. "citeproc-json", "crossref-xml", "crossref-tdm",
#' "onix-xml".
#'
#' MEDRA DOIs only work with "rdf-xml", "turtle", "citeproc-json-ish", "ris",
#' "bibtex", "bibentry", "onix-xml".
#'
#' See examples below.
#'
#' See [cr_agency()]
#'
#' Note that the format type `citeproc-json` uses the CrossRef API at
#' `api.crossref.org`, while all others are content negotiated via
#' `http://data.crossref.org`, `http://data.datacite.org` or
#' `http://data.medra.org`. DOI agency is checked first (see
#' [cr_agency()]).
#'
#' @examples \dontrun{
#' cr_cn(dois="10.1126/science.169.3946.635")
#' cr_cn(dois="10.1126/science.169.3946.635", "citeproc-json")
#' cr_cn(dois="10.1126/science.169.3946.635", "citeproc-json-ish")
#' cr_cn("10.1126/science.169.3946.635", "rdf-xml")
#' cr_cn("10.1126/science.169.3946.635", "crossref-xml")
#' cr_cn("10.1126/science.169.3946.635", "text")
#'
#' # return an R bibentry type
#' cr_cn("10.1126/science.169.3946.635", "bibentry")
#' cr_cn("10.6084/m9.figshare.97218", "bibentry")
#'
#' # return an apa style citation
#' cr_cn("10.1126/science.169.3946.635", "text", "apa")
#' cr_cn("10.1126/science.169.3946.635", "text", "harvard3")
#' cr_cn("10.1126/science.169.3946.635", "text", "elsevier-harvard")
#' cr_cn("10.1126/science.169.3946.635", "text", "ecoscience")
#' cr_cn("10.1126/science.169.3946.635", "text", "heredity")
#' cr_cn("10.1126/science.169.3946.635", "text", "oikos")
#'
#' # example with many DOIs
#' dois <- cr_r(2)
#' cr_cn(dois, "text", "apa")
#'
#' # Cycle through random styles - print style on each try
#' stys <- get_styles()
#' foo <- function(x){
#' cat(sprintf("<Style>:%s\n", x), sep = "\n\n")
#' cat(cr_cn("10.1126/science.169.3946.635", "text", style=x))
#' }
#' foo(sample(stys, 1))
#'
#' # Using DataCite DOIs
#' ## some formats don't work
#' # cr_cn("10.5284/1011335", "crossref-xml")
#' # cr_cn("10.5284/1011335", "crossref-tdm")
#' ## But most do work
#' cr_cn("10.5284/1011335", "text")
#' cr_cn("10.5284/1011335", "datacite-xml")
#' cr_cn("10.5284/1011335", "rdf-xml")
#' cr_cn("10.5284/1011335", "turtle")
#' cr_cn("10.5284/1011335", "citeproc-json-ish")
#' cr_cn("10.5284/1011335", "ris")
#' cr_cn("10.5284/1011335", "bibtex")
#' cr_cn("10.5284/1011335", "bibentry")
#'
#' # Using Medra DOIs
#' cr_cn("10.3233/ISU-150780", "onix-xml")
#'
#' # Get raw output
#' cr_cn(dois = "10.1002/app.27716", format = "citeproc-json", raw = TRUE)
#'
#' # sometimes messy DOIs even work
#' ## in this case, a DOI minting agency can't be found
#' ## but we proceed anyway, just assuming it's "crossref"
#' cr_cn("10.1890/0012-9615(1999)069[0569:EDILSA]2.0.CO;2")
#'
#' # Use a different base url
#' cr_cn("10.1126/science.169.3946.635", "text", url = "https://data.datacite.org")
#' cr_cn("10.1126/science.169.3946.635", "text", url = "http://dx.doi.org")
#' cr_cn("10.1126/science.169.3946.635", "text", "heredity", url = "http://dx.doi.org")
#' cr_cn("10.5284/1011335", url = "https://citation.crosscite.org/format",
#' style = "oikos")
#' cr_cn("10.5284/1011335", url = "https://citation.crosscite.org/format",
#' style = "plant-cell-and-environment")
#' cr_cn("10.5284/1011335", url = "https://data.datacite.org",
#' style = "plant-cell-and-environment")
#' }
`cr_cn` <- function(dois, format = "bibtex", style = 'apa',
locale = "en-US", raw = FALSE, .progress = "none", url = NULL, ...) {
format <- match.arg(format, c("rdf-xml", "turtle", "citeproc-json",
"citeproc-json-ish", "text", "ris", "bibtex",
"crossref-xml", "datacite-xml", "bibentry",
"crossref-tdm", "onix-xml"))
cn <- function(doi, ...){
agency_id <- suppressWarnings(GET_agency_id(doi))
if (is.null(agency_id)) {
warning(doi, " agency not found - proceeding with 'crossref' ...",
call. = FALSE)
agency_id <- "crossref"
}
assert(url, "character")
if (is.null(url)) url <- "https://doi.org"
# need separate setup for citation.crosscite.org vs. others
args <- list()
if (grepl("citation.crosscite.org", url)) {
args <- cr_compact(list(doi = doi, lang = locale, style = style))
} else {
url <- file.path(url, doi)
}
# check cn data provider
if (!format %in% supported_cn_types[[agency_id]]) {
stop(paste0("Format '", format, "' for '", doi,
"' is not supported by the DOI registration agency: '",
agency_id, "'.\nTry one of the following formats: ",
paste0(supported_cn_types[[agency_id]], collapse = ", ")))
}
pick <- c(
"rdf-xml" = "application/rdf+xml",
"turtle" = "text/turtle",
"citeproc-json" =
"transform/application/vnd.citationstyles.csl+json",
"citeproc-json-ish" = "application/vnd.citationstyles.csl+json",
"text" = "text/x-bibliography",
"ris" = "application/x-research-info-systems",
"bibtex" = "application/x-bibtex",
"crossref-xml" = "application/vnd.crossref.unixref+xml",
"datacite-xml" = "application/vnd.datacite.datacite+xml",
"bibentry" = "application/x-bibtex",
"crossref-tdm" = "application/vnd.crossref.unixsd+xml",
"onix-xml" = "application/vnd.medra.onixdoi+xml")
type <- pick[[format]]
if (format == "citeproc-json") {
cli <- crul::HttpClient$new(
url = file.path("https://api.crossref.org/works", doi, type),
headers = list(
`User-Agent` = rcrossref_ua(), `X-USER-AGENT` = rcrossref_ua()
)
)
response <- cli$get(...)
} else {
if (format == "text") {
type <- paste(type, "; style = ", style, "; locale = ", locale,
sep = "")
}
cli <- crul::HttpClient$new(
url = url,
opts = list(followlocation = 1),
headers = list(
`User-Agent` = rcrossref_ua(), `X-USER-AGENT` = rcrossref_ua(),
Accept = type
)
)
response <- cli$get(query = args, ...)
}
warn_status(response)
if (response$status_code < 202) {
select <- c(
"rdf-xml" = "text/xml",
"turtle" = "text/plain",
"citeproc-json" = "application/json",
"citeproc-json-ish" = "application/json",
"text" = "text/plain",
"ris" = "text/plain",
"bibtex" = "text/plain",
"crossref-xml" = "text/xml",
"datacite-xml" = "text/xml",
"bibentry" = "text/plain",
"crossref-tdm" = "text/xml",
"onix-xml" = "text/xml")
parser <- select[[format]]
if (raw) {
response$parse("UTF-8")
} else {
out <- response$parse("UTF-8")
if (format == "text") {
out <- gsub("\n", "", out)
}
if (format == "bibentry") {
out <- parse_bibtex(out)
}
if (parser == "application/json") {
out <- jsonlite::fromJSON(out)
}
if (parser == "text/xml") {
out <- xml2::read_xml(out)
}
out
}
}
}
if (length(dois) > 1) {
llply(dois, function(z, ...) {
out <- try(cn(z, ...), silent = TRUE)
if ("try-error" %in% class(out)) {
warning(
paste0("Failure in resolving '", z,
"'. See error detail in results."),
call. = FALSE
)
out <- list(doi = z, error = out[[1]])
}
return(out)
}, .progress = .progress)
} else {
cn(dois, ...)
}
}
parse_bibtex <- function(x) {
chk4pk("bibtex")
x <- gsub("@[Dd]ata", "@Misc", x)
writeLines(x, "tmpscratch.bib")
out <- bibtex::do_read_bib("tmpscratch.bib",
srcfile = srcfile("tmpscratch.bib"))
unlink("tmpscratch.bib")
if (length(out) > 0) {
out <- out[[1]]
atts <- attributes(out)
attsuse <- atts[c('key', 'entry')]
out <- c(as.list(out), attsuse)
} else {
out <- list()
}
return(out)
}
warn_status <- function(x) {
if (x$status_code > 202) {
mssg <- x$parse("UTF-8")
if (!is.character(mssg)) {
mssg <- if (x$status_code == 406) {
"(406) - probably bad format type"
} else {
x$status_http()$message
}
} else {
mssg <- paste(sprintf("(%s)", x$status_code), "-", mssg)
}
warning(
sprintf(
"%s w/ %s",
gsub("%2F", "/", crul::url_parse(x$url)$path),
mssg
),
call. = FALSE
)
}
}
#' Get doi agency id to identify resource location
#'
#' @param x doi
#' @keywords internal
GET_agency_id <- function(x, ...) {
if (is.null(x)) {
stop("no doi for doi agency check provided", call. = FALSE)
}
cr_agency(x)$agency$id
}
# Supported content types
# See http://www.crosscite.org/cn/
supported_cn_types <- list(
crossref = c("rdf-xml", "turtle", "citeproc-json", "citeproc-json-ish",
"text", "ris", "bibtex", "crossref-xml", "bibentry",
"crossref-tdm"),
datacite = c("rdf-xml", "turtle", "datacite-xml", "citeproc-json-ish", "text",
"ris", "bibtex", "bibentry"),
medra = c("rdf-xml", "turtle", "citeproc-json-ish", "ris", "bibtex",
"bibentry", "onix-xml")
)
|
Formal statement is: lemma AE_E3: assumes "AE x in M. P x" obtains N where "\<And>x. x \<in> space M - N \<Longrightarrow> P x" "N \<in> null_sets M" Informal statement is: If $P$ holds almost everywhere, then there exists a set $N$ of measure zero such that $P$ holds outside of $N$. |
\section{Introduction}\label{sec:introduction}
This document is written for the course 2015-T-514-VEF at Reykjavik University, fall 2015. We give a drive-by introduction to the JavaScript programming language and how to set up development environment for writing JavaScript code. It is not our intention to make this guide a complete reference for the language or as a replacement for other text in the course. We look at this is an introduction level tutorial for beginners in JavaScript.
Note that we only cover parts of the language which we find relevant for this course. We intentionally leave out important aspects of the language, such as closures and prototypes to name a few. In section~\ref{sec:reading_material} we give a list of material which is good to look at after reading this document. We encourage interested students to check them out.
This document is consider to be a work in progress and is currently in version \currentVersion. We apologize if it includes any strange sentences or misspelling. The markup for this document is stored on Github\footnote{\url{https://github.com/reykjavik-university/2015-T-514-VEFT/}}.Suggestions, spotted misspellings or comments are well accepted in the form a pull-requests or by email.
Section~\ref{change_list} contains a change-list for each version of this document.
|
{-# LANGUAGE FlexibleContexts #-}
-----------------------------------------------------------------------------
-- |
-- Module : Numeric.Statistics.Information
-- Copyright : (c) A. V. H. McPhail 2010, 2014
-- License : BSD3
--
-- Maintainer : haskell.vivian.mcphail <at> gmail <dot> com
-- Stability : provisional
-- Portability : portable
--
-- Shannon entropy
--
-----------------------------------------------------------------------------
module Numeric.Statistics.Information (
entropy
, mutual_information
) where
-----------------------------------------------------------------------------
import Numeric.Statistics.PDF
import qualified Numeric.LinearAlgebra as LA
--import Numeric.LinearAlgebra.Data hiding(Vector)
--import qualified Data.Vector as DV
import qualified Data.Vector.Storable as V
import Prelude hiding(map,zip)
-----------------------------------------------------------------------------
zeroToOne x
| x == 0.0 = 1.0
| otherwise = x
logE = V.map (log . zeroToOne)
-----------------------------------------------------------------------------
-- | the entropy \sum p_i l\ln{p_i} of a sequence
entropy :: PDF a Double
=> a -- ^ the underlying distribution
-> LA.Vector Double -- ^ the sequence
-> Double -- ^ the entropy
entropy p x = let ps = probability p x
in negate $ (LA.dot ps (logE ps))
-- | the mutual information \sum_x \sum_y p(x,y) \ln{\frac{p(x,y)}{p(x)p(y)}}
mutual_information :: (PDF a Double, PDF b (Double,Double))
=> b -- ^ the underlying distribution
-> a -- ^ the first dimension distribution
-> a -- ^ the second dimension distribution
-> (LA.Vector Double, LA.Vector Double) -- ^ the sequence
-> Double -- ^ the mutual information
mutual_information p px py (x,y) = let ps = probability p $ V.zipWith (,) x y
xs = probability px x
ys = probability py y
in (LA.dot ps (logE ps - logE (xs*ys)))
-----------------------------------------------------------------------------
|
#include <boost/python.hpp>
#include <boost/interprocess/xsi_shared_memory.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>
using namespace boost::interprocess;
#ifndef _XSI_H
#define _XSI_H
class Xsi{
public:
Xsi(){
std::cout<< "\033[1;32m" << "Xsi [constructor start]" << "\033[0m" << std::endl;
char *path = "/usr";
xsi_key key(path, 1);
try {
shm = new xsi_shared_memory(open_or_create, key, 1);
}catch(boost::interprocess::interprocess_exception &e){
std::cout<< "\\033[1;31m" << "Xsi " << e.what() << "\033[0m" << std::endl;
}
//Map the whole shared memory in this process
region = new mapped_region(*shm, read_write);
std::cout<< "\033[1;32m" << "Xsi [constructor end]" << "\033[0m" << std::endl;
}
~Xsi(){
//Remove shared memory on destruction
struct shm_remove
{
int shmid_;
shm_remove(int shmid) : shmid_(shmid){}
~shm_remove(){ xsi_shared_memory::remove(shmid_); }
} remover(shm->get_shmid());
}
void step(){
std::memset(region->get_address(), i, region->get_size());
i=(i+1)%128;
}
void initialise_step(){
std::memset(region->get_address(), 0, region->get_size());
}
void run(){
std::memset(region->get_address(), -1, region->get_size());
}
void stop(){
std::memset(region->get_address(), -2, region->get_size());
}
private:
xsi_shared_memory* shm;
mapped_region* region;
int i = 0;
};
#endif // _XSI_H
BOOST_PYTHON_MODULE(pyipc)
{
using namespace boost::python;
class_<Xsi>("Xsi")
.def("step", &Xsi::step)
.def("initialise_step", &Xsi::initialise_step)
.def("run", &Xsi::run)
.def("stop", &Xsi::stop)
;
}
|
#include <bindings.cmacros.h>
#include <gsl/gsl_vector.h>
BC_INLINE2(GSL_COMPLEX_AT,gsl_vector_complex*,size_t,gsl_complex*)
BC_INLINE2(GSL_COMPLEX_FLOAT_AT,gsl_vector_complex_float*,size_t,gsl_complex_float*)
/* BC_INLINE2(GSL_COMPLEX_LONG_DOUBLE_AT,gsl_vector_complex_long_double*,size_t,gsl_complex_long_double*) */
|
using TaskGraphs
# NOTE that the experiments described in "Optimal Sequential Task Assignment and
# Path Finding for Multi-Agent Robotic Assembly Planning", Brown et al.
# were performed using Gurobi as the black box MILP solver. To use the default
# (GLPK), simply comment out the following two lines.
using Gurobi
set_default_milp_optimizer!(Gurobi.Optimizer)
## ICRA experiments
# You may want to redefine base_dis
# -------------------------- #
base_dir = joinpath("/scratch/task_graphs_experiments")
# -------------------------- #
problem_dir = joinpath(base_dir,"pctapf_problem_instances")
base_results_path = joinpath(base_dir,"pctapf_results")
feats = [
RunTime(),
FeasibleFlag(),
OptimalFlag(),
OptimalityGap(),
SolutionCost(),
PrimaryCost(),
SolutionAdjacencyMatrix(),
]
solver_configs = [
(
solver = NBSSolver(
assignment_model = TaskGraphsMILPSolver(AssignmentMILP()),
path_planner = CBSSolver(ISPS()),
),
results_path = joinpath(base_results_path,"AssignmentMILP"),
feats = feats,
objective = MakeSpan(),
),
]
base_config = Dict(
:env_id => "env_2",
:num_trials => 16,
:max_parents => 3,
:depth_bias => 0.4,
:dt_min => 0,
:dt_max => 0,
:dt_collect => 0,
:dt_deliver => 0,
)
size_configs = [Dict(:M => m, :N => n) for (n,m) in Base.Iterators.product(
[10,20,30,40],[10,20,30,40,50,60]
)][:]
problem_configs = map(d->merge(d,base_config), size_configs)
# loader = PCTA_Loader() # to test task assignment only
loader = PCTAPF_Loader()
add_env!(loader,"env_2",init_env_2())
write_problems!(loader,problem_configs,problem_dir)
for solver_config in solver_configs
set_runtime_limit!(solver_config.solver,100)
warmup(loader,solver_config,problem_dir)
run_profiling(loader,solver_config,problem_dir)
end |
import System.Concurrency.Channels
data Message = Add Nat Nat
adder : IO ()
adder =
do
Just senderChan <- listen 1
| Nothing => adder
Just msg <- unsafeRecv Message senderChan
| Nothing => adder
case msg of
Add x y =>
do
ok <- unsafeSend senderChan (x + y)
adder
main : IO ()
main =
do
Just addedPID <- spawn adder
| Nothing => putStrLn "Spawn failed"
Just chan <- connect addedPID
| Nothing => putStrLn "Connection failed"
ok <- unsafeSend chan (Add 2 3)
Just answer <- unsafeRecv String chan
| Nothing => putStrLn "Send failed"
printLn answer
|
If $c \neq 0$, then $\lim_{x \to l} f(x) c = \lim_{x \to l} f(x)$. |
function eeg_plot_metric
% eeg_plot_metric - create TeX plot label (Y is uV, X is msec)
% $Revision: 1.1 $ $Date: 2009-04-28 22:13:52 $
% Licence: GNU GPL, no express or implied warranties
% History: 07/2000, Darren.Weber_at_radiology.ucsf.edu
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Font.FontName = 'Helvetica';
Font.FontUnits = 'Pixels';
Font.FontSize = 12;
Font.FontWeight = 'normal';
Font.FontAngle = 'normal';
ylab = get(gca,'ylabel');
set(ylab,'string','\muV','Rotation',0,Font,'units','normalized',...
'Position',[-0.10 0.95 0]);
xlab = get(gca,'xlabel');
set(xlab,'string','msec','Rotation',0,Font,'units','normalized',...
'Position',[ 1.07 -0.01 0]);
return
|
[STATEMENT]
lemma fin_append_com_Nil2:
"fin_inf_append x (fin_inf_append [] z)
= fin_inf_append (x @ []) z"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. fin_inf_append x (fin_inf_append [] z) = fin_inf_append (x @ []) z
[PROOF STEP]
by (simp add: fin_append_Nil) |
Set Implicit Arguments.
Require Import Bedrock.Platform.Cito.ProgramLogic2.
Require Import Bedrock.Platform.AutoSep.
Require Import Bedrock.Platform.Cito.Syntax.
Require Import Bedrock.Platform.Cito.SyntaxExpr Bedrock.Memory Bedrock.IL Coq.Strings.String.
Require Import Bedrock.Platform.Cito.Notations3.
Local Open Scope expr.
Infix ";;" := SeqEx : stmtex_scope.
Delimit Scope stmtex_scope with stmtex.
Arguments SkipEx {_}.
Arguments SeqEx {_} _ _.
Arguments IfEx {_} _ _ _.
Arguments WhileEx {_} _ _ _.
Arguments AssignEx {_} _ _.
Arguments AssertEx {_} _.
Arguments DCallEx {_} _ _ _.
Notation "'skip'" := SkipEx : stmtex_scope.
Notation "'BEFORE' ( vs , h ) 'AFTER' ( vs' , h' ) p" :=
(fun _ s s' => let vs := sel (fst s) in let h := snd s in let vs' := sel (fst s') in let h' := snd s' in
p%word) (at level 0, p at level 200) : stmtex_inv_scope.
Delimit Scope stmtex_inv_scope with stmtex_inv.
Notation "[ inv ] 'While' cond { body }" := (WhileEx inv%stmtex_inv cond%expr body) : stmtex_scope.
Notation "'If' cond { trueStmt } 'else' { falseStmt }" := (IfEx cond%expr trueStmt falseStmt) : stmtex_scope.
Notation "x <- e" := (AssignEx x e%expr) : stmtex_scope.
Notation "'Assert' [ p ]" := (AssertEx p%stmtex_inv) : stmtex_scope.
Notation "'DCall' f ()" := (DCallEx None f nil)
(no associativity, at level 95, f at level 0) : stmtex_scope.
Notation "'DCall' f ( x1 , .. , xN )" := (DCallEx None f (@cons Expr x1 (.. (@cons Expr xN nil) ..))%expr)
(no associativity, at level 95, f at level 0) : stmtex_scope.
Notation "x <-- 'DCall' f ()" := (DCallEx (Some x) f nil)
(no associativity, at level 95, f at level 0) : stmtex_scope.
Notation "x <-- 'DCall' f ( x1 , .. , xN )" := (DCallEx (Some x) f (@cons Expr x1 (.. (@cons Expr xN nil) ..))%expr) (no associativity, at level 95, f at level 0) : stmtex_scope.
Notation "a ! b" := (a, b) (only parsing) : stmtex_scope.
Section ADTValue.
Variable ADTValue : Type.
Local Close Scope expr.
Require Import Bedrock.Platform.Cito.SyntaxFunc Bedrock.Platform.Cito.GeneralTactics.
Require Import Bedrock.Platform.Cito.FuncCore.
Notation is_false := (@is_false ADTValue).
Theorem lt0_false : forall (n : string) env v v',
is_false (0 < n)%expr env v v'
-> ($0 >= sel (fst v') n)%word.
intros.
hnf in H.
simpl in H.
unfold wltb in H.
destruct (wlt_dec (natToW 0) (fst v' n)); try discriminate; auto.
Qed.
Notation is_true := (@is_true ADTValue).
Theorem lt0_true : forall (n : string) env v v',
is_true (0 < n)%expr env v v'
-> ($0 < sel (fst v') n)%word.
intros.
hnf in H.
simpl in H.
unfold wltb in H.
destruct (wlt_dec (natToW 0) (fst v' n)); try tauto; auto.
Qed.
Hint Immediate lt0_false lt0_true.
Import List.
Lemma map_length_eq : forall A B ls1 ls2 (f : A -> B), List.map f ls1 = ls2 -> length ls1 = length ls2.
intros.
eapply f_equal with (f := @length _) in H.
simpl in *; rewrite map_length in *; eauto.
Qed.
Require Import Bedrock.Platform.Cito.Semantics.
Notation Value := (@Value ADTValue).
Fixpoint make_triples_2 words (in_outs : list (Value * option ADTValue)) :=
match words, in_outs with
| p :: ps, o :: os => {| Word := p; ADTIn := fst o; ADTOut := snd o |} :: make_triples_2 ps os
| _, _ => nil
end.
Lemma triples_intro : forall triples words in_outs, words = List.map (@Word _) triples -> List.map (fun x => (ADTIn x, ADTOut x)) triples = in_outs -> triples = make_triples_2 words in_outs.
induction triples; destruct words; destruct in_outs; simpl in *; intuition.
f_equal; intuition.
destruct a; destruct p; simpl in *.
injection H; injection H0; intros; subst.
eauto.
Qed.
End ADTValue.
Ltac selify :=
repeat match goal with
| [ |- context[upd ?a ?b ?c ?d] ] => change (upd a b c d) with (sel (upd a b c) d)
| [ |- context[fst ?X ?S] ] => change (fst X S) with (sel (fst X) S)
end.
Ltac unfold_all :=
repeat match goal with
| H := _ |- _ => unfold H in *; clear H
end.
Ltac cito' :=
repeat (subst; simpl; selify; autorewrite with sepFormula in *;
repeat match goal with
| [ H : _ |- _ ] => rewrite H
end).
Ltac cito_vcs body := unfold body; simpl;
unfold imply_close, and_lift, interp; simpl;
firstorder cito'; auto.
Ltac solve_vcs vcs_good :=
match goal with
| |- and_all _ _ => eapply vcs_good
| |- _ => idtac
end.
Ltac cito_runsto f pre vcs_good :=
intros;
match goal with
| [ H : _ |- _ ] =>
unfold f, Body, Core in H;
eapply sound_runsto' with (p := pre) (s := Body f) in H;
solve_vcs vcs_good
; simpl in *;
auto; openhyp; subst; simpl in *; unfold pre, and_lift, or_lift in *; openhyp
end.
Ltac cito_safe f pre vcs_good :=
intros;
unfold f, Body, Core; eapply sound_safe with (p := pre);
solve_vcs vcs_good
; simpl in *; try unfold pre in *; unfold pre, imply_close, and_lift in *; simpl in *;
auto; openhyp; subst; simpl in *.
Ltac inversion_Forall :=
repeat match goal with
| H : List.Forall _ _ |- _ => inversion H; subst; clear H
end.
|
lemma is_zeroth_power [simp]: "is_nth_power 0 x \<longleftrightarrow> x = 1" |
On October 23 , an open trough was centered north of Hispaniola near the Turks and Caicos islands . At 0000 UTC the following day , the area of disturbed weather became organized and was analyzed to have become a tropical storm southeast of Inagua , based on nearby vessel reports . Initially , the storm drifted northward , but later began to accelerate towards the northeast after a roughly 12 @-@ hour period . At 0600 UTC on September 25 , the disturbance slightly gained in intensity to attain maximum wind speeds of 45 mph ( 75 km / h ) ; these would be the strongest winds associated with the storm as a fully tropical cyclone . A reanalysis of the system indicated that due to a lack of definite tropical features , the storm may have had been a subtropical cyclone . On October 26 , the system became increasingly asymmetric and had developed frontal boundaries , allowing for it to be classified as an extratropical cyclone at 0600 UTC that day . Once transitioning into an extratropical system , the storm continued to intensified as it moved northward . On October 27 , the system was analyzed to have a minimum pressure of at least 985 mbar ( hPa ; 29 @.@ 09 inHg ) after passing to the southeast of Bermuda . At 1200 UTC later that day , the cyclone reached an extratropical peak intensity with winds of 80 mph ( 130 km / h ) just east of Newfoundland . Had the storm been tropical at the time , it would have been classified as a modern @-@ day Category 1 hurricane . Subsequently , the extratropical storm curved eastward , where it persisted before dissipating by 1800 UTC on September 29 .
|
import tactic.ring
import tactic.tidy
import group_theory.group_action
import linear_algebra.matrix.special_linear_group
import linear_algebra.determinant
import data.matrix.notation
import group_theory.group_action.basic
import algebra.hom.group_action
import linear_algebra.matrix
import linear_algebra.matrix.general_linear_group
import data.complex.basic
import mod_forms.modular_group.mat_m
--import .matrix_groups
/- This is an attempt to update the kbb birthday repo, so most is not orginal to me-/
open finset
open matrix
open_locale matrix
section
universe u
variables (n : Type* ) [decidable_eq n] [fintype n] (m : ℤ)
namespace modular_group
local attribute [-instance] matrix.special_linear_group.has_coe_to_fun
local notation `SL2Z`:=special_linear_group (fin 2) ℤ
variables {R : Type*} [comm_ring R]
lemma det_m (M: integral_matrices_with_determinant (fin 2) m): (M 0 0 * M 1 1 - M 0 1 * M 1 0)= m :=
begin
have H:= matrix.det_fin_two M.1,
simp at *,
have m2:=M.2,
rw ← H,
simp_rw ← m2,
simp,
end
lemma det_one (M : SL2Z) : (M 0 0 * M 1 1 - M 0 1 * M 1 0) = 1 :=
begin
apply det_m,
end
lemma det_onne (M : SL2Z) : (M 0 0 * M 1 1 - M 1 0 * M 0 1) = 1 :=
begin
have:= det_one M,
have h1: M 1 0 * M 0 1 = M 0 1 * M 1 0, by {apply mul_comm},
rw h1,
apply this,
end
@[simp] lemma mat_mul_expl (A B : matrix (fin 2) (fin 2) R) :
(A * B) 0 0 = A 0 0 * B 0 0 + A 0 1 * B 1 0 ∧
(A * B) 0 1 = A 0 0 * B 0 1 + A 0 1 * B 1 1 ∧
(A * B) 1 0 = A 1 0 * B 0 0 + A 1 1 * B 1 0 ∧
(A * B) 1 1 = A 1 0 * B 0 1 + A 1 1 * B 1 1 :=
begin
split, work_on_goal 2 {split}, work_on_goal 3 {split},
all_goals {simp only [mul_eq_mul],
rw matrix.mul_apply,
rw finset.sum_fin_eq_sum_range,
rw finset.sum_range_succ,
rw finset.sum_range_succ,
simp [nat.succ_pos', lt_self_iff_false, dite_eq_ite, fin.mk_zero, if_true, finset.sum_empty, not_le,
finset.range_zero, nat.one_lt_bit0_iff, zero_add, add_right_inj, fin.mk_one, subtype.val_eq_coe,
ite_eq_left_iff]},
end
lemma SL2_inv_det_expl (A : SL2Z) : det ![![A.1 1 1, -A.1 0 1], ![-A.1 1 0 , A.1 0 0]] = 1 :=
begin
rw [matrix.det_fin_two, mul_comm],
simp only [subtype.val_eq_coe, cons_val_zero, cons_val_one, head_cons, mul_neg, neg_mul, neg_neg],
have := A.2,
rw matrix.det_fin_two at this,
convert this,
end
lemma SL2_inv_expl (A : SL2Z) : A⁻¹ = ⟨![![A.1 1 1, -A.1 0 1], ![-A.1 1 0 , A.1 0 0]],
SL2_inv_det_expl A⟩ :=
begin
ext,
have := matrix.adjugate_fin_two A.1,
simp only [subtype.val_eq_coe] at this,
simp at *,
simp_rw [this],
simp,
end
@[simp] lemma SL2Z_inv_a (A : SL2Z) : (A⁻¹).1 0 0 = A.1 1 1 :=
begin
rw SL2_inv_expl, simp,
end
@[simp] lemma SL2Z_inv_b (A : SL2Z) : (A⁻¹).1 0 1 = -A.1 0 1 :=
begin
rw SL2_inv_expl, simp,
end
@[simp] lemma SL2Z_inv_c (A : SL2Z) : (A⁻¹).1 1 0 = -A.1 1 0 :=
begin
rw SL2_inv_expl, simp,
end
@[simp] lemma SL2Z_inv_d (A : SL2Z) : (A⁻¹).1 1 1 = A.1 0 0 :=
begin
rw SL2_inv_expl, simp,
end
lemma m_a_b (m : ℤ) (hm : m ≠ 0) (A : SL2Z) (M N : integral_matrices_with_determinant (fin 2) m):
(A • M) = N ↔ N 0 0= A 0 0 * M 0 0 + A 0 1 * M 1 0 ∧
N 0 1= A 0 0 * M 0 1 + A 0 1 * M 1 1 ∧
N 1 0= A 1 0 * M 0 0 + A 1 1 * M 1 0 ∧
N 1 1= A 1 0 * M 0 1 + A 1 1 * M 1 1 :=
begin
split,
intro h,
have:= mat_mul_expl A M, rw ← h, simp ,intro h, ext i j, fin_cases i; fin_cases j, simp at *, rw h.1,
simp at *, rw h.2.1,simp at *, rw h.2.2.1,simp at *, rw h.2.2.2,
end
@[simp] lemma SLnZ_M_a (A: SL2Z) (M: integral_matrices_with_determinant (fin 2) m) :
(A • M) 0 0= A 0 0 * M 0 0 + A 0 1 * M 1 0 :=
begin
simp [integral_matrices_with_determinant.SLnZ_M, add_mul, mul_add, mul_assoc],
end
@[simp] lemma SLnZ_M_b (A: SL2Z) (M: integral_matrices_with_determinant (fin 2) m) :
(A • M) 0 1= A 0 0 * M 0 1 + A 0 1 * M 1 1 :=
begin
simp [integral_matrices_with_determinant.SLnZ_M, add_mul, mul_add, mul_assoc],
end
@[simp] lemma SLnZ_M_c (A: SL2Z) (M: integral_matrices_with_determinant (fin 2) m) :
(A • M) 1 0= A 1 0 * M 0 0 + A 1 1 * M 1 0 :=
begin
simp [integral_matrices_with_determinant.SLnZ_M, add_mul, mul_add, mul_assoc],
end
@[simp] lemma SLnZ_M_d (A: SL2Z) (M: integral_matrices_with_determinant (fin 2) m) :
(A • M) 1 1= A 1 0 * M 0 1 + A 1 1 * M 1 1 :=
begin
simp [integral_matrices_with_determinant.SLnZ_M, add_mul, mul_add, mul_assoc],
end
def mat_Z_to_R (A : matrix (fin 2) (fin 2) ℤ ) :matrix (fin 2) (fin 2) ℝ :=
![![A 0 0, A 0 1], ![A 1 0 , A 1 1]]
instance Z_to_R: has_coe (matrix (fin 2) (fin 2) ℤ) (matrix (fin 2) (fin 2) ℝ ) :=⟨λ A, mat_Z_to_R A⟩
lemma nonzero_inv (a: ℝ) (h: 0 < a): is_unit (a):=
begin
have h2: a ≠ 0, {simp only [ne.def], by_contradiction h1, rw h1 at h, simp only [lt_self_iff_false] at h, exact h},
rw is_unit_iff_exists_inv, use a⁻¹, apply mul_inv_cancel h2,
end
@[simp]lemma mat_val (A: SL2Z) (i j : fin 2): (mat_Z_to_R A.1) i j = (A.1 i j : ℝ):=
begin
rw mat_Z_to_R, fin_cases i; fin_cases j, simp only [matrix.cons_val_zero],
simp only [matrix.head_cons, matrix.cons_val_one, matrix.cons_val_zero],
simp only [matrix.head_cons, matrix.cons_val_one, matrix.cons_val_zero],
simp only [matrix.head_cons, matrix.cons_val_one],
end
instance SLZ_to_GLZ: has_coe SL2Z (matrix.special_linear_group (fin 2 ) ℝ):=
⟨λ A, ⟨mat_Z_to_R A.1, by {rw mat_Z_to_R, rw matrix.det_fin_two, have:= matrix.det_fin_two A,
simp at *,
norm_cast, exact this.symm,}, ⟩⟩
variable (C : GL_pos (fin 2) ℤ)
@[simp]lemma mat_vals (A: SL2Z) (i j : fin 2): ( A : (GL (fin 2) ℝ)) i j = (A.1 i j : ℝ):=
begin
simp [mat_val, mat_Z_to_R], fin_cases i; fin_cases j, refl,refl,refl,refl,
end
@[simp] lemma det_coe_sl (A: SL2Z): (A: GL (fin 2) ℝ).val.det= (A.val.det: ℝ):=
begin
have:=A.2, rw this, simp, rw ← coe_coe, rw ← coe_coe, simp,
end
end modular_group
end
|
\begin{appendix}
\section{Additional experimental results}
\subsection{Graph\textsc{WCOJ} local mode scaling} \label{app:local-mode-scaling}
Run-times and speedups of the local mode GraphWCOJ scaling experiment.
Time shown in minutes.
\begin{center}
Twitter
\input{generated/graphWCOJ-scaling-twitter.tex}
LiveJournal
\input{generated/graphWCOJ-scaling-livej.tex}
Orkut
\input{generated/graphWCOJ-scaling-orkut.tex}
\end{center}
\subsection{Graph\textsc{WCOJ} distributed scaling} \label{app:distributed-scaling}
Run-times and speedups of the distributed GraphWCOJ scaling experiment.
Time shown in minutes.
\begin{center}
LiveJournal
\input{generated/distributed-scaling-livej.tex}
Orkut
\input{generated/distributed-scaling-orkut.tex}
\end{center}
\end{appendix} |
[STATEMENT]
lemma AI_correct: "AI c = Some C \<Longrightarrow> CS c \<le> \<gamma>\<^sub>c C"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. AI c = Some C \<Longrightarrow> CS c \<le> \<gamma>\<^sub>c C
[PROOF STEP]
proof(simp add: CS_def AI_def)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. pfp (step' \<top>) (bot c) = Some C \<Longrightarrow> Collecting.lfp c (step UNIV) \<le> \<gamma>\<^sub>c C
[PROOF STEP]
assume 1: "pfp (step' \<top>) (bot c) = Some C"
[PROOF STATE]
proof (state)
this:
pfp (step' \<top>) (bot c) = Some C
goal (1 subgoal):
1. pfp (step' \<top>) (bot c) = Some C \<Longrightarrow> Collecting.lfp c (step UNIV) \<le> \<gamma>\<^sub>c C
[PROOF STEP]
have pfp': "step' \<top> C \<le> C"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. step' \<top> C \<le> C
[PROOF STEP]
by(rule pfp_pfp[OF 1])
[PROOF STATE]
proof (state)
this:
step' \<top> C \<le> C
goal (1 subgoal):
1. pfp (step' \<top>) (bot c) = Some C \<Longrightarrow> Collecting.lfp c (step UNIV) \<le> \<gamma>\<^sub>c C
[PROOF STEP]
have 2: "step (\<gamma>\<^sub>o \<top>) (\<gamma>\<^sub>c C) \<le> \<gamma>\<^sub>c C" \<comment> \<open>transfer the pfp'\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. step (\<gamma>\<^sub>o \<top>) (\<gamma>\<^sub>c C) \<le> \<gamma>\<^sub>c C
[PROOF STEP]
proof(rule order_trans)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. step (\<gamma>\<^sub>o \<top>) (\<gamma>\<^sub>c C) \<le> ?y
2. ?y \<le> \<gamma>\<^sub>c C
[PROOF STEP]
show "step (\<gamma>\<^sub>o \<top>) (\<gamma>\<^sub>c C) \<le> \<gamma>\<^sub>c (step' \<top> C)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. step (\<gamma>\<^sub>o \<top>) (\<gamma>\<^sub>c C) \<le> \<gamma>\<^sub>c (step' \<top> C)
[PROOF STEP]
by(rule step_step')
[PROOF STATE]
proof (state)
this:
step (\<gamma>\<^sub>o \<top>) (\<gamma>\<^sub>c C) \<le> \<gamma>\<^sub>c (step' \<top> C)
goal (1 subgoal):
1. \<gamma>\<^sub>c (step' \<top> C) \<le> \<gamma>\<^sub>c C
[PROOF STEP]
show "... \<le> \<gamma>\<^sub>c C"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<gamma>\<^sub>c (step' \<top> C) \<le> \<gamma>\<^sub>c C
[PROOF STEP]
by (metis mono_gamma_c[OF pfp'])
[PROOF STATE]
proof (state)
this:
\<gamma>\<^sub>c (step' \<top> C) \<le> \<gamma>\<^sub>c C
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
step (\<gamma>\<^sub>o \<top>) (\<gamma>\<^sub>c C) \<le> \<gamma>\<^sub>c C
goal (1 subgoal):
1. pfp (step' \<top>) (bot c) = Some C \<Longrightarrow> Collecting.lfp c (step UNIV) \<le> \<gamma>\<^sub>c C
[PROOF STEP]
have 3: "strip (\<gamma>\<^sub>c C) = c"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. strip (\<gamma>\<^sub>c C) = c
[PROOF STEP]
by(simp add: strip_pfp[OF _ 1] step'_def)
[PROOF STATE]
proof (state)
this:
strip (\<gamma>\<^sub>c C) = c
goal (1 subgoal):
1. pfp (step' \<top>) (bot c) = Some C \<Longrightarrow> Collecting.lfp c (step UNIV) \<le> \<gamma>\<^sub>c C
[PROOF STEP]
have "lfp c (step (\<gamma>\<^sub>o \<top>)) \<le> \<gamma>\<^sub>c C"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Collecting.lfp c (step (\<gamma>\<^sub>o \<top>)) \<le> \<gamma>\<^sub>c C
[PROOF STEP]
by(rule lfp_lowerbound[simplified,where f="step (\<gamma>\<^sub>o \<top>)", OF 3 2])
[PROOF STATE]
proof (state)
this:
Collecting.lfp c (step (\<gamma>\<^sub>o \<top>)) \<le> \<gamma>\<^sub>c C
goal (1 subgoal):
1. pfp (step' \<top>) (bot c) = Some C \<Longrightarrow> Collecting.lfp c (step UNIV) \<le> \<gamma>\<^sub>c C
[PROOF STEP]
thus "lfp c (step UNIV) \<le> \<gamma>\<^sub>c C"
[PROOF STATE]
proof (prove)
using this:
Collecting.lfp c (step (\<gamma>\<^sub>o \<top>)) \<le> \<gamma>\<^sub>c C
goal (1 subgoal):
1. Collecting.lfp c (step UNIV) \<le> \<gamma>\<^sub>c C
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
Collecting.lfp c (step UNIV) \<le> \<gamma>\<^sub>c C
goal:
No subgoals!
[PROOF STEP]
qed |
-------------------------------------------------------------------------------
--
-- SET (in Hedberg library) for agda2
-- as of 2006.9.29 morning
-- Yoshiki.
--
module SET where
----------------------------------------------------------------------------
-- Auxiliary.
----------------------------------------------------------------------------
-- no : (x : A) -> B : Set if A : Set B : Set
-- yes : (x : A) -> B type if A type B type
-- El M type if M : Set
data Unop (A : Set) : Set1 where
unopI : (A -> A) -> Unop A
data Pred (A : Set) : Set1 where
PredI : (A -> Set) -> Pred A
data Rel (A : Set) : Set1 where
RelI : (A -> A -> Set) -> Rel A
data Reflexive {A : Set} (R : A -> A -> Set) : Set where
reflexiveI : ((a : A) -> R a a) -> Reflexive R
data Symmetrical {A : Set} (R : A -> A -> Set) : Set where
symmetricalI : ({a b : A} -> R a b -> R a b) -> Symmetrical R
data Transitive {A : Set} (R : A -> A -> Set) : Set where
transitiveI : ({a b c : A} -> R a b -> R b c -> R a c) -> Transitive R
compositionalI :
{A : Set} -> (R : A -> A -> Set)
-> ({a b c : A} -> R b c -> R a b -> R a c) -> Transitive R
compositionalI {A} R f =
transitiveI (\{a b c : A} -> \(x : R a b) -> \(y : R b c) -> f y x)
data Substitutive {A : Set} (R : A -> A -> Set) : Set1 where
substitutiveI : ((P : A -> Set) -> {a b : A} -> R a b -> P a -> P b)
-> Substitutive R
data Collapsed (A : Set) : Set1 where
collapsedI : ((P : A -> Set) -> {a b : A} -> P a -> P b) -> Collapsed A
cmp : {A B C : Set} -> (B -> C) -> (A -> B) -> A -> C
cmp f g a = f (g a)
seq : {A B C : Set} -> (A -> B) -> (B -> C) -> A -> C
seq f g = cmp g f
S : {A B C : Set} -> (C -> B -> A) -> (C -> B) -> C -> A
S x y z = x z (y z)
K : {A B : Set} -> A -> B -> A
K x y = x
I : {A : Set} -> A -> A
I a = a
-- of course I = S K K
id = \{A : Set} -> I {A}
const = \{A B : Set} -> K {A}{B}
-- Set version
pS : {P Q R : Set} -> (R -> Q -> P) -> (R -> Q) -> R -> P
pS x y z = x z (y z)
pK : {P Q : Set} -> P -> Q -> P
pK x y = x
pI : {P : Set} -> P -> P
pI a = a
proj : {A : Set} -> (B : A -> Set) -> (a : A) -> (f : (aa : A) -> B aa) -> B a
proj B a f = f a
flip : {A B C : Set} (f : A -> B -> C) (b : B) (a : A) -> C
flip f b a = f a b
-- separate definition of FlipRel is necessary because it is not the case
-- that Set : Set.
FlipRel : {A : Set} -> (R : A -> A -> Set) -> (a b : A) -> Set
FlipRel R a b = R b a
----------------------------------------------------------------------------
-- Product sets.
----------------------------------------------------------------------------
-- Prod : (A : Set) -> (A -> Set) -> Set
-- Prod A B = (a : A) -> B a
-- The above is not type-correct since (a : A) -> B a is not well-formed
-- but the following works.
data Prod (A : Set) (B : A -> Set) : Set where
prodI : ((a : A) -> B a) -> Prod A B
mapProd : {A : Set} -> {B C : A -> Set} -> ((a : A) -> B a -> C a)
-> Prod A B -> Prod A C
mapProd {A} f (prodI g) = prodI (\(a : A) -> f a (g a))
-- data Fun (A B : Set) : Set1 where
-- funI : (A -> B) -> Fun A B
Fun : Set -> Set -> Set
Fun A B = Prod A (\(_ : A) -> B)
mapFun : {A B C D : Set} -> (B -> A) -> (C -> D) -> (A -> C) -> B -> D
mapFun {A} {B} {C} {D} f g h x = g (h (f x))
-- mapFun (|X1 |X2 |Y1 |Y2 :: Set)
-- :: (X2 -> X1) -> (Y1 -> Y2) -> (X1 -> Y1) -> X2 -> Y2
-- = \f -> \g -> \h -> \x ->
-- g (h (f x))
---------------------------------------------------------------------------
-- Identity proof sets.
---------------------------------------------------------------------------
-- to accept the following definition more general scheme of
-- inductive definition is required
-- data Id (A : Set) (a b : A) : Set1 where
-- ref : (a : A) -> Id A a a
--
-- elimId (|X :: Set)
-- (C :: (x1 x2 :: X) |-> Id x1 x2 -> Set)
-- (refC :: (x :: X) -> C (refId x))
-- (|x1 |x2 :: X)
-- (u :: Id x1 x2) ::
-- C u
-- = case u of { (ref x) -> refC x;}
--
-- abstract whenId (|X :: Set)(C :: Rel X)(c :: (x :: X) -> C x x)
-- :: (x1 x2 :: X) |-> Id x1 x2 -> C x1 x2
-- = elimId (\x1 x2 |-> \(u :: Id x1 x2) -> C x1 x2) c
--
-- abstract substId (|X :: Set) :: Substitutive Id
-- = \(C :: Pred X) ->
-- whenId (\x1 x2 -> C x1 -> C x2) (\x -> id)
--
-- abstract mapId (|X :: Set)(|Y :: Set)(f :: X -> Y)
-- :: (x1 x2 :: X) |-> Id x1 x2 -> Id (f x1) (f x2)
-- = whenId (\x1 x2 -> Id (f x1) (f x2)) (\(x :: X) -> refId (f x))
--
-- abstract symId (|X :: Set) :: Symmetrical Id
-- = whenId (\(x1 x2 :: X) -> Id x2 x1) refId
--
-- abstract cmpId (|X :: Set) :: Compositional Id
-- = let lem :: (x y :: X) |-> Id x y -> (z :: X) |-> Id z x -> Id z y
-- = whenId ( \(x y :: _) -> (z :: X) |-> Id z x -> Id z y)
-- ( \x -> \z |-> id)
-- in \(x1 x2 x3 :: _) |->
-- \(u :: Id x2 x3) ->
-- \(v :: Id x1 x2) ->
-- lem u v
--
-- abstract tranId (|X :: Set) :: Transitive Id
-- = \(x1 x2 x3 :: X) |->
-- \(u :: Id x1 x2) ->
-- \(v :: Id x2 x3) ->
-- cmpId v u
----------------------------------------------------------------------------
-- The empty set.
----------------------------------------------------------------------------
data Zero : Set where
-- --abstract whenZero (X :: Set)(z :: Zero) :: X
-- -- = case z of { }
-- do not know how to encode whenZero; the following does not work.
-- whenZero : (X : Set) -> (z : Zero) -> X
-- whenZero X z =
-- --elimZero (C :: Zero -> Set)(z :: Zero) :: C z
-- -- = case z of { }
-- elimZero either!
-- elimZero : (C : Zero -> Set) -> (z : Zero) -> C z
-- elimZero C z =
--
-- abstract collZero :: Collapsed Zero
-- = \(C :: Zero -> Set) ->
-- \(z1 z2 :: Zero) |->
-- \(c :: C z1) ->
-- case z1 of { }
--
----------------------------------------------------------------------------
-- The singleton set.
----------------------------------------------------------------------------
data Unit : Set where
uu : Unit
elUnit = uu
elimUnit : (C : Unit -> Set) -> C uu -> (u : Unit) -> C u
elimUnit C c uu = c
-- Do not know of the exact use of Collapse!
-- collUnit : (C : Unit -> Set) -> {u1 u2 : Unit} -> C u1 -> Collapsed Unit
-- collUnit C {uu} {uu} A = collapsedI (\(P : Unit -> Set) -> \{a b : Unit} -> \(y : P a) -> A)
-- abstract collUnit :: Collapsed Unit
-- = \(C :: Unit -> Set) ->
-- \(u1 u2 :: Unit) |->
-- \(c :: C u1) ->
-- case u1 of { (tt) -> case u2 of { (tt) -> c;};}
---------------------------------------------------------------------------
-- The successor set adds a new element.
---------------------------------------------------------------------------
data Succ (A : Set) : Set where
zerS : Succ A
sucS : A -> Succ A
zerSucc = \{A : Set} -> zerS {A}
sucSucc = \{A : Set} -> sucS {A}
elimSucc : {X : Set} -> (C : Succ X -> Set)
-> C zerS -> ((x : X) -> C (sucS x)) -> (xx : Succ X) -> (C xx)
elimSucc C c_z c_s zerS = c_z
elimSucc C c_z c_s (sucS x) = c_s x
whenSucc : {X Y : Set} -> Y -> (X -> Y) -> (Succ X) -> Y
whenSucc y_z y_s zerS = y_z
whenSucc y_z y_s (sucS x) = y_s x
mapSucc : {X Y : Set} -> (X -> Y) -> Succ X -> Succ Y
mapSucc {X} {_} f
= whenSucc zerS (\(x : X) -> sucS (f x))
---------------------------------------------------------------------------
-- The (binary) disjoint union.
---------------------------------------------------------------------------
data Plus (A B : Set) : Set where
inl : A -> Plus A B
inr : B -> Plus A B
elimPlus : {X Y : Set} ->
(C : Plus X Y -> Set) ->
((x : X) -> C (inl x)) ->
((y : Y) -> C (inr y)) ->
(z : Plus X Y) ->
C z
elimPlus {X} {Y} C c_lft c_rgt (inl x) = c_lft x
elimPlus {X} {Y} C c_lft c_rgt (inr x) = c_rgt x
when : {X Y Z : Set} -> (X -> Z) -> (Y -> Z) -> Plus X Y -> Z
when {X} {Y} {Z} f g (inl x) = f x
when {X} {Y} {Z} f g (inr y) = g y
whenplus : {X Y Z : Set} -> (X -> Z) -> (Y -> Z) -> Plus X Y -> Z
whenplus = when
mapPlus : {X1 X2 Y1 Y2 : Set} -> (X1 -> X2) -> (Y1 -> Y2)
-> Plus X1 Y1 -> Plus X2 Y2
mapPlus f g = when (\x1 -> inl (f x1)) (\y1 -> inr (g y1))
swapPlus : {X Y : Set} -> Plus X Y -> Plus Y X
swapPlus = when inr inl
----------------------------------------------------------------------------
-- Dependent pairs.
----------------------------------------------------------------------------
data Sum (A : Set) (B : A -> Set) : Set where
sumI : (fst : A) -> B fst -> Sum A B
depPair : {A : Set} -> {B : A -> Set} -> (a : A) -> B a -> Sum A B
depPair a b = sumI a b
depFst : {A : Set} -> {B : A -> Set} -> (c : Sum A B) -> A
depFst (sumI fst snd) = fst
depSnd : {A : Set} -> {B : A -> Set} -> (c : Sum A B) -> B (depFst c)
depSnd (sumI fst snd) = snd
depCur : {A : Set} -> {B : A -> Set} -> {C : Set} -> (f : Sum A B -> C)
-> (a : A) -> B a -> C
depCur f = \a -> \b -> f (depPair a b)
-- the above works but the below does not---why?
-- depCur : {X : Set} -> {Y : X -> Set} -> {Z : Set} -> (f : Sum X Y -> Z)
-- -> {x : X} -> Y x -> Z
-- depCur {X} {Y} {Z} f = \{x} -> \y -> f (depPair x y)
-- Error message :
-- When checking that the expression \{x} -> \y -> f (depPair x y)
-- has type Y _x -> Z
-- found an implicit lambda where an explicit lambda was expected
depUncur : {A : Set} -> {B : A -> Set} -> {C : Set}
-> ((a : A) -> B a -> C) -> Sum A B -> C
depUncur f ab = f (depFst ab) (depSnd ab)
depCurry : {A : Set} ->
{B : A -> Set} ->
{C : Sum A B -> Set} ->
(f : (ab : Sum A B) -> C ab) ->
(a : A) ->
(b : B a) ->
C (depPair a b)
depCurry f a b = f (depPair a b)
depUncurry : {A : Set} ->
{B : A -> Set} ->
{C : Sum A B -> Set} ->
(f : (a : A) -> (b : B a) -> C (depPair a b)) ->
(ab : Sum A B) ->
C ab
depUncurry f (sumI fst snd) = f fst snd
mapSum : {A : Set} -> {B1 : A -> Set} -> {B2 : A -> Set}
-> (f : (a : A) -> B1 a -> B2 a)
-> Sum A B1 -> Sum A B2
mapSum f (sumI fst snd) = depPair fst (f fst snd)
elimSum = \{A : Set}{B : A -> Set}{C : Sum A B -> Set} -> depUncurry{A}{B}{C}
---------------------------------------------------------------------------
-- Nondependent pairs (binary) cartesian product.
---------------------------------------------------------------------------
Times : Set -> Set -> Set
Times A B = Sum A (\(_ : A) -> B)
pair : {A : Set} -> {B : Set} -> A -> B -> Times A B
pair a b = sumI a b
fst : {A : Set} -> {B : Set} -> Times A B -> A
fst (sumI a _) = a
snd : {A : Set} -> {B : Set} -> Times A B -> B
snd (sumI _ b) = b
pairfun : {C : Set} -> {A : Set} -> {B : Set}
-> (C -> A) -> (C -> B) -> C -> Times A B
pairfun f g c = pair (f c) (g c)
mapTimes : {A1 : Set} -> {A2 : Set} -> {B1 : Set} -> {B2 : Set}
-> (A1 -> A2) -> (B1 -> B2) -> Times A1 B1 -> Times A2 B2
mapTimes f g (sumI a b) = pair (f a) (g b)
swapTimes : {A : Set} -> {B : Set} -> Times A B -> Times B A
swapTimes (sumI a b) = sumI b a
cur : {A : Set} -> {B : Set} -> {C : Set} -> (f : Times A B -> C) -> A -> B -> C
cur f a b = f (pair a b)
uncur : {A : Set} -> {B : Set} -> {C : Set} -> (A -> B -> C) -> Times A B -> C
uncur f (sumI a b) = f a b
curry : {A : Set} -> {B : Set} -> {C : Times A B -> Set}
-> ((p : Times A B) -> C p) -> (a : A) ->(b : B) -> C (pair a b)
curry f a b = f (pair a b)
uncurry : {A : Set} -> {B : Set} -> {C : Times A B -> Set}
-> ((a : A) -> (b : B) -> C (pair a b)) -> (p : Times A B) -> C p
uncurry f (sumI a b) = f a b
elimTimes = \{A B : Set}{C : Times A B -> Set} -> uncurry{A}{B}{C}
---------------------------------------------------------------------------
-- Natural numbers.
---------------------------------------------------------------------------
data Nat : Set where
zero : Nat
succ : Nat -> Nat
elimNat : (C : Nat -> Set)
-> (C zero) -> ((m : Nat) -> C m -> C (succ m)) -> (n : Nat) -> C n
elimNat C c_z c_s zero = c_z
elimNat C c_z c_s (succ m') = c_s m' (elimNat C c_z c_s m')
----------------------------------------------------------------------------
-- Linear universe of finite sets.
----------------------------------------------------------------------------
Fin : (m : Nat) -> Set
Fin zero = Zero
Fin (succ n) = Succ (Fin n)
{-
Fin 0 = {}
Fin 1 = { zerS }
Fin 2 = { zerS (sucS zerS) }
Fin 3 = { zerS (sucS zerS) (sucS (sucS zerS)) }
-}
valFin : (n' : Nat) -> Fin n' -> Nat
valFin zero ()
valFin (succ n) zerS = zero
valFin (succ n) (sucS x) = succ (valFin n x)
zeroFin : (n : Nat) -> Fin (succ n)
zeroFin n = zerS
succFin : (n : Nat) -> Fin n -> Fin (succ n)
succFin n N = sucS N
----------------------------------------------------------------------------
-- Do these really belong here?
----------------------------------------------------------------------------
HEAD : {A : Set} -> (n : Nat) -> (Fin (succ n) -> A) -> A
HEAD n f = f (zeroFin n)
TAIL : {A : Set} -> (n : Nat) -> (Fin (succ n) -> A) -> Fin n -> A
TAIL n f N = f (succFin n N)
----------------------------------------------------------------------------
-- Lists.
----------------------------------------------------------------------------
data List (A : Set) : Set where
nil : List A
con : A -> List A -> List A
elimList : {A : Set} ->
(C : List A -> Set) ->
(C nil) ->
((a : A) -> (as : List A) -> C as -> C (con a as)) ->
(as : List A) ->
C as
elimList _ c_nil _ nil = c_nil
elimList C c_nil c_con (con a as) = c_con a as (elimList C c_nil c_con as)
----------------------------------------------------------------------------
-- Tuples are "dependently typed vectors".
----------------------------------------------------------------------------
data Nill : Set where
nill : Nill
data Cons (A B : Set) : Set where
cons : A -> B -> Cons A B
Tuple : (n : Nat) -> (C : Fin n -> Set) -> Set
Tuple zero = \ C -> Nill
Tuple (succ n) = \ C -> Cons (C zerS) (Tuple n (\(N : Fin n) -> C (sucS N)))
----------------------------------------------------------------------------
-- Vectors homogeneously typed tuples.
----------------------------------------------------------------------------
Vec : Set -> Nat -> Set
Vec A m = Tuple m (\(n : Fin m) -> A)
----------------------------------------------------------------------------
-- Monoidal expressions.
----------------------------------------------------------------------------
data Mon (A : Set) : Set where
unit : Mon A
at : A -> Mon A
mul : Mon A -> Mon A -> Mon A
{-
-}
----------------------------------------------------------------------------
-- Propositions.
----------------------------------------------------------------------------
data Implies (A B : Set) : Set where
impliesI : (A -> B) -> Implies A B
data Absurd : Set where
data Taut : Set where
tt : Taut
data Not (P : Set) : Set where
notI : (P -> Absurd) -> Not P
-- encoding of Exists is unsatisfactory! Its type should be Set.
data Exists (A : Set) (P : A -> Set) : Set where
existsI : (evidence : A) -> P evidence -> Exists A P
data Forall (A : Set) (P : A -> Set) : Set where
forallI : ((a : A) -> P a) -> Forall A P
data And (A B : Set) : Set where
andI : A -> B -> And A B
Iff : Set -> Set -> Set
Iff A B = And (Implies A B) (Implies B A)
data Or (A B : Set) : Set where
orIl : (a : A) -> Or A B
orIr : (b : B) -> Or A B
Decidable : Set -> Set
Decidable P = Or P (Implies P Absurd)
data DecidablePred {A : Set} (P : A -> Set) : Set where
decidablepredIl : (a : A) -> (P a) -> DecidablePred P
decidablepredIr : (a : A) -> (Implies (P a) Absurd) -> DecidablePred P
data DecidableRel {A : Set} (R : A -> A -> Set) : Set where
decidablerelIl : (a b : A) -> (R a b) -> DecidableRel R
decidablerelIr : (a b : A) -> (Implies (R a b) Absurd) -> DecidableRel R
data Least {A : Set} (_<=_ : A -> A -> Set) (P : A -> Set) (a : A) : Set where
leastI : (P a) -> ((aa : A) -> P aa -> (a <= aa)) -> Least _<=_ P a
data Greatest {A : Set} (_<=_ : A -> A -> Set) (P : A -> Set) (a : A) : Set where
greatestI : (P a) -> ((aa : A) -> P aa -> (aa <= a)) -> Greatest _<=_ P a
----------------------------------------------------------------------------
-- Booleans.
----------------------------------------------------------------------------
data Bool : Set where
true : Bool
false : Bool
elimBool : (C : Bool -> Set) -> C true -> C false -> (b : Bool) -> C b
elimBool C c_t c_f true = c_t
elimBool C c_t c_f false = c_f
whenBool : (C : Set) -> C -> C -> Bool -> C
whenBool C c_t c_f b = elimBool (\(_ : Bool) -> C) c_t c_f b
data pred (A : Set) : Set where
predI : (A -> Bool) -> pred A
data rel (A : Set) : Set where
relI : (A -> A -> Bool) -> rel A
True : Bool -> Set
True true = Taut
True false = Absurd
bool2set = True
pred2Pred : {A : Set} -> pred A -> Pred A
pred2Pred (predI p) = PredI (\a -> True (p a))
rel2Rel : {A : Set} -> rel A -> Rel A
rel2Rel (relI r) = RelI (\a -> \b -> True (r a b))
-- decTrue : (p : Bool) -> Decidable (True p)
-- decTrue true = orIl tt
-- decTrue false = orIr (impliesI pI)
-- decTrue false = orIr (impliesI (\(p : (True false)) -> p))
-- dec_lem : {P : Set} -> (decP : Decidable P)
-- -> Exists A
{-
abstract dec_lem (|P :: Set)(decP :: Decidable P)
:: Exist |_ (\(b :: Bool) -> Iff (True b) P)
= case decP of {
(inl trueP) ->
struct {
fst = true@_;
snd =
struct {
fst = const |_ |_ trueP; -- (True true@_)
snd = const |_ |_ tt;};};
(inr notP) ->
struct {
fst = false@_;
snd =
struct {
fst = whenZero P;
snd = notP;};};}
dec2bool :: (P :: Set) |-> (decP :: Decidable P) -> Bool
= \(P :: Set) |-> \(decP :: Decidable P) -> (dec_lem |_ decP).fst
dec2bool_spec (|P :: Set)(decP :: Decidable P)
:: Iff (True (dec2bool |_ decP)) P
= (dec_lem |_ decP).snd
abstract collTrue :: (b :: Bool) -> Collapsed (True b)
= let aux (X :: Set)(C :: X -> Set)
:: (b :: Bool) ->
(f :: True b -> X) ->
(t1 :: True b) |->
(t2 :: True b) |->
C (f t1) -> C (f t2)
= \(b :: Bool) ->
case b of {
(true) ->
\(f :: (x :: True true@_) -> X) ->
\(t1 t2 :: True true@_) |->
\(c :: C (f t1)) ->
case t1 of { (tt) -> case t2 of { (tt) -> c;};};
(false) ->
\(f :: (x :: True false@_) -> X) ->
\(t1 t2 :: True false@_) |->
\(c :: C (f t1)) ->
case t1 of { };}
in \(b :: Bool) -> \(P :: True b -> Set) -> aux (True b) P b id
bool2nat (p :: Bool) :: Nat
= case p of {
(true) -> succ zero;
(false) -> zero;}
-}
|
lemma asymp_equiv_tendsto_transfer: assumes "f \<sim>[F] g" and "(f \<longlongrightarrow> c) F" shows "(g \<longlongrightarrow> c) F" |
using HypergraphsEpidemics
using DataStructures
using SimpleHypergraphs
using Dates
households = generate_dataset("resources/gen_settings/Salerno/gen_param.json","resources/datasets/Salerno/")
# mean = sum(h -> h.num_components, households) / length(households)
start_simulation(
"resources/datasets/Salerno/dataset.csv",
"resources/datasets/Salerno/contacts.csv",
"resources/gen_settings/Salerno/gen_param.json",
"resources/datasets/Salerno/info.json"
)
df_generated_model, intervals, user2vertex, loc2he = HypergraphsEpidemics.generate_model_data(
"resources/datasets/Salerno/contacts.csv",
[:Time, :Id, :position], #Column list
:Id, #userid column
:position, #venue column
:Time, #Check in column
"yyyy-mm-ddTHH:MM:SS", #Date format
Δ = Dates.Millisecond(86400000), # 24 hours
δ = Dates.Millisecond(900000), # minutes
datarow = 2 # Data starts at second row
# limit = 10000 # limit
)
length(keys(loc2he)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.