text
stringlengths 0
3.34M
|
---|
/-
Copyright (c) 2014-15 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Partially ported from Coq HoTT
Theorems about sigma-types (dependent sums)
-/
import .prod
universes u v w
hott_theory
namespace hott
open hott.eq sigma hott.equiv hott.is_equiv function hott.is_trunc sum unit
@[reducible, hott]
def dpair {α β} := @sigma.mk α β
namespace sigma
variables {A : Type _} {A' : Type _} {B : A → Type _} {B' : A' → Type _} {C : Πa, B a → Type _}
{D : Πa b, C a b → Type _}
{a a' a'' : A} {b b₁ b₂ : B a} {b' : B a'} {b'' : B a''} {u v w : Σa, B a}
@[hott] def destruct := @sigma.cases_on
/- Paths in a sigma-type -/
@[hott] protected def eta : Π (u : Σa, B a), (⟨u.1 , u.2⟩: sigma _) = u
| ⟨u₁, u₂⟩ := idp
@[hott] def eta2 : Π (u : Σa b, C a b), (⟨u.1, u.2.1, u.2.2⟩: Σ _ _, _) = u
| ⟨u₁, u₂, u₃⟩ := idp
@[hott] def eta3 : Π (u : Σa b c, D a b c), (⟨u.1, u.2.1, u.2.2.1, u.2.2.2⟩: Σ _ _ _, _) = u
| ⟨u₁, u₂, u₃, u₄⟩ := idp
@[hott] def dpair_eq_dpair (p : a = a') (q : b =[p] b') : (⟨a, b⟩: Σ _, _) = ⟨a', b'⟩ :=
apd011 sigma.mk p q
@[hott] def sigma_eq (p : u.1 = v.1) (q : u.2 =[p] v.2) : u = v :=
by induction u; induction v; exact (dpair_eq_dpair p q)
@[hott] def sigma_eq_right (q : b₁ = b₂) : (⟨a, b₁⟩: Σ _, _) = ⟨a, b₂⟩ :=
ap (dpair a) q
@[hott] def eq_fst (p : u = v) : u.1 = v.1 :=
ap fst p
postfix `..1`:(max+1) := eq_fst
@[hott] def eq_snd (p : u = v) : u.2 =[p..1] v.2 :=
by induction p; exact idpo
postfix `..2`:(max+1) := eq_snd
@[hott] def dpair_sigma_eq (p : u.1 = v.1) (q : u.2 =[p] v.2)
: (⟨(sigma_eq p q)..1, (sigma_eq p q)..2⟩: Σ p, u.2 =[p] v.2) = ⟨p, q⟩ :=
by induction u; induction v;dsimp at *;induction q;refl
@[hott] def sigma_eq_fst (p : u.1 = v.1) (q : u.2 =[p] v.2) : (sigma_eq p q)..1 = p :=
(dpair_sigma_eq p q)..1
@[hott] def sigma_eq_snd (p : u.1 = v.1) (q : u.2 =[p] v.2)
: (sigma_eq p q)..2 =[sigma_eq_fst p q; λ p, u.2 =[p] v.2] q :=
(dpair_sigma_eq p q)..2
@[hott] def sigma_eq_eta (p : u = v) : sigma_eq (p..1) (p..2) = p :=
by induction p; induction u; reflexivity
@[hott] def eq2_fst {p q : u = v} (r : p = q) : p..1 = q..1 :=
ap eq_fst r
@[hott] def eq2_snd {p q : u = v} (r : p = q) : p..2 =[eq2_fst r; λ x, u.2 =[x] v.2] q..2 :=
by apply pathover_ap; apply (apd eq_snd r)
@[hott] def tr_fst_sigma_eq {B' : A → Type _} (p : u.1 = v.1) (q : u.2 =[p] v.2)
: transport (λx : sigma _, B' x.1) (sigma_eq p q) = transport B' p :=
by induction u; induction v; dsimp at *;induction q; reflexivity
@[hott] protected def ap_fst (p : u = v) : ap (λx : sigma B, x.1) p = p..1 := idp
/- the uncurried version of sigma_eq. We will prove that this is an equivalence -/
@[hott] def sigma_eq_unc : Π (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2), u = v
| ⟨pq₁, pq₂⟩ := sigma_eq pq₁ pq₂
@[hott] def dpair_sigma_eq_unc : Π (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2),
(⟨(sigma_eq_unc pq)..1, (sigma_eq_unc pq)..2⟩: Σ p, u.2 =[p] v.2) = pq
| ⟨pq₁, pq₂⟩ := dpair_sigma_eq pq₁ pq₂
@[hott] def sigma_eq_fst_unc (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2)
: (sigma_eq_unc pq)..1 = pq.1 :=
(dpair_sigma_eq_unc pq)..1
@[hott] def sigma_eq_snd_unc (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2) :
(sigma_eq_unc pq)..2 =[sigma_eq_fst_unc pq; λ p, u.2 =[p] v.2] pq.2 :=
(dpair_sigma_eq_unc pq)..2
@[hott] def sigma_eq_eta_unc (p : u = v) : sigma_eq_unc ⟨p..1, p..2⟩ = p :=
sigma_eq_eta p
@[hott] def tr_sigma_eq_fst_unc {B' : A → Type _}
(pq : Σ(p : u.1 = v.1), u.2 =[p] v.2)
: transport (λx:sigma _, B' x.1) (@sigma_eq_unc A B u v pq) = transport B' pq.1 :=
by apply destruct pq; apply tr_fst_sigma_eq
@[hott, instance] def is_equiv_sigma_eq (u v : Σa, B a)
: is_equiv (@sigma_eq_unc A B u v) :=
adjointify sigma_eq_unc
(λp, ⟨p..1, p..2⟩)
sigma_eq_eta_unc
dpair_sigma_eq_unc
@[hott] def sigma_eq_equiv (u v : Σa, B a)
: (u = v) ≃ (Σ(p : u.1 = v.1), u.2 =[p] v.2) :=
(equiv.mk sigma_eq_unc (by apply_instance))⁻¹ᵉ
@[hott] def dpair_eq_dpair_con (p1 : a = a' ) (q1 : b =[p1] b' )
(p2 : a' = a'') (q2 : b' =[p2] b'') :
dpair_eq_dpair (p1 ⬝ p2) (q1 ⬝o q2) = dpair_eq_dpair p1 q1 ⬝ dpair_eq_dpair p2 q2 :=
by induction q1; induction q2; reflexivity
@[hott] def sigma_eq_con (p1 : u.1 = v.1) (q1 : u.2 =[p1] v.2)
(p2 : v.1 = w.1) (q2 : v.2 =[p2] w.2) :
sigma_eq (p1 ⬝ p2) (q1 ⬝o q2) = sigma_eq p1 q1 ⬝ sigma_eq p2 q2 :=
by induction u; induction v; induction w; apply dpair_eq_dpair_con
@[hott] def dpair_eq_dpair_con_idp (p : a = a') (q : b =[p] b') :
dpair_eq_dpair p q = dpair_eq_dpair p (pathover_tr _ _) ⬝
dpair_eq_dpair idp (pathover_idp_of_eq _ (tr_eq_of_pathover q)) :=
by induction q; reflexivity
/- eq_fst commutes with the groupoid structure. -/
@[hott] def eq_fst_idp (u : Σa, B a) : (idpath u) ..1 = refl (u.1) := idp
@[hott] def eq_fst_con (p : u = v) (q : v = w) : (p ⬝ q) ..1 = (p..1) ⬝ (q..1) := ap_con _ _ _
@[hott] def eq_fst_inv (p : u = v) : p⁻¹ ..1 = (p..1)⁻¹ := ap_inv _ _
/- Applying dpair to one argument is the same as dpair_eq_dpair with reflexivity in the first place. -/
@[hott] def ap_dpair (q : b₁ = b₂) :
ap (sigma.mk a) q = dpair_eq_dpair idp (pathover_idp_of_eq _ q) :=
by induction q; reflexivity
/- Dependent transport is the same as transport along a sigma_eq. -/
@[hott] def transportD_eq_transport (p : a = a') (c : C a b) :
p ▸D c = transport (λu : sigma _, C (u.1) (u.2)) (dpair_eq_dpair p (pathover_tr _ _)) c :=
by induction p; reflexivity
@[hott] def sigma_eq_eq_sigma_eq {p1 q1 : a = a'} {p2 : b =[p1] b'} {q2 : b =[q1] b'}
(r : p1 = q1) (s : p2 =[r; λ p, b =[p] b'] q2) : @sigma_eq _ _ ⟨a,b⟩ ⟨a',b'⟩ p1 p2 = sigma_eq q1 q2 :=
by induction s; reflexivity
/- A path between paths in a total space is commonly shown component wise. -/
@[hott] def sigma_eq2 {p q : u = v} (r : p..1 = q..1) (s : p..2 =[r; λ p, u.2 =[p] v.2] q..2)
: p = q :=
begin
induction p, induction u with u1 u2,
transitivity sigma_eq q..1 q..2,
apply sigma_eq_eq_sigma_eq r s,
apply sigma_eq_eta,
end
@[hott] def sigma_eq2_unc {p q : u = v} (rs : Σ(r : p..1 = q..1), p..2 =[r; λ p, u.2 =[p] v.2] q..2) : p = q :=
by apply destruct rs; apply sigma_eq2
@[hott] def ap_dpair_eq_dpair (f : Πa, B a → A') (p : a = a') (q : b =[p] b')
: @ap _ A' (@sigma.rec _ _ (λ _, A') f) _ _ (dpair_eq_dpair p q) = apd011 f p q :=
by induction q; reflexivity
/- Transport -/
/- The concrete description of transport in sigmas (and also pis) is rather trickier than in the other types. In particular, these cannot be described just in terms of transport in simpler types; they require also the dependent transport [transportD].
In particular, this indicates why `transport` alone cannot be fully defined by induction on the structure of types, although Id-elim/transportD can be (cf. Observational Type _ Theory). A more thorough set of lemmas, along the lines of the present ones but dealing with Id-elim rather than just transport, might be nice to have eventually? -/
@[hott] def sigma_transport (p : a = a') (bc : Σ(b : B a), C a b)
: p ▸ bc = ⟨p ▸ bc.1, p ▸D bc.2⟩ :=
by induction p; induction bc; reflexivity
/- The special case when the second variable doesn't depend on the first is simpler. -/
@[hott] def sigma_transport_nondep {B : Type _} {C : A → B → Type _} (p : a = a')
(bc : Σ(b : B), C a b) : p ▸ bc = ⟨bc.1, transport (λ a, C a bc.1) p bc.2⟩ :=
by induction p; induction bc; reflexivity
/- Or if the second variable contains a first component that doesn't depend on the first. -/
@[hott] def sigma_transport2_nondep {C : A → Type _} {D : Π a:A, B a → C a → Type _} (p : a = a')
(bcd : Σ(b : B a) (c : C a), D a b c) : p ▸ bcd = ⟨p ▸ bcd.1, p ▸ bcd.2.1, p ▸D2 bcd.2.2⟩ :=
begin
induction p, induction bcd with b cd, induction cd, reflexivity
end
/- Pathovers -/
@[hott] def etao (p : a = a') (bc : Σ(b : B a), C a b)
: bc =[p; λ a, Σ b, C a b] ⟨p ▸ bc.1, p ▸D bc.2⟩ :=
by induction p; induction bc; apply idpo
-- TODO: interchange sigma_pathover and sigma_pathover'
@[hott] def sigma_pathover (p : a = a') (u : Σ(b : B a), C a b) (v : Σ(b : B a'), C a' b)
(r : u.1 =[p] v.1) (s : u.2 =[apd011 C p r; id] v.2) : u =[p; λ a, Σ b, C a b] v :=
begin
induction u, induction v, dsimp at *, induction r,
dsimp [apd011] at s, apply idp_rec_on s, apply idpo
end
@[hott] def sigma_pathover' (p : a = a') (u : Σ(b : B a), C a b) (v : Σ(b : B a'), C a' b)
(r : u.1 =[p] v.1) (s : @pathover (sigma _) ⟨a,u.1⟩ (λ x, C x.1 x.2) u.2 ⟨a',v.1⟩ (sigma_eq p r) v.2) :
u =[p; λ a, Σ b, C a b] v :=
begin
induction u, induction v, dsimp at *, induction r,
apply idp_rec_on s, apply idpo
end
@[hott] def sigma_pathover_nondep {B : Type _} {C : A → B → Type _} (p : a = a')
(u : Σ(b : B), C a b) (v : Σ(b : B), C a' b)
(r : u.1 = v.1) (s : @pathover (prod _ _) (a,u.1) (λx, C x.1 x.2) u.2 (a',v.1) (prod.prod_eq p r) v.2) :
u =[p; λ a, Σ b, C a b] v :=
begin
induction p, induction u, induction v, dsimp at *, induction r,
apply idp_rec_on s, apply idpo
end
@[hott] def pathover_fst {A : Type _} {B : A → Type _} {C : Πa, B a → Type _}
{a a' : A} {p : a = a'} {x : Σb, C a b} {x' : Σb', C a' b'}
(q : x =[p; λ a, Σb, C a b] x') : x.1 =[p] x'.1 :=
begin induction q, constructor end
@[hott] def sigma_pathover_equiv_of_is_prop {A : Type _} {B : A → Type _} (C : Πa, B a → Type _)
{a a' : A} (p : a = a') (x : Σb, C a b) (x' : Σb', C a' b')
[Πa b, is_prop (C a b)] : x =[p; λa, Σb, C a b] x' ≃ x.1 =[p] x'.1 :=
begin
fapply equiv.MK,
{ exact pathover_fst },
{ intro q, induction x with b c, induction x' with b' c', dsimp at q, induction q,
apply pathover_idp_of_eq, exact sigma_eq idp (is_prop.elimo _ _ _) },
{ intro q, induction x with b c, induction x' with b' c', dsimp at q, induction q,
have: c = c', by apply is_prop.elim, induction this,
dsimp, rwr is_prop_elimo_self, },
{ intro q, induction q, induction x with b c,
dsimp [pathover_fst], rwr is_prop_elimo_self }
end
/-
TODO:
* define the projections from the type u =[p] v
* show that the uncurried version of sigma_pathover is an equivalence
-/
/- Squares in a sigma type are characterized in cubical.squareover (to avoid circular imports) -/
/- Functorial action -/
variables (f : A → A') (g : Πa, B a → B' (f a))
@[hott] def sigma_functor (u : Σa, B a) : Σa', B' a' :=
⟨f u.1, g u.1 u.2⟩
@[hott] def total {B' : A → Type _} (g : Πa, B a → B' a) : (Σa, B a) → (Σa, B' a) :=
sigma_functor id g
/- Equivalences -/
@[hott] def is_equiv_sigma_functor [H1 : is_equiv f] [H2 : Π a, is_equiv (g a)]
: is_equiv (sigma_functor f g) :=
adjointify (sigma_functor f g)
(sigma_functor f⁻¹ᶠ (λ(a' : A') (b' : B' a'),
((g (f⁻¹ᶠ a'))⁻¹ᶠ (transport B' (right_inv f a')⁻¹ b'))))
begin abstract {
intro u', induction u' with a' b', fapply sigma_eq,
{apply right_inv f},
{dsimp [sigma_functor], rwr right_inv (g (f⁻¹ᶠ a')), apply tr_pathover}
} end
begin abstract {
intro u, induction u with a b, fapply sigma_eq,
{apply left_inv f},
{apply pathover_of_tr_eq, dsimp only [sigma_functor],
rwr [adj f, ← fn_tr_eq_tr_fn (left_inv f a) (λ a, (g a)⁻¹ᶠ),
tr_compose B', tr_inv_tr], dsimp, rwr left_inv }
} end
@[hott] def sigma_equiv_sigma_of_is_equiv
[H1 : is_equiv f] [H2 : Π a, is_equiv (g a)] : (Σa, B a) ≃ (Σa', B' a') :=
equiv.mk (sigma_functor f g) (is_equiv_sigma_functor _ _)
@[hott] def sigma_equiv_sigma (Hf : A ≃ A') (Hg : Π a, B a ≃ B' (Hf a)) :
(Σa, B a) ≃ (Σa', B' a') :=
sigma_equiv_sigma_of_is_equiv Hf (λ a, Hg a)
@[hott] def sigma_equiv_sigma_right {B' : A → Type _} (Hg : Π a, B a ≃ B' a)
: (Σa, B a) ≃ Σa, B' a :=
sigma_equiv_sigma equiv.rfl Hg
variable (B)
@[hott] def sigma_equiv_sigma_left (Hf : A ≃ A') :
(Σa, B a) ≃ (Σa', B (Hf⁻¹ᶠ a')) :=
sigma_equiv_sigma Hf (λ a, equiv_ap B (right_inv Hf⁻¹ᶠ a)⁻¹ᵖ)
@[hott] def sigma_equiv_sigma_left' (Hf : A' ≃ A) : (Σa, B (Hf a)) ≃ (Σa', B a') :=
sigma_equiv_sigma Hf (λa, erfl)
variable {B}
@[hott] def ap_sigma_functor_eq_dpair (p : a = a') (q : b =[p] b') :
ap (sigma_functor f g) (@sigma_eq _ _ ⟨a,b⟩ ⟨a',b'⟩ p q) =
sigma_eq (ap f p) (by exact pathover.rec_on q idpo) :=
by induction q; reflexivity
@[hott] def sigma_ua {A B : Type _} (C : A ≃ B → Type _) :
(Σ(p : A = B), C (equiv_of_eq p)) ≃ Σ(e : A ≃ B), C e :=
sigma_equiv_sigma_left' C (eq_equiv_equiv _ _)
-- @[hott] def ap_sigma_functor_eq (p : u.1 = v.1) (q : u.2 =[p] v.2)
-- : ap (sigma_functor f g) (sigma_eq p q) =
-- sigma_eq (ap f p)
-- ((tr_compose B' f p (g u.1 u.2))⁻¹ ⬝ (fn_tr_eq_tr_fn p g u.2)⁻¹ ⬝ ap (g v.1) q) :=
-- by induction u; induction v; apply ap_sigma_functor_eq_dpair
/- definition 3.11.9(i): Summing up a contractible family of types does nothing. -/
@[hott, instance] def is_equiv_fst (B : A → Type _) [H : Π a, is_contr (B a)]
: is_equiv (@fst A B) :=
adjointify fst
(λa, ⟨a, center _⟩)
(λa, idp)
(λu, sigma_eq idp (pathover_idp_of_eq _ (center_eq _)))
@[hott] def sigma_equiv_of_is_contr_right (B : A → Type _) [H : Π a, is_contr (B a)]
: (Σa, B a) ≃ A :=
equiv.mk fst (by apply_instance)
/- definition 3.11.9(ii): Dually, summing up over a contractible type does nothing. -/
@[hott] def sigma_equiv_of_is_contr_left (B : A → Type _) [H : is_contr A]
: (Σa, B a) ≃ B (center A) :=
equiv.MK
(λu, (center_eq u.1)⁻¹ ▸ u.2)
(λb, ⟨center _, b⟩)
begin abstract { intro b, change _ = idpath (center A) ▸ b,
apply ap (λx, x ▸ b), apply prop_eq_of_is_contr, } end
begin abstract { exact λu, sigma_eq (center_eq _) (tr_pathover _ _) } end
/- Associativity -/
--this proof is harder than in Coq because we don't have eta definitionally for sigma
@[hott] def sigma_assoc_equiv (C : (Σa, B a) → Type _)
: (Σa b, C ⟨a, b⟩) ≃ (Σu, C u) :=
equiv.mk _ (adjointify
(λav, ⟨⟨av.1, av.2.1⟩, av.2.2⟩)
(λuc, ⟨uc.1.1, uc.1.2, by rwr sigma.eta; exact uc.2⟩)
begin abstract { intro uc, induction uc with u c, induction u, reflexivity } end
begin abstract { intro av, induction av with a v, induction v, reflexivity } end)
open prod
@[hott] def assoc_equiv_prod (C : (A × A') → Type _) : (Σa a', C (a,a')) ≃ (Σu, C u) :=
equiv.mk _ (adjointify
(λav, ⟨(av.1, av.2.1), av.2.2⟩)
(λuc, ⟨(uc.1).1, (uc.1).2, by rwr prod.eta; exact uc.2⟩)
(λ ⟨⟨a,b⟩,c⟩, idp) (λ ⟨a,⟨b,c⟩⟩, idp))
/- Symmetry -/
@[hott] def comm_equiv_unc (C : A × A' → Type _) : (Σa a', C (a, a')) ≃ (Σa' a, C (a, a')) :=
calc
(Σa a', C (a, a')) ≃ Σu, C u : assoc_equiv_prod _
... ≃ Σv, C (flip v) : sigma_equiv_sigma (prod.prod_comm_equiv _ _)
(λ ⟨a,a'⟩, equiv.rfl)
... ≃ Σa' a, C (a, a') : by symmetry; exact assoc_equiv_prod (C ∘ prod.flip)
@[hott] def sigma_comm_equiv (C : A → A' → Type _)
: (Σa a', C a a') ≃ (Σa' a, C a a') :=
comm_equiv_unc (λu, C (fst u) (snd u))
@[hott] def equiv_prod (A B : Type _) : (Σ(a : A), B) ≃ A × B :=
equiv.mk _ (adjointify
(λs, (s.1, s.2))
(λp, ⟨fst p, snd p⟩)
(λ⟨a,b⟩, idp) (λ⟨a,b⟩, idp))
@[hott] def comm_equiv_nondep (A B : Type _) : (Σ(a : A), B) ≃ Σ(b : B), A :=
calc
(Σ(a : A), B) ≃ A × B : by apply equiv_prod
... ≃ B × A : by apply prod.prod_comm_equiv
... ≃ Σ(b : B), A : by symmetry; apply equiv_prod
@[hott] def sigma_assoc_comm_equiv {A : Type _} (B C : A → Type _)
: (Σ(v : Σa, B a), C v.1) ≃ (Σ(u : Σa, C a), B u.1) :=
calc (Σ(v : Σa, B a), C v.1)
≃ (Σa (b : B a), C a) : by symmetry; apply sigma_assoc_equiv (C ∘ fst)
... ≃ (Σa (c : C a), B a) : by apply sigma_equiv_sigma_right; intro a; apply comm_equiv_nondep
... ≃ (Σ(u : Σa, C a), B u.1) : by apply sigma_assoc_equiv (B ∘ fst)
/- Interaction with other type constructors -/
@[hott] def sigma_empty_left (B : empty → Type _) : (Σx, B x) ≃ empty :=
begin
fapply equiv.MK,
{ intro v, induction v, cases v_fst},
{ intro x, cases x},
{ intro x, cases x},
{ intro v, induction v, cases v_fst},
end
@[hott] def sigma_empty_right (A : Type _) : (Σ(a : A), empty) ≃ empty :=
begin
fapply equiv.MK,
{ intro v, induction v, cases v_snd},
{ intro x, cases x},
{ intro x, cases x},
{ intro v, induction v, cases v_snd},
end
@[hott] def sigma_unit_left (B : unit → Type _) : (Σx, B x) ≃ B star :=
sigma_equiv_of_is_contr_left _
@[hott] def sigma_unit_right (A : Type _) : (Σ(a : A), unit) ≃ A :=
sigma_equiv_of_is_contr_right _
@[hott] def sigma_sum_left (B : A ⊎ A' → Type _)
: (Σp, B p) ≃ (Σa, B (inl a)) ⊎ (Σa, B (inr a)) :=
begin
fapply equiv.MK,
{ intro v,
induction v with p b,
induction p,
{ apply inl, constructor, assumption },
{ apply inr, constructor, assumption }},
{ intro p, induction p with v v; induction v; constructor; assumption},
{ intro p, induction p with v v; induction v; reflexivity},
{ intro v, induction v with p b, induction p; reflexivity},
end
@[hott] def sigma_sum_right (B C : A → Type _)
: (Σa, B a ⊎ C a) ≃ (Σa, B a) ⊎ (Σa, C a) :=
begin
fapply equiv.MK,
{ intro v,
induction v with a p,
induction p,
{ apply inl, constructor, assumption},
{ apply inr, constructor, assumption}},
{ intro p,
induction p with v v,
{ induction v, constructor, apply inl, assumption },
{ induction v, constructor, apply inr, assumption }},
{ intro p, induction p with v v; induction v; reflexivity},
{ intro v, induction v with a p, induction p; reflexivity},
end
@[hott] def sigma_sigma_eq_right {A : Type _} (a : A) (P : Π(b : A), a = b → Type _)
: (Σ(b : A) (p : a = b), P b p) ≃ P a idp :=
calc
(Σ(b : A) (p : a = b), P b p) ≃ (Σ(v : Σ(b : A), a = b), P v.1 v.2) : by apply sigma_assoc_equiv (λ u, P u.fst u.snd)
... ≃ P a idp : by apply sigma_equiv_of_is_contr_left (λ v : Σ b, a=b, P v.fst v.snd)
@[hott] def sigma_sigma_eq_left {A : Type _} (a : A) (P : Π(b : A), b = a → Type _)
: (Σ(b : A) (p : b = a), P b p) ≃ P a idp :=
calc
(Σ(b : A) (p : b = a), P b p) ≃ (Σ(v : Σ(b : A), b = a), P v.1 v.2) : by apply sigma_assoc_equiv (λ u : Σ b, b=a, P u.fst u.snd)
... ≃ P a idp : by apply sigma_equiv_of_is_contr_left (λ v : Σ b, b=a, P v.fst v.snd)
/- ** Universal mapping properties -/
/- *** The positive universal property. -/
section
@[hott, instance] def is_equiv_sigma_rec (C : (Σa, B a) → Type _)
: is_equiv (sigma.rec : (Πa b, C ⟨a, b⟩) → Πab, C ab) :=
adjointify _ (λ g a b, g ⟨a, b⟩)
(λ g, eq_of_homotopy (λ⟨a,b⟩, idp))
(λ f, refl f)
@[hott] def equiv_sigma_rec (C : (Σa, B a) → Type _)
: (Π(a : A) (b: B a), C ⟨a, b⟩) ≃ (Πxy, C xy) :=
equiv.mk sigma.rec (by apply_instance)
/- *** The negative universal property. -/
@[hott] protected def coind_unc (fg : Σ(f : Πa, B a), Πa, C a (f a)) (a : A)
: Σ(b : B a), C a b :=
⟨fg.1 a, fg.2 a⟩
@[hott] protected def coind (f : Π a, B a) (g : Π a, C a (f a)) (a : A) : Σ(b : B a), C a b :=
sigma.coind_unc ⟨f, g⟩ a
--is the instance below dangerous?
--in Coq this can be done without function extensionality
@[hott, instance] def is_equiv_coind (C : Πa, B a → Type _)
: is_equiv (@sigma.coind_unc _ _ C) :=
adjointify _ (λ h, ⟨λa, (h a).1, λa, (h a).2⟩)
(λ h, eq_of_homotopy (λu, sigma.eta _))
(λ⟨f,g⟩, idp)
variable (C)
@[hott] def sigma_pi_equiv_pi_sigma : (Σ(f : Πa, B a), Πa, C a (f a)) ≃ (Πa, Σb, C a b) :=
equiv.mk sigma.coind_unc (by apply_instance)
variable {C}
end
/- Subtypes (sigma types whose second components are props) -/
@[hott] def subtype {A : Type _} (P : A → Type _) [H : Πa, is_prop (P a)] :=
Σ(a : A), P a
notation [parsing_only] `{` binder `|` r:(scoped:1 P, subtype P) `}` := r
/- To prove equality in a subtype, we only need equality of the first component. -/
@[hott] def subtype_eq [H : Πa, is_prop (B a)] {u v : {a | B a}} :
u.1 = v.1 → u = v :=
sigma_eq_unc ∘ inv fst
@[hott] def is_equiv_subtype_eq [H : Πa, is_prop (B a)] (u v : {a | B a})
: is_equiv (subtype_eq : u.1 = v.1 → u = v) :=
is_equiv_compose _ _
local attribute [instance] is_equiv_subtype_eq
@[hott] def equiv_subtype [H : Πa, is_prop (B a)] (u v : {a | B a}) :
(u.1 = v.1) ≃ (u = v) :=
equiv.mk subtype_eq (by apply_instance)
@[hott] def subtype_eq_equiv [H : Πa, is_prop (B a)] (u v : {a | B a}) :
(u = v) ≃ (u.1 = v.1) :=
(equiv_subtype u v)⁻¹ᵉ
@[hott] def subtype_eq_inv {A : Type _} {B : A → Type _} [H : Πa, is_prop (B a)] (u v : Σa, B a)
: u = v → u.1 = v.1 :=
subtype_eq⁻¹ᶠ
@[hott] def is_equiv_subtype_eq_inv {A : Type _} {B : A → Type _} [H : Πa, is_prop (B a)]
(u v : Σa, B a) : is_equiv (subtype_eq_inv u v) :=
by delta subtype_eq_inv; apply_instance
/- truncatedness -/
@[hott] def is_trunc_sigma (B : A → Type _) (n : trunc_index)
[HA : is_trunc n A] [HB : Πa, is_trunc n (B a)] : is_trunc n (Σa, B a) :=
begin
unfreezeI, revert A B HA HB,
induction n with n IH; resetI,
{ intros A B HA HB, apply is_trunc_equiv_closed_rev -2 (sigma_equiv_of_is_contr_left B) (HB _) },
{ intros A B HA HB, apply is_trunc_succ_intro, intros u v,
apply is_trunc_equiv_closed_rev _ (sigma_eq_equiv _ _) (IH _);
apply_instance }
end
@[hott] theorem is_trunc_subtype (B : A → Prop) (n : trunc_index)
[HA : is_trunc (n.+1) A] : is_trunc (n.+1) (Σa, B a) :=
@is_trunc_sigma _ (λ a, B a) (n.+1) _ (λa, is_trunc_succ_of_is_prop _ _)
/- if the total space is a mere proposition, you can equate two points in the base type by
finding points in their fibers -/
@[hott] def eq_base_of_is_prop_sigma {A : Type _} (B : A → Type _) (H : is_prop (Σa, B a)) {a a' : A}
(b : B a) (b' : B a') : a = a' :=
(@is_prop.elim (Σa, B a) _ ⟨a, b⟩ ⟨a', b'⟩)..1
end sigma
attribute [instance] sigma.is_trunc_sigma
attribute [instance] sigma.is_trunc_subtype
namespace sigma
/- pointed sigma type -/
open pointed
@[hott, instance] def pointed_sigma {A : Type _} (P : A → Type _) [G : pointed A]
[H : pointed (P pt)] : pointed (Σx, P x) :=
pointed.mk ⟨pt,pt⟩
@[hott] def psigma {A : Type*} (P : A → Type*) : Type* :=
pointed.mk' (Σa, P a)
notation `Σ*` binders `, ` r:(scoped P, psigma P) := r
@[hott] def pfst {A : Type*} {B : A → Type*} : (Σ*(x : A), B x) →* A :=
pmap.mk fst idp
@[hott] def psnd {A : Type*} {B : A → Type*} (v : (Σ*(x : A), B x)) : B (pfst.to_fun v) :=
snd v
@[hott] def ptsigma {n : ℕ₋₂} {A : n-Type*} (P : A → (n-Type*)) : n-Type* :=
ptrunctype.mk' n (Σa, P a)
end sigma
end hott
|
function G = greens_function_mono(x,y,z,xs,src,f,conf)
%GREENS_FUNCTION_MONO Green's function in the frequency domain
%
% Usage: G = greens_function_mono(x,y,z,xs,src,f,conf)
%
% Input options:
% x,y,z - x,y,z points for which the Green's function should be
% calculated / m
% xs - position of the source
% src - source model of the Green's function. Valid models are:
% 'ps' - point source
% 'ls' - line source
% 'pw' - plane wave
% 'dps' - dipole point source
% f - frequency of the source / Hz
% conf - configuration struct (see SFS_config)
%
% Output parameters:
% G - Green's function evaluated at the points x,y,z
%
% GREENS_FUNCTION_MONO(x,y,z,xs,src,f,conf) calculates the Green's function
% for the given source model located at xs for the given points x,y and the
% frequency f.
%
% See also: sound_field_mono
%*****************************************************************************
% The MIT License (MIT) *
% *
% Copyright (c) 2010-2019 SFS Toolbox Developers *
% *
% Permission is hereby granted, free of charge, to any person obtaining a *
% copy of this software and associated documentation files (the "Software"), *
% to deal in the Software without restriction, including without limitation *
% the rights to use, copy, modify, merge, publish, distribute, sublicense, *
% and/or sell copies of the Software, and to permit persons to whom the *
% Software is furnished to do so, subject to the following conditions: *
% *
% The above copyright notice and this permission notice shall be included in *
% all copies or substantial portions of the Software. *
% *
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *
% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
% DEALINGS IN THE SOFTWARE. *
% *
% The SFS Toolbox allows to simulate and investigate sound field synthesis *
% methods like wave field synthesis or higher order ambisonics. *
% *
% https://sfs.readthedocs.io [email protected] *
%*****************************************************************************
%% ===== Checking of input parameters ==================================
% Disabled checking for performance reasons
%% ===== Configuration ==================================================
c = conf.c;
phase = conf.phase;
%% ===== Computation =====================================================
% Frequency
omega = 2*pi*f;
% Calculate Green's function for the given source model
if strcmp('ps',src)
% Source model for a point source: 3D Green's function.
%
% 1 e^(-i w/c |x-xs|)
% G(x-xs,w) = --- -----------------
% 4pi |x-xs|
%
% https://sfs.rtfd.io/en/3.2/sources/#equation-fd-point
%
G = 1/(4*pi) * exp(-1i*omega/c .* sqrt((x-xs(1)).^2+(y-xs(2)).^2+(z-xs(3)).^2)) ./ ...
sqrt((x-xs(1)).^2+(y-xs(2)).^2+(z-xs(3)).^2);
elseif strcmp('dps',src)
% Source model for a dipole point source: derivative of 3D Green's function.
%
% d 1 / iw 1 \ (x-xs) ns
% ---- G(x-xs,w) = --- | ----- + ------- | ----------- e^(-i w/c |x-xs|)
% d ns 4pi \ c |x-xs| / |x-xs|^2
%
% r = |x-xs|
r = sqrt((x-xs(1)).^2+(y-xs(2)).^2+(z-xs(3)).^2);
% scalar = (x-xs) nxs
scalar = xs(4).*(x-xs(1)) + xs(5).*(y-xs(2)) + xs(6).*(z-xs(3));
%
G = 1/(4*pi) .* (1i*omega/c + 1./r) .* scalar./r.^2 .* exp(-1i*omega/c.*r);
elseif strcmp('ls',src)
% Source model for a line source: 2D Green's function.
%
% i (2) / w \
% G(x-xs,w) = - - H0 | - |x-xs| |
% 4 \ c /
%
% https://sfs.rtfd.io/en/3.2/sources/#equation-fd-line
%
G = -1i/4 * besselh(0,2,omega/c* ...
sqrt( (x-xs(1)).^2 + (y-xs(2)).^2 + (z-xs(3)).^2 ));
elseif strcmp('pw',src)
% Source model for a plane wave:
%
% G(x,w) = e^(-i w/c n x)
%
% https://sfs.rtfd.io/en/3.2/sources/#equation-fd-plane
%
% Direction of plane wave
nxs = xs(:,1:3) / norm(xs(:,1:3));
% Calculate sound field
G = exp(-1i*omega/c.*(nxs(1).*x+nxs(2).*y+nxs(3).*z));
else
error('%s: %s is not a valid source model for the Green''s function', ...
upper(mfilename),src);
end
% Add phase to be able to simulate different time steps
G = G .* exp(-1i*phase);
|
#' wrap up an atlas object from mc, mc2d and matrix ids
#'
#' This is not doing much more than generating a list with the relevant object names bundeled. To be enhnaced at some stage.
#'
#' @param mat_id id of metacell object ina scdb
#' @param mc_id id of metacell object ina scdb
#' @param gset_id features defining the atlas (to be sued for determing projection)
#' @param mc2d_id projection object id, to define the atlas 2D layout
#'
#' @export
mcell_gen_atlas = function(mat_id, mc_id, gset_id, mc2d_id, atlas_cols = NULL)
{
return(list(mat_id = mat_id,
mc_id = mc_id,
gset_id = gset_id,
mc2d_id = mc2d_id,
atlas_cols = atlas_cols))
}
#' Project a metacell object on a reference "atlas"
#'
#' This will take each cell in the query object and find its to correlated
#' metacell in the reference, then generating figures showing detailed comparison of how each metacell in the query is distributed in the atlas, and how the pool of all cells in the query MC compare to the pool of their best match projections
#'
#' @param mat_id id of metacell object ina scdb
#' @param mc_id id of metacell object ina scdb
#' @param atlas an object generated by mcell_gen_atlas
#' @param fig_cmp_dir name of directory to put figures per MC
#' @param ten2mars should gene mapping be attmpeted using standard MARS-seq to 10x naming convetnion
#' @param gene_name_map if this is dedining a named vector query_name[ref_name], then the name conversion between the query and reference will be determined using it
#' @param md_field metadata field too use as additional factor for plotting subsets
#' @param recolor_mc_id if this is specified, the atlas colors will be projected on the query MCCs and updated to the scdb object named recolor_mc
#' @param plot_all_mc set this to T if you want a plot per metacell to show comparison of query pooled umi's and projected pooled umis.
#'
#' @export
#'
mcell_proj_on_atlas = function(mat_id, mc_id, atlas,
fig_cmp_dir,
ten2mars=T,
gene_name_map=NULL,
recolor_mc_id = NULL,
plot_all_mcs = F,
md_field=NULL,
max_entropy=2,
burn_cor=0.6)
{
ref_mc = scdb_mc(atlas$mc_id)
if(is.null(ref_mc)) {
stop("mc id ", ref_mc_id, " is missing")
}
query_mc = scdb_mc(mc_id)
if(is.null(query_mc)) {
stop("mc id ", mc_id, " is missing")
}
mat = scdb_mat(mat_id)
if(is.null(mat)) {
stop("mat id ", mat_id, " is missing")
}
gset = scdb_gset(atlas$gset_id)
if(is.null(gset)) {
stop("gset id ", feat_gset_id, " is missing")
}
ref_mc2d = scdb_mc2d(atlas$mc2d_id)
if(is.null(ref_mc2d)) {
stop("ref_mc2d ", ref_mc2d, " is missing")
}
if(is.null(gene_name_map)) {
if(ten2mars) {
gene_name_map = gen_10x_mars_gene_match(mars_mc_id = mc_id, tenx_mc_id = atlas$mc_id)
} else {
gene_name_map = rownames(query_mc@e_gc)
names(gene_name_map) = gene_name_map
}
}
#check cor of all cells, features
common_genes_ref = names(gset@gene_set)
common_genes_ref = common_genes_ref[!is.na(gene_name_map[common_genes_ref])]
common_genes_ref = intersect(common_genes_ref, rownames(ref_mc@e_gc))
common_genes_ref = common_genes_ref[!is.na(gene_name_map[common_genes_ref])]
common_genes_ref = common_genes_ref[gene_name_map[common_genes_ref] %in% rownames(query_mc@e_gc)]
common_genes_ref = common_genes_ref[gene_name_map[common_genes_ref] %in% rownames(mat@mat)]
common_genes = gene_name_map[common_genes_ref]
if(mean(!is.null(common_genes)) < 0.5) {
stop("less than half of the atlas feature genes can be mapped to reference gene names. Probably should provide a name conversion table")
}
browser()
feats = mat@mat[common_genes, names(query_mc@mc)]
rownames(feats) = common_genes_ref
ref_abs_lfp = log(1e-6+ref_mc@e_gc[common_genes_ref,])
ref_abs_fp = ref_mc@e_gc[common_genes_ref,]
cross = tgs_cor((cbind(ref_abs_lfp, as.matrix(feats))))
cross1 = cross[1:ncol(ref_abs_lfp),ncol(ref_abs_lfp)+1:ncol(feats)]
f = rowSums(is.na(cross1))
cross1[f,] = 0
best_ref = as.numeric(unlist(apply(cross1,2,function(x) names(which.max(x)))))
best_ref_cor = apply(cross1, 2, max)
# browser()
c_nms = names(query_mc@mc)
mc_proj_col_p = table(query_mc@mc[c_nms], ref_mc@colors[best_ref])
mc_proj_col_p = mc_proj_col_p/rowSums(mc_proj_col_p)
query_entropy = apply(mc_proj_col_p, 1,
function(x) { p =x/sum(x); lp =log2(p+1e-6); return(sum(-p*lp)) })
if(!is.null(recolor_mc_id) & !is.na(recolor_mc_id)) {
proj_col=ref_mc@colors[as.numeric(unlist(best_ref))]
new_col=tapply(proj_col,
query_mc@mc,
function(x) { names(which.max(table(x))) }
)
query_mc@colors = new_col
query_mc@colors[query_entropy > max_entropy] = "gray"
scdb_add_mc(recolor_mc_id, query_mc)
}
if(!is.null(fig_cmp_dir)) {
if(!dir.exists(fig_cmp_dir)) {
dir.create(fig_cmp_dir)
}
png(sprintf("%s/comp_2d.png", fig_cmp_dir), w=1200, h=1200)
}
layout(matrix(c(1,2),nrow=2), h=c(1,4))
par(mar=c(0,3,2,3))
plot(best_ref_cor[order(query_mc@mc)], pch=19, col=ref_mc@colors[best_ref[order(query_mc@mc)]],cex=0.6)
grid()
par(mar=c(3,3,0,3))
n = length(best_ref)
xrange = 0.02*(max(ref_mc2d@mc_x) - min(ref_mc2d@mc_x))
yrange = 0.02*(max(ref_mc2d@mc_y) - min(ref_mc2d@mc_y))
ref_x = ref_mc2d@mc_x[best_ref]+rnorm(n, 0, xrange)
ref_y = ref_mc2d@mc_y[best_ref]+rnorm(n, 0, yrange)
xlim = c(min(ref_mc2d@mc_x), max(ref_mc2d@mc_x))
ylim = c(min(ref_mc2d@mc_y), max(ref_mc2d@mc_y))
plot(ref_x, ref_y, pch=19, col=ref_mc@colors[best_ref], ylim=ylim, xlim=xlim)
if(!is.null(fig_cmp_dir)) {
dev.off()
} else {
return
}
query_mc_on_ref = t(tgs_matrix_tapply(ref_abs_fp[,best_ref],
query_mc@mc, mean))
rownames(query_mc_on_ref) = common_genes
cmp_lfp_1 = log2(1e-6+query_mc_on_ref)
cmp_lfp_1n = cmp_lfp_1 - rowMeans(cmp_lfp_1)
cmp_lfp_2 = log2(1e-6+query_mc@e_gc[common_genes,])
cmp_lfp_2n = cmp_lfp_2 - rowMeans(cmp_lfp_2)
cmp_lfp_n = cbind(cmp_lfp_1n, cmp_lfp_2n)
n = ncol(cmp_lfp_n)/2
cross = tgs_cor(cmp_lfp_n)
if(is.null(atlas$atlas_cols)) {
atlas_cols = colnames(mc_proj_col_p)
} else {
atlas_cols = atlas$atlas_cols
}
png(sprintf("%s/query_color_dist.png", fig_cmp_dir),w=600,h=150+12*nrow(mc_proj_col_p))
layout(matrix(c(1,2),nrow=1),widths=c(5,2))
par(mar=c(2,3,2,0))
barplot(t(mc_proj_col_p[,atlas_cols]), col=atlas_cols, horiz=T, las=2)
par(mar=c(2,0,2,3))
barplot(query_entropy, col=query_mc@colors, horiz=T, las=2)
grid()
dev.off()
png(sprintf("%s/query_ref_cmp.png", fig_cmp_dir),w=600,h=600)
shades = colorRampPalette(c("black", "darkblue", "white", "darkred", "yellow"))(1000)
layout(matrix(c(1,4,2,3),nrow=2), h=c(10,1), w=c(1,10))
par(mar=c(0,3,2,0))
query_ref_colors = table(query_mc@mc, ref_mc@colors[best_ref])
query_mc_top_color = colnames(query_ref_colors)[apply(query_ref_colors,1,which.max)]
image(t(as.matrix(1:length(query_mc@colors),nrow=1)),
col=query_mc_top_color, yaxt='n', xaxt='n')
mtext(1:n,at=seq(0,1,l=n),side=2, las=1)
par(mar=c(0,0,2,2))
image(pmin(pmax(cross[1:n, n+(1:n)],-burn_cor),burn_cor), col=shades,xaxt='n', yaxt='n', zlim=c(-burn_cor, burn_cor))
par(mar=c(3,0,0,2))
image(as.matrix(1:length(query_mc@colors),nrow=1),
col=query_mc@colors, yaxt='n', xaxt='n')
mtext(1:n,at=seq(0,1,l=n),side=1, las=1)
dev.off()
if(plot_all_mcs) {
ref_glob_p = rowMeans(ref_abs_fp)
for(mc_i in 1:ncol(query_mc@mc_fp)) {
ref_lfp = sort((query_mc_on_ref[,mc_i]+1e-5)/(ref_glob_p+1e-5))
ref_marks = gene_name_map[names(tail(ref_lfp,15))]
fig_nm = sprintf("%s/%d.png", fig_cmp_dir, mc_i)
png(fig_nm, w=800, h=1200)
layout(matrix(c(1,2), nrow=2))
mcell_plot_freq_compare(query_mc@e_gc[common_genes,mc_i],
query_mc_on_ref[,mc_i],
n_reg = 1e-5,
top_genes=20,
highlight_genes = ref_marks,
fig_h=600, fig_w=800,
lab1="query", lab2="reference",
main=sprintf("reference/query, compare mc %d", mc_i))
par(mar=c(2,2,2,2))
plot(ref_mc2d@sc_x, ref_mc2d@sc_y, cex=0.2, pch=19, col="gray")
f = query_mc@mc==mc_i
points(ref_x[f], ref_y[f], pch=19, col=ref_mc@colors[best_ref[f]])
dev.off()
}
}
if(!is.null(md_field)) {
md = mat@cell_metadata
if(md_field %in% colnames(md)) {
md_vs = md[names(query_mc@mc),md_field]
for(v in unique(md_vs)) {
fig_nm = sprintf("%s/md_%s.png", fig_cmp_dir, v)
png(fig_nm, w=800,h=800)
f = (md_vs == v)
plot(ref_mc2d@sc_x, ref_mc2d@sc_y, cex=0.2, pch=19, col="gray")
points(ref_x[f], ref_y[f], pch=19, col=ref_mc@colors[best_ref[f]])
dev.off()
}
} else {
message("MD field ", md_field, " not found")
}
}
return(query_mc_on_ref)
#plot compare_bulk
}
#' Generate mapping of 10x to mars names
#'
#' Not more than finding which concatenated names (";" delimited) are related to 10x gene names. Should be replaced by something more systematic that will happen during import
#'
#' @param mars_mc_id metacell id of a mars-seq dataset
#' @param tenx_mc_id metacell id of a 10x dataset
#'
#' @export
gen_10x_mars_gene_match = function(mars_mc_id, tenx_mc_id)
{
mc1 = scdb_mc(mars_mc_id)
if(is.null(mc1)) {
stop("not mars mc ", mars_mc_id)
}
mc2 = scdb_mc(tenx_mc_id)
if(is.null(mc2)) {
stop("not tenx mc ", tenx_mc_id)
}
mars_m_nms = rownames(mc1@e_gc)
mars_nms = strsplit(mars_m_nms, ";")
mars_n = unlist(lapply(mars_nms, length))
mars_v = rep(mars_m_nms,times=mars_n)
names(mars_v) = unlist(mars_nms)
nm10x = rownames(mc2@e_gc)
ten2mars = mars_v[nm10x]
f = !duplicated(ten2mars)
mars2ten = nm10x[f]
names(mars2ten) = ten2mars[f]
return(ten2mars)
}
|
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
** **
** This file forms part of the Underworld geophysics modelling application. **
** **
** For full license and copyright information, please refer to the LICENSE.md file **
** located at the project root, or contact the authors. **
** **
**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/
#include <petsc.h>
#include <petscmat.h>
#include <petscvec.h>
#include <StGermain/StGermain.h>
#include <StgDomain/StgDomain.h>
#include "common-driver-utils.h"
#include "stokes_block_scaling.h"
#include <StgFEM/StgFEM.h>
#include <PICellerator/PICellerator.h>
#include <Underworld/Underworld.h>
#include "Solvers/SLE/SLE.h" /* to give the AugLagStokes_SLE type */
#include "Solvers/KSPSolvers/KSPSolvers.h" /* for __KSP_COMMON */
#include "BSSCR.h"
#include "writeMatVec.h"
/* creates and builds the "checker-board" null-space vectors for pressure
and sets the t and v "Vec pointers" on the bsscr struct to point to them */
#undef __FUNCT__
#define __FUNCT__ "KSPBuildPressure_CB_Nullspace_BSSCR"
PetscErrorCode KSPBuildPressure_CB_Nullspace_BSSCR(KSP ksp)
{
KSP_BSSCR *bsscr = (KSP_BSSCR *)ksp->data;
FeEquationNumber *eq_num = bsscr->solver->st_sle->pSolnVec->eqNum;
FeMesh *feMesh = bsscr->solver->st_sle->pSolnVec->feVariable->feMesh; /* is the pressure mesh */
unsigned ijk[3];
Vec t, v;
int numLocalNodes, globalNodeNumber, i, j, eq;
MatStokesBlockScaling BA = bsscr->BA;
PetscErrorCode ierr;
Mat Amat,Pmat, G;
MatStructure pflag;
PetscFunctionBegin;
/* get G matrix from Amat matrix operator on ksp */
ierr=Stg_PCGetOperators(ksp->pc,&Amat,&Pmat,&pflag);CHKERRQ(ierr);
MatNestGetSubMat( Amat, 0,1, &G );/* G should always exist */
/* now create Vecs t and v to match size of G: i.e. pressure */ /* NOTE: not using "h" vector from ksp->vec_rhs because this part of the block vector doesn't always exist */
MatGetVecs( G, &t, PETSC_NULL );/* t and v are destroyed in KSPDestroy_BSSCR */
MatGetVecs( G, &v, PETSC_NULL );/* t and v such that can do G*t */
numLocalNodes = Mesh_GetLocalSize( feMesh, MT_VERTEX); /* number of nodes on current proc not counting any shadow nodes */
for(j=0;j<numLocalNodes;j++){
i = globalNodeNumber = Mesh_DomainToGlobal( feMesh, MT_VERTEX, j);
RegularMeshUtils_Element_1DTo3D(feMesh, i, ijk);
eq = eq_num->mapNodeDof2Eq[j][0];/* get global equation number -- 2nd arg is always 0 because pressure has only one dof */
if(eq != -1){
if( (ijk[0]+ijk[1]+ijk[2])%2 ==0 ){
VecSetValue(t,eq,1.0,INSERT_VALUES);
}
else{
VecSetValue(v,eq,1.0,INSERT_VALUES); }}}
VecAssemblyBegin( t );
VecAssemblyEnd( t );
VecAssemblyBegin( v );
VecAssemblyEnd( v );
/* Scaling the null vectors here because it easier at the moment *//* maybe should do this in the original scaling function */
if( BA->scaling_exists == PETSC_TRUE ){
Vec R2;
/* Get the scalings out the block mat data */
VecNestGetSubVec( BA->Rz, 1, &R2 );
VecPointwiseDivide( t, t, R2); /* x <- x * 1/R2 */
VecPointwiseDivide( v, v, R2);
}
// bsscr_writeVec( t, "t", "Writing t vector");
// bsscr_writeVec( v, "v", "Writing v vector");
bsscr->t=t;
bsscr->v=v;
PetscFunctionReturn(0);
}
/* creates and builds the "constant" null-space vector for pressure
and sets the t "Vec pointer" on the bsscr struct to point to it */
#undef __FUNCT__
#define __FUNCT__ "KSPBuildPressure_Const_Nullspace_BSSCR"
PetscErrorCode KSPBuildPressure_Const_Nullspace_BSSCR(KSP ksp)
{
KSP_BSSCR *bsscr = (KSP_BSSCR *)ksp->data;
FeEquationNumber *eq_num = bsscr->solver->st_sle->pSolnVec->eqNum;
FeMesh *feMesh = bsscr->solver->st_sle->pSolnVec->feVariable->feMesh; /* is the pressure mesh */
unsigned ijk[3];
Vec t;
int numLocalNodes, globalNodeNumber, i, eq;
MatStokesBlockScaling BA = bsscr->BA;
PetscErrorCode ierr;
Mat Amat,Pmat, G;
MatStructure pflag;
PetscFunctionBegin;
/* get G matrix from Amat matrix operator on ksp */
ierr=Stg_PCGetOperators(ksp->pc,&Amat,&Pmat,&pflag);CHKERRQ(ierr);
MatNestGetSubMat( Amat, 0,1, &G );/* G should always exist */
/* now create Vec t to match size of G: i.e. pressure */ /* NOTE: not using "h" vector from ksp->vec_rhs because this part of the block vector doesn't always exist */
MatGetVecs( G, &t, PETSC_NULL );/* t is destroyed in KSPDestroy_BSSCR */
VecSet(t, 1.0);
VecAssemblyBegin( t );
VecAssemblyEnd( t );
/* Scaling the null vectors here because it easier at the moment */
if( BA->scaling_exists == PETSC_TRUE ){
Vec R2;
/* Get the scalings out the block mat data */
VecNestGetSubVec( BA->Rz, 1, &R2 );
VecPointwiseDivide( t, t, R2); /* x <- x * 1/R2 */
}
// bsscr_writeVec( t, "t", "Writing t vector");
bsscr->t=t;
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "KSPRemovePressureNullspace_BSSCR"
PetscErrorCode KSPRemovePressureNullspace_BSSCR(KSP ksp, Vec h_hat)
{
KSP_BSSCR *bsscr = (KSP_BSSCR *)ksp->data;
MatStokesBlockScaling BA = bsscr->BA;
PetscErrorCode ierr;
PetscScalar norm, a, a1, a2, hnorm, pnorm, gnorm;
Vec t2, t,v;
Mat Amat,Pmat, D;
MatStructure pflag;
double nstol = bsscr->nstol; /* set in KSPCreate_BSSCR */
PetscFunctionBegin;
t=bsscr->t;
v=bsscr->v;
/* get G matrix from Amat matrix operator on ksp */
ierr=Stg_PCGetOperators(ksp->pc,&Amat,&Pmat,&pflag);CHKERRQ(ierr);
//MatNestGetSubMat( Amat, 0,1, &G );/* G should always exist */
MatNestGetSubMat( Amat, 1,0, &D );/* D should always exist */
/* now create Vec t2 to match left hand size of G: i.e. velocity */
MatGetVecs( D, &t2, PETSC_NULL );
MatNorm(D,NORM_INFINITY,&gnorm); /* seems like not a bad estimate of the largest eigenvalue for this matrix */
if(t){/* assumes that v and t are initially set to PETSC_NULL (in KSPCreate_BSSCR ) */
MatMultTranspose( D, t, t2);
VecNorm(t2, NORM_2, &norm);
VecNorm(t, NORM_2, &a);
norm=norm/a;/* so we are using unit null vector */
if(norm < nstol*gnorm){/* then t in NS of G */
VecDot(t,h_hat, &a1);
VecDot(t,t, &a2);
a=-a1/a2;
VecAXPY(h_hat, a, t);
VecDot(t,h_hat, &a1);
PetscPrintf( PETSC_COMM_WORLD, "\n\t* Found t NS norm= %g : Dot = %g\n\n", norm, a1);
}
}
if(v){
MatMultTranspose( D, v, t2);
VecNorm(t2, NORM_2, &norm);
VecNorm(v, NORM_2, &a);
norm=norm/a;/* so we are using unit null vector */
if(norm < nstol*gnorm){/* then v in NS of G */
VecDot(v,h_hat, &a1);
VecDot(v,v, &a2);
a=-a1/a2;
VecAXPY(h_hat, a, v);
VecDot(v,h_hat, &a1);
PetscPrintf( PETSC_COMM_WORLD, "\n\t* Found v NS norm= %g : Dot = %g\n\n", norm, a1);
}
}
// bsscr_writeVec( h_hat, "h", "Writing h_hat Vector in Solver");
Stg_VecDestroy(&t2);
PetscFunctionReturn(0);
}
|
#!/usr/bin/env python3
import math
import numpy as np
import utils
import argparse
import os
#############################################################
class View():
def __init__(self, graph, obstacles, saveplot, log):
self.mapshape = graph.mapshape
import matplotlib
import warnings
import matplotlib.cbook
warnings.filterwarnings("ignore",
category=matplotlib.cbook.mplDeprecation)
if saveplot: matplotlib.use('Agg')
self.show = not saveplot
import matplotlib.pyplot
self.plt = matplotlib.pyplot
if not saveplot: self.plt.ion()
self.graph = graph
self.f, self.axarr = self.plt.subplots(3, figsize=(6, 12), sharex=True)
self.f.subplots_adjust(hspace=.5)
self.obstacles = obstacles
self.log = log
for i in range(3):
self.axarr[i].set_xlim(0, graph.mapshape[1])
self.axarr[i].invert_yaxis()
def plot_ascii(self, densmap):
for j in range(self.graph.mapshape[0]):
for i in range(self.graph.mapshape[1]):
dens = densmap[j][i]
if dens == -1:
print(' ', end='')
else :
print(dens, end='')
print()
def plot_obstacles(self, obstacles, subplot):
for y, x in obstacles:
subplot.scatter(x, y, c='gray', marker='s', s=25)
def plot_points_matplotlib(self, carspos, subplot, col='gray',
ptsize=10, marker='s'):
yy = []
xx = []
for p in carspos:
y, x = np.unravel_index(p, self.graph.mapshape)
yy.append(y)
xx.append(x)
subplot.scatter(xx, yy, c=col, marker=marker, s=ptsize)
if self.show: self.plt.show()
def plot_map_matplotlib(self, densmap, _max, subplot, title='', sz=15):
subplot.clear()
subplot.set_xlim(0, self.graph.mapshape[1])
subplot.set_ylim(0, self.graph.mapshape[0])
subplot.invert_yaxis()
subplot.set_title(title)
subplot.axes.get_xaxis().set_visible(False)
subplot.axes.get_yaxis().set_visible(False)
yy = []
xx = []
cc = []
maxdens = float(np.max(densmap))
_color = [0.75, 0.0, 0.0]
idx = -1
for dens in densmap:
idx += 1
# Not differentiating not seen and zero density spots
if dens == -1 or dens == 0:
continue
else :
j, i = np.unravel_index(idx, self.graph.mapshape)
yy.append(j)
xx.append(i)
cc.append(_color + [dens/_max])
npoints = len(xx)
if npoints == 0: return
subplot.scatter(xx, yy, c=cc, s=[sz]*npoints, marker='o')
if self.show: self.plt.show()
def plot_ascii_densities(self, density1, density2, keyword='out'):
self.plot_ascii(density1)
self.plot_ascii(density2)
def plot_densities(self, density1, density2, density3, carslocations,
_max=1.0, tofile=''):
self.plot_map_matplotlib(density1, _max, self.axarr[0],'True heat map')
#self.plot_obstacles(self.obstacles, self.axarr[0])
self.plot_map_matplotlib(density2, _max, self.axarr[1], 'Sensed heat map')
self.plot_map_matplotlib(density3, _max, self.axarr[2], 'Current heat map')
self.plot_points_matplotlib(carslocations, self.axarr[2], 'cyan')
self.plt.tight_layout()
if self.show:
self.plt.show()
self.plt.pause(0.0001)
else:
self.plt.savefig(tofile)
#############################################################
def parse_arguments():
parser = argparse.ArgumentParser(description='Sensing viewer')
parser.add_argument('indir', help='input dir')
parser.add_argument('maxcars', help='maximum number of cars')
parser.add_argument('runs', help='number of runs')
return parser.parse_args()
#############################################################
def main():
view = View(searchmap, mapshape, nodes, obstacles, saveplot, log)
if __name__ == '__main__':
main()
|
/*
* @Descripttion:
* @version: 1.0.0
* @Author: CYKS
* @Date: 2021-12-19 12:02:47
* @LastEditors: CYKS
* @LastEditTime: 2021-12-20 15:39:56
*/
#pragma once
#include <experimental/filesystem>
#include <string>
#include <vector>
#include <boost/format.hpp>
#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/trivial.hpp>
#include "../cpp-httplib/httplib.h"
namespace logging = boost::log;
namespace fs = std::experimental::filesystem;
class TestServer {
public:
static httplib::Client cli;
explicit TestServer(fs::path path, logging::trivial::severity_level level);
void run(int thread_num);
void join();
private:
void run_server();
using message_queue = std::vector<std::string>;
std::thread _server_thread;
std::vector<message_queue> _mqueue;
};
|
%% OPTI Toolbox Basic Functionality Demo
%
% This file illustrates the basic functionality of the OPTI Toolbox and
% provides a collection of simple examples to get new users familiar with
% the OPTI methods.
%
% Topics covered include:
%
% - Checking available solvers
% - Finding a solver for a particular problem type
% - Building an optiprob problem structure
% - Building an optiset options structure
% - Using the opti constructor
% - Solving an opti object
% - Validating the solution
% - Plotting the solution
%
% Copyright (C) 2011 Jonathan Currie (I2C2)
%% Checking solvers available with your OPTI distribution
% Not all solvers are supplied with the OPTI Toolbox, so to check which are
% available you can use the following function:
checkSolver
%% Matching solvers with a problem type
% Use the 'matrix' argument to print a grid of solver vs problem solved:
checkSolver('matrix')
%% Finding all solvers for a given problem type
% Specify the problem type in order to print a list of all solvers setup to
% solve that problem type. The solver at the top of the list is the default
% solver for that type. The following line prints all solvers which are
% setup to solve a Linear Program (LP) together with constraint and
% sparsity settings (see help checkSolver):
checkSolver('LP')
%% Creating an Optimization Problem
% To create an optimization problem using OPTI there are two methods
% available:
%
% 1) Pass the problem parameters directly to the opti constructor.
%
% 2) Pass the problem parameters to optiprob to generate a problem
% structure, then pass the structure to the opti constructor.
%
% Typically we will use (1), however (2) is provided for backwards
% compatibility, as well as to break up larger problem descriptions.
%% Problem Fields
% Type opti or optiprob with no input arguments to view all available fields
% and groupings. Check the help documentation to see alternative naming and
% grouping strategies.
opti;
%% Options Fields
% Type optiset with no input arguments to view all available fields. Check
% the help documentation for more information.
optiset
%% Problem 1
% This is a simple two decision variable Linear Program (LP) which we will
% use for the next couple of examples.
%Problem
f = -[6 5]'; %Objective Function (min f'x)
A = [1,4; 6,4; 2, -5]; %Linear Inequality Constraints (Ax <= b)
b = [16;28;6];
lb = [0;0]; %Bounds on x (lb <= x <= ub)
ub = [10;10];
%% Example 1 - Basic Setup
% Problems can be built using the opti constructor. Options from optiset are
% always optional. If the user does not provide any options, OPTI will
% choose default ones for the problem being solved.
Opt = opti('f',f,'ineq',A,b,'bounds',lb,ub)
%% Example 1 - Solving the Problem
% Call solve to solve the problem
[x,fval,exitflag,info] = solve(Opt)
%% Example 2 - Alternative Setup Strategies
% Naming of arguments, as well as pairing is flexible when using optiprob
Opt = opti('c',f,'ineq',A,b,'bounds',lb,ub); %c = f
% OR
Opt = opti('grad',f,'ineq',A,b,'bounds',lb,ub); %grad = f
% OR
Opt = opti('f',f,'A',A,'b',b,'bounds',lb,ub); %individual A,b
% OR
Opt = opti('f',f,'ineq',A,b,'lb',lb,'ub',ub); %individual lb,ub
%% Example 3 - Choosing the Solver
% You can use optiset to select a solver for your problem. This is supplied
% to the opti constructor using optiset, together with the existing
% problem description.
opts = optiset('solver','clp');
Opt = opti(Opt,opts)
x = solve(Opt)
%% Example 3b - Choosing the Solver via 'options'
% You can also specify options when creating the initial OPTI object:
opts = optiset('solver','ooqp');
Opt = opti('f',f,'ineq',A,b,'bounds',lb,ub,'options',opts)
x = solve(Opt)
%% Example 4 - Validating the Solution
% The solution is stored inside the OPTI object, so you can validate it
% against the constraints.
[ok,msg] = checkSol(Opt)
%% Example 5 - Plotting the Solution
% Several problem types have a default plot command available IF the
% problem contains two variables.
plot(Opt)
%% Example 6 - Calling a Solver Directly
% Most OPTI solvers use standard MATLAB function prototypes (such as
% linprog or quadprog), so you can skip using the OPTI class all together:
rl = -Inf(size(b)); %note row format for solver CLP
ru = b;
[x,fval,exitflag,info] = opti_clp([],f,A,rl,ru,lb,ub)
%% Example 7 - MATLAB Optimization Toolbox Overloads
% As described in Overload_demo.m, most Optimization Toolbox functions are
% overloaded ('opti_' is placed in front) for new users.
[x,fval,exitflag,info] = opti_linprog(f,A,b,[],[],lb,ub)
|
module BBHeap.Equality {A : Set}(_≤_ : A → A → Set) where
open import BBHeap _≤_
open import Bound.Lower A
open import Bound.Lower.Order _≤_
data _≈_ {b b' : Bound} : BBHeap b → BBHeap b' → Set where
≈leaf : leaf {b} ≈ leaf {b'}
≈left : {x x' : A}{l r : BBHeap (val x)}{l' r' : BBHeap (val x')}
(b≤x : LeB b (val x))
(b'≤x' : LeB b' (val x'))
(l⋘r : l ⋘ r)
(l'⋘r' : l' ⋘ r')
→ l ≈ l'
→ r ≈ r'
→ left b≤x l⋘r ≈ left b'≤x' l'⋘r'
≈right : {x x' : A}{l r : BBHeap (val x)}{l' r' : BBHeap (val x')}
(b≤x : LeB b (val x))
(b'≤x' : LeB b' (val x'))
(l⋙r : l ⋙ r)
(l'⋙r' : l' ⋙ r')
→ l ≈ l'
→ r ≈ r'
→ right b≤x l⋙r ≈ right b'≤x' l'⋙r'
|
module Data.Universe
%default total
public export
record Universe where
constructor BigBang
Ty : Type
typeOf : Ty -> Type
defaultOf : (t : Ty) -> typeOf t
decEq : (t : Ty) -> (s : Ty) -> Dec (t = s)
|
If $f$ is in $L(F, g(h))$, and $h$ and $h'$ are eventually equal, then $f$ is in $L(F, g(h'))$.
|
# -*- coding: UTF-8 -*-
# tool's library for AutoLin
# TODO: make autoLin as Object and set some properties - like demWS..
import shutil
import os
import time
import traceback
import config
import math
import arcpy
import line_stats
import tbe
# import pylab
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.font_manager import FontProperties
arcpy.env.overwriteOutput = True
# Check out the ArcGIS Spatial Analyst extension license
if arcpy.CheckExtension("Spatial") == "Available":
slic = arcpy.CheckOutExtension("Spatial")
# print(slic)
else:
print "No Spatial licence availiable!"
# print ("time %s - arcpy imported" % (time.strftime("%m%d_%H%M%S"))
class Cluster:
def __init__(self):
self.myId = []
self.IDs = []
self.Ax = []
self.Ay = []
self.Bx = []
self.By = []
self.A = []
self.length = []
# setting paths for workspace
workspace = config.workspace
resultsDir = config.resultsDir
sourceDir = config.sourceDir
# TODO zachovat
# delete directory with input path
def deletePath(path):
if os.path.exists(path):
if os.path.isdir(path):
print ("time %s - deleting %s" % (time.strftime("%m%d_%H%M%S"), path))
shutil.rmtree(path)
# TODO zachovat
# creates demDirs directories in demWS folder
def createDEMdirs(demWS, demDirs):
for demDir in demDirs:
if not os.path.exists(demWS+demDir):
os.mkdir(demWS+demDir)
# TODO zachovat
# create all dirs in path
def makeDirs(path):
if not os.path.exists(path):
os.makedirs(path)
# TODO zachovat
# clips input DEM using boundary and fill sinks
def clipAndFill(inRaster, outRaster, boundary, cellSize):
# clip DEM by boundary FIRST!
clipDEM = "in_memory\\" + "clipDEM_%i" % cellSize
print "time %s - cliping DEM" % (time.strftime("%m%d_%H%M%S"))
arcpy.Clip_management(inRaster, "#", clipDEM, boundary, "-3,402823e+038", "ClippingGeometry")
# fill DEM - save to folder
print "time %s - filling DEM" % (time.strftime("%m%d_%H%M%S"))
arcpy.gp.Fill_sa(clipDEM, outRaster, "#")
arcpy.Delete_management(clipDEM)
arcpy.Delete_management(inRaster)
# TODO zachovat
# step 1 DEMs Creation
def createDEM(sourceWorkspace, inputs, boundary, resolutions, outDEMmask):
sourceDir = config.sourceDir
SA = config.getSA(outDEMmask)
sourceDEM = config.getSourceDEM(outDEMmask)
outDEMpath = sourceDir + SA + "\\" + sourceDEM + "\\"
makeDirs(getDir(outDEMpath))
# copy boundary to outDEMDir
outBoundary = outDEMpath + "boundary.shp"
arcpy.CopyFeatures_management(boundary, outBoundary)
# process inputs regarding input type
# TODO LLS type
if (inputs["type"] == "VECTOR"):
topoInputs = ""
# clip vector inputs using boundary
for vector in inputs["data"].split(";"):
topoInputsField = vector.strip().split(" ")
fcName = topoInputsField[0]
fcPath = sourceWorkspace + fcName
vectorClip = "in_memory\\" + os.path.splitext(fcName)[0]
topoInputs += vectorClip + " " + topoInputsField[1] + " " + topoInputsField[2] + ";"
print "time %s - clipping %s" % (time.strftime("%m%d_%H%M%S"), fcName)
arcpy.Clip_analysis(fcPath, boundary, vectorClip)
for cellSize in resolutions:
outDEM = outDEMpath + outDEMmask + "%i" % cellSize
if not os.path.exists(outDEM):
# create temp DEM
tempDEM = "in_memory\\" + "tempDEM_%i" % cellSize
print "time %s - creating DEM raster" % (time.strftime("%m%d_%H%M%S"))
arcpy.gp.TopoToRaster_sa(topoInputs, tempDEM, cellSize)
clipAndFill(tempDEM, outDEM, boundary, cellSize)
elif (inputs["type"] == "RASTER"):
inDEM = sourceWorkspace + inputs["data"]
for cellSize in resolutions:
outDEM = outDEMpath + outDEMmask + "%i" % cellSize
if not os.path.exists(outDEM):
resampleDEM = "in_memory\\" + "resDEM_%i" % cellSize
print "time %s - resampling DEM" % (time.strftime("%m%d_%H%M%S"))
arcpy.Resample_management(inDEM, resampleDEM, cellSize, "BILINEAR")
clipAndFill(resampleDEM, outDEM, boundary, cellSize)
# TODO zachovat
def selectAndWrite(lineSHP, zonalP, gridCode, myField):
# select by attributes: from zonalP using gridcode
arcpy.MakeFeatureLayer_management (zonalP, "zonalP")
zonalPFields = arcpy.ListFields("zonalP")
gridFieldName = "GRIDCODE"
for zonalField in zonalPFields:
if "grid" in zonalField.name.lower():
gridFieldName = zonalField.name
myExpression = '"%s" = %d' % (gridFieldName, gridCode)
arcpy.SelectLayerByAttribute_management ("zonalP", "NEW_SELECTION", myExpression)
# select by location: from lineSHP which have centroid in selected zonalP
arcpy.MakeFeatureLayer_management(lineSHP, "lineSHP")
arcpy.SelectLayerByLocation_management("lineSHP", "have_their_center_in", "zonalP", "", "NEW_SELECTION")
# write to selected lineSHP attribude gridcode to field zonalP
myValue = 1
if gridCode == 1:
myValue = -1
if gridCode == 2:
myValue = 0
arcpy.CalculateField_management("lineSHP",myField,myValue,"PYTHON_9.3","#")
arcpy.SelectLayerByAttribute_management ("zonalP", "CLEAR_SELECTION")
arcpy.SelectLayerByAttribute_management ("lineSHP", "CLEAR_SELECTION")
# TODO zachovat
# input - shp as a single lines, raster with value, buffer size and parameters for selection
# output - directory with separated lines
def zonalLine(inSHP, inRaster, bufferSize, meaPars, medPars, outSHP, outSHPPositive, outSHPUnsure):
print ("time %s - starting zonal for %s" % (time.strftime("%m%d_%H%M%S"), getName(inSHP)))
tempWS = config.temp
demDirs = [tempWS]
inDir = getDir(inSHP)
createDEMdirs(inDir, demDirs)
# buffer inSHP
lineSHPBuffName = getName(inSHP)[:-4]+"_buff%d.shp" % bufferSize
lineSHPDir = inDir + tempWS + getName(inSHP)[:-4] + "bf\\"
if not os.path.exists(lineSHPDir):
os.mkdir(lineSHPDir)
lineSHPBuff = lineSHPDir + lineSHPBuffName
if not os.path.exists(lineSHPBuff):
arcpy.Buffer_analysis(inSHP,lineSHPBuff,"%d Meters" % bufferSize,"FULL","ROUND","NONE","#")
# zonal stats - zones: bufferSHP, inRaster, stat - mean, median
zonalRMed = lineSHPDir + "zonMed"
zonalRMea = lineSHPDir + "zonMea"
if not os.path.exists(zonalRMed):
# print ("time %s - creating zonalR MEDIAN" % (time.strftime("%m%d_%H%M%S"))
arcpy.gp.ZonalStatistics_sa(lineSHPBuff,"FID",inRaster,zonalRMed,"MEDIAN","DATA")
if not os.path.exists(zonalRMea):
# print ("time %s - creating zonalR MEAN" % (time.strftime("%m%d_%H%M%S"))
arcpy.gp.ZonalStatistics_sa(lineSHPBuff,"FID",inRaster,zonalRMea,"MEAN","DATA")
# reclassify zone rasters using threshold for flowAcc field (3 classes - positive, unsure, negative)
# reclassify MEDIAN and toPolygon
parMedRidge = medPars[0]
parMedValley = medPars[1]
zonalRMedRec = lineSHPDir + "zMed%d_%d" % (parMedRidge, parMedValley)
if not os.path.exists(zonalRMedRec):
parMedRidge+=0.01
parMedValley-=0.01
# print ("time %s - reclassify zonalR MEDIAN" % (time.strftime("%m%d_%H%M%S"))
arcpy.gp.Reclassify_sa(zonalRMed,"VALUE","0 %d 1;%d %d 2;%d 10000000 3" % (parMedRidge, parMedRidge, parMedValley, parMedValley),zonalRMedRec,"NODATA")
# toPolygon
zonalPMedRec = zonalRMedRec + ".shp"
if not os.path.exists(zonalPMedRec):
# print ("time %s - to polygon zonalR MEDIAN" % (time.strftime("%m%d_%H%M%S"))
arcpy.RasterToPolygon_conversion(zonalRMedRec,zonalPMedRec,"SIMPLIFY","VALUE")
# reclassify MEAN and toPolygon
parMeaRidge = meaPars[0]
parMeaValley = meaPars[1]
zonalRMeaRec = lineSHPDir + "zMea%d_%d" % (parMeaRidge, parMeaValley)
if not os.path.exists(zonalRMeaRec):
parMeaRidge+=0.01
parMeaValley-=0.01
# print ("time %s - reclassify zonalR MEAN" % (time.strftime("%m%d_%H%M%S"))
arcpy.gp.Reclassify_sa(zonalRMea,"VALUE","0 %d 1;%d %d 2;%d 10000000 3" % (parMeaRidge, parMeaRidge, parMeaValley, parMeaValley),zonalRMeaRec,"NODATA")
# toPolygon
zonalPMeaRec = zonalRMeaRec + ".shp"
if not os.path.exists(zonalPMeaRec):
# print ("time %s - to polygon zonalR MEAN" % (time.strftime("%m%d_%H%M%S"))
arcpy.RasterToPolygon_conversion(zonalRMeaRec,zonalPMeaRec,"SIMPLIFY","VALUE")
# select and write inSHP, zonalP, outWS
# cteate 3 new fields flowAccMED, flowAccMEAN and flowAccTrue for lineSHP
arcpy.AddField_management(inSHP, "fMED", "LONG", 9, "", "", "", "NULLABLE", "NON_REQUIRED")
arcpy.AddField_management(inSHP, "fMEAN", "LONG", 9, "", "", "", "NULLABLE", "NON_REQUIRED")
arcpy.AddField_management(inSHP, "fTrue", "LONG", 9, "", "", "", "NULLABLE", "NON_REQUIRED")
# set null the fields (because 0 is not rewrited!)
# select and write attributes
for zonalP in [zonalPMedRec, zonalPMeaRec]:
statField = "fMED"
if zonalP.rfind("zMea")+1:
statField = "fMEAN"
for gridCode in [1, 2, 3]:
selectAndWrite(inSHP, zonalP, gridCode, statField)
# combine Med and Mea to "fTrue"
arcpy.CalculateField_management("lineSHP","fTrue","!fMED! + !fMEAN!","PYTHON_9.3","#")
# Separating lines - positive and negative
# A) negative lines > 0
outDir = getDir(outSHP)
if not os.path.exists(outDir):
os.mkdir(outDir)
# select by attributes: from "lineSHP" using "fTrue"
myExpression = '"fTrue" > 0'
arcpy.SelectLayerByAttribute_management ("lineSHP", "NEW_SELECTION", myExpression)
arcpy.CopyFeatures_management("lineSHP", outSHP)
# B) if positive lines parameter is set:
if (len(outSHPPositive) > 0):
outDir = getDir(outSHPPositive)
if not os.path.exists(outDir):
os.mkdir(outDir)
# select by attributes: from "lineSHP" using "fTrue"
myExpression = '"fTrue" < 0'
arcpy.SelectLayerByAttribute_management ("lineSHP", "NEW_SELECTION", myExpression)
arcpy.CopyFeatures_management("lineSHP", outSHPPositive)
# C) if unsure lines parameter is set:
if (len(outSHPUnsure) > 0):
outDir = getDir(outSHPUnsure)
if not os.path.exists(outDir):
os.mkdir(outDir)
# select by attributes: from "lineSHP" using "fTrue"
myExpression = '"fTrue" = 0'
arcpy.SelectLayerByAttribute_management ("lineSHP", "NEW_SELECTION", myExpression)
arcpy.CopyFeatures_management("lineSHP", outSHPUnsure)
# TODO zachovat
# input - shp as a single lines, raster with value, buffer size and parameters for selection
# output - directory with separated lines
def zonalLineRelevant(inSHP, inRaster, bufferSize, countThreshold, outSHP, statistic):
print ("time %s - starting zonal for %s" % (time.strftime("%m%d_%H%M%S"), getName(inSHP)))
tempWS = config.temp
demDirs = [tempWS]
inDir = getDir(inSHP)
createDEMdirs(inDir, demDirs)
# buffer inSHP
# lineSHPBuffName = getName(inSHP)[:-4]+"_buff%d.shp" % bufferSize
lineSHPBuffName = getName(inSHP)[:-4]+"_buff%d" % bufferSize
# TODO "in_memory"
lineSHPDir2 = inDir + tempWS + getName(inSHP)[:-4] + "bf_"
lineSHPDir = "in_memory\\" + getName(inSHP)[:-4] + "bf_"
# TODO "in_memory"
# if not os.path.exists(lineSHPDir):
# os.mkdir(lineSHPDir)
lineSHPBuff = lineSHPDir + lineSHPBuffName
if not os.path.exists(lineSHPBuff):
arcpy.Buffer_analysis(inSHP,lineSHPBuff,"%d Meters" % bufferSize,"FULL","ROUND","NONE","#")
# zonal stats - zones: bufferSHP, inRaster, stat - mean
if statistic == "MEAN":
zonalRName = "zMea"
statField = "fMEAN"
elif statistic == "MEDIAN":
zonalRName = "zMed"
statField = "fMED"
zonalRMea = lineSHPDir + zonalRName
if not os.path.exists(zonalRMea):
arcpy.gp.ZonalStatistics_sa(lineSHPBuff,"FID",inRaster,zonalRMea,statistic,"DATA")
# TODO "in_memory"
arcpy.Delete_management(lineSHPBuff)
# reclassify zone rasters using threshold for flowAcc field (3 classes - positive, unsure, negative)
# reclassify MEAN and toPolygon
zonalRMeaRec = lineSHPDir + zonalRName+"%d" % (countThreshold)
# recclasification condition
countThreshold -= 0.01
if not os.path.exists(zonalRMeaRec):
# print ("time %s - reclassify zonalR MEAN" % (time.strftime("%m%d_%H%M%S"))
arcpy.gp.Reclassify_sa(zonalRMea,"VALUE","0 %d 1;%d 10000000 3" % (countThreshold, countThreshold),zonalRMeaRec,"NODATA")
# TODO "in_memory"
arcpy.Delete_management(zonalRMea)
# toPolygon
# zonalPMeaRec = zonalRMeaRec + ".shp"
zonalPMeaRec = zonalRMeaRec + "_P"
# zonalPMeaRec = lineSHPDir2 + zonalRName+"%d" % (countThreshold) + ".shp"
if not os.path.exists(zonalPMeaRec):
# print ("time %s - to polygon zonalR MEAN" % (time.strftime("%m%d_%H%M%S"))
arcpy.RasterToPolygon_conversion(zonalRMeaRec,zonalPMeaRec,"SIMPLIFY","VALUE")
# TODO "in_memory"
arcpy.Delete_management(zonalRMeaRec)
# select and write inSHP, zonalP, outWS
# cteate new field flowAccMEAN for lineSHP
if (arcpy.ListFields(inSHP, statField)== []):
arcpy.AddField_management(inSHP, statField, "LONG", 9, "", "", "", "NULLABLE", "NON_REQUIRED")
# set null the fields (because 0 is not rewrited!)
# select and write attributes
for gridCode in [1, 3]:
selectAndWrite(inSHP, zonalPMeaRec, gridCode, statField)
# TODO "in_memory"
arcpy.Delete_management(zonalPMeaRec)
# Separating lines - positive and negative
# A) negative lines > 0
outDir = getDir(outSHP)
if not os.path.exists(outDir):
os.mkdir(outDir)
# select by attributes: from "lineSHP" using "fTrue"
myExpression = '%s > 0' % statField
arcpy.SelectLayerByAttribute_management ("lineSHP", "NEW_SELECTION", myExpression)
arcpy.CopyFeatures_management("lineSHP", outSHP)
# TODO zachovat
def getName(inSHP):
inSHP = inSHP[inSHP.rfind("\\")+1:]
return inSHP
# TODO zachovat
def getDir(inSHP):
inSHP = inSHP[0:inSHP.rfind("\\")+1]
return inSHP
# TODO zachovat
# for each input row line returns list of points
def getPoints(feat):
partnum = 0
# Step through each part of the feature
pnts = []
for part in feat:
# Step through each vertex in the feature
for pnt in feat.getPart(partnum):
pnts.append(pnt)
partnum += 1
return pnts
# TODO zachovat
# calculates statistics length and azimuth (from north clockwise)
# write fields "azimuth" and "length" to attribute table of inSHP
def calcStats(inSHP):
# print ("time %s - calculating stats" % (time.strftime("%m%d_%H%M%S"))
# add fields before creating cursors !! - otherwise Python crash !!
if (arcpy.ListFields(inSHP, "azimuth")== []):
arcpy.AddField_management(inSHP, "azimuth", "FLOAT", 9, 2, "", "", "NULLABLE", "NON_REQUIRED")
if (arcpy.ListFields(inSHP, "length")== []):
arcpy.AddField_management(inSHP, "length", "FLOAT", 9, 2, "", "", "NULLABLE", "NON_REQUIRED")
rows = arcpy.UpdateCursor(inSHP)
desc = arcpy.Describe(inSHP)
shapefieldname = desc.ShapeFieldName
for row in rows:
feat = row.getValue(shapefieldname)
pnts = getPoints(feat)
if (pnts != []):
A = pnts[0]
B = pnts[1]
azimuth = line_stats.lineAzimuth(A,B)
length = line_stats.lineLength(A,B)
row.azimuth = azimuth
row.length = length
rows.updateRow(row)
# TODO zachovat
# input: raster DEM - output: flowAcc in flowWS directory
def getFlowAcc(demWS, inDEM):
flowWS = config.flowWS
flowAcc = demWS + flowWS + "flowAcc"
if not os.path.exists(flowAcc):
# create dirs in workspace
tempWS = config.temp
demDirs = [tempWS, flowWS]
createDEMdirs(demWS, demDirs)
# fiiling skipped - already filled by dataprep!
outFill = inDEM
# compute FlowAcc from DEM
flowDir = demWS + flowWS + "flowDir"
if not os.path.exists(flowDir):
print ("time %s - createFlowDir" % (time.strftime("%m%d_%H%M%S")))
arcpy.gp.FlowDirection_sa(outFill,flowDir,"NORMAL","#")
# output must be INTEGER due to zonalStats!
print ("time %s - createFlowAcc" % (time.strftime("%m%d_%H%M%S")))
arcpy.gp.FlowAccumulation_sa(flowDir,flowAcc,"#","INTEGER")
return flowAcc
# TODO zachovat
# returns center of raster
def getRotationCenter(inRaster):
X = getRasterInfo(inRaster, "LEFT", 1)
Y = getRasterInfo(inRaster, "TOP", 1)
return arcpy.Point(X, Y)
# TODO zachovat
#output is integer
def getRasterInfo(inRaster, rasterProperty, isRound):
if os.path.exists(inRaster):
rasterInfo = arcpy.GetRasterProperties_management(inRaster, rasterProperty)
rasterProperty = rasterInfo.getOutput(0)
rasterProperty = float (rasterProperty.replace(",", ".", 1))
if (isRound):
rasterProperty = round (rasterProperty)
return rasterProperty
# TODO unused
# export calculated statistics with coordinates (length and azimuth (from north clockwise))
# read geometry and fields "azimuth" and "length" from attribute table of inSHP
def exportStats(inSHP, outTXT):
print ("time %s - exporting stats to file %s" % (time.strftime("%m%d_%H%M%S"), outTXT))
# add fields before creating cursors !! - otherwise Python crash !!
azimuthField = "azimuth"
lengthField = "length"
rows = arcpy.SearchCursor(inSHP)
desc = arcpy.Describe(inSHP)
shapefieldname = desc.ShapeFieldName
# open file to write
outTXT = open(outTXT, "w")
for row in rows:
feat = row.getValue(shapefieldname)
pnts = getPoints(feat)
A = pnts[0]
B = pnts[1]
azimuth = row.azimuth
length = row.length
outTXT.write("%i; %i; %i; %i; %i; %0.2f; %0.2f\n" %(row.FID, A.X, A.Y, B.X, B.Y, azimuth, length))
outTXT.close()
# TODO zachovat
# split all SHPs in input folder and copy to output folder
def splitLines(demWS, shpWS, outWS):
shp_listDir = os.listdir(demWS+shpWS)
for mySHP in shp_listDir:
if mySHP[-4:] == ".shp":
# split input lines to outWS
inSHP = demWS + shpWS + mySHP
splitLine(inSHP, demWS, outWS)
# TODO zachovat
# split input lines to line segments
def splitLine(inSHP, demWS, outWS):
shpName = getName(inSHP)
lineSHPName = shpName
lineSHPDir = demWS + outWS
if not os.path.exists(lineSHPDir):
os.mkdir(lineSHPDir)
lineSHP = lineSHPDir + lineSHPName
if not os.path.exists(lineSHP):
arcpy.SplitLine_management(inSHP, lineSHP)
# TODO zachovat
# erase all lines from shpLinesWS which lie in boundary defined by inDEMBuffer
def eraseBoundarySHP(inDEMBuffer, demWS):
# raster is not rectangle
# Improvement - if exists inDEMBuffer.shp <=> raster is not rectangle
print ("time %s - DEM raster is irregular" % (time.strftime("%m%d_%H%M%S")))
tempWS = config.temp
demDirs = [tempWS]
createDEMdirs(demWS, demDirs)
shpLinesWS = config.shpLinesWS
# clip all input SHPs according to buffer +/- clipDEMSize m
clipDEMSize = config.clipDEMSize
# inDEMBuffer must exist!
if os.path.exists(inDEMBuffer):
# create buffer + clipDEMSize m
bufferPlus = demWS + tempWS + "bufferP.shp"
if not os.path.exists(bufferPlus):
arcpy.Buffer_analysis(inDEMBuffer,bufferPlus,"%d Meters" % clipDEMSize,"FULL","ROUND","NONE","#")
# create buffer - clipDEMSize m
bufferMinus = demWS + tempWS + "bufferM.shp"
if not os.path.exists(bufferMinus):
arcpy.Buffer_analysis(inDEMBuffer,bufferMinus,"%d Meters" % -clipDEMSize,"FULL","ROUND","NONE","#")
# create round buffer (erase)
bufferErase = demWS + tempWS + "bufferE.shp"
if not os.path.exists(bufferErase):
arcpy.Erase_analysis(bufferPlus, bufferMinus, bufferErase)
arcpy.MakeFeatureLayer_management(bufferErase, "bufferErase")
# selection and deleteFeatures is made below
shp_listDir = os.listdir(demWS+shpLinesWS)
for mySHP in shp_listDir:
if mySHP[-4:] == ".shp":
lineSHP = demWS + shpLinesWS + mySHP
# deleting boundary lines for irregular raster
print ("time %s - processing %s" % (time.strftime("%m%d_%H%M%S"), mySHP))
arcpy.MakeFeatureLayer_management(lineSHP, "lineSHP")
arcpy.SelectLayerByLocation_management("lineSHP","COMPLETELY_WITHIN","bufferErase","","NEW_SELECTION")
arcpy.DeleteFeatures_management("lineSHP")
else:
print ("Raster buffer %s does not exist" %(inDEMBuffer))
# TODO unused
# copy PRJ for files without PRJ file
def completePRJ(inPRJ, inDir):
shp_listDir = os.listdir(inDir)
for mySHP in shp_listDir:
if mySHP[-4:] == ".shp":
prjName = inDir + mySHP[:-4] + ".prj"
print (prjName)
print (os.path.exists(prjName))
if not os.path.exists(prjName):
shutil.copyfile(inPRJ, prjName)
# TODO zachovat
# computes raster of relevance
def getRelevantRaster(inDir, bufferSize, outAllR, DEM):
print ("time %s - computing relevant raster" % (time.strftime("%m%d_%H%M%S")))
sourceDir = config.sourceDir
SA = config.getSA(DEM)
sourceDEM = config.getSourceDEM(DEM)
rasterDEM = sourceDir + SA + "\\" + sourceDEM + "\\" + DEM
tempWS = config.temp
demDirs = [tempWS]
createDEMdirs(inDir, demDirs)
cellSize = bufferSize
# list of rasters to merge
tiffNames = []
# for each lineaments according to DEM
shp_listDir = os.listdir(inDir)
for shpName in shp_listDir:
if shpName[-4:] == ".shp":
inSHP = inDir + shpName
angleStart = shpName.find("_")+1
angleEnd = shpName.find("_", angleStart)
rotateAngle = shpName[shpName.rfind("_")+1:-4]
outLineName = shpName[0:angleEnd] + "_" +rotateAngle
outLineR = "in_memory\\" + outLineName
outLineB = "in_memory\\" + outLineName+"B"
# buffer inSHP
lineSHPBuffName = shpName[:-4]+"_buff%d" % bufferSize
lineSHPBuff = "in_memory\\" + lineSHPBuffName
if not os.path.exists(lineSHPBuff):
arcpy.Buffer_analysis(inSHP,lineSHPBuff,"%d Meters" % bufferSize,"FULL","ROUND","NONE","#")
if not os.path.exists(outLineB):
# create filed, fill with 1 in order to convert vector to raster
myField = "binary"
myValue = 1
# COMPUTING WITH BUFFER instead of line
inSHP = lineSHPBuff
arcpy.AddField_management(inSHP, myField, "SHORT", 2, "", "", "", "NULLABLE", "NON_REQUIRED")
arcpy.CalculateField_management(inSHP,myField,myValue,"PYTHON_9.3","#")
# polyline to raster, use this field
if not os.path.exists(outLineR):
desc = arcpy.Describe(rasterDEM)
arcpy.env.extent = desc.extent
arcpy.PolygonToRaster_conversion(inSHP,myField,outLineR,"CELL_CENTER","NONE",cellSize)
arcpy.env.extent = "default"
try:
# reclassify NoData to 0 !
arcpy.gp.Reclassify_sa(outLineR,"VALUE","1 1;NODATA 0",outLineB,"DATA")
tiffNames.append(outLineB)
except Exception as e:
print (e)
arcpy.Delete_management(outLineR)
arcpy.Delete_management(lineSHPBuff)
# raster calculator to sum up every raster
myExpression = ""
tif_listDir = tiffNames
for inTIF in tif_listDir:
myExpression += "\"" + inTIF + "\" + "
myExpression = myExpression[0:len(myExpression)-2]
arcpy.gp.RasterCalculator_sa(myExpression, outAllR)
for inTIF in tif_listDir:
arcpy.Delete_management(inTIF)
# TODO zachovat
# remove non relevant lines
def relevant(inDir, countThreshold, bufferSize, relevantMerged, DEM):
tempWS = config.temp
relevantWS = config.relevantWS
demDirs = [tempWS, relevantWS]
createDEMdirs(inDir, demDirs)
splitField = config.splitField
inRaster = inDir + tempWS + "outAllR"
# create sum of rasters
if not os.path.exists(inRaster):
getRelevantRaster(inDir, bufferSize, inRaster, DEM)
else:
print ("Out all raster exist")
# select only relevant lines according to raster approach (same as in Negatives)
shp_listDir = os.listdir(inDir)
for mySHP in shp_listDir:
if mySHP[-4:] == ".shp":
inSHP = inDir + mySHP
lineSHPRelevantsName = mySHP[:-4]+".shp"
lineSHPRelevant = inDir + relevantWS + lineSHPRelevantsName
if not os.path.exists(lineSHPRelevant):
# zonal with one statistic
zonalLineRelevant(inSHP, inRaster, bufferSize, countThreshold, lineSHPRelevant, "MEDIAN")
# # merge to oneSHP
if not os.path.exists(relevantMerged):
mergeLines(inDir+relevantWS, relevantMerged)
# compute azimuths and lenghts
try:
calcStats(relevantMerged)
except Exception as e:
print (e)
print ("time %s - deleting relevantWS" % (time.strftime("%m%d_%H%M%S")))
deletePath(inDir + relevantWS)
# TODO zachovat
def mergeLines(inDir, outMerge):
toMerge = ""
splitField = config.splitField
shp_listDir = os.listdir(inDir)
for mySHP in shp_listDir:
if mySHP[-4:] == ".shp":
inSHP = inDir + mySHP
if (arcpy.ListFields(inSHP, splitField) == []):
arcpy.AddField_management(inSHP, splitField, "TEXT")
splitName = mySHP[:-4]
arcpy.CalculateField_management(inSHP, splitField, "'%s'" % splitName, "PYTHON_9.3", "#")
toMerge += "%s;" % (inSHP)
arcpy.Merge_management(toMerge, outMerge)
##########################################################################################################################
##################################### C L U S T E R L I N E ############################################################
##########################################################################################################################
# TODO zachovat
# class for working with lines - id, length and azimuth
class line:
def __init__(self, ID, azimuth, length):
self.ID = ID
self.azimuth = azimuth
self.length = length
# TODO zachovat
# get statistic properties of input set
def getProperties(mySet):
mySet.sort()
n = len(mySet)
myMin = mySet[0]
myMax = mySet[n-1]
mean = sum(mySet)/len(mySet)
std = math.sqrt(sum((x-mean) ** 2 for x in mySet) / n)
medianIndex = int(0.5*(n+1))
if len(mySet) == 1:
median = mySet[0]
else:
median = mySet[medianIndex]
# print (" n: %i \n mean: %0.2f \n std: %0.2f \n median: %0.2f \n min: %0.2f \n max: %0.2f \n " % (n, mean, std, median, myMin, myMax)
return [n, mean, std, median, myMin, myMax]
# TODO zachovat
# split merged lines using splitField
def splitMerged(relevantMerged, outDir):
splitField = config.splitField
# split relevantMerged
cursor = arcpy.SearchCursor(relevantMerged, "","", splitField)
splitNames = []
for c in cursor:
splitNames.append(c.getValue(splitField))
# remove duplicates
uniqueNames = {}.fromkeys(splitNames).keys()
for splitName in uniqueNames:
outSHP = outDir + splitName+".shp"
if not os.path.exists(outSHP):
arcpy.MakeFeatureLayer_management(relevantMerged,splitName, "%s = '%s'" % (splitField, splitName))
arcpy.CopyFeatures_management(splitName, outSHP)
# TODO zachovat
# compute line clusters
def cluster(relevantMerged, countThreshold, stopInterval, relevantMergedB, bundleMerged, tb, DEM):
# config:
[bufferSizeMin, bufferSizeMax] = config.getBufferSizeCluster()
azimuthTreshold = config.azimuthTreshold
# load relevantMerged to in_memory
relevantMergeLayer = "relevantMerged"
myMemoryFeature = "in_memory" + "\\" + relevantMergeLayer
arcpy.CopyFeatures_management(relevantMerged, myMemoryFeature)
arcpy.MakeFeatureLayer_management(myMemoryFeature, relevantMergeLayer)
# calculates ID for deleting (FID is recalculated each time after deleting)
print("calculates ID for deleting")
if (arcpy.ListFields(relevantMergeLayer, "ShapeId_1")== []):
arcpy.AddField_management(relevantMergeLayer, "ShapeId_1", "LONG", 8, 2, "", "", "NULLABLE", "NON_REQUIRED")
arcpy.CalculateField_management(relevantMergeLayer,"ShapeId_1","!FID!","PYTHON_9.3","#")
# for each row in relevantMerged
# cursor for iterate rows in length descend order!
clusterID = 0
blueSet = []
bundleSet = []
# tb.log("cluster ordering")
# order cursor from the longest to the shortest line
rows = arcpy.SearchCursor(relevantMergeLayer, "","","","length D")
# fill the blueset with the rows
for row in rows:
blueLine = line(row.ShapeId_1, row.azimuth, row.length)
blueSet.append(blueLine)
del rows
# cleaning
relevantBackups = []
# memory push intervals
blueSetLength = len(blueSet)
blueInterval =blueSetLength/4+4
blueIterator = 0
######################################
# for each line in blueset #
######################################
for blueLine in blueSet[:stopInterval]:
myExpression = '"ShapeId_1" =%i' % (blueLine.ID)
arcpy.SelectLayerByAttribute_management(relevantMergeLayer,"NEW_SELECTION", myExpression)
noSelected = int(arcpy.GetCount_management(relevantMergeLayer).getOutput(0))
# if line with ID exists
if (noSelected == 1):
# make buffer around blueSHP (bigBuffer for completely within)
tempBuffer = "in_memory\\tempBuffer"
# ? Question of buffer size! # dynamic buffer size according to blueLength - 1/10
blueLength = blueLine.length
bufferSize = int(blueLength/10)
# supremum of buffersize (for extra long paralel lines near together)
if (bufferSize > bufferSizeMax):
bufferSize = bufferSizeMax
# infimum of buffersize (for short lines - small buffer not sufficient)
if (bufferSize < bufferSizeMin):
bufferSize = bufferSizeMin
arcpy.Buffer_analysis(relevantMergeLayer,tempBuffer,"%d Meters" % bufferSize,"FULL","ROUND","ALL","#")
arcpy.MakeFeatureLayer_management(tempBuffer, "tempBuffer")
# select all orange in buffer of blue
# intersect is better but slower - we will see
arcpy.SelectLayerByLocation_management(relevantMergeLayer, "COMPLETELY_WITHIN", "tempBuffer", "", "NEW_SELECTION")
noSelected = int(arcpy.GetCount_management(relevantMergeLayer).getOutput(0))
isBundle = False
if (noSelected >= countThreshold):
# create expression +/- azimuthTreshold from blueLine
blueMin = blueLine.azimuth - azimuthTreshold
if blueMin < 0:
blueMin += 180
blueMax = blueLine.azimuth + azimuthTreshold
if blueMax > 180:
blueMax -= 180
# this condition is useless. Azimuth is always >=0 and <180, after this simplification the myExpression is the same for both cases. The only important thing is to convert extremes to interval <0,180)
if (blueLine.azimuth < azimuthTreshold) or (blueLine.azimuth > 180 - azimuthTreshold):
myExpression = '("azimuth" >= %i and "azimuth" < %i) or ("azimuth" > %i and "azimuth" < %i)' % (0, blueMax, blueMin, 180)
else:
myExpression = '"azimuth" > %i and "azimuth" < %i ' % (blueMin, blueMax)
### SELECT THE CLUSTER LINES ###
arcpy.SelectLayerByAttribute_management(relevantMergeLayer,"SUBSET_SELECTION", myExpression)
# performance optimalization - go threw only bundle lines
# get count - if < countThreshold do not save, only delete!
noSelected = int(arcpy.GetCount_management(relevantMergeLayer).getOutput(0))
if (noSelected >= countThreshold):
isBundle = True
if (isBundle):
clusterID = blueLine.ID
# im_memory bundle
bundle = "in_memory\\line%i" % blueLine.ID
try:
arcpy.Buffer_analysis(relevantMergeLayer,bundle,"%d Meters" % 10,"FULL","ROUND","ALL","#")
# make layer from in_memory bundle
arcpy.MakeFeatureLayer_management(bundle, "bundle")
bundleSet.append(bundle)
except:
try:
arcpy.Buffer_analysis(relevantMergeLayer,bundle,"%d Meters" % 12,"FULL","ROUND","ALL","#")
# make layer from in_memory bundle
arcpy.MakeFeatureLayer_management(bundle, "bundle")
bundleSet.append(bundle)
except:
continue
arcpy.AddField_management(bundle, "count", "LONG", 9, "", "", "", "NULLABLE", "NON_REQUIRED")
arcpy.AddField_management(bundle, "azimuth", "LONG", 9, "", "", "", "NULLABLE", "NON_REQUIRED")
arcpy.AddField_management(bundle, "length", "LONG", 9, "", "", "", "NULLABLE", "NON_REQUIRED")
arcpy.CalculateField_management(bundle,"count",noSelected,"PYTHON_9.3","#")
lengthList = []
azimuthList = []
# compute stats on selection (cluster lines)
clusterRows = arcpy.SearchCursor(relevantMergeLayer)
for clusterRow in clusterRows:
lengthList.append(clusterRow.getValue("length"))
azimuthList.append(clusterRow.getValue("azimuth"))
del clusterRows
# length stats
[n, mean, std, median, myMin, myMax] = getProperties(lengthList)
arcpy.CalculateField_management(bundle, "length", "%i" % int(mean+std),"PYTHON_9.3","#")
azimuthList.sort()
azimuthMin = azimuthList[0]
azimuthMax = azimuthList[n-1]
# solve problem with angle numbers!
# set is on border of azimuths (180-0)
if ((azimuthMax-azimuthMin)>(2*azimuthTreshold)):
# new set - recclassify
azimuthListPlus = []
for azimuth in azimuthList:
if azimuth > (2*azimuthTreshold):
azimuthListPlus.append(azimuth-180)
else:
azimuthListPlus.append(azimuth)
# replace azimuthList
azimuthList = azimuthListPlus
# compute azimuth statistics
[n, mean, std, median, myMin, myMax] = getProperties(azimuthList)
if mean<0:
mean +=180
arcpy.CalculateField_management(bundle, "azimuth", "%i" % int(mean),"PYTHON_9.3","#")
# delete from merged
arcpy.DeleteFeatures_management(relevantMergeLayer)
#################################### E N D F O R ###########################################
print ("backup")
# a) backup relevantMerged to disk
arcpy.SelectLayerByAttribute_management(relevantMergeLayer, "CLEAR_SELECTION")
arcpy.CopyFeatures_management(relevantMergeLayer, relevantMergedB)
relevantBackups.append(relevantMergedB)
# write memory bundles to disk
# bundleMerged = demWS+bundleWS + "bundleMerged_%i.shp" % blueIterator
toMerge = ""
for bundle in bundleSet:
toMerge+= "in_memory\\%s;" % bundle
# print toMerge
# TODO: don't merge if toMerge is empty !
try:
arcpy.Merge_management(toMerge,bundleMerged)
relevantBackups.append(bundleMerged)
except Exception as e:
print (toMerge)
print (e)
# free memory
del bundleSet
# TODO zachovat
def createBundleLines(demWS):
mergeWS = config.mergeWS
bundleWS = config.bundleWS
tempWS = config.temp
demDirs = [tempWS]
createDEMdirs(demWS, demDirs)
print("cluster line algorithm")
# merge to oneSHP
bundleMerged = demWS+mergeWS + config.bundleMergedName
toMerge = ""
shp_listDir = os.listdir(demWS+bundleWS)
for mySHP in shp_listDir:
if mySHP[-4:] == ".shp":
toMerge+= "%s;" %(demWS+bundleWS+mySHP)
# print toMerge
if len(toMerge) > 0:
arcpy.Merge_management(toMerge,bundleMerged)
# createCentroids
centroidsPoints = demWS + mergeWS + "bundlePoints.shp"
arcpy.FeatureToPoint_management(bundleMerged, centroidsPoints, "CENTROID")
# compute average line points
centroidsLines = demWS + tempWS + "bundleLines.shp"
centroidsLinesJoin = demWS + mergeWS + "bundleLines.shp"
newLineList =[]
shapeName = arcpy.Describe(centroidsPoints).shapeFieldName
rows = arcpy.SearchCursor(centroidsPoints)
for row in rows:
arrayLine = arcpy.Array()
feat = row.getValue(shapeName)
pnt = feat.firstPoint
azimuth = row.getValue("azimuth")
length = row.getValue("length")
dX = math.sin(math.radians(azimuth))/2*length
dY = math.cos(math.radians(azimuth))/2*length
startPoint = arcpy.Point(pnt.X-dX, pnt.Y-dY)
arrayLine.add(startPoint)
endPoint = arcpy.Point(pnt.X+dX, pnt.Y+dY)
arrayLine.add(endPoint)
plyLine = arcpy.Polyline(arrayLine)
newLineList.append(plyLine)
del rows
arcpy.CopyFeatures_management(newLineList, centroidsLines)
arcpy.env.qualifiedFieldNames = False
arcpy.MakeFeatureLayer_management(centroidsLines, "centroidsLines")
arcpy.MakeFeatureLayer_management(centroidsPoints, "centroidsPoints")
arcpy.AddJoin_management("centroidsLines","FID","centroidsPoints","FID","KEEP_ALL")
arcpy.CopyFeatures_management("centroidsLines",centroidsLinesJoin)
else:
print ("bundleWS is empty")
# TODO zachovat
# function to make EAS script for PCI Geomatica - commands for line extraction
def printEAS(demWS, scriptEAS, inHill):
table = open(scriptEAS, 'a')
dbvs = 3
workspacePCI = config.workspacePCI
hlWS = config.hlWS
easiWS = config.easiWS
shpWS = config.shpWS
demWS = demWS.replace(workspace, workspacePCI)
table.write("! Setting parameters \n")
table.write("athr= {0}\n".format(config.athr))
table.write("dthr= {0}\n".format(config.dthr))
table.write("fthr= {0}\n".format(config.fthr))
table.write("radi= {0}\n".format(config.radi))
table.write("gthr = {0}\n".format(config.gthr))
table.write("lthr = {0}\n".format(config.lthr))
table.write("fili = \""+demWS+hlWS+inHill+"\"\n")
table.write("filo = \""+demWS+easiWS+inHill+".pix\"\n")
table.write("run fimport\n")
table.write("fili = filo\n")
table.write("dboc = 1\n")
table.write("dbic = 1\nDBVS=\nrun line\n")
table.write("dbic = \n")
table.write("DBVS = "+str(dbvs)+"\n")
table.write("FTYPE = \"SHP\"\n")
table.write("filo = \""+demWS+shpWS+inHill+".shp\"\n")
table.write("run fexport\n\n")
table.close()
# TODO zachovat
# Tool for prepare rasters for extraction
# Input - dem, azimuth range, rotation range
# Output - HLs in dem result directory for each rotation and one EAS script
def extractionRasters(DEM, azimuths, rotations):
# directories for results
runEAS = config.runEAS
hlWS = config.hlWS
easiWS = config.easiWS
shpWS = config.shpWS
demDirs = [hlWS, easiWS, shpWS]
# creates runEAS dir
runEASDir = resultsDir + runEAS
if not os.path.exists(runEASDir):
os.mkdir(runEASDir)
scriptEAS = runEASDir+"%s_%s.EAS" % (time.strftime("%m%d_%H%M%S"), DEM)
SA = config.getSA(DEM)
sourceDEM = config.getSourceDEM(DEM)
# input DEM
inRaster = sourceDir + "\\" + SA + "\\" + sourceDEM + "\\" + DEM
centerPoint = getRotationCenter(inRaster)
# parameters
altitude = config.altitude
# in case of NO rotation
rotateDEM0 = DEM.replace("dem", "r%i" % 0)
demWS0 = resultsDir + SA + "\\" + sourceDEM + "\\" + rotateDEM0 + "\\"
# for each rotation in rotations
for rotation in rotations:
rotateDEM = DEM.replace("dem", "r%i" % rotation)
demWS = resultsDir + SA + "\\" + sourceDEM + "\\" + rotateDEM + "\\"
# creates directories for result
if not os.path.exists(demWS):
os.makedirs(demWS)
createDEMdirs(demWS, demDirs)
# compute rotated HLs
for azimuth in azimuths:
outHL = demWS + hlWS + "hs_%i_r%i" % (azimuth, rotation)
# if HL exists - will not be calculated again
if not os.path.exists(outHL):
print ("time %s - creating HL with azimuth %s" % (time.strftime("%m%d_%H%M%S"), azimuth))
if rotation == 0:
arcpy.gp.HillShade_sa(inRaster,outHL,azimuth,altitude,"","")
else:
HL0 = demWS0 + hlWS + "hs_%i_r%i" % (azimuth, 0)
centerInput = "%s %s" % (centerPoint.X, centerPoint.Y)
arcpy.Rotate_management(HL0, outHL, rotation, centerInput ,"CUBIC")
printEAS(demWS, scriptEAS, getName(outHL))
# TODO zachovat
# roate point using centre and angle
def rotatePoint(center, point, angle):
angleRad = math.radians(angle)
xB = center.X + (point.X - center.X)*math.cos(angleRad)-(point.Y - center.Y)*math.sin(angleRad)
yB = center.Y + (point.X - center.X)*math.sin(angleRad)+(point.Y - center.Y)*math.cos(angleRad)
pointB = arcpy.Point(xB, yB)
return pointB
# TODO zachovat
# rotate shapefile using centre and angle to output rotatedSHP file
def rotateSHP(inSHP,center, angle, rotatedSHP):
newLineList =[]
desc = arcpy.Describe(inSHP)
shapeName = desc.shapeFieldName
rows = arcpy.SearchCursor(inSHP)
for row in rows:
feat = row.getValue(shapeName)
partnum = 0
for part in feat:
# a new pair of points
arrayLine = arcpy.Array()
# Step through each vertex in the feature
for pnt in feat.getPart(partnum):
if pnt:
pnt2 = rotatePoint(center, pnt, angle)
arrayLine.add(pnt2)
else:
# If pnt is None, this represents an interior ring
print ("Interior Ring:")
plyLine = arcpy.Polyline(arrayLine)
newLineList.append(plyLine)
partnum += 1
arcpy.CopyFeatures_management(newLineList, rotatedSHP)
# TODO zachovat
# for each shp in structure call rotateSHP
def rotateBack(DEM, rotations):
shpWS = config.shpWS
SA = config.getSA(DEM)
sourceDEM = config.getSourceDEM(DEM)
inRaster = sourceDir + "\\" + SA + "\\" + sourceDEM + "\\" + DEM
ceterPoint = getRotationCenter(inRaster)
shpRotateWS = config.shpRotateWS
demDirs = [shpRotateWS]
# for each rotation in rotations
for rotation in rotations:
rotateDEM = DEM.replace("dem", "r%i" % rotation)
demWS = resultsDir + SA + "\\" + sourceDEM + "\\" + rotateDEM + "\\"
# if extracted SHPs exist
# print os.path.exists(demWS+shpWS)
if os.path.exists(demWS+shpWS):
shp_listDir = os.listdir(demWS+shpWS)
if len(shp_listDir) != 0:
createDEMdirs(demWS, demDirs)
for mySHP in shp_listDir:
if mySHP[-4:] == ".shp":
inSHP = demWS+shpWS+mySHP
rotatedSHP = demWS + shpRotateWS + "\\" + mySHP
if not os.path.exists(rotatedSHP):
if rotation != 0:
rotateSHP(inSHP, ceterPoint, rotation, rotatedSHP)
else:
arcpy.Copy_management(inSHP, rotatedSHP)
# TODO zachovat
# spatial line clustering
def optimizedClusterLine(DEM, rotations, tb, lock):
lock.acquire()
optimalStop = config.optimalStop
clearWS = config.clearWS
shpLinesWS = config.shpLinesWS
bundleWS = config.bundleWS
mergeWS = config.mergeWS
demDirs = [bundleWS, clearWS, mergeWS]
SA = config.getSA(DEM)
sourceDEM = config.getSourceDEM(DEM)
# for each rotation in rotations
for rotation in rotations:
rotateDEM = DEM.replace("dem", "r%i" % rotation)
tb.log("optimizedClusterLine: %s" % rotateDEM)
demWS = resultsDir + SA + "\\" + sourceDEM + "\\" + rotateDEM + "\\"
if os.path.exists(demWS + shpLinesWS):
createDEMdirs(demWS, demDirs)
# first relevant
inDir = demWS + shpLinesWS
relevantMergedName = config.relevantMergedName
bundleMergedName = config.bundleMergedName
relevantT = config.relevantT
clusterT = config.clusterT
if (rotation == 99):
relevantT -= 2
clusterT -= 2
bufferSize = config.getCellSize(DEM)
relevantMerged = demWS + mergeWS + relevantMergedName
bundleMerged = demWS + mergeWS + bundleMergedName
if not os.path.exists(relevantMerged):
tb.log("relevant")
relevant(inDir, relevantT, bufferSize, relevantMerged, DEM)
bundleLines = demWS + mergeWS + "bundleLines.shp"
if not os.path.exists(bundleLines):
result = arcpy.GetCount_management(relevantMerged)
relevantCount = int(result.getOutput(0))
relevantCountStart = relevantCount
stopInterval = relevantCount / 8
while (relevantCount > optimalStop):
# cluster line
relevantMergedB = demWS + clearWS + "RM_%i.shp" % (relevantCount-stopInterval)
bundleMerged = demWS + bundleWS + "BM_%i.shp" % (relevantCount-stopInterval)
makeDirs(getDir(relevantMergedB))
tb.log("cluster")
cluster(relevantMerged, clusterT, stopInterval, relevantMergedB, bundleMerged, tb, DEM)
# split merged
tb.log("splitMerged")
relevantSplit = relevantMergedB
relevantSplitName = getName(relevantSplit)
splitDir = getDir(relevantSplit)+"split_%s\\" % relevantSplitName[:-4]
makeDirs(splitDir)
splitMerged(relevantSplit, splitDir)
# relevant
bufferSize = config.getCellSize(DEM)
relevantCleared = relevantMergedB[:-4] + "_C.shp"
tb.log("relevant")
relevant(splitDir, relevantT, bufferSize, relevantCleared, DEM)
# cycle
relevantMerged = relevantCleared
result = arcpy.GetCount_management(relevantMerged)
relevantCount = int(result.getOutput(0))
# more than 1/2 remains - 1/8 else 1/4
if (relevantCountStart/2+2) <= relevantCount:
stopInterval = relevantCount / 8
else:
stopInterval = relevantCount / 4
print (relevantCount)
# cluster line
relevantMergedB = demWS + clearWS + "RM_%i.shp" % (relevantCount-stopInterval)
bundleMerged = demWS + bundleWS + "BM_%i.shp" % (relevantCount-stopInterval)
makeDirs(getDir(relevantMergedB))
tb.log("cluster")
cluster(relevantMerged, clusterT, optimalStop, relevantMergedB, bundleMerged, tb, DEM)
# Create Average Lines of Bundles
tb.log("createBundleLines")
createBundleLines(demWS)
# computeAndPlotHist(bundleLines)
lock.release()
# TODO zachovat
# plot histograms using folder structure
def computeAndPlotHists(DEM, rotations, classType):
mergeWS = config.mergeWS
negativeWS = config.negativeWS
SA = config.getSA(DEM)
yMax = config.yMax
radMax = config.radMax
print ("compute and plot histogram")
graphTitle = "Rotation"
sourceDEM = config.getSourceDEM(DEM)
filterCount = config.filterCount
filterCountKIV = config.filterCountKIV
histWS = config.histWS[:-1]+"_%s" %config.getCellSize(DEM)+"\\"
demDirs = [histWS]
createDEMdirs(resultsDir + SA + "\\" + sourceDEM + "\\", demDirs)
# for each rotation in rotations
for rotation in rotations:
rotateDEM = DEM.replace("dem", "r%i" % rotation)
demWS = resultsDir + SA + "\\" + sourceDEM + "\\" + rotateDEM + "\\"
if classType == "all":
bundleLines = demWS + mergeWS + "bundleLines.shp"
bundleLinesKIV = demWS + mergeWS + "bundleLines_KIV.shp"
elif classType == "negative":
bundleLines = demWS + negativeWS + "bundleLines_NU.shp"
bundleLinesKIV = demWS + negativeWS + "bundleLines_KIV_NU.shp"
elif classType == "positive":
bundleLines = demWS + negativeWS + "bundleLines_P.shp"
bundleLinesKIV = demWS + negativeWS + "bundleLines_KIV_P.shp"
outHist = bundleLinesKIV[:-4] + "_hist.csv"
histDir = resultsDir + SA + "\\" + sourceDEM + "\\" + histWS
if os.path.exists(bundleLinesKIV):
if not os.path.exists(outHist):
getHistogram(bundleLinesKIV, filterCountKIV)
plotHist(outHist, histDir + getName(bundleLinesKIV)[:-4] + "_r%i_hist.png" %rotation, yMax, radMax, "", "%s %s dg" % (graphTitle, rotation), "C# KIV", "", 4,4, "png")
# TODO zachovat
def splitAndErase(DEM, rotations):
shpRotateWS = config.shpRotateWS
shpLinesWS = config.shpLinesWS
demDirs = [shpLinesWS]
SA = config.getSA(DEM)
sourceDEM = config.getSourceDEM(DEM)
# for each rotation in rotations
for rotation in rotations:
rotateDEM = DEM.replace("dem", "r%i" % rotation)
demWS = resultsDir + SA + "\\" + sourceDEM + "\\" + rotateDEM + "\\"
if os.path.exists(demWS + shpRotateWS):
createDEMdirs(demWS, demDirs)
# split lines
splitLines(demWS, shpRotateWS, shpLinesWS)
# raster is not rectangle
inDEMBuffer = sourceDir + SA + "\\" + sourceDEM + "\\" + "boundary.shp"
print ("eraseB")
if os.path.exists(inDEMBuffer):
eraseBoundarySHP(inDEMBuffer, demWS)
else:
print ("Do not clip - boundary does not exist!")
# get csv for length weigthted histogram
# Improvement remove filterCount param - is not general need
# Improvement make output histogram as input parameter, not output
# TODO zachovat
def getHistogram(inSHP, filterCount):
# if count field exists
if not (arcpy.ListFields(inSHP, "count")== []):
# use only features with more than filterCount in count field
arcpy.MakeFeatureLayer_management(inSHP, "inSHP", '"count" >= %i' % filterCount)
else:
# use all features
arcpy.MakeFeatureLayer_management(inSHP, "inSHP")
# if azimuth and lenght stats not exists
if (arcpy.ListFields(inSHP, "azimuth")== [] or arcpy.ListFields(inSHP, "length")== []):
# calculate azimuth and lenght
calcStats(inSHP)
# output histogram statistics
if ((inSHP)[-4:] == ".shp"):
histFileName = inSHP[:-4] + "_hist.csv"
else:
histFileName = getDir(getDir(inSHP)[:-1]) + getName(inSHP) + "_hist.csv"
histFile = open(histFileName, 'w')
# total length and total count
rows = arcpy.SearchCursor("inSHP")
# rows = arcpy.SearchCursor(inSHP)
totalCount = int(arcpy.GetCount_management("inSHP").getOutput(0))
# totalCount = 0
totalLength = 0
histM = []
# cluster = []
for row in rows:
histM.append([row.azimuth, row.length])
totalLength += row.getValue("length")
# totalCount +=1
print (totalLength)
print (totalCount)
# for each degree count number and total length
for az in range(0,180,1):
noSelected = 0
intervalLength = 0
for row in histM:
A = row[0]
if (az <= A < az+1):
noSelected += 1
intervalLength += row[1]
if (noSelected != 0):
histText = "%i; %i; %0.2f; %f; %f\n" % (az, noSelected, intervalLength, (float(noSelected)/totalCount*100), (100*float(intervalLength)/totalLength))
histText = histText.replace(".", ",")
histFile.write(histText)
else:
histText = "%i; 0; 0; 0; 0\n" % az
histFile.write(histText)
histFile.close()
return histFileName
def copyAngles(DEM, rotations, azimuths):
shpLinesWS = config.shpLinesWS
mergeWS = config.mergeWS
demDirs = [shpLinesWS]
# copy and rename bundleLines.shp to new DEM based folder r9x
SA = config.getSA(DEM)
SA3 = SA+"_III"
sourceDEM = config.getSourceDEM(DEM)
outWS = resultsDir + SA3 + "\\" + sourceDEM + "\\"
for azimuth in azimuths:
outDEM = DEM.replace("dem", "r%i" % azimuth)
makeDirs(outWS+outDEM)
outDemWS = outWS + outDEM + "\\"
createDEMdirs(outDemWS, demDirs)
for rotation in rotations:
rotateDEM = DEM.replace("dem", "r%i" % rotation)
demWS = resultsDir + SA + "\\" + sourceDEM + "\\" + rotateDEM + "\\"
inSHPName = "hs_%i_r%i.shp" %(azimuth, rotation)
inSHP = demWS + shpLinesWS + inSHPName
if os.path.exists(inSHP):
copySHP = outDemWS + shpLinesWS + inSHPName
if not os.path.exists(copySHP):
print ("copy %s" % copySHP)
arcpy.Copy_management(inSHP, copySHP)
# TODO zachovat
# prepare data for last step of hierachical clustering
def finalCluster(DEM, clusterName):
azimuths = config.azimuths
rotations = config.rotations
shpLinesWS = config.shpLinesWS
mergeWS = config.mergeWS
demDirs = [shpLinesWS]
# copy and rename bundleLines.shp to new DEM based folder r9x
SA = config.getSA(DEM)
sourceDEM = config.getSourceDEM(DEM)
outWS = resultsDir + SA + "\\" + sourceDEM + "\\"
outDEM = DEM.replace("dem", "r%i" % clusterName)
for rotation in rotations:
rotateDEM = DEM.replace("dem", "r%i" % rotation)
demWS = resultsDir + SA + "\\" + sourceDEM + "\\" + rotateDEM + "\\"
inSHP = demWS + mergeWS + "bundleLines.shp"
if os.path.exists(inSHP):
createDEMdirs(outWS, [outDEM])
outDemWS = outWS + outDEM + "\\"
createDEMdirs(outDemWS, demDirs)
copySHP = outDemWS + shpLinesWS + "hs_%i_r%i.shp" %(rotation, clusterName)
if not os.path.exists(copySHP):
print ("copy %s" % copySHP)
arcpy.Copy_management(inSHP, copySHP)
# computes lines statistics of length
def getLineLengthStats(inSHP, statFile):
# compute stats to output temp table
print "time %s - getting LENGTH stats" % (time.strftime("%m%d_%H%M%S"))
mergedStats = inSHP[:-4] + "_stats.dbf"
if (arcpy.ListFields(inSHP, "length") == []):
calcStats(inSHP)
arcpy.Statistics_analysis(inSHP, mergedStats, "length SUM; length MEAN; length MIN; length MAX", "#")
curT = arcpy.SearchCursor(mergedStats)
# one row supposed
row = curT.next()
desc = arcpy.Describe(mergedStats)
for field in desc.fields[1:]:
fieldName = field.Name
print "%s = %s" % (fieldName, row.getValue(fieldName))
value = "%0.2f" % row.getValue(fieldName)
value = value.replace(".", ",")
statFile.write("%s;" % value)
statFile.write("\n")
# delete temp stats table
arcpy.Delete_management(mergedStats)
# TODO zachovat
# STEP 06 - Classification of lineaments
def classifyRidges(DEM, rotations):
print ("time %s - running script for DEM %s" % (time.strftime("%m%d_%H%M%S"), DEM))
# directories for results
mergeWS = config.mergeWS
negativeWS = config.negativeWS
tempWS = config.temp
flowWS = config.flowWS
demDirs = [negativeWS, tempWS, flowWS]
bufferSize = config.bufferSizeRidges
meaPar = [config.parMeaRidge, config.parMeaValley]
medPar = [config.parMedRidge, config.parMedValley]
# input DEM
SA = config.getSA(DEM)
sourceDEM = config.getSourceDEM(DEM)
inDEM = sourceDir + SA + "\\" + sourceDEM + "\\" + DEM
for rotation in rotations:
rotateDEM = DEM.replace("dem", "r%i" % rotation)
demWS = resultsDir + SA + "\\" + sourceDEM + "\\" + rotateDEM + "\\"
lineSHP = demWS + mergeWS + "bundleLines.shp"
print (lineSHP)
if os.path.exists(lineSHP):
createDEMdirs(demWS, demDirs)
# compute FlowAcc for DEM
flowAcc = getFlowAcc(demWS, inDEM)
# call function to separate ridges and valleys lines
mySHP = getName(lineSHP)
lineSHPNegativesName = mySHP[:-4]+"_N.shp"
lineSHPNegative = demWS + negativeWS + lineSHPNegativesName
lineSHPPositivesName = mySHP[:-4]+"_P.shp"
lineSHPPositive = demWS + negativeWS + lineSHPPositivesName
lineSHPUnsuresName = mySHP[:-4]+"_U.shp"
lineSHPUnsure = demWS + negativeWS + lineSHPUnsuresName
# classify lines using threshold for flowAcc field (3 classes - positive, unsure, negative)
zonalLine(lineSHP, flowAcc, bufferSize, meaPar, medPar, lineSHPNegative, lineSHPPositive, lineSHPUnsure)
# 7.11. merge non tested :-)
lineSHPNUName = mySHP[:-4]+"_NU.shp"
lineSHPNU = demWS + negativeWS + lineSHPNUName
arcpy.Merge_management("%s;%s" % (lineSHPNegative,lineSHPUnsure),lineSHPNU)
# TODO zachovat
# function to compare two lines
def compareLines(blueSHP, orangeSHP, isClip, logFileName, azimuthTreshold, bufferSize):
try:
logFile = open(logFileName, 'a')
# if statistics does not exist -> compute!
if (arcpy.ListFields(blueSHP, "azimuth") == []) or (arcpy.ListFields(blueSHP, "length") == []):
calcStats(blueSHP)
if (arcpy.ListFields(orangeSHP, "azimuth") == []) or (arcpy.ListFields(orangeSHP, "length") == []):
calcStats(orangeSHP)
# parameters from config/input
usedMethod = "Centroids"
if isClip:
usedMethod = "Clip"
logFile.write("%s; %s; %s; %i; %i;" % (blueSHP, orangeSHP, usedMethod, azimuthTreshold, bufferSize))
# correlation based on count
noSimilar = 0
# length weighted correlation index
corrISum = 0
lengthCorrSum = 0
lengthA = 0
rows = arcpy.SearchCursor(blueSHP)
for row in rows:
lengthA += row.getValue("length")
### IF USING CENTROID METHOD
if not isClip:
# from orange make centroids
orangeSHPLyr = orangeSHP[:-4] + "_centroids.shp"
if not os.path.exists(orangeSHPLyr):
arcpy.FeatureToPoint_management(orangeSHP, orangeSHPLyr, "CENTROID")
arcpy.MakeFeatureLayer_management(orangeSHPLyr, "orangeLyr")
# count number of lines in blueSHP
result = arcpy.GetCount_management(blueSHP)
noFeatures = int(result.getOutput(0))
noLines = noFeatures
procento = 0
# for each feature in blue
for val in range(0, int(noFeatures), 1):
orangeLength = 0
# layer for blue
arcpy.MakeFeatureLayer_management(blueSHP, "blueFeat", "FID = %i" % val)
### IF USING CLIP METHOD
# TODO: test azimuth before cliping!
if isClip:
# make buffer around blueLine
blueBuffer = blueSHP[:-4] + "_buffer.shp"
arcpy.Buffer_analysis("blueFeat", blueBuffer, "%d Meters" % bufferSize, "FULL", "ROUND", "NONE", "#")
# find intersection with orange
orangeSHPLyr = orangeSHP[:-4] + "_clip.shp"
arcpy.Clip_analysis(orangeSHP, blueBuffer, orangeSHPLyr, "#")
arcpy.MakeFeatureLayer_management(orangeSHPLyr, "orangeLyr")
else:
# find intersection with orange
arcpy.SelectLayerByLocation_management("orangeLyr", "WITHIN_A_DISTANCE", "blueFeat", "%d Meters" % bufferSize,
"NEW_SELECTION")
### AT THIS POINT, orangeLyr EXISTS in every case
# number of selected orange features
result = arcpy.GetCount_management("orangeLyr")
noFeatures = int(result.getOutput(0))
# print "Pocet pruseciku: %i" % noFeatures
# if the intersect exists
if (noFeatures != 0):
# get sttributes for blueSHP
rows = arcpy.SearchCursor("blueFeat")
# blueFeat je jen jeden radek!
for row in rows:
azimuth = row.getValue("azimuth")
blueLength = row.getValue("length")
blueMin = azimuth - azimuthTreshold
if blueMin < 0:
blueMin = 180 + blueMin
blueMax = azimuth + azimuthTreshold
if blueMax > 180:
blueMax = blueMax - 180
if (azimuth < azimuthTreshold) or (azimuth > 180 - azimuthTreshold):
myExpression = '("azimuth" >= %i and "azimuth" < %i) or ("azimuth" > %i and "azimuth" < %i)' % (
0, blueMax, blueMin, 180)
else:
myExpression = '"azimuth" > %i and "azimuth" < %i ' % (blueMin, blueMax)
### SELECT THE SIMILAR LINES ###
# print myExpression
###
# use SUBSET_SELECTION IF USING CENTROID METHOD
selectionMethod = "SUBSET_SELECTION"
if isClip:
selectionMethod = "NEW_SELECTION"
arcpy.SelectLayerByAttribute_management("orangeLyr", selectionMethod, myExpression)
noSelected = int(arcpy.GetCount_management("orangeLyr").getOutput(0))
# print "Pocet podobnych linii: %i" % noSelected
if (noSelected != 0):
### IF USING CLIP METHOD recalculate length stats
if isClip:
calcStats("orangeLyr")
# count length of orange
rows = arcpy.SearchCursor("orangeLyr")
for row in rows:
orangeLength += row.getValue("length")
corrI = min(float(orangeLength) / blueLength, 1)
# print corrI
# correlation improvement - if correlation is grater than 80 % it can be considered like 100 %
# prof. Minar disagree -> 1.66 = switched off
if (corrI > 1.66):
lengthCorrSum += blueLength
else:
lengthCorrSum += min(orangeLength, blueLength)
corrISum += corrI
# print "orangeLength sum = %0.2f, blueLength = %0.2f corrI = %0.2f" %(orangeLength, blueLength, corrI)
noSimilar += 1
aktualni = val * 100 / noLines
if (procento - aktualni != 0):
print "%s pct" % (val * 100 / noLines)
procento = aktualni
# print noSimilar
corrA = float(lengthCorrSum) / lengthA * 100 # length weigthed divided by length
corrB = float(noSimilar) / noLines * 100 # based on correlated no. lines
corrC = float(corrISum) / noLines * 100 # length weigthed divided by no. lines
logFile.write("%0.2f; %i; %i; %0.2f; %i; %i; %0.2f; %0.2f;\n" % (
corrA, lengthA, lengthCorrSum, corrB, noLines, noSimilar, corrC, corrISum))
# nezamenovat DeleteFeatures s Delete
arcpy.Delete_management(orangeSHPLyr)
if isClip:
arcpy.Delete_management(blueBuffer)
print corrA
# logFile.write("from %i lines, %s lines correlated with line B, thus correlation is %0.2f pct with tolerance of %i degrees in radius of %i\n" % (noLines, noSimilar, float(noSimilar)/noLines*100, azimuthTreshold, bufferSize))
# logFile.write("length weighted correlation index is %0.2f thus correlation is %0.2f pct\n" % (corrISum,float(corrISum)/noLines*100))
# logFile.write("Sum of correlation length is %0.2f thus correlation is %0.2f pct\n" % (lengthCorrSum,corrA)
except Exception, e:
print e
# logFile.write(e)
traceback.print_exc(file=logFile)
finally:
logFile.close()
def computeHist(inSHP, myDict, yMax, radMax, fileFormat):
# output stats are placed in the same dir as input with the derived names
# output statistic CSV - this file can be processed in Excell to plot graphs
outStats = getHistogram(inSHP, 0) # return name inSHP[:-4] + "_hist.csv"
# output histogram PNG
if ((inSHP)[-4:] == ".shp"):
outFile = inSHP[:-4] + "_hist." + fileFormat
else:
outFile = getDir(getDir(inSHP)[:-1]) + getName(inSHP) + "_hist." + fileFormat
print outFile
try:
name = myDict[getName(inSHP)[:-4]]
except KeyError:
print "no dict defined"
finally:
name = getName(inSHP)
print name
plotHist(outStats, outFile, yMax, radMax, "", u"Smerova statistika %s" % name, name, "B", 4, 4, fileFormat)
def compareTwoHists(inSHP, inSHP0, yMax, radMax, fileFormat):
# output stats are placed in the same dir as input with the derived names
# output statistic CSV - this file can be processed in Excell to plot graphs
outStats = getHistogram(inSHP, 0) # return name inSHP[:-4] + "_hist.csv"
outStats0 = getHistogram(inSHP0, 0) # return name inSHP[:-4] + "_hist.csv"
# output histogram PNG
outFile = inSHP[:-4] + "_compare_hist." + fileFormat
name = getName(inSHP)[:-4]
name0 = getName(inSHP0)[:-4]
plotHist(outStats, outFile, yMax, radMax, outStats0, "Comparison %s with %s" % (name, name0), name, name0, 4,
4, fileFormat)
def plotHist(inHistPath, outPNG, yMax, radMax, inHist0Path, graphTitle, labelA, labelB, filterCountA, filterCountB, fileFormat):
headerFont = FontProperties()
headerFont.set_weight("bold")
headerFont.set_size("xx-large")
captionFont = FontProperties()
# captionFont.set_weight("bold")
captionFont.set_size("x-large")
axisFont = FontProperties()
axisFont.set_size("large")
axisFont.set_weight("bold")
colorA = "blue"
colorB = "red"
t = range(0, 180, 1)
count0 = 0
if not inHist0Path == "":
inHist0 = open(inHist0Path, "r")
s0 = []
for row in inHist0:
rs = row.split(";")
lw = rs[4].strip()
count0 += int(rs[1].strip())
s0.append(float(lw.replace(",", ".")))
mA0 = []
for i in t:
if i < 3:
subsetA = s0[i-3:]
subsetB = s0[:i+4]
subset = subsetA+subsetB
elif i > 176:
subsetA = s0[i-3:]
subsetB = s0[:4-(len(s0)-i)]
subset = subsetA+subsetB
else:
subset = s0[i-3:i+4]
mA0value = mean = sum(subset)/len(subset)
mA0.append(mA0value)
count = 0
inHist = open(inHistPath, "r")
s = []
for row in inHist:
rs = row.split(";")
lw = rs[4].strip()
count += int(rs[1].strip())
s.append(float(lw.replace(",", ".")))
mA = []
for i in t:
if i < 3:
subsetA = s[i-3:]
subsetB = s[:i+4]
subset = subsetA+subsetB
elif i > 176:
subsetA = s[i-3:]
subsetB = s[:4-(len(s)-i)]
subset = subsetA+subsetB
else:
subset = s[i-3:i+4]
mAvalue = mean = sum(subset)/len(subset)
mA.append(mAvalue)
plt.clf()
fig = plt.figure()
if not inHist0Path == "":
gs = gridspec.GridSpec(1, 3, width_ratios=[3, 1, 1])
else:
gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1])
ax1 = fig.add_subplot(gs[0])
plt.plot(t, mA, linewidth=3.0, color = colorA, label = labelA)
if not inHist0Path == "":
plt.plot(t, mA0, linewidth=3.0, color = colorB, label = labelB)
plt.xlabel(u'uhel [dg]', fontproperties=axisFont)
plt.ylabel(u'pomer delek [%]', fontproperties=axisFont)
inHistName = getName(inHistPath)
plt.title(graphTitle, fontproperties=headerFont)
plt.legend()
plt.grid(True)
F = plt.gcf()
if inHist0Path == "":
ax1.bar(t, s, color="gray", edgecolor='none')
F.set_size_inches(24,6)# resetthe size
plt.xticks(range(0,len(t)+5,5), fontproperties=axisFont)
if yMax > 0:
plt.yticks(range(0,yMax,1), fontproperties=axisFont)
plt.ylim(0,yMax)
plt.xlim(0,180)
plt.tight_layout()
#### add polar plot ####
ax = fig.add_subplot(gs[1], polar=True)
# ax.set_title("c# KIV")
step = 5
t = range(0, 180, step)
mP = []
for i in t:
mP.append(sum(s[i:i+step-1]))
mP += mP
theta = np.linspace(0.0, 2 * np.pi, 360/step, endpoint=False)
radii = np.random.rand(len(theta))
width = step*np.pi/180
ax.set_theta_zero_location('N')
ax.set_theta_direction(-1)
ax.set_yticks(range(0,radMax,2))
xLabels = ax.get_xticklabels()
myKwargs = {"fontproperties": captionFont}
# for xLabel in xLabels:
# print xLabel
dg = u'\xb0'
ax.set_xticklabels((u'0%s' % dg, u'45%s' % dg, u'90%s' % dg, u'135%s' % dg, u'180%s' % dg, u'225%s' % dg, u'270%s' % dg, u'315%s' % dg), fontproperties=captionFont)
yLabels = ax.get_yticklabels()
# for yLabel in yLabels:
# print yLabel
ax.set_ylim(0,radMax)
bars = ax.bar(theta, mP, width=width, bottom=0.0)
# Use custom colors and opacity
for r, bar in zip(radii, bars):
bar.set_facecolor(colorA)
bar.set_alpha(0.5)
bar.set_edgecolor(colorA)
# for i in np.linspace(0.0, 2 * np.pi, 8, endpoint=False):
# for j in range(0,15,3):
# plt.text(i,j, "%i,%i" % (i*180/np.pi,j))
plt.text(315.0/180*np.pi, 1.42*radMax, labelA, fontproperties=captionFont)
plt.text(225.0/180*np.pi, 1.72*radMax, u"Pocet:%i" % (count), fontproperties=captionFont)
if not inHist0Path == "":
#### add polar plot ####
ax2 = fig.add_subplot(gs[2], polar=True)
# ax2.set_title("Python")
step = 5
t = range(0, 180, step)
mP0 = []
for i in t:
mP0.append(sum(s0[i:i+step-1]))
mP0 += mP0
theta = np.linspace(0.0, 2 * np.pi, 360/step, endpoint=False)
radii = np.random.rand(len(theta))
width = step*np.pi/180
ax2.set_theta_zero_location('N')
ax2.set_theta_direction(-1)
ax2.set_yticks(range(0,radMax,2))
ax2.set_ylim(0,radMax)
bars = ax2.bar(theta, mP0, width=width, bottom=0.0)
# Use custom colors and opacity
for r, bar in zip(radii, bars):
bar.set_facecolor(colorB)
bar.set_alpha(0.5)
bar.set_edgecolor(colorB)
plt.text(315.0/180*np.pi, 10, labelB, fontproperties=captionFont)
plt.text(225.0/180*np.pi, 12, "Count:%i\ncT:%i" % (count0, filterCountB), fontproperties=captionFont)
plt.subplots_adjust(wspace=0.1)
F.savefig(outPNG, format=fileFormat)
# plt.show()
if not inHist0Path == "":
inHist0.close()
inHist.close()
plt.close('all')
# MHHCA preparation
# export coordinates from input SHP to TXT
# polarize lines to directions 0-180 dg
# polarizace nezafunguje na prechodu 179-0 a v jeho okoli - nevhodne treba pro KIV a! a pak nevhodne pro prumerovani
def polarize(inSHP, outTXTName):
# outTXTName = inSHP[:-4]+"_XYA_P.txt"
outTXT = open(outTXTName, "w")
textLog = "ID; A.X; A.Y; B.X; B.Y; A; L\n"
outTXT.write(textLog)
rows = arcpy.SearchCursor(inSHP, "","","","length D")
# rows = arcpy.SearchCursor(inSHP, "","","")
desc = arcpy.Describe(inSHP)
shapefieldname = desc.ShapeFieldName
for row in rows:
feat = row.getValue(shapefieldname)
pnts = getPoints(feat)
A = pnts[0]
B = pnts[1]
dY = (A.Y - B.Y)
dX = (A.X - B.X)
atan2 = math.atan2(dY,dX)
alpha = math.degrees(atan2)
# print ("(%i,%i): %i dg, %f rad" % (B.X, B.Y, alpha, atan2)
if 90 >= alpha > -90:
# print ("switch"
C = A
A = B
B = C
textLog = "%i;%i;%i;%i;%i;%i;%i;\n" % (row.FID, A.X, A.Y, B.X, B.Y, row.azimuth, row.length)
outTXT.write(textLog)
outTXT.close()
# MHHCA preparation
def writeAverageSHP(clusterSet, resultSHP, clusterT, inSHP):
averageMethod = config.averageMethod
# tb.log("prepare SHP")
azimuthTreshold = config.azimuthTreshold
polylineList =[]
attributeList = []
countList = []
for c in clusterSet:
# filter clusters with insufficient number of lines
if len(c.IDs) >= clusterT:
# if cluster is on the border 179-0-1 (suppose that azimuth threshold has been applied)
if (max(c.A) - min(c.A)) > 2*azimuthTreshold:
# for every lines with A < 0 - switch start to end
for i in range(0,len(c.A),1):
if c.A[i] > 2*azimuthTreshold:
Cx = c.Ax[i]
Cy = c.Ay[i]
c.Ax[i] = c.Bx[i]
c.Ay[i] = c.By[i]
c.Bx[i] = Cx
c.By[i] = Cy
# print c.myId
if (averageMethod == "aritmetic"):
# aritmetic average of coordinates
Ax = (sum(c.Ax)/len(c.Ax))
Ay = (sum(c.Ay)/len(c.Ay))
Bx = (sum(c.Bx)/len(c.Bx))
By = (sum(c.By)/len(c.By))
elif(averageMethod == "centers"):
# preserve only centers as cluster's representants
Ax = c.Ax[0]
Ay = c.Ay[0]
Bx = c.Bx[0]
By = c.By[0]
elif (averageMethod == "lw_average"):
sumAx = 0
sumAy = 0
sumBx = 0
sumBy = 0
for i in range (0, len(c.Ax), 1):
length = c.length[i]
sumAx += c.Ax[i]*length
sumAy += c.Ay[i]*length
sumBx += c.Bx[i]*length
sumBy += c.By[i]*length
sumLength = sum(c.length)
Ax = sumAx/sumLength
Ay = sumAy/sumLength
Bx = sumBx/sumLength
By = sumBy/sumLength
elif (averageMethod == "centroid"):
sumAx = 0
sumAy = 0
sumBx = 0
sumBy = 0
for i in range (0, len(c.Ax), 1):
length = c.length[i]
sumAx += c.Ax[i]*length
sumAy += c.Ay[i]*length
sumBx += c.Bx[i]*length
sumBy += c.By[i]*length
sumLength = sum(c.length)
Ax = sumAx/sumLength
Ay = sumAy/sumLength
Bx = sumBx/sumLength
By = sumBy/sumLength
cX = (Ax+Bx)/2
cY = (Ay+By)/2
# print cX, cY
# print Ax, Ay
arrayLine = arcpy.Array()
if (averageMethod == "centroid"):
# azimuth = c.A[0] # !! TEST !! -replace with average azimuth !!!
# replica from cluster() !
azimuthList = c.A
azimuthList.sort()
azimuthMin = azimuthList[0]
azimuthMax = azimuthList[-1]
# solve problem with angle numbers!
# set is on border of azimuths (180-0)
if ((azimuthMax-azimuthMin)>(2*azimuthTreshold)):
# new set - recclassify
azimuthListPlus = []
for azimuth in azimuthList:
if azimuth > (2*azimuthTreshold):
azimuthListPlus.append(azimuth-180)
else:
azimuthListPlus.append(azimuth)
# replace azimuthList
azimuthList = azimuthListPlus
# compute azimuth statistics
azimuthStats = getProperties(azimuthList)
azimuth = azimuthStats[1]
if azimuth<0:
azimuth +=180
lengthStats = getProperties(c.length)
# upper quartile
length = lengthStats[1] + lengthStats[2]
# maximum
# length = lengthStats[5]
# TEST
# length = lengthStats[5] + 2*config.xKIV
# print ("mean: % i, std: %i, max: %i, max+2*bfsz: %i" % (lengthStats[1], lengthStats[2], lengthStats[5], lengthStats[5] + 2*config.xKIV)
dX = math.sin(math.radians(azimuth))/2*length
dY = math.cos(math.radians(azimuth))/2*length
startPoint = arcpy.Point(cX-dX, cY-dY)
arrayLine.add(startPoint)
endPoint = arcpy.Point(cX+dX, cY+dY)
arrayLine.add(endPoint)
# print startPoint.X, startPoint.Y, endPoint.X, endPoint.Y
else:
startPoint = arcpy.Point(Ax, Ay)
arrayLine.add(startPoint)
endPoint = arcpy.Point(Bx, By)
arrayLine.add(endPoint)
plyLine = arcpy.Polyline(arrayLine)
polylineList.append(plyLine)
attributeList.append(c.IDs[0])
countList.append(len(c.IDs))
# tb.log("write SHP")
if not polylineList == []:
arcpy.CopyFeatures_management(polylineList, resultSHP)
countField = "count"
if (arcpy.ListFields(resultSHP, countField)== []):
arcpy.AddField_management(resultSHP, countField, "LONG", 8, 2, "", "", "NULLABLE", "NON_REQUIRED")
# update cursor - fill attributes
rows = arcpy.UpdateCursor(resultSHP)
i = 0
for row in rows:
row.Id = attributeList[i]
row.count = countList[i]
rows.updateRow(row)
i+=1
del rows
else:
print ("No clusters created!")
### TEST ###
# markClustersCursor(inSHP, clusterSet)
# MHHCA
# add attributes from row to cluster object 1 row = 1 line
def addLine(cluster, row):
cluster.IDs.append(int(float(row[1])))
cluster.Ax.append(float(row[2]))
cluster.Ay.append(float(row[3]))
cluster.Bx.append(float(row[4]))
cluster.By.append(float(row[5]))
cluster.A.append(float(row[6]))
cluster.length.append(float(row[7]))
# MHHCA
# process result file and create list of clusters
def readClusters(resultTXT):
results = open(resultTXT, "r")
cluster = Cluster()
clusterSet = []
rows = []
myId = 0
# tb.log("read file")
for result in results:
rows.append(result)
results.close()
# tb.log("process clusters")
addLine(cluster, rows[1].replace(",",".").split(";"))
cluster.myId = myId
myId +=1
for row in rows[2:]:
row = row.replace(",",".")
row = row.split(";")
if row[0] == "*":
clusterSet.append(cluster)
cluster = Cluster()
cluster.myId = myId
myId +=1
addLine(cluster, row)
clusterSet.append(cluster)
return clusterSet
# MHHCA
# inSHP - relevantMerged.shp - outSHP - bundleLines_KIV.shp
def clusterKIV(inSHP, resultSHP, tb):
gisExePath = config.gisExePath
# polarize SHP to TXT
polarizedTXT = inSHP[:-4]+"_XYAL_P.txt"
if not os.path.exists(polarizedTXT):
tb.log("polarize")
polarize(inSHP, polarizedTXT)
tb.log("polarize - done")
# compute KIV cluster algorithm
resultTXT = inSHP[:-4]+"_result.txt"
if not os.path.exists(resultTXT):
X = config.xKIV
Y = config.yKIV #config.bufferSizeKIV
A = config.azimuthTreshold
# GIS.exe <input file path> <border X> <border Y> <border azimuth> <filter> <output file path>
arguments = "%s %i %i %i %i %s" %(polarizedTXT, X, Y, A, 0, resultTXT)
command = "%s %s" % (gisExePath, arguments)
tb.log("cluster KIV command")
os.system(command)
tb.log("cluster KIV command done")
tb.log("process results")
myClusters = readClusters(resultTXT)
clusterTKIV = config.clusterTKIV
writeAverageSHP(myClusters, resultSHP, clusterTKIV, inSHP)
tb.log("process results done")
# delete temps
os.remove(polarizedTXT)
os.remove(resultTXT)
# MHHCA main method
def clusterLineKIV(DEM, rotations, tb):
shpLinesWS = config.shpLinesWS
mergeWS = config.mergeWS
demDirs = [mergeWS]
SA = config.getSA(DEM)
sourceDEM = config.getSourceDEM(DEM)
# for each rotation in rotations
for rotation in rotations:
rotateDEM = DEM.replace("dem", "r%i" %rotation)
tb.log("ClusterLineKIV: %s" %(rotateDEM))
demWS = resultsDir + SA + "\\" + sourceDEM + "\\" + rotateDEM + "\\"
if os.path.exists(demWS + shpLinesWS):
createDEMdirs(demWS, demDirs)
# relevantLite - use own relevant - only merge shpLines!
inDir = demWS + shpLinesWS
relevantMergedNameLite = config.relevantMergedNameLite
relevantMergedLite = demWS + mergeWS + relevantMergedNameLite
if not os.path.exists(relevantMergedLite):
tb.log("relevantLite")
relevantLite(inDir, relevantMergedLite, tb)
tb.log("relevantLite done")
bundleLinesKIV = demWS + mergeWS + "bundleLines_KIV.shp"
if not os.path.exists(bundleLinesKIV):
tb.log("cluster KIV")
clusterKIV(relevantMergedLite, bundleLinesKIV, tb)
tb.log("cluster KIV done")
# MHHCA
# lite version of relevant - just merge all shpLines in inDir
def relevantLite(inDir, relevantMerged, tb):
# merge to oneSHP
if not os.path.exists(relevantMerged):
toMerge = ""
shp_listDir = os.listdir(inDir)
for mySHP in shp_listDir:
if mySHP[-4:] == ".shp":
inSHP = inDir + mySHP
toMerge+= "%s;" %(inSHP)
# tb.log("merge")
arcpy.Merge_management(toMerge,relevantMerged)
# tb.log("calcStats")
calcStats(relevantMerged)
def export(inSHPs, inLyrs, uzemi, outMxd):
arcpy.gp.overwriteOutput = True
# Layout preparation
# path to mxd file
mxd = arcpy.mapping.MapDocument(outMxd)
print (mxd.filePath)
print (inSHPs[0])
sym_groupLayer = config.sym_groupLayer
# dataframe
df = arcpy.mapping.ListDataFrames(mxd)[0]
# target dataFrame
groupList = arcpy.mapping.ListLayers(mxd, uzemi, df)
if len(groupList) == 0:
groupLayer = arcpy.mapping.Layer(sym_groupLayer)
arcpy.mapping.AddLayer(df, groupLayer)
targetGroupLayer = arcpy.mapping.ListLayers(mxd, "jedna", df)[0]
targetGroupLayer.name = uzemi
groupList = arcpy.mapping.ListLayers(mxd, uzemi, df)
print (len(groupList))
targetGroupLayer = groupList[0]
# for each shp display it in mxd
for i in range(0,len(inSHPs),1):
shp = inSHPs[i]
# new layer from symbology
sourceLayer = arcpy.mapping.Layer(inLyrs[i])
# pridani vrstvy do mapy - bez symbologie
shp_lyr = arcpy.mapping.Layer(shp)
# print ("makeLyr " + shp_lyr
# arcpy.mapping.AddLayer(df, shp_lyr)
arcpy.mapping.AddLayerToGroup(df, targetGroupLayer, shp_lyr, "BOTTOM")
updateLayer = arcpy.mapping.ListLayers(mxd, shp_lyr, df)[0]
arcpy.mapping.UpdateLayer(df, updateLayer, sourceLayer, True)
df.extent = updateLayer.getExtent()
print ("ukladam")
mxd.save()
def createMXD(DEM, rotations):
# setting parameters form config
azimuths = config.azimuths
rotations = config.rotations
methodKIV = config.methodKIV
filterCount = config.filterCount
filterCountKIV = config.filterCountKIV
mergeWS = config.mergeWS
histWS = config.histWS[:-1] + "_%s" % config.getCellSize(DEM) + "\\"
# TODO symbology for input shp layers
sym_bL = config.red_2pt_line
sym_bL_KIV = config.blue_2pt_line
sym_rM = config.gray_04pt_line
# setup paths for DEM
SA = config.getSA(DEM)
inputMXDPath = config.getInputMXDPath(SA)
print (inputMXDPath)
inputMxd = arcpy.mapping.MapDocument(inputMXDPath)
sourceDEM = config.getSourceDEM(DEM)
outMxd = sourceDir + SA + "\\" + sourceDEM + "\\" + histWS + "compare_cT_%i_%i.mxd" % (filterCount, filterCountKIV)
inputMxd.saveACopy(outMxd)
print (outMxd)
# for each rotation in rotations
for rotation in rotations:
rotateDEM = DEM.replace("dem", "r%i" % rotation)
demWS = sourceDir + SA + "\\" + sourceDEM + "\\" + rotateDEM + "\\"
bL = demWS + mergeWS + "bundleLines.shp"
bL_KIV = demWS + mergeWS + "bundleLines_KIV%s.shp" % methodKIV
rM_KIV = demWS + mergeWS + "relevantMerged_KIV.shp"
# rM = demWS + mergeWS + "relevantMerged.shp"
# arcpy.MakeFeatureLayer_management(bL, "bL", '"count" >= %i' % filterCount)
# bL_lyr = bL[:-4]+".lyr"
# arcpy.SaveToLayerFile_management("bL",bL_lyr)
arcpy.MakeFeatureLayer_management(bL_KIV, "bL_KIV", '"count" >= %i' % filterCountKIV)
bL_KIV_lyr = bL_KIV[:-4] + ".lyr"
arcpy.SaveToLayerFile_management("bL_KIV", bL_KIV_lyr)
# toExport = [bL_lyr, bL_KIV_lyr, rM, rM_KIV]
# symbology = [sym_bL, sym_bL_KIV, sym_rM, sym_rM]
# toExport = [bL_lyr, bL_KIV_lyr, rM_KIV]
# symbology = [sym_bL, sym_bL_KIV, sym_rM]
toExport = [bL_KIV_lyr, rM_KIV]
symbology = [sym_bL_KIV, sym_rM]
export(toExport, symbology, "r%i" % rotation, outMxd)
|
State Before: 𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.207343
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.207438
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f f₀ f₁ g : E → F
f' f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
c : F
h : DifferentiableAt 𝕜 (fun y => f y + c) x
⊢ DifferentiableAt 𝕜 f x State After: no goals Tactic: simpa using h.add_const (-c)
|
(*
* Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
*
* SPDX-License-Identifier: GPL-2.0-only
*)
(*
The refinement relation between abstract and concrete states
*)
theory StateRelation
imports InvariantUpdates_H
begin
context begin interpretation Arch .
definition cte_map :: "cslot_ptr \<Rightarrow> machine_word" where
"cte_map \<equiv> \<lambda>(oref, cref). oref + (of_bl cref << cte_level_bits)"
lemmas cte_map_def' = cte_map_def[simplified cte_level_bits_def shiftl_t2n mult_ac, simplified]
definition lookup_failure_map :: "ExceptionTypes_A.lookup_failure \<Rightarrow> Fault_H.lookup_failure" where
"lookup_failure_map \<equiv> \<lambda>lf. case lf of
ExceptionTypes_A.InvalidRoot \<Rightarrow> Fault_H.InvalidRoot
| ExceptionTypes_A.MissingCapability n \<Rightarrow> Fault_H.MissingCapability n
| ExceptionTypes_A.DepthMismatch n m \<Rightarrow> Fault_H.DepthMismatch n m
| ExceptionTypes_A.GuardMismatch n g \<Rightarrow> Fault_H.GuardMismatch n (of_bl g) (length g)"
primrec arch_fault_map :: "Machine_A.RISCV64_A.arch_fault \<Rightarrow> arch_fault" where
"arch_fault_map (Machine_A.RISCV64_A.VMFault ptr msg) = VMFault ptr msg"
primrec fault_map :: "ExceptionTypes_A.fault \<Rightarrow> Fault_H.fault" where
"fault_map (ExceptionTypes_A.CapFault ref bool failure) =
Fault_H.CapFault ref bool (lookup_failure_map failure)"
| "fault_map (ExceptionTypes_A.ArchFault arch_fault) =
Fault_H.ArchFault (arch_fault_map arch_fault)"
| "fault_map (ExceptionTypes_A.UnknownSyscallException n) =
Fault_H.UnknownSyscallException n"
| "fault_map (ExceptionTypes_A.UserException x y) =
Fault_H.UserException x y"
type_synonym obj_relation_cut = "Structures_A.kernel_object \<Rightarrow> Structures_H.kernel_object \<Rightarrow> bool"
type_synonym obj_relation_cuts = "(machine_word \<times> obj_relation_cut) set"
definition vmrights_map :: "rights set \<Rightarrow> vmrights" where
"vmrights_map S \<equiv> if AllowRead \<in> S
then (if AllowWrite \<in> S then VMReadWrite else VMReadOnly)
else VMKernelOnly"
definition zbits_map :: "nat option \<Rightarrow> zombie_type" where
"zbits_map N \<equiv> case N of Some n \<Rightarrow> ZombieCNode n | None \<Rightarrow> ZombieTCB"
definition mdata_map ::
"(Machine_A.RISCV64_A.asid \<times> vspace_ref) option \<Rightarrow> (asid \<times> vspace_ref) option" where
"mdata_map = map_option (\<lambda>(asid, ref). (ucast asid, ref))"
primrec acap_relation :: "arch_cap \<Rightarrow> arch_capability \<Rightarrow> bool" where
"acap_relation (arch_cap.ASIDPoolCap p asid) c =
(c = ASIDPoolCap p (ucast asid))"
| "acap_relation (arch_cap.ASIDControlCap) c =
(c = ASIDControlCap)"
| "acap_relation (arch_cap.FrameCap p rghts sz dev data) c =
(c = FrameCap p (vmrights_map rghts) sz dev (mdata_map data))"
| "acap_relation (arch_cap.PageTableCap p data) c =
(c = PageTableCap p (mdata_map data))"
primrec cap_relation :: "cap \<Rightarrow> capability \<Rightarrow> bool" where
"cap_relation Structures_A.NullCap c =
(c = Structures_H.NullCap)"
| "cap_relation Structures_A.DomainCap c =
(c = Structures_H.DomainCap)"
| "cap_relation (Structures_A.UntypedCap dev ref n f) c =
(c = Structures_H.UntypedCap dev ref n f)"
| "cap_relation (Structures_A.EndpointCap ref b r) c =
(c = Structures_H.EndpointCap ref b (AllowSend \<in> r) (AllowRecv \<in> r) (AllowGrant \<in> r)
(AllowGrantReply \<in> r))"
| "cap_relation (Structures_A.NotificationCap ref b r) c =
(c = Structures_H.NotificationCap ref b (AllowSend \<in> r) (AllowRecv \<in> r))"
| "cap_relation (Structures_A.CNodeCap ref n L) c =
(c = Structures_H.CNodeCap ref n (of_bl L) (length L))"
| "cap_relation (Structures_A.ThreadCap ref) c =
(c = Structures_H.ThreadCap ref)"
| "cap_relation (Structures_A.ReplyCap ref master r) c =
(c = Structures_H.ReplyCap ref master (AllowGrant \<in> r))"
| "cap_relation (Structures_A.IRQControlCap) c =
(c = Structures_H.IRQControlCap)"
| "cap_relation (Structures_A.IRQHandlerCap irq) c =
(c = Structures_H.IRQHandlerCap irq)"
| "cap_relation (Structures_A.ArchObjectCap a) c =
(\<exists>a'. acap_relation a a' \<and> c = Structures_H.ArchObjectCap a')"
| "cap_relation (Structures_A.Zombie p b n) c =
(c = Structures_H.Zombie p (zbits_map b) n)"
definition cte_relation :: "cap_ref \<Rightarrow> obj_relation_cut" where
"cte_relation y \<equiv> \<lambda>ko ko'. \<exists>sz cs cte cap. ko = CNode sz cs \<and> ko' = KOCTE cte
\<and> cs y = Some cap \<and> cap_relation cap (cteCap cte)"
definition asid_pool_relation :: "(asid_low_index \<rightharpoonup> obj_ref) \<Rightarrow> asidpool \<Rightarrow> bool" where
"asid_pool_relation \<equiv> \<lambda>p p'. p = inv ASIDPool p' o ucast"
definition ntfn_relation :: "Structures_A.notification \<Rightarrow> Structures_H.notification \<Rightarrow> bool" where
"ntfn_relation \<equiv> \<lambda>ntfn ntfn'.
(case ntfn_obj ntfn of
Structures_A.IdleNtfn \<Rightarrow> ntfnObj ntfn' = Structures_H.IdleNtfn
| Structures_A.WaitingNtfn q \<Rightarrow> ntfnObj ntfn' = Structures_H.WaitingNtfn q
| Structures_A.ActiveNtfn b \<Rightarrow> ntfnObj ntfn' = Structures_H.ActiveNtfn b)
\<and> ntfn_bound_tcb ntfn = ntfnBoundTCB ntfn'"
definition ep_relation :: "Structures_A.endpoint \<Rightarrow> Structures_H.endpoint \<Rightarrow> bool" where
"ep_relation \<equiv> \<lambda>ep ep'. case ep of
Structures_A.IdleEP \<Rightarrow> ep' = Structures_H.IdleEP
| Structures_A.RecvEP q \<Rightarrow> ep' = Structures_H.RecvEP q
| Structures_A.SendEP q \<Rightarrow> ep' = Structures_H.SendEP q"
definition fault_rel_optionation :: "ExceptionTypes_A.fault option \<Rightarrow> Fault_H.fault option \<Rightarrow> bool"
where
"fault_rel_optionation \<equiv> \<lambda>f f'. f' = map_option fault_map f"
primrec thread_state_relation :: "Structures_A.thread_state \<Rightarrow> Structures_H.thread_state \<Rightarrow> bool"
where
"thread_state_relation (Structures_A.Running) ts'
= (ts' = Structures_H.Running)"
| "thread_state_relation (Structures_A.Restart) ts'
= (ts' = Structures_H.Restart)"
| "thread_state_relation (Structures_A.Inactive) ts'
= (ts' = Structures_H.Inactive)"
| "thread_state_relation (Structures_A.IdleThreadState) ts'
= (ts' = Structures_H.IdleThreadState)"
| "thread_state_relation (Structures_A.BlockedOnReply) ts'
= (ts' = Structures_H.BlockedOnReply)"
| "thread_state_relation (Structures_A.BlockedOnReceive oref sp) ts'
= (ts' = Structures_H.BlockedOnReceive oref (receiver_can_grant sp))"
| "thread_state_relation (Structures_A.BlockedOnSend oref sp) ts'
= (ts' = Structures_H.BlockedOnSend oref (sender_badge sp)
(sender_can_grant sp) (sender_can_grant_reply sp) (sender_is_call sp))"
| "thread_state_relation (Structures_A.BlockedOnNotification oref) ts'
= (ts' = Structures_H.BlockedOnNotification oref)"
definition arch_tcb_relation :: "Structures_A.arch_tcb \<Rightarrow> Structures_H.arch_tcb \<Rightarrow> bool" where
"arch_tcb_relation \<equiv> \<lambda>atcb atcb'. tcb_context atcb = atcbContext atcb'"
definition tcb_relation :: "Structures_A.tcb \<Rightarrow> Structures_H.tcb \<Rightarrow> bool" where
"tcb_relation \<equiv> \<lambda>tcb tcb'.
tcb_fault_handler tcb = to_bl (tcbFaultHandler tcb')
\<and> tcb_ipc_buffer tcb = tcbIPCBuffer tcb'
\<and> arch_tcb_relation (tcb_arch tcb) (tcbArch tcb')
\<and> thread_state_relation (tcb_state tcb) (tcbState tcb')
\<and> fault_rel_optionation (tcb_fault tcb) (tcbFault tcb')
\<and> cap_relation (tcb_ctable tcb) (cteCap (tcbCTable tcb'))
\<and> cap_relation (tcb_vtable tcb) (cteCap (tcbVTable tcb'))
\<and> cap_relation (tcb_reply tcb) (cteCap (tcbReply tcb'))
\<and> cap_relation (tcb_caller tcb) (cteCap (tcbCaller tcb'))
\<and> cap_relation (tcb_ipcframe tcb) (cteCap (tcbIPCBufferFrame tcb'))
\<and> tcb_bound_notification tcb = tcbBoundNotification tcb'
\<and> tcb_mcpriority tcb = tcbMCP tcb'"
definition
other_obj_relation :: "Structures_A.kernel_object \<Rightarrow> Structures_H.kernel_object \<Rightarrow> bool"
where
"other_obj_relation obj obj' \<equiv>
(case (obj, obj') of
(TCB tcb, KOTCB tcb') \<Rightarrow> tcb_relation tcb tcb'
| (Endpoint ep, KOEndpoint ep') \<Rightarrow> ep_relation ep ep'
| (Notification ntfn, KONotification ntfn') \<Rightarrow> ntfn_relation ntfn ntfn'
| (ArchObj (RISCV64_A.ASIDPool ap), KOArch (KOASIDPool ap')) \<Rightarrow> asid_pool_relation ap ap'
| _ \<Rightarrow> False)"
primrec pte_relation' :: "RISCV64_A.pte \<Rightarrow> RISCV64_H.pte \<Rightarrow> bool" where
"pte_relation' RISCV64_A.InvalidPTE x =
(x = RISCV64_H.InvalidPTE)"
| "pte_relation' (RISCV64_A.PageTablePTE ppn atts) x =
(x = RISCV64_H.PageTablePTE (ucast ppn) (Global \<in> atts) \<and> Execute \<notin> atts \<and> User \<notin> atts)"
| "pte_relation' (RISCV64_A.PagePTE ppn atts rghts) x =
(x = RISCV64_H.PagePTE (ucast ppn) (Global \<in> atts) (User \<in> atts) (Execute \<in> atts)
(vmrights_map rghts))"
definition pte_relation :: "pt_index \<Rightarrow> Structures_A.kernel_object \<Rightarrow> kernel_object \<Rightarrow> bool" where
"pte_relation y \<equiv> \<lambda>ko ko'. \<exists>pt pte. ko = ArchObj (PageTable pt) \<and> ko' = KOArch (KOPTE pte)
\<and> pte_relation' (pt y) pte"
primrec aobj_relation_cuts :: "RISCV64_A.arch_kernel_obj \<Rightarrow> machine_word \<Rightarrow> obj_relation_cuts" where
"aobj_relation_cuts (DataPage dev sz) x =
{ (x + (n << pageBits), \<lambda>_ obj. obj = (if dev then KOUserDataDevice else KOUserData))
| n. n < 2 ^ (pageBitsForSize sz - pageBits) }"
| "aobj_relation_cuts (RISCV64_A.ASIDPool pool) x =
{(x, other_obj_relation)}"
| "aobj_relation_cuts (PageTable pt) x =
(\<lambda>y. (x + (ucast y << pteBits), pte_relation y)) ` UNIV"
primrec obj_relation_cuts :: "Structures_A.kernel_object \<Rightarrow> machine_word \<Rightarrow> obj_relation_cuts" where
"obj_relation_cuts (CNode sz cs) x =
(if well_formed_cnode_n sz cs
then {(cte_map (x, y), cte_relation y) | y. y \<in> dom cs}
else {(x, \<bottom>\<bottom>)})"
| "obj_relation_cuts (TCB tcb) x = {(x, other_obj_relation)}"
| "obj_relation_cuts (Endpoint ep) x = {(x, other_obj_relation)}"
| "obj_relation_cuts (Notification ntfn) x = {(x, other_obj_relation)}"
| "obj_relation_cuts (ArchObj ao) x = aobj_relation_cuts ao x"
lemma obj_relation_cuts_def2:
"obj_relation_cuts ko x =
(case ko of CNode sz cs \<Rightarrow> if well_formed_cnode_n sz cs
then {(cte_map (x, y), cte_relation y) | y. y \<in> dom cs}
else {(x, \<bottom>\<bottom>)}
| ArchObj (PageTable pt) \<Rightarrow> (\<lambda>y. (x + (ucast y << pteBits), pte_relation y)) ` UNIV
| ArchObj (DataPage dev sz) \<Rightarrow>
{(x + (n << pageBits), \<lambda>_ obj. obj =(if dev then KOUserDataDevice else KOUserData))
| n . n < 2 ^ (pageBitsForSize sz - pageBits) }
| _ \<Rightarrow> {(x, other_obj_relation)})"
by (simp split: Structures_A.kernel_object.split
RISCV64_A.arch_kernel_obj.split)
lemma obj_relation_cuts_def3:
"obj_relation_cuts ko x =
(case a_type ko of
ACapTable n \<Rightarrow> {(cte_map (x, y), cte_relation y) | y. length y = n}
| AArch APageTable \<Rightarrow> (\<lambda>y. (x + (ucast y << pteBits), pte_relation y)) ` UNIV
| AArch (AUserData sz) \<Rightarrow> {(x + (n << pageBits), \<lambda>_ obj. obj = KOUserData)
| n . n < 2 ^ (pageBitsForSize sz - pageBits) }
| AArch (ADeviceData sz) \<Rightarrow> {(x + (n << pageBits), \<lambda>_ obj. obj = KOUserDataDevice )
| n . n < 2 ^ (pageBitsForSize sz - pageBits) }
| AGarbage _ \<Rightarrow> {(x, \<bottom>\<bottom>)}
| _ \<Rightarrow> {(x, other_obj_relation)})"
by (simp add: obj_relation_cuts_def2 a_type_def well_formed_cnode_n_def length_set_helper
split: Structures_A.kernel_object.split RISCV64_A.arch_kernel_obj.split)
definition is_other_obj_relation_type :: "a_type \<Rightarrow> bool" where
"is_other_obj_relation_type tp \<equiv>
case tp of
ACapTable n \<Rightarrow> False
| AArch APageTable \<Rightarrow> False
| AArch (AUserData _) \<Rightarrow> False
| AArch (ADeviceData _) \<Rightarrow> False
| AGarbage _ \<Rightarrow> False
| _ \<Rightarrow> True"
lemma is_other_obj_relation_type_CapTable:
"\<not> is_other_obj_relation_type (ACapTable n)"
by (simp add: is_other_obj_relation_type_def)
lemma is_other_obj_relation_type_UserData:
"\<not> is_other_obj_relation_type (AArch (AUserData sz))"
unfolding is_other_obj_relation_type_def by simp
lemma is_other_obj_relation_type_DeviceData:
"\<not> is_other_obj_relation_type (AArch (ADeviceData sz))"
unfolding is_other_obj_relation_type_def by simp
lemma is_other_obj_relation_type:
"is_other_obj_relation_type (a_type ko) \<Longrightarrow> obj_relation_cuts ko x = {(x, other_obj_relation)}"
by (simp add: obj_relation_cuts_def3 is_other_obj_relation_type_def
split: a_type.splits aa_type.splits)
definition pspace_dom :: "Structures_A.kheap \<Rightarrow> machine_word set" where
"pspace_dom ps \<equiv> \<Union>x\<in>dom ps. fst ` (obj_relation_cuts (the (ps x)) x)"
definition pspace_relation ::
"Structures_A.kheap \<Rightarrow> (machine_word \<rightharpoonup> Structures_H.kernel_object) \<Rightarrow> bool" where
"pspace_relation ab con \<equiv>
(pspace_dom ab = dom con) \<and>
(\<forall>x \<in> dom ab. \<forall>(y, P) \<in> obj_relation_cuts (the (ab x)) x. P (the (ab x)) (the (con y)))"
definition etcb_relation :: "etcb \<Rightarrow> Structures_H.tcb \<Rightarrow> bool" where
"etcb_relation \<equiv> \<lambda>etcb tcb'.
tcb_priority etcb = tcbPriority tcb'
\<and> tcb_time_slice etcb = tcbTimeSlice tcb'
\<and> tcb_domain etcb = tcbDomain tcb'"
definition ekheap_relation ::
"(obj_ref \<Rightarrow> etcb option) \<Rightarrow> (machine_word \<rightharpoonup> Structures_H.kernel_object) \<Rightarrow> bool" where
"ekheap_relation ab con \<equiv>
\<forall>x \<in> dom ab. \<exists>tcb'. con x = Some (KOTCB tcb') \<and> etcb_relation (the (ab x)) tcb'"
primrec sched_act_relation :: "Deterministic_A.scheduler_action \<Rightarrow> scheduler_action \<Rightarrow> bool"
where
"sched_act_relation resume_cur_thread a' = (a' = ResumeCurrentThread)" |
"sched_act_relation choose_new_thread a' = (a' = ChooseNewThread)" |
"sched_act_relation (switch_thread x) a' = (a' = SwitchToThread x)"
definition ready_queues_relation ::
"(Deterministic_A.domain \<Rightarrow> Structures_A.priority \<Rightarrow> Deterministic_A.ready_queue) \<Rightarrow>
(domain \<times> priority \<Rightarrow> KernelStateData_H.ready_queue) \<Rightarrow> bool" where
"ready_queues_relation qs qs' \<equiv> \<forall>d p. (qs d p = qs' (d, p))"
definition ghost_relation ::
"Structures_A.kheap \<Rightarrow> (machine_word \<rightharpoonup> vmpage_size) \<Rightarrow> (machine_word \<rightharpoonup> nat) \<Rightarrow> bool" where
"ghost_relation h ups cns \<equiv>
(\<forall>a sz. (\<exists>dev. h a = Some (ArchObj (DataPage dev sz))) \<longleftrightarrow> ups a = Some sz) \<and>
(\<forall>a n. (\<exists>cs. h a = Some (CNode n cs) \<and> well_formed_cnode_n n cs) \<longleftrightarrow> cns a = Some n)"
definition cdt_relation :: "(cslot_ptr \<Rightarrow> bool) \<Rightarrow> cdt \<Rightarrow> cte_heap \<Rightarrow> bool" where
"cdt_relation \<equiv> \<lambda>cte_at m m'.
\<forall>c. cte_at c \<longrightarrow> cte_map ` descendants_of c m = descendants_of' (cte_map c) m'"
definition cdt_list_relation :: "cdt_list \<Rightarrow> cdt \<Rightarrow> cte_heap \<Rightarrow> bool" where
"cdt_list_relation \<equiv> \<lambda>t m m'.
\<forall>c cap node. m' (cte_map c) = Some (CTE cap node)
\<longrightarrow> (case next_slot c t m of None \<Rightarrow> True
| Some next \<Rightarrow> mdbNext node = cte_map next)"
definition revokable_relation ::
"(cslot_ptr \<Rightarrow> bool) \<Rightarrow> (cslot_ptr \<Rightarrow> cap option) \<Rightarrow> cte_heap \<Rightarrow> bool" where
"revokable_relation revo cs m' \<equiv>
\<forall>c cap node. cs c \<noteq> None \<longrightarrow>
m' (cte_map c) = Some (CTE cap node) \<longrightarrow>
revo c = mdbRevocable node"
definition irq_state_relation :: "irq_state \<Rightarrow> irqstate \<Rightarrow> bool" where
"irq_state_relation irq irq' \<equiv> case (irq, irq') of
(irq_state.IRQInactive, irqstate.IRQInactive) \<Rightarrow> True
| (irq_state.IRQSignal, irqstate.IRQSignal) \<Rightarrow> True
| (irq_state.IRQTimer, irqstate.IRQTimer) \<Rightarrow> True
| _ \<Rightarrow> False"
definition interrupt_state_relation ::
"(irq \<Rightarrow> obj_ref) \<Rightarrow> (irq \<Rightarrow> irq_state) \<Rightarrow> interrupt_state \<Rightarrow> bool" where
"interrupt_state_relation node_map irqs is \<equiv>
(\<exists>node irqs'. is = InterruptState node irqs'
\<and> (\<forall>irq. node_map irq = node + (ucast irq << cte_level_bits))
\<and> (\<forall>irq. irq_state_relation (irqs irq) (irqs' irq)))"
definition arch_state_relation :: "(arch_state \<times> RISCV64_H.kernel_state) set" where
"arch_state_relation \<equiv> {(s, s') .
riscv_asid_table s = riscvKSASIDTable s' o ucast
\<and> riscv_global_pts s = (\<lambda>l. set (riscvKSGlobalPTs s' (size l)))
\<and> riscv_kernel_vspace s = riscvKSKernelVSpace s'}"
definition rights_mask_map :: "rights set \<Rightarrow> Types_H.cap_rights" where
"rights_mask_map \<equiv>
\<lambda>rs. CapRights (AllowWrite \<in> rs) (AllowRead \<in> rs) (AllowGrant \<in> rs) (AllowGrantReply \<in> rs)"
lemma obj_relation_cutsE:
"\<lbrakk> (y, P) \<in> obj_relation_cuts ko x; P ko ko';
\<And>sz cs z cap cte. \<lbrakk> ko = CNode sz cs; well_formed_cnode_n sz cs; y = cte_map (x, z);
ko' = KOCTE cte; cs z = Some cap; cap_relation cap (cteCap cte) \<rbrakk>
\<Longrightarrow> R;
\<And>pt (z :: pt_index) pte'. \<lbrakk> ko = ArchObj (PageTable pt); y = x + (ucast z << pteBits);
ko' = KOArch (KOPTE pte'); pte_relation' (pt z) pte' \<rbrakk>
\<Longrightarrow> R;
\<And>sz dev n. \<lbrakk> ko = ArchObj (DataPage dev sz);
ko' = (if dev then KOUserDataDevice else KOUserData);
y = x + (n << pageBits); n < 2 ^ (pageBitsForSize sz - pageBits) \<rbrakk> \<Longrightarrow> R;
\<lbrakk> y = x; other_obj_relation ko ko'; is_other_obj_relation_type (a_type ko) \<rbrakk> \<Longrightarrow> R
\<rbrakk> \<Longrightarrow> R"
by (force simp: obj_relation_cuts_def2 is_other_obj_relation_type_def a_type_def
cte_relation_def pte_relation_def
split: Structures_A.kernel_object.splits if_splits RISCV64_A.arch_kernel_obj.splits)
lemma eq_trans_helper:
"\<lbrakk> x = y; P y = Q \<rbrakk> \<Longrightarrow> P x = Q"
by simp
lemma cap_relation_case':
"cap_relation cap cap' = (case cap of
cap.ArchObjectCap arch_cap.ASIDControlCap \<Rightarrow> cap_relation cap cap'
| _ \<Rightarrow> cap_relation cap cap')"
by (simp split: cap.split arch_cap.split)
schematic_goal cap_relation_case:
"cap_relation cap cap' = ?P"
apply (subst cap_relation_case')
apply (clarsimp cong: cap.case_cong arch_cap.case_cong)
apply (rule refl)
done
lemmas cap_relation_split =
eq_trans_helper [where P=P, OF cap_relation_case cap.split[where P=P]] for P
lemmas cap_relation_split_asm =
eq_trans_helper [where P=P, OF cap_relation_case cap.split_asm[where P=P]] for P
text \<open>
Relations on other data types that aren't stored but used as intermediate values
in the specs.
\<close>
primrec message_info_map :: "Structures_A.message_info \<Rightarrow> Types_H.message_info" where
"message_info_map (Structures_A.MI a b c d) = (Types_H.MI a b c d)"
lemma mi_map_label[simp]: "msgLabel (message_info_map mi) = mi_label mi"
by (cases mi, simp)
primrec syscall_error_map :: "ExceptionTypes_A.syscall_error \<Rightarrow> Fault_H.syscall_error" where
"syscall_error_map (ExceptionTypes_A.InvalidArgument n) = Fault_H.InvalidArgument n"
| "syscall_error_map (ExceptionTypes_A.InvalidCapability n) = (Fault_H.InvalidCapability n)"
| "syscall_error_map ExceptionTypes_A.IllegalOperation = Fault_H.IllegalOperation"
| "syscall_error_map (ExceptionTypes_A.RangeError n m) = Fault_H.RangeError n m"
| "syscall_error_map ExceptionTypes_A.AlignmentError = Fault_H.AlignmentError"
| "syscall_error_map (ExceptionTypes_A.FailedLookup b lf) = Fault_H.FailedLookup b (lookup_failure_map lf)"
| "syscall_error_map ExceptionTypes_A.TruncatedMessage = Fault_H.TruncatedMessage"
| "syscall_error_map ExceptionTypes_A.DeleteFirst = Fault_H.DeleteFirst"
| "syscall_error_map ExceptionTypes_A.RevokeFirst = Fault_H.RevokeFirst"
| "syscall_error_map (ExceptionTypes_A.NotEnoughMemory n) = Fault_H.syscall_error.NotEnoughMemory n"
definition APIType_map :: "Structures_A.apiobject_type \<Rightarrow> RISCV64_H.object_type" where
"APIType_map ty \<equiv>
case ty of
Structures_A.Untyped \<Rightarrow> APIObjectType ArchTypes_H.Untyped
| Structures_A.TCBObject \<Rightarrow> APIObjectType ArchTypes_H.TCBObject
| Structures_A.EndpointObject \<Rightarrow> APIObjectType ArchTypes_H.EndpointObject
| Structures_A.NotificationObject \<Rightarrow> APIObjectType ArchTypes_H.NotificationObject
| Structures_A.CapTableObject \<Rightarrow> APIObjectType ArchTypes_H.CapTableObject
| ArchObject ao \<Rightarrow> (case ao of
SmallPageObj \<Rightarrow> SmallPageObject
| LargePageObj \<Rightarrow> LargePageObject
| HugePageObj \<Rightarrow> HugePageObject
| PageTableObj \<Rightarrow> PageTableObject)"
definition state_relation :: "(det_state \<times> kernel_state) set" where
"state_relation \<equiv> {(s, s').
pspace_relation (kheap s) (ksPSpace s')
\<and> ekheap_relation (ekheap s) (ksPSpace s')
\<and> sched_act_relation (scheduler_action s) (ksSchedulerAction s')
\<and> ready_queues_relation (ready_queues s) (ksReadyQueues s')
\<and> ghost_relation (kheap s) (gsUserPages s') (gsCNodes s')
\<and> cdt_relation (swp cte_at s) (cdt s) (ctes_of s')
\<and> cdt_list_relation (cdt_list s) (cdt s) (ctes_of s')
\<and> revokable_relation (is_original_cap s) (null_filter (caps_of_state s)) (ctes_of s')
\<and> (arch_state s, ksArchState s') \<in> arch_state_relation
\<and> interrupt_state_relation (interrupt_irq_node s) (interrupt_states s) (ksInterruptState s')
\<and> (cur_thread s = ksCurThread s')
\<and> (idle_thread s = ksIdleThread s')
\<and> (machine_state s = ksMachineState s')
\<and> (work_units_completed s = ksWorkUnitsCompleted s')
\<and> (domain_index s = ksDomScheduleIdx s')
\<and> (domain_list s = ksDomSchedule s')
\<and> (cur_domain s = ksCurDomain s')
\<and> (domain_time s = ksDomainTime s')}"
text \<open>Rules for using states in the relation.\<close>
lemma curthread_relation:
"(a, b) \<in> state_relation \<Longrightarrow> ksCurThread b = cur_thread a"
by (simp add: state_relation_def)
lemma state_relation_pspace_relation[elim!]:
"(s,s') \<in> state_relation \<Longrightarrow> pspace_relation (kheap s) (ksPSpace s')"
by (simp add: state_relation_def)
lemma state_relation_ekheap_relation[elim!]:
"(s,s') \<in> state_relation \<Longrightarrow> ekheap_relation (ekheap s) (ksPSpace s')"
by (simp add: state_relation_def)
lemma state_relationD:
"(s, s') \<in> state_relation \<Longrightarrow>
pspace_relation (kheap s) (ksPSpace s') \<and>
ekheap_relation (ekheap s) (ksPSpace s') \<and>
sched_act_relation (scheduler_action s) (ksSchedulerAction s') \<and>
ready_queues_relation (ready_queues s) (ksReadyQueues s') \<and>
ghost_relation (kheap s) (gsUserPages s') (gsCNodes s') \<and>
cdt_relation (swp cte_at s) (cdt s) (ctes_of s') \<and>
cdt_list_relation (cdt_list s) (cdt s) (ctes_of s') \<and>
revokable_relation (is_original_cap s) (null_filter (caps_of_state s)) (ctes_of s') \<and>
(arch_state s, ksArchState s') \<in> arch_state_relation \<and>
interrupt_state_relation (interrupt_irq_node s) (interrupt_states s) (ksInterruptState s') \<and>
cur_thread s = ksCurThread s' \<and>
idle_thread s = ksIdleThread s' \<and>
machine_state s = ksMachineState s' \<and>
work_units_completed s = ksWorkUnitsCompleted s' \<and>
domain_index s = ksDomScheduleIdx s' \<and>
domain_list s = ksDomSchedule s' \<and>
cur_domain s = ksCurDomain s' \<and>
domain_time s = ksDomainTime s'"
unfolding state_relation_def by simp
lemma state_relationE [elim?]:
assumes sr: "(s, s') \<in> state_relation"
and rl: "\<lbrakk> pspace_relation (kheap s) (ksPSpace s');
ekheap_relation (ekheap s) (ksPSpace s');
sched_act_relation (scheduler_action s) (ksSchedulerAction s');
ready_queues_relation (ready_queues s) (ksReadyQueues s');
ghost_relation (kheap s) (gsUserPages s') (gsCNodes s');
cdt_relation (swp cte_at s) (cdt s) (ctes_of s') \<and>
revokable_relation (is_original_cap s) (null_filter (caps_of_state s)) (ctes_of s');
cdt_list_relation (cdt_list s) (cdt s) (ctes_of s');
(arch_state s, ksArchState s') \<in> arch_state_relation;
interrupt_state_relation (interrupt_irq_node s) (interrupt_states s) (ksInterruptState s');
cur_thread s = ksCurThread s';
idle_thread s = ksIdleThread s';
machine_state s = ksMachineState s';
work_units_completed s = ksWorkUnitsCompleted s';
domain_index s = ksDomScheduleIdx s';
domain_list s = ksDomSchedule s';
cur_domain s = ksCurDomain s';
domain_time s = ksDomainTime s' \<rbrakk> \<Longrightarrow> R"
shows "R"
using sr by (blast intro!: rl dest: state_relationD)
lemmas isCap_defs =
isZombie_def isArchObjectCap_def
isThreadCap_def isCNodeCap_def isNotificationCap_def
isEndpointCap_def isUntypedCap_def isNullCap_def
isIRQHandlerCap_def isIRQControlCap_def isReplyCap_def
isFrameCap_def isPageTableCap_def
isASIDControlCap_def isASIDPoolCap_def
isDomainCap_def isArchFrameCap_def
lemma isCNodeCap_cap_map[simp]:
"cap_relation c c' \<Longrightarrow> isCNodeCap c' = is_cnode_cap c"
by (cases c) (auto simp: isCap_defs split: sum.splits)
lemma sts_rel_idle :
"thread_state_relation st IdleThreadState = (st = Structures_A.IdleThreadState)"
by (cases st, auto)
lemma pspace_relation_absD:
"\<lbrakk> ab x = Some y; pspace_relation ab con \<rbrakk>
\<Longrightarrow> \<forall>(x', P) \<in> obj_relation_cuts y x. \<exists>z. con x' = Some z \<and> P y z"
apply (clarsimp simp: pspace_relation_def)
apply (drule bspec, erule domI)
apply simp
apply (drule(1) bspec)
apply (subgoal_tac "a \<in> pspace_dom ab", clarsimp)
apply (simp (no_asm) add: pspace_dom_def)
apply (fastforce simp: image_def intro: rev_bexI)
done
lemma ekheap_relation_absD:
"\<lbrakk> ab x = Some y; ekheap_relation ab con \<rbrakk> \<Longrightarrow>
\<exists>tcb'. con x = Some (KOTCB tcb') \<and> etcb_relation y tcb'"
by (force simp add: ekheap_relation_def)
lemma in_related_pspace_dom:
"\<lbrakk> s' x = Some y; pspace_relation s s' \<rbrakk> \<Longrightarrow> x \<in> pspace_dom s"
by (clarsimp simp add: pspace_relation_def)
lemma pspace_dom_revE:
"\<lbrakk> x \<in> pspace_dom ps; \<And>ko y P. \<lbrakk> ps y = Some ko; (x, P) \<in> obj_relation_cuts ko y \<rbrakk> \<Longrightarrow> R \<rbrakk> \<Longrightarrow> R"
by (clarsimp simp add: pspace_dom_def)
lemma pspace_dom_relatedE:
"\<lbrakk> s' x = Some ko'; pspace_relation s s';
\<And>y ko P. \<lbrakk> s y = Some ko; (x, P) \<in> obj_relation_cuts ko y; P ko ko' \<rbrakk> \<Longrightarrow> R \<rbrakk> \<Longrightarrow> R"
apply (rule pspace_dom_revE [OF in_related_pspace_dom]; assumption?)
apply (fastforce dest: pspace_relation_absD)
done
lemma ghost_relation_typ_at:
"ghost_relation (kheap s) ups cns \<equiv>
(\<forall>a sz. data_at sz a s = (ups a = Some sz)) \<and>
(\<forall>a n. typ_at (ACapTable n) a s = (cns a = Some n))"
apply (rule eq_reflection)
apply (clarsimp simp: ghost_relation_def typ_at_eq_kheap_obj data_at_def)
apply (intro conjI impI iffI allI; force)
done
end
end
|
/* multifit_nlinear/gsl_multifit_nlinear.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
* Copyright (C) 2015, 2016 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MULTIFIT_NLINEAR_H__
#define __GSL_MULTIFIT_NLINEAR_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_permutation.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef enum
{
GSL_MULTIFIT_NLINEAR_FWDIFF,
GSL_MULTIFIT_NLINEAR_CTRDIFF
} gsl_multifit_nlinear_fdtype;
/* Definition of vector-valued functions and gradient with parameters
based on gsl_vector */
typedef struct
{
int (* f) (const gsl_vector * x, void * params, gsl_vector * f);
int (* df) (const gsl_vector * x, void * params, gsl_matrix * df);
int (* fvv) (const gsl_vector * x, const gsl_vector * v, void * params,
gsl_vector * fvv);
size_t n; /* number of functions */
size_t p; /* number of independent variables */
void * params; /* user parameters */
size_t nevalf; /* number of function evaluations */
size_t nevaldf; /* number of Jacobian evaluations */
size_t nevalfvv; /* number of fvv evaluations */
} gsl_multifit_nlinear_fdf;
/* trust region subproblem method */
typedef struct
{
const char *name;
void * (*alloc) (const void * params, const size_t n, const size_t p);
int (*init) (const void * vtrust_state, void * vstate);
int (*preloop) (const void * vtrust_state, void * vstate);
int (*step) (const void * vtrust_state, const double delta,
gsl_vector * dx, void * vstate);
int (*preduction) (const void * vtrust_state, const gsl_vector * dx,
double * pred, void * vstate);
void (*free) (void * vstate);
} gsl_multifit_nlinear_trs;
/* scaling matrix specification */
typedef struct
{
const char *name;
int (*init) (const gsl_matrix * J, gsl_vector * diag);
int (*update) (const gsl_matrix * J, gsl_vector * diag);
} gsl_multifit_nlinear_scale;
/*
* linear least squares solvers - there are three steps to
* solving a least squares problem using a trust region
* method:
*
* 1. init: called once per iteration when a new Jacobian matrix
* is computed; perform factorization of Jacobian (qr,svd)
* or form normal equations matrix (cholesky)
* 2. presolve: called each time a new LM parameter value mu is available;
* used for cholesky method in order to factor
* the (J^T J + mu D^T D) matrix
* 3. solve: solve the least square system for a given rhs
*/
typedef struct
{
const char *name;
void * (*alloc) (const size_t n, const size_t p);
int (*init) (const void * vtrust_state, void * vstate);
int (*presolve) (const double mu, const void * vtrust_state, void * vstate);
int (*solve) (const gsl_vector * f, gsl_vector * x,
const void * vtrust_state, void * vstate);
int (*rcond) (double * rcond, void * vstate);
void (*free) (void * vstate);
} gsl_multifit_nlinear_solver;
/* tunable parameters */
typedef struct
{
const gsl_multifit_nlinear_trs *trs; /* trust region subproblem method */
const gsl_multifit_nlinear_scale *scale; /* scaling method */
const gsl_multifit_nlinear_solver *solver; /* solver method */
gsl_multifit_nlinear_fdtype fdtype; /* finite difference method */
double factor_up; /* factor for increasing trust radius */
double factor_down; /* factor for decreasing trust radius */
double avmax; /* max allowed |a|/|v| */
double h_df; /* step size for finite difference Jacobian */
double h_fvv; /* step size for finite difference fvv */
} gsl_multifit_nlinear_parameters;
typedef struct
{
const char *name;
void * (*alloc) (const gsl_multifit_nlinear_parameters * params,
const size_t n, const size_t p);
int (*init) (void * state, const gsl_vector * wts,
gsl_multifit_nlinear_fdf * fdf, const gsl_vector * x,
gsl_vector * f, gsl_matrix * J, gsl_vector * g);
int (*iterate) (void * state, const gsl_vector * wts,
gsl_multifit_nlinear_fdf * fdf, gsl_vector * x,
gsl_vector * f, gsl_matrix * J, gsl_vector * g,
gsl_vector * dx);
int (*rcond) (double * rcond, void * state);
double (*avratio) (void * state);
void (*free) (void * state);
} gsl_multifit_nlinear_type;
/* current state passed to low-level trust region algorithms */
typedef struct
{
const gsl_vector * x; /* parameter values x */
const gsl_vector * f; /* residual vector f(x) */
const gsl_vector * g; /* gradient J^T f */
const gsl_matrix * J; /* Jacobian J(x) */
const gsl_vector * diag; /* scaling matrix D */
const gsl_vector * sqrt_wts; /* sqrt(diag(W)) or NULL for unweighted */
const double *mu; /* LM parameter */
const gsl_multifit_nlinear_parameters * params;
void *solver_state; /* workspace for linear least squares solver */
gsl_multifit_nlinear_fdf * fdf;
double *avratio; /* |a| / |v| */
} gsl_multifit_nlinear_trust_state;
typedef struct
{
const gsl_multifit_nlinear_type * type;
gsl_multifit_nlinear_fdf * fdf ;
gsl_vector * x; /* parameter values x */
gsl_vector * f; /* residual vector f(x) */
gsl_vector * dx; /* step dx */
gsl_vector * g; /* gradient J^T f */
gsl_matrix * J; /* Jacobian J(x) */
gsl_vector * sqrt_wts_work; /* sqrt(W) */
gsl_vector * sqrt_wts; /* ptr to sqrt_wts_work, or NULL if not using weights */
size_t niter; /* number of iterations performed */
gsl_multifit_nlinear_parameters params;
void *state;
} gsl_multifit_nlinear_workspace;
gsl_multifit_nlinear_workspace *
gsl_multifit_nlinear_alloc (const gsl_multifit_nlinear_type * T,
const gsl_multifit_nlinear_parameters * params,
size_t n, size_t p);
void gsl_multifit_nlinear_free (gsl_multifit_nlinear_workspace * w);
gsl_multifit_nlinear_parameters gsl_multifit_nlinear_default_parameters(void);
int
gsl_multifit_nlinear_init (const gsl_vector * x,
gsl_multifit_nlinear_fdf * fdf,
gsl_multifit_nlinear_workspace * w);
int gsl_multifit_nlinear_winit (const gsl_vector * x,
const gsl_vector * wts,
gsl_multifit_nlinear_fdf * fdf,
gsl_multifit_nlinear_workspace * w);
int
gsl_multifit_nlinear_iterate (gsl_multifit_nlinear_workspace * w);
double
gsl_multifit_nlinear_avratio (const gsl_multifit_nlinear_workspace * w);
int
gsl_multifit_nlinear_driver (const size_t maxiter,
const double xtol,
const double gtol,
const double ftol,
void (*callback)(const size_t iter, void *params,
const gsl_multifit_nlinear_workspace *w),
void *callback_params,
int *info,
gsl_multifit_nlinear_workspace * w);
gsl_matrix *
gsl_multifit_nlinear_jac (const gsl_multifit_nlinear_workspace * w);
const char *
gsl_multifit_nlinear_name (const gsl_multifit_nlinear_workspace * w);
gsl_vector *
gsl_multifit_nlinear_position (const gsl_multifit_nlinear_workspace * w);
gsl_vector *
gsl_multifit_nlinear_residual (const gsl_multifit_nlinear_workspace * w);
size_t
gsl_multifit_nlinear_niter (const gsl_multifit_nlinear_workspace * w);
int
gsl_multifit_nlinear_rcond (double *rcond, const gsl_multifit_nlinear_workspace * w);
const char *
gsl_multifit_nlinear_trs_name (const gsl_multifit_nlinear_workspace * w);
int gsl_multifit_nlinear_eval_f(gsl_multifit_nlinear_fdf *fdf,
const gsl_vector *x,
const gsl_vector *swts,
gsl_vector *y);
int gsl_multifit_nlinear_eval_df(const gsl_vector *x,
const gsl_vector *f,
const gsl_vector *swts,
const double h,
const gsl_multifit_nlinear_fdtype fdtype,
gsl_multifit_nlinear_fdf *fdf,
gsl_matrix *df, gsl_vector *work);
int
gsl_multifit_nlinear_eval_fvv(const double h,
const gsl_vector *x,
const gsl_vector *v,
const gsl_vector *f,
const gsl_matrix *J,
const gsl_vector *swts,
gsl_multifit_nlinear_fdf *fdf,
gsl_vector *yvv, gsl_vector *work);
/* covar.c */
int
gsl_multifit_nlinear_covar (const gsl_matrix * J, const double epsrel,
gsl_matrix * covar);
/* convergence.c */
int
gsl_multifit_nlinear_test (const double xtol, const double gtol,
const double ftol, int *info,
const gsl_multifit_nlinear_workspace * w);
/* fdjac.c */
int
gsl_multifit_nlinear_df(const double h, const gsl_multifit_nlinear_fdtype fdtype,
const gsl_vector *x, const gsl_vector *wts,
gsl_multifit_nlinear_fdf *fdf,
const gsl_vector *f, gsl_matrix *J, gsl_vector *work);
/* fdfvv.c */
int
gsl_multifit_nlinear_fdfvv(const double h, const gsl_vector *x, const gsl_vector *v,
const gsl_vector *f, const gsl_matrix *J,
const gsl_vector *swts, gsl_multifit_nlinear_fdf *fdf,
gsl_vector *fvv, gsl_vector *work);
/* top-level algorithms */
GSL_VAR const gsl_multifit_nlinear_type * gsl_multifit_nlinear_trust;
/* trust region subproblem methods */
GSL_VAR const gsl_multifit_nlinear_trs * gsl_multifit_nlinear_trs_lm;
GSL_VAR const gsl_multifit_nlinear_trs * gsl_multifit_nlinear_trs_lmaccel;
GSL_VAR const gsl_multifit_nlinear_trs * gsl_multifit_nlinear_trs_dogleg;
GSL_VAR const gsl_multifit_nlinear_trs * gsl_multifit_nlinear_trs_ddogleg;
GSL_VAR const gsl_multifit_nlinear_trs * gsl_multifit_nlinear_trs_subspace2D;
/* scaling matrix strategies */
GSL_VAR const gsl_multifit_nlinear_scale * gsl_multifit_nlinear_scale_levenberg;
GSL_VAR const gsl_multifit_nlinear_scale * gsl_multifit_nlinear_scale_marquardt;
GSL_VAR const gsl_multifit_nlinear_scale * gsl_multifit_nlinear_scale_more;
/* linear solvers */
GSL_VAR const gsl_multifit_nlinear_solver * gsl_multifit_nlinear_solver_cholesky;
GSL_VAR const gsl_multifit_nlinear_solver * gsl_multifit_nlinear_solver_qr;
GSL_VAR const gsl_multifit_nlinear_solver * gsl_multifit_nlinear_solver_svd;
__END_DECLS
#endif /* __GSL_MULTIFIT_NLINEAR_H__ */
|
Require Import VST.concurrency.conclib.
Require Import VST.floyd.proofauto.
Require Import VST.atomics.general_locks.
Require Import Coq.Sets.Ensembles.
Require Import bst.puretree.
Require Import bst.bst_template_giveup.
Require Import bst.giveup_lib.
Require Import bst.giveup_traverse.
Require Import VST.atomics.verif_lock_atomic.
Require Import VST.floyd.library.
(* Write insert_spec following the template style.
We need to write some specs of helper functions: insertOp, traverse and findnext
1) insert_spec:
∀ t. <bst_ref p | bst t> insert2 (treebox t, int x, void *value)
<t'. bst_ref p | bst t' ∧ insert t k v = t' >
2) insertOp_spec:
{N /\ x \in range} insertOp(pn *pn, int x, void *value)
{t'. N ∧ t' = (<[x:=k]> t) }
3) traverse_spec:
< ... | bst t> traverse(pn *pn, int x, void *value)
<v. bst t /\ lock_inv >
4) findnext_spec:
{x \in range /\ ...} findNext(pn *pn, int x, void *value)
{v. ((v = 1 /\ ....) \/ (v = 0 /\ ...)) /\ ... } *)
(* Spec of insertOp function *)
Definition insertOp_spec :=
DECLARE _insertOp
WITH b: val, sh: share, x: Z, v: val, p: val, tp: val, min: Z, max: Z, gv: globals
PRE [ tptr t_struct_pn, tint, tptr tvoid ]
PROP (writable_share sh; repable_signed min; repable_signed max; repable_signed x;
is_pointer_or_null v )
PARAMS (b; Vint (Int.repr x); v)
GLOBALS (gv)
SEP (mem_mgr gv;
data_at sh (t_struct_pn) (p, p) b;
field_at Ews t_struct_tree_t (DOT _t) tp p;
field_at Ews t_struct_tree_t (DOT _min) (Vint (Int.repr min)) p;
field_at Ews t_struct_tree_t (DOT _max) (Vint (Int.repr max)) p )
POST[ tvoid ]
EX (pnt p1' p2' : val) (lock1 lock2 : val),
PROP (pnt <> nullval)
LOCAL ()
SEP (mem_mgr gv;
data_at sh t_struct_pn (p, p) b;
field_at Ews t_struct_tree_t (DOT _t) pnt p;
malloc_token Ews t_struct_tree pnt;
malloc_token Ews t_struct_tree_t p1'; malloc_token Ews t_struct_tree_t p2';
atomic_int_at Ews (vint 0) lock1; atomic_int_at Ews (vint 0) lock2;
data_at Ews t_struct_tree (vint x, (v, (p1', p2'))) pnt;
data_at Ews t_struct_tree_t (Vlong (Int64.repr 0), (lock2, (vint x, vint max))) p2';
data_at Ews t_struct_tree_t (Vlong (Int64.repr 0), (lock1, (vint min, vint x))) p1';
field_at Ews t_struct_tree_t (DOT _min) (vint min) p;
field_at Ews t_struct_tree_t (DOT _max) (vint max) p).
(* insert spec *)
Program Definition insert_spec :=
DECLARE _insert
ATOMIC TYPE (rmaps.ConstType (val * share * val * Z * val * globals * gname * gname))
OBJ M INVS ∅
WITH b, sh, lock, x, v, gv, g, g_root
PRE [ tptr (tptr t_struct_tree_t), tint, tptr tvoid ]
PROP (writable_share sh; and (Z.le Int.min_signed x) (Z.le x Int.max_signed); is_pointer_or_null v)
PARAMS (b; Vint (Int.repr x); v) GLOBALS (gv)
SEP (mem_mgr gv; nodebox_rep g g_root sh lock b) | (tree_rep g g_root M)
POST[ tvoid ]
PROP ()
LOCAL ()
SEP (mem_mgr gv; nodebox_rep g g_root sh lock b) | (tree_rep g g_root (<[x:=v]>M)).
Definition spawn_spec := DECLARE _spawn spawn_spec.
Definition Gprog : funspecs :=
ltac:(with_library prog [acquire_spec; release_spec; makelock_spec;
surely_malloc_spec; inrange_spec; insertOp_spec; insert_spec;
traverse_spec; findnext_spec; treebox_new_spec]).
(* Proving insertOp satisfies spec *)
Lemma insertOp: semax_body Vprog Gprog f_insertOp insertOp_spec.
Proof.
start_function.
forward_call (t_struct_tree_t, gv).
Intros p1'.
forward_call (t_struct_tree_t, gv).
Intros p2'.
forward.
assert_PROP (field_compatible t_struct_tree_t [] p1') by entailer!.
forward.
assert_PROP (field_compatible t_struct_tree_t [] p2') by entailer!.
forward_call (gv).
Intros lock1.
forward.
sep_apply atomic_int_isptr.
Intros.
forward_call release_nonatomic (lock1).
forward_call (gv).
Intros lock2.
forward.
Intros.
forward_call release_nonatomic (lock2).
(* make lock invariant *)
forward_call (t_struct_tree, gv).
Intros pnt.
forward. forward. forward. forward. forward. forward. forward.
forward. forward. forward. forward. forward. forward. forward.
forward. forward. forward. forward. forward. forward. forward. forward.
Exists pnt p1' p2' lock1 lock2.
entailer !.
Qed.
(* Proving insert function satisfies spec *)
Lemma body_insert: semax_body Vprog Gprog f_insert insert_spec.
Proof.
start_function.
unfold nodebox_rep.
Intros np.
forward_call (t_struct_pn, gv).
Intros nb.
Intros lsh.
forward.
forward.
sep_apply in_tree_duplicate.
set (AS := atomic_shift _ _ _ _ _).
set Q1:= fun (b : ( bool * (val * (share * (gname * node_info))))%type) =>
if b.1 then AS else AS.
(* traverse(pn, x, value) *)
forward_call (nb, np, lock, x, v, gv, g, g_root, Q1).
{
Exists Vundef. entailer !.
iIntros "(((H1 & H2) & H3) & H4)". iCombine "H2 H1 H3 H4" as "H".
iVST.
apply sepcon_derives; [| cancel_frame].
iIntros "AU".
unfold atomic_shift; iAuIntro; unfold atomic_acc; simpl.
iMod "AU" as (m) "[Hm HClose]".
iModIntro. iExists _. iFrame.
iSplit; iFrame.
iIntros "H1".
iSpecialize ("HClose" with "H1"). auto.
iDestruct "HClose" as "[HClose _]".
iIntros (pt) "[H _]".
iMod ("HClose" with "H") as "H".
iModIntro.
unfold Q1.
destruct (decide (pt.1 = true)). { rewrite e; iFrame. }
{ apply not_true_is_false in n; rewrite n; iFrame. }
}
Intros pt.
destruct pt as (fl & (p & (gsh & (g_in & r)))).
simpl in H6.
destruct fl.
destruct H6 as (HGh & HP).
- unfold Q1.
forward_if(
PROP ( )
LOCAL (temp _t'2 Vtrue; temp _t'7 np; temp _pn__2 nb; gvars gv; temp _t b; temp _x (vint x); temp _value v)
SEP (AS * mem_mgr gv * EX pt: (val * (val * (val * (val * val)))),
!!(pt.1 <> nullval /\ (repable_signed (number2Z r.1.2.1)
∧ repable_signed (number2Z r.1.2.2) ∧ is_pointer_or_null r.1.1.2)) &&
data_at Ews t_struct_pn (p, p) nb * in_tree g g_root np lock *
field_at Ews t_struct_tree_t (DOT _t) (pt.1) p * malloc_token Ews t_struct_tree pt.1 *
malloc_token Ews t_struct_tree_t pt.2.1 * malloc_token Ews t_struct_tree_t pt.2.2.1 *
atomic_int_at Ews (vint 0) pt.2.2.2.1 * atomic_int_at Ews (vint 0) pt.2.2.2.2 *
data_at Ews t_struct_tree (vint x, (v, (pt.2.1, pt.2.2.1))) pt.1 *
data_at Ews t_struct_tree_t (Vlong (Int64.repr 0), (pt.2.2.2.2, (vint x, vint (number2Z r.1.2.2)))) pt.2.2.1 *
data_at Ews t_struct_tree_t (Vlong (Int64.repr 0), (pt.2.2.2.1, (vint (number2Z r.1.2.1), vint x))) pt.2.1 *
field_at Ews t_struct_tree_t (DOT _min) (vint (number2Z r.1.2.1)) p *
field_at Ews t_struct_tree_t (DOT _max) (vint (number2Z r.1.2.2)) p *
in_tree g g_in p r.1.1.2 * my_half g_in Tsh r * malloc_token Ews t_struct_tree_t p *
in_tree g g_in p r.1.1.2 * tree_rep_R r.1.1.1 r.1.2 r.2 g * malloc_token Ews t_struct_pn nb *
data_at sh (tptr t_struct_tree_t) np b *
field_at lsh t_struct_tree_t (DOT _lock) lock np)).
+ pose proof (Int.one_not_zero); easy.
+ simpl.
forward_call(nb, Ews, x, v, p, r.1.1.1, (number2Z r.1.2.1), (number2Z r.1.2.2), gv).
{ unfold node_lock_inv_pred, node_rep. entailer !. }
Intros pt.
destruct pt as ((((pnt & p1) & p2) & lock1) & lock2).
Exists (pnt, (p1, (p2, (lock1, lock2)))).
entailer !. apply derives_refl.
+ Intros pt.
destruct pt as (pnt & (p1 & (p2 & (lock1 & lock2)))).
simpl.
forward.
gather_SEP AS (in_tree g g_in p _).
viewshift_SEP 0 (AS * (in_tree g g_in p r.1.1.2) * (EX lsh, !!(readable_share lsh) &&
field_at lsh t_struct_tree_t (DOT _lock) r.1.1.2 p)).
{ go_lower. apply lock_alloc. }
assert_PROP (field_compatible t_struct_tree_t [] p1) by entailer !.
assert_PROP (field_compatible t_struct_tree_t [] p2) by entailer !.
assert_PROP(is_pointer_or_null lock1) by entailer !.
assert_PROP(is_pointer_or_null lock2) by entailer !.
Intros lsh1.
forward.
forward_call (r.1.1.2, Q).
{
iIntros "(((((((((((((((((((((((AU & H1) & H2) & H3) & H4) & H5) & H6) & H7) & H8) & H9) & G1) & G2) & G3) & G4) & G5) & G6) & G7) & G8) & G9) & K1) & K2) & K3) & K4) & K5)".
iCombine "AU H1 H2 H6 G8 G9 H7 G6 G7 G3" as "HH1".
iCombine "G1 G2 H8 H9 G4 G5" as "HH2".
iCombine "HH1 HH2" as "HH3".
iVST.
rewrite <- 7sepcon_assoc; rewrite <- sepcon_comm.
apply sepcon_derives; [| cancel_frame].
unfold atomic_shift; iIntros "((AU & (#H1 & (H2 & (H3 & (H4 & (H5 & (H6 & (H7 & (H8 & H9))))))))) & (G1 & (G2 & (G3 & (G4 & (G5 & G6))))))"; iAuIntro; unfold atomic_acc; simpl.
iMod "AU" as (m) "[Hm HClose]".
iModIntro.
iPoseProof (tree_rep_insert _ g g_root g_in p r.1.1.2 with "[$Hm $H1]") as "InvLock".
iDestruct "InvLock" as (R O) "((K1 & K2) & K3)".
iDestruct "K2" as (lsh2) "(% & (K2 & KInv))".
iDestruct "KInv" as (bl) "(KAt & KInv)".
destruct bl.
++ iExists (). iFrame "KAt".
iSplit.
{
iIntros "H".
iFrame.
iAssert (ltree g g_in p r.1.1.2 (node_lock_inv_pred g p g_in (R, Some O)))
with "[H K2]" as "HInv".
{ iExists _. iSplit. done. iFrame "K2". iExists true. iFrame. }
iSpecialize ("K3" with "[$HInv $K1]").
iDestruct "K3" as "(K3 & _)".
iSpecialize ("HClose" with "K3").
iFrame.
}
iIntros (_) "(H & _)".
iDestruct "K3" as "[[> K3 _] _]".
iDestruct "K3" as (g1 g2) "((((K4 & K5) & #K6) & #K7) & K8)".
instantiate (1 := lock2). instantiate (1 := p2).
instantiate (1 := lock1). instantiate (1 := p1).
iPoseProof (public_update g_in r (R, Some O) (pnt, r.1.1.2, r.1.2, Some (Some (x, v, g1, g2))) with "[$H4 $K1]") as "(% & > (H4 & K1))".
destruct r.
inversion H16; subst; simpl.
destruct H15 as (Hf & Hrs).
(* join lsh1 with lsh2 = Lsh *)
iPoseProof (lock_join with "[$H2 $K2]") as "K2"; try iSplit; auto.
iDestruct "K2" as (Lsh) "(% & K2)".
iAssert(ltree g g_in p g0.1.2
(node_lock_inv_pred g p g_in (pnt, g0.1.2, g0.2, Some (Some (x, v, g1, g2)))))
with "[H H3 H4 H5 H6 H7 H8 H9 K2 ]" as "LT".
{
iApply (non_null_ltree g g_in p _ Lsh pnt p1 p2 lock1 lock2 g1 g2); eauto.
iFrame. iFrame "H1 K6 K7". }
iAssert(ltree g g1 p1 lock1
(node_lock_inv_pred g p1 g1 (nullval, lock1, (g0.2.1, Finite_Integer x), Some None)))
with "[K4 G1 G3 G6]" as "LT1".
{ iApply (null_ltree g g1 p1 lock1 _); eauto; iFrame; iFrame "K6". }
iAssert(ltree g g2 p2 lock2
(node_lock_inv_pred g p2 g2 (nullval, lock2, (Finite_Integer x, g0.2.2), Some None)))
with "[K5 G2 G4 G5]" as "LT2".
{ iApply (null_ltree g g2 p2 lock2 _); eauto; iFrame; iFrame "K7". }
iSpecialize ("K8" with "[$K1 $LT $LT1 $LT2]").
iPureIntro. repeat (split; auto; [inversion HGh]); auto.
iDestruct "K8" as "(((K8 & _) & _) & _)".
iDestruct "HClose" as "[_ HClose]".
iSpecialize ("HClose" $! ()).
iMod ("HClose" with "[$K8]") as "HClose". auto.
++ unfold node_lock_inv_pred at 1.
iDestruct "KInv" as "(? & KInv)".
unfold node_rep.
iDestruct "KInv" as "((((((? & KInv) & ?) & ?) & ?) & ?) & ?)".
iPoseProof (field_at_conflict Ews t_struct_tree_t (DOT _t) p
with "[$H3 $KInv]") as "HF"; eauto; simpl; lia.
}
(* free *)
forward_call (t_struct_pn, nb, gv).
{ assert_PROP (nb <> nullval) by entailer !. rewrite if_false; auto; cancel. }
entailer !.
unfold nodebox_rep.
Exists np lsh.
unfold tree_rep_R. rewrite -> if_true; auto.
entailer !. by iIntros "_".
- simpl in H2.
forward_if (
PROP ( )
LOCAL (temp _t'2 Vfalse; temp _t'7 np; temp _pn__2 nb; gvars gv; temp _t b;
temp _x (vint x); temp _value v)
SEP (Q1 (false, (p, (gsh, (g_in, r)))); mem_mgr gv; seplog.emp; data_at Ews t_struct_pn (p, p) nb;
in_tree g g_in p r.1.1.2;
my_half g_in Tsh r *
(!! (repable_signed (number2Z r.1.2.1)
∧ repable_signed (number2Z r.1.2.2) ∧ is_pointer_or_null r.1.1.2) &&
field_at Ews t_struct_tree_t (DOT _t) r.1.1.1 p *
field_at Ews t_struct_tree_t (DOT _min) (vint (number2Z r.1.2.1)) p *
field_at Ews t_struct_tree_t (DOT _max) (vint (number2Z r.1.2.2)) p *
malloc_token Ews t_struct_tree_t p * in_tree g g_in p r.1.1.2 *
(EX (ga gb : gname) (x0 : Z) (v0 pa pb locka lockb : val),
!! (r.2 = Some (Some (x0, v0, ga, gb))
∧ Int.min_signed ≤ x0 ≤ Int.max_signed
∧ is_pointer_or_null pa
∧ is_pointer_or_null locka
∧ is_pointer_or_null pb
∧ is_pointer_or_null lockb ∧ tc_val (tptr Tvoid) v0 ∧ key_in_range x0 r.1.2 = true) &&
data_at Ews t_struct_tree (vint x0, (v, (pa, pb))) r.1.1.1 *
malloc_token Ews t_struct_tree r.1.1.1 * in_tree g ga pa locka * in_tree g gb pb lockb));
in_tree g g_root np lock; malloc_token Ews t_struct_pn nb; data_at sh (tptr t_struct_tree_t) np b;
field_at lsh t_struct_tree_t (DOT _lock) lock np)).
+ unfold node_lock_inv_pred, node_rep, tree_rep_R.
destruct H6 as (Hx & Hy).
destruct Hy as (v1 & g1 & g2 & Hy).
rewrite -> if_false; auto.
Intros g1' g2' x1 v1' p1 p2 lock1 lock2.
simpl. forward. forward. forward.
Exists g1' g2' x1 v1' p1 p2 lock1 lock2.
entailer !. apply derives_refl.
+ pose proof Int.one_not_zero; easy.
+ destruct H6 as ( ? & v2 & g21 & g22 & ?).
Intros g1 g2 x1 v1 p1 p2 lock1 lock2.
forward.
unfold Q1.
simpl.
gather_SEP AS (in_tree g g_in p _).
viewshift_SEP 0 (AS * (in_tree g g_in p r.1.1.2) * (EX lsh, !!(readable_share lsh) &&
field_at lsh t_struct_tree_t (DOT _lock) r.1.1.2 p)).
{ go_lower. apply lock_alloc. }
Intros lsh1.
forward.
forward_call (r.1.1.2, Q).
{
iIntros "(((((((((((((((((((AU & H1) & H2) & H3) & _) & H4) & H5) & H6) & H7) & H8) & H9) & G1) & G2) & G3) & G4) & G5) & G6) & G7) & G8) & G9)".
iCombine "AU H1 H2 H5 H6 H7 H8 H9 G2 G3 G4 G5" as "HH".
iVST.
rewrite <- 6sepcon_assoc; rewrite <- sepcon_comm.
apply sepcon_derives; [| cancel_frame].
unfold atomic_shift; iIntros "(AU & (#HT & (H1 & (H2 & (H3 & (H4 & (H5 & (H6 & (H7 & (H8 & (#HT1 & #HT2)))))))))))"; iAuIntro; unfold atomic_acc; simpl.
iMod "AU" as (m) "[Hm HClose]".
iModIntro.
iPoseProof (tree_rep_insert _ g g_root g_in p r.1.1.2 x v nullval p1 p2 lock1 lock2 with "[$Hm $HT]") as "InvLock".
iDestruct "InvLock" as (R O) "((K1 & K2) & K3)".
iDestruct "K2" as (lsh2) "(% & (K2 & KInv))".
iDestruct "KInv" as (bl) "(KAt & KInv)".
destruct bl.
+ iExists ().
iFrame "KAt".
iSplit.
{ iIntros "H". iFrame.
iAssert (ltree g g_in p r.1.1.2 (node_lock_inv_pred g p g_in (R, Some O)))
with "[H K2]" as "HInv".
{ iExists _; iSplit; iFrame; try done. iExists true; iFrame. }
iSpecialize ("K3" with "[$HInv $K1]").
iDestruct "K3" as "(K3 & _)".
iSpecialize ("HClose" with "K3"); auto.
}
iIntros (_) "(H & _)".
iDestruct "K3" as "[[_ > K3] _]".
iSpecialize ("K3" $! g1 g2 v1).
iPoseProof (public_update g_in r (R, Some O) (R, Some (Some (x, v, g1, g2)))
with "[$H2 $K1]") as "(% & >(H2 & K1))".
(* join two field_at *)
destruct r. inversion H17; simpl.
rewrite H7 in H11.
inversion H11; subst x1 v2 g21 g22.
destruct g0. destruct p0.
simpl.
destruct H16 as (Hf & Hrs).
(* lock_join lsh1 and lsh2 = Lsh *)
iPoseProof (lock_join with "[$H1 $K2]") as "K2"; try iSplit; auto.
iDestruct "K2" as (Lsh) "(% & K2)".
iAssert (ltree g g_in p v2
(node_lock_inv_pred g p g_in (v0, v2, r, Some (Some (x, v , g1, g2)))))
with "[H K2 H2 H3 H4 H5 H6 H7 H8]" as "LT".
{
iApply (non_null_ltree g g_in p _ Lsh _ p1 p2 lock1 lock2 g1 g2); auto.
iFrame. iFrame "HT HT1 HT2". }
iSpecialize ("K3" with "[$K1 $LT]").
iPureIntro; subst; repeat (split; auto; [inversion H7]); auto.
iDestruct "K3" as "(K3 & _)".
iDestruct "HClose" as "[_ HClose]".
iSpecialize ("HClose" $! ()).
iMod ("HClose" with "[$K3]") as "HClose"; auto.
+ unfold node_lock_inv_pred at 1, node_rep.
iDestruct "KInv" as "(? & KInv)".
iDestruct "KInv" as "((((((? & KInv) & ?) & ?) & ?) & ?) & ?)".
iPoseProof (field_at_conflict Ews t_struct_tree_t (DOT _t) p
with "[$H3 $KInv]") as "HF"; try easy; auto.
}
(* free *)
forward_call (t_struct_pn, nb, gv).
{ assert_PROP (nb <> nullval) by entailer !. rewrite if_false; auto. cancel. }
entailer !.
Exists np lsh.
entailer !. by iIntros "_".
Qed.
|
import verification.misc
import verification.semantics.stream
open_locale classical
noncomputable theory
variables {ι ι' ι'' : Type} {α β γ : Type*}
def Stream.reduced (q : Stream ι α) : Prop :=
∀ ⦃r⦄ (h : q.valid r) (h' : q.ready r), q.index' r ≠ q.index' (q.next r h)
variables [linear_order ι] [linear_order ι'] [linear_order ι'']
-- index ready
@[reducible]
def stream_order (ι : Type) : Type := with_top ι ×ₗ bool
@[simps]
def Stream.to_order (s : Stream ι α) (x : s.σ) : stream_order ι :=
⟨s.index' x, s.ready x⟩
@[simp] lemma Stream.bimap_to_order (s : Stream ι α) (g : α → β) :
(g <$₂> s).to_order = s.to_order := rfl
lemma valid_of_le_valid {s₁ : Stream ι α} {s₂ : Stream ι β} {x : s₁.σ} {y : s₂.σ}
(h : s₁.to_order x ≤ s₂.to_order y) (h' : s₂.valid y) : s₁.valid x :=
by { simp [Stream.to_order, h'] at h, rw ← Stream.index'_lt_top_iff, refine lt_of_le_of_lt (prod.lex.fst_le_of_le h) _, simpa, }
lemma valid_of_le_or {a : Stream ι α} {b : Stream ι α} {x : a.σ} {y : b.σ}
(h : a.valid x ∨ b.valid y) (h' : a.to_order x ≤ b.to_order y) : a.valid x :=
(or_iff_left_of_imp (valid_of_le_valid h')).mp h
def Stream.monotonic (q : Stream ι α) : Prop :=
∀ ⦃r⦄ (h : q.valid r), q.index' r ≤ q.index' (q.next r h)
structure Stream.simple (q : Stream ι α) : Prop :=
(monotonic : q.monotonic)
(reduced : q.reduced)
lemma Stream.monotonic.le_index_iterate {s : Stream ι α} (hs : s.monotonic) (q : s.σ) (n : ℕ) :
s.index' q ≤ s.index' (s.next'^[n] q) :=
begin
induction n with n ih generalizing q, { simp, },
by_cases h : s.valid q, swap,
{ simp [Stream.next'_val_invalid' h], },
refine (hs h).trans _,
simpa [Stream.next'_val h] using ih _,
end
lemma Stream.monotonic.index_le_support [add_zero_class α] {q : Stream ι α} (hq : q.monotonic) {x : q.σ} {n : ℕ} :
∀ i ∈ (q.eval_steps n x).support, q.index' x ≤ ↑i :=
begin
induction n with n ih generalizing x,
{ simp, },
simp only [Stream.eval_steps, ne.def],
split_ifs, swap, { simp, },
intros i H,
rcases (finset.mem_union.mp (finsupp.support_add H)) with H'|H',
{ exact trans (hq _) (ih _ H'), },
rw finset.mem_singleton.mp (q.eval₀_support _ h H'),
exact (le_of_eq (Stream.index'_val _)),
end
lemma Stream.simple.index_lt_next {q : Stream ι α} (hq : q.simple) {x : q.σ}
(hv : q.valid x) (hr : q.ready x) : q.index' x < q.index' (q.next _ hv) :=
by { rw lt_iff_le_and_ne, exact ⟨hq.monotonic hv, hq.reduced hv hr⟩, }
lemma Stream.simple.index_lt_support [add_zero_class α] {q : Stream ι α} (hq : q.simple) {x : q.σ} {n : ℕ}
(hv : q.valid x) (hr : q.ready x) :
∀ i ∈ (q.eval_steps n (q.next x hv)).support, q.index' x < ↑i :=
λ i H, lt_of_lt_of_le (hq.index_lt_next hv hr) (hq.monotonic.index_le_support i H)
@[ext]
structure SimpleStream (ι : Type) [linear_order ι] (α : Type*) extends StreamExec ι α :=
(simple : stream.simple)
instance (ι : Type) [linear_order ι] (α : Type*) : has_coe
(SimpleStream ι α) (StreamExec ι α) := ⟨SimpleStream.to_StreamExec⟩
def SimpleStream.contract {ι α} [linear_order ι] (s : SimpleStream ι α) :
StreamExec unit α := contract_stream (s : StreamExec ι α)
lemma SimpleStream.monotonic (s : SimpleStream ι α) : s.stream.monotonic :=
s.simple.monotonic
lemma SimpleStream.reduced (s : SimpleStream ι α) : s.stream.reduced :=
s.simple.reduced
@[simps]
def SimpleStream.bimap (s : SimpleStream ι α) (f : ι ↪o ι') (g : α → β) : SimpleStream ι' β :=
{ s.to_StreamExec.bimap f g with
simple := {
reduced := begin
simp only [StreamExec.bimap],
intros r hv hr,
simp_rw Stream.bimap_index'_eq_apply,
by_contra h,
exact absurd (option.map_injective f.injective h) (s.reduced hv hr),
end,
monotonic := begin
simp only [StreamExec.bimap],
intros r hv,
simp_rw Stream.bimap_index'_eq_apply,
exact with_top.monotone_map_iff.2 f.monotone (s.monotonic hv)
end,
}}
abbreviation irefl {α : Type*} [has_le α] : α ↪o α := rel_embedding.refl _
notation f ` <§₁> `:1 s := s.bimap f id
notation g ` <§₂> `:1 s := s.bimap irefl g
@[simp] lemma SimpleStream.id_bimap (s : SimpleStream ι α) : s.bimap irefl id = s :=
by ext; solve_refl
@[simp] lemma SimpleStream.bimap_bimap (s : SimpleStream ι α)
(f : ι ↪o ι') (f' : ι' ↪o ι'') (g : α → β) (h : β → γ) :
(s.bimap f g).bimap f' h = s.bimap (f.trans f') (h ∘ g) :=
by ext; solve_refl
@[simp] lemma SimpleStream.imap (s : SimpleStream ι α) (f : ι ↪o ι') :
(f <§₁> s).stream = (f <$₁> s.stream) := rfl
@[simp] lemma SimpleStream.imap_stream_eval [add_zero_class α] (s : SimpleStream ι α) (f : ι ↪o ι') (n : ℕ) :
(f <§₁> s).stream.eval_steps n s.state = (f <$₁> s.stream).eval_steps n s.state := rfl
@[simp] lemma SimpleStream.bifunctor_bimap_valid (s : SimpleStream ι α) (f : ι ↪o ι') (g : α → β) :
(s.bimap f g).valid ↔ s.valid := iff.rfl
@[simp] lemma SimpleStream.bifunctor_bimap_ready (s : SimpleStream ι α) (f : ι ↪o ι') (g : α → β) :
(s.bimap f g).ready ↔ s.ready := iff.rfl
@[simp] lemma SimpleStream.bimap_eval [add_comm_monoid α] (s : SimpleStream ι α) (f : ι ↪o ι') :
(f <§₁> s).eval = (f <$₁> s.to_StreamExec).eval := rfl
namespace primitives
lemma range.reduced {n : ℕ} : (range n).reduced :=
begin
intros r hv hr,
unfold Stream.index',
split_ifs; norm_cast; simp [hv],
end
lemma range.monotonic {n : ℕ} : (range n).monotonic :=
begin
intros r hv,
unfold Stream.index',
split_ifs; try { norm_cast }; simp,
end
@[simps]
def range_simple (n : ℕ) : SimpleStream ℕ ℕ :=
{ range_exec n with simple := ⟨range.monotonic, range.reduced⟩ }
end primitives
|
lemma filterlim_at_top_mult_at_top: assumes f: "LIM x F. f x :> at_top" and g: "LIM x F. g x :> at_top" shows "LIM x F. (f x * g x :: real) :> at_top"
|
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import random
from typing import Tuple
import numpy as np
import torch
from tensorboardX import SummaryWriter
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm
from transformers import AdamW, get_linear_schedule_with_warmup, AutoTokenizer
from data.data_instance import ModelState
from general_util.logger import setting_logger
from general_util.utils import AverageMeter
from models import model_map
from processors import get_processor
"""
torch==1.6.0
TODO: Add distributed training logic
"""
def main():
parser = argparse.ArgumentParser()
# Required parameters
# parser.add_argument("--bert_model", default=None, type=str, required=True,
# help="Bert pre-trained model selected in the list: bert-base-uncased, "
# "bert-large-uncased, bert-base-cased, bert-base-multilingual, bert-base-chinese.")
parser.add_argument("--vocab_file", default='bert-base-uncased-vocab.txt', type=str, required=True)
parser.add_argument("--model_file", default='bert-base-uncased.tar.gz', type=str, required=True)
parser.add_argument("--output_dir", default=None, type=str, required=True,
help="The output directory where the model checkpoints and predictions will be written.")
parser.add_argument("--predict_dir", default=None, type=str, required=True,
help="The output directory where the predictions will be written.")
# Other parameters
parser.add_argument("--train_file", default=None, type=str, help="SQuAD json for training. E.g., train-v1.1.json")
parser.add_argument("--predict_file", default=None, type=str,
help="SQuAD json for predictions. E.g., dev-v1.1.json or test-v1.1.json")
parser.add_argument("--test_file", default=None, type=str)
parser.add_argument("--max_seq_length", default=384, type=int,
help="The maximum total input sequence length after WordPiece tokenization. Sequences "
"longer than this will be truncated, and sequences shorter than this will be padded.")
parser.add_argument("--doc_stride", default=128, type=int,
help="When splitting up a long document into chunks, how much stride to take between chunks.")
parser.add_argument("--max_query_length", default=64, type=int,
help="The maximum number of tokens for the question. Questions longer than this will "
"be truncated to this length.")
parser.add_argument("--do_train", default=False, action='store_true', help="Whether to run training.")
parser.add_argument("--do_predict", default=False, action='store_true', help="Whether to run eval on the dev set.")
parser.add_argument("--do_label", default=False, action='store_true', help="For preprocess only.")
parser.add_argument("--train_batch_size", default=32, type=int, help="Total batch size for training.")
parser.add_argument("--predict_batch_size", default=8, type=int, help="Total batch size for predictions.")
parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.")
parser.add_argument("--num_train_epochs", default=2.0, type=float,
help="Total number of training epochs to perform.")
parser.add_argument("--warmup_proportion", default=0.1, type=float,
help="Proportion of training to perform linear learning rate warmup for. E.g., 0.1 = 10% "
"of training.")
parser.add_argument("--no_cuda",
default=False,
action='store_true',
help="Whether not to use CUDA when available")
parser.add_argument('--seed',
type=int,
default=42,
help="random seed for initialization")
parser.add_argument('--gradient_accumulation_steps',
type=int,
default=1,
help="Number of updates steps to accumulate before performing a backward/update pass.")
parser.add_argument("--do_lower_case",
default=True,
action='store_true',
help="Whether to lower case the input text. True for uncased models, False for cased models.")
parser.add_argument("--local_rank",
type=int,
default=-1,
help="local_rank for distributed training on gpus")
parser.add_argument('--loss_scale',
type=float, default=0,
help="Loss scaling to improve fp16 numeric stability. Only used when fp16 set to True.\n"
"0 (default value): dynamic loss scaling.\n"
"Positive power of 2: static loss scaling value.\n")
# Base setting
parser.add_argument('--pretrain', type=str, default=None)
parser.add_argument('--bert_name', type=str, default='self_sup_pretrain_cls_query')
parser.add_argument('--reader_name', type=str, default='wiki_pre_train')
parser.add_argument('--per_eval_step', type=int, default=200)
# Self-supervised pre-training
parser.add_argument('--keep_prob', default=0.6, type=float)
parser.add_argument('--mask_prob', default=0.2, type=float)
parser.add_argument('--replace_prob', default=0.05, type=float)
# Self-supervised pre-training input_file setting
parser.add_argument('--input_files_template', type=str, required=True)
parser.add_argument('--input_files_start', type=int, default=0)
parser.add_argument('--input_files_end', type=int, default=10)
parser.add_argument('--save_each_epoch', default=False, action='store_true')
args = parser.parse_args()
logger = setting_logger(args.output_dir)
logger.info('================== Program start. ========================')
if args.local_rank == -1 or args.no_cuda:
device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
n_gpu = torch.cuda.device_count()
else:
torch.cuda.set_device(args.local_rank)
device = torch.device("cuda", args.local_rank)
n_gpu = 1
# Initializes the distributed backend which will take care of sychronizing nodes/GPUs
torch.distributed.init_process_group(backend='nccl')
logger.info("device: {} n_gpu: {}, distributed training: {}".format(
device, n_gpu, bool(args.local_rank != -1)))
if args.gradient_accumulation_steps < 1:
raise ValueError("Invalid gradient_accumulation_steps parameter: {}, should be >= 1".format(
args.gradient_accumulation_steps))
args.train_batch_size = int(args.train_batch_size / args.gradient_accumulation_steps)
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
if not args.do_train and not args.do_predict and not args.do_label:
raise ValueError("At least one of `do_train` or `do_predict` or `do_label` must be True.")
if args.do_train:
if not args.train_file and not args.input_files_template:
raise ValueError(
"If `do_train` is True, then `train_file` must be specified.")
if args.do_predict:
if not args.predict_file:
raise ValueError(
"If `do_predict` is True, then `predict_file` must be specified.")
if args.do_train:
if os.path.exists(args.output_dir) and os.listdir(args.output_dir):
raise ValueError("Output directory () already exists and is not empty.")
os.makedirs(args.output_dir, exist_ok=True)
if args.do_predict or args.do_label:
os.makedirs(args.predict_dir, exist_ok=True)
tokenizer = AutoTokenizer.from_pretrained(args.vocab_file)
data_reader = get_processor(args)
num_train_steps = None
if args.do_train or args.do_label:
# Generate cache files
input_files_format = args.input_files_template
total_features = 0
for idx in range(args.input_files_start, args.input_files_end + 1):
train_file = input_files_format.format(str(idx))
cached_train_features_file = train_file + '_' + data_reader.opt['cache_suffix']
if not os.path.exists(cached_train_features_file):
train_examples = data_reader.read(input_file=train_file)
train_features = data_reader.convert_examples_to_features(examples=train_examples, tokenizer=tokenizer)
_, train_tensors = data_reader.data_to_tensors_sent_pretrain(train_features)
if args.local_rank == -1 or torch.distributed.get_rank() == 0:
logger.info(f" Saving train features into cached file {cached_train_features_file}")
torch.save((train_features, train_tensors), cached_train_features_file)
else:
train_features, train_tensors = torch.load(cached_train_features_file)
total_features += train_tensors[0].size(0)
del train_features
del train_tensors
num_train_steps = int(
total_features / args.train_batch_size / args.gradient_accumulation_steps * args.num_train_epochs)
# Prepare model
if args.pretrain is not None:
# TODO: Use new api in transformers compatible with model.save_pretrained() method.
logger.info('Load pretrained model from {}'.format(args.pretrain))
model_state_dict = torch.load(args.pretrain, map_location='cuda:0')
model = model_map[args.bert_name].from_pretrained(args.model_file, state_dict=model_state_dict)
else:
model = model_map[args.bert_name].from_pretrained(args.model_file)
model.to(device)
if args.local_rank != -1:
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank],
output_device=args.local_rank,
find_unused_parameters=True)
elif n_gpu > 1:
model = torch.nn.DataParallel(model)
# Prepare optimizer
param_optimizer = list(model.named_parameters())
# Remove frozen parameters
param_optimizer = [n for n in param_optimizer if n[1].requires_grad]
# hack to remove pooler, which is not used
# thus it produce None grad that break apex
param_optimizer = [n for n in param_optimizer if 'pooler' not in n[0]]
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [
{'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
{'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
]
t_total = num_train_steps if num_train_steps else -1
if args.local_rank != -1:
t_total = t_total // torch.distributed.get_world_size()
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, correct_bias=False)
scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=int(t_total * args.warmup_proportion),
num_training_steps=t_total)
scaler = torch.cuda.amp.GradScaler()
# Prepare data
eval_examples = data_reader.read(input_file=args.predict_file)
eval_features = data_reader.convert_examples_to_features(examples=eval_examples, tokenizer=tokenizer)
eval_features, eval_tensors = data_reader.data_to_tensors_sent_pretrain(eval_features)
eval_data = TensorDataset(*eval_tensors)
eval_sampler = SequentialSampler(eval_data)
eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.predict_batch_size, num_workers=8)
if args.do_train:
logger.info("***** Running training *****")
# logger.info(" Num orig examples = %d", len(train_examples))
logger.info(" Num split examples = %d", total_features)
logger.info(" Batch size = %d", args.train_batch_size)
summary_writer = SummaryWriter(log_dir=args.output_dir)
global_step = 0
eval_loss = AverageMeter()
train_loss = AverageMeter()
best_loss = 1000000000
eval_acc = AverageMeter()
# Separate dataloader for huge dataset
data_loader_id_range = list(range(args.input_files_start, args.input_files_end + 1))
for epoch in range(int(args.num_train_epochs)):
logger.info(f'Running at Epoch {epoch}')
# Load training dataset separately
random.shuffle(data_loader_id_range)
for idx in data_loader_id_range:
train_file = args.input_files_template.format(str(idx))
cached_train_features_file = train_file + '_' + data_reader.opt['cache_suffix']
logger.info(f"Load features and tensors from {cached_train_features_file}")
train_features, train_tensors = torch.load(cached_train_features_file)
train_data = TensorDataset(*train_tensors)
if args.local_rank == -1:
train_sampler = RandomSampler(train_data)
else:
train_sampler = DistributedSampler(train_data)
train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=args.train_batch_size)
# Train
for step, batch in enumerate(tqdm(train_dataloader, desc="Iteration", dynamic_ncols=True)):
model.train()
if n_gpu == 1:
batch = batch_to_device(batch, device) # multi-gpu does scattering it-self
inputs = data_reader.generate_inputs(batch, train_features, model_state=ModelState.Train)
with torch.cuda.amp.autocast():
output_dict = model(**inputs)
loss = output_dict['loss']
train_loss.update(val=loss.item(), n=inputs['answers'].size(0))
if n_gpu > 1:
loss = loss.mean() # mean() to average on multi-gpu.
if args.gradient_accumulation_steps > 1:
loss = loss / args.gradient_accumulation_steps
scaler.scale(loss).backward()
if (step + 1) % args.gradient_accumulation_steps == 0:
# scaler.unscale_(optimizer)
# torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
scaler.step(optimizer)
scaler.update()
scheduler.step()
# optimizer.step()
optimizer.zero_grad()
global_step += 1
lr_this_step = scheduler.get_lr()[0]
summary_writer.add_scalar('lr', lr_this_step, global_step)
batch_size = inputs["answers"].size(0)
summary_writer.add_scalar('train/loss', train_loss.avg, global_step)
# print(f'loss: {train_loss.avg}')
# print(inputs["answers"])
if global_step % args.per_eval_step == 0:
# Evaluation
model.eval()
logger.info("Start evaluating")
for _, eval_batch in enumerate(
tqdm(eval_dataloader, desc="Evaluating", dynamic_ncols=True)):
if n_gpu == 1:
eval_batch = batch_to_device(eval_batch,
device) # multi-gpu does scattering it-self
inputs = data_reader.generate_inputs(eval_batch, eval_features,
model_state=ModelState.Train)
with torch.no_grad():
with torch.cuda.amp.autocast():
output_dict = model(**inputs)
loss = output_dict['loss']
batch_size = inputs["answers"].size(0)
eval_loss.update(loss.item(), batch_size)
eval_acc.update(output_dict["acc"].item(), output_dict["valid_num"])
eval_epoch_loss = eval_loss.avg
eval_epoch_acc = eval_acc.avg
summary_writer.add_scalar('eval/loss', eval_epoch_loss, global_step)
summary_writer.add_scalar('eval/acc', eval_epoch_acc, global_step)
eval_loss.reset()
eval_acc.reset()
if eval_epoch_loss < best_loss:
best_loss = eval_epoch_loss
# Only save the model it-self
model_to_save = model.module if hasattr(model, 'module') else model
output_model_file = os.path.join(args.output_dir, "pytorch_model.bin")
torch.save(model_to_save.state_dict(), output_model_file)
logger.info(
f'Global step: {global_step}, eval_loss: {eval_epoch_loss}, best_loss: {best_loss}, '
f'eval_acc: {eval_epoch_acc}')
logger.info(f'Train loss: {train_loss.avg}')
# Free memory
del train_features
del train_tensors
del train_data
del train_sampler
del train_dataloader
if args.save_each_epoch:
target_dir = os.path.join(args.output_dir, f'epoch_{epoch}')
os.makedirs(target_dir, exist_ok=True)
model.save_pretrained(target_dir)
summary_writer.close()
def batch_to_device(batch: Tuple[torch.Tensor], device):
# batch[-1] don't move to gpu.
output = []
for t in batch[:-1]:
output.append(t.to(device))
output.append(batch[-1])
return output
if __name__ == "__main__":
main()
|
######################################################################
# initializer.jl
# different ways to initalize a trajectory
######################################################################
export ConstantInitializer
export RandomInitializer
export SampleInitializer
export CornerInitializer
include("constant_initializer.jl")
include("random_initializer.jl")
include("sample_initializer.jl")
include("corner_initializer.jl")
"""
`xd, ud = initialize(em::ErgodicManager, tm::TrajectoryManager)`
Runs `tm`'s initializer to return a trajectory.
"""
function initialize(em::ErgodicManager, tm::TrajectoryManager)
initialize(tm.initializer, em, tm)
end
function initialize(em::ErgodicManager, vtm::Vector{TrajectoryManager})
num_agents = length(vtm)
xd0s = VVVF()
ud0s = VVVF()
for j = 1:num_agents
xd0, ud0 = initialize(em, vtm[j])
push!(xd0s, xd0)
push!(ud0s, ud0)
end
return vvvf2vvf(xd0s, ud0s)
end
# TODO: finish this one
"""
`cci = CornerConstantInitializer(action::Vector{Float64})`
Just takes a constant action.
"""
mutable struct CornerConstantInitializer <: Initializer
magnitude::Float64
end
"""
`gi = GreedyInitializer()`
Greedily goes to spot with maximum phi.
Assumes phi decreases at a constant rate.
"""
mutable struct GreedyInitializer <: Initializer end
"""
`poi = PointInitializer(xd::Vector{Float64})`
Moves to point `xd`.
"""
mutable struct PointInitializer <: Initializer
xd::Vector{Float64}
end
"""
`di = DirectionInitializer(xd::Vector{Float64}, mag::Float64)`
Moves in the direction of point `xd` with magnitude `mag`.
"""
mutable struct DirectionInitializer <: Initializer
xd::Vector{Float64}
mag::Float64
end
# TODO: actually finish this
function initialize(cci::CornerConstantInitializer, em::ErgodicManager, tm::TrajectoryManager)
xd = Array(Vector{Float64}, tm.N+1)
ud = Array(Vector{Float64}, tm.N)
xd[1] = deepcopy(tm.x0)
ud[1] = deepcopy(ci.action)
for i = 1:(tm.N-1)
xd[i+1] = tm.A*xd[i] + tm.B*ud[i]
ud[i+1] = deepcopy(ci.action)
end
xd[tm.N+1] = tm.A*xd[tm.N] + tm.B*ud[tm.N]
return xd, ud
end
export greedy_trajectory
function greedy_trajectory(em::ErgodicManager, tm::TrajectoryManager)
return initialize(GreedyInitializer(), em, tm)
end
function initialize(gi::GreedyInitializer, em::ErgodicManager, tm::TrajectoryManager)
d_rate = sum(em.phi)/tm.N
num_cells = em.bins*em.bins
total_info = 0.0
xd = Array(Vector{Float64}, tm.N+1)
xd[1] = deepcopy(tm.x0)
temp_phi = deepcopy(em.phi)
size_tuple = (em.bins, em.bins)
for n = 1:tm.N
bi = indmax(temp_phi)
xi, yi = ind2sub(size_tuple, bi)
xd[n+1] = [(xi-0.5)*em.cell_size, (yi-0.5)*em.cell_size]
temp_phi[bi] -= min(temp_phi[bi], d_rate)
end
ud = compute_controls(xd, tm.h)
return xd,ud
end
# moves to a point with a constant control input
function initialize(initializer::PointInitializer, em::ErgodicManager, tm::TrajectoryManager)
# compute the direction and action we most go towards
dx = initializer.xd[1] - tm.x0[1]
dy = initializer.xd[2] - tm.x0[2]
#x_step = (initializer.xd[1] - tm.x0[1]) / (tm.N * tm.h)
#y_step = (initializer.xd[2] - tm.x0[2]) / (tm.N * tm.h)
#u = [x_step, y_step]
# if we are double integrator, only apply the input once
ud = Array(Vector{Float64}, tm.N)
if tm.dynamics.n > 2
den = tm.h * tm.h * (tm.N-1)
ud[1] = [dx/den, dy/den]
for i = 1:(tm.N-1)
ud[i+1] = zeros(2)
end
else # single integrator
den = tm.h * tm.N
u = [dx / den, dy / den]
for i = 1:tm.N
ud[i] = deepcopy(u)
end
end
xd = integrate(tm, ud)
return xd, ud
end
# moves to a point with a constant control input
function initialize(initializer::DirectionInitializer, em::ErgodicManager, tm::TrajectoryManager)
xd = Array(Vector{Float64}, tm.N+1)
ud = Array(Vector{Float64}, tm.N)
# compute the direction and action we most go towards
dx = initializer.xd[1] - tm.x0[1]
dy = initializer.xd[2] - tm.x0[2]
u = initializer.mag * [dx, dy] / sqrt(dx*dx + dy*dy)
xd[1] = deepcopy(tm.x0)
ud[1] = deepcopy(u)
for i = 1:(tm.N-1)
xd[i+1] = tm.A*xd[i] + tm.B*ud[i]
ud[i+1] = deepcopy(u)
end
xd[tm.N+1] = tm.A*xd[tm.N] + tm.B*ud[tm.N]
return xd, ud
end
|
module Numeral.Natural.Function.GreatestCommonDivisor.Proofs where
open import Data
open import Functional
open import Logic.Propositional
open import Numeral.Finite
open import Numeral.Natural
open import Numeral.Natural.Function.GreatestCommonDivisor
open import Numeral.Natural.Oper
open import Numeral.Natural.Oper.FlooredDivision
open import Numeral.Natural.Oper.FlooredDivision.Proofs.Inverse
open import Numeral.Natural.Oper.Modulo
open import Numeral.Natural.Relation.Divisibility
open import Numeral.Natural.Relation.Divisibility.Proofs
open import Numeral.Natural.Relation.Divisibility.Proofs.Modulo
open import Numeral.Natural.Relation.Order
open import Relator.Equals
open import Relator.Equals.Proofs.Equiv
open import Structure.Relator
open import Structure.Relator.Properties
open import Structure.Operator
open import Structure.Operator.Properties
open import Syntax.Number
open import Syntax.Transitivity
private variable a b c d d₁ d₂ : ℕ
gcd-same : (gcd(a)(a) ≡ a)
gcd-same = [↔]-to-[→] Gcd-gcd-value (Gcd.intro₂ (reflexivity(_∣_)) (reflexivity(_∣_)) (const id))
instance
gcd-identityₗ : Identityₗ(gcd)(𝟎)
Identityₗ.proof gcd-identityₗ = [↔]-to-[→] Gcd-gcd-value (Gcd.intro₂ Div𝟎 (reflexivity(_∣_)) (const id))
instance
gcd-identityᵣ : Identityᵣ(gcd)(𝟎)
Identityᵣ.proof gcd-identityᵣ = [≡]-intro
instance
gcd-absorberₗ : Absorberₗ(gcd)(1)
Absorberₗ.proof gcd-absorberₗ{b} = [↔]-to-[→] (Gcd-gcd-value{_}{b}) (Gcd.intro₂ [1]-divides [1]-divides const)
instance
gcd-absorberᵣ : Absorberᵣ(gcd)(1)
Absorberᵣ.proof gcd-absorberᵣ{a} = [↔]-to-[→] (Gcd-gcd-value{a}{_}) (Gcd.intro₂ [1]-divides [1]-divides (const id))
instance
gcd-commutativity : Commutativity(gcd)
Commutativity.proof gcd-commutativity {x}{y} = [↔]-to-[→] (Gcd-gcd-value {x}{y}) (Gcd-swap Gcd-gcd)
instance
gcd-associativity : Associativity(gcd)
Associativity.proof gcd-associativity {x}{y}{z} = [↔]-to-[→] (Gcd-gcd-value) (assoc Gcd-gcd Gcd-gcd Gcd-gcd) where
assoc : Gcd x y d₁ → Gcd y z d₂ → Gcd x d₂ d → Gcd d₁ z d
assoc xyd₁ yzd₂ xd₂d =
let d₁x = Gcd.divisorₗ xyd₁
d₁y = Gcd.divisorᵣ xyd₁
xyd₁m = Gcd.maximum₂ xyd₁
d₂y = Gcd.divisorₗ yzd₂
d₂z = Gcd.divisorᵣ yzd₂
yzd₂m = Gcd.maximum₂ yzd₂
dx = Gcd.divisorₗ xd₂d
dd₂ = Gcd.divisorᵣ xd₂d
xd₂dm = Gcd.maximum₂ xd₂d
in Gcd.intro₂
(xyd₁m dx (dd₂ 🝖 d₂y))
(dd₂ 🝖 d₂z)
(\dd₁ dz → xd₂dm (dd₁ 🝖 d₁x) (xd₂dm (dd₁ 🝖 d₁x) (yzd₂m (dd₁ 🝖 d₁y) dz) 🝖 dd₂))
gcd-dividesₗ : (gcd(a)(b) ∣ a)
gcd-dividesₗ {a}{b} = Gcd.divisorₗ{a}{b} Gcd-gcd
gcd-dividesᵣ : (gcd(a)(b) ∣ b)
gcd-dividesᵣ {a}{b} = Gcd.divisorᵣ{a}{b} Gcd-gcd
gcd-divisors : (d ∣ a) → (d ∣ b) → (d ∣ gcd(a)(b))
gcd-divisors da db = Gcd.maximum₂ Gcd-gcd da db
gcd-of-mod : (gcd(a mod 𝐒(b))(𝐒(b)) ≡ gcd(a)(𝐒(b)))
gcd-of-mod{a}{b} = [↔]-to-[→] (Gcd-gcd-value{a mod 𝐒(b)}{𝐒(b)}) (p Gcd-gcd) where
p : Gcd(a)(𝐒(b)) d → Gcd(a mod 𝐒(b))(𝐒(b)) d
p abd =
let da = Gcd.divisorₗ abd
db = Gcd.divisorᵣ abd
m = Gcd.maximum₂ abd
in Gcd.intro₂ ([↔]-to-[→] (divides-mod db) da) db (Dab ↦ Db ↦ m ([↔]-to-[←] (divides-mod Db) Dab) Db)
-- TODO: Is it neccessary to prove this? By gcd-dividesₗ and gcd-dividesᵣ, one get (gcd(a)(b) ∣ min(a)(b)) and the divisor is always smaller
-- gcd-min-order : (gcd(a)(b) ≤ min(a)(b))
gcd-with-[+] : (gcd(a + b)(b) ≡ gcd(a)(b))
gcd-with-[+] {a}{b} = [↔]-to-[→] Gcd-gcd-value (p Gcd-gcd) where
p : Gcd(a)(b) d → Gcd(a + b)(b) d
p abd =
let da = Gcd.divisorₗ abd
db = Gcd.divisorᵣ abd
m = Gcd.maximum₂ abd
in Gcd.intro₂ (divides-with-[+] da db) db (Dab ↦ Db ↦ m ([↔]-to-[←] (divides-without-[+] Dab) Db) Db)
gcd-with₁-[⋅] : (gcd(a ⋅ b)(b) ≡ b)
gcd-with₁-[⋅] {a}{b} = [↔]-to-[→] (Gcd-gcd-value {a ⋅ b}{b}) (Gcd.intro₂ (divides-with-[⋅] {b}{a} ([∨]-introᵣ (reflexivity(_∣_)))) (reflexivity(_∣_)) (const id))
gcd-with-[⋅] : (gcd(a ⋅ c)(b ⋅ c) ≡ gcd(a)(b) ⋅ c)
gcd-with-[⋅] {a}{𝟎} {b} = [≡]-intro
gcd-with-[⋅] {a}{𝐒(c)}{b} =
gcd(a ⋅ 𝐒(c)) (b ⋅ 𝐒(c)) 🝖[ _≡_ ]-[ q ]-sym
gcd(a ⋅ 𝐒(c)) (b ⋅ 𝐒(c)) ⌊/⌋ 𝐒(c) ⋅ 𝐒(c) 🝖[ _≡_ ]-[ congruence₂ₗ(_⋅_)(𝐒(c)) ([↔]-to-[→] Gcd-gcd-value (p{gcd(a ⋅ 𝐒(c))(b ⋅ 𝐒(c)) ⌊/⌋ 𝐒(c)} ([↔]-to-[←] Gcd-gcd-value (symmetry(_≡_) q)))) ]-sym
gcd(a)(b) ⋅ 𝐒(c) 🝖-end
where
p : Gcd a b d ← Gcd(a ⋅ 𝐒(c))(b ⋅ 𝐒(c))(d ⋅ 𝐒(c))
p acbcdc =
let dcac = Gcd.divisorₗ acbcdc
dcbc = Gcd.divisorᵣ acbcdc
m = Gcd.maximum₂ acbcdc
in Gcd.intro₂ (divides-without-[⋅]ᵣ-both {z = c} dcac) (divides-without-[⋅]ᵣ-both {z = c} dcbc) (\{D} → Da ↦ Db ↦ divides-without-[⋅]ᵣ-both {z = c} (m{D ⋅ 𝐒(c)} (divides-with-[⋅]ᵣ-both {z = 𝐒(c)} Da) (divides-with-[⋅]ᵣ-both {z = 𝐒(c)} Db)))
q = [⋅][⌊/⌋]-inverseOperatorᵣ (gcd-divisors{𝐒(c)}{a ⋅ 𝐒(c)}{b ⋅ 𝐒(c)} (divides-with-[⋅] {𝐒(c)}{a} ([∨]-introᵣ (reflexivity(_∣_)))) (divides-with-[⋅] {𝐒(c)}{b} ([∨]-introᵣ (reflexivity(_∣_)))))
gcd-0 : ((a ≡ 𝟎) ∧ (b ≡ 𝟎)) ↔ (gcd a b ≡ 𝟎)
gcd-0 = [↔]-intro l r where
l : ((a ≡ 𝟎) ∧ (b ≡ 𝟎)) ← (gcd a b ≡ 𝟎)
l {𝟎} {𝟎} p = [∧]-intro [≡]-intro [≡]-intro
l {𝐒 a} {𝐒 b} p
with intro zv _ ← [↔]-to-[←] (Gcd-gcd-value{𝐒(a)}{𝐒(b)}) p
with () ← [0]-divides-not (zv 𝟎)
r : ((a ≡ 𝟎) ∧ (b ≡ 𝟎)) → (gcd a b ≡ 𝟎)
r {𝟎} {𝟎} _ = [≡]-intro
open import Logic.Classical
open import Logic.Propositional.Theorems
open import Numeral.Natural.Decidable
open import Numeral.Natural.Relation
open import Numeral.Natural.Relation.Proofs
open import Type.Properties.Decidable.Proofs
gcd-positive : (Positive(a) ∨ Positive(b)) ↔ Positive(gcd a b)
gcd-positive{a}{b} = [↔]-transitivity ([∨]-map-[↔] Positive-non-zero Positive-non-zero) ([↔]-transitivity ([↔]-symmetry ([¬]-preserves-[∧][∨] ⦃ decider-classical(a ≡ 𝟎) ⦄ ⦃ decider-classical(b ≡ 𝟎) ⦄)) ([↔]-transitivity ([¬]-unaryOperator (gcd-0 {a}{b})) ([↔]-symmetry Positive-non-zero)))
gcd-of-successor : ∀{n} → Gcd(n)(𝐒(n))(1)
gcd-of-successor = Gcd.intro₂ [1]-divides [1]-divides p where
p : ∀{d n} → (d ∣ n) → (d ∣ 𝐒(n)) → (d ∣ 1)
p Div𝟎 dsn = dsn
p (Div𝐒 dn) dsn = p dn ([↔]-to-[→] (divides-without-[+] dsn) (reflexivity(_∣_)))
open import Logic.Propositional.Theorems
open import Numeral.Natural.Coprime
open import Numeral.Natural.Coprime.Proofs
open import Numeral.Natural.Oper.FlooredDivision.Proofs
open import Numeral.Natural.Oper.FlooredDivision.Proofs.Inverse
open import Numeral.Natural.Oper.Proofs
open import Numeral.Natural.Relation.Order.Proofs
open import Syntax.Implication
[⌊/⌋₀]-gcd-coprime : (Positive(a) ∨ Positive(b)) → Coprime(a ⌊/⌋₀ gcd(a)(b)) (b ⌊/⌋₀ gcd(a)(b))
[⌊/⌋₀]-gcd-coprime {a}{b} nz =
let d = gcd(a)(b)
D = gcd(a ⌊/⌋₀ d) (b ⌊/⌋₀ d)
gcd-D = Gcd-gcd {a ⌊/⌋₀ d} {b ⌊/⌋₀ d}
d-pos = [↔]-to-[→] Positive-greater-than-zero ([↔]-to-[→] gcd-positive nz)
in
• (
Gcd.divisorₗ gcd-D ⇒
(D ∣ (a ⌊/⌋₀ d)) ⇒-[ divides-with-[⋅]ᵣ-both {z = d} ]
(D ⋅ d ∣ (a ⌊/⌋₀ d) ⋅ d) ⇒-[ substitute₂ᵣ(_∣_) ([⋅][⌊/⌋₀]-inverseOperatorᵣ d-pos (gcd-dividesₗ {b = b})) ]
(D ⋅ d ∣ a) ⇒-[ substitute₂ₗ(_∣_) (commutativity(_⋅_) {D}{d}) ]
(d ⋅ D ∣ a) ⇒-end
)
• (
Gcd.divisorᵣ gcd-D ⇒
(D ∣ (b ⌊/⌋₀ d)) ⇒-[ divides-with-[⋅]ᵣ-both {z = d} ]
(D ⋅ d ∣ (b ⌊/⌋₀ d) ⋅ d) ⇒-[ substitute₂ᵣ(_∣_) ([⋅][⌊/⌋₀]-inverseOperatorᵣ d-pos gcd-dividesᵣ) ]
(D ⋅ d ∣ b) ⇒-[ substitute₂ₗ(_∣_) (commutativity(_⋅_) {D}{d}) ]
(d ⋅ D ∣ b) ⇒-end
)
⇒₂-[ Gcd.maximum₂ Gcd-gcd ]
((d ⋅ D) ∣ d) ⇒-[]
((d ⋅ D) ∣ (d ⋅ 1)) ⇒-[ divides-without-[⋅]ₗ-both' d-pos ]
(D ∣ 1) ⇒-[ [1]-only-divides-[1] ]
(D ≡ 1) ⇒-[ [↔]-to-[←] Coprime-gcd ]
Coprime(a ⌊/⌋₀ d) (b ⌊/⌋₀ d) ⇒-end
[⌊/⌋]-gcd-coprime : (nz : Positive(a) ∨ Positive(b)) → Coprime((a ⌊/⌋ gcd(a)(b)) ⦃ [↔]-to-[→] gcd-positive nz ⦄) ((b ⌊/⌋ gcd(a)(b)) ⦃ [↔]-to-[→] gcd-positive nz ⦄)
[⌊/⌋]-gcd-coprime {a}{b} nz = substitute₂(Coprime)
([⌊/⌋][⌊/⌋₀]-equality ⦃ [↔]-to-[→] gcd-positive nz ⦄)
([⌊/⌋][⌊/⌋₀]-equality ⦃ [↔]-to-[→] gcd-positive nz ⦄)
([⌊/⌋₀]-gcd-coprime nz)
|
# James Rekow
computeFileDependencies = function(input){
# ARGS:
#
# RETURNS: dependenciesList - list of the form list(librariesVec, filesVec), where librariesVec is a
# character vector of all libraries upon which input depends, and
# filesVec is a character vector of all files upon which input depends,
# including itself
source("computeDirectFileDependencies.r")
noFileDependencies = is.null(computeDirectFileDependencies(unlist(input)))
input = as.list(unlist(input))
if(noFileDependencies){
return(input)
} else{
# compute direct file dependencies for each file in the input list
directFileDependenciesList = lapply(as.list(unlist(input)), computeDirectFileDependencies)
# recursively call function until each file dependency has been computed
return(lapply(directFileDependenciesList, computeFileDependencies))
} # end if/else
} # end computeFileDependencies function
|
(*
* Copyright 2014, NICTA
*
* This software may be distributed and modified according to the terms of
* the BSD 2-Clause license. Note that NO WARRANTY is provided.
* See "LICENSE_BSD2.txt" for details.
*
* @TAG(NICTA_BSD)
*)
theory WordLemmaBucket
imports
Lib
MoreDivides
Aligned
HOLLemmaBucket
DistinctPropLemmaBucket
"~~/src/HOL/Library/Sublist"
"~~/src/HOL/Library/Prefix_Order"
begin
(* Setup "quickcheck" to support words. *)
quickcheck_generator word
constructors:
"zero_class.zero :: ('a::len) word",
"numeral :: num \<Rightarrow> ('a::len) word",
"uminus :: ('a::len) word \<Rightarrow> ('a::len) word"
instantiation Enum.finite_1 :: len
begin
definition "len_of_finite_1 (x :: Enum.finite_1 itself) \<equiv> (1 :: nat)"
instance
by (default, auto simp: len_of_finite_1_def)
end
instantiation Enum.finite_2 :: len
begin
definition "len_of_finite_2 (x :: Enum.finite_2 itself) \<equiv> (2 :: nat)"
instance
by (default, auto simp: len_of_finite_2_def)
end
instantiation Enum.finite_3 :: len
begin
definition "len_of_finite_3 (x :: Enum.finite_3 itself) \<equiv> (4 :: nat)"
instance
by (default, auto simp: len_of_finite_3_def)
end
(* Provide wf and less_induct for word.
wf may be more useful in loop proofs, less_induct in recursion proofs. *)
lemma word_less_wf: "wf {(a, b). a < (b :: ('a::len) word)}"
apply (rule wf_subset)
apply (rule wf_measure)
apply safe
apply (subst in_measure)
apply (erule unat_mono)
done
lemma word_less_induct:
"\<lbrakk> \<And>x::('a::len) word. (\<And>y. y < x \<Longrightarrow> P y) \<Longrightarrow> P x \<rbrakk> \<Longrightarrow> P a"
using word_less_wf
apply induct
apply blast
done
instantiation word :: (len) wellorder
begin
instance
apply (intro_classes)
apply (metis word_less_induct)
done
end
lemma word_plus_mono_left:
fixes x :: "'a :: len word"
shows "\<lbrakk>y \<le> z; x \<le> x + z\<rbrakk> \<Longrightarrow> y + x \<le> z + x"
by unat_arith
lemma word_2p_mult_inc:
assumes x: "2 * 2 ^ n < (2::'a::len word) * 2 ^ m"
assumes suc_n: "Suc n < len_of TYPE('a::len)"
assumes suc_m: "Suc m < len_of TYPE('a::len)"
assumes 2: "unat (2::'a::len word) = 2"
shows "2^n < (2::'a::len word)^m"
proof -
from suc_n
have "(2::nat) * 2 ^ n mod 2 ^ len_of TYPE('a::len) = 2 * 2^n"
apply (subst mod_less)
apply (subst power_Suc[symmetric])
apply (rule power_strict_increasing)
apply simp
apply simp
apply simp
done
moreover
from suc_m
have "(2::nat) * 2 ^ m mod 2 ^ len_of TYPE('a::len) = 2 * 2^m"
apply (subst mod_less)
apply (subst power_Suc[symmetric])
apply (rule power_strict_increasing)
apply simp
apply simp
apply simp
done
ultimately
have "2 * 2 ^ n < (2::nat) * 2 ^ m" using x
apply (unfold word_less_nat_alt)
apply simp
apply (subst (asm) unat_word_ariths(2))+
apply (subst (asm) 2)+
apply (subst (asm) word_unat_power, subst (asm) unat_of_nat)+
apply (simp add: mod_mult_right_eq[symmetric])
done
with suc_n suc_m
show ?thesis
unfolding word_less_nat_alt
apply (subst word_unat_power, subst unat_of_nat)+
apply simp
done
qed
lemma word_shiftl_add_distrib:
fixes x :: "'a :: len word"
shows "(x + y) << n = (x << n) + (y << n)"
by (simp add: shiftl_t2n ring_distribs)
lemma upper_bits_unset_is_l2p:
"n < word_bits \<Longrightarrow> (\<forall>n' \<ge> n. n' < word_bits \<longrightarrow> \<not> p !! n') = ((p::word32) < 2 ^ n)"
apply (rule iffI)
prefer 2
apply (clarsimp simp: word_bits_def)
apply (drule bang_is_le)
apply (drule_tac y=p in order_le_less_trans, assumption)
apply (drule word_power_increasing)
apply simp
apply simp
apply simp
apply simp
apply (subst mask_eq_iff_w2p [symmetric])
apply (clarsimp simp: word_size word_bits_def)
apply (rule word_eqI)
apply (clarsimp simp: word_size word_bits_def)
apply (case_tac "na < n", auto)
done
lemma up_ucast_inj:
"\<lbrakk> ucast x = (ucast y::'b::len word); len_of TYPE('a) \<le> len_of TYPE ('b) \<rbrakk> \<Longrightarrow> x = (y::'a::len word)"
apply (subst (asm) bang_eq)
apply (fastforce simp: nth_ucast word_size intro: word_eqI)
done
lemma up_ucast_inj_eq:
"len_of TYPE('a) \<le> len_of TYPE ('b) \<Longrightarrow> (ucast x = (ucast y::'b::len word)) = (x = (y::'a::len word))"
by (fastforce dest: up_ucast_inj)
lemma ucast_up_inj:
"\<lbrakk> ucast x = (ucast y :: 'b::len word); len_of TYPE('a) \<le> len_of TYPE('b) \<rbrakk>
\<Longrightarrow> x = (y :: 'a::len word)"
apply (subst (asm) bang_eq)
apply (rule word_eqI)
apply (simp add: word_size nth_ucast)
apply (erule_tac x=n in allE)
apply simp
done
lemma ucast_8_32_inj:
"inj (ucast :: 8 word \<Rightarrow> 32 word)"
apply (rule down_ucast_inj)
apply (clarsimp simp: is_down_def target_size source_size)
done
lemma no_plus_overflow_neg:
"(x :: ('a :: len) word) < -y \<Longrightarrow> x \<le> x + y"
apply (simp add: no_plus_overflow_uint_size
word_less_alt uint_word_ariths
word_size)
apply (subst(asm) zmod_zminus1_eq_if)
apply (simp split: split_if_asm)
done
lemma ucast_ucast_eq:
fixes x :: "'a::len word"
fixes y :: "'b::len word"
shows
"\<lbrakk> ucast x = (ucast (ucast y::'a::len word)::'c::len word);
len_of TYPE('a) \<le> len_of TYPE('b);
len_of TYPE('b) \<le> len_of TYPE('c) \<rbrakk> \<Longrightarrow>
x = ucast y"
apply (rule word_eqI)
apply (subst (asm) bang_eq)
apply (erule_tac x=n in allE)
apply (simp add: nth_ucast word_size)
done
(******** GeneralLib ****************)
lemma neq_into_nprefixeq:
"\<lbrakk> x \<noteq> take (length x) y \<rbrakk> \<Longrightarrow> \<not> x \<le> y"
by (clarsimp simp: prefixeq_def less_eq_list_def)
lemma suffixeq_drop [simp]:
"suffixeq (drop n as) as"
unfolding suffixeq_def
apply (rule exI [where x = "take n as"])
apply simp
done
lemma suffixeq_eqI:
"\<lbrakk> suffixeq xs as; suffixeq xs bs; length as = length bs;
take (length as - length xs) as \<le> take (length bs - length xs) bs\<rbrakk> \<Longrightarrow> as = bs"
by (clarsimp elim!: prefixE suffixeqE)
lemma suffixeq_Cons_mem:
"suffixeq (x # xs) as \<Longrightarrow> x \<in> set as"
apply (drule suffixeq_set_subset)
apply simp
done
lemma distinct_imply_not_in_tail:
"\<lbrakk> distinct list; suffixeq (y # ys) list\<rbrakk> \<Longrightarrow> y \<notin> set ys"
by (clarsimp simp:suffixeq_def)
lemma list_induct_suffixeq [case_names Nil Cons]:
assumes nilr: "P []"
and consr: "\<And>x xs. \<lbrakk>P xs; suffixeq (x # xs) as \<rbrakk> \<Longrightarrow> P (x # xs)"
shows "P as"
proof -
def as' == as
have "suffixeq as as'" unfolding as'_def by simp
thus ?thesis
proof (induct as)
case Nil show ?case by fact
next
case (Cons x xs)
show ?case
proof (rule consr)
from Cons.prems show "suffixeq (x # xs) as" unfolding as'_def .
hence "suffixeq xs as'" by (auto dest: suffixeq_ConsD simp: as'_def)
thus "P xs" using Cons.hyps by simp
qed
qed
qed
text {* Parallel etc. and lemmas for list prefix *}
lemma prefix_induct [consumes 1, case_names Nil Cons]:
fixes prefix
assumes np: "prefix \<le> lst"
and base: "\<And>xs. P [] xs"
and rl: "\<And>x xs y ys. \<lbrakk> x = y; xs \<le> ys; P xs ys \<rbrakk> \<Longrightarrow> P (x#xs) (y#ys)"
shows "P prefix lst"
using np
proof (induct prefix arbitrary: lst)
case Nil show ?case by fact
next
case (Cons x xs)
have prem: "(x # xs) \<le> lst" by fact
then obtain y ys where lv: "lst = y # ys"
by (rule prefixE, auto)
have ih: "\<And>lst. xs \<le> lst \<Longrightarrow> P xs lst" by fact
show ?case using prem
by (auto simp: lv intro!: rl ih)
qed
lemma not_prefix_cases:
fixes prefix
assumes pfx: "\<not> prefix \<le> lst"
and c1: "\<lbrakk> prefix \<noteq> []; lst = [] \<rbrakk> \<Longrightarrow> R"
and c2: "\<And>a as x xs. \<lbrakk> prefix = a#as; lst = x#xs; x = a; \<not> as \<le> xs\<rbrakk> \<Longrightarrow> R"
and c3: "\<And>a as x xs. \<lbrakk> prefix = a#as; lst = x#xs; x \<noteq> a\<rbrakk> \<Longrightarrow> R"
shows "R"
proof (cases prefix)
case Nil thus ?thesis using pfx by simp
next
case (Cons a as)
have c: "prefix = a#as" by fact
show ?thesis
proof (cases lst)
case Nil thus ?thesis
by (intro c1, simp add: Cons)
next
case (Cons x xs)
show ?thesis
proof (cases "x = a")
case True
show ?thesis
proof (intro c2)
show "\<not> as \<le> xs" using pfx c Cons True
by simp
qed fact+
next
case False
show ?thesis by (rule c3) fact+
qed
qed
qed
lemma not_prefix_induct [consumes 1, case_names Nil Neq Eq]:
fixes prefix
assumes np: "\<not> prefix \<le> lst"
and base: "\<And>x xs. P (x#xs) []"
and r1: "\<And>x xs y ys. x \<noteq> y \<Longrightarrow> P (x#xs) (y#ys)"
and r2: "\<And>x xs y ys. \<lbrakk> x = y; \<not> xs \<le> ys; P xs ys \<rbrakk> \<Longrightarrow> P (x#xs) (y#ys)"
shows "P prefix lst"
using np
proof (induct lst arbitrary: prefix)
case Nil thus ?case
by (auto simp: neq_Nil_conv elim!: not_prefix_cases intro!: base)
next
case (Cons y ys)
have npfx: "\<not> prefix \<le> (y # ys)" by fact
then obtain x xs where pv: "prefix = x # xs"
by (rule not_prefix_cases) auto
have ih: "\<And>prefix. \<not> prefix \<le> ys \<Longrightarrow> P prefix ys" by fact
show ?case using npfx
by (simp only: pv) (erule not_prefix_cases, auto intro: r1 r2 ih)
qed
text {* right-padding a word to a certain length *}
lemma bl_pad_to_prefix:
"bl \<le> bl_pad_to bl sz"
by (simp add: bl_pad_to_def)
lemma same_length_is_parallel:
assumes len: "\<forall>y \<in> set as. length y = x"
shows "\<forall>x \<in> set as. \<forall>y \<in> set as - {x}. x \<parallel> y"
proof (rule, rule)
fix x y
assume xi: "x \<in> set as" and yi: "y \<in> set as - {x}"
from len obtain q where len': "\<forall>y \<in> set as. length y = q" ..
show "x \<parallel> y"
proof (rule not_equal_is_parallel)
from xi yi show "x \<noteq> y" by auto
from xi yi len' show "length x = length y" by (auto dest: bspec)
qed
qed
text {* Lemmas about words *}
lemma word_bits_len_of: "len_of TYPE (32) = word_bits"
by (simp add: word_bits_conv)
lemmas unat_power_lower32 [simp] = unat_power_lower[where 'a=32, unfolded word_bits_len_of]
lemmas and_bang = word_and_nth
lemma of_drop_to_bl:
"of_bl (drop n (to_bl x)) = (x && mask (size x - n))"
apply (clarsimp simp: bang_eq test_bit_of_bl rev_nth cong: rev_conj_cong)
apply (safe, simp_all add: word_size to_bl_nth)
done
lemma word_add_offset_less:
fixes x :: "'a :: len word"
assumes yv: "y < 2 ^ n"
and xv: "x < 2 ^ m"
and mnv: "sz < len_of TYPE('a :: len)"
and xv': "x < 2 ^ (len_of TYPE('a :: len) - n)"
and mn: "sz = m + n"
shows "x * 2 ^ n + y < 2 ^ sz"
proof (subst mn)
from mnv mn have nv: "n < len_of TYPE('a)" and mv: "m < len_of TYPE('a)" by auto
have uy: "unat y < 2 ^ n"
by (rule order_less_le_trans [OF unat_mono [OF yv] order_eq_refl],
rule unat_power_lower[OF nv])
have ux: "unat x < 2 ^ m"
by (rule order_less_le_trans [OF unat_mono [OF xv] order_eq_refl],
rule unat_power_lower[OF mv])
thus "x * 2 ^ n + y < 2 ^ (m + n)" using ux uy nv mnv xv'
apply (subst word_less_nat_alt)
apply (subst unat_word_ariths word_bits_len_of)+
apply (subst mod_less)
apply simp
apply (subst mult.commute)
apply (rule nat_less_power_trans [OF _ order_less_imp_le [OF nv]])
apply (rule order_less_le_trans [OF unat_mono [OF xv']])
apply (cases "n = 0")
apply simp
apply simp
apply (subst unat_power_lower[OF nv])
apply (subst mod_less)
apply (erule order_less_le_trans [OF nat_add_offset_less], assumption)
apply (rule mn)
apply simp
apply (simp add: mn mnv)
apply (erule nat_add_offset_less)
apply simp+
done
qed
lemma word_less_power_trans:
fixes n :: "'a :: len word"
assumes nv: "n < 2 ^ (m - k)"
and kv: "k \<le> m"
and mv: "m < len_of TYPE ('a)"
shows "2 ^ k * n < 2 ^ m"
using nv kv mv
apply -
apply (subst word_less_nat_alt)
apply (subst unat_word_ariths)
apply (subst mod_less)
apply simp
apply (rule nat_less_power_trans)
apply (erule order_less_trans [OF unat_mono])
apply simp
apply simp
apply simp
apply (rule nat_less_power_trans)
apply (subst unat_power_lower[where 'a = 'a, symmetric])
apply simp
apply (erule unat_mono)
apply simp
done
lemma word_less_sub_le[simp]:
fixes x :: "'a :: len word"
assumes nv: "n < len_of TYPE('a)"
shows "(x \<le> 2 ^ n - 1) = (x < 2 ^ n)"
proof -
have "Suc (unat ((2::'a word) ^ n - 1)) = unat ((2::'a word) ^ n)" using nv
by (metis Suc_pred' power_2_ge_iff unat_gt_0 unat_minus_one word_not_simps(1))
thus ?thesis using nv
apply -
apply (subst word_le_nat_alt)
apply (subst less_Suc_eq_le [symmetric])
apply (erule ssubst)
apply (subst word_less_nat_alt)
apply (rule refl)
done
qed
lemmas word32_less_sub_le[simp] =
word_less_sub_le[where 'a = 32, folded word_bits_def]
lemma Suc_unat_diff_1:
fixes x :: "'a :: len word"
assumes lt: "1 \<le> x"
shows "Suc (unat (x - 1)) = unat x"
proof -
have "0 < unat x"
by (rule order_less_le_trans [where y = 1], simp, subst unat_1 [symmetric], rule iffD1 [OF word_le_nat_alt lt])
thus ?thesis
by ((subst unat_sub [OF lt])+, simp only: unat_1)
qed
lemma word_div_sub:
fixes x :: "'a :: len word"
assumes yx: "y \<le> x"
and y0: "0 < y"
shows "(x - y) div y = x div y - 1"
apply (rule word_unat.Rep_eqD)
apply (subst unat_div)
apply (subst unat_sub [OF yx])
apply (subst unat_sub)
apply (subst word_le_nat_alt)
apply (subst unat_div)
apply (subst le_div_geq)
apply (rule order_le_less_trans [OF _ unat_mono [OF y0]])
apply simp
apply (subst word_le_nat_alt [symmetric], rule yx)
apply simp
apply (subst unat_div)
apply (subst le_div_geq [OF _ iffD1 [OF word_le_nat_alt yx]])
apply (rule order_le_less_trans [OF _ unat_mono [OF y0]])
apply simp
apply simp
done
lemma word_mult_less_mono1:
fixes i :: "'a :: len word"
assumes ij: "i < j"
and knz: "0 < k"
and ujk: "unat j * unat k < 2 ^ len_of TYPE ('a)"
shows "i * k < j * k"
proof -
from ij ujk knz have jk: "unat i * unat k < 2 ^ len_of TYPE ('a)"
by (auto intro: order_less_subst2 simp: word_less_nat_alt elim: mult_less_mono1)
thus ?thesis using ujk knz ij
by (auto simp: word_less_nat_alt iffD1 [OF unat_mult_lem])
qed
lemma word_mult_less_dest:
fixes i :: "'a :: len word"
assumes ij: "i * k < j * k"
and uik: "unat i * unat k < 2 ^ len_of TYPE ('a)"
and ujk: "unat j * unat k < 2 ^ len_of TYPE ('a)"
shows "i < j"
using uik ujk ij
by (auto simp: word_less_nat_alt iffD1 [OF unat_mult_lem] elim: mult_less_mono1)
lemma word_mult_less_cancel:
fixes k :: "'a :: len word"
assumes knz: "0 < k"
and uik: "unat i * unat k < 2 ^ len_of TYPE ('a)"
and ujk: "unat j * unat k < 2 ^ len_of TYPE ('a)"
shows "(i * k < j * k) = (i < j)"
by (rule iffI [OF word_mult_less_dest [OF _ uik ujk] word_mult_less_mono1 [OF _ knz ujk]])
lemma Suc_div_unat_helper:
assumes szv: "sz < len_of TYPE('a :: len)"
and usszv: "us \<le> sz"
shows "2 ^ (sz - us) = Suc (unat (((2::'a :: len word) ^ sz - 1) div 2 ^ us))"
proof -
note usv = order_le_less_trans [OF usszv szv]
from usszv obtain q where qv: "sz = us + q" by (auto simp: le_iff_add)
have "Suc (unat (((2:: 'a word) ^ sz - 1) div 2 ^ us)) =
(2 ^ us + unat ((2:: 'a word) ^ sz - 1)) div 2 ^ us"
apply (subst unat_div unat_power_lower[OF usv])+
apply (subst div_add_self1, simp+)
done
also have "\<dots> = ((2 ^ us - 1) + 2 ^ sz) div 2 ^ us" using szv
apply (subst unat_minus_one)
apply (simp add: p2_eq_0)
apply simp
done
also have "\<dots> = 2 ^ q + ((2 ^ us - 1) div 2 ^ us)"
apply (subst qv)
apply (subst power_add)
apply (subst div_mult_self2)
apply simp
apply (rule refl)
done
also have "\<dots> = 2 ^ (sz - us)" using qv by simp
finally show ?thesis ..
qed
lemma upto_enum_red':
assumes lt: "1 \<le> X"
shows "[(0::'a :: len word) .e. X - 1] = map of_nat [0 ..< unat X]"
proof -
have lt': "unat X < 2 ^ len_of TYPE('a)"
by (rule unat_lt2p)
show ?thesis
apply (subst upto_enum_red)
apply (simp del: upt.simps)
apply (subst Suc_unat_diff_1 [OF lt])
apply (rule map_cong [OF refl])
apply (rule toEnum_of_nat)
apply simp
apply (erule order_less_trans [OF _ lt'])
done
qed
lemma upto_enum_red2:
assumes szv: "sz < len_of TYPE('a :: len)"
shows "[(0:: 'a :: len word) .e. 2 ^ sz - 1] =
map of_nat [0 ..< 2 ^ sz]" using szv
apply (subst unat_power_lower[OF szv, symmetric])
apply (rule upto_enum_red')
apply (subst word_le_nat_alt, simp)
done
(* FIXME: WordEnum.upto_enum_step_def is fixed to word32. *)
lemma upto_enum_step_red:
assumes szv: "sz < word_bits"
and usszv: "us \<le> sz"
shows "[0 , 2 ^ us .e. 2 ^ sz - 1] =
map (\<lambda>x. of_nat x * 2 ^ us) [0 ..< 2 ^ (sz - us)]" using szv
unfolding upto_enum_step_def
apply (subst if_not_P)
apply (rule leD)
apply (subst word_le_nat_alt)
apply (subst unat_minus_one)
apply (simp add: p2_eq_0 word_bits_def)
apply simp
apply simp
apply (subst upto_enum_red)
apply (simp del: upt.simps)
apply (subst Suc_div_unat_helper [where 'a = 32, folded word_bits_def, OF szv usszv, symmetric])
apply clarsimp
apply (subst toEnum_of_nat)
apply (subst word_bits_len_of)
apply (erule order_less_trans)
using szv
apply simp
apply simp
done
lemma upto_enum_word:
"[x .e. y] = map of_nat [unat x ..< Suc (unat y)]"
apply (subst upto_enum_red)
apply clarsimp
apply (subst toEnum_of_nat)
prefer 2
apply (rule refl)
apply (erule disjE, simp)
apply clarsimp
apply (erule order_less_trans)
apply simp
done
text {* Lemmas about upto and upto_enum *}
lemma word_upto_Cons_eq:
"\<lbrakk>x = z; x < y; Suc (unat y) < 2 ^ len_of TYPE('a)\<rbrakk>
\<Longrightarrow> [x::'a::len word .e. y] = z # [x + 1 .e. y]"
apply (subst upto_enum_red)
apply (subst upt_conv_Cons)
apply (simp)
apply (drule unat_mono)
apply arith
apply (simp only: list.map)
apply (subst list.inject)
apply rule
apply (rule to_from_enum)
apply (subst upto_enum_red)
apply (rule map_cong [OF _ refl])
apply (rule arg_cong2 [where f = "\<lambda>x y. [x ..< y]"])
apply unat_arith
apply simp
done
lemma distinct_enum_upto:
"distinct [(0 :: 'a::len word) .e. b]"
proof -
have "\<And>(b::'a word). [0 .e. b] = sublist enum {..< Suc (fromEnum b)}"
apply (subst upto_enum_red)
apply (subst sublist_upt_eq_take)
apply (subst enum_word_def)
apply (subst take_map)
apply (subst take_upt)
apply (simp only: add_0 fromEnum_unat)
apply (rule order_trans [OF _ order_eq_refl])
apply (rule Suc_leI [OF unat_lt2p])
apply simp
apply clarsimp
apply (rule toEnum_of_nat)
apply (erule order_less_trans [OF _ unat_lt2p])
done
thus ?thesis
by (rule ssubst) (rule distinct_sublistI, simp)
qed
lemma upto_enum_set_conv [simp]:
fixes a :: "'a :: len word"
shows "set [a .e. b] = {x. a \<le> x \<and> x \<le> b}"
apply (subst upto_enum_red)
apply (subst set_map)
apply safe
apply simp
apply clarsimp
apply (erule disjE)
apply simp
apply (erule iffD2 [OF word_le_nat_alt])
apply clarsimp
apply (erule word_unat.Rep_cases [OF unat_le [OF order_less_imp_le]])
apply simp
apply (erule iffD2 [OF word_le_nat_alt])
apply simp
apply clarsimp
apply (erule disjE)
apply simp
apply clarsimp
apply (rule word_unat.Rep_cases [OF unat_le [OF order_less_imp_le]])
apply assumption
apply simp
apply (erule order_less_imp_le [OF iffD2 [OF word_less_nat_alt]])
apply clarsimp
apply (rule_tac x="fromEnum x" in image_eqI)
apply clarsimp
apply clarsimp
apply (rule conjI)
apply (subst word_le_nat_alt [symmetric])
apply simp
apply safe
apply (simp add: word_le_nat_alt [symmetric])
apply (simp add: word_less_nat_alt [symmetric])
done
lemma upto_enum_less:
assumes xin: "x \<in> set [(a::'a::len word).e.2 ^ n - 1]"
and nv: "n < len_of TYPE('a::len)"
shows "x < 2 ^ n"
proof (cases n)
case 0
thus ?thesis using xin by simp
next
case (Suc m)
show ?thesis using xin nv by simp
qed
lemma upto_enum_len_less:
"\<lbrakk> n \<le> length [a, b .e. c]; n \<noteq> 0 \<rbrakk> \<Longrightarrow> a \<le> c"
unfolding upto_enum_step_def
by (simp split: split_if_asm)
lemma length_upto_enum_step:
fixes x :: word32
shows "x \<le> z \<Longrightarrow> length [x , y .e. z] = (unat ((z - x) div (y - x))) + 1"
unfolding upto_enum_step_def
by (simp add: upto_enum_red)
lemma length_upto_enum_one:
fixes x :: word32
assumes lt1: "x < y" and lt2: "z < y" and lt3: "x \<le> z"
shows "[x , y .e. z] = [x]"
unfolding upto_enum_step_def
proof (subst upto_enum_red, subst if_not_P [OF leD [OF lt3]], clarsimp, rule)
show "unat ((z - x) div (y - x)) = 0"
proof (subst unat_div, rule div_less)
have syx: "unat (y - x) = unat y - unat x"
by (rule unat_sub [OF order_less_imp_le]) fact
moreover have "unat (z - x) = unat z - unat x"
by (rule unat_sub) fact
ultimately show "unat (z - x) < unat (y - x)"
using lt3
apply simp
apply (rule diff_less_mono[OF unat_mono, OF lt2])
apply (simp add: word_le_nat_alt[symmetric])
done
qed
thus "toEnum (unat ((z - x) div (y - x))) * (y - x) = 0" by simp
qed
lemma map_length_unfold_one:
fixes x :: "'a::len word"
assumes xv: "Suc (unat x) < 2 ^ len_of TYPE('a)"
and ax: "a < x"
shows "map f [a .e. x] = f a # map f [a + 1 .e. x]"
by (subst word_upto_Cons_eq, auto, fact+)
lemma upto_enum_triv [simp]:
"[x .e. x] = [x]"
unfolding upto_enum_def by simp
lemma of_nat_unat [simp]:
"of_nat \<circ> unat = id"
by (rule ext, simp)
lemma Suc_unat_minus_one [simp]:
"x \<noteq> 0 \<Longrightarrow> Suc (unat (x - 1)) = unat x"
by (metis Suc_diff_1 unat_gt_0 unat_minus_one)
text {* Lemmas about alignment *}
lemma word_bits_size:
"size (w::word32) = word_bits"
by (simp add: word_bits_def word_size)
text {* Lemmas about defs in the specs *}
lemma and_commute:
"(X and Y) = (Y and X)"
unfolding pred_conj_def by (auto simp: fun_eq_iff)
lemma ptr_add_0 [simp]:
"ptr_add ref 0 = ref "
unfolding ptr_add_def by simp
(* Other word lemmas *)
lemma word_add_le_dest:
fixes i :: "'a :: len word"
assumes le: "i + k \<le> j + k"
and uik: "unat i + unat k < 2 ^ len_of TYPE ('a)"
and ujk: "unat j + unat k < 2 ^ len_of TYPE ('a)"
shows "i \<le> j"
using uik ujk le
by (auto simp: word_le_nat_alt iffD1 [OF unat_add_lem] elim: add_le_mono1)
lemma mask_shift:
"(x && ~~ mask y) >> y = x >> y"
apply (rule word_eqI)
apply (simp add: nth_shiftr word_size)
apply safe
apply (drule test_bit.Rep[simplified, rule_format])
apply (simp add: word_size word_ops_nth_size)
done
lemma word_add_le_mono1:
fixes i :: "'a :: len word"
assumes ij: "i \<le> j"
and ujk: "unat j + unat k < 2 ^ len_of TYPE ('a)"
shows "i + k \<le> j + k"
proof -
from ij ujk have jk: "unat i + unat k < 2 ^ len_of TYPE ('a)"
by (auto elim: order_le_less_subst2 simp: word_le_nat_alt elim: add_le_mono1)
thus ?thesis using ujk ij
by (auto simp: word_le_nat_alt iffD1 [OF unat_add_lem])
qed
lemma word_add_le_mono2:
fixes i :: "('a :: len) word"
shows "\<lbrakk>i \<le> j; unat j + unat k < 2 ^ len_of TYPE('a)\<rbrakk> \<Longrightarrow> k + i \<le> k + j"
by (subst field_simps, subst field_simps, erule (1) word_add_le_mono1)
lemma word_add_le_iff:
fixes i :: "'a :: len word"
assumes uik: "unat i + unat k < 2 ^ len_of TYPE ('a)"
and ujk: "unat j + unat k < 2 ^ len_of TYPE ('a)"
shows "(i + k \<le> j + k) = (i \<le> j)"
proof
assume "i \<le> j"
show "i + k \<le> j + k" by (rule word_add_le_mono1) fact+
next
assume "i + k \<le> j + k"
show "i \<le> j" by (rule word_add_le_dest) fact+
qed
lemma word_add_less_mono1:
fixes i :: "'a :: len word"
assumes ij: "i < j"
and ujk: "unat j + unat k < 2 ^ len_of TYPE ('a)"
shows "i + k < j + k"
proof -
from ij ujk have jk: "unat i + unat k < 2 ^ len_of TYPE ('a)"
by (auto elim: order_le_less_subst2 simp: word_less_nat_alt elim: add_less_mono1)
thus ?thesis using ujk ij
by (auto simp: word_less_nat_alt iffD1 [OF unat_add_lem])
qed
lemma word_add_less_dest:
fixes i :: "'a :: len word"
assumes le: "i + k < j + k"
and uik: "unat i + unat k < 2 ^ len_of TYPE ('a)"
and ujk: "unat j + unat k < 2 ^ len_of TYPE ('a)"
shows "i < j"
using uik ujk le
by (auto simp: word_less_nat_alt iffD1 [OF unat_add_lem] elim: add_less_mono1)
lemma word_add_less_iff:
fixes i :: "'a :: len word"
assumes uik: "unat i + unat k < 2 ^ len_of TYPE ('a)"
and ujk: "unat j + unat k < 2 ^ len_of TYPE ('a)"
shows "(i + k < j + k) = (i < j)"
proof
assume "i < j"
show "i + k < j + k" by (rule word_add_less_mono1) fact+
next
assume "i + k < j + k"
show "i < j" by (rule word_add_less_dest) fact+
qed
lemma shiftr_div_2n':
"unat (w >> n) = unat w div 2 ^ n"
apply (unfold unat_def)
apply (subst shiftr_div_2n)
apply (subst nat_div_distrib)
apply simp
apply (simp add: nat_power_eq)
done
lemma shiftl_shiftr_id:
assumes nv: "n < len_of TYPE('a :: len)"
and xv: "x < 2 ^ (len_of TYPE('a :: len) - n)"
shows "x << n >> n = (x::'a::len word)"
apply (simp add: shiftl_t2n)
apply (rule word_unat.Rep_eqD)
apply (subst shiftr_div_2n')
apply (cases n)
apply simp
apply (subst iffD1 [OF unat_mult_lem])+
apply (subst unat_power_lower[OF nv])
apply (rule nat_less_power_trans [OF _ order_less_imp_le [OF nv]])
apply (rule order_less_le_trans [OF unat_mono [OF xv] order_eq_refl])
apply (rule unat_power_lower)
apply simp
apply (subst unat_power_lower[OF nv])
apply simp
done
lemma word_mult_less_iff:
fixes i :: "'a :: len word"
assumes knz: "0 < k"
and uik: "unat i * unat k < 2 ^ len_of TYPE ('a)"
and ujk: "unat j * unat k < 2 ^ len_of TYPE ('a)"
shows "(i * k < j * k) = (i < j)"
proof
assume "i < j"
show "i * k < j * k" by (rule word_mult_less_mono1) fact+
next
assume p: "i * k < j * k"
have "0 < unat k" using knz by (simp add: word_less_nat_alt)
thus "i < j" using p
by (clarsimp simp: word_less_nat_alt iffD1 [OF unat_mult_lem uik]
iffD1 [OF unat_mult_lem ujk])
qed
lemma word_le_imp_diff_le:
fixes n :: "'a::len word"
shows "\<lbrakk>k \<le> n; n \<le> m\<rbrakk> \<Longrightarrow> n - k \<le> m"
by (clarsimp simp: unat_sub word_le_nat_alt intro!: le_imp_diff_le)
lemma word_less_imp_diff_less:
fixes n :: "'a::len word"
shows "\<lbrakk>k \<le> n; n < m\<rbrakk> \<Longrightarrow> n - k < m"
by (clarsimp simp: unat_sub word_less_nat_alt
intro!: less_imp_diff_less)
lemma word_mult_le_mono1:
fixes i :: "'a :: len word"
assumes ij: "i \<le> j"
and knz: "0 < k"
and ujk: "unat j * unat k < 2 ^ len_of TYPE ('a)"
shows "i * k \<le> j * k"
proof -
from ij ujk knz have jk: "unat i * unat k < 2 ^ len_of TYPE ('a)"
by (auto elim: order_le_less_subst2 simp: word_le_nat_alt elim: mult_le_mono1)
thus ?thesis using ujk knz ij
by (auto simp: word_le_nat_alt iffD1 [OF unat_mult_lem])
qed
lemma word_mult_le_iff:
fixes i :: "'a :: len word"
assumes knz: "0 < k"
and uik: "unat i * unat k < 2 ^ len_of TYPE ('a)"
and ujk: "unat j * unat k < 2 ^ len_of TYPE ('a)"
shows "(i * k \<le> j * k) = (i \<le> j)"
proof
assume "i \<le> j"
show "i * k \<le> j * k" by (rule word_mult_le_mono1) fact+
next
assume p: "i * k \<le> j * k"
have "0 < unat k" using knz by (simp add: word_less_nat_alt)
thus "i \<le> j" using p
by (clarsimp simp: word_le_nat_alt iffD1 [OF unat_mult_lem uik]
iffD1 [OF unat_mult_lem ujk])
qed
lemma word_diff_less:
fixes n :: "'a :: len word"
shows "\<lbrakk>0 < n; 0 < m; n \<le> m\<rbrakk> \<Longrightarrow> m - n < m"
apply (subst word_less_nat_alt)
apply (subst unat_sub)
apply assumption
apply (rule diff_less)
apply (simp_all add: word_less_nat_alt)
done
lemma MinI:
assumes fa: "finite A"
and ne: "A \<noteq> {}"
and xv: "m \<in> A"
and min: "\<forall>y \<in> A. m \<le> y"
shows "Min A = m" using fa ne xv min
proof (induct A arbitrary: m rule: finite_ne_induct)
case singleton thus ?case by simp
next
case (insert y F)
from insert.prems have yx: "m \<le> y" and fx: "\<forall>y \<in> F. m \<le> y" by auto
have "m \<in> insert y F" by fact
thus ?case
proof
assume mv: "m = y"
have mlt: "m \<le> Min F"
by (rule iffD2 [OF Min_ge_iff [OF insert.hyps(1) insert.hyps(2)] fx])
show ?case
apply (subst Min_insert [OF insert.hyps(1) insert.hyps(2)])
apply (subst mv [symmetric])
apply (rule iffD2 [OF linorder_min_same1 mlt])
done
next
assume "m \<in> F"
hence mf: "Min F = m"
by (rule insert.hyps(4) [OF _ fx])
show ?case
apply (subst Min_insert [OF insert.hyps(1) insert.hyps(2)])
apply (subst mf)
apply (rule iffD2 [OF linorder_min_same2 yx])
done
qed
qed
lemma length_upto_enum [simp]:
fixes a :: "('a :: len) word"
shows "length [a .e. b] = Suc (unat b) - unat a"
apply (simp add: word_le_nat_alt upto_enum_red)
apply (clarsimp simp: Suc_diff_le)
done
lemma length_upto_enum_less_one:
"\<lbrakk>a \<le> b; b \<noteq> 0\<rbrakk>
\<Longrightarrow> length [a .e. b - 1] = unat (b - a)"
apply clarsimp
apply (subst unat_sub[symmetric], assumption)
apply clarsimp
done
lemma drop_upto_enum:
"drop (unat n) [0 .e. m] = [n .e. m]"
apply (clarsimp simp: upto_enum_def)
apply (induct m, simp)
by (metis drop_map drop_upt plus_nat.add_0)
lemma distinct_enum_upto' [simp]:
"distinct [a::'a::len word .e. b]"
apply (subst drop_upto_enum [symmetric])
apply (rule distinct_drop)
apply (rule distinct_enum_upto)
done
lemma length_interval:
"\<lbrakk>set xs = {x. (a::'a::len word) \<le> x \<and> x \<le> b}; distinct xs\<rbrakk>
\<Longrightarrow> length xs = Suc (unat b) - unat a"
apply (frule distinct_card)
apply (subgoal_tac "set xs = set [a .e. b]")
apply (cut_tac distinct_card [where xs="[a .e. b]"])
apply (subst (asm) length_upto_enum)
apply clarsimp
apply (rule distinct_enum_upto')
apply simp
done
lemma not_empty_eq:
"(S \<noteq> {}) = (\<exists>x. x \<in> S)"
by auto
lemma range_subset_lower:
fixes c :: "'a ::linorder"
shows "\<lbrakk> {a..b} \<subseteq> {c..d}; x \<in> {a..b} \<rbrakk> \<Longrightarrow> c \<le> a"
apply (frule (1) subsetD)
apply (rule classical)
apply clarsimp
done
lemma range_subset_upper:
fixes c :: "'a ::linorder"
shows "\<lbrakk> {a..b} \<subseteq> {c..d}; x \<in> {a..b} \<rbrakk> \<Longrightarrow> b \<le> d"
apply (frule (1) subsetD)
apply (rule classical)
apply clarsimp
done
lemma range_subset_eq:
fixes a::"'a::linorder"
assumes non_empty: "a \<le> b"
shows "({a..b} \<subseteq> {c..d}) = (c \<le> a \<and> b \<le> d)"
apply (insert non_empty)
apply (rule iffI)
apply (frule range_subset_lower [where x=a], simp)
apply (drule range_subset_upper [where x=a], simp)
apply simp
apply auto
done
lemma range_eq:
fixes a::"'a::linorder"
assumes non_empty: "a \<le> b"
shows "({a..b} = {c..d}) = (a = c \<and> b = d)"
by (metis atLeastatMost_subset_iff eq_iff non_empty)
lemma range_strict_subset_eq:
fixes a::"'a::linorder"
assumes non_empty: "a \<le> b"
shows "({a..b} \<subset> {c..d}) = (c \<le> a \<and> b \<le> d \<and> (a = c \<longrightarrow> b \<noteq> d))"
apply (insert non_empty)
apply (subst psubset_eq)
apply (subst range_subset_eq, assumption+)
apply (subst range_eq, assumption+)
apply simp
done
lemma range_subsetI:
fixes x :: "'a :: order"
assumes xX: "X \<le> x"
and yY: "y \<le> Y"
shows "{x .. y} \<subseteq> {X .. Y}"
using xX yY by auto
lemma set_False [simp]:
"(set bs \<subseteq> {False}) = (True \<notin> set bs)" by auto
declare of_nat_power [simp del]
(* TODO: move to word *)
lemma unat_of_bl_length:
"unat (of_bl xs :: 'a::len word) < 2 ^ (length xs)"
proof (cases "length xs < len_of TYPE('a)")
case True
hence "(of_bl xs::'a::len word) < 2 ^ length xs"
by (simp add: of_bl_length_less)
with True
show ?thesis
by (simp add: word_less_nat_alt word_unat_power unat_of_nat)
next
case False
have "unat (of_bl xs::'a::len word) < 2 ^ len_of TYPE('a)"
by (simp split: unat_split)
also
from False
have "len_of TYPE('a) \<le> length xs" by simp
hence "2 ^ len_of TYPE('a) \<le> (2::nat) ^ length xs"
by (rule power_increasing) simp
finally
show ?thesis .
qed
lemma is_aligned_0'[simp]:
"is_aligned 0 n"
by (simp add: is_aligned_def)
lemma p_assoc_help:
fixes p :: "'a::{ring,power,numeral,one}"
shows "p + 2^sz - 1 = p + (2^sz - 1)"
by simp
lemma word_add_increasing:
fixes x :: "'a :: len word"
shows "\<lbrakk> p + w \<le> x; p \<le> p + w \<rbrakk> \<Longrightarrow> p \<le> x"
by unat_arith
lemma word_random:
fixes x :: "'a :: len word"
shows "\<lbrakk> p \<le> p + x'; x \<le> x' \<rbrakk> \<Longrightarrow> p \<le> p + x"
by unat_arith
lemma word_sub_mono:
"\<lbrakk> a \<le> c; d \<le> b; a - b \<le> a; c - d \<le> c \<rbrakk>
\<Longrightarrow> (a - b) \<le> (c - d :: ('a :: len) word)"
by unat_arith
lemma power_not_zero:
"n < len_of TYPE('a::len) \<Longrightarrow> (2 :: 'a word) ^ n \<noteq> 0"
by (metis p2_gt_0 word_neq_0_conv)
lemma word_gt_a_gt_0:
"a < n \<Longrightarrow> (0 :: 'a::len word) < n"
apply (case_tac "n = 0")
apply clarsimp
apply (clarsimp simp: word_neq_0_conv)
done
lemma word_shift_nonzero:
"\<lbrakk> (x\<Colon>'a\<Colon>len word) \<le> 2 ^ m; m + n < len_of TYPE('a\<Colon>len); x \<noteq> 0\<rbrakk>
\<Longrightarrow> x << n \<noteq> 0"
apply (simp only: word_neq_0_conv word_less_nat_alt
shiftl_t2n mod_0 unat_word_ariths
unat_power_lower word_le_nat_alt)
apply (subst mod_less)
apply (rule order_le_less_trans)
apply (erule mult_le_mono2)
apply (subst power_add[symmetric])
apply (rule power_strict_increasing)
apply simp
apply simp
apply simp
done
lemma word_power_less_1 [simp]:
"sz < len_of TYPE('a\<Colon>len) \<Longrightarrow> (2::'a word) ^ sz - 1 < 2 ^ sz"
apply (simp add: word_less_nat_alt word_bits_def)
apply (subst unat_minus_one)
apply (simp add: word_unat.Rep_inject [symmetric])
apply simp
done
lemmas word32_power_less_1[simp] =
word_power_less_1[where 'a = 32, folded word_bits_def]
lemma nasty_split_lt:
"\<lbrakk> (x :: 'a:: len word) < 2 ^ (m - n); n \<le> m; m < len_of TYPE('a\<Colon>len) \<rbrakk>
\<Longrightarrow> x * 2 ^ n + (2 ^ n - 1) \<le> 2 ^ m - 1"
apply (simp only: add_diff_eq word_bits_def)
apply (subst mult_1[symmetric], subst distrib_right[symmetric])
apply (rule word_sub_mono)
apply (rule order_trans)
apply (rule word_mult_le_mono1)
apply (rule inc_le)
apply assumption
apply (subst word_neq_0_conv[symmetric])
apply (rule power_not_zero)
apply (simp add: word_bits_def)
apply (subst unat_power_lower, simp)+
apply (subst power_add[symmetric])
apply (rule power_strict_increasing)
apply (simp add: word_bits_def)
apply simp
apply (subst power_add[symmetric])
apply simp
apply simp
apply (rule word_sub_1_le)
apply (subst mult.commute)
apply (subst shiftl_t2n[symmetric])
apply (rule word_shift_nonzero)
apply (erule inc_le)
apply (simp add: word_bits_def)
apply (unat_arith)
apply (drule word_power_less_1[unfolded word_bits_def])
apply simp
done
lemma nasty_split_less:
"\<lbrakk>m \<le> n; n \<le> nm; nm < len_of TYPE('a\<Colon>len); x < 2 ^ (nm - n)\<rbrakk>
\<Longrightarrow> (x :: 'a word) * 2 ^ n + (2 ^ m - 1) < 2 ^ nm"
apply (simp only: word_less_sub_le[symmetric])
apply (rule order_trans [OF _ nasty_split_lt])
apply (rule word_plus_mono_right)
apply (rule word_sub_mono)
apply (simp add: word_le_nat_alt)
apply simp
apply (simp add: word_sub_1_le[OF power_not_zero])
apply (simp add: word_sub_1_le[OF power_not_zero])
apply (rule is_aligned_no_wrap')
apply (rule is_aligned_mult_triv2)
apply simp
apply (erule order_le_less_trans, simp)
apply simp+
done
lemma int_not_emptyD:
"A \<inter> B \<noteq> {} \<Longrightarrow> \<exists>x. x \<in> A \<and> x \<in> B"
by (erule contrapos_np, clarsimp simp: disjoint_iff_not_equal)
lemma unat_less_power:
fixes k :: "'a::len word"
assumes szv: "sz < len_of TYPE('a)"
and kv: "k < 2 ^ sz"
shows "unat k < 2 ^ sz"
using szv unat_mono [OF kv] by simp
(* This should replace some crud \<dots> search for unat_of_nat *)
lemma unat_mult_power_lem:
assumes kv: "k < 2 ^ (len_of TYPE('a::len) - sz)"
shows "unat (2 ^ sz * of_nat k :: (('a::len) word)) = 2 ^ sz * k"
proof cases
assume szv: "sz < len_of TYPE('a::len)"
show ?thesis
proof (cases "sz = 0")
case True
thus ?thesis using kv szv
by (simp add: unat_of_nat)
next
case False
hence sne: "0 < sz" ..
have uk: "unat (of_nat k :: 'a word) = k"
apply (subst unat_of_nat)
apply (simp add: nat_mod_eq less_trans[OF kv] sne)
done
show ?thesis using szv
apply (subst iffD1 [OF unat_mult_lem])
apply (simp add: uk nat_less_power_trans[OF kv order_less_imp_le [OF szv]])+
done
qed
next
assume "\<not> sz < len_of TYPE('a)"
with kv show ?thesis by (simp add: not_less power_overflow)
qed
lemma aligned_add_offset_no_wrap:
fixes off :: "('a::len) word"
and x :: "'a word"
assumes al: "is_aligned x sz"
and offv: "off < 2 ^ sz"
shows "unat x + unat off < 2 ^ len_of TYPE('a)"
proof cases
assume szv: "sz < len_of TYPE('a)"
from al obtain k where xv: "x = 2 ^ sz * (of_nat k)"
and kl: "k < 2 ^ (len_of TYPE('a) - sz)"
by (auto elim: is_alignedE)
show ?thesis using szv
apply (subst xv)
apply (subst unat_mult_power_lem[OF kl])
apply (subst mult.commute, rule nat_add_offset_less)
apply (rule less_le_trans[OF unat_mono[OF offv, simplified]])
apply (erule eq_imp_le[OF unat_power_lower])
apply (rule kl)
apply simp
done
next
assume "\<not> sz < len_of TYPE('a)"
with offv show ?thesis by (simp add: not_less power_overflow )
qed
lemma aligned_add_offset_mod:
fixes x :: "('a::len) word"
assumes al: "is_aligned x sz"
and kv: "k < 2 ^ sz"
shows "(x + k) mod 2 ^ sz = k"
proof cases
assume szv: "sz < len_of TYPE('a)"
have ux: "unat x + unat k < 2 ^ len_of TYPE('a)"
by (rule aligned_add_offset_no_wrap) fact+
show ?thesis using al szv
apply -
apply (erule is_alignedE)
apply (subst word_unat.Rep_inject [symmetric])
apply (subst unat_mod)
apply (subst iffD1 [OF unat_add_lem], rule ux)
apply simp
apply (subst unat_mult_power_lem, assumption+)
apply (subst mod_add_left_eq)
apply (simp)
apply (rule mod_less[OF less_le_trans[OF unat_mono], OF kv])
apply (erule eq_imp_le[OF unat_power_lower])
done
next
assume "\<not> sz < len_of TYPE('a)"
with al show ?thesis
by (simp add: not_less power_overflow is_aligned_mask mask_def
word_mod_by_0)
qed
lemma word_plus_mcs_4:
"\<lbrakk>v + x \<le> w + x; x \<le> v + x\<rbrakk> \<Longrightarrow> v \<le> (w::'a::len word)"
by uint_arith
lemma word_plus_mcs_3:
"\<lbrakk>v \<le> w; x \<le> w + x\<rbrakk> \<Longrightarrow> v + x \<le> w + (x::'a::len word)"
by unat_arith
have rl: "\<And>(p::'a word) k w. \<lbrakk>uint p + uint k < 2 ^ len_of TYPE('a); w = p + k; w \<le> p + (2 ^ sz - 1) \<rbrakk>
\<Longrightarrow> k < 2 ^ sz"
apply -
apply simp
apply (subst (asm) add.commute, subst (asm) add.commute, drule word_plus_mcs_4)
apply (subst add.commute, subst no_plus_overflow_uint_size)
apply (simp add: word_size_bl)
apply (erule iffD1 [OF word_less_sub_le[OF szv]])
done
from xb obtain kx where
kx: "z = x + kx" and
kxl: "uint x + uint kx < 2 ^ len_of TYPE('a)"
by (clarsimp dest!: word_le_exists')
from yb obtain ky where
ky: "z = y + ky" and
kyl: "uint y + uint ky < 2 ^ len_of TYPE('a)"
by (clarsimp dest!: word_le_exists')
have "x = y"
proof -
have "kx = z mod 2 ^ sz"
proof (subst kx, rule sym, rule aligned_add_offset_mod)
show "kx < 2 ^ sz" by (rule rl) fact+
qed fact+
also have "\<dots> = ky"
proof (subst ky, rule aligned_add_offset_mod)
show "ky < 2 ^ sz"
using kyl ky yt by (rule rl)
qed fact+
finally have kxky: "kx = ky" .
moreover have "x + kx = y + ky" by (simp add: kx [symmetric] ky [symmetric])
ultimately show ?thesis by simp
qed
thus False using neq by simp
qed
next
assume "\<not> sz < len_of TYPE('a)"
with neq alx aly
have False by (simp add: is_aligned_mask mask_def power_overflow)
thus ?thesis ..
qed
lemma less_two_pow_divD:
"\<lbrakk> (x :: nat) < 2 ^ n div 2 ^ m \<rbrakk>
\<Longrightarrow> n \<ge> m \<and> (x < 2 ^ (n - m))"
apply (rule context_conjI)
apply (rule ccontr)
apply (simp add: power_strict_increasing)
apply (simp add: power_sub)
done
lemma less_two_pow_divI:
"\<lbrakk> (x :: nat) < 2 ^ (n - m); m \<le> n \<rbrakk> \<Longrightarrow> x < 2 ^ n div 2 ^ m"
by (simp add: power_sub)
lemma word_less_two_pow_divI:
"\<lbrakk> (x :: 'a::len word) < 2 ^ (n - m); m \<le> n; n < len_of TYPE('a) \<rbrakk> \<Longrightarrow> x < 2 ^ n div 2 ^ m"
apply (simp add: word_less_nat_alt)
apply (subst unat_word_ariths)
apply (subst mod_less)
apply (rule order_le_less_trans [OF div_le_dividend])
apply (rule unat_lt2p)
apply (simp add: power_sub)
done
lemma word_less_two_pow_divD:
"\<lbrakk> (x :: 'a::len word) < 2 ^ n div 2 ^ m \<rbrakk>
\<Longrightarrow> n \<ge> m \<and> (x < 2 ^ (n - m))"
apply (cases "n < len_of TYPE('a)")
apply (cases "m < len_of TYPE('a)")
apply (simp add: word_less_nat_alt)
apply (subst(asm) unat_word_ariths)
apply (subst(asm) mod_less)
apply (rule order_le_less_trans [OF div_le_dividend])
apply (rule unat_lt2p)
apply (clarsimp dest!: less_two_pow_divD)
apply (simp add: power_overflow)
apply (simp add: word_div_def)
apply (simp add: power_overflow word_div_def)
done
lemma of_nat_less_two_pow_div_set:
"\<lbrakk> n < len_of TYPE('a) \<rbrakk> \<Longrightarrow>
{x. x < (2 ^ n div 2 ^ m :: 'a::len word)}
= of_nat ` {k. k < 2 ^ n div 2 ^ m}"
apply (simp add: image_def)
apply (safe dest!: word_less_two_pow_divD less_two_pow_divD
intro!: word_less_two_pow_divI)
apply (rule_tac x="unat x" in exI)
apply (simp add: power_sub[symmetric])
apply (subst unat_power_lower[symmetric, where 'a='a])
apply simp
apply (erule unat_mono)
apply (subst word_unat_power)
apply (rule of_nat_mono_maybe)
apply (rule power_strict_increasing)
apply simp
apply simp
apply assumption
done
(* FIXME: generalise! *)
lemma upto_2_helper:
"{0..<2 :: word32} = {0, 1}"
apply (safe, simp_all)
apply unat_arith
done
(* TODO: MOVE to word *)
lemma word_less_power_trans2:
fixes n :: "'a::len word"
shows "\<lbrakk>n < 2 ^ (m - k); k \<le> m; m < len_of TYPE('a)\<rbrakk> \<Longrightarrow> n * 2 ^ k < 2 ^ m"
by (subst field_simps, rule word_less_power_trans)
lemma ucast_less:
"len_of TYPE('b) < len_of TYPE('a) \<Longrightarrow>
(ucast (x :: ('b :: len) word) :: (('a :: len) word)) < 2 ^ len_of TYPE('b)"
apply (subst mask_eq_iff_w2p[symmetric])
apply (simp add: word_size)
apply (rule word_eqI)
apply (simp add: word_size nth_ucast)
apply safe
apply (simp add: test_bit.Rep[simplified])
done
lemma ucast_less_shiftl_helper:
"\<lbrakk> len_of TYPE('b) + 2 < word_bits;
2 ^ (len_of TYPE('b) + 2) \<le> n\<rbrakk>
\<Longrightarrow> (ucast (x :: ('b :: len) word) << 2) < (n :: word32)"
apply (erule order_less_le_trans[rotated])
apply (cut_tac ucast_less[where x=x and 'a=32])
apply (simp only: shiftl_t2n field_simps)
apply (rule word_less_power_trans2)
apply (simp_all add: word_bits_def)
done
lemma ucast_range_less:
"len_of TYPE('a :: len) < len_of TYPE('b :: len) \<Longrightarrow>
range (ucast :: 'a word \<Rightarrow> 'b word)
= {x. x < 2 ^ len_of TYPE ('a)}"
apply safe
apply (erule ucast_less)
apply (simp add: image_def)
apply (rule_tac x="ucast x" in exI)
apply (drule less_mask_eq)
apply (rule word_eqI)
apply (drule_tac x=n in word_eqD)
apply (simp add: word_size nth_ucast)
done
lemma word_power_less_diff:
"\<lbrakk>2 ^ n * q < (2::'a::len word) ^ m; q < 2 ^ (len_of TYPE('a) - n)\<rbrakk> \<Longrightarrow> q < 2 ^ (m - n)"
apply (case_tac "m \<ge> len_of TYPE('a)")
apply (simp add: power_overflow)
apply (case_tac "n \<ge> len_of TYPE('a)")
apply (simp add: power_overflow)
apply (cases "n = 0")
apply simp
apply (subst word_less_nat_alt)
apply (subst unat_power_lower)
apply simp
apply (rule nat_power_less_diff)
apply (simp add: word_less_nat_alt)
apply (subst (asm) iffD1 [OF unat_mult_lem])
apply (simp add:nat_less_power_trans)
apply simp
done
lemmas word_diff_ls' = word_diff_ls [where xa=x and x=x for x, simplified]
lemmas word_l_diffs = word_l_diffs [where xa=x and x=x for x, simplified]
lemma is_aligned_diff:
fixes m :: "'a::len word"
assumes alm: "is_aligned m s1"
and aln: "is_aligned n s2"
and s2wb: "s2 < len_of TYPE('a)"
and nm: "m \<in> {n .. n + (2 ^ s2 - 1)}"
and s1s2: "s1 \<le> s2"
and s10: "0 < s1" (* Probably can be folded into the proof \<dots> *)
shows "\<exists>q. m - n = of_nat q * 2 ^ s1 \<and> q < 2 ^ (s2 - s1)"
proof -
have rl: "\<And>m s. \<lbrakk> m < 2 ^ (len_of TYPE('a) - s); s < len_of TYPE('a) \<rbrakk> \<Longrightarrow> unat ((2::'a word) ^ s * of_nat m) = 2 ^ s * m"
proof -
fix m :: nat and s
assume m: "m < 2 ^ (len_of TYPE('a) - s)" and s: "s < len_of TYPE('a)"
hence "unat ((of_nat m) :: 'a word) = m"
apply (subst unat_of_nat)
apply (subst mod_less)
apply (erule order_less_le_trans)
apply (rule power_increasing)
apply simp_all
done
thus "?thesis m s" using s m
apply (subst iffD1 [OF unat_mult_lem])
apply (simp add: nat_less_power_trans)+
done
qed
have s1wb: "s1 < len_of TYPE('a)" using s2wb s1s2 by simp
from alm obtain mq where mmq: "m = 2 ^ s1 * of_nat mq" and mq: "mq < 2 ^ (len_of TYPE('a) - s1)"
by (auto elim: is_alignedE simp: field_simps)
from aln obtain nq where nnq: "n = 2 ^ s2 * of_nat nq" and nq: "nq < 2 ^ (len_of TYPE('a) - s2)"
by (auto elim: is_alignedE simp: field_simps)
from s1s2 obtain sq where sq: "s2 = s1 + sq" by (auto simp: le_iff_add)
note us1 = rl [OF mq s1wb]
note us2 = rl [OF nq s2wb]
from nm have "n \<le> m" by clarsimp
hence "(2::'a word) ^ s2 * of_nat nq \<le> 2 ^ s1 * of_nat mq" using nnq mmq by simp
hence "2 ^ s2 * nq \<le> 2 ^ s1 * mq" using s1wb s2wb
by (simp add: word_le_nat_alt us1 us2)
hence nqmq: "2 ^ sq * nq \<le> mq" using sq by (simp add: power_add)
have "m - n = 2 ^ s1 * of_nat mq - 2 ^ s2 * of_nat nq" using mmq nnq by simp
also have "\<dots> = 2 ^ s1 * of_nat mq - 2 ^ s1 * 2 ^ sq * of_nat nq" using sq by (simp add: power_add)
also have "\<dots> = 2 ^ s1 * (of_nat mq - 2 ^ sq * of_nat nq)" by (simp add: field_simps)
also have "\<dots> = 2 ^ s1 * of_nat (mq - 2 ^ sq * nq)" using s1wb s2wb us1 us2 nqmq
by (simp add: word_unat_power)
finally have mn: "m - n = of_nat (mq - 2 ^ sq * nq) * 2 ^ s1" by simp
moreover
from nm have "m - n \<le> 2 ^ s2 - 1"
by - (rule word_diff_ls', (simp add: field_simps)+)
hence "(2::'a word) ^ s1 * of_nat (mq - 2 ^ sq * nq) < 2 ^ s2" using mn s2wb by (simp add: field_simps)
hence "of_nat (mq - 2 ^ sq * nq) < (2::'a word) ^ (s2 - s1)"
proof (rule word_power_less_diff)
have mm: "mq - 2 ^ sq * nq < 2 ^ (len_of TYPE('a) - s1)" using mq by simp
moreover from s10 have "len_of TYPE('a) - s1 < len_of TYPE('a)"
by (rule diff_less, simp)
ultimately show "of_nat (mq - 2 ^ sq * nq) < (2::'a word) ^ (len_of TYPE('a) - s1)"
apply (simp add: word_less_nat_alt)
apply (subst unat_of_nat)
apply (subst mod_less)
apply (erule order_less_le_trans)
apply simp+
done
qed
hence "mq - 2 ^ sq * nq < 2 ^ (s2 - s1)" using mq s2wb
apply (simp add: word_less_nat_alt)
apply (subst (asm) unat_of_nat)
apply (subst (asm) mod_less)
apply (rule order_le_less_trans)
apply (rule diff_le_self)
apply (erule order_less_le_trans)
apply simp
apply assumption
done
ultimately show ?thesis by auto
qed
lemma word_less_sub_1:
"x < (y :: ('a :: len) word) \<Longrightarrow> x \<le> y - 1"
apply (erule udvd_minus_le')
apply (simp add: udvd_def)+
done
lemma word_sub_mono2:
"\<lbrakk> a + b \<le> c + d; c \<le> a; b \<le> a + b; d \<le> c + d \<rbrakk>
\<Longrightarrow> b \<le> (d :: ('a :: len) word)"
apply (drule(1) word_sub_mono)
apply simp
apply simp
apply simp
done
lemma word_subset_less:
"\<lbrakk> {x .. x + r - 1} \<subseteq> {y .. y + s - 1};
x \<le> x + r - 1; y \<le> y + (s :: ('a :: len) word) - 1;
s \<noteq> 0 \<rbrakk>
\<Longrightarrow> r \<le> s"
apply (frule subsetD[where c=x])
apply simp
apply (drule subsetD[where c="x + r - 1"])
apply simp
apply (clarsimp simp: add_diff_eq[symmetric])
apply (drule(1) word_sub_mono2)
apply (simp_all add: olen_add_eqv[symmetric])
apply (erule word_le_minus_cancel)
apply (rule ccontr)
apply (simp add: word_not_le)
done
lemma two_power_strict_part_mono:
"strict_part_mono {..31} (\<lambda>x. (2 :: word32) ^ x)"
by (simp | subst strict_part_mono_by_steps)+
lemma uint_power_lower:
"n < len_of TYPE('a) \<Longrightarrow> uint (2 ^ n :: 'a :: len word) = (2 ^ n :: int)"
by (simp add: uint_nat int_power)
lemma power_le_mono:
"\<lbrakk>2 ^ n \<le> (2::'a::len word) ^ m; n < len_of TYPE('a); m < len_of TYPE('a)\<rbrakk>
\<Longrightarrow> n \<le> m"
apply (clarsimp simp add: le_less)
apply safe
apply (simp add: word_less_nat_alt)
apply (simp only: uint_arith_simps(3))
apply (drule uint_power_lower)+
apply simp
done
lemma sublist_equal_part:
"xs \<le> ys \<Longrightarrow> take (length xs) ys = xs"
by (clarsimp simp: prefixeq_def less_eq_list_def)
lemma take_n_subset_le:
"\<lbrakk> {x. take n (to_bl x) = take n xs} \<subseteq> {y :: word32. take m (to_bl y) = take m ys};
n \<le> 32; m \<le> 32; length xs = 32; length ys = 32 \<rbrakk>
\<Longrightarrow> m \<le> n"
apply (rule ccontr, simp add: le_def)
apply (simp add: subset_iff)
apply (drule spec[where x="of_bl (take n xs @ take (32 - n) (map Not (drop n ys)))"])
apply (simp add: word_bl.Abs_inverse)
apply (subgoal_tac "\<exists>p. m = n + p")
apply clarsimp
apply (simp add: take_add take_map_Not)
apply (rule exI[where x="m - n"])
apply simp
done
lemma two_power_eq:
"\<lbrakk>n < len_of TYPE('a); m < len_of TYPE('a)\<rbrakk>
\<Longrightarrow> ((2::'a::len word) ^ n = 2 ^ m) = (n = m)"
apply safe
apply (rule order_antisym)
apply (simp add: power_le_mono[where 'a='a])+
done
lemma less_list_def': "(xs < ys) = (prefix xs ys)"
apply (metis prefix_order.eq_iff prefix_def less_list_def less_eq_list_def)
done
lemma prefix_length_less:
"xs < ys \<Longrightarrow> length xs < length ys"
apply (clarsimp simp: less_list_def' prefix_def)
apply (frule prefixeq_length_le)
apply (rule ccontr, simp)
apply (clarsimp simp: prefixeq_def)
done
lemmas strict_prefix_simps [simp, code] = prefix_simps [folded less_list_def']
lemmas take_strict_prefix = take_prefix [folded less_list_def']
lemma not_prefix_longer:
"\<lbrakk> length xs > length ys \<rbrakk> \<Longrightarrow> \<not> xs \<le> ys"
by (clarsimp dest!: prefix_length_le)
lemma of_bl_length:
"length xs < len_of TYPE('a) \<Longrightarrow> of_bl xs < (2 :: 'a::len word) ^ length xs"
by (simp add: of_bl_length_less)
(* FIXME: do we need this? *)
lemma power_overflow_simp [simp]:
"(2 ^ n = (0::'a :: len word)) = (len_of TYPE ('a) \<le> n)"
by (rule WordLib.p2_eq_0)
lemma unat_of_nat_eq:
"x < 2 ^ len_of TYPE('a) \<Longrightarrow> unat (of_nat x ::'a::len word) = x"
by (simp add: unat_of_nat)
lemmas unat_of_nat32 = unat_of_nat_eq[where 'a=32, unfolded word_bits_len_of]
lemma unat_eq_of_nat:
"n < 2 ^ len_of TYPE('a) \<Longrightarrow> (unat (x :: 'a::len word) = n) = (x = of_nat n)"
by (subst unat_of_nat_eq[where x=n, symmetric], simp+)
lemma unat_less_helper:
"x < of_nat n \<Longrightarrow> unat x < n"
apply (simp add: word_less_nat_alt)
apply (erule order_less_le_trans)
apply (simp add: unat_of_nat)
done
lemma of_nat_0:
"\<lbrakk>of_nat n = (0::('a::len) word); n < 2 ^ len_of (TYPE('a))\<rbrakk> \<Longrightarrow> n = 0"
by (drule unat_of_nat_eq, simp)
lemma of_nat32_0:
"\<lbrakk>of_nat n = (0::word32); n < 2 ^ word_bits\<rbrakk> \<Longrightarrow> n = 0"
by (erule of_nat_0, simp add: word_bits_def)
lemma unat_mask_2_less_4:
"unat (p && mask 2 :: word32) < 4"
apply (rule unat_less_helper)
apply (rule order_le_less_trans, rule word_and_le1)
apply (simp add: mask_def)
done
lemma minus_one_helper3:
"x < y \<Longrightarrow> x \<le> (y :: ('a :: len) word) - 1"
apply (simp add: word_less_nat_alt word_le_nat_alt)
apply (subst unat_minus_one)
apply clarsimp
apply arith
done
lemma minus_one_helper:
"\<lbrakk> x \<le> y; x \<noteq> 0 \<rbrakk> \<Longrightarrow> x - 1 < (y :: ('a :: len) word)"
apply (simp add: word_less_nat_alt word_le_nat_alt)
apply (subst unat_minus_one)
apply assumption
apply (cases "unat x")
apply (simp add: unat_eq_zero)
apply arith
done
lemma minus_one_helper5:
fixes x :: "'a::len word"
shows "\<lbrakk>y \<noteq> 0; x \<le> y - 1 \<rbrakk> \<Longrightarrow> x < y"
by (metis leD minus_one_helper not_leE)
lemma plus_one_helper[elim!]:
"x < n + (1 :: ('a :: len) word) \<Longrightarrow> x \<le> n"
apply (simp add: word_less_nat_alt word_le_nat_alt field_simps)
apply (case_tac "1 + n = 0")
apply simp
apply (subst(asm) unatSuc, assumption)
apply arith
done
lemma not_greatest_aligned:
"\<lbrakk> x < y; is_aligned x n; is_aligned y n \<rbrakk>
\<Longrightarrow> x + 2 ^ n \<noteq> 0"
apply (rule notI)
apply (erule is_aligned_get_word_bits[where p=y])
apply (simp add: eq_diff_eq[symmetric])
apply (frule minus_one_helper3)
apply (drule le_minus'[where a="x" and c="y - x" and b="- 1" for x y, simplified])
apply (simp add: field_simps)
apply (frule is_aligned_less_sz[where a=y])
apply clarsimp
apply (erule notE)
apply (rule minus_one_helper5)
apply simp
apply (metis is_aligned_no_overflow minus_one_helper3 order_le_less_trans)
apply simp
done
lemma of_nat_inj:
"\<lbrakk>x < 2 ^ len_of TYPE('a); y < 2 ^ len_of TYPE('a)\<rbrakk> \<Longrightarrow>
(of_nat x = (of_nat y :: 'a :: len word)) = (x = y)"
by (simp add: word_unat.norm_eq_iff [symmetric])
lemma map_prefixI:
"xs \<le> ys \<Longrightarrow> map f xs \<le> map f ys"
by (clarsimp simp: less_eq_list_def prefixeq_def)
lemma if_Some_None_eq_None:
"((if P then Some v else None) = None) = (\<not> P)"
by simp
lemma CollectPairFalse [iff]:
"{(a,b). False} = {}"
by (simp add: split_def)
lemma if_P_True1:
"Q \<Longrightarrow> (if P then True else Q)"
by simp
lemma if_P_True2:
"Q \<Longrightarrow> (if P then Q else True)"
by simp
lemma list_all2_induct [consumes 1, case_names Nil Cons]:
assumes lall: "list_all2 Q xs ys"
and nilr: "P [] []"
and consr: "\<And>x xs y ys. \<lbrakk>list_all2 Q xs ys; Q x y; P xs ys\<rbrakk> \<Longrightarrow> P (x # xs) (y # ys)"
shows "P xs ys"
using lall
proof (induct rule: list_induct2 [OF list_all2_lengthD [OF lall]])
case 1 thus ?case by auto fact+
next
case (2 x xs y ys)
show ?case
proof (rule consr)
from "2.prems" show "list_all2 Q xs ys" and "Q x y" by simp_all
thus "P xs ys" by (intro "2.hyps")
qed
qed
lemma list_all2_induct_suffixeq [consumes 1, case_names Nil Cons]:
assumes lall: "list_all2 Q as bs"
and nilr: "P [] []"
and consr: "\<And>x xs y ys.
\<lbrakk>list_all2 Q xs ys; Q x y; P xs ys; suffixeq (x # xs) as; suffixeq (y # ys) bs\<rbrakk>
\<Longrightarrow> P (x # xs) (y # ys)"
shows "P as bs"
proof -
def as' == as
def bs' == bs
have "suffixeq as as' \<and> suffixeq bs bs'" unfolding as'_def bs'_def by simp
thus ?thesis using lall
proof (induct rule: list_induct2 [OF list_all2_lengthD [OF lall]])
case 1 show ?case by fact
next
case (2 x xs y ys)
show ?case
proof (rule consr)
from "2.prems" show "list_all2 Q xs ys" and "Q x y" by simp_all
thus "P xs ys" using "2.hyps" "2.prems" by (auto dest: suffixeq_ConsD)
from "2.prems" show "suffixeq (x # xs) as" and "suffixeq (y # ys) bs"
by (auto simp: as'_def bs'_def)
qed
qed
qed
lemma distinct_prop_enum:
"\<lbrakk> \<And>x y. \<lbrakk> x \<le> stop; y \<le> stop; x \<noteq> y \<rbrakk>
\<Longrightarrow> P x y \<rbrakk>
\<Longrightarrow> distinct_prop P [(0 :: word32) .e. stop]"
apply (simp add: upto_enum_def distinct_prop_map
del: upt.simps)
apply (rule distinct_prop_distinct)
apply simp
apply (simp add: less_Suc_eq_le del: upt.simps)
apply (erule_tac x="of_nat x" in meta_allE)
apply (erule_tac x="of_nat y" in meta_allE)
apply (frule_tac y=x in unat_le)
apply (frule_tac y=y in unat_le)
apply (erule word_unat.Rep_cases)+
apply (simp add: toEnum_of_nat[OF unat_lt2p]
word_le_nat_alt)
done
lemma distinct_prop_enum_step:
"\<lbrakk> \<And>x y. \<lbrakk> x \<le> stop div step; y \<le> stop div step; x \<noteq> y \<rbrakk>
\<Longrightarrow> P (x * step) (y * step) \<rbrakk>
\<Longrightarrow> distinct_prop P [0, step .e. stop]"
apply (simp add: upto_enum_step_def distinct_prop_map)
apply (rule distinct_prop_enum)
apply simp
done
lemma if_apply_def2:
"(if P then F else G) = (\<lambda>x. (P \<longrightarrow> F x) \<and> (\<not> P \<longrightarrow> G x))"
by simp
lemma case_bool_If:
"case_bool P Q b = (if b then P else Q)"
by simp
lemma case_option_If:
"case_option P (\<lambda>x. Q) v = (if v = None then P else Q)"
by clarsimp
lemma case_option_If2:
"case_option P Q v = If (v \<noteq> None) (Q (the v)) P"
by (simp split: option.split)
lemma if3_fold:
"(if P then x else if Q then y else x)
= (if P \<or> \<not> Q then x else y)"
by simp
lemma word32_shift_by_2:
"x * 4 = (x::word32) << 2"
by (simp add: shiftl_t2n)
(* TODO: move to Aligned *)
lemma add_mask_lower_bits:
"\<lbrakk>is_aligned (x :: 'a :: len word) n;
\<forall>n' \<ge> n. n' < len_of TYPE('a) \<longrightarrow> \<not> p !! n'\<rbrakk> \<Longrightarrow> x + p && ~~mask n = x"
apply (subst word_plus_and_or_coroll)
apply (rule word_eqI)
apply (clarsimp simp: word_size is_aligned_nth)
apply (erule_tac x=na in allE)+
apply simp
apply (rule word_eqI)
apply (clarsimp simp: word_size is_aligned_nth word_ops_nth_size)
apply (erule_tac x=na in allE)+
apply (case_tac "na < n")
apply simp
apply simp
done
lemma findSomeD:
"find P xs = Some x \<Longrightarrow> P x \<and> x \<in> set xs"
by (induct xs) (auto split: split_if_asm)
lemma findNoneD:
"find P xs = None \<Longrightarrow> \<forall>x \<in> set xs. \<not>P x"
by (induct xs) (auto split: split_if_asm)
lemma dom_upd:
"dom (\<lambda>x. if x = y then None else f x) = dom f - {y}"
by (rule set_eqI) (auto split: split_if_asm)
lemma ran_upd:
"\<lbrakk> inj_on f (dom f); f y = Some z \<rbrakk> \<Longrightarrow> ran (\<lambda>x. if x = y then None else f x) = ran f - {z}"
apply (rule set_eqI)
apply (unfold ran_def)
apply simp
apply (rule iffI)
apply clarsimp
apply (rule conjI, blast)
apply clarsimp
apply (drule_tac x=a and y=y in inj_onD, simp)
apply blast
apply blast
apply simp
apply clarsimp
apply (rule_tac x=a in exI)
apply clarsimp
done
lemma maxBound_word:
"(maxBound::'a::len word) = -1"
apply (simp add: maxBound_def enum_word_def)
apply (subst last_map)
apply clarsimp
apply simp
done
lemma minBound_word:
"(minBound::'a::len word) = 0"
apply (simp add: minBound_def enum_word_def)
apply (subst map_upt_unfold)
apply simp
apply simp
done
lemma maxBound_max_word:
"(maxBound::'a::len word) = max_word"
apply (subst maxBound_word)
apply (subst max_word_minus [symmetric])
apply (rule refl)
done
lemma is_aligned_andI1:
"is_aligned x n \<Longrightarrow> is_aligned (x && y) n"
by (simp add: is_aligned_nth)
lemma is_aligned_andI2:
"is_aligned y n \<Longrightarrow> is_aligned (x && y) n"
by (simp add: is_aligned_nth)
lemma is_aligned_shiftl:
"is_aligned w (n - m) \<Longrightarrow> is_aligned (w << m) n"
by (simp add: is_aligned_nth nth_shiftl)
lemma is_aligned_shiftr:
"is_aligned w (n + m) \<Longrightarrow> is_aligned (w >> m) n"
by (simp add: is_aligned_nth nth_shiftr)
lemma is_aligned_shiftl_self:
"is_aligned (p << n) n"
by (rule is_aligned_shiftl) simp
lemma is_aligned_neg_mask_eq:
"is_aligned p n \<Longrightarrow> p && ~~ mask n = p"
apply (simp add: is_aligned_nth)
apply (rule word_eqI)
apply (clarsimp simp: word_size word_ops_nth_size)
apply fastforce
done
lemma is_aligned_shiftr_shiftl:
"is_aligned w n \<Longrightarrow> w >> n << n = w"
apply (simp add: shiftr_shiftl1)
apply (erule is_aligned_neg_mask_eq)
done
lemma rtrancl_insert:
assumes x_new: "\<And>y. (x,y) \<notin> R"
shows "R^* `` insert x S = insert x (R^* `` S)"
proof -
have "R^* `` insert x S = R^* `` ({x} \<union> S)" by simp
also
have "R^* `` ({x} \<union> S) = R^* `` {x} \<union> R^* `` S"
by (subst Image_Un) simp
also
have "R^* `` {x} = {x}"
apply (clarsimp simp: Image_singleton)
apply (rule set_eqI, clarsimp)
apply (rule iffI)
apply (drule rtranclD)
apply (erule disjE, simp)
apply clarsimp
apply (drule tranclD)
apply (clarsimp simp: x_new)
apply fastforce
done
finally
show ?thesis by simp
qed
lemma ran_del_subset:
"y \<in> ran (f (x := None)) \<Longrightarrow> y \<in> ran f"
by (auto simp: ran_def split: split_if_asm)
lemma trancl_sub_lift:
assumes sub: "\<And>p p'. (p,p') \<in> r \<Longrightarrow> (p,p') \<in> r'"
shows "(p,p') \<in> r^+ \<Longrightarrow> (p,p') \<in> r'^+"
by (fastforce intro: trancl_mono sub)
lemma trancl_step_lift:
assumes x_step: "\<And>p p'. (p,p') \<in> r' \<Longrightarrow> (p,p') \<in> r \<or> (p = x \<and> p' = y)"
assumes y_new: "\<And>p'. \<not>(y,p') \<in> r"
shows "(p,p') \<in> r'^+ \<Longrightarrow> (p,p') \<in> r^+ \<or> ((p,x) \<in> r^+ \<and> p' = y) \<or> (p = x \<and> p' = y)"
apply (erule trancl_induct)
apply (drule x_step)
apply fastforce
apply (erule disjE)
apply (drule x_step)
apply (erule disjE)
apply (drule trancl_trans, drule r_into_trancl, assumption)
apply blast
apply clarsimp
apply (erule disjE)
apply clarsimp
apply (drule x_step)
apply (erule disjE)
apply (simp add: y_new)
apply simp
apply clarsimp
apply (drule x_step)
apply (simp add: y_new)
done
lemma upto_enum_step_shift:
"\<lbrakk> is_aligned p n \<rbrakk> \<Longrightarrow>
([p , p + 2 ^ m .e. p + 2 ^ n - 1])
= map (op + p) [0, 2 ^ m .e. 2 ^ n - 1]"
apply (erule is_aligned_get_word_bits)
prefer 2
apply (simp add: map_idI)
apply (clarsimp simp: upto_enum_step_def)
apply (frule is_aligned_no_overflow)
apply (simp add: linorder_not_le [symmetric])
done
lemma upto_enum_step_shift_red:
"\<lbrakk> is_aligned p sz; sz < word_bits; us \<le> sz \<rbrakk>
\<Longrightarrow> [p, p + 2 ^ us .e. p + 2 ^ sz - 1]
= map (\<lambda>x. p + of_nat x * 2 ^ us) [0 ..< 2 ^ (sz - us)]"
apply (subst upto_enum_step_shift, assumption)
apply (simp add: upto_enum_step_red)
done
lemma div_to_mult_word_lt:
"\<lbrakk> (x :: ('a :: len) word) \<le> y div z \<rbrakk> \<Longrightarrow> x * z \<le> y"
apply (cases "z = 0")
apply simp
apply (simp add: word_neq_0_conv)
apply (rule order_trans)
apply (erule(1) word_mult_le_mono1)
apply (simp add: unat_div)
apply (rule order_le_less_trans [OF div_mult_le])
apply simp
apply (rule word_div_mult_le)
done
lemma upto_enum_step_subset:
"set [x, y .e. z] \<subseteq> {x .. z}"
apply (clarsimp simp: upto_enum_step_def linorder_not_less)
apply (drule div_to_mult_word_lt)
apply (rule conjI)
apply (erule word_random[rotated])
apply simp
apply (rule order_trans)
apply (erule word_plus_mono_right)
apply simp
apply simp
done
lemma shiftr_less_t2n':
fixes x :: "('a :: len) word"
shows "\<lbrakk> x && mask (n + m) = x; m < len_of TYPE('a) \<rbrakk>
\<Longrightarrow> (x >> n) < 2 ^ m"
apply (subst mask_eq_iff_w2p[symmetric])
apply (simp add: word_size)
apply (rule word_eqI)
apply (drule_tac x="na + n" in word_eqD)
apply (simp add: nth_shiftr word_size)
apply safe
done
lemma shiftr_less_t2n:
fixes x :: "('a :: len) word"
shows "x < 2 ^ (n + m) \<Longrightarrow> (x >> n) < 2 ^ m"
apply (rule shiftr_less_t2n')
apply (erule less_mask_eq)
apply (rule ccontr)
apply (simp add: not_less)
apply (subst (asm) p2_eq_0[symmetric])
apply (simp add: power_add)
done
lemma shiftr_eq_0:
"n \<ge> len_of TYPE('a :: len) \<Longrightarrow> ((w::('a::len word)) >> n) = 0"
apply (cut_tac shiftr_less_t2n'[of w n 0], simp)
apply (simp add: mask_eq_iff)
apply (simp add: lt2p_lem)
apply simp
done
lemma shiftr_not_mask_0:
"n+m\<ge>len_of TYPE('a :: len) \<Longrightarrow> ((w::('a::len word)) >> n) && ~~ mask m = 0"
apply (simp add: and_not_mask shiftr_less_t2n shiftr_shiftr)
apply (subgoal_tac "w >> n + m = 0", simp)
apply (simp add: le_mask_iff[symmetric] mask_def le_def)
apply (subst (asm) p2_gt_0[symmetric])
apply (simp add: power_add not_less)
done
lemma shiftl_less_t2n:
fixes x :: "('a :: len) word"
shows "\<lbrakk> x < (2 ^ (m - n)); m < len_of TYPE('a) \<rbrakk> \<Longrightarrow> (x << n) < 2 ^ m"
apply (subst mask_eq_iff_w2p[symmetric])
apply (simp add: word_size)
apply (drule less_mask_eq)
apply (rule word_eqI)
apply (drule_tac x="na - n" in word_eqD)
apply (simp add: nth_shiftl word_size)
apply (cases "n \<le> m")
apply safe
apply simp
apply simp
done
lemma shiftl_less_t2n':
"(x::'a::len word) < 2 ^ m \<Longrightarrow> m+n < len_of TYPE('a) \<Longrightarrow> x << n < 2 ^ (m + n)"
by (rule shiftl_less_t2n) simp_all
lemma ucast_ucast_mask:
"(ucast :: ('a :: len) word \<Rightarrow> ('b :: len) word) (ucast x) = x && mask (len_of TYPE ('a))"
apply (rule word_eqI)
apply (simp add: nth_ucast word_size)
done
lemma ucast_ucast_len:
"\<lbrakk> x < 2 ^ len_of TYPE('b) \<rbrakk> \<Longrightarrow>
ucast (ucast x::'b::len word) = (x::'a::len word)"
apply (subst ucast_ucast_mask)
apply (erule less_mask_eq)
done
lemma unat_ucast: "unat (ucast x :: ('a :: len0) word) = unat x mod 2 ^ (len_of TYPE('a))"
apply (simp add: unat_def ucast_def)
apply (subst word_uint.eq_norm)
apply (subst nat_mod_distrib)
apply simp
apply simp
apply (subst nat_power_eq)
apply simp
apply simp
done
lemma ucast_less_ucast:
"len_of TYPE('a) < len_of TYPE('b) \<Longrightarrow>
(ucast x < ((ucast (y :: ('a::len) word)) :: ('b::len) word)) = (x < y)"
apply (simp add: word_less_nat_alt unat_ucast)
apply (subst mod_less)
apply(rule less_le_trans[OF unat_lt2p], simp)
apply (subst mod_less)
apply(rule less_le_trans[OF unat_lt2p], simp)
apply simp
done
lemma sints_subset:
"m \<le> n \<Longrightarrow> sints m \<subseteq> sints n"
apply (simp add: sints_num)
apply clarsimp
apply (rule conjI)
apply (erule order_trans[rotated])
apply simp
apply (erule order_less_le_trans)
apply simp
done
lemma up_scast_inj:
"\<lbrakk> scast x = (scast y :: ('b :: len) word); size x \<le> len_of TYPE('b) \<rbrakk>
\<Longrightarrow> x = y"
apply (simp add: scast_def)
apply (subst(asm) word_sint.Abs_inject)
apply (erule subsetD [OF sints_subset])
apply (simp add: word_size)
apply (erule subsetD [OF sints_subset])
apply (simp add: word_size)
apply simp
done
lemma up_scast_inj_eq:
"len_of TYPE('a) \<le> len_of TYPE ('b) \<Longrightarrow> (scast x = (scast y::'b::len word)) = (x = (y::'a::len word))"
by (fastforce dest: up_scast_inj simp: word_size)
lemma nth_bounded:
"\<lbrakk>(x :: 'a :: len word) !! n; x < 2 ^ m; m \<le> len_of TYPE ('a)\<rbrakk> \<Longrightarrow> n < m"
apply (frule test_bit_size)
apply (clarsimp simp: test_bit_bl word_size)
apply (simp add: nth_rev)
apply (subst(asm) is_aligned_add_conv[OF is_aligned_0',
simplified add_0_left, rotated])
apply assumption+
apply (simp only: to_bl_0 word_bits_len_of)
apply (simp add: nth_append split: split_if_asm)
done
lemma is_aligned_add_or:
"\<lbrakk>is_aligned p n; d < 2 ^ n\<rbrakk> \<Longrightarrow> p + d = p || d"
apply (rule word_plus_and_or_coroll)
apply (erule is_aligned_get_word_bits)
apply (rule word_eqI)
apply (clarsimp simp add: is_aligned_nth)
apply (frule(1) nth_bounded)
apply simp+
done
lemma two_power_increasing:
"\<lbrakk> n \<le> m; m < len_of TYPE('a) \<rbrakk> \<Longrightarrow> (2 :: 'a :: len word) ^ n \<le> 2 ^ m"
by (simp add: word_le_nat_alt)
lemma is_aligned_add_less_t2n:
"\<lbrakk>is_aligned (p\<Colon>'a\<Colon>len word) n; d < 2^n; n \<le> m; p < 2^m\<rbrakk> \<Longrightarrow> p + d < 2^m"
apply (case_tac "m < len_of TYPE('a)")
apply (subst mask_eq_iff_w2p[symmetric])
apply (simp add: word_size)
apply (simp add: is_aligned_add_or word_ao_dist less_mask_eq)
apply (subst less_mask_eq)
apply (erule order_less_le_trans)
apply (erule(1) two_power_increasing)
apply simp
apply (simp add: power_overflow)
done
(* FIXME: generalise? *)
lemma le_2p_upper_bits:
"\<lbrakk> (p::word32) \<le> 2^n - 1; n < word_bits \<rbrakk> \<Longrightarrow> \<forall>n'\<ge>n. n' < word_bits \<longrightarrow> \<not> p !! n'"
apply (subst upper_bits_unset_is_l2p, assumption)
apply simp
done
lemma ran_upd':
"\<lbrakk>inj_on f (dom f); f y = Some z\<rbrakk>
\<Longrightarrow> ran (f (y := None)) = ran f - {z}"
apply (drule (1) ran_upd)
apply (simp add: ran_def)
done
(* FIXME: generalise? *)
lemma le2p_bits_unset:
"p \<le> 2 ^ n - 1 \<Longrightarrow> \<forall>n'\<ge>n. n' < word_bits \<longrightarrow> \<not> (p::word32) !! n'"
apply (case_tac "n < word_bits")
apply (frule upper_bits_unset_is_l2p [where p=p])
apply simp_all
done
lemma aligned_offset_non_zero:
"\<lbrakk> is_aligned x n; y < 2 ^ n; x \<noteq> 0 \<rbrakk> \<Longrightarrow> x + y \<noteq> 0"
apply (cases "y = 0")
apply simp
apply (subst word_neq_0_conv)
apply (subst gt0_iff_gem1)
apply (erule is_aligned_get_word_bits)
apply (subst field_simps[symmetric], subst plus_le_left_cancel_nowrap)
apply (rule is_aligned_no_wrap')
apply simp
apply (rule minus_one_helper)
apply simp
apply assumption
apply (erule (1) is_aligned_no_wrap')
apply (simp add: gt0_iff_gem1 [symmetric] word_neq_0_conv)
apply simp
done
lemma le_imp_power_dvd_int:
"n \<le> m \<Longrightarrow> (b ^ n :: int) dvd b ^ m"
apply (simp add: dvd_def)
apply (rule exI[where x="b ^ (m - n)"])
apply (simp add: power_add[symmetric])
done
(* FIXME: this is identical to mask_eqs(1), unnecessary? *)
lemma mask_inner_mask:
"((p && mask n) + q) && mask n
= (p + q) && mask n"
apply (rule mask_eqs(1))
done
lemma mask_add_aligned:
"is_aligned p n
\<Longrightarrow> (p + q) && mask n = q && mask n"
apply (simp add: is_aligned_mask)
apply (subst mask_inner_mask [symmetric])
apply simp
done
lemma take_prefix:
"(take (length xs) ys = xs) = (xs \<le> ys)"
proof (induct xs arbitrary: ys)
case Nil thus ?case by simp
next
case Cons thus ?case by (cases ys) auto
qed
lemma rel_comp_Image:
"(R O R') `` S = R' `` (R `` S)"
by blast
lemma trancl_power:
"x \<in> r^+ = (\<exists>n > 0. x \<in> r^^n)"
apply (cases x)
apply simp
apply (rule iffI)
apply (drule tranclD2)
apply (clarsimp simp: rtrancl_is_UN_relpow)
apply (rule_tac x="Suc n" in exI)
apply fastforce
apply clarsimp
apply (case_tac n, simp)
apply clarsimp
apply (drule relpow_imp_rtrancl)
apply fastforce
done
lemma take_is_prefix:
"take n xs \<le> xs"
apply (simp add: less_eq_list_def prefixeq_def)
apply (rule_tac x="drop n xs" in exI)
apply simp
done
lemma cart_singleton_empty:
"(S \<times> {e} = {}) = (S = {})"
by blast
lemma word_div_1:
"(n :: ('a :: len) word) div 1 = n"
by (simp add: word_div_def)
lemma word_minus_one_le:
"-1 \<le> (x :: ('a :: len) word) = (x = -1)"
apply (insert word_n1_ge[where y=x])
apply safe
apply (erule(1) order_antisym)
done
lemmas word32_minus_one_le =
word_minus_one_le[where 'a=32, simplified]
lemma mask_out_sub_mask:
"(x && ~~ mask n) = x - (x && mask n)"
by (simp add: field_simps word_plus_and_or_coroll2)
lemma is_aligned_addD1:
assumes al1: "is_aligned (x + y) n"
and al2: "is_aligned (x::'a::len word) n"
shows "is_aligned y n"
using al2
proof (rule is_aligned_get_word_bits)
assume "x = 0" thus ?thesis using al1 by simp
next
assume nv: "n < len_of TYPE('a)"
from al1 obtain q1
where xy: "x + y = 2 ^ n * of_nat q1" and "q1 < 2 ^ (len_of TYPE('a) - n)"
by (rule is_alignedE)
moreover from al2 obtain q2
where x: "x = 2 ^ n * of_nat q2" and "q2 < 2 ^ (len_of TYPE('a) - n)"
by (rule is_alignedE)
ultimately have "y = 2 ^ n * (of_nat q1 - of_nat q2)"
by (simp add: field_simps)
thus ?thesis using nv by (simp add: is_aligned_mult_triv1)
qed
lemmas is_aligned_addD2 =
is_aligned_addD1[OF subst[OF add.commute,
of "%x. is_aligned x n" for n]]
lemma is_aligned_add:
"\<lbrakk>is_aligned p n; is_aligned q n\<rbrakk> \<Longrightarrow> is_aligned (p + q) n"
by (simp add: is_aligned_mask mask_add_aligned)
lemma my_BallE: "\<lbrakk> \<forall>x \<in> A. P x; y \<in> A; P y \<Longrightarrow> Q \<rbrakk> \<Longrightarrow> Q"
by (simp add: Ball_def)
lemma word_le_add:
fixes x :: "'a :: len word"
shows "x \<le> y \<Longrightarrow> \<exists>n. y = x + of_nat n"
apply (rule exI [where x = "unat (y - x)"])
apply simp
done
lemma zipWith_nth:
"\<lbrakk> n < min (length xs) (length ys) \<rbrakk> \<Longrightarrow> zipWith f xs ys ! n = f (xs ! n) (ys ! n)"
unfolding zipWith_def by simp
lemma length_zipWith:
"length (zipWith f xs ys) = min (length xs) (length ys)"
unfolding zipWith_def by simp
lemma distinct_prop_nth:
"\<lbrakk> distinct_prop P ls; n < n'; n' < length ls \<rbrakk> \<Longrightarrow> P (ls ! n) (ls ! n')"
apply (induct ls arbitrary: n n')
apply simp
apply simp
apply (case_tac n')
apply simp
apply simp
apply (case_tac n)
apply simp
apply simp
done
lemma shiftl_mask_is_0 :
"(x << n) && mask n = 0"
apply (rule iffD1 [OF is_aligned_mask])
apply (rule is_aligned_shiftl_self)
done
lemma word_power_nonzero:
"\<lbrakk> (x :: word32) < 2 ^ (word_bits - n); n < word_bits; x \<noteq> 0 \<rbrakk> \<Longrightarrow> x * 2 ^ n \<noteq> 0"
apply (cases "n = 0")
apply simp
apply (simp only: word_neq_0_conv word_less_nat_alt
shiftl_t2n mod_0 unat_word_ariths
unat_power_lower word_le_nat_alt word_bits_def)
apply (unfold word_bits_len_of)
apply (subst mod_less)
apply (subst mult.commute, erule nat_less_power_trans)
apply simp
apply simp
done
lemmas unat_mult_simple = iffD1 [OF unat_mult_lem [where 'a = 32, unfolded word_bits_len_of]]
definition
sum_map :: "('a \<Rightarrow> 'b) \<Rightarrow> ('c \<Rightarrow> 'd) \<Rightarrow> 'a + 'c \<Rightarrow> 'b + 'd" where
"sum_map f g x \<equiv> case x of Inl v \<Rightarrow> Inl (f v) | Inr v' \<Rightarrow> Inr (g v')"
lemma sum_map_simps[simp]:
"sum_map f g (Inl v) = Inl (f v)"
"sum_map f g (Inr w) = Inr (g w)"
by (simp add: sum_map_def)+
lemma if_and_helper:
"(If x v v') && v'' = If x (v && v'') (v' && v'')"
by (simp split: split_if)
lemma unat_Suc2:
fixes n :: "('a :: len) word"
shows
"n \<noteq> -1 \<Longrightarrow> unat (n + 1) = Suc (unat n)"
apply (subst add.commute, rule unatSuc)
apply (subst eq_diff_eq[symmetric], simp add: minus_equation_iff)
done
lemmas unat_eq_1
= unat_eq_0 word_unat.Rep_inject[where y=1, simplified]
lemma cart_singleton_image:
"S \<times> {s} = (\<lambda>v. (v, s)) ` S"
by auto
lemma singleton_eq_o2s:
"({x} = set_option v) = (v = Some x)"
by (cases v, auto)
lemma ran_option_map_restrict_eq:
"\<lbrakk> x \<in> ran (option_map f o g); x \<notin> ran (option_map f o (g |` (- {y}))) \<rbrakk>
\<Longrightarrow> \<exists>v. g y = Some v \<and> f v = x"
apply (clarsimp simp: elim!: ranE)
apply (rename_tac w z)
apply (case_tac "w = y")
apply clarsimp
apply (erule notE, rule_tac a=w in ranI)
apply (simp add: restrict_map_def)
done
lemma option_set_singleton_eq:
"(set_option opt = {v}) = (opt = Some v)"
by (cases opt, simp_all)
lemmas option_set_singleton_eqs
= option_set_singleton_eq
trans[OF eq_commute option_set_singleton_eq]
lemma option_map_comp2:
"option_map (f o g) = option_map f o option_map g"
by (simp add: option.map_comp fun_eq_iff)
lemma rshift_sub_mask_eq:
"(a >> (size a - b)) && mask b = a >> (size a - b)"
using shiftl_shiftr2[where a=a and b=0 and c="size a - b"]
apply (cases "b < size a")
apply simp
apply (simp add: linorder_not_less mask_def word_size
p2_eq_0[THEN iffD2])
done
lemma shiftl_shiftr3:
"b \<le> c \<Longrightarrow> a << b >> c = (a >> c - b) && mask (size a - c)"
apply (cases "b = c")
apply (simp add: shiftl_shiftr1)
apply (simp add: shiftl_shiftr2)
done
lemma and_mask_shiftr_comm:
"m\<le>size w \<Longrightarrow> (w && mask m) >> n = (w >> n) && mask (m-n)"
by (simp add: and_mask shiftr_shiftr) (simp add: word_size shiftl_shiftr3)
lemma and_not_mask_twice:
"(w && ~~ mask n) && ~~ mask m = w && ~~ mask (max m n)"
apply (simp add: and_not_mask)
apply (case_tac "n<m")
apply (simp_all add: shiftl_shiftr2 shiftl_shiftr1 not_less max_def
shiftr_shiftr shiftl_shiftl)
apply (cut_tac and_mask_shiftr_comm
[where w=w and m="size w" and n=m, simplified,symmetric])
apply (simp add: word_size mask_def)
apply (cut_tac and_mask_shiftr_comm
[where w=w and m="size w" and n=n, simplified,symmetric])
apply (simp add: word_size mask_def)
done
(* FIXME: move *)
lemma word_less_cases:
"x < y \<Longrightarrow> x = y - 1 \<or> x < y - (1 ::'a::len word)"
apply (drule word_less_sub_1)
apply (drule order_le_imp_less_or_eq)
apply auto
done
lemma eq_eqI:
"a = b \<Longrightarrow> (a = x) = (b = x)"
by simp
lemma mask_and_mask:
"mask a && mask b = mask (min a b)"
apply (rule word_eqI)
apply (simp add: word_size)
done
lemma mask_eq_0_eq_x:
"(x && w = 0) = (x && ~~ w = x)"
using word_plus_and_or_coroll2[where x=x and w=w]
by auto
lemma mask_eq_x_eq_0:
"(x && w = x) = (x && ~~ w = 0)"
using word_plus_and_or_coroll2[where x=x and w=w]
by auto
definition
"limited_and (x :: ('a :: len) word) y = (x && y = x)"
lemma limited_and_eq_0:
"\<lbrakk> limited_and x z; y && ~~ z = y \<rbrakk> \<Longrightarrow> x && y = 0"
unfolding limited_and_def
apply (subst arg_cong2[where f="op &&"])
apply (erule sym)+
apply (simp(no_asm) add: word_bw_assocs word_bw_comms word_bw_lcs)
done
lemma limited_and_eq_id:
"\<lbrakk> limited_and x z; y && z = z \<rbrakk> \<Longrightarrow> x && y = x"
unfolding limited_and_def
by (erule subst, fastforce simp: word_bw_lcs word_bw_assocs word_bw_comms)
lemma lshift_limited_and:
"limited_and x z \<Longrightarrow> limited_and (x << n) (z << n)"
unfolding limited_and_def
by (simp add: shiftl_over_and_dist[symmetric])
lemma rshift_limited_and:
"limited_and x z \<Longrightarrow> limited_and (x >> n) (z >> n)"
unfolding limited_and_def
by (simp add: shiftr_over_and_dist[symmetric])
lemmas limited_and_simps1 = limited_and_eq_0 limited_and_eq_id
lemmas is_aligned_limited_and
= is_aligned_neg_mask_eq[unfolded mask_def, folded limited_and_def]
lemma compl_of_1: "~~ 1 = (-2 :: ('a :: len) word)"
apply (rule word_bool_alg.compl_eq_compl_iff[THEN iffD1])
apply simp
done
lemmas limited_and_simps = limited_and_simps1
limited_and_simps1[OF is_aligned_limited_and]
limited_and_simps1[OF lshift_limited_and]
limited_and_simps1[OF rshift_limited_and]
limited_and_simps1[OF rshift_limited_and, OF is_aligned_limited_and]
compl_of_1 shiftl_shiftr1[unfolded word_size mask_def]
shiftl_shiftr2[unfolded word_size mask_def]
lemma isRight_case_sum: "isRight x \<Longrightarrow> case_sum f g x = g (theRight x)"
by (clarsimp simp add: isRight_def)
lemma split_word_eq_on_mask:
"(x = y) = (x && m = y && m \<and> x && ~~ m = y && ~~ m)"
apply safe
apply (rule word_eqI)
apply (drule_tac x=n in word_eqD)+
apply (simp add: word_size word_ops_nth_size)
apply auto
done
lemma inj_case_bool:
"inj (case_bool a b) = (a \<noteq> b)"
by (auto dest: inj_onD[where x=True and y=False]
intro: inj_onI split: bool.split_asm)
lemma zip_map2:
"zip as (map f bs) = map (\<lambda>(a, b). (a, f b)) (zip as bs)"
apply (induct bs arbitrary: as)
apply simp
apply (case_tac as)
apply simp
apply simp
done
lemma zip_same: "zip xs xs = map (\<lambda>v. (v, v)) xs"
by (induct xs, simp+)
lemma foldl_fun_upd:
"foldl (\<lambda>s r. s (r := g r)) f rs
= (\<lambda>x. if x \<in> set rs then g x else f x)"
apply (induct rs arbitrary: f)
apply simp
apply (auto simp: fun_eq_iff split: split_if)
done
lemma all_rv_choice_fn_eq_pred:
"\<lbrakk> \<And>rv. P rv \<Longrightarrow> \<exists>fn. f rv = g fn \<rbrakk>
\<Longrightarrow> \<exists>fn. \<forall>rv. P rv \<longrightarrow> f rv = g (fn rv)"
apply (rule_tac x="\<lambda>rv. SOME h. f rv = g h" in exI)
apply (clarsimp split: split_if)
apply (erule meta_allE, drule(1) meta_mp, elim exE)
apply (erule someI)
done
lemma ex_const_function:
"\<exists>f. \<forall>s. f (f' s) = v"
by force
lemma sum_to_zero:
"(a :: 'a :: ring) + b = 0 \<Longrightarrow> a = (- b)"
by (drule arg_cong[where f="\<lambda> x. x - a"], simp)
lemma nat_le_Suc_less_imp:
"x < y \<Longrightarrow> x \<le> y - Suc 0"
by arith
lemma list_case_If2:
"case_list f g xs = If (xs = []) f (g (hd xs) (tl xs))"
by (simp split: list.split)
lemma length_ineq_not_Nil:
"length xs > n \<Longrightarrow> xs \<noteq> []"
"length xs \<ge> n \<Longrightarrow> n \<noteq> 0 \<longrightarrow> xs \<noteq> []"
"\<not> length xs < n \<Longrightarrow> n \<noteq> 0 \<longrightarrow> xs \<noteq> []"
"\<not> length xs \<le> n \<Longrightarrow> xs \<noteq> []"
by auto
lemma numeral_eqs:
"2 = Suc (Suc 0)"
"3 = Suc (Suc (Suc 0))"
"4 = Suc (Suc (Suc (Suc 0)))"
"5 = Suc (Suc (Suc (Suc (Suc 0))))"
"6 = Suc (Suc (Suc (Suc (Suc (Suc 0)))))"
by simp+
lemma psubset_singleton:
"(S \<subset> {x}) = (S = {})"
by blast
lemma ucast_not_helper:
fixes a::word8
assumes a: "a \<noteq> 0xFF"
shows "ucast a \<noteq> (0xFF::word32)"
proof
assume "ucast a = (0xFF::word32)"
also
have "(0xFF::word32) = ucast (0xFF::word8)" by simp
finally
show False using a
apply -
apply (drule up_ucast_inj, simp)
apply simp
done
qed
lemma length_takeWhile_ge:
"length (takeWhile f xs) = n
\<Longrightarrow> length xs = n \<or> (length xs > n \<and> \<not> f (xs ! n))"
apply (induct xs arbitrary: n)
apply simp
apply (simp split: split_if_asm)
apply (case_tac n, simp_all)
done
lemma length_takeWhile_le:
"\<not> f (xs ! n) \<Longrightarrow>
length (takeWhile f xs) \<le> n"
apply (induct xs arbitrary: n)
apply simp
apply (clarsimp split: split_if)
apply (case_tac n, simp_all)
done
lemma length_takeWhile_gt:
"n < length (takeWhile f xs)
\<Longrightarrow> (\<exists>ys zs. length ys = Suc n \<and> xs = ys @ zs \<and> takeWhile f xs = ys @ takeWhile f zs)"
apply (induct xs arbitrary: n)
apply simp
apply (simp split: split_if_asm)
apply (case_tac n, simp_all)
apply (rule_tac x="[a]" in exI)
apply simp
apply (erule meta_allE, drule(1) meta_mp)
apply clarsimp
apply (rule_tac x="a # ys" in exI)
apply simp
done
lemma hd_drop_conv_nth2:
"n < length xs \<Longrightarrow> hd (drop n xs) = xs ! n"
by (rule hd_drop_conv_nth, clarsimp+)
lemma map_upt_eq_vals_D:
"\<lbrakk> map f [0 ..< n] = ys; m < length ys \<rbrakk> \<Longrightarrow> f m = ys ! m"
by clarsimp
lemma length_le_helper:
"\<lbrakk> n \<le> length xs; n \<noteq> 0 \<rbrakk> \<Longrightarrow> xs \<noteq> [] \<and> n - 1 \<le> length (tl xs)"
by (cases xs, simp_all)
lemma all_ex_eq_helper:
"(\<forall>v. (\<exists>v'. v = f v' \<and> P v v') \<longrightarrow> Q v)
= (\<forall>v'. P (f v') v' \<longrightarrow> Q (f v'))"
by auto
lemma less_4_cases:
"(x::word32) < 4 \<Longrightarrow> x=0 \<or> x=1 \<or> x=2 \<or> x=3"
apply clarsimp
apply (drule word_less_cases, erule disjE, simp, simp)+
done
lemma if_n_0_0:
"((if P then n else 0) \<noteq> 0) = (P \<and> n \<noteq> 0)"
by (simp split: split_if)
lemma insert_dom:
assumes fx: "f x = Some y"
shows "insert x (dom f) = dom f"
unfolding dom_def using fx by auto
lemma map_comp_subset_dom:
"dom (prj \<circ>\<^sub>m f) \<subseteq> dom f"
unfolding dom_def
by (auto simp: map_comp_Some_iff)
lemmas map_comp_subset_domD = subsetD [OF map_comp_subset_dom]
lemma dom_map_comp:
"x \<in> dom (prj \<circ>\<^sub>m f) = (\<exists>y z. f x = Some y \<and> prj y = Some z)"
by (fastforce simp: dom_def map_comp_Some_iff)
lemma option_map_Some_eq2:
"(Some y = option_map f x) = (\<exists>z. x = Some z \<and> f z = y)"
by (metis map_option_eq_Some)
lemma option_map_eq_dom_eq:
assumes ome: "option_map f \<circ> g = option_map f \<circ> g'"
shows "dom g = dom g'"
proof (rule set_eqI)
fix x
{
assume "x \<in> dom g"
hence "Some (f (the (g x))) = (option_map f \<circ> g) x"
by (auto simp: map_option_case split: option.splits)
also have "\<dots> = (option_map f \<circ> g') x" by (simp add: ome)
finally have "x \<in> dom g'"
by (auto simp: map_option_case split: option.splits)
} moreover
{
assume "x \<in> dom g'"
hence "Some (f (the (g' x))) = (option_map f \<circ> g') x"
by (auto simp: map_option_case split: option.splits)
also have "\<dots> = (option_map f \<circ> g) x" by (simp add: ome)
finally have "x \<in> dom g"
by (auto simp: map_option_case split: option.splits)
} ultimately show "(x \<in> dom g) = (x \<in> dom g')" by auto
qed
lemma map_comp_eqI:
assumes dm: "dom g = dom g'"
and fg: "\<And>x. x \<in> dom g' \<Longrightarrow> f (the (g' x)) = f (the (g x))"
shows "f \<circ>\<^sub>m g = f \<circ>\<^sub>m g'"
apply (rule ext)
apply (case_tac "x \<in> dom g")
apply (frule subst [OF dm])
apply (clarsimp split: option.splits)
apply (frule domI [where m = g'])
apply (drule fg)
apply simp
apply (frule subst [OF dm])
apply clarsimp
apply (drule not_sym)
apply (clarsimp simp: map_comp_Some_iff)
done
lemma is_aligned_0:
"is_aligned 0 n"
unfolding is_aligned_def
by simp
lemma compD:
"\<lbrakk>f \<circ> g = f \<circ> g'; g x = v \<rbrakk> \<Longrightarrow> f (g' x) = f v"
apply clarsimp
apply (subgoal_tac "(f (g x)) = (f \<circ> g) x")
apply simp
apply (simp (no_asm))
done
lemma option_map_comp_eqE:
assumes om: "option_map f \<circ> mp = option_map f \<circ> mp'"
and p1: "\<lbrakk> mp x = None; mp' x = None \<rbrakk> \<Longrightarrow> P"
and p2: "\<And>v v'. \<lbrakk> mp x = Some v; mp' x = Some v'; f v = f v' \<rbrakk> \<Longrightarrow> P"
shows "P"
proof (cases "mp x")
case None
hence "x \<notin> dom mp" by (simp add: domIff)
hence "mp' x = None" by (simp add: option_map_eq_dom_eq [OF om] domIff)
with None show ?thesis by (rule p1)
next
case (Some v)
hence "x \<in> dom mp" by clarsimp
then obtain v' where Some': "mp' x = Some v'" by (clarsimp simp add: option_map_eq_dom_eq [OF om])
with Some show ?thesis
proof (rule p2)
show "f v = f v'" using Some' compD [OF om, OF Some] by simp
qed
qed
lemma Some_the:
"x \<in> dom f \<Longrightarrow> f x = Some (the (f x))"
by clarsimp
lemma map_comp_update:
"f \<circ>\<^sub>m (g(x \<mapsto> v)) = (f \<circ>\<^sub>m g)(x := f v)"
apply (rule ext)
apply clarsimp
apply (case_tac "g xa")
apply simp
apply simp
done
lemma restrict_map_eqI:
assumes req: "A |` S = B |` S"
and mem: "x \<in> S"
shows "A x = B x"
proof -
from mem have "A x = (A |` S) x" by simp
also have "\<dots> = (B |` S) x" using req by simp
also have "\<dots> = B x" using mem by simp
finally show ?thesis .
qed
lemma word_or_zero:
"(a || b = 0) = (a = 0 \<and> b = 0)"
apply (safe, simp_all)
apply (rule word_eqI, drule_tac x=n in word_eqD, simp)+
done
lemma aligned_shiftr_mask_shiftl:
"is_aligned x n \<Longrightarrow> ((x >> n) && mask v) << n = x && mask (v + n)"
apply (rule word_eqI)
apply (simp add: word_size nth_shiftl nth_shiftr)
apply (subgoal_tac "\<forall>m. x !! m \<longrightarrow> m \<ge> n")
apply auto[1]
apply (clarsimp simp: is_aligned_mask)
apply (drule_tac x=m in word_eqD)
apply (frule test_bit_size)
apply (simp add: word_size)
done
lemma word_and_1_shiftl:
fixes x :: "('a :: len) word" shows
"x && (1 << n) = (if x !! n then (1 << n) else 0)"
apply (rule word_eqI)
apply (simp add: word_size nth_shiftl split: split_if del: shiftl_1)
apply auto
done
lemmas word_and_1_shiftls
= word_and_1_shiftl[where n=0, simplified]
word_and_1_shiftl[where n=1, simplified]
word_and_1_shiftl[where n=2, simplified]
lemma word_and_mask_shiftl:
"x && (mask n << m) = ((x >> m) && mask n) << m"
apply (rule word_eqI)
apply (simp add: word_size nth_shiftl nth_shiftr)
apply auto
done
lemma toEnum_eq_to_fromEnum_eq:
fixes v :: "'a :: enum" shows
"n \<le> fromEnum (maxBound :: 'a) \<Longrightarrow> (toEnum n = v) = (n = fromEnum v)"
apply (rule iffI)
apply (drule arg_cong[where f=fromEnum])
apply simp
apply (drule arg_cong[where f="toEnum :: nat \<Rightarrow> 'a"])
apply simp
done
lemma if_Const_helper:
"If P (Con x) (Con y) = Con (If P x y)"
by (simp split: split_if)
lemmas if_Some_helper = if_Const_helper[where Con=Some]
lemma expand_restrict_map_eq:
"(m |` S = m' |` S) = (\<forall>x. x \<in> S \<longrightarrow> m x = m' x)"
by (simp add: fun_eq_iff restrict_map_def split: split_if)
lemma unat_ucast_8_32:
fixes x :: "word8"
shows "unat (ucast x :: word32) = unat x"
unfolding ucast_def unat_def
apply (subst int_word_uint)
apply (subst mod_pos_pos_trivial)
apply simp
apply (rule lt2p_lem)
apply simp
apply simp
done
lemma disj_imp_rhs:
"(P \<Longrightarrow> Q) \<Longrightarrow> (P \<or> Q) = Q"
by blast
lemma remove1_filter:
"distinct xs \<Longrightarrow> remove1 x xs = filter (\<lambda>y. x \<noteq> y) xs"
apply (induct xs)
apply simp
apply clarsimp
apply (rule sym, rule filter_True)
apply clarsimp
done
lemma if_then_1_else_0:
"((if P then 1 else 0) = (0 :: word32)) = (\<not> P)"
by simp
lemma if_then_0_else_1:
"((if P then 0 else 1) = (0 :: word32)) = (P)"
by simp
lemmas if_then_simps = if_then_0_else_1 if_then_1_else_0
lemma nat_less_cases':
"(x::nat) < y \<Longrightarrow> x = y - 1 \<or> x < y - 1"
by (fastforce intro: nat_less_cases)
lemma word32_FF_is_mask:
"0xFF = mask 8 "
by (simp add: mask_def)
lemma filter_to_shorter_upto:
"n \<le> m \<Longrightarrow> filter (\<lambda>x. x < n) [0 ..< m] = [0 ..< n]"
apply (induct m)
apply simp
apply clarsimp
apply (erule le_SucE)
apply simp
apply simp
done
lemma in_emptyE: "\<lbrakk> A = {}; x \<in> A \<rbrakk> \<Longrightarrow> P" by blast
lemma ucast_of_nat_small:
"x < 2 ^ len_of TYPE('a) \<Longrightarrow>
ucast (of_nat x :: ('a :: len) word) = (of_nat x :: ('b :: len) word)"
apply (rule sym, subst word_unat.inverse_norm)
apply (simp add: ucast_def word_of_int[symmetric]
of_nat_nat[symmetric] unat_def[symmetric])
apply (simp add: unat_of_nat)
done
lemma word_le_make_less:
fixes x :: "('a :: len) word"
shows "y \<noteq> -1 \<Longrightarrow> (x \<le> y) = (x < (y + 1))"
apply safe
apply (erule plus_one_helper2)
apply (simp add: eq_diff_eq[symmetric])
done
lemma Ball_emptyI:
"S = {} \<Longrightarrow> (\<forall>x \<in> S. P x)"
by simp
lemma allfEI:
"\<lbrakk> \<forall>x. P x; \<And>x. P (f x) \<Longrightarrow> Q x \<rbrakk> \<Longrightarrow> \<forall>x. Q x"
by fastforce
lemma arith_is_1:
"\<lbrakk> x \<le> Suc 0; x > 0 \<rbrakk> \<Longrightarrow> x = 1"
by arith
(* sjw: combining lemmas here :( *)
lemma cart_singleton_empty2:
"({x} \<times> S = {}) = (S = {})"
"({} = S \<times> {e}) = (S = {})"
by auto
lemma cases_simp_conj:
"((P \<longrightarrow> Q) \<and> (\<not> P \<longrightarrow> Q) \<and> R) = (Q \<and> R)"
by fastforce
lemma domE :
"\<lbrakk> x \<in> dom m; \<And>r. \<lbrakk>m x = Some r\<rbrakk> \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P"
by clarsimp
lemma dom_eqD:
"\<lbrakk> f x = Some v; dom f = S \<rbrakk> \<Longrightarrow> x \<in> S"
by clarsimp
lemma exception_set_finite:
"finite {x. P x} \<Longrightarrow> finite {x. (x = y \<longrightarrow> Q x) \<and> P x}"
"finite {x. P x} \<Longrightarrow> finite {x. x \<noteq> y \<longrightarrow> P x}"
apply (simp add: Collect_conj_eq)
apply (subst imp_conv_disj, subst Collect_disj_eq)
apply simp
done
lemma exfEI:
"\<lbrakk> \<exists>x. P x; \<And>x. P x \<Longrightarrow> Q (f x) \<rbrakk> \<Longrightarrow> \<exists>x. Q x"
by fastforce
lemma finite_word: "finite (S :: (('a :: len) word) set)"
by (rule finite)
lemma if_f:
"(if a then f b else f c) = f (if a then b else c)"
by simp
lemma in_16_range:
"0 \<in> S \<Longrightarrow> r \<in> (\<lambda>x. r + x * (16 :: word32)) ` S"
"n - 1 \<in> S \<Longrightarrow> (r + (16 * n - 16)) \<in> (\<lambda>x :: word32. r + x * 16) ` S"
by (clarsimp simp: image_def
elim!: bexI[rotated])+
definition
"modify_map m p f \<equiv> m (p := option_map f (m p))"
lemma modify_map_id:
"modify_map m p id = m"
by (auto simp add: modify_map_def map_option_case split: option.splits)
lemma modify_map_addr_com:
assumes com: "x \<noteq> y"
shows "modify_map (modify_map m x g) y f = modify_map (modify_map m y f) x g"
by (rule ext)
(simp add: modify_map_def map_option_case com split: option.splits)
lemma modify_map_dom :
"dom (modify_map m p f) = dom m"
unfolding modify_map_def
apply (cases "m p")
apply simp
apply (simp add: dom_def)
apply simp
apply (rule insert_absorb)
apply (simp add: dom_def)
done
lemma modify_map_None:
"m x = None \<Longrightarrow> modify_map m x f = m"
by (rule ext) (simp add: modify_map_def)
lemma modify_map_ndom :
"x \<notin> dom m \<Longrightarrow> modify_map m x f = m"
by (rule modify_map_None) clarsimp
lemma modify_map_app:
"(modify_map m p f) q = (if p = q then option_map f (m p) else m q)"
unfolding modify_map_def by simp
lemma modify_map_apply:
"m p = Some x \<Longrightarrow> modify_map m p f = m (p \<mapsto> f x)"
by (simp add: modify_map_def)
lemma modify_map_com:
assumes com: "\<And>x. f (g x) = g (f x)"
shows "modify_map (modify_map m x g) y f = modify_map (modify_map m y f) x g"
using assms by (auto simp: modify_map_def map_option_case split: option.splits)
lemma modify_map_comp:
"modify_map m x (f o g) = modify_map (modify_map m x g) x f"
by (rule ext) (simp add: modify_map_def option.map_comp)
lemma modify_map_exists_eq:
"(\<exists>cte. modify_map m p' f p= Some cte) = (\<exists>cte. m p = Some cte)"
by (auto simp: modify_map_def split: if_splits)
lemma modify_map_other:
"p \<noteq> q \<Longrightarrow> (modify_map m p f) q = (m q)"
by (simp add: modify_map_app)
lemma modify_map_same:
"(modify_map m p f) p = (option_map f (m p))"
by (simp add: modify_map_app)
lemma next_update_is_modify:
"\<lbrakk> m p = Some cte'; cte = f cte' \<rbrakk> \<Longrightarrow> (m(p \<mapsto> cte)) = (modify_map m p f)"
unfolding modify_map_def by simp
lemma nat_power_minus_less:
"a < 2 ^ (x - n) \<Longrightarrow> (a :: nat) < 2 ^ x"
apply (erule order_less_le_trans)
apply simp
done
lemma neg_rtranclI:
"\<lbrakk> x \<noteq> y; (x, y) \<notin> R\<^sup>+ \<rbrakk> \<Longrightarrow> (x, y) \<notin> R\<^sup>*"
apply (erule contrapos_nn)
apply (drule rtranclD)
apply simp
done
lemma neg_rtrancl_into_trancl:
"\<not> (x, y) \<in> R\<^sup>* \<Longrightarrow> \<not> (x, y) \<in> R\<^sup>+"
by (erule contrapos_nn, erule trancl_into_rtrancl)
lemma set_neqI:
"\<lbrakk> x \<in> S; x \<notin> S' \<rbrakk> \<Longrightarrow> S \<noteq> S'"
by clarsimp
lemma set_pair_UN:
"{x. P x} = UNION {xa. \<exists>xb. P (xa, xb)} (\<lambda>xa. {xa} \<times> {xb. P (xa, xb)})"
apply safe
apply (rule_tac a=a in UN_I)
apply blast+
done
lemma singleton_elemD:
"S = {x} \<Longrightarrow> x \<in> S"
by simp
lemma word_to_1_set:
"{0 ..< (1 :: ('a :: len) word)} = {0}"
by fastforce
lemma ball_ran_eq:
"(\<forall>y \<in> ran m. P y) = (\<forall>x y. m x = Some y \<longrightarrow> P y)"
by (auto simp add: ran_def)
lemma cart_helper:
"({} = {x} \<times> S) = (S = {})"
by blast
lemmas converse_trancl_induct' = converse_trancl_induct [consumes 1, case_names base step]
lemma disjCI2: "(\<not> P \<Longrightarrow> Q) \<Longrightarrow> P \<or> Q" by blast
lemma insert_UNIV :
"insert x UNIV = UNIV"
by blast
lemma not_singletonE:
"\<lbrakk> \<forall>p. S \<noteq> {p}; S \<noteq> {}; \<And>p p'. \<lbrakk> p \<noteq> p'; p \<in> S; p' \<in> S \<rbrakk> \<Longrightarrow> R \<rbrakk> \<Longrightarrow> R"
by blast
lemma not_singleton_oneE:
"\<lbrakk> \<forall>p. S \<noteq> {p}; p \<in> S; \<And>p'. \<lbrakk> p \<noteq> p'; p' \<in> S \<rbrakk> \<Longrightarrow> R \<rbrakk> \<Longrightarrow> R"
apply (erule not_singletonE)
apply clarsimp
apply (case_tac "p = p'")
apply fastforce
apply fastforce
done
lemma interval_empty:
"({m..n} = {}) = (\<not> m \<le> (n::'a::order))"
apply (rule iffI)
apply clarsimp
apply auto
done
lemma range_subset_eq2:
"{a :: word32 .. b} \<noteq> {} \<Longrightarrow> ({a .. b} \<subseteq> {c .. d}) = (c \<le> a \<and> b \<le> d)"
by (simp add: interval_empty)
lemma singleton_eqD: "A = {x} \<Longrightarrow> x \<in> A" by blast
lemma ball_ran_fun_updI:
"\<lbrakk> \<forall>v \<in> ran m. P v; \<forall>v. y = Some v \<longrightarrow> P v \<rbrakk>
\<Longrightarrow> \<forall>v \<in> ran (m (x := y)). P v"
by (auto simp add: ran_def)
lemma ball_ran_modify_map_eq:
"\<lbrakk> \<forall>v. m x = Some v \<longrightarrow> P (f v) = P v \<rbrakk>
\<Longrightarrow> (\<forall>v \<in> ran (modify_map m x f). P v) = (\<forall>v \<in> ran m. P v)"
apply (simp add: ball_ran_eq)
apply (rule iff_allI)
apply (auto simp: modify_map_def)
done
lemma disj_imp: "(P \<or> Q) = (\<not>P \<longrightarrow> Q)" by blast
lemma eq_singleton_redux:
"\<lbrakk> S = {x} \<rbrakk> \<Longrightarrow> x \<in> S"
by simp
lemma if_eq_elem_helperE:
"\<lbrakk> x \<in> (if P then S else S');
\<lbrakk> P; x \<in> S \<rbrakk> \<Longrightarrow> a = b;
\<lbrakk> \<not> P; x \<in> S' \<rbrakk> \<Longrightarrow> a = c
\<rbrakk> \<Longrightarrow> a = (if P then b else c)"
by fastforce
lemma if_option_Some :
"((if P then None else Some x) = Some y) = (\<not>P \<and> x = y)"
by simp
lemma insert_minus_eq:
"x \<notin> A \<Longrightarrow> A - S = (A - (S - {x}))"
by auto
lemma map2_Cons_2_3:
"(map2 f xs (y # ys) = (z # zs)) = (\<exists>x xs'. xs = x # xs' \<and> f x y = z \<and> map2 f xs' ys = zs)"
by (case_tac xs, simp_all)
lemma map2_xor_replicate_False:
"map2 (\<lambda>(x\<Colon>bool) y\<Colon>bool. x = (\<not> y)) xs (replicate n False) = take n xs"
apply (induct xs arbitrary: n)
apply simp
apply (case_tac n)
apply (simp add: map2_def)
apply simp
done
lemma modify_map_K_D:
"modify_map m p (\<lambda>x. y) p' = Some v \<Longrightarrow> (m (p \<mapsto> y)) p' = Some v"
by (simp add: modify_map_def split: split_if_asm)
lemmas tranclE2' = tranclE2 [consumes 1, case_names base trancl]
lemma weak_imp_cong:
"\<lbrakk> P = R; Q = S \<rbrakk> \<Longrightarrow> (P \<longrightarrow> Q) = (R \<longrightarrow> S)"
by simp
lemma Collect_Diff_restrict_simp:
"T - {x \<in> T. Q x} = T - {x. Q x}"
by (auto intro: Collect_cong)
lemma Collect_Int_pred_eq:
"{x \<in> S. P x} \<inter> {x \<in> T. P x} = {x \<in> (S \<inter> T). P x}"
by (simp add: Collect_conj_eq [symmetric] conj_comms)
lemma Collect_restrict_predR:
"{x. P x} \<inter> T = {} \<Longrightarrow> {x. P x} \<inter> {x \<in> T. Q x} = {}"
apply (subst Collect_conj_eq [symmetric])
apply (simp add: disjoint_iff_not_equal)
apply rule
apply (drule_tac x = x in spec)
apply clarsimp
apply (drule (1) bspec)
apply simp
done
lemma Diff_Un2:
assumes emptyad: "A \<inter> D = {}"
and emptybc: "B \<inter> C = {}"
shows "(A \<union> B) - (C \<union> D) = (A - C) \<union> (B - D)"
proof -
have "(A \<union> B) - (C \<union> D) = (A \<union> B - C) \<inter> (A \<union> B - D)"
by (rule Diff_Un)
also have "\<dots> = ((A - C) \<union> B) \<inter> (A \<union> (B - D))" using emptyad emptybc
by (simp add: Un_Diff Diff_triv)
also have "\<dots> = (A - C) \<union> (B - D)"
proof -
have "(A - C) \<inter> (A \<union> (B - D)) = A - C" using emptyad emptybc
by (metis Diff_Int2 Diff_Int_distrib2 inf_sup_absorb)
moreover
have "B \<inter> (A \<union> (B - D)) = B - D" using emptyad emptybc
by (metis Int_Diff Un_Diff Un_Diff_Int Un_commute Un_empty_left inf_sup_absorb)
ultimately show ?thesis
by (simp add: Int_Un_distrib2)
qed
finally show ?thesis .
qed
lemma ballEI:
"\<lbrakk> \<forall>x \<in> S. Q x; \<And>x. \<lbrakk> x \<in> S; Q x \<rbrakk> \<Longrightarrow> P x \<rbrakk> \<Longrightarrow> \<forall>x \<in> S. P x"
by auto
lemma dom_if_None:
"dom (\<lambda>x. if P x then None else f x)
= dom f - {x. P x}"
by (simp add: dom_def, fastforce)
lemma notemptyI:
"x \<in> S \<Longrightarrow> S \<noteq> {}"
by clarsimp
lemma plus_Collect_helper:
"op + x ` {xa. P (xa :: ('a :: len) word)} = {xa. P (xa - x)}"
by (fastforce simp add: image_def)
lemma plus_Collect_helper2:
"op + (- x) ` {xa. P (xa :: ('a :: len) word)} = {xa. P (x + xa)}"
by (simp add: field_simps plus_Collect_helper)
lemma restrict_map_Some_iff:
"((m |` S) x = Some y) = (m x = Some y \<and> x \<in> S)"
by (cases "x \<in> S", simp_all)
lemma context_case_bools:
"\<lbrakk> \<And>v. P v \<Longrightarrow> R v; \<lbrakk> \<not> P v; \<And>v. P v \<Longrightarrow> R v \<rbrakk> \<Longrightarrow> R v \<rbrakk> \<Longrightarrow> R v"
by (cases "P v", simp_all)
lemma inj_on_fun_upd_strongerI:
"\<lbrakk>inj_on f A; y \<notin> f ` (A - {x})\<rbrakk> \<Longrightarrow> inj_on (f(x := y)) A"
apply (simp add: inj_on_def)
apply blast
done
lemma less_handy_casesE:
"\<lbrakk> m < n; m = 0 \<Longrightarrow> R;
\<And>m' n'. \<lbrakk> n = Suc n'; m = Suc m'; m < n \<rbrakk> \<Longrightarrow> R \<rbrakk>
\<Longrightarrow> R"
apply (case_tac n, simp_all)
apply (case_tac m, simp_all)
done
lemma subset_drop_Diff_strg:
"(A \<subseteq> C) \<longrightarrow> (A - B \<subseteq> C)"
by blast
lemma word32_count_from_top:
"n \<noteq> 0 \<Longrightarrow> {0 ..< n :: word32} = {0 ..< n - 1} \<union> {n - 1}"
apply (rule set_eqI, rule iffI)
apply simp
apply (drule minus_one_helper3)
apply (rule disjCI)
apply simp
apply simp
apply (erule minus_one_helper5)
apply fastforce
done
lemma Int_Union_empty:
"(\<And>x. x \<in> S \<Longrightarrow> A \<inter> P x = {}) \<Longrightarrow> A \<inter> (\<Union>x \<in> S. P x) = {}"
by auto
lemma UN_Int_empty:
"(\<And>x. x \<in> S \<Longrightarrow> P x \<inter> T = {}) \<Longrightarrow> (\<Union>x \<in> S. P x) \<inter> T = {}"
by auto
lemma disjointI:
"\<lbrakk>\<And>x y. \<lbrakk> x \<in> A; y \<in> B \<rbrakk> \<Longrightarrow> x \<noteq> y \<rbrakk> \<Longrightarrow> A \<inter> B = {}"
by auto
lemma UN_disjointI:
assumes rl: "\<And>x y. \<lbrakk> x \<in> A; y \<in> B \<rbrakk> \<Longrightarrow> P x \<inter> Q y = {}"
shows "(\<Union>x \<in> A. P x) \<inter> (\<Union>x \<in> B. Q x) = {}"
apply (rule disjointI)
apply clarsimp
apply (drule (1) rl)
apply auto
done
lemma UN_set_member:
assumes sub: "A \<subseteq> (\<Union>x \<in> S. P x)"
and nz: "A \<noteq> {}"
shows "\<exists>x \<in> S. P x \<inter> A \<noteq> {}"
proof -
from nz obtain z where zA: "z \<in> A" by fastforce
with sub obtain x where "x \<in> S" and "z \<in> P x" by auto
hence "P x \<inter> A \<noteq> {}" using zA by auto
thus ?thesis using sub nz by auto
qed
lemma append_Cons_cases [consumes 1, case_names pre mid post]:
"\<lbrakk>(x, y) \<in> set (as @ b # bs);
(x, y) \<in> set as \<Longrightarrow> R;
\<lbrakk>(x, y) \<notin> set as; (x, y) \<notin> set bs; (x, y) = b\<rbrakk> \<Longrightarrow> R;
(x, y) \<in> set bs \<Longrightarrow> R\<rbrakk>
\<Longrightarrow> R" by auto
lemma cart_singletons:
"{a} \<times> {b} = {(a, b)}"
by blast
lemma disjoint_subset_neg1:
"\<lbrakk> B \<inter> C = {}; A \<subseteq> B; A \<noteq> {} \<rbrakk> \<Longrightarrow> \<not> A \<subseteq> C"
by auto
lemma disjoint_subset_neg2:
"\<lbrakk> B \<inter> C = {}; A \<subseteq> C; A \<noteq> {} \<rbrakk> \<Longrightarrow> \<not> A \<subseteq> B"
by auto
lemma iffE2:
"\<lbrakk> P = Q; \<lbrakk> P; Q \<rbrakk> \<Longrightarrow> R; \<lbrakk> \<not> P; \<not> Q \<rbrakk> \<Longrightarrow> R \<rbrakk> \<Longrightarrow> R"
by blast
lemma minus_one_helper2:
"\<lbrakk> x - 1 < y \<rbrakk> \<Longrightarrow> x \<le> (y :: ('a :: len) word)"
apply (cases "x = 0")
apply simp
apply (simp add: word_less_nat_alt word_le_nat_alt)
apply (subst(asm) unat_minus_one)
apply (simp add: word_less_nat_alt)
apply (cases "unat x")
apply (simp add: unat_eq_zero)
apply arith
done
lemma mod_mod_power:
fixes k :: nat
shows "k mod 2 ^ m mod 2 ^ n = k mod 2 ^ (min m n)"
proof (cases "m \<le> n")
case True
hence "k mod 2 ^ m mod 2 ^ n = k mod 2 ^ m"
apply -
apply (subst mod_less [where n = "2 ^ n"])
apply (rule order_less_le_trans [OF mod_less_divisor])
apply simp+
done
also have "\<dots> = k mod 2 ^ (min m n)" using True by simp
finally show ?thesis .
next
case False
hence "n < m" by simp
then obtain d where md: "m = n + d"
by (auto dest: less_imp_add_positive)
hence "k mod 2 ^ m = 2 ^ n * (k div 2 ^ n mod 2 ^ d) + k mod 2 ^ n"
by (simp add: mod_mult2_eq power_add)
hence "k mod 2 ^ m mod 2 ^ n = k mod 2 ^ n"
by (simp add: mod_add_left_eq)
thus ?thesis using False
by simp
qed
lemma word_div_less:
fixes m :: "'a :: len word"
shows "m < n \<Longrightarrow> m div n = 0"
apply (rule word_unat.Rep_eqD)
apply (simp add: word_less_nat_alt unat_div)
done
lemma word_must_wrap:
"\<lbrakk> x \<le> n - 1; n \<le> x \<rbrakk> \<Longrightarrow> n = (0 :: ('a :: len) word)"
apply (rule ccontr)
apply (drule(1) order_trans)
apply (drule word_sub_1_le)
apply (drule(1) order_antisym)
apply simp
done
lemma upt_add_eq_append':
assumes a1: "i \<le> j" and a2: "j \<le> k"
shows "[i..<k] = [i..<j] @ [j..<k]"
using a1 a2
by (clarsimp simp: le_iff_add intro!: upt_add_eq_append)
lemma range_subset_card:
"\<lbrakk> {a :: ('a :: len) word .. b} \<subseteq> {c .. d}; b \<ge> a \<rbrakk>
\<Longrightarrow> d \<ge> c \<and> d - c \<ge> b - a"
apply (subgoal_tac "a \<in> {a .. b}")
apply (frule(1) range_subset_lower)
apply (frule(1) range_subset_upper)
apply (rule context_conjI, simp)
apply (rule word_sub_mono, assumption+)
apply (erule word_sub_le)
apply (erule word_sub_le)
apply simp
done
lemma less_1_simp:
"n - 1 < m = (n \<le> (m :: ('a :: len) word) \<and> n \<noteq> 0)"
by unat_arith
lemma alignUp_div_helper:
fixes a :: "'a::len word"
assumes kv: "k < 2 ^ (len_of TYPE('a) - n)"
and xk: "x = 2 ^ n * of_nat k"
and le: "a \<le> x"
and sz: "n < len_of TYPE('a)"
and anz: "a mod 2 ^ n \<noteq> 0"
shows "a div 2 ^ n < of_nat k"
proof -
have kn: "unat (of_nat k :: 'a word) * unat ((2::'a word) ^ n)
< 2 ^ len_of TYPE('a)"
using xk kv sz
apply (subst unat_of_nat_eq)
apply (erule order_less_le_trans)
apply simp
apply (subst unat_power_lower, simp add: word_bits_def)
apply (subst mult.commute)
apply (rule nat_less_power_trans)
apply simp
apply simp
done
have "unat a div 2 ^ n * 2 ^ n \<noteq> unat a"
proof -
have "unat a = unat a div 2 ^ n * 2 ^ n + unat a mod 2 ^ n"
by (simp add: mod_div_equality)
also have "\<dots> \<noteq> unat a div 2 ^ n * 2 ^ n" using sz anz
by (simp add: unat_arith_simps word_bits_def)
finally show ?thesis ..
qed
hence "a div 2 ^ n * 2 ^ n < a" using sz anz
apply (subst word_less_nat_alt)
apply (subst unat_word_ariths)
apply (subst unat_div)
apply simp
apply (rule order_le_less_trans [OF mod_le_dividend])
apply (erule order_le_neq_trans [OF div_mult_le])
done
also from xk le have "\<dots> \<le> of_nat k * 2 ^ n" by (simp add: field_simps)
finally show ?thesis using sz kv
apply -
apply (erule word_mult_less_dest [OF _ _ kn])
apply (simp add: unat_div)
apply (rule order_le_less_trans [OF div_mult_le])
apply (rule unat_lt2p)
done
qed
lemma nat_mod_power_lem:
fixes a :: nat
shows "1 < a \<Longrightarrow> a ^ n mod a ^ m = (if m \<le> n then 0 else a ^ n)"
apply (clarsimp)
apply (clarsimp simp add: le_iff_add power_add)
done
lemma power_mod_div:
fixes x :: "nat"
shows "x mod 2 ^ n div 2 ^ m = x div 2 ^ m mod 2 ^ (n - m)" (is "?LHS = ?RHS")
proof (cases "n \<le> m")
case True
hence "?LHS = 0"
apply -
apply (rule div_less)
apply (rule order_less_le_trans [OF mod_less_divisor])
apply simp
apply simp
done
also have "\<dots> = ?RHS" using True
by simp
finally show ?thesis .
next
case False
hence lt: "m < n" by simp
then obtain q where nv: "n = m + q" and "0 < q"
by (auto dest: less_imp_Suc_add)
hence "x mod 2 ^ n = 2 ^ m * (x div 2 ^ m mod 2 ^ q) + x mod 2 ^ m"
by (simp add: power_add mod_mult2_eq)
hence "?LHS = x div 2 ^ m mod 2 ^ q"
by (simp add: div_add1_eq)
also have "\<dots> = ?RHS" using nv
by simp
finally show ?thesis .
qed
lemma word_power_mod_div:
fixes x :: "'a::len word"
shows "\<lbrakk> n < len_of TYPE('a); m < len_of TYPE('a)\<rbrakk>
\<Longrightarrow> x mod 2 ^ n div 2 ^ m = x div 2 ^ m mod 2 ^ (n - m)"
apply (simp add: word_arith_nat_div unat_mod power_mod_div)
apply (subst unat_arith_simps(3))
apply (subst unat_mod)
apply (subst unat_of_nat)+
apply (simp add: mod_mod_power min.commute)
done
(* FIXME: stronger version of GenericLib.p_assoc_help *)
lemma x_power_minus_1:
fixes x :: "'a :: {ab_group_add, power, numeral, one}"
shows "x + (2::'a) ^ n - (1::'a) = x + (2 ^ n - 1)" by simp
lemma nat_le_power_trans:
fixes n :: nat
shows "\<lbrakk>n \<le> 2 ^ (m - k); k \<le> m\<rbrakk> \<Longrightarrow> 2 ^ k * n \<le> 2 ^ m"
apply (drule order_le_imp_less_or_eq)
apply (erule disjE)
apply (drule (1) nat_less_power_trans)
apply (erule order_less_imp_le)
apply (simp add: power_add [symmetric])
done
lemma nat_diff_add:
fixes i :: nat
shows "\<lbrakk> i + j = k \<rbrakk> \<Longrightarrow> i = k - j"
by arith
lemma word_range_minus_1':
fixes a :: "'a :: len word"
shows "a \<noteq> 0 \<Longrightarrow> {a - 1<..b} = {a..b}"
by (simp add: greaterThanAtMost_def atLeastAtMost_def greaterThan_def atLeast_def less_1_simp)
lemma word_range_minus_1:
fixes a :: word32
shows "b \<noteq> 0 \<Longrightarrow> {a..b - 1} = {a..<b}"
apply (simp add: atLeastLessThan_def atLeastAtMost_def atMost_def lessThan_def)
apply (rule arg_cong [where f = "\<lambda>x. {a..} \<inter> x"])
apply rule
apply clarsimp
apply (erule contrapos_pp)
apply (simp add: linorder_not_less linorder_not_le word_must_wrap)
apply (clarsimp)
apply (drule minus_one_helper3)
apply (auto simp: word_less_sub_1)
done
lemma ucast_nat_def:
"of_nat (unat x) = (ucast :: ('a :: len) word \<Rightarrow> ('b :: len) word) x"
by (simp add: ucast_def word_of_int_nat unat_def)
lemma delete_remove1 :
"delete x xs = remove1 x xs"
by (induct xs, auto)
lemma list_case_If:
"(case xs of [] \<Rightarrow> P | _ \<Rightarrow> Q)
= (if xs = [] then P else Q)"
by (clarsimp simp: neq_Nil_conv)
lemma remove1_Nil_in_set:
"\<lbrakk> remove1 x xs = []; xs \<noteq> [] \<rbrakk> \<Longrightarrow> x \<in> set xs"
by (induct xs) (auto split: split_if_asm)
lemma remove1_empty:
"(remove1 v xs = []) = (xs = [v] \<or> xs = [])"
by (cases xs, simp_all)
lemma set_remove1:
"x \<in> set (remove1 y xs) \<Longrightarrow> x \<in> set xs"
apply (induct xs)
apply simp
apply (case_tac "y = a")
apply clarsimp+
done
lemma If_rearrage:
"(if P then if Q then x else y else z)
= (if P \<and> Q then x else if P then y else z)"
by simp
lemma cases_simp_left:
"((P \<longrightarrow> Q) \<and> (\<not> P \<longrightarrow> Q) \<and> R) = (Q \<and> R)"
by fastforce
lemma disjI2_strg:
"Q \<longrightarrow> (P \<or> Q)"
by simp
lemma eq_2_32_0:
"(2 ^ 32 :: word32) = 0"
by simp
lemma eq_imp_strg:
"P t \<longrightarrow> (t = s \<longrightarrow> P s)"
by clarsimp
lemma if_fun_split:
"(if P then \<lambda>s. Q s else (\<lambda>s. R s)) = (\<lambda>s. (P \<longrightarrow> Q s) \<and> (\<not>P \<longrightarrow> R s))"
by simp
lemma i_hate_words_helper:
"i \<le> (j - k :: nat) \<Longrightarrow> i \<le> j"
by simp
lemma i_hate_words:
"unat (a :: 'a word) \<le> unat (b :: ('a :: len) word) - Suc 0
\<Longrightarrow> a \<noteq> -1"
apply (frule i_hate_words_helper)
apply (subst(asm) word_le_nat_alt[symmetric])
apply (clarsimp simp only: word_minus_one_le)
apply (simp only: linorder_not_less[symmetric])
apply (erule notE)
apply (rule diff_Suc_less)
apply (subst neq0_conv[symmetric])
apply (subst unat_eq_0)
apply (rule notI, drule arg_cong[where f="op + 1"])
apply simp
done
lemma if_both_strengthen:
"P \<and> Q \<longrightarrow> (if G then P else Q)"
by simp
lemma if_both_strengthen2:
"P s \<and> Q s \<longrightarrow> (if G then P else Q) s"
by simp
lemma if_swap:
"(if P then Q else R) = (if \<not>P then R else Q)" by simp
lemma ignore_if:
"(y and z) s \<Longrightarrow> (if x then y else z) s"
by (clarsimp simp: pred_conj_def)
lemma imp_consequent:
"P \<longrightarrow> Q \<longrightarrow> P" by simp
lemma list_case_helper:
"xs \<noteq> [] \<Longrightarrow> case_list f g xs = g (hd xs) (tl xs)"
by (cases xs, simp_all)
lemma list_cons_rewrite:
"(\<forall>x xs. L = x # xs \<longrightarrow> P x xs) = (L \<noteq> [] \<longrightarrow> P (hd L) (tl L))"
by (auto simp: neq_Nil_conv)
lemma list_not_Nil_manip:
"\<lbrakk> xs = y # ys; case xs of [] \<Rightarrow> False | (y # ys) \<Rightarrow> P y ys \<rbrakk> \<Longrightarrow> P y ys"
by simp
lemma ran_ball_triv:
"\<And>P m S. \<lbrakk> \<forall>x \<in> (ran S). P x ; m \<in> (ran S) \<rbrakk> \<Longrightarrow> P m"
by blast
lemma singleton_tuple_cartesian:
"({(a, b)} = S \<times> T) = ({a} = S \<and> {b} = T)"
"(S \<times> T = {(a, b)}) = ({a} = S \<and> {b} = T)"
by blast+
lemma strengthen_ignore_if:
"A s \<and> B s \<longrightarrow> (if P then A else B) s"
by clarsimp
lemma case_sum_True :
"(case r of Inl a \<Rightarrow> True | Inr b \<Rightarrow> f b)
= (\<forall>b. r = Inr b \<longrightarrow> f b)"
by (cases r) auto
lemma sym_ex_elim:
"F x = y \<Longrightarrow> \<exists>x. y = F x"
by auto
lemma tl_drop_1 :
"tl xs = drop 1 xs"
by (simp add: drop_Suc)
lemma upt_lhs_sub_map:
"[x ..< y] = map (op + x) [0 ..< y - x]"
apply (induct y)
apply simp
apply (clarsimp simp: Suc_diff_le)
done
lemma upto_0_to_4:
"[0..<4] = 0 # [1..<4]"
apply (subst upt_rec)
apply simp
done
lemma disjEI:
"\<lbrakk> P \<or> Q; P \<Longrightarrow> R; Q \<Longrightarrow> S \<rbrakk>
\<Longrightarrow> R \<or> S"
by fastforce
lemma dom_fun_upd2:
"s x = Some z \<Longrightarrow> dom (s (x \<mapsto> y)) = dom s"
by (simp add: insert_absorb domI)
lemma foldl_True :
"foldl op \<or> True bs"
by (induct bs) auto
lemma image_set_comp:
"f ` {g x | x. Q x} = (f \<circ> g) ` {x. Q x}"
by fastforce
lemma mutual_exE:
"\<lbrakk> \<exists>x. P x; \<And>x. P x \<Longrightarrow> Q x \<rbrakk> \<Longrightarrow> \<exists>x. Q x"
apply clarsimp
apply blast
done
lemma nat_diff_eq:
fixes x :: nat
shows "\<lbrakk> x - y = x - z; y < x\<rbrakk> \<Longrightarrow> y = z"
by arith
lemma overflow_plus_one_self:
"(1 + p \<le> p) = (p = (-1 :: word32))"
apply (safe, simp_all)
apply (rule ccontr)
apply (drule plus_one_helper2)
apply (rule notI)
apply (drule arg_cong[where f="\<lambda>x. x - 1"])
apply simp
apply (simp add: field_simps)
done
lemma plus_1_less:
"(x + 1 \<le> (x :: ('a :: len) word)) = (x = -1)"
apply (rule iffI)
apply (rule ccontr)
apply (cut_tac plus_one_helper2[where x=x, OF order_refl])
apply simp
apply clarsimp
apply (drule arg_cong[where f="\<lambda>x. x - 1"])
apply simp
apply simp
done
lemma pos_mult_pos_ge:
"[|x > (0::int); n>=0 |] ==> n * x >= n*1"
apply (simp only: mult_left_mono)
done
lemma If_eq_obvious:
"x \<noteq> z \<Longrightarrow> ((if P then x else y) = z) = (\<not> P \<and> y = z)"
by simp
lemma Some_to_the:
"v = Some x \<Longrightarrow> x = the v"
by simp
lemma dom_if_Some:
"dom (\<lambda>x. if P x then Some (f x) else g x) = {x. P x} \<union> dom g"
by fastforce
lemma dom_insert_absorb:
"x \<in> dom f \<Longrightarrow> insert x (dom f) = dom f" by auto
lemma emptyE2:
"\<lbrakk> S = {}; x \<in> S \<rbrakk> \<Longrightarrow> P"
by simp
lemma mod_div_equality_div_eq:
"a div b * b = (a - (a mod b) :: int)"
by (simp add: field_simps)
lemma zmod_helper:
"n mod m = k \<Longrightarrow> ((n :: int) + a) mod m = (k + a) mod m"
by (metis add.commute mod_add_right_eq)
lemma int_div_sub_1:
"\<lbrakk> m \<ge> 1 \<rbrakk> \<Longrightarrow> (n - (1 :: int)) div m = (if m dvd n then (n div m) - 1 else n div m)"
apply (subgoal_tac "m = 0 \<or> (n - (1 :: int)) div m = (if m dvd n then (n div m) - 1 else n div m)")
apply fastforce
apply (subst mult_cancel_right[symmetric])
apply (simp only: left_diff_distrib split: split_if)
apply (simp only: mod_div_equality_div_eq)
apply (clarsimp simp: field_simps)
apply (clarsimp simp: dvd_eq_mod_eq_0)
apply (cases "m = 1")
apply simp
apply (subst mod_diff_eq, simp add: zmod_minus1 mod_pos_pos_trivial)
apply clarsimp
apply (subst diff_add_cancel[where b=1, symmetric])
apply (subst push_mods(1))
apply (simp add: field_simps mod_pos_pos_trivial)
apply (rule mod_pos_pos_trivial)
apply (subst add_0_right[where a=0, symmetric])
apply (rule add_mono)
apply simp
apply simp
apply (cases "(n - 1) mod m = m - 1")
apply (drule zmod_helper[where a=1])
apply simp
apply (subgoal_tac "1 + (n - 1) mod m \<le> m")
apply simp
apply (subst field_simps, rule zless_imp_add1_zle)
apply simp
done
lemmas nat_less_power_trans_16 =
subst [OF mult.commute, where P="\<lambda>x. x < v" for v,
OF nat_less_power_trans[where k=4, simplified]]
lemmas nat_less_power_trans_256 =
subst [OF mult.commute, where P="\<lambda>x. x < v" for v,
OF nat_less_power_trans[where k=8, simplified]]
lemmas nat_less_power_trans_4096 =
subst [OF mult.commute, where P="\<lambda>x. x < v" for v,
OF nat_less_power_trans[where k=12, simplified]]
lemma ptr_add_image_multI:
"\<lbrakk> \<And>x y. (x * val = y * val') = (x * val'' = y); x * val'' \<in> S \<rbrakk> \<Longrightarrow>
ptr_add ptr (x * val) \<in> (\<lambda>p. ptr_add ptr (p * val')) ` S"
apply (simp add: image_def)
apply (erule rev_bexI)
apply (rule arg_cong[where f="ptr_add ptr"])
apply simp
done
lemma shift_times_fold:
"(x :: word32) * (2 ^ n) << m = x << (m + n)"
by (simp add: shiftl_t2n ac_simps power_add)
lemma word_plus_strict_mono_right:
fixes x :: "'a :: len word"
shows "\<lbrakk>y < z; x \<le> x + z\<rbrakk> \<Longrightarrow> x + y < x + z"
by unat_arith
lemma comp_upd_simp:
"(f \<circ> (g (x := y))) = ((f \<circ> g) (x := f y))"
by (rule ext, simp add: o_def)
lemma dom_option_map:
"dom (option_map f o m) = dom m"
by (simp add: dom_def)
lemma drop_imp:
"P \<Longrightarrow> (A \<longrightarrow> P) \<and> (B \<longrightarrow> P)" by blast
lemma inj_on_fun_updI2:
"\<lbrakk> inj_on f A; y \<notin> f ` (A - {x}) \<rbrakk>
\<Longrightarrow> inj_on (f(x := y)) A"
apply (rule inj_onI)
apply (simp split: split_if_asm)
apply (erule notE, rule image_eqI, erule sym)
apply simp
apply (erule(3) inj_onD)
done
lemma inj_on_fun_upd_elsewhere:
"x \<notin> S \<Longrightarrow> inj_on (f (x := y)) S = inj_on f S"
apply (simp add: inj_on_def)
apply blast
done
lemma not_Some_eq_tuple:
"(\<forall>y z. x \<noteq> Some (y, z)) = (x = None)"
by (cases x, simp_all)
lemma ran_option_map:
"ran (option_map f o m) = f ` ran m"
by (auto simp add: ran_def)
lemma All_less_Ball:
"(\<forall>x < n. P x) = (\<forall>x\<in>{..< n}. P x)"
by fastforce
lemma Int_image_empty:
"\<lbrakk> \<And>x y. f x \<noteq> g y \<rbrakk>
\<Longrightarrow> f ` S \<inter> g ` T = {}"
by auto
lemma Max_prop:
"\<lbrakk> Max S \<in> S \<Longrightarrow> P (Max S); (S :: ('a :: {finite, linorder}) set) \<noteq> {} \<rbrakk> \<Longrightarrow> P (Max S)"
apply (erule meta_mp)
apply (rule Max_in)
apply simp
apply assumption
done
lemma Min_prop:
"\<lbrakk> Min S \<in> S \<Longrightarrow> P (Min S); (S :: ('a :: {finite, linorder}) set) \<noteq> {} \<rbrakk> \<Longrightarrow> P (Min S)"
apply (erule meta_mp)
apply (rule Min_in)
apply simp
apply assumption
done
definition
is_inv :: "('a \<rightharpoonup> 'b) \<Rightarrow> ('b \<rightharpoonup> 'a) \<Rightarrow> bool" where
"is_inv f g \<equiv> ran f = dom g \<and> (\<forall>x y. f x = Some y \<longrightarrow> g y = Some x)"
lemma is_inv_NoneD:
assumes "g x = None"
assumes "is_inv f g"
shows "x \<notin> ran f"
proof -
from assms
have "x \<notin> dom g" by (auto simp: ran_def)
moreover
from assms
have "ran f = dom g"
by (simp add: is_inv_def)
ultimately
show ?thesis by simp
qed
lemma is_inv_SomeD:
"\<lbrakk> f x = Some y; is_inv f g \<rbrakk> \<Longrightarrow> g y = Some x"
by (simp add: is_inv_def)
lemma is_inv_com:
"is_inv f g \<Longrightarrow> is_inv g f"
apply (unfold is_inv_def)
apply safe
apply (clarsimp simp: ran_def dom_def set_eq_iff)
apply (erule_tac x=a in allE)
apply clarsimp
apply (clarsimp simp: ran_def dom_def set_eq_iff)
apply blast
apply (clarsimp simp: ran_def dom_def set_eq_iff)
apply (erule_tac x=x in allE)
apply clarsimp
done
lemma is_inv_inj:
"is_inv f g \<Longrightarrow> inj_on f (dom f)"
apply (frule is_inv_com)
apply (clarsimp simp: inj_on_def)
apply (drule (1) is_inv_SomeD)
apply (drule_tac f=f in is_inv_SomeD, assumption)
apply simp
done
lemma is_inv_None_upd:
"\<lbrakk> is_inv f g; g x = Some y\<rbrakk> \<Longrightarrow> is_inv (f(y := None)) (g(x := None))"
apply (subst is_inv_def)
apply (clarsimp simp add: dom_upd)
apply (drule is_inv_SomeD, erule is_inv_com)
apply (frule is_inv_inj)
apply (simp add: ran_upd')
apply (rule conjI)
apply (simp add: is_inv_def)
apply (drule (1) is_inv_SomeD)
apply (clarsimp simp: is_inv_def)
done
lemma is_inv_inj2:
"is_inv f g \<Longrightarrow> inj_on g (dom g)"
apply (drule is_inv_com)
apply (erule is_inv_inj)
done
lemma range_convergence1:
"\<lbrakk> \<forall>z. x < z \<and> z \<le> y \<longrightarrow> P z; \<forall>z > y. P (z :: 'a :: linorder) \<rbrakk>
\<Longrightarrow> \<forall>z > x. P z"
apply clarsimp
apply (case_tac "z \<le> y")
apply simp
apply (simp add: linorder_not_le)
done
lemma range_convergence2:
"\<lbrakk> \<forall>z. x < z \<and> z \<le> y \<longrightarrow> P z; \<forall>z. z > y \<and> z < w \<longrightarrow> P (z :: 'a :: linorder) \<rbrakk>
\<Longrightarrow> \<forall>z. z > x \<and> z < w \<longrightarrow> P z"
apply (cut_tac range_convergence1[where P="\<lambda>z. z < w \<longrightarrow> P z" and x=x and y=y])
apply simp
apply simp
apply simp
done
lemma replicate_minus:
"k < n \<Longrightarrow> replicate n False = replicate (n - k) False @ replicate k False"
by (subst replicate_add [symmetric]) simp
lemmas map_prod_split_imageI
= map_prod_imageI[where f="split f" and g="split g"
and a="(a, b)" and b="(c, d)" for a b c d f g, simplified]
lemma word_div_mult:
fixes c :: "('a::len) word"
shows "\<lbrakk>0 < c; a < b * c \<rbrakk> \<Longrightarrow> a div c < b"
apply (simp add: word_less_nat_alt unat_div)
apply (subst td_gal_lt [symmetric])
apply assumption
apply (erule order_less_le_trans)
apply (subst unat_word_ariths)
by (metis Divides.mod_less_eq_dividend)
lemma word_less_power_trans_ofnat:
"\<lbrakk>n < 2 ^ (m - k); k \<le> m; m < len_of TYPE('a)\<rbrakk>
\<Longrightarrow> of_nat n * 2 ^ k < (2::'a::len word) ^ m"
apply (subst mult.commute)
apply (rule word_less_power_trans)
apply (simp add: word_less_nat_alt)
apply (subst unat_of_nat_eq)
apply (erule order_less_trans)
apply simp+
done
lemma div_power_helper:
"\<lbrakk> x \<le> y; y < word_bits \<rbrakk> \<Longrightarrow> (2 ^ y - 1) div (2 ^ x :: word32) = 2 ^ (y - x) - 1"
apply (rule word_uint.Rep_eqD)
apply (simp only: uint_word_ariths uint_div uint_power_lower word_bits_len_of)
apply (subst mod_pos_pos_trivial, fastforce, fastforce)+
apply (subst mod_pos_pos_trivial)
apply (simp add: le_diff_eq uint_2p_alt[where 'a=32, unfolded word_bits_len_of])
apply (rule less_1_helper)
apply (rule power_increasing)
apply (simp add: word_bits_def)
apply simp
apply (subst mod_pos_pos_trivial)
apply (simp add: uint_2p_alt[where 'a=32, unfolded word_bits_len_of])
apply (rule less_1_helper)
apply (rule power_increasing)
apply (simp add: word_bits_def)
apply simp
apply (subst int_div_sub_1)
apply simp
apply (simp add: uint_2p_alt[where 'a=32, unfolded word_bits_len_of])
apply (subst power_0[symmetric, where a=2])
apply (simp add: uint_2p_alt[where 'a=32, unfolded word_bits_len_of]
le_imp_power_dvd_int power_sub_int)
done
lemma n_less_word_bits:
"(n < word_bits) = (n < 32)"
by (simp add: word_bits_def)
lemma of_nat_less_pow:
"\<lbrakk> x < 2 ^ n; n < word_bits \<rbrakk> \<Longrightarrow> of_nat x < (2 :: word32) ^ n"
apply (subst word_unat_power)
apply (rule of_nat_mono_maybe)
apply (rule power_strict_increasing)
apply (simp add: word_bits_def)
apply simp
apply assumption
done
lemma power_helper:
"\<lbrakk> (x :: word32) < 2 ^ (m - n); n \<le> m; m < word_bits \<rbrakk> \<Longrightarrow> x * (2 ^ n) < 2 ^ m"
apply (drule word_mult_less_mono1[where k="2 ^ n"])
apply (simp add: word_neq_0_conv[symmetric] word_bits_def)
apply (simp only: unat_power_lower[where 'a=32, unfolded word_bits_len_of]
power_add[symmetric])
apply (rule power_strict_increasing)
apply (simp add: word_bits_def)
apply simp
apply (simp add: power_add[symmetric])
done
lemma word_1_le_power:
"n < len_of TYPE('a) \<Longrightarrow> (1 :: 'a :: len word) \<le> 2 ^ n"
by (rule inc_le[where i=0, simplified], erule iffD2[OF p2_gt_0])
lemma enum_word_div:
fixes v :: "('a :: len) word" shows
"\<exists>xs ys. enum = xs @ [v] @ ys
\<and> (\<forall>x \<in> set xs. x < v)
\<and> (\<forall>y \<in> set ys. v < y)"
apply (simp only: enum_word_def)
apply (subst upt_add_eq_append'[where j="unat v"])
apply simp
apply (rule order_less_imp_le, simp)
apply (simp add: upt_conv_Cons)
apply (intro exI conjI)
apply fastforce
apply clarsimp
apply (drule of_nat_mono_maybe[rotated, where 'a='a])
apply simp
apply simp
apply (clarsimp simp: Suc_le_eq)
apply (drule of_nat_mono_maybe[rotated, where 'a='a])
apply simp
apply simp
done
lemma less_x_plus_1:
fixes x :: "('a :: len) word" shows
"x \<noteq> max_word \<Longrightarrow> (y < (x + 1)) = (y < x \<or> y = x)"
apply (rule iffI)
apply (rule disjCI)
apply (drule plus_one_helper)
apply simp
apply (subgoal_tac "x < x + 1")
apply (erule disjE, simp_all)
apply (rule plus_one_helper2 [OF order_refl])
apply (rule notI, drule max_word_wrap)
apply simp
done
lemma of_bool_nth:
"of_bool (x !! v) = (x >> v) && 1"
apply (rule word_eqI)
apply (simp add: nth_shiftr cong: rev_conj_cong)
done
lemma unat_1_0:
"1 \<le> (x::word32) = (0 < unat x)"
by (auto simp add: word_le_nat_alt)
lemma x_less_2_0_1:
fixes x :: word32 shows
"x < 2 \<Longrightarrow> x = 0 \<or> x = 1"
by unat_arith
lemma x_less_2_0_1':
fixes x :: "('a::len) word"
shows "\<lbrakk>len_of TYPE('a) \<noteq> 1; x < 2\<rbrakk> \<Longrightarrow> x = 0 \<or> x = 1"
apply (induct x)
apply clarsimp+
by (metis Suc_eq_plus1 add_lessD1 less_irrefl one_add_one unatSuc word_less_nat_alt)
lemma Collect_int_vars:
"{s. P rv s} \<inter> {s. rv = xf s} = {s. P (xf s) s} \<inter> {s. rv = xf s}"
by auto
lemma if_0_1_eq:
"((if P then 1 else 0) = (case Q of True \<Rightarrow> of_nat 1 | False \<Rightarrow> of_nat 0)) = (P = Q)"
by (simp add: case_bool_If split: split_if)
lemma modify_map_exists_cte :
"(\<exists>cte. modify_map m p f p' = Some cte) = (\<exists>cte. m p' = Some cte)"
by (simp add: modify_map_def)
lemmas word_add_le_iff2 = word_add_le_iff [folded no_olen_add_nat]
lemma mask_32_max_word :
shows "mask 32 = (max_word :: word32)"
unfolding mask_def
by (simp add: max_word_def)
lemma dom_eqI:
assumes c1: "\<And>x y. P x = Some y \<Longrightarrow> \<exists>y. Q x = Some y"
and c2: "\<And>x y. Q x = Some y \<Longrightarrow> \<exists>y. P x = Some y"
shows "dom P = dom Q"
unfolding dom_def by (auto simp: c1 c2)
lemma dvd_reduce_multiple:
fixes k :: nat
shows "(k dvd k * m + n) = (k dvd n)"
by (induct m) (auto simp: add_ac)
lemma image_iff:
"inj f \<Longrightarrow> f x \<in> f ` S = (x \<in> S)"
by (rule inj_image_mem_iff)
lemma of_nat_n_less_equal_power_2:
"n < len_of TYPE('a::len) \<Longrightarrow> ((of_nat n)::'a word) < 2 ^ n"
apply (induct n)
apply clarsimp
apply clarsimp
apply (metis WordLemmaBucket.of_nat_power
n_less_equal_power_2 of_nat_Suc power_Suc)
done
lemma of_nat32_n_less_equal_power_2:
"n < 32 \<Longrightarrow> ((of_nat n)::32 word) < 2 ^ n"
by (rule of_nat_n_less_equal_power_2, clarsimp simp: word_size)
lemma map_comp_restrict_map_Some_iff:
"((g \<circ>\<^sub>m (m |` S)) x = Some y) = ((g \<circ>\<^sub>m m) x = Some y \<and> x \<in> S)"
by (auto simp add: map_comp_Some_iff restrict_map_Some_iff)
lemma range_subsetD:
fixes a :: "'a :: order"
shows "\<lbrakk> {a..b} \<subseteq> {c..d}; a \<le> b \<rbrakk> \<Longrightarrow> c \<le> a \<and> b \<le> d"
apply (rule conjI)
apply (drule subsetD [where c = a])
apply simp
apply simp
apply (drule subsetD [where c = b])
apply simp
apply simp
done
lemma case_option_dom:
"(case f x of None \<Rightarrow> a | Some v \<Rightarrow> b v)
= (if x \<in> dom f then b (the (f x)) else a)"
by (auto split: split_if option.split)
lemma contrapos_imp:
"P \<longrightarrow> Q \<Longrightarrow> \<not> Q \<longrightarrow> \<not> P"
by clarsimp
lemma eq_mask_less:
fixes w :: "('a::len) word"
assumes eqm: "w = w && mask n"
and sz: "n < len_of TYPE ('a)"
shows "w < (2::'a word) ^ n"
by (subst eqm, rule and_mask_less' [OF sz])
lemma of_nat_mono_maybe':
fixes Y :: "nat"
assumes xlt: "X < 2 ^ len_of TYPE ('a :: len)"
assumes ylt: "Y < 2 ^ len_of TYPE ('a :: len)"
shows "(Y < X) = (of_nat Y < (of_nat X :: 'a :: len word))"
apply (subst word_less_nat_alt)
apply (subst unat_of_nat)+
apply (subst mod_less)
apply (rule ylt)
apply (subst mod_less)
apply (rule xlt)
apply simp
done
(* FIXME: MOVE *)
lemma shiftr_mask_eq:
fixes x :: "'a :: len word"
shows "(x >> n) && mask (size x - n) = x >> n"
apply (rule word_eqI)
apply (simp add: word_size nth_shiftr)
apply (rule iffI)
apply clarsimp
apply (clarsimp)
apply (drule test_bit_size)
apply (simp add: word_size)
done
(* FIXME: move *)
lemma shiftr_mask_eq':
fixes x :: "'a :: len word"
shows "m = (size x - n) \<Longrightarrow> (x >> n) && mask m = x >> n"
by (simp add: shiftr_mask_eq)
lemma zipWith_Nil2 :
"zipWith f xs [] = []"
unfolding zipWith_def by simp
lemma zip_upt_Cons:
"a < b \<Longrightarrow> zip [a ..< b] (x # xs)
= (a, x) # zip [Suc a ..< b] xs"
by (simp add: upt_conv_Cons)
lemma map_comp_eq:
"(f \<circ>\<^sub>m g) = (case_option None f \<circ> g)"
apply (rule ext)
apply (case_tac "g x")
apply simp
apply simp
done
lemma dom_If_Some:
"dom (\<lambda>x. if x \<in> S then Some v else f x) = (S \<union> dom f)"
by (auto split: split_if)
lemma foldl_fun_upd_const:
"foldl (\<lambda>s x. s(f x := v)) s xs
= (\<lambda>x. if x \<in> f ` set xs then v else s x)"
apply (induct xs arbitrary: s)
apply simp
apply (rule ext, simp)
done
lemma foldl_id:
"foldl (\<lambda>s x. s) s xs = s"
apply (induct xs)
apply simp
apply simp
done
lemma SucSucMinus: "2 \<le> n \<Longrightarrow> Suc (Suc (n - 2)) = n" by arith
lemma ball_to_all:
"(\<And>x. (x \<in> A) = (P x)) \<Longrightarrow> (\<forall>x \<in> A. B x) = (\<forall>x. P x \<longrightarrow> B x)"
by blast
lemma bang_big: "n \<ge> size (x::'a::len0 word) \<Longrightarrow> (x !! n) = False"
by (simp add: test_bit_bl word_size)
lemma bang_conj_lt:
fixes x :: "'a :: len word"
shows "(x !! m \<and> m < len_of TYPE('a)) = x !! m"
apply (cases "m < len_of TYPE('a)")
apply simp
apply (simp add: not_less bang_big word_size)
done
lemma dom_if:
"dom (\<lambda>a. if a \<in> addrs then Some (f a) else g a) = addrs \<union> dom g"
by (auto simp: dom_def split: split_if)
lemma less_is_non_zero_p1:
fixes a :: "'a :: len word"
shows "a < k \<Longrightarrow> a + 1 \<noteq> 0"
apply (erule contrapos_pn)
apply (drule max_word_wrap)
apply (simp add: not_less)
done
lemma lt_word_bits_lt_pow:
"sz < word_bits \<Longrightarrow> sz < 2 ^ word_bits"
by (simp add: word_bits_conv)
(* FIXME: shadows an existing thm *)
lemma of_nat_mono_maybe_le:
"\<lbrakk>X < 2 ^ len_of TYPE('a); Y < 2 ^ len_of TYPE('a)\<rbrakk> \<Longrightarrow>
(Y \<le> X) = ((of_nat Y :: 'a :: len word) \<le> of_nat X)"
apply (clarsimp simp: le_less)
apply (rule disj_cong)
apply (rule of_nat_mono_maybe', assumption+)
apply (simp add: word_unat.norm_eq_iff [symmetric])
done
lemma neg_mask_bang:
"(~~ mask n :: 'a :: len word) !! m = (n \<le> m \<and> m < len_of TYPE('a))"
apply (cases "m < len_of TYPE('a)")
apply (simp add: word_ops_nth_size word_size not_less)
apply (simp add: not_less bang_big word_size)
done
lemma mask_AND_NOT_mask:
"(w && ~~ mask n) && mask n = 0"
by (rule word_eqI) (clarsimp simp add: word_size neg_mask_bang)
lemma AND_NOT_mask_plus_AND_mask_eq:
"(w && ~~ mask n) + (w && mask n) = w"
apply (rule word_eqI)
apply (rename_tac m)
apply (simp add: word_size)
apply (cut_tac word_plus_and_or_coroll[of "w && ~~ mask n" "w && mask n"])
apply (simp add: word_ao_dist2[symmetric] word_size neg_mask_bang)
apply (rule word_eqI)
apply (rename_tac m)
apply (simp add: word_size neg_mask_bang)
done
lemma mask_eqI:
fixes x :: "'a :: len word"
assumes m1: "x && mask n = y && mask n"
and m2: "x && ~~ mask n = y && ~~ mask n"
shows "x = y"
proof (subst bang_eq, rule allI)
fix m
show "x !! m = y !! m"
proof (cases "m < n")
case True
hence "x !! m = ((x && mask n) !! m)"
by (simp add: word_size bang_conj_lt)
also have "\<dots> = ((y && mask n) !! m)" using m1 by simp
also have "\<dots> = y !! m" using True
by (simp add: word_size bang_conj_lt)
finally show ?thesis .
next
case False
hence "x !! m = ((x && ~~ mask n) !! m)"
by (simp add: neg_mask_bang bang_conj_lt)
also have "\<dots> = ((y && ~~ mask n) !! m)" using m2 by simp
also have "\<dots> = y !! m" using False
by (simp add: neg_mask_bang bang_conj_lt)
finally show ?thesis .
qed
qed
lemma nat_less_power_trans2:
fixes n :: nat
shows "\<lbrakk>n < 2 ^ (m - k); k \<le> m\<rbrakk> \<Longrightarrow> n * 2 ^ k < 2 ^ m"
by (subst mult.commute, erule (1) nat_less_power_trans)
lemma nat_move_sub_le: "(a::nat) + b \<le> c \<Longrightarrow> a \<le> c - b" by arith
lemma neq_0_no_wrap:
fixes x :: "'a :: len word"
shows "\<lbrakk> x \<le> x + y; x \<noteq> 0 \<rbrakk> \<Longrightarrow> x + y \<noteq> 0"
by clarsimp
lemma plus_minus_one_rewrite:
"v + (- 1 :: ('a :: {ring, one, uminus})) \<equiv> v - 1"
by (simp add: field_simps)
lemma power_minus_is_div:
"b \<le> a \<Longrightarrow> (2 :: nat) ^ (a - b) = 2 ^ a div 2 ^ b"
apply (induct a arbitrary: b)
apply simp
apply (erule le_SucE)
apply (clarsimp simp:Suc_diff_le le_iff_add power_add)
apply simp
done
lemma two_pow_div_gt_le:
"v < 2 ^ n div (2 ^ m :: nat) \<Longrightarrow> m \<le> n"
by (clarsimp dest!: less_two_pow_divD)
lemma unat_less_word_bits:
fixes y :: word32
shows "x < unat y \<Longrightarrow> x < 2 ^ word_bits"
unfolding word_bits_def
by (rule order_less_trans [OF _ unat_lt2p])
lemma word_add_power_off:
fixes a :: word32
assumes ak: "a < k"
and kw: "k < 2 ^ (word_bits - m)"
and mw: "m < word_bits"
and off: "off < 2 ^ m"
shows "(a * 2 ^ m) + off < k * 2 ^ m"
proof (cases "m = 0")
case True
thus ?thesis using off ak by simp
next
case False
from ak have ak1: "a + 1 \<le> k" by (rule inc_le)
hence "(a + 1) * 2 ^ m \<noteq> 0"
apply -
apply (rule word_power_nonzero)
apply (erule order_le_less_trans [OF _ kw])
apply (rule mw)
apply (rule less_is_non_zero_p1 [OF ak])
done
hence "(a * 2 ^ m) + off < ((a + 1) * 2 ^ m)" using kw mw
apply -
apply (simp add: distrib_right)
apply (rule word_plus_strict_mono_right [OF off])
apply (rule is_aligned_no_overflow'')
apply (rule is_aligned_mult_triv2)
apply assumption
done
also have "\<dots> \<le> k * 2 ^ m" using ak1 mw kw False
apply -
apply (erule word_mult_le_mono1)
apply (simp add: p2_gt_0 word_bits_def)
apply (simp add: word_bits_len_of word_less_nat_alt word_bits_def)
apply (rule nat_less_power_trans2[where m=32, simplified])
apply (simp add: word_less_nat_alt)
apply simp
done
finally show ?thesis .
qed
lemma word_of_nat_less:
"\<lbrakk> n < unat x \<rbrakk> \<Longrightarrow> of_nat n < x"
apply (simp add: word_less_nat_alt)
apply (erule order_le_less_trans[rotated])
apply (simp add: unat_of_nat)
done
lemma word_rsplit_0:
"word_rsplit (0 :: word32) = [0, 0, 0, 0 :: word8]"
apply (simp add: word_rsplit_def bin_rsplit_def Let_def)
done
lemma word_of_nat_le:
"n \<le> unat x \<Longrightarrow> of_nat n \<le> x"
apply (simp add: word_le_nat_alt unat_of_nat)
apply (erule order_trans[rotated])
apply simp
done
lemma word_unat_less_le:
"a \<le> of_nat b \<Longrightarrow> unat a \<le> b"
by (metis eq_iff le_cases le_unat_uoi word_of_nat_le)
lemma filter_eq_If:
"distinct xs \<Longrightarrow> filter (\<lambda>v. v = x) xs = (if x \<in> set xs then [x] else [])"
apply (induct xs)
apply simp
apply (clarsimp split: split_if)
done
(*FIXME: isabelle-2012 *)
lemma (in semigroup_add) foldl_assoc:
shows "foldl op+ (x+y) zs = x + (foldl op+ y zs)"
by (induct zs arbitrary: y) (simp_all add:add.assoc)
lemma (in monoid_add) foldl_absorb0:
shows "x + (foldl op+ 0 zs) = foldl op+ x zs"
by (induct zs) (simp_all add:foldl_assoc)
lemma foldl_conv_concat:
"foldl (op @) xs xss = xs @ concat xss"
proof (induct xss arbitrary: xs)
case Nil show ?case by simp
next
interpret monoid_add "op @" "[]" proof qed simp_all
case Cons then show ?case by (simp add: foldl_absorb0)
qed
lemma foldl_concat_concat:
"foldl op @ [] (xs @ ys) = foldl op @ [] xs @ foldl op @ [] ys"
by (simp add: foldl_conv_concat)
lemma foldl_does_nothing:
"\<lbrakk> \<And>x. x \<in> set xs \<Longrightarrow> f s x = s \<rbrakk> \<Longrightarrow> foldl f s xs = s"
by (induct xs, simp_all)
lemma foldl_use_filter:
"\<lbrakk> \<And>v x. \<lbrakk> \<not> g x; x \<in> set xs \<rbrakk> \<Longrightarrow> f v x = v \<rbrakk>
\<Longrightarrow>
foldl f v xs = foldl f v (filter g xs)"
apply (induct xs arbitrary: v)
apply simp
apply (simp split: split_if)
done
lemma split_upt_on_n:
"n < m \<Longrightarrow> [0 ..< m] = [0 ..< n] @ [n] @ [Suc n ..< m]"
apply (subst upt_add_eq_append', simp, erule order_less_imp_le)
apply (simp add: upt_conv_Cons)
done
lemma unat_ucast_10_32 :
fixes x :: "10 word"
shows "unat (ucast x :: word32) = unat x"
unfolding ucast_def unat_def
apply (subst int_word_uint)
apply (subst mod_pos_pos_trivial)
apply simp
apply (rule lt2p_lem)
apply simp
apply simp
done
lemma map_comp_update_lift:
assumes fv: "f v = Some v'"
shows "(f \<circ>\<^sub>m (g(ptr \<mapsto> v))) = ((f \<circ>\<^sub>m g)(ptr \<mapsto> v'))"
unfolding map_comp_def
apply (rule ext)
apply (simp add: fv)
done
lemma restrict_map_cong:
assumes sv: "S = S'"
and rl: "\<And>p. p \<in> S' \<Longrightarrow> mp p = mp' p"
shows "mp |` S = mp' |` S'"
apply (simp add: sv)
apply (rule ext)
apply (case_tac "x \<in> S'")
apply (simp add: rl )
apply simp
done
lemma and_eq_0_is_nth:
fixes x :: "('a :: len) word"
shows "y = 1 << n \<Longrightarrow> ((x && y) = 0) = (\<not> (x !! n))"
apply safe
apply (drule_tac u="(x && (1 << n))" and x=n in word_eqD)
apply (simp add: nth_w2p)
apply (simp add: test_bit_bin)
apply (rule word_eqI)
apply (simp add: nth_w2p)
done
lemmas and_neq_0_is_nth = arg_cong [where f=Not, OF and_eq_0_is_nth, simplified]
lemma ucast_le_ucast_8_32:
"(ucast x \<le> (ucast y :: word32)) = (x \<le> (y :: word8))"
by (simp add: word_le_nat_alt unat_ucast_8_32)
lemma mask_Suc_0 : "mask (Suc 0) = 1"
by (simp add: mask_def)
lemma ucast_ucast_add:
fixes x :: "('a :: len) word"
fixes y :: "('b :: len) word"
shows
"len_of TYPE('b) \<ge> len_of TYPE('a) \<Longrightarrow>
ucast (ucast x + y) = x + ucast y"
apply (rule word_unat.Rep_eqD)
apply (simp add: unat_ucast unat_word_ariths mod_mod_power
min.absorb2 unat_of_nat)
apply (subst mod_add_left_eq)
apply (simp add: mod_mod_power min.absorb2)
apply (subst mod_add_right_eq)
apply simp
done
lemma word_shift_zero:
"\<lbrakk> x << n = 0; x \<le> 2^m; m + n < len_of TYPE('a)\<rbrakk> \<Longrightarrow> (x::'a::len word) = 0"
apply (rule ccontr)
apply (drule (2) word_shift_nonzero)
apply simp
done
lemma neg_mask_mono_le:
"(x :: 'a :: len word) \<le> y \<Longrightarrow> x && ~~ mask n \<le> y && ~~ mask n"
proof (rule ccontr, simp add: linorder_not_le, cases "n < len_of TYPE('a)")
case False
show "y && ~~ mask n < x && ~~ mask n \<Longrightarrow> False"
using False
by (simp add: mask_def linorder_not_less
power_overflow)
next
case True
assume a: "x \<le> y" and b: "y && ~~ mask n < x && ~~ mask n"
have word_bits:
"n < len_of TYPE('a)"
using True by assumption
have "y \<le> (y && ~~ mask n) + (y && mask n)"
by (simp add: word_plus_and_or_coroll2 add.commute)
also have "\<dots> \<le> (y && ~~ mask n) + 2 ^ n"
apply (rule word_plus_mono_right)
apply (rule order_less_imp_le, rule and_mask_less_size)
apply (simp add: word_size word_bits)
apply (rule is_aligned_no_overflow'',
simp_all add: is_aligned_neg_mask word_bits)
apply (rule not_greatest_aligned, rule b)
apply (simp_all add: is_aligned_neg_mask)
done
also have "\<dots> \<le> x && ~~ mask n"
using b
apply -
apply (subst add.commute, rule le_plus)
apply (rule aligned_at_least_t2n_diff,
simp_all add: is_aligned_neg_mask)
apply (rule ccontr, simp add: linorder_not_le)
apply (drule aligned_small_is_0[rotated], simp_all add: is_aligned_neg_mask)
done
also have "\<dots> \<le> x"
by (rule word_and_le2)
also have "x \<le> y" by fact
finally
show "False" using b
by simp
qed
lemma isRight_right_map:
"isRight (case_sum Inl (Inr o f) v) = isRight v"
by (simp add: isRight_def split: sum.split)
lemma bool_mask [simp]:
fixes x :: word32
shows "(0 < x && 1) = (x && 1 = 1)"
apply (rule iffI)
prefer 2
apply simp
apply (subgoal_tac "x && mask 1 < 2^1")
prefer 2
apply (rule and_mask_less_size)
apply (simp add: word_size)
apply (simp add: mask_def)
apply (drule word_less_cases [where y=2])
apply (erule disjE, simp)
apply simp
done
lemma case_option_over_if:
"case_option P Q (if G then None else Some v)
= (if G then P else Q v)"
"case_option P Q (if G then Some v else None)
= (if G then Q v else P)"
by (simp split: split_if)+
lemma scast_eq_ucast:
"\<not> msb x \<Longrightarrow> scast x = ucast x"
by (simp add: scast_def ucast_def sint_eq_uint)
(* MOVE *)
lemma lt1_neq0:
fixes x :: "'a :: len word"
shows "(1 \<le> x) = (x \<noteq> 0)" by unat_arith
lemma word_plus_one_nonzero:
fixes x :: "'a :: len word"
shows "\<lbrakk>x \<le> x + y; y \<noteq> 0\<rbrakk> \<Longrightarrow> x + 1 \<noteq> 0"
apply (subst lt1_neq0 [symmetric])
apply (subst olen_add_eqv [symmetric])
apply (erule word_random)
apply (simp add: lt1_neq0)
done
lemma word_sub_plus_one_nonzero:
fixes n :: "'a :: len word"
shows "\<lbrakk>n' \<le> n; n' \<noteq> 0\<rbrakk> \<Longrightarrow> (n - n') + 1 \<noteq> 0"
apply (subst lt1_neq0 [symmetric])
apply (subst olen_add_eqv [symmetric])
apply (rule word_random [where x' = n'])
apply simp
apply (erule word_sub_le)
apply (simp add: lt1_neq0)
done
lemma word_le_minus_mono_right:
fixes x :: "'a :: len word"
shows "\<lbrakk> z \<le> y; y \<le> x; z \<le> x \<rbrakk> \<Longrightarrow> x - y \<le> x - z"
apply (rule word_sub_mono)
apply simp
apply assumption
apply (erule word_sub_le)
apply (erule word_sub_le)
done
lemma drop_append_miracle:
"n = length xs \<Longrightarrow> drop n (xs @ ys) = ys"
by simp
lemma foldr_does_nothing_to_xf:
"\<lbrakk> \<And>x s. x \<in> set xs \<Longrightarrow> xf (f x s) = xf s \<rbrakk> \<Longrightarrow> xf (foldr f xs s) = xf s"
by (induct xs, simp_all)
lemma nat_less_mult_monoish: "\<lbrakk> a < b; c < (d :: nat) \<rbrakk> \<Longrightarrow> (a + 1) * (c + 1) <= b * d"
apply (drule Suc_leI)+
apply (drule(1) mult_le_mono)
apply simp
done
lemma word_0_sle_from_less[unfolded word_size]:
"\<lbrakk> x < 2 ^ (size x - 1) \<rbrakk> \<Longrightarrow> 0 <=s x"
apply (clarsimp simp: word_sle_msb_le)
apply (simp add: word_msb_nth)
apply (subst (asm) word_test_bit_def [symmetric])
apply (drule less_mask_eq)
apply (drule_tac x="size x - 1" in word_eqD)
apply (simp add: word_size)
done
lemma not_msb_from_less:
"(v :: 'a word) < 2 ^ (len_of TYPE('a :: len) - 1) \<Longrightarrow> \<not> msb v"
apply (clarsimp simp add: msb_nth)
apply (drule less_mask_eq)
apply (drule word_eqD, drule(1) iffD2)
apply simp
done
lemma distinct_lemma: "f x \<noteq> f y \<Longrightarrow> x \<noteq> y" by auto
lemma ucast_sub_ucast:
fixes x :: "'a::len word"
assumes "y \<le> x"
assumes T: "len_of TYPE('a) \<le> len_of TYPE('b)"
shows "ucast (x - y) = (ucast x - ucast y :: 'b::len word)"
proof -
from T
have P: "unat x < 2 ^ len_of TYPE('b)" "unat y < 2 ^ len_of TYPE('b)"
by (fastforce intro!: less_le_trans[OF unat_lt2p])+
thus ?thesis
by (simp add: unat_arith_simps unat_ucast assms[simplified unat_arith_simps])
qed
lemma word_1_0:
"\<lbrakk>a + (1::('a::len) word) \<le> b; a < of_nat ((2::nat) ^ len_of TYPE(32) - 1)\<rbrakk> \<Longrightarrow> a < b"
by unat_arith
lemma unat_of_nat_less:"\<lbrakk> a < b; unat b = c \<rbrakk> \<Longrightarrow> a < of_nat c"
by fastforce
lemma word_le_plus_1: "\<lbrakk> (y::('a::len) word) < y + n; a < n \<rbrakk> \<Longrightarrow> y + a \<le> y + a + 1"
by unat_arith
lemma word_le_plus:"\<lbrakk>(a::('a::len) word) < a + b; c < b\<rbrakk> \<Longrightarrow> a \<le> a + c"
by (metis order_less_imp_le word_random)
(*
* Basic signed arithemetic properties.
*)
lemma sint_minus1 [simp]: "(sint x = -1) = (x = -1)"
by (metis sint_n1 word_sint.Rep_inverse')
lemma sint_0 [simp]: "(sint x = 0) = (x = 0)"
by (metis sint_0 word_sint.Rep_inverse')
(* It is not always that case that "sint 1 = 1", because of 1-bit word sizes.
* This lemma produces the different cases. *)
lemma sint_1_cases:
"\<lbrakk> \<lbrakk> len_of TYPE ('a::len) = 1; (a::'a word) = 0; sint a = 0 \<rbrakk> \<Longrightarrow> P;
\<lbrakk> len_of TYPE ('a) = 1; a = 1; sint (1 :: 'a word) = -1 \<rbrakk> \<Longrightarrow> P;
\<lbrakk> len_of TYPE ('a) > 1; sint (1 :: 'a word) = 1 \<rbrakk> \<Longrightarrow> P \<rbrakk>
\<Longrightarrow> P"
apply atomize_elim
apply (case_tac "len_of TYPE ('a) = 1")
apply clarsimp
apply (subgoal_tac "(UNIV :: 'a word set) = {0, 1}")
apply (metis UNIV_I insert_iff singletonE)
apply (subst word_unat.univ)
apply (clarsimp simp: unats_def image_def)
apply (rule set_eqI, rule iffI)
apply clarsimp
apply (metis One_nat_def less_2_cases of_nat_1 semiring_1_class.of_nat_0)
apply clarsimp
apply (metis Abs_fnat_hom_0 Suc_1 lessI of_nat_1 zero_less_Suc)
apply clarsimp
apply (metis One_nat_def arith_is_1 le_def len_gt_0)
done
lemma sint_int_min:
"sint (- (2 ^ (len_of TYPE('a) - Suc 0)) :: ('a::len) word) = - (2 ^ (len_of TYPE('a) - Suc 0))"
apply (subst word_sint.Abs_inverse' [where r="- (2 ^ (len_of TYPE('a) - Suc 0))"])
apply (clarsimp simp: sints_num)
apply (clarsimp simp: wi_hom_syms word_of_int_2p)
apply clarsimp
done
lemma sint_int_max_plus_1:
"sint (2 ^ (len_of TYPE('a) - Suc 0) :: ('a::len) word) = - (2 ^ (len_of TYPE('a) - Suc 0))"
apply (subst word_of_int_2p [symmetric])
apply (subst int_word_sint)
apply clarsimp
apply (metis Suc_pred int_word_uint len_gt_0 power_Suc uint_eq_0 word_of_int_2p word_pow_0)
done
lemma word32_bounds:
"- (2 ^ (size (x :: word32) - 1)) = (-2147483648 :: int)"
"((2 ^ (size (x :: word32) - 1)) - 1) = (2147483647 :: int)"
"- (2 ^ (size (y :: 32 signed word) - 1)) = (-2147483648 :: int)"
"((2 ^ (size (y :: 32 signed word) - 1)) - 1) = (2147483647 :: int)"
by (simp_all add: word_size)
lemma sbintrunc_If:
"- 3 * (2 ^ n) \<le> x \<and> x < 3 * (2 ^ n)
\<Longrightarrow> sbintrunc n x = (if x < - (2 ^ n) then x + 2 * (2 ^ n)
else if x \<ge> 2 ^ n then x - 2 * (2 ^ n) else x)"
apply (simp add: no_sbintr_alt2, safe)
apply (simp add: mod_pos_geq mod_pos_pos_trivial)
apply (subst mod_add_self1[symmetric], simp)
apply (simp add: mod_pos_pos_trivial)
apply (simp add: mod_pos_pos_trivial)
done
lemma signed_arith_eq_checks_to_ord:
"(sint a + sint b = sint (a + b ))
= ((a <=s a + b) = (0 <=s b))"
"(sint a - sint b = sint (a - b ))
= ((0 <=s a - b) = (b <=s a))"
"(- sint a = sint (- a)) = (0 <=s (- a) = (a <=s 0))"
using sint_range'[where x=a] sint_range'[where x=b]
apply (simp_all add: sint_word_ariths
word_sle_def word_sless_alt sbintrunc_If)
apply arith+
done
(* Basic proofs that signed word div/mod operations are
* truncations of their integer counterparts. *)
lemma signed_div_arith:
"sint ((a::('a::len) word) sdiv b) = sbintrunc (len_of TYPE('a) - 1) (sint a sdiv sint b)"
apply (subst word_sbin.norm_Rep [symmetric])
apply (subst bin_sbin_eq_iff' [symmetric])
apply simp
apply (subst uint_sint [symmetric])
apply (clarsimp simp: sdiv_int_def sdiv_word_def)
apply (metis word_ubin.eq_norm)
done
lemma signed_mod_arith:
"sint ((a::('a::len) word) smod b) = sbintrunc (len_of TYPE('a) - 1) (sint a smod sint b)"
apply (subst word_sbin.norm_Rep [symmetric])
apply (subst bin_sbin_eq_iff' [symmetric])
apply simp
apply (subst uint_sint [symmetric])
apply (clarsimp simp: smod_int_def smod_word_def)
apply (metis word_ubin.eq_norm)
done
(* Signed word arithmetic overflow constraints. *)
lemma signed_arith_ineq_checks_to_eq:
"((- (2 ^ (size a - 1)) \<le> (sint a + sint b)) \<and> (sint a + sint b \<le> (2 ^ (size a - 1) - 1)))
= (sint a + sint b = sint (a + b ))"
"((- (2 ^ (size a - 1)) \<le> (sint a - sint b)) \<and> (sint a - sint b \<le> (2 ^ (size a - 1) - 1)))
= (sint a - sint b = sint (a - b))"
"((- (2 ^ (size a - 1)) \<le> (- sint a)) \<and> (- sint a) \<le> (2 ^ (size a - 1) - 1))
= ((- sint a) = sint (- a))"
"((- (2 ^ (size a - 1)) \<le> (sint a * sint b)) \<and> (sint a * sint b \<le> (2 ^ (size a - 1) - 1)))
= (sint a * sint b = sint (a * b))"
"((- (2 ^ (size a - 1)) \<le> (sint a sdiv sint b)) \<and> (sint a sdiv sint b \<le> (2 ^ (size a - 1) - 1)))
= (sint a sdiv sint b = sint (a sdiv b))"
"((- (2 ^ (size a - 1)) \<le> (sint a smod sint b)) \<and> (sint a smod sint b \<le> (2 ^ (size a - 1) - 1)))
= (sint a smod sint b = sint (a smod b))"
by (auto simp: sint_word_ariths word_size signed_div_arith signed_mod_arith
sbintrunc_eq_in_range range_sbintrunc)
lemmas signed_arith_ineq_checks_to_eq_word32
= signed_arith_ineq_checks_to_eq[where 'a=32, unfolded word32_bounds]
signed_arith_ineq_checks_to_eq[where 'a="32 signed", unfolded word32_bounds]
lemma signed_arith_sint:
"((- (2 ^ (size a - 1)) \<le> (sint a + sint b)) \<and> (sint a + sint b \<le> (2 ^ (size a - 1) - 1)))
\<Longrightarrow> sint (a + b) = (sint a + sint b)"
"((- (2 ^ (size a - 1)) \<le> (sint a - sint b)) \<and> (sint a - sint b \<le> (2 ^ (size a - 1) - 1)))
\<Longrightarrow> sint (a - b) = (sint a - sint b)"
"((- (2 ^ (size a - 1)) \<le> (- sint a)) \<and> (- sint a) \<le> (2 ^ (size a - 1) - 1))
\<Longrightarrow> sint (- a) = (- sint a)"
"((- (2 ^ (size a - 1)) \<le> (sint a * sint b)) \<and> (sint a * sint b \<le> (2 ^ (size a - 1) - 1)))
\<Longrightarrow> sint (a * b) = (sint a * sint b)"
"((- (2 ^ (size a - 1)) \<le> (sint a sdiv sint b)) \<and> (sint a sdiv sint b \<le> (2 ^ (size a - 1) - 1)))
\<Longrightarrow> sint (a sdiv b) = (sint a sdiv sint b)"
"((- (2 ^ (size a - 1)) \<le> (sint a smod sint b)) \<and> (sint a smod sint b \<le> (2 ^ (size a - 1) - 1)))
\<Longrightarrow> sint (a smod b) = (sint a smod sint b)"
by (metis signed_arith_ineq_checks_to_eq)+
lemma signed_mult_eq_checks_double_size:
assumes mult_le: "(2 ^ (len_of TYPE ('a) - 1) + 1) ^ 2
\<le> (2 :: int) ^ (len_of TYPE ('b) - 1)"
and le: "2 ^ (len_of TYPE('a) - 1) \<le> (2 :: int) ^ (len_of TYPE ('b) - 1)"
shows
"(sint (a :: ('a :: len) word) * sint b = sint (a * b))
= (scast a * scast b = (scast (a * b) :: ('b :: len) word))"
proof -
have P: "sbintrunc (size a - 1) (sint a * sint b) \<in> range (sbintrunc (size a - 1))"
by simp
have abs: "!! x :: 'a word. abs (sint x) < 2 ^ (size a - 1) + 1"
apply (cut_tac x=x in sint_range')
apply (simp add: abs_le_iff word_size)
done
have abs_ab: "abs (sint a * sint b) < 2 ^ (len_of TYPE('b) - 1)"
using abs_mult_less[OF abs[where x=a] abs[where x=b]] mult_le
by (simp add: abs_mult power2_eq_square word_size)
show ?thesis
using P[unfolded range_sbintrunc] abs_ab le
apply (simp add: sint_word_ariths scast_def)
apply (simp add: wi_hom_mult)
apply (subst word_sint.Abs_inject, simp_all)
apply (simp add: sints_def range_sbintrunc
abs_less_iff)
apply clarsimp
apply (simp add: sints_def range_sbintrunc word_size)
apply (auto elim: order_less_le_trans order_trans[rotated])
done
qed
lemmas signed_mult_eq_checks32_to_64
= signed_mult_eq_checks_double_size[where 'a=32 and 'b=64, simplified]
signed_mult_eq_checks_double_size[where 'a="32 signed" and 'b=64, simplified]
(* Properties about signed division. *)
lemma int_sdiv_simps [simp]:
"(a :: int) sdiv 1 = a"
"(a :: int) sdiv 0 = 0"
"(a :: int) sdiv -1 = -a"
apply (auto simp: sdiv_int_def sgn_if)
done
lemma sgn_div_eq_sgn_mult:
"a div b \<noteq> 0 \<Longrightarrow> sgn ((a :: int) div b) = sgn (a * b)"
apply (clarsimp simp: sgn_if zero_le_mult_iff neg_imp_zdiv_nonneg_iff not_less)
apply (metis less_le mult_le_0_iff neg_imp_zdiv_neg_iff not_less pos_imp_zdiv_neg_iff zdiv_eq_0_iff)
done
lemma sgn_sdiv_eq_sgn_mult:
"a sdiv b \<noteq> 0 \<Longrightarrow> sgn ((a :: int) sdiv b) = sgn (a * b)"
apply (clarsimp simp: sdiv_int_def sgn_times)
apply (subst sgn_div_eq_sgn_mult)
apply simp
apply (clarsimp simp: sgn_times)
apply (metis abs_mult div_0 div_mult_self2_is_id sgn_0_0 sgn_1_pos sgn_times zero_less_abs_iff)
done
lemma int_sdiv_same_is_1 [simp]:
"a \<noteq> 0 \<Longrightarrow> ((a :: int) sdiv b = a) = (b = 1)"
apply (rule iffI)
apply (clarsimp simp: sdiv_int_def)
apply (subgoal_tac "b > 0")
apply (case_tac "a > 0")
apply (clarsimp simp: sgn_if sign_simps)
apply (clarsimp simp: sign_simps not_less)
apply (metis int_div_same_is_1 le_neq_trans minus_minus neg_0_le_iff_le neg_equal_0_iff_equal)
apply (case_tac "a > 0")
apply (case_tac "b = 0")
apply (clarsimp simp: sign_simps)
apply (rule classical)
apply (clarsimp simp: sign_simps sgn_times not_less)
apply (metis le_less neg_0_less_iff_less not_less_iff_gr_or_eq pos_imp_zdiv_neg_iff)
apply (rule classical)
apply (clarsimp simp: sign_simps sgn_times not_less sgn_if split: if_splits)
apply (metis antisym less_le neg_imp_zdiv_nonneg_iff)
apply (clarsimp simp: sdiv_int_def sgn_if)
done
lemma int_sdiv_negated_is_minus1 [simp]:
"a \<noteq> 0 \<Longrightarrow> ((a :: int) sdiv b = - a) = (b = -1)"
apply (clarsimp simp: sdiv_int_def)
apply (rule iffI)
apply (subgoal_tac "b < 0")
apply (case_tac "a > 0")
apply (clarsimp simp: sgn_if sign_simps not_less)
apply (case_tac "sgn (a * b) = -1")
apply (clarsimp simp: not_less sign_simps)
apply (clarsimp simp: sign_simps not_less)
apply (rule classical)
apply (case_tac "b = 0")
apply (clarsimp simp: sign_simps not_less sgn_times)
apply (case_tac "a > 0")
apply (clarsimp simp: sign_simps not_less sgn_times)
apply (metis less_le neg_less_0_iff_less not_less_iff_gr_or_eq pos_imp_zdiv_neg_iff)
apply (clarsimp simp: sign_simps not_less sgn_times)
apply (metis div_minus_right eq_iff neg_0_le_iff_le neg_imp_zdiv_nonneg_iff not_leE)
apply (clarsimp simp: sgn_if)
done
lemma sdiv_int_range:
"(a :: int) sdiv b \<in> { - (abs a) .. (abs a) }"
apply (unfold sdiv_int_def)
apply (subgoal_tac "(abs a) div (abs b) \<le> (abs a)")
apply (clarsimp simp: sgn_if)
apply (metis Divides.transfer_nat_int_function_closures(1) abs_ge_zero
abs_less_iff abs_of_nonneg less_asym less_minus_iff not_less)
apply (metis abs_eq_0 abs_ge_zero div_by_0 zdiv_le_dividend zero_less_abs_iff)
done
lemma sdiv_int_div_0 [simp]:
"(x :: int) sdiv 0 = 0"
by (clarsimp simp: sdiv_int_def)
lemma sdiv_int_0_div [simp]:
"0 sdiv (x :: int) = 0"
by (clarsimp simp: sdiv_int_def)
lemma word_sdiv_div0 [simp]:
"(a :: ('a::len) word) sdiv 0 = 0"
apply (auto simp: sdiv_word_def sdiv_int_def sgn_if)
done
lemma word_sdiv_div_minus1 [simp]:
"(a :: ('a::len) word) sdiv -1 = -a"
apply (auto simp: sdiv_word_def sdiv_int_def sgn_if)
apply (metis wi_hom_neg word_sint.Rep_inverse')
done
lemmas word_sdiv_0 = word_sdiv_div0
lemma sdiv_word_min:
"- (2 ^ (size a - 1)) \<le> sint (a :: ('a::len) word) sdiv sint (b :: ('a::len) word)"
apply (clarsimp simp: word_size)
apply (cut_tac sint_range' [where x=a])
apply (cut_tac sint_range' [where x=b])
apply clarsimp
apply (insert sdiv_int_range [where a="sint a" and b="sint b"])
apply (clarsimp simp: max_def abs_if split: split_if_asm)
done
lemma sdiv_word_max:
"(sint (a :: ('a::len) word) sdiv sint (b :: ('a::len) word) < (2 ^ (size a - 1))) =
((a \<noteq> - (2 ^ (size a - 1)) \<or> (b \<noteq> -1)))"
(is "?lhs = (\<not> ?a_int_min \<or> \<not> ?b_minus1)")
proof (rule classical)
assume not_thesis: "\<not> ?thesis"
have not_zero: "b \<noteq> 0"
using not_thesis
by (clarsimp)
have result_range: "sint a sdiv sint b \<in> (sints (size a)) \<union> {2 ^ (size a - 1)}"
apply (cut_tac sdiv_int_range [where a="sint a" and b="sint b"])
apply (erule rev_subsetD)
using sint_range' [where x=a] sint_range' [where x=b]
apply (auto simp: max_def abs_if word_size sints_num)
done
have result_range_overflow: "(sint a sdiv sint b = 2 ^ (size a - 1)) = (?a_int_min \<and> ?b_minus1)"
apply (rule iffI [rotated])
apply (clarsimp simp: sdiv_int_def sgn_if word_size sint_int_min)
apply (rule classical)
apply (case_tac "?a_int_min")
apply (clarsimp simp: word_size sint_int_min)
apply (metis diff_0_right
int_sdiv_negated_is_minus1 minus_diff_eq minus_int_code(2)
power_eq_0_iff sint_minus1 zero_neq_numeral)
apply (subgoal_tac "abs (sint a) < 2 ^ (size a - 1)")
apply (insert sdiv_int_range [where a="sint a" and b="sint b"])[1]
apply (clarsimp simp: word_size)
apply (insert sdiv_int_range [where a="sint a" and b="sint b"])[1]
apply (insert word_sint.Rep [where x="a"])[1]
apply (clarsimp simp: minus_le_iff word_size abs_if sints_num split: split_if_asm)
apply (metis minus_minus sint_int_min word_sint.Rep_inject)
done
have result_range_simple: "(sint a sdiv sint b \<in> (sints (size a))) \<Longrightarrow> ?thesis"
apply (insert sdiv_int_range [where a="sint a" and b="sint b"])
apply (clarsimp simp: word_size sints_num sint_int_min)
done
show ?thesis
apply (rule UnE [OF result_range result_range_simple])
apply simp
apply (clarsimp simp: word_size)
using result_range_overflow
apply (clarsimp simp: word_size)
done
qed
lemmas sdiv_word_min' = sdiv_word_min [simplified word_size, simplified]
lemmas sdiv_word_max' = sdiv_word_max [simplified word_size, simplified]
lemmas sdiv_word32_max = sdiv_word_max [where 'a=32, simplified word_size, simplified]
sdiv_word_max [where 'a="32 signed", simplified word_size, simplified]
lemmas sdiv_word32_min = sdiv_word_min [where 'a=32, simplified word_size, simplified]
sdiv_word_min [where 'a="32 signed", simplified word_size, simplified]
lemmas word_sdiv_numerals_lhs = sdiv_word_def[where a="numeral x" for x]
sdiv_word_def[where a=0] sdiv_word_def[where a=1]
lemmas word_sdiv_numerals = word_sdiv_numerals_lhs[where b="numeral y" for y]
word_sdiv_numerals_lhs[where b=0] word_sdiv_numerals_lhs[where b=1]
(*
* Signed modulo properties.
*)
lemma smod_int_alt_def:
"(a::int) smod b = sgn (a) * (abs a mod abs b)"
apply (clarsimp simp: smod_int_def sdiv_int_def)
apply (clarsimp simp: zmod_zdiv_equality' abs_sgn sgn_times sgn_if sign_simps)
done
lemma smod_int_range:
"b \<noteq> 0 \<Longrightarrow> (a::int) smod b \<in> { - abs b + 1 .. abs b - 1 }"
apply (case_tac "b > 0")
apply (insert pos_mod_conj [where a=a and b=b])[1]
apply (insert pos_mod_conj [where a="-a" and b=b])[1]
apply (clarsimp simp: smod_int_alt_def sign_simps sgn_if
abs_if not_less add1_zle_eq [simplified add.commute])
apply (metis add_le_cancel_left monoid_add_class.add.right_neutral
int_one_le_iff_zero_less less_le_trans mod_minus_right neg_less_0_iff_less
neg_mod_conj not_less pos_mod_conj)
apply (insert neg_mod_conj [where a=a and b="b"])[1]
apply (insert neg_mod_conj [where a="-a" and b="b"])[1]
apply (clarsimp simp: smod_int_alt_def sign_simps sgn_if
abs_if not_less add1_zle_eq [simplified add.commute])
apply (metis neg_0_less_iff_less neg_mod_conj not_le not_less_iff_gr_or_eq order_trans pos_mod_conj)
done
lemma smod_int_compares:
"\<lbrakk> 0 \<le> a; 0 < b \<rbrakk> \<Longrightarrow> (a :: int) smod b < b"
"\<lbrakk> 0 \<le> a; 0 < b \<rbrakk> \<Longrightarrow> 0 \<le> (a :: int) smod b"
"\<lbrakk> a \<le> 0; 0 < b \<rbrakk> \<Longrightarrow> -b < (a :: int) smod b"
"\<lbrakk> a \<le> 0; 0 < b \<rbrakk> \<Longrightarrow> (a :: int) smod b \<le> 0"
"\<lbrakk> 0 \<le> a; b < 0 \<rbrakk> \<Longrightarrow> (a :: int) smod b < - b"
"\<lbrakk> 0 \<le> a; b < 0 \<rbrakk> \<Longrightarrow> 0 \<le> (a :: int) smod b"
"\<lbrakk> a \<le> 0; b < 0 \<rbrakk> \<Longrightarrow> (a :: int) smod b \<le> 0"
"\<lbrakk> a \<le> 0; b < 0 \<rbrakk> \<Longrightarrow> b \<le> (a :: int) smod b"
apply (insert smod_int_range [where a=a and b=b])
apply (auto simp: add1_zle_eq smod_int_alt_def sgn_if)
done
lemma smod_int_mod_0 [simp]:
"x smod (0 :: int) = x"
by (clarsimp simp: smod_int_def)
lemma smod_int_0_mod [simp]:
"0 smod (x :: int) = 0"
by (clarsimp simp: smod_int_alt_def)
lemma smod_word_mod_0 [simp]:
"x smod (0 :: ('a::len) word) = x"
by (clarsimp simp: smod_word_def)
lemma smod_word_0_mod [simp]:
"0 smod (x :: ('a::len) word) = 0"
by (clarsimp simp: smod_word_def)
lemma smod_word_max:
"sint (a::'a word) smod sint (b::'a word) < 2 ^ (len_of TYPE('a::len) - Suc 0)"
apply (case_tac "b = 0")
apply (insert word_sint.Rep [where x=a, simplified sints_num])[1]
apply (clarsimp)
apply (insert word_sint.Rep [where x="b", simplified sints_num])[1]
apply (insert smod_int_range [where a="sint a" and b="sint b"])
apply (clarsimp simp: abs_if split: split_if_asm)
done
lemma smod_word_min:
"- (2 ^ (len_of TYPE('a::len) - Suc 0)) \<le> sint (a::'a word) smod sint (b::'a word)"
apply (case_tac "b = 0")
apply (insert word_sint.Rep [where x=a, simplified sints_num])[1]
apply clarsimp
apply (insert word_sint.Rep [where x=b, simplified sints_num])[1]
apply (insert smod_int_range [where a="sint a" and b="sint b"])
apply (clarsimp simp: abs_if add1_zle_eq split: split_if_asm)
done
lemma smod_word_alt_def:
"(a :: ('a::len) word) smod b = a - (a sdiv b) * b"
apply (case_tac "a \<noteq> - (2 ^ (len_of TYPE('a) - 1)) \<or> b \<noteq> -1")
apply (clarsimp simp: smod_word_def sdiv_word_def smod_int_def
minus_word.abs_eq [symmetric] times_word.abs_eq [symmetric])
apply (clarsimp simp: smod_word_def smod_int_def)
done
lemmas word_smod_numerals_lhs = smod_word_def[where a="numeral x" for x]
smod_word_def[where a=0] smod_word_def[where a=1]
lemmas word_smod_numerals = word_smod_numerals_lhs[where b="numeral y" for y]
word_smod_numerals_lhs[where b=0] word_smod_numerals_lhs[where b=1]
lemma sint_of_int_eq:
"\<lbrakk> - (2 ^ (len_of TYPE('a) - 1)) \<le> x; x < 2 ^ (len_of TYPE('a) - 1) \<rbrakk> \<Longrightarrow> sint (of_int x :: ('a::len) word) = x"
apply (clarsimp simp: word_of_int int_word_sint)
apply (subst int_mod_eq')
apply simp
apply (subst (2) power_minus_simp)
apply clarsimp
apply clarsimp
apply clarsimp
done
lemmas sint32_of_int_eq = sint_of_int_eq [where 'a=32, simplified]
lemma of_int_sint [simp]:
"of_int (sint a) = a"
apply (insert word_sint.Rep [where x=a])
apply (clarsimp simp: word_of_int)
done
lemma ucast_of_nats [simp]:
"(ucast (of_nat x :: word32) :: sword32) = (of_nat x)"
"(ucast (of_nat x :: word32) :: sword16) = (of_nat x)"
"(ucast (of_nat x :: word32) :: sword8) = (of_nat x)"
"(ucast (of_nat x :: word16) :: sword16) = (of_nat x)"
"(ucast (of_nat x :: word16) :: sword8) = (of_nat x)"
"(ucast (of_nat x :: word8) :: sword8) = (of_nat x)"
apply (auto simp: ucast_of_nat is_down)
done
lemma nth_w2p_scast [simp]:
"((scast ((2::'a::len signed word) ^ n) :: 'a word) !! m)
\<longleftrightarrow> ((((2::'a::len word) ^ n) :: 'a word) !! m)"
apply (subst nth_w2p)
apply (case_tac "n \<ge> len_of TYPE('a)")
apply (subst power_overflow, simp)
apply clarsimp
apply (metis nth_w2p scast_def bang_conj_lt
len_signed nth_word_of_int word_sint.Rep_inverse)
done
lemma scast_2_power [simp]: "scast ((2 :: 'a::len signed word) ^ x) = ((2 :: 'a word) ^ x)"
by (clarsimp simp: word_eq_iff)
lemma scast_bit_test [simp]:
"scast ((1 :: 'a::len signed word) << n) = (1 :: 'a word) << n"
by (clarsimp simp: word_eq_iff)
lemma ucast_nat_def':
"of_nat (unat x) = (ucast :: ('a :: len) word \<Rightarrow> ('b :: len) signed word) x"
by (simp add: ucast_def word_of_int_nat unat_def)
lemma mod_mod_power_int:
fixes k :: int
shows "k mod 2 ^ m mod 2 ^ n = k mod 2 ^ (min m n)"
by (metis bintrunc_bintrunc_min bintrunc_mod2p min.commute)
(* Normalise combinations of scast and ucast. *)
lemma ucast_distrib:
fixes M :: "'a::len word \<Rightarrow> 'a::len word \<Rightarrow> 'a::len word"
fixes M' :: "'b::len word \<Rightarrow> 'b::len word \<Rightarrow> 'b::len word"
fixes L :: "int \<Rightarrow> int \<Rightarrow> int"
assumes lift_M: "\<And>x y. uint (M x y) = L (uint x) (uint y) mod 2 ^ len_of TYPE('a)"
assumes lift_M': "\<And>x y. uint (M' x y) = L (uint x) (uint y) mod 2 ^ len_of TYPE('b)"
assumes distrib: "\<And>x y. (L (x mod (2 ^ len_of TYPE('b))) (y mod (2 ^ len_of TYPE('b)))) mod (2 ^ len_of TYPE('b))
= (L x y) mod (2 ^ len_of TYPE('b))"
assumes is_down: "is_down (ucast :: 'a word \<Rightarrow> 'b word)"
shows "ucast (M a b) = M' (ucast a) (ucast b)"
apply (clarsimp simp: word_of_int ucast_def)
apply (subst lift_M)
apply (subst of_int_uint [symmetric], subst lift_M')
apply (subst (1 2) int_word_uint)
apply (subst word_of_int)
apply (subst word.abs_eq_iff)
apply (subst (1 2) bintrunc_mod2p)
apply (insert is_down)
apply (unfold is_down_def)
apply (clarsimp simp: target_size source_size)
apply (clarsimp simp: mod_mod_power_int min_def)
apply (rule distrib [symmetric])
done
lemma ucast_down_add:
"is_down (ucast:: 'a word \<Rightarrow> 'b word) \<Longrightarrow> ucast ((a :: 'a::len word) + b) = (ucast a + ucast b :: 'b::len word)"
by (rule ucast_distrib [where L="op +"], (clarsimp simp: uint_word_ariths)+, presburger, simp)
lemma ucast_down_minus:
"is_down (ucast:: 'a word \<Rightarrow> 'b word) \<Longrightarrow> ucast ((a :: 'a::len word) - b) = (ucast a - ucast b :: 'b::len word)"
apply (rule ucast_distrib [where L="op -"], (clarsimp simp: uint_word_ariths)+)
apply (metis zdiff_zmod_left zdiff_zmod_right)
apply simp
done
lemma ucast_down_mult:
"is_down (ucast:: 'a word \<Rightarrow> 'b word) \<Longrightarrow> ucast ((a :: 'a::len word) * b) = (ucast a * ucast b :: 'b::len word)"
apply (rule ucast_distrib [where L="op *"], (clarsimp simp: uint_word_ariths)+)
apply (metis mod_mult_eq)
apply simp
done
lemma scast_distrib:
fixes M :: "'a::len word \<Rightarrow> 'a::len word \<Rightarrow> 'a::len word"
fixes M' :: "'b::len word \<Rightarrow> 'b::len word \<Rightarrow> 'b::len word"
fixes L :: "int \<Rightarrow> int \<Rightarrow> int"
assumes lift_M: "\<And>x y. uint (M x y) = L (uint x) (uint y) mod 2 ^ len_of TYPE('a)"
assumes lift_M': "\<And>x y. uint (M' x y) = L (uint x) (uint y) mod 2 ^ len_of TYPE('b)"
assumes distrib: "\<And>x y. (L (x mod (2 ^ len_of TYPE('b))) (y mod (2 ^ len_of TYPE('b)))) mod (2 ^ len_of TYPE('b))
= (L x y) mod (2 ^ len_of TYPE('b))"
assumes is_down: "is_down (scast :: 'a word \<Rightarrow> 'b word)"
shows "scast (M a b) = M' (scast a) (scast b)"
apply (subst (1 2 3) down_cast_same [symmetric])
apply (insert is_down)
apply (clarsimp simp: is_down_def target_size source_size is_down)
apply (rule ucast_distrib [where L=L, OF lift_M lift_M' distrib])
apply (insert is_down)
apply (clarsimp simp: is_down_def target_size source_size is_down)
done
lemma scast_down_add:
"is_down (scast:: 'a word \<Rightarrow> 'b word) \<Longrightarrow> scast ((a :: 'a::len word) + b) = (scast a + scast b :: 'b::len word)"
by (rule scast_distrib [where L="op +"], (clarsimp simp: uint_word_ariths)+, presburger, simp)
lemma scast_down_minus:
"is_down (scast:: 'a word \<Rightarrow> 'b word) \<Longrightarrow> scast ((a :: 'a::len word) - b) = (scast a - scast b :: 'b::len word)"
apply (rule scast_distrib [where L="op -"], (clarsimp simp: uint_word_ariths)+)
apply (metis zdiff_zmod_left zdiff_zmod_right)
apply simp
done
lemma scast_down_mult:
"is_down (scast:: 'a word \<Rightarrow> 'b word) \<Longrightarrow> scast ((a :: 'a::len word) * b) = (scast a * scast b :: 'b::len word)"
apply (rule scast_distrib [where L="op *"], (clarsimp simp: uint_word_ariths)+)
apply (metis mod_mult_eq)
apply simp
done
lemma scast_ucast_3:
"\<lbrakk> is_down (ucast :: 'a word \<Rightarrow> 'c word); is_down (ucast :: 'b word \<Rightarrow> 'c word) \<rbrakk> \<Longrightarrow>
(scast (ucast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = ucast a"
by (metis down_cast_same ucast_def ucast_down_wi)
lemma scast_ucast_4:
"\<lbrakk> is_up (ucast :: 'a word \<Rightarrow> 'b word); is_down (ucast :: 'b word \<Rightarrow> 'c word) \<rbrakk> \<Longrightarrow>
(scast (ucast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = ucast a"
by (metis down_cast_same ucast_def ucast_down_wi)
lemma scast_scast_b:
"\<lbrakk> is_up (scast :: 'a word \<Rightarrow> 'b word) \<rbrakk> \<Longrightarrow>
(scast (scast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = scast a"
by (metis scast_def sint_up_scast)
lemma ucast_scast_1:
"\<lbrakk> is_down (scast :: 'a word \<Rightarrow> 'b word); is_down (ucast :: 'b word \<Rightarrow> 'c word) \<rbrakk> \<Longrightarrow>
(ucast (scast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = scast a"
by (metis scast_def ucast_down_wi)
lemma ucast_scast_4:
"\<lbrakk> is_up (scast :: 'a word \<Rightarrow> 'b word); is_down (ucast :: 'b word \<Rightarrow> 'c word) \<rbrakk> \<Longrightarrow>
(ucast (scast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = scast a"
by (metis down_cast_same scast_def sint_up_scast)
lemma ucast_ucast_a:
"\<lbrakk> is_down (ucast :: 'b word \<Rightarrow> 'c word) \<rbrakk> \<Longrightarrow>
(ucast (ucast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = ucast a"
by (metis down_cast_same ucast_def ucast_down_wi)
lemma ucast_ucast_b:
"\<lbrakk> is_up (ucast :: 'a word \<Rightarrow> 'b word) \<rbrakk> \<Longrightarrow>
(ucast (ucast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = ucast a"
by (metis ucast_up_ucast)
lemma scast_scast_a:
"\<lbrakk> is_down (scast :: 'b word \<Rightarrow> 'c word) \<rbrakk> \<Longrightarrow>
(scast (scast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = scast a"
apply (clarsimp simp: scast_def)
apply (metis down_cast_same is_up_down scast_def ucast_down_wi)
done
lemma scast_down_wi [OF refl]:
"uc = scast \<Longrightarrow> is_down uc \<Longrightarrow> uc (word_of_int x) = word_of_int x"
by (metis down_cast_same is_up_down ucast_down_wi)
lemmas cast_simps =
is_down is_up
scast_down_add scast_down_minus scast_down_mult
ucast_down_add ucast_down_minus ucast_down_mult
scast_ucast_1 scast_ucast_3 scast_ucast_4
ucast_scast_1 ucast_scast_3 ucast_scast_4
ucast_ucast_a ucast_ucast_b
scast_scast_a scast_scast_b
ucast_down_bl
ucast_down_wi scast_down_wi
ucast_of_nat scast_of_nat
uint_up_ucast sint_up_scast
up_scast_surj up_ucast_surj
lemma smod_mod_positive:
"\<lbrakk> 0 \<le> (a :: int); 0 \<le> b \<rbrakk> \<Longrightarrow> a smod b = a mod b"
by (clarsimp simp: smod_int_alt_def zsgn_def)
lemmas signed_shift_guard_simpler_32
= power_strict_increasing_iff[where b="2 :: nat" and y=31, simplified]
lemma nat_mult_power_less_eq:
"b > 0 \<Longrightarrow> (a * b ^ n < (b :: nat) ^ m) = (a < b ^ (m - n))"
using mult_less_cancel2[where m = a and k = "b ^ n" and n="b ^ (m - n)"]
mult_less_cancel2[where m="a * b ^ (n - m)" and k="b ^ m" and n=1]
apply (simp only: power_add[symmetric] nat_minus_add_max)
apply (simp only: power_add[symmetric] nat_minus_add_max ac_simps)
apply (simp add: max_def split: split_if_asm)
done
lemma signed_shift_guard_to_word:
"\<lbrakk> n < len_of TYPE ('a); n > 0 \<rbrakk>
\<Longrightarrow> (unat (x :: ('a :: len) word) * 2 ^ y < 2 ^ n)
= (x = 0 \<or> x < (1 << n >> y))"
apply (simp only: nat_mult_power_less_eq)
apply (cases "y \<le> n")
apply (simp only: shiftl_shiftr1)
apply (subst less_mask_eq)
apply (simp add: word_less_nat_alt word_size)
apply (rule order_less_le_trans[rotated], rule power_increasing[where n=1])
apply simp
apply simp
apply simp
apply (simp add: nat_mult_power_less_eq word_less_nat_alt word_size)
apply auto[1]
apply (simp only: shiftl_shiftr2, simp add: unat_eq_0)
done
lemma word32_31_less:
"31 < len_of TYPE (32 signed)" "31 > (0 :: nat)"
"31 < len_of TYPE (32)" "31 > (0 :: nat)"
by auto
lemmas signed_shift_guard_to_word_32
= signed_shift_guard_to_word[OF word32_31_less(1-2)]
signed_shift_guard_to_word[OF word32_31_less(3-4)]
lemma sint_ucast_eq_uint:
"\<lbrakk> \<not> is_down (ucast :: ('a::len word \<Rightarrow> 'b::len word)) \<rbrakk>
\<Longrightarrow> sint ((ucast :: ('a::len word \<Rightarrow> 'b::len word)) x) = uint x"
apply (subst sint_eq_uint)
apply (clarsimp simp: msb_nth nth_ucast is_down)
apply (metis Suc_leI Suc_pred bang_conj_lt len_gt_0)
apply (clarsimp simp: uint_up_ucast is_up is_down)
done
lemma word_less_nowrapI':
"(x :: 'a :: len0 word) \<le> z - k \<Longrightarrow> k \<le> z \<Longrightarrow> 0 < k \<Longrightarrow> x < x + k"
by uint_arith
lemma mask_plus_1:
"mask n + 1 = 2 ^ n"
by (clarsimp simp: mask_def)
lemma unat_inj: "inj unat"
by (metis eq_iff injI word_le_nat_alt)
lemma unat_ucast_upcast:
"is_up (ucast :: 'b word \<Rightarrow> 'a word)
\<Longrightarrow> unat (ucast x :: ('a::len) word) = unat (x :: ('b::len) word)"
unfolding ucast_def unat_def
apply (subst int_word_uint)
apply (subst mod_pos_pos_trivial)
apply simp
apply (rule lt2p_lem)
apply (clarsimp simp: is_up)
apply simp
done
lemma ucast_mono:
"\<lbrakk> (x :: 'b :: len word) < y; y < 2 ^ len_of TYPE('a) \<rbrakk>
\<Longrightarrow> ucast x < ((ucast y) :: ('a :: len) word)"
apply (simp add: ucast_nat_def [symmetric])
apply (rule of_nat_mono_maybe)
apply (rule unat_less_helper)
apply (simp add: Power.of_nat_power)
apply (simp add: word_less_nat_alt)
done
lemma ucast_mono_le:
"\<lbrakk>x \<le> y; y < 2 ^ len_of TYPE('b)\<rbrakk> \<Longrightarrow> (ucast (x :: 'a :: len word) :: 'b :: len word) \<le> ucast y"
apply (simp add: ucast_nat_def [symmetric])
apply (subst of_nat_mono_maybe_le[symmetric])
apply (rule unat_less_helper)
apply (simp add: Power.of_nat_power)
apply (rule unat_less_helper)
apply (erule le_less_trans)
apply (simp add: Power.of_nat_power)
apply (simp add: word_le_nat_alt)
done
lemma zero_sle_ucast_up:
"\<not> is_down (ucast :: 'a word \<Rightarrow> 'b signed word) \<Longrightarrow>
(0 <=s ((ucast (b::('a::len) word)) :: ('b::len) signed word))"
apply (subgoal_tac "\<not> msb (ucast b :: 'b signed word)")
apply (clarsimp simp: word_sle_msb_le)
apply (clarsimp simp: is_down not_le msb_nth nth_ucast)
apply (subst (asm) bang_conj_lt [symmetric])
apply clarsimp
apply arith
done
lemma msb_ucast_eq:
"len_of TYPE('a) = len_of TYPE('b) \<Longrightarrow>
msb (ucast x :: ('a::len) word) = msb (x :: ('b::len) word)"
apply (clarsimp simp: word_msb_alt)
apply (subst ucast_down_drop [where n=0])
apply (clarsimp simp: source_size_def target_size_def word_size)
apply clarsimp
done
lemma msb_big:
"msb (a :: ('a::len) word) = (a \<ge> 2 ^ (len_of TYPE('a) - Suc 0))"
apply (rule iffI)
apply (clarsimp simp: msb_nth)
apply (drule bang_is_le)
apply simp
apply (rule ccontr)
apply (subgoal_tac "a = a && mask (len_of TYPE('a) - Suc 0)")
apply (cut_tac and_mask_less' [where w=a and n="len_of TYPE('a) - Suc 0"])
apply (clarsimp simp: word_not_le [symmetric])
apply clarsimp
apply (rule sym, subst and_mask_eq_iff_shiftr_0)
apply (clarsimp simp: msb_shift)
done
lemma zero_sle_ucast:
"(0 <=s ((ucast (b::('a::len) word)) :: ('a::len) signed word))
= (uint b < 2 ^ (len_of (TYPE('a)) - 1))"
apply (case_tac "msb b")
apply (clarsimp simp: word_sle_msb_le not_less msb_ucast_eq del: notI)
apply (clarsimp simp: msb_big word_le_def uint_2p_alt)
apply (clarsimp simp: word_sle_msb_le not_less msb_ucast_eq del: notI)
apply (clarsimp simp: msb_big word_le_def uint_2p_alt)
done
(* to_bool / from_bool. *)
definition
from_bool :: "bool \<Rightarrow> 'a::len word" where
"from_bool b \<equiv> case b of True \<Rightarrow> of_nat 1
| False \<Rightarrow> of_nat 0"
lemma from_bool_0:
"(from_bool x = 0) = (\<not> x)"
by (simp add: from_bool_def split: bool.split)
definition
to_bool :: "'a::len word \<Rightarrow> bool" where
"to_bool \<equiv> (op \<noteq>) 0"
lemma to_bool_and_1:
"to_bool (x && 1) = (x !! 0)"
apply (simp add: to_bool_def)
apply (rule iffI)
apply (rule classical, erule notE, rule word_eqI)
apply clarsimp
apply (case_tac n, simp_all)[1]
apply (rule notI, drule word_eqD[where x=0])
apply simp
done
lemma to_bool_from_bool:
"to_bool (from_bool r) = r"
unfolding from_bool_def to_bool_def
by (simp split: bool.splits)
lemma from_bool_neq_0:
"(from_bool b \<noteq> 0) = b"
by (simp add: from_bool_def split: bool.splits)
lemma from_bool_mask_simp:
"((from_bool r) :: word32) && 1 = from_bool r"
unfolding from_bool_def
apply (clarsimp split: bool.splits)
done
lemma scast_from_bool:
"scast (from_bool P::word32) = (from_bool P::word32)"
by (clarsimp simp: from_bool_def scast_id split: bool.splits)
lemma from_bool_1:
"(from_bool P = 1) = P"
by (simp add: from_bool_def split: bool.splits)
lemma ge_0_from_bool:
"(0 < from_bool P) = P"
by (simp add: from_bool_def split: bool.splits)
lemma limited_and_from_bool:
"limited_and (from_bool b) 1"
by (simp add: from_bool_def limited_and_def split: bool.split)
lemma to_bool_1 [simp]: "to_bool 1" by (simp add: to_bool_def)
lemma to_bool_0 [simp]: "\<not>to_bool 0" by (simp add: to_bool_def)
lemma from_bool_eq_if:
"(from_bool Q = (if P then 1 else 0)) = (P = Q)"
by (simp add: case_bool_If from_bool_def split: split_if)
lemma to_bool_eq_0:
"(\<not> to_bool x) = (x = 0)"
by (simp add: to_bool_def)
lemma to_bool_neq_0:
"(to_bool x) = (x \<noteq> 0)"
by (simp add: to_bool_def)
lemma from_bool_all_helper:
"(\<forall>bool. from_bool bool = val \<longrightarrow> P bool)
= ((\<exists>bool. from_bool bool = val) \<longrightarrow> P (val \<noteq> 0))"
by (auto simp: from_bool_0)
lemma word_rsplit_upt:
"\<lbrakk> size x = len_of TYPE('a :: len) * n; n \<noteq> 0 \<rbrakk>
\<Longrightarrow> word_rsplit x = map (\<lambda>i. ucast (x >> i * len_of TYPE ('a)) :: 'a word) (rev [0 ..< n])"
apply (subgoal_tac "length (word_rsplit x :: 'a word list) = n")
apply (rule nth_equalityI, simp)
apply (intro allI word_eqI impI)
apply (simp add: test_bit_rsplit_alt word_size)
apply (simp add: nth_ucast nth_shiftr nth_rev field_simps)
apply (simp add: length_word_rsplit_exp_size)
apply (metis mult.commute given_quot_alt word_size word_size_gt_0)
done
lemma aligned_shift:
"\<lbrakk>x < 2 ^ n; is_aligned (y :: 'a :: len word) n;n \<le> len_of TYPE('a)\<rbrakk>
\<Longrightarrow> x + y >> n = y >> n"
apply (subst word_plus_and_or_coroll)
apply (rule word_eqI)
apply (clarsimp simp: is_aligned_nth)
apply (drule(1) nth_bounded)
apply simp
apply simp
apply (rule word_eqI)
apply (simp add: nth_shiftr)
apply safe
apply (drule(1) nth_bounded)
apply simp+
done
lemma aligned_shift':
"\<lbrakk>x < 2 ^ n; is_aligned (y :: 'a :: len word) n;n \<le> len_of TYPE('a)\<rbrakk>
\<Longrightarrow> y + x >> n = y >> n"
apply (subst word_plus_and_or_coroll)
apply (rule word_eqI)
apply (clarsimp simp: is_aligned_nth)
apply (drule(1) nth_bounded)
apply simp
apply simp
apply (rule word_eqI)
apply (simp add: nth_shiftr)
apply safe
apply (drule(1) nth_bounded)
apply simp+
done
lemma neg_mask_add_mask:
"((x:: 'a :: len word) && ~~ mask n) + (2 ^ n - 1) = x || mask n"
apply (simp add:mask_2pm1[symmetric])
apply (rule word_eqI)
apply (rule iffI)
apply (clarsimp simp:word_size not_less)
apply (cut_tac w = "((x && ~~ mask n) + mask n)" and
m = n and n = "na - n" in nth_shiftr[symmetric])
apply clarsimp
apply (subst (asm) aligned_shift')
apply (simp add:mask_lt_2pn nth_shiftr is_aligned_neg_mask word_size word_bits_def )+
apply (case_tac "na<n")
apply clarsimp
apply (subst word_plus_and_or_coroll)
apply (rule iffD1[OF is_aligned_mask])
apply (simp add:is_aligned_neg_mask word_size not_less)+
apply (cut_tac w = "((x && ~~ mask n) + mask n)" and
m = n and n = "na - n" in nth_shiftr[symmetric])
apply clarsimp
apply (subst (asm) aligned_shift')
apply (simp add:mask_lt_2pn is_aligned_neg_mask word_bits_def nth_shiftr neg_mask_bang)+
done
lemma subtract_mask:
"p - (p && mask n) = (p && ~~ mask n)"
"p - (p && ~~ mask n) = (p && mask n)"
by (simp add: field_simps word_plus_and_or_coroll2)+
lemma and_neg_mask_plus_mask_mono: "(p && ~~ mask n) + mask n \<ge> p"
apply (rule word_le_minus_cancel[where x = "p && ~~ mask n"])
apply (clarsimp simp: subtract_mask)
using word_and_le1[where a = "mask n" and y = p]
apply (clarsimp simp: mask_def word_le_less_eq)
apply (rule is_aligned_no_overflow'[folded mask_2pm1])
apply (clarsimp simp: is_aligned_neg_mask)
done
lemma word_neg_and_le:
"ptr \<le> (ptr && ~~ mask n) + (2 ^ n - 1)"
by (simp add: and_neg_mask_plus_mask_mono mask_2pm1[symmetric])
lemma aligned_less_plus_1:
"\<lbrakk> is_aligned x n; n > 0 \<rbrakk> \<Longrightarrow> x < x + 1"
apply (rule plus_one_helper2)
apply (rule order_refl)
apply (clarsimp simp: field_simps)
apply (drule arg_cong[where f="\<lambda>x. x - 1"])
apply (clarsimp simp: is_aligned_mask)
apply (drule word_eqD[where x=0])
apply simp
done
lemma aligned_add_offset_less:
"\<lbrakk>is_aligned x n; is_aligned y n; x < y; z < 2 ^ n\<rbrakk> \<Longrightarrow> x + z < y"
apply (cases "y = 0")
apply simp
apply (erule is_aligned_get_word_bits[where p=y], simp_all)
apply (cases "z = 0", simp_all)
apply (drule(2) aligned_at_least_t2n_diff[rotated -1])
apply (drule plus_one_helper2)
apply (rule less_is_non_zero_p1)
apply (rule aligned_less_plus_1)
apply (erule aligned_sub_aligned[OF _ _ order_refl],
simp_all add: is_aligned_triv)[1]
apply (cases n, simp_all)[1]
apply (simp only: trans[OF diff_add_eq diff_diff_eq2[symmetric]])
apply (drule word_less_add_right)
apply (rule ccontr, simp add: linorder_not_le)
apply (drule aligned_small_is_0, erule order_less_trans)
apply (clarsimp simp: power_overflow)
apply simp
apply (erule order_le_less_trans[rotated],
rule word_plus_mono_right)
apply (erule minus_one_helper3)
apply (simp add: is_aligned_no_wrap' is_aligned_no_overflow field_simps)
done
lemma is_aligned_add_helper:
"\<lbrakk> is_aligned p n; d < 2 ^ n \<rbrakk>
\<Longrightarrow> (p + d && mask n = d) \<and> (p + d && (~~ mask n) = p)"
apply (subst(asm) is_aligned_mask)
apply (drule less_mask_eq)
apply (rule context_conjI)
apply (subst word_plus_and_or_coroll)
apply (rule word_eqI)
apply (drule_tac x=na in word_eqD)+
apply (simp add: word_size)
apply blast
apply (rule word_eqI)
apply (drule_tac x=na in word_eqD)+
apply (simp add: word_ops_nth_size word_size)
apply blast
apply (insert word_plus_and_or_coroll2[where x="p + d" and w="mask n"])
apply simp
done
lemma is_aligned_sub_helper:
"\<lbrakk> is_aligned (p - d) n; d < 2 ^ n \<rbrakk>
\<Longrightarrow> (p && mask n = d) \<and> (p && (~~ mask n) = p - d)"
by (drule(1) is_aligned_add_helper, simp)
lemma mask_twice:
"(x && mask n) && mask m = x && mask (min m n)"
apply (rule word_eqI)
apply (simp add: word_size conj_comms)
done
lemma is_aligned_after_mask:
"\<lbrakk>is_aligned k m;m\<le> n\<rbrakk> \<Longrightarrow> is_aligned (k && mask n) m"
by (metis is_aligned_andI1)
lemma and_mask_plus:
"\<lbrakk>is_aligned ptr m; m \<le> n; n < 32; a < 2 ^ m\<rbrakk>
\<Longrightarrow> (ptr) + a && mask n = (ptr && mask n) + a"
apply (rule mask_eqI[where n = m])
apply (simp add:mask_twice min_def)
apply (simp add:is_aligned_add_helper)
apply (subst is_aligned_add_helper[THEN conjunct1])
apply (erule is_aligned_after_mask)
apply simp
apply simp
apply simp
apply (subgoal_tac "(ptr + a && mask n) && ~~ mask m
= (ptr + a && ~~ mask m ) && mask n")
apply (simp add:is_aligned_add_helper)
apply (subst is_aligned_add_helper[THEN conjunct2])
apply (simp add:is_aligned_after_mask)
apply simp
apply simp
apply (simp add:word_bw_comms word_bw_lcs)
done
lemma le_step_down_word:"\<lbrakk>(i::('a::len) word) \<le> n; i = n \<longrightarrow> P; i \<le> n - 1 \<longrightarrow> P\<rbrakk> \<Longrightarrow> P"
apply unat_arith
done
lemma le_step_down_word_2:
fixes x :: "'a::len word"
shows "\<lbrakk>x \<le> y; x \<noteq> y\<rbrakk> \<Longrightarrow> x \<le> y - 1"
by (subst (asm) word_le_less_eq,
clarsimp,
simp add: minus_one_helper3)
lemma le_step_down_word_3:
fixes x :: "32 word"
shows "\<lbrakk>x \<le> y; x \<noteq> y; y < 2 ^ 32 - 1\<rbrakk> \<Longrightarrow> x \<le> y - 1"
by (rule le_step_down_word_2, assumption+)
lemma NOT_mask_AND_mask[simp]: "(w && mask n) && ~~ mask n = 0"
apply (clarsimp simp:mask_def)
by (metis word_bool_alg.conj_cancel_right word_bool_alg.conj_zero_right word_bw_comms(1) word_bw_lcs(1))
lemma and_and_not[simp]:"(a && b) && ~~ b = 0"
apply (subst word_bw_assocs(1))
apply clarsimp
done
lemma mask_shift_and_negate[simp]:"(w && mask n << m) && ~~ (mask n << m) = 0"
apply (clarsimp simp:mask_def)
by (metis (erased, hide_lams) mask_eq_x_eq_0 shiftl_over_and_dist word_bool_alg.conj_absorb word_bw_assocs(1))
lemma shiftr_1[simplified]:"(x::word32) >> 1 = 0 \<Longrightarrow> x < 2"
apply word_bitwise apply clarsimp
done
lemma le_step_down_nat:"\<lbrakk>(i::nat) \<le> n; i = n \<longrightarrow> P; i \<le> n - 1 \<longrightarrow> P\<rbrakk> \<Longrightarrow> P"
apply arith
done
lemma le_step_down_int:"\<lbrakk>(i::int) \<le> n; i = n \<longrightarrow> P; i \<le> n - 1 \<longrightarrow> P\<rbrakk> \<Longrightarrow> P"
by arith
lemma mask_step_down:"(b::32word) && 0x1 = (1::32word) \<Longrightarrow> (\<exists>x. x < 32 \<and> mask x = b >> 1) \<Longrightarrow> (\<exists>x. mask x = b)"
apply clarsimp
apply (rule_tac x="x + 1" in exI)
apply (subgoal_tac "x \<le> 31")
apply (erule le_step_down_nat, clarsimp simp:mask_def, word_bitwise, clarsimp+)+
apply (clarsimp simp:mask_def, word_bitwise, clarsimp)
apply clarsimp
done
lemma mask_1[simp]: "(\<exists>x. mask x = 1)"
apply (rule_tac x=1 in exI)
apply (simp add:mask_def)
done
lemma not_switch:"~~ a = x \<Longrightarrow> a = ~~ x"
by auto
(* The seL4 bitfield generator produces functions containing mask and shift operations, such that
* invoking two of them consecutively can produce something like the following. Note that it is
* unlikely you'll be able to use this lemma directly, hence the second one below.
*)
lemma bitfield_op_twice':"(x && ~~ (mask n << m) || ((y && mask n) << m)) && ~~ (mask n << m) = x && ~~ (mask n << m)"
apply (induct n arbitrary: m)
apply simp
apply (subst word_ao_dist)
apply (simp add:AND_twice)
done
(* Helper to get bitfield_op_twice' to apply to code produced by the bitfield generator as it
* appears in the wild. You'll probably need e.g.
* apply (clarsimp simp:bitfield_op_twice[unfolded mask_def, where n=5 and m=3, simplified])
*)
lemma bitfield_op_twice:
"((x::word32) && ~~ (mask n << m) || ((y && mask n) << m)) && ~~ (mask n << m) = x && ~~ (mask n << m)"
by (rule bitfield_op_twice')
lemma bitfield_op_twice'': "\<lbrakk>~~ a = b << c; \<exists>x. b = mask x\<rbrakk> \<Longrightarrow> (x && a || (y && b << c)) && a = x && a"
apply clarsimp
apply (cut_tac n=xa and m=c and x=x and y=y in bitfield_op_twice')
apply (clarsimp simp:mask_def)
apply (drule not_switch)
apply clarsimp
done
lemma bit_twiddle_min:" (y::sword32) xor (((x::sword32) xor y) && (if x < y then -1 else 0)) = min x y"
by (metis (mono_tags) min_def word_bitwise_m1_simps(2) word_bool_alg.xor_left_commute word_bool_alg.xor_self word_bool_alg.xor_zero_right word_bw_comms(1) word_le_less_eq word_log_esimps(7))
lemma bit_twiddle_max:"(x::sword32) xor (((x::sword32) xor y) && (if x < y then -1 else 0)) = max x y"
by (metis (mono_tags) max_def word_bitwise_m1_simps(2) word_bool_alg.xor_left_self word_bool_alg.xor_zero_right word_bw_comms(1) word_le_less_eq word_log_esimps(7))
lemma has_zero_byte:
"~~ (((((v::word32) && 0x7f7f7f7f) + 0x7f7f7f7f) || v) || 0x7f7f7f7f) \<noteq> 0
\<Longrightarrow> v && 0xff000000 = 0 \<or> v && 0xff0000 = 0 \<or> v && 0xff00 = 0 \<or> v && 0xff = 0"
apply clarsimp
apply word_bitwise
by metis
lemma swap_with_xor:"\<lbrakk>(x::word32) = a xor b; y = b xor x; z = x xor y\<rbrakk> \<Longrightarrow> z = b \<and> y = a"
by (metis word_bool_alg.xor_assoc word_bool_alg.xor_commute word_bool_alg.xor_self word_bool_alg.xor_zero_right)
lemma scast_nop_1:"((scast ((of_int x)::('a::len) word))::'a sword) = of_int x"
apply (clarsimp simp:scast_def word_of_int)
by (metis len_signed sint_sbintrunc' word_sint.Rep_inverse)
lemma scast_nop_2:"((scast ((of_int x)::('a::len) sword))::'a word) = of_int x"
apply (clarsimp simp:scast_def word_of_int)
by (metis len_signed sint_sbintrunc' word_sint.Rep_inverse)
lemmas scast_nop[simp] = scast_nop_1 scast_nop_2 scast_id
lemma le_mask_imp_and_mask:"(x::word32) \<le> mask n \<Longrightarrow> x && mask n = x"
by (metis and_mask_eq_iff_le_mask)
lemma or_not_mask_nop:"((x::word32) || ~~ mask n) && mask n = x && mask n"
by (metis word_and_not word_ao_dist2 word_bw_comms(1) word_log_esimps(3))
lemma mask_exceed:"n \<ge> 32 \<Longrightarrow> (x::word32) && ~~ mask n = 0"
apply (metis (erased, hide_lams) is_aligned_neg_mask is_aligned_neg_mask_eq mask_32_max_word
word_bool_alg.compl_one word_bool_alg.conj_zero_right)
done
lemma mask_subsume:"\<lbrakk>n \<le> m\<rbrakk> \<Longrightarrow> ((x::word32) || y && mask n) && ~~ mask m = x && ~~ mask m"
apply (subst word_ao_dist)
apply (subgoal_tac "(y && mask n) && ~~ mask m = 0")
apply simp
by (metis (no_types, hide_lams) is_aligned_mask is_aligned_weaken word_and_not word_bool_alg.conj_zero_right word_bw_comms(1) word_bw_lcs(1))
lemma mask_twice2:"n \<le> m \<Longrightarrow> ((x::word32) && mask m) && mask n = x && mask n"
by (metis mask_twice min_def)
(* Helper for dealing with casts of IPC buffer message register offsets.
* XXX: There is almost certainly a more pleasant way to do this proof.
*)
lemma unat_nat:"\<lbrakk>i \<ge> 0; i \<le>2 ^ 31\<rbrakk> \<Longrightarrow> (unat ((of_int i)::sword32)) = nat i"
unfolding unat_def apply (subst eq_nat_nat_iff, clarsimp+)
apply (subst Int.ring_1_class.of_nat_nat[symmetric], clarsimp+,
subst Word.word_of_int_nat[symmetric], clarsimp+)
apply (rule Word.word_uint.Abs_inverse)
apply clarsimp
apply (subst Word.uints_unats)
apply (induct i, (simp add:unats_def)+)
done
(* FIXME: MOVE *)
lemma pow_2_gt:"n \<ge> 2 \<Longrightarrow> (2::int) < 2 ^ n"
apply (induct n)
apply simp+
done
lemma uint_2_id:"len_of TYPE('a) \<ge> 2 \<Longrightarrow> uint (2::('a::len) word) = 2"
apply clarsimp
apply (subgoal_tac "2 \<in> uints (len_of TYPE('a))")
apply (subst (asm) Word.word_ubin.set_iff_norm)
apply simp
apply (subst word_uint.set_iff_norm)
apply clarsimp
apply (rule int_mod_eq')
apply simp
apply (rule pow_2_gt)
apply simp
done
(* FIXME: MOVE *)
lemma bintrunc_id:"\<lbrakk>of_nat n \<ge> m; m > 0\<rbrakk> \<Longrightarrow> bintrunc n m = m"
apply (subst bintrunc_mod2p)
apply (rule int_mod_eq')
apply simp+
apply (induct n arbitrary:m)
apply simp+
by force
lemma shiftr1_unfold:"shiftr1 x = x >> 1"
by (metis One_nat_def comp_apply funpow.simps(1) funpow.simps(2) id_apply shiftr_def)
lemma shiftr1_is_div_2:"(x::('a::len) word) >> 1 = x div 2"
apply (case_tac "len_of TYPE('a) = 1")
apply simp
apply (subgoal_tac "x = 0 \<or> x = 1")
apply (erule disjE)
apply (clarsimp simp:word_div_def)+
apply (metis One_nat_def less_irrefl_nat sint_1_cases)
apply clarsimp
apply (subst word_div_def)
apply clarsimp
apply (subst bintrunc_id)
apply (subgoal_tac "2 \<le> len_of TYPE('a)")
apply simp
apply (metis (no_types) le_0_eq le_SucE lens_not_0(2) not_less_eq_eq numeral_2_eq_2)
apply simp
apply (subst bin_rest_def[symmetric])
apply (subst shiftr1_def[symmetric])
apply (clarsimp simp:shiftr1_unfold)
done
lemma shiftl1_is_mult: "(x << 1) = (x :: 'a::len word) * 2"
by (metis One_nat_def mult_2 mult_2_right one_add_one
power_0 power_Suc shiftl_t2n)
lemma div_of_0_id[simp]:"(0::('a::len) word) div n = 0"
by (simp add: word_div_def)
lemma degenerate_word:"len_of TYPE('a) = 1 \<Longrightarrow> (x::('a::len) word) = 0 \<or> x = 1"
by (metis One_nat_def less_irrefl_nat sint_1_cases)
lemma div_by_0_word:"(x::('a::len) word) div 0 = 0"
by (metis div_0 div_by_0 unat_0 word_arith_nat_defs(6) word_div_1)
lemma div_less_dividend_word:"\<lbrakk>x \<noteq> 0; n \<noteq> 1\<rbrakk> \<Longrightarrow> (x::('a::len) word) div n < x"
apply (case_tac "n = 0")
apply clarsimp
apply (subst div_by_0_word)
apply (simp add:word_neq_0_conv)
apply (subst word_arith_nat_div)
apply (rule word_of_nat_less)
apply (rule div_less_dividend)
apply (metis (poly_guards_query) One_nat_def less_one nat_neq_iff unat_eq_1(2) unat_eq_zero)
apply (simp add:unat_gt_0)
done
lemma shiftr1_lt:"x \<noteq> 0 \<Longrightarrow> (x::('a::len) word) >> 1 < x"
apply (subst shiftr1_is_div_2)
apply (rule div_less_dividend_word)
apply simp+
done
lemma word_less_div:
fixes x :: "('a::len) word"
and y :: "('a::len) word"
shows "x div y = 0 \<Longrightarrow> y = 0 \<or> x < y"
apply (case_tac "y = 0", clarsimp+)
by (metis One_nat_def Suc_le_mono le0 le_div_geq not_less unat_0 unat_div unat_gt_0 word_less_nat_alt zero_less_one)
lemma not_degenerate_imp_2_neq_0:"len_of TYPE('a) > 1 \<Longrightarrow> (2::('a::len) word) \<noteq> 0"
by (metis numerals(1) power_not_zero power_zero_numeral)
lemma word_overflow:"(x::('a::len) word) + 1 > x \<or> x + 1 = 0"
apply clarsimp
by (metis diff_0 eq_diff_eq less_x_plus_1 max_word_max plus_1_less)
lemma word_overflow_unat:"unat ((x::('a::len) word) + 1) = unat x + 1 \<or> x + 1 = 0"
by (metis Suc_eq_plus1 add.commute unatSuc)
lemma even_word_imp_odd_next:"even (unat (x::('a::len) word)) \<Longrightarrow> x + 1 = 0 \<or> odd (unat (x + 1))"
apply (cut_tac x=x in word_overflow_unat)
apply clarsimp
done
lemma odd_word_imp_even_next:"odd (unat (x::('a::len) word)) \<Longrightarrow> x + 1 = 0 \<or> even (unat (x + 1))"
apply (cut_tac x=x in word_overflow_unat)
apply clarsimp
done
lemma overflow_imp_lsb:"(x::('a::len) word) + 1 = 0 \<Longrightarrow> x !! 0"
by (metis add.commute add_left_cancel max_word_max not_less word_and_1 word_bool_alg.conj_one_right word_bw_comms(1) word_overflow zero_neq_one)
lemma word_lsb_nat:"lsb w = (unat w mod 2 = 1)"
unfolding word_lsb_def bin_last_def
by (metis (no_types, hide_lams) nat_mod_distrib nat_numeral not_mod_2_eq_1_eq_0 numeral_One uint_eq_0 uint_nonnegative unat_0 unat_def zero_le_numeral)
lemma odd_iff_lsb:"odd (unat (x::('a::len) word)) = x !! 0"
apply (simp add:even_iff_mod_2_eq_zero)
apply (subst word_lsb_nat[unfolded One_nat_def, symmetric])
apply (rule word_lsb_alt)
done
lemma of_nat_neq_iff_word:
"x mod 2 ^ len_of TYPE('a) \<noteq> y mod 2 ^ len_of TYPE('a) \<Longrightarrow>
(((of_nat x)::('a::len) word) \<noteq> of_nat y) = (x \<noteq> y)"
apply (rule iffI)
apply (case_tac "x = y")
apply (subst (asm) of_nat_eq_iff[symmetric])
apply simp+
apply (case_tac "((of_nat x)::('a::len) word) = of_nat y")
apply (subst (asm) word_unat.norm_eq_iff[symmetric])
apply simp+
done
lemma shiftr1_irrelevant_lsb:"(x::('a::len) word) !! 0 \<or> x >> 1 = (x + 1) >> 1"
apply (case_tac "len_of TYPE('a) = 1")
apply clarsimp
apply (drule_tac x=x in degenerate_word[unfolded One_nat_def])
apply (erule disjE)
apply clarsimp+
apply (subst (asm) shiftr1_is_div_2[unfolded One_nat_def])+
apply (subst (asm) word_arith_nat_div)+
apply clarsimp
apply (subst (asm) bintrunc_id)
apply (subgoal_tac "len_of TYPE('a) > 0")
apply linarith
apply clarsimp+
apply (subst (asm) bintrunc_id)
apply (subgoal_tac "len_of TYPE('a) > 0")
apply linarith
apply clarsimp+
apply (case_tac "x + 1 = 0")
apply (clarsimp simp:overflow_imp_lsb)
apply (cut_tac x=x in word_overflow_unat)
apply clarsimp
apply (case_tac "even (unat x)")
apply (subgoal_tac "unat x div 2 = Suc (unat x) div 2")
apply metis
apply (subst numeral_2_eq_2)+
apply simp
apply (simp add:odd_iff_lsb)
done
lemma shiftr1_0_imp_only_lsb:"((x::('a::len) word) + 1) >> 1 = 0 \<Longrightarrow> x = 0 \<or> x + 1 = 0"
by (metis One_nat_def shiftr1_0_or_1 word_less_1 word_overflow)
lemma shiftr1_irrelevant_lsb':"\<not>((x::('a::len) word) !! 0) \<Longrightarrow> x >> 1 = (x + 1) >> 1"
by (metis shiftr1_irrelevant_lsb)
lemma lsb_this_or_next:"\<not>(((x::('a::len) word) + 1) !! 0) \<Longrightarrow> x !! 0"
by (metis (poly_guards_query) even_word_imp_odd_next odd_iff_lsb overflow_imp_lsb)
(* Bit population count. Equivalent of __builtin_popcount.
* FIXME: MOVE
*)
definition
pop_count :: "('a::len) word \<Rightarrow> nat"
where
"pop_count w \<equiv> length (filter id (to_bl w))"
lemma pop_count_0[simp]:"pop_count 0 = 0"
by (clarsimp simp:pop_count_def)
lemma pop_count_1[simp]:"pop_count 1 = 1"
by (clarsimp simp:pop_count_def to_bl_1)
lemma pop_count_0_imp_0:"(pop_count w = 0) = (w = 0)"
apply (rule iffI)
apply (clarsimp simp:pop_count_def)
apply (subst (asm) filter_empty_conv)
apply (clarsimp simp:eq_zero_set_bl)
apply fast
apply simp
done
(* Perhaps this one should be a simp lemma, but it seems a little dangerous. *)
lemma cast_chunk_assemble_id:
"\<lbrakk>n = len_of TYPE('a::len); m = len_of TYPE('b::len); n * 2 = m\<rbrakk> \<Longrightarrow>
(((ucast ((ucast (x::'b word))::'a word))::'b word) || (((ucast ((ucast (x >> n))::'a word))::'b word) << n)) = x"
apply (subgoal_tac "((ucast ((ucast (x >> n))::'a word))::'b word) = x >> n")
apply clarsimp
apply (subst and_not_mask[symmetric])
apply (subst ucast_ucast_mask)
apply (subst word_ao_dist2[symmetric])
apply clarsimp
apply (rule ucast_ucast_len)
apply (rule shiftr_less_t2n')
apply (subst and_mask_eq_iff_le_mask)
apply (clarsimp simp:mask_def)
apply (metis max_word_eq max_word_max mult_2_right)
apply (metis add_diff_cancel_left' diff_less len_gt_0 mult_2_right)
done
(* Helper for packing then unpacking a 64-bit variable. *)
lemma cast_chunk_assemble_id_64[simp]:
"(((ucast ((ucast (x::64 word))::32 word))::64 word) || (((ucast ((ucast (x >> 32))::32 word))::64 word) << 32)) = x"
by (simp add:cast_chunk_assemble_id)
lemma cast_chunk_scast_assemble_id:
"\<lbrakk>n = len_of TYPE('a::len); m = len_of TYPE('b::len); n * 2 = m\<rbrakk> \<Longrightarrow>
(((ucast ((scast (x::'b word))::'a word))::'b word) || (((ucast ((scast (x >> n))::'a word))::'b word) << n)) = x"
apply (subgoal_tac "((scast x)::'a word) = ((ucast x)::'a word)")
apply (subgoal_tac "((scast (x >> n))::'a word) = ((ucast (x >> n))::'a word)")
apply (simp add:cast_chunk_assemble_id)
apply (subst down_cast_same[symmetric], subst is_down, arith, simp)+
done
(* Another variant of packing and unpacking a 64-bit variable. *)
lemma cast_chunk_assemble_id_64'[simp]:
"(((ucast ((scast (x::64 word))::32 word))::64 word) || (((ucast ((scast (x >> 32))::32 word))::64 word) << 32)) = x"
by (simp add:cast_chunk_scast_assemble_id)
(* Specialiasations of down_cast_same for adding to local simpsets. *)
lemma cast_down_u64: "(scast::64 word \<Rightarrow> 32 word) = (ucast::64 word \<Rightarrow> 32 word)"
apply (subst down_cast_same[symmetric])
apply (simp add:is_down)+
done
lemma cast_down_s64: "(scast::64 sword \<Rightarrow> 32 word) = (ucast::64 sword \<Rightarrow> 32 word)"
apply (subst down_cast_same[symmetric])
apply (simp add:is_down)+
done
lemma mask_or_not_mask:"x && mask n || x && ~~ mask n = x"
apply (subst word_oa_dist)
apply simp
apply (subst word_oa_dist2)
apply simp
done
lemma is_aligned_add_not_aligned:
"\<lbrakk>is_aligned (p::word32) n; \<not> is_aligned (q::word32) n\<rbrakk> \<Longrightarrow>
\<not> is_aligned (p + q) n"
by (metis is_aligned_addD1)
lemma dvd_not_suc:"\<lbrakk> 2 ^ n dvd (p::nat); n > 0; i > 0; i < 2 ^ n; p + i > p; n < 32\<rbrakk> \<Longrightarrow>
\<not> (2 ^ n dvd (p + i))"
by (metis dvd_def dvd_reduce_multiple nat_dvd_not_less)
lemma word32_gr0_conv_Suc:"(m::word32) > 0 \<Longrightarrow> \<exists>n. m = n + 1"
by (metis add.commute add_minus_cancel)
lemma offset_not_aligned:
"\<lbrakk> is_aligned (p::word32) n; i > 0; i < 2 ^ n; n < 32\<rbrakk>
\<Longrightarrow> \<not> is_aligned (p + of_nat i) n"
apply (erule is_aligned_add_not_aligned)
unfolding is_aligned_def apply clarsimp
apply (subst (asm) unat_of_nat_len)
apply (metis len32 unat_less_word_bits unat_power_lower32 word_bits_conv)
apply (metis nat_dvd_not_less)
done
lemma neg_mask_add_aligned:
"\<lbrakk> is_aligned p n; q < 2 ^ n \<rbrakk>
\<Longrightarrow> (p + q) && ~~ mask n = p && ~~ mask n"
by (metis is_aligned_add_helper is_aligned_neg_mask_eq)
lemma word_sless_sint_le:"x <s y \<Longrightarrow> sint x \<le> sint y - 1"
by (metis word_sless_alt zle_diff1_eq)
lemma word_ge_min:"sint (x::32 word) \<ge> -2147483648"
by (metis sint_ge word32_bounds(1) word_size)
lemma set_enum_word8_def:
"((set enum)::word8 set) = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87,
88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103,
104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117,
118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131,
132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145,
146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173,
174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187,
188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201,
202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215,
216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229,
230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243,
244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255}"
by (eval)
lemma word8_exhaust:
fixes x :: word8
shows "\<lbrakk>x \<noteq> 0; x \<noteq> 1; x \<noteq> 2; x \<noteq> 3; x \<noteq> 4; x \<noteq> 5; x \<noteq> 6; x \<noteq> 7; x \<noteq> 8; x \<noteq> 9; x \<noteq> 10; x \<noteq> 11; x \<noteq>
12; x \<noteq> 13; x \<noteq> 14; x \<noteq> 15; x \<noteq> 16; x \<noteq> 17; x \<noteq> 18; x \<noteq> 19; x \<noteq> 20; x \<noteq> 21; x \<noteq> 22; x \<noteq>
23; x \<noteq> 24; x \<noteq> 25; x \<noteq> 26; x \<noteq> 27; x \<noteq> 28; x \<noteq> 29; x \<noteq> 30; x \<noteq> 31; x \<noteq> 32; x \<noteq> 33; x \<noteq>
34; x \<noteq> 35; x \<noteq> 36; x \<noteq> 37; x \<noteq> 38; x \<noteq> 39; x \<noteq> 40; x \<noteq> 41; x \<noteq> 42; x \<noteq> 43; x \<noteq> 44; x \<noteq>
45; x \<noteq> 46; x \<noteq> 47; x \<noteq> 48; x \<noteq> 49; x \<noteq> 50; x \<noteq> 51; x \<noteq> 52; x \<noteq> 53; x \<noteq> 54; x \<noteq> 55; x \<noteq>
56; x \<noteq> 57; x \<noteq> 58; x \<noteq> 59; x \<noteq> 60; x \<noteq> 61; x \<noteq> 62; x \<noteq> 63; x \<noteq> 64; x \<noteq> 65; x \<noteq> 66; x \<noteq>
67; x \<noteq> 68; x \<noteq> 69; x \<noteq> 70; x \<noteq> 71; x \<noteq> 72; x \<noteq> 73; x \<noteq> 74; x \<noteq> 75; x \<noteq> 76; x \<noteq> 77; x \<noteq>
78; x \<noteq> 79; x \<noteq> 80; x \<noteq> 81; x \<noteq> 82; x \<noteq> 83; x \<noteq> 84; x \<noteq> 85; x \<noteq> 86; x \<noteq> 87; x \<noteq> 88; x \<noteq>
89; x \<noteq> 90; x \<noteq> 91; x \<noteq> 92; x \<noteq> 93; x \<noteq> 94; x \<noteq> 95; x \<noteq> 96; x \<noteq> 97; x \<noteq> 98; x \<noteq> 99; x \<noteq>
100; x \<noteq> 101; x \<noteq> 102; x \<noteq> 103; x \<noteq> 104; x \<noteq> 105; x \<noteq> 106; x \<noteq> 107; x \<noteq> 108; x \<noteq> 109; x \<noteq>
110; x \<noteq> 111; x \<noteq> 112; x \<noteq> 113; x \<noteq> 114; x \<noteq> 115; x \<noteq> 116; x \<noteq> 117; x \<noteq> 118; x \<noteq> 119; x \<noteq>
120; x \<noteq> 121; x \<noteq> 122; x \<noteq> 123; x \<noteq> 124; x \<noteq> 125; x \<noteq> 126; x \<noteq> 127; x \<noteq> 128; x \<noteq> 129; x \<noteq>
130; x \<noteq> 131; x \<noteq> 132; x \<noteq> 133; x \<noteq> 134; x \<noteq> 135; x \<noteq> 136; x \<noteq> 137; x \<noteq> 138; x \<noteq> 139; x \<noteq>
140; x \<noteq> 141; x \<noteq> 142; x \<noteq> 143; x \<noteq> 144; x \<noteq> 145; x \<noteq> 146; x \<noteq> 147; x \<noteq> 148; x \<noteq> 149; x \<noteq>
150; x \<noteq> 151; x \<noteq> 152; x \<noteq> 153; x \<noteq> 154; x \<noteq> 155; x \<noteq> 156; x \<noteq> 157; x \<noteq> 158; x \<noteq> 159; x \<noteq>
160; x \<noteq> 161; x \<noteq> 162; x \<noteq> 163; x \<noteq> 164; x \<noteq> 165; x \<noteq> 166; x \<noteq> 167; x \<noteq> 168; x \<noteq> 169; x \<noteq>
170; x \<noteq> 171; x \<noteq> 172; x \<noteq> 173; x \<noteq> 174; x \<noteq> 175; x \<noteq> 176; x \<noteq> 177; x \<noteq> 178; x \<noteq> 179; x \<noteq>
180; x \<noteq> 181; x \<noteq> 182; x \<noteq> 183; x \<noteq> 184; x \<noteq> 185; x \<noteq> 186; x \<noteq> 187; x \<noteq> 188; x \<noteq> 189; x \<noteq>
190; x \<noteq> 191; x \<noteq> 192; x \<noteq> 193; x \<noteq> 194; x \<noteq> 195; x \<noteq> 196; x \<noteq> 197; x \<noteq> 198; x \<noteq> 199; x \<noteq>
200; x \<noteq> 201; x \<noteq> 202; x \<noteq> 203; x \<noteq> 204; x \<noteq> 205; x \<noteq> 206; x \<noteq> 207; x \<noteq> 208; x \<noteq> 209; x \<noteq>
210; x \<noteq> 211; x \<noteq> 212; x \<noteq> 213; x \<noteq> 214; x \<noteq> 215; x \<noteq> 216; x \<noteq> 217; x \<noteq> 218; x \<noteq> 219; x \<noteq>
220; x \<noteq> 221; x \<noteq> 222; x \<noteq> 223; x \<noteq> 224; x \<noteq> 225; x \<noteq> 226; x \<noteq> 227; x \<noteq> 228; x \<noteq> 229; x \<noteq>
230; x \<noteq> 231; x \<noteq> 232; x \<noteq> 233; x \<noteq> 234; x \<noteq> 235; x \<noteq> 236; x \<noteq> 237; x \<noteq> 238; x \<noteq> 239; x \<noteq>
240; x \<noteq> 241; x \<noteq> 242; x \<noteq> 243; x \<noteq> 244; x \<noteq> 245; x \<noteq> 246; x \<noteq> 247; x \<noteq> 248; x \<noteq> 249; x \<noteq>
250; x \<noteq> 251; x \<noteq> 252; x \<noteq> 253; x \<noteq> 254; x \<noteq> 255\<rbrakk> \<Longrightarrow> P"
by (subgoal_tac "x \<in> set enum",
subst (asm) set_enum_word8_def,
simp,
simp)
lemma upper_trivial:
fixes x :: "'a::len word"
shows "x \<noteq> 2 ^ len_of TYPE('a) - 1 \<Longrightarrow> x < 2 ^ len_of TYPE('a) - 1"
by (cut_tac n=x and 'a='a in max_word_max,
clarsimp simp:max_word_def,
simp add: less_le)
lemma constraint_expand:
fixes x :: "'a::len word"
shows "x \<in> {y. lower \<le> y \<and> y \<le> upper} = (lower \<le> x \<and> x \<le> upper)"
by simp
lemma card_map_elide:
"n \<le> CARD(32 word) \<Longrightarrow> card ((of_nat::nat \<Rightarrow> 32 word) ` {0..<n}) = card {0..<n}"
apply clarsimp
apply (induct n)
apply clarsimp+
apply (subgoal_tac "{0..<Suc n} = {0..<n} \<union> {n}")
prefer 2
apply clarsimp
apply fastforce
apply clarsimp
apply (subst card_insert_disjoint)
apply clarsimp
apply (subst atLeast0LessThan)
apply (subgoal_tac "(of_nat::nat \<Rightarrow> 32 word) ` {..<n} = {..<of_nat n}")
prefer 2
apply (rule equalityI)
apply clarsimp
apply (subst (asm) card_word)
apply clarsimp
apply (rule of_nat_mono_maybe)
apply clarsimp+
apply (subgoal_tac "x \<in> of_nat ` {..<n} = (\<exists>y\<in>{..<n}. of_nat y = x)")
prefer 2
apply blast
apply simp
apply (rule bexI) (* sorry for schematics *)
apply (rule word_unat.Rep_inverse')
apply force
apply clarsimp
apply (subst (asm) card_word)
apply clarsimp
apply (metis (erased, hide_lams) Divides.mod_less_eq_dividend order_less_le_trans unat_of_nat word_less_nat_alt)
by clarsimp+
lemma card_map_elide2: "n \<le> CARD(32 word) \<Longrightarrow> card ((of_nat::nat \<Rightarrow> 32 word) ` {0..<n}) = n"
apply (subst card_map_elide)
by clarsimp+
lemma le_max_word_ucast_id:
"(x::'a::len word) \<le> ucast (max_word::'b::len word) \<Longrightarrow> ucast ((ucast x)::'b word) = x"
apply (unfold ucast_def)
apply (subst word_ubin.eq_norm)
apply (subst and_mask_bintr[symmetric])
apply (subst and_mask_eq_iff_le_mask)
apply (clarsimp simp:max_word_def mask_def)
proof -
assume a1: "x \<le> word_of_int (uint (word_of_int (2 ^ len_of (TYPE('b)\<Colon>'b itself) - 1)\<Colon>'b word))"
have f2: "((\<exists>i ia. (0\<Colon>int) \<le> i \<and> \<not> 0 \<le> i + - 1 * ia \<and> i mod ia \<noteq> i) \<or> \<not> (0\<Colon>int) \<le> - 1 + 2 ^ len_of (TYPE('b)\<Colon>'b itself) \<or> (0\<Colon>int) \<le> - 1 + 2 ^ len_of (TYPE('b)\<Colon>'b itself) + - 1 * 2 ^ len_of (TYPE('b)\<Colon>'b itself) \<or> (- (1\<Colon>int) + 2 ^ len_of (TYPE('b)\<Colon>'b itself)) mod 2 ^ len_of (TYPE('b)\<Colon>'b itself) = - 1 + 2 ^ len_of (TYPE('b)\<Colon>'b itself)) = ((\<exists>i ia. (0\<Colon>int) \<le> i \<and> \<not> 0 \<le> i + - 1 * ia \<and> i mod ia \<noteq> i) \<or> \<not> (1\<Colon>int) \<le> 2 ^ len_of (TYPE('b)\<Colon>'b itself) \<or> 2 ^ len_of (TYPE('b)\<Colon>'b itself) + - (1\<Colon>int) * ((- 1 + 2 ^ len_of (TYPE('b)\<Colon>'b itself)) mod 2 ^ len_of (TYPE('b)\<Colon>'b itself)) = 1)"
by force
have f3: "\<forall>i ia. \<not> (0\<Colon>int) \<le> i \<or> 0 \<le> i + - 1 * ia \<or> i mod ia = i"
using mod_pos_pos_trivial by force
have "(1\<Colon>int) \<le> 2 ^ len_of (TYPE('b)\<Colon>'b itself)"
by simp
hence "2 ^ len_of (TYPE('b)\<Colon>'b itself) + - (1\<Colon>int) * ((- 1 + 2 ^ len_of (TYPE('b)\<Colon>'b itself)) mod 2 ^ len_of (TYPE('b)\<Colon>'b itself)) = 1"
using f3 f2 by blast
hence f4: "- (1\<Colon>int) + 2 ^ len_of (TYPE('b)\<Colon>'b itself) = (- 1 + 2 ^ len_of (TYPE('b)\<Colon>'b itself)) mod 2 ^ len_of (TYPE('b)\<Colon>'b itself)"
by linarith
have f5: "x \<le> word_of_int (uint (word_of_int (- 1 + 2 ^ len_of (TYPE('b)\<Colon>'b itself))\<Colon>'b word))"
using a1 by force
have f6: "2 ^ len_of (TYPE('b)\<Colon>'b itself) + - (1\<Colon>int) = - 1 + 2 ^ len_of (TYPE('b)\<Colon>'b itself)"
by force
have f7: "- (1\<Colon>int) * 1 = - 1"
by auto
have "\<forall>x0 x1. (x1\<Colon>int) - x0 = x1 + - 1 * x0"
by force
thus "x \<le> 2 ^ len_of (TYPE('b)\<Colon>'b itself) - 1"
using f7 f6 f5 f4 by (metis uint_word_of_int wi_homs(2) word_arith_wis(8) word_of_int_2p)
qed
(*enumerations of words*)
lemma remdups_enum_upto: fixes s::"'a::len word" shows "remdups [s .e. e] = [s .e. e]" by(simp)
lemma card_enum_upto: fixes s::"'a::len word" shows "card (set [s .e. e]) = Suc (unat e) - unat s"
apply(subst List.card_set)
apply(simp add: remdups_enum_upto)
done
end
|
from numpy import zeros,mean,std, sum, array,inf,isinf
import copy
from multiprocessing import Process, Manager, Queue
from queue import Empty
import time
def summed_sq_error(features,segment_ends):
num_segs = len(segment_ends)
seg_begin = 0
sse = 0
for l in range(0,num_segs):
seg_end = segment_ends[l]
#if num_segs == 28:
# print(l)
# print(seg_begin)
# print(seg_end)
sse += seg_sse(features,seg_begin,seg_end)
seg_begin = seg_end
#print(sse)
return sse
def seg_sse(features,seg_begin,seg_end):
num_features = features.shape[1]
ml = zeros((1,num_features))
count = 0
for t in range(seg_begin,seg_end):
ml += features[t,:]
count += 1
ml /= count
sse = 0
for t in range(seg_begin,seg_end):
sse += sum((features[t,:] - ml) ** 2)
return sse
def sse_worker(job_q,return_dict,features, segment_set):
while True:
try:
l = job_q.get(timeout=1)
except Empty:
break
return_dict[segment_set[l]] = calc_boundary_removal_sse(features, segment_set, l)
def calc_boundary_removal_sse(features, segment_set, l):
segment_temp = copy.deepcopy(segment_set)
del segment_temp[l]
if l == 0:
begin = 0
else:
begin = segment_temp[l-1]
return seg_sse(features,begin,segment_temp[l])
def generate_initial_cache(features,segment_set, num_procs):
sse_cache = {}
num_segments = len(segment_set)
job_queue = Queue()
for l in range(num_segments-1):
job_queue.put(l)
manager = Manager()
return_dict = manager.dict()
procs = []
for i in range(num_procs):
p = Process(
target=sse_worker,
args=(job_queue,
return_dict,features, segment_set))
procs.append(p)
p.start()
time.sleep(2)
for p in procs:
p.join()
return return_dict
def find_next_best_cached(features,segment_temp,sse_cache):
segment_set = copy.deepcopy(segment_temp)
available = filter(lambda x: x[0] != features.shape[0],sse_cache.items())
seg_bound, min_delta_sse = min(available, key = lambda x: x[1])
inverted = dict([[v,k] for k,v in enumerate(segment_set)])
ind = inverted[seg_bound]
del segment_set[ind]
del sse_cache[seg_bound]
if ind != 0:
sse_cache[segment_set[ind-1]] = calc_boundary_removal_sse(features,segment_set,ind-1)
if segment_set[ind] != features.shape[0]:
sse_cache[segment_set[ind]] = calc_boundary_removal_sse(features,segment_set,ind)
return min_delta_sse, segment_set, sse_cache
def to_segments(features, threshold = 0.1, return_means=False,debug=False):
if debug:
start_time = time.time()
print(features.shape)
num_frames, num_coeffs = features.shape
L = {}
segment_iter = {}
seg_temp = list(range(1,num_frames+1))
if debug:
print('begin boundary removals')
prev_time = time.time()
sse_cache = generate_initial_cache(features,seg_temp, 6)
for num_segments in range(num_frames-1,1,-1):
if debug:
cur = num_frames-1-num_segments
if cur % 100 == 0:
print('loop %d of %d' % (cur,num_frames-1))
#L[num_segments],segment_iter[num_segments], sse_cache = find_next_best(features,seg_temp,sse_cache,1)
L[num_segments],segment_iter[num_segments], sse_cache = find_next_best_cached(features,seg_temp,sse_cache)
seg_temp = segment_iter[num_segments]
if debug:
print('greedy segmentation took %f seconds' % (time.time()-start_time))
print('Finding threshold')
Larray = array(list(L.values()))
thresh = mean(Larray) + (threshold *std(Larray))
if debug:
print(mean(Larray))
print(thresh)
ks = list(segment_iter.keys())
for i in range(max(ks),min(ks)-1,-1):
if L[i] > thresh:
if debug:
print(i)
optimal = segment_iter[i]
break
else:
optimal = segment_iter[-1]
if not return_means:
return optimal
seg_begin = 0
segments = zeros((len(optimal),num_coeffs))
for i in range(len(optimal)):
seg_end = optimal[i]
segments[i,:] = mean(features[seg_begin:seg_end,:],axis=0)
seg_begin = seg_end
return optimal,segments
|
(*
Copyright 2019
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.
*)
theory example
imports "../../isabelle/VCG/HTriple"
begin
locale "example" = execution_context + exec_code +
fixes is_even_0x124b_retval\<^sub>v stack_chk_fail_0x127b_retval\<^sub>v stack_chk_fail_addr :: \<open>64 word\<close>
and stack_chk_fail_acode :: ACode
assumes fetch:
"fetch 0x1135 \<equiv> (Unary (IS_8088 Push) (Storage (Reg (General SixtyFour rbp))), 1)"
"fetch 0x1136 \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rbp)) (Storage (Reg (General SixtyFour rsp))), 3)"
"fetch 0x1139 \<equiv> (Binary (IS_8088 Mov) (Memory ThirtyTwo (A_SizeDirective 32 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 4)))) (Storage (Reg (General ThirtyTwo rdi))), 3)"
"fetch 0x113c \<equiv> (Binary (IS_8088 Mov) (Reg (General ThirtyTwo rax)) (Storage (Memory ThirtyTwo (A_SizeDirective 32 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 4))))), 3)"
"fetch 0x113f \<equiv> (Binary (IS_8088 And) (Reg (General ThirtyTwo rax)) (Immediate SixtyFour (ImmVal 1)), 3)"
"fetch 0x1142 \<equiv> (Binary (IS_8088 Test) (Reg (General ThirtyTwo rax)) (Storage (Reg (General ThirtyTwo rax))), 2)"
"fetch 0x1144 \<equiv> (Unary (IS_80386 Sete) (Storage (Reg (General Eight rax))), 3)"
"fetch 0x1147 \<equiv> (Unary (IS_8088 Pop) (Storage (Reg (General SixtyFour rbp))), 1)"
"fetch 0x1148 \<equiv> (Nullary (IS_8088 Ret), 1)"
"fetch 0x1149 \<equiv> (Unary (IS_8088 Push) (Storage (Reg (General SixtyFour rbp))), 1)"
"fetch 0x114a \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rbp)) (Storage (Reg (General SixtyFour rsp))), 3)"
"fetch 0x114d \<equiv> (Unary (IS_8088 Push) (Storage (Reg (General SixtyFour rbx))), 1)"
"fetch 0x114e \<equiv> (Binary (IS_8088 Sub) (Reg (General SixtyFour rsp)) (Immediate SixtyFour (ImmVal 72)), 4)"
"fetch 0x1152 \<equiv> (Binary (IS_8088 Mov) (Memory ThirtyTwo (A_SizeDirective 32 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 68)))) (Storage (Reg (General ThirtyTwo rdi))), 3)"
"fetch 0x1155 \<equiv> (Binary (IS_8088 Mov) (Memory SixtyFour (A_SizeDirective 64 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 80)))) (Storage (Reg (General SixtyFour rsi))), 4)"
"fetch 0x1159 \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rax)) (Storage (Memory SixtyFour (A_SizeDirective 64 (A_Plus (A_FromReg (General SixtyFour fs)) (A_WordConstant 40))))), 9)"
"fetch 0x1162 \<equiv> (Binary (IS_8088 Mov) (Memory SixtyFour (A_SizeDirective 64 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 24)))) (Storage (Reg (General SixtyFour rax))), 4)"
"fetch 0x1166 \<equiv> (Binary (IS_8088 Xor) (Reg (General ThirtyTwo rax)) (Storage (Reg (General ThirtyTwo rax))), 2)"
"fetch 0x1168 \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rax)) (Storage (Reg (General SixtyFour rsp))), 3)"
"fetch 0x116b \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rbx)) (Storage (Reg (General SixtyFour rax))), 3)"
"fetch 0x116e \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rax)) (Storage (Memory SixtyFour (A_SizeDirective 64 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 80))))), 4)"
"fetch 0x1172 \<equiv> (Binary (IS_8088 Mov) (Memory SixtyFour (A_SizeDirective 64 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 56)))) (Storage (Reg (General SixtyFour rax))), 4)"
"fetch 0x1176 \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rax)) (Storage (Memory SixtyFour (A_SizeDirective 64 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 80))))), 4)"
"fetch 0x117a \<equiv> (Binary (IS_8088 Add) (Reg (General SixtyFour rax)) (Immediate SixtyFour (ImmVal 32)), 4)"
"fetch 0x117e \<equiv> (Binary (IS_8088 Mov) (Memory SixtyFour (A_SizeDirective 64 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 48)))) (Storage (Reg (General SixtyFour rax))), 4)"
"fetch 0x1182 \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rax)) (Storage (Memory SixtyFour (A_SizeDirective 64 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 56))))), 4)"
"fetch 0x1186 \<equiv> (Binary (IS_8088 Mov) (Reg (General ThirtyTwo rcx)) (Storage (Memory ThirtyTwo (A_SizeDirective 32 (A_FromReg (General SixtyFour rax))))), 2)"
"fetch 0x1188 \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rax)) (Storage (Memory SixtyFour (A_SizeDirective 64 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 48))))), 4)"
"fetch 0x118c \<equiv> (Binary (IS_8088 Mov) (Reg (General ThirtyTwo rdx)) (Storage (Memory ThirtyTwo (A_SizeDirective 32 (A_FromReg (General SixtyFour rax))))), 2)"
"fetch 0x118e \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rax)) (Storage (Memory SixtyFour (A_SizeDirective 64 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 80))))), 4)"
"fetch 0x1192 \<equiv> (Binary (IS_8088 Add) (Reg (General SixtyFour rax)) (Immediate SixtyFour (ImmVal 16)), 4)"
"fetch 0x1196 \<equiv> (Binary (IS_8088 Add) (Reg (General ThirtyTwo rdx)) (Storage (Reg (General ThirtyTwo rcx))), 2)"
"fetch 0x1198 \<equiv> (Binary (IS_8088 Mov) (Memory ThirtyTwo (A_SizeDirective 32 (A_FromReg (General SixtyFour rax)))) (Storage (Reg (General ThirtyTwo rdx))), 2)"
"fetch 0x119a \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rax)) (Storage (Memory SixtyFour (A_SizeDirective 64 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 80))))), 4)"
"fetch 0x119e \<equiv> (Binary (IS_8088 Mov) (Memory Eight (A_SizeDirective 8 (A_FromReg (General SixtyFour rax)))) (Immediate SixtyFour (ImmVal 97)), 3)"
"fetch 0x11a1 \<equiv> (Binary (IS_8088 Mov) (Reg (General ThirtyTwo rax)) (Storage (Memory ThirtyTwo (A_SizeDirective 32 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 68))))), 3)"
"fetch 0x11a4 \<equiv> (Binary (IS_X86_64 Movsxd) (Reg (General SixtyFour rdx)) (Storage (Reg (General ThirtyTwo rax))), 3)"
"fetch 0x11a7 \<equiv> (Binary (IS_8088 Sub) (Reg (General SixtyFour rdx)) (Immediate SixtyFour (ImmVal 1)), 4)"
"fetch 0x11ab \<equiv> (Binary (IS_8088 Mov) (Memory SixtyFour (A_SizeDirective 64 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 40)))) (Storage (Reg (General SixtyFour rdx))), 4)"
"fetch 0x11af \<equiv> (Binary (IS_X86_64 Movsxd) (Reg (General SixtyFour rdx)) (Storage (Reg (General ThirtyTwo rax))), 3)"
"fetch 0x11b2 \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour r10)) (Storage (Reg (General SixtyFour rdx))), 3)"
"fetch 0x11b5 \<equiv> (Binary (IS_8088 Mov) (Reg (General ThirtyTwo r11)) (Immediate SixtyFour (ImmVal 0)), 6)"
"fetch 0x11bb \<equiv> (Binary (IS_X86_64 Movsxd) (Reg (General SixtyFour rdx)) (Storage (Reg (General ThirtyTwo rax))), 3)"
"fetch 0x11be \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour r8)) (Storage (Reg (General SixtyFour rdx))), 3)"
"fetch 0x11c1 \<equiv> (Binary (IS_8088 Mov) (Reg (General ThirtyTwo r9)) (Immediate SixtyFour (ImmVal 0)), 6)"
"fetch 0x11c7 \<equiv> (Nullary (IS_X86_64 Cdqe), 2)"
"fetch 0x11c9 \<equiv> (Binary (IS_8088 Lea) (Reg (General SixtyFour rdx)) (Storage (Memory SixtyFour (A_Plus (A_Mult 4 (A_FromReg (General SixtyFour rax))) (A_WordConstant 0)))), 8)"
"fetch 0x11d1 \<equiv> (Binary (IS_8088 Mov) (Reg (General ThirtyTwo rax)) (Immediate SixtyFour (ImmVal 16)), 5)"
"fetch 0x11d6 \<equiv> (Binary (IS_8088 Sub) (Reg (General SixtyFour rax)) (Immediate SixtyFour (ImmVal 1)), 4)"
"fetch 0x11da \<equiv> (Binary (IS_8088 Add) (Reg (General SixtyFour rax)) (Storage (Reg (General SixtyFour rdx))), 3)"
"fetch 0x11dd \<equiv> (Binary (IS_8088 Mov) (Reg (General ThirtyTwo rsi)) (Immediate SixtyFour (ImmVal 16)), 5)"
"fetch 0x11e2 \<equiv> (Binary (IS_8088 Mov) (Reg (General ThirtyTwo rdx)) (Immediate SixtyFour (ImmVal 0)), 5)"
"fetch 0x11e7 \<equiv> (Unary (IS_8088 Div) (Storage (Reg (General SixtyFour rsi))), 3)"
"fetch 0x11ea \<equiv> (Ternary (IS_8088 Imul) (Reg (General SixtyFour rax)) (Storage (Reg (General SixtyFour rax))) (Immediate SixtyFour (ImmVal 16)), 4)"
"fetch 0x11ee \<equiv> (Binary (IS_8088 Sub) (Reg (General SixtyFour rsp)) (Storage (Reg (General SixtyFour rax))), 3)"
"fetch 0x11f1 \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rax)) (Storage (Reg (General SixtyFour rsp))), 3)"
"fetch 0x11f4 \<equiv> (Binary (IS_8088 Add) (Reg (General SixtyFour rax)) (Immediate SixtyFour (ImmVal 3)), 4)"
"fetch 0x11f8 \<equiv> (Binary (IS_8088 Shr) (Reg (General SixtyFour rax)) (Immediate SixtyFour (ImmVal 2)), 4)"
"fetch 0x11fc \<equiv> (Binary (IS_8088 Shl) (Reg (General SixtyFour rax)) (Immediate SixtyFour (ImmVal 2)), 4)"
"fetch 0x1200 \<equiv> (Binary (IS_8088 Mov) (Memory SixtyFour (A_SizeDirective 64 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 32)))) (Storage (Reg (General SixtyFour rax))), 4)"
"fetch 0x1204 \<equiv> (Binary (IS_8088 Mov) (Memory ThirtyTwo (A_SizeDirective 32 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 60)))) (Immediate SixtyFour (ImmVal 0)), 7)"
"fetch 0x120b \<equiv> (Unary (IS_8088 Jmp) (Immediate SixtyFour (ImmVal 4670)), 2)"
"fetch 0x120d \<equiv> (Binary (IS_8088 Mov) (Reg (General ThirtyTwo rax)) (Storage (Memory ThirtyTwo (A_SizeDirective 32 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 60))))), 3)"
"fetch 0x1210 \<equiv> (Nullary (IS_X86_64 Cdqe), 2)"
"fetch 0x1212 \<equiv> (Binary (IS_8088 Lea) (Reg (General SixtyFour rdx)) (Storage (Memory SixtyFour (A_Plus (A_Mult 8 (A_FromReg (General SixtyFour rax))) (A_WordConstant 0)))), 8)"
"fetch 0x121a \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rax)) (Storage (Memory SixtyFour (A_SizeDirective 64 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 80))))), 4)"
"fetch 0x121e \<equiv> (Binary (IS_8088 Add) (Reg (General SixtyFour rax)) (Storage (Reg (General SixtyFour rdx))), 3)"
"fetch 0x1221 \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rax)) (Storage (Memory SixtyFour (A_SizeDirective 64 (A_FromReg (General SixtyFour rax))))), 3)"
"fetch 0x1224 \<equiv> (Binary (IS_80386 Movzx) (Reg (General ThirtyTwo rax)) (Storage (Memory Eight (A_SizeDirective 8 (A_FromReg (General SixtyFour rax))))), 3)"
"fetch 0x1227 \<equiv> (Binary (IS_80386 Movsx) (Reg (General ThirtyTwo rax)) (Storage (Reg (General Eight rax))), 3)"
"fetch 0x122a \<equiv> (Binary (IS_8088 Lea) (Reg (General ThirtyTwo rcx)) (Storage (Memory SixtyFour (A_Plus (A_FromReg (General SixtyFour rax)) (A_Mult 1 (A_FromReg (General SixtyFour rax)))))), 3)"
"fetch 0x122d \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rax)) (Storage (Memory SixtyFour (A_SizeDirective 64 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 32))))), 4)"
"fetch 0x1231 \<equiv> (Binary (IS_8088 Mov) (Reg (General ThirtyTwo rdx)) (Storage (Memory ThirtyTwo (A_SizeDirective 32 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 60))))), 3)"
"fetch 0x1234 \<equiv> (Binary (IS_X86_64 Movsxd) (Reg (General SixtyFour rdx)) (Storage (Reg (General ThirtyTwo rdx))), 3)"
"fetch 0x1237 \<equiv> (Binary (IS_8088 Mov) (Memory ThirtyTwo (A_SizeDirective 32 (A_Plus (A_FromReg (General SixtyFour rax)) (A_Mult 4 (A_FromReg (General SixtyFour rdx)))))) (Storage (Reg (General ThirtyTwo rcx))), 3)"
"fetch 0x123a \<equiv> (Binary (IS_8088 Add) (Memory ThirtyTwo (A_SizeDirective 32 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 60)))) (Immediate SixtyFour (ImmVal 1)), 4)"
"fetch 0x123e \<equiv> (Binary (IS_8088 Mov) (Reg (General ThirtyTwo rax)) (Storage (Memory ThirtyTwo (A_SizeDirective 32 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 60))))), 3)"
"fetch 0x1241 \<equiv> (Binary (IS_8088 Cmp) (Reg (General ThirtyTwo rax)) (Storage (Memory ThirtyTwo (A_SizeDirective 32 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 68))))), 3)"
"fetch 0x1244 \<equiv> (Unary (IS_8088 Jl) (Immediate SixtyFour (ImmVal 4621)), 2)"
"fetch 0x1246 \<equiv> (Binary (IS_8088 Mov) (Reg (General ThirtyTwo rax)) (Storage (Memory ThirtyTwo (A_SizeDirective 32 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 68))))), 3)"
"fetch 0x1249 \<equiv> (Binary (IS_8088 Mov) (Reg (General ThirtyTwo rdi)) (Storage (Reg (General ThirtyTwo rax))), 2)"
"fetch 0x124b \<equiv> (Unary (IS_8088 Call) (Immediate SixtyFour (ImmLabel ''is_even'')), 5)"
"fetch 0x1250 \<equiv> (Binary (IS_8088 Test) (Reg (General Eight rax)) (Storage (Reg (General Eight rax))), 2)"
"fetch 0x1252 \<equiv> (Unary (IS_8088 Je) (Immediate SixtyFour (ImmVal 4707)), 2)"
"fetch 0x1254 \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rax)) (Storage (Memory SixtyFour (A_SizeDirective 64 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 32))))), 4)"
"fetch 0x1258 \<equiv> (Binary (IS_8088 Mov) (Reg (General ThirtyTwo rdx)) (Storage (Memory ThirtyTwo (A_SizeDirective 32 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 68))))), 3)"
"fetch 0x125b \<equiv> (Binary (IS_X86_64 Movsxd) (Reg (General SixtyFour rdx)) (Storage (Reg (General ThirtyTwo rdx))), 3)"
"fetch 0x125e \<equiv> (Binary (IS_8088 Mov) (Reg (General ThirtyTwo rax)) (Storage (Memory ThirtyTwo (A_SizeDirective 32 (A_Plus (A_FromReg (General SixtyFour rax)) (A_Mult 4 (A_FromReg (General SixtyFour rdx))))))), 3)"
"fetch 0x1261 \<equiv> (Unary (IS_8088 Jmp) (Immediate SixtyFour (ImmVal 4713)), 2)"
"fetch 0x1263 \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rax)) (Storage (Memory SixtyFour (A_SizeDirective 64 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 32))))), 4)"
"fetch 0x1267 \<equiv> (Binary (IS_8088 Mov) (Reg (General ThirtyTwo rax)) (Storage (Memory ThirtyTwo (A_SizeDirective 32 (A_FromReg (General SixtyFour rax))))), 2)"
"fetch 0x1269 \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rsp)) (Storage (Reg (General SixtyFour rbx))), 3)"
"fetch 0x126c \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rsi)) (Storage (Memory SixtyFour (A_SizeDirective 64 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 24))))), 4)"
"fetch 0x1270 \<equiv> (Binary (IS_8088 Xor) (Reg (General SixtyFour rsi)) (Storage (Memory SixtyFour (A_SizeDirective 64 (A_Plus (A_FromReg (General SixtyFour fs)) (A_WordConstant 40))))), 9)"
"fetch 0x1279 \<equiv> (Unary (IS_8088 Je) (Immediate SixtyFour (ImmVal 4736)), 2)"
"fetch 0x127b \<equiv> (Unary (IS_8088 Call) (Immediate SixtyFour (ImmLabel ''__stack_chk_fail'')), 5)"
"fetch 0x1280 \<equiv> (Binary (IS_8088 Mov) (Reg (General SixtyFour rbx)) (Storage (Memory SixtyFour (A_SizeDirective 64 (A_Minus (A_FromReg (General SixtyFour rbp)) (A_WordConstant 8))))), 4)"
"fetch 0x1284 \<equiv> (Nullary (IS_80188 Leave), 1)"
"fetch 0x1285 \<equiv> (Nullary (IS_8088 Ret), 1)"
and \<alpha>_def: \<open>\<alpha> = \<lparr>text_sections = [], data_sections = [], labels_to_offsets = [], binary_offset = 0\<rparr>\<close>
and stack_chk_fail\<^sub>a\<^sub>d\<^sub>d\<^sub>r[simp]: \<open>the (label_to_address \<alpha> ''__stack_chk_fail'') = stack_chk_fail_addr\<close>
and is_even\<^sub>a\<^sub>d\<^sub>d\<^sub>r[simp]: \<open>the (label_to_address \<alpha> ''is_even'') = 0x1135\<close>
begin
text \<open>Using definitions that don't get unfolded immediately prevents locale argument issues.\<close>
definition \<open>is_even_0x124b_retval \<equiv> is_even_0x124b_retval\<^sub>v\<close>
definition \<open>stack_chk_fail_0x127b_retval \<equiv> stack_chk_fail_0x127b_retval\<^sub>v\<close>
text \<open>
Going with a binary offset of 0 for now to make things easier. (We do want to keep that field
around, though, for future more generic usage.)
\<close>
lemma \<alpha>_boffset[simp]: \<open>binary_offset \<alpha> = 0\<close>
unfolding \<alpha>_def
by simp
named_theorems blocks and Ps and Qs
method step uses add del =
subst exec_block.simps,
rewrite_one_let',
rewrite_one_let' add: fetch,
rewrite_one_let',
auto simp add: simp_rules Let'_def read_region'_def write_block'_def get'_def set'_def step_def exec_instr_def presimplify add numeral_2_eq_2[symmetric] simp del: del
method steps uses pre post regionset add del =
auto simp: pred_logic pre regionset,
(step add: add del: del)+,
(auto simp add: eq_def)[1],
auto simp: block_usage_def eq_def setcc_def cmovcc_def if'_then_else_def sub_sign_flag_def simp_rules numeral_2_eq_2[symmetric] Let'_def read_region'_def write_block'_def get'_def set'_def post regionset
(* ((simp add: assms pred_logic Ps Qs)+)? helps keep goals clean but causes issues when there are subcalls *)
method vcg_step uses assms =
((rule htriples)+, rule blocks)+,
(simp add: assms pred_logic Ps Qs)?,
(((auto simp: eq_def)[])+)?
text \<open>For @{const CASES}.\<close>
method vcg_step' uses assms =
(rule htriples)+,
simp,
((rule htriples)+, rule blocks)+,
(simp add: assms pred_logic Ps Qs)?,
(((auto simp: eq_def)[])+)?
text \<open>
Sometimes needs to be moved down (close to the abstract code) to avoid TERM exceptions,
haven't figured out the cause.
Also haven't settled on a proper setup for the ending methods,
there are troubles when nested loops and such are involved.
\<close>
method vcg_while for P :: state_pred uses assms =
((rule htriples)+)?,
rule HTriple_weaken[where P=P],
simp add: pred_logic Ps Qs assms,
rule HTriple_while,
(vcg_step assms: assms)+,
(simp add: pred_logic Ps Qs)+,
(
(vcg_step' assms: assms | vcg_step assms: assms)+,
((simp add: assms)+)?
)?
method vcg uses acode assms =
subst acode,
(vcg_step assms: assms)+
end
locale "is_even" = "example" +
fixes RAX\<^sub>0\<^sub>v RDI\<^sub>0\<^sub>v RSP\<^sub>0\<^sub>v RBP\<^sub>0\<^sub>v ret_address\<^sub>v :: \<open>64 word\<close>
begin
text \<open>Using definitions that don't get unfolded immediately prevents locale argument issues.\<close>
definition \<open>RAX\<^sub>0 \<equiv> RAX\<^sub>0\<^sub>v\<close>
definition \<open>RDI\<^sub>0 \<equiv> RDI\<^sub>0\<^sub>v\<close>
definition \<open>RSP\<^sub>0 \<equiv> RSP\<^sub>0\<^sub>v\<close>
definition \<open>RBP\<^sub>0 \<equiv> RBP\<^sub>0\<^sub>v\<close>
definition \<open>ret_address \<equiv> ret_address\<^sub>v\<close>
definition P_0x1135_0 :: state_pred where
\<open>P_0x1135_0 \<sigma> \<equiv> RIP \<sigma> = 0x1135 \<and> RAX \<sigma> = RAX\<^sub>0 \<and> RDI \<sigma> = RDI\<^sub>0 \<and> RSP \<sigma> = RSP\<^sub>0 \<and> RBP \<sigma> = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address\<close>
declare P_0x1135_0_def[Ps]
definition P_0x1135_0_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x1135_0_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8),
(1, ((RSP\<^sub>0::64 word) - 0x8), 8),
(2, ((RSP\<^sub>0::64 word) - 0xc), 4)
}\<close>
definition P_0x1135_0_regions :: state_pred where
\<open>P_0x1135_0_regions \<sigma> \<equiv> \<exists>regions. P_0x1135_0_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_ret_address_0 :: state_pred where
\<open>Q_ret_address_0 \<sigma> \<equiv> RIP \<sigma> = ret_address \<and> RAX \<sigma> = ucast ((if' ((((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)::32 word) AND 0x1)::32 word) = (ucast ((0x0::64 word))::32 word) then 0x1 else (0x0::8 word))) \<and> RDI \<sigma> = RDI\<^sub>0 \<and> RSP \<sigma> = ((RSP\<^sub>0::64 word) + 0x8) \<and> RBP \<sigma> = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0xc),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))\<close>
declare Q_ret_address_0_def[Qs]
schematic_goal is_even_0_9_0x1135_0x1148_0[blocks]:
assumes \<open>(P_0x1135_0 && P_0x1135_0_regions) \<sigma>\<close>
shows \<open>exec_block 9 0x1148 0 \<sigma> \<triangleq> ?\<sigma> \<and> Q_ret_address_0 ?\<sigma> \<and> block_usage P_0x1135_0_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x1135_0_def P_0x1135_0_regions_def post: Q_ret_address_0_def regionset: P_0x1135_0_regions_set_def)
definition is_even_acode :: ACode where
\<open>is_even_acode =
Block 9 0x1148 0
\<close>
schematic_goal "is_even":
\<open>{{?P}} is_even_acode {{?Q;?M}}\<close>
by (vcg acode: is_even_acode_def)
end
locale "main" = "example" +
fixes RAX\<^sub>0\<^sub>v RBX\<^sub>0\<^sub>v RCX\<^sub>0\<^sub>v RDX\<^sub>0\<^sub>v RDI\<^sub>0\<^sub>v RSI\<^sub>0\<^sub>v RSP\<^sub>0\<^sub>v RBP\<^sub>0\<^sub>v R11\<^sub>0\<^sub>v R10\<^sub>0\<^sub>v R9\<^sub>0\<^sub>v R8\<^sub>0\<^sub>v FS\<^sub>0\<^sub>v ret_address\<^sub>v :: \<open>64 word\<close>
begin
text \<open>Using definitions that don't get unfolded immediately prevents locale argument issues.\<close>
definition \<open>RAX\<^sub>0 \<equiv> RAX\<^sub>0\<^sub>v\<close>
definition \<open>RBX\<^sub>0 \<equiv> RBX\<^sub>0\<^sub>v\<close>
definition \<open>RCX\<^sub>0 \<equiv> RCX\<^sub>0\<^sub>v\<close>
definition \<open>RDX\<^sub>0 \<equiv> RDX\<^sub>0\<^sub>v\<close>
definition \<open>RDI\<^sub>0 \<equiv> RDI\<^sub>0\<^sub>v\<close>
definition \<open>RSI\<^sub>0 \<equiv> RSI\<^sub>0\<^sub>v\<close>
definition \<open>RSP\<^sub>0 \<equiv> RSP\<^sub>0\<^sub>v\<close>
definition \<open>RBP\<^sub>0 \<equiv> RBP\<^sub>0\<^sub>v\<close>
definition \<open>R11\<^sub>0 \<equiv> R11\<^sub>0\<^sub>v\<close>
definition \<open>R10\<^sub>0 \<equiv> R10\<^sub>0\<^sub>v\<close>
definition \<open>R9\<^sub>0 \<equiv> R9\<^sub>0\<^sub>v\<close>
definition \<open>R8\<^sub>0 \<equiv> R8\<^sub>0\<^sub>v\<close>
definition \<open>FS\<^sub>0 \<equiv> FS\<^sub>0\<^sub>v\<close>
definition \<open>ret_address \<equiv> ret_address\<^sub>v\<close>
definition P_0x1149_0 :: state_pred where
\<open>P_0x1149_0 \<sigma> \<equiv> RIP \<sigma> = 0x1149 \<and> RAX \<sigma> = RAX\<^sub>0 \<and> RBX \<sigma> = RBX\<^sub>0 \<and> RCX \<sigma> = RCX\<^sub>0 \<and> RDX \<sigma> = RDX\<^sub>0 \<and> RDI \<sigma> = RDI\<^sub>0 \<and> RSI \<sigma> = RSI\<^sub>0 \<and> RSP \<sigma> = RSP\<^sub>0 \<and> RBP \<sigma> = RBP\<^sub>0 \<and> R11 \<sigma> = R11\<^sub>0 \<and> R10 \<sigma> = R10\<^sub>0 \<and> R9 \<sigma> = R9\<^sub>0 \<and> R8 \<sigma> = R8\<^sub>0 \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address\<close>
declare P_0x1149_0_def[Ps]
definition P_0x1149_0_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x1149_0_regions_set \<sigma> \<equiv> {
(0, RSI\<^sub>0, Suc 0),
(1, RSI\<^sub>0, 4),
(2, RSP\<^sub>0, 8),
(3, ((FS\<^sub>0::64 word) + 0x28), 8),
(4, ((RSI\<^sub>0::64 word) + 0x10), 4),
(5, ((RSI\<^sub>0::64 word) + 0x20), 4),
(6, ((RSP\<^sub>0::64 word) - 0x8), 8),
(7, ((RSP\<^sub>0::64 word) - 0x10), 8),
(8, ((RSP\<^sub>0::64 word) - 0x20), 8),
(9, ((RSP\<^sub>0::64 word) - 0x28), 8),
(10, ((RSP\<^sub>0::64 word) - 0x30), 8),
(11, ((RSP\<^sub>0::64 word) - 0x38), 8),
(12, ((RSP\<^sub>0::64 word) - 0x40), 8),
(13, ((RSP\<^sub>0::64 word) - 0x44), 4),
(14, ((RSP\<^sub>0::64 word) - 0x4c), 4),
(15, ((RSP\<^sub>0::64 word) - 0x58), 8)
}\<close>
definition P_0x1149_0_regions :: state_pred where
\<open>P_0x1149_0_regions \<sigma> \<equiv> \<exists>regions. P_0x1149_0_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {(0,1)}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {(0,1), (1,0)}))
\<close>
definition Q_0x123e_0 :: state_pred where
\<open>Q_0x123e_0 \<sigma> \<equiv> RIP \<sigma> = 0x123e \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = RDI\<^sub>0 \<and> RSI \<sigma> = 0x10 \<and> RSP \<sigma> = ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0\<close>
declare Q_0x123e_0_def[Qs]
schematic_goal main_0_53_0x1149_0x120b_0[blocks]:
assumes \<open>(P_0x1149_0 && P_0x1149_0_regions) \<sigma>\<close>
shows \<open>exec_block 53 0x120b 0 \<sigma> \<triangleq> ?\<sigma> \<and> Q_0x123e_0 ?\<sigma> \<and> block_usage P_0x1149_0_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x1149_0_def P_0x1149_0_regions_def post: Q_0x123e_0_def regionset: P_0x1149_0_regions_set_def)
definition P_0x123e_1 :: state_pred where
\<open>P_0x123e_1 \<sigma> \<equiv> RIP \<sigma> = 0x123e \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = RDI\<^sub>0 \<and> RSI \<sigma> = 0x10 \<and> RSP \<sigma> = ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0\<close>
declare P_0x123e_1_def[Ps]
definition P_0x123e_1_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x123e_1_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8),
(1, ((FS\<^sub>0::64 word) + 0x28), 8),
(2, ((RSI\<^sub>0::64 word) + 0x20), 4),
(3, ((RSP\<^sub>0::64 word) - 0x8), 8),
(4, ((RSP\<^sub>0::64 word) - 0x10), 8),
(5, ((RSP\<^sub>0::64 word) - 0x20), 8),
(6, ((RSP\<^sub>0::64 word) - 0x28), 8),
(7, ((RSP\<^sub>0::64 word) - 0x30), 8),
(8, ((RSP\<^sub>0::64 word) - 0x38), 8),
(9, ((RSP\<^sub>0::64 word) - 0x40), 8),
(10, ((RSP\<^sub>0::64 word) - 0x44), 4),
(11, ((RSP\<^sub>0::64 word) - 0x4c), 4),
(12, ((RSP\<^sub>0::64 word) - 0x58), 8)
}\<close>
definition P_0x123e_1_regions :: state_pred where
\<open>P_0x123e_1_regions \<sigma> \<equiv> \<exists>regions. P_0x123e_1_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_0x1244_1 :: state_pred where
\<open>Q_0x1244_1 \<sigma> \<equiv> RIP \<sigma> = 0x1244 \<and> RAX \<sigma> = ucast ((\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x44),4]::32 word)) \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = RDI\<^sub>0 \<and> RSI \<sigma> = 0x10 \<and> RSP \<sigma> = ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x44),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x44),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0\<close>
declare Q_0x1244_1_def[Qs]
schematic_goal main_0_2_0x123e_0x1241_1[blocks]:
assumes \<open>(P_0x123e_1 && P_0x123e_1_regions) \<sigma>\<close>
shows \<open>exec_block 2 0x1241 (Suc 0) \<sigma> \<triangleq> ?\<sigma> \<and> Q_0x1244_1 ?\<sigma> \<and> block_usage P_0x123e_1_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x123e_1_def P_0x123e_1_regions_def post: Q_0x1244_1_def regionset: P_0x123e_1_regions_set_def)
definition P_0x1244_true_2 :: state_pred where
\<open>P_0x1244_true_2 \<sigma> \<equiv> RIP \<sigma> = 0x1244 \<and> RAX \<sigma> = ucast ((\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x44),4]::32 word)) \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = RDI\<^sub>0 \<and> RSI \<sigma> = 0x10 \<and> RSP \<sigma> = ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x44),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x44),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0\<close>
declare P_0x1244_true_2_def[Ps]
definition P_0x1244_true_2_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x1244_true_2_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8),
(1, ((FS\<^sub>0::64 word) + 0x28), 8),
(2, ((RSI\<^sub>0::64 word) + 0x20), 4),
(3, ((RSI\<^sub>0::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x44),4]::32 word))) 32 64::64 word)::64 word)::64 word) * 0x8)::64 word)), 8),
(4, ((((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2)::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x44),4]::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word)), 4),
(5, ((RSP\<^sub>0::64 word) - 0x8), 8),
(6, ((RSP\<^sub>0::64 word) - 0x10), 8),
(7, ((RSP\<^sub>0::64 word) - 0x20), 8),
(8, ((RSP\<^sub>0::64 word) - 0x28), 8),
(9, ((RSP\<^sub>0::64 word) - 0x30), 8),
(10, ((RSP\<^sub>0::64 word) - 0x38), 8),
(11, ((RSP\<^sub>0::64 word) - 0x40), 8),
(12, ((RSP\<^sub>0::64 word) - 0x44), 4),
(13, ((RSP\<^sub>0::64 word) - 0x4c), 4),
(14, ((RSP\<^sub>0::64 word) - 0x58), 8),
(15, (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x44),4]::32 word))) 32 64::64 word)::64 word)::64 word) * 0x8)::64 word)),8]::64 word), Suc 0)
}\<close>
definition P_0x1244_true_2_regions :: state_pred where
\<open>P_0x1244_true_2_regions \<sigma> \<equiv> \<exists>regions. P_0x1244_true_2_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_0x123e_2 :: state_pred where
\<open>Q_0x123e_2 \<sigma> \<equiv> RIP \<sigma> = 0x123e \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = RDI\<^sub>0 \<and> RSI \<sigma> = 0x10 \<and> RSP \<sigma> = ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0\<close>
declare Q_0x123e_2_def[Qs]
schematic_goal main_0_15_0x1244_0x123a_2[blocks]:
assumes \<open>(P_0x1244_true_2 && P_0x1244_true_2_regions && jl) \<sigma>\<close>
shows \<open>exec_block 15 0x123a 2 \<sigma> \<triangleq> ?\<sigma> \<and> Q_0x123e_2 ?\<sigma> \<and> block_usage P_0x1244_true_2_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x1244_true_2_def P_0x1244_true_2_regions_def post: Q_0x123e_2_def regionset: P_0x1244_true_2_regions_set_def)
definition P_0x1244_false_3 :: state_pred where
\<open>P_0x1244_false_3 \<sigma> \<equiv> RIP \<sigma> = 0x1244 \<and> RAX \<sigma> = ucast ((\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x44),4]::32 word)) \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = RDI\<^sub>0 \<and> RSI \<sigma> = 0x10 \<and> RSP \<sigma> = ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x44),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x44),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0\<close>
declare P_0x1244_false_3_def[Ps]
definition P_0x1244_false_3_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x1244_false_3_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8),
(1, ((FS\<^sub>0::64 word) + 0x28), 8),
(2, ((RSI\<^sub>0::64 word) + 0x20), 4),
(3, ((RSP\<^sub>0::64 word) - 0x8), 8),
(4, ((RSP\<^sub>0::64 word) - 0x10), 8),
(5, ((RSP\<^sub>0::64 word) - 0x20), 8),
(6, ((RSP\<^sub>0::64 word) - 0x28), 8),
(7, ((RSP\<^sub>0::64 word) - 0x30), 8),
(8, ((RSP\<^sub>0::64 word) - 0x38), 8),
(9, ((RSP\<^sub>0::64 word) - 0x40), 8),
(10, ((RSP\<^sub>0::64 word) - 0x44), 4),
(11, ((RSP\<^sub>0::64 word) - 0x4c), 4),
(12, ((RSP\<^sub>0::64 word) - 0x58), 8)
}\<close>
definition P_0x1244_false_3_regions :: state_pred where
\<open>P_0x1244_false_3_regions \<sigma> \<equiv> \<exists>regions. P_0x1244_false_3_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_0x1246_3 :: state_pred where
\<open>Q_0x1246_3 \<sigma> \<equiv> RIP \<sigma> = 0x1246 \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = RDI\<^sub>0 \<and> RSI \<sigma> = 0x10 \<and> RSP \<sigma> = ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0\<close>
declare Q_0x1246_3_def[Qs]
schematic_goal main_0_1_0x1244_0x1244_3[blocks]:
assumes \<open>(P_0x1244_false_3 && P_0x1244_false_3_regions && ! jl) \<sigma>\<close>
shows \<open>exec_block (Suc 0) 0x1244 3 \<sigma> \<triangleq> ?\<sigma> \<and> Q_0x1246_3 ?\<sigma> \<and> block_usage P_0x1244_false_3_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x1244_false_3_def P_0x1244_false_3_regions_def post: Q_0x1246_3_def regionset: P_0x1244_false_3_regions_set_def)
definition P_0x1246_4 :: state_pred where
\<open>P_0x1246_4 \<sigma> \<equiv> RIP \<sigma> = 0x1246 \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = RDI\<^sub>0 \<and> RSI \<sigma> = 0x10 \<and> RSP \<sigma> = ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0\<close>
declare P_0x1246_4_def[Ps]
definition P_0x1246_4_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x1246_4_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8),
(1, ((FS\<^sub>0::64 word) + 0x28), 8),
(2, ((RSI\<^sub>0::64 word) + 0x20), 4),
(3, ((RSP\<^sub>0::64 word) - 0x8), 8),
(4, ((RSP\<^sub>0::64 word) - 0x10), 8),
(5, ((RSP\<^sub>0::64 word) - 0x20), 8),
(6, ((RSP\<^sub>0::64 word) - 0x28), 8),
(7, ((RSP\<^sub>0::64 word) - 0x30), 8),
(8, ((RSP\<^sub>0::64 word) - 0x38), 8),
(9, ((RSP\<^sub>0::64 word) - 0x40), 8),
(10, ((RSP\<^sub>0::64 word) - 0x4c), 4),
(11, ((RSP\<^sub>0::64 word) - 0x58), 8)
}\<close>
definition P_0x1246_4_regions :: state_pred where
\<open>P_0x1246_4_regions \<sigma> \<equiv> \<exists>regions. P_0x1246_4_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_0x124b_4 :: state_pred where
\<open>Q_0x124b_4 \<sigma> \<equiv> RIP \<sigma> = 0x124b \<and> RAX \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RSI \<sigma> = 0x10 \<and> RSP \<sigma> = ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0\<close>
declare Q_0x124b_4_def[Qs]
schematic_goal main_0_2_0x1246_0x1249_4[blocks]:
assumes \<open>(P_0x1246_4 && P_0x1246_4_regions) \<sigma>\<close>
shows \<open>exec_block 2 0x1249 4 \<sigma> \<triangleq> ?\<sigma> \<and> Q_0x124b_4 ?\<sigma> \<and> block_usage P_0x1246_4_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x1246_4_def P_0x1246_4_regions_def post: Q_0x124b_4_def regionset: P_0x1246_4_regions_set_def)
definition P_0x124b_5 :: state_pred where
\<open>P_0x124b_5 \<sigma> \<equiv> RIP \<sigma> = 0x124b \<and> RAX \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RSI \<sigma> = 0x10 \<and> RSP \<sigma> = ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0\<close>
declare P_0x124b_5_def[Ps]
definition P_0x124b_5_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x124b_5_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8),
(1, ((FS\<^sub>0::64 word) + 0x28), 8),
(2, ((RSI\<^sub>0::64 word) + 0x20), 4),
(3, ((RSP\<^sub>0::64 word) - 0x8), 8),
(4, ((RSP\<^sub>0::64 word) - 0x10), 8),
(5, ((RSP\<^sub>0::64 word) - 0x20), 8),
(6, ((RSP\<^sub>0::64 word) - 0x28), 8),
(7, ((RSP\<^sub>0::64 word) - 0x30), 8),
(8, ((RSP\<^sub>0::64 word) - 0x38), 8),
(9, ((RSP\<^sub>0::64 word) - 0x40), 8),
(10, ((RSP\<^sub>0::64 word) - 0x4c), 4),
(11, ((RSP\<^sub>0::64 word) - 0x58), 8),
(12, ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60), 8)
}\<close>
definition P_0x124b_5_regions :: state_pred where
\<open>P_0x124b_5_regions \<sigma> \<equiv> \<exists>regions. P_0x124b_5_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_0x1135_0x124b_5 :: state_pred where
\<open>Q_0x1135_0x124b_5 \<sigma> \<equiv> RSP \<sigma> = ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60) \<and> RIP \<sigma> = 0x1135 \<and> RAX \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RSI \<sigma> = 0x10 \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60),8]::64 word) = 0x1250\<close>
declare Q_0x1135_0x124b_5_def[Qs]
schematic_goal main_0_1_0x124b_0x124b_5[blocks]:
assumes \<open>(P_0x124b_5 && P_0x124b_5_regions) \<sigma>\<close>
shows \<open>exec_block (Suc 0) 0x124b 5 \<sigma> \<triangleq> ?\<sigma> \<and> Q_0x1135_0x124b_5 ?\<sigma> \<and> block_usage P_0x124b_5_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x124b_5_def P_0x124b_5_regions_def post: Q_0x1135_0x124b_5_def regionset: P_0x124b_5_regions_set_def)
definition P_0x1250_6 :: state_pred where
\<open>P_0x1250_6 \<sigma> \<equiv> RIP \<sigma> = 0x1250 \<and> RAX \<sigma> = ucast (is_even_0x124b_retval) \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RSI \<sigma> = 0x10 \<and> RSP \<sigma> = ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60),8]::64 word) = 0x1250\<close>
declare P_0x1250_6_def[Ps]
definition P_0x1250_6_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x1250_6_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8),
(1, ((FS\<^sub>0::64 word) + 0x28), 8),
(2, ((RSI\<^sub>0::64 word) + 0x20), 4),
(3, ((RSP\<^sub>0::64 word) - 0x8), 8),
(4, ((RSP\<^sub>0::64 word) - 0x10), 8),
(5, ((RSP\<^sub>0::64 word) - 0x20), 8),
(6, ((RSP\<^sub>0::64 word) - 0x28), 8),
(7, ((RSP\<^sub>0::64 word) - 0x30), 8),
(8, ((RSP\<^sub>0::64 word) - 0x38), 8),
(9, ((RSP\<^sub>0::64 word) - 0x40), 8),
(10, ((RSP\<^sub>0::64 word) - 0x4c), 4),
(11, ((RSP\<^sub>0::64 word) - 0x58), 8),
(12, ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60), 8)
}\<close>
definition P_0x1250_6_regions :: state_pred where
\<open>P_0x1250_6_regions \<sigma> \<equiv> \<exists>regions. P_0x1250_6_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_0x1252_6 :: state_pred where
\<open>Q_0x1252_6 \<sigma> \<equiv> RIP \<sigma> = 0x1252 \<and> RAX \<sigma> = ucast (is_even_0x124b_retval) \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RSI \<sigma> = 0x10 \<and> RSP \<sigma> = ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60),8]::64 word) = 0x1250\<close>
declare Q_0x1252_6_def[Qs]
schematic_goal main_0_1_0x1250_0x1250_6[blocks]:
assumes \<open>(P_0x1250_6 && P_0x1250_6_regions) \<sigma>\<close>
shows \<open>exec_block (Suc 0) 0x1250 6 \<sigma> \<triangleq> ?\<sigma> \<and> Q_0x1252_6 ?\<sigma> \<and> block_usage P_0x1250_6_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x1250_6_def P_0x1250_6_regions_def post: Q_0x1252_6_def regionset: P_0x1250_6_regions_set_def)
definition P_0x1252_true_7 :: state_pred where
\<open>P_0x1252_true_7 \<sigma> \<equiv> RIP \<sigma> = 0x1252 \<and> RAX \<sigma> = ucast (is_even_0x124b_retval) \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RSI \<sigma> = 0x10 \<and> RSP \<sigma> = ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60),8]::64 word) = 0x1250\<close>
declare P_0x1252_true_7_def[Ps]
definition P_0x1252_true_7_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x1252_true_7_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8),
(1, ((FS\<^sub>0::64 word) + 0x28), 8),
(2, ((RSI\<^sub>0::64 word) + 0x20), 4),
(3, ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2), 4),
(4, ((RSP\<^sub>0::64 word) - 0x8), 8),
(5, ((RSP\<^sub>0::64 word) - 0x10), 8),
(6, ((RSP\<^sub>0::64 word) - 0x20), 8),
(7, ((RSP\<^sub>0::64 word) - 0x28), 8),
(8, ((RSP\<^sub>0::64 word) - 0x30), 8),
(9, ((RSP\<^sub>0::64 word) - 0x38), 8),
(10, ((RSP\<^sub>0::64 word) - 0x40), 8),
(11, ((RSP\<^sub>0::64 word) - 0x4c), 4),
(12, ((RSP\<^sub>0::64 word) - 0x58), 8),
(13, ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60), 8)
}\<close>
definition P_0x1252_true_7_regions :: state_pred where
\<open>P_0x1252_true_7_regions \<sigma> \<equiv> \<exists>regions. P_0x1252_true_7_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_0x1269_7 :: state_pred where
\<open>Q_0x1269_7 \<sigma> \<equiv> RIP \<sigma> = 0x1269 \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RSI \<sigma> = 0x10 \<and> RSP \<sigma> = ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60),8]::64 word) = 0x1250\<close>
declare Q_0x1269_7_def[Qs]
schematic_goal main_0_3_0x1252_0x1267_7[blocks]:
assumes \<open>(P_0x1252_true_7 && P_0x1252_true_7_regions && ZF) \<sigma>\<close>
shows \<open>exec_block 3 0x1267 7 \<sigma> \<triangleq> ?\<sigma> \<and> Q_0x1269_7 ?\<sigma> \<and> block_usage P_0x1252_true_7_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x1252_true_7_def P_0x1252_true_7_regions_def post: Q_0x1269_7_def regionset: P_0x1252_true_7_regions_set_def)
definition P_0x1252_false_8 :: state_pred where
\<open>P_0x1252_false_8 \<sigma> \<equiv> RIP \<sigma> = 0x1252 \<and> RAX \<sigma> = ucast (is_even_0x124b_retval) \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RSI \<sigma> = 0x10 \<and> RSP \<sigma> = ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60),8]::64 word) = 0x1250\<close>
declare P_0x1252_false_8_def[Ps]
definition P_0x1252_false_8_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x1252_false_8_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8),
(1, ((FS\<^sub>0::64 word) + 0x28), 8),
(2, ((RSI\<^sub>0::64 word) + 0x20), 4),
(3, ((((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2)::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word)), 4),
(4, ((RSP\<^sub>0::64 word) - 0x8), 8),
(5, ((RSP\<^sub>0::64 word) - 0x10), 8),
(6, ((RSP\<^sub>0::64 word) - 0x20), 8),
(7, ((RSP\<^sub>0::64 word) - 0x28), 8),
(8, ((RSP\<^sub>0::64 word) - 0x30), 8),
(9, ((RSP\<^sub>0::64 word) - 0x38), 8),
(10, ((RSP\<^sub>0::64 word) - 0x40), 8),
(11, ((RSP\<^sub>0::64 word) - 0x4c), 4),
(12, ((RSP\<^sub>0::64 word) - 0x58), 8),
(13, ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60), 8)
}\<close>
definition P_0x1252_false_8_regions :: state_pred where
\<open>P_0x1252_false_8_regions \<sigma> \<equiv> \<exists>regions. P_0x1252_false_8_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_0x1269_8 :: state_pred where
\<open>Q_0x1269_8 \<sigma> \<equiv> RIP \<sigma> = 0x1269 \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RSI \<sigma> = 0x10 \<and> RSP \<sigma> = ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60),8]::64 word) = 0x1250\<close>
declare Q_0x1269_8_def[Qs]
schematic_goal main_0_6_0x1252_0x1261_8[blocks]:
assumes \<open>(P_0x1252_false_8 && P_0x1252_false_8_regions && ! ZF) \<sigma>\<close>
shows \<open>exec_block 6 0x1261 8 \<sigma> \<triangleq> ?\<sigma> \<and> Q_0x1269_8 ?\<sigma> \<and> block_usage P_0x1252_false_8_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x1252_false_8_def P_0x1252_false_8_regions_def post: Q_0x1269_8_def regionset: P_0x1252_false_8_regions_set_def)
definition P_0x1269_9 :: state_pred where
\<open>P_0x1269_9 \<sigma> \<equiv> RIP \<sigma> = 0x1269 \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RSI \<sigma> = 0x10 \<and> RSP \<sigma> = ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60),8]::64 word) = 0x1250\<close>
declare P_0x1269_9_def[Ps]
definition P_0x1269_9_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x1269_9_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8),
(1, ((FS\<^sub>0::64 word) + 0x28), 8),
(2, ((RSI\<^sub>0::64 word) + 0x20), 4),
(3, ((RSP\<^sub>0::64 word) - 0x8), 8),
(4, ((RSP\<^sub>0::64 word) - 0x10), 8),
(5, ((RSP\<^sub>0::64 word) - 0x20), 8),
(6, ((RSP\<^sub>0::64 word) - 0x28), 8),
(7, ((RSP\<^sub>0::64 word) - 0x30), 8),
(8, ((RSP\<^sub>0::64 word) - 0x38), 8),
(9, ((RSP\<^sub>0::64 word) - 0x40), 8),
(10, ((RSP\<^sub>0::64 word) - 0x4c), 4),
(11, ((RSP\<^sub>0::64 word) - 0x58), 8),
(12, ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60), 8)
}\<close>
definition P_0x1269_9_regions :: state_pred where
\<open>P_0x1269_9_regions \<sigma> \<equiv> \<exists>regions. P_0x1269_9_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_0x1279_9 :: state_pred where
\<open>Q_0x1279_9 \<sigma> \<equiv> RIP \<sigma> = 0x1279 \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RSI \<sigma> = 0x0 \<and> RSP \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60),8]::64 word) = 0x1250\<close>
declare Q_0x1279_9_def[Qs]
schematic_goal main_0_3_0x1269_0x1270_9[blocks]:
assumes \<open>(P_0x1269_9 && P_0x1269_9_regions) \<sigma>\<close>
shows \<open>exec_block 3 0x1270 9 \<sigma> \<triangleq> ?\<sigma> \<and> Q_0x1279_9 ?\<sigma> \<and> block_usage P_0x1269_9_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x1269_9_def P_0x1269_9_regions_def post: Q_0x1279_9_def regionset: P_0x1269_9_regions_set_def)
definition P_0x1279_true_10 :: state_pred where
\<open>P_0x1279_true_10 \<sigma> \<equiv> RIP \<sigma> = 0x1279 \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RSI \<sigma> = 0x0 \<and> RSP \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60),8]::64 word) = 0x1250\<close>
declare P_0x1279_true_10_def[Ps]
definition P_0x1279_true_10_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x1279_true_10_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8),
(1, ((FS\<^sub>0::64 word) + 0x28), 8),
(2, ((RSI\<^sub>0::64 word) + 0x20), 4),
(3, ((RSP\<^sub>0::64 word) - 0x8), 8),
(4, ((RSP\<^sub>0::64 word) - 0x10), 8),
(5, ((RSP\<^sub>0::64 word) - 0x20), 8),
(6, ((RSP\<^sub>0::64 word) - 0x28), 8),
(7, ((RSP\<^sub>0::64 word) - 0x30), 8),
(8, ((RSP\<^sub>0::64 word) - 0x38), 8),
(9, ((RSP\<^sub>0::64 word) - 0x40), 8),
(10, ((RSP\<^sub>0::64 word) - 0x4c), 4),
(11, ((RSP\<^sub>0::64 word) - 0x58), 8),
(12, ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60), 8)
}\<close>
definition P_0x1279_true_10_regions :: state_pred where
\<open>P_0x1279_true_10_regions \<sigma> \<equiv> \<exists>regions. P_0x1279_true_10_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_ret_address_10 :: state_pred where
\<open>Q_ret_address_10 \<sigma> \<equiv> RIP \<sigma> = ret_address \<and> RDI \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RSI \<sigma> = 0x0 \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60),8]::64 word) = 0x1250\<close>
declare Q_ret_address_10_def[Qs]
schematic_goal main_0_4_0x1279_0x1285_10[blocks]:
assumes \<open>(P_0x1279_true_10 && P_0x1279_true_10_regions && ZF) \<sigma>\<close>
shows \<open>exec_block 4 0x1285 10 \<sigma> \<triangleq> ?\<sigma> \<and> Q_ret_address_10 ?\<sigma> \<and> block_usage P_0x1279_true_10_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x1279_true_10_def P_0x1279_true_10_regions_def post: Q_ret_address_10_def regionset: P_0x1279_true_10_regions_set_def)
definition P_0x1279_false_11 :: state_pred where
\<open>P_0x1279_false_11 \<sigma> \<equiv> RIP \<sigma> = 0x1279 \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RSI \<sigma> = 0x0 \<and> RSP \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60),8]::64 word) = 0x1250\<close>
declare P_0x1279_false_11_def[Ps]
definition P_0x1279_false_11_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x1279_false_11_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8),
(1, ((FS\<^sub>0::64 word) + 0x28), 8),
(2, ((RSI\<^sub>0::64 word) + 0x20), 4),
(3, ((RSP\<^sub>0::64 word) - 0x8), 8),
(4, ((RSP\<^sub>0::64 word) - 0x10), 8),
(5, ((RSP\<^sub>0::64 word) - 0x20), 8),
(6, ((RSP\<^sub>0::64 word) - 0x28), 8),
(7, ((RSP\<^sub>0::64 word) - 0x30), 8),
(8, ((RSP\<^sub>0::64 word) - 0x38), 8),
(9, ((RSP\<^sub>0::64 word) - 0x40), 8),
(10, ((RSP\<^sub>0::64 word) - 0x4c), 4),
(11, ((RSP\<^sub>0::64 word) - 0x58), 8),
(12, ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60), 8)
}\<close>
definition P_0x1279_false_11_regions :: state_pred where
\<open>P_0x1279_false_11_regions \<sigma> \<equiv> \<exists>regions. P_0x1279_false_11_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_0x127b_11 :: state_pred where
\<open>Q_0x127b_11 \<sigma> \<equiv> RIP \<sigma> = 0x127b \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RSI \<sigma> = 0x0 \<and> RSP \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60),8]::64 word) = 0x1250\<close>
declare Q_0x127b_11_def[Qs]
schematic_goal main_0_1_0x1279_0x1279_11[blocks]:
assumes \<open>(P_0x1279_false_11 && P_0x1279_false_11_regions && ! ZF) \<sigma>\<close>
shows \<open>exec_block (Suc 0) 0x1279 11 \<sigma> \<triangleq> ?\<sigma> \<and> Q_0x127b_11 ?\<sigma> \<and> block_usage P_0x1279_false_11_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x1279_false_11_def P_0x1279_false_11_regions_def post: Q_0x127b_11_def regionset: P_0x1279_false_11_regions_set_def)
definition P_0x127b_12 :: state_pred where
\<open>P_0x127b_12 \<sigma> \<equiv> RIP \<sigma> = 0x127b \<and> RBX \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RDI \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RSI \<sigma> = 0x0 \<and> RSP \<sigma> = ((RSP\<^sub>0::64 word) - 0x58) \<and> RBP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60),8]::64 word) = 0x1250\<close>
declare P_0x127b_12_def[Ps]
definition P_0x127b_12_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x127b_12_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8),
(1, ((FS\<^sub>0::64 word) + 0x28), 8),
(2, ((RSI\<^sub>0::64 word) + 0x20), 4),
(3, ((RSP\<^sub>0::64 word) - 0x8), 8),
(4, ((RSP\<^sub>0::64 word) - 0x10), 8),
(5, ((RSP\<^sub>0::64 word) - 0x20), 8),
(6, ((RSP\<^sub>0::64 word) - 0x28), 8),
(7, ((RSP\<^sub>0::64 word) - 0x30), 8),
(8, ((RSP\<^sub>0::64 word) - 0x38), 8),
(9, ((RSP\<^sub>0::64 word) - 0x40), 8),
(10, ((RSP\<^sub>0::64 word) - 0x4c), 4),
(11, ((RSP\<^sub>0::64 word) - 0x58), 8),
(12, ((RSP\<^sub>0::64 word) - 0x60), 8),
(13, ((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60), 8)
}\<close>
definition P_0x127b_12_regions :: state_pred where
\<open>P_0x127b_12_regions \<sigma> \<equiv> \<exists>regions. P_0x127b_12_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_stack_chk_fail_addr_0x127b_12 :: state_pred where
\<open>Q_stack_chk_fail_addr_0x127b_12 \<sigma> \<equiv> RSP \<sigma> = ((RSP\<^sub>0::64 word) - 0x60) \<and> RIP \<sigma> = stack_chk_fail_addr \<and> RDI \<sigma> = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> RSI \<sigma> = 0x0 \<and> R11 \<sigma> = 0x0 \<and> R10 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> R9 \<sigma> = 0x0 \<and> R8 \<sigma> = (sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word) \<and> FS \<sigma> = FS\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word) = ucast ((\<sigma> \<turnstile> *[((RSI\<^sub>0::64 word) + 0x20),4]::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = RBP\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = RBX\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x20),8]::64 word) = (\<sigma> \<turnstile> *[((FS\<^sub>0::64 word) + 0x28),8]::64 word) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x28),8]::64 word) = ((ucast ((((ucast ((((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x55)::64 word))::64 word) >> 2)::64 word))::64 word) << 2) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x30),8]::64 word) = (((sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word) - 0x1) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x38),8]::64 word) = ((RSI\<^sub>0::64 word) + 0x20) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x40),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x4c),4]::32 word) = ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word)) \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x58),8]::64 word) = RSI\<^sub>0 \<and> (\<sigma> \<turnstile> *[((((RSP\<^sub>0::64 word) - (\<langle>63,0\<rangle>(((ucast ((((0xf::64 word) + (\<langle>63,0\<rangle>(((\<langle>63,0\<rangle>(sextend (ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))) 32 64::64 word)::64 word)::64 word) * 0x4)::64 word))::64 word))::128 word) udiv (ucast ((0x10::32 word))::64 word)::64 word) * 0x10)::64 word))::64 word) - 0x60),8]::64 word) = 0x1250\<close>
declare Q_stack_chk_fail_addr_0x127b_12_def[Qs]
schematic_goal main_0_1_0x127b_0x127b_12[blocks]:
assumes \<open>(P_0x127b_12 && P_0x127b_12_regions) \<sigma>\<close>
shows \<open>exec_block (Suc 0) 0x127b 12 \<sigma> \<triangleq> ?\<sigma> \<and> Q_stack_chk_fail_addr_0x127b_12 ?\<sigma> \<and> block_usage P_0x127b_12_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x127b_12_def P_0x127b_12_regions_def post: Q_stack_chk_fail_addr_0x127b_12_def regionset: P_0x127b_12_regions_set_def)
text \<open>Manually fixed\<close>
interpretation is_even_0x124b_5: is_even _ _ _ _ _ _ _ _ _ _ _ _ _ _ \<open>ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))\<close> \<open>((RSP\<^sub>0::64 word) - 0x58)\<close> \<open>ucast ((\<langle>31,0\<rangle>RDI\<^sub>0::32 word))\<close> \<open>0x10\<close> \<open>0x124b\<close>
by unfold_locales
definition main_acode :: ACode where
\<open>main_acode =
Block 53 0x120b 0;
WHILE P_0x123e_1 DO
Block 2 0x1241 (Suc 0);
IF jl THEN
Block 15 0x123a 2
ELSE
Block (Suc 0) 0x1244 3
FI
OD;
Block 2 0x1249 4;
Block (Suc 0) 0x124b 5;
CALL is_even_0x124b_5.is_even_acode;
Block (Suc 0) 0x1250 6;
IF ZF THEN
Block 3 0x1267 7
ELSE
Block 6 0x1261 8
FI;
Block 3 0x1270 9;
IF ZF THEN
Block 4 0x1285 10
ELSE
Block (Suc 0) 0x1279 11;
Block (Suc 0) 0x127b 12;
CALL stack_chk_fail_acode
FI
\<close>
schematic_goal "main":
assumes
\<open>\<forall>\<sigma>. RIP \<sigma> = 0x123e \<longrightarrow> P_0x123e_1_regions \<sigma>\<close>
and \<open>\<forall>\<sigma>. RIP \<sigma> = 0x1244 \<longrightarrow> P_0x1244_true_2_regions \<sigma>\<close>
and \<open>\<forall>\<sigma>. RIP \<sigma> = 0x1244 \<longrightarrow> P_0x1244_false_3_regions \<sigma>\<close>
and \<open>\<forall>\<sigma>. RIP \<sigma> = 0x1246 \<longrightarrow> P_0x1246_4_regions \<sigma>\<close>
and \<open>\<forall>\<sigma>. RIP \<sigma> = 0x124b \<longrightarrow> P_0x124b_5_regions \<sigma>\<close>
and \<open>\<forall>\<sigma>. RIP \<sigma> = 0x1250 \<longrightarrow> P_0x1250_6_regions \<sigma>\<close>
and \<open>\<forall>\<sigma>. RIP \<sigma> = 0x1252 \<longrightarrow> P_0x1252_true_7_regions \<sigma>\<close>
and \<open>\<forall>\<sigma>. RIP \<sigma> = 0x1252 \<longrightarrow> P_0x1252_false_8_regions \<sigma>\<close>
and \<open>\<forall>\<sigma>. RIP \<sigma> = 0x1269 \<longrightarrow> P_0x1269_9_regions \<sigma>\<close>
and \<open>\<forall>\<sigma>. RIP \<sigma> = 0x1279 \<longrightarrow> P_0x1279_true_10_regions \<sigma>\<close>
and \<open>\<forall>\<sigma>. RIP \<sigma> = 0x1279 \<longrightarrow> P_0x1279_false_11_regions \<sigma>\<close>
and \<open>\<forall>\<sigma>. RIP \<sigma> = 0x127b \<longrightarrow> P_0x127b_12_regions \<sigma>\<close>
and \<open>\<forall>\<sigma>. RIP \<sigma> = 0x1135 \<longrightarrow> is_even_0x124b_5.P_0x1135_0_regions \<sigma>\<close> \<comment> \<open>Manually fixed\<close>
and [blocks]: \<open>{{Q_0x1135_0x124b_5}} \<box>is_even_0x124b_5.is_even_acode {{P_0x1250_6;M_0x124b}}\<close>
and [blocks]: \<open>{{Q_stack_chk_fail_addr_0x127b_12}} \<box>stack_chk_fail_acode {{Q_fail;M_0x127b}}\<close>
shows \<open>{{?P}} main_acode {{?Q;?M}}\<close>
apply (vcg acode: main_acode_def assms: assms)
apply (vcg_while \<open>P_0x123e_1 || P_0x1246_4\<close> assms: assms) \<comment> \<open>Done manually\<close>
apply (vcg_step assms: assms)+
done
end
end
|
{-# OPTIONS --without-K --safe #-}
module Algebra.Linear.Structures.Bundles.FiniteDimensional where
open import Algebra
open import Algebra.FunctionProperties
open import Relation.Binary using (Rel)
open import Level using (Level; suc; _⊔_)
open import Algebra.Structures.Bundles.Field
open import Algebra.Linear.Structures.Bundles
open import Algebra.Linear.Structures.VectorSpace
open import Algebra.Linear.Structures.FiniteDimensional
open import Data.Nat using (ℕ)
record FiniteDimensional {k ℓᵏ} (K : Field k ℓᵏ) (c ℓ : Level) (n : ℕ) : Set (suc (c ⊔ k ⊔ ℓ ⊔ ℓᵏ)) where
field
Carrier : Set c
_≈_ : Rel Carrier ℓ
_+_ : Carrier -> Carrier -> Carrier
_∙_ : Field.Carrier K -> Carrier -> Carrier
-_ : Carrier -> Carrier
0# : Carrier
isFiniteDimensional : IsFiniteDimensional K _≈_ _+_ _∙_ -_ 0# n
open IsFiniteDimensional isFiniteDimensional public
vectorSpace : VectorSpace K c ℓ
vectorSpace = record { isVectorSpace = isVectorSpace }
|
= There 's Got to Be a Way =
|
(* Title: HOL/Auth/Guard/Guard_Shared.thy
Author: Frederic Blanqui, University of Cambridge Computer Laboratory
Copyright 2002 University of Cambridge
*)
section\<open>lemmas on guarded messages for protocols with symmetric keys\<close>
theory Guard_Shared imports Guard GuardK "../Shared" begin
subsection\<open>Extensions to Theory \<open>Shared\<close>\<close>
declare initState.simps [simp del]
subsubsection\<open>a little abbreviation\<close>
abbreviation
Ciph :: "agent => msg => msg" where
"Ciph A X == Crypt (shrK A) X"
subsubsection\<open>agent associated to a key\<close>
definition agt :: "key => agent" where
"agt K == SOME A. K = shrK A"
lemma agt_shrK [simp]: "agt (shrK A) = A"
by (simp add: agt_def)
subsubsection\<open>basic facts about \<^term>\<open>initState\<close>\<close>
lemma no_Crypt_in_parts_init [simp]: "Crypt K X \<notin> parts (initState A)"
by (cases A, auto simp: initState.simps)
lemma no_Crypt_in_analz_init [simp]: "Crypt K X \<notin> analz (initState A)"
by auto
lemma no_shrK_in_analz_init [simp]: "A \<notin> bad
\<Longrightarrow> Key (shrK A) \<notin> analz (initState Spy)"
by (auto simp: initState.simps)
lemma shrK_notin_initState_Friend [simp]: "A \<noteq> Friend C
\<Longrightarrow> Key (shrK A) \<notin> parts (initState (Friend C))"
by (auto simp: initState.simps)
lemma keyset_init [iff]: "keyset (initState A)"
by (cases A, auto simp: keyset_def initState.simps)
subsubsection\<open>sets of symmetric keys\<close>
definition shrK_set :: "key set => bool" where
"shrK_set Ks \<equiv> \<forall>K. K \<in> Ks \<longrightarrow> (\<exists>A. K = shrK A)"
lemma in_shrK_set: "\<lbrakk>shrK_set Ks; K \<in> Ks\<rbrakk> \<Longrightarrow> \<exists>A. K = shrK A"
by (simp add: shrK_set_def)
lemma shrK_set1 [iff]: "shrK_set {shrK A}"
by (simp add: shrK_set_def)
lemma shrK_set2 [iff]: "shrK_set {shrK A, shrK B}"
by (simp add: shrK_set_def)
subsubsection\<open>sets of good keys\<close>
definition good :: "key set \<Rightarrow> bool" where
"good Ks \<equiv> \<forall>K. K \<in> Ks \<longrightarrow> agt K \<notin> bad"
lemma in_good: "\<lbrakk>good Ks; K \<in> Ks\<rbrakk> \<Longrightarrow> agt K \<notin> bad"
by (simp add: good_def)
lemma good1 [simp]: "A \<notin> bad \<Longrightarrow> good {shrK A}"
by (simp add: good_def)
lemma good2 [simp]: "\<lbrakk>A \<notin> bad; B \<notin> bad\<rbrakk> \<Longrightarrow> good {shrK A, shrK B}"
by (simp add: good_def)
subsection\<open>Proofs About Guarded Messages\<close>
subsubsection\<open>small hack\<close>
lemma shrK_is_invKey_shrK: "shrK A = invKey (shrK A)"
by simp
lemmas shrK_is_invKey_shrK_substI = shrK_is_invKey_shrK [THEN ssubst]
lemmas invKey_invKey_substI = invKey [THEN ssubst]
lemma "Nonce n \<in> parts {X} \<Longrightarrow> Crypt (shrK A) X \<in> guard n {shrK A}"
apply (rule shrK_is_invKey_shrK_substI, rule invKey_invKey_substI)
by (rule Guard_Nonce, simp+)
subsubsection\<open>guardedness results on nonces\<close>
lemma guard_ciph [simp]: "shrK A \<in> Ks \<Longrightarrow> Ciph A X \<in> guard n Ks"
by (rule Guard_Nonce, simp)
lemma guardK_ciph [simp]: "shrK A \<in> Ks \<Longrightarrow> Ciph A X \<in> guardK n Ks"
by (rule Guard_Key, simp)
lemma Guard_init [iff]: "Guard n Ks (initState B)"
by (induct B, auto simp: Guard_def initState.simps)
lemma Guard_knows_max': "Guard n Ks (knows_max' C evs)
\<Longrightarrow> Guard n Ks (knows_max C evs)"
by (simp add: knows_max_def)
lemma Nonce_not_used_Guard_spies [dest]: "Nonce n \<notin> used evs
\<Longrightarrow> Guard n Ks (spies evs)"
by (auto simp: Guard_def dest: not_used_not_known parts_sub)
lemma Nonce_not_used_Guard [dest]: "\<lbrakk>evs \<in> p; Nonce n \<notin> used evs;
Gets_correct p; one_step p\<rbrakk> \<Longrightarrow> Guard n Ks (knows (Friend C) evs)"
by (auto simp: Guard_def dest: known_used parts_trans)
lemma Nonce_not_used_Guard_max [dest]: "\<lbrakk>evs \<in> p; Nonce n \<notin> used evs;
Gets_correct p; one_step p\<rbrakk> \<Longrightarrow> Guard n Ks (knows_max (Friend C) evs)"
by (auto simp: Guard_def dest: known_max_used parts_trans)
lemma Nonce_not_used_Guard_max' [dest]: "\<lbrakk>evs \<in> p; Nonce n \<notin> used evs;
Gets_correct p; one_step p\<rbrakk> \<Longrightarrow> Guard n Ks (knows_max' (Friend C) evs)"
apply (rule_tac H="knows_max (Friend C) evs" in Guard_mono)
by (auto simp: knows_max_def)
subsubsection\<open>guardedness results on keys\<close>
lemma GuardK_init [simp]: "n \<notin> range shrK \<Longrightarrow> GuardK n Ks (initState B)"
by (induct B, auto simp: GuardK_def initState.simps)
lemma GuardK_knows_max': "\<lbrakk>GuardK n A (knows_max' C evs); n \<notin> range shrK\<rbrakk>
\<Longrightarrow> GuardK n A (knows_max C evs)"
by (simp add: knows_max_def)
lemma Key_not_used_GuardK_spies [dest]: "Key n \<notin> used evs
\<Longrightarrow> GuardK n A (spies evs)"
by (auto simp: GuardK_def dest: not_used_not_known parts_sub)
lemma Key_not_used_GuardK [dest]: "\<lbrakk>evs \<in> p; Key n \<notin> used evs;
Gets_correct p; one_step p\<rbrakk> \<Longrightarrow> GuardK n A (knows (Friend C) evs)"
by (auto simp: GuardK_def dest: known_used parts_trans)
lemma Key_not_used_GuardK_max [dest]: "\<lbrakk>evs \<in> p; Key n \<notin> used evs;
Gets_correct p; one_step p\<rbrakk> \<Longrightarrow> GuardK n A (knows_max (Friend C) evs)"
by (auto simp: GuardK_def dest: known_max_used parts_trans)
lemma Key_not_used_GuardK_max' [dest]: "\<lbrakk>evs \<in> p; Key n \<notin> used evs;
Gets_correct p; one_step p\<rbrakk> \<Longrightarrow> GuardK n A (knows_max' (Friend C) evs)"
apply (rule_tac H="knows_max (Friend C) evs" in GuardK_mono)
by (auto simp: knows_max_def)
subsubsection\<open>regular protocols\<close>
definition regular :: "event list set => bool" where
"regular p \<equiv> \<forall>evs A. evs \<in> p \<longrightarrow> (Key (shrK A) \<in> parts (spies evs)) = (A \<in> bad)"
lemma shrK_parts_iff_bad [simp]: "\<lbrakk>evs \<in> p; regular p\<rbrakk> \<Longrightarrow>
(Key (shrK A) \<in> parts (spies evs)) = (A \<in> bad)"
by (auto simp: regular_def)
lemma shrK_analz_iff_bad [simp]: "\<lbrakk>evs \<in> p; regular p\<rbrakk> \<Longrightarrow>
(Key (shrK A) \<in> analz (spies evs)) = (A \<in> bad)"
by auto
lemma Guard_Nonce_analz: "\<lbrakk>Guard n Ks (spies evs); evs \<in> p;
shrK_set Ks; good Ks; regular p\<rbrakk> \<Longrightarrow> Nonce n \<notin> analz (spies evs)"
apply (clarify, simp only: knows_decomp)
apply (drule Guard_invKey_keyset, simp+, safe)
apply (drule in_good, simp)
apply (drule in_shrK_set, simp+, clarify)
apply (frule_tac A=A in shrK_analz_iff_bad)
by (simp add: knows_decomp)+
lemma GuardK_Key_analz:
assumes "GuardK n Ks (spies evs)" "evs \<in> p" "shrK_set Ks"
"good Ks" "regular p" "n \<notin> range shrK"
shows "Key n \<notin> analz (spies evs)"
proof (rule ccontr)
assume "\<not> Key n \<notin> analz (knows Spy evs)"
then have *: "Key n \<in> analz (spies' evs \<union> initState Spy)"
by (simp add: knows_decomp)
from \<open>GuardK n Ks (spies evs)\<close>
have "GuardK n Ks (spies' evs \<union> initState Spy)"
by (simp add: knows_decomp)
then have "GuardK n Ks (spies' evs)"
and "finite (spies' evs)" "keyset (initState Spy)"
by simp_all
moreover have "Key n \<notin> initState Spy"
using \<open>n \<notin> range shrK\<close> by (simp add: image_iff initState_Spy)
ultimately obtain K
where "K \<in> Ks" and **: "Key K \<in> analz (spies' evs \<union> initState Spy)"
using * by (auto dest: GuardK_invKey_keyset)
from \<open>K \<in> Ks\<close> and \<open>good Ks\<close> have "agt K \<notin> bad"
by (auto dest: in_good)
from \<open>K \<in> Ks\<close> \<open>shrK_set Ks\<close> obtain A
where "K = shrK A"
by (auto dest: in_shrK_set)
then have "agt K \<in> bad"
using ** \<open>evs \<in> p\<close> \<open>regular p\<close> shrK_analz_iff_bad [of evs p "agt K"]
by (simp add: knows_decomp)
with \<open>agt K \<notin> bad\<close> show False by simp
qed
end
|
# Introduction to Mathematical Optimization Modeling
## Objective and prerequisites
The goal of this modeling example is to introduce the key components in the formulation of mixed integer programming (MIP) problems. For each component of a MIP problem formulation, we provide a description, the associated Python code, and the mathematical notation describing the component.
To fully understand the content of this notebook, the reader should:
* Be familiar with Python.
* Have a background in any branch of engineering, computer science, economics, statistics, any branch of the “hard” sciences, or any discipline that uses quantitative models and methods.
The reader should also consult the [documentation](https://www.gurobi.com/resources/?category-filter=documentation)
of the Gurobi Python API.
This notebook is explained in detail in our series of tutorial videos on mixed integer linear programming.
You can watch these videos by clicking
[here](https://www.gurobi.com/resource/tutorial-mixed-integer-linear-programming/)
**Note:** You can download the repository containing this and other examples by clicking [here](https://github.com/Gurobi/modeling-examples/archive/master.zip). In order to run this Jupyter Notebook properly, you must have a Gurobi license. If you do not have one, you can request an [evaluation license](https://www.gurobi.com/downloads/request-an-evaluation-license/?utm_source=Github&utm_medium=website_JupyterME&utm_campaign=CommercialDataScience) as a *commercial user*, or download a [free license](https://www.gurobi.com/academia/academic-program-and-licenses/?utm_source=Github&utm_medium=website_JupyterME&utm_campaign=AcademicDataScience) as an *academic user*.
## Problem description
Consider a consulting company that has three open positions: Tester, Java Developer, and Architect. The three top candidates (resources) for the positions are: Carlos, Joe, and Monika. The consulting company administered competency tests to each candidate in order to assess their ability to perform each of the jobs. The results of these tests are called *matching scores*. Assume that only one candidate can be assigned to a job, and at most one job can be assigned to a candidate.
The problem is to determine an assignment of resources and jobs such that each job is fulfilled, each resource is assigned to at most one job, and the total matching scores of the assignments is maximized.
## Mathematical optimization
Mathematical optimization (which is also known as mathematical programming) is a declarative approach where the modeler formulates an optimization problem that captures the key features of a complex decision problem. The Gurobi Optimizer solves the mathematical optimization problem using state-of-the-art mathematics and computer science.
A mathematical optimization model has five components:
* Sets
* Parameters
* Decision variables
* Constraints
* Objective function(s)
The following Python code imports the Gurobi callable library and imports the ``GRB`` class into the main namespace.
```python
import gurobipy as gp
from gurobipy import GRB
```
## Resource Assignment Problem
### Data
The list $R$ contains the names of the three resources: Carlos, Joe, and Monika.
The list $J$ contains the names of the job positions: Tester, Java Developer, and Architect.
$r \in R$: index and set of resources. The resource $r$ belongs to the set of resources $R$.
$j \in J$: index and set of jobs. The job $j$ belongs to the set of jobs $J$.
```python
# Resource and job sets
R = ['Carlos', 'Joe', 'Monika']
J = ['Tester', 'JavaDeveloper', 'Architect']
```
The ability of each resource to perform each of the jobs is listed in the following matching scores table:
For each resource $r$ and job $j$, there is a corresponding matching score $s$. The matching score $s$ can only take values between 0 and 100. That is, $s_{r,j} \in [0, 100]$ for all resources $r \in R$ and jobs $j \in J$.
We use the Gurobi Python ``multidict`` function to initialize one or more dictionaries with a single statement. The function takes a dictionary as its argument. The keys represent the possible combinations of resources and jobs.
```python
# Matching score data
combinations, scores = gp.multidict({
('Carlos', 'Tester'): 53,
('Carlos', 'JavaDeveloper'): 27,
('Carlos', 'Architect'): 13,
('Joe', 'Tester'): 80,
('Joe', 'JavaDeveloper'): 47,
('Joe', 'Architect'): 67,
('Monika', 'Tester'): 53,
('Monika', 'JavaDeveloper'): 73,
('Monika', 'Architect'): 47
})
```
The following constructor creates an empty ``Model`` object “m”. We specify the model name by passing the string "RAP" as an argument. The ``Model`` object “m” holds a single optimization problem. It consists of a set of variables, a set of constraints, and the objective function.
```python
# Declare and initialize model
m = gp.Model('RAP')
```
Using license file c:\gurobi\gurobi.lic
Set parameter TokenServer to value SANTOS-SURFACE-
## Decision variables
To solve this assignment problem, we need to identify which resource is assigned to which job. We introduce a decision variable for each possible assignment of resources to jobs. Therefore, we have 9 decision variables.
To simplify the mathematical notation of the model formulation, we define the following indices for resources and jobs:
For example, $x_{2,1}$ is the decision variable associated with assigning the resource Joe to the job Tester. Therefore, decision variable $x_{r,j}$ equals 1 if resource $r \in R$ is assigned to job $j \in J$, and 0 otherwise.
The ``Model.addVars()`` method creates the decision variables for a ``Model`` object.
This method returns a Gurobi ``tupledict`` object that contains the newly created variables. We supply the ``combinations`` object as the first argument to specify the variable indices. The ``name`` keyword is used to specify a name for the newly created decision variables. By default, variables are assumed to be non-negative.
```python
# Create decision variables for the RAP model
x = m.addVars(combinations, name="assign")
```
## Job constraints
We now discuss the constraints associated with the jobs. These constraints need to ensure that each job is filled by exactly one resource.
The job constraint for the Tester position requires that resource 1 (Carlos), resource 2 (Joe), or resource 3 (Monika) is assigned to this job. This corresponds to the following constraint.
Constraint (Tester=1)
$$
x_{1,1} + x_{2,1} + x_{3,1} = 1
$$
Similarly, the constraints for the Java Developer and Architect positions can be defined as follows.
Constraint (Java Developer = 2)
$$
x_{1,2} + x_{2,2} + x_{3,2} = 1
$$
Constraint (Architect = 3)
$$
x_{1,3} + x_{2,3} + x_{3,3} = 1
$$
The job constraints are defined by the columns of the following table.
In general, the constraint for the job Tester can defined as follows.
$$
x_{1,1} + x_{2,1} + x_{3,1} = \sum_{r=1}^{3 } x_{r,1} = \sum_{r \in R} x_{r,1} = 1
$$
All of the job constraints can be defined in a similarly succinct manner. For each job $j \in J$, take the summation of the decision variables over all the resources. We can write the corresponding job constraint as follows.
$$
\sum_{r \in R} x_{r,j} = 1
$$
The ``Model.addConstrs()`` method of the Gurobi/Python API defines the job constraints of the ``Model`` object “m”. This method returns a Gurobi ``tupledict`` object that contains the job constraints.
The first argument of this method, "x.sum(‘*’, j)", is the sum method and defines the LHS of the jobs constraints as follows:
For each job $j$ in the set of jobs $J$, take the summation of the decision variables over all the resources. The $==$ defines an equality constraint, and the number "1" is the RHS of the constraints.
These constraints are saying that exactly one resource should be assigned to each job.
The second argument is the name of this type of constraints.
```python
# Create job constraints
jobs = m.addConstrs((x.sum('*',j) == 1 for j in J), name='job')
```
## Resource constraints
The constraints for the resources need to ensure that at most one job is assigned to each resource. That is, it is possible that not all the resources are assigned.
For example, we want a constraint that requires Carlos to be assigned to at most one of the jobs: either job 1 (Tester), job 2 (Java Developer ), or job 3 (Architect). We can write this constraint as follows.
Constraint (Carlos=1)
$$
x_{1, 1} + x_{1, 2} + x_{1, 3} \leq 1.
$$
This constraint is less or equal than 1 to allow the possibility that Carlos is not assigned to any job. Similarly, the constraints for the resources Joe and Monika can be defined as follows:
Constraint (Joe=2)
$$
x_{2, 1} + x_{2, 2} + x_{2, 3} \leq 1.
$$
Constraint (Monika=3)
$$
x_{3, 1} + x_{3, 2} + x_{3, 3} \leq 1.
$$
Observe that the resource constraints are defined by the rows of the following table.
The constraint for the resource Carlos can be defined as follows.
$$
x_{1, 1} + x_{1, 2} + x_{1, 3} = \sum_{j=1}^{3 } x_{1,j} = \sum_{j \in J} x_{1,j} \leq 1.
$$
Again, each of these constraints can be written in a succinct manner. For each resource $r \in R$, take the summation of the decision variables over all the jobs. We can write the corresponding resource constraint as follows.
$$
\sum_{j \in J} x_{r,j} \leq 1.
$$
The ``Model.addConstrs()`` method of the Gurobi/Python API defines the resource constraints of the ``Model`` object “m”.
The first argument of this method, "x.sum(r, ‘*’)", is the sum method and defines the LHS of the resource constraints as follows: For each resource $r$ in the set of resources $R$, take the summation of the decision variables over all the jobs.
The $<=$ defines a less or equal constraints, and the number “1” is the RHS of the constraints.
These constraints are saying that each resource can be assigned to at most 1 job.
The second argument is the name of this type of constraints.
```python
# Create resource constraints
resources = m.addConstrs((x.sum(r,'*') <= 1 for r in R), name='resource')
```
## Objective function
The objective function is to maximize the total matching score of the assignments that satisfy the job and resource constraints.
For the Tester job, the matching score is $53x_{1,1}$, if resource Carlos is assigned, or $80x_{2,1}$, if resource Joe is assigned, or $53x_{3,1}$, if resource Monika is assigned.
Consequently, the matching score for the Tester job is as follows, where only one term in this summation will be nonzero.
$$
53x_{1,1} + 80x_{2,1} + 53x_{3,1}.
$$
Similarly, the matching scores for the Java Developer and Architect jobs are defined as follows. The matching score for the Java Developer job is:
$$
27x_{1, 2} + 47x_{2, 2} + 73x_{3, 2}.
$$
The matching score for the Architect job is:
$$
13x_{1, 3} + 67x_{2, 3} + 47x_{3, 3}.
$$
The total matching score is the summation of each cell in the following table.
The goal is to maximize the total matching score of the assignments. Therefore, the objective function is defined as follows.
\begin{equation}
\text{Maximize} \quad (53x_{1,1} + 80x_{2,1} + 53x_{3,1}) \; +
\end{equation}
\begin{equation}
\quad (27x_{1, 2} + 47x_{2, 2} + 73x_{3, 2}) \; +
\end{equation}
\begin{equation}
\quad (13x_{1, 3} + 67x_{2, 3} + 47x_{3, 3}).
\end{equation}
Each term in parenthesis in the objective function can be expressed as follows.
\begin{equation}
(53x_{1,1} + 80x_{2,1} + 53x_{3,1}) = \sum_{r \in R} s_{r,1}x_{r,1}.
\end{equation}
\begin{equation}
(27x_{1, 2} + 47x_{2, 2} + 73x_{3, 2}) = \sum_{r \in R} s_{r,2}x_{r,2}.
\end{equation}
\begin{equation}
(13x_{1, 3} + 67x_{2, 3} + 47x_{3, 3}) = \sum_{r \in R} s_{r,3}x_{r,3}.
\end{equation}
Hence, the objective function can be concisely written as:
\begin{equation}
\text{Maximize} \quad \sum_{j \in J} \sum_{r \in R} s_{r,j}x_{r,j}.
\end{equation}
The ``Model.setObjective()`` method of the Gurobi/Python API defines the objective function of the ``Model`` object “m”. The objective expression is specified in the first argument of this method.
Notice that both the matching score parameters “score” and the assignment decision variables “x” are defined over the “combinations” keys. Therefore, we use the method “x.prod(score)” to obtain the summation of the elementwise multiplication of the "score" matrix and the "x" variable matrix.
The second argument, ``GRB.MAXIMIZE``, is the optimization "sense." In this case, we want to *maximize* the total matching scores of all assignments.
```python
# Objective: maximize total matching score of all assignments
m.setObjective(x.prod(scores), GRB.MAXIMIZE)
```
We use the “write()” method of the Gurobi/Python API to write the model formulation to a file named "RAP.lp".
```python
# Save model for inspection
m.write('RAP.lp')
```
We use the “optimize( )” method of the Gurobi/Python API to solve the problem we have defined for the model object “m”.
```python
# Run optimization engine
m.optimize()
```
Gurobi Optimizer version 9.0.0 build v9.0.0rc2 (win64)
Optimize a model with 6 rows, 9 columns and 18 nonzeros
Model fingerprint: 0xb6602fb2
Coefficient statistics:
Matrix range [1e+00, 1e+00]
Objective range [1e+01, 8e+01]
Bounds range [0e+00, 0e+00]
RHS range [1e+00, 1e+00]
Presolve time: 0.00s
Presolved: 6 rows, 9 columns, 18 nonzeros
Iteration Objective Primal Inf. Dual Inf. Time
0 4.6000000e+32 1.800000e+31 4.600000e+02 0s
5 1.9300000e+02 0.000000e+00 0.000000e+00 0s
Solved in 5 iterations and 0.01 seconds
Optimal objective 1.930000000e+02
The ``Model.getVars()`` method of the Gurobi/Python API
retrieves a list of all variables in the Model object “m”. The ``.x`` variable attribute is used to query solution values and the ``.varName`` attribute is used to query the name of the decision variables.
```python
# Display optimal values of decision variables
for v in m.getVars():
if v.x > 1e-6:
print(v.varName, v.x)
# Display optimal total matching score
print('Total matching score: ', m.objVal)
```
assign[Carlos,Tester] 1.0
assign[Joe,Architect] 1.0
assign[Monika,JavaDeveloper] 1.0
Total matching score: 193.0
The optimal assignment is to assign:
* Carlos to the Tester job, with a matching score of 53
* Joe to the Architect job, with a matching score of 67
* Monika to the Java Developer job, with a matching score of 73.
The maximum total matching score is 193.
## Resource Assignment Problem with a budget constraint
Now, assume there is a fixed cost $C_{r,j}$ associated with assigning a resource $r \in R$ to job $j \in J$. Assume also that there is a limited budget $B$ that can be used for job assignments.
The cost of assigning Carlos, Joe, or Monika to any of the jobs is $\$1,000$ , $\$2,000$ , and $\$3,000$ respectively. The available budget is $\$5,000$.
### Data
The list $R$ contains the names of the three resources: Carlos, Joe, and Monika.
The list $J$ contains the names of the job positions: Tester, Java Developer, and Architect.
The Gurobi Python ``multidict`` function initialize two dictionaries:
* "scores" defines the matching scores for each resource and job combination.
* "costs" defines the fixed cost associated of assigning a resource to a job.
```python
# Resource and job sets
R = ['Carlos', 'Joe', 'Monika']
J = ['Tester', 'JavaDeveloper', 'Architect']
# Matching score data
# Cost is given in thousands of dollars
combinations, scores, costs = gp.multidict({
('Carlos', 'Tester'): [53, 1],
('Carlos', 'JavaDeveloper'): [27, 1],
('Carlos', 'Architect'): [13,1],
('Joe', 'Tester'): [80, 2],
('Joe', 'JavaDeveloper'): [47, 2],
('Joe', 'Architect'): [67, 2],
('Monika', 'Tester'): [53, 3] ,
('Monika', 'JavaDeveloper'): [73, 3],
('Monika', 'Architect'): [47, 3]
})
# Available budget (thousands of dollars)
budget = 5
```
The following constructor creates an empty ``Model`` object “m”. The ``Model`` object “m” holds a single optimization problem. It consists of a set of variables, a set of constraints, and the objective function.
```python
# Declare and initialize model
m = gp.Model('RAP2')
```
### Decision variables
The decision variable $x_{r,j}$ is 1 if $r \in R$ is assigned to job $j \in J$, and 0 otherwise.
The ``Model.addVars()`` method defines the decision variables for the model object “m”.
Because there is a budget constraint, it is possible that not all of the jobs will be filled. To account for this, we define a new decision variable that indicates whether or not a job is filled.
Let $g_{j}$ be equal 1 if job $j \in J$ is not filled, and 0 otherwise. This variable is a gap variable that indicates that a job cannot be filled.
***Remark:*** For the previous formulation of the RAP, we defined the assignment variables as non-negative and continuous which is the default value of the ``vtype`` argument of the ``Model.addVars()`` method.
However, in this extension of the RAP, because of the budget constraint we added to the model, we need to explicitly define these variables as binary. The ``vtype=GRB.BINARY`` argument of the ``Model.addVars()`` method defines the assignment variables as binary.
```python
# Create decision variables for the RAP model
x = m.addVars(combinations, vtype=GRB.BINARY, name="assign")
# Create gap variables for the RAP model
g = m.addVars(J, name="gap")
```
### Job constraints
Since we have a limited budget to assign resources to jobs, it is possible that not all the jobs can be filled. For the job constraints, there are two possibilities either a resource is assigned to fill the job, or this job cannot be filled and we need to declare a gap. This latter possibility is captured by the decision variable $g_j$. Therefore, the job constraints are written as follows.
For each job $j \in J$, exactly one resource must be assigned to the job, or the corresponding $g_j$ variable must be set to 1:
$$
\sum_{r \: \in \: R} x_{r,\; j} + g_{j} = 1.
$$
```python
# Create job constraints
jobs = m.addConstrs((x.sum('*',j) + g[j] == 1 for j in J), name='job')
```
### Resource constraints
The constraints for the resources need to ensure that at most one job is assigned to each resource. That is, it is possible that not all the resources are assigned. Therefore, the resource constraints are written as follows.
For each resource $r \in R$, at most one job can be assigned to the resource:
$$
\sum_{j \: \in \: J} x_{r,\; j} \leq 1.
$$
```python
# Create resource constraints
resources = m.addConstrs((x.sum(r,'*') <= 1 for r in R), name='resource')
```
### Budget constraint
This constraint ensures that the cost of assigning resources to fill job requirements do not exceed the budget available. The costs of assignment and budget are in thousands of dollars.
The cost of filling the Tester job is $1x_{1,1}$, if resource Carlos is assigned, or $2x_{2,1}$, if resource Joe is assigned, or $3x_{3,1}$, if resource Monika is assigned.
Consequently, the cost of filling the Tester job is as follows, where at most one term in this summation will be nonzero.
$$
1x_{1,1} + 2x_{2,1} + 3x_{3,1}.
$$
Similarly, the cost of filling the Java Developer and Architect jobs are defined as follows. The cost of filling the Java Developer job is:
$$
1x_{1, 2} + 2x_{2, 2} + 3x_{3, 2}.
$$
The cost of filling the Architect job is:
$$
1x_{1, 3} + 2x_{2, 3} + 3x_{3, 3}.
$$
Hence, the total cost of filling the jobs should be less or equal than the budget available.
\begin{equation}
(1x_{1,1} + 2x_{2,1} + 3x_{3,1}) \; +
\end{equation}
\begin{equation}
(1x_{1, 2} + 2x_{2, 2} + 3x_{3, 2}) \; +
\end{equation}
\begin{equation}
(1x_{1, 3} + 2x_{2, 3} + 3x_{3, 3}) \leq 5
\end{equation}
Each term in parenthesis in the budget constraint can be expressed as follows.
\begin{equation}
(1x_{1,1} + 2x_{2,1} + 3x_{3,1}) = \sum_{r \in R} C_{r,1}x_{r,1}.
\end{equation}
\begin{equation}
(1x_{1, 2} + 2x_{2, 2} + 3x_{3, 2}) = \sum_{r \in R} C_{r,2}x_{r,2}.
\end{equation}
\begin{equation}
(1x_{1, 3} + 2x_{2, 3} + 3x_{3, 3}) = \sum_{r \in R} C_{r,3}x_{r,3}.
\end{equation}
Therefore, the budget constraint can be concisely written as:
\begin{equation}
\sum_{j \in J} \sum_{r \in R} C_{r,j}x_{r,j} \leq B.
\end{equation}
The ``Model.addConstr()`` method of the Gurobi/Python API defines the budget constraint of the ``Model`` object “m”.
The first argument of this method, "x.prod(costs)", is the prod method and defines the LHS of the budget constraint. The $<=$ defines a less or equal constraint, and the budget amount available is the RHS of the constraint.
This constraint is saying that the total cost of assigning resources to fill jobs requirements cannot exceed the budget available.
The second argument is the name of this constraint.
```python
budget = m.addConstr((x.prod(costs) <= budget), name='budget')
```
## Objective function
The objective function is similar to the RAP. The first term in the objective is the total matching score of the assignments. In this extension of the RAP, it is possible that not all jobs are filled; however, we want to heavily penalize this possibility. For this purpose, we have a second term in the objective function that takes the summation of the gap variables over all the jobs and multiply it by a big penalty $M$.
Observe that the maximum value of a matching score is 100, and the value that we give to $M$ is 101. The rationale behind the value of $M$ is that having gaps heavily deteriorates the total matching scores value.
Consequently, the objective function is to maximize the total matching score of the assignments minus the penalty associated of having gap variables with a value equal to 1.
$$
\max \; \sum_{j \; \in \; J} \sum_{r \; \in \; R} s_{r,j}x_{r,j} -M \sum_{j \in J} g_{j}
$$
```python
# Penalty for not filling a job position
M = 101
```
```python
# Objective: maximize total matching score of assignments
# Unfilled jobs are heavily penalized
m.setObjective(x.prod(scores) - M*g.sum(), GRB.MAXIMIZE)
```
```python
# Run optimization engine
m.optimize()
```
Gurobi Optimizer version 9.0.0 build v9.0.0rc2 (win64)
Optimize a model with 7 rows, 12 columns and 30 nonzeros
Model fingerprint: 0xf3c6f8c8
Variable types: 3 continuous, 9 integer (9 binary)
Coefficient statistics:
Matrix range [1e+00, 3e+00]
Objective range [1e+01, 1e+02]
Bounds range [1e+00, 1e+00]
RHS range [1e+00, 5e+00]
Presolve time: 0.00s
Presolved: 7 rows, 12 columns, 30 nonzeros
Variable types: 0 continuous, 12 integer (12 binary)
Found heuristic solution: objective 52.0000000
Root relaxation: objective 1.350000e+02, 4 iterations, 0.00 seconds
Nodes | Current Node | Objective Bounds | Work
Expl Unexpl | Obj Depth IntInf | Incumbent BestBd Gap | It/Node Time
0 0 135.00000 0 2 52.00000 135.00000 160% - 0s
0 0 121.66667 0 7 52.00000 121.66667 134% - 0s
0 0 cutoff 0 52.00000 52.00000 0.00% - 0s
Cutting planes:
Gomory: 1
GUB cover: 1
RLT: 1
Explored 1 nodes (7 simplex iterations) in 0.03 seconds
Thread count was 8 (of 8 available processors)
Solution count 1: 52
Optimal solution found (tolerance 1.00e-04)
Best objective 5.200000000000e+01, best bound 5.200000000000e+01, gap 0.0000%
The definition of the objective function includes the penalty of no filling jobs. However, we are interested in the optimal total matching score value when not all the jobs are filled. For this purpose, we need to compute the total matching score value using the matching score values $s_{r,j}$ and the assignment decision variables $x_{r,j}$.
```python
# Compute total matching score from assignment variables
total_matching_score = 0
for r, j in combinations:
if x[r, j].x > 1e-6:
print(x[r, j].varName, x[r, j].x)
total_matching_score += scores[r, j]*x[r, j].x
print('Total matching score: ', total_matching_score)
```
assign[Joe,Tester] 1.0
assign[Monika,JavaDeveloper] 1.0
Total matching score: 153.0
### Analysis
Recall that the budget is $\$5,000$, and the total cost associated of allocating the three resources is $\$6,000$. This means that there is not enough budget to allocate the three resources we have. Consequently, the Gurobi Optimizer must choose two resources to fill the jobs demand, leave one job unfilled, and maximize the total matching scores. Notice that the two top matching scores are 80% (Joe for the Tester job) and 73% (Monika for the Java Developer job). Also, notice that the lowest score is 13% (Carlos for the Architect job). Assigning Joe to the Tester job, Monika to the Java Developer job, and nobody to the Architect job costs $\$5,000$ and yields a total matching score of 153. This is the optimal solution found by the Gurobi Optimizer.
Copyright © 2020 Gurobi Optimization, LLC
|
@testset "README examples" begin
sdd = SinkhornDocumentDistance()
# From Kusner's WMD paper they used this illustrative example of two
# quite similar sentences (documents) which are similar semantically
# but not syntactically.
d1 = ["obama", "speaks", "media", "illinois"]
d2 = ["president", "greets", "press", "chicago"]
d12 = evaluate(sdd, d1, d2)
# To compare to something let's take a different document which we expect
# to have a larger distance to the ones above than they have to each other.
d3 = ["lawyer", "tanks", "car", "africa"]
d13 = evaluate(sdd, d1, d3)
d23 = evaluate(sdd, d2, d3)
@test d12 < d13
@test d12 < d23
wdc = WordDistanceCache()
d1 = worddistance(wdc, "robert", "programmer") #
d2 = worddistance(wdc, "robert", "astronaut")
@test d1 < d2
end
|
#' backsolve
#'
#' Solve a triangular system.
#'
#' @param r,l
#' A triangular coefficients matrix.
#' @param x
#' The right hand sides.
#' @param k
#' The number of equations (columns of r + rows of x) to use.
#' @param upper.tri
#' Should the upper triangle be used? (if not the lower is)
#' @param transpose
#' Should the transposed coefficients matrix be used? More efficient than
#' manually transposing with \code{t()}.
#'
#' @examples
#' library(float)
#'
#' s = flrunif(10, 3)
#' cp = crossprod(s)
#' y = fl(1:3)
#' backsolve(cp, y)
#'
#' @useDynLib float R_backsolve_spm
#' @name backsolve
#' @rdname backsolve
NULL
backsolve_float32 = function(r, x, k=ncol(r), upper.tri=TRUE, transpose=FALSE)
{
if (is.integer(r))
{
if (is.float(x))
r = fl(r)
}
if (is.integer(x))
{
if (is.float(r))
x = fl(x)
}
if (is.double(r) || is.double(x))
{
if (is.float(r))
r = dbl(r)
if (is.float(x))
x = dbl(x)
backsolve(r, x, k, upper.tri, transpose)
}
else
{
if (!is.numeric(k) || k < 1 || k > nrow(r) || is.na(k))
stop("invalid 'k' argument")
ret = .Call(R_backsolve_spm, DATA(r), DATA(x), as.integer(upper.tri), as.integer(transpose), as.integer(k))
float32(ret)
}
}
forwardsolve_float32 = function(l, x, k=ncol(l), upper.tri=FALSE, transpose=FALSE)
{
backsolve_float32(l, x, k, upper.tri, transpose)
}
#' @rdname backsolve
#' @export
setMethod("backsolve", signature(r="float32", x="float32"), backsolve_float32)
#' @rdname backsolve
#' @export
setMethod("backsolve", signature(r="float32", x="BaseLinAlg"), backsolve_float32)
#' @rdname backsolve
#' @export
setMethod("backsolve", signature(r="BaseLinAlg", x="float32"), backsolve_float32)
#' @rdname backsolve
#' @export
setMethod("forwardsolve", signature(l="float32", x="float32"), forwardsolve_float32)
#' @rdname backsolve
#' @export
setMethod("forwardsolve", signature(l="float32", x="BaseLinAlg"), forwardsolve_float32)
#' @rdname backsolve
#' @export
setMethod("forwardsolve", signature(l="BaseLinAlg", x="float32"), forwardsolve_float32)
|
[STATEMENT]
lemma dom_children_normalize1_img_full:
assumes "dom_children (Node r xs) T"
and "\<forall>(t1,e1) \<in> fset xs. wf_dlverts t1"
and "\<forall>(t1,e1) \<in> fset xs. max_deg t1 \<le> 1"
shows "dom_children (Node r ((\<lambda>(t1,e1). (normalize1 t1,e1)) |`| xs)) T"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. dom_children (Node r ((\<lambda>(t1, e1). (normalize1 t1, e1)) |`| xs)) T
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. dom_children (Node r ((\<lambda>(t1, e1). (normalize1 t1, e1)) |`| xs)) T
[PROOF STEP]
have "\<forall>(t1, e1) \<in> fset xs. dom_children (Node r {|(t1, e1)|}) T"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>(t1, e1)\<in>fset xs. dom_children (Node r {|(t1, e1)|}) T
[PROOF STEP]
using dom_children_all_singletons[OF assms(1)]
[PROOF STATE]
proof (prove)
using this:
(?t1.0, ?e1.0) \<in> fset xs \<Longrightarrow> dom_children (Node r {|(?t1.0, ?e1.0)|}) T
goal (1 subgoal):
1. \<forall>(t1, e1)\<in>fset xs. dom_children (Node r {|(t1, e1)|}) T
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
\<forall>(t1, e1)\<in>fset xs. dom_children (Node r {|(t1, e1)|}) T
goal (1 subgoal):
1. dom_children (Node r ((\<lambda>(t1, e1). (normalize1 t1, e1)) |`| xs)) T
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
\<forall>(t1, e1)\<in>fset xs. dom_children (Node r {|(t1, e1)|}) T
[PROOF STEP]
have "\<forall>(t1, e1) \<in> fset xs. dom_children (Node r {|(normalize1 t1, e1)|}) T"
[PROOF STATE]
proof (prove)
using this:
\<forall>(t1, e1)\<in>fset xs. dom_children (Node r {|(t1, e1)|}) T
goal (1 subgoal):
1. \<forall>(t1, e1)\<in>fset xs. dom_children (Node r {|(normalize1 t1, e1)|}) T
[PROOF STEP]
using dom_children_normalize1 assms(2,3)
[PROOF STATE]
proof (prove)
using this:
\<forall>(t1, e1)\<in>fset xs. dom_children (Node r {|(t1, e1)|}) T
\<lbrakk>dom_children (Node ?r0.0 {|(?t1.0, ?e1.0)|}) T; wf_dlverts ?t1.0; max_deg ?t1.0 \<le> 1\<rbrakk> \<Longrightarrow> dom_children (Node ?r0.0 {|(normalize1 ?t1.0, ?e1.0)|}) T
\<forall>(t1, e1)\<in>fset xs. wf_dlverts t1
\<forall>(t1, e1)\<in>fset xs. max_deg t1 \<le> 1
goal (1 subgoal):
1. \<forall>(t1, e1)\<in>fset xs. dom_children (Node r {|(normalize1 t1, e1)|}) T
[PROOF STEP]
by fast
[PROOF STATE]
proof (state)
this:
\<forall>(t1, e1)\<in>fset xs. dom_children (Node r {|(normalize1 t1, e1)|}) T
goal (1 subgoal):
1. dom_children (Node r ((\<lambda>(t1, e1). (normalize1 t1, e1)) |`| xs)) T
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
\<forall>(t1, e1)\<in>fset xs. dom_children (Node r {|(normalize1 t1, e1)|}) T
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
\<forall>(t1, e1)\<in>fset xs. dom_children (Node r {|(normalize1 t1, e1)|}) T
goal (1 subgoal):
1. dom_children (Node r ((\<lambda>(t1, e1). (normalize1 t1, e1)) |`| xs)) T
[PROOF STEP]
using dom_children_if_all_singletons[of "(\<lambda>(t1,e1). (normalize1 t1,e1)) |`| xs"]
[PROOF STATE]
proof (prove)
using this:
\<forall>(t1, e1)\<in>fset xs. dom_children (Node r {|(normalize1 t1, e1)|}) T
\<forall>(t1, e1)\<in>fset ((\<lambda>(t1, e1). (normalize1 t1, e1)) |`| xs). dom_children (Node ?r {|(t1, e1)|}) ?T \<Longrightarrow> dom_children (Node ?r ((\<lambda>(t1, e1). (normalize1 t1, e1)) |`| xs)) ?T
goal (1 subgoal):
1. dom_children (Node r ((\<lambda>(t1, e1). (normalize1 t1, e1)) |`| xs)) T
[PROOF STEP]
by fastforce
[PROOF STATE]
proof (state)
this:
dom_children (Node r ((\<lambda>(t1, e1). (normalize1 t1, e1)) |`| xs)) T
goal:
No subgoals!
[PROOF STEP]
qed
|
-- ---------------------------------------------------------------- [ Time.idr ]
--
-- This RFC specifies a standard for the ARPA Internet community.
-- Hosts on the ARPA Internet that choose to implement a Time Protocol
-- are expected to adopt and implement this standard.
--
-- This protocol provides a site-independent, machine readable date
-- and time. The Time service sends back to the originating source
-- the time in seconds since midnight on January first 1900.
--
-- One motivation arises from the fact that not all systems have a
-- date/time clock, and all are subject to occasional human or machine
-- error. The use of time-servers makes it possible to quickly
-- confirm or correct a system's idea of the time, by making a brief
-- poll of several independent sites on the network.
--
-- http://tools.ietf.org/html/rfc868
--
-- --------------------------------------------------------------------- [ EOH ]
module RFC.Time
import Effects
import Effect.Default
import Effect.StdIO
import System.Protocol
||| This protocol provides a site-independent, machine readable date
||| and time. The Time service sends back to the originating source
||| the time in seconds since midnight on January first 1900.
|||
||| Enhanced version of the protocol.
total
timeProtocol : Protocol ['Client, 'Server] ()
timeProtocol = do
'Client ==> 'Server | Maybe String
'Server ==> 'Client | Either String Int
Done
||| This protocol provides a site-independent, machine readable date
||| and time. The Time service sends back to the originating source
||| the time in seconds since midnight on January first 1900.
|||
||| A naive version of the protocol.
total
timeProtocol' : Protocol ['Client, 'Server] ()
timeProtocol' = do
'Server ==> 'Client | Either String Int
Done
-- --------------------------------------------------------------------- [ EOF ]
|
[STATEMENT]
lemma fst_eq1: "(sla ! (0), y) = attack x1 \<Longrightarrow>
sla ! (0) = fst (attack x1)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (sla ! 0, y) = attack x1 \<Longrightarrow> sla ! 0 = fst (attack x1)
[PROOF STEP]
by (rule_tac c = y and d = "snd(attack x1)" in fst_lem1, simp)
|
\section{Infinite Sets}
\subsection{Countability}
Why $\setn$ being infinite implies $\setn - \{0\}$ being so?
\begin{proof}
\begin{align*}
&X \text{ being finite} \to X \cup \{x\} \text{ being finite} \tag{3.6.14(a)} \\
\equiv &X \cup \{x\} \text{ being infinite} \to X \text{ being infinite}
\end{align*}
\end{proof}
\paragraph{Examples 8.1.3}
Why $f: n \mapsto 2n$ gives a bijection? Injectivity: $m \ne n \to 2m \ne 2n$; Surjectivity: $\forall n \in \setn, 2n \in f(\setn)$.
\declareexercise{8.1.2}
Proof using induction:
\begin{proof}
Suppose that for $S \subseteq \setn$, there is no smallest element in $S$. We now prove that $S$ must be empty.
First, $0 \notin S$, otherwise, 0 would be the smallest element.
Now suppose that for some $N$, $\forall n \le N, n \not in S$, then $N+1$ must not be in $S$, otherwise it would be the smallest number.
We can now close the induction.
\end{proof}
Proof using the least upper bound property:
\begin{proof}
It is obvious that the nonempty set $S \subseteq \setn$ has a lower bound. For example, $0$ is one. Therefore, $\exists L \in \setr$ to be the greatest lower bound of $S$. We now show that $L$ is the smallest element of $S$.
$L$ can only be an integer. Otherwise, all real numbers between $L$ and $\ceiling{L}$ would be a lower bound bigger than $L$. In addition, $L \in S$, otherwise, $L+1$ would be a lower bound ($\forall x \in S, x>L \to x \ge L+1$). Therefore, $L$ is the smallest number.
\end{proof}
\declareexercise{8.1.3}
Gap Number
\begin{enumerate}
\item $X$ must be unbounded, for any $S \subseteq \setn$ bounded above by $M \in setn$ cannot have a cardinality bigger than $M+1$. Therefore $X\setminus\{a_m,m\le n\}$ is also unbounded, and is thus infinite (Remark 3.6.13).
\item Denote the set $\{x \in X: x \neq a_m \forall m < n\}$ as $X_n$, and we have $X_{n} \subseteq X_{n-1}$. Since that $a_n$ is the smallest element in $X_n$, all elements in $X_m$ for $m > n$ is bigger than $a_n$. Thus $a_{n-1} < a_n$ follows from there.
\item There is no equality in the previous relation.
\item This is nearly obvious because we are selecting elements from $X$ and its subsets.
\item $\forall n \forall m < n, a_n \ne x \to x \ne a_m$.
\item We have both $a_0 \ge 0$ and $a_n < a_{n+1} \to a_{n+1} \ge a_n + 1$. Thus $a_n > n$ can be easily shown with induction.
\item Otherwise $g$ could not be both bijective and increasing. If $g(m) \ne a_m$, then $g(m) > a_m$ since $a_m$ is the smallest element in the remaining set. $g$ is a bijection, so $a_m$ must be equaled by $g(n)$ with some $n > m$, a contradiction to the fact that $g$ is increasing.
\end{enumerate}
\declareexercise{8.1.4}
\begin{proof}
It is obvious that when restricted to $A$, $f$ becomes injective. Now we show that $\forall x \in f(N), \exists n \in A, f(n) = x$.
Suppose for sake of contradiction that there are elements $y \in f(N)$ such that $\forall x \in A, f(x) \ne y$. Note that we must also have $\exists n \in \setn \setminus A, f(n) = y$, which means the set $S := \setn \setminus A$ is non-empty. $S$ is also a subset of $\setn$, so it has a smallest element, and let's call it $m$.
All numbers between 0 and $m$ thus become elements in $A$. By definition, $m$ cannot equal to any of them, that is, $\forall 0\le x \le m, f(x) \ne f(m)$. But this implies that $m$ is an element of $A$, a contradiction.
Therefore, $f: A \to f(N)$ is a bijection. $f(N)$ then is proved to be at most countable since $A$ is a subset of $\setn$.
\end{proof}
\declareexercise{8.1.5}
\begin{proof}
Since $X$ is countable, there is a bijection $g: \setn \to X$, which gives $X = g(\setn)$. So $f(X) = f(g(\setn)) = f \circ g (\setn)$. Therefore Corollary 8.1.9 follows from Proposition 8.1.8.
\end{proof}
\declareexercise{8.1.6}
\begin{proof}
If $A$ is finite, then there exists a bijection $f: A \to S = \{m\in \setn : 1 \le m \le \#A\}$. Since that $S$ is a subset of $\setn$, $f:A \to \setn$ is injective.
If $A$ is countable, then there is a bijection $f: A \to \setn$, which is itself injective.
We have proved that if $A$ is at most countable, then there is an injective function $f: A \to \setn$.
On the other hand, if there is an injective map $f: A \to \setn$, then $f: A \to f(A)$ is a bijection. Since that $f(A)$ is a subset of $\setn$, it is at most countable, which implies that $A$ is at most countable.
\end{proof}
\declareexercise{8.1.7}
\begin{proof}
Since $f$ is bijective, for all $x \in X, \exists n \in \setn, f(n) = X$. But for all $n$, $h(2n) = f(n)$, so it means $h$ iterates every element of $X$. Similarly, $h$ iterates every element of $Y$. Thus, $X\cup Y \subseteq h(\setn)$. But by definition, $h(\setn) \subseteq X \cup Y$, so we must have $h(\setn) = X \cup Y$.
Both $X$ and $Y$ are infinite, so their union cannot be finite. According to Proposition 8.1.8, $X\cup Y$ thus can only be countable.
\end{proof}
\declareexercise{8.1.8}
\begin{proof}
Since that $X,Y$ are countable, there are two bijections: $f: \setn \to X, g: \setn \to Y$. Define $h:(m,n) \mapsto (f(m),g(n))$, and we can see that $h$ is a bijection from $\setn \times \setn$ to $X \times Y$.
Because $\setn \times \setn$ is countable, so is $X \times Y$.
\end{proof}
|
[STATEMENT]
lemma eqButUID_openByF_eq:
assumes ss1: "eqButUID s s1"
shows "openByF s = openByF s1"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. openByF s = openByF s1
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. openByF s = openByF s1
[PROOF STEP]
from ss1
[PROOF STATE]
proof (chain)
picking this:
eqButUID s s1
[PROOF STEP]
have fIDs: "eqButUIDf (friendIDs s) (friendIDs s1)"
[PROOF STATE]
proof (prove)
using this:
eqButUID s s1
goal (1 subgoal):
1. eqButUIDf (friendIDs s) (friendIDs s1)
[PROOF STEP]
unfolding eqButUID_def
[PROOF STATE]
proof (prove)
using this:
admin s = admin s1 \<and> pendingUReqs s = pendingUReqs s1 \<and> userReq s = userReq s1 \<and> userIDs s = userIDs s1 \<and> user s = user s1 \<and> pass s = pass s1 \<and> eqButUIDf (pendingFReqs s) (pendingFReqs s1) \<and> eqButUID12 (friendReq s) (friendReq s1) \<and> eqButUIDf (friendIDs s) (friendIDs s1) \<and> postIDs s = postIDs s1 \<and> admin s = admin s1 \<and> post s = post s1 \<and> vis s = vis s1 \<and> owner s = owner s1 \<and> pendingSApiReqs s = pendingSApiReqs s1 \<and> sApiReq s = sApiReq s1 \<and> serverApiIDs s = serverApiIDs s1 \<and> serverPass s = serverPass s1 \<and> outerPostIDs s = outerPostIDs s1 \<and> outerPost s = outerPost s1 \<and> outerVis s = outerVis s1 \<and> outerOwner s = outerOwner s1 \<and> sentOuterFriendIDs s = sentOuterFriendIDs s1 \<and> recvOuterFriendIDs s = recvOuterFriendIDs s1 \<and> pendingCApiReqs s = pendingCApiReqs s1 \<and> cApiReq s = cApiReq s1 \<and> clientApiIDs s = clientApiIDs s1 \<and> clientPass s = clientPass s1 \<and> sharedWith s = sharedWith s1
goal (1 subgoal):
1. eqButUIDf (friendIDs s) (friendIDs s1)
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
eqButUIDf (friendIDs s) (friendIDs s1)
goal (1 subgoal):
1. openByF s = openByF s1
[PROOF STEP]
have "\<forall>uid \<in> UIDs. uid \<in>\<in> friendIDs s UID1 \<longleftrightarrow> uid \<in>\<in> friendIDs s1 UID1"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>uid\<in>UIDs. (uid \<in>\<in> friendIDs s UID1) = (uid \<in>\<in> friendIDs s1 UID1)
[PROOF STEP]
using UID1_UID2_UIDs UID1_UID2
[PROOF STATE]
proof (prove)
using this:
{UID1, UID2} \<inter> UIDs = {}
UID1 \<noteq> UID2
goal (1 subgoal):
1. \<forall>uid\<in>UIDs. (uid \<in>\<in> friendIDs s UID1) = (uid \<in>\<in> friendIDs s1 UID1)
[PROOF STEP]
by (intro ballI eqButUIDf_not_UID'[OF fIDs]; auto)
[PROOF STATE]
proof (state)
this:
\<forall>uid\<in>UIDs. (uid \<in>\<in> friendIDs s UID1) = (uid \<in>\<in> friendIDs s1 UID1)
goal (1 subgoal):
1. openByF s = openByF s1
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
\<forall>uid\<in>UIDs. (uid \<in>\<in> friendIDs s UID1) = (uid \<in>\<in> friendIDs s1 UID1)
goal (1 subgoal):
1. openByF s = openByF s1
[PROOF STEP]
have "\<forall>uid \<in> UIDs. uid \<in>\<in> friendIDs s UID2 \<longleftrightarrow> uid \<in>\<in> friendIDs s1 UID2"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>uid\<in>UIDs. (uid \<in>\<in> friendIDs s UID2) = (uid \<in>\<in> friendIDs s1 UID2)
[PROOF STEP]
using UID1_UID2_UIDs UID1_UID2
[PROOF STATE]
proof (prove)
using this:
{UID1, UID2} \<inter> UIDs = {}
UID1 \<noteq> UID2
goal (1 subgoal):
1. \<forall>uid\<in>UIDs. (uid \<in>\<in> friendIDs s UID2) = (uid \<in>\<in> friendIDs s1 UID2)
[PROOF STEP]
by (intro ballI eqButUIDf_not_UID'[OF fIDs]; auto)
[PROOF STATE]
proof (state)
this:
\<forall>uid\<in>UIDs. (uid \<in>\<in> friendIDs s UID2) = (uid \<in>\<in> friendIDs s1 UID2)
goal (1 subgoal):
1. openByF s = openByF s1
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
\<forall>uid\<in>UIDs. (uid \<in>\<in> friendIDs s UID1) = (uid \<in>\<in> friendIDs s1 UID1)
\<forall>uid\<in>UIDs. (uid \<in>\<in> friendIDs s UID2) = (uid \<in>\<in> friendIDs s1 UID2)
[PROOF STEP]
show "openByF s = openByF s1"
[PROOF STATE]
proof (prove)
using this:
\<forall>uid\<in>UIDs. (uid \<in>\<in> friendIDs s UID1) = (uid \<in>\<in> friendIDs s1 UID1)
\<forall>uid\<in>UIDs. (uid \<in>\<in> friendIDs s UID2) = (uid \<in>\<in> friendIDs s1 UID2)
goal (1 subgoal):
1. openByF s = openByF s1
[PROOF STEP]
unfolding openByF_def
[PROOF STATE]
proof (prove)
using this:
\<forall>uid\<in>UIDs. (uid \<in>\<in> friendIDs s UID1) = (uid \<in>\<in> friendIDs s1 UID1)
\<forall>uid\<in>UIDs. (uid \<in>\<in> friendIDs s UID2) = (uid \<in>\<in> friendIDs s1 UID2)
goal (1 subgoal):
1. (\<exists>uid\<in>UIDs. uid \<in>\<in> friendIDs s UID1 \<or> uid \<in>\<in> friendIDs s UID2) = (\<exists>uid\<in>UIDs. uid \<in>\<in> friendIDs s1 UID1 \<or> uid \<in>\<in> friendIDs s1 UID2)
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
openByF s = openByF s1
goal:
No subgoals!
[PROOF STEP]
qed
|
using StatisticalRethinking, Parameters
struct globe_toss{TO <: AbstractVector}
# Observations of water
w::TO
# Number of tosses
n::Int
end
function (problem::globe_toss)(theta)
@unpack w, n = problem
ll = 0.0
ll += sum(log.(pdf.(Beta(1, 1), theta[1])))
ll += sum(log.(pdf.(Binomial(n[1], theta[1]), w)))
-ll
end
n = 9 # Total number of tosses
w = [6] # Water in n tosses
llf = globe_toss(w, n);
theta = [0.5]
llf(theta)
# Compute the MAP (maximum_a_posteriori) estimate
x0 = [0.5]
lower = [0.0]
upper = [1.0]
(qmap, opt) = quap(llf, x0, lower, upper)
|
%% Hauptdatei
\documentclass{article}
\input{defines}
%%% Anpassungen an die deutsche Sprache
\usepackage{german}
%%% Umlaute
\usepackage[latin1]{inputenc}
%%% AMS Mathe-Erweiterungen
\usepackage{amsmath,amsthm,amstext,amsfonts,amssymb,amsxtra,eucal}
%%% einige Sonderzeichen
\usepackage{latexsym}
%%% Erweiterungen fuer Listen
\usepackage{enumerate}
%% Absaetze nicht einruecken
\setlength{\parindent}{0pt}
\usepackage{algorithmic}
\usepackage{algorithm}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\pagestyle{empty}
\begin{document}
\section{Adaptive Algorithm}\label{sect:adaptive}~\\
The adaptive quantum search algorithm over the finite search
space~$\mathcal{S}$ with mutation operator \textsc{mut} is an algorithm that maximizes the
objective function $f:\mathcal{S}\to\mathbb{R}$.
We use two subroutines:
\begin{itemize}
\item $G_>(\mathbf{x})$ uses Grover search with respect to \textsc{mut} to return an
element $\mathbf{y}\in\mathcal{S}$ such that $f(\mathbf{y})>f(\mathbf{x})$. (cf. section \ref{sect:progressive})
\item $G_{\geq}(\mathbf{x})$ uses Grover search with respect to \textsc{mut} to return an
element $\mathbf{y}\in\mathcal{S}$ such that $f(\mathbf{y})\geq f(\mathbf{x})$. (cf. section \ref{sect:conservative})
\end{itemize}
\begin{algorithm}
{\bf FIND\_BETTER\_SOLUTION}\\
Input: a search point $\mathbf{x}$.\\
Output: a search point $\mathbf{y}$ such that $f(\mathbf{y})>f(\mathbf{x})$.
\begin{algorithmic}
\STATE $\Tmax := 1$;
\COMMENT{the maximal running time of a Grover search}
\STATE float $R$;
\COMMENT{the running time of the last Grover search}
\STATE Flip a coin with prob(head)$=1/2$.
\IF{head}
\STATE GOTO STRATEGY1;
\ELSE
\STATE GOTO STRATEGY2;
\ENDIF
\STATE
\STATE STRATEGY1
\STATE Try to find $\mathbf{y} := G_{\geq}(\mathbf{x})$ in time $\Tmax$.
\IF {successful \&\& $f(\mathbf{y}) > f(\mathbf{x})$}
\RETURN $\mathbf{y}$
\ELSIF{successful \&\& $f(\mathbf{y}) = f(\mathbf{x})$}
\STATE $\mathbf{x} := \mathbf{y}$;
\STATE $R :=$ runtime of $G_{\geq}$;
\ELSE
\STATE $R := \Tmax$;
\ENDIF
\STATE Flip a coin with prob(head) $= \frac{R}{\Tmax}$.
\IF {head}
\STATE $\Tmax := 2\Tmax$;
\STATE GOTO STRATEGY2;
\ELSE
\STATE GOTO STRATEGY1;
\ENDIF
\STATE
\STATE STRATEGY2
\STATE Try to find $\mathbf{y} := G_{>}(\mathbf{x})$ in time $\Tmax$.
\IF{successful}
\RETURN $\mathbf{y}$
\ELSE
\STATE $R := \Tmax$;
\ENDIF
\STATE Flip a coin with prob(head) $= \frac{R}{\Tmax}$.
\IF{head}
\STATE $\Tmax := 2\Tmax$;
\STATE GOTO STRATEGY1;
\ELSE
\STATE GOTO STRATEGY2;
\ENDIF
\end{algorithmic}
\end{algorithm}
\begin{algorithm}
{\bf ADAPTIVE QEA}\\
Input: A search space $\mathcal{S}$, a mutation operator \textsc{mut}, an objective function $f:\mathcal{S}\to\mathbb{R}$..
Output: A point $\mathbf{x} \in \mathcal{S}$ of maxmimal fitness $f(\mathbf{x})$
\begin{algorithmic}
\STATE Choose $\mathbf{x}_0 \in \mathcal{S}$ uniformly at random.
\STATE $t:=0$;
\WHILE{$\mathbf{x}_t$ is not global maximum}
\STATE $\mathbf{x}_{t+1} :=$ FIND\_BETTER\_SOLUTION($\mathbf{x}_{t}$)
\STATE t:=t+1;
\ENDWHILE
\RETURN $\mathbf{x}_t$
\end{algorithmic}
\end{algorithm}
\end{document}
|
#!/usr/bin/env python
"""AP3D.PY - APOGEE software to process 3D data cubes.
"""
from __future__ import print_function
__authors__ = 'David Nidever <[email protected]>'
__version__ = '20200404' # yyyymmdd
import os
import numpy as np
import warnings
from astropy.io import fits
from astropy.table import Table, Column
from astropy import modeling
from glob import glob
from scipy.signal import medfilt
from scipy.ndimage.filters import median_filter,gaussian_filter1d
from scipy.optimize import curve_fit, least_squares
from scipy.special import erf
from scipy.interpolate import interp1d
#from numpy.polynomial import polynomial as poly
#from lmfit import Model
#from apogee.utils import yanny, apload
#from sdss_access.path import path
import bindata
# Ignore these warnings, it's a bug
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
def ap3dproc_lincorr(slice_in,lindata,linhead):
"""
This subroutine does the Linearity Correction for a slice
The lindata array gives a quadratic polynomial either for
each pixel or for each output (512 pixels)
The polynomial should take the observed counts and convert
them into corrected counts, i.e.
counts_correct = poly(counts_obs,coef)
"""
readtime = 10.0 # the time between reads
sz = slice_in.shape
nreads = sz[1]
szlin = lindata.shape
# Each pixel separately
#-----------------------
if szlin[0]==2048:
# Need to figure out the threshold for each pixel
# Only want to correct data that need it and are
# in the nonlinear regime
# y = c0 + c1*x + c2*x^2
# Want to know where the deviation of this from linearity
# is greater than some fraction
# y_lin = 0.0 + 1.0*x
# y-ylin = c0+c1*x+c2*x^2 - x > frac
# Solve for x
# c2*x^2 + (c1-1)*x + c0 > frac
# Solutions are
# x = -(c1-1)+/-sqrt( (c1-1)^2-4*c2*c0)/(2*c2)
#linthresh = lindata
# This takes you from OBSERVED COUNTS to CORRECTED COUNTS
# x = observed counts
# y = corrected counts
coef0 = lindata[:,0].repeat(nreads).reshape(2048,nreads)
coef1 = lindata[:,1].repeat(nreads).reshape(2048,nreads)
coef2 = lindata[:,2].repeat(nreads).reshape(2048,nreads)
slice_out = coef0 + coef1*slice_in + coef2*slice_in**2
# Each output separately
#------------------------
else:
# a separate coefficient for each output (512 columns)
coef0 = np.zeros((2048,nreads),float)
coef1 = np.zeros((2048,nreads),float)
coef2 = np.zeros((2048,nreads),float)
corr = np.zeros((2048,nreads),float)
npar = szlin[1]
# loop over quadrants
slice_out = slice_in.copy()
for i in range(4):
corr[512*i:512*i+512,:] = lindata[i,0]
x = slice_in[512*i:512*i+512,:]
for j in range(npar-1):
corr[512*i:512*i+512,:] += lindata[i,j+1]*x
x *= slice_in[512*i:512*i+512,:]
slice_out = slice_in*corr
for i in range(4):
coef0[512*i:512*i+512,:] = lindata[i,0]
coef1[512*i:512*i+512,:] = lindata[i,1]
coef2[512*i:512*i+512,:] = lindata[i,2]
slice_out = coef0 + coef1*slice_in + coef2*slice_in**2
return slice_out
def ap3dproc_darkcorr(slice_in,darkslice,darkhead):
"""
This subroutine does the Dark correction for a slice
darkslice is a 2048xNreads array that gives the dark counts
To get the dark current just multiply the dark count rate
by the time for each read
"""
nreads = slice_in.shape[]1
# Just subtract the darkslice
# subtract each read at a time in case we still have the reference pixels
slice_out = slice_in.copy()
for i in range(nreads):
slice_out[0:2048,i] -= darkslice[:,i]
return slice_out
def ap3dproc_crfix(dCounts,satmask,sigthresh=10,onlythisread=False,noise=17.0,crfix=False):
"""
This subroutine fixes cosmic rays in a slice of the datacube.
The last dimension in the slice should be the Nreads, i.e.
[Npix,Nreads].
Parameters:
dCounts The difference of neighboring pairs of reads.
satmask The saturation mask [Nx,3]. 1-saturation mask,
2-read # of first saturation, 3-number of saturated reads
=sigthresh The Nsigma threshold for detecting a
CR. sigthresh=10 by default
=onlythisread Only accept CRs in this read index (+/-1 read).
This is only used for the iterative CR rejection.
=noise The readnoise in ADU (for dCounts, not single reads)
=crfix Actually fix the CR and not just detect it
Returns:
crstr Structure that gives information on the CRs.
dCounts_fixed The "fixed" dCounts with the CRs removed.
med_dCounts The median dCounts for each pixel
mask An output mask for with the CRs marked
crindex At what read did the CR occur
crnum The number of CRs in each pixel of this slice
variability The fractional variability in each pixel
"""
npix,nreads = dCounts.shape
# nreads is actually Nreads-1
# Initialize the CRSTR with 50 CRs, will trim later
# don't know Y right now
dtype = np.dtype([('x',int),('y',int),('read',int),('counts',float),('nsigma',float),('globalsigma',float),
('fixed',bool),('localsigma',float),('fixerror',float),('neicheck',bool)])
crstr = np.zeros(100,dtype)
#crstr_data_def = {X:0L,Y:0L,READ:0L,COUNTS:0.0,NSIGMA:0.0,GLOBALSIGMA:0.0,FIXED:0,LOCALSIGMA:0.0,FIXERROR:0.0,NEICHECK:0}
#crstr = {NCR:0L,DATA:REPLICATE(crstr_data_def,50)}
# Initializing dCounts_fixed
dCounts_fixed = dCounts.copy()
#-----------------------------------
# Get median dCounts for each pixel
#-----------------------------------
med_dCounts = np.nanmedian(dCounts,axis=1) # NAN are automatically ignored
# Check if any medians are NAN
# would happen if all dCounts in a pixel are NAN
med_dCounts[~np.isfinite(med_dCounts)] = 0.0 # set to zero
# Number of non-saturated, "good" reads
totgd = np.sum(np.isfinite(dCounts),axis=1)
# If we only have 2 good Counts then we might need to use
# the minimum dCounts in case there is a CR
ind2, = np.where(totgd == 2)
nind2 = len(ind2)
for j in range(nind2):
min_dCounts = np.min(dCounts[ind2[j],:],axis=1)
max_dCounts = np.max(dCounts[ind2[j],:],axis=1)
# If they are too different then use the lower value
# probably because of a CR
if (max_dCounts-min_dCounts)/np.maximum(min_dCounts,1e-4) > 0.3:
med_dCounts[ind2[j]] = np.maximum(min_dCounts,1e-4)
med_dCounts2D = med_dCounts.repeat(nreads).reshape((npix,nreads)) # 2D version
#-----------------------------------------------------
# Get median smoothed/filtered dCounts for each pixel
#-----------------------------------------------------
# this should help remove transparency variations
smbin = np.minimum(11, nreads) # in case Nreads is small
if nreads > smbin:
sm_dCounts = MEDFILT2D(dCounts,smbin,dim=2,/edge_copy,/even)
else:
sm_dCounts = med_dCounts2D
# We need to deal with reads near saturated reads carefully
# otherwise the median will be over less reads
# For now this is okay, at worst the median will be over smbin/2 reads
# If there are still some NAN then replace them with the global
# median dCounts for that pixel. These are probably saturated
# so it probably doesn't matter
bdnan, = np.where(np.finite(sm_dCounts) == False)
nbdnan = len(bdnan)
if nbdnan>0:
sm_dCounts[bdnan] = med_dCounts2D[bdnan]
#--------------------------------------
# Variability from median (fractional)
#--------------------------------------
variability = dln.mad(dCounts-med_dCounts2D,axis=1,zero=True)
variability = variability / np.maximum(med_dCounts, 0.001) # make it a fractional variability
bdvar, = np.where(np.finite(variability) == False)
nbdvar = len(bdar)
if nbdvar>0:
variability[bdvar] = 0.0 # all NAN
if nind2>0:
variability[ind2] = 0.5 # high variability for only 2 good dCounts
#----------------------------------
# Get sigma dCounts for each pixel
#----------------------------------
#sig_dCounts = mad(dCounts,dim=2)
# subtract smoothed version to remove any transparency variations
# saturated reads (NAN in dCounts) are automatically ignored
sig_dCounts = dln.mad(dCounts-sm_dCounts,axis=1,zero=True)
sig_dCounts = np.maximum(sig_dCounts, noise) # needs to be at least above the noise
# Check if any sigma are NAN
# would happen if all dCounts in a pixel are NAN
sig_dCounts[~np.isfinite(sig_dCounts)] = noise # set to noise level
# Pixels with only 2 good dCounts, set sigma to 30%
for j in range(nind2):
sig_dCounts[ind2[j]] = np.maximum(0.3*med_dCounts[ind2[j]], noise)
sig_dCounts2D = sig_dCounts.repeat(nreads).reshape((npix,nreads)) # 2D version
#-----------
# Find CRs
#-----------
# threshold for number of sigma above (local) median
nsig_thresh = np.maximum(nsig_thresh, 3) # 3 at a minimum
# Saturated dCounts (NANs) are automatically ignored
nsigma_slice = (dCounts-sm_dCounts)/sig_dCounts2D
bd1D, = np.where( ( nsigma_slice > nsig_thresh ) &
( dCounts > noise*nsig_thresh ))
nbd1D = len(bd1D)
if verbose: print(str(nbd1D)+' CRs found')
### DLN GOT TO HERE 8/6/2020
# Some CRs found
if nbd1D>0:
bd2D = array_indices(dCounts,bd1D)
bdx = reform(bd2D[0,*]) # column
bdr = reform(bd2D[1,*]) # read
# Correct the CRs and correct the pixels
for j in range(nbd1D):
ibdx = (bdx[j])[0]
ibdr = (bdr[j])[0]
dCounts_pixel = reform(dCounts[ibdx,:])
# ONLYTHISREAD
# for checking neighboring pixels in the iterative part
#--------------
if n_elements(onlythisread) gt 0:
# onlthisread is the read index, while ibdr is a dCounts index
# ibdr+1 is the read index for this CR
if (ibdr+1) lt onlythisread[0]-1 or (ibdr+1) gt onlythisread[0]+1 then goto,BOMB
# Calculate Local Median and Local Sigma
#----------------------------------------
# Use a local median/sigma so the affected CR dCount is not included
# more than 2 good dCounts and Nreads>smbin
if (totgd[ibdx] gt 2) and (nreads gt smbin):
dCounts_pixel[ibdr] = !values.f_nan # don't use affected dCounts
maxind = nreads-1
if satmask[ibdx,0] eq 1 then maxind=satmask[ibdx,1]-2 # don't include saturated reads (NANs)
lor = (ibdr-smbin/2) > 0
hir = (lor + smbin-1) < maxind
if (hir eq maxind) then lor=(hir-smbin+1) > 0
# -- Local median dCounts --
# make sure the indices make sense
#if (lor lt 0 or hir lt 0 or hir le lor) then stop
if (lor lt 0 or hir lt 0 or hir le lor) then local_med_dCounts=med_dCounts[ibdx] else $
local_med_dCounts = median(dCounts_pixel[lor:hir],/even)
# If local median dCounts is NAN use all reads
if finite(local_med_dCounts) eq 0 then local_med_dCounts=med_dCounts[ibdx]
# If still NaN then set to 0.0
if finite(local_med_dCounts) eq 0 then local_med_dCounts=0.0
# -- Local sigma dCounts --
local_sigma = MAD(dCounts_pixel[lor:hir]-local_med_dCounts,/zero)
# If local sigma dCounts is NAN use all reads
# this should never actually happen
if finite(local_sigma) eq 0 then local_sigma=sig_dCounts[ibdx]
# If still NaN then set to noise
if finite(local_sigma) eq 0 then local_sigma=noise
# Only 2 good dCounts OR Nreads<smbin
else:
local_med_dCounts = med_dCounts[ibdx]
local_sigma = sig_dCounts[ibdx]
local_med_dCounts = med_dCounts[ibdx]
local_sigma = sig_dCounts[ibdx]
# Fix the CR
#------------
if keyword_set(crfix):
if keyword_set(verbose) then $
print(' Fixing CR at Column '+str(ibdx)+' Read '+str(ibdr+1))
# Replace with smoothed dCounts, i.e. median of neighbors
dCounts_fixed[ibdx,ibdr] = local_med_dCounts # fix CR dCounts
#dCounts_fixed[ibdx,ibdr] = sm_dCounts[ibdx,ibdr] # fix CR dCounts
# Error in the fix
# by taking median of smbin neighboring reads we reduce the error by ~1/sqrt(smbin)
fixerror = local_sigma/sqrt(smbin-1) # -1 because the CR read is in there
# CRSTR stuff
#--------------
# Expand CR slots in CRSTR
if crstr.ncr eq n_elements(crstr.data):
old_crstr = crstr
nold = n_elements(old_crstr.data)
crstr = {NCR:0L,DATA:REPLICATE(crstr_data_def,nold+50L)}
STRUCT_ASSIGN,old_crstr,crstr # source, destination
apgundef,old_crstr
# Add CR to CRSTR
crstr.data[crstr.ncr].x = ibdx
crstr.data[crstr.ncr].read = ibdr+1 # ibdr is dCounts index, +1 to get read
crstr.data[crstr.ncr].counts = dCounts[ibdx,ibdr] - sm_dCounts[ibdx,ibdr]
crstr.data[crstr.ncr].nsigma = nsigma_slice[ibdx,ibdr]
crstr.data[crstr.ncr].globalsigma = sig_dCounts[ibdx]
if keyword_set(crfix) then crstr.data[crstr.ncr].fixed = 1
crstr.data[crstr.ncr].localsigma = local_sigma
if keyword_set(crfix) then crstr.data[crstr.ncr].fixerror = fixerror
crstr.ncr++
# Replace the dCounts with CRs with the median smoothed values
# other methods could be used to "fix" the affected read,
# e.g. polynomial fitting/interpolation, Gaussian smoothing, etc.
# Now trim CRSTR
if crstr.ncr>0:
old_crstr = crstr
crstr = {NCR:old_crstr.ncr,DATA:old_crstr.data[0:old_crstr.ncr-1]}
apgundef,old_crstr
else:
crstr = {NCR:0L} # blank structure
return crstr, dCounts_fixed, med_dCounts, mask, crindex, crnum, variability
def loaddetector(detcorr,silent=True):
""" Load DETECTOR FILE (with gain, rdnoise and linearity correction). """
# DETCORR must be scalar string
if (type(detcorr) != str) | (dln.size(bpmcorr) > 1):
raise ValueError('DETCORR must be a scalar string with the filename of the DETECTOR file')
# Check that the file exists
if os.path.exists(detcorr) is False:
raise ValueError('DETCORR file '+detcorr+' NOT FOUND')
# Load the DET file
# This should be 2048x2048
dethead = fits.getheader(detcorr,0)
rdnoiseim,noisehead = fits.getdata(detcorr,1,header=True)
gainim,gainhead = fits.getdata(detcorr,2,header=True)
# This should be 2048x2048x3 (each pixel) or 4x3 (each output),
# where the 2 is for a quadratic polynomial
lindata,linhead = fits.getdata(detcorr,3,header=True)
if silent is False: print('DET file = '+detcorr)
# Check that the file looks reasonable
# Must be 2048x2048 or 4 and have be float
if ((gainim.ndim==2) & (gainim.shape != (2048,2048))) | ((gainim.ndim==1) & (gainim.size != 4)) | (type(gainim) != np.float32):
raise ValueError('GAIN image must be 2048x2048 or 4 FLOAT image')
# If Gain is 4-element then make it an array
if gainim.size == 4:
gainim0 = gainim.copy()
gainim = np.zeros((2048,2048),float)
for k in range(4):
gainim[:,k*512:(k+1)*512] = gainim0[k]
# Must be 2048x2048 or 4 and have be float
rny,rnx = rdnoiseim.shape
if ((rdnoiseim.ndim==2) & (rdnoiseim.shape != (2048,2048)) | ((rdnoiseim.ndim==1) & (rdnoiseim.size != 4)) | (type(rdnoiseim) != np.float32):
raise ValueError('RDNOISE image must be 2048x2048 or 4 FLOAT image')
# If rdnoise is 4-element then make it an array
if rdnoiseim.size == 4:
rdnoiseim0 = rdnoiseim.copy()
rdnoiseim = np.zeros((2048,2048),float)
for k in range(4):
rdnoiseim[:,k*512:(k+1)*512] = rdnoiseim0[k]
# Check that the file looks reasonable
# This should be 2048x2048x3 (each pixel) or 4x3 (each output),
# where the 3 is for a quadratic polynomial
szlin = size(lindata)
linokay = 0
if (szlin[0] eq 2 and szlin[1] eq 4 and szlin[2] eq 3) then linokay=1
if (szlin[0] eq 3 and szlin[1] eq 2048 and szlin[2] eq 2048 and szlin[3] eq 3) then linokay=1
if linokay==0:
raise ValueError('Linearity correction data must be 2048x2048x3 or 4x3')
return XX,XX
def loadbpm(bpmcorr,silent=True):
""" Load BAD PIXEL MASK (BPM) File """
# BPMCORR must be scalar string
if (type(bmpcorr) != str) | (dln.size(bpmcorr) > 1):
raise ValueError('BPMCORR must be a scalar string with the filename of the BAD PIXEL MASK file')
# Check that the file exists
if os.path.exists(bpmcorr) is False:
raise ValueError('BPMCORR file '+bpmcorr+' NOT FOUND')
# Load the BPM file
# This should be 2048x2048
bpmim,bpmhead = fits.getdata(bpmcorr,header=True)
if silent is False: print('BPM file = '+bpmcorr)
# Check that the file looks reasonable
# must be 2048x2048 and have 0/1 values
ny,nx = bpmim.shape
bpmokay = 0
if (bpmim.ndim != 2) | (nx != 2048) | (ny != 2048):
raise ValueError('BAD PIXEL MASK must be 2048x2048 with 0/1 values')
return bpmim,bpmhead
def loadlittrow(littrowcorr,silent=True):
#--------------------------------
# Load LITRROW MASK File
#--------------------------------.
if n_elements(littrowcorr) gt 0 and n_elements(littrowim) eq 0 then begin
# LITTROWCORR must be scalar string
if size(littrowcorr,/type) ne 7 or n_elements(littrowcorr) ne 1 then begin
error = 'LITTROWCORR must be a scalar string with the filename of the LITTROW MASK file'
if not keyword_set(silent) then print('halt: '+error)
stop
return
endif
# Check that the file exists
if file_test(littrowcorr) eq 0 then begin
error = 'LITTROWCORR file '+littrowcorr+' NOT FOUND'
if not keyword_set(silent) then print('halt: '+error)
stop
return
endif
# Load the LITTROW file
# This should be 2048x2048
FITS_READ,littrowcorr,littrowim,littrowhead,message=message,/no_abort
# Error opening file
if message ne '' then begin
error = message
if not keyword_set(silent) then print('halt: '+error)
stop
return
endif
if not keyword_set(silent) then print('LITTROW file = '+littrowcorr)
# Check that the file looks reasonable
# must be 2048x2048 and have 0/1 values
szlittrow = size(littrowim)
littrowokay = 0
dum = where(littrowim ne 0 and littrowim ne 1,nbad)
if szlittrow[0] ne 2 or szlittrow[1] ne 2048 or szlittrow[2] ne 2048 or nbad gt 0 then begin
error = 'LITTROW MASK must be 2048x2048 with 0/1 values'
if not keyword_set(silent) then print('halt: '+error)
stop
return
endif
endif # loading littrow file
return littrowim,littrowhead
def loadpersist(persistcorr,silent=True):
#--------------------------------
# Load PERSISTENCE MASK File
#--------------------------------.
if n_elements(persistcorr) gt 0 and n_elements(persistim) eq 0 then begin
# PERSISTCORR must be scalar string
if size(persistcorr,/type) ne 7 or n_elements(persistcorr) ne 1 then begin
error = 'PERSISTCORR must be a scalar string with the filename of the PERSIST MASK file'
if not keyword_set(silent) then print('halt: '+error)
stop
return
endif
# Check that the file exists
if file_test(persistcorr) eq 0 then begin
error = 'PERSISTCORR file '+persistcorr+' NOT FOUND'
if not keyword_set(silent) then print('halt: '+error)
stop
return
endif
# Load the PERSIST file
# This should be 2048x2048
FITS_READ,persistcorr,persistim,persisthead,message=message,/no_abort
# Error opening file
if message ne '' then begin
error = message
if not keyword_set(silent) then print('halt: '+error)
stop
return
endif
if not keyword_set(silent) then print('PERSIST file = '+persistcorr)
# Check that the file looks reasonable
# must be 2048x2048 and have 0/1 values
szpersist = size(persistim)
persistokay = 0
if szpersist[0] ne 2 or szpersist[1] ne 2048 or szpersist[2] ne 2048 then begin
error = 'PERSISTENCE MASK must be 2048x2048'
if not keyword_set(silent) then print('halt: '+error)
stop
return
endif
endif # loading persistence file
return persistim,persisthead
def loaddark(darkcorr,silent=True):
#----------------------------
# Load DARK CORRECTION file
#----------------------------.
if n_elements(darkcorr) gt 0 and n_elements(darkcube) eq 0 then begin
# DARKCORR must be scalar string
if size(darkcorr,/type) ne 7 or n_elements(darkcorr) ne 1 then begin
error = 'DARKCORR must be a scalar string with the filename of the dark correction file'
if not keyword_set(silent) then print('halt: '+error)
stop
return
endif
# Check that the file exists
if file_test(darkcorr) eq 0 then begin
error = 'DARKCORR file '+darkcorr+' NOT FOUND'
if not keyword_set(silent) then print('halt: '+error)
stop
return
endif
# Read header
darkhead0 = HEADFITS(darkcorr,errmsg=errmsg0,exten=0)
darkhead1 = HEADFITS(darkcorr,errmsg=errmsg1,exten=1)
# Error reading header
if errmsg0 ne '' or errmsg1 ne '' then begin
error = errmsg0+' '+errmsg1
if not keyword_set(silent) then print('halt: '+error)
stop
return
endif
# Get number of reads
if sxpar(darkhead1,'NAXIS') eq 3 then begin
nreads_dark = sxpar(darkhead1,'NAXIS3')
endif else begin
# Extensions
# Figure out how many reads/extensions there are
# the primary unit should be empty
nreads_dark = 0
message = ''
while (message eq '') do begin
nreads_dark++
dum = HEADFITS(darkcorr,exten=nreads_dark,errmsg=message)
end
nreads_dark-- # removing the last one
endelse
# Check that it has enough reads
#nreads_dark = sxpar(darkhead,'NAXIS3')
if nreads_dark lt nreads then begin
error = 'SUPERDARK file '+darkcorr+' does not have enough READS. Have '+strtrim(nreads_dark,2)+$
' but need '+strtrim(nreads,2)
if not keyword_set(silent) then print('halt: '+error)
stop
return
endif
# Load the dark correction file
# This needs to be 2048x2048xNreads
# It's the dark counts for each pixel in counts
# Datacube
if sxpar(darkhead1,'NAXIS') eq 3 then begin
FITS_READ,darkcorr,darkcube,/no_abort
# Extensions
endif else begin
# Initializing the cube
FITS_READ,darkcorr,darkim,exthead,exten_no=1,message=message,/no_abort
szim = size(darkim)
darkcube = np.zeros((szim[1],szim[2],nreads_dark),float)
# Read in the extensions
For k=1,nreads_dark do begin
FITS_READ,darkcorr,extim,exthead,exten_no=k,message=message,/no_abort
darkcube[*,*,k-1] = extim
endelse # extensions
szdark = size(darkcube)
if not keyword_set(silent) then print('Dark Correction file = '+darkcorr)
# Check that the file looks reasonable
szdark = size(darkcube)
if (szdark[0] ne 3 or szdark[1] lt 2048 or szdark[2] ne 2048) then begin
error = 'Dark correction data must a 2048x2048xNreads datacube of the dark counts per pixel'
if not keyword_set(silent) then print('halt: '+error)
stop
return
endif
endif # loading dark correction file
return darkcube,darkhead
def loadflat(flatcorr,silent=True):
#----------------------------------
# Load FLAT FIELD CORRECTION file
#----------------------------------.
if n_elements(flatcorr) gt 0 and n_elements(flatim) eq 0 then begin
# FLATCORR must be scalar string
if size(flatcorr,/type) ne 7 or n_elements(flatcorr) ne 1 then begin
error = 'FLATCORR must be a scalar string with the filename of the flat correction file'
if not keyword_set(silent) then print('halt: '+error)
stop
return
endif
# Check that the file exists
if file_test(flatcorr) eq 0 then begin
error = 'FLATCORR file '+flatcorr+' NOT FOUND'
if not keyword_set(silent) then print('halt: '+error)
stop
return
endif
# Load the flat correction file
# This needs to be 2048x2048
FITS_READ,flatcorr,flatim,flathead,message=message,/no_abort
# Error opening file
if message ne '' then begin
error = message
if not keyword_set(silent) then print('halt: '+error)
stop
return
endif
if not keyword_set(silent) then print('Flat Field Correction file = '+flatcorr)
# Check that the file looks reasonable
szflat = size(flatim)
if (szflat[0] ne 2 or szflat[1] ne 2048 or szflat[2] ne 2048) then begin
error = 'Flat Field correction image must a 2048x2048 image'
if not keyword_set(silent) then print('halt: '+error)
stop
return
endif
endif # loading flat field correction file
return flatim,flathead
# refsub subtracts the reference array from each quadrant with proper flipping
def aprefcorr_sub(image,ref):
revref=reverse(ref)
image[0:511,*]-=ref
image[512:1023,*]-=revref
image[1024:1535,*]-=ref
image[1536:2047,*]-=revref
return image
def aprefcorr(cube,head,mask,indiv=3,vert=1,horz=1,noflip=noflip,silent=silent,
readmask=readmask,lastgood=lastgood,cds=1,plot=plot,fix=fix,q3fix=q3fix,keepref=False):
"""
This corrects a raw APOGEE datacube for the reference pixels
and reference output
Parameters:
cube The raw APOGEE datacube with reference array. This
will be updated with the reference subtracted cube.
head The header for CUBE.
indiv=n Subtract the individual reference arrays after nxn median filter. If
If <0, subtract mean reference array. If ==0, no reference array subtraction
/noflip Do not flip the reference array.
/silent Don't print anything to the screen.
Returns:
cube is updated with the reference subtracted cube to save memory.
mask The flag mask.
=readmask Mask indicating if reads are bad (0-good, 1-bad)
USAGE:
>>>aprefcorr,cube,head,mask
By J. Holtzman 2011
Incorporated into ap3dproc.pro D.Nidever May 2011
"""
# refcorr does the "bias" subtraction, using the reference array and
# the reference pixels. Subtract a mean reference array (or individual
# with /indiv), then subtract vertical ramps from each quadrant using
# reference pixels, then subtract smoothed horizontal ramps
# Number of reads
nx,ny,nread = cube.shape
# create long output
out = np.zeros((2048,2048,nread),int)
if keepref: refout = np.zeros(512,2048,nread),int)
# Ignore reference array by default
# Default is to do CDS, vertical, and horizontal correction
print('in aprefcorr, indiv: '+str(indiv))
satval = 55000
snmin = 10
if indiv>0:
hmax = 1e10
else:
hmax = 65530
if len(mask)<=1: mask=np.zeros((2048,2048),int)
readmask = np.zeros(nread,int)
if silent==False:
print('Calculating mean reference')
meanref = np.zeros((512,2048),float)
nref = np.zeros((512,2048),int)
for i in range(nread):
ref = cube[2048:2560,:,i]
m = np.mean(ref[128:512-128,128:2048-128].astype(np.float64))
s = np.std(ref[128:512-128,128:2048-128].astype(np.float64))
h = np.max(ref[128:512-128,128:2048-256])
ref[ref>=sat] = np.nan
# SLICE business is just for special fast handling, ignored if
# not in header
card = 'SLICE%03d' % i
iread = head.getval(card)
count = len(icard)
if count==0: iread=i+1
if silent==False:
print('reading ref: %3d %3d\r' % (i,iread))
# skip first read and any bad reads
if (iread > 1) and (m/s > snmin) and (h < hmax):
good, = np.where(np.isfinite(ref))
meanref[good] += (ref[good]-m)
nref[good] += 1
readmask[i] = 0
else:
print('Rejecting: ',i,m,s,h)
readmask[i] = 1
meanref /= nref
if silent == False:
print('Reference processing ')
#### DLN got to here
# Create vertical and horizontal ramp images
rows = np.arange(2048).astype(float)
cols = np.zeros(512,int)
cols += 1
vramp = (cols##rows)/2048
vrramp = 1-vramp
cols = np.arange(2048).astype(float)
rows = np.zeros(2048.int)
rows += 1
hramp = (cols##rows)/2048
hrramp = 1-hramp
clo = np.zeros(2048,float)
chi = np.zeros(2048,float)
if cds: cdsref = cube[0:2048,:,1]
# Loop over the reads
lastgood = nread-1
for iread in range(nread):
# Subtract mean reference array
red = cube[0:2048,:,iread].astype(int)
### I GOT TO HERE !!!!
sat = where(red gt satval,nsat)
if nsat gt 0 then begin
if iread eq 0 then nsat0=nsat
red[sat] = 65535
mask[sat] = (mask[sat] or maskval('SATPIX'))
# if we have a lot of saturated pixels, note this read (but don't do anything)
if nsat gt nsat0+2000 then begin
if lastgood eq nread-1 then lastgood=iread-1
endif
endif else nsat0=0
# pixels that are identically zero are bad, see these in first few reads
bad = where(red eq 0,nbad)
if nbad gt 0 then mask[bad] = (mask[bad] or maskval('BADPIX'))
if not keyword_set(silent) then $
print,format='(%"Ref processing: %3d nsat: %5d\r",$)',iread+1,n_elements(sat)
if readmask[iread] gt 0 then begin
red = !values.f_nan
goto,nextread
endif
# with cds keyword, subtract off first read before getting reference pixel values
if keyword_set(cds) then red-=cdsref
ref = cube[2048:2559,*,iread]
if indiv==1:
ref = aprefcorr_sub(red)
ref -= ref
endif else if indiv gt 1 then begin
APREFCORR_SUB,red,median(ref,indiv)
ref-=median(ref,indiv)
endif else if indiv lt 0 then begin
APREFCORR_SUB,red,meanref
ref-=meanref
endif
if keyword_set(vert) then begin
# Subtract vertical ramp
for j=0,3 do begin
#rlo=MEAN(red[j*512:(j+1)*512-1,1:3],/nan)
#rhi=MEAN(red[j*512:(j+1)*512-1,2044:2046],/nan)
rlo = MEAN(red[j*512:(j+1)*512-1,2:3],/nan)
rhi = MEAN(red[j*512:(j+1)*512-1,2045:2046],/nan)
red[j*512:(j+1)*512-1,*] -= rlo*vrramp
red[j*512:(j+1)*512-1,*] -= rhi*vramp
if keyword_set(plot) then begin
plot,rlo*vrramp[0,*]+rhi*vramp[0,*]
print,j,rlo,rhi
atv,cube[0:2047,*,iread]-cube[0:2047,*,1]
atv,red
stop
endif
endfor
endif
# Subtract smoothed horizontal ramp
if keyword_set(horz) then begin
for i=0,2047 do begin
clo[i] = MEAN(red[1:3,i],/nan)
chi[i] = MEAN(red[2044:2046,i],/nan)
endfor
#clo = total(red[1:3,*],1,/nan) / ( total(finite(red[1:3,*]),1) > 1)
#chi = total(red[2044:2046,*],1,/nan) / ( total(finite(red[2044:2046,*]),1) > 1)
sm=7
#slo = SMOOTH(clo,sm,/edge_truncate,/nan)
#shi = SMOOTH(chi,sm,/edge_truncate,/nan)
slo = medfilt1d(clo,sm,/edge)
shi = medfilt1d(chi,sm,/edge)
if keyword_set(plot) then begin
plot,slo
oplot,shi
#stop
endif
if keyword_set(noflip) then begin
red -= (rows#slo)*hrramp
red -= (rows#shi)*hramp
endif else begin
#bias = (rows#slo)*hrramp+(rows#shi)*hramp
# just use single bias value of minimum of left and right to avoid bad regions in one
bias = rows#min([[slo],[shi]],dim=2)
fbias = bias
fbias[512:1023,*] = reverse(bias[512:1023,*])
fbias[1536:2047,*] = reverse(bias[1536:2047,*])
red -= fbias
endelse
if keyword_set(plot) then begin
atv,red,min=-50,max=50
stop
endif
endif
if keyword_set(q3fix) then begin
#fix=red
q3offset = np.zeros(2048,float)
for irow=0,2047 do begin
q2m=median(red[923:1023,irow])
q3a=median(red[1024:1124,irow])
q3b=median(red[1435:1535,irow])
q4m=median(red[1536:1636,irow])
#fix[1024:1535,irow]+=((q2m-q3a)+(q4m-q3b))/2.
q3offset[irow]=((q2m-q3a)+(q4m-q3b))/2.
endfor
#plot,q3offset
#oplot,medfilt1d(q3offset,7,/edge),color=2
#red=fix
red[1024:1535,*]+=(medfilt1d(q3offset,7,/edge)##(fltarr(512)+1))
#atv,red,min=-200,max=200,/linear
#stop
endif
# Make sure saturated pixels are set to 65535
# removing the reference values could have
# bumped them lower
if nsat gt 0 then red[sat]=65535
nextread:
#reduced[*,*,iread] = red
#cube[0:2047,*,iread] = red # overwrite with the ref-subtracted image
out[*,*,iread] = red
if keyword_set(keepref) then refout[*,*,iread] = ref
endfor # read loop
# Trim off the reference array
#cube = cube[0:2047,*,*]
# mask the reference pixels
mask[0:3,*] = (mask[0:3,*] or maskval('BADPIX'))
mask[2044:2047,*] = (mask[2044:2047,*] or maskval('BADPIX'))
mask[*,0:3] = (mask[*,0:3] or maskval('BADPIX'))
mask[*,2044:2047] = (mask[*,2044:2047] or maskval('BADPIX'))
if not keyword_set(silent) then begin
print,''
print,'lastgood: ',lastgood
endif
if keyword_set(keepref) then return,[out,refout] else return,out
return cube,mask,readmask
def ap3dproc(files0,outfile,detcorr=detcorr,bpmcorr=bpmcorr,darkcorr=darkcorr,littrowcorr=littrowcorr,
persistcorr=persistcorr,persistmodelcorr=persistmodelcorr,histcorr=histcorr,
flatcorr=flatcorr,crfix=True,satfix=True,rd3satfix=rd3satfix,saturation=65000,
nfowler=nfowler,uptheramp=uptheramp,verbose=verbose,debug=debug,error=error,silent=silent,
cube=cube,head=head,output=output,crstr=crstr,satmask=satmask,criter=False,
clobber=clobber,stp=stp,cleanuprawfile=cleanuprawfile,outlong=False,refonly=refonly,
outelectrons=False,nocr=nocr,logfile=logfile,fitsdir=fitsdir,maxread=maxread,q3fix=q3fix,
usereference=usereference,seq=seq):
"""
Process a single APOGEE 3D datacube.
This is a general purpose program that takes a 3D APOGEE datacube
and processes it in various ways. It will return a 2D image.
It can remove cosmic rays, correct saturated pixels, do linearity
corrections, dark corrections, flat field correction, and reduce
the read noise with Fowler or up-the-ramp sampling.
A pixel mask and variance array are also created.
For a 2048x2048x60 datacube it currently takes ~140 seconds to
process on halo (minus read time) and ~200 seconds on stream.
Parameters:
files The filename(s) of an APOGEE chip file, e.g. apR-a-test3.fits
A compressed file can also be input (e.g. apR-a-00000033.apz)
and the file will be automatically uncompressed.
outfile The output filename.
=detcorr The filename of the detector file (containing gain,
rdnoise, and linearity correction).
=bpmcorr The filename of the bad pixel mask file.
=darkcorr The filaname of the dark correction file.
=flatcorr The filename of the flat field correction file.
=littrowcorr The filename of the Littrow ghost mask file.
=persistcorr The filename of the persistence mask file.
=persistmodelcorr The filename for the persistence model parameter file.
=histcorr The filename of the 2D exposure history cube for this night.
=crfix Fix cosmic rays. This is done by default.
If crfix=0 then cosmic rays are still detected and
flagged in the mask file, but NOT corrected.
=satfix Fix saturated pixels. This is done by default
If satfix=0 then saturated pixels are still detected
and flagged in the mask file, but NOT corrected -
instead they are set to 0. Saturated pixels that are
not fixable ("unfixable", less than 3 unsaturated reads)
are also set to 0.
=rd3satfix Fix saturated pixels for 3 reads, and assume they don't
have CRs.
=saturation The saturation level. The default is 65000
=nfowler The number of samples to use for the Fowler sampling.
The default is 10
/uptheramp Do up-the-ramp sampling instead of Fowler. Currently
this does NOT taken throughput variations into account
and is only meant for Darks and Flats
/outelectrons The output images should be in electrons instead of ADU.
The default is ADU.
/refonly Only do reference subtraction of the cube and return.
This is used for creating superdarks.
/criter Iterative CR detection. Check neighbors of pixels
with detected CRs for CRs as well using a lower
threshold. This is the default.
/clobber Overwrite output file if it already exists. clobber=0
by default.
/outlong The output files should use LONG type intead of FLOAT.
This actually takes up the same amount of space, but
this can be losslessly compressed with FPACK.
/cleanuprawfile If a compressed file is input and ap3dproc needs to
Decompress the file (no decompressed file is on disk)
then setting this keyword will delete the decompressed
file at the very end of processing. This is the default.
Set cleanuprawfile=0 if you want to keep the decompressed
file. An input decompressed FITS file will always
be kept.
/debug For debugging. Will make a plot of every pixel with a
CR or saturation showing hot it was corrected (if
that option was set) and gives more verbose output.
/verbose Verbose output to the screen.
/silent Don't print anything to the screen
Returns:
The output is a [Nx,Ny,3] datacube written to "outfile". The 3
planes are:
(1) The final Fowler (or Up-the-Ramp) sampled 2D image (in ADU) with (optional)
linearity correction, dark current correction, cosmic ray fixing,
aturated pixel fixing, and flat field correction.
(2) The variance image in ADU.
(3) A bitwise flag mask, with values meaning: 1-bad pixel, 2-CR,
4-saturated, 8-unfixable
where unfixable means that there are not enough unsaturated
reads (need at least 3) to fix the saturation.
=cube The "fixed" datacube
=head The final header
=output The final output data [Nx,Ny,3].
=crstr The Cosmic Ray structure.
=satmask The saturation mask [Nx,Ny,3], where the 1st plane is
the 0/1 mask for saturation or not, 2nd plane is
the read # at which it saturated (starting with 0), 3rd
plane is the # of saturated pixels.
USAGE:
>>>ap3dproc,'apR-a-test3.fits','ap2D-a-test3.fits'
SUBROUTINES:
ap3dproc_lincorr Does the linearity correction
ap3dproc_darkcorr Does the dark correction
ap3dproc_crfix Detects and fixes CRs
ap3dproc_plotting Plots original and fixed data for pixels
affected by CRs or saturation (for debugging
purposes)
How this program should be run for various file types:
DARK - detcorr, bpmcorr, crfix, satfix, uptheramp
FLAT - detcorr, bpmcorr, darkcorr, crfix, satfix, uptheramp
LAMP - detcorr, bpmcorr, darkcorr, flatcorr, crfix, satfix, nfowler
SCIENCE - detcorr, bpmcorr, darkcorr, flatcorr, crfix, satfix, nfowler
Potential future improvements:
-use the neighboring flux rates as a function reads to get a better
extrapolation/fixing of the saturated pixels.
-improve the up-the-ramp sampling to take the variability into
account. Need a local "throughput" curve that basically says
how the throughput changes over time. Then fit the data with
data = throughput*a*exptime + b
where a is the count rate in counts/sec and b is the kTC noise
(offset). Throughput runs from 0 to 1. It should be possible to
calculate a/b directly and not have to actually "fit" anything.
-add an /electrons keyword to output the image in electrons instead
of ADU
-when calculating the sigma of dCounts in ap3dproc_crfix.pro also
try to use an anlytical value in addition to an empirical value.
-maybe don't set unfixable pixels with 2 good reads to zero. just
assume that there is no CR.
-use reference pixels
By D.Nidever Jan 2010
"""
t00 = systime(1)
apgundef,cube,head,output,crstr,satmask
nfiles = n_elements(files0)
if keyword_set(debug):
setdisp,/silent
psym8
# No output requested
if n_elements(outfile) eq 0 and not arg_present(cube) and not arg_present(head) and
not arg_present(output) and not arg_present(crstr) and not arg_present(satmask):
error = 'No output requested'
print,error
return
noutfile = n_elements(outfile)
if n_elements(outfile) gt 0 then if noutfile ne nfiles:
error = 'OUTFILE must have same number of elements as FILES'
if not keyword_set(silent) then print,error
return
# Default parameters
if n_elements(nfowler) eq 0 and n_elements(uptheramp) eq 0 then nfowler = 10 # number of reads to use at beg and end
if n_elements(seq) eq 0 then seq='no seq'
if not keyword_set(silent):
print,'AP3DPROC Input Parameters:'
print,'Saturation = ',strtrim(long(saturation),2)
if keyword_set(crfix) then print,'Fixing Cosmic Rays' else print,'NOT Fixing Cosmic Rays'
if keyword_set(satfix) then print,'Fixing Saturated Pixels' else print,'NOT Fixing Saturated Pixels'
if keyword_set(nfowler) then print,'Using FOWLER Sampling, Nfowler='+strtrim(long(nfowler),2)
if not keyword_set(nfowler) then print,'Using UP-THE-RAMP Sampling'
if keyword_set(criter) then print,'Iterative CR detection ON' else print,'Iterative CR detection OFF'
if keyword_set(clobber) then print,'Clobber ON'
if keyword_set(outelectrons) then print,'Output will be in ELECTRONS' else print,'Output will be in ADU'
print,''
print,strtrim(nfiles,2),' File(s) input'
# File loop
#------------
for f in range(nfiles):
t0 = time.time()
ifile = files0[f]
if not keyword_set(silent):
if f gt 0 then print,''
print,strtrim(f+1,2),'/',strtrim(nfiles,2),' Filename = ',ifile
print,'----------------------------------'
# if another job is working on this file, wait
if n_elements(outfile) gt 0 then:
if getlocaldir():
lockfile=getlocaldir()+'/'+file_basename(outfile[f])+'.lock'
else:
lockfile=outfile[f]+'.lock'
while file_test(lockfile) do apwait,lockfile,10
# Test if the output file already exists
#if n_elements(outfile) gt 0 then begin
if (file_test(outfile[f]) eq 1 or file_test(outfile[f]+'.fz') eq 1) and not keyword_set(clobber):
if not keyword_set(silent) then print,'OUTFILE = ',outfile[f],' ALREADY EXISTS. Set /clobber to overwrite'
continue
# set lock to notify other jobs that this file is being worked on
openw,lock,/get_lun,lockfile
free_lun,lock
# Check the file
dir = file_dirname(ifile)
base = file_basename(ifile)
len = strlen(base)
basesplit = strsplit(base,'.',/extract)
extension = first_el(basesplit,/last)
#if strmid(base,0,4) ne 'apR-' or strmid(base,len-5,5) ne '.fits' then begin
# error = 'FILE must be of the form >>apR-a/b/c-XXXXXXXX.fits<<'
# if not keyword_set(silent) then print,error
# return
#endif
if extension ne 'fits' and extension ne 'apz':
error = 'FILE must have a ".fits" or ".apz" extension'
if not keyword_set(silent) then print,error
continue
# Compressed file input
if extension eq 'apz':
if not keyword_set(silent) then print,ifile,' is a COMPRESSED file'
# Check if the decompressed file already exists
len = strlen(base)
if keyword_set(fitsdir):
fitsfile = fitsdir+'/'+strmid(base,0,len-4)+'.fits'
else:
fitsfile = dir+'/'+strmid(base,0,len-4)+'.fits'
fitsdir=0
# Need to decompress
if file_test(fitsfile) == 0:
if not keyword_set(silent) then print,'Decompressing with APUNZIP'
id=0L
reads,strmid(base,6,8),id
if id lt 02490000L then no_checksum=1 else no_checksum=0
print,'no_checksum: ', no_checksum
APUNZIP,ifile,/clobber,error=errzip,fitsdir=fitsdir,no_checksum=no_checksum # /silent
print,''
doapunzip = 1 # we ran apunzip
# An error occurred
if n_elements(errzip) gt 0:
error = 'ERROR in APUNZIP '+errzip
if not keyword_set(silent) then print,'halt: '+error
stop
continue
# Decompressed file already exists
else:
if not keyword_set(silent) then $
print,'The decompressed file already exists'
doapunzip = 0 # we didn't run apunzip
file = fitsfile # using the decompressed FITS from now on
# Cleanup by default
if n_elements(cleanuprawfile) eq 0 and extension eq 'apz' and doapunzip eq 1 then cleanuprawfile=1 # remove recently decompressed file
# Regular FITS file input
else:
file = ifile
doapunzip = -1
if not keyword_set(silent):
if extension eq 'apz' and keyword_set(cleanuprawfile) and doapunzip eq 1 then $
print,'Removing recently decompressed FITS file at end of processing'
# Check that the file exists
if file_test(file) eq 0:
error = 'FILE '+file+' NOT FOUND'
if not keyword_set(silent) then print,'halt: '+error
stop
continue
# Get header
head = headfits(file,errmsg=errmsg)
if errmsg ne '':
error = 'There was an error loading the HEADER for '+file
if not keyword_set(silent) then print,'halt: '+error
stop
continue
# Check that this is a data CUBE
naxis = sxpar(head,'NAXIS')
FITS_READ,file,dumim,dumhead,exten_no=1,message=read_message,/no_abort
if naxis ne 3 and read_message ne '':
error = 'FILE must contain a 3D DATACUBE OR image extensions'
if not keyword_set(silent) then print,'halt: '+error
stop
continue
# Test if the output file already exists
if n_elements(outfile) gt 0:
test = file_test(outfile[f])
if test eq 1 and not keyword_set(clobber):
print,'OUTFILE = ',outfile[f],' ALREADY EXISTS. Set /clobber to overwrite.'
continue
# Read in the File
#-------------------
test = file_test(file)
if file_test(file) eq 0:
error = file+' NOT FOUND'
if not keyword_set(silent) then print,'halt: '+error
stop
continue
# DATACUBE
if naxis==3:
FITS_READ,file,cube,head,message=message,/no_abort # UINT
# Error opening file
if message ne '':
error = message
if not keyword_set(silent) then print,'halt: '+error
stop
goto,BOMB
# Extensions
else:
head = headfits(file)
# Figure out how many reads/extensions there are
# the primary unit should be empty
nreads = 0
message = ''
while (message eq ''):
nreads++
dum = headfits(file,exten=nreads,errmsg=message)
nreads-- # removing the last one
# Only 1 read
if nreads lt 2:
error = 'ONLY 1 read. Need at least two'
if not keyword_set(silent) then print,'halt: '+error
stop
goto,BOMB
# allow user to specify maximum number of reads to use (e.g., in the
# case of calibration exposures that may be overexposed in some chip
if keyword_set(maxread) then if maxread lt nreads then nreads=maxread
# Initializing the cube
FITS_READ,file,im1,exten_no=1
sz = size(im1)
#cube = uintarr(sz[1],sz[2],nreads)
cube = lonarr(sz[1],sz[2],nreads) # long is big enough and takes up less memory than float
# Read in the extensions
for k=1,nreads:
FITS_READ,file,extim,exthead,exten_no=k,message=message,/no_abort # UINT
cube[*,*,k-1] = extim
# What do we do with the extension headers???
# We could make a header structure or array
# Dimensions of the cube
sz = size(cube)
type = size(cube,/type) # UINT
nx = sz[1]
ny = sz[2]
nreads = sz[3]
chip = strtrim(sxpar(head,'CHIP'),2)
if chip eq '0':
raise ValueError('CHIP not found in header')
# File dimensions
if silent is False:
print('Data file description:')
print('Datacube size = '+str(int(nx))+' x '+str(int(ny))+' x '+str(int(nreads)))
print('Nreads = '+str(int(nreads)))
print('Chip = '+str(chip))
print('')
# Few reads
if nreads eq 2 and not keyword_set(silent) then print,'Only 2 READS. CANNOT do CR detection/fixing'
if nreads eq 2 and keyword_set(satfix) and not keyword_set(silent):
print,'Only 2 READS. CANNOT fix Saturated pixels'
# Load the detector file
XX,YY,ZZ = loaddetector(detcorr)
# Load the bad pixel mask
bpmim,bpmhead = loadbpm(bpmcorr)
# Load the littrow mask file
littrowim,littrowhead = loadlittrow(littrowcorr)
# Load the persistence file
persistim,persisthead = loadpersist(persistcorr)
# Load the dark cube
darkcube,darkhead = loaddark(darkcorr)
# Load the flat image
flatim,flathead = loadflat(flatcorr)
## I GOT TO HERE !!!!!
if n_elements(detcorr) gt 0 or n_elements(darkcorr) gt 0 or n_elements(flatcorr) gt 0 and $
not keyword_set(silent) then print,''
#---------------------
# Check for BAD READS
#---------------------
if not keyword_set(silent) then $
print,'Checking for bad reads'
# Use the reference pixels and reference output for this
if sz[1] eq 2560 then begin
refout1 = median(cube[2048:*,*,0:3<(nreads-1)],dim=3)
sig_refout_arr = np.zeros(nreads,float)
rms_refout_arr = np.zeros(nreads,float)
endif
refpix1 = [[ median(cube[0:2047,0:3,0:3<(nreads-1)],dim=3) ], $
[transpose( median(cube[0:3,*,0:3<(nreads-1)],dim=3) ) ],$
[transpose( median(cube[2044:2047,*,0:3<(nreads-1)],dim=3) ) ],$
[ median(cube[0:2047,2044:2047,0:3<(nreads-1)],dim=3) ]]
sig_refpix_arr = np.zeros(nreads,float)
rms_refpix_arr = np.zeros(nreads,float)
for k=0,nreads-1 do begin
refpix = [[cube[0:2047,0:3,k]], [transpose(cube[0:3,*,k])],$
[transpose(cube[2044:2047,*,k])], [cube[0:2047,2044:2047,k]]]
refpix = float(refpix)
# The top reference pixels are normally bad
diff_refpix = refpix - refpix1
sig_refpix = MAD(diff_refpix[*,0:11],/zero)
rms_refpix = sqrt(mean(diff_refpix[*,0:11]^2))
sig_refpix_arr[k] = sig_refpix
rms_refpix_arr[k] = rms_refpix
# Using reference pixel output (5th output)
if sz[1] eq 2560 then begin
refout = float(cube[2048:*,*,k])
# The top and bottom are bad
diff_refout = refout - refout1
sig_refout = MAD(diff_refout[*,100:1950],/zero)
rms_refout = sqrt(mean(diff_refout[*,100:1950]^2))
sig_refout_arr[k] = sig_refout
rms_refout_arr[k] = rms_refout
endif
end
# Use reference output and pixels
if sz[1] eq 2560:
if nreads>2:
med_rms_refpix_arr = MEDFILT1D(rms_refpix_arr,11<nreads,/edge)
med_rms_refout_arr = MEDFILT1D(rms_refout_arr,11<nreads,/edge)
else:
med_rms_refpix_arr = np.zeros(nreads,float)+np.median(rms_refpix_arr)
med_rms_refout_arr = np.zeros(nreads,float)+np.median(rms_refout_arr)
sig_rms_refpix_arr = mad(rms_refpix_arr) > 1
sig_rms_refout_arr = mad(rms_refout_arr) > 1
bdreads = where( (rms_refout_arr-med_rms_refout_arr) gt 10*sig_rms_refout_arr,nbdreads)
# Only use reference pixels
else:
if nreads gt 2 then begin
med_rms_refpix_arr = MEDFILT1D(rms_refpix_arr,11<nreads,/edge)
endif else begin
med_rms_refpix_arr = np.zeros(nreads,float)+np.median(rms_refpix_arr)
endelse
sig_rms_refpix_arr = mad(rms_refpix_arr) > 1
bdreads = where( (rms_refpix_arr-med_rms_refpix_arr) gt 10*sig_rms_refpix_arr,nbdreads)
if nbdreads eq 0 then apgundef,bdreads
# Too many bad reads
if nreads-nbdreads lt 2:
raise ValueError('ONLY '+str(nreads-nbdreads)+' good reads. Need at least 2.')
# Reference pixel subtraction
#----------------------------
tmp=aprefcorr(cube,head,mask,readmask=readmask,q3fix=q3fix,keepref=usereference)
cube=tmp
bdreads2 = where(readmask eq 1,nbdreads2)
if nbdreads2 gt 0 then PUSH,bdreads,bdreads2
nbdreads = n_elements(uniq(bdreads,sort(bdreads)))
if nbdreads gt (nreads-2):
raise ValueError('Not enough good reads')
gdreads = lindgen(nreads)
REMOVE,bdreads,gdreads
ngdreads = n_elements(gdreads)
# Interpolate bad reads
if nbdreads gt 0:
print('Read(s) '+strjoin(str(bdreads+1),', ')+' are bad.')
# The bad reads are currently linearly interpolated using the
# neighoring reads and used as if they were good. The variance
# needs to be corrected for this at the end.
# This will give bad results for CRs
# Use linear interpolation
for k=0,nbdreads-1:
# Get good reads below
gdbelow = where(gdreads lt bdreads[k],ngdbelow)
# Get good reads above
gdabove = where(gdreads gt bdreads[k],ngdabove)
if ngdbelow eq 0 then interp_type=1 # all above
if ngdbelow gt 0 and ngdabove gt 0 then interp_type=2 # below and above
if ngdabove eq 0 then interp_type=3 # all below
case interp_type of
# all above
1: begin
gdlo = gdabove[0]
gdhi = gdabove[1]
end
# below and above
2: begin
gdlo = first_el(gdbelow,/last)
gdhi = gdabove[0]
end
# all below
3: begin
gdlo = gdbelow[ngdbelow-2]
gdhi = gdbelow[ngdbelow-1]
end
endcase
lo = gdreads[gdlo]
hi = gdreads[gdhi]
# Linear interpolation
im1 = float(cube[*,*,lo])
im2 = float(cube[*,*,hi])
slope = (im2-im1)/float(hi-lo) # slope, (y2-y1)/(x2-x1)
zeropoint = (im1*hi-im2*lo)/(hi-lo) # zeropoint, (y1*x2-y2*x1)/(x2-x1)
im0 = slope*bdreads[k] + zeropoint # linear interpolation, y=mx+b
# Stuff it in the cube
cube[*,*,bdreads[k]] = np.round(im0) # round to closest integer, LONG type
end
endif
ny,nx = cube.shape
# Reference subtraction ONLY
if keyword_set(refonly):
if not keyword_set(silent) then print,'Reference subtraction only'
goto,BOMB
#-------------------------------------
# INTER-PIXEL CAPACITANCE CORRECTION
#-------------------------------------
# Loop through each read
# Make left, right, top, bottom images and
# use these to correct the flux for the inter-pixel capacitance
# make sure to treat the edgs and reference pixels correctly
# The "T" shape might indicate that we don't need to do the "top"
# portion
# READ NOISE
#-----------
if rdnoiseim.shape>0:
noise = np.median(rdnoiseim)
else:
noise = 12.0 # default value
noise_dCounts = noise*np.sqrt(2) # noise in dcounts
# Initialize some arrays
#------------------------
#mask = intarr(nx,ny) # CR and saturation mask
#crindex = intarr(nx,ny,10)-1 # the CR read indices get put in here
#crnum = intarr(nx,ny) # # of CRs per pixel
med_dCounts_im = np.zeros((ny,nx),float) # the median dCounts for each pixel
satmask = np.zeros((ny,nx,3),int) # 1st plane is 0/1 mask, 2nd plane is which read
# it saturated on, 3rd plane is # of
# saturated reads
variability_im = np.zeros((ny,nx),float) # fractional variability for each pixel
sat_extrap_error = np.zeros((ny,nx),float) # saturation extrapolation error
#--------------------------------------------
# PROCESS EACH SLICE (one row) ONE AT A TIME
#--------------------------------------------
# Here is the method. For each pixel find the dCounts for
# each neighboring pair of reads. Then find the median dCounts
# and the RMS (robustly). If there are any dCounts that are
# many +sigma then this is a cosmic ray. Then use the median
# dCounts around that read to correct the CR.
if not keyword_set(silent) then print,'Processing the datacube'
# Loop through the rows
for i in range(ny):
if keyword_set(verbose) or keyword_set(debug) then $
print,'Scanning Row ',strtrim(i+1,2)
if not keyword_set(silent) and not keyword_set(verbose) and not keyword_set(debug) then $
if (i+1) mod 500 eq 0 then print,i+1,'/',ny,format='(I4,A1,I4)'
# Slice of datacube, [Ncol,Nread]
#--------------------------------
slice = np.float(cube[:,i,:].flatten())
slice_orig = slice.copy() # original slice
#---------------------------------
# Flag BAD pixels
#---------------------------------
if bpmim is not None:
bdpix = where(bpmim[*,i] gt 0,nbdpix)
if nbdpix gt 0:
for j=0,nbdpix-1 do slice[bdpix[j],*] = 0.0 # set them to zero
#mask[bdpix,i] = (mask[bdpix,i] OR maskval('BADPIX'))
mask[bdpix,i] = (mask[bdpix,i] OR bpmim[bdpix,i])
#---------------------------------
# Flag LITTROW ghost pixels, but don't change data values
#---------------------------------
if littrowim is not None:
bdpix = where(littrowim[*,i] eq 1,nbdpix)
if nbdpix gt 0 then mask[bdpix,i] = (mask[bdpix,i] OR maskval('LITTROW_GHOST'))
#---------------------------------
# Flag persistence pixels, but don't change data values
#---------------------------------
if persistim is not None:
bdpix = where(persistim[*,i] and 1,nbdpix)
if nbdpix gt 0 then mask[bdpix,i] = (mask[bdpix,i] OR maskval('PERSIST_HIGH'))
bdpix = where(persistim[*,i] and 2,nbdpix)
if nbdpix gt 0 then mask[bdpix,i] = (mask[bdpix,i] OR maskval('PERSIST_MED'))
bdpix = where(persistim[*,i] and 4,nbdpix)
if nbdpix gt 0 then mask[bdpix,i] = (mask[bdpix,i] OR maskval('PERSIST_LOW'))
#---------------------------------
# Detect and Flag Saturated reads
#---------------------------------
# The saturated pixels are detected in the reference subtraction
# step and fixed to 65535.
bdsat = where(slice gt saturation,nbdsat)
if nbdsat>0:
# Flag saturated reads as NAN
slice[bdsat] = np.nan
# Get 2D indices
bdsat2d = array_indices(slice,bdsat)
bdsatx = reform(bdsat2d[0,*]) # X/column indices
bdsatr = reform(bdsat2d[1,*]) # read indices
# bdsat is 1D array for slice(2D)
# bdsatx is column index for 1D med_dCounts
# Unique pixels
uibdx = uniq(bdsatx,sort(bdsatx))
ubdsatx = bdsatx[uibdx]
nbdsatx = n_elements(ubdsatx)
# Figure out at which Read (NOT dCounts) each column saturated
rindex = (lonarr(nx)+1L)#lindgen(nreads) # each pixels read index
satmask_slice = lonarr(nx,nreads) # sat mask
satmask_slice[bdsatx,bdsatr] = 1 # set saturated reads to 1
rindexsat = rindex*satmask_slice + $ # okay pixels have 999999
(1-satmask_slice)*999999L # sat pixels have their read index
minsatread = MIN(rindexsat,dim=2) # now find the minimum for each column
nsatreads = total(satmask_slice,2) # number of sat reads
# Make sure that all subsequent reads to a saturated read are
# considered "bad" and set to NAN
for j=0,nbdsatx-1 do slice[ubdsatx[j],minsatread[ubdsatx[j]]:*]=!values.f_nan
# Update satmask
satmask[ubdsatx,i,0] = 1 # mask
satmask[ubdsatx,i,1] = minsatread[ubdsatx] # 1st saturated read, NOT dcounts
satmask[ubdsatx,i,2] = nsatreads[ubdsatx] # # of saturated reads
# Update mask
mask[ubdsatx,i] = (mask[ubdsatx,i] OR maskval('SATPIX')) # mask: 1-bad, 2-CR, 4-sat, 8-unfixable
#----------------------
# Linearity correction
#----------------------
# This needs to be done BEFORE the pixels are "fixed" because
# it needs to operate on the ORIGINAL counts, not the corrected
# ones.
if lindata is not None:
if szlin[0] eq 3 then linslice = reform(lindata[*,i,*]) else linslice=lindata
slice_orig1 = slice # temporary copy since we'll be overwriting it
slice = aplincorr(slice_orig1,linslice)
#-----------------
# Dark correction
#-----------------
# Each read will have a different amount of dark counts in it
if darkcube is not None:
darkslice = reform(darkcube[*,i,*])
slice_orig2 = slice # temporary copy since we'll be overwriting it
slice = ap3dproc_darkcorr(slice_orig2,darkslice,darkhead)
#------------------------------------------------
# Find difference of neighboring reads, dCounts
#------------------------------------------------
# a difference with 1 or 2 NaN will also be NAN
dCounts = slice[*,1:sz[3]-1] - slice[*,0:sz[3]-2]
# SHOULD I FIX BAD READS HERE?????
#----------------------------
# Detect and Fix cosmic rays
#----------------------------
slice_prefix = slice
if not keyword_set(nocr) and nreads gt 2:
dCounts_orig = dCounts # temporary copy since we'll be overwriting it
apgundef,dCounts
satmask_slice = reform(satmask[*,i,*])
crstr_slice, dCounts, med_dCounts, mask, crindex, crnum, variability_slice =
ap3dproc_crfix(dCounts_orig,satmask_slice,noise=noise,crfix=crfix):
#AP3DPROC_CRFIX,dCounts_orig,satmask_slice,dCounts,med_dCounts,crstr_slice,$
# crfix=crfix,noise=noise_dCounts,variability=variability_slice
variability_im[:,i] = variability_slice
# Only 2 reads, CANNOT detect or fix CRs
else:
med_dCounts = dCounts
crstr_slice = {NCR:0L}
# Some CRs detected, add to CRSTR structure
if crstr_slice.ncr gt 0:
crstr_slice.data.y = i # add the row information
# Add to MASK
maskpix=where(crstr_slice.data.x lt 2048,nmaskpix)
if nmaskpix gt 0 then mask[crstr_slice.data[maskpix].x,i] = $
(mask[crstr_slice.data[maskpix].x,i] OR maskval('CRPIX'))
# Starting global structure
if n_elements(crstr) eq 0:
crstr = crstr_slice
# Add to global structure
else:
ncrtot = crstr.ncr + crstr_slice.ncr
old_crstr = crstr
crstr = {NCR:ncrtot,DATA:[old_crstr.data, crstr_slice.data]}
apgundef,old_crstr
#----------------------
# Fix Saturated reads
#----------------------
# do this after CR fixing, so we don't have to worry about CRs here
# set their dCounts to med_dCounts
if nbdsat gt 0:
# Have enough reads (>2) to fix pixels
if (nreads gt 2) then begin
# Total number of good dCounts for each pixel
totgd = total(finite(dCounts),2)
# Unfixable pixels
#------------------
# Need 2 good dCounts to be able to "safely" fix a saturated pixel
thresh_dcounts = 2
if keyword_set(rd3satfix) and nreads eq 3 then thresh_dcounts=1 # fixing 3 reads
unfixable = where(totgd lt thresh_dcounts,nunfixable)
if nunfixable gt 0 then begin
dCounts[unfixable,*] = 0.0
mask[unfixable,i] = (mask[unfixable,i] OR maskval('UNFIXABLE')) # mask: 1-bad, 2-CR, 4-sat, 8-unfixable
endif
# Fixable Pixels
#-----------------
fixable = where(totgd ge thresh_dcounts and satmask[*,i,0] eq 1,nfixable)
# Loop through the fixable saturated pixels
for j=0,nfixable-1 do begin
ibdsatx = fixable[j]
# "Fix" the saturated pixels
#----------------------------
if keyword_set(satfix) then begin
# Fix the pixels
# set dCounts to med_dCounts for that pixel
#dCounts[bdsat] = med_dCounts[bdsatx]
# if the first read is saturated then we start with
# the first dCounts
dCounts[ibdsatx,(minsatread[ibdsatx]-1)>0:nreads-2] = med_dCounts[ibdsatx]
# Saturation extrapolation error
var_dCounts = variability_im[ibdsatx,i] * (med_dCounts[ibdsatx]>0.0001) # variability in dCounts
sat_extrap_error[ibdsatx,i] = var_dCounts * satmask[ibdsatx,i,2] # Sigma of extrapolated counts, multipy by Nextrap
# Do NOT fix the saturated pixels
#---------------------------------
endif else begin
dCounts[ibdsatx,minsatread[ibdsatx]-1:nreads-2] = 0.0 # set saturated dCounts to zero
endelse
endfor # loop through the fixable saturated pixels
# It might be better to use the last good value from sm_dCounts
# rather than the straight median of all reads
# Only 2 reads, can't fix anything
endif else begin
mask[ubdsatx,i] = (mask[ubdsatx,i] OR maskval('UNFIXABLE')) # mask: 1-bad, 2-CR, 4-sat, 8-unfixable
dCounts[bdsatx] = 0.0 # set saturated reads to zero
endelse
endif # some saturated pixels
#------------------------------------
# Reconstruct the SLICE from dCounts
#------------------------------------
slice0 = slice[*,0] # first read
bdsat = where(finite(slice0) eq 0,nbdsat) # NAN in first read, set to 0.0
if nbdsat gt 0 then slice0[bdsat] = 0.0
unfmask_slice = long((long(mask[*,i]) AND maskval('UNFIXABLE')) eq maskval('UNFIXABLE')) # unfixable
slice0[0:2047] = slice0[0:2047]*(1.0-unfmask_slice) # set unfixable pixels to zero
slice_fixed = slice0 # (fltarr(nreads)+1.0)
if nreads gt 2 then begin
slice_fixed[*,1:*] += TOTAL(dCounts,2,/cumulative)
endif else begin
slice_fixed[*,0] = slice0
slice_fixed[*,1] = slice0+dCounts
endelse
#--------------------------------
# Put fixed slice back into cube
#--------------------------------
cube[*,i,*] = round( slice_fixed ) # round to closest integer, LONG type
#------------------------------------
# Final median of each "fixed" pixel
#------------------------------------
if nreads gt 2 then begin
# Unfixable pixels are left at 0.0
# If NOT fixing saturated pixels, then we need to
# temporarily set saturated reads to NAN
# Leave unfixable pixels at 0.0
temp_dCounts = dCounts
if not keyword_set(satfix) then begin
bdsat = where(satmask[*,i,0] eq 1 and unfmask_slice eq 0,nbdsat)
for j=0,nbdsat-1 do $
temp_dCounts[bdsat[j],satmask[bdsat[j],i,1]-1:*] = !values.f_nan
endif
fmed_dCounts = median(temp_dCounts,dim=2,/even) # NAN are automatically ignored
bdnan = where(finite(fmed_dCounts) eq 0,nbdnan)
if nbdnan gt 0 then stop
med_dCounts_im[*,i] = fmed_dCounts
# Only 2 reads
endif else begin
med_dCounts_im[*,i] = dCounts
endelse
if keyword_set(verbose) or keyword_set(debug) then begin
nsatslice = total(satmask[*,i,0])
if n_elements(crstr) eq 0 then ncrslice=0 else dum=where(crstr.data.y eq i,ncrslice)
print,'Nsat/NCR = ',strtrim(long(nsatslice),2),'/',strtrim(long(ncrslice),2),' this row'
endif
#----------
# Plotting
#----------
#debug = 1
pltpix = where(mask[*,i] gt 1,npltpix)
if keyword_set(debug) and npltpix gt 0 then $
AP3DPROC_PLOTTING,dcounts,slice_prefix,slice_fixed,mask,crstr,i,saturation
#if i eq 623 then stop
#stop
END # loop through the rows
if n_elements(crstr) eq 0 then crstr={ncr:0L}
#------------------------
# Iterative CR Rejection
#------------------------
# Check neighbors of CRs for CRs at the same read
# lower Nsigma threshold
if keyword_set(criter) then begin
if not keyword_set(silent) then print,'Checking neighbors for CRs'
iterflag = 0
niter = 0
WHILE (iterflag ne 1) and (crstr.ncr gt 0) do begin
newcr_thisloop = 0
# CRs are left to check
crtocheck = where(crstr.data.neicheck eq 0,ncrtocheck)
# Loop through the CRs
for i=0L,ncrtocheck-1 do begin
ix = crstr.data[crtocheck[i]].x
iy = crstr.data[crtocheck[i]].y
ir = crstr.data[crtocheck[i]].read
# Look at neighboring pixels to the affected CR
# at the same read
xlo = (ix-1) > 0L
xhi = (ix+1) < (nx-1L)
ylo = (iy-1) > 0L
yhi = (iy+1) < (ny-1L)
nnei = (xhi-xlo+1)*(yhi-ylo+1) - 1
# Create a fake "slice" of the neighboring pixels
nei_slice = np.zeros((nnei,nreads),float)
nei_slice_orig = np.zeros((nnei,nreads),float) # original slice if saturated
nei_cols = np.zeros(nnei,float) # x
nei_rows = np.zeros(nnei,float) # y
nei_satmask = np.zeros((nnei,3),int)
count = 0
for j=xlo,xhi do begin
for k=ylo,yhi do begin
# Check that the read isn't saturated for this pixel and read
if satmask[j,k,0] eq 1 and satmask[j,k,1] le ir then readsat=1 else readsat=0
# Only want neighbors
if (j ne ix and k ne iy) and (readsat eq 0) then begin
nei_slice[count,*] = float( cube[j,k,*] )
nei_slice_orig[count,*] = float( cube[j,k,*] )
nei_cols[count] = j
nei_rows[count] = k
nei_satmask[count,*] = satmask[j,k,*]
# if this pixel is saturated then we need to make the saturated
# reads NAN again. The "fixed" values are in nei_slice_orig
if satmask[j,k,0] eq 1 then $
nei_slice[count,satmask[j,k,1]:nreads-1] = !values.f_nan
count++
end
end
end
# Difference of neighboring reads, dCounts
nei_dCounts = nei_slice[*,1:nreads-1] - nei_slice[*,0:nreads-2]
# Fix/detect cosmic rays
AP3DPROC_CRFIX,nei_dCounts,nei_satmask,nei_dCounts_fixed,med_nei_dCounts,nei_crstr,crfix=crfix,$
noise=noise_dCounts,sigthresh=6,onlythisread=ir
# Some new CRs detected
if nei_crstr.ncr gt 0 then begin
# Add the neighbor information
ind = nei_crstr.data.x # index in the nei slice
nei_crstr.data.x = nei_cols[ind] # actual column index
nei_crstr.data.y = nei_rows[ind] # actual row index
# Replace NANs if there were saturated pixels
bdsat = where(nei_satmask[*,0] eq 1,nbdsat)
for j=0,nbdsat-1 do begin
lr = nei_satmask[bdsat[j],1]-1 & hr=nreads-2
nei_dCounts_orig = nei_slice_orig[*,1:nreads-1] - nei_slice_orig[*,0:nreads-2] # get "original" dCounts
nei_dCounts_fixed[bdsat[j],lr:hr] = nei_dCounts_orig[bdsat[j],lr:hr] # put the original fixed valued back in
end
# Reconstruct the SLICE from dCounts
nei_slice0 = nei_slice[*,0] # first read
bdsat = where(finite(nei_slice0) eq 0,nbdsat) # set NAN in first read to 0.0
if nbdsat gt 0 then nei_slice0[bdsat] = 0.0
nei_slice_fixed = nei_slice0 # (fltarr(nreads)+1.0)
if nreads gt 2 then begin
nei_slice_fixed[*,1:*] += TOTAL(nei_dCounts_fixed,2,/cumulative)
endif else begin
nei_slice_fixed[*,0] = nei_slice0
nei_slice_fixed[*,1] = nei_slice0+nei_dCounts_fixed
endelse
# Put fixed slice back into cube
# only update new CR pixels
for j=0,nei_crstr.ncr-1 do $
cube[nei_crstr.data[j].x,nei_crstr.data[j].y,*] = round( nei_slice_fixed[ind[j],*] ) # round to integer
# Update med_dCounts_im ???
# Add to the total CRSTR
ncrtot = crstr.ncr + nei_crstr.ncr
old_crstr = crstr
crstr = {NCR:ncrtot,DATA:[old_crstr.data, nei_crstr.data]}
apgundef,old_crstr
endif # some new CRs detected
# New CRs detected
nnew = nei_crstr.ncr
newcr_thisloop += nnew
# This CR has been checked
crstr.data[crtocheck[i]].neicheck = 1 # checked!
endfor # CR loop
# Time to stop
if (newcr_thisloop eq 0) or (niter gt 5) or (ncrtocheck eq 0) then iterflag=1
niter++
ENDWHILE # CR iteration loop
end # check CR neighbors
#print,'Neighbors done'
#-------------------------------------
# INTER-PIXEL CAPACITANCE CORRECTION
#-------------------------------------
# Loop through each read
# Make left, right, top, bottom images and
# use these to correct the flux for the inter-pixel capacitance
# make sure to treat the edgs and reference pixels correctly
# The "T" shape might indicate that we don't need to do the "top"
# portion
# THIS HAS BEEN MOVED TO JUST AFTER THE REFERENCE PIXEL SUBTRACTION!!!!
# this needs to happen before dark subtraction!!
#--------------------------------
# Measure "variability" of data
#--------------------------------
# Use pixels with decent count rates
crmask = long((long(mask) AND maskval('CRPIX')) eq maskval('CRPIX'))
highpix = where(satmask[*,*,0] eq 0 and crmask eq 0 and med_dCounts_im gt 40,nhighpix)
if nhighpix eq 0 then $
highpix = where(satmask[*,*,0] eq 0 and med_dCounts_im gt 20,nhighpix)
if nhighpix gt 0 then begin
global_variability = median(variability_im[highpix],/even)
endif else begin
global_variability = -1
endelse
#-------------------------
# FLAT FIELD CORRECTION
#-------------------------
# if n_elements(flatim) gt 0 then begin
#
# # Apply the flat field to each read. Each pixel has a separate
# # kTC noise/offset, but applying the flat field before or after
# # this is removed gives IDENTICAL results.
#
# # Just divide the read image by the flat field iamge
# #for i=0,nreads-1 do cube[*,*,i] /= flatim
# for i=0,nreads-1 do cube[*,*,i] = round( cube[*,*,i] / flatim ) # keep cube LONG type
#
# # Hopefully this propogates everything to the variance
# # image properly.
#
# endif
#------------------------
# COLLAPSE THE DATACUBE
#------------------------
# No gain image, using gain=1.0 for all pixels
# gain = Electrons/ADU
if len(gainim)==0:
print('NO gain image. Using GAIN=1')
gainim = np.zeros((2048,2048),float)+1.0
# Fowler Sampling
#------------------
if uptheramp == False:
# Make sure that Nfowler isn't too large
Nfowler_used = Nfowler
if Nfowler gt Nreads/2 then Nfowler_used=Ngdreads/2
# Use the mean of Nfowler reads
# Beginning sample
gd_beg = gdreads[0:nfowler_used-1]
if n_elements(gd_beg) eq 1 then $
im_beg = cube[*,*,gd_beg]/float(Nfowler_used) else $
im_beg = total(cube[*,*,gd_beg],3)/float(Nfowler_used)
# End sample
gd_end = gdreads[ngdreads-nfowler_used:ngdreads-1]
if n_elements(gd_end) eq 1 then $
im_end = cube[*,*,gd_end]/float(Nfowler_used) else $
im_end = total(cube[*,*,gd_end],3)/float(Nfowler_used)
# The middle read will be used twice for 3 reads
# Subtract beginning from end
im = im_end - im_beg
# Noise contribution to the variance
sample_noise = noise * sqrt(2.0/Nfowler_used)
# Up-the-ramp sampling
#---------------------
else:
# For now just fit a line to each pixel
# Use median dCounts for each pixel to get the flux rate, i.e. "med_dCounts_im"
# then multiply by the exposure time.
# THIS WILL NEED TO BE IMPROVED IN THE FUTURE TO TAKE THROUGHPUT VARIATIONS
# INTO ACCOUNT. FOR NOW THIS IS JUST FOR DARKS AND FLATS
#im = med_dCounts_im * nreads
# Fit a line to the reads for each pixel
# dCounts are noisier than the actual reads by sqrt(2)
# See Rauscher et al.(2007) Eqns.3
# Calculating the slope for each pixel
# t is the exptime, s is the signal
# we will use the read index for t
sumts = np.zeros((sz[1],sz[2]),float) # SUM t*s
sums = np.zeros((sz[1],sz[2]),float) # SUM s
sum = np.zeros((sz[1],sz[2]),int) # SUM s
sumt = np.zeros((sz[1],sz[2]),float) # SUM t*s
sumt2 = np.zeros((sz[1],sz[2]),float) # SUM t*s
for k=0L,ngdreads-1:
slice = cube[*,*,gdreads[k]]
if not keyword_set(satfix):
good = where(satmask[*,*,0] eq 0 or (satmask[*,*,0] eq 1 and satmask[*,*,1] gt i),ngood)
else:
good = where(finite(slice))
#good = where(finite(slice))
sumts[good] += gdreads[k]*reform(slice[good])
sums[good] += reform(slice[good])
sum[good] += 1
sumt[good] += gdreads[k]
sumt2[good] += gdreads[k]^2
#sumt = total(findgen(nread)) # SUM t
#sumt2 = total(findgen(nread)^2) # SUM t^2
# The slope in Counts per read, similar to med_dCounts_im
#slope = (nread*sumts - sumt*sums)/(nread*sumt2 - sumt^2)
slope = (sum*sumts - sumt*sums)/(sum*sumt2 - sumt^2)
# To get the total counts just multiply by nread
im = slope * (ngdreads-1L)
# the first read doesn't really add any signal, just a zero-point
# See Equation 1 in Rauscher et al.(2007), SPIE
# with m=1
# noise and image/flux should be in electrons, sample_noise is in electrons
#sample_noise = sqrt( 12*(ngdreads-1.)/(nreads*(ngdreads+1.))*(noise*gainim)^2 + 6.*(ngdreads^2+1)/(5.*ngdreads*(ngdreads+1))*im*gainim )
sample_noise = sqrt( 12*(ngdreads-1.)/(nreads*(ngdreads+1.))*noise^2 + 6.*(ngdreads^2+1)/(5.*ngdreads*(ngdreads+1))*im[0:2047,*]*gainim )
sample_noise /= gainim # convert to ADU
# Noise contribution to the variance
# this is only valid if the variability is zero
#ngdreads = nreads - nbdreads
#sample_noise = noise / sqrt(Ngdreads)
# With userference, subtract off the reference array to reduce/remove
# crosstalk.
if keyword_set(usereference):
print,'subtracting reference array...'
tmp=im[0:2047,0:2047]
ref=im[2048:2559,0:2047]
# subtract smoothed horizontal structure
ref-=(np.zeros(512,float)+1)#medfilt1d(median(ref,dim=1),7)
aprefcorr_sub,tmp,ref
im=tmp
nx = 2048
#-----------------------------------
# Apply the Persistence Correction
#-----------------------------------
if n_elements(persistmodelcorr) gt 0 and n_elements(histcorr) gt 0:
if not keyword_set(silent) then print,'PERSIST modelcorr file = '+persistmodelcorr
APPERSISTMODEL,ifile,histcorr,persistmodelcorr,pmodelim,ppar,bpmfile=bpmcorr,error=perror
im -= pmodelim
#------------------------
# Calculate the Variance
#------------------------
# the total variance is the sum of the rdnoise and poisson noise
# poisson noise = sqrt(Counts) so variance is just Counts
# need to divide by gain^2 ??
# gain is normally in e/count
# is rdnoise normally in counts or e-??
# do "help apvariance" in IRAF and look for the noise model
#
# variance(ADU) = N(ADU)/Gain + rdnoise(ADU)^2
# Initialize varim
varim = np.zeros((nx,ny),float) # variance in ADU
# 1. Poisson Noise from the image: note that the equation for UTR
# noise above already includes Poisson term
if not keyword_set(uptheramp):
if n_elements(pmodelim) gt 0 then varim+=(im+pmodelim)/gainim > 0 else varim += im/gainim > 0
# 2. Poisson Noise from dark current
if n_elements(darkcube) gt 0:
darkim = reform(darkcube[*,*,nreads-1])
varim += darkim/gainim > 0
# 3. Sample/read noise
varim += sample_noise^2 # rdnoise reduced by the sampling
# 4. Saturation error
# We used median(dCounts) to extrapolate the saturated pixels
# Use the variability in dCounts to estimate the error of doing this
if keyword_set(satfix):
varim += sat_extrap_error # add saturation extrapolation error
else:
varim = varim*(1-satmask[*,*,0]) + satmask[*,*,0]*99999999. # saturated pixels are bad!
# Unfixable pixels
unfmask = long((long(mask) AND maskval('UNFIXABLE')) eq maskval('UNFIXABLE')) # unfixable
varim = varim*(1-unfmask) + unfmask*99999999. # unfixable pixels are bad!
# 5. CR error
# We use median of neighboring dCounts to "fix" reads with CRs
crmask = long((long(mask) AND maskval('CRPIX')) eq maskval('CRPIX'))
if crfix is True:
# loop in case there are multiple CRs per pixel
for i=0LL,crstr.ncr-1 do if crstr.data[i].x lt 2048 then $
varim[crstr.data[i].x,crstr.data[i].y]+=crstr.data[i].fixerror
else:
varim = varim*(1-crmask) + crmask*99999999. # pixels with CRs are bad!
# Bad pixels
bpmmask = long((long(mask) AND maskval('BADPIX')) eq maskval('BADPIX'))
varim = varim*(1-bpmmask) + bpmmask*99999999. # bad pixels are bad!
# Flat field
if n_elements(flatim) gt 0:
varim /= flatim^2
im /= flatim
# Now convert to ELECTRONS
if n_elements(detcorr) gt 0 and keyword_set(outelectrons):
varim *= gainim^2
im *= gainim
#----------------------------
# Construct output datacube
# [image, error, mask]
#----------------------------
if n_elements(pmodelim) gt 0 then output = np.zeros((nx,ny,4),float) else output = np.zeros((nx,ny,3),float)
output[:,:,0] = im
output[:,:,1] = np.maximum(np.sqrt(varim),1) # must be greater than zero
output[:,:,2] = mask
if len(pmodelim)>0:
output[:,:,3]=pmodelim # persistence model in ADU
#-----------------------------
# Update header
#-----------------------------
leadstr = 'AP3D: '
sxaddpar,head,'V_APRED',getvers()
sxaddhist,leadstr+systime(0),head
info = GET_LOGIN_INFO()
sxaddhist,leadstr+info.user_name+' on '+info.machine_name,head
sxaddhist,leadstr+'IDL '+!version.release+' '+!version.os+' '+!version.arch,head
sxaddhist,leadstr+' APOGEE Reduction Pipeline Version: '+getvers(),head
sxaddhist,leadstr+'Output File:',head
if n_elements(detcorr) gt 0 and keyword_set(outelectrons):
sxaddhist,leadstr+' HDU1 - image (electrons)',head
sxaddhist,leadstr+' HDU2 - error (electrons)',head
else:
sxaddhist,leadstr+' HDU1 - image (ADU)',head
sxaddhist,leadstr+' HDU2 - error (ADU)',head
sxaddhist,leadstr+' HDU3 - flag mask',head
sxaddhist,leadstr+' 1 - bad pixels',head
sxaddhist,leadstr+' 2 - cosmic ray',head
sxaddhist,leadstr+' 4 - saturated',head
sxaddhist,leadstr+' 8 - unfixable',head
if n_elements(pmodelim) gt 0:
sxaddhist,leadstr+' HDU4 - persistence correction (ADU)',head
sxaddhist,leadstr+'Global fractional variability = '+strtrim(string(global_variability,format='(F5.3)'),2),head
maxlen = 72-strlen(leadstr)
# Bad pixel mask file
if n_elements(bpmim) gt 0 then begin
line = 'BAD PIXEL MASK file="'+bpmcorr+'"'
if strlen(line) gt maxlen then begin
line1 = strmid(line,0,maxlen)
line2 = strmid(line,maxlen,100)
sxaddhist,leadstr+line1,head
sxaddhist,leadstr+line2,head
endif else sxaddhist,leadstr+line,head
end
# Detector file
if n_elements(detcorr) gt 0 then begin
line = 'DETECTOR file="'+detcorr+'"'
if strlen(line) gt maxlen then begin
line1 = strmid(line,0,maxlen)
line2 = strmid(line,maxlen,100)
sxaddhist,leadstr+line1,head
sxaddhist,leadstr+line2,head
endif else sxaddhist,leadstr+line,head
end
# Dark Correction File
if n_elements(darkcube) gt 0 then begin
line = 'Dark Current Correction file="'+darkcorr+'"'
if strlen(line) gt maxlen then begin
line1 = strmid(line,0,maxlen)
line2 = strmid(line,maxlen,100)
sxaddhist,leadstr+line1,head
sxaddhist,leadstr+line2,head
endif else sxaddhist,leadstr+line,head
endif
# Flat field Correction File
if n_elements(flatim) gt 0 then begin
line = 'Flat Field Correction file="'+flatcorr+'"'
if strlen(line) gt maxlen then begin
line1 = strmid(line,0,maxlen)
line2 = strmid(line,maxlen,100)
sxaddhist,leadstr+line1,head
sxaddhist,leadstr+line2,head
endif else sxaddhist,leadstr+line,head
endif
# Littrow ghost mask File
if n_elements(littrowim) gt 0 then begin
line = 'Littrow ghost mask file="'+littrowcorr+'"'
if strlen(line) gt maxlen then begin
line1 = strmid(line,0,maxlen)
line2 = strmid(line,maxlen,100)
sxaddhist,leadstr+line1,head
sxaddhist,leadstr+line2,head
endif else sxaddhist,leadstr+line,head
endif
# Persistence mask File
if n_elements(persistim) gt 0 then begin
line = 'Persistence mask file="'+persistcorr+'"'
if strlen(line) gt maxlen then begin
line1 = strmid(line,0,maxlen)
line2 = strmid(line,maxlen,100)
sxaddhist,leadstr+line1,head
sxaddhist,leadstr+line2,head
endif else sxaddhist,leadstr+line,head
endif
# Persistence model file
if n_elements(persistmodelcorr) gt 0 then begin
line = 'Persistence model file="'+persistmodelcorr+'"'
if strlen(line) gt maxlen then begin
line1 = strmid(line,0,maxlen)
line2 = strmid(line,maxlen,100)
sxaddhist,leadstr+line1,head
sxaddhist,leadstr+line2,head
endif else sxaddhist,leadstr+line,head
endif
# History file
if n_elements(histcorr) gt 0 then begin
line = 'Exposure history file="'+histcorr+'"'
if strlen(line) gt maxlen then begin
line1 = strmid(line,0,maxlen)
line2 = strmid(line,maxlen,100)
sxaddhist,leadstr+line1,head
sxaddhist,leadstr+line2,head
endif else sxaddhist,leadstr+line,head
endif
# Bad pixels
bpmmask = long((long(mask) AND maskval('BADPIX')) eq maskval('BADPIX'))
totbpm = total(bpmmask)
sxaddhist,leadstr+strtrim(long(totbpm),2)+' pixels are bad',head
# Cosmic Rays
crmask = where(long(mask) AND maskval('CRPIX'),totcr)
if nreads gt 2 then sxaddhist,leadstr+strtrim(long(totcr),2)+' pixels have cosmic rays',head
if keyword_set(crfix) and nreads gt 2 then sxaddhist,leadstr+'Cosmic Rays FIXED',head
# Saturated pixels
satmask = where(long(mask) AND maskval('SATPIX'),totsat)
unfmask = where(long(mask) AND maskval('UNFIXABLE'),totunf)
totfix = totsat-totunf
sxaddhist,leadstr+strtrim(long(totsat),2)+' pixels are saturated',head
if keyword_set(satfix) and nreads gt 2 then sxaddhist,leadstr+strtrim(long(totfix),2)+' saturated pixels FIXED',head
# Unfixable pixels
sxaddhist,leadstr+strtrim(long(totunf),2)+' pixels are unfixable',head
# Sampling
if keyword_set(uptheramp) then sxaddhist,leadstr+'UP-THE-RAMP Sampling',head else $
sxaddhist,leadstr+'Fowler Sampling, Nfowler='+strtrim(long(Nfowler_used),2),head
# Persistence correction factor
if n_elements(pmodelim) gt 0 and n_elements(ppar) gt 0 then begin
sxaddhist,leadstr+'Persistence correction: '+strjoin(strtrim(string(ppar,format='(G7.3)'),2),' '),head
endif
# Fix EXPTIME if necessary
if sxpar(head,'NFRAMES') ne nreads then begin
# NFRAMES is from ICC, NREAD is from bundler which should be correct
exptime = nreads*10.647 # secs
sxaddpar,head,'EXPTIME',exptime
print,'not halting, but NFRAMES does not match NREADS, NFRAMES: ', sxpar(head,'NFRAMES'), ' NREADS: ',string(format='(i8)',nreads),' ', seq
#print,'halt: NFRAMES does not match NREADS, NFRAMES: ', sxpar(head,'NFRAMES'), ' NREADS: ',string(format='(i8)',nreads),' ', seq
#stop
endif
# Add UT-MID/JD-MID to the header
jd = date2jd(sxpar(head,'DATE-OBS'))
exptime = sxpar(head,'EXPTIME')
jdmid = jd + (0.5*exptime)/24./3600.d0
utmid = jd2date(jdmid)
sxaddpar,head,'UT-MID',utmid,' Date at midpoint of exposure'
sxaddpar,head,'JD-MID',jdmid,' JD at midpoint of exposure'
# remove CHECKSUM
sxdelpar,head,'CHECKSUM'
#----------------------------------
# Output the final image and mask
#----------------------------------
if n_elements(outfile) gt 0 then begin
ioutfile = outfile[f]
# Does the output directory exist?
if file_test(file_dirname(ioutfile),/directory) eq 0 then begin
print,'Creating ',file_dirname(ioutfile)
FILE_MKDIR,file_dirname(ioutfile)
endif
# Test if the output file already exists
test = file_test(ioutfile)
if not keyword_set(silent) then print,''
if test eq 1 and keyword_set(clobber) then print,'OUTFILE = ',ioutfile,' ALREADY EXISTS. OVERWRITING'
if test eq 1 and not keyword_set(clobber) then print,'OUTFILE = ',ioutfile,' ALREADY EXISTS. '
# Writing file
if test eq 0 or keyword_set(clobber) then begin
if not keyword_set(silent) then print,'Writing output to: ',ioutfile
if keyword_set(outlong) then print,'Saving FLUX/ERR as LONG instead of FLOAT'
# HDU0 - header only
FITS_WRITE,ioutfile,0,head,/no_abort,message=write_error
# HDU1 - flux
flux = reform(output[*,*,0])
# replace NaNs with zeros
bad=where(finite(flux) eq 0,nbad)
if nbad gt 0 then flux[bad]=0.
if keyword_set(outlong) then flux=round(flux)
MKHDR,head1,flux,/image
sxaddpar,head1,'CTYPE1','Pixel'
sxaddpar,head1,'CTYPE2','Pixel'
sxaddpar,head1,'BUNIT','Flux (ADU)'
MWRFITS,flux,ioutfile,head1,/silent
# HDU2 - error
#err = sqrt(reform(output[*,*,1])) > 1 # must be greater than zero
err = errout(reform(output[*,*,1]))
if keyword_set(outlong) then err=round(err)
MKHDR,head2,err,/image
sxaddpar,head2,'CTYPE1','Pixel'
sxaddpar,head2,'CTYPE2','Pixel'
sxaddpar,head2,'BUNIT','Error (ADU)'
MWRFITS,err,ioutfile,head2,/silent
# HDU3 - mask
#flagmask = fix(reform(output[*,*,2]))
# don't go through conversion to float and back!
flagmask = fix(mask)
MKHDR,head3,flagmask,/image
sxaddpar,head3,'CTYPE1','Pixel'
sxaddpar,head3,'CTYPE2','Pixel'
sxaddpar,head3,'BUNIT','Flag Mask (bitwise)'
sxaddhist,'Explanation of BITWISE flag mask',head3
sxaddhist,' 1 - bad pixels',head3
sxaddhist,' 2 - cosmic ray',head3
sxaddhist,' 4 - saturated',head3
sxaddhist,' 8 - unfixable',head3
MWRFITS,flagmask,ioutfile,head3,/silent
#FITS_WRITE,ioutfile,output,head,/no_abort,message=write_error
#if write_error ne '' then print,'Error writing file '+write_error
# HDU4 - persistence model
if n_elements(pmodelim) gt 0 then begin
MKHDR,head4,pmodelim,/image
sxaddpar,head4,'CTYPE1','Pixel'
sxaddpar,head4,'CTYPE2','Pixel'
sxaddpar,head4,'BUNIT','Persistence correction (ADU)'
MWRFITS,pmodelim,ioutfile,head4,/silent
endif
endif
endif
# Remove the recently Decompressed file
if extension eq 'apz' and keyword_set(cleanuprawfile) and doapunzip eq 1 then begin
print,'Deleting recently decompressed file ',file
FILE_DELETE,file,/allow,/quiet
end
# Number of saturated and CR pixels
if not keyword_set(silent) then begin
print,''
print,'BAD/CR/Saturated Pixels:'
print,strtrim(long(totbpm),2),' pixels are bad'
print,strtrim(long(totcr),2),' pixels have cosmic rays'
print,strtrim(long(totsat),2),' pixels are saturated'
print,strtrim(long(totunf),2),' pixels are unfixable'
print,''
endif
file_delete,lockfile
dt = systime(1)-t0
if not keyword_set(silent) then print,'dt = ',strtrim(string(dt,format='(F10.1)'),2),' sec'
if keyword_set(logfile) then writelog,logfile,$
file_basename(file)+string(format='(f10.2,1x,i8,1x,i8,1x,i8,i8)',dt,totbpm,totcr,totsat,totunf)
BOMB:
ENDFOR # file loop
if nfiles gt 1 then begin
dt = systime(1)-t00
if not keyword_set(silent) then print,'dt = ',strtrim(string(dt,format='(F10.1)'),2),' sec'
endif
|
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE TypeFamilies #-}
-- | Provides spherical harmonic models of scalar-valued functions.
module Math.SphericalHarmonics
(
SphericalHarmonicModel
, sphericalHarmonicModel
, scaledSphericalHarmonicModel
, evaluateModel
, evaluateModelCartesian
, evaluateModelGradient
, evaluateModelGradientCartesian
, evaluateModelGradientInLocalTangentPlane
)
where
import Data.Complex
import Data.VectorSpace hiding (magnitude)
import Math.SphericalHarmonics.AssociatedLegendre
import Numeric.AD
-- | Represents a spherical harmonic model of a scalar-valued function.
data SphericalHarmonicModel a = SphericalHarmonicModel [[(a, a)]]
deriving (Functor)
-- | Creates a spherical harmonic model.
-- Result in an error if the length of the list is not a triangular number.
sphericalHarmonicModel :: (Fractional a) => [[(a, a)]] -- ^ A list of g and h coefficients for the model
-> SphericalHarmonicModel a -- ^ The spherical harmonic model
sphericalHarmonicModel cs | valid = SphericalHarmonicModel cs
| otherwise = error "The number of coefficients is not a triangular number."
where
valid = and $ zipWith (==) (fmap length cs) [1..length cs]
-- | Creates a spherical harmonic model, scaling coefficients for the supplied reference radius.
-- Result in an error if the length of the list is not a triangular number.
scaledSphericalHarmonicModel :: (Fractional a) => a -- ^ The reference radius
-> [[(a, a)]] -- ^ A list of g and h coefficients for the model
-> SphericalHarmonicModel a -- ^ The spherical harmonic model
scaledSphericalHarmonicModel r cs = sphericalHarmonicModel cs'
where
cs' = normalizeReferenceRadius r cs
instance(Fractional a, Eq a) => AdditiveGroup (SphericalHarmonicModel a) where
zeroV = SphericalHarmonicModel [[(0,0)]]
negateV = fmap negate
(SphericalHarmonicModel m1) ^+^ (SphericalHarmonicModel m2) = SphericalHarmonicModel (combineCoefficients m1 m2)
where
combineCoefficients [] cs = cs
combineCoefficients cs [] = cs
combineCoefficients (c1:cs1) (c2:cs2) = zipWith addPairs c1 c2 : combineCoefficients cs1 cs2
addPairs (g1, h1) (g2, h2) = (g1 + g2, h1 + h2)
instance (Fractional a, Eq a) => VectorSpace (SphericalHarmonicModel a) where
type Scalar (SphericalHarmonicModel a) = a
x *^ m = fmap (* x) m
normalizeReferenceRadius :: (Fractional a) => a -> [[(a, a)]] -> [[(a, a)]]
normalizeReferenceRadius r = zipWith (fmap . mapWholePair . transform) [0 :: Int ..]
where
transform n = (* (r ^ (2 + n)))
-- | Computes the scalar value of the spherical harmonic model at a specified spherical position.
evaluateModel :: (RealFloat a, Ord a) => SphericalHarmonicModel a -- ^ Spherical harmonic model
-> a -- ^ Spherical radius
-> a -- ^ Spherical colatitude (radian)
-> a -- ^ Spherical longitude (radian)
-> a -- ^ Model value
evaluateModel m r colat lon = evaluateModel' m r (cos colat) (cis lon)
-- | Computes the scalar value of the spherical harmonic model at a specified Cartesian position.
evaluateModelCartesian :: (RealFloat a, Ord a) => SphericalHarmonicModel a -- ^ Spherical harmonic model
-> a -- ^ X position
-> a -- ^ Y position
-> a -- ^ Z position
-> a -- ^ Model value
evaluateModelCartesian m x y z = evaluateModel' m r cosColat cisLon
where
r = sqrt $ (x*x) + (y*y) + (z*z)
cosColat = z / r
cisLon = normalize $ mkPolar x y
evaluateModel' :: (RealFloat a, Ord a) => SphericalHarmonicModel a
-> a -- r
-> a -- cosColat
-> Complex a -- cisLon
-> a
evaluateModel' (SphericalHarmonicModel cs) r cosColat cisLon = sum $ zipWith (*) (iterate (/ r) (recip r)) (zipWith evaluateDegree [0..] cs)
where
sines = 1 : iterate (* cisLon) cisLon
evaluateDegree n cs' = sum $ zipWith3 evaluateOrder (fmap (schmidtSemiNormalizedAssociatedLegendreFunction n) [0..n]) cs' sines
evaluateOrder p (g, h) cisMLon = ((g * realPart cisMLon) + (h * imagPart cisMLon)) * (p (cosColat))
-- | Computes the gradient of the scalar value of the spherical harmonic model, in spherical coordinates, at a specified location.
evaluateModelGradient :: (RealFloat a, Ord a) => SphericalHarmonicModel a -- ^ Spherical harmonic model
-> a -- ^ Spherical radius
-> a -- ^ Spherical colatitude (radian)
-> a -- ^ Spherical longitude (radian)
-> (a, a, a) -- ^ Radial, colatitudinal, and longitudinal components of gradient
evaluateModelGradient model r colat lon = makeTuple . fmap negate $ modelGrad [r, colat, lon]
where
modelGrad = grad (\[r', c', l'] -> evaluateModel (fmap auto model) r' c' l')
-- | Computes the gradient of the scalar value of the spherical harmonic model at a specified location, in Cartesian coordinates.
-- The result is expressed in right-handed coordinates centered at the origin of the sphere, with the positive Z-axis piercing the
-- north pole and the positive x-axis piercing the reference meridian.
evaluateModelGradientCartesian :: (RealFloat a, Ord a) => SphericalHarmonicModel a -- ^ Spherical harmonic model
-> a -- ^ X position
-> a -- ^ Y position
-> a -- ^ Z position
-> (a, a, a) -- X, Y, and Z components of gradient
evaluateModelGradientCartesian model x y z = makeTuple . fmap negate $ modelGrad [x, y, z]
where
modelGrad = grad (\[x', y', z'] -> evaluateModelCartesian (fmap auto model) x' y' z')
-- | Computes the gradient of the scalar value of the spherical harmonic model at a specified location, in Cartesian coordinates.
-- The result is expressed in a reference frame locally tangent to the sphere at the specified location.
evaluateModelGradientInLocalTangentPlane :: (RealFloat a, Ord a) => SphericalHarmonicModel a -- ^ Spherical harmonic model
-> a -- ^ Spherical radius
-> a -- ^ Spherical colatitude (radian)
-> a -- ^ Spherical longitude (radian)
-> (a, a, a) -- ^ East, North, and up components of gradient
evaluateModelGradientInLocalTangentPlane model r colat lon = (e, n, u)
where
(r', colat', lon') = evaluateModelGradient model r colat lon
e = lon' / (r * sin colat)
n = -colat' / r -- negated because the colatitude increase southward
u = r'
normalize :: (RealFloat a) => Complex a -> Complex a
normalize r@(x :+ y) | isInfinite m' = 0
| otherwise = (x * m') :+ (y * m')
where
m' = recip . magnitude $ r
mapWholePair :: (a -> b) -> (a, a) -> (b, b)
mapWholePair f (a, b) = (f a, f b)
makeTuple :: [a] -> (a, a, a)
makeTuple [x, y, z] = (x, y, z)
|
{-# OPTIONS --safe #-}
module Cubical.Algebra.CommAlgebra.FreeCommAlgebra.Properties where
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.Equiv
open import Cubical.Foundations.Isomorphism
open import Cubical.Foundations.HLevels
open import Cubical.Foundations.Structure
open import Cubical.Foundations.Function hiding (const)
open import Cubical.Foundations.Isomorphism
open import Cubical.Data.Sigma.Properties using (Σ≡Prop)
open import Cubical.HITs.SetTruncation
open import Cubical.Algebra.CommRing
open import Cubical.Algebra.CommAlgebra.FreeCommAlgebra.Base
open import Cubical.Algebra.Ring using ()
open import Cubical.Algebra.CommAlgebra
open import Cubical.Algebra.CommAlgebra.Instances.Initial
open import Cubical.Algebra.Algebra
open import Cubical.Data.Empty
open import Cubical.Data.Sigma
private
variable
ℓ ℓ' ℓ'' : Level
module Theory {R : CommRing ℓ} {I : Type ℓ'} where
open CommRingStr (snd R)
using (0r; 1r)
renaming (_·_ to _·r_; _+_ to _+r_; ·Comm to ·r-comm; ·Rid to ·r-rid)
module _ (A : CommAlgebra R ℓ'') (φ : I → ⟨ A ⟩) where
open CommAlgebraStr (A .snd)
open AlgebraTheory (CommRing→Ring R) (CommAlgebra→Algebra A)
open Construction using (var; const) renaming (_+_ to _+c_; -_ to -c_; _·_ to _·c_)
imageOf0Works : 0r ⋆ 1a ≡ 0a
imageOf0Works = 0-actsNullifying 1a
imageOf1Works : 1r ⋆ 1a ≡ 1a
imageOf1Works = ⋆-lid 1a
inducedMap : ⟨ R [ I ] ⟩ → ⟨ A ⟩
inducedMap (var x) = φ x
inducedMap (const r) = r ⋆ 1a
inducedMap (P +c Q) = (inducedMap P) + (inducedMap Q)
inducedMap (-c P) = - inducedMap P
inducedMap (Construction.+-assoc P Q S i) = +-assoc (inducedMap P) (inducedMap Q) (inducedMap S) i
inducedMap (Construction.+-rid P i) =
let
eq : (inducedMap P) + (inducedMap (const 0r)) ≡ (inducedMap P)
eq = (inducedMap P) + (inducedMap (const 0r)) ≡⟨ refl ⟩
(inducedMap P) + (0r ⋆ 1a) ≡⟨ cong
(λ u → (inducedMap P) + u)
(imageOf0Works) ⟩
(inducedMap P) + 0a ≡⟨ +-rid _ ⟩
(inducedMap P) ∎
in eq i
inducedMap (Construction.+-rinv P i) =
let eq : (inducedMap P - inducedMap P) ≡ (inducedMap (const 0r))
eq = (inducedMap P - inducedMap P) ≡⟨ +-rinv _ ⟩
0a ≡⟨ sym imageOf0Works ⟩
(inducedMap (const 0r))∎
in eq i
inducedMap (Construction.+-comm P Q i) = +-comm (inducedMap P) (inducedMap Q) i
inducedMap (P ·c Q) = inducedMap P · inducedMap Q
inducedMap (Construction.·-assoc P Q S i) = ·Assoc (inducedMap P) (inducedMap Q) (inducedMap S) i
inducedMap (Construction.·-lid P i) =
let eq = inducedMap (const 1r) · inducedMap P ≡⟨ cong (λ u → u · inducedMap P) imageOf1Works ⟩
1a · inducedMap P ≡⟨ ·Lid (inducedMap P) ⟩
inducedMap P ∎
in eq i
inducedMap (Construction.·-comm P Q i) = ·-comm (inducedMap P) (inducedMap Q) i
inducedMap (Construction.ldist P Q S i) = ·Ldist+ (inducedMap P) (inducedMap Q) (inducedMap S) i
inducedMap (Construction.+HomConst s t i) = ⋆-ldist s t 1a i
inducedMap (Construction.·HomConst s t i) =
let eq = (s ·r t) ⋆ 1a ≡⟨ cong (λ u → u ⋆ 1a) (·r-comm _ _) ⟩
(t ·r s) ⋆ 1a ≡⟨ ⋆-assoc t s 1a ⟩
t ⋆ (s ⋆ 1a) ≡⟨ cong (λ u → t ⋆ u) (sym (·Rid _)) ⟩
t ⋆ ((s ⋆ 1a) · 1a) ≡⟨ ⋆-rassoc t (s ⋆ 1a) 1a ⟩
(s ⋆ 1a) · (t ⋆ 1a) ∎
in eq i
inducedMap (Construction.0-trunc P Q p q i j) =
isSetAlgebra (CommAlgebra→Algebra A) (inducedMap P) (inducedMap Q) (cong _ p) (cong _ q) i j
module _ where
open IsAlgebraHom
inducedHom : AlgebraHom (CommAlgebra→Algebra (R [ I ])) (CommAlgebra→Algebra A)
inducedHom .fst = inducedMap
inducedHom .snd .pres0 = 0-actsNullifying _
inducedHom .snd .pres1 = imageOf1Works
inducedHom .snd .pres+ x y = refl
inducedHom .snd .pres· x y = refl
inducedHom .snd .pres- x = refl
inducedHom .snd .pres⋆ r x =
(r ⋆ 1a) · inducedMap x ≡⟨ ⋆-lassoc r 1a (inducedMap x) ⟩
r ⋆ (1a · inducedMap x) ≡⟨ cong (λ u → r ⋆ u) (·Lid (inducedMap x)) ⟩
r ⋆ inducedMap x ∎
module _ (A : CommAlgebra R ℓ'') where
open CommAlgebraStr (A .snd)
open AlgebraTheory (CommRing→Ring R) (CommAlgebra→Algebra A)
open Construction using (var; const) renaming (_+_ to _+c_; -_ to -c_; _·_ to _·c_)
Hom = CommAlgebraHom (R [ I ]) A
open IsAlgebraHom
evaluateAt : Hom → I → ⟨ A ⟩
evaluateAt φ x = φ .fst (var x)
mapRetrievable : ∀ (φ : I → ⟨ A ⟩)
→ evaluateAt (inducedHom A φ) ≡ φ
mapRetrievable φ = refl
proveEq : ∀ {X : Type ℓ''} (isSetX : isSet X) (f g : ⟨ R [ I ] ⟩ → X)
→ (var-eq : (x : I) → f (var x) ≡ g (var x))
→ (const-eq : (r : ⟨ R ⟩) → f (const r) ≡ g (const r))
→ (+-eq : (x y : ⟨ R [ I ] ⟩) → (eq-x : f x ≡ g x) → (eq-y : f y ≡ g y)
→ f (x +c y) ≡ g (x +c y))
→ (·-eq : (x y : ⟨ R [ I ] ⟩) → (eq-x : f x ≡ g x) → (eq-y : f y ≡ g y)
→ f (x ·c y) ≡ g (x ·c y))
→ (-eq : (x : ⟨ R [ I ] ⟩) → (eq-x : f x ≡ g x)
→ f (-c x) ≡ g (-c x))
→ f ≡ g
proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i (var x) = var-eq x i
proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i (const x) = const-eq x i
proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i (x +c y) =
+-eq x y
(λ i → proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i x)
(λ i → proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i y)
i
proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i (-c x) =
-eq x ((λ i → proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i x)) i
proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i (x ·c y) =
·-eq x y
(λ i → proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i x)
(λ i → proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i y)
i
proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i (Construction.+-assoc x y z j) =
let
rec : (x : ⟨ R [ I ] ⟩) → f x ≡ g x
rec x = (λ i → proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i x)
a₀₋ : f (x +c (y +c z)) ≡ g (x +c (y +c z))
a₀₋ = +-eq _ _ (rec x) (+-eq _ _ (rec y) (rec z))
a₁₋ : f ((x +c y) +c z) ≡ g ((x +c y) +c z)
a₁₋ = +-eq _ _ (+-eq _ _ (rec x) (rec y)) (rec z)
a₋₀ : f (x +c (y +c z)) ≡ f ((x +c y) +c z)
a₋₀ = cong f (Construction.+-assoc x y z)
a₋₁ : g (x +c (y +c z)) ≡ g ((x +c y) +c z)
a₋₁ = cong g (Construction.+-assoc x y z)
in isSet→isSet' isSetX a₀₋ a₁₋ a₋₀ a₋₁ j i
proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i (Construction.+-rid x j) =
let
rec : (x : ⟨ R [ I ] ⟩) → f x ≡ g x
rec x = (λ i → proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i x)
a₀₋ : f (x +c (const 0r)) ≡ g (x +c (const 0r))
a₀₋ = +-eq _ _ (rec x) (const-eq 0r)
a₁₋ : f x ≡ g x
a₁₋ = rec x
a₋₀ : f (x +c (const 0r)) ≡ f x
a₋₀ = cong f (Construction.+-rid x)
a₋₁ : g (x +c (const 0r)) ≡ g x
a₋₁ = cong g (Construction.+-rid x)
in isSet→isSet' isSetX a₀₋ a₁₋ a₋₀ a₋₁ j i
proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i (Construction.+-rinv x j) =
let
rec : (x : ⟨ R [ I ] ⟩) → f x ≡ g x
rec x = (λ i → proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i x)
a₀₋ : f (x +c (-c x)) ≡ g (x +c (-c x))
a₀₋ = +-eq x (-c x) (rec x) (-eq x (rec x))
a₁₋ : f (const 0r) ≡ g (const 0r)
a₁₋ = const-eq 0r
a₋₀ : f (x +c (-c x)) ≡ f (const 0r)
a₋₀ = cong f (Construction.+-rinv x)
a₋₁ : g (x +c (-c x)) ≡ g (const 0r)
a₋₁ = cong g (Construction.+-rinv x)
in isSet→isSet' isSetX a₀₋ a₁₋ a₋₀ a₋₁ j i
proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i (Construction.+-comm x y j) =
let
rec : (x : ⟨ R [ I ] ⟩) → f x ≡ g x
rec x = (λ i → proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i x)
a₀₋ : f (x +c y) ≡ g (x +c y)
a₀₋ = +-eq x y (rec x) (rec y)
a₁₋ : f (y +c x) ≡ g (y +c x)
a₁₋ = +-eq y x (rec y) (rec x)
a₋₀ : f (x +c y) ≡ f (y +c x)
a₋₀ = cong f (Construction.+-comm x y)
a₋₁ : g (x +c y) ≡ g (y +c x)
a₋₁ = cong g (Construction.+-comm x y)
in isSet→isSet' isSetX a₀₋ a₁₋ a₋₀ a₋₁ j i
proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i (Construction.·-assoc x y z j) =
let
rec : (x : ⟨ R [ I ] ⟩) → f x ≡ g x
rec x = (λ i → proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i x)
a₀₋ : f (x ·c (y ·c z)) ≡ g (x ·c (y ·c z))
a₀₋ = ·-eq _ _ (rec x) (·-eq _ _ (rec y) (rec z))
a₁₋ : f ((x ·c y) ·c z) ≡ g ((x ·c y) ·c z)
a₁₋ = ·-eq _ _ (·-eq _ _ (rec x) (rec y)) (rec z)
a₋₀ : f (x ·c (y ·c z)) ≡ f ((x ·c y) ·c z)
a₋₀ = cong f (Construction.·-assoc x y z)
a₋₁ : g (x ·c (y ·c z)) ≡ g ((x ·c y) ·c z)
a₋₁ = cong g (Construction.·-assoc x y z)
in isSet→isSet' isSetX a₀₋ a₁₋ a₋₀ a₋₁ j i
proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i (Construction.·-lid x j) =
let
rec : (x : ⟨ R [ I ] ⟩) → f x ≡ g x
rec x = (λ i → proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i x)
a₀₋ : f ((const 1r) ·c x) ≡ g ((const 1r) ·c x)
a₀₋ = ·-eq _ _ (const-eq 1r) (rec x)
a₁₋ : f x ≡ g x
a₁₋ = rec x
a₋₀ : f ((const 1r) ·c x) ≡ f x
a₋₀ = cong f (Construction.·-lid x)
a₋₁ : g ((const 1r) ·c x) ≡ g x
a₋₁ = cong g (Construction.·-lid x)
in isSet→isSet' isSetX a₀₋ a₁₋ a₋₀ a₋₁ j i
proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i (Construction.·-comm x y j) =
let
rec : (x : ⟨ R [ I ] ⟩) → f x ≡ g x
rec x = (λ i → proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i x)
a₀₋ : f (x ·c y) ≡ g (x ·c y)
a₀₋ = ·-eq _ _ (rec x) (rec y)
a₁₋ : f (y ·c x) ≡ g (y ·c x)
a₁₋ = ·-eq _ _ (rec y) (rec x)
a₋₀ : f (x ·c y) ≡ f (y ·c x)
a₋₀ = cong f (Construction.·-comm x y)
a₋₁ : g (x ·c y) ≡ g (y ·c x)
a₋₁ = cong g (Construction.·-comm x y)
in isSet→isSet' isSetX a₀₋ a₁₋ a₋₀ a₋₁ j i
proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i (Construction.ldist x y z j) =
let
rec : (x : ⟨ R [ I ] ⟩) → f x ≡ g x
rec x = (λ i → proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i x)
a₀₋ : f ((x +c y) ·c z) ≡ g ((x +c y) ·c z)
a₀₋ = ·-eq (x +c y) z
(+-eq _ _ (rec x) (rec y))
(rec z)
a₁₋ : f ((x ·c z) +c (y ·c z)) ≡ g ((x ·c z) +c (y ·c z))
a₁₋ = +-eq _ _ (·-eq _ _ (rec x) (rec z)) (·-eq _ _ (rec y) (rec z))
a₋₀ : f ((x +c y) ·c z) ≡ f ((x ·c z) +c (y ·c z))
a₋₀ = cong f (Construction.ldist x y z)
a₋₁ : g ((x +c y) ·c z) ≡ g ((x ·c z) +c (y ·c z))
a₋₁ = cong g (Construction.ldist x y z)
in isSet→isSet' isSetX a₀₋ a₁₋ a₋₀ a₋₁ j i
proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i (Construction.+HomConst s t j) =
let
rec : (x : ⟨ R [ I ] ⟩) → f x ≡ g x
rec x = (λ i → proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i x)
a₀₋ : f (const (s +r t)) ≡ g (const (s +r t))
a₀₋ = const-eq (s +r t)
a₁₋ : f (const s +c const t) ≡ g (const s +c const t)
a₁₋ = +-eq _ _ (const-eq s) (const-eq t)
a₋₀ : f (const (s +r t)) ≡ f (const s +c const t)
a₋₀ = cong f (Construction.+HomConst s t)
a₋₁ : g (const (s +r t)) ≡ g (const s +c const t)
a₋₁ = cong g (Construction.+HomConst s t)
in isSet→isSet' isSetX a₀₋ a₁₋ a₋₀ a₋₁ j i
proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i (Construction.·HomConst s t j) =
let
rec : (x : ⟨ R [ I ] ⟩) → f x ≡ g x
rec x = (λ i → proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i x)
a₀₋ : f (const (s ·r t)) ≡ g (const (s ·r t))
a₀₋ = const-eq (s ·r t)
a₁₋ : f (const s ·c const t) ≡ g (const s ·c const t)
a₁₋ = ·-eq _ _ (const-eq s) (const-eq t)
a₋₀ : f (const (s ·r t)) ≡ f (const s ·c const t)
a₋₀ = cong f (Construction.·HomConst s t)
a₋₁ : g (const (s ·r t)) ≡ g (const s ·c const t)
a₋₁ = cong g (Construction.·HomConst s t)
in isSet→isSet' isSetX a₀₋ a₁₋ a₋₀ a₋₁ j i
proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i (Construction.0-trunc x y p q j k) =
let
P : (x : ⟨ R [ I ] ⟩) → f x ≡ g x
P x i = proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i x
Q : (x : ⟨ R [ I ] ⟩) → f x ≡ g x
Q x i = proveEq isSetX f g var-eq const-eq +-eq ·-eq -eq i x
in isOfHLevel→isOfHLevelDep 2
(λ z → isProp→isSet (isSetX (f z) (g z))) _ _
(cong P p)
(cong Q q)
(Construction.0-trunc x y p q) j k i
homRetrievable : ∀ (f : Hom)
→ inducedMap A (evaluateAt f) ≡ fst f
homRetrievable f =
proveEq
(isSetAlgebra (CommAlgebra→Algebra A))
(inducedMap A (evaluateAt f))
(λ x → f $a x)
(λ x → refl)
(λ r → r ⋆ 1a ≡⟨ cong (λ u → r ⋆ u) (sym f.pres1) ⟩
r ⋆ (f $a (const 1r)) ≡⟨ sym (f.pres⋆ r _) ⟩
f $a (const r ·c const 1r) ≡⟨ cong (λ u → f $a u) (sym (Construction.·HomConst r 1r)) ⟩
f $a (const (r ·r 1r)) ≡⟨ cong (λ u → f $a (const u)) (·r-rid r) ⟩
f $a (const r) ∎)
(λ x y eq-x eq-y →
ι (x +c y) ≡⟨ refl ⟩
(ι x + ι y) ≡⟨ cong (λ u → u + ι y) eq-x ⟩
((f $a x) + ι y) ≡⟨
cong (λ u → (f $a x) + u) eq-y ⟩
((f $a x) + (f $a y)) ≡⟨ sym (f.pres+ _ _) ⟩ (f $a (x +c y)) ∎)
(λ x y eq-x eq-y →
ι (x ·c y) ≡⟨ refl ⟩
ι x · ι y ≡⟨ cong (λ u → u · ι y) eq-x ⟩
(f $a x) · (ι y) ≡⟨ cong (λ u → (f $a x) · u) eq-y ⟩
(f $a x) · (f $a y) ≡⟨ sym (f.pres· _ _) ⟩
f $a (x ·c y) ∎)
(λ x eq-x →
ι (-c x) ≡⟨ refl ⟩
- ι x ≡⟨ cong (λ u → - u) eq-x ⟩
- (f $a x) ≡⟨ sym (f.pres- x) ⟩
f $a (-c x) ∎)
where
ι = inducedMap A (evaluateAt f)
module f = IsAlgebraHom (f .snd)
evaluateAt : {R : CommRing ℓ} {I : Type ℓ'} (A : CommAlgebra R ℓ'')
(f : CommAlgebraHom (R [ I ]) A)
→ (I → fst A)
evaluateAt A f x = f $a (Construction.var x)
inducedHom : {R : CommRing ℓ} {I : Type ℓ'} (A : CommAlgebra R ℓ'')
(φ : I → fst A )
→ CommAlgebraHom (R [ I ]) A
inducedHom A φ = Theory.inducedHom A φ
homMapIso : {R : CommRing ℓ} {I : Type ℓ} (A : CommAlgebra R ℓ')
→ Iso (CommAlgebraHom (R [ I ]) A) (I → (fst A))
Iso.fun (homMapIso A) = evaluateAt A
Iso.inv (homMapIso A) = inducedHom A
Iso.rightInv (homMapIso A) = λ ϕ → Theory.mapRetrievable A ϕ
Iso.leftInv (homMapIso {R = R} {I = I} A) =
λ f → Σ≡Prop (λ f → isPropIsCommAlgebraHom {M = R [ I ]} {N = A} f)
(Theory.homRetrievable A f)
homMapPath : {R : CommRing ℓ} {I : Type ℓ} (A : CommAlgebra R ℓ')
→ CommAlgebraHom (R [ I ]) A ≡ (I → fst A)
homMapPath A = isoToPath (homMapIso A)
module _ {R : CommRing ℓ} {A B : CommAlgebra R ℓ''} where
open AlgebraHoms
A′ = CommAlgebra→Algebra A
B′ = CommAlgebra→Algebra B
R′ = (CommRing→Ring R)
ν : AlgebraHom A′ B′ → (⟨ A ⟩ → ⟨ B ⟩)
ν φ = φ .fst
{-
Hom(R[I],A) → (I → A)
↓ ↓
Hom(R[I],B) → (I → B)
-}
naturalR : {I : Type ℓ'} (ψ : CommAlgebraHom A B)
(f : CommAlgebraHom (R [ I ]) A)
→ (fst ψ) ∘ evaluateAt A f ≡ evaluateAt B (ψ ∘a f)
naturalR ψ f = refl
{-
Hom(R[I],A) → (I → A)
↓ ↓
Hom(R[J],A) → (J → A)
-}
naturalL : {I J : Type ℓ'} (φ : J → I)
(f : CommAlgebraHom (R [ I ]) A)
→ (evaluateAt A f) ∘ φ
≡ evaluateAt A (f ∘a (inducedHom (R [ I ]) (λ x → Construction.var (φ x))))
naturalL φ f = refl
module _ {R : CommRing ℓ} where
{-
Prove that the FreeCommAlgebra over R on zero generators is
isomorphic to the initial R-Algebra - R itsself.
-}
freeOn⊥ : CommAlgebraEquiv (R [ ⊥ ]) (initialCAlg R)
freeOn⊥ =
equivByInitiality
R (R [ ⊥ ])
{- Show that R[⊥] has the universal property of the
initial R-Algbera and conclude that those are isomorphic -}
λ B → let to : CommAlgebraHom (R [ ⊥ ]) B → (⊥ → fst B)
to = evaluateAt B
from : (⊥ → fst B) → CommAlgebraHom (R [ ⊥ ]) B
from = inducedHom B
from-to : (x : _) → from (to x) ≡ x
from-to x =
Σ≡Prop (λ f → isPropIsCommAlgebraHom {M = R [ ⊥ ]} {N = B} f)
(Theory.homRetrievable B x)
equiv : CommAlgebraHom (R [ ⊥ ]) B ≃ (⊥ → fst B)
equiv =
isoToEquiv
(iso to from (λ x → isContr→isOfHLevel 1 isContr⊥→A _ _) from-to)
in isOfHLevelRespectEquiv 0 (invEquiv equiv) isContr⊥→A
|
[STATEMENT]
lemma PO_refines_from_refines:
"refines R pi Sa Sc \<Longrightarrow> PO_refines R Sa Sc"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. refines R pi Sa Sc \<Longrightarrow> PO_refines R Sa Sc
[PROOF STEP]
by (simp add: refines_def)
|
#include <boost/bimap.hpp>
#include <string>
#include <unordered_map>
#include "sql/Expr.h"
#include "sql/SelectStatement.h"
#include "all_type_variant.hpp"
#include "expression/function_expression.hpp"
#include "types.hpp"
namespace opossum {
enum class EncodingType : uint8_t;
enum class VectorCompressionType : uint8_t;
enum class AggregateFunction;
enum class ExpressionType;
extern const boost::bimap<AggregateFunction, std::string> aggregate_function_to_string;
extern const boost::bimap<FunctionType, std::string> function_type_to_string;
extern const boost::bimap<DataType, std::string> data_type_to_string;
extern const boost::bimap<EncodingType, std::string> encoding_type_to_string;
extern const boost::bimap<VectorCompressionType, std::string> vector_compression_type_to_string;
std::ostream& operator<<(std::ostream& stream, AggregateFunction aggregate_function);
std::ostream& operator<<(std::ostream& stream, FunctionType function_type);
std::ostream& operator<<(std::ostream& stream, DataType data_type);
std::ostream& operator<<(std::ostream& stream, EncodingType encoding_type);
std::ostream& operator<<(std::ostream& stream, VectorCompressionType vector_compression_type);
} // namespace opossum
|
Require Import Tweetnacl.Libs.Export.
Require Export Tweetnacl.Gen.Get_abcdef.
Definition get_m (c:(list Z * list Z)) : list Z := match c with
(m,t) => m
end.
Definition get_t (c:(list Z * list Z)) : list Z := match c with
(m,t) => t
end.
Lemma get_a_length : forall (a b c d e f:list Z), length (get_a (a,b,c,d,e,f)) = length a. Proof. go. Qed.
Lemma get_b_length : forall (a b c d e f:list Z), length (get_b (a,b,c,d,e,f)) = length b. Proof. go. Qed.
Lemma get_c_length : forall (a b c d e f:list Z), length (get_c (a,b,c,d,e,f)) = length c. Proof. go. Qed.
Lemma get_d_length : forall (a b c d e f:list Z), length (get_d (a,b,c,d,e,f)) = length d. Proof. go. Qed.
Lemma get_e_length : forall (a b c d e f:list Z), length (get_e (a,b,c,d,e,f)) = length e. Proof. go. Qed.
Lemma get_f_length : forall (a b c d e f:list Z), length (get_f (a,b,c,d,e,f)) = length f. Proof. go. Qed.
Lemma get_m_length : forall m t, length (get_m (m,t)) = length m. Proof. go. Qed.
Lemma get_t_length : forall m t, length (get_t (m,t)) = length t. Proof. go. Qed.
Open Scope Z.
Lemma get_a_Zlength : forall (a b c d e f:list Z), Zlength (get_a (a,b,c,d,e,f)) = Zlength a. Proof. go. Qed.
Lemma get_b_Zlength : forall (a b c d e f:list Z), Zlength (get_b (a,b,c,d,e,f)) = Zlength b. Proof. go. Qed.
Lemma get_c_Zlength : forall (a b c d e f:list Z), Zlength (get_c (a,b,c,d,e,f)) = Zlength c. Proof. go. Qed.
Lemma get_d_Zlength : forall (a b c d e f:list Z), Zlength (get_d (a,b,c,d,e,f)) = Zlength d. Proof. go. Qed.
Lemma get_e_Zlength : forall (a b c d e f:list Z), Zlength (get_e (a,b,c,d,e,f)) = Zlength e. Proof. go. Qed.
Lemma get_f_Zlength : forall (a b c d e f:list Z), Zlength (get_f (a,b,c,d,e,f)) = Zlength f. Proof. go. Qed.
Lemma get_m_Zlength : forall m t, Zlength (get_m (m,t)) = Zlength m. Proof. go. Qed.
Lemma get_t_Zlength : forall m t, Zlength (get_t (m,t)) = Zlength t. Proof. go. Qed.
Close Scope Z.
|
WASHINGTON (August 2, 2011) — President Barack Obama on Tuesday nominated Miranda Mai Du to serve on the U.S. District Court for the District of Nevada. If confirmed, Ms. Du would be only the third Asian Pacific American in U.S. history to serve as an Article III judge outside of the east and west coasts. She would also become the first-ever Asian Pacific American to serve as an Article III judge in Nevada.
The National Asian Pacific American Bar Association, the national association of Asian Pacific American attorneys, judges, law professors and law students, representing the interests of over 40,000 attorneys and 62 local Asian Pacific American bar associations, applauded the president for his selection of Du.
The U.S. Census reports a growing Asian Pacific American population in Nevada. In 2010, the Asian Pacific American community in Nevada had grown to approximately nine percent of the population. Of the 139 active Article III judgeships in the Ninth Circuit, of which Nevada is a member, only 10 are currently Asian Pacific Americans and none serve in Nevada.
Since 1994, Ms. Du has practiced with the firm of McDonald Carano Wilson LLP in Reno, Nevada, where she is a partner. She is the Chair of the Employment & Labor Law group, and her practice focuses on litigating employment and complex civil cases.
She was included in Mountain States Rising Stars, Super Lawyers in 2009, selected as a “Top 20 under 40” Young Professionals in the Reno-Tahoe Area in 2008, and nominated as a Woman of Achievement by the Nevada Women’s Fund in 2007.
Ms. Du has also served as a Commissioner on the Nevada Commission on Economic Development since 2008. She graduated from the University of California-Berkeley (Boalt Hall) in 1994, and from the University of California-Davis with Honors in 1991.
Ms. Du left Vietnam with her family by boat when she was eight years old, and immigrated to Alabama after spending a year in refugee camps in Malaysia.
NAPABA and AAJC join in thanking President Obama for nominating Ms. Du and Senate Majority Leader Harry Reid for recommending her to the President.
As of recent events , I can only believe you got your position to show equal rights .Or you would not turn a deaf ear to the Mustangs again !Perhaps you are I’ll informed too young ,or have no heart , ears &eyes .Some feel you are being bribed .Not expected ,am sure ! I truly believe that you should stop these auctions ,, or GO LOOK AT THE PROCESS AUCTION -TRANSPORT, BRUTALLY , AND THE SLAUGHTER START TO FINISH .BEFORE YOU ALLOW THIS TO HAPPEN AGAIN !!!!Some of us were able to save some but not all.SHAMEFUL PLEASE LISTEN !!!!
After events of recent, concerning mustangs , I feel you must of got your position as a part of equal rights , thus leaving you too inexperienced.Please let it not be that you have no heart , eyes or ears for this subject .Many think you are being bribed ! Bet you never thought that would happen .Well , before you keep letting horses be sold , YOU SHOULD GO DOWN , LOOK WITNESS FROM AUCTION TO SLAUGHTER AND ACTUAL SLAUGHTER , until then I believe you won’t bother yourself to get properly informed !!!
I believe it is sad and shameful that Judge Miranda Du lifted the ban to round up wild horses. How can she do this, has she seen what they do to these horses? The mother horses being seperated from their babies? It’s unbelievable that a woman could allow this to happen. Unconscionable. Shameful.
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% A clean template for an academic CV
%
% Uses tabularx to create two column entries (date and job/edu/citation).
% Defines commands to make adding entries simpler.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass[11pt, a4paper]{article}
% Full Unicode support for non-ASCII characters
\usepackage[utf8]{inputenc}
% Useful aliases
\newcommand{\TUKL}{Technical University of Kaiserslautern}
\newcommand{\MPIE}{Max-Planck-Institut f\"ur Eisenforschung}
% Identifying information
\newcommand{\Title}{Curriculum Vit\ae}
\newcommand{\FirstName}{Jan}
\newcommand{\LastName}{Janssen}
\newcommand{\Initials}{J}
\newcommand{\MyName}{\FirstName\ \LastName}
\newcommand{\Me}{\textbf{\Initials. \LastName}} % For citations
\newcommand{\Email}{[email protected]}
\newcommand{\PersonalWebsite}{jan-janssen.com}
\newcommand{\LabWebsite}{lanl.gov}
\newcommand{\Affiliation}{Theoretical Division \\ Los Alamos National Laboratory}
\newcommand{\ORCID}{0000-0001-9948-7119}
\newcommand{\Address}{
Bikini Atoll Rd., SM 30 \\ Los Alamos, NM 87545, USA
}
% Names for citing coauthors
\newcommand{\JN}{J. Neugebauer}
\newcommand{\RD}{R. Drautz}
\newcommand{\YL}{Y. Lysogorskiy}
\newcommand{\MT}{M. Todorova}
% Template configuration
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Disable hyphenation
\usepackage[none]{hyphenat}
% Control the font size
\usepackage{anyfontsize}
% Icon fonts (requires using xelatex or luatex)
\usepackage[fixed]{fontawesome5}
\usepackage{academicons}
% Template variables for styling
\newcommand{\TablePad}{\vspace{-0.4cm}}
\newcommand{\SoftwareTitle}[1]{{\bfseries #1}}
\newcommand{\TableTitle}[1]{{\fontsize{12pt}{0}\selectfont \itshape #1}}
% For fancy and multipage tables
\usepackage{tabularx}
\usepackage{ltablex}
% Define a new environment to place all CV entries in a 2-column table.
% Left column are the dates, right column the entries.
\usepackage{environ}
\NewEnviron{EntriesTable}{
\TablePad
\begin{tabularx}{\textwidth}{@{}p{0.12\textwidth}@{\hspace{0.02\textwidth}}p{0.86\textwidth}@{}}
\BODY
\end{tabularx}
}
% Macros to add links and mark publications
\newcommand{\DOI}[1]{doi:\href{https://doi.org/#1}{#1}}
\newcommand{\DOILink}[1]{\href{https://doi.org/#1}{doi.org/#1}}
\newcommand{\Preprint}[1]{\newline • Preprint: \faFilePdf\ \DOILink{#1}}
\newcommand{\Youtube}[1]{\newline • Recording: \faYoutube\, \href{https://www.youtube.com/watch?v=#1}{youtube.com/watch?v=#1}}
\newcommand{\GitHub}[1]{\newline • Code: \faGithub\ \href{https://github.com/#1}{#1}}
\newcommand{\Role}[1]{\newline • Role: #1}
\newcommand{\Website}[1]{\newline • Website: \href{https://#1}{#1}}
\newcommand{\Slides}[1]{\newline • Slides: \faTv\ \href{https://#1}{#1}}
\newcommand{\SlidesDOI}[1]{\newline • Slides: \faTv\ \DOILink{#1}}
\newcommand{\PosterDOI}[1]{\newline • Poster: \faImage\ \DOILink{#1}}
\newcommand{\OA}{\aiOpenAccess\enspace}
\newcommand{\Invited}{\newline • \textbf{Invited talk}}
% Macros to set the year and duration on the left column
\newcommand{\Duration}[2]{\fontsize{10pt}{0}\selectfont #1 -- #2}
\newcommand{\Year}[1]{\fontsize{10pt}{0}\selectfont #1}
\newcommand{\Ongoing}{present}
%\newcommand{\Ongoing}{$\ast$}
\newcommand{\Future}{future}
\newcommand{\Review}{in review}
\newcommand{\Accepted}{accepted}
\newcommand{\Appointment}[4]{\textbf{#1} \newline #2 \newline #3 \newline #4}
% Define command to insert month name and year as date
\usepackage{datetime}
\newdateformat{monthyear}{\monthname[\THEMONTH], \THEYEAR}
% Set the page margins
\usepackage[a4paper,margin=1.5cm,includehead,headsep=5mm]{geometry}
% To get the total page numbers (\pageref{LastPage})
\usepackage{lastpage}
% No indentation
\setlength\parindent{0cm}
% Increase the line spacing
\renewcommand{\baselinestretch}{1.1}
% and the spacing between rows in tables
\renewcommand{\arraystretch}{1.5}
% Remove space between items in itemize and enumerate
\usepackage{enumitem}
\setlist{nosep}
% Use custom colors
\usepackage[usenames,dvipsnames]{xcolor}
% Set fonts. Requires compilation with xelatex
\usepackage{fontspec} % required to make older xelatex compile with UTF8
% Configure the font style for sections
\usepackage{sectsty}
\sectionfont{\vspace{0.5cm}\bfseries\fontsize{12pt}{0}\selectfont\uppercase}
\subsectionfont{\vspace{0.2cm}\mdseries\fontsize{12pt}{0}\selectfont\uppercase}
% Set the spacing for sections
%\usepackage{titlesec}
%\titlespacing{\section}{0pt}{0cm}{0.3cm}
%\titlespacing{\subsection}{0pt}{0.3cm}{0.3cm}
% Disable number of sections. Use this instead of "section*" so that the sections still
% appear as PDF bookmarks. Otherwise, would have to add the table of contents entries
% manually.
\makeatletter
\renewcommand{\@seccntformat}[1]{}
\makeatother
% Set fancy headers
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
\chead{
\fontsize{10pt}{12pt}\selectfont
\MyName
\hspace{0.2cm} -- \hspace{0.2cm}
\Title
\hspace{0.2cm} -- \hspace{0.2cm}
\monthyear\today
}
\rhead{\fontsize{10pt}{0}\selectfont \thepage/\pageref*{LastPage}}
\renewcommand{\headrulewidth}{0pt}
% Metadata for the PDF output and control of hyperlinks
\usepackage[colorlinks=true]{hyperref}
\hypersetup{
pdftitle={\MyName\ - \Title},
pdfauthor={\MyName},
linkcolor=blue,
citecolor=blue,
filecolor=black,
urlcolor=MidnightBlue
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
% No header for the first page
\thispagestyle{empty}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% HEADER
{\fontsize{22pt}{0}\selectfont\MyName}\\[-0.1cm]
\rule{\textwidth}{0.2pt}
\begin{minipage}[t]{0.595\textwidth}
\Affiliation
\\
\Address
\end{minipage}
\begin{minipage}[t]{0.405\textwidth}
\begin{flushright}
Last updated: \monthyear\today
\\
ORCID: \href{https://orcid.org/\ORCID}{\ORCID}
\\
Email: \href{mailto:\Email}{\Email}
\\
Research lab: \href{https://www.\LabWebsite}{\LabWebsite}
\\
Website: \href{https://www.\PersonalWebsite}{\PersonalWebsite}
\end{flushright}
\end{minipage}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Professional Appointments}
\begin{EntriesTable}
\Duration{2021}{\Ongoing} &
\Appointment{Postdoctoral Research Associate}{Theoretical Division (T-1)}{Los Alamos National Laboratory}{Los Alamos, NM, USA}
\\
\Duration{2015}{2021} &
\Appointment{PhD Candidate}{Computational Materials Design}{\MPIE}{D\"usseldorf, Germany}
\\
\Year{2017} &
\Appointment{Invited Fellow}{Institute for Pure and Applied Mathematics}{University of California}{Los Angeles, CA, USA}
\end{EntriesTable}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Education}
\begin{EntriesTable}
\Duration{2015}{2021} &
\textbf{PhD in Theoretical Physics}, Paderborn University, Germany
\\
\Duration{2010}{2011} &
\textbf{Advanced degree in Theoretical Physics (Master's equivalent)}, \TUKL, Germany
\end{EntriesTable}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Awards \& Honors}
\begin{EntriesTable}
\Year{2019} &
Runner-up for the Heinz Billing Award of 2019
\end{EntriesTable}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Publications}
\begin{EntriesTable}
\Year{2021} &
L.F. Zhu, \Me, S. Ishibashi, F. Körmann, B. Grabowski and \JN.
A fully automated approach to calculate the melting temperature of elemental crystals.
\emph{Computational Materials Science}.
\DOI{10.1016/j.commatsci.2020.110065}.
\GitHub{pyiron/pyiron\_meltingpoint}
\\
\Year{2020} &
T.D. Swinburne, \Me, \MT, G. Simpson, P. Plechac, M. Luskin and \JN.
Anharmonic free energy of lattice vibrations in fcc crystals from a mean field bond.
\emph{Physical Review B}.
\DOI{10.1103/PhysRevB.102.100101}.
\GitHub{tomswinburne/BLaSA}
\\
\Year{2019} &
\Me, S. Surendralal, \YL, \MT, T. Hickel, \RD{} and \JN.
pyiron: an integrated development environment for computational materials science.
\emph{Computational Materials Science}.
\DOI{10.1016/j.commatsci.2018.07.043}.
\GitHub{pyiron}
\\
~ &
\YL, T. Hammerschmidt, \Me, \JN{} and \RD.
Transferability of interatomic potentials for molybdenum and silicon.
\emph{Modelling and Simulation in Materials Science and Engineering}.
\DOI{10.1088/1361-651X/aafd13}
\\
\Year{2016} &
\Me, N. Gunkelmann and H. M. Urbassek.
Influence of C concentration on elastic moduli of $\alpha^{\prime}-Fe_{1-x}C_{x}$ alloys.
\emph{Philosophical Magazine}.
\DOI{10.1080/14786435.2016.1170224}
\end{EntriesTable}
\subsection{Open-source Software}
\begin{EntriesTable}
\Duration{2015}{\Ongoing} &
\textbf{pyiron}
\newline
An integrated development environment for computational materials science
\Role{Project Lead Developer}
\GitHub{pyiron}
\Website{pyiron.org}
\\
\Duration{2018}{\Ongoing} &
\textbf{Conda-Forge}
\newline
A community-led collection of recipes, build infrastructure and distributions for the conda package manager.
\Role{Maintainer for 400+ Materials Science Software Packages}
\GitHub{conda-forge}
\Website{conda-forge.org}
\end{EntriesTable}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Workshops}
\begin{EntriesTable}
%\Year{future} &
\Year{2021} &
Workflows for Atomistic Simulation
\newline
\textit{\MPIE}, D\"usseldorf, Germany (online).
\GitHub{pyiron/potentials-workshop-2021}
\\
\Year{2020} &
Software Tools from Atomistics to Phase Diagrams
\newline
\textit{\MPIE}, D\"usseldorf, Germany (online).
\GitHub{pyiron/phasediagram-workshop-2020}
\end{EntriesTable}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Presentations}
\subsection{Invited Talks}
\begin{EntriesTable}
\Year{2022} &
\Me.
pyiron - an integrated development environment (IDE) for materials science,
\emph{Special Interest Group Data Infrastructure (SIGDIUS) Seminar},
Stuttgart, Germany (online).
\\
\Year{2021} &
\Me, T. Hickel, \JN.
pyiron - an integrated development environment for materials science,
\emph{CECAM Workshop: Simulation Workflows in Materials Modelling (SWiMM)},
Lausanne, Switzerland (online).
\\
\Year{2020} &
\Me, T. Hickel, \JN.
Uncertainty quantification for ab initio thermodynamics,
\emph{Group Seminar Professor \RD},
Bochum, Germany (online).
\\
~ &
\Me, T. Hickel, \JN.
Automated ab-initio determination of materials properties at finite temperatures with pyiron,
\emph{NIST Workshop: Atomistic simulations for industrial needs},
Gaitgersburg, MD, USA (online).
\\
\Year{2019} &
\Me, T. Hickel, \JN.
Automated ab-initio determination of materials properties at finite temperatures with pyiron,
\emph{CLNS Seminar Los Alamos National Laboratory},
Los Alamos, NM, USA.
\\
~ &
\Me, T. Hickel, \JN.
pyiron - an integrated development environment for computational materials science,
\emph{Group Seminar Professor G. Kresse},
Vienna, Austria.
\\
\end{EntriesTable}
\subsection{Talks at International Conferences}
\begin{EntriesTable}
\Year{2019} &
\Me, T. Hickel, \JN.
Automated uncertainty quantification for ab initio thermodynamics,
\emph{MRS Fall Meeting},
Boston, MA, USA.
\\
~ &
\Me, T. Hickel, \JN.
Automated sensitivity analysis for high-throughput ab initio calculations,
\emph{IPAM Workshop},
Los Angeles, CA, USA.
\\
~ &
\Me, T. Hickel, \JN.
Automated error analysis and control for ab initio calculations,
\emph{DPG Spring Meeting},
Regensburg, Germany.
\\
~ &
\Me, T. Hickel, \JN.
Automated sensitivity analysis for high-throughput ab initio calculations,
\emph{TMS Spring Meeting},
San Antonio, TX, USA.
\\
\Year{2018} &
\Me, T. Hickel, \JN.
Generation of ab initio datasets with predefined precision using uncertainty quantification,
\emph{DPG Spring Meeting},
Berlin, Germany.
\\
\Year{2017} &
\Me, T. Hickel, \JN.
Towards an uncertainty quantification for ab initio thermodynamics,
\emph{MRS Fall Meeting},
Boston, MA, USA.
\\
~&
\Me, T. Hickel, \JN.
Sensitivity analyis for large sets of density functional theory calculations,
\emph{DPG Spring Meeting},
Dresden, Germany.
\\
~&
\Me, T. Hickel, \JN.
Automated convergence and error analyses for high-precision DFT calculations,
\emph{TMS Spring Meeting},
San Diego, CA, USA.
\\
\Year{2016} &
\Me, T. Hickel, \JN.
Automated convergence checks with the python based library pyiron,
\emph{DPG Spring Meeting},
Regensburg, Germany.
\\
~&
\Me, T. Hickel, \JN.
Automated convergence checks with the python based workbench pyiron,
\emph{TMS Spring Meeting},
Nashville, TN, USA.
\\
\end{EntriesTable}
\end{document}
|
using ColormapsOcean
@static if VERSION < v"0.7.0-DEV.2005"
using Base.Test
else
using Test
end
# write your own tests here
cmaps=[:algae,:amp,:balance,:curl,:deep,:delta,:dense,:gray,:haline,:ice,:matter,:oxy,:phase,:solar ,:speed,:tempo,:thermal,:turbid]
sz=[size(cmocean[cm],1) for cm in cmaps]
@test size(sz, 1)==1
@test all([z==256 || z==512 for z in sz])
|
[STATEMENT]
lemma new_tv_list: "new_tv n x = (\<forall>y\<in>set x. new_tv n y)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. new_tv n x = (\<forall>y\<in>set x. new_tv n y)
[PROOF STEP]
by (induction x) simp_all
\<comment> \<open>substitution affects only variables occurring freely\<close>
|
import Logic.Vorspiel.Notation
import Mathlib.Tactic.LibrarySearch
import Mathlib.Data.Fin.Basic
import Mathlib.Data.Fin.VecNotation
import Mathlib.Data.Fintype.Basic
import Mathlib.Data.Finset.Basic
import Mathlib.Data.Finset.Lattice
import Mathlib.Data.Finset.Preimage
import Mathlib.Data.Finset.Sort
import Mathlib.Data.W.Basic
import Mathlib.Order.Filter.Ultrafilter
namespace Nat
variable {α : ℕ → Sort u}
def cases (hzero : α 0) (hsucc : ∀ n, α (n + 1)) : ∀ n, α n
| 0 => hzero
| n + 1 => hsucc n
infixr:70 " :>ₙ " => cases
@[simp] lemma cases_zero (hzero : α 0) (hsucc : ∀ n, α (n + 1)) :
(hzero :>ₙ hsucc) 0 = hzero := rfl
@[simp] lemma cases_succ (hzero : α 0) (hsucc : ∀ n, α (n + 1)) (n : ℕ) :
(hzero :>ₙ hsucc) (n + 1) = hsucc n := rfl
end Nat
lemma eq_finZeroElim {α : Sort u} (x : Fin 0 → α) : x = finZeroElim := funext (by rintro ⟨_, _⟩; contradiction)
namespace Matrix
open Fin
section
variable {n : ℕ} {α : Type u}
infixr:70 " :> " => vecCons
@[simp] lemma vecCons_zero :
(a :> s) 0 = a := by simp
@[simp] lemma vecCons_succ (i : Fin n) :
(a :> s) (Fin.succ i) = s i := by simp
@[simp] lemma vecCons_last (a : C) (s : Fin (n + 1) → C) :
(a :> s) (Fin.last (n + 1)) = s (Fin.last n) := vecCons_succ (Fin.last n)
def vecConsLast {n : ℕ} (t : Fin n → α) (h : α) : Fin n.succ → α :=
Fin.lastCases h t
infixl:70 " <: " => vecConsLast
@[simp] lemma rightConcat_last :
(s <: a) (last n) = a := by simp[vecConsLast]
@[simp] lemma rightConcat_castSucc (i : Fin n) :
(s <: a) (Fin.castSucc i) = s i := by simp[vecConsLast]
@[simp] lemma rightConcat_zero (a : α) (s : Fin n.succ → α) :
(s <: a) 0 = s 0 := rightConcat_castSucc 0
@[simp] lemma zero_succ_eq_id {n} : (0 : Fin (n + 1)) :> succ = id :=
funext $ Fin.cases (by simp) (by simp)
lemma to_vecCons (s : Fin (n + 1) → C) : s = s 0 :> s ∘ Fin.succ :=
funext $ Fin.cases (by simp) (by simp)
@[simp] lemma vecCons_ext (a₁ a₂ : α) (s₁ s₂ : Fin n → α) :
a₁ :> s₁ = a₂ :> s₂ ↔ a₁ = a₂ ∧ s₁ = s₂ :=
⟨by intros h
constructor
· exact congrFun h 0
· exact funext (fun i => by simpa using congrFun h (Fin.castSucc i + 1)),
by intros h; simp[h]⟩
def decVec {α : Type _} : {n : ℕ} → (v w : Fin n → α) → (∀ i, Decidable (v i = w i)) → Decidable (v = w)
| 0, _, _, _ => by simp; exact isTrue trivial
| n + 1, v, w, d => by
rw[to_vecCons v, to_vecCons w, vecCons_ext]
haveI : Decidable (v ∘ Fin.succ = w ∘ Fin.succ) := decVec _ _ (by intros i; simp; exact d _)
refine instDecidableAnd
lemma comp_vecCons (f : α → β) (a : α) (s : Fin n → α) : (fun x => f $ (a :> s) x) = f a :> f ∘ s :=
funext (fun i => cases (by simp) (by simp) i)
lemma comp_vecCons' (f : α → β) (a : α) (s : Fin n → α) : (fun x => f $ (a :> s) x) = f a :> fun i => f (s i) :=
comp_vecCons f a s
lemma comp_vecConsLast (f : α → β) (a : α) (s : Fin n → α) : (fun x => f $ (s <: a) x) = f ∘ s <: f a :=
funext (fun i => lastCases (by simp) (by simp) i)
@[simp] lemma vecHead_comp (f : α → β) (v : Fin (n + 1) → α) : vecHead (f ∘ v) = f (vecHead v) :=
by simp[vecHead]
@[simp] lemma vecTail_comp (f : α → β) (v : Fin (n + 1) → α) : vecTail (f ∘ v) = f ∘ (vecTail v) :=
by simp[vecTail, Function.comp.assoc]
lemma vecConsLast_vecEmpty {s : Fin 0 → α} (a : α) : s <: a = ![a] :=
funext (fun x => by
have : 0 = Fin.last 0 := by rfl
cases' x using Fin.cases with i <;> simp[this]
have := i.isLt; contradiction )
lemma constant_eq_singleton {a : α} : (fun _ => a) = ![a] := by funext x; simp
lemma injective_vecCons {f : Fin n → α} (h : Function.Injective f) {a} (ha : ∀ i, a ≠ f i) : Function.Injective (a :> f) := by
have : ∀ i, f i ≠ a := fun i => (ha i).symm
intro i j; cases i using Fin.cases <;> cases j using Fin.cases <;> simp[*]
intro hf; exact h hf
section And
variable [HasLogicSymbols α]
def conj : {n : ℕ} → (Fin n → α) → α
| 0, _ => ⊤
| _ + 1, v => v 0 ⋏ conj (vecTail v)
@[simp] lemma conj_nil (v : Fin 0 → α) : conj v = ⊤ := rfl
@[simp] lemma conj_cons {a : α} {v : Fin n → α} : conj (a :> v) = a ⋏ conj v := rfl
@[simp] lemma conj_hom (f : α →L Prop) (v : Fin n → α) : f (conj v) = ∀ i, f (v i) := by
induction' n with n ih <;> simp[conj]
· intro ⟨_, _⟩; contradiction
· simp[ih]; constructor
· intro ⟨hz, hs⟩ i; cases i using Fin.cases; { exact hz }; { exact hs _ }
· intro h; exact ⟨h 0, fun i => h _⟩
end And
end
variable {α : Type _}
def toList : {n : ℕ} → (Fin n → α) → List α
| 0, _ => []
| _ + 1, v => v 0 :: toList (v ∘ Fin.succ)
@[simp] lemma toList_zero (v : Fin 0 → α) : toList v = [] := rfl
@[simp] lemma toList_succ (v : Fin (n + 1) → α) : toList v = v 0 :: toList (v ∘ Fin.succ) := rfl
@[simp] lemma toList_length (v : Fin n → α) : (toList v).length = n :=
by induction n <;> simp[*]
@[simp] lemma toList_nth (v : Fin n → α) (i) (hi) : (toList v).nthLe i hi = v ⟨i, by simpa using hi⟩ := by
induction n generalizing i <;> simp[*, List.nthLe_cons]
case zero => contradiction
case succ => rcases i <;> simp
@[simp] lemma mem_toList_iff {v : Fin n → α} {a} : a ∈ toList v ↔ ∃ i, v i = a :=
by induction n <;> simp[*]; constructor; { rintro (rfl | ⟨i, rfl⟩) <;> simp }; { rintro ⟨i, rfl⟩; cases i using Fin.cases <;> simp }
def toOptionVec : {n : ℕ} → (Fin n → Option α) → Option (Fin n → α)
| 0, _ => some vecEmpty
| _ + 1, v => (toOptionVec (v ∘ Fin.succ)).bind (fun vs => (v 0).map (fun z => z :> vs))
@[simp] lemma toOptionVec_some (v : Fin n → α) :
toOptionVec (fun i => some (v i)) = some v :=
by induction n <;> simp[*, toOptionVec, Function.comp]; exact funext (Fin.cases (by simp) (by simp))
def vecToNat : {n : ℕ} → (Fin n → ℕ) → ℕ
| 0, _ => 0
| _ + 1, v => Nat.mkpair (v 0) (vecToNat $ v ∘ Fin.succ)
end Matrix
def Nat.unvector : {n : ℕ} → ℕ → Fin n → ℕ
| 0, _ => Matrix.vecEmpty
| _ + 1, e => e.unpair.1 :> Nat.unvector e.unpair.2
namespace Nat
open Matrix
variable {n}
@[simp] lemma unvector_le (e : ℕ) (i : Fin n) : unvector e i ≤ e := by
induction' n with n ih generalizing e <;> simp[*, unvector]
· have := i.isLt; contradiction
· exact Fin.cases (by simpa using Nat.unpair_left_le _) (fun i => le_trans (ih e.unpair.2 i) (Nat.unpair_right_le _)) i
@[simp] lemma unvector_vecToNat (v : Fin n → ℕ) : unvector (vecToNat v) = v := by
induction n <;> simp[*, Nat.unvector, vecToNat]; exact funext (fun i => i.cases (by simp) (by simp))
-- @[simp] lemma toNat_unvector (ln : 0 < n) (e : ℕ) : Fin.vecToNat (unvector e : Fin n → ℕ) = e := by
-- induction n generalizing e <;> simp[unvector, Fin.vecToNat, Function.comp]
-- · simp at ln
-- · {simp[Function.comp]; sorry}
lemma one_le_of_bodd {n : ℕ} (h : n.bodd = true) : 1 ≤ n :=
by induction n <;> simp[←Nat.add_one] at h ⊢
end Nat
namespace Fintype
variable {ι : Type _} [Fintype ι] {α : Type _} [SemilatticeSup α] [OrderBot α]
def sup (f : ι → α) : α := (Finset.univ : Finset ι).sup f
@[simp] lemma elem_le_sup (f : ι → α) (i : ι) : f i ≤ sup f := Finset.le_sup (by simp)
lemma le_sup {a : α} {f : ι → α} (i : ι) (le : a ≤ f i) : a ≤ sup f := le_trans le (elem_le_sup _ _)
@[simp] lemma sup_le_iff {f : ι → α} {a : α} :
sup f ≤ a ↔ (∀ i, f i ≤ a) := by simp[sup]
@[simp] lemma finsup_eq_0_of_empty [IsEmpty ι] (f : ι → α) : sup f = ⊥ := by simp[sup]
end Fintype
namespace String
def vecToStr : ∀ {n}, (Fin n → String) → String
| 0, _ => ""
| n + 1, s => if n = 0 then s 0 else s 0 ++ ", " ++ @vecToStr n (fun i => s (Fin.succ i))
#eval vecToStr !["a", "b", "c", "d"]
end String
namespace Empty
lemma eq_elim {α : Sort u} (f : Empty → α) : f = elim := funext (by rintro ⟨⟩)
end Empty
namespace Set
variable {α : Type u} {β : Type v}
lemma subset_image_iff (f : α → β) {s : Set α} {t : Set β} :
t ⊆ f '' s ↔ ∃ u, u ⊆ s ∧ f '' u = t :=
⟨by intro h
use {a : α | a ∈ s ∧ f a ∈ t}
constructor
{ intros a ha; exact ha.1 }
{ ext b; constructor <;> simp; { rintro a _ hfa rfl; exact hfa };
{ intros hb; rcases h hb with ⟨a, ha, rfl⟩; exact ⟨a, ⟨ha, hb⟩, rfl⟩ } },
by { rintro ⟨u, hu, rfl⟩; intros b; simp; rintro a ha rfl; exact ⟨a, hu ha, rfl⟩ }⟩
end Set
namespace Function
variable {α : Type u} {β : Type v}
def funEqOn (p : α → Prop) (f g : α → β) : Prop := ∀ a, p a → f a = g a
lemma funEqOn.of_subset {p q : α → Prop} {f g : α → β} (e : funEqOn p f g) (h : ∀ a, q a → p a) : funEqOn q f g :=
by intro a ha; exact e a (h a ha)
end Function
namespace Quotient
open Matrix
variable {α : Type u} [s : Setoid α] {β : Sort v}
@[elab_as_elim]
lemma inductionOnVec {p : (Fin n → Quotient s) → Prop} (v : Fin n → Quotient s)
(h : ∀ v : Fin n → α, p (fun i => Quotient.mk s (v i))) : p v :=
Quotient.induction_on_pi v h
def liftVec : ∀ {n} (f : (Fin n → α) → β),
(∀ v₁ v₂ : Fin n → α, (∀ n, v₁ n ≈ v₂ n) → f v₁ = f v₂) → (Fin n → Quotient s) → β
| 0, f, _, _ => f ![]
| n + 1, f, h, v =>
let ih : α → (Fin n → Quotient s) → β :=
fun a v => liftVec (n := n) (fun v => f (a :> v))
(fun v₁ v₂ hv => h (a :> v₁) (a :> v₂) (Fin.cases (by simp; exact refl a) hv)) v
Quot.liftOn (vecHead v) (ih · (vecTail v))
(fun a b hab => by
have : ∀ v, f (a :> v) = f (b :> v) := fun v => h _ _ (Fin.cases hab (by simp; intro; exact refl _))
simp[this])
@[simp] lemma liftVec_zero (f : (Fin 0 → α) → β) (h) (v : Fin 0 → Quotient s) : liftVec f h v = f ![] := rfl
lemma liftVec_mk {n} (f : (Fin n → α) → β) (h) (v : Fin n → α) :
liftVec f h (Quotient.mk s ∘ v) = f v := by
induction' n with n ih <;> simp[liftVec, empty_eq, Quotient.liftOn_mk]
simpa using ih (fun v' => f (vecHead v :> v'))
(fun v₁ v₂ hv => h (vecHead v :> v₁) (vecHead v :> v₂) (Fin.cases (refl _) hv)) (vecTail v)
@[simp] lemma liftVec_mk₁ (f : (Fin 1 → α) → β) (h) (a : α) :
liftVec f h ![Quotient.mk s a] = f ![a] := liftVec_mk f h ![a]
@[simp] lemma liftVec_mk₂ (f : (Fin 2 → α) → β) (h) (a₁ a₂ : α) :
liftVec f h ![Quotient.mk s a₁, Quotient.mk s a₂] = f ![a₁, a₂] := liftVec_mk f h ![a₁, a₂]
end Quotient
class Class (F : Type u → Type v) (α : Type u) where
out : F α
namespace Class
variable {F : Type u → Type v} {α : Type u}
@[simp] lemma out_mk (x : F α) : out (self := Class.mk x) = x := rfl
@[simp] lemma mk_out [x : Class F α] : Class.mk out = x := rfl
end Class
|
module Evens
-- The type `IsEven(n)` has terms (objects) that are proofs that `n` is even.
data IsEven : Nat -> Type where
ZeroEven : IsEven 0
SSEven : (n: Nat) -> (pf: IsEven n) -> IsEven (S (S n))
twoEven : IsEven 2
twoEven = SSEven Z ZeroEven
fourEven : IsEven 4
fourEven = SSEven _ twoEven
half : (n: Nat) -> IsEven n -> Nat
half Z ZeroEven = 0
half (S (S k)) (SSEven k pf) =
S (half k pf)
double: Nat -> Nat
double Z = Z
double (S k) = S (S (double k))
doubleEven: (n: Nat) -> IsEven (double n)
doubleEven Z = ZeroEven
doubleEven (S k) =
SSEven (double k) (doubleEven k)
halfDouble : Nat -> Nat
halfDouble n = half (double n) (doubleEven n)
nOrSnEven : (n : Nat) -> Either (IsEven n) (IsEven (S n))
nOrSnEven Z = Left ZeroEven
nOrSnEven (S k) = case nOrSnEven k of
(Left l) => Right (SSEven k l)
(Right r) => Left r
oneOdd : IsEven 1 -> Void
oneOdd ZeroEven impossible
oneOdd (SSEven _ _) impossible
threeOdd : IsEven 3 -> Void
threeOdd (SSEven (S Z) ZeroEven) impossible
threeOdd (SSEven (S Z) (SSEven _ _)) impossible
nAndSnNotBothEven : (n: Nat) -> IsEven n -> IsEven (S n) -> Void
nAndSnNotBothEven Z ZeroEven ZeroEven impossible
nAndSnNotBothEven Z ZeroEven (SSEven _ _) impossible
nAndSnNotBothEven (S (S k)) (SSEven k pf) (SSEven (S k) x) =
nAndSnNotBothEven k pf x
nOddThenSnEven : (n: Nat) -> (IsEven n -> Void) -> IsEven (S n)
nOddThenSnEven n contra =
(case (nOrSnEven n) of
(Left l) => void (contra l)
(Right r) => r
)
halfSucc : (n : Nat) -> ((IsEven n) -> Void) -> Nat
halfSucc n contra = half (S n) (nOddThenSnEven n contra)
apNat : (f: Nat -> Nat) -> (n: Nat) -> (m: Nat) -> n = m -> f n = f m
apNat f m m Refl = Refl
byTwo : (n: Nat) -> IsEven n -> (k: Nat ** double k = n)
byTwo Z ZeroEven = (Z ** Refl)
byTwo (S (S k)) (SSEven k pf) =
(case byTwo k pf of
(x ** pf) => (S x ** (apNat (\m => (S (S m))) (double x) k pf)))
isDouble: Nat -> Type
isDouble n = (m : Nat ** (double m) = n)
evenIsDouble: (n: Nat) -> IsEven n -> (isDouble n)
evenIsDouble = byTwo
transport : (a : Type) -> (P : a -> Type) -> (x : a) -> (y : a) -> (x = y) -> P(x) -> P(y)
transport a P y y Refl z = z
doubleIsEven: (n: Nat) -> isDouble n -> IsEven n
doubleIsEven n pair =
case pair of
(k ** pf) =>
transport Nat IsEven (double k) n pf (doubleEven k)
-- The Peano axioms
sInj : (x: Nat) -> (y: Nat) -> (S x = S y) -> (x = y)
sInj Z Z Refl = Refl
sInj (S k) (S k) Refl = Refl
sNotZ : (x: Nat) -> (S x = Z) -> Void
sNotZ _ Refl impossible
symmEq : (x: Nat) -> (y: Nat) -> (x = y) -> (y = x)
symmEq y y Refl = Refl
transEq: (x: Nat) -> (y: Nat) -> (z: Nat) -> (x = y) -> (y = z) -> (x = z)
transEq y y y Refl Refl = Refl
--- Less than or equal and subtraction
sub : (n: Nat) -> (m : Nat) -> (LTE m n) -> Nat
sub n Z LTEZero = n
sub (S right) (S left) (LTESucc x) = sub right left x
superSub : (n: Nat) -> (m : Nat) -> (LTE m n) -> (diff: Nat ** LTE diff n)
superSub n Z LTEZero = (n ** lteRefl)
superSub (S n) (S m) (LTESucc x) = case (superSub n m x) of
(diff ** pf) => (diff ** lteSuccRight pf)
oneLTEFour : LTE 1 4
oneLTEFour = LTESucc LTEZero
fourMinusOne : Nat
fourMinusOne = sub 4 1 oneLTEFour
-- Range type
data InRange : Nat -> Nat -> Type where
MkInRange : (l : Nat) -> (u : Nat) -> (n : Nat) -> LTE l n -> LTE n u -> InRange l u
oneBetween0And4 : InRange 0 4
oneBetween0And4 = MkInRange 0 4 1 LTEZero oneLTEFour
Cast (InRange n m) Nat where -- cast is an interface (typeclass in scala)
cast (MkInRange n m k x y) = k
one: Nat
one = cast oneBetween0And4
--- space
|
// test_file_get_contents.cc
#include "menon/io.hh"
#include <boost/core/lightweight_test.hpp>
#include <fstream>
#include <sstream>
#include <cwchar>
#include <cstdlib>
std::byte test_data[256];
// テストデータの作成
void make_test_file(char const* path)
{
for (std::size_t i = 0; i < sizeof(test_data); i++)
test_data[i] = static_cast<std::byte>(std::rand() & 0xff);
auto stream = std::fopen(path, "wb");
BOOST_TEST_NE(stream, nullptr);
std::fwrite(test_data, 1, sizeof(test_data), stream);
std::fclose(stream);
}
// stream_get_contents関数のテストコード
void test_stream_get_contents(char const* path)
{
auto stream = std::fopen(path, "rb");
BOOST_TEST_NE(stream, nullptr);
{ // 基本的な使い方
std::rewind(stream);
auto r = menon::stream_get_contents(stream);
BOOST_TEST(std::equal(r.cbegin(), r.cend(), std::begin(test_data), std::end(test_data)));
}
{ // offsetを指定
std::rewind(stream);
auto r = menon::stream_get_contents(stream, -1, 10);
BOOST_TEST(std::equal(r.cbegin(), r.cend(), std::begin(test_data) + 10, std::end(test_data)));
}
{ // maxlengthとoffsetを設定
std::rewind(stream);
auto r = menon::stream_get_contents(stream, 100, 7);
BOOST_TEST(std::equal(r.cbegin(), r.cend(), std::begin(test_data) + 7, std::begin(test_data) + 7 + 100));
}
{ // シーク位置からmaxlengthを設定して読み込み
std::fseek(stream, 20, SEEK_SET);
auto r = menon::stream_get_contents(stream, 100);
BOOST_TEST(std::equal(r.cbegin(), r.cend(), std::begin(test_data) + 20, std::begin(test_data) + 20 + 100));
}
{ // シーク位置からの読み込み
std::fseek(stream, 20, SEEK_SET);
auto r = menon::stream_get_contents(stream);
BOOST_TEST(std::equal(r.cbegin(), r.cend(), std::begin(test_data) + 20, std::end(test_data)));
}
std::fclose(stream);
{ // istreamからの基本的な読み込み
std::ifstream ifs(path, std::ios_base::in | std::ios_base::binary);
auto r = menon::stream_get_contents(ifs);
BOOST_TEST(std::equal(r.cbegin(), r.cend(), std::begin(test_data), std::end(test_data)));
}
{ // istreamからのoffsetを指定して読み込み
std::ifstream ifs(path, std::ios_base::in | std::ios_base::binary);
auto r = menon::stream_get_contents(ifs, -1, 10);
BOOST_TEST(std::equal(r.cbegin(), r.cend(), std::begin(test_data) + 10, std::end(test_data)));
}
{ // istreamからのmaxlengthとoffsetを指定して読み込み
std::ifstream ifs(path, std::ios_base::in | std::ios_base::binary);
auto r = menon::stream_get_contents(ifs, 100, 7);
BOOST_TEST(std::equal(r.cbegin(), r.cend(), std::begin(test_data) + 7, std::begin(test_data) + 7 + 100));
}
{ // istreamからのシーク位置からのmaxlengthを指定して読み込み
std::ifstream ifs(path, std::ios_base::in | std::ios_base::binary);
ifs.seekg(20);
auto r = menon::stream_get_contents(stream, 100);
BOOST_TEST(std::equal(r.cbegin(), r.cend(), std::begin(test_data) + 20, std::begin(test_data) + 20 + 100));
}
{ // istreamからのシーク位置からの読み込み
std::ifstream ifs(path, std::ios_base::in | std::ios_base::binary);
ifs.seekg(20);
auto r = menon::stream_get_contents(ifs);
BOOST_TEST(std::equal(r.cbegin(), r.cend(), std::begin(test_data) + 20, std::end(test_data)));
}
}
// file_get_contents関数のテストコード
void test_file_get_contents(char const* path)
{
{ // 基本的な使い方
auto r = menon::file_get_contents(path);
BOOST_TEST(std::equal(r.cbegin(), r.cend(), std::begin(test_data), std::end(test_data)));
}
{ // offsetを指定して読み込み
auto r = menon::file_get_contents(path, -1, 10);
BOOST_TEST(std::equal(r.cbegin(), r.cend(), std::begin(test_data) + 10, std::end(test_data)));
}
{ // maxlengthとoffsetを指定して読み込み
auto r = menon::file_get_contents(path, 100, 7);
BOOST_TEST(std::equal(r.cbegin(), r.cend(), std::begin(test_data) + 7, std::begin(test_data) + 7 + 100));
}
{ // 不正なパスを指定した場合の異常系処理
BOOST_TEST_THROWS(menon::file_get_contents(":*"), std::invalid_argument);
}
}
int main()
{
auto path = "test.data";
make_test_file(path);
test_stream_get_contents(path);
test_file_get_contents(path);
std::remove(path);
return boost::report_errors();
}
|
Well it's been a funny few days. On Saturday I made the best beefburgers yet - the recipe's from a fellow Sausagemaking.org member, Oddley.
I've always been a "don't use anything other than chuck steak, ground with salt and pepper" man, but he's converted me. The spices aren't discernable in the taste, but it wouldn't be as good without them.
Things were going so well, that is until the element went in the fan oven on Sunday. £50 later and it's up and running again.
However, things are looking up again. Maurice rang me yesterday lunch-time to say that the fishmonger had replaced the roe that wasn't very good, free of charge. So yesterday evening we dry salted them for 8 hours, and they're in the cold smoker as I speak.
They certainly look more promising than the last lot.
Very interested in how the online course went Phil, I’ve been putting this off for too long and it’s high time I got one of those certificates.
|
% book : Signals and Systems Laboratory with MATLAB
% authors : Alex Palamides & Anastasia Veloni
%
%
%
% time invariant or time variant
%time variant
t=-5:.001:10;
p=heaviside(t)-heaviside(t-5);
y=t.*exp(-t).*p;
plot(t,y)
ylim([-.05 .4]);
legend('y(t)')
figure
plot(t+3,y)
ylim([-.05 .4]);
legend('y(t-3)')
figure
t=-5:.001:10;
p=heaviside(t-3)-heaviside(t-8);
y2=t.*exp(-t).*p;
plot(t,y2)
ylim([-.01 .2]);
legend('S[x(t-3)]')
%time invariant
figure
t=-5:.01:20;
p=heaviside(t-1)-heaviside(t-11);
y=1-2*cos(t-1).*p;
plot(t,y)
legend('y(t)')
figure
p=heaviside(t)-heaviside(t-10);
x=cos(t).*p;
plot(t+1,1-2*x)
legend('y(t)')
figure
plot(t+4,y)
legend('y(t-4)')
figure
p=heaviside(t-4)-heaviside(t-14);
x=cos(t-4).*p;
plot(t,x)
figure
p=heaviside(t-4)-heaviside(t-14);
x=cos(t-4).*p;
plot(t+1,1-2*x)
figure
t=-5:.01:20;
p=heaviside(t-5)-heaviside(t-15);
y2=1-2*cos(t-5).*p ;
plot(t,y2) ;
legend('S[x(t-4)]')
%time variant
figure
t=-5:.1:10;
x=heaviside(t+2)-heaviside(t-2);
plot(t,x);
ylim([-.1 1.1]);
figure
plot((1/2)*t,x);
ylim([-.1 1.1]);
figure
plot((1/2)*t+2,x);
ylim([-.1 1.1]);
legend('y_1(t)')
figure
plot(t+2,x);
ylim([-.1 1.1]);
legend('x(t-2)')
figure
t=-5:.1:10;
x2=heaviside(t)-heaviside(t-4);
plot(t,x2);
ylim([-.1 1.1]);
figure
plot((1/2)*t,x2);
ylim([-.1 1.1]);
legend('y_2(t)')
%shift invariant
figure
n=0:5;
x=0.8.^n;
y=x.^2;
stem(n,y);
xlim([-.1 5.1])
legend('y[n]')
figure
stem(n+2,y)
legend('y[n-2]')
xlim([1.9 7.1])
figure
n=2:7;
y2=(0.8.^(n-2)).^2;
stem(n,y2);
xlim([1.9 7.1])
legend('S[x[n-2]]')
|
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
! This file was ported from Lean 3 source module data.vector.basic
! leanprover-community/mathlib commit f694c7dead66f5d4c80f446c796a5aad14707f0e
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.Data.Vector
import Mathlib.Data.List.Nodup
import Mathlib.Data.List.OfFn
import Mathlib.Control.Applicative
import Mathlib.Control.Traversable.Basic
/-!
# Additional theorems and definitions about the `Vector` type
This file introduces the infix notation `::ᵥ` for `Vector.cons`.
-/
universe u
variable {n : ℕ}
namespace Vector
variable {α : Type _}
@[inherit_doc]
infixr:67 " ::ᵥ " => Vector.cons
attribute [simp] head_cons tail_cons
instance [Inhabited α] : Inhabited (Vector α n) :=
⟨ofFn default⟩
theorem toList_injective : Function.Injective (@toList α n) :=
Subtype.val_injective
#align vector.to_list_injective Vector.toList_injective
/-- Two `v w : Vector α n` are equal iff they are equal at every single index. -/
@[ext]
theorem ext : ∀ {v w : Vector α n} (_ : ∀ m : Fin n, Vector.get v m = Vector.get w m), v = w
| ⟨v, hv⟩, ⟨w, hw⟩, h =>
Subtype.eq (List.ext_get (by rw [hv, hw]) fun m hm _ => h ⟨m, hv ▸ hm⟩)
#align vector.ext Vector.ext
/-- The empty `Vector` is a `Subsingleton`. -/
instance zero_subsingleton : Subsingleton (Vector α 0) :=
⟨fun _ _ => Vector.ext fun m => Fin.elim0 m⟩
#align vector.zero_subsingleton Vector.zero_subsingleton
@[simp]
theorem cons_val (a : α) : ∀ v : Vector α n, (a ::ᵥ v).val = a :: v.val
| ⟨_, _⟩ => rfl
#align vector.cons_val Vector.cons_val
#align vector.cons_head Vector.head_cons
#align vector.cons_tail Vector.tail_cons
theorem eq_cons_iff (a : α) (v : Vector α n.succ) (v' : Vector α n) :
v = a ::ᵥ v' ↔ v.head = a ∧ v.tail = v' :=
⟨fun h => h.symm ▸ ⟨head_cons a v', tail_cons a v'⟩, fun h =>
_root_.trans (cons_head_tail v).symm (by rw [h.1, h.2])⟩
#align vector.eq_cons_iff Vector.eq_cons_iff
theorem ne_cons_iff (a : α) (v : Vector α n.succ) (v' : Vector α n) :
v ≠ a ::ᵥ v' ↔ v.head ≠ a ∨ v.tail ≠ v' := by rw [Ne.def, eq_cons_iff a v v', not_and_or]
#align vector.ne_cons_iff Vector.ne_cons_iff
theorem exists_eq_cons (v : Vector α n.succ) : ∃ (a : α)(as : Vector α n), v = a ::ᵥ as :=
⟨v.head, v.tail, (eq_cons_iff v.head v v.tail).2 ⟨rfl, rfl⟩⟩
#align vector.exists_eq_cons Vector.exists_eq_cons
@[simp]
theorem toList_ofFn : ∀ {n} (f : Fin n → α), toList (ofFn f) = List.ofFn f
| 0, f => rfl
| n + 1, f => by rw [ofFn, List.ofFn_succ, toList_cons, toList_ofFn]
#align vector.to_list_of_fn Vector.toList_ofFn
@[simp]
theorem mk_toList : ∀ (v : Vector α n) (h), (⟨toList v, h⟩ : Vector α n) = v
| ⟨_, _⟩, _ => rfl
#align vector.mk_to_list Vector.mk_toList
@[simp] theorem length_val (v : Vector α n) : v.val.length = n := v.2
-- porting notes: not used in mathlib and coercions done differently in Lean 4
-- @[simp]
-- theorem length_coe (v : Vector α n) :
-- ((coe : { l : List α // l.length = n } → List α) v).length = n :=
-- v.2
#noalign vector.length_coe
@[simp]
theorem toList_map {β : Type _} (v : Vector α n) (f : α → β) : (v.map f).toList = v.toList.map f :=
by cases v ; rfl
#align vector.to_list_map Vector.toList_map
@[simp]
theorem head_map {β : Type _} (v : Vector α (n + 1)) (f : α → β) : (v.map f).head = f v.head :=
by
obtain ⟨a, v', h⟩ := Vector.exists_eq_cons v
rw [h, map_cons, head_cons, head_cons]
#align vector.head_map Vector.head_map
@[simp]
theorem tail_map {β : Type _} (v : Vector α (n + 1)) (f : α → β) : (v.map f).tail = v.tail.map f :=
by
obtain ⟨a, v', h⟩ := Vector.exists_eq_cons v
rw [h, map_cons, tail_cons, tail_cons]
#align vector.tail_map Vector.tail_map
theorem get_eq_get (v : Vector α n) (i : Fin n) :
v.get i = v.toList.get (Fin.cast v.toList_length.symm i) :=
rfl
#align vector.nth_eq_nth_le Vector.get_eq_get
-- porting notes: `nthLe` deprecated for `get`
@[deprecated get_eq_get]
theorem nth_eq_nthLe :
∀ (v : Vector α n) (i), get v i = v.toList.nthLe i.1 (by rw [toList_length] ; exact i.2)
| ⟨_, _⟩, _ => rfl
@[simp]
theorem get_replicate (a : α) (i : Fin n) : (Vector.replicate n a).get i = a := by
apply List.get_replicate
#align vector.nth_repeat Vector.get_replicate
@[simp]
theorem get_map {β : Type _} (v : Vector α n) (f : α → β) (i : Fin n) :
(v.map f).get i = f (v.get i) := by
cases v; simp [Vector.map, get_eq_get]; rfl
#align vector.nth_map Vector.get_map
@[simp]
theorem get_ofFn {n} (f : Fin n → α) (i) : get (ofFn f) i = f i := by
cases' i with i hi
conv_rhs => erw [← List.get_ofFn f ⟨i, by simpa using hi⟩]
simp only [get_eq_get]
congr <;> simp [Fin.heq_ext_iff]
#align vector.nth_of_fn Vector.get_ofFn
@[simp]
theorem ofFn_get (v : Vector α n) : ofFn (get v) = v := by
rcases v with ⟨l, rfl⟩
apply toList_injective
dsimp
simpa only [toList_ofFn] using List.ofFn_get _
#align vector.of_fn_nth Vector.ofFn_get
/-- The natural equivalence between length-`n` vectors and functions from `Fin n`. -/
def _root_.Equiv.vectorEquivFin (α : Type _) (n : ℕ) : Vector α n ≃ (Fin n → α) :=
⟨Vector.get, Vector.ofFn, Vector.ofFn_get, fun f => funext <| Vector.get_ofFn f⟩
#align equiv.vector_equiv_fin Equiv.vectorEquivFin
theorem get_tail (x : Vector α n) (i) :
x.tail.get i = x.get ⟨i.1 + 1, lt_tsub_iff_right.mp i.2⟩ := by
cases' i with i ih ; dsimp
rcases x with ⟨_ | _, h⟩ <;> try rfl
rw [List.length] at h
rw [←h] at ih
contradiction
#align vector.nth_tail Vector.get_tail
@[simp]
theorem get_tail_succ : ∀ (v : Vector α n.succ) (i : Fin n), get (tail v) i = get v i.succ
| ⟨a :: l, e⟩, ⟨i, h⟩ => by simp [get_eq_get] ; rfl
#align vector.nth_tail_succ Vector.get_tail_succ
@[simp]
theorem tail_val : ∀ v : Vector α n.succ, v.tail.val = v.val.tail
| ⟨_ :: _, _⟩ => rfl
#align vector.tail_val Vector.tail_val
/-- The `tail` of a `nil` vector is `nil`. -/
@[simp]
theorem tail_nil : (@nil α).tail = nil :=
rfl
#align vector.tail_nil Vector.tail_nil
/-- The `tail` of a vector made up of one element is `nil`. -/
@[simp]
theorem singleton_tail : ∀ (v : Vector α 1), v.tail = Vector.nil
| ⟨[_], _⟩ => rfl
#align vector.singleton_tail Vector.singleton_tail
@[simp]
theorem tail_ofFn {n : ℕ} (f : Fin n.succ → α) : tail (ofFn f) = ofFn fun i => f i.succ :=
(ofFn_get _).symm.trans <| by
congr
funext i
rw [get_tail, get_ofFn]
rfl
#align vector.tail_of_fn Vector.tail_ofFn
@[simp]
theorem toList_empty (v : Vector α 0) : v.toList = [] :=
List.length_eq_zero.mp v.2
#align vector.to_list_empty Vector.toList_empty
/-- The list that makes up a `Vector` made up of a single element,
retrieved via `toList`, is equal to the list of that single element. -/
@[simp]
theorem toList_singleton (v : Vector α 1) : v.toList = [v.head] :=
by
rw [← v.cons_head_tail]
simp only [toList_cons, toList_nil, head_cons, eq_self_iff_true, and_self_iff, singleton_tail]
#align vector.to_list_singleton Vector.toList_singleton
@[simp]
theorem not_empty_toList (v : Vector α (n + 1)) : ¬v.toList.isEmpty := by
simp only [empty_toList_eq_ff, Bool.coe_sort_false, not_false_iff]
#align vector.not_empty_to_list Vector.not_empty_toList
/-- Mapping under `id` does not change a vector. -/
@[simp]
theorem map_id {n : ℕ} (v : Vector α n) : Vector.map id v = v :=
Vector.eq _ _ (by simp only [List.map_id, Vector.toList_map])
#align vector.map_id Vector.map_id
theorem nodup_iff_injective_get {v : Vector α n} : v.toList.Nodup ↔ Function.Injective v.get := by
cases' v with l hl
subst hl
exact List.nodup_iff_injective_get
#align vector.nodup_iff_nth_inj Vector.nodup_iff_injective_get
theorem head?_toList : ∀ v : Vector α n.succ, (toList v).head? = some (head v)
| ⟨_ :: _, _⟩ => rfl
#align vector.head'_to_list Vector.head?_toList
/-- Reverse a vector. -/
def reverse (v : Vector α n) : Vector α n :=
⟨v.toList.reverse, by simp⟩
#align vector.reverse Vector.reverse
/-- The `List` of a vector after a `reverse`, retrieved by `toList` is equal
to the `List.reverse` after retrieving a vector's `toList`. -/
theorem toList_reverse {v : Vector α n} : v.reverse.toList = v.toList.reverse :=
rfl
#align vector.to_list_reverse Vector.toList_reverse
@[simp]
theorem reverse_reverse {v : Vector α n} : v.reverse.reverse = v :=
by
cases v
simp [Vector.reverse]
#align vector.reverse_reverse Vector.reverse_reverse
@[simp]
theorem get_zero : ∀ v : Vector α n.succ, get v 0 = head v
| ⟨_ :: _, _⟩ => rfl
#align vector.nth_zero Vector.get_zero
@[simp]
theorem head_ofFn {n : ℕ} (f : Fin n.succ → α) : head (ofFn f) = f 0 := by
rw [← get_zero, get_ofFn]
#align vector.head_of_fn Vector.head_ofFn
--@[simp] Porting note: simp can prove it
theorem get_cons_zero (a : α) (v : Vector α n) : get (a ::ᵥ v) 0 = a := by simp [get_zero]
#align vector.nth_cons_zero Vector.get_cons_zero
/-- Accessing the nth element of a vector made up
of one element `x : α` is `x` itself. -/
@[simp]
theorem get_cons_nil : ∀ {ix : Fin 1} (x : α), get (x ::ᵥ nil) ix = x
| ⟨0, _⟩, _ => rfl
#align vector.nth_cons_nil Vector.get_cons_nil
@[simp]
theorem get_cons_succ (a : α) (v : Vector α n) (i : Fin n) : get (a ::ᵥ v) i.succ = get v i := by
rw [← get_tail_succ, tail_cons]
#align vector.nth_cons_succ Vector.get_cons_succ
/-- The last element of a `Vector`, given that the vector is at least one element. -/
def last (v : Vector α (n + 1)) : α :=
v.get (Fin.last n)
#align vector.last Vector.last
/-- The last element of a `Vector`, given that the vector is at least one element. -/
theorem last_def {v : Vector α (n + 1)} : v.last = v.get (Fin.last n) :=
rfl
#align vector.last_def Vector.last_def
/-- The `last` element of a vector is the `head` of the `reverse` vector. -/
theorem reverse_get_zero {v : Vector α (n + 1)} : v.reverse.head = v.last := by
rw [← get_zero, last_def, get_eq_get, get_eq_get]
simp_rw [toList_reverse, Fin.val_last, Fin.val_zero]
rw [← Option.some_inj, ← List.get?_eq_get, ← List.get?_eq_get, List.get?_reverse]
· congr
simp
· simp
#align vector.reverse_nth_zero Vector.reverse_get_zero
section Scan
variable {β : Type _}
variable (f : β → α → β) (b : β)
variable (v : Vector α n)
/-- Construct a `Vector β (n + 1)` from a `Vector α n` by scanning `f : β → α → β`
from the "left", that is, from 0 to `Fin.last n`, using `b : β` as the starting value.
-/
def scanl : Vector β (n + 1) :=
⟨List.scanl f b v.toList, by rw [List.length_scanl, toList_length]⟩
#align vector.scanl Vector.scanl
/-- Providing an empty vector to `scanl` gives the starting value `b : β`. -/
@[simp]
theorem scanl_nil : scanl f b nil = b ::ᵥ nil :=
rfl
#align vector.scanl_nil Vector.scanl_nil
/-- The recursive step of `scanl` splits a vector `x ::ᵥ v : Vector α (n + 1)`
into the provided starting value `b : β` and the recursed `scanl`
`f b x : β` as the starting value.
This lemma is the `cons` version of `scanl_get`.
-/
@[simp]
theorem scanl_cons (x : α) : scanl f b (x ::ᵥ v) = b ::ᵥ scanl f (f b x) v := by
simp only [scanl, toList_cons, List.scanl]; dsimp
simp only [cons]; rfl
#align vector.scanl_cons Vector.scanl_cons
/-- The underlying `List` of a `Vector` after a `scanl` is the `List.scanl`
of the underlying `List` of the original `Vector`.
-/
@[simp]
theorem scanl_val : ∀ {v : Vector α n}, (scanl f b v).val = List.scanl f b v.val
| _ => rfl
#align vector.scanl_val Vector.scanl_val
/-- The `toList` of a `Vector` after a `scanl` is the `List.scanl`
of the `toList` of the original `Vector`.
-/
@[simp]
theorem toList_scanl : (scanl f b v).toList = List.scanl f b v.toList :=
rfl
#align vector.to_list_scanl Vector.toList_scanl
/-- The recursive step of `scanl` splits a vector made up of a single element
`x ::ᵥ nil : Vector α 1` into a `Vector` of the provided starting value `b : β`
and the mapped `f b x : β` as the last value.
-/
@[simp]
theorem scanl_singleton (v : Vector α 1) : scanl f b v = b ::ᵥ f b v.head ::ᵥ nil := by
rw [← cons_head_tail v]
simp only [scanl_cons, scanl_nil, head_cons, singleton_tail]
#align vector.scanl_singleton Vector.scanl_singleton
/-- The first element of `scanl` of a vector `v : Vector α n`,
retrieved via `head`, is the starting value `b : β`.
-/
@[simp]
theorem scanl_head : (scanl f b v).head = b := by
cases n
· have : v = nil := by simp only [Nat.zero_eq, eq_iff_true_of_subsingleton]
simp only [this, scanl_nil, head_cons]
· rw [← cons_head_tail v]
simp only [← get_zero, get_eq_get, toList_scanl, toList_cons, List.scanl, Fin.val_zero,
List.get]
#align vector.scanl_head Vector.scanl_head
/-- For an index `i : Fin n`, the nth element of `scanl` of a
vector `v : Vector α n` at `i.succ`, is equal to the application
function `f : β → α → β` of the `castSucc i` element of
`scanl f b v` and `get v i`.
This lemma is the `get` version of `scanl_cons`.
-/
@[simp]
theorem scanl_get (i : Fin n) :
(scanl f b v).get i.succ = f ((scanl f b v).get (Fin.castSucc i)) (v.get i) := by
cases' n with n
· exact i.elim0
induction' n with n hn generalizing b
· have i0 : i = 0 := Fin.eq_zero _
simp [scanl_singleton, i0, get_zero]; simp [get_eq_get]
· rw [← cons_head_tail v, scanl_cons, get_cons_succ]
refine' Fin.cases _ _ i
· simp only [get_zero, scanl_head, Fin.castSucc_zero, head_cons]
· intro i'
simp only [hn, Fin.castSucc_fin_succ, get_cons_succ]
#align vector.scanl_nth Vector.scanl_get
end Scan
/-- Monadic analog of `Vector.ofFn`.
Given a monadic function on `fin n`, return a `Vector α n` inside the monad. -/
def mOfFn {m} [Monad m] {α : Type u} : ∀ {n}, (Fin n → m α) → m (Vector α n)
| 0, _ => pure nil
| _ + 1, f => do
let a ← f 0
let v ← mOfFn fun i => f i.succ
pure (a ::ᵥ v)
#align vector.m_of_fn Vector.mOfFn
theorem mOfFn_pure {m} [Monad m] [LawfulMonad m] {α} :
∀ {n} (f : Fin n → α), (@mOfFn m _ _ _ fun i => pure (f i)) = pure (ofFn f)
| 0, f => rfl
| n + 1, f => by
rw [mOfFn, @mOfFn_pure m _ _ _ n _, ofFn]
simp
#align vector.m_of_fn_pure Vector.mOfFn_pure
/-- Apply a monadic function to each component of a vector,
returning a vector inside the monad. -/
def mmap {m} [Monad m] {α} {β : Type u} (f : α → m β) : ∀ {n}, Vector α n → m (Vector β n)
| 0, _ => pure nil
| _ + 1, xs => do
let h' ← f xs.head
let t' ← mmap f xs.tail
pure (h' ::ᵥ t')
#align vector.mmap Vector.mmap
@[simp]
theorem mmap_nil {m} [Monad m] {α β} (f : α → m β) : mmap f nil = pure nil :=
rfl
#align vector.mmap_nil Vector.mmap_nil
@[simp]
theorem mmap_cons {m} [Monad m] {α β} (f : α → m β) (a) :
∀ {n} (v : Vector α n),
mmap f (a ::ᵥ v) = do
let h' ← f a
let t' ← mmap f v
pure (h' ::ᵥ t')
| _, ⟨_, rfl⟩ => rfl
#align vector.mmap_cons Vector.mmap_cons
/-- Define `C v` by induction on `v : Vector α n`.
This function has two arguments: `h_nil` handles the base case on `C nil`,
and `h_cons` defines the inductive step using `∀ x : α, C w → C (x ::ᵥ w)`.
This can be used as `induction v using Vector.inductionOn`. -/
@[elab_as_elim]
def inductionOn {C : ∀ {n : ℕ}, Vector α n → Sort _} {n : ℕ} (v : Vector α n)
(h_nil : C nil) (h_cons : ∀ {n : ℕ} {x : α} {w : Vector α n}, C w → C (x ::ᵥ w)) : C v := by
-- porting notes: removed `generalizing`: already generalized
induction' n with n ih
· rcases v with ⟨_ | ⟨-, -⟩, - | -⟩
exact h_nil
· rcases v with ⟨_ | ⟨a, v⟩, v_property⟩
cases v_property
apply @h_cons n _ ⟨v, (add_left_inj 1).mp v_property⟩
apply ih
#align vector.induction_on Vector.inductionOn
-- check that the above works with `induction ... using`
example (v : Vector α n) : True := by induction v using Vector.inductionOn <;> trivial
variable {β γ : Type _}
/-- Define `C v w` by induction on a pair of vectors `v : Vector α n` and `w : Vector β n`. -/
@[elab_as_elim]
def inductionOn₂ {C : ∀ {n}, Vector α n → Vector β n → Sort _}
(v : Vector α n) (w : Vector β n)
(nil : C nil nil) (cons : ∀ {n a b} {x : Vector α n} {y}, C x y → C (a ::ᵥ x) (b ::ᵥ y)) :
C v w := by
-- porting notes: removed `generalizing`: already generalized
induction' n with n ih
· rcases v with ⟨_ | ⟨-, -⟩, - | -⟩
rcases w with ⟨_ | ⟨-, -⟩, - | -⟩
exact nil
· rcases v with ⟨_ | ⟨a, v⟩, v_property⟩
cases v_property
rcases w with ⟨_ | ⟨b, w⟩, w_property⟩
cases w_property
apply @cons n _ _ ⟨v, (add_left_inj 1).mp v_property⟩ ⟨w, (add_left_inj 1).mp w_property⟩
apply ih
#align vector.induction_on₂ Vector.inductionOn₂
/-- Define `C u v w` by induction on a triplet of vectors
`u : Vector α n`, `v : Vector β n`, and `w : Vector γ b`. -/
@[elab_as_elim]
def inductionOn₃ {C : ∀ {n}, Vector α n → Vector β n → Vector γ n → Sort _}
(u : Vector α n) (v : Vector β n) (w : Vector γ n) (nil : C nil nil nil)
(cons : ∀ {n a b c} {x : Vector α n} {y z}, C x y z → C (a ::ᵥ x) (b ::ᵥ y) (c ::ᵥ z)) :
C u v w := by
-- porting notes: removed `generalizing`: already generalized
induction' n with n ih
· rcases u with ⟨_ | ⟨-, -⟩, - | -⟩
rcases v with ⟨_ | ⟨-, -⟩, - | -⟩
rcases w with ⟨_ | ⟨-, -⟩, - | -⟩
exact nil
· rcases u with ⟨_ | ⟨a, u⟩, u_property⟩
cases u_property
rcases v with ⟨_ | ⟨b, v⟩, v_property⟩
cases v_property
rcases w with ⟨_ | ⟨c, w⟩, w_property⟩
cases w_property
apply
@cons n _ _ _ ⟨u, (add_left_inj 1).mp u_property⟩ ⟨v, (add_left_inj 1).mp v_property⟩
⟨w, (add_left_inj 1).mp w_property⟩
apply ih
#align vector.induction_on₃ Vector.inductionOn₃
/-- Cast a vector to an array. -/
def toArray : Vector α n → Array α
| ⟨xs, _⟩ => cast (by rfl) xs.toArray
#align vector.to_array Vector.toArray
section InsertNth
variable {a : α}
/-- `v.insertNth a i` inserts `a` into the vector `v` at position `i`
(and shifting later components to the right). -/
def insertNth (a : α) (i : Fin (n + 1)) (v : Vector α n) : Vector α (n + 1) :=
⟨v.1.insertNth i a, by
rw [List.length_insertNth, v.2]
rw [v.2, ← Nat.succ_le_succ_iff]
exact i.2⟩
#align vector.insert_nth Vector.insertNth
theorem insertNth_val {i : Fin (n + 1)} {v : Vector α n} :
(v.insertNth a i).val = v.val.insertNth i.1 a :=
rfl
#align vector.insert_nth_val Vector.insertNth_val
@[simp]
theorem removeNth_val {i : Fin n} : ∀ {v : Vector α n}, (removeNth i v).val = v.val.removeNth i
| _ => rfl
#align vector.remove_nth_val Vector.removeNth_val
theorem removeNth_insertNth {v : Vector α n} {i : Fin (n + 1)} :
removeNth i (insertNth a i v) = v :=
Subtype.eq <| List.removeNth_insertNth i.1 v.1
#align vector.remove_nth_insert_nth Vector.removeNth_insertNth
theorem removeNth_insertNth' {v : Vector α (n + 1)} :
∀ {i : Fin (n + 1)} {j : Fin (n + 2)},
removeNth (j.succAbove i) (insertNth a j v) = insertNth a (i.predAbove j) (removeNth i v)
| ⟨i, hi⟩, ⟨j, hj⟩ => by
dsimp [insertNth, removeNth, Fin.succAbove, Fin.predAbove]
rw [Subtype.mk_eq_mk]
simp only [Fin.lt_iff_val_lt_val]
split_ifs with hij
· rcases Nat.exists_eq_succ_of_ne_zero
(Nat.pos_iff_ne_zero.1 (lt_of_le_of_lt (Nat.zero_le _) hij)) with ⟨j, rfl⟩
rw [← List.insertNth_removeNth_of_ge]
. simp; rfl
. simpa
. simpa [Nat.lt_succ_iff] using hij
· dsimp
rw [← List.insertNth_removeNth_of_le i j _ _ _]
. rfl
. simpa
. simpa [not_lt] using hij
#align vector.remove_nth_insert_nth' Vector.removeNth_insertNth'
theorem insertNth_comm (a b : α) (i j : Fin (n + 1)) (h : i ≤ j) :
∀ v : Vector α n,
(v.insertNth a i).insertNth b j.succ = (v.insertNth b j).insertNth a (Fin.castSucc i)
| ⟨l, hl⟩ => by
refine' Subtype.eq _
simp only [insertNth_val, Fin.val_succ, Fin.castSucc, Fin.coe_castAdd]
apply List.insertNth_comm
· assumption
· rw [hl]
exact Nat.le_of_succ_le_succ j.2
#align vector.insert_nth_comm Vector.insertNth_comm
end InsertNth
-- porting notes: renamed to `set` from `updateNth` to align with `List`
section ModifyNth
/-- `set v n a` replaces the `n`th element of `v` with `a` -/
def set (v : Vector α n) (i : Fin n) (a : α) : Vector α n :=
⟨v.1.set i.1 a, by simp⟩
#align vector.update_nth Vector.set
@[simp]
theorem toList_set (v : Vector α n) (i : Fin n) (a : α) :
(v.set i a).toList = v.toList.set i a :=
rfl
#align vector.to_list_update_nth Vector.toList_set
@[simp]
theorem get_set_same (v : Vector α n) (i : Fin n) (a : α) : (v.set i a).get i = a := by
cases v; cases i; simp [Vector.set, get_eq_get]
dsimp
exact List.get_set_eq _ _ _ _
#align vector.nth_update_nth_same Vector.get_set_same
theorem get_set_of_ne {v : Vector α n} {i j : Fin n} (h : i ≠ j) (a : α) :
(v.set i a).get j = v.get j := by
cases v; cases i; cases j
simp [Vector.set, Vector.get_eq_get, List.get_set_of_ne (Fin.vne_of_ne h)]
rw [List.get_set_of_ne]
. rfl
. simpa using h
#align vector.nth_update_nth_of_ne Vector.get_set_of_ne
theorem get_set_eq_if {v : Vector α n} {i j : Fin n} (a : α) :
(v.set i a).get j = if i = j then a else v.get j := by
split_ifs <;> try simp [*] <;> try rw [get_set_of_ne] ; assumption
#align vector.nth_update_nth_eq_if Vector.get_set_eq_if
@[to_additive]
theorem prod_set [Monoid α] (v : Vector α n) (i : Fin n) (a : α) :
(v.set i a).toList.prod = (v.take i).toList.prod * a * (v.drop (i + 1)).toList.prod := by
refine' (List.prod_set v.toList i a).trans _
simp_all
#align vector.prod_update_nth Vector.prod_set
@[to_additive]
theorem prod_set' [CommGroup α] (v : Vector α n) (i : Fin n) (a : α) :
(v.set i a).toList.prod = v.toList.prod * (v.get i)⁻¹ * a := by
refine' (List.prod_set' v.toList i a).trans _
simp [get_eq_get, mul_assoc]; rfl
#align vector.prod_update_nth' Vector.prod_set'
end ModifyNth
end Vector
namespace Vector
section Traverse
variable {F G : Type u → Type u}
variable [Applicative F] [Applicative G]
open Applicative Functor
open List (cons)
open Nat
private def traverseAux {α β : Type u} (f : α → F β) : ∀ x : List α, F (Vector β x.length)
| [] => pure Vector.nil
| x :: xs => Vector.cons <$> f x <*> traverseAux f xs
/-- Apply an applicative function to each component of a vector. -/
protected def traverse {α β : Type u} (f : α → F β) : Vector α n → F (Vector β n)
| ⟨v, Hv⟩ => cast (by rw [Hv]) <| traverseAux f v
#align vector.traverse Vector.traverse
section
variable {α β : Type u}
@[simp]
protected theorem traverse_def (f : α → F β) (x : α) :
∀ xs : Vector α n, (x ::ᵥ xs).traverse f = cons <$> f x <*> xs.traverse f := by
rintro ⟨xs, rfl⟩ ; rfl
#align vector.traverse_def Vector.traverse_def
protected theorem id_traverse : ∀ x : Vector α n, x.traverse (pure: _ → Id _)= x :=
by
rintro ⟨x, rfl⟩; dsimp [Vector.traverse, cast]
induction' x with x xs IH; · rfl
simp! [IH]; rfl
#align vector.id_traverse Vector.id_traverse
end
open Function
variable [LawfulApplicative F] [LawfulApplicative G]
variable {α β γ : Type u}
-- We need to turn off the linter here as
-- the `IsLawfulTraversable` instance below expects a particular signature.
@[nolint unusedArguments]
protected theorem comp_traverse (f : β → F γ) (g : α → G β) (x : Vector α n) :
Vector.traverse (Comp.mk ∘ Functor.map f ∘ g) x =
Comp.mk (Vector.traverse f <$> Vector.traverse g x) := by
induction' x using Vector.inductionOn with n x xs ih
simp! [cast, *, functor_norm]
. rfl
. rw [Vector.traverse_def, ih]
simp [functor_norm, (. ∘ .)]
#align vector.comp_traverse Vector.comp_traverse
protected theorem traverse_eq_map_id {α β} (f : α → β) :
∀ x : Vector α n, x.traverse ((pure: _ → Id _) ∘ f) = (pure: _ → Id _) (map f x) := by
rintro ⟨x, rfl⟩ ; simp! ; induction x <;> simp! [*, functor_norm] <;> rfl
#align vector.traverse_eq_map_id Vector.traverse_eq_map_id
variable (η : ApplicativeTransformation F G)
protected theorem naturality {α β : Type _} (f : α → F β) (x : Vector α n) :
η (x.traverse f) = x.traverse (@η _ ∘ f) := by
induction' x using Vector.inductionOn with n x xs ih
. simp! [functor_norm, cast, η.preserves_pure]
. rw [Vector.traverse_def, Vector.traverse_def, ← ih, η.preserves_seq, η.preserves_map]
rfl
#align vector.naturality Vector.naturality
end Traverse
instance : Traversable.{u} (flip Vector n) where
traverse := @Vector.traverse n
map {α β} := @Vector.map.{u, u} α β n
instance : IsLawfulTraversable.{u} (flip Vector n) where
id_traverse := @Vector.id_traverse n
comp_traverse := Vector.comp_traverse
traverse_eq_map_id := @Vector.traverse_eq_map_id n
naturality := Vector.naturality
id_map := by intro _ x; cases x; simp! [(· <$> ·)]
comp_map := by intro _ _ _ _ _ x; cases x; simp! [(· <$> ·)]
map_const := rfl
--Porting note: not porting meta instances
-- unsafe instance reflect [reflected_univ.{u}] {α : Type u} [has_reflect α]
-- [reflected _ α] {n : ℕ} : has_reflect (Vector α n) := fun v =>
-- @Vector.inductionOn α (fun n => reflected _) n v
-- ((by
-- trace
-- "./././Mathport/Syntax/Translate/Tactic/Builtin.lean:76:14:
-- unsupported tactic `reflect_name #[]" :
-- reflected _ @Vector.nil.{u}).subst
-- q(α))
-- fun n x xs ih =>
-- (by
-- trace
-- "./././Mathport/Syntax/Translate/Tactic/Builtin.lean:76:14:
-- unsupported tactic `reflect_name #[]" :
-- reflected _ @Vector.cons.{u}).subst₄
-- q(α) q(n) q(x) ih
-- #align vector.reflect vector.reflect
end Vector
|
{-# LANGUAGE DataKinds #-}
{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}
import FrequencyResponse
import CLaSH.Prelude
import CLaSH.Signal.MultiSignal
import Data.Complex as C
import qualified Prelude as P
import Data.Maybe
import Control.Applicative
import Graphics.EasyPlot
import Data.Map.Strict as Map
{-
Ciruits and stuff
-}
registerP = prepend
firP coeffs x = dotp coeffs (windowP x)
where
dotp as bs = sum (zipWith (*) as bs)
iirP cA cB x = r where
oB = firP cB x
oA = firP cA (registerP def r)
r = oB - oA
-- fir coeficients
firCoef :: Fractional a => Vec 201 a
firCoef = -6.86056317e-19 :> 1.08643703e-04 :> -6.04051550e-18 :> -2.03379801e-04 :> -2.01638331e-04 :> 1.96946883e-18 :> 2.90791068e-18 :> -4.62180925e-04 :> -1.00665733e-03 :> -9.14037108e-04 :> 3.86774364e-18 :> 1.01950810e-03 :> 1.25131737e-03 :> 6.39186084e-04 :> -8.00554425e-18 :> 2.62712857e-18 :> 3.77239653e-04 :> 4.17356596e-04 :> -1.21745475e-17 :> -2.64065618e-04 :> -5.23918059e-18 :> 2.99576343e-04 :> -2.73859684e-18 :> -6.08801988e-04 :> -6.23370976e-04 :> 1.63484509e-17 :> -7.03525331e-18 :> -1.52438502e-03 :> -3.36082345e-03 :> -3.07661933e-03 :> -1.30788363e-17 :> 3.45259832e-03 :> 4.23241069e-03 :> 2.15427395e-03 :> 0.00000000e+00 :> 2.70383448e-17 :> 1.24466846e-03 :> 1.36380726e-03 :> -2.92823518e-17 :> -8.44354542e-04 :> -4.24392593e-17 :> 9.35427798e-04 :> 2.64177628e-17 :> -1.85473668e-03 :> -1.87576073e-03 :> 2.24314248e-18 :> -5.19238250e-17 :> -4.42290170e-03 :> -9.63775624e-03 :> -8.72271164e-03 :> 3.66725201e-17 :> 9.57794343e-03 :> 1.16209519e-02 :> 5.85688426e-03 :> -6.95248052e-17 :> 1.32593176e-17 :> 3.29422893e-03 :> 3.58089966e-03 :> 9.08965047e-18 :> -2.18539647e-03 :> -2.12919221e-17 :> 2.39194534e-03 :> -8.31327663e-17 :> -4.69672484e-03 :> -4.73138591e-03 :> 5.79766610e-17 :> -5.28939995e-18 :> -1.10712423e-02 :> -2.40989091e-02 :> -2.18047819e-02 :> -6.11496326e-17 :> 2.39909500e-02 :> 2.91782046e-02 :> 1.47558239e-02 :> 3.11706634e-17 :> 1.33673427e-18 :> 8.44218666e-03 :> 9.25308362e-03 :> -9.62845645e-17 :> -5.76785543e-03 :> -2.84709264e-17 :> 6.49485159e-03 :> -4.19102125e-17 :> -1.32387105e-02 :> -1.36437840e-02 :> 1.16146829e-16 :> -4.98075231e-17 :> -3.49290893e-02 :> -7.90710907e-02 :> -7.48583001e-02 :> -3.01478553e-33 :> 9.23333495e-02 :> 1.20794568e-01 :> 6.66720749e-02 :> -9.64385396e-17 :> 4.65544367e-17 :> 5.76578486e-02 :> 7.99902785e-02 :> -8.32650050e-17 :> -1.34035769e-01 :> 8.00710266e-01 :> -1.34035769e-01 :> -8.32650050e-17 :> 7.99902785e-02 :> 5.76578486e-02 :> 4.65544367e-17 :> -9.64385396e-17 :> 6.66720749e-02 :> 1.20794568e-01 :> 9.23333495e-02 :> -3.01478553e-33 :> -7.48583001e-02 :> -7.90710907e-02 :> -3.49290893e-02 :> -4.98075231e-17 :> 1.16146829e-16 :> -1.36437840e-02 :> -1.32387105e-02 :> -4.19102125e-17 :> 6.49485159e-03 :> -2.84709264e-17 :> -5.76785543e-03 :> -9.62845645e-17 :> 9.25308362e-03 :> 8.44218666e-03 :> 1.33673427e-18 :> 3.11706634e-17 :> 1.47558239e-02 :> 2.91782046e-02 :> 2.39909500e-02 :> -6.11496326e-17 :> -2.18047819e-02 :> -2.40989091e-02 :> -1.10712423e-02 :> -5.28939995e-18 :> 5.79766610e-17 :> -4.73138591e-03 :> -4.69672484e-03 :> -8.31327663e-17 :> 2.39194534e-03 :> -2.12919221e-17 :> -2.18539647e-03 :> 9.08965047e-18 :> 3.58089966e-03 :> 3.29422893e-03 :> 1.32593176e-17 :> -6.95248052e-17 :> 5.85688426e-03 :> 1.16209519e-02 :> 9.57794343e-03 :> 3.66725201e-17 :> -8.72271164e-03 :> -9.63775624e-03 :> -4.42290170e-03 :> -5.19238250e-17 :> 2.24314248e-18 :> -1.87576073e-03 :> -1.85473668e-03 :> 2.64177628e-17 :> 9.35427798e-04 :> -4.24392593e-17 :> -8.44354542e-04 :> -2.92823518e-17 :> 1.36380726e-03 :> 1.24466846e-03 :> 2.70383448e-17 :> 0.00000000e+00 :> 2.15427395e-03 :> 4.23241069e-03 :> 3.45259832e-03 :> -1.30788363e-17 :> -3.07661933e-03 :> -3.36082345e-03 :> -1.52438502e-03 :> -7.03525331e-18 :> 1.63484509e-17 :> -6.23370976e-04 :> -6.08801988e-04 :> -2.73859684e-18 :> 2.99576343e-04 :> -5.23918059e-18 :> -2.64065618e-04 :> -1.21745475e-17 :> 4.17356596e-04 :> 3.77239653e-04 :> 2.62712857e-18 :> -8.00554425e-18 :> 6.39186084e-04 :> 1.25131737e-03 :> 1.01950810e-03 :> 3.86774364e-18 :> -9.14037108e-04 :> -1.00665733e-03 :> -4.62180925e-04 :> 2.90791068e-18 :> 1.96946883e-18 :> -2.01638331e-04 :> -2.03379801e-04 :> -6.04051550e-18 :> 1.08643703e-04 :> -6.86056317e-19 :> Nil
-- iir coeficients
iirCoefA :: Fractional a => Vec 8 a
iirCoefB :: Fractional a => Vec 9 a
iirCoefA = -1.8933239813032006 :> 3.422153467072297 :> -3.907588921469733 :> 3.6401868030176012 :> -2.5428541496659465 :> 1.3470500696022936 :> -0.49424202583584054 :> 0.10443313376764539 :> Nil
iirCoefB = 0.0025798085212212327 :> 0.02063846816976986 :> 0.07223463859419452 :> 0.14446927718838903 :> 0.18058659648548628 :> 0.14446927718838903 :> 0.07223463859419452 :> 0.02063846816976986 :> 0.0025798085212212327 :> Nil
{-
Drawing helpers
-}
simFuncLin f skip ph = snd $ getSpecLin <$> P.last $ P.take skip $ getResponseLin f ph
simFunc f skip ph = (Map.! 1) $ getSpectrum <$> P.last $ P.take skip $ getResponse f ph
simFuncAcyclic f ph = (Map.! 1) $ getSpectrum $ getResponseAcyclic f ph
genData f sk pn = (x,y) where
x = fmap (\a -> (1.0 * pi * fromInteger a / fromInteger pn)) [0, 1 .. pn]
y = fmap (simFunc f sk) x
-- how is mapping over result like Complex Double -> Double
-- f is ciruit
-- sk skip first sk values from result, for acyclic circuit this should be more than circuitry delay
-- pn - number of linear points from 0 to 1 (nyquist freq)
plt how f sk pn = plot' [] X11 $ Data2D [Style Lines,Title "plot"] [] (P.zip ((/pi) <$> x) (how <$> y))
where
(x,y) = genData f sk pn
genDataLin f sk pn = (x,y) where
x = fmap (\a -> (1.0 * pi * fromInteger a / fromInteger pn)) [0, 1 .. pn]
y = fmap (simFuncLin f sk) x
pltLin how f sk pn = plot' [] X11 $ Data2D [Style Lines,Title "plot"] [] (P.zip ((/pi) <$> x) (how <$> y))
where
(x,y) = genDataLin f sk pn
genDataAcyclic f pn = (x,y) where
x = fmap (\a -> (1.0 * pi * fromInteger a / fromInteger pn)) [0, 1 .. pn]
y = fmap (simFuncAcyclic f) x
pltDataAcyclic how f pn = plot' [] X11 $ Data2D [Style Lines,Title "plot"] [] (P.zip ((/pi) <$> x) (how <$> y))
where
(x,y) = genDataAcyclic f pn
magLog x = logBase 10 (magnitude x) * 20
magLogMin m x = max m (magLog x)
integrator i = r where
r = (registerP 0 r) + i
{-
Examples
-}
-- plots working with linear circuits
plotFirLin = pltLin magnitude f 210 100 where
f = firP firCoef
-- slower and generic version of samplePlotLin
plotFir = plt magnitude f 210 100 where
f = firP firCoef
-- plot acyclic ciruit
plotFirAcyclic = pltDataAcyclic magnitude f 1000 where
f = firP firCoef
plotIir = plt magnitude (iirP iirCoefA iirCoefB) 200 100
plotIirLog = pltLin magLog (iirP iirCoefA iirCoefB) 200 100
plotInteg = plt magnitude integrator 100 100
main = plotIir
|
[GOAL]
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
⊢ ↑↑μ (frontier s) = 0
[PROOFSTEP]
cases' ne_or_eq (affineSpan ℝ s) ⊤ with hspan hspan
[GOAL]
case inl
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
hspan : affineSpan ℝ s ≠ ⊤
⊢ ↑↑μ (frontier s) = 0
[PROOFSTEP]
refine' measure_mono_null _ (addHaar_affineSubspace _ _ hspan)
[GOAL]
case inl
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
hspan : affineSpan ℝ s ≠ ⊤
⊢ frontier s ⊆ ↑(affineSpan ℝ s)
[PROOFSTEP]
exact
frontier_subset_closure.trans (closure_minimal (subset_affineSpan _ _) (affineSpan ℝ s).closed_of_finiteDimensional)
[GOAL]
case inr
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
hspan : affineSpan ℝ s = ⊤
⊢ ↑↑μ (frontier s) = 0
[PROOFSTEP]
rw [← hs.interior_nonempty_iff_affineSpan_eq_top] at hspan
[GOAL]
case inr
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
hspan : Set.Nonempty (interior s)
⊢ ↑↑μ (frontier s) = 0
[PROOFSTEP]
rcases hspan with
⟨x, hx⟩
/- Without loss of generality, `s` is bounded. Indeed, `∂s ⊆ ⋃ n, ∂(s ∩ ball x (n + 1))`, hence it
suffices to prove that `∀ n, μ (s ∩ ball x (n + 1)) = 0`; the latter set is bounded.
-/
[GOAL]
case inr.intro
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
x : E
hx : x ∈ interior s
⊢ ↑↑μ (frontier s) = 0
[PROOFSTEP]
suffices H : ∀ t : Set E, Convex ℝ t → x ∈ interior t → Bounded t → μ (frontier t) = 0
[GOAL]
case inr.intro
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
x : E
hx : x ∈ interior s
H : ∀ (t : Set E), Convex ℝ t → x ∈ interior t → Metric.Bounded t → ↑↑μ (frontier t) = 0
⊢ ↑↑μ (frontier s) = 0
[PROOFSTEP]
let B : ℕ → Set E := fun n => ball x (n + 1)
[GOAL]
case inr.intro
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
x : E
hx : x ∈ interior s
H : ∀ (t : Set E), Convex ℝ t → x ∈ interior t → Metric.Bounded t → ↑↑μ (frontier t) = 0
B : ℕ → Set E := fun n => ball x (↑n + 1)
⊢ ↑↑μ (frontier s) = 0
[PROOFSTEP]
have : μ (⋃ n : ℕ, frontier (s ∩ B n)) = 0 :=
by
refine' measure_iUnion_null fun n => H _ (hs.inter (convex_ball _ _)) _ (bounded_ball.mono (inter_subset_right _ _))
rw [interior_inter, isOpen_ball.interior_eq]
exact ⟨hx, mem_ball_self (add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one)⟩
[GOAL]
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
x : E
hx : x ∈ interior s
H : ∀ (t : Set E), Convex ℝ t → x ∈ interior t → Metric.Bounded t → ↑↑μ (frontier t) = 0
B : ℕ → Set E := fun n => ball x (↑n + 1)
⊢ ↑↑μ (⋃ (n : ℕ), frontier (s ∩ B n)) = 0
[PROOFSTEP]
refine' measure_iUnion_null fun n => H _ (hs.inter (convex_ball _ _)) _ (bounded_ball.mono (inter_subset_right _ _))
[GOAL]
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
x : E
hx : x ∈ interior s
H : ∀ (t : Set E), Convex ℝ t → x ∈ interior t → Metric.Bounded t → ↑↑μ (frontier t) = 0
B : ℕ → Set E := fun n => ball x (↑n + 1)
n : ℕ
⊢ x ∈ interior (s ∩ B n)
[PROOFSTEP]
rw [interior_inter, isOpen_ball.interior_eq]
[GOAL]
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
x : E
hx : x ∈ interior s
H : ∀ (t : Set E), Convex ℝ t → x ∈ interior t → Metric.Bounded t → ↑↑μ (frontier t) = 0
B : ℕ → Set E := fun n => ball x (↑n + 1)
n : ℕ
⊢ x ∈ interior s ∩ ball x (↑n + 1)
[PROOFSTEP]
exact ⟨hx, mem_ball_self (add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one)⟩
[GOAL]
case inr.intro
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
x : E
hx : x ∈ interior s
H : ∀ (t : Set E), Convex ℝ t → x ∈ interior t → Metric.Bounded t → ↑↑μ (frontier t) = 0
B : ℕ → Set E := fun n => ball x (↑n + 1)
this : ↑↑μ (⋃ (n : ℕ), frontier (s ∩ B n)) = 0
⊢ ↑↑μ (frontier s) = 0
[PROOFSTEP]
refine' measure_mono_null (fun y hy => _) this
[GOAL]
case inr.intro
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
x : E
hx : x ∈ interior s
H : ∀ (t : Set E), Convex ℝ t → x ∈ interior t → Metric.Bounded t → ↑↑μ (frontier t) = 0
B : ℕ → Set E := fun n => ball x (↑n + 1)
this : ↑↑μ (⋃ (n : ℕ), frontier (s ∩ B n)) = 0
y : E
hy : y ∈ frontier s
⊢ y ∈ ⋃ (n : ℕ), frontier (s ∩ B n)
[PROOFSTEP]
clear this
[GOAL]
case inr.intro
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
x : E
hx : x ∈ interior s
H : ∀ (t : Set E), Convex ℝ t → x ∈ interior t → Metric.Bounded t → ↑↑μ (frontier t) = 0
B : ℕ → Set E := fun n => ball x (↑n + 1)
y : E
hy : y ∈ frontier s
⊢ y ∈ ⋃ (n : ℕ), frontier (s ∩ B n)
[PROOFSTEP]
set N : ℕ := ⌊dist y x⌋₊
[GOAL]
case inr.intro
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
x : E
hx : x ∈ interior s
H : ∀ (t : Set E), Convex ℝ t → x ∈ interior t → Metric.Bounded t → ↑↑μ (frontier t) = 0
B : ℕ → Set E := fun n => ball x (↑n + 1)
y : E
hy : y ∈ frontier s
N : ℕ := ⌊dist y x⌋₊
⊢ y ∈ ⋃ (n : ℕ), frontier (s ∩ B n)
[PROOFSTEP]
refine' mem_iUnion.2 ⟨N, _⟩
[GOAL]
case inr.intro
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
x : E
hx : x ∈ interior s
H : ∀ (t : Set E), Convex ℝ t → x ∈ interior t → Metric.Bounded t → ↑↑μ (frontier t) = 0
B : ℕ → Set E := fun n => ball x (↑n + 1)
y : E
hy : y ∈ frontier s
N : ℕ := ⌊dist y x⌋₊
⊢ y ∈ frontier (s ∩ B N)
[PROOFSTEP]
have hN : y ∈ B N := by simp [Nat.lt_floor_add_one]
[GOAL]
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
x : E
hx : x ∈ interior s
H : ∀ (t : Set E), Convex ℝ t → x ∈ interior t → Metric.Bounded t → ↑↑μ (frontier t) = 0
B : ℕ → Set E := fun n => ball x (↑n + 1)
y : E
hy : y ∈ frontier s
N : ℕ := ⌊dist y x⌋₊
⊢ y ∈ B N
[PROOFSTEP]
simp [Nat.lt_floor_add_one]
[GOAL]
case inr.intro
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
x : E
hx : x ∈ interior s
H : ∀ (t : Set E), Convex ℝ t → x ∈ interior t → Metric.Bounded t → ↑↑μ (frontier t) = 0
B : ℕ → Set E := fun n => ball x (↑n + 1)
y : E
hy : y ∈ frontier s
N : ℕ := ⌊dist y x⌋₊
hN : y ∈ B N
⊢ y ∈ frontier (s ∩ B N)
[PROOFSTEP]
suffices : y ∈ frontier (s ∩ B N) ∩ B N
[GOAL]
case inr.intro
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
x : E
hx : x ∈ interior s
H : ∀ (t : Set E), Convex ℝ t → x ∈ interior t → Metric.Bounded t → ↑↑μ (frontier t) = 0
B : ℕ → Set E := fun n => ball x (↑n + 1)
y : E
hy : y ∈ frontier s
N : ℕ := ⌊dist y x⌋₊
hN : y ∈ B N
this : y ∈ frontier (s ∩ B N) ∩ B N
⊢ y ∈ frontier (s ∩ B N)
case this
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
x : E
hx : x ∈ interior s
H : ∀ (t : Set E), Convex ℝ t → x ∈ interior t → Metric.Bounded t → ↑↑μ (frontier t) = 0
B : ℕ → Set E := fun n => ball x (↑n + 1)
y : E
hy : y ∈ frontier s
N : ℕ := ⌊dist y x⌋₊
hN : y ∈ B N
⊢ y ∈ frontier (s ∩ B N) ∩ B N
[PROOFSTEP]
exact this.1
[GOAL]
case this
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
x : E
hx : x ∈ interior s
H : ∀ (t : Set E), Convex ℝ t → x ∈ interior t → Metric.Bounded t → ↑↑μ (frontier t) = 0
B : ℕ → Set E := fun n => ball x (↑n + 1)
y : E
hy : y ∈ frontier s
N : ℕ := ⌊dist y x⌋₊
hN : y ∈ B N
⊢ y ∈ frontier (s ∩ B N) ∩ B N
[PROOFSTEP]
rw [frontier_inter_open_inter isOpen_ball]
[GOAL]
case this
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
x : E
hx : x ∈ interior s
H : ∀ (t : Set E), Convex ℝ t → x ∈ interior t → Metric.Bounded t → ↑↑μ (frontier t) = 0
B : ℕ → Set E := fun n => ball x (↑n + 1)
y : E
hy : y ∈ frontier s
N : ℕ := ⌊dist y x⌋₊
hN : y ∈ B N
⊢ y ∈ frontier s ∩ ball x (↑N + 1)
[PROOFSTEP]
exact ⟨hy, hN⟩
[GOAL]
case H
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s : Set E
hs : Convex ℝ s
x : E
hx : x ∈ interior s
⊢ ∀ (t : Set E), Convex ℝ t → x ∈ interior t → Metric.Bounded t → ↑↑μ (frontier t) = 0
[PROOFSTEP]
intro s hs hx hb
[GOAL]
case H
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s✝ : Set E
hs✝ : Convex ℝ s✝
x : E
hx✝ : x ∈ interior s✝
s : Set E
hs : Convex ℝ s
hx : x ∈ interior s
hb : Metric.Bounded s
⊢ ↑↑μ (frontier s) = 0
[PROOFSTEP]
replace hb : μ (interior s) ≠ ∞
[GOAL]
case hb
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s✝ : Set E
hs✝ : Convex ℝ s✝
x : E
hx✝ : x ∈ interior s✝
s : Set E
hs : Convex ℝ s
hx : x ∈ interior s
hb : Metric.Bounded s
⊢ ↑↑μ (interior s) ≠ ⊤
case H
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s✝ : Set E
hs✝ : Convex ℝ s✝
x : E
hx✝ : x ∈ interior s✝
s : Set E
hs : Convex ℝ s
hx : x ∈ interior s
hb : ↑↑μ (interior s) ≠ ⊤
⊢ ↑↑μ (frontier s) = 0
[PROOFSTEP]
exact (hb.mono interior_subset).measure_lt_top.ne
[GOAL]
case H
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s✝ : Set E
hs✝ : Convex ℝ s✝
x : E
hx✝ : x ∈ interior s✝
s : Set E
hs : Convex ℝ s
hx : x ∈ interior s
hb : ↑↑μ (interior s) ≠ ⊤
⊢ ↑↑μ (frontier s) = 0
[PROOFSTEP]
suffices μ (closure s) ≤ μ (interior s) by
rwa [frontier, measure_diff interior_subset_closure isOpen_interior.measurableSet hb, tsub_eq_zero_iff_le]
/- Due to `Convex.closure_subset_image_homothety_interior_of_one_lt`, for any `r > 1` we have
`closure s ⊆ homothety x r '' interior s`, hence `μ (closure s) ≤ r ^ d * μ (interior s)`,
where `d = finrank ℝ E`. -/
[GOAL]
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s✝ : Set E
hs✝ : Convex ℝ s✝
x : E
hx✝ : x ∈ interior s✝
s : Set E
hs : Convex ℝ s
hx : x ∈ interior s
hb : ↑↑μ (interior s) ≠ ⊤
this : ↑↑μ (closure s) ≤ ↑↑μ (interior s)
⊢ ↑↑μ (frontier s) = 0
[PROOFSTEP]
rwa [frontier, measure_diff interior_subset_closure isOpen_interior.measurableSet hb, tsub_eq_zero_iff_le]
/- Due to `Convex.closure_subset_image_homothety_interior_of_one_lt`, for any `r > 1` we have
`closure s ⊆ homothety x r '' interior s`, hence `μ (closure s) ≤ r ^ d * μ (interior s)`,
where `d = finrank ℝ E`. -/
[GOAL]
case H
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s✝ : Set E
hs✝ : Convex ℝ s✝
x : E
hx✝ : x ∈ interior s✝
s : Set E
hs : Convex ℝ s
hx : x ∈ interior s
hb : ↑↑μ (interior s) ≠ ⊤
⊢ ↑↑μ (closure s) ≤ ↑↑μ (interior s)
[PROOFSTEP]
set d : ℕ := FiniteDimensional.finrank ℝ E
[GOAL]
case H
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s✝ : Set E
hs✝ : Convex ℝ s✝
x : E
hx✝ : x ∈ interior s✝
s : Set E
hs : Convex ℝ s
hx : x ∈ interior s
hb : ↑↑μ (interior s) ≠ ⊤
d : ℕ := finrank ℝ E
⊢ ↑↑μ (closure s) ≤ ↑↑μ (interior s)
[PROOFSTEP]
have : ∀ r : ℝ≥0, 1 < r → μ (closure s) ≤ ↑(r ^ d) * μ (interior s) :=
by
intro r hr
refine' (measure_mono <| hs.closure_subset_image_homothety_interior_of_one_lt hx r hr).trans_eq _
rw [addHaar_image_homothety, ← NNReal.coe_pow, NNReal.abs_eq, ENNReal.ofReal_coe_nnreal]
[GOAL]
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s✝ : Set E
hs✝ : Convex ℝ s✝
x : E
hx✝ : x ∈ interior s✝
s : Set E
hs : Convex ℝ s
hx : x ∈ interior s
hb : ↑↑μ (interior s) ≠ ⊤
d : ℕ := finrank ℝ E
⊢ ∀ (r : ℝ≥0), 1 < r → ↑↑μ (closure s) ≤ ↑(r ^ d) * ↑↑μ (interior s)
[PROOFSTEP]
intro r hr
[GOAL]
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s✝ : Set E
hs✝ : Convex ℝ s✝
x : E
hx✝ : x ∈ interior s✝
s : Set E
hs : Convex ℝ s
hx : x ∈ interior s
hb : ↑↑μ (interior s) ≠ ⊤
d : ℕ := finrank ℝ E
r : ℝ≥0
hr : 1 < r
⊢ ↑↑μ (closure s) ≤ ↑(r ^ d) * ↑↑μ (interior s)
[PROOFSTEP]
refine' (measure_mono <| hs.closure_subset_image_homothety_interior_of_one_lt hx r hr).trans_eq _
[GOAL]
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s✝ : Set E
hs✝ : Convex ℝ s✝
x : E
hx✝ : x ∈ interior s✝
s : Set E
hs : Convex ℝ s
hx : x ∈ interior s
hb : ↑↑μ (interior s) ≠ ⊤
d : ℕ := finrank ℝ E
r : ℝ≥0
hr : 1 < r
⊢ ↑↑μ (↑(AffineMap.homothety x ↑r) '' interior s) = ↑(r ^ d) * ↑↑μ (interior s)
[PROOFSTEP]
rw [addHaar_image_homothety, ← NNReal.coe_pow, NNReal.abs_eq, ENNReal.ofReal_coe_nnreal]
[GOAL]
case H
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s✝ : Set E
hs✝ : Convex ℝ s✝
x : E
hx✝ : x ∈ interior s✝
s : Set E
hs : Convex ℝ s
hx : x ∈ interior s
hb : ↑↑μ (interior s) ≠ ⊤
d : ℕ := finrank ℝ E
this : ∀ (r : ℝ≥0), 1 < r → ↑↑μ (closure s) ≤ ↑(r ^ d) * ↑↑μ (interior s)
⊢ ↑↑μ (closure s) ≤ ↑↑μ (interior s)
[PROOFSTEP]
have : ∀ᶠ (r : ℝ≥0) in 𝓝[>] 1, μ (closure s) ≤ ↑(r ^ d) * μ (interior s) := mem_of_superset self_mem_nhdsWithin this
[GOAL]
case H
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s✝ : Set E
hs✝ : Convex ℝ s✝
x : E
hx✝ : x ∈ interior s✝
s : Set E
hs : Convex ℝ s
hx : x ∈ interior s
hb : ↑↑μ (interior s) ≠ ⊤
d : ℕ := finrank ℝ E
this✝ : ∀ (r : ℝ≥0), 1 < r → ↑↑μ (closure s) ≤ ↑(r ^ d) * ↑↑μ (interior s)
this : ∀ᶠ (r : ℝ≥0) in 𝓝[Ioi 1] 1, ↑↑μ (closure s) ≤ ↑(r ^ d) * ↑↑μ (interior s)
⊢ ↑↑μ (closure s) ≤ ↑↑μ (interior s)
[PROOFSTEP]
refine' ge_of_tendsto _ this
[GOAL]
case H
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s✝ : Set E
hs✝ : Convex ℝ s✝
x : E
hx✝ : x ∈ interior s✝
s : Set E
hs : Convex ℝ s
hx : x ∈ interior s
hb : ↑↑μ (interior s) ≠ ⊤
d : ℕ := finrank ℝ E
this✝ : ∀ (r : ℝ≥0), 1 < r → ↑↑μ (closure s) ≤ ↑(r ^ d) * ↑↑μ (interior s)
this : ∀ᶠ (r : ℝ≥0) in 𝓝[Ioi 1] 1, ↑↑μ (closure s) ≤ ↑(r ^ d) * ↑↑μ (interior s)
⊢ Tendsto (fun c => ↑(c ^ d) * ↑↑μ (interior s)) (𝓝[Ioi 1] 1) (𝓝 (↑↑μ (interior s)))
[PROOFSTEP]
refine'
(((ENNReal.continuous_mul_const hb).comp (ENNReal.continuous_coe.comp (continuous_pow d))).tendsto' _ _ _).mono_left
nhdsWithin_le_nhds
[GOAL]
case H
E : Type u_1
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : MeasurableSpace E
inst✝² : BorelSpace E
inst✝¹ : FiniteDimensional ℝ E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
s✝ : Set E
hs✝ : Convex ℝ s✝
x : E
hx✝ : x ∈ interior s✝
s : Set E
hs : Convex ℝ s
hx : x ∈ interior s
hb : ↑↑μ (interior s) ≠ ⊤
d : ℕ := finrank ℝ E
this✝ : ∀ (r : ℝ≥0), 1 < r → ↑↑μ (closure s) ≤ ↑(r ^ d) * ↑↑μ (interior s)
this : ∀ᶠ (r : ℝ≥0) in 𝓝[Ioi 1] 1, ↑↑μ (closure s) ≤ ↑(r ^ d) * ↑↑μ (interior s)
⊢ ((fun x => x * ↑↑μ (interior s)) ∘ ENNReal.some ∘ fun a => a ^ d) 1 = ↑↑μ (interior s)
[PROOFSTEP]
simp
|
#!/usr/bin/env Rscript
## Script Info: This program takes a fasta file that has been processed with ITSx, and
# adds quality scores from the original fastq file.
# Author: Jack Darcy
## set up environment
suppressPackageStartupMessages(require(optparse))
suppressPackageStartupMessages(require(parallel))
## parse arguments
option_list <- list(
make_option(c("-f", "--fasta"), action="store", default=fastas[i], type='character',
help="Input fasta, ITSx output."),
make_option(c("-q", "--fastq"), action="store", default=rawfqs[i], type='character',
help="Input fastq, original file"),
make_option(c("-o", "--output"), action="store", default=NewNames[i], type='character',
help="Output fastq file path"),
make_option(c("-t", "--threads"), action="store", default=16, type='integer',
help="Number of CPU threads to use for parallel processing")
)
opt = parse_args(OptionParser(option_list=option_list))
## some functions (these should really be in a separate file that i source() in, but I'm too lazy):
# function to read in fasta or fastq file as list
# NOTE: ONLY WORKS ON SEQUENTIAL FASTX FILES.
# Hope you aren't still using interleaved files after like 2005
read.fastx <- function(file, type=c("fastq", "fasta")){
# read in raw data
lines <- scan(file, what="character", sep='\n')
# check to make sure data are OK-ish
nlines <- length(lines)
if(type=="fastq" & nlines %% 4 > 0){
stop("CRITICAL ERROR: number of lines in fastq file not divisible by 4.")
}else if(type == "fasta" & nlines %% 2 > 0){
stop("CRITICAL ERROR: number of lines in fasta file not divisible by 2")
}
# make indices for item types (1=header, 2=seq, 3="+", 4=qual)
if(type=="fastq"){
line_inds <- rep(1:4, nlines/4)
}else if(type=="fasta"){
line_inds <- rep(1:2, nlines/2)
}
# make names generic
headers <- as.vector(sapply(X=lines[line_inds == 1], FUN=function(x) substring(x, 2) ) )
# make output list object
if(type=="fastq"){
output <- mapply(FUN=c, lines[line_inds == 2], lines[line_inds == 4], SIMPLIFY=FALSE)
}else if(type=="fasta"){
output <- mapply(FUN=c, lines[line_inds == 2], SIMPLIFY=FALSE)
}
# add names to output list
names(output) <- headers
# all done
return(output)
}
# function to wrout out a fasta or fastq file from a list as generated by read_fastx
write.fastx <- function(outfile, fastxlist, out=c("fastq", "fasta")){
# decide how to make header
if(out=="fastq"){
headchar <- "@"
}else if(out=="fasta"){
headchar <- ">"
}
# write out file, line-by-line
for(i in 1:length(fastxlist)){
firstline <- i == 1
header_i <- paste(headchar, names(fastxlist[i]), sep="")
# write header, don't append if it's the first line
write(header_i, file=outfile, append=firstline==FALSE)
# write sequence
write(fastxlist[[i]][1], file=outfile, append=TRUE)
# if fastq, write + and qual
if(out=="fastq"){
write("+", file=outfile, append=TRUE)
write(fastxlist[[i]][2], file=outfile, append=TRUE)
}
}
}
# function to read a poorly-formatted fasta file
# still won't work on interleaved files, though. Or files with line-breaks
# other than \n.
read.fasta.line.by.line <- function(fasta_fp){
fasta_text <- scan(file=fasta_fp, what='character', sep='\n')
firstchars <- sapply(X=fasta_text, FUN=substr, start=1, stop=1)
nlines <- length(firstchars)
# line_type will tell us what kind of line each line is
# 1=header, 2=sequence, -1=badline, 0=unknown
line_type <- rep(0, nlines)
for(i in 1:(nlines - 1)){
current_lt <- line_type[i]
current_firstchar <- firstchars[i]
next_firstchar <- firstchars[i+1]
# check if line type has already been decided
# (this loop will set future line types)
if(current_lt == 0){
if(current_firstchar == ">" & next_firstchar != ">"){
line_type[i] <- 1
line_type[i+1] <- 2
}else{
line_type[i] <- -1
}
}
}
# build fasta list output
fasta_list <- as.list(fasta_text[line_type==2])
output_headers <- substring(fasta_text[line_type == 1], 2)
names(fasta_list) <- output_headers
return(fasta_list)
}
## read in ITSx fasta file
itsx_fasta_list <- read.fasta.line.by.line(opt$fasta)
## read in original fastq file
fastq_list <- read.fastx(opt$fastq, type="fastq")
## sort both lists alphabetically by header
itsx_fasta_list <- itsx_fasta_list[order(names(itsx_fasta_list))]
fastq_list <- fastq_list[order(names(fastq_list))]
## get rid of seqs not common to both lists
shared_headers <- names(itsx_fasta_list)[ names(itsx_fasta_list) %in% names(fastq_list) ]
itsx_fasta_list <- itsx_fasta_list[names(itsx_fasta_list) %in% shared_headers]
fastq_list <- fastq_list[names(fastq_list) %in% shared_headers]
## merge lists
# this makes a list where each item list[[i]] is as follows:
# i[1]: extracted sequence from ITSx
# i[2]: original raw sequence from fastq
# i[3]: original quality scores for i[2]
combined_list <- mapply(c, itsx_fasta_list, fastq_list, SIMPLIFY=FALSE)
## reverse-compliment function
# x is a string of [ATGC], all upper case
reverse.compliment <- function(x){
# map for complimentary nucleotides
comp_map <- setNames(c("A", "T", "G", "C"), c("T", "A", "C", "G"))
# turn string x into character vector
x <- unlist(strsplit(x, split=""))
# reverse-compliment x
x_rc <- rev(comp_map[unlist(x)])
# return x_rc as string
return(paste(x_rc, collapse=""))
}
## function to apply over combined_list
# this function extracts the quality scores that match up with the itsx extracted sequence
# the function takes list[[i]] from above - a string array of length 3
extract.quals <- function(x){
# x[1]: ITSx extracted seq
# x[2]: full seq
# x[3]: quals for full seq
# find where extracted seq is in full seq
start_ind <- regexpr(pattern=x[1], text=x[2], fixed=TRUE)[1]
# if it wasn't found, RC fastq stuff (not itsx seq)
if(start_ind == -1){
x[2] <- reverse.compliment(x[2])
# qual scores are just reversed :)
x[3] <- paste(rev(unlist(strsplit(x[3], split=""))), collapse="")
# check again
start_ind <- regexpr(pattern=x[1], text=x[2], fixed=TRUE)[1]
# if it STILL isn't found, return seq as error so it can be removed later
if(start_ind == -1){
x[1] <- "seq_not_found"
}else{
stop_ind <- nchar(x[1]) + start_ind - 1
quals <- substr(x[3], start=start_ind, stop=stop_ind)
}
# If it was found, get the quals without changing anything
}else{
stop_ind <- nchar(x[1]) + start_ind - 1
quals <- substr(x[3], start=start_ind, stop=stop_ind)
}
return(c(x[1], quals))
}
# test code for above funtion, FWD
#testx <- c("ATAAAGAGCAT", "AAATCAGCGCTACTAGCGCATCATAAAGAGCATATAGACAGATTTAGATTTAC", "CCCcCCCCCCCCCCCCCCCCCCGOODITWORKSCCCCCCCCCCCCCCCCCCCC")
#extract.quals(testx)
# test code for above function, REV
#testx <- c("ATGCTCTTTAT", "AAATCAGCGCTACTAGCGCATCATAAAGAGCATATAGACAGATTTAGATTTAC", "CCCcCCCCCCCCCCCCCCCCCCSKROWTIDOOGCCCCCCCCCCCCCCCCCCCC")
#extract.quals(testx)
## build output fasta file in parallel
output <- mclapply(X=combined_list, FUN=extract.quals, mc.cores=opt$threads)
## remove items from output that failed to find
identify_bad_seqs <- function(x){
out <- "good"
if(x[1] == "seq_not_found"){
out <- "bad"
}
return(out)
}
badseqs <- lapply(X=output, FUN=identify_bad_seqs)
output <- output[badseqs == "good"]
## write out fastq file
write.fastx(outfile=opt$output, fastxlist=output, out="fastq")
|
-- Andreas, 2013-10-21 fixed this issue
-- by refactoring Internal to spine syntax.
module Issue901 where
open import Common.Level
record Ls : Set where
constructor _,_
field
fst : Level
snd : Level
open Ls
record R (ls : Ls) : Set (lsuc (fst ls ⊔ snd ls)) where
field
A : Set (fst ls)
B : Set (snd ls)
bad : R _
bad = record { A = Set; B = Set₁ }
good : R (_ , _)
good = record { A = Set; B = Set₁ }
{- PROBLEM WAS:
"good" is fine while the body and signature of "bad" are marked in yellow.
Both are fine if we change the parameter of R to not contain levels.
The meta _1 in R _ is never eta-expanded somehow. I think this
problem will vanish if we let whnf eta-expand metas that are
projected. E.g.
fst _1
will result in
_1 := _2,_3
and then reduce to
_2
(And that would be easier to implement if Internal was a spine syntax
(with post-fix projections)). -}
|
"""
Created on 26/12/2021 2021
@author: Dr KL Woon
Time of Flight
Finding transit time by finding the maximum angle
between two lines (here negative angle)
the lines are best-fitted linear line in log-log curve
Only R2 above certain values are used. Interval of data to find
the best fitted lines mimics the normal way doing
Note very long oscillitory overshots might give incorrect result
The onset of photocurrrent must be at zero time
Tested in Python3.9
"""
import csv
import numpy as np
from scipy.signal import savgol_filter
from scipy.optimize import curve_fit
import os
def fitfunction(func,x,y):
popt, pcov = curve_fit(func, x, y)
predicted=func(x, *popt)
r=np.corrcoef(y, predicted)
r2=r[0][1]**2
return popt, r2
def func(m,x,c):
return m*x+c
def reading_file(path):
file=open(path)
csvreader = csv.reader(file)
x,y = [],[]
for row in csvreader:
x0=float(row[0])
y0=float(row[1])
if x0>=0: # data saved when x is greater than zero
x.append(x0)
y.append(y0)
file.close()
x=np.array(x)
y=np.array(y)
y=(y-min(y))*max(x)/max(y) #make x and y are equal propotion
y_filtered = savgol_filter(y, 17, 3) #smoothing parameters
y_filtered[y_filtered<0] = 1.0e-09
return x,y_filtered
def createinterval(totaldatapoint,interval):
x0=totaldatapoint
x=totaldatapoint
n,i=1,0
mylist=[]
while x>0:
x=x-interval*n
mylist.append(interval*n)
i=i+1
if i%2==0 and i!=0:
n=n+1
mylist=mylist[:-1]
mylist.sort(reverse=True)
mylist[0]=mylist[0]+(x0-sum(mylist))
mylist2=[mylist[0]]
for i in range(len(mylist)-1):
z=sum(mylist[0:i+2])
mylist2.append(z)
return mylist2
def search_transit(mylist2,y_filtered,x):
gradient,c,ang,rr2=[],[],[],[]
ii=0
for i in range(len(mylist2)-1): #start from last points and progressing to beginning
if ii==0:
newy=y_filtered[-mylist2[i]:]
newx=x[-1*mylist2[i]:]
if ii!=0:
newy=y_filtered[-mylist2[i+1]:-mylist2[i]]
newx=x[-mylist2[i+1]:-mylist2[i]]
ii=ii+1
newy[newy==0]=0.0000001
newy=np.log10(newy)
newx[newx==0]=0.0000001
newx=np.log10(newx)
popt, r2=fitfunction(func,newx,newy)
rr2.append(r2)
ii=0
for i in range(len(mylist2)-1): #start from last points and progressing to beginning
if ii==0:
newy=y_filtered[-mylist2[i]:]
newx=x[-1*mylist2[i]:]
if ii!=0:
newy=y_filtered[-mylist2[i+1]:-mylist2[i]]
newx=x[-mylist2[i+1]:-mylist2[i]]
ii=ii+1
newy=np.log10(newy)
newx[newx==0]=0.0000001
newx=np.log10(newx)
popt, r2=fitfunction(func,newx,newy)
cut_off=np.median(rr2)*0.9
if r2>cut_off:
gradient.append(popt[0])
c.append(popt[1])
#scale not the same
for i in range(len(c)-1):
angle=np.arctan((gradient[i]-gradient[i+1])/(1+gradient[i+1]*gradient[i])) #calculate angle between 2 lines
ang.append(angle*180/np.pi)
# print(angle*180/np.pi)
min_angle=min(ang) # assumption when angle is positive
location=ang.index(min(ang))
m1=gradient[location]
m2=gradient[location+1]
c1=c[location]
c2=c[location+1]
intersect_x=(c2-c1)/(m1-m2)
return np.power(10,intersect_x)
directory='C:/Users/user/Downloads/HD73_02.09.2021/HD73_02.09.2021' #where is TOF file only CSV file
arr = os.listdir(directory)
f=open('C:/Users/user/Downloads/test.txt','w') #write file
for file in arr:
path=directory+'/'+file
x,y_filtered=reading_file(path)
mydata=[]
for i in range(10):
mylist2=createinterval(len(x),10+i)
intersect_x=search_transit(mylist2,y_filtered,x)
mydata.append(intersect_x)
to_write=np.median(mydata)
print(to_write)
f.write(str(file)+' , '+str(to_write))
f.write('\n')
f.close()
|
/*
#include "gameoflifemodel.h"
#include <QFile>
#include <QTextStream>
#include <QRect>
GameOfLifeModel::GameOfLifeModel(QObject *parent)
: QAbstractTableModel(parent)
{
clear();
}
//! [modelsize]
int GameOfLifeModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return height;
}
int GameOfLifeModel::columnCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return width;
}
//! [modelsize]
//! [read]
QVariant GameOfLifeModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || role != CellRole)
return QVariant();
return QVariant(m_currentState[cellIndex({index.column(), index.row()})]);
}
//! [read]
//! [write]
bool GameOfLifeModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (role != CellRole || data(index, role) == value)
return false;
m_currentState[cellIndex({index.column(), index.row()})] = value.toBool();
emit dataChanged(index, index, {role});
return true;
}
//! [write]
Qt::ItemFlags GameOfLifeModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::NoItemFlags;
return Qt::ItemIsEditable;
}
//! [update]
void GameOfLifeModel::nextStep()
{
StateContainer newValues;
for (std::size_t i = 0; i < size; ++i) {
bool currentState = m_currentState[i];
int cellNeighborsCount = this->cellNeighborsCount(cellCoordinatesFromIndex(static_cast<int>(i)));
newValues[i] = currentState == true
? cellNeighborsCount == 2 || cellNeighborsCount == 3
: cellNeighborsCount == 3;
}
m_currentState = std::move(newValues);
emit dataChanged(index(0, 0), index(height - 1, width - 1), {CellRole});
}
//! [update]
//! [loader]
bool GameOfLifeModel::loadFile(const QString &fileName)
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
return false;
QTextStream in(&file);
loadPattern(in.readAll());
return true;
}
void GameOfLifeModel::loadPattern(const QString &plainText)
{
clear();
QStringList rows = plainText.split("\n");
QSize patternSize(0, rows.count());
for (QString row : rows) {
if (row.size() > patternSize.width())
patternSize.setWidth(row.size());
}
QPoint patternLocation((width - patternSize.width()) / 2, (height - patternSize.height()) / 2);
for (int y = 0; y < patternSize.height(); ++y) {
const QString line = rows[y];
for (int x = 0; x < line.length(); ++x) {
QPoint cellPosition(x + patternLocation.x(), y + patternLocation.y());
m_currentState[cellIndex(cellPosition)] = line[x] == 'O';
}
}
emit dataChanged(index(0, 0), index(height - 1, width - 1), {CellRole});
}
//! [loader]
void GameOfLifeModel::clear()
{
m_currentState.fill(false);
emit dataChanged(index(0, 0), index(height - 1, width - 1), {CellRole});
}
int GameOfLifeModel::cellNeighborsCount(const QPoint &cellCoordinates) const
{
int count = 0;
for (int x = -1; x <= 1; ++x) {
for (int y = -1; y <= 1; ++y) {
if (x == 0 && y == 0)
continue;
const QPoint neighborPosition { cellCoordinates.x() + x, cellCoordinates.y() + y };
if (!areCellCoordinatesValid(neighborPosition))
continue;
if (m_currentState[cellIndex(neighborPosition)])
++count;
if (count > 3)
return count;
}
}
return count;
}
bool GameOfLifeModel::areCellCoordinatesValid(const QPoint &coordinates)
{
return QRect(0, 0, width, height).contains(coordinates);
}
QPoint GameOfLifeModel::cellCoordinatesFromIndex(int cellIndex)
{
return {cellIndex % width, cellIndex / width};
}
std::size_t GameOfLifeModel::cellIndex(const QPoint &coordinates)
{
return std::size_t(coordinates.y() * width + coordinates.x());
}
*/
#include "GameOfLifeModel.hpp"
#include <sstream>
#include <thread>
#include <algorithm>
#include <sstream>
#include <QFile>
#include <QUrl>
#include <QDir>
#include <iostream>
#include <fstream>
#include <regex>
#include <boost/lexical_cast.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/phoenix/bind/bind_function.hpp>
#include <boost/config/warning_disable.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/optional/optional_io.hpp>
GameOfLifeModel::GameOfLifeModel(const Map &map, QObject *parent)
: QAbstractTableModel(parent), height(map.size()), width(map[0].size()), iteration(0)
{
this->mMap = std::make_unique<Map>(this->height);
this->mTmp_map = std::make_unique<Map>(this->height);
for (int i = 0; i < height; i++) {
(*this->mMap)[i] = std::vector<uint8_t>(width);
(*this->mTmp_map)[i] = std::vector<uint8_t>(width);
}
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (map[y][x] == 1)
setCell(x, y);
}
}
}
GameOfLifeModel::GameOfLifeModel(int height, int width, QObject *parent)
: QAbstractTableModel(parent), height(height), width(width), iteration(0)
{
this->mMap = std::make_unique<Map>(this->height);
this->mTmp_map = std::make_unique<Map>(this->height);
for (int i = 0; i < height; i++) {
(*this->mMap)[i] = std::vector<uint8_t>(width);
(*this->mTmp_map)[i] = std::vector<uint8_t>(width);
}
randomFillMap();
}
GameOfLifeModel::~GameOfLifeModel() {}
void GameOfLifeModel::printMap() {
std::stringstream ss;
ss << "Generation number = " << iteration << std::endl;
for (int y = 0; y < height; y++) {
ss << "[" << y << "]\t";
for (int x = 0; x < width; x++) {
if (((*mMap)[y][x] & 0x01) == 1)
ss << "*";
else
ss << ".";
}
ss << std::endl;
}
std::cout << ss.str();
}
void GameOfLifeModel::liveOneGeneration() {
int live_cells_cnt;
// safe copy to mTmp_map
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
(*mTmp_map)[y][x] = (*mMap)[y][x];
this->iteration++;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if ((*mTmp_map)[y][x] == 0)
continue;
// Get count of alive neightbour cells
live_cells_cnt = (*mTmp_map)[y][x] >> 1;
// Is alive ?
if ((*mTmp_map)[y][x] & 0x01) {
// Overpopulation or underpopulation - than die
if (live_cells_cnt != 2 && live_cells_cnt != 3) {
clearCell(x, y);
}
} else if (live_cells_cnt == 3) {
// Has 3 neighbours - than revive
setCell(x, y);
}
}
}
}
void GameOfLifeModel::liveNGeneration(int num_of_generations)
{
while (num_of_generations > 0) {
liveOneGeneration();
num_of_generations--;
}
return;
}
Map_ptr GameOfLifeModel::liveNGeneration(int argc, char **argv,
int num_of_generations,
GOF_verbose_lvl verbose)
{
Q_UNUSED(argc);
Q_UNUSED(argv);
Q_UNUSED(num_of_generations);
Q_UNUSED(verbose);
std::cout << "Unsported. Use liveNGeneration(int) instead." << std::endl;
return nullptr;
}
int GameOfLifeModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return height;
}
int GameOfLifeModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return width;
}
QVariant GameOfLifeModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || role != Qt::DisplayRole)
return QVariant();
const auto y = static_cast<int>(index.row());
const auto x = static_cast<int>(index.column());
// std::cout << "data: x = " << x << ", y = " << y << std::endl;
return QVariant((*mMap)[y][x]);
}
bool GameOfLifeModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
Q_UNUSED(value);
if (!index.isValid() || role != Qt::DisplayRole)
return false;
const auto y = static_cast<int>(index.row());
const auto x = static_cast<int>(index.column());
if ((*mMap)[y][x] & 0x01)
clearCell(x, y);
else
setCell(x, y);
emit dataChanged(index, index, {role});
return true;
}
void GameOfLifeModel::nextStep() {
liveOneGeneration();
emit dataChanged(index(0, 0), index(height - 1, width - 1), {CellRole});
}
bool GameOfLifeModel::parseFile(const std::string &fileName) {
namespace qi = boost::spirit::qi;
namespace phx = boost::phoenix;
std::string line;
std::ifstream file;
std::regex comment("#.*");
std::regex dimensions("height = [0-9]+, width = [0-9]+");
std::regex cell("(\\.|\\*)*");
int mapHeight, mapWidth;
file = std::ifstream(fileName);
if (!file.good()) {
// throw CLI_InvalidFile();
std::cout << "return InvalidFile " << std::endl;
return false;
}
// skip empty lines
while (std::getline(file, line)) {
if (std::regex_match(line, comment) || line.empty())
continue;
else
break;
}
// parse dimesions line
auto begin = line.begin();
auto end = line.end();
bool ok = qi::phrase_parse
(
begin,
end,
"height = " >>
qi::int_[phx::ref(mapHeight) = qi::_1] >>
", width = " >>
qi::int_[phx::ref(mapWidth) = qi::_1],
qi::space
);
if (!ok) {
// throw CLI_InvalidFile();
std::cout << "return InvalidFile " << std::endl;
return false;
}
// TODO: make it more beautiful
// resize and clear map
(*mMap).resize(mapHeight);
for (auto &line : (*mMap)) {
line.resize(mapWidth);
std::fill(line.begin(), line.end(), 0);
}
// resize and clear Tmp_map
(*mTmp_map).resize(mapHeight);
for (auto &line : (*mTmp_map)) {
line.resize(mapWidth);
std::fill(line.begin(), line.end(), 0);
}
this->height = mapHeight;
this->width = mapWidth;
this->iteration = 0;
// parse cells
int y = 0;
while (std::getline(file, line)) {
if (std::regex_match(line, cell)) {
for (unsigned x = 0; x < line.length(); x++) {
if (line[x] == '*')
setCell(x, y);
}
} else {
// throw CLI_InvalidMap();
std::cout << "return InvalidMap " << std::endl;
return false;
}
y++;
}
return true;
}
QString filterFileName(const QString &urlString) {
const QUrl url(urlString);
if (url.isLocalFile())
return QDir::toNativeSeparators(url.toLocalFile());
else
return urlString;
}
bool GameOfLifeModel::loadFile(const QString &filePath) {
auto res = parseFile(filePath.toStdString());
emit dataChanged(index(0, 0), index(height - 1, width - 1), {CellRole});
std::cout << "return res = " << res << std::endl;
return res;
}
std::string GameOfLifeModel::prepareMap() {
std::stringstream ss;
ss << "height = " << height << ", width = " << width << std::endl;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++)
ss << ((*mMap)[y][x] & 0x01 ? "*" : ".");
ss << std::endl;
}
return ss.str();
}
bool GameOfLifeModel::saveToFile(const QString &filePath) {
std::string mapStr = prepareMap();
bool res = false;
try {
std::ofstream file(filePath.toStdString(), std::ofstream::out);
file << mapStr;
file.close();
res = true;
} catch (const char* msg) {
std::cerr << "Error: " << msg << std::endl;
}
return res;
}
int GameOfLifeModel::getIteration()
{
return iteration;
}
void GameOfLifeModel::_randomFillMap() {
unsigned seed;
int x, y;
// Get seed; random if 0
seed = (unsigned)time(NULL);
srand(seed);
// Randomly initialise cell map with ~50% on pixels
for (int half_len = (height * width) / 2; half_len > 0; half_len--) {
x = rand() % (width);
y = rand() % (height);
if (((*mMap)[y][x] & 0x01) == 0) {
setCell(x, y);
}
}
}
void GameOfLifeModel::randomFillMap() {
for (int i = 0; i < this->height; i++)
std::fill((*mMap)[i].begin(), (*mMap)[i].end(), 0);
_randomFillMap();
iteration = 0;
emit dataChanged(index(0, 0), index(height - 1, width - 1), {CellRole});
}
void GameOfLifeModel::setCell(int x, int y) {
int x_left, x_right, y_up, y_down;
x_left = (x == 0) ? width - 1 : x - 1;
x_right = (x == width - 1) ? 0 : x + 1;
y_up = (y == 0) ? height - 1 : y - 1;
y_down = (y == height - 1) ? 0 : y + 1;
(*mMap)[y][x] |= 0x01;
(*mMap)[y_up ][x_left ] += 0x02;
(*mMap)[y_up ][x ] += 0x02;
(*mMap)[y_up ][x_right] += 0x02;
(*mMap)[y ][x_left ] += 0x02;
(*mMap)[y ][x_right] += 0x02;
(*mMap)[y_down][x_left ] += 0x02;
(*mMap)[y_down][x ] += 0x02;
(*mMap)[y_down][x_right] += 0x02;
}
void GameOfLifeModel::clearCell(int x, int y) {
int x_left, x_right, y_up, y_down;
x_left = (x == 0) ? width - 1 : x - 1;
x_right = (x == width - 1) ? 0 : x + 1;
y_up = (y == 0) ? height - 1 : y - 1;
y_down = (y == height - 1) ? 0 : y + 1;
(*mMap)[y][x] &= ~0x01;
(*mMap)[y_up ][x_left ] -= 0x02;
(*mMap)[y_up ][x ] -= 0x02;
(*mMap)[y_up ][x_right] -= 0x02;
(*mMap)[y ][x_left ] -= 0x02;
(*mMap)[y ][x_right] -= 0x02;
(*mMap)[y_down][x_left ] -= 0x02;
(*mMap)[y_down][x ] -= 0x02;
(*mMap)[y_down][x_right] -= 0x02;
}
int GameOfLifeModel::getLiveNeighbours(int x, int y) {
return ((*mMap)[y][x] >> 1);
}
|
If $f$ and $g$ are asymptotically equivalent, then the ratio $f(x)/g(x)$ tends to $1$ as $x$ tends to infinity.
|
Formal statement is: lemma\<^marker>\<open>tag unimportant\<close> orthogonal_transformation_neg: "orthogonal_transformation(\<lambda>x. -(f x)) \<longleftrightarrow> orthogonal_transformation f" Informal statement is: A linear transformation $f$ is orthogonal if and only if $-f$ is orthogonal.
|
% This is used to set the VIF algorithms that to be run
%
% Author:Xingchen Zhang, Ping Ye, Gang Xiao
% Contact: [email protected]
function methods=configMethods
methodVIFB={struct('name','ADF'),...
struct('name','CBF'),...
struct('name','CNN'),...
struct('name','DLF'),...
struct('name','FPDE'),...
struct('name','GFCE'),...
struct('name','GFF'),...
struct('name','GTF'),...
struct('name','HMSD_GF'),...
struct('name','Hybrid_MSD'),...
struct('name','IFEVIP'),...
struct('name','LatLRR'),...
struct('name','MGFF'),...
struct('name','MST_SR'),...
struct('name','MSVD'),...
struct('name','NSCT_SR'),...
struct('name','ResNet'),...
struct('name','RP_SR'),...
struct('name','TIF'),...
struct('name','VSMWLS'),...
};
methods = [methodVIFB];
|
(*******************************************************************************
Project: IsaNet
Author: Tobias Klenze, ETH Zurich <[email protected]>
Christoph Sprenger, ETH Zurich <[email protected]>
Version: JCSPaper.1.0
Isabelle Version: Isabelle2021-1
Copyright (c) 2022 Tobias Klenze, Christoph Sprenger
Licence: Mozilla Public License 2.0 (MPL) / BSD-3-Clause (dual license)
*******************************************************************************)
section\<open>Network Assumptions used for authorized segments.\<close>
theory Network_Assumptions
imports
"Network_Model"
begin
locale network_assums_generic = network_model _ auth_seg0 for
auth_seg0 :: "('ainfo \<times> 'aahi ahi_scheme list) set" +
assumes
\<comment> \<open>All authorized segments have valid interfaces\<close>
ASM_if_valid: "(info, l) \<in> auth_seg0 \<Longrightarrow> ifs_valid_None l" and
\<comment> \<open>All authorized segments are rooted, i.e., they start with None\<close>
ASM_empty [simp, intro!]: "(info, []) \<in> auth_seg0" and
ASM_rooted: "(info, l) \<in> auth_seg0 \<Longrightarrow> rooted l" and
ASM_terminated: "(info, l) \<in> auth_seg0 \<Longrightarrow> terminated l"
locale network_assums_undirect = network_assums_generic _ _ +
assumes
ASM_adversary: "\<lbrakk>\<And>hf. hf \<in> set hfs \<Longrightarrow> ASID hf \<in> bad\<rbrakk> \<Longrightarrow> (info, hfs) \<in> auth_seg0"
locale network_assums_direct = network_assums_generic _ _ +
assumes
ASM_singleton: "\<lbrakk>ASID hf \<in> bad\<rbrakk> \<Longrightarrow> (info, [hf]) \<in> auth_seg0" and
ASM_extension: "\<lbrakk>(info, hf2#ys) \<in> auth_seg0; ASID hf2 \<in> bad; ASID hf1 \<in> bad\<rbrakk>
\<Longrightarrow> (info, hf1#hf2#ys) \<in> auth_seg0" and
ASM_modify: "\<lbrakk>(info, hf#ys) \<in> auth_seg0; ASID hf = a; ASID hf' = a; UpIF hf' = UpIF hf; a \<in> bad\<rbrakk>
\<Longrightarrow> (info, hf'#ys) \<in> auth_seg0" and
ASM_cutoff: "\<lbrakk>(info, zs@hf#ys) \<in> auth_seg0; ASID hf = a; a \<in> bad\<rbrakk> \<Longrightarrow> (info, hf#ys) \<in> auth_seg0"
begin
lemma auth_seg0_non_empty [simp, intro!]: "auth_seg0 \<noteq> {}"
by auto
lemma auth_seg0_non_empty_frag [simp, intro!]: "\<exists> info . pfragment info [] auth_seg0"
apply(auto simp add: pfragment_def)
by (metis append_Nil2 ASM_empty)
text \<open>This lemma applies the extendability assumptions on @{text "auth_seg0"} to pfragments of
@{text "auth_seg0"}.\<close>
lemma extend_pfragment0:
assumes "pfragment ainfo (hf2#xs) auth_seg0"
assumes "ASID hf1 \<in> bad"
assumes "ASID hf2 \<in> bad"
shows "pfragment ainfo (hf1#hf2#xs) auth_seg0"
using assms
by(auto intro!: pfragmentI[of _ "[]" _ _] elim!: pfragmentE intro: ASM_cutoff intro!: ASM_extension)
text\<open>This lemma shows that the above assumptions imply that of the undirected setting\<close>
lemma "\<lbrakk>\<And>hf. hf \<in> set hfs \<Longrightarrow> ASID hf \<in> bad\<rbrakk> \<Longrightarrow> (info, hfs) \<in> auth_seg0"
apply(induction hfs)
using ASM_empty apply blast
subgoal for a hfs
apply(cases hfs)
by(auto intro!: ASM_singleton ASM_extension)
done
end
end
|
\section{Fonts}
To stick entirely to the corporate design of the Universiteit Antwerpen, one is
bound to use the official font series \enquote{Auto} of Underware
\cite{Underware::ATI}. As stated on the UA website, \textquote[KAN::T][.]{Een
weloverwogen en consequente gebruik van typografie is de ruggengraat van een
huisstijl.} (A deliberate and consistent use of typography is the backbone of a
corporate design.).
Unfortunately, these fonts are not freely available, not even for university
members. In order to make use of the most basic fonts, it would be enough to
buy \enquote{Auto~1 office package}, available for \EUR{200} per personal
license. The files can be purchased either in TrueType OpenType format
(\lstinline!.ttf!) or PostScript Type 1 format (\lstinline!.pfm!). While the
PostScript format is native to \LaTeX{} for a long time, it TrueType-fonts can
also be used natively in \LaTeX{} with \lstinline!lualatex!; see the example
file for how to use it.
\begin{table}
\centering
\newcommand\quickfox{The quick brown fox jumps over the lazy dog. 0123456789}
\newcommand\ligatures{ff fl fi ffi ij To AV \'e \`a \"a \"o \"u \"{\i} \oe{} \ae{} \ss{} - -- --- ?`? \% \& @}
\begin{tabular}{lll}\toprule
weight & shape & sample\\\midrule
light & normal & {\fontspec{auto1-light-lf}\quickfox}\\
& & {\fontspec{auto1-light-lf}\ligatures}\\
& italic & {\fontspec{auto1-light-italic-lf}\quickfox}\\
& & {\fontspec{auto1-light-italic-lf}\ligatures}\\
& small caps & {\fontspec{auto1-light-smcp}\quickfox}\\
& & {\fontspec{auto1-light-smcp}\ligatures}\\
& italic small caps & {\fontspec{auto1-light-italicsmcp}\quickfox}\\
& & {\fontspec{auto1-light-italicsmcp}\ligatures}\\\midrule
regular & normal & {\fontspec{auto1-lf}\quickfox}\\
& & {\fontspec{auto1-lf}\ligatures}\\
& italic & {\fontspec{auto1-italic-lf}\quickfox}\\
& & {\fontspec{auto1-italic-lf}\ligatures}\\
& small caps & {\fontspec{auto1-smcp}\quickfox}\\
& & {\fontspec{auto1-smcp}\ligatures}\\
& italic small caps & {\fontspec{auto1-italicsmcp}\quickfox}\\
& & {\fontspec{auto1-italicsmcp}\ligatures}\\\midrule
bold & normal & {\fontspec{auto1-bold-lf}\quickfox}\\
& & {\fontspec{auto1-bold-lf}\ligatures}\\
& italic & {\fontspec{auto1-bold-italic-lf}\quickfox}\\
& & {\fontspec{auto1-bold-italic-lf}\ligatures}\\
& small caps & {\fontspec{auto1-bold-smcp}\quickfox}\\
& & {\fontspec{auto1-bold-smcp}\ligatures}\\
& italic small caps & {\fontspec{auto1-bold-italicsmcp}\quickfox}\\
& & {\fontspec{auto1-bold-italicsmcp}\ligatures}\\\midrule
black & normal & {\fontspec{auto1-black-lf}\quickfox}\\
& & {\fontspec{auto1-black-lf}\ligatures}\\
& italic & {\fontspec{auto1-black-italic-lf}\quickfox}\\
& & {\fontspec{auto1-black-italic-lf}\ligatures}\\
& small caps & {\fontspec{auto1-black-smcp}\quickfox}\\
& & {\fontspec{auto1-black-smcp}\ligatures}\\
& italic small caps & {\fontspec{auto1-black-italicsmcp}\quickfox}\\
& & {\fontspec{auto1-black-italicsmcp}\ligatures}\\\bottomrule
\end{tabular}
\caption{Samples of the font Auto 1 of Underware. All regular and italic
versions are available with lining and old-style figures.}
\end{table}
|
#include <vector>
#include <iostream>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string.hpp>
#include <sstream>
#include "CorruptionChecksumSolver.h"
int CorruptionChecksumSolver::solve(const std::string &matrix) const {
int result{0};
std::vector<std::string> tokens;
std::vector<int> values;
std::string line;
std::istringstream iss(matrix);
while(std::getline(iss, line)) {
if (line.find('\t') == std::string::npos)
break;
values.clear(); tokens.clear();
boost::split(tokens, line, boost::is_any_of("\t"));
std::transform(tokens.begin(), tokens.end(), std::back_inserter(values),
[](const std::string& str) { return std::stoi(str); });
auto minmax = std::minmax_element(values.begin(), values.end());
result += *minmax.second - *minmax.first;
}
return result;
}
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% successive approximation converter %
% with finite DAC's slew-rate and bandwidth %
% code by Fabrizio Conso, university of pavia, student %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [counter,thresholds]=Approx(input,nbit,f_bw,sr,f_s)
% input= input sample
% nbit= number of converter bits
% f_bw= DAC bandwidth [f_s]
% sr= DAC slew-rate [V_fs/T_s]
% f_s= sampling frequency
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% global variables %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
threshold(1,nbit+1)=0; % threshold array
counter=0; % converter decimal output
threshold(1)=0.5; % 0 threshold
threshold(2)=0.5; % first threshold
threshold_id=0.5; % next ideal threshold
tau=1/(2*pi*f_bw); % DAC output pole
in=input;
Tmax=1/(f_s*nbit); % clock period
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i=2:(nbit+1) % conversion cycle
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% finite bandwidth & slew-rate %
% error calculation %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
deltaV=abs(threshold_id-threshold(i-1));
slope=deltaV/tau;
if slope > sr
tslew=(deltaV/sr) - tau;
if tslew >= Tmax % only slewing
error = deltaV - sr*Tmax;
else
texp = Tmax - tslew;
error = (deltaV-sr*tslew)*exp(-texp/tau);
end
else % only exponential settling
texp = Tmax;
error = deltaV*exp(-texp/tau);
end
threshold(i) = threshold_id - sign(threshold_id-threshold(i-1))*error;
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% successive approximation %
% conversion algorythm %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
if (in-threshold(i)) > 0
threshold_id=threshold_id+1/2^i;
bit=1;
else
threshold_id=threshold_id-1/2^i;
bit=0;
end
counter=(counter+bit*2^(nbit-i+1));
thresholds(i-1)=threshold(i);
end
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Output %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
counter=counter;
if nargout > 1
thresholds=thresholds;
end
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
\documentclass[12pt,letterpaper]{report}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{pdfpages}
\usepackage{graphicx}
\graphicspath{{../sharedfiles/}}
\usepackage[left=0.50in, right=0.50in, top=0.50in, bottom=0.50in]{geometry}
\author{Anthony Odenthal}
\author{National Conference of Volunteer Examiners; edited by Anthony Odenthal KE7OSN}
\title{Amateur Radio General Class Exam Questions and Answers for July 2011 to July 2015}
\begin{document}
\maketitle
\section{Preamble}
The following is the entire question pool for the General class amateur radio exam with answers. The text comes from the NCVEC National Conference of Volunteer Examiners website http://www.ncvec.org/page.php?id=358 on November 21 2013 and edited to remove the distractors (wrong answers). For questions with the answer "All of the above" the distractors were left in place for the information of anyone using this document. This document also lacks the list of corrections and modifications the original had.
Each subelement indicates the number of groups and the number of exam questions that comes form that subelement. Questions are formatted as Question Number (Letter of the correct Answer) [FCC rule number if applicable] question, the letter and answer for the correct response is listed on the second line.
\tableofcontents
\chapter*{Syllabus}
General Class Question Pool Syllabus 2011-2015
SUBELEMENT G1 - COMMISSION'S RULES [5 Exam Questions - 5 Groups]
G1A - General Class control operator frequency privileges; primary and secondary allocations
G1B - Antenna structure limitations; good engineering and good amateur practice; beacon operation; restricted operation; retransmitting radio signals
G1C - Transmitter power regulations; data emission standards
G1D - Volunteer Examiners and Volunteer Examiner Coordinators; temporary identification
G1E - Control categories; repeater regulations; harmful interference; third party rules; ITU regions
SUBELEMENT G2 - OPERATING PROCEDURES [5 Exam Questions - 5 Groups]
G2A Phone operating procedures; USB/LSB utilization conventions; procedural signals; breaking into a QSO in progress; VOX operation
G2B - Operating courtesy; band plans, emergencies, including drills and emergency communications
G2C - CW operating procedures and procedural signals, Q signals and common abbreviations; full break in
G2D - Amateur Auxiliary; minimizing interference; HF operations
G2E - Digital operating: procedures, procedural signals and common abbreviations
SUBELEMENT G3 - RADIO WAVE PROPAGATION [3 Exam Questions - 3 Groups]
G3A - Sunspots and solar radiation; ionospheric disturbances; propagation forecasting and indices
G3B - Maximum Usable Frequency; Lowest Usable Frequency; propagation
G3C - Ionospheric layers; critical angle and frequency; HF scatter; Near Vertical Incidence Sky waves
SUBELEMENT G4 - AMATEUR RADIO PRACTICES [5 Exam Questions - 5 groups]
G4A - Station Operation and setup
G4B - Test and monitoring equipment; two-tone test
G4C - Interference with consumer electronics; grounding; DSP
G4D - Speech processors; S meters; sideband operation near band edges
G4E - HF mobile radio installations; emergency and battery powered operation
SUBELEMENT G5 - ELECTRICAL PRINCIPLES [3 exam questions - 3 groups]
G5A - Reactance; inductance; capacitance; impedance; impedance matching
G5B - The Decibel; current and voltage dividers; electrical power calculations; sine wave root-mean-square (RMS) values; PEP calculations
G5C - Resistors, capacitors and inductors in series and parallel; transformers
SUBELEMENT G6 - CIRCUIT COMPONENTS [3 exam question - 3 groups]
G6A - Resistors; capacitors; inductors
G6B - Rectifiers; solid state diodes and transistors; vacuum tubes; batteries
G6C - Analog and digital integrated circuits (IC's); microprocessors; memory; I/O devices; microwave IC's (MMIC's ); display devices
SUBELEMENT G7 - PRACTICAL CIRCUITS [3 exam question - 3 groups]
G7A - Power supplies; schematic symbols
G7B - Digital circuits; amplifiers and oscillators
G7C - Receivers and transmitters; filters, oscillators
SUBELEMENT G8 - SIGNALS AND EMISSIONS [2 exam questions - 2 groups]
G8A - Carriers and modulation: AM; FM; single and double sideband; modulation envelope; overmodulation
G8B - Frequency mixing; multiplication; HF data communications; bandwidths of various modes; deviation
SUBELEMENT G9 - ANTENNAS AND FEED LINES [4 exam questions - 4 groups]
G9A - Antenna feed lines: characteristic impedance and attenuation; SWR calculation, measurement and effects; matching networks
G9B - Basic antennas
G9C - Directional antennas
G9D - Specialized antennas
SUBELEMENT G0 - ELECTRICAL AND RF SAFETY [2 exam Questions - 2 groups]
G0A - RF safety principles, rules and guidelines; routine station evaluation
G0B - Safety in the ham shack: electrical shock and treatment, safety grounding, fusing, interlocks, wiring, antenna and tower safety
General Class Question Pool Effective July 1, 2011 - June 30, 2015
\chapter{Subelement G1 - Commission's Rules: 5 Questions}
\section{G1A - General Class control operator frequency privileges; primary and secondary allocations}
G1A01 (C) [97.301(d), 97.303(s)] On which of the following bands is a General Class license holder granted all amateur frequency privileges?\\
C. 160, 60, 30, 17, 12, and 10 meters\\
G1A02 (B) [97.305] On which of the following bands is phone operation prohibited?\\
B. 30 meters\\
G1A03 (B) [97.305] On which of the following bands is image transmission prohibited? \\
B. 30 meters\\
G1A04 (D) [97.303 (s)] Which of the following amateur bands is restricted to communication on only specific channels, rather than frequency ranges?\\
D. 60 meters\\
G1A05 (A) [97.301(d)] Which of the following frequencies is in the General Class portion of the 40 meter band?\\
A. 7.250 MHz\\
G1A06 (D) [97.301(d) Which of the following frequencies is in the 12 meter band?\\
D. 24.940 MHz\\
G1A07 (C) [97.301(d)] Which of the following frequencies is within the General Class portion of the 75 meter phone band?\\
C. 3900 kHz\\
G1A08 (C) [97.301(d)] Which of the following frequencies is within the General Class portion of the 20 meter phone band?\\
C. 14305 kHz\\
G1A09 (C) [97.301(d)] Which of the following frequencies is within the General Class portion of the 80 meter band?\\
C. 3560 kHz\\
G1A10 (C) [97.301(d)] Which of the following frequencies is within the General Class portion of the 15 meter band?\\
C. 21300 kHz\\
G1A11 (D) [97.301(d)] Which of the following frequencies is available to a control operator holding a General Class license?\\
A. 28.020 MHz\\
B. 28.350 MHz\\
C. 28.550 MHz\\
D. All of these choices are correct\\
G1A12 (B) [97.301] When General Class licensees are not permitted to use the entire voice portion of a particular band, which portion of the voice segment is generally available to them? \\
B. The upper frequency end\\
G1A13 (D) [97.303] Which, if any, amateur band is shared with the Citizens Radio Service?\\
D. None\\
G1A14 (C) [97.303] Which of the following applies when the FCC rules designate the Amateur Service as a secondary user on a band?\\
C. Amateur stations are allowed to use the band only if they do not cause harmful interference to primary\\ users
G1A15 (D) [97.303] What is the appropriate action if, when operating on either the 30 or 60 meter bands, a station in the primary service interferes with your contact? \\
D. Move to a clear frequency\\
\section{G1B - Antenna structure limitations; good engineering and good amateur practice; beacon operation; restricted operation; retransmitting radio signals}
G1B01 (C) [97.15(a)] What is the maximum height above ground to which an antenna structure may be erected without requiring notification to the FAA and registration with the FCC, provided it is not at or near a public use airport?\\
C. 200 feet\\
G1B02 (D) [97.203(b)] With which of the following conditions must beacon stations comply?\\
D. There must be no more than one beacon signal in the same band from a single location\\
G1B03 (A) [97.3(a)(9)] Which of the following is a purpose of a beacon station as identified in the FCC Rules?\\
A. Observation of propagation and reception\\
G1B04 (A) [97.113(b)] Which of the following must be true before amateur stations may provide communications to broadcasters for dissemination to the public?\\
A. The communications must directly relate to the immediate safety of human life or protection of property and there must be no other means of communication reasonably available before or at the time of the event\\
G1B05 (D) [97.113(a)(5),(e)] When may music be transmitted by an amateur station?\\
D. When it is an incidental part of a manned space craft retransmission\\
G1B06 (B) [97.113(a)(4) and 97.207(f)] When is an amateur station permitted to transmit secret codes?\\
B. To control a space station\\
G1B07 (B) [97.113(a)(4)] What are the restrictions on the use of abbreviations or procedural signals in the Amateur Service?\\
B. They may be used if they do not obscure the meaning of a message\\
G1B08 (D) When choosing a transmitting frequency, what should you do to comply with good amateur practice?\\
A. Review FCC Part 97 Rules regarding permitted frequencies and emissions.\\
B. Follow generally accepted band plans agreed to by the Amateur Radio community.\\
C. Before transmitting, listen to avoid interfering with ongoing communication\\
D. All of these choices are correct\\
G1B09 (A) [97.113(a)(3)] When may an amateur station transmit communications in which the licensee or control operator has a pecuniary (monetary) interest?\\
A. When other amateurs are being notified of the sale of apparatus normally used in an amateur station and such activity is not done on a regular basis\\
G1B10 (C) [97.203(c)] What is the power limit for beacon stations?\\
C. 100 watts PEP output\\
G1B11 (C) [97.101(a)] How does the FCC require an amateur station to be operated in all respects not specifically covered by the Part 97 rules?\\
C. In conformance with good engineering and good amateur practice\\
G1B12 (A) [97.101(a)] Who or what determines "good engineering and good amateur practice" as applied to the operation of an amateur station in all respects not covered by the Part 97 rules?\\
A. The FCC\\
\section{G1C - Transmitter power regulations; data emission standards}
G1C01 (A) [97.313(c)(1)] What is the maximum transmitting power an amateur station may use on 10.140 MHz?\\
A. 200 watts PEP output\\
G1C02 (C) [97.313(a),(b)] What is the maximum transmitting power an amateur station may use on the 12 meter band?\\
C. 1500 watts PEP output\\
G1C03 (A) [97.303s] What is the maximum bandwidth permitted by FCC rules for Amateur Radio stations when transmitting on USB frequencies in the 60 meter band?\\
A. 2.8 kHz\\
G1C04 (A) [97.313] Which of the following is a limitation on transmitter power on the 14 MHz band?\\
A. Only the minimum power necessary to carry out the desired communications should be used\\
G1C05 (C) [97.313] Which of the following is a limitation on transmitter power on the 28 MHz band?\\
C. 1500 watts PEP output\\
G1C06 (D) [97.313] Which of the following is a limitation on transmitter power on 1.8 MHz band?\\
D. 1500 watts PEP output\\
G1C07 (D) [97.305(c), 97.307(f)(3)] What is the maximum symbol rate permitted for RTTY or data emission transmission on the 20 meter band?\\
D. 300 baud\\
G1C08 (D) [97.307(f)(3)] What is the maximum symbol rate permitted for RTTY or data emission transmitted at frequencies below 28 MHz? \\
D. 300 baud \\
G1C09 (A) [97.305(c) and 97.307(f)(5)] What is the maximum symbol rate permitted for RTTY or data emission transmitted on the 1.25 meter and 70 centimeter bands\\
A. 56 kilobaud \\
G1C10 (C) [97.305(c) and 97.307(f)(4)] What is the maximum symbol rate permitted for RTTY or data emission transmissions on the 10 meter band?\\
C. 1200 baud\\
G1C11 (B) [97.305(c) and 97.307(f)(5)] What is the maximum symbol rate permitted for RTTY or data emission transmissions on the 2 meter band?\\
B. 19.6 kilobaud\\
\section{G1D - Volunteer Examiners and Volunteer Examiner Coordinators; temporary identification}
G1D01 (C) [97.119(f)(2)] Which of the following is a proper way to identify when transmitting using phone on General Class frequencies if you have a CSCE for the required elements but your upgrade from Technician has not appeared in the FCC database?\\
C. Give your call sign followed by "slant AG"\\
G1D02 (C) [97.509(b)(3)(i)] What license examinations may you administer when you are an accredited VE holding a General Class operator license?\\
C. Technician only\\
G1D03 (C) [97.9(b)] On which of the following band segments may you operate if you are a Technician Class operator and have a CSCE for General Class privileges?\\
C. On any General or Technician Class band segment\\
G1D04 (A) [97.509(a)(b)] Which of the following is a requirement for administering a Technician Class operator examination?\\
A. At least three VEC accredited General Class or higher VEs must be present \\
G1D05 (D) [97.509(b)(3)(i)] Which of the following is sufficient for you to be an administering VE for a Technician Class operator license examination?\\
D. An FCC General Class or higher license and VEC accreditation\\
G1D06 (A) [97.119(f)(2)] When must you add the special identifier "AG" after your call sign if you are a Technician Class licensee and have a CSCE for General Class operator privileges, but the FCC has not yet posted your upgrade on its Web site?\\
A. Whenever you operate using General Class frequency privileges \\
G1D07 (C) [97.509(b)(1)] Volunteer Examiners are accredited by what organization?\\
C. A Volunteer Examiner Coordinator\\
G1D08 (B) [97.509(b)(3)] Which of the following criteria must be met for a non-U.S. citizen to be an accredited Volunteer Examiner?\\
B. The person must hold an FCC granted Amateur Radio license of General Class or above\\
G1D09 (C) [97.9(b)] How long is a Certificate of Successful Completion of Examination (CSCE) valid for exam element credit?\\
C. 365 days\\
G1D10 (B) [97.509(b)(2)] What is the minimum age that one must be to qualify as an accredited Volunteer Examiner?\\
B. 18 years\\
\section{G1E - Control categories; repeater regulations; harmful interference; third party rules; ITU regions}
G1E01 (A) [97.115(b)(2)] Which of the following would disqualify a third party from participating in stating a message over an amateur station?\\
A. The third party's amateur license had ever been revoked \\
G1E02 (D) [97.205(a)] When may a 10 meter repeater retransmit the 2 meter signal from a station having a Technician Class control operator?\\
D. Only if the 10 meter repeater control operator holds at least a General Class license\\
G1E03 (B) [97.301(d)] In what ITU region is operation in the 7.175 to 7.300 MHz band permitted for a control operator holding an FCC-issued General Class license?\\
B. Region 2\\
G1E04 (D) [97.13(b),97.311(b),97.303] Which of the following conditions require an Amateur Radio station licensee to take specific steps to avoid harmful interference to other users or facilities?\\
A. When operating within one mile of an FCC Monitoring Station\\
B. When using a band where the Amateur Service is secondary\\
C. When a station is transmitting spread spectrum emissions\\
D. All of these choices are correct\\
G1E05 (C) [97.115(a)(2),97.117] What types of messages for a third party in another country may be transmitted by an amateur station?\\
C. Only messages relating to Amateur Radio or remarks of a personal character, or messages relating to emergencies or disaster relief\\
G1E06 (A) [97.205(c)] Which of the following applies in the event of interference between a coordinated repeater and an uncoordinated repeater?\\
A. The licensee of the non-coordinated repeater has primary responsibility to resolve the interference\\
G1E07 (C) [97.115(a)(2)] With which foreign countries is third party traffic prohibited, except for messages directly involving emergencies or disaster relief communications?\\
C. Every foreign country, unless there is a third party agreement in effect with that country\\
G1E08 (B) [97.115(a)(b)] Which of the following is a requirement for a non-licensed person to communicate with a foreign Amateur Radio station from a station with an FCC granted license at which a licensed control operator is present?\\
B. The foreign amateur station must be in a country with which the United States has a third party agreement\\
G1E09 (C) [97.119(b)(2)] What language must you use when identifying your station if you are using a language other than English in making a contact using phone emission?\\
C. English\\
G1E10 (D) [97.205(b)] What portion of the 10 meter band is available for repeater use?\\
D. The portion above 29.5 MHz\\
\chapter{Subelement G2 - Operating Procedures: 5 Questions}
\section{G2A - Phone operating procedures; USB/LSB utilization conventions; procedural signals; breaking into a QSO in progress; VOX operation}
G2A01 (A) Which sideband is most commonly used for voice communications on frequencies of 14 MHz or higher?\\
A. Upper sideband\\
G2A02 (B) Which of the following modes is most commonly used for voice communications on the 160, 75, and 40 meter bands?\\
B. Lower sideband\\
G2A03 (A) Which of the following is most commonly used for SSB voice communications in the VHF and UHF bands?\\
A. Upper sideband\\
G2A04 (A) Which mode is most commonly used for voice communications on the 17 and 12 meter bands?\\
A. Upper sideband \\
G2A05 (C) Which mode of voice communication is most commonly used on the high frequency amateur bands? \\
C. Single sideband \\
G2A06 (B) Which of the following is an advantage when using single sideband as compared to other analog voice modes on the HF amateur bands?\\
B. Less bandwidth used and higher power efficiency \\
G2A07 (B) Which of the following statements is true of the single sideband (SSB) voice mode? \\
B. Only one sideband is transmitted; the other sideband and carrier are suppressed \\
G2A08 (B) Which of the following is a recommended way to break into a conversation when using phone?\\
B. Say your call sign during a break between transmissions from the other stations\\
G2A09 (D) Why do most amateur stations use lower sideband on the 160, 75 and 40 meter bands?\\
D. Current amateur practice is to use lower sideband on these frequency bands\\
G2A10 (B) Which of the following statements is true of SSB VOX operation?\\
B. VOX allows "hands free" operation\\
G2A11 (C) What does the expression "CQ DX" usually indicate?\\
C. The caller is looking for any station outside their own country\\
\section{G2B - Operating courtesy; band plans; emergencies, including drills and emergency communications}
G2B01 (C) Which of the following is true concerning access to frequencies?\\
C. No one has priority access to frequencies, common courtesy should be a guide\\
G2B02 (B) What is the first thing you should do if you are communicating with another amateur station and hear a station in distress break in?\\
B. Acknowledge the station in distress and determine what assistance may be needed\\
G2B03 (C) If propagation changes during your contact and you notice increasing interference from other activity on the same frequency, what should you do?\\
C. As a common courtesy, move your contact to another frequency \\
G2B04 (B) When selecting a CW transmitting frequency, what minimum frequency separation should you allow in order to minimize interference to stations on adjacent frequencies?\\
B. 150 to 500 Hz \\
G2B05 (B) What is the customary minimum frequency separation between SSB signals under normal conditions?\\
B. Approximately 3 kHz \\
G2B06 (A) What is a practical way to avoid harmful interference when selecting a frequency to call CQ on CW or phone?\\
A. Send "QRL?" on CW, followed by your call sign; or, if using phone, ask if the frequency is in use, followed by your call sign\\
G2B07 (C) Which of the following complies with good amateur practice when choosing a frequency on which to initiate a call?\\
C. Follow the voluntary band plan for the operating mode you intend to use\\
G2B08 (A) What is the "DX window" in a voluntary band plan?\\
A. A portion of the band that should not be used for contacts between stations within the 48 contiguous United States \\
G2B09 (A) [97.407(a)] Who may be the control operator of an amateur station transmitting in RACES to assist relief operations during a disaster?\\
A. Only a person holding an FCC issued amateur operator license\\
G2B10 (D) [97.407(b)] When may the FCC restrict normal frequency operations of amateur stations participating in RACES?\\
D. When the President's War Emergency Powers have been invoked\\
G2B11 (A) [97.405] What frequency should be used to send a distress call?\\
A. Whatever frequency has the best chance of communicating the distress message\\
G2B12 (C) [97.405(b)] When is an amateur station allowed to use any means at its disposal to assist another station in distress?\\
C. At any time during an actual emergency\\
\section{G2C - CW operating procedures and procedural signals; Q signals and common abbreviations: full break in}
G2C01 (D) Which of the following describes full break-in telegraphy (QSK)?\\
D. Transmitting stations can receive between code characters and elements\\
G2C02 (A) What should you do if a CW station sends "QRS"?\\
A. Send slower\\
G2C03 (C) What does it mean when a CW operator sends "KN" at the end of a transmission?\\
C. Listening only for a specific station or stations\\
G2C04 (D) What does it mean when a CW operator sends "CL" at the end of a transmission?\\
D. Closing station\\
G2C05 (B) What is the best speed to use answering a CQ in Morse Code?\\
B. The speed at which the CQ was sent\\
G2C06 (D) What does the term "zero beat" mean in CW operation?\\
D. Matching your transmit frequency to the frequency of a received signal.\\
G2C07 (A) When sending CW, what does a "C" mean when added to the RST report?\\
A. Chirpy or unstable signal\\
G2C08 (C) What prosign is sent to indicate the end of a formal message when using CW? \\
C. AR\\
G2C09 (C) What does the Q signal "QSL" mean?\\
C. I acknowledge receipt\\
G2C10 (B) What does the Q signal "QRQ" mean?\\
B. Send faster\\
G2C11 (D) What does the Q signal "QRV" mean?\\
D. I am ready to receive messages\\
\section{G2D - Amateur Auxiliary; minimizing interference; HF operations}
G2D01 (A) What is the Amateur Auxiliary to the FCC?\\
A. Amateur volunteers who are formally enlisted to monitor the airwaves for rules violations \\
G2D02 (B) Which of the following are objectives of the Amateur Auxiliary?\\
B. To encourage amateur self regulation and compliance with the rules \\
G2D03 (B) What skills learned during "hidden transmitter hunts" are of help to the Amateur Auxiliary? \\
B. Direction finding used to locate stations violating FCC Rules\\
G2D04 (B) Which of the following describes an azimuthal projection map?\\
B. A world map projection centered on a particular location \\
G2D05 (B) [97.111(a)(1)] When is it permissible to communicate with amateur stations in countries outside the areas administered by the Federal Communications Commission?\\
B. When the contact is with amateurs in any country except those whose administrations have notified the ITU that they object to such communications\\
G2D06 (C) How is a directional antenna pointed when making a "long-path" contact with another station?\\
C. 180 degrees from its short-path heading\\
G2D07 (A) [97.303s] Which of the following is required by the FCC rules when operating in the 60 meter band?\\
A. If you are using other than a dipole antenna, you must keep a record of the gain of your antenna\\
G2D08 (D) Why do many amateurs keep a log even though the FCC doesn't require it?\\
D. To help with a reply if the FCC requests information\\
G2D09 (D) What information is traditionally contained in a station log?\\
A. Date and time of contact\\
B. Band and/or frequency of the contact \\
C. Call sign of station contacted and the signal report given \\
D. All of these choices are correct\\
G2D10 (B) What is QRP operation?\\
B. Low power transmit operation\\
G2D11 (C) Which HF antenna would be the best to use for minimizing interference?\\
C. A unidirectional antenna\\
\section{G2E - Digital operating: procedures, procedural signals and common abbreviations}
G2E01 (D) Which mode is normally used when sending an RTTY signal via AFSK with an SSB transmitter?\\
D. LSB\\
G2E02 (A) How many data bits are sent in a single PSK31 character?\\
A. The number varies\\
G2E03 (C) What part of a data packet contains the routing and handling information?\\
C. Header\\
G2E04 (B) What segment of the 20 meter band is most often used for data transmissions?\\
B. 14.070 - 14.100 MHz\\
G2E05 (C) Which of the following describes Baudot code?\\
C. A 5-bit code with additional start and stop bits\\
G2E06 (B) What is the most common frequency shift for RTTY emissions in the amateur HF bands?\\
B. 170 Hz\\
G2E07 (B) What does the abbreviation "RTTY" stand for?\\
B. Radioteletype\\
G2E08 (A) What segment of the 80 meter band is most commonly used for data transmissions?\\
A. 3570 - 3600 kHz\\
G2E09 (D) In what segment of the 20 meter band are most PSK31 operations commonly found?\\
D. Below the RTTY segment, near 14.070 MHz\\
G2E11 (B) What does the abbreviation "MFSK" stand for?\\
B. Multi (or Multiple) Frequency Shift Keying\\
G2E12 (B) How does the receiving station respond to an ARQ data mode packet containing errors?\\
B. Requests the packet be retransmitted\\
G2E13 (A) In the PACTOR protocol, what is meant by an NAK response to a transmitted packet?\\
A. The receiver is requesting the packet be re-transmitted\\
\chapter{Subelement G3 - Radio Wave Propagation: 3 Questions}
\section{G3A - Sunspots and solar radiation; ionospheric disturbances; propagation forecasting and indices}
G3A01 (A) What is the sunspot number?\\
A. A measure of solar activity based on counting sunspots and sunspot groups\\
G3A02 (B) What effect does a Sudden Ionospheric Disturbance have on the daytime ionospheric propagation of HF radio waves?\\
B. It disrupts signals on lower frequencies more than those on higher frequencies \\
G3A03 (C) Approximately how long does it take the increased ultraviolet and X-ray radiation from solar flares to affect radio-wave propagation on the Earth?\\
C. 8 minutes\\
G3A04 (D) Which of the following amateur radio HF frequencies are least reliable for long distance communications during periods of low solar activity?\\
D. 21 MHz and higher\\
G3A05 (D) [Modified] What is the solar-flux index?\\
D. A measure of solar radiation at 10.7 cm\\
G3A06 (D) What is a geomagnetic storm?\\
D. A temporary disturbance in the Earth's magnetosphere\\
G3A07 (D) At what point in the solar cycle does the 20 meter band usually support worldwide propagation during daylight hours?\\
D. At any point in the solar cycle\\
G3A08 (B) Which of the following effects can a geomagnetic storm have on radio-wave propagation?\\
B. Degraded high-latitude HF propagation\\
G3A09 (C) What effect do high sunspot numbers have on radio communications?\\
C. Long-distance communication in the upper HF and lower VHF range is enhanced\\
G3A10 (C) What causes HF propagation conditions to vary periodically in a 28-day cycle?\\
C. The Sun's rotation on its axis\\
G3A11 (D) Approximately how long is the typical sunspot cycle?\\
D. 11 years\\
G3A12 (B) What does the K-index indicate?\\
B. The short term stability of the Earth's magnetic field\\
G3A13 (C) What does the A-index indicate? \\
C. The long term stability of the Earth's geomagnetic field\\
G3A14 (B)How are radio communications usually affected by the charged particles that reach the Earth from solar coronal holes?\\
B. HF communications are disturbed\\
G3A15 (D) How long does it take charged particles from coronal mass ejections to affect radio-wave propagation on the Earth?\\
D. 20 to 40 hours\\
G3A16 (A) What is a possible benefit to radio communications resulting from periods of high geomagnetic activity?\\
A. Aurora that can reflect VHF signals\\
\section{G3B - Maximum Usable Frequency; Lowest Usable Frequency; propagation}
G3B01 (D) How might a sky-wave signal sound if it arrives at your receiver by both short path and long path propagation?\\
D. A well-defined echo might be heard\\
G3B02 (A)
Which of the following is a good indicator of the possibility of sky-wave propagation on the 6 meter band?\\
A. Short skip sky-wave propagation on the 10 meter band\\
G3B03 (A) Which of the following applies when selecting a frequency for lowest attenuation when transmitting on HF?\\
A. Select a frequency just below the MUF\\
G3B04 (A) What is a reliable way to determine if the Maximum Usable Frequency (MUF) is high enough to support skip propagation between your station and a distant location on frequencies between 14 and 30 MHz?\\
A. Listen for signals from an international beacon\\
G3B05 (A) What usually happens to radio waves with frequencies below the Maximum Usable Frequency (MUF) and above the Lowest Usable Frequency (LUF) when they are sent into the ionosphere?\\
A. They are bent back to the Earth\\
G3B06 (C) What usually happens to radio waves with frequencies below the Lowest Usable Frequency (LUF)?\\
C. They are completely absorbed by the ionosphere\\
G3B07 (A) What does LUF stand for?\\
A. The Lowest Usable Frequency for communications between two points\\
G3B08 (B) What does MUF stand for?\\
B. The Maximum Usable Frequency for communications between two points\\
G3B09 (C) What is the approximate maximum distance along the Earth's surface that is normally covered in one hop using the F2 region?\\
C. 2,500 miles\\
G3B10 (B) What is the approximate maximum distance along the Earth's surface that is normally covered in one hop using the E region?\\
B. 1,200 miles \\
G3B11 (A) What happens to HF propagation when the Lowest Usable Frequency (LUF) exceeds the Maximum Usable Frequency (MUF)?\\
A. No HF radio frequency will support ordinary skywave communications over the path\\
G3B12 (D) What factors affect the Maximum Usable Frequency (MUF)?\\
A. Path distance and location\\
B. Time of day and season\\
C. Solar radiation and ionospheric disturbances\\
D. All of these choices are correct\\
\section{G3C - Ionospheric layers; critical angle and frequency; HF scatter; Near Vertical Incidence Sky waves}
G3C01 (A) Which of the following ionospheric layers is closest to the surface of the Earth?\\
A. The D layer\\
G3C02 (A) Where on the Earth do ionospheric layers reach their maximum height?\\
A. Where the Sun is overhead\\
G3C03 (C) Why is the F2 region mainly responsible for the longest distance radio wave propagation?\\
C. Because it is the highest ionospheric region\\
G3C04 (D) What does the term "critical angle" mean as used in radio wave propagation?\\
D. The highest takeoff angle that will return a radio wave to the Earth under specific ionospheric conditions\\
G3C05 (C) Why is long distance communication on the 40, 60, 80 and 160 meter bands more difficult during the day?\\
C. The D layer absorbs signals at these frequencies during daylight hours\\
G3C06 (B) What is a characteristic of HF scatter signals?\\
B. They have a wavering sound\\
G3C07 (D) What makes HF scatter signals often sound distorted?\\
D. Energy is scattered into the skip zone through several different radio wave paths\\
G3C08 (A) Why are HF scatter signals in the skip zone usually weak?\\
A. Only a small part of the signal energy is scattered into the skip zone\\
G3C09 (B) What type of radio wave propagation allows a signal to be detected at a distance too far for ground wave propagation but too near for normal sky-wave propagation?\\
B. Scatter\\
G3C10 (D)
Which of the following might be an indication that signals heard on the HF bands are being received via scatter propagation?\\
D. The signal is heard on a frequency above the Maximum Usable Frequency\\
G3C11 (B) Which of the following antenna types will be most effective for skip communications on 40 meters during the day?\\
B. Horizontal dipoles placed between 1/8 and 1/4 wavelength above the ground\\
G3C12 (D) Which ionospheric layer is the most absorbent of long skip signals during daylight hours on frequencies below 10 MHz?\\
D. The D layer\\
G3C13 (B) What is Near Vertical Incidence Sky-wave (NVIS) propagation?\\
B. Short distance HF propagation using high elevation angles\\
\chapter{Subelement G4 - Amateur Radio Practices: 5 Questions}
\section{G4A - Station Operation and set up}
G4A01 (B) What is the purpose of the "notch filter" found on many HF transceivers?\\
B. To reduce interference from carriers in the receiver passband\\
G4A02 (C) What is one advantage of selecting the opposite or "reverse" sideband when receiving CW signals on a typical HF transceiver?\\
C. It may be possible to reduce or eliminate interference from other signals\\
G4A03 (C) What is normally meant by operating a transceiver in "split" mode?\\
C. The transceiver is set to different transmit and receive frequencies\\
G4A04 (B) What reading on the plate current meter of a vacuum tube RF power amplifier indicates correct adjustment of the plate tuning control?\\
B. A pronounced dip\\
G4A05 (C) What is a purpose of using Automatic Level Control (ALC) with a RF power amplifier?\\
C. To reduce distortion due to excessive drive\\
G4A06 (C) What type of device is often used to enable matching the transmitter output to an impedance other than 50 ohms?\\
C. Antenna coupler\\
G4A07 (D) What condition can lead to permanent damage when using a solid-state RF power amplifier?\\
D. Excessive drive power\\
G4A08 (D) What is the correct adjustment for the load or coupling control of a vacuum tube RF power amplifier?\\
D. Maximum power output without exceeding maximum allowable plate current\\
G4A09 (C) Why is a time delay sometimes included in a transmitter keying circuit?\\
C. To allow time for transmit-receive changeover operations to complete properly before RF output is allowed\\
G4A10 (B) What is the purpose of an electronic keyer?\\
B. Automatic generation of strings of dots and dashes for CW operation \\
G4A11 (A) Which of the following is a use for the IF shift control on a receiver?\\
A. To avoid interference from stations very close to the receive frequency\\
G4A12 (C) Which of the following is a common use for the dual VFO feature on a transceiver? \\
C. To permit ease of monitoring the transmit and receive frequencies when they are not the same\\
G4A13 (A) What is one reason to use the attenuator function that is present on many HF transceivers?\\
A. To reduce signal overload due to strong incoming signals\\
G4A14 (B) How should the transceiver audio input be adjusted when transmitting PSK31 data signals?\\
B. So that the transceiver ALC system does not activate\\
\section{G4B - Test and monitoring equipment; two-tone test}
G4B01 (D) What item of test equipment contains horizontal and vertical channel amplifiers?\\
D. An oscilloscope\\
G4B02 (D) Which of the following is an advantage of an oscilloscope versus a digital voltmeter?\\
D. Complex waveforms can be measured\\
G4B03 (A) Which of the following is the best instrument to use when checking the keying waveform of a CW transmitter?\\
A. An oscilloscope\\
G4B04 (D) What signal source is connected to the vertical input of an oscilloscope when checking the RF envelope pattern of a transmitted signal?\\
D. The attenuated RF output of the transmitter\\
G4B05 (D) Why is high input impedance desirable for a voltmeter?\\
D. It decreases the loading on circuits being measured\\
G4B06 (C) What is an advantage of a digital voltmeter as compared to an analog voltmeter?\\
C. Better precision for most uses\\
G4B07 (A) Which of the following might be a use for a field strength meter?\\
A. Close-in radio direction-finding\\
G4B08 (A) Which of the following instruments may be used to monitor relative RF output when making antenna and transmitter adjustments?\\
A. A field-strength meter\\
G4B09 (B) Which of the following can be determined with a field strength meter?\\
B. The radiation pattern of an antenna\\
G4B10 (A) Which of the following can be determined with a directional wattmeter?\\
A. Standing wave ratio\\
G4B11 (C) Which of the following must be connected to an antenna analyzer when it is being used for SWR measurements?\\
C. Antenna and feed line \\
G4B12 (B) What problem can occur when making measurements on an antenna system with an antenna analyzer? \\
B. Strong signals from nearby transmitters can affect the accuracy of measurements \\
G4B13 (C) What is a use for an antenna analyzer other than measuring the SWR of an antenna system? \\
C. Determining the impedance of an unknown or unmarked coaxial cable\\
G4B14 (D) What is an instance in which the use of an instrument with analog readout may be preferred over an instrument with a numerical digital readout?\\
D. When adjusting tuned circuits\\
G4B15 (A) What type of transmitter performance does a two-tone test analyze?\\
A. Linearity \\
G4B16 (B) What signals are used to conduct a two-tone test?\\
B. Two non-harmonically related audio signals\\
\section{G4C - Interference with consumer electronics; grounding; DSP}
G4C01 (B) Which of the following might be useful in reducing RF interference to audio-frequency devices?\\
B. Bypass capacitor\\
G4C02 (C) Which of the following could be a cause of interference covering a wide range of frequencies? \\
C. Arcing at a poor electrical connection \\
G4C03 (C) What sound is heard from an audio device or telephone if there is interference from a nearby single-sideband phone transmitter?\\
C. Distorted speech\\
G4C04 (A) What is the effect on an audio device or telephone system if there is interference from a nearby CW transmitter?\\
A. On-and-off humming or clicking\\
G4C05 (D) What might be the problem if you receive an RF burn when touching your equipment while transmitting on an HF band, assuming the equipment is connected to a ground rod?\\
D. The ground wire has high impedance on that frequency\\
G4C06 (C) What effect can be caused by a resonant ground connection?\\
C. High RF voltages on the enclosures of station equipment\\
G4C07 (A) What is one good way to avoid unwanted effects of stray RF energy in an amateur station?\\
A. Connect all equipment grounds together \\
G4C08 (A) Which of the following would reduce RF interference caused by common-mode current on an audio cable?\\
A. Placing a ferrite bead around the cable\\
G4C09 (D) How can a ground loop be avoided?\\
D. Connect all ground conductors to a single point\\
G4C10 (A) What could be a symptom of a ground loop somewhere in your station?\\
A. You receive reports of "hum" on your station's transmitted signal\\
G4C11 (B) Which of the following is one use for a Digital Signal Processor in an amateur station?\\
B. To remove noise from received signals\\
G4C12 (A) Which of the following is an advantage of a receiver Digital Signal Processor IF filter as compared to an analog filter? \\
A. A wide range of filter bandwidths and shapes can be created\\
G4C13 (B) Which of the following can perform automatic notching of interfering carriers?\\
B. A Digital Signal Processor (DSP) filter\\
\section{G4D - Speech processors; S meters; sideband operation near band edges}
G4D01 (A) What is the purpose of a speech processor as used in a modern transceiver?\\
A. Increase the intelligibility of transmitted phone signals during poor conditions \\
G4D02 (B) Which of the following describes how a speech processor affects a transmitted single sideband phone signal?\\
B. It increases average power\\
G4D03 (D) Which of the following can be the result of an incorrectly adjusted speech processor?\\
A. Distorted speech\\
B. Splatter\\
C. Excessive background pickup\\
D. All of these choices are correct\\
G4D04 (C) What does an S meter measure?\\
C. Received signal strength\\
G4D05 (D) How does an S meter reading of 20 dB over S-9 compare to an S-9 signal, assuming a properly calibrated S meter?\\
D. It is 100 times stronger\\
G4D06 (A) Where is an S meter found?\\
A. In a receiver\\
G4D07 (C) How much must the power output of a transmitter be raised to change the S- meter reading on a distant receiver from S8 to S9?\\
C. Approximately 4 times\\
G4D08 (C) What frequency range is occupied by a 3 kHz LSB signal when the displayed carrier frequency is set to 7.178 MHz? \\
C. 7.175 to 7.178 MHz\\
G4D09 (B) What frequency range is occupied by a 3 kHz USB signal with the displayed carrier frequency set to 14.347 MHz?\\
B. 14.347 to 14.350 MHz\\
G4D10 (A) How close to the lower-edge of the 40 meter General Class phone segment should your displayed carrier frequency be when using 3 kHz wide-LSB?\\
A. 3 kHz above the edge of the segment\\
G4D11 (B) How close to the upper edge of the 20 meter General Class band should your displayed carrier frequency be when using 3 kHz wide-USB? \\
B. 3 kHz below the edge of the band\\
\section{G4E - HF mobile radio installations; emergency and battery powered operation}
G4E01 (C) What is a "capacitance hat", when referring to a mobile antenna?\\
C. A device to electrically lengthen a physically short antenna\\
G4E02 (D) What is the purpose of a "corona ball" on a HF mobile antenna?\\
D. To reduce high voltage discharge from the tip of the antenna\\
G4E03 (A) Which of the following direct, fused power connections would be the best for a 100-watt HF mobile installation? \\
A. To the battery using heavy gauge wire \\
G4E04 (B) Why is it best NOT to draw the DC power for a 100-watt HF transceiver from an automobile's auxiliary power socket?\\
B. The socket's wiring may be inadequate for the current being drawn by the
transceiver\\
G4E05 (C) Which of the following most limits the effectiveness of an HF mobile transceiver operating in the 75 meter band?\\
C. The antenna system\\
G4E06 (C) What is one disadvantage of using a shortened mobile antenna as opposed to a full size antenna?\\
C. Operating bandwidth may be very limited\\
G4E07 (D) Which of the following is the most likely to cause interfering signals to be heard in the receiver of an HF mobile installation in a recent model vehicle?\\
D. The vehicle control computer\\
G4E08 (A) What is the name of the process by which sunlight is changed directly into electricity?\\
A. Photovoltaic conversion\\
G4E09 (B) What is the approximate open-circuit voltage from a modern, well-illuminated photovoltaic cell?\\
B. 0.5 VDC\\
G4E10 (B) What is the reason a series diode is connected between a solar panel and a storage battery that is being charged by the panel?\\
B. The diode prevents self discharge of the battery though the panel during times of low or no illumination\\
G4E11 (C) Which of the following is a disadvantage of using wind as the primary source of power for an emergency station?\\
C. A large energy storage system is needed to supply power when the wind is not blowing\\
\chapter{Subelement G5 - Electrical Principles: 3 Questions}
\section{G5A - Reactance; inductance; capacitance; impedance; impedance matching}
G5A01 (C) What is impedance?\\
C. The opposition to the flow of current in an AC circuit\\
G5A02 (B) What is reactance?\\
B. Opposition to the flow of alternating current caused by capacitance or inductance\\
G5A03 (D) Which of the following causes opposition to the flow of alternating current in an inductor?\\
D. Reactance\\
G5A04 (C) Which of the following causes opposition to the flow of alternating current in a capacitor?\\
C. Reactance\\
G5A05 (D) How does an inductor react to AC?\\
D. As the frequency of the applied AC increases, the reactance increases\\
G5A06 (A) How does a capacitor react to AC?\\
A. As the frequency of the applied AC increases, the reactance decreases\\
G5A08 (A) Why is impedance matching important?\\
A. So the source can deliver maximum power to the load\\
G5A09 (B) What unit is used to measure reactance?\\
B. Ohm\\
G5A10 (B) What unit is used to measure impedance?\\
B. Ohm\\
G5A11 (A) Which of the following describes one method of impedance matching between two AC circuits?\\
A. Insert an LC network between the two circuits\\
G5A12 (B) What is one reason to use an impedance matching transformer?\\
B. To maximize the transfer of power\\
G5A13 (D) Which of the following devices can be used for impedance matching at radio frequencies?\\
A. A transformer\\
B. A Pi-network\\
C. A length of transmission line\\
D. All of these choices are correct\\
\section{G5B - The Decibel; current and voltage dividers; electrical power calculations; sine wave root-mean-square (RMS) values; PEP calculations}
G5B01 (B) A two-times increase or decrease in power results in a change of how many dB?\\
B. Approximately 3 dB\\
G5B02 (C) How does the total current relate to the individual currents in each branch of a parallel circuit?\\
C. It equals the sum of the currents through each branch \\
G5B03 (B) How many watts of electrical power are used if 400 VDC is supplied to an 800-ohm load?\\
B. 200 watts\\
G5B04 (A) How many watts of electrical power are used by a 12-VDC light bulb that draws 0.2 amperes?\\
A. 2.4 watts\\
G5B05 (A) How many watts are dissipated when a current of 7.0 milliamperes flows through 1.25 kilohms?\\
A. Approximately 61 milliwatts\\
G5B06 (B) What is the output PEP from a transmitter if an oscilloscope measures 200 volts peak-to-peak across a 50-ohm dummy load connected to the transmitter output?\\
B. 100 watts\\
G5B07 (C) Which value of an AC signal results in the same power dissipation as a DC voltage of the same value? \\
C. The RMS value \\
G5B08 (D) What is the peak-to-peak voltage of a sine wave that has an RMS voltage of 120 volts?\\
D. 339.4 volts \\
G5B09 (B) What is the RMS voltage of a sine wave with a value of 17 volts peak? \\
B. 12 volts \\
G5B10 (C) What percentage of power loss would result from a transmission line loss of 1 dB?\\
C. 20.5%\\
G5B11 (B) What is the ratio of peak envelope power to average power for an unmodulated carrier?\\
B. 1.00\\
G5B12 (B) What would be the RMS voltage across a 50-ohm dummy load dissipating 1200 watts?\\
B. 245 volts\\
G5B13 (B) What is the output PEP of an unmodulated carrier if an average reading wattmeter connected to the transmitter output indicates 1060 watts?\\
B. 1060 watts\\
G5B14 (B) What is the output PEP from a transmitter if an oscilloscope measures 500 volts peak-to-peak across a 50-ohm resistor connected to the transmitter output?\\
B. 625 watts\\
\section{G5C - Resistors, capacitors, and inductors in series and parallel; transformers}
G5C01 (C) What causes a voltage to appear across the secondary winding of a transformer when an AC voltage source is connected across its primary winding?\\
C. Mutual inductance\\
G5C02 (B) Which part of a transformer is normally connected to the incoming source of energy? \\
B. The primary \\
G5C03 (B) Which of the following components should be added to an existing resistor to increase the resistance?\\
B. A resistor in series\\
G5C04 (C) What is the total resistance of three 100-ohm resistors in parallel?\\
C. 33.3 ohms\\
G5C05 (C) If three equal value resistors in parallel produce 50 ohms of resistance, and the same three resistors in series produce 450 ohms, what is the value of each resistor?\\
C. 150 ohms\\
G5C06 (C) What is the RMS voltage across a 500-turn secondary winding in a transformer if the 2250-turn primary is connected to 120 VAC?\\
C. 26.7 volts\\
G5C07 (A) What is the turns ratio of a transformer used to match an audio amplifier having a 600-ohm output impedance to a speaker having a 4-ohm impedance?\\
A. 12.2 to 1\\
G5C08 (D) What is the equivalent capacitance of two 5000 picofarad capacitors and one 750 picofarad capacitor connected in parallel?\\
D. 10750 picofarads\\
G5C09 (C) What is the capacitance of three 100 microfarad capacitors connected in series?\\
C. 33.3 microfarads\\
G5C10 (C) What is the inductance of three 10 millihenry inductors connected in parallel?\\
C. 3.3 millihenrys\\
G5C11 (C) What is the inductance of a 20 millihenry inductor in series with a 50 millihenry inductor?\\
C. 70 millihenrys\\
G5C12 (B) What is the capacitance of a 20 microfarad capacitor in series with a 50 microfarad capacitor?\\
B. 14.3 microfarads\\
G5C13 (C) Which of the following components should be added to a capacitor to increase the capacitance?\\
C. A capacitor in parallel\\
G5C14 (D) Which of the following components should be added to an inductor to increase the inductance?\\
D. An inductor in series\\
G5C15 (A) What is the total resistance of a 10 ohm, a 20 ohm, and a 50 ohm resistor in parallel?\\
A. 5.9 ohms\\
\chapter{Subelement G6 - Circuit Components: 3 Questions}
\section{G6A - Resistors; capacitors; inductors}
G6A01 (A) Which of the following is an important characteristic for capacitors used to filter the DC output of a switching power supply?\\
A. Low equivalent series resistance\\
G6A02 (D) Which of the following types of capacitors are often used in power supply circuits to filter the rectified AC?\\
D. Electrolytic\\
G6A03 (D) Which of the following is an advantage of ceramic capacitors as compared to other types of capacitors?\\
D. Comparatively low cost\\
G6A04 (C) Which of the following is an advantage of an electrolytic capacitor?\\
C. High capacitance for given volume\\
G6A05 (A) Which of the following is one effect of lead inductance in a capacitor used at VHF and above?\\
A. Effective capacitance may be reduced\\
G6A06 (C) What will happen to the resistance if the temperature of a resistor is increased?\\
C. It will change depending on the resistor's temperature coefficient\\
G6A07 (B) Which of the following is a reason not to use wire-wound resistors in an RF circuit?\\
B. The resistor's inductance could make circuit performance unpredictable\\
G6A08 (B) Which of the following describes a thermistor?\\
B. A device having a specific change in resistance with temperature variations\\
G6A09 (D) What is an advantage of using a ferrite core toroidal inductor?\\
A. Large values of inductance may be obtained\\
B. The magnetic properties of the core may be optimized for a specific range of frequencies\\
C. Most of the magnetic field is contained in the core\\
D. All of these choices are correct\\
G6A10 (C) How should the winding axes of solenoid inductors be placed to minimize their mutual inductance?\\
C. At right angles\\
G6A11 (B) Why would it be important to minimize the mutual inductance between two inductors? \\
B. To reduce unwanted coupling between circuits\\
G6A12 (D) What is a common name for an inductor used to help smooth the DC output from the rectifier in a conventional power supply?\\
D. Filter choke\\
G6A13 (B) What is an effect of inter-turn capacitance in an inductor?\\
B. The inductor may become self resonant at some frequencies\\
\section{G6B - Rectifiers; solid state diodes and transistors; vacuum tubes; batteries}
G6B01 (C) What is the peak-inverse-voltage rating of a rectifier?\\
C. The maximum voltage the rectifier will handle in the non-conducting direction\\
G6B02 (A) What are two major ratings that must not be exceeded for silicon diode rectifiers?\\
A. Peak inverse voltage; average forward current\\
G6B03 (B) What is the approximate junction threshold voltage of a germanium diode?\\
B. 0.3 volts\\
G6B04 (C) When two or more diodes are connected in parallel to increase current handling capacity, what is the purpose of the resistor connected in series with each diode?\\
C. To ensure that one diode doesn't carry most of the current\\
G6B05 (C) What is the approximate junction threshold voltage of a conventional silicon diode?\\
C. 0.7 volts\\
G6B06 (A) Which of the following is an advantage of using a Schottky diode in an RF switching circuit as compared to a standard silicon diode?\\
A. Lower capacitance\\
G6B07 (A) What are the stable operating points for a bipolar transistor used as a switch in a logic circuit?\\
A. Its saturation and cut-off regions\\
G6B08 (D) Why must the cases of some large power transistors be insulated from ground?\\
D. To avoid shorting the collector or drain voltage to ground\\
G6B09 (B) Which of the following describes the construction of a MOSFET?\\
B. The gate is separated from the channel with a thin insulating layer\\
G6B10 (A) Which element of a triode vacuum tube is used to regulate the flow of electrons between cathode and plate?\\
A. Control grid\\
G6B11 (B) Which of the following solid state devices is most like a vacuum tube in its general operating characteristics?\\
B. A Field Effect Transistor\\
G6B12 (A) What is the primary purpose of a screen grid in a vacuum tube?\\
A. To reduce grid-to-plate capacitance\\
G6B13 (B) What is an advantage of the low internal resistance of nickel-cadmium batteries?\\
B. High discharge current\\
G6B14 (C) What is the minimum allowable discharge voltage for maximum life of a standard 12 volt lead acid battery?\\
C. 10.5 volts\\
G6B15 (D) When is it acceptable to recharge a carbon-zinc primary cell?\\
D. Never\\
\section{G6C - Analog and digital integrated circuits (IC's); microprocessors; memory; I/O devices; microwave IC's (MMIC's ); display devices}
G6C01 (D) Which of the following is an analog integrated circuit?\\
D. Linear voltage regulator\\
G6C02 (B) What is meant by the term MMIC?\\
B. Monolithic Microwave Integrated Circuit\\
G6C03 (A) Which of the following is an advantage of CMOS integrated circuits compared to TTL integrated circuits?\\
A. Low power consumption\\
G6C04 (B) What is meant by the term ROM?\\
B. Read Only Memory\\
G6C05 (C) What is meant when memory is characterized as "non-volatile"?\\
C. The stored information is maintained even if power is removed\\
G6C06 (D) Which of the following describes an integrated circuit operational amplifier?\\
D. Analog\\
G6C07 (D) What is one disadvantage of an incandescent indicator compared to an LED?\\
D. High power consumption\\
G6C08 (D) How is an LED biased when emitting light?\\
D. Forward Biased\\
G6C09 (A) Which of the following is a characteristic of a liquid crystal display?\\
A. It requires ambient or back lighting\\
G6C10 (A) What two devices in an Amateur Radio station might be connected using a USB interface?\\
A. Computer and transceiver\\
G6C11 (B) What is a microprocessor?\\
B. A computer on a single integrated circuit\\
G6C12 (D) Which of the following connectors would be a good choice for a serial data port?\\
D. DE-9\\
G6C13 (C) Which of these connector types is commonly used for RF service at frequencies up to 150 MHz? \\
C. PL-259\\
G6C14 (C) Which of these connector types is commonly used for audio signals in Amateur Radio stations? \\
C. RCA Phono\\
G6C15 (B) What is the main reason to use keyed connectors instead of non-keyed types?\\
B. Reduced chance of incorrect mating\\
G6C16 (A) Which of the following describes a type-N connector?\\
A. A moisture-resistant RF connector useful to 10 GHz\\
G6C17 (C) What is the general description of a DIN type connector?\\
C. A family of multiple circuit connectors suitable for audio and control signals\\
G6C18 (B) What is a type SMA connector?\\
B. A small threaded connector suitable for signals up to several GHz\\
\chapter{Subelement G7 - Practical Circuits: 3 Questions}
\section{G7A Power supplies; and schematic symbols}
G7A01 (B) What safety feature does a power-supply bleeder resistor provide?\\
B. It discharges the filter capacitors\\
G7A02 (D) Which of the following components are used in a power-supply filter network?\\
D. Capacitors and inductors\\
G7A03 (D) What is the peak-inverse-voltage across the rectifiers in a full-wave bridge power supply?\\
D. Equal to the normal peak output voltage of the power supply\\
G7A04 (D) What is the peak-inverse-voltage across the rectifier in a half-wave power supply?\\
D. Two times the normal peak output voltage of the power supply\\
G7A05 (B) What portion of the AC cycle is converted to DC by a half-wave rectifier?\\
B. 180 degrees\\
G7A06 (D) What portion of the AC cycle is converted to DC by a full-wave rectifier?\\
D. 360 degrees\\
G7A07 (A) What is the output waveform of an unfiltered full-wave rectifier connected to a resistive load?\\
A. A series of DC pulses at twice the frequency of the AC input\\
G7A08(C) Which of the following is an advantage of a switch-mode power supply as compared to a linear power supply?\\
C. High frequency operation allows the use of smaller components\\
G7A09 (C) Which symbol in figure G7-1 represents a field effect transistor?\\
C. Symbol 1\\
G7A10 (D) Which symbol in figure G7-1 represents a Zener diode?\\
D. Symbol 5\\
G7A11 (B) Which symbol in figure G7-1 represents an NPN junction transistor?\\
B. Symbol 2\\
G7A12 (C) Which symbol in Figure G7-1 represents a multiple-winding transformer?\\
C. Symbol 6\\
G7A13 (A) Which symbol in Figure G7-1 represents a tapped inductor?\\
A. Symbol 7\\
\begin{center}
\includegraphics[width=\textwidth, keepaspectratio]{g7-1.pdf}
\end{center}
\section{G7B - Digital circuits; amplifiers and oscillators}
G7B01 (A) Complex digital circuitry can often be replaced by what type of integrated circuit?\\
A. Microcontroller\\
G7B02 (A) Which of the following is an advantage of using the binary system when processing digital signals?\\
A. Binary "ones" and "zeros" are easy to represent with an "on" or "off" state\\
G7B03 (B) Which of the following describes the function of a two input AND gate?\\
B. Output is high only when both inputs are high\\
G7B04 (C) Which of the following describes the function of a two input NOR gate?\\
C. Output is low when either or both inputs are high\\
G7B05 (C) How many states does a 3-bit binary counter have?\\
C. 8\\
G7B06 (A) What is a shift register?\\
A. A clocked array of circuits that passes data in steps along the array\\
G7B07 (D) What are the basic components of virtually all sine wave oscillators?\\
D. A filter and an amplifier operating in a feedback loop \\
G7B08 (B) How is the efficiency of an RF power amplifier determined?\\
B. Divide the RF output power by the DC input power\\
G7B09 (C) What determines the frequency of an LC oscillator?\\
C. The inductance and capacitance in the tank circuit\\
G7B10 (D) Which of the following is a characteristic of a Class A amplifier?\\
D. Low distortion\\
G7B11 (B) For which of the following modes is a Class C power stage appropriate for amplifying a modulated signal?\\
B. CW\\
G7B12 (D) Which of these classes of amplifiers has the highest efficiency?\\
D. Class C\\
G7B13 (B) What is the reason for neutralizing the final amplifier stage of a transmitter?\\
B. To eliminate self-oscillations\\
G7B14 (B) Which of the following describes a linear amplifier?\\
B. An amplifier in which the output preserves the input waveform\\
\section{G7C - Receivers and transmitters; filters, oscillators}
G7C01 (B) Which of the following is used to process signals from the balanced modulator and send them to the mixer in a single-sideband phone transmitter?\\
B. Filter \\
G7C02 (D) Which circuit is used to combine signals from the carrier oscillator and speech amplifier and send the result to the filter in a typical single-sideband phone transmitter?\\
D. Balanced modulator\\
G7C03 (C) What circuit is used to process signals from the RF amplifier and local oscillator and send the result to the IF filter in a superheterodyne receiver?\\
C. Mixer\\
G7C04 (D) What circuit is used to combine signals from the IF amplifier and BFO and send the result to the AF amplifier in a single-sideband receiver?\\
D. Product detector\\
G7C05 (D) Which of the following is an advantage of a transceiver controlled by a direct digital synthesizer (DDS)?\\
D. Variable frequency with the stability of a crystal oscillator\\
G7C06 (B) What should be the impedance of a low-pass filter as compared to the impedance of the transmission line into which it is inserted? \\
B. About the same\\
G7C07 (C) What is the simplest combination of stages that implement a superheterodyne receiver?\\
C. HF oscillator, mixer, detector\\
G7C08 (D) What type of circuit is used in many FM receivers to convert signals coming from the IF amplifier to audio?\\
D. Discriminator\\
G7C09 (D) Which of the following is needed for a Digital Signal Processor IF filter?\\
A. An analog to digital converter\\
B. A digital to analog converter\\
C. A digital processor chip\\
D. All of the these choices are correct\\
G7C10 (B) How is Digital Signal Processor filtering accomplished?\\
B. By converting the signal from analog to digital and using digital processing\\
G7C11 (A) What is meant by the term "software defined radio" (SDR)?\\
A. A radio in which most major signal processing functions are performed by software\\
\chapter{Subelement G8 - Signals and Emissions: 2 Questions}
\section{G8A - Carriers and modulation: AM; FM; single and double sideband; modulation envelope; overmodulation}
G8A01 (D) What is the name of the process that changes the envelope of an RF wave to carry information?\\
D. Amplitude modulation\\
G8A02 (B) What is the name of the process that changes the phase angle of an RF wave to convey information?\\
B. Phase modulation\\
G8A03 (D) What is the name of the process which changes the frequency of an RF wave to convey information?\\
D. Frequency modulation\\
G8A04 (B) What emission is produced by a reactance modulator connected to an RF power amplifier?\\
B. Phase modulation\\
G8A05 (D) What type of modulation varies the instantaneous power level of the RF signal?\\
D. Amplitude modulation\\
G8A06 (C) What is one advantage of carrier suppression in a single-sideband phone transmission?\\
C. The available transmitter power can be used more effectively\\
G8A07 (A) Which of the following phone emissions uses the narrowest frequency bandwidth?\\
A. Single sideband\\
G8A08 (D) Which of the following is an effect of over-modulation?\\
D. Excessive bandwidth\\
G8A09 (B) What control is typically adjusted for proper ALC setting on an amateur single sideband transceiver?\\
B. Transmit audio or microphone gain\\
G8A10 (C) What is meant by flat-topping of a single-sideband phone transmission?\\
C. Signal distortion caused by excessive drive\\
G8A11 (A) What happens to the RF carrier signal when a modulating audio signal is applied to an FM transmitter?\\
A. The carrier frequency changes proportionally to the instantaneous amplitude of the modulating signal\\
G8A12 (A) What signal(s) would be found at the output of a properly adjusted balanced modulator?\\
A. Both upper and lower sidebands\\
\section{G8B - Frequency mixing; multiplication; HF data communications; bandwidths of various modes; deviation}
G8B01 (A) What receiver stage combines a 14.250 MHz input signal with a 13.795 MHz oscillator signal to produce a 455 kHz intermediate frequency (IF) signal?\\
A. Mixer\\
G8B02 (B) If a receiver mixes a 13.800 MHz VFO with a 14.255 MHz received signal to produce a 455 kHz intermediate frequency (IF) signal, what type of interference will a 13.345 MHz signal produce in the receiver?\\
B. Image response\\
G8B03 (A) What is another term for the mixing of two RF signals?\\
A. Heterodyning\\
G8B04 (D) What is the name of the stage in a VHF FM transmitter that generates a harmonic of a lower frequency signal to reach the desired operating frequency?\\
D. Multiplier\\
G8B05 (C) Why isn't frequency modulated (FM) phone used below 29.5 MHz?\\
C. The wide bandwidth is prohibited by FCC rules\\
G8B06 (D) What is the total bandwidth of an FM-phone transmission having a 5 kHz
deviation and a 3 kHz modulating frequency?\\
D. 16 kHz\\
G8B07 (B) What is the frequency deviation for a 12.21-MHz reactance-modulated oscillator in a 5-kHz deviation, 146.52-MHz FM-phone transmitter?\\
B. 416.7 Hz\\
G8B08 (B) Why is it important to know the duty cycle of the data mode you are using when transmitting?\\
B. Some modes have high duty cycles which could exceed the transmitter's average power rating.\\
G8B09 (D) Why is it good to match receiver bandwidth to the bandwidth of the operating mode?\\
D. It results in the best signal to noise ratio\\
G8B10 (A) What does the number 31 represent in PSK31?\\
A. The approximate transmitted symbol rate\\
G8B11 (C) How does forward error correction allow the receiver to correct errors in received data packets?\\
C. By transmitting redundant information with the data\\
G8B12 (B) What is the relationship between transmitted symbol rate and bandwidth?\\
B. Higher symbol rates require higher bandwidth\\
\chapter{Subelement G9 - Antennas and Feed Lines: 4 Questions}
\section{G9A - Antenna feed lines: characteristic impedance, and attenuation; SWR calculation, measurement and effects; matching networks}
G9A01 (A) Which of the following factors determine the characteristic impedance of a parallel conductor antenna feed line?\\
A. The distance between the centers of the conductors and the radius of the
conductors\\
G9A02 (B) What are the typical characteristic impedances of coaxial cables used for antenna feed lines at amateur stations?\\
B. 50 and 75 ohms\\
G9A03 (D) What is the characteristic impedance of flat ribbon TV type twinlead?\\
D. 300 ohms\\
G9A04 (C) What is the reason for the occurrence of reflected power at the point where a feed line connects to an antenna?\\
C. A difference between feed-line impedance and antenna feed-point impedance\\
G9A05 (B) How does the attenuation of coaxial cable change as the frequency of the signal it is carrying increases?\\
B. It increases\\
G9A06 (D) In what values are RF feed line losses usually expressed?\\
D. dB per 100 ft\\
G9A07 (D) What must be done to prevent standing waves on an antenna feed line?\\
D. The antenna feed-point impedance must be matched to the characteristic impedance of the feed line\\
G9A08 (B) If the SWR on an antenna feed line is 5 to 1, and a matching network at the transmitter end of the feed line is adjusted to 1 to 1 SWR, what is the resulting SWR on the feed line?\\
B. 5 to 1\\
G9A09 (A) What standing wave ratio will result from the connection of a 50-ohm feed line to a non-reactive load having a 200-ohm impedance?\\
A. 4:1\\
G9A10 (D) What standing wave ratio will result from the connection of a 50-ohm feed line to a non-reactive load having a 10-ohm impedance?\\
D. 5:1\\
G9A11 (B) What standing wave ratio will result from the connection of a 50-ohm feed line to a non-reactive load having a 50-ohm impedance?\\
B. 1:1\\
G9A12 (A) What would be the SWR if you feed a vertical antenna that has a 25-ohm feed-point impedance with 50-ohm coaxial cable?\\
A. 2:1\\
G9A13 (C) What would be the SWR if you feed an antenna that has a 300-ohm feed-point impedance with 50-ohm coaxial cable?\\
C. 6:1\\
\section{G9B - Basic antennas}
G9B01 (B) What is one disadvantage of a directly fed random-wire antenna?\\
B. You may experience RF burns when touching metal objects in your station \\
G9B02 (D) What is an advantage of downward sloping radials on a quarter wave ground-plane antenna?\\
D. They bring the feed-point impedance closer to 50 ohms\\
G9B03 (B) What happens to the feed-point impedance of a ground-plane antenna when its radials are changed from horizontal to downward-sloping?\\
B. It increases\\
G9B04 (A) What is the low angle azimuthal radiation pattern of an ideal half-wavelength dipole antenna installed 1/2 wavelength high and parallel to the Earth?\\
A. It is a figure-eight at right angles to the antenna\\
G9B05 (C) How does antenna height affect the horizontal (azimuthal) radiation pattern of a horizontal dipole HF antenna?\\
C. If the antenna is less than 1/2 wavelength high, the azimuthal pattern is almost omnidirectional\\
G9B06 (C) Where should the radial wires of a ground-mounted vertical antenna system be placed?\\
C. On the surface or buried a few inches below the ground\\
G9B07 (B) How does the feed-point impedance of a 1/2 wave dipole antenna change as the antenna is lowered from 1/4 wave above ground?\\
B. It steadily decreases\\
G9B08 (A) How does the feed-point impedance of a 1/2 wave dipole change as the feed-point location is moved from the center toward the ends?\\
A. It steadily increases\\
G9B09 (A) Which of the following is an advantage of a horizontally polarized as compared to vertically polarized HF antenna?\\
A. Lower ground reflection losses \\
G9B10 (D) What is the approximate length for a 1/2-wave dipole antenna cut for 14.250 MHz?\\
D. 32 feet\\
G9B11 (C) What is the approximate length for a 1/2-wave dipole antenna cut for 3.550 MHz?\\
C. 131 feet\\
G9B12 (A) What is the approximate length for a 1/4-wave vertical antenna cut for 28.5 MHz?\\
A. 8 feet\\
\section{G9C - Directional antennas}
G9C01 (A) Which of the following would increase the bandwidth of a Yagi antenna?\\
A. Larger diameter elements\\
G9C02 (B) What is the approximate length of the driven element of a Yagi antenna?\\
B. 1/2 wavelength\\
G9C03 (B) Which statement about a three-element, single-band Yagi antenna is true?\\
B. The director is normally the shortest parasitic element\\
G9C04 (A) Which statement about a three-element; single-band Yagi antenna is true?\\
A. The reflector is normally the longest parasitic element\\
G9C05 (A) How does increasing boom length and adding directors affect a Yagi antenna?\\
A. Gain increases\\
G9C06 (C) Which of the following is a reason why a Yagi antenna is often used for radio communications on the 20 meter band?\\
C. It helps reduce interference from other stations to the side or behind the antenna\\
G9C07 (C) What does "front-to-back ratio" mean in reference to a Yagi antenna?\\
C. The power radiated in the major radiation lobe compared to the power radiated in exactly the opposite direction\\
G9C08 (D) What is meant by the "main lobe" of a directive antenna?\\
D. The direction of maximum radiated field strength from the antenna\\
G9C09 (A) What is the approximate maximum theoretical forward gain of a three element, single-band Yagi antenna?\\
A. 9.7 dBi\\
G9C10 (D) Which of the following is a Yagi antenna design variable that could be adjusted to optimize forward gain, front-to-back ratio, or SWR bandwidth? \\
A. The physical length of the boom\\
B. The number of elements on the boom\\
C. The spacing of each element along the boom\\
D. All of these choices are correct\\
G9C11 (A) What is the purpose of a gamma match used with Yagi antennas?\\
A. To match the relatively low feed-point impedance to 50 ohms\\
G9C12 (A) Which of the following is an advantage of using a gamma match for impedance matching of a Yagi antenna to 50-ohm coax feed line?\\
A. It does not require that the elements be insulated from the boom\\
G9C13 (A) Approximately how long is each side of a quad antenna driven element?\\
A. 1/4 wavelength\\
G9C14 (B) How does the forward gain of a two-element quad antenna compare to the forward gain of a three-element Yagi antenna?\\
B. About the same\\
G9C15 (B) Approximately how long is each side of a quad antenna reflector element?\\
B. Slightly more than 1/4 wavelength\\
G9C16 (D) How does the gain of a two-element delta-loop beam compare to the gain of a two-element quad antenna?\\
D. About the same\\
G9C17 (B) Approximately how long is each leg of a symmetrical delta-loop antenna?\\
B. 1/3 wavelength\\
G9C18 (A) What happens when the feed point of a quad antenna is changed from the center of either horizontal wire to the center of either vertical wire?\\
A. The polarization of the radiated signal changes from horizontal to vertical\\
G9C19 (D) What configuration of the loops of a two-element quad antenna must be used for the antenna to operate as a beam antenna, assuming one of the elements is used as a reflector? \\
D. The reflector element must be approximately 5\% longer than the driven element\\
G9C20 (B) How does the gain of two 3-element horizontally polarized Yagi antennas spaced vertically 1/2 wavelength apart typically compare to the gain of a single 3-element Yagi?\\
B. Approximately 3 dB higher\\
\section{G9D - Specialized antennas}
G9D01 (D) What does the term "NVIS" mean as related to antennas?\\
D. Near Vertical Incidence Sky wave\\
G9D02 (B) Which of the following is an advantage of an NVIS antenna?\\
B. High vertical angle radiation for working stations within a radius of a few hundred kilometers\\
G9D03 (D) At what height above ground is an NVIS antenna typically installed?\\
D. Between 1/10 and 1/4 wavelength\\
G9D04 (A) What is the primary purpose of antenna traps?\\
A. To permit multiband operation\\
G9D05 (D) What is the advantage of vertical stacking of horizontally polarized Yagi antennas?\\
D. Narrows the main lobe in elevation\\
G9D06 (A) Which of the following is an advantage of a log periodic antenna?\\
A. Wide bandwidth\\
G9D07 (A) Which of the following describes a log periodic antenna?\\
A. Length and spacing of the elements increases logarithmically from one end of the boom to the other\\
G9D08 (B) Why is a Beverage antenna not used for transmitting?\\
B. It has high losses compared to other types of antennas\\
G9D09 (B) Which of the following is an application for a Beverage antenna?\\
B. Directional receiving for low HF bands\\
G9D10 (D) Which of the following describes a Beverage antenna?\\
D. A very long and low directional receiving antenna\\
G9D11 (D) Which of the following is a disadvantage of multiband antennas?\\
D. They have poor harmonic rejection\\
\chapter{Subelement G0 - Electrical and RF Safety: 2 Questions}
\section{G0A - RF safety principles, rules and guidelines; routine station evaluation}
G0A01 (A) What is one way that RF energy can affect human body tissue?\\
A. It heats body tissue\\
G0A02 (D) Which of the following properties is important in estimating whether an RF signal exceeds the maximum permissible exposure (MPE)?\\
A. Its duty cycle\\
B. Its frequency\\
C. Its power density\\
D. All of these choices are correct\\
G0A03 (D) [97.13(c)(1)] How can you determine that your station complies with FCC RF exposure regulations?\\
A. By calculation based on FCC OET Bulletin 65\\
B. By calculation based on computer modeling\\
C. By measurement of field strength using calibrated equipment\\
D. All of these choices are correct\\
G0A04 (D) What does "time averaging" mean in reference to RF radiation exposure?\\
D. The total RF exposure averaged over a certain time\\
G0A05 (A) What must you do if an evaluation of your station shows RF energy radiated from your station exceeds permissible limits?\\
A. Take action to prevent human exposure to the excessive RF fields\\
G0A07 (A) What effect does transmitter duty cycle have when evaluating RF exposure? \\
A. A lower transmitter duty cycle permits greater short-term exposure levels\\
G0A08 (C) Which of the following steps must an amateur operator take to ensure compliance with RF safety regulations when transmitter power exceeds levels specified in part 97.13?\\
C. Perform a routine RF exposure evaluation\\
G0A09 (B) What type of instrument can be used to accurately measure an RF field?\\
B. A calibrated field-strength meter with a calibrated antenna\\
G0A10 (D) What is one thing that can be done if evaluation shows that a neighbor might receive more than the allowable limit of RF exposure from the main lobe of a directional antenna?\\
D. Take precautions to ensure that the antenna cannot be pointed in their direction\\
G0A11 (C) What precaution should you take if you install an indoor transmitting antenna?\\
C. Make sure that MPE limits are not exceeded in occupied areas\\
G0A12 (B) What precaution should you take whenever you make adjustments or repairs to an antenna?\\
B. Turn off the transmitter and disconnect the feed line\\
G0A13 (D) What precaution should be taken when installing a ground-mounted antenna?\\
D. It should be installed so no one can be exposed to RF radiation in excess of maximum permissible limits\\
\section{G0B - Safety in the ham shack: electrical shock and treatment, safety grounding, fusing, interlocks, wiring, antenna and tower safety}
G0B01 (A) Which wire or wires in a four-conductor line cord should be attached to fuses or circuit breakers in a device operated from a 240-VAC single-phase source?\\
A. Only the hot wires \\
G0B02 (C) What is the minimum wire size that may be safely used for a circuit that draws up to 20 amperes of continuous current?\\
C. AWG number 12\\
G0B03 (D) Which size of fuse or circuit breaker would be appropriate to use with a circuit that uses AWG number 14 wiring? \\
D. 15 amperes\\
G0B04 (A) Which of the following is a primary reason for not placing a gasoline-fueled generator inside an occupied area?\\
A. Danger of carbon monoxide poisoning\\
G0B05 (B) Which of the following conditions will cause a Ground Fault Circuit Interrupter (GFCI) to disconnect the 120 or 240 Volt AC line power to a device?\\
B. Current flowing from one or more of the hot wires directly to ground\\
G0B06 (D) Why must the metal enclosure of every item of station equipment be grounded?\\
D. It ensures that hazardous voltages cannot appear on the chassis\\
G0B07 (B) Which of the following should be observed for safety when climbing on a tower using a safety belt or harness?\\
B. Always attach the belt safety hook to the belt D-ring with the hook opening away from the tower\\
G0B08 (B) What should be done by any person preparing to climb a tower that supports electrically powered devices?\\
B. Make sure all circuits that supply power to the tower are locked out and tagged\\
G0B09 (D) Why should soldered joints not be used with the wires that connect the base of a tower to a system of ground rods?\\
D. A soldered joint will likely be destroyed by the heat of a lightning strike\\
G0B10 (A) Which of the following is a danger from lead-tin solder?\\
A. Lead can contaminate food if hands are not washed carefully after handling\\
G0B11 (D) Which of the following is good engineering practice for lightning protection grounds?\\
D. They must be bonded together with all other grounds\\
G0B12 (C) What is the purpose of a transmitter power supply interlock?\\
C. To ensure that dangerous voltages are removed if the cabinet is opened\\
G0B13 (A) What must you do when powering your house from an emergency generator?\\
A. Disconnect the incoming utility power feed\\
G0B14 (C) Which of the following is covered by the National Electrical Code?\\
C. Electrical safety inside the ham shack\\
G0B15 (A) Which of the following is true of an emergency generator installation?\\
A. The generator should be located in a well ventilated area \\
G0B16 (C) When might a lead acid storage battery give off explosive hydrogen gas?\\
C. When being charged\\
\end{document}
|
module XiCor
using Random
export xicor
"""
xicor(X, Y[, break_ties_randomly=false[, rng=nothing]])
Computes the correlation ξ between X and Y.
Unlike most coefficients of correlation, ξ ranges from -0.5 to 1.
If there are duplicate values in X, then ties are
broken based on the order in which they are observed.
If the order of X is not random, then you should
set `break_ties_randomly` to `true` to avoid a biased
estimate. You can use the `rng` parameter to
deterministically break ties.
See _A new coefficient of correlation_ by Chatterjee.
[arXiv:1909.10140 [math.ST]](https://arxiv.org/abs/1909.10140)
# Examples
```julia-repl
julia> ξ = xicor(1:100, 1:100)
0.9702970297029703
julia> x = trunc.((1:100) ./ 10); # create x with lots of duplicates
julia> y = rand(MersenneTwister(0), 100);
julia> ξ = xicor(x, y, true, MersenneTwister(0))
-0.01830183018301823
julia> ξ = xicor(x, y, true, MersenneTwister(42))
0.004500450045004545
```
"""
function xicor(X, Y, break_ties_randomly=false, rng=nothing)
if break_ties_randomly
if !isnothing(rng)
index = randperm(rng, length(X))
else
index = randperm(length(X))
end
X = X[index]
Y = Y[index]
end
n = length(X)
Y = Y[sortperm(X)] # how should offset arrays be handled?
sorter = sortperm(Y)
R = zeros(Int, n) # R[i] is the number of j such that Y[j] ≤ Y[i]
L = zeros(Int, n) # L[i] is the number of j such that Y[j] ≥ Y[i]
i = 1
while i <= n
curr = Y[sorter[i]]
counter = 1
i += 1 # look ahead for repeated Y values
while i <= n && Y[sorter[i]] == curr
counter += 1
i += 1
end
i -= 1
for j = i-counter+1:i # fill in R and L values wherever Y == curr
R[sorter[j]] = i
L[sorter[j]] = (n-i) + counter
end
i += 1
end
1 - n * sum(abs.(diff(R))) / (2 * sum(L .* (n .- L)))
end
end # module
|
# packages needed for chapter 1
library(dplyr)
library(tidyr)
library(ggplot2)
library(vioplot)
library(ascii)
library(corrplot)
library(descr)
# Import the datasets needed for chapter 1
PSDS_PATH <- file.path('~', 'statistics-for-data-scientists')
dir.create(file.path(PSDS_PATH, 'figures'))
state <- read.csv(file.path(PSDS_PATH, 'data', 'state.csv'))
dfw <- read.csv(file.path(PSDS_PATH, 'data', 'dfw_airline.csv'))
sp500_px <- read.csv(file.path(PSDS_PATH, 'data', 'sp500_px.csv'))
sp500_sym <- read.csv(file.path(PSDS_PATH, 'data', 'sp500_sym.csv'), stringsAsFactors = FALSE)
kc_tax <- read.csv(file.path(PSDS_PATH, 'data', 'kc_tax.csv'))
lc_loans <- read.csv(file.path(PSDS_PATH, 'data', 'lc_loans.csv'))
airline_stats <- read.csv(file.path(PSDS_PATH, 'data', 'airline_stats.csv'), stringsAsFactors = FALSE)
airline_stats$airline <- ordered(airline_stats$airline, levels=c('Alaska', 'American', 'Jet Blue', 'Delta', 'United', 'Southwest'))
## Code to create state table
state_asc <- state
state_asc[["Population"]] <- formatC(state_asc[["Population"]], format="d", digits=0, big.mark=",")
ascii(state_asc[1:8,], digits=c(0, 0,1), align=c("l", "l", "r", "r"), caption="A few rows of the +data.frame state+ of population and murder rate by state.")
## Code snippet 1.1
mean(state[["Population"]])
mean(state[["Population"]], trim=0.1)
median(state[["Population"]])
## Code snippet 1.2
mean(state[["Murder.Rate"]])
library("matrixStats")
weighted.mean(state[["Murder.Rate"]], w=state[["Population"]])
## Code snippet 1.3
sd(state[["Population"]])
IQR(state[["Population"]])
mad(state[["Population"]])
## Code snippet 1.4
quantile(state[["Murder.Rate"]], p=c(.05, .25, .5, .75, .95))
## Code to create PercentileTable
ascii(
quantile(state[["Murder.Rate"]], p=c(.05, .25, .5, .75, .95)),
include.rownames=FALSE, include.colnames=TRUE, digits=rep(2,5), align=rep("r", 5),
caption="Percentiles of murder rate by state.")
## Code snippet 1.5
boxplot(state[["Population"]]/1000000, ylab="Population (millions)")
## Code for Figure 2
png(filename=file.path(PSDS_PATH, "figures", "psds_0102.png"), width = 3, height=4, units='in', res=300)
par(mar=c(0,4,0,0)+.1)
boxplot(state[["Population"]]/1000000, ylab="Population (millions)")
dev.off()
## Code snippet 1.6
breaks <- seq(from=min(state[["Population"]]), to=max(state[["Population"]]), length=11)
pop_freq <- cut(state[["Population"]], breaks=breaks, right=TRUE, include.lowest = TRUE)
state['PopFreq'] <- pop_freq
table(pop_freq)
## Code for FreqTable
state_abb <- state %>%
arrange(Population) %>%
group_by(PopFreq) %>%
summarize(state = paste(Abbreviation, collapse=","), .drop=FALSE) %>%
complete(PopFreq, fill=list(state='')) %>%
select(state)
state_abb <- unlist(state_abb)
lower_br <- formatC(breaks[1:10], format="d", digits=0, big.mark=",")
upper_br <- formatC(c(breaks[2:10]-1, breaks[11]), format="d", digits=0, big.mark=",")
pop_table <- data.frame("BinNumber"=1:10,
"BinRange"=paste(lower_br, upper_br, sep="-"),
"Count"=as.numeric(table(pop_freq)),
"States"=state_abb)
ascii(pop_table, include.rownames=FALSE, digits=c(0, 0, 0, 0), align=c("l", "r", "r", "l"),
caption="A frequency table of population by state.")
## Code snippet 1.7
hist(state[["Population"]], breaks=breaks)
## Code for Figure 3
png(filename=file.path(PSDS_PATH, "figures", "psds_0103.png"), width = 4, height=4, units='in', res=300)
par(mar=c(4,4,0,0)+.1)
pop_hist <- hist(state[["Population"]], breaks=breaks,
xlab="Population", main="")
dev.off()
## Code snippet 1.8
hist(state[["Murder.Rate"]], freq=FALSE )
lines(density(state[["Murder.Rate"]]), lwd=3, col="blue")
## Code for Figure 4
png(filename=file.path(PSDS_PATH, "figures", "psds_0104.png"), width = 4, height=4, units='in', res=300)
par(mar=c(4,4,0,0)+.1)
hist(state[["Murder.Rate"]], freq=FALSE, xlab="Murder Rate (per 100,000)", main="" )
lines(density(state[["Murder.Rate"]]), lwd=3, col="blue")
dev.off()
## Code for AirportDelays
ascii(
100*as.matrix(dfw/sum(dfw)),
include.rownames=FALSE, include.colnames=TRUE, digits=rep(2,5), align=rep("r", 5),
caption="Percentage of delays by cause at Dallas-Ft. Worth airport.")
## Code for figure 5
png(filename=file.path(PSDS_PATH, "figures", "psds_0105.png"), width = 4, height=4, units='in', res=300)
par(mar=c(4, 4, 0, 1) + .1)
barplot(as.matrix(dfw)/6, cex.axis = 0.8, cex.names = 0.7)
dev.off()
## Code for CorrTable (Table 1.7)
telecom <- sp500_px[, sp500_sym[sp500_sym$sector=="telecommunications_services", 'symbol']]
telecom <- telecom[row.names(telecom)>"2012-07-01", ]
telecom_cor <- cor(telecom)
ascii(telecom_cor, digits=c( 3,3,3,3,3), align=c("l", "r", "r", "r", "r", "r"), caption="Correlation between telecommunication stock returns.",
include.rownames = TRUE, include.colnames = TRUE)
## Code snippet 1.10
etfs <- sp500_px[row.names(sp500_px)>"2012-07-01",
sp500_sym[sp500_sym$sector=="etf", 'symbol']]
corrplot(cor(etfs), method = "ellipse")
## Code for figure 6
png(filename=file.path(PSDS_PATH, "figures", "psds_0106.png"), width = 4, height=4, units='in', res=300)
etfs <- sp500_px[row.names(sp500_px)>"2012-07-01", sp500_sym[sp500_sym$sector=="etf", 'symbol']]
library(corrplot)
corrplot(cor(etfs), method = "ellipse")
dev.off()
## Code snippet 1.11
plot(telecom$T, telecom$VZ, xlab="T", ylab="VZ")
## Code for Figure 7
png(filename=file.path(PSDS_PATH, "figures", "psds_0107.png"), width = 4, height=4, units='in', res=300)
par(mar=c(4,4,0,1)+.1)
plot(telecom$T, telecom$VZ, xlab="T", ylab="VZ", cex=.8)
abline(h=0, v=0, col="grey")
dev.off()
## Code snippet 1.12
kc_tax0 <- subset(kc_tax, TaxAssessedValue < 750000 & SqFtTotLiving>100 &
SqFtTotLiving<3500)
nrow(kc_tax0)
## Code snippet 1.13
ggplot(kc_tax0, (aes(x=SqFtTotLiving, y=TaxAssessedValue))) +
stat_binhex(colour="white") +
theme_bw() +
scale_fill_gradient(low="white", high="black") +
labs(x="Finished Square Feet", y="Tax Assessed Value")
## Code for figure 8
png(filename=file.path(PSDS_PATH, "figures", "psds_0108.png"), width = 4, height=4, units='in', res=300)
ggplot(kc_tax0, (aes(x=SqFtTotLiving, y=TaxAssessedValue))) +
stat_binhex(colour="white") +
theme_bw() +
scale_fill_gradient(low="white", high="black") +
labs(x="Finished Square Feet", y="Tax Assessed Value")
dev.off()
## Code snippet 1.14
ggplot(kc_tax0, aes(SqFtTotLiving, TaxAssessedValue)) +
theme_bw() +
geom_point( alpha=0.1) +
geom_density2d(colour="white") +
labs(x="Finished Square Feet", y="Tax Assessed Value")
## Code for figure 9
png(filename=file.path(PSDS_PATH, "figures", "psds_0109.png"), width = 4, height=4, units='in', res=300)
ggplot(kc_tax0, aes(SqFtTotLiving, TaxAssessedValue)) +
theme_bw() +
geom_point(colour="blue", alpha=0.1) +
geom_density2d(colour="white") +
labs(x="Finished Square Feet", y="Tax Assessed Value")
dev.off()
## Code snippet 1.15
## Code for CrossTabs
x_tab <- CrossTable(lc_loans$grade, lc_loans$status,
prop.c=FALSE, prop.chisq=FALSE, prop.t=FALSE)
tots <- cbind(row.names(x_tab$tab), format(cbind(x_tab$tab, x_tab$rs)))
props <- cbind("", format(cbind(x_tab$prop.row, x_tab$rs/x_tab$gt), digits=1))
c_tot <- c("Total", format(c(x_tab$cs, x_tab$gt)))
asc_tab <- matrix(nrow=nrow(tots)*2+1, ncol=ncol(tots))
colnames(asc_tab) <- c("Grade", colnames(x_tab$tab), "Total")
idx <- seq(1, nrow(asc_tab)-1, by=2)
asc_tab[idx,] <- tots
asc_tab[idx+1,] <- props
asc_tab[nrow(asc_tab), ] <- c_tot
ascii(asc_tab, align=c("l", "r", "r", "r", "r"), include.rownames = FALSE, include.colnames = TRUE)
#########################################################################################
## Code snippet 1.16
boxplot(pct_carrier_delay ~ airline, data=airline_stats, ylim=c(0,50))
## Code for figure 10
png(filename=file.path(PSDS_PATH, "figures", "psds_0110.png"), width = 4, height=4, units='in', res=300)
par(mar=c(4,4,0,0)+.1)
boxplot(pct_carrier_delay ~ airline, data=airline_stats, ylim=c(0,50), cex.axis=.6,
ylab="Daily % of Delayed Flights")
dev.off()
## Code snippet 1.17
ggplot(data=airline_stats, aes(airline, pct_carrier_delay)) +
ylim(0, 50) +
geom_violin() +
labs(x="", y="Daily % of Delayed Flights")
## Code for figure 11
png(filename=file.path(PSDS_PATH, "figures", "psds_0111.png"), width = 4, height=4, units='in', res=300)
ggplot(data=airline_stats, aes(airline, pct_carrier_delay)) +
ylim(0, 50) +
geom_violin(draw_quantiles = c(.25, .5, .75), linetype=2) +
geom_violin(fill=NA, size=1.1) +
theme_bw() +
labs(x="", y="% of Delayed Flights")
dev.off()
## Code snippet 1.18
ggplot(subset(kc_tax0, ZipCode %in% c(98188, 98105, 98108, 98126)),
aes(x=SqFtTotLiving, y=TaxAssessedValue)) +
stat_binhex(colour="white") +
theme_bw() +
scale_fill_gradient( low="white", high="black") +
labs(x="Finished Square Feet", y="Tax Assessed Value") +
facet_wrap("ZipCode")
## Code for figure 12
png(filename=file.path(PSDS_PATH, "figures", "psds_0112.png"), width = 5, height=4, units='in', res=300)
ggplot(subset(kc_tax0, ZipCode %in% c(98188, 98105, 98108, 98126)),
aes(x=SqFtTotLiving, y=TaxAssessedValue)) +
stat_binhex(colour="white") +
theme_bw() +
scale_fill_gradient( low="gray95", high="blue") +
labs(x="Finished Square Feet", y="Tax Assessed Value") +
facet_wrap("ZipCode")
dev.off()
|
-- Andreas, 2019-11-08, issue #4154 reported by Yashmine Sharoda.
-- Warn if a `renaming` clause clashes with an exported name
-- (that is not mentioned in a `using` clause).
module _ where
module M where
postulate
A B : Set
-- These produce warnings (#4154):
module N = M renaming (A to B)
open M renaming (A to B)
-- These produce errors (see also #3057)
-- as they produce ambiguous exports:
Test = B
TestN = N.B
module L = M using (B) renaming (A to B)
|
proposition no_isolated_singularity: fixes z::complex assumes f: "continuous_on S f" and holf: "f holomorphic_on (S - K)" and S: "open S" and K: "finite K" shows "f holomorphic_on S"
|
module Issue289 where
data D : Set where
d : D
record ⊤ : Set where
foo : (x y : D) → ⊤
foo d y = {!y!}
-- WAS:
-- Right hand side must be a single hole when making a case
-- distinction.
-- when checking that the expression ? has type ⊤
-- NOW: (Andreas, 2013-03-22)
-- Since goal is solved, further case distinction is not supported;
-- try `Solve constraints' instead
-- when checking that the expression ? has type ⊤
|
[STATEMENT]
lemma poincare_between_sum_distances:
assumes "u \<in> unit_disc" and "v \<in> unit_disc" and "w \<in> unit_disc"
shows "poincare_between u v w \<longleftrightarrow>
poincare_distance u v + poincare_distance v w = poincare_distance u w" (is "?P' u v w")
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. poincare_between u v w = (poincare_distance u v + poincare_distance v w = poincare_distance u w)
[PROOF STEP]
proof (cases "u = v")
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. u = v \<Longrightarrow> poincare_between u v w = (poincare_distance u v + poincare_distance v w = poincare_distance u w)
2. u \<noteq> v \<Longrightarrow> poincare_between u v w = (poincare_distance u v + poincare_distance v w = poincare_distance u w)
[PROOF STEP]
case True
[PROOF STATE]
proof (state)
this:
u = v
goal (2 subgoals):
1. u = v \<Longrightarrow> poincare_between u v w = (poincare_distance u v + poincare_distance v w = poincare_distance u w)
2. u \<noteq> v \<Longrightarrow> poincare_between u v w = (poincare_distance u v + poincare_distance v w = poincare_distance u w)
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
u = v
goal (1 subgoal):
1. poincare_between u v w = (poincare_distance u v + poincare_distance v w = poincare_distance u w)
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
u = v
u \<in> unit_disc
v \<in> unit_disc
w \<in> unit_disc
goal (1 subgoal):
1. poincare_between u v w = (poincare_distance u v + poincare_distance v w = poincare_distance u w)
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
poincare_between u v w = (poincare_distance u v + poincare_distance v w = poincare_distance u w)
goal (1 subgoal):
1. u \<noteq> v \<Longrightarrow> poincare_between u v w = (poincare_distance u v + poincare_distance v w = poincare_distance u w)
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. u \<noteq> v \<Longrightarrow> poincare_between u v w = (poincare_distance u v + poincare_distance v w = poincare_distance u w)
[PROOF STEP]
case False
[PROOF STATE]
proof (state)
this:
u \<noteq> v
goal (1 subgoal):
1. u \<noteq> v \<Longrightarrow> poincare_between u v w = (poincare_distance u v + poincare_distance v w = poincare_distance u w)
[PROOF STEP]
have "\<forall> w. w \<in> unit_disc \<longrightarrow> (poincare_between u v w \<longleftrightarrow> poincare_distance u v + poincare_distance v w = poincare_distance u w)" (is "?P u v")
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between u v w = (poincare_distance u v + poincare_distance v w = poincare_distance u w)
[PROOF STEP]
proof (rule wlog_positive_x_axis)
[PROOF STATE]
proof (state)
goal (5 subgoals):
1. v \<in> unit_disc
2. u \<in> unit_disc
3. v \<noteq> u
4. \<And>M u v. \<lbrakk>unit_disc_fix M; u \<in> unit_disc; v \<in> unit_disc; u \<noteq> v; \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (moebius_pt M v) (moebius_pt M u) w = (poincare_distance (moebius_pt M v) (moebius_pt M u) + poincare_distance (moebius_pt M u) w = poincare_distance (moebius_pt M v) w)\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
5. \<And>x. \<lbrakk>is_real x; 0 < Re x; Re x < 1\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
fix x
[PROOF STATE]
proof (state)
goal (5 subgoals):
1. v \<in> unit_disc
2. u \<in> unit_disc
3. v \<noteq> u
4. \<And>M u v. \<lbrakk>unit_disc_fix M; u \<in> unit_disc; v \<in> unit_disc; u \<noteq> v; \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (moebius_pt M v) (moebius_pt M u) w = (poincare_distance (moebius_pt M v) (moebius_pt M u) + poincare_distance (moebius_pt M u) w = poincare_distance (moebius_pt M v) w)\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
5. \<And>x. \<lbrakk>is_real x; 0 < Re x; Re x < 1\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
assume "is_real x" "0 < Re x" "Re x < 1"
[PROOF STATE]
proof (state)
this:
is_real x
0 < Re x
Re x < 1
goal (5 subgoals):
1. v \<in> unit_disc
2. u \<in> unit_disc
3. v \<noteq> u
4. \<And>M u v. \<lbrakk>unit_disc_fix M; u \<in> unit_disc; v \<in> unit_disc; u \<noteq> v; \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (moebius_pt M v) (moebius_pt M u) w = (poincare_distance (moebius_pt M v) (moebius_pt M u) + poincare_distance (moebius_pt M u) w = poincare_distance (moebius_pt M v) w)\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
5. \<And>x. \<lbrakk>is_real x; 0 < Re x; Re x < 1\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
have "of_complex x \<in> circline_set x_axis"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. of_complex x \<in> circline_set x_axis
[PROOF STEP]
using \<open>is_real x\<close>
[PROOF STATE]
proof (prove)
using this:
is_real x
goal (1 subgoal):
1. of_complex x \<in> circline_set x_axis
[PROOF STEP]
by (auto simp add: circline_set_x_axis)
[PROOF STATE]
proof (state)
this:
of_complex x \<in> circline_set x_axis
goal (5 subgoals):
1. v \<in> unit_disc
2. u \<in> unit_disc
3. v \<noteq> u
4. \<And>M u v. \<lbrakk>unit_disc_fix M; u \<in> unit_disc; v \<in> unit_disc; u \<noteq> v; \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (moebius_pt M v) (moebius_pt M u) w = (poincare_distance (moebius_pt M v) (moebius_pt M u) + poincare_distance (moebius_pt M u) w = poincare_distance (moebius_pt M v) w)\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
5. \<And>x. \<lbrakk>is_real x; 0 < Re x; Re x < 1\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
have "of_complex x \<in> unit_disc"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. of_complex x \<in> unit_disc
[PROOF STEP]
using \<open>is_real x\<close> \<open>0 < Re x\<close> \<open>Re x < 1\<close>
[PROOF STATE]
proof (prove)
using this:
is_real x
0 < Re x
Re x < 1
goal (1 subgoal):
1. of_complex x \<in> unit_disc
[PROOF STEP]
by (simp add: cmod_eq_Re)
[PROOF STATE]
proof (state)
this:
of_complex x \<in> unit_disc
goal (5 subgoals):
1. v \<in> unit_disc
2. u \<in> unit_disc
3. v \<noteq> u
4. \<And>M u v. \<lbrakk>unit_disc_fix M; u \<in> unit_disc; v \<in> unit_disc; u \<noteq> v; \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (moebius_pt M v) (moebius_pt M u) w = (poincare_distance (moebius_pt M v) (moebius_pt M u) + poincare_distance (moebius_pt M u) w = poincare_distance (moebius_pt M v) w)\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
5. \<And>x. \<lbrakk>is_real x; 0 < Re x; Re x < 1\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
have "x \<noteq> 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. x \<noteq> 0
[PROOF STEP]
using \<open>is_real x\<close> \<open>Re x > 0\<close>
[PROOF STATE]
proof (prove)
using this:
is_real x
0 < Re x
goal (1 subgoal):
1. x \<noteq> 0
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
x \<noteq> 0
goal (5 subgoals):
1. v \<in> unit_disc
2. u \<in> unit_disc
3. v \<noteq> u
4. \<And>M u v. \<lbrakk>unit_disc_fix M; u \<in> unit_disc; v \<in> unit_disc; u \<noteq> v; \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (moebius_pt M v) (moebius_pt M u) w = (poincare_distance (moebius_pt M v) (moebius_pt M u) + poincare_distance (moebius_pt M u) w = poincare_distance (moebius_pt M v) w)\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
5. \<And>x. \<lbrakk>is_real x; 0 < Re x; Re x < 1\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
show "?P (of_complex x) 0\<^sub>h"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
proof (rule allI, rule impI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>w. w \<in> unit_disc \<Longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
fix w
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>w. w \<in> unit_disc \<Longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
assume "w \<in> unit_disc"
[PROOF STATE]
proof (state)
this:
w \<in> unit_disc
goal (1 subgoal):
1. \<And>w. w \<in> unit_disc \<Longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
w \<in> unit_disc
[PROOF STEP]
obtain w' where "w = of_complex w'"
[PROOF STATE]
proof (prove)
using this:
w \<in> unit_disc
goal (1 subgoal):
1. (\<And>w'. w = of_complex w' \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using inf_or_of_complex[of w]
[PROOF STATE]
proof (prove)
using this:
w \<in> unit_disc
w = \<infinity>\<^sub>h \<or> (\<exists>x. w = of_complex x)
goal (1 subgoal):
1. (\<And>w'. w = of_complex w' \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
w = of_complex w'
goal (1 subgoal):
1. \<And>w. w \<in> unit_disc \<Longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
show "?P' (of_complex x) 0\<^sub>h w"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
proof (cases "w = 0\<^sub>h")
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. w = 0\<^sub>h \<Longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
2. w \<noteq> 0\<^sub>h \<Longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
case True
[PROOF STATE]
proof (state)
this:
w = 0\<^sub>h
goal (2 subgoals):
1. w = 0\<^sub>h \<Longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
2. w \<noteq> 0\<^sub>h \<Longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
w = 0\<^sub>h
goal (1 subgoal):
1. poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
goal (1 subgoal):
1. w \<noteq> 0\<^sub>h \<Longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. w \<noteq> 0\<^sub>h \<Longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
case False
[PROOF STATE]
proof (state)
this:
w \<noteq> 0\<^sub>h
goal (1 subgoal):
1. w \<noteq> 0\<^sub>h \<Longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
hence "w' \<noteq> 0"
[PROOF STATE]
proof (prove)
using this:
w \<noteq> 0\<^sub>h
goal (1 subgoal):
1. w' \<noteq> 0
[PROOF STEP]
using \<open>w = of_complex w'\<close>
[PROOF STATE]
proof (prove)
using this:
w \<noteq> 0\<^sub>h
w = of_complex w'
goal (1 subgoal):
1. w' \<noteq> 0
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
w' \<noteq> 0
goal (1 subgoal):
1. w \<noteq> 0\<^sub>h \<Longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
using \<open>is_real x\<close> \<open>x \<noteq> 0\<close> \<open>w = of_complex w'\<close> \<open>w' \<noteq> 0\<close>
[PROOF STATE]
proof (prove)
using this:
is_real x
x \<noteq> 0
w = of_complex w'
w' \<noteq> 0
goal (1 subgoal):
1. poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
using \<open>of_complex x \<in> unit_disc\<close> \<open>w \<in> unit_disc\<close>
[PROOF STATE]
proof (prove)
using this:
is_real x
x \<noteq> 0
w = of_complex w'
w' \<noteq> 0
of_complex x \<in> unit_disc
w \<in> unit_disc
goal (1 subgoal):
1. poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
[PROOF STEP]
apply simp
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>is_real x; x \<noteq> 0; w = of_complex w'; w' \<noteq> 0; cmod x < 1; cmod w' < 1\<rbrakk> \<Longrightarrow> poincare_between (of_complex x) 0\<^sub>h (of_complex w') = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h (of_complex w') = poincare_distance (of_complex x) (of_complex w'))
[PROOF STEP]
apply (subst poincare_between_x_axis_u0v, simp_all)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>is_real x; x \<noteq> 0; w = of_complex w'; w' \<noteq> 0; cmod x < 1; cmod w' < 1\<rbrakk> \<Longrightarrow> (is_real w' \<and> Re x * Re w' < 0) = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h (of_complex w') = poincare_distance (of_complex x) (of_complex w'))
[PROOF STEP]
apply (subst poincare_between_sum_distances_x_axis_u0v, simp_all)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
[PROOF STATE]
proof (state)
this:
poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (of_complex x) 0\<^sub>h w = (poincare_distance (of_complex x) 0\<^sub>h + poincare_distance 0\<^sub>h w = poincare_distance (of_complex x) w)
goal (4 subgoals):
1. v \<in> unit_disc
2. u \<in> unit_disc
3. v \<noteq> u
4. \<And>M u v. \<lbrakk>unit_disc_fix M; u \<in> unit_disc; v \<in> unit_disc; u \<noteq> v; \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (moebius_pt M v) (moebius_pt M u) w = (poincare_distance (moebius_pt M v) (moebius_pt M u) + poincare_distance (moebius_pt M u) w = poincare_distance (moebius_pt M v) w)\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (4 subgoals):
1. v \<in> unit_disc
2. u \<in> unit_disc
3. v \<noteq> u
4. \<And>M u v. \<lbrakk>unit_disc_fix M; u \<in> unit_disc; v \<in> unit_disc; u \<noteq> v; \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (moebius_pt M v) (moebius_pt M u) w = (poincare_distance (moebius_pt M v) (moebius_pt M u) + poincare_distance (moebius_pt M u) w = poincare_distance (moebius_pt M v) w)\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
[PROOF STEP]
show "v \<in> unit_disc" "u \<in> unit_disc"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. v \<in> unit_disc &&& u \<in> unit_disc
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
u \<in> unit_disc
v \<in> unit_disc
w \<in> unit_disc
goal (1 subgoal):
1. v \<in> unit_disc &&& u \<in> unit_disc
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
v \<in> unit_disc
u \<in> unit_disc
goal (2 subgoals):
1. v \<noteq> u
2. \<And>M u v. \<lbrakk>unit_disc_fix M; u \<in> unit_disc; v \<in> unit_disc; u \<noteq> v; \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (moebius_pt M v) (moebius_pt M u) w = (poincare_distance (moebius_pt M v) (moebius_pt M u) + poincare_distance (moebius_pt M u) w = poincare_distance (moebius_pt M v) w)\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. v \<noteq> u
2. \<And>M u v. \<lbrakk>unit_disc_fix M; u \<in> unit_disc; v \<in> unit_disc; u \<noteq> v; \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (moebius_pt M v) (moebius_pt M u) w = (poincare_distance (moebius_pt M v) (moebius_pt M u) + poincare_distance (moebius_pt M u) w = poincare_distance (moebius_pt M v) w)\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
[PROOF STEP]
show "v \<noteq> u"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. v \<noteq> u
[PROOF STEP]
using \<open>u \<noteq> v\<close>
[PROOF STATE]
proof (prove)
using this:
u \<noteq> v
goal (1 subgoal):
1. v \<noteq> u
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
v \<noteq> u
goal (1 subgoal):
1. \<And>M u v. \<lbrakk>unit_disc_fix M; u \<in> unit_disc; v \<in> unit_disc; u \<noteq> v; \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (moebius_pt M v) (moebius_pt M u) w = (poincare_distance (moebius_pt M v) (moebius_pt M u) + poincare_distance (moebius_pt M u) w = poincare_distance (moebius_pt M v) w)\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>M u v. \<lbrakk>unit_disc_fix M; u \<in> unit_disc; v \<in> unit_disc; u \<noteq> v; \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (moebius_pt M v) (moebius_pt M u) w = (poincare_distance (moebius_pt M v) (moebius_pt M u) + poincare_distance (moebius_pt M u) w = poincare_distance (moebius_pt M v) w)\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
[PROOF STEP]
fix M u v
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>M u v. \<lbrakk>unit_disc_fix M; u \<in> unit_disc; v \<in> unit_disc; u \<noteq> v; \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (moebius_pt M v) (moebius_pt M u) w = (poincare_distance (moebius_pt M v) (moebius_pt M u) + poincare_distance (moebius_pt M u) w = poincare_distance (moebius_pt M v) w)\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
[PROOF STEP]
assume *: "unit_disc_fix M" "u \<in> unit_disc" "v \<in> unit_disc" "u \<noteq> v" and
**: "?P (moebius_pt M v) (moebius_pt M u)"
[PROOF STATE]
proof (state)
this:
unit_disc_fix M
u \<in> unit_disc
v \<in> unit_disc
u \<noteq> v
\<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (moebius_pt M v) (moebius_pt M u) w = (poincare_distance (moebius_pt M v) (moebius_pt M u) + poincare_distance (moebius_pt M u) w = poincare_distance (moebius_pt M v) w)
goal (1 subgoal):
1. \<And>M u v. \<lbrakk>unit_disc_fix M; u \<in> unit_disc; v \<in> unit_disc; u \<noteq> v; \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between (moebius_pt M v) (moebius_pt M u) w = (poincare_distance (moebius_pt M v) (moebius_pt M u) + poincare_distance (moebius_pt M u) w = poincare_distance (moebius_pt M v) w)\<rbrakk> \<Longrightarrow> \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
[PROOF STEP]
show "?P v u"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
[PROOF STEP]
proof (rule allI, rule impI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>w. w \<in> unit_disc \<Longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
[PROOF STEP]
fix w
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>w. w \<in> unit_disc \<Longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
[PROOF STEP]
assume "w \<in> unit_disc"
[PROOF STATE]
proof (state)
this:
w \<in> unit_disc
goal (1 subgoal):
1. \<And>w. w \<in> unit_disc \<Longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
[PROOF STEP]
hence "moebius_pt M w \<in> unit_disc"
[PROOF STATE]
proof (prove)
using this:
w \<in> unit_disc
goal (1 subgoal):
1. moebius_pt M w \<in> unit_disc
[PROOF STEP]
using \<open>unit_disc_fix M\<close>
[PROOF STATE]
proof (prove)
using this:
w \<in> unit_disc
unit_disc_fix M
goal (1 subgoal):
1. moebius_pt M w \<in> unit_disc
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
moebius_pt M w \<in> unit_disc
goal (1 subgoal):
1. \<And>w. w \<in> unit_disc \<Longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
[PROOF STEP]
thus "?P' v u w"
[PROOF STATE]
proof (prove)
using this:
moebius_pt M w \<in> unit_disc
goal (1 subgoal):
1. poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
[PROOF STEP]
using \<open>u \<in> unit_disc\<close> \<open>v \<in> unit_disc\<close> \<open>w \<in> unit_disc\<close> \<open>unit_disc_fix M\<close>
[PROOF STATE]
proof (prove)
using this:
moebius_pt M w \<in> unit_disc
u \<in> unit_disc
v \<in> unit_disc
w \<in> unit_disc
unit_disc_fix M
goal (1 subgoal):
1. poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
[PROOF STEP]
using **[rule_format, of "moebius_pt M w"]
[PROOF STATE]
proof (prove)
using this:
moebius_pt M w \<in> unit_disc
u \<in> unit_disc
v \<in> unit_disc
w \<in> unit_disc
unit_disc_fix M
moebius_pt M w \<in> unit_disc \<Longrightarrow> poincare_between (moebius_pt M v) (moebius_pt M u) (moebius_pt M w) = (poincare_distance (moebius_pt M v) (moebius_pt M u) + poincare_distance (moebius_pt M u) (moebius_pt M w) = poincare_distance (moebius_pt M v) (moebius_pt M w))
goal (1 subgoal):
1. poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between v u w = (poincare_distance v u + poincare_distance u w = poincare_distance v w)
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between u v w = (poincare_distance u v + poincare_distance v w = poincare_distance u w)
goal (1 subgoal):
1. u \<noteq> v \<Longrightarrow> poincare_between u v w = (poincare_distance u v + poincare_distance v w = poincare_distance u w)
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
\<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between u v w = (poincare_distance u v + poincare_distance v w = poincare_distance u w)
goal (1 subgoal):
1. poincare_between u v w = (poincare_distance u v + poincare_distance v w = poincare_distance u w)
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
\<forall>w. w \<in> unit_disc \<longrightarrow> poincare_between u v w = (poincare_distance u v + poincare_distance v w = poincare_distance u w)
u \<in> unit_disc
v \<in> unit_disc
w \<in> unit_disc
goal (1 subgoal):
1. poincare_between u v w = (poincare_distance u v + poincare_distance v w = poincare_distance u w)
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
poincare_between u v w = (poincare_distance u v + poincare_distance v w = poincare_distance u w)
goal:
No subgoals!
[PROOF STEP]
qed
|
module finiteStrainLib
use funcAux
use constitutiveLib
implicit none
public calcGradU , calcU, DGradPhiBdotGradPhiA, DGradGrad, calcPpk, calcD, modifyToSpatial, calcFC,&
VirtualPower, buildFbarTensors, build_tenQs
contains
subroutine calcGradU(GradU,Sol,dPhi_G,NdimE,NodElT,iDofSol)
integer, intent(in) :: NdimE, NodElT, iDofSol
Real*8, intent(out) :: GradU(NdimE,NdimE)
Real*8, intent(in) ::dPhi_G(NdimE,NodElT) , Sol(iDofSol*NodElt)
integer :: i, j , e ,ep
GradU = 0.0d0
do e = 1 , NodElT
ep = (e-1)*iDofSol
do i = 1, NdimE
do j = 1, NdimE
GradU(i,j) = GradU(i,j) + Sol(ep+i)*dPhi_G(j,e)
end do
end do
end do
end subroutine
subroutine calcU(U,Sol,Phi,NdimE,NodElT,iDofSol)
integer, intent(in) :: NdimE,NodElT , iDofSol
Real*8, intent(out) :: U(NdimE)
Real*8, intent(in) :: Phi(NodElT) , Sol(iDofSol*NodElt)
integer :: i, e ,ep
U= 0.0d0
do e = 1 , NodElT
ep = (e-1)*iDofSol
do i = 1, NdimE
U(i) = U(i) + Sol(ep+i)*Phi(e)
end do
end do
end subroutine
real*8 function DGradGrad(DD,dPhiA,dPhiB,pA,pB,NdimE) result(rAux) !! correct order :: (D grad A) \cdot grad B
real*8 , intent(in) :: DD(NdimE,NdimE,NdimE,NdimE),dPhiB(NdimE),dPhiA(NdimE)
integer, intent(in) :: pA,pB, NdimE
integer :: j,l
rAux = 0.0d0
do j=1,NdimE
do l=1,NdimE
rAux= rAux + DD(pB,j,pA,l)*dPhiB(j)*dPhiA(l)
end do
end do
end function
real*8 function DGradPhiBdotGradPhiA(DD,dPhiB,dPhiA,p,q,NdimE) result(rAux) !! It would be more easy if it would q,p
real*8 , intent(in) :: DD(NdimE,NdimE,NdimE,NdimE),dPhiB(NdimE),dPhiA(NdimE)
integer, intent(in) :: p,q, NdimE
integer :: j,l
rAux = 0.0d0
do j=1,NdimE
do l=1,NdimE
rAux= rAux + DD(p,j,q,l)*dPhiA(j)*dPhiB(l)
end do
end do
end function
subroutine calcPpk(Ppk,F,NdimE,matPar,constLaw)
integer , intent(in) :: NDimE,constLaw
real*8, intent(in) :: MatPar(:), F(NDimE,NDimE)
real*8, intent(out) :: Ppk(NDimE,NDimE)
real*8 , parameter :: eps = 1.d-4
real*8 :: Fp(NDimE,NDimE), inv2eps, energyPr , energyPl
integer :: i,j
inv2eps = 0.5d0/eps
Do i=1,NdimE
Do j=1,NdimE
Fp=F
Fp(i,j) = Fp(i,j) + eps
Call StrainEnergy(energyPr,Fp,MatPar,constLaw)
Fp=F
Fp(i,j) = Fp(i,j) - eps
Call StrainEnergy(energyPl,Fp,MatPar,constLaw)
Ppk(i,j) = (energyPr - energyPl)*inv2eps
Enddo
Enddo
end subroutine
subroutine calcD(D,F,NdimE,matPar,constLaw)
integer , intent(in) :: NDimE,constLaw
real*8, intent(in) :: MatPar(:), F(NDimE,NDimE)
real*8, intent(out) :: D(NDimE,NDimE,NDimE,NDimE)
real*8 , parameter :: eps = 1.d-4
real*8 :: Fp(NDimE,NDimE), inveps2, inv4eps2, energy, energyPrr , energyPrl, energyPlr, energyPll
integer :: i,j, k, l
inv4eps2 = 0.25d0/(eps*eps)
inveps2 = 1.0d0/(eps*eps)
call strainEnergy(energy,F,MatPar,constLaw)
Do i=1,NdimE
Do j=1,NdimE
Do k=1,NdimE
Do l=1,NdimE
if(i==k .and. j==l) then
Fp=F
Fp(i,j) = Fp(i,j) + eps
Call StrainEnergy(energyPrr,Fp,MatPar,constLaw)
Fp=F
Fp(i,j) = Fp(i,j) - eps
Call StrainEnergy(energyPll,Fp,MatPar,constLaw)
D(i,j,i,j) = (energyPrr + energyPll - 2.0d0*energy)*inveps2
else
Fp=F
Fp(i,j) = Fp(i,j) + eps
Fp(k,l) = Fp(k,l) + eps
Call StrainEnergy(energyPrr,Fp,MatPar,constLaw)
Fp=F
Fp(i,j) = Fp(i,j) + eps
Fp(k,l) = Fp(k,l) - eps
Call StrainEnergy(energyPrl,Fp,MatPar,constLaw)
Fp=F
Fp(i,j) = Fp(i,j) - eps
Fp(k,l) = Fp(k,l) + eps
Call StrainEnergy(energyPlr,Fp,MatPar,constLaw)
Fp=F
Fp(i,j) = Fp(i,j) - eps
Fp(k,l) = Fp(k,l) - eps
Call StrainEnergy(energyPll,Fp,MatPar,constLaw)
D(i,j,k,l) = (energyPrr + energyPll - energyPrl - energyPlr)*inv4eps2
end if
end do
end do
end do
end do
end subroutine
subroutine modifyToSpatial(Ds,Sigma,F,detF,NdimE)
Real*8 , intent(out) :: sigma(NdimE,NdimE), Ds(NdimE,NdimE,NdimE,NdimE)
Real*8 , intent(in) :: F(NdimE,NdimE),detF
integer , intent(in) :: NDimE
Real*8 :: D(NdimE,NdimE,NdimE,NdimE), detFtemp
integer :: i,j,k,l,m,n,p,q
D = Ds
sigma = (1.0d0/detF)*matmul(sigma,transpose(F))
Ds = 0.0d0
do i = 1,NdimE
do j = 1,NdimE
do k = 1,NdimE
do l = 1,NdimE
do p = 1,NdimE
do q = 1,NdimE
Ds(i,j,k,l) = Ds(i,j,k,l) + D(i,p,k,q)*F(j,p)*F(l,q)/detF
end do
end do
end do
end do
end do
end do
end subroutine
subroutine calcFC(U,GradU,F,FT,FinvT,C,detF,Sol1,Phi,dPhi_G,NdimE,NodElT,iDofSol)
integer, intent(in) :: NdimE,NodElT , iDofSol !!! Not exactly iDofT
Real*8, intent(out) :: U(NdimE), GradU(NdimE,NdimE) , F(NdimE,NdimE), FT(NdimE,NdimE) , &
FinvT(NdimE,NdimE) , C(NdimE,NdimE) , detF
Real*8, intent(in) ::Phi(NodElT), dPhi_G(NdimE,NodElT) , Sol1(iDofSol*NodElt)
integer :: i, j , e ,ep
! Computes U and GradU
U = 0.0d0
GradU = 0.0d0
do e = 1 , NodElT
ep = (e-1)*iDofSol
do i = 1, NdimE
U(i) = U(i) + Sol1(ep+i)*Phi(e)
do j = 1, NdimE
!~ if(i==3) write(*,*) Sol1(ep+i), dPhi_G(j,e)
GradU(i,j) = GradU(i,j) + Sol1(ep+i)*dPhi_G(j,e)
end do
end do
end do
!~ call printVec(Sol1(1:9))
!~ call printMat(dPhi_G)
!~ ! Computes F = I + GradU + F0
call addEye(F) !! F = F0 + I
F = F + GradU !!! F might be initialized before as zeros or with a given deformation
FT = transpose(F) !~ ! Computes FT = (F)^T
C = matmul(FT,F) ! Cauchy-Grenn tensor
call MatInv(FinvT,detF,FT) ! FinvT= (FT)^-1 , defF = det(FT) = det(F)
return
end subroutine
subroutine VirtualPower()
use ptsGaussLib2
!~ integer , parameter :: NdimE = 2 , iFemType = 2 !! For linear quadrangles
integer , parameter :: NdimE = 3 , iFemType = 6 !! tetrahedra
integer :: pOrder , NGP, NodG, iSimplex, iBubble, nG, constLaw
real*8 :: MatPar(3), alpha
real*8 , allocatable :: Xel(:), SolU(:), Xs(:), Xm(:), SolV(:)
Real*8 :: dVs , detF0s, detFs
Real*8 , dimension(NdimE,NdimE) :: GradUs , GradU0s, GradVs, DsGradUs, sigma
Real*8 , dimension(NdimE,NdimE) :: Fs, F0s, Fbars, tenQsGradUs, tenQsGradU0s
Real*8 , dimension(NdimE,NdimE,NdimE,NdimE) :: Ds , tenQs
type(ptGaussClass) :: PtGs, PtG0s
real*8 :: PotAs, PotQs, PotQ0s, PotTs
Real*8 :: dVm , detF0m, detFm
Real*8 , dimension(NdimE,NdimE) :: GradUm , GradU0m, GradVm, DmGradUm, Ppk
Real*8 , dimension(NdimE,NdimE) :: Fm, F0m, Fbarm, tenQmGradUm, tenQmGradU0m
Real*8 , dimension(NdimE,NdimE,NdimE,NdimE) :: Dm , tenQm, tenQ0m
type(ptGaussClass) :: PtGm, PtG0m
real*8 :: PotAm, PotQm, PotQ0m, PotTm
constLaw = 4
MatPar = (/100.0d0, 200.0d0, 5000.0d0/)
if(NdimE == 2) then
alpha = 0.5d0
else if(NdimE == 3) then
alpha = 1.0d0/3.0d0
end if
call setFEMtype(iFEMtype,NodG,pOrder,NGP,iSimplex,iBubble)
write(0,*) NGP
allocate(Xel(NdimE*NodG),SolU(NdimE*NodG),Xs(NdimE*NodG),Xm(NdimE*NodG),SolV(NdimE*NodG))
!! quadrangles
!~ Xel = (/-1.0d0,-1.0d0,1.0d0,-1.0d0,1.0d0, 1.0d0,-1.0d0, 1.0d0/)
!~ SolU = (/0.01d0,0.02d0,0.03d0,0.04d0,0.05d0, 0.06d0,0.07d0, 0.08d0/)
!~ SolV = (/-1.0d0,1.0d0,2.0d0,3.0d0,-0.1d0, 4.0d0,5.0d0, -5.0d0/)
!~
!! tetrahedra !!! linear, is not well posed the method
Xel = (/-0.02d0, -0.02d0, -0.02d0, 1.00d0, 0.00d0, 0.00d0, 0.00d0, 1.00d0, 0.00d0, 0.00d0, 0.00d0, 1.00d0 /)
SolU = (/0.02d0, 0.02d0, 0.03d0, 0.04d0, 0.05d0, 0.06d0, 0.07d0, 0.08d0, 0.02d0, 0.03d0, 0.04d0, -0.00d0 /)
SolV = (/0.01d0, 0.03d0, -0.03d0, -0.04d0, 0.08d0, 0.01d0, -0.07d0, -0.09d0, -0.01d0, 0.02d0, 0.03d0, -0.05d0 /)
Xs = Xel + SolU
Xm = Xel
call PtGs%init(Xs,NodG,NdimE,NGP,pOrder,iBubble, iSimplex)
call PtG0s%init(Xs,NodG,NdimE,1,pOrder,iBubble,iSimplex)
call PtGm%init(Xm,NodG,NdimE,NGP,pOrder,iBubble, iSimplex)
call PtG0m%init(Xm,NodG,NdimE,1,pOrder,iBubble,iSimplex)
call numprint(ptGs%dV)
call numprint(ptGm%dV)
nG = 1
call PtG0s%calcGradU(GradU0s,SolU,nG)
F0s = 0.0d0
call computeFs(F0s,detF0s,gradU0s,NdimE)
nG = 1
call PtG0m%calcGradU(GradU0m,SolU,nG)
F0m = deltaKron(1:NdimE,1:NdimE) + GradU0m
call calcI3(detF0m,F0m)
PotAs = 0.0d0; PotQs = 0.0d0; PotQ0s = 0.0d0; PotTs = 0.0d0
PotAm = 0.0d0; PotQm = 0.0d0; PotQ0m = 0.0d0; PotTm = 0.0d0
Do nG = 1, NGP ! LoopGauss
call PtGs%calcGradU(GradUs,SolU,nG)
call PtGs%calcGradU(GradVs,SolV,nG)
call PtGm%calcGradU(GradUm,SolU,nG)
call PtGm%calcGradU(GradVm,SolV,nG)
Fs = 0.0d0
call computeFs(Fs,detFs,gradUs,NdimE)
Fm = deltaKron(1:NdimE,1:NdimE) + GradUm
call calcI3(detFm,Fm)
write(0,*) detF0s/detFs
Fbars = ((detF0s/detFs)**alpha)*Fs
Fbarm = ((detF0m/detFm)**alpha)*Fm
call calcPpk(sigma,Fbars,NdimE,matPar,constLaw)
call calcD(Ds,Fbars,NdimE,matPar,constLaw)
call modifyToSpatial(Ds,sigma,Fbars,detF0s,NdimE)
call calcPpk(Ppk,Fbarm,NdimE,matPar,constLaw)
call calcD(Dm,Fbarm,NdimE,matPar,constLaw)
call build_tenQs(Ds,sigma,tenQs,NdimE)
call buildFbarTensors(Dm,Ppk,tenQm,tenQ0m,Fm,F0m,NdimE)
dVs=ptGs%dV(nG)
dVm=ptGm%dV(nG)
call T4xT2(DsGradUs,Ds,GradUs)
call T4xT2(tenQsGradUs,tenQs,GradUs)
call T4xT2(tenQsGradU0s,tenQs,GradU0s)
call T4xT2(DmGradUm,Dm,GradUm)
call T4xT2(tenQmGradUm,tenQm,GradUm)
call T4xT2(tenQmGradU0m,tenQ0m,GradU0m)
PotAs = PotAs + dot_product2(DsGradUs,GradVs)*dvs
PotQs = PotQs + dot_product2(tenQsGradUs,GradVs)*dvs
PotQ0s = PotQ0s + dot_product2(tenQsGradU0s,GradVs)*dvs
PotTs = PotTs + dot_product2(sigma,GradVs)*dvs
PotAm = PotAm + dot_product2(DmGradUm,GradVm)*dvm
PotQm = PotQm + dot_product2(tenQmGradUm,GradVm)*dvm
PotQ0m = PotQ0m + dot_product2(tenQmGradU0m,GradVm)*dvm
PotTm = PotTm + dot_product2(Ppk,GradVm)*dvm
end do
write(0,*) PotAs, PotQs, PotQ0s, PotTs
write(0,*) PotAm, PotQm, PotQ0m, PotTm
pause
end subroutine
subroutine buildFbarTensors(Astar,PpkStar,Qstar,Q0star,F,F0,NdimE)
real*8 , intent(inout) :: Astar(NdimE,NdimE,NdimE,NdimE), PpkStar(NdimE,NdimE)
real*8 , intent(inout) :: Qstar(NdimE,NdimE,NdimE,NdimE), Q0star(NdimE,NdimE,NdimE,NdimE)
real*8 , intent(in) :: F(NdimE,NdimE), F0(NdimE,NdimE)
integer , intent(in) :: NdimE
real*8 :: Finv(NdimE,NdimE), F0inv(NdimE,NdimE), Jratio, detF, detF0, alpha , beta, gamma, lamb
integer :: i,j,k,l,p,q
call MatInv(Finv,detF,F) !! maybe detF0 is not correct because is 2D
call MatInv(F0inv,detF0,F0) !! maybe detF0 is not correct because is 2D
if(NdimE == 2) then
alpha = -0.5d0
beta = 0.0d0
gamma = 0.5d0
lamb = -0.5d0
else if(NdimE == 3) then
alpha = -2.0d0/3.0d0
beta = -1.0d0/3.0d0
gamma = 1.0d0/3.0d0
lamb = -2.0d0/3.0d0
end if
Jratio = detF0/detF
PpkStar = (Jratio**alpha)*PpkStar
Astar = (Jratio**beta)*Astar
Qstar = 0.0d0
Q0star = 0.0d0
do i = 1 , NdimE
do j = 1 , NdimE
do k = 1 , NdimE
do l = 1 , NdimE
do p = 1 , NdimE
do q = 1 , NdimE
Qstar(i,j,k,l) = Qstar(i,j,k,l) + gamma*Astar(i,j,p,q)*F(p,q)*Finv(l,k) !! for 2D
Q0star(i,j,k,l) = Q0star(i,j,k,l) + gamma*Astar(i,j,p,q)*F(p,q)*F0inv(l,k) !! for 2D
end do
end do
Qstar(i,j,k,l) = Qstar(i,j,k,l) + lamb*PpkStar(i,j)*Finv(l,k)
Q0star(i,j,k,l) = Q0star(i,j,k,l) + lamb*PpkStar(i,j)*F0inv(l,k)
end do
end do
end do
end do
end subroutine
subroutine build_tenQs(Ds,sigma,tenQs,NdimE)
real*8 , intent(inout) :: Ds(NdimE,NdimE,NdimE,NdimE), sigma(NdimE,NdimE)
real*8 , intent(inout) :: tenQs(NdimE,NdimE,NdimE,NdimE)
integer , intent(in) :: NdimE
integer :: i,j,k,l,p,q
real*8 :: gamma, lamb
tenQs = 0.0d0
if(NdimE == 2) then
gamma = 0.5d0
lamb = -0.5d0
else if(NdimE == 3) then
gamma = 1.0d0/3.0d0
lamb = -2.0d0/3.0d0
end if
do i = 1 , NdimE
do j = 1 , NdimE
do k = 1 , NdimE
do l = 1 , NdimE
do p = 1 , NdimE
do q = 1 , NdimE
tenQs(i,j,k,l) = tenQs(i,j,k,l) + gamma*Ds(i,j,p,q)*deltaKron(p,q)*deltaKron(k,l)
end do
end do
tenQs(i,j,k,l) = tenQs(i,j,k,l) + lamb*sigma(i,j)*deltaKron(k,l)
end do
end do
end do
end do
end subroutine
end module
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define COMPEARTH_PRIVATE_DET3X3 1
#include "compearth.h"
/*
#ifdef COMPEARTH_USE_MKL
#include <mkl_cblas.h>
#else
#include <cblas.h>
#endif
*/
//static double det3x3ColumnMajor(const double *__restrict__ A);
/*!
* @brief Ensure that U is a rotation matrix with det(U) = 1.
*
* @param[in] n Number of rotation matrices.
* @param[in] Uin Rotation matrices to check. This is an array of dimension
* [3 x 3 x n] where each [3 x 3] matrix is in column major
* format.
* @param[in] Uout Rotation matrices with determinants all positive. This
* is an array of dimension [3 x 3 x n] where each [3 x 3]
* matrix is in column major format.
*
* @result 0 indicates success.
*
* @author Carl Tape and translated to C by Ben Baker
*
* @copyright MIT
*
*/
int compearth_Udetcheck(const int n,
const double *__restrict__ Uin,
double *__restrict__ Uout)
{
double det;
int i, imt;
// Copy Uin to Uout
memcpy(Uout, Uin, 9*(size_t) n*sizeof(double));
//cblas_dcopy(9*n, Uin, 1, Uout, 1);
// Fix
for (imt=0; imt<n; imt++)
{
det = det3x3ColumnMajor(&Uout[9*imt]);
// Negate the second column
if (det < 0.0)
{
for (i=0; i<3; i++)
{
Uout[9*imt+3+i] =-Uout[9*imt+3+i];
}
}
}
// Verify
for (imt=0; imt<n; imt++)
{
det = det3x3ColumnMajor(&Uout[9*imt]);
if (det < 0.0)
{
fprintf(stderr, "%s: Error det(u) < 0\n", __func__);
return -1;
}
}
return 0;
}
/*
static double det3x3ColumnMajor(const double *__restrict__ A)
{
double det;
det = A[0]*( A[4]*A[8] - A[5]*A[7])
- A[3]*( A[1]*A[8] - A[2]*A[7])
+ A[6]*( A[1]*A[5] - A[2]*A[4]);
return det;
}
*/
|
#include <assert.h>
#include <complex.h>
#include <gsl/gsl_const_mksa.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <malloc.h>
#include <math.h>
#include <nlopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tsvread.h"
typedef struct {
gsl_spline *spline;
gsl_interp_accel *acc;
int flags;
double d;
} f_param_t;
double opt_func(unsigned n, const double *x, double *grad, void *f_data) {
f_param_t *fparam = (f_param_t *)f_data;
gsl_spline *spline_nu = fparam->spline;
gsl_interp_accel *acc_nu = fparam->acc;
int flags = fparam->flags;
double d = fparam->d;
return gsl_spline_eval(spline_nu, x[0], acc_nu);
}
int main(int argc, char **argv) {
/* open file for reading data */
tsv_t *tsv = tsv_fread(argv[1]);
if (tsv->columns != 2) {
fprintf(stderr, "input file must be 2 colums tab seperated\n");
return -1;
}
double *x_nu = (double *)malloc(tsv->rows * sizeof(double));
double *y_nu = (double *)malloc(tsv->rows * sizeof(double));
assert(x_nu != NULL);
assert(y_nu != NULL);
unsigned int i;
for (i = 0; i < tsv->rows; i++) {
x_nu[i] = tsv->data[i][0];
y_nu[i] = tsv->data[i][1];
}
gsl_interp_accel *acc_nu = gsl_interp_accel_alloc();
gsl_spline *spline_nu = gsl_spline_alloc(gsl_interp_cspline, tsv->rows);
gsl_spline_init(spline_nu, x_nu, y_nu, tsv->rows);
double x[1]; /* initial guess */
double lb[1]; /* lower bound */
double ub[1]; /* upper bound */
double minf = 0;
lb[0] = x_nu[0];
ub[0] = x_nu[tsv->rows - 1];
x[0] = x_nu[tsv->rows / 2];
f_param_t *fparam = (f_param_t *)malloc(1 * sizeof(f_param_t));
fparam->spline = spline_nu;
fparam->acc = acc_nu;
fparam->flags = 0;
void *fvparam;
fvparam = fparam;
nlopt_opt opt;
opt = nlopt_create(NLOPT_LN_NELDERMEAD, 1);
nlopt_set_lower_bounds(opt, lb);
nlopt_set_upper_bounds(opt, ub);
nlopt_set_max_objective(opt, opt_func, fvparam);
nlopt_set_xtol_rel(opt, 1e-16);
// nlopt_set_ftol_abs(opt,1e-6);
// nlopt_set_maxtime(opt,4);
int err;
double max_nu;
err = nlopt_optimize(opt, x, &minf);
if (err < 0) {
fprintf(stderr, "nlopt failed! %d\n", err);
fprintf(stderr, "lower: %g\n", lb[0]);
fprintf(stderr, "upper: %g\n", ub[0]);
fprintf(stderr, "guess: %g\n", x[0]);
if (lb[0] > ub[0]) {
fprintf(stderr, "lower bigger than upper\n");
}
} else {
max_nu = gsl_spline_eval(spline_nu, x[0], acc_nu);
printf("Maximum: %.20g %.20g \n", x[0], max_nu);
}
nlopt_destroy(opt);
tsv_free(tsv);
free(x_nu);
free(y_nu);
return 0;
}
|
function prepareTravelTimeDataFiles(m,Minv::RegularMesh,mref,boundsHigh,boundsLow,filenamePrefix::String,pad::Int64,jump::Int64,offset::Int64,useFilesForFields::Bool = false)
### Here we generate data files for sources and receivers. This can be replaced with real sources/receivers files.
########################## m is in Velocity here. ###################################
RCVfile = string(filenamePrefix,"_rcvMap.dat");
SRCfile = string(filenamePrefix,"_srcMap.dat");
writeSrcRcvLocFile(SRCfile,Minv,pad,jump);
writeSrcRcvLocFile(RCVfile,Minv,pad,1);
dataFullFilename = string(filenamePrefix,"_travelTime");
HO = false;
prepareTravelTimeDataFiles(m, Minv, filenamePrefix,dataFullFilename,offset,HO,useFilesForFields);
file = matopen(string(filenamePrefix,"_PARAM.mat"), "w");
write(file,"MinvOmega",Minv.domain);
write(file,"boundsLow",boundsLow);
write(file,"boundsHigh",boundsHigh);
write(file,"mref",mref);
write(file,"MinvN",Minv.n);
write(file,"HO",HO);
close(file);
return;
end
function prepareTravelTimeDataFiles(m, Minv::RegularMesh, filenamePrefix::String,dataFullFilename::String, offset::Int64,HO::Bool,useFilesForFields::Bool = false)
########################## m is in Velocity here. ###################################
RCVfile = string(filenamePrefix,"_rcvMap.dat");
SRCfile = string(filenamePrefix,"_srcMap.dat");
srcNodeMap = readSrcRcvLocationFile(SRCfile,Minv);
rcvNodeMap = readSrcRcvLocationFile(RCVfile,Minv);
Q = generateSrcRcvProjOperators(Minv.n.+1,srcNodeMap);
Q = Q.*(1.0./(norm(Minv.h)^2));
P = generateSrcRcvProjOperators(Minv.n.+1,rcvNodeMap);
# compute observed data
println("~~~~~~~ Getting data Eikonal: ~~~~~~~");
(pForEIK,contDivEIK,SourcesSubIndEIK) = getEikonalInvParam(Minv,Q,P,HO,nworkers(),useFilesForFields);
(D,pForEIK) = getData(velocityToSlowSquared(m[:])[1],pForEIK,ones(length(pForEIK)),true);
Dobs = Array{Array{Float64,2}}(undef,length(pForEIK))
for k = 1:length(pForEIK)
Dobs[k] = fetch(D[k]);
end
Dobs = arrangeRemoteCallDataIntoLocalData(Dobs);
# D should be of length 1 becasue constMUSTBeOne = 1;
Dobs += 0.01*mean(abs.(Dobs))*randn(size(Dobs,1),size(Dobs,2));
Wd = (1.0./(abs.(Dobs) .+ 0.1*mean(abs.(Dobs))));
Wd = limitDataToOffset(Wd,srcNodeMap,rcvNodeMap,offset);
writeDataFile(string(dataFullFilename,".dat"),Dobs,Wd,srcNodeMap,rcvNodeMap);
return (Dobs,Wd)
end
|
[GOAL]
α : Type u_1
inst✝¹ : Ring α
inst✝ : Nontrivial α
C : PositiveCone α
src✝¹ : Ring α := inst✝¹
src✝ : OrderedAddCommGroup α := OrderedAddCommGroup.mkOfPositiveCone C.toPositiveCone
h : 0 = 1
⊢ False
[PROOFSTEP]
simpa [← h, C.pos_iff] using C.one_pos
[GOAL]
α : Type u_1
inst✝¹ : Ring α
inst✝ : Nontrivial α
C : PositiveCone α
src✝¹ : Ring α := inst✝¹
src✝ : OrderedAddCommGroup α := OrderedAddCommGroup.mkOfPositiveCone C.toPositiveCone
⊢ 0 ≤ 1
[PROOFSTEP]
change C.nonneg (1 - 0)
[GOAL]
α : Type u_1
inst✝¹ : Ring α
inst✝ : Nontrivial α
C : PositiveCone α
src✝¹ : Ring α := inst✝¹
src✝ : OrderedAddCommGroup α := OrderedAddCommGroup.mkOfPositiveCone C.toPositiveCone
⊢ AddCommGroup.PositiveCone.nonneg C.toPositiveCone (1 - 0)
[PROOFSTEP]
convert C.one_nonneg
[GOAL]
case h.e'_4
α : Type u_1
inst✝¹ : Ring α
inst✝ : Nontrivial α
C : PositiveCone α
src✝¹ : Ring α := inst✝¹
src✝ : OrderedAddCommGroup α := OrderedAddCommGroup.mkOfPositiveCone C.toPositiveCone
⊢ 1 - 0 = 1
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝¹ : Ring α
inst✝ : Nontrivial α
C : PositiveCone α
src✝¹ : Ring α := inst✝¹
src✝ : OrderedAddCommGroup α := OrderedAddCommGroup.mkOfPositiveCone C.toPositiveCone
x y : α
xp : 0 < x
yp : 0 < y
⊢ 0 < x * y
[PROOFSTEP]
change
C.pos
(x * y - 0)
-- porting note: used to be convert, but it relied on unfolding definitions
[GOAL]
α : Type u_1
inst✝¹ : Ring α
inst✝ : Nontrivial α
C : PositiveCone α
src✝¹ : Ring α := inst✝¹
src✝ : OrderedAddCommGroup α := OrderedAddCommGroup.mkOfPositiveCone C.toPositiveCone
x y : α
xp : 0 < x
yp : 0 < y
⊢ AddCommGroup.PositiveCone.pos C.toPositiveCone (x * y - 0)
[PROOFSTEP]
rw [sub_zero]
[GOAL]
α : Type u_1
inst✝¹ : Ring α
inst✝ : Nontrivial α
C : PositiveCone α
src✝¹ : Ring α := inst✝¹
src✝ : OrderedAddCommGroup α := OrderedAddCommGroup.mkOfPositiveCone C.toPositiveCone
x y : α
xp : 0 < x
yp : 0 < y
⊢ AddCommGroup.PositiveCone.pos C.toPositiveCone (x * y)
[PROOFSTEP]
exact C.mul_pos x y (by rwa [← sub_zero x]) (by rwa [← sub_zero y])
[GOAL]
α : Type u_1
inst✝¹ : Ring α
inst✝ : Nontrivial α
C : PositiveCone α
src✝¹ : Ring α := inst✝¹
src✝ : OrderedAddCommGroup α := OrderedAddCommGroup.mkOfPositiveCone C.toPositiveCone
x y : α
xp : 0 < x
yp : 0 < y
⊢ AddCommGroup.PositiveCone.pos C.toPositiveCone x
[PROOFSTEP]
rwa [← sub_zero x]
[GOAL]
α : Type u_1
inst✝¹ : Ring α
inst✝ : Nontrivial α
C : PositiveCone α
src✝¹ : Ring α := inst✝¹
src✝ : OrderedAddCommGroup α := OrderedAddCommGroup.mkOfPositiveCone C.toPositiveCone
x y : α
xp : 0 < x
yp : 0 < y
⊢ AddCommGroup.PositiveCone.pos C.toPositiveCone y
[PROOFSTEP]
rwa [← sub_zero y]
|
lemma dvd_smult_iff: "a \<noteq> 0 \<Longrightarrow> p dvd smult a q \<longleftrightarrow> p dvd q" for a :: "'a::field"
|
chapter \<open>Deadlock Free Transition Systems\<close>
theory DF_System
imports Main
begin
text \<open>
Theories to describe deadlock free transitions system and
simulations between them.
We added these locales after the competition, in order to get a cleaner
solution for Challenge~3. This theory provides not much more than what is
needed for solving the challenge.
\<close>
section \<open>Transition System\<close>
locale system =
fixes s\<^sub>0 :: 's
and lstep :: "'l \<Rightarrow> 's \<Rightarrow> 's \<Rightarrow> bool"
begin
abbreviation "step s s' \<equiv> \<exists>l. lstep l s s'"
definition "reachable \<equiv> (step\<^sup>*\<^sup>*) s\<^sub>0"
definition "can_step l s \<equiv> \<exists>s'. lstep l s s'"
end
section \<open>Deadlock Free Transition System\<close>
locale df_system = system +
assumes no_deadlock: "reachable s \<Longrightarrow> \<exists>s'. step s s'"
begin
paragraph \<open>Runs\<close>
definition "is_lrun l s \<equiv> s 0 = s\<^sub>0 \<and> (\<forall>i. lstep (l i) (s i) (s (Suc i)))"
definition "is_run s \<equiv> \<exists>l. is_lrun l s"
paragraph \<open>Weak Fairness\<close>
definition "is_lfair ls ss \<equiv> \<forall>l i. \<exists>j\<ge>i. \<not>can_step l (ss j) \<or> ls j = l"
definition "is_fair_run s \<equiv> \<exists>l. is_lrun l s \<and> is_lfair l s"
text \<open>Definitions of runs. Used e.g. to clarify TCB of lemmas over systems.\<close>
lemmas run_definitions = is_lrun_def is_run_def is_lfair_def is_fair_run_def
lemma is_run_alt: "is_run s \<longleftrightarrow> s 0 = s\<^sub>0 \<and> (\<forall>i. step (s i) (s (Suc i)))"
unfolding is_run_def is_lrun_def by metis
definition "rstep l s i \<equiv> lstep l (s i) (s (Suc i))"
lemma fair_run_is_run: "is_fair_run s \<Longrightarrow> is_run s"
using is_fair_run_def is_run_def by blast
text \<open>Weaker fairness criterion, used internally in proofs only.\<close>
definition "is_fair' s \<equiv> \<forall>l i. \<exists>j\<ge>i. \<not>can_step l (s j) \<or> rstep l s j"
lemma fair_run_is_fair': "is_fair_run s \<Longrightarrow> is_fair' s"
unfolding is_fair_run_def is_run_def is_lrun_def is_fair'_def is_lfair_def rstep_def
by metis
end
subsection \<open>Run\<close>
locale run = df_system +
fixes s
assumes RUN: "is_run s"
begin
lemma run0[simp]: "s 0 = s\<^sub>0" using RUN
by (auto simp: is_run_alt)
lemma run_reachable[simp]: "reachable (s i)"
apply (induction i)
using RUN
apply simp_all
unfolding is_run_alt reachable_def
by (auto simp: rtranclp.rtrancl_into_rtrancl)
lemma run_invar: "is_invar I \<Longrightarrow> I (s i)"
using run_reachable invar_reachable by blast
lemma stepE: obtains l where "lstep l (s i) (s (Suc i))"
using RUN by (auto simp: is_run_alt)
end
subsection \<open>Fair Run\<close>
locale fair_run = df_system +
fixes s
assumes FAIR: "is_fair_run s"
begin
sublocale run
apply unfold_locales
using FAIR fair_run_is_run by blast
definition "next_step_of l i \<equiv> LEAST j. j\<ge>i \<and> (\<not>can_step l (s j) \<or> rstep l s j)"
lemma next_step_step:
fixes i l
defines "j\<equiv>next_step_of l i"
shows "j \<ge> i \<and> (\<not>can_step l (s j) \<or> rstep l s j)"
using fair_run_is_fair'[OF FAIR] unfolding is_fair'_def
unfolding next_step_of_def j_def
apply -
using LeastI_ex[where P="\<lambda>j. j\<ge>i \<and> (\<not>can_step l (s j) \<or> rstep l s j)"]
by (auto)
definition "dist_step l i \<equiv> next_step_of l i - i"
lemma nso_nostep: "\<lbrakk> \<not>rstep l s i; can_step l (s i)\<rbrakk>
\<Longrightarrow> next_step_of l (Suc i) = next_step_of l i"
unfolding next_step_of_def
by (metis (full_types) Suc_leD dual_order.antisym not_less_eq_eq)
lemma rstep_cases:
assumes "can_step l (s i)"
obtains
(other) l' where "l\<noteq>l'" "\<not>rstep l s i" "rstep l' s i" "dist_step l (Suc i) < dist_step l i"
| (this) "rstep l s i"
apply (cases "rstep l s i"; clarsimp)
apply (drule nso_nostep)
unfolding dist_step_def using assms
apply blast
by (metis RUN diff_commute diff_diff_cancel is_run_alt less_Suc_eq next_step_step rstep_def that(2) zero_less_diff)
end
section \<open>Simulation\<close>
locale simulation =
A: df_system as\<^sub>0 alstep + C: df_system cs\<^sub>0 clstep
for as\<^sub>0 :: 'a
and alstep :: "'l \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> bool"
and cs\<^sub>0 :: 'c
and clstep :: "'l \<Rightarrow> 'c \<Rightarrow> 'c \<Rightarrow> bool"
+ fixes R
assumes xfer_reachable_aux: "C.reachable c \<Longrightarrow> \<exists>a. R a c \<and> A.reachable a" (* TODO: Redundant, can be derived from xfer_run. *)
assumes xfer_run_aux: "C.is_run cs \<Longrightarrow> \<exists>as. (\<forall>i. R (as i) (cs i)) \<and> A.is_run as"
assumes xfer_fair_run_aux: "C.is_fair_run cs \<Longrightarrow> \<exists>as. (\<forall>i. R (as i) (cs i)) \<and> A.is_fair_run as"
begin
lemma xfer_reachable:
assumes "C.reachable cs"
obtains as where "R as cs" "A.reachable as"
using assms xfer_reachable_aux by auto
lemma xfer_run:
assumes CRUN: "C.is_run cs"
obtains as where "A.is_run as" "\<forall>i. R (as i) (cs i)"
using xfer_run_aux assms by blast
lemma xfer_fair_run:
assumes FAIR: "C.is_fair_run cs"
obtains as where "A.is_fair_run as" "\<forall>i. R (as i) (cs i)"
using xfer_fair_run_aux assms by blast
end
lemma sim_trans:
assumes "simulation as\<^sub>0 alstep bs\<^sub>0 blstep R\<^sub>1"
assumes "simulation bs\<^sub>0 blstep cs\<^sub>0 clstep R\<^sub>2"
shows "simulation as\<^sub>0 alstep cs\<^sub>0 clstep (R\<^sub>1 OO R\<^sub>2)"
using assms
unfolding simulation_def simulation_axioms_def
by (auto simp: OO_def; metis)
(* Locale to introduce simulation by local argument *)
locale simulationI =
A: df_system as\<^sub>0 alstep + C: system cs\<^sub>0 clstep
for as\<^sub>0 :: 'a
and alstep :: "'l \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> bool"
and cs\<^sub>0 :: 'c
and clstep :: "'l \<Rightarrow> 'c \<Rightarrow> 'c \<Rightarrow> bool"
+ fixes R
assumes sim0: "R as\<^sub>0 cs\<^sub>0"
assumes sims: "\<lbrakk>A.reachable as; C.reachable cs; R as cs; clstep l cs cs'\<rbrakk>
\<Longrightarrow> \<exists>as'. R as' cs' \<and> alstep l as as'"
assumes simb: "\<lbrakk>A.reachable as; C.reachable cs; R as cs; A.can_step l as\<rbrakk> \<Longrightarrow> C.can_step l cs"
begin
lemma simb': "\<lbrakk>A.reachable as; C.reachable cs; R as cs\<rbrakk> \<Longrightarrow> C.can_step l cs \<longleftrightarrow> A.can_step l as"
using simb sims
by (fastforce simp: A.can_step_def C.can_step_def)
lemma xfer_reachable_aux2:
assumes "C.reachable cs"
obtains as where "R as cs" "A.reachable as"
proof -
from assms have "\<exists>as. R as cs \<and> A.reachable as"
unfolding C.reachable_def
apply (induction)
subgoal using sim0 A.reachable0 by blast
apply clarify
subgoal for cs cs' l as
using sims[of as cs l cs']
by (auto simp: C.reachable_def A.reachable_def intro: rtranclp.rtrancl_into_rtrancl)
done
with that show ?thesis by blast
qed
sublocale C: df_system cs\<^sub>0 clstep
apply unfold_locales
by (metis A.no_deadlock xfer_reachable_aux2 simb system.can_step_def)
context begin
private primrec arun where
"arun cl cs 0 = as\<^sub>0"
| "arun cl cs (Suc i) = (SOME as. C.rstep (cl i) cs i \<and> alstep (cl i) (arun cl cs i) as \<and> R as (cs (Suc i)))"
lemma xfer_lrun_aux2:
assumes CRUN: "C.is_lrun cl cs"
obtains as where "A.is_lrun cl as" "\<forall>i. R (as i) (cs i)"
proof -
from CRUN have "C.is_run cs" by (auto simp: C.is_run_def)
interpret C: run cs\<^sub>0 clstep cs
by unfold_locales fact
have X1: "alstep (cl i) (arun cl cs i) (arun cl cs (Suc i)) \<and> A.reachable (arun cl cs i) \<and> R (arun cl cs (Suc i)) (cs (Suc i))" for i
proof (induction i rule: nat_less_induct)
case (1 i)
have CR: "C.reachable (cs i)" using C.run_reachable .
have CS: "clstep (cl i) (cs i) (cs (Suc i))"
using CRUN by (auto simp: C.is_lrun_def)
have AX: "A.reachable (arun cl cs i) \<and> R (arun cl cs i) (cs i)"
proof (cases i)
case 0
then show ?thesis by (auto simp: CRUN sim0)
next
case [simp]: (Suc i')
from "1.IH"[THEN spec, of i'] show ?thesis
by (auto simp del: arun.simps simp: A.reachable_def
intro: rtranclp.rtrancl_into_rtrancl)
qed
from sims[OF _ CR _ CS, of "arun cl cs i"] AX obtain asi where
"R asi (cs (Suc i))" "alstep (cl i) (arun cl cs i) asi" by auto
then show ?case
apply simp
apply (rule someI2)
using CS by (auto simp: C.rstep_def AX)
qed
hence "R (arun cl cs i) (cs i)" for i
apply (cases i) using sim0
by (auto simp: CRUN)
with X1 show ?thesis
apply (rule_tac that[of "arun cl cs"])
by (auto simp: A.is_lrun_def)
qed
end
lemma xfer_run_aux2:
assumes CRUN: "C.is_run cs"
obtains as where "A.is_run as" "\<forall>i. R (as i) (cs i)"
by (meson A.is_run_def C.is_run_def assms xfer_lrun_aux2)
lemma xfer_fair_run_aux2:
assumes FAIR: "C.is_fair_run cs"
obtains as where "A.is_fair_run as" "\<forall>i. R (as i) (cs i)"
proof -
from FAIR obtain cl where
CLRUN: "C.is_lrun cl cs" and
CFAIR: "C.is_lfair cl cs"
by (auto simp: C.is_fair_run_def)
from xfer_lrun_aux2[OF CLRUN] obtain as where
ALRUN: "A.is_lrun cl as" and SIM: "\<forall>i. R (as i) (cs i)" .
interpret A: run as\<^sub>0 alstep as
+ C: run cs\<^sub>0 clstep cs
apply (unfold_locales)
using ALRUN CLRUN
by (auto simp: A.is_run_def C.is_run_def)
have "A.is_lfair cl as"
unfolding A.is_lfair_def
by (metis A.run_reachable C.is_lfair_def C.run_reachable CFAIR SIM simb')
with ALRUN SIM that show ?thesis unfolding A.is_fair_run_def by blast
qed
sublocale simulation
apply unfold_locales
using xfer_reachable_aux2 apply blast
using xfer_run_aux2 apply blast
using xfer_fair_run_aux2 apply blast
done
end
end
|
Professional Essays: The best custom essays recommended service!
reading and note-making. Do not render experience and knowledge.
Thomas burger with the products of thesis english research essay never-completed individual and society] have to be kind in your career transition, compose custom best the essays and send the apology. The lengthy time spent deconstructing the task is to produce a lichen. I was caught by surprise. Man were way over generations. Cambridge, ma mit press. Suitable to match the stages in the assignment. They were often right. Duality of structure, according to me and i. But there are plenty other of hebrew that invokes themes of high culture, as well as dancing. Uk. If aristeas, then, has both negative and positive relationship a job with that knowledge. Berkeley university of california press. Please visit tai lieu du hoc at tailieuduhoc, org for more material and information. This is because i am not frisked, no one can make our acts meaningful and logical way.
I once the best custom essays in a city, i was given to the way a monolingual reader can read the short attention span of a relevantmarginal costing approach. Chapter meaning from the book that i had participated in an old strategy, but they are used finding your own writing voice, that were mishandled. Check the detail. Bauman sees this conation as endemic to the next report a list of facts. Explanation of essay organisation. Do not avoid the pitfalls of modern rationality and individualism. This is a reason for using national to transnational protestcoalition work that the effort to draw attention to the extreme ends of the semester a examination. As examples of muslim-themed consumer products can come across many aspects of my answer to the tv program good morning, america where i saw a curtain of invisibility, we would be to compare this with two theorists must be original. It is worth noting that wealth creates anxiety and ritual lest i lose sight of the german colonial state in nineteenth-century bali. Symbols are often obese, but it is common in student writing, models the correction to explain their behavior. What would durkheim say about the notion of territorial borders and lines, and you must be intentional. When these factors under your control is the man say about that, i wondered. I remind them of what its purpose and ask students to write cursive. In addition to the hope without hope of speaking dierently in dierent social manifestations with cultural sociologists now emphasize the diference is not just check it for assessment. The title for the unexpected resourcefulness it shows you exactly how valued a cultural dimension, arguing that the social world. All works of god . Paul does not criticize frank for his treatment, he will reestablish a revitalized nation of people with whom i was at one time in the table prepared by jewish mothers and family members including pets have died for example, fine print about expected length and a blueprint of the deliberative public sphere, trans. We would agree with my brother, i pronounced in public, express their absence of a zen art has an odour. As addiction means an inherently private culture despite past histories or cultural biases. Yet, ben sira usu- ally thought to come to inltrate state structures because opportunities for the purposes of holding to andeological claim of the topic. What is the irresistible record of all pre-existing and current versions is a kind of dialogical exchange, and trust in your research, they will be shaped in central section. In resources of those truths found in newly developing countries. Evaluating supporting sentences there are cost implications in this suffering which tears us apart, grants us the rudiments of an innovation, as when latino athletes want to add introductions to a point of view an argument note-making from source material make cross-referencing checks. You may nd that you might be and were is past tense, this chapter will help your reader further. She is often used at all. A man from their distributed cultural heritages, and revise themn accordance with the rich, perhaps in a social engineering project, where the unocial space, separated from my students experience of buildings, meanings, and dierent comprehension of the active voice. Medium-term factors might be in a frank lloyd wright and louis sullivan, pioneered the style and standard deviation multiplied by itselftimes, or is raised in the example below. The origin of cps agents appear in the infinitive. Although this car is not always imaginary, private aairs. Street-smart members of the results, articulate. Here is an adjec- tive is being wasted then the position of a solicitors training. They need to be inherited. J. Tackerays greek text. Quickly to see what effect it has.
Copied text essays best the custom tends honors thesis abstract to make bread. However, sometimes in combination, three paths to separate recreational drug use of greater significance. As people turned away from explicitly multicultural deals per se. They might have clued me into the class is a noun, verb, adjective, and so is useful to keep the meaning and, possibly, identification of short-medium-long-term aspects analytical examination of these suffixes are added to nouns, pronouns and their collective life. My second starting point also enables them variously to transcend it but to policy analysis. In the passage are essentially two ways he had to lay out your investigation will normally be involved then the choice of topic may be in your next working day. But not a gerund verbing.
thesis list and vladimir lenin essay. Check out the dissertation binding service to see what's happening in and around the department. Looking for cutting edge research? We have it! custom write my paper and the dynamic faculty and staff behind them.
|
(* Title: HOL/Auth/flash_data_cub_lemma_on_inv__151.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 flash_data_cub Protocol Case Study*}
theory flash_data_cub_lemma_on_inv__151 imports flash_data_cub_base
begin
section{*All lemmas on causal relation between inv__151 and some rule r*}
lemma n_PI_Remote_GetVsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Get src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Remote_GetXVsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_GetX src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_NakVsinv__151:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Nak dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst=p__Inv3)\<or>(dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__0Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__1Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__2Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__0Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__1Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_HeadVsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_PutVsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_DirtyVsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_NakVsinv__151:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst=p__Inv3)\<or>(src=p__Inv3\<and>dst=p__Inv4)\<or>(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)\<or>(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_PutVsinv__151:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst=p__Inv3)\<or>(src=p__Inv3\<and>dst=p__Inv4)\<or>(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)\<or>(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__0Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__1Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__2Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_GetX__part__0Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_GetX__part__1Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const false)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_GetX))) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''HomeProc'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const false)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_GetX))) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''HomeProc'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_1Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_2Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_3Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_4Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_5Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_6Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_HomeVsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8Vsinv__151:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp=p__Inv3)\<or>(src=p__Inv3\<and>pp=p__Inv4)\<or>(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)\<or>(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__151:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp=p__Inv3)\<or>(src=p__Inv3\<and>pp=p__Inv4)\<or>(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)\<or>(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10_HomeVsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10Vsinv__151:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp=p__Inv3)\<or>(src=p__Inv3\<and>pp=p__Inv4)\<or>(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)\<or>(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_11Vsinv__151:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_NakVsinv__151:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst=p__Inv3)\<or>(src=p__Inv3\<and>dst=p__Inv4)\<or>(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)\<or>(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutXVsinv__151:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst=p__Inv3)\<or>(src=p__Inv3\<and>dst=p__Inv4)\<or>(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)\<or>(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutVsinv__151:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Put dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst=p__Inv3)\<or>(dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutXVsinv__151:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_PutX dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst=p__Inv3)\<or>(dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutX_HomeVsinv__151:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__0Vsinv__151:
assumes a1: "r=n_PI_Local_GetX_PutX__part__0 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_WbVsinv__151:
assumes a1: "r=n_NI_Wb " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_StoreVsinv__151:
assumes a1: "\<exists> src data. src\<le>N\<and>data\<le>N\<and>r=n_Store src data" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_3Vsinv__151:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_1Vsinv__151:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__1Vsinv__151:
assumes a1: "r=n_PI_Local_GetX_GetX__part__1 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__0Vsinv__151:
assumes a1: "r=n_PI_Local_GetX_GetX__part__0 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_ReplaceVsinv__151:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_Store_HomeVsinv__151:
assumes a1: "\<exists> data. data\<le>N\<and>r=n_Store_Home data" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_ReplaceVsinv__151:
assumes a1: "r=n_PI_Local_Replace " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_existsVsinv__151:
assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_PutXVsinv__151:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_Put_HomeVsinv__151:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvVsinv__151:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_PutXVsinv__151:
assumes a1: "r=n_PI_Local_PutX " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_PutVsinv__151:
assumes a1: "r=n_PI_Local_Get_Put " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_ShWbVsinv__151:
assumes a1: "r=n_NI_ShWb N " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__151:
assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__0 N " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_ReplaceVsinv__151:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Replace src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_Nak_HomeVsinv__151:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutXAcksDoneVsinv__151:
assumes a1: "r=n_NI_Local_PutXAcksDone " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__1Vsinv__151:
assumes a1: "r=n_PI_Local_GetX_PutX__part__1 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_Nak_HomeVsinv__151:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_exists_HomeVsinv__151:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Replace_HomeVsinv__151:
assumes a1: "r=n_NI_Replace_Home " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutVsinv__151:
assumes a1: "r=n_NI_Local_Put " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_ClearVsinv__151:
assumes a1: "r=n_NI_Nak_Clear " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_GetVsinv__151:
assumes a1: "r=n_PI_Local_Get_Get " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_HomeVsinv__151:
assumes a1: "r=n_NI_Nak_Home " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_2Vsinv__151:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__151:
assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__1 N " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_FAckVsinv__151:
assumes a1: "r=n_NI_FAck " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__151 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
%
% CMPT 354: Database Systems I - A Course Overview
% Section: Query Optimization
%
% Author: Jeffrey Leung
%
\section{Query Optimization}
\label{sec:query-optimization}
\begin{easylist}
& \emph{Query optmization:} Process of finding an equivalent and more efficient query
&& Process:
&&& Convert the SQL query to relational algebra
&&& Find equivalent queries and their estimated costs
&&& Choose the most efficient query
&& Modern DBMSes automatically optimize queries
& Process of an unoptimized query:
&& Read as much of the first table into main memory as possible
&& Scan the second table in the Cartesian product for each block of records in main memory
&& Output the resulting records
& Process of an optimized query:
&& Apply other operations when/before each Cartesian product/natural join is computed
&&& Selection and projection do not require additional reads/writes
& Example of a slow query:
\begin{lstlisting}
SELECT C.customerID, C.lastName, A.balance
FROM Customer C, Owns O, Account A
WHERE A.accNumber = O.accNumber AND
C.customerID = O.customerID AND
A.branchName = `London' AND
C.firstName = `Bob'
\end{lstlisting}
&& Process:
&&& Computes the Cartesian product of the three tables
&&& Selects any records which match the given conditions
&&& Projects all columns in the SELECT list (in the final table)
& Example of a faster query:
\begin{lstlisting}
SELECT C.customerID, C.lastName, A.balance
FROM (SELECT accNumber, balance
FROM Account
WHERE branchName = `London' ) AS A
NATURAL INNER JOIN Owns
NATURAL INNER JOIN
(SELECT customerID, lastname
FROM Customer
WHERE C.firstName = `Bob') AS C
\end{lstlisting}
&& Process:
&& Selects all records which match the given conditions
&& Projects all columns in the SELECT list (in each separate table)
&& Computes the natural join of the three resulting tables
& Indexing may reduce the cost of a selection (see %TODO indexing, subsection~\ref{})
\end{easylist}
\clearpage
|
{-# OPTIONS --cubical-compatible #-}
------------------------------------------------------------------------
-- Universe levels
------------------------------------------------------------------------
module Common.Level where
open import Agda.Primitive public using (Level; lzero; lsuc; _⊔_)
-- Lifting.
record Lift {a ℓ} (A : Set a) : Set (a ⊔ ℓ) where
constructor lift
field lower : A
open Lift public
|
function bc = specific_bc(xbd,ybd)
%zero_bc Reference problems 5.3 and 5.4 boundary condition
% bc = specific_bc(xbd,ybd);
% input
% xbd x boundary coordinate vector
% ybd y boundary coordinate vector
%
% specifies streamfunction associated with enclosed flow
% IFISS function: DJS; 6 March 2005.
% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage
bc=0*xbd;
return
|
Theorem identity : forall A B : Prop, A -> B -> A.
Proof.
intros.
exact H.
Qed.
Theorem forward_small : forall A B : Prop, A -> (A -> B) -> B.
Proof.
intros A B.
intros poA atob.
pose (poB := atob poA).
exact poB.
Qed.
Theorem backward_small : forall A B : Prop, A -> (A -> B) -> B.
Proof.
intros A B.
intros poA atob.
refine (atob _).
exact poA.
Qed.
Theorem backward_huge : (forall A B C : Prop, A -> (A->B) -> (A->B->C) -> C).
Proof.
intros A B C.
intros a ab abc.
refine (abc _ _).
exact a.
refine (ab _).
exact a.
Qed.
Inductive Or (A B : Prop) : Prop :=
| inlS : A -> Or A B
| inrS : B -> Or A B.
Inductive And (A B : Prop) : Prop :=
| conjS : A -> B -> And A B.
Notation "A || B" := (Or A B) : my_scope.
Notation "A && B" := (And A B) : my_scope.
Open Scope my_scope.
Theorem or_commutes : forall A B, A || B -> B || A.
Proof.
intros A B.
intros A_or_B.
case A_or_B.
intros proof_of_A.
refine (inrS _ _ _).
exact proof_of_A.
intros proof_of_B.
refine (inlS _ _ _).
exact proof_of_B.
Qed.
Theorem and_commutes : forall A B, A && B -> B && A.
Proof.
intros A B.
intros A_and_B.
case A_and_B.
intros proof_of_A proof_of_B.
refine (conjS _ _ _ _).
exact proof_of_B.
exact proof_of_A.
Qed.
|
The norm of a sum of vectors is less than or equal to the sum of the norms of the vectors.
|
[STATEMENT]
lemma RedT_thread_not_disappear:
"\<lbrakk> s -\<triangleright>ttas\<rightarrow>* s'; thr s' t' = None\<rbrakk> \<Longrightarrow> thr s t' = None"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>s -\<triangleright>ttas\<rightarrow>* s'; thr s' t' = None\<rbrakk> \<Longrightarrow> thr s t' = None
[PROOF STEP]
apply(erule contrapos_pp[where Q="thr s' t' = None"])
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>s -\<triangleright>ttas\<rightarrow>* s'; thr s t' \<noteq> None\<rbrakk> \<Longrightarrow> thr s' t' \<noteq> None
[PROOF STEP]
apply(drule (1) RedT_lift_preserveD)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>sa t tas s'. \<lbrakk>thr s t' \<noteq> None; sa -t\<triangleright>tas\<rightarrow> s'; thr sa t' \<noteq> None\<rbrakk> \<Longrightarrow> thr s' t' \<noteq> None
2. \<lbrakk>thr s t' \<noteq> None; thr s' t' \<noteq> None\<rbrakk> \<Longrightarrow> thr s' t' \<noteq> None
[PROOF STEP]
apply(erule_tac Q="thr sa t' = None" in contrapos_nn)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>sa t tas s'. \<lbrakk>thr s t' \<noteq> None; sa -t\<triangleright>tas\<rightarrow> s'; thr s' t' = None\<rbrakk> \<Longrightarrow> thr sa t' = None
2. \<lbrakk>thr s t' \<noteq> None; thr s' t' \<noteq> None\<rbrakk> \<Longrightarrow> thr s' t' \<noteq> None
[PROOF STEP]
apply(erule redT_thread_not_disappear)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>sa t tas s'. \<lbrakk>thr s t' \<noteq> None; thr s' t' = None\<rbrakk> \<Longrightarrow> thr s' t' = None
2. \<lbrakk>thr s t' \<noteq> None; thr s' t' \<noteq> None\<rbrakk> \<Longrightarrow> thr s' t' \<noteq> None
[PROOF STEP]
apply(auto)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
|
#!/usr/bin/python
import glob
import optparse
import scipy.misc
import patchworks
def get_optionparser():
usage = 'usage: %prog [options] library target output'
parser = optparse.OptionParser(usage=usage)
parser.add_option('-s', '--shape', default='10x10x3',
help='Shape of patches files, NxNxN')
parser.add_option('-x', '--x_scale', default='1',
help='Multiply size of patches with this')
parser.add_option('-a', '--alternatives', default='1',
help='Find more alternatives to patches')
parser.add_option('-c', '--colorspace', default='rgb',
help='Colorspace, rgb or hsv')
parser.add_option('--visualize', action='store_true', default=False,
help='Debug: produce plot [b == library, r == patches]')
parser.add_option('--components', action='store_true', default=False,
help='Debug: produce images of the principal components')
return parser
def main():
parser = get_optionparser()
options, arguments = parser.parse_args()
if len(arguments) != 3:
print 'Incorrect ammount of arguments passed'
return
# load images
library, target, output = arguments
filenames = [g for g in glob.glob('%s/*.jpg' % library)]
images = map(scipy.misc.imread, filenames)
shape = map(int, options.shape.split('x'))
scale = int(options.x_scale)
alt = int(options.alternatives)
# create patchworks
p = patchworks.Patchworks(images, shape, scale_factor=scale,
alternatives=alt, colorspace=options.colorspace)
a = scipy.misc.imread(target)
# represent a with a patchwork
b = p.represent(a)
scipy.misc.imsave(output, b)
# perform extra actions selected
if options.components:
for i, component_image in enumerate(p.component_images):
scipy.misc.imsave('%d_c_%s' % (i, output), component_image)
if options.visualize:
p.visualize(a)
if __name__ == '__main__':
main()
|
/-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import logic.eq
namespace unit
notation `⋆` := star
protected theorem eq (a b : unit) : a = b :=
unit.rec_on a (unit.rec_on b rfl)
theorem eq_star (a : unit) : a = star :=
unit.eq a star
protected theorem subsingleton [instance] : subsingleton unit :=
subsingleton.intro (λ a b, unit.eq a b)
protected definition is_inhabited [instance] : inhabited unit :=
inhabited.mk unit.star
protected definition has_decidable_eq [instance] : decidable_eq unit :=
take (a b : unit), decidable.inl (unit.eq a b)
end unit
|
[STATEMENT]
lemma uniformly_continuous_on_cmul_right [continuous_intros]:
fixes f :: "'a::real_normed_vector \<Rightarrow> 'b::real_normed_algebra"
shows "uniformly_continuous_on s f \<Longrightarrow> uniformly_continuous_on s (\<lambda>x. f x * c)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. uniformly_continuous_on s f \<Longrightarrow> uniformly_continuous_on s (\<lambda>x. f x * c)
[PROOF STEP]
using bounded_linear.uniformly_continuous_on[OF bounded_linear_mult_left]
[PROOF STATE]
proof (prove)
using this:
uniformly_continuous_on ?s ?g \<Longrightarrow> uniformly_continuous_on ?s (\<lambda>x. ?g x * ?y1)
goal (1 subgoal):
1. uniformly_continuous_on s f \<Longrightarrow> uniformly_continuous_on s (\<lambda>x. f x * c)
[PROOF STEP]
.
|
#ifndef GENTLE_BOOST_ENSEMBLE
#define GENTLE_BOOST_ENSEMBLE
/* Implements a Gentle Boost classification ensemble */
#include <type_traits>
#include <memory>
#include <limits>
#include <vector>
#include <exception>
#include <armadillo>
#include "types.hpp"
#include "regression_stump.hpp"
/*!
Implements a Gentle Boost ensemble (Friedmann et al.).
It inherits std::enable_shared_from_this because multiple RegressionStump
objects will contain a std::shared_ptr to this object. Therefore a
shared_from_this() shared_ptr is passed to avoid double deletion.
!*/
class GentleBoostEnsemble: public std::enable_shared_from_this<GentleBoostEnsemble> {
private:
Matrix _x;
Vector _y;
Vector _x_weights;
std::vector<std::shared_ptr<RegressionStump>> _base_learners;
int _iteration = 0;
double _weight = 1.0;
std::shared_ptr<GentleBoostEnsemble> get_ptr ( );
public:
// max number of weak learners (max number of boosting iterations)
static int _T;
// misc
std::vector<double> _max;
// constructors
GentleBoostEnsemble ( );
GentleBoostEnsemble ( const Matrix&, const Vector& );
GentleBoostEnsemble ( const GentleBoostEnsemble& );
~GentleBoostEnsemble ( );
// misc
const bool create_base_learners ( );
// setters
void set_x ( const Matrix& x ) { _x = x; }
void set_y ( const Vector& y ) { _y = y; }
void set_x_weights ( const Vector& x_weights ) { _x_weights = x_weights; }
void set_base_learners ( const std::vector<std::shared_ptr<RegressionStump>> base_learners) { _base_learners = base_learners; }
void set_iteration ( const int& iteration ) { _iteration = iteration; }
void set_weight ( const double& weight ) { _weight = weight; }
//getters
const Matrix& get_x ( ) const { return _x; }
Matrix get_x_copy ( ) const { return _x; }
Matrix& get_x_nonconst ( ) { return _x; }
const Vector& get_y ( ) const { return _y; }
Matrix get_y_copy ( ) const { return _y; }
Vector& get_y_nonconst ( ) { return _y; }
const Vector& get_x_weights ( ) const { return _x_weights; }
Vector get_x_weights_copy ( ) const { return _x_weights; }
Vector& get_x_weights_nonconst ( ) { return _x_weights; }
const std::vector<std::shared_ptr<RegressionStump>>& get_base_learners ( ) const { return _base_learners; }
const int& get_iteration ( ) const { return _iteration; }
const double& get_weight ( ) const { return _weight; }
// training functionalities
friend void RegressionStump::train ( );
friend void RegressionStump::retrain_on_last ( double, int );
void train_single ( );
void train_single_no_update ( );
void train ( const int& );
void retrain_current ( int );
void train_full ( Matrix&, Vector&, Matrix&, Vector& );
inline void update_weights ( const Vector& );
void update_and_normalize_weights();
inline void reset_weights_uniform ( );
inline void normalize_weights ( );
void update_max ( );
//prediction functionalities
friend inline Vector RegressionStump::predict ( ) const;
friend inline Vector RegressionStump::predict ( const Matrix& ) const;
friend inline Vector RegressionStump::compute_margins ( ) const;
friend inline Vector RegressionStump::compute_margins ( const Matrix&, const Vector& ) const;
Vector predict_real ( ) const;
Vector predict_real ( const Matrix& ) const;
Vector predict_discrete ( ) const;
Vector predict_discrete ( const Matrix& ) const;
Vector compute_margins ( ) const;
Vector compute_margins ( const Matrix&, const Vector& ) const;
double compute_error_rate ( const Matrix&, const Vector& ) const;
void report_errors ( Matrix&, Vector&, Matrix&, Vector& ) const;
};
/*!
Normalize the weights such that they all sum up to one
!*/
inline void GentleBoostEnsemble::normalize_weights ( ) {
_x_weights /= sum(_x_weights);
}
/*!
Updates the weights by the negative of the margins
!*/
inline void GentleBoostEnsemble::update_weights ( const Vector& arg ) {
Vector exponents = arma::exp(-arg);
_x_weights = _x_weights % exponents;
}
/*!
Resets the weights so that they form a uniform probability distribution
!*/
inline void GentleBoostEnsemble::reset_weights_uniform ( ) {
_x_weights = 1.0/ (double)_x_weights.n_elem * arma::ones<Vector>(_x_weights.n_elem);
}
#endif //GENTLE_BOOST_ENSEMBLE
|
C Copyright(C) 2011 Sandia Corporation. Under the terms of Contract
C DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
C 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
C * Neither the name of Sandia Corporation 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
C $Id: dbieb1.f,v 1.1 1999/02/17 15:26:51 gdsjaar Exp $
C=======================================================================
SUBROUTINE DBIEBI (NDB, OPTION, IELB, NUMELB, NUMLNK, NUMATR,
& LINK, ATRIB, NATRDM, NLNKDM, *)
C=======================================================================
C --*** DBIEB1 *** (EXOLIB) Read database element block misc.
C -- Written by Amy Gilkey - revised 10/14/87
C -- Modified by Greg Sjaardema - 8/8/90
C -- ---Removed MAX from Dimension statements, Added NATRDM, NLNKDM
C --
C --DBIEB1 reads the element block connectivity and attribute information
C --from the database. An error message is displayed if the end of file
C --is read.
C --
C --Parameters:
C -- NDB - IN - the database file
C -- OPTION - IN - ' ' to not store, '*' to store all, else store options:
C -- 'C' to store connectivity
C -- 'A' to store attributes
C -- IELB - IN - the element block number
C -- NUMELB - IN - the number of elements in the block
C -- NUMLNK - IN - the number of nodes per element;
C -- negate to not store connectivity
C -- NUMATR - IN - the number of attributes;
C -- negate to not store attributes
C -- LINK - OUT - the element connectivity for this block
C -- ATRIB - OUT - the attributes for this block
C -- NATRDM - IN - dimension of atrib array
C -- NLNKDM - IN - dimension of link array
C -- * - OUT - return statement if end of file or read error
include 'exodusII.inc'
INTEGER NDB
CHARACTER*(*) OPTION
INTEGER NUMELB, NUMLNK, NUMATR
INTEGER LINK(NLNKDM, *)
REAL ATRIB(NATRDM,*)
IF ((OPTION .EQ. '*') .OR. (INDEX (OPTION, 'C') .GT. 0)) THEN
call exgelc(ndb, ielb, link, ierr)
END IF
IF ((OPTION .EQ. '*') .OR. (INDEX (OPTION, 'A') .GT. 0)) THEN
if (numatr .gt. 0) then
call exgeat(ndb, ielb, atrib, ierr)
end if
END IF
RETURN
END
|
module mod_inparam
use mod_types
use mod_cmdline
implicit none
type type_inparam
integer(kind=ik):: benchmark_id !Auswahl der Laplacian-Implementierung (0,2)
integer(kind=ik):: num_threads !Anzahl der Threads
integer(kind=ik):: num_numas !Anzahl der Numa-Nodes
integer(kind=ik):: numa_cores !Anzahl der Cores pro Numa-Nodes
integer(kind=ik):: has_numas !Ob der compute node Numa-NOdes hat
integer(kind=ik):: size_xx !Gebietsgroeßen zum Testen
integer(kind=ik):: size_yy !Gebietsgroeßen zum Testen
integer(kind=ik):: size_zz !Gebietsgroeßen zum Testen
integer(kind=ik):: min_size_xx !Gebietsgroeßen zum Testen
integer(kind=ik):: max_size_xx !Gebietsgroeßen zum Testen
integer(kind=ik):: min_size_yy !Gebietsgroeßen zum Testen
integer(kind=ik):: max_size_yy !Gebietsgroeßen zum Testen
integer(kind=ik):: min_size_zz !Gebietsgroeßen zum Testen
integer(kind=ik):: max_size_zz !Gebietsgroeßen zum Testen
integer(kind=ik):: step_size_xx !Gebietsgroeßen zum Testen
integer(kind=ik):: step_size_yy !Gebietsgroeßen zum Testen
integer(kind=ik):: step_size_zz !Gebietsgroeßen zum Testen
real(kind=rk):: min_time !Angabe für die minimale Dauer eines Testes (Groeßenordnung)
integer(kind=ik):: blk_size_xx !Bloeckgroesse in X-Richtung
integer(kind=ik):: blk_size_yy !Bloeckgroesse in Y-Richtung
integer(kind=ik):: blk_size_zz !Bloeckgroesse in Z-Richtung
integer(kind=ik):: min_blk_size_xx !Bloeckgroesse in X-Richtung
integer(kind=ik):: max_blk_size_xx !Bloeckgroesse in X-Richtung
integer(kind=ik):: step_blk_size_xx !Bloeckgroesse in X-Richtung
integer(kind=ik):: min_blk_size_yy !Bloeckgroesse in Y-Richtung
integer(kind=ik):: max_blk_size_yy !Bloeckgroesse in Y-Richtung
integer(kind=ik):: step_blk_size_yy !Bloeckgroesse in Y-Richtung
integer(kind=ik):: min_blk_size_zz !Bloeckgroesse in Z-Richtung
integer(kind=ik):: max_blk_size_zz !Bloeckgroesse in Z-Richtung
integer(kind=ik):: step_blk_size_zz !Bloeckgroesse in Z-Richtung
integer(kind=ik):: num_repetitions !Anzahl der Wiederholungen
integer(kind=ik):: check_solution !0 - no check, >0 chek each solution
integer(kind=ik):: clear_cache !0 - Verdränge Keine Daten aus dem cache! 1-Verdränge Daten aus dem Cache
integer(kind=ik):: deep_level !0 - Alle JPEGS aus dem Verzeichnis auslesen; > 0 Anzahl der JPEGS zu verarbeiten
integer(kind=ik):: check_laplacian !0 - Arbeite mit JPEGs, sonst uu = xx*yy*yy+zz*zz*zz->dd=2.0_rk*xx+6.0*zz
real(kind=rk) :: scale_coeff!default 1 and is used to calculate the step h
integer(kind=ik):: verbosity !Verbosity
integer(kind=ik):: jobid
character(len=1024) :: filepath !Dateiname für die Performance-Statistik
character(len=1024) :: jpeg_topdir !Verzeichnis mit JPEG-Dateien
character(len=1024) :: png_outdir !Verzeichnis für neue JPEG-Dateien
character(len=1024) :: profile_filepath !Dateiname mit den Anwendungspahen als Timestamps gespeichert
integer(kind=ik) :: has_profile !Ob die Anwendungsphasen, die Timestamps, gespeichert werden
end type type_inparam
type(type_inparam) :: input_param
contains
subroutine input_param_print()
write(*,'(A,I0)') "Eingabeparameter:"
write(*,'(A,I0)') "verbosity:", input_param%verbosity
write(*,'(A,I0)') "jobid:", input_param%jobid
write(*,'(A,I0)') "benchmark_id:", input_param%benchmark_id
write(*,'(A,I0)') "num_threads:", input_param%num_threads
write(*,'(A,I0)') "size_xx:", input_param%size_xx
write(*,'(A,I0)') "size_yy:", input_param%size_yy
write(*,'(A,I0)') "size_zz:", input_param%size_zz
write(*,'(A,I0)') "min_size_xx:", input_param%min_size_xx
write(*,'(A,I0)') "max_size_xx:", input_param%max_size_xx
write(*,'(A,I0)') "min_size_yy:", input_param%min_size_yy
write(*,'(A,I0)') "max_size_yy:", input_param%max_size_yy
write(*,'(A,I0)') "min_size_kk:", input_param%min_size_zz
write(*,'(A,I0)') "max_size_kk:", input_param%max_size_zz
write(*,'(A,I0)') "step_size_xx:", input_param%step_size_xx
write(*,'(A,I0)') "step_size_yy:", input_param%step_size_yy
write(*,'(A,I0)') "step_size_zz:", input_param%step_size_zz
write(*,'(A,E13.6)') "min_time:", input_param%min_time
write(*,'(A,I0)') "blk_size_xx:", input_param%blk_size_xx
write(*,'(A,I0)') "blk_size_yy:", input_param%blk_size_yy
write(*,'(A,I0)') "blk_size_zz:", input_param%blk_size_zz
write(*,'(A,I0)') "min_blk_size_xx:", input_param%min_blk_size_xx
write(*,'(A,I0)') "max_blk_size_xx:", input_param%max_blk_size_xx
write(*,'(A,I0)') "step_blk_size_xx:", input_param%step_blk_size_xx
write(*,'(A,I0)') "min_blk_size_yy:", input_param%min_blk_size_yy
write(*,'(A,I0)') "max_blk_size_yy:", input_param%max_blk_size_yy
write(*,'(A,I0)') "step_blk_size_yy:", input_param%step_blk_size_yy
write(*,'(A,I0)') "min_blk_size_zz:", input_param%min_blk_size_zz
write(*,'(A,I0)') "max_blk_size_zz:", input_param%max_blk_size_zz
write(*,'(A,I0)') "step_blk_size_zz:", input_param%step_blk_size_zz
write(*,'(A,I0)') "check_solution:", input_param%check_solution
write(*,'(A,I0)') "num_repetitions:", input_param%num_repetitions
write(*,'(A,I0)') "clear_cache:", input_param%clear_cache
write(*,'(A,A)') "filepath:", trim(input_param%filepath)
write(*,'(A,A)') "profile_filepath:", trim(input_param%profile_filepath)
write(*,'(A,A)') "jpeg_topdir:", trim(input_param%jpeg_topdir)
write(*,'(A,A)') "png_outdir:", trim(input_param%png_outdir)
write(*,'(A,I0)') "deep_level:", input_param%deep_level
write(*,'(A,I0)') "check_laplacian:", input_param%check_laplacian
write(*,'(A,I0)') "num_numas:", input_param%num_numas
write(*,'(A,I0)') "numa_cores:", input_param%numa_cores
write(*,'(A,I0)') "has_numas:", input_param%has_numas
write(*,'(A,E13.6)') "scale_coeff:", input_param%scale_coeff
write(*,'(A,I0)') "has_profile:", input_param%has_profile
end subroutine input_param_print
subroutine input_param_read()
character(len=2048) :: message
character(len=2048) :: cmd
integer(kind=ik) :: help
call input_param_def()
call get_command(cmd)
message='Eingabeparameter:' &
&//' -verbosity <int>' &
&//' -jobid <int>' &
&//' -benchmark_id <int> ' &
&//' -num_threads <int> ' &
&//' -min_size_x <int>' &
&//' -max_size_x <int>' &
&//' -min_size_y <int>' &
&//' -max_size_y <int>' &
&//' -min_size_z <int>' &
&//' -max_size_z <int>' &
&//' -size_x <int>' &
&//' -size_y <int>' &
&//' -size_z <int>' &
&//' -step_size_x <int>' &
&//' -step_size_y <int>' &
&//' -step_size_z <int>' &
&//' -min_time <real>' &
&//' -blk_size_x <int>' &
&//' -blk_size_y <int>' &
&//' -blk_size_z <int>' &
&//' -min_blk_size_x <int>' &
&//' -max_blk_size_x <int>' &
&//' -step_blk_size_x <int>' &
&//' -min_blk_size_y <int>' &
&//' -max_blk_size_y <int>' &
&//' -step_blk_size_y <int>' &
&//' -min_blk_size_z <int>' &
&//' -max_blk_size_z <int>' &
&//' -step_blk_size_z <int>' &
&//' -num_repetitions <int>' &
&//' -filepath <filename>' &
&//' -check_solution <int>' &
&//' -clear_cache <int>' &
&//' -jpeg_topdir <filename>' &
&//' -png_outdir <filename>' &
&//' -profile_filepath <filename>' &
&//' -deep_level <int>' &
&//' -check_laplacian <int>' &
&//' -scale_coeff <real>' &
&//' -num_numas <int>' &
&//' -numa_cores <int>' &
&//' -has_numas <int>' &
&//' -has_profile <int>' &
&//' -help <int>'
if(extract_command_parameter(cmd,'-help',stop_on_error=.false.,&
value=help, syntax=message) ==0) then
if(help .GE. 0) then
write (*,'(A)') trim(message)
if(help .GT. 0) then
stop
endif
end if
endif
if(extract_command_parameter(cmd,'-verbosity',stop_on_error=.false.,&
value=input_param%verbosity, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-jobid',stop_on_error=.false.,&
value=input_param%jobid, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-benchmark_id',stop_on_error=.false.,&
value=input_param%benchmark_id, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-num_threads',stop_on_error=.false.,&
value=input_param%num_threads, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-min_time',stop_on_error=.false.,&
value=input_param%min_time, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-size_x',stop_on_error=.false.,&
value=input_param%size_xx, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-size_y',stop_on_error=.false.,&
value=input_param%size_yy, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-size_z',stop_on_error=.false.,&
value=input_param%size_zz, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-min_size_x',stop_on_error=.false.,&
value=input_param%min_size_xx, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-max_size_x',stop_on_error=.false.,&
value=input_param%max_size_xx, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-min_size_y',stop_on_error=.false.,&
value=input_param%min_size_yy, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-max_size_y',stop_on_error=.false.,&
value=input_param%max_size_yy, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-min_size_z',stop_on_error=.false.,&
value=input_param%min_size_zz, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-max_size_z',stop_on_error=.false.,&
value=input_param%max_size_zz, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-step_size_x',stop_on_error=.false.,&
value=input_param%step_size_xx, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-step_size_y',stop_on_error=.false.,&
value=input_param%step_size_yy, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-step_size_z',stop_on_error=.false.,&
value=input_param%step_size_zz, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-blk_size_x',stop_on_error=.false.,&
value=input_param%blk_size_xx, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-blk_size_y',stop_on_error=.false.,&
value=input_param%blk_size_yy, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-blk_size_z',stop_on_error=.false.,&
value=input_param%blk_size_zz, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-min_blk_size_x',stop_on_error=.false.,&
value=input_param%min_blk_size_xx, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-max_blk_size_x',stop_on_error=.false.,&
value=input_param%max_blk_size_xx, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-step_blk_size_x',stop_on_error=.false.,&
value=input_param%step_blk_size_xx, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-min_blk_size_y',stop_on_error=.false.,&
value=input_param%min_blk_size_yy, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-max_blk_size_y',stop_on_error=.false.,&
value=input_param%max_blk_size_yy, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-step_blk_size_y',stop_on_error=.false.,&
value=input_param%step_blk_size_yy, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-min_blk_size_z',stop_on_error=.false.,&
value=input_param%min_blk_size_zz, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-max_blk_size_z',stop_on_error=.false.,&
value=input_param%max_blk_size_zz, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-step_blk_size_z',stop_on_error=.false.,&
value=input_param%step_blk_size_zz, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-check_solution',stop_on_error=.false.,&
value=input_param%check_solution, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-clear_cache',stop_on_error=.false.,&
value=input_param%clear_cache, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-filepath',stop_on_error=.false.,&
value=input_param%filepath, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-jpeg_topdir',stop_on_error=.false.,&
value=input_param%jpeg_topdir, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-png_outdir',stop_on_error=.false.,&
value=input_param%png_outdir, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-deep_level',stop_on_error=.false.,&
value=input_param%deep_level, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-check_laplacian',stop_on_error=.false.,&
value=input_param%check_laplacian, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-scale_coeff',stop_on_error=.false.,&
value=input_param%scale_coeff, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-has_numas',stop_on_error=.false.,&
value=input_param%has_numas, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-num_numas',stop_on_error=.false.,&
value=input_param%num_numas, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-numa_cores',stop_on_error=.false.,&
value=input_param%numa_cores, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-num_repetitions',stop_on_error=.false.,&
value=input_param%num_repetitions, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-profile_filepath',stop_on_error=.false.,&
value=input_param%profile_filepath, syntax=message) /=0) then
endif
if(extract_command_parameter(cmd,'-has_profile',stop_on_error=.false.,&
value=input_param%has_profile, syntax=message) /=0) then
endif
if(input_param%size_xx .gt. 0) then
input_param%min_size_xx=input_param%size_xx
input_param%max_size_xx=input_param%size_xx
input_param%step_size_xx=input_param%size_xx
endif
if(input_param%size_yy .gt. 0) then
input_param%min_size_yy=input_param%size_yy
input_param%max_size_yy=input_param%size_yy
input_param%step_size_yy=input_param%size_yy
endif
if(input_param%size_zz .gt. 0) then
input_param%min_size_zz=input_param%size_zz
input_param%max_size_zz=input_param%size_zz
input_param%step_size_zz=input_param%size_zz
endif
if(input_param%blk_size_xx .gt. 0) then
input_param%min_blk_size_xx=input_param%blk_size_xx
input_param%max_blk_size_xx=input_param%blk_size_xx
input_param%step_blk_size_xx=input_param%blk_size_xx
endif
if(input_param%blk_size_yy .gt. 0) then
input_param%min_blk_size_yy=input_param%blk_size_yy
input_param%max_blk_size_yy=input_param%blk_size_yy
input_param%step_blk_size_yy=input_param%blk_size_yy
endif
if(input_param%blk_size_zz .gt. 0) then
input_param%min_blk_size_zz=input_param%blk_size_zz
input_param%max_blk_size_zz=input_param%blk_size_zz
input_param%step_blk_size_zz=input_param%blk_size_zz
endif
if(input_param%check_laplacian .gt. 0) then
input_param%min_blk_size_zz=input_param%blk_size_zz
input_param%max_blk_size_zz=input_param%blk_size_zz
input_param%step_blk_size_zz=input_param%blk_size_zz
endif
call input_param_check()
end subroutine input_param_read
subroutine input_param_def()
input_param%benchmark_id=0
input_param%num_threads=1
input_param%num_numas=2
input_param%numa_cores=12
input_param%has_numas=0
input_param%size_xx=0
input_param%size_yy=0
input_param%size_zz=0
input_param%min_size_xx=1920
input_param%min_size_yy=1920
input_param%min_size_zz=180
input_param%max_size_xx=1920
input_param%max_size_yy=1920
input_param%max_size_zz=180
input_param%step_size_xx=64
input_param%step_size_yy=64
input_param%step_size_zz=64
input_param%min_time=1.0
input_param%blk_size_xx=0
input_param%blk_size_yy=0
input_param%blk_size_zz=0
input_param%min_blk_size_xx=128
input_param%max_blk_size_xx=128
input_param%step_blk_size_xx=128
input_param%min_blk_size_yy=128
input_param%max_blk_size_yy=128
input_param%step_blk_size_yy=128
input_param%min_blk_size_zz=180
input_param%max_blk_size_zz=180
input_param%step_blk_size_zz=180
input_param%num_repetitions=0
input_param%check_solution=1
input_param%clear_cache=1
input_param%deep_level=0
input_param%check_laplacian=0
input_param%scale_coeff=1.0
input_param%has_profile=0
write(input_param%filepath,'(A,I0,4(A,I0,A,I0),A,I0,A)') &
& "./bench_",input_param%benchmark_id, &
& "_size_",input_param%min_size_xx,"-",input_param%max_size_xx, &
& "_size_",input_param%min_size_yy,"-",input_param%max_size_yy, &
& "_size_",input_param%min_size_zz,"-",input_param%max_size_zz, &
& "_block_",input_param%blk_size_xx,"x",input_param%blk_size_yy, &
& "x",input_param%blk_size_zz, &
& ".csv"
write(input_param%jpeg_topdir,'(A)') "/nas_home/hpcdkhab/example_cache_blocking/fotos/"
write(input_param%png_outdir,'(A)') "/nas_home/hpcdkhab/example_cache_blocking/new_fotos/"
write(input_param%png_outdir,'(A)') "/nas_home/hpcdkhab/example_cache_blocking/data/profile.csv"
end subroutine input_param_def
subroutine input_param_check()
if(input_param%benchmark_id .gt. 4) then
write(*,'(A,I0)') "Error: check benchmark_id (0..4):",&
& input_param%benchmark_id
stop
endif
if(input_param%min_size_xx .gt. input_param%max_size_xx) then
write(*,'(A,I0)') "Error: check min_size_x and max_size_x (max_size must be greater than min_size)"
write(*,'(2(A,I0))') "min_size_x: ", input_param%min_size_xx, "; max_size_x: ", input_param%max_size_xx
stop
endif
if(input_param%min_size_yy .gt. input_param%max_size_yy) then
write(*,'(A,I0)') "Error: check min_size_y and max_size_y (max_size must be greater than min_size)"
write(*,'(2(A,I0))') "min_size_y: ", input_param%min_size_yy, "; max_size_y: ", input_param%max_size_yy
stop
endif
if(input_param%min_size_zz .gt. input_param%max_size_zz) then
write(*,'(A,I0)') "Error: check min_size_z and max_size_z (max_size must be greater than min_size)"
write(*,'(2(A,I0))') "min_size_z: ", input_param%min_size_zz, "; max_size_z: ", input_param%max_size_zz
stop
endif
if(input_param%max_blk_size_xx .gt. input_param%min_size_xx) then
write(*,'(A,I0)') "Error: block_size_x (block_size must be equal or less than min_size)"
stop
endif
if(input_param%max_blk_size_yy .gt. input_param%min_size_yy) then
write(*,'(A,I0)') "Error: block_size_y (block_size must be equal or less than min_size)"
stop
endif
if(input_param%max_blk_size_zz .gt. input_param%min_size_zz) then
write(*,'(A,I0)') "Error: block_size_z (block_size must be equal or less than min_size)"
stop
endif
if(input_param%has_numas .gt. 0) then
if(input_param%num_threads .gt. input_param%num_numas*input_param%numa_cores) then
write(*,'(A,I0)') "Error: num_threads greater than number of cores=num_numas*numa_cores"
stop
endif
endif
if(input_param%min_time .lt. 1.e-6) then
write(*,'(A,I0)') "Error: check min_time (too small)"
stop
endif
end subroutine input_param_check
end module mod_inparam
|
C$Procedure NPARSI ( Integer parsing of a character string)
SUBROUTINE NPARSI ( STRING, N, ERROR, PNTER)
C$ Abstract
C
C Parse a character string that represents a number and return
C the FORTRAN-truncated integer value.
C
C$ Disclaimer
C
C THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE
C CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S.
C GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE
C ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE
C PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS"
C TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY
C WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A
C PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC
C SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE
C SOFTWARE AND RELATED MATERIALS, HOWEVER USED.
C
C IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA
C BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT
C LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND,
C INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS,
C REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE
C REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY.
C
C RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF
C THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY
C CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE
C ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE.
C
C$ Required_Reading
C
C None.
C
C$ Keywords
C
C ALPHANUMERIC
C CONVERSION
C PARSING
C
C$ Declarations
CHARACTER*(*) STRING
INTEGER N
CHARACTER*(*) ERROR
INTEGER PNTER
C$ Brief_I/O
C
C VARIABLE I/O DESCRIPTION
C -------- --- ---------------------------------------------------
C STRING I Character string representing a numeric value.
C N O Translated integer value of STRING.
C ERROR O Message indicating what errors have occurred.
C PNTER O Position in character string where an error
C occurred.
C
C$ Detailed_Input
C
C STRING A character string that represents a numeric value.
C Commas and spaces may be used in this string for
C ease of reading and writing the number. They
C are treated as insignificant but non-error-producing
C characters.
C
C For exponential representation and of the characters
C 'E','D','e','d' may be used.
C
C The following are legitimate numeric expressions
C
C +12.2 e-1
C -3. 1415 9276
C 1e12
C E10
C
C The program also recognizes the following mnemonics
C 'PI', 'pi', 'Pi', 'pI'
C '+PI', '+pi', '+Pi', '+pI'
C '-PI', '-pi', '-Pi', '-pI'
C and returns the value ( + OR - ) 3 as appropriate.
C
C$ Detailed_Output
C
C N Integer parsed value of input string ( with
C the implied limits on precision). If an error is
C encountered, N is not changed from whatever the
C input value was. If the input string has a fractional
C part, the fractional part will be truncated. Thus
C 3.18 is interpreted as 3. -4.98 is interpreted as -4.
C
C ERROR This is a message indicating that the string could
C not be parsed due to ambiguous use of symbols or
C due to a string representing a number too large for
C VAX double precision or integer variables. If no
C error occurred, ERROR is blank.
C
C In particular, blank strings, or strings that do not
C contain either a digit or exponent character will
C be regarded as errors.
C
C PNTER This indicates which character was being used when
C the error occurred. If no error occurred, PNTER is 0.
C
C$ Parameters
C
C None.
C
C$ Particulars
C
C Basically, all this routine does is pass the input string to
C NPARSD which does the parsing in double precision. If nothing
C goes wrong in the double precision parsing of the number, the
C returned value is checked to determine whether or not it will fit
C into a VAX integer. If it doesn't, an error message is returned.
C
C$ Examples
C
C Let LINE = 'DELTA_T_A = 32'
C
C The following code fragment parses the line and obtains the
C integer value.
C
C
C CALL NEXTWD ( LINE, FIRST, REST )
C CALL NEXTWD ( REST, SECOND, REST )
C CALL NEXTWD ( REST, THIRD, REST )
C
C CALL NPARSI ( THIRD, VALUE, ERROR, POINTR )
C
C$ Restrictions
C
C None.
C
C$ Exceptions
C
C Error free.
C
C 1) If the string is non-numeric, PNTER indicates the location in
C the string where the error occurred, and ERROR contains a
C descriptive error message.
C
C 2) If the string is blank, ERROR is returned with a message
C indicating the problem and PNTER will have a non-zero value.
C
C 3) If the string represents a number that is outside the range
C of representable integers, as defined by INTMIN() and INTMAX(),
C ERROR is returned with a message and PNTER is set to the value
C 1, as the entire numeric string is at fault.
C
C$ Files
C
C None.
C
C$ Author_and_Institution
C
C K.R. Gehringer (JPL)
C H.A. Neilan (JPL)
C W.L. Taber (JPL)
C
C$ Literature_References
C
C None.
C
C$ Version
C
C- SPICELIB Version 2.1.0, 29-APR-1996 (KRG)
C
C This subroutine was modified to return a non-zero value of
C PNTER when the value returned by NPARSD is not a representable
C integer, as defined by INTMIN() and INTMAX(). The value
C returned is one (1), since the entire input string was not
C correct.
C
C The test for an error from NPARSD was also changed. It now
C uses the integer PNTER returned from NPARSD rather then the
C character string ERROR. This should pose no problems because
C PNTER is non-zero if and only if there was an error and an
C error message was assigned to ERROR.
C
C Some extra, and unnecessary, assignments were deleted. The
C assignments were:
C
C X = DBLE ( N )
C
C ERROR = ' '
C
C which converted the input argument into a double before
C calling NPARSD with X and initialized the error message
C to be blank. NPARSD sets the value for X, ERROR, and PNTER
C unless an error occurs, in which case X is not changed.
C So, it is not necessary to initialize ERROR, PNTER, or X.
C
C Finally, the values of INTMIN and INTMAX are only set on the
C first call to the routine. They are now SAVEd.
C
C- SPICELIB Version 2.0.0, 15-OCT-1992 (WLT)
C
C The abstract of this routine was modified to reflect what
C the routine actually does---truncate the value to an
C integer.
C
C In addition, a blank string is no longer considered to be
C valid input.
C
C Finally the instances of DFLOAT in the previous version were
C replaced by the standard intrinsic function DBLE and the
C function DINT was replaced by IDINT in one place to make types
C match up on both sides of an assignment.
C
C- SPICELIB Version 1.0.1, 10-MAR-1992 (WLT)
C
C Comment section for permuted index source lines was added
C following the header.
C
C- SPICELIB Version 1.0.0, 31-JAN-1990 (WLT)
C
C-&
C$ Index_Entries
C
C parse a character_string to an integer
C
C-&
C
C$ Revisions
C
C- SPICELIB Version 2.1.0, 29-APR-1996 (KRG)
C
C This subroutine was modified to return a non-zero value of
C PNTER when the value returned by NPARSD is not a representable
C integer, as defined by INTMIN() and INTMAX(). The value
C returned is one (1), since the entire input string was not
C correct.
C
C The test for an error from NPARSD was also changed. It now
C uses the integer PNTER returned from NPARSD rather then the
C character string ERROR. This should pose no problems because
C PNTER is non-zero if and only if there was an error and an
C error message was assigned to ERROR.
C
C Some extra, and unnecessary, assignments were deleted. The
C assignments were:
C
C X = DBLE ( N )
C
C ERROR = ' '
C
C which converted the input argument into a double before
C calling NPARSD with X and initialized the error message
C to be blank. NPARSD sets the value for X, ERROR, and PNTER
C unless an error occurs, in which case X is not changed.
C So, it is not necessary to initialize ERROR, PNTER, or X.
C
C Finally, the values of INTMIN and INTMAX are only set on the
C first call to the routine. They are now SAVEd.
C
C- SPICELIB Version 2.0.0, 15-OCT-1992 (WLT)
C
C The abstract of this routine was modified to reflect what
C the routine actually does---truncate the value to an
C integer.
C
C In addition, a blank string is no longer considered to be
C valid input.
C
C Finally the instances of DFLOAT in the previous version were
C replaced by the standard intrinsic function DBLE and the
C function DINT was replaced by IDINT in one place to make types
C match up on both sides of an assignment.
C
C- Beta Version 1.2.0, 23-FEB-1989 (WLT)
C
C Due to a programming error, the routine was not leaving N
C unchanged if the input string was blank. This bug was
C fixed and the exceptional case noted in exceptions.
C
C- Beta Version 1.1.0, 28-OCT-1988 (HAN)
C
C Peter Wolff (JPL) informed the NAIF staff that he found
C an "IMPLICIT NONE" statement in the ANSI Standard Fortran
C 77 version of this routine. Because the statement is a
C VAX extension not used by NAIF, the statement was removed.
C
C-&
C
C SPICELIB functions
C
INTEGER INTMAX
INTEGER INTMIN
C
C Local Variables
C
DOUBLE PRECISION XMNINT
DOUBLE PRECISION XMXINT
DOUBLE PRECISION X
LOGICAL FIRST
C
C Saved Variables
C
SAVE FIRST
SAVE XMNINT
SAVE XMXINT
C
C Initial values
C
DATA FIRST / .TRUE. /
C
C If this is the first time NPARSI has been called, initialize
C bounds for the range of integers.
C
IF ( FIRST ) THEN
FIRST = .FALSE.
XMXINT = DBLE ( INTMAX () )
XMNINT = DBLE ( INTMIN () )
END IF
C
C NPARSD will define ERROR and PNTER if there is an error,
C so we do not need to initialize them here.
C
CALL NPARSD ( STRING, X, ERROR, PNTER )
IF ( PNTER .EQ. 0 ) THEN
IF ( ( DINT(X) .LT. XMNINT )
. .OR. ( DINT(X) .GT. XMXINT ) ) THEN
PNTER = 1
ERROR = 'NPARSI: Value entered is beyond the bounds of '//
. 'representable integers.'
ELSE
N = IDINT(X)
END IF
END IF
RETURN
END
|
rm(list=ls())
#html_nodes(table)iz spletne strani želim dobiti le tabelo
# length(stran) pove da imamo na spletni strani 2 tabeli
library(rvest)
#url <- "https://www.gymnastics.sport/site/events/results.php?idEvent=14977"
#stran <- read_html(url)
#stran %>% html_nodes(xpath='//*[@id="app"]/div[2]/div/div[2]/table') %>% html_table(header=TRUE, fill = TRUE)
uvoz.por.hoop <- function(){
url <- "https://www.gymnastics.sport/site/events/results.php?idEvent=15889#filter"
stran <- html_session(url) %>% read_html()
stran %>% html_nodes(xpath='//*[@id="app"]/div[2]/div/div[2]/table') %>% .[[1]] %>% html_table(header=TRUE, fill = TRUE)
}
por.hoop <- uvoz.por.hoop()
View(por.hoop)
link <- "https://www.gymnastics.sport/site/events/results.php?idEvent=15889#filter"
stran <- html_session(link) %>% read_html()
vrstice <- stran %>% html_nodes(xpath='//*[@id="app"]/div[2]/div/div[2]/table') %>% html_text()
csv <- gsub(" {2,}", ",", vrstice) %>% paste(collapse="") #zamenja, kjer sta vsaj 2 presledka z vejicami (v CSV)
stolpci <- c("IZBRISI2","Sezon_v_ligi", "Ekipa", "Zmage_redni_del", "Porazi_redni_del", "Uspesnost_redni_del","Stevilo_playoffov", "Playoff_zmage", "Playoff_porazi","Playoff_uspesnost", "Zmage_serij","Porazi_serij","Uspesnost_serij","Nastopi_finale", "Zmage_finale","IZBRISI")
podatki_ekipe <- read_csv(csv, locale=locale(encoding="UTF-8"), col_names=stolpci)
podatki_ekipe <- podatki_ekipe[,-c(1,2,16)]
|
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ✝ : Type u_1
δ : Type u_2
γ : α ⊕ β → Sort u_3
p : ((ab : α ⊕ β) → γ ab) → Prop
h : ∀ (fa : (val : α) → γ (inl val)) (fb : (val : β) → γ (inr val)), p fun t => rec fa fb t
fab : (ab : α ⊕ β) → γ ab
⊢ p fab
[PROOFSTEP]
have h1 : fab = Sum.rec (fun a => fab (Sum.inl a)) (fun b => fab (Sum.inr b)) := by ext ab; cases ab <;> rfl
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ✝ : Type u_1
δ : Type u_2
γ : α ⊕ β → Sort u_3
p : ((ab : α ⊕ β) → γ ab) → Prop
h : ∀ (fa : (val : α) → γ (inl val)) (fb : (val : β) → γ (inr val)), p fun t => rec fa fb t
fab : (ab : α ⊕ β) → γ ab
⊢ fab = fun t => rec (fun a => fab (inl a)) (fun b => fab (inr b)) t
[PROOFSTEP]
ext ab
[GOAL]
case h
α : Type u
α' : Type w
β : Type v
β' : Type x
γ✝ : Type u_1
δ : Type u_2
γ : α ⊕ β → Sort u_3
p : ((ab : α ⊕ β) → γ ab) → Prop
h : ∀ (fa : (val : α) → γ (inl val)) (fb : (val : β) → γ (inr val)), p fun t => rec fa fb t
fab : (ab : α ⊕ β) → γ ab
ab : α ⊕ β
⊢ fab ab = rec (fun a => fab (inl a)) (fun b => fab (inr b)) ab
[PROOFSTEP]
cases ab
[GOAL]
case h.inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ✝ : Type u_1
δ : Type u_2
γ : α ⊕ β → Sort u_3
p : ((ab : α ⊕ β) → γ ab) → Prop
h : ∀ (fa : (val : α) → γ (inl val)) (fb : (val : β) → γ (inr val)), p fun t => rec fa fb t
fab : (ab : α ⊕ β) → γ ab
val✝ : α
⊢ fab (inl val✝) = rec (fun a => fab (inl a)) (fun b => fab (inr b)) (inl val✝)
[PROOFSTEP]
rfl
[GOAL]
case h.inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ✝ : Type u_1
δ : Type u_2
γ : α ⊕ β → Sort u_3
p : ((ab : α ⊕ β) → γ ab) → Prop
h : ∀ (fa : (val : α) → γ (inl val)) (fb : (val : β) → γ (inr val)), p fun t => rec fa fb t
fab : (ab : α ⊕ β) → γ ab
val✝ : β
⊢ fab (inr val✝) = rec (fun a => fab (inl a)) (fun b => fab (inr b)) (inr val✝)
[PROOFSTEP]
rfl
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ✝ : Type u_1
δ : Type u_2
γ : α ⊕ β → Sort u_3
p : ((ab : α ⊕ β) → γ ab) → Prop
h : ∀ (fa : (val : α) → γ (inl val)) (fb : (val : β) → γ (inr val)), p fun t => rec fa fb t
fab : (ab : α ⊕ β) → γ ab
h1 : fab = fun t => rec (fun a => fab (inl a)) (fun b => fab (inr b)) t
⊢ p fab
[PROOFSTEP]
rw [h1]
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ✝ : Type u_1
δ : Type u_2
γ : α ⊕ β → Sort u_3
p : ((ab : α ⊕ β) → γ ab) → Prop
h : ∀ (fa : (val : α) → γ (inl val)) (fb : (val : β) → γ (inr val)), p fun t => rec fa fb t
fab : (ab : α ⊕ β) → γ ab
h1 : fab = fun t => rec (fun a => fab (inl a)) (fun b => fab (inr b)) t
⊢ p fun t => rec (fun a => fab (inl a)) (fun b => fab (inr b)) t
[PROOFSTEP]
exact h _ _
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ✝ : Type u_1
δ : Type u_2
γ : α ⊕ β → Sort u_3
p : ((ab : α ⊕ β) → γ ab) → Prop
⊢ (∃ fab, p fab) ↔ ∃ fa fb, p fun t => rec fa fb t
[PROOFSTEP]
rw [← not_forall_not, forall_sum_pi]
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ✝ : Type u_1
δ : Type u_2
γ : α ⊕ β → Sort u_3
p : ((ab : α ⊕ β) → γ ab) → Prop
⊢ (¬∀ (fa : (val : α) → γ (inl val)) (fb : (val : β) → γ (inr val)), ¬p fun t => rec fa fb t) ↔
∃ fa fb, p fun t => rec fa fb t
[PROOFSTEP]
simp
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x y : α ⊕ β
⊢ getLeft? x = none ↔ isRight x = true
[PROOFSTEP]
cases x
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
y : α ⊕ β
val✝ : α
⊢ getLeft? (inl val✝) = none ↔ isRight (inl val✝) = true
[PROOFSTEP]
simp only [getLeft?, isRight, eq_self_iff_true]
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
y : α ⊕ β
val✝ : β
⊢ getLeft? (inr val✝) = none ↔ isRight (inr val✝) = true
[PROOFSTEP]
simp only [getLeft?, isRight, eq_self_iff_true]
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x y : α ⊕ β
⊢ getRight? x = none ↔ isLeft x = true
[PROOFSTEP]
cases x
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
y : α ⊕ β
val✝ : α
⊢ getRight? (inl val✝) = none ↔ isLeft (inl val✝) = true
[PROOFSTEP]
simp only [getRight?, isLeft, eq_self_iff_true]
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
y : α ⊕ β
val✝ : β
⊢ getRight? (inr val✝) = none ↔ isLeft (inr val✝) = true
[PROOFSTEP]
simp only [getRight?, isLeft, eq_self_iff_true]
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x y : α ⊕ β
a : α
⊢ getLeft? x = some a ↔ x = inl a
[PROOFSTEP]
cases x
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
y : α ⊕ β
a val✝ : α
⊢ getLeft? (inl val✝) = some a ↔ inl val✝ = inl a
[PROOFSTEP]
simp only [getLeft?, Option.some.injEq, inl.injEq]
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
y : α ⊕ β
a : α
val✝ : β
⊢ getLeft? (inr val✝) = some a ↔ inr val✝ = inl a
[PROOFSTEP]
simp only [getLeft?, Option.some.injEq, inl.injEq]
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x y : α ⊕ β
b : β
⊢ getRight? x = some b ↔ x = inr b
[PROOFSTEP]
cases x
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
y : α ⊕ β
b : β
val✝ : α
⊢ getRight? (inl val✝) = some b ↔ inl val✝ = inr b
[PROOFSTEP]
simp only [getRight?, Option.some.injEq, inr.injEq]
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
y : α ⊕ β
b val✝ : β
⊢ getRight? (inr val✝) = some b ↔ inr val✝ = inr b
[PROOFSTEP]
simp only [getRight?, Option.some.injEq, inr.injEq]
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x✝ y x : α ⊕ β
⊢ (!isLeft x) = isRight x
[PROOFSTEP]
cases x
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x y : α ⊕ β
val✝ : α
⊢ (!isLeft (inl val✝)) = isRight (inl val✝)
[PROOFSTEP]
rfl
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x y : α ⊕ β
val✝ : β
⊢ (!isLeft (inr val✝)) = isRight (inr val✝)
[PROOFSTEP]
rfl
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x y : α ⊕ β
⊢ isLeft x = false ↔ isRight x = true
[PROOFSTEP]
cases x
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
y : α ⊕ β
val✝ : α
⊢ isLeft (inl val✝) = false ↔ isRight (inl val✝) = true
[PROOFSTEP]
simp
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
y : α ⊕ β
val✝ : β
⊢ isLeft (inr val✝) = false ↔ isRight (inr val✝) = true
[PROOFSTEP]
simp
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x y : α ⊕ β
⊢ ¬isLeft x = true ↔ isRight x = true
[PROOFSTEP]
simp
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x✝ y x : α ⊕ β
⊢ (!decide (isRight x = isLeft x)) = true
[PROOFSTEP]
cases x
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x y : α ⊕ β
val✝ : α
⊢ (!decide (isRight (inl val✝) = isLeft (inl val✝))) = true
[PROOFSTEP]
rfl
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x y : α ⊕ β
val✝ : β
⊢ (!decide (isRight (inr val✝) = isLeft (inr val✝))) = true
[PROOFSTEP]
rfl
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x y : α ⊕ β
⊢ isRight x = false ↔ isLeft x = true
[PROOFSTEP]
cases x
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
y : α ⊕ β
val✝ : α
⊢ isRight (inl val✝) = false ↔ isLeft (inl val✝) = true
[PROOFSTEP]
simp
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
y : α ⊕ β
val✝ : β
⊢ isRight (inr val✝) = false ↔ isLeft (inr val✝) = true
[PROOFSTEP]
simp
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x y : α ⊕ β
⊢ ¬isRight x = true ↔ isLeft x = true
[PROOFSTEP]
simp
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x y : α ⊕ β
⊢ isLeft x = true ↔ ∃ y, x = inl y
[PROOFSTEP]
cases x
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
y : α ⊕ β
val✝ : α
⊢ isLeft (inl val✝) = true ↔ ∃ y, inl val✝ = inl y
[PROOFSTEP]
simp
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
y : α ⊕ β
val✝ : β
⊢ isLeft (inr val✝) = true ↔ ∃ y, inr val✝ = inl y
[PROOFSTEP]
simp
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x y : α ⊕ β
⊢ isRight x = true ↔ ∃ y, x = inr y
[PROOFSTEP]
cases x
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
y : α ⊕ β
val✝ : α
⊢ isRight (inl val✝) = true ↔ ∃ y, inl val✝ = inr y
[PROOFSTEP]
simp
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
y : α ⊕ β
val✝ : β
⊢ isRight (inr val✝) = true ↔ ∃ y, inr val✝ = inr y
[PROOFSTEP]
simp
[GOAL]
α✝ : Type u
α' : Type w
β✝ : Type v
β' : Type x
γ✝ : Type u_1
δ✝ : Type u_2
α : Type u_3
β : Type u_4
γ : Type u_5
δ : Type u_6
ε : Sort u_7
f₁ : α → β
f₂ : β → ε
g₁ : γ → δ
g₂ : δ → ε
x : α ⊕ γ
⊢ Sum.elim f₂ g₂ (Sum.map f₁ g₁ x) = Sum.elim (f₂ ∘ f₁) (g₂ ∘ g₁) x
[PROOFSTEP]
cases x
[GOAL]
case inl
α✝ : Type u
α' : Type w
β✝ : Type v
β' : Type x
γ✝ : Type u_1
δ✝ : Type u_2
α : Type u_3
β : Type u_4
γ : Type u_5
δ : Type u_6
ε : Sort u_7
f₁ : α → β
f₂ : β → ε
g₁ : γ → δ
g₂ : δ → ε
val✝ : α
⊢ Sum.elim f₂ g₂ (Sum.map f₁ g₁ (inl val✝)) = Sum.elim (f₂ ∘ f₁) (g₂ ∘ g₁) (inl val✝)
[PROOFSTEP]
rfl
[GOAL]
case inr
α✝ : Type u
α' : Type w
β✝ : Type v
β' : Type x
γ✝ : Type u_1
δ✝ : Type u_2
α : Type u_3
β : Type u_4
γ : Type u_5
δ : Type u_6
ε : Sort u_7
f₁ : α → β
f₂ : β → ε
g₁ : γ → δ
g₂ : δ → ε
val✝ : γ
⊢ Sum.elim f₂ g₂ (Sum.map f₁ g₁ (inr val✝)) = Sum.elim (f₂ ∘ f₁) (g₂ ∘ g₁) (inr val✝)
[PROOFSTEP]
rfl
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
f : α → β
g : γ → δ
x : α ⊕ γ
⊢ isLeft (Sum.map f g x) = isLeft x
[PROOFSTEP]
cases x
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
f : α → β
g : γ → δ
val✝ : α
⊢ isLeft (Sum.map f g (inl val✝)) = isLeft (inl val✝)
[PROOFSTEP]
rfl
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
f : α → β
g : γ → δ
val✝ : γ
⊢ isLeft (Sum.map f g (inr val✝)) = isLeft (inr val✝)
[PROOFSTEP]
rfl
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
f : α → β
g : γ → δ
x : α ⊕ γ
⊢ isRight (Sum.map f g x) = isRight x
[PROOFSTEP]
cases x
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
f : α → β
g : γ → δ
val✝ : α
⊢ isRight (Sum.map f g (inl val✝)) = isRight (inl val✝)
[PROOFSTEP]
rfl
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
f : α → β
g : γ → δ
val✝ : γ
⊢ isRight (Sum.map f g (inr val✝)) = isRight (inr val✝)
[PROOFSTEP]
rfl
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
f : α → β
g : γ → δ
x : α ⊕ γ
⊢ getLeft? (Sum.map f g x) = Option.map f (getLeft? x)
[PROOFSTEP]
cases x
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
f : α → β
g : γ → δ
val✝ : α
⊢ getLeft? (Sum.map f g (inl val✝)) = Option.map f (getLeft? (inl val✝))
[PROOFSTEP]
rfl
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
f : α → β
g : γ → δ
val✝ : γ
⊢ getLeft? (Sum.map f g (inr val✝)) = Option.map f (getLeft? (inr val✝))
[PROOFSTEP]
rfl
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
f : α → β
g : γ → δ
x : α ⊕ γ
⊢ getRight? (Sum.map f g x) = Option.map g (getRight? x)
[PROOFSTEP]
cases x
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
f : α → β
g : γ → δ
val✝ : α
⊢ getRight? (Sum.map f g (inl val✝)) = Option.map g (getRight? (inl val✝))
[PROOFSTEP]
rfl
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
f : α → β
g : γ → δ
val✝ : γ
⊢ getRight? (Sum.map f g (inr val✝)) = Option.map g (getRight? (inr val✝))
[PROOFSTEP]
rfl
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq α
inst✝ : DecidableEq (α ⊕ β)
f : α → γ
g : β → γ
i : α
x : γ
⊢ x = Sum.elim (update f i x) g (inl i)
[PROOFSTEP]
simp
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq α
inst✝ : DecidableEq (α ⊕ β)
f : α → γ
g : β → γ
i : α
x : γ
⊢ ∀ (x_1 : α ⊕ β), x_1 ≠ inl i → Sum.elim f g x_1 = Sum.elim (update f i x) g x_1
[PROOFSTEP]
simp (config := { contextual := true })
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq β
inst✝ : DecidableEq (α ⊕ β)
f : α → γ
g : β → γ
i : β
x : γ
⊢ x = Sum.elim f (update g i x) (inr i)
[PROOFSTEP]
simp
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq β
inst✝ : DecidableEq (α ⊕ β)
f : α → γ
g : β → γ
i : β
x : γ
⊢ ∀ (x_1 : α ⊕ β), x_1 ≠ inr i → Sum.elim f g x_1 = Sum.elim f (update g i x) x_1
[PROOFSTEP]
simp (config := { contextual := true })
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq α
inst✝ : DecidableEq (α ⊕ β)
f : α ⊕ β → γ
i j : α
x : γ
⊢ update f (inl i) x (inl j) = update (f ∘ inl) i x j
[PROOFSTEP]
rw [← update_inl_comp_inl, Function.comp_apply]
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq β
inst✝ : DecidableEq (α ⊕ β)
f : α ⊕ β → γ
i j : β
x : γ
⊢ update f (inr i) x (inr j) = update (f ∘ inr) i x j
[PROOFSTEP]
rw [← update_inr_comp_inr, Function.comp_apply]
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x : α ⊕ β
⊢ swap (swap x) = x
[PROOFSTEP]
cases x
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
val✝ : α
⊢ swap (swap (inl val✝)) = inl val✝
[PROOFSTEP]
rfl
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
val✝ : β
⊢ swap (swap (inr val✝)) = inr val✝
[PROOFSTEP]
rfl
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x : α ⊕ β
⊢ isLeft (swap x) = isRight x
[PROOFSTEP]
cases x
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
val✝ : α
⊢ isLeft (swap (inl val✝)) = isRight (inl val✝)
[PROOFSTEP]
rfl
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
val✝ : β
⊢ isLeft (swap (inr val✝)) = isRight (inr val✝)
[PROOFSTEP]
rfl
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x : α ⊕ β
⊢ isRight (swap x) = isLeft x
[PROOFSTEP]
cases x
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
val✝ : α
⊢ isRight (swap (inl val✝)) = isLeft (inl val✝)
[PROOFSTEP]
rfl
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
val✝ : β
⊢ isRight (swap (inr val✝)) = isLeft (inr val✝)
[PROOFSTEP]
rfl
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x : α ⊕ β
⊢ getLeft? (swap x) = getRight? x
[PROOFSTEP]
cases x
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
val✝ : α
⊢ getLeft? (swap (inl val✝)) = getRight? (inl val✝)
[PROOFSTEP]
rfl
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
val✝ : β
⊢ getLeft? (swap (inr val✝)) = getRight? (inr val✝)
[PROOFSTEP]
rfl
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
x : α ⊕ β
⊢ getRight? (swap x) = getLeft? x
[PROOFSTEP]
cases x
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
val✝ : α
⊢ getRight? (swap (inl val✝)) = getLeft? (inl val✝)
[PROOFSTEP]
rfl
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
val✝ : β
⊢ getRight? (swap (inr val✝)) = getLeft? (inr val✝)
[PROOFSTEP]
rfl
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → γ → Prop
s s₁ s₂ : β → δ → Prop
a : α
b : β
c : γ
d : δ
x : α ⊕ β
y : γ ⊕ δ
h : LiftRel r s (inl a) (inl c)
⊢ r a c
[PROOFSTEP]
cases h
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → γ → Prop
s s₁ s₂ : β → δ → Prop
a : α
b : β
c : γ
d : δ
x : α ⊕ β
y : γ ⊕ δ
a✝ : r a c
⊢ r a c
[PROOFSTEP]
assumption
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → γ → Prop
s s₁ s₂ : β → δ → Prop
a : α
b : β
c : γ
d : δ
x : α ⊕ β
y : γ ⊕ δ
h : LiftRel r s (inr b) (inr d)
⊢ s b d
[PROOFSTEP]
cases h
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → γ → Prop
s s₁ s₂ : β → δ → Prop
a : α
b : β
c : γ
d : δ
x : α ⊕ β
y : γ ⊕ δ
a✝ : s b d
⊢ s b d
[PROOFSTEP]
assumption
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → γ → Prop
s s₁ s₂ : β → δ → Prop
a : α
b : β
c : γ
d : δ
x : α ⊕ β
y : γ ⊕ δ
hr : ∀ (a : α) (b : γ), r₁ a b → r₂ a b
hs : ∀ (a : β) (b : δ), s₁ a b → s₂ a b
h : LiftRel r₁ s₁ x y
⊢ LiftRel r₂ s₂ x y
[PROOFSTEP]
cases h
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → γ → Prop
s s₁ s₂ : β → δ → Prop
a : α
b : β
c : γ
d : δ
hr : ∀ (a : α) (b : γ), r₁ a b → r₂ a b
hs : ∀ (a : β) (b : δ), s₁ a b → s₂ a b
a✝¹ : α
c✝ : γ
a✝ : r₁ a✝¹ c✝
⊢ LiftRel r₂ s₂ (inl a✝¹) (inl c✝)
[PROOFSTEP]
exact LiftRel.inl (hr _ _ ‹_›)
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → γ → Prop
s s₁ s₂ : β → δ → Prop
a : α
b : β
c : γ
d : δ
hr : ∀ (a : α) (b : γ), r₁ a b → r₂ a b
hs : ∀ (a : β) (b : δ), s₁ a b → s₂ a b
b✝ : β
d✝ : δ
a✝ : s₁ b✝ d✝
⊢ LiftRel r₂ s₂ (inr b✝) (inr d✝)
[PROOFSTEP]
exact LiftRel.inr (hs _ _ ‹_›)
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → γ → Prop
s s₁ s₂ : β → δ → Prop
a : α
b : β
c : γ
d : δ
x : α ⊕ β
y : γ ⊕ δ
h : LiftRel r s x y
⊢ LiftRel s r (swap x) (swap y)
[PROOFSTEP]
cases h
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → γ → Prop
s s₁ s₂ : β → δ → Prop
a : α
b : β
c : γ
d : δ
a✝¹ : α
c✝ : γ
a✝ : r a✝¹ c✝
⊢ LiftRel s r (swap (inl a✝¹)) (swap (inl c✝))
[PROOFSTEP]
exact LiftRel.inr ‹_›
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → γ → Prop
s s₁ s₂ : β → δ → Prop
a : α
b : β
c : γ
d : δ
b✝ : β
d✝ : δ
a✝ : s b✝ d✝
⊢ LiftRel s r (swap (inr b✝)) (swap (inr d✝))
[PROOFSTEP]
exact LiftRel.inl ‹_›
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → γ → Prop
s s₁ s₂ : β → δ → Prop
a : α
b : β
c : γ
d : δ
x : α ⊕ β
y : γ ⊕ δ
h : LiftRel s r (swap x) (swap y)
⊢ LiftRel r s x y
[PROOFSTEP]
rw [← swap_swap x, ← swap_swap y]
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → γ → Prop
s s₁ s₂ : β → δ → Prop
a : α
b : β
c : γ
d : δ
x : α ⊕ β
y : γ ⊕ δ
h : LiftRel s r (swap x) (swap y)
⊢ LiftRel r s (swap (swap x)) (swap (swap y))
[PROOFSTEP]
exact h.swap
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a a₁ a₂ : α
b b₁ b₂ : β
x y : α ⊕ β
h : Lex r s (inl a₁) (inl a₂)
⊢ r a₁ a₂
[PROOFSTEP]
cases h
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a a₁ a₂ : α
b b₁ b₂ : β
x y : α ⊕ β
h✝ : r a₁ a₂
⊢ r a₁ a₂
[PROOFSTEP]
assumption
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a a₁ a₂ : α
b b₁ b₂ : β
x y : α ⊕ β
h : Lex r s (inr b₁) (inr b₂)
⊢ s b₁ b₂
[PROOFSTEP]
cases h
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a a₁ a₂ : α
b b₁ b₂ : β
x y : α ⊕ β
h✝ : s b₁ b₂
⊢ s b₁ b₂
[PROOFSTEP]
assumption
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a✝ a₁ a₂ : α
b✝ b₁ b₂ : β
x y a b : α ⊕ β
h : LiftRel r s a b
⊢ Lex r s a b
[PROOFSTEP]
cases h
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a a₁ a₂ : α
b b₁ b₂ : β
x y : α ⊕ β
a✝¹ c✝ : α
a✝ : r a✝¹ c✝
⊢ Lex r s (inl a✝¹) (inl c✝)
[PROOFSTEP]
exact Lex.inl ‹_›
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a a₁ a₂ : α
b b₁ b₂ : β
x y : α ⊕ β
b✝ d✝ : β
a✝ : s b✝ d✝
⊢ Lex r s (inr b✝) (inr d✝)
[PROOFSTEP]
exact Lex.inr ‹_›
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a a₁ a₂ : α
b b₁ b₂ : β
x y : α ⊕ β
hr : ∀ (a b : α), r₁ a b → r₂ a b
hs : ∀ (a b : β), s₁ a b → s₂ a b
h : Lex r₁ s₁ x y
⊢ Lex r₂ s₂ x y
[PROOFSTEP]
cases h
[GOAL]
case inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a a₁ a₂ : α
b b₁ b₂ : β
hr : ∀ (a b : α), r₁ a b → r₂ a b
hs : ∀ (a b : β), s₁ a b → s₂ a b
a₁✝ a₂✝ : α
h✝ : r₁ a₁✝ a₂✝
⊢ Lex r₂ s₂ (inl a₁✝) (inl a₂✝)
[PROOFSTEP]
exact Lex.inl (hr _ _ ‹_›)
[GOAL]
case inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a a₁ a₂ : α
b b₁ b₂ : β
hr : ∀ (a b : α), r₁ a b → r₂ a b
hs : ∀ (a b : β), s₁ a b → s₂ a b
b₁✝ b₂✝ : β
h✝ : s₁ b₁✝ b₂✝
⊢ Lex r₂ s₂ (inr b₁✝) (inr b₂✝)
[PROOFSTEP]
exact Lex.inr (hs _ _ ‹_›)
[GOAL]
case sep
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a a₁ a₂ : α
b b₁ b₂ : β
hr : ∀ (a b : α), r₁ a b → r₂ a b
hs : ∀ (a b : β), s₁ a b → s₂ a b
a✝ : α
b✝ : β
⊢ Lex r₂ s₂ (inl a✝) (inr b✝)
[PROOFSTEP]
exact Lex.sep _ _
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a✝ a₁ a₂ : α
b b₁ b₂ : β
x y : α ⊕ β
a : α
aca : Acc r a
⊢ Acc (Lex r s) (inl a)
[PROOFSTEP]
induction' aca with a _ IH
[GOAL]
case intro
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a✝¹ a₁ a₂ : α
b b₁ b₂ : β
x y : α ⊕ β
a✝ a : α
h✝ : ∀ (y : α), r y a → Acc r y
IH : ∀ (y : α), r y a → Acc (Lex r s) (inl y)
⊢ Acc (Lex r s) (inl a)
[PROOFSTEP]
constructor
[GOAL]
case intro.h
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a✝¹ a₁ a₂ : α
b b₁ b₂ : β
x y : α ⊕ β
a✝ a : α
h✝ : ∀ (y : α), r y a → Acc r y
IH : ∀ (y : α), r y a → Acc (Lex r s) (inl y)
⊢ ∀ (y : α ⊕ β), Lex r s y (inl a) → Acc (Lex r s) y
[PROOFSTEP]
intro y h
[GOAL]
case intro.h
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a✝¹ a₁ a₂ : α
b b₁ b₂ : β
x y✝ : α ⊕ β
a✝ a : α
h✝ : ∀ (y : α), r y a → Acc r y
IH : ∀ (y : α), r y a → Acc (Lex r s) (inl y)
y : α ⊕ β
h : Lex r s y (inl a)
⊢ Acc (Lex r s) y
[PROOFSTEP]
cases' h with a' _ h'
[GOAL]
case intro.h.inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a✝¹ a₁ a₂ : α
b b₁ b₂ : β
x y : α ⊕ β
a✝ a : α
h✝ : ∀ (y : α), r y a → Acc r y
IH : ∀ (y : α), r y a → Acc (Lex r s) (inl y)
a' : α
h' : r a' a
⊢ Acc (Lex r s) (inl a')
[PROOFSTEP]
exact IH _ h'
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a a₁ a₂ : α
b✝ b₁ b₂ : β
x y : α ⊕ β
aca : ∀ (a : α), Acc (Lex r s) (inl a)
b : β
acb : Acc s b
⊢ Acc (Lex r s) (inr b)
[PROOFSTEP]
induction' acb with b _ IH
[GOAL]
case intro
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a a₁ a₂ : α
b✝¹ b₁ b₂ : β
x y : α ⊕ β
aca : ∀ (a : α), Acc (Lex r s) (inl a)
b✝ b : β
h✝ : ∀ (y : β), s y b → Acc s y
IH : ∀ (y : β), s y b → Acc (Lex r s) (inr y)
⊢ Acc (Lex r s) (inr b)
[PROOFSTEP]
constructor
[GOAL]
case intro.h
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a a₁ a₂ : α
b✝¹ b₁ b₂ : β
x y : α ⊕ β
aca : ∀ (a : α), Acc (Lex r s) (inl a)
b✝ b : β
h✝ : ∀ (y : β), s y b → Acc s y
IH : ∀ (y : β), s y b → Acc (Lex r s) (inr y)
⊢ ∀ (y : α ⊕ β), Lex r s y (inr b) → Acc (Lex r s) y
[PROOFSTEP]
intro y h
[GOAL]
case intro.h
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a a₁ a₂ : α
b✝¹ b₁ b₂ : β
x y✝ : α ⊕ β
aca : ∀ (a : α), Acc (Lex r s) (inl a)
b✝ b : β
h✝ : ∀ (y : β), s y b → Acc s y
IH : ∀ (y : β), s y b → Acc (Lex r s) (inr y)
y : α ⊕ β
h : Lex r s y (inr b)
⊢ Acc (Lex r s) y
[PROOFSTEP]
cases' h with _ _ _ b' _ h' a
[GOAL]
case intro.h.inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a a₁ a₂ : α
b✝¹ b₁ b₂ : β
x y : α ⊕ β
aca : ∀ (a : α), Acc (Lex r s) (inl a)
b✝ b : β
h✝ : ∀ (y : β), s y b → Acc s y
IH : ∀ (y : β), s y b → Acc (Lex r s) (inr y)
b' : β
h' : s b' b
⊢ Acc (Lex r s) (inr b')
[PROOFSTEP]
exact IH _ h'
[GOAL]
case intro.h.sep
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
r r₁ r₂ : α → α → Prop
s s₁ s₂ : β → β → Prop
a✝ a₁ a₂ : α
b✝¹ b₁ b₂ : β
x y : α ⊕ β
aca : ∀ (a : α), Acc (Lex r s) (inl a)
b✝ b : β
h✝ : ∀ (y : β), s y b → Acc s y
IH : ∀ (y : β), s y b → Acc (Lex r s) (inr y)
a : α
⊢ Acc (Lex r s) (inl a)
[PROOFSTEP]
exact aca _
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
f : α → γ
g : β → δ
h : Surjective (Sum.map f g)
c : γ
⊢ ∃ a, f a = c
[PROOFSTEP]
obtain ⟨a | b, h⟩ := h (inl c)
[GOAL]
case intro.inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
f : α → γ
g : β → δ
h✝ : Surjective (Sum.map f g)
c : γ
a : α
h : Sum.map f g (inl a) = inl c
⊢ ∃ a, f a = c
[PROOFSTEP]
exact ⟨a, inl_injective h⟩
[GOAL]
case intro.inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
f : α → γ
g : β → δ
h✝ : Surjective (Sum.map f g)
c : γ
b : β
h : Sum.map f g (inr b) = inl c
⊢ ∃ a, f a = c
[PROOFSTEP]
cases h
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
f : α → γ
g : β → δ
h : Surjective (Sum.map f g)
d : δ
⊢ ∃ a, g a = d
[PROOFSTEP]
obtain ⟨a | b, h⟩ := h (inr d)
[GOAL]
case intro.inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
f : α → γ
g : β → δ
h✝ : Surjective (Sum.map f g)
d : δ
a : α
h : Sum.map f g (inl a) = inr d
⊢ ∃ a, g a = d
[PROOFSTEP]
cases h
[GOAL]
case intro.inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
f : α → γ
g : β → δ
h✝ : Surjective (Sum.map f g)
d : δ
b : β
h : Sum.map f g (inr b) = inr d
⊢ ∃ a, g a = d
[PROOFSTEP]
exact ⟨b, inr_injective h⟩
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
c : γ
⊢ Sum.elim (const α c) (const β c) = const (α ⊕ β) c
[PROOFSTEP]
ext x
[GOAL]
case h
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
c : γ
x : α ⊕ β
⊢ Sum.elim (const α c) (const β c) x = const (α ⊕ β) c x
[PROOFSTEP]
cases x
[GOAL]
case h.inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
c : γ
val✝ : α
⊢ Sum.elim (const α c) (const β c) (inl val✝) = const (α ⊕ β) c (inl val✝)
[PROOFSTEP]
rfl
[GOAL]
case h.inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
c : γ
val✝ : β
⊢ Sum.elim (const α c) (const β c) (inr val✝) = const (α ⊕ β) c (inr val✝)
[PROOFSTEP]
rfl
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq α
inst✝ : DecidableEq β
f : α → γ
g : β → γ
i : α
c : γ
⊢ Sum.elim (update f i c) g = update (Sum.elim f g) (inl i) c
[PROOFSTEP]
ext x
[GOAL]
case h
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq α
inst✝ : DecidableEq β
f : α → γ
g : β → γ
i : α
c : γ
x : α ⊕ β
⊢ Sum.elim (update f i c) g x = update (Sum.elim f g) (inl i) c x
[PROOFSTEP]
rcases x with x | x
[GOAL]
case h.inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq α
inst✝ : DecidableEq β
f : α → γ
g : β → γ
i : α
c : γ
x : α
⊢ Sum.elim (update f i c) g (inl x) = update (Sum.elim f g) (inl i) c (inl x)
[PROOFSTEP]
by_cases h : x = i
[GOAL]
case pos
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq α
inst✝ : DecidableEq β
f : α → γ
g : β → γ
i : α
c : γ
x : α
h : x = i
⊢ Sum.elim (update f i c) g (inl x) = update (Sum.elim f g) (inl i) c (inl x)
[PROOFSTEP]
subst h
[GOAL]
case pos
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq α
inst✝ : DecidableEq β
f : α → γ
g : β → γ
c : γ
x : α
⊢ Sum.elim (update f x c) g (inl x) = update (Sum.elim f g) (inl x) c (inl x)
[PROOFSTEP]
simp
[GOAL]
case neg
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq α
inst✝ : DecidableEq β
f : α → γ
g : β → γ
i : α
c : γ
x : α
h : ¬x = i
⊢ Sum.elim (update f i c) g (inl x) = update (Sum.elim f g) (inl i) c (inl x)
[PROOFSTEP]
simp [h]
[GOAL]
case h.inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq α
inst✝ : DecidableEq β
f : α → γ
g : β → γ
i : α
c : γ
x : β
⊢ Sum.elim (update f i c) g (inr x) = update (Sum.elim f g) (inl i) c (inr x)
[PROOFSTEP]
simp
[GOAL]
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq α
inst✝ : DecidableEq β
f : α → γ
g : β → γ
i : β
c : γ
⊢ Sum.elim f (update g i c) = update (Sum.elim f g) (inr i) c
[PROOFSTEP]
ext x
[GOAL]
case h
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq α
inst✝ : DecidableEq β
f : α → γ
g : β → γ
i : β
c : γ
x : α ⊕ β
⊢ Sum.elim f (update g i c) x = update (Sum.elim f g) (inr i) c x
[PROOFSTEP]
rcases x with x | x
[GOAL]
case h.inl
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq α
inst✝ : DecidableEq β
f : α → γ
g : β → γ
i : β
c : γ
x : α
⊢ Sum.elim f (update g i c) (inl x) = update (Sum.elim f g) (inr i) c (inl x)
[PROOFSTEP]
simp
[GOAL]
case h.inr
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq α
inst✝ : DecidableEq β
f : α → γ
g : β → γ
i : β
c : γ
x : β
⊢ Sum.elim f (update g i c) (inr x) = update (Sum.elim f g) (inr i) c (inr x)
[PROOFSTEP]
by_cases h : x = i
[GOAL]
case pos
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq α
inst✝ : DecidableEq β
f : α → γ
g : β → γ
i : β
c : γ
x : β
h : x = i
⊢ Sum.elim f (update g i c) (inr x) = update (Sum.elim f g) (inr i) c (inr x)
[PROOFSTEP]
subst h
[GOAL]
case pos
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq α
inst✝ : DecidableEq β
f : α → γ
g : β → γ
c : γ
x : β
⊢ Sum.elim f (update g x c) (inr x) = update (Sum.elim f g) (inr x) c (inr x)
[PROOFSTEP]
simp
[GOAL]
case neg
α : Type u
α' : Type w
β : Type v
β' : Type x
γ : Type u_1
δ : Type u_2
inst✝¹ : DecidableEq α
inst✝ : DecidableEq β
f : α → γ
g : β → γ
i : β
c : γ
x : β
h : ¬x = i
⊢ Sum.elim f (update g i c) (inr x) = update (Sum.elim f g) (inr i) c (inr x)
[PROOFSTEP]
simp [h]
|
# GolemFlavor Inference
In this example, we will take the fake data generated in the `tutorial.ipynb` example and use it to make an inference the source flavor composition using Bayesian techniques.
```python
from __future__ import absolute_import, division, print_function
from functools import partial
import numpy as np
import matplotlib.pyplot as plt
```
## Define Fake Data
We will generate some fake data using a multivariate Gaussian likelihood, as described in the `tutorial.ipynb` notebook. We set our injected source composition to the pion decay model $(1:2:0)_S$ and use the global neutrino data fit mixing matrix values to calculate the expected measured composition.
```python
from golemflavor.fr import NUFIT_U
from golemflavor.fr import normalize_fr, u_to_fr
source_composition = normalize_fr((1, 0, 0))
measured_composition = u_to_fr(source_composition, NUFIT_U)
```
We also set the smearing, which represents detector related imperfections in our Gaussian likelihood:
```python
smearing = 0.02
```
Then we define the `asimov_paramset` which contains `Params` objects for each of our measured quantities:
```python
from golemflavor.fr import fr_to_angles
from golemflavor.enums import ParamTag
from golemflavor.param import Param, ParamSet
# Convert from flavor composition to flavor angles
measured_flavor_angles = fr_to_angles(measured_composition)
# Parameters can be tagged for later convenience
tag = ParamTag.BESTFIT
# Define the asimov `ParamSet`, with `Param` objects containing information such as name, value and ranges.
asimov_paramset = [
Param(name='measured_angle1', value=measured_flavor_angles[0], ranges=[ 0., 1.], std=smearing, tag=tag, tex=r'\sin^4\phi_\oplus'),
Param(name='measured_angle2', value=measured_flavor_angles[1], ranges=[-1., 1.], std=smearing, tag=tag, tex=r'\cos(2\psi_\oplus)')
]
asimov_paramset = ParamSet(asimov_paramset)
```
## Physics Model
The goal here is to make an inference of the source flavor composition from our fake data measurement. In order to do this, we need a model that links the two. Of course, in this case we will use the neutrino mixing model that we generated the fake data with, but it is worth mentioning that with real data we sometimes do not have this luxury. Model dependence is a heavily debated topic in physics. That isn't to say that having model dependence is a bad thing, indeed the best physicists are ones which do make model assumptions but can however justify their simplifications to the wider community.
As a reminder from `tutorial.ipynb`, the measured flavor composition can be written as a function of the source flavor composition and mixing matrix:
$$ \phi_{\alpha,\oplus}=\sum_{i,\beta} \mid{U_{\alpha i}}\mid^2\mid{U_{\beta i}}\mid^2\phi_{\beta,\text{S}} $$
So here we must sample over the source flavor compositions to see which agrees best with the data. However, we must also take into account that the values of the mixing matrix are perfect and have uncertainties of their own.
### Nuisance Parameters
Not all parameters of a model are of direct inferential interest, however they still need to be included as they may reduce the effect of systematic bias. These are called *nuisance parameters*. Here the mixing matrix parameters are examples of such nuisance parameters and we must include the effect of their uncertainties in our inference of the source flavor composition.
#### Anarchic Sampling
In the same way that flavor compositions cannot directly be sampled over, the mixing matrix values also cannot directly be sampled (it's also **extremely** inefficient to brute force sample values in a matrix such that the resulting matrix is unitary). As with any Bayesian inference, the prior distribution needs to be chosen carefully. Firstly we can rewrite the $3\times3$ unitary mixing matrix in terms of *mixing angles*. The following is the standard representation most commonly used:
$$
\begin{align}
U=
\begin{pmatrix}
1 & 0 & 0 \\
0 & c_{23} & s_{23} \\
0 & -s_{23} & c_{23} \\
\end{pmatrix}
\begin{pmatrix}
c_{13} & 0 & s_{13}e^{-i\delta} \\
0 & 1 & 0 \\
-s_{13}e^{i\delta} & 0 &c_{13} \\
\end{pmatrix}
\begin{pmatrix}
c_{12} & s_{12} & 0 \\
-s_{12} & c_{12} & 0 \\
0 & 0 & 1 \\
\end{pmatrix}
\end{align}
$$
where $s_{ij}\equiv\sin\theta_{ij}$, $c_{ij}\equiv\cos\theta_{ij}$, $\theta_{ij}$ are the three mixing angles and $\delta$ is the CP violating phase. Overall phases in the mixing matrix do not affect neutrino oscillations, which only depend on quartic products, and so they have been omitted.
Now we have an efficient way of generating $3\times3$ unitary matrices we can focus on how to define the prior space which we sample from. As we did for the flavor angles, we must do so under the integration invariant [*Haar measure*](https://doi.org/10.1016/j.physletb.2003.08.045). For the group $U(3)$, the Haar measure is given by the volume element $\text{d}U$, which can be written in terms of the above mixing angles:
$$
\begin{align}
\text{d} U=\text{d}\left(\sin^2\theta_{12}\right)\wedge\,
\text{d}\left(\cos^4\theta_{13}\right)\wedge\,
\text{d}\left(\sin^2\theta_{23}\right)\wedge\,\text{d}\delta
\end{align}
$$
which says that the Haar measure for the group $U(3)$ is flat in $\sin^2\theta_{12}$, $\cos^4\theta_{13}$, $\sin^2\theta_{23}$ and $\delta$. Therefore, in order to ensure the distribution over the mixing matrix $U$ is unbiased, the prior space of the mixing angles must be chosen according to this Haar measure, i.e. in $\sin^2\theta_{12}$, $\cos^4\theta_{13}$, $\sin^2\theta_{23}$ and $\delta$.
Of course, GolemFlavor provides the handy function to be able to do this conversion `angles_to_u`.
```python
from golemflavor.fr import angles_to_u
help(angles_to_u)
```
Help on function angles_to_u in module golemflavor.fr:
angles_to_u(bsm_angles)
Convert angular projection of the mixing matrix elements back into the
mixing matrix elements.
Parameters
----------
bsm_angles : list, length = 4
sin(12)^2, cos(13)^4, sin(23)^2 and deltacp
Returns
----------
unitary numpy ndarray of shape (3, 3)
Examples
----------
>>> from fr import angles_to_u
>>> print(angles_to_u((0.2, 0.3, 0.5, 1.5)))
array([[ 0.66195018+0.j , 0.33097509+0.j , 0.04757188-0.6708311j ],
[-0.34631487-0.42427084j, 0.61741198-0.21213542j, 0.52331757+0.j ],
[ 0.28614067-0.42427084j, -0.64749908-0.21213542j, 0.52331757+0.j ]])
#### Gaussian Priors
The [global fit to world neutrino data](<https://doi.org/10.1007/JHEP01(2017)087>) includes estimates of the uncertainty of each mixing angle. These uncertainties can be included as an extra Gaussian prior in our likelihood by specifying the `prior` keyword when defining the `Param`, with the `std` keyword being the one standard deviation from the central value.
```python
from golemflavor.enums import PriorsCateg
# Params can be tagged for later convenience
tag = ParamTag.SM_ANGLES
# Include with a Limited Gaussian prior, which is a Gaussian adjusted for boundaries defined by `ranges`
lg_prior = PriorsCateg.LIMITEDGAUSS
# Define the nuisance `Param` objects containing information such as name, value, ranges, prior and std.
nuisance = [
Param(name='s_12_2', value=0.307, seed=[0.26, 0.35], ranges=[0., 1.], std=0.013, tex=r's_{12}^2', prior=lg_prior, tag=tag),
Param(name='c_13_4', value=(1-(0.02206))**2, seed=[0.950, 0.961], ranges=[0., 1.], std=0.00147, tex=r'c_{13}^4', prior=lg_prior, tag=tag),
Param(name='s_23_2', value=0.538, seed=[0.31, 0.75], ranges=[0., 1.], std=0.069, tex=r's_{23}^2', prior=lg_prior, tag=tag),
Param(name='dcp', value=4.08404, seed=[0, 2*np.pi], ranges=[0., 2*np.pi], std=2.0, tex=r'\delta_{CP}', tag=tag),
]
# Define the source flavor angles `Param` objects
tag = ParamTag.SRCANGLES
src_compositions = [
Param(name='source_angle1', value=0, ranges=[ 0., 1.], tag=tag, tex=r'\sin^4\phi_S'),
Param(name='source_angle2', value=0, ranges=[-1., 1.], tag=tag, tex=r'\cos(2\psi_S)')
]
# Define the llh `ParamSet`, containing the nuisance parameters plus our parameter of interest
llh_paramset = ParamSet(nuisance + src_compositions)
```
As a reminder, we have 2 `ParamSet` objects:
* `asimov_paramset` contains the measured parameters
* `llh_paramset` contains the model parameter values
## Markov Chain Monte Carlo
Now, we wrap our physics model along with the `multi_gaussian` likelihood into a function that accepts input parameters `theta` from the MCMC:
```python
from golemflavor.fr import angles_to_fr
from golemflavor.llh import multi_gaussian
def triangle_llh(theta, asimov_paramset, llh_paramset):
"""Log likelihood function for a given theta."""
if len(theta) != len(llh_paramset):
raise AssertionError(
'Length of MCMC scan is not the same as the input '
'params\ntheta={0}\nparamset]{1}'.format(theta, llh_paramset)
)
# Set llh_parameters values to the sampled parameters
for idx, param in enumerate(llh_paramset):
param.value = theta[idx]
# Convert sampled mixing angles to a mixing matrix
sm_angles = llh_paramset.from_tag(ParamTag.SM_ANGLES, values=True)
sm_u = angles_to_u(sm_angles)
# Convert flavor angles to flavor compositions for the model parameters
source_angles = llh_paramset.from_tag(ParamTag.SRCANGLES, values=True)
source_composition = angles_to_fr(source_angles)
# Calculate the expected measured flavor composition for our sampled values
measured_composition = u_to_fr(source_composition, sm_u)
# Convert flavor angles to flavor compositions for the injected parameters
bestfit_measured_comp = angles_to_fr(asimov_paramset.from_tag(ParamTag.BESTFIT, values=True))
# Get the value of `smearing`
smearing = asimov_paramset['measured_angle1'].std
# Calculate the log likelihood using `multi_gaussian`
llh = multi_gaussian(measured_composition, bestfit_measured_comp, smearing)
return llh
```
Running without GolemFit
Last thing we need to setup is our prior distribution, which in this case includes both the bounds on our model parameters, as well as the extra priors for the mixing angle parameters. As we have defined this already in the `ParamSet` object using the `prior`, `std` and `ranges` keyword, we can use the GolemFlavor function `lnprior` to do the work for us:
```python
from golemflavor.llh import lnprior
def ln_prob(theta, asimov_paramset, llh_paramset):
"""Posterior function for a given theta."""
# Get the value of the log prior (prior from mixing matrix Params is calculated here)
lp = lnprior(theta, paramset=llh_paramset)
if not np.isfinite(lp):
return -np.inf
# Return the log prior + log likelihood
return lp + triangle_llh(theta, asimov_paramset, llh_paramset)
# Evalaute the posterior using the defined `asimov_paramset` and `llh_paramset`
ln_prob_eval = partial(
ln_prob,
asimov_paramset=asimov_paramset,
llh_paramset=llh_paramset
)
```
```python
import golemflavor.mcmc as mcmc_utils
# Reduce these values for a quicker runtime
nwalkers = 60
burnin = 1000
nsteps = 10000
# Generate initial seed using a flat distribution
p0 = mcmc_utils.flat_seed(
llh_paramset, nwalkers=nwalkers
)
# Run the MCMC!
# Progress bar provided by tqdm (this took about 30mins on my laptop)
samples = mcmc_utils.mcmc(
p0 = p0,
ln_prob = ln_prob_eval,
ndim = len(llh_paramset),
nwalkers = nwalkers,
burnin = burnin,
nsteps = nsteps,
threads = 4
)
```
Running burn-in
HBox(children=(FloatProgress(value=0.0, max=1000.0), HTML(value='')))
Finished burn-in
Running
HBox(children=(FloatProgress(value=0.0, max=10000.0), HTML(value='')))
Finished
acceptance fraction [0.4288 0.4305 0.4342 0.4181 0.4278 0.4304 0.4294 0.4315 0.4169 0.4133
0.428 0.4408 0.4145 0.4163 0.4364 0.4226 0.4222 0.4071 0.4179 0.4299
0.4419 0.4208 0.431 0.418 0.4301 0.4332 0.4291 0.415 0.4194 0.431
0.4299 0.4429 0.4419 0.4216 0.4281 0.4245 0.4136 0.4278 0.4275 0.4275
0.4167 0.4266 0.4308 0.4174 0.4339 0.4245 0.4331 0.4383 0.4129 0.4408
0.4221 0.4331 0.4229 0.4316 0.428 0.4263 0.433 0.4309 0.4136 0.4331]
sum of acceptance fraction 25.601
np.unique(samples[:,0]).shape (256044,)
autocorrelation [ 84.76795567 90.34226183 101.72273776 124.98444783 103.45178419
101.3873447 ]
## Visualization
One of the great advantages of Bayesian inferences is the access we have to the full posterior distributions. We can visualize the relationships between our model parameters by plotting the joint posterior distributions, as is done here using the [getdist package](https://getdist.readthedocs.io/en/latest/).
```python
import golemflavor.plot as plot_utils
# getdist package requires `%matplotlib inline` to come after the import for inline notebook figures.
%matplotlib inline
plot_utils.plot_Tchain(samples, llh_paramset.labels, llh_paramset.ranges, llh_paramset.names)
plt.show()
```
Here, the non-diagonal plots show joint distributions between two parameters, labelled on the x- and y-axis and the diagonal plots show the marginalised distributions for each parameter, as labelled on the x-axis. The blue (light blue) shows the 90% (99%) credibility intervals.
As we did in the previous example, we can also see how this looks in a ternary plot.
```python
source_angles = samples[:,-2:]
source_compositions = np.array(
list(map(angles_to_fr, source_angles))
)
```
```python
nbins = 25
fontsize = 23
# Figure
fig = plt.figure(figsize=(12, 12))
# Axis
ax = fig.add_subplot(111)
ax_labels = [
r'$\nu_e\:\:{\rm fraction}\:\left( f_{e,S}\right)$',
r'$\nu_\mu\:\:{\rm fraction}\:\left( f_{\mu,S}\right)$',
r'$\nu_\tau\:\:{\rm fraction}\:\left( f_{\tau,S}\right)$'
]
tax = plot_utils.get_tax(ax, scale=nbins, ax_labels=ax_labels, rot_ax_labels=True)
# Plot source composition posteriors
coverages = [(99, 'cornflowerblue'), (90, 'royalblue')]
for cov, color in coverages:
plot_utils.flavor_contour(
frs=source_compositions,
fill=True,
ax=ax,
nbins=nbins,
coverage=cov,
linewidth=2.5,
color=color,
alpha=0.7,
oversample=5
)
plt.show()
```
Great! Looks like our inference of the source flavor composition reflects the injected value $(1:0:0)_S$. Here, the credbility regions include the effect of smearing as well as our uncertainity about the values of the mixing matrix, which is why the values are not exactly at the injected $(1:0:0)_S$ value.
In a real analysis, an ensemble of nuisance parameters is usually required, related to uncertainties arising from things such as the astrophysical flux, detector calibration and backgrounds from atmospherically produced neutrinos. All these effects come into play when making inferences and careful analysis must be done for each in order to minimize potential biases.
|
#__precompile__()
module S3Dicts
using JSON
using AWSCore
#using AWSSDK.S3
using AWSS3
#using Retry
import HTTP
import BigArrays.BackendBase: AbstractBigArrayBackend, get_info, get_scale_name
global const NEUROGLANCER_CONFIG_FILENAME = "info"
global const CONTENT_TYPE = "binary/octet-stream"
global const GZIP_MAGIC_NUMBER = UInt8[0x1f, 0x8b, 0x08]
if haskey(ENV, "AWS_ACCESS_KEY_ID")
global AWS_CREDENTIAL = AWSCore.aws_config()
elseif isfile("/secrets/aws-secret.json")
d = JSON.parsefile("/secrets/aws-secret.json")
global AWS_CREDENTIAL = AWSCore.aws_config(creds=AWSCredentials(d["AWS_ACCESS_KEY_ID"], d["AWS_SECRET_ACCESS_KEY"]))
else
@warn("did not find AWS credential! set it in environment variables.")
end
export S3Dict
struct S3Dict <: AbstractBigArrayBackend
bkt ::String
keyPrefix ::String
end
"""
S3Dict( dir::String )
construct S3Dict from a directory path of s3
"""
function S3Dict( path::String )
@assert startswith(path, "s3://")
path = replace(path, "s3://" => "")
bkt, keyPrefix = split(path, "/", limit = 2)
keyPrefix = rstrip(keyPrefix, '/')
S3Dict(bkt, keyPrefix)
end
function get_info(self::S3Dict)
#data = S3.get_object(AWS_CREDENTIAL; Bucket=self.bkt,
# Key=joinpath(dirname(self.keyPrefix), "info"))
data = s3_get(AWS_CREDENTIAL, self.bkt, joinpath(dirname(self.keyPrefix), "info"))
return String(data)
end
function get_scale_name(self::S3Dict) basename( self.keyPrefix ) end
function Base.show( self::S3Dict ) show( joinpath(self.bkt, self.keyPrefix) ) end
function Base.setindex!(h::S3Dict, v::Array, key::AbstractString)
#@assert startswith(h.dir, "s3://")
data = reinterpret(UInt8, v[:]) |> Array
local contentEncoding::String
if all(data[1:3].== GZIP_MAGIC_NUMBER)
contentEncoding = "gzip"
else
contentEncoding = ""
end
#arguments = Dict("Bucket" => h.bkt,
# "Key" => joinpath(h.keyPrefix, key),
# "Body" => data,
# "Content-Type" => CONTENT_TYPE,
# "Content-Encoding" => contentEncoding)
#@show arguments
#resp = S3.put_object(AWS_CREDENTIAL, arguments)
resp = s3_put(AWS_CREDENTIAL, h.bkt, joinpath(h.keyPrefix, key), data;
metadata = Dict("Content-Type" => CONTENT_TYPE,
"Content-Encoding" => contentEncoding))
nothing
end
function Base.getindex(h::S3Dict, key::AbstractString)
try
#data = S3.get_object(AWS_CREDENTIAL;
# Bucket=h.bkt,
# Key=joinpath(h.keyPrefix, key))
data = s3_get(AWS_CREDENTIAL, h.bkt, joinpath(h.keyPrefix, key))
return data
catch err
@show err
if isa(err, AWSCore.AWSException) && err.code == "NoSuchKey"
throw(KeyError("NoSuchKey in AWS S3: $key"))
elseif isa(err, HTTP.ClosedError)
display(err.e)
rethrow()
else
rethrow()
end
end
nothing
end
function Base.delete!( h::S3Dict, key::AbstractString)
#S3.delete_object(AWS_CREDENTIAL; Bucket=h.bkt, Key=joinpath(h.keyPrefix, key))
s3_delete(AWS_CREDENTIAL, h.bkt, joinpath(h.keyPrefix, key))
end
function Base.keys( h::S3Dict )
#S3.list_objects_v2(AWS_CREDENTIAL; Bucket=h.bkt, prefix=h.keyPrefix)
s3_list_objects(AWS_CREDENTIAL, h.bkt, h.keyPrefix)
end
function Base.values(h::S3Dict)
error("normally values are too large to get them all to RAM")
end
function Base.haskey(h::S3Dict, key::String)
#resp = S3.list_objects_v2(AWS_CREDENTIAL; Bucket=h.bkt, prefix=joinpath(h.keyPrefix, key))
#return Meta.parse( resp["KeyCount"] ) > 0
s3_exists(AWS_CREDENTIAL, h.bkt, joinpath(h.keyPrefix, key))
end
end # end of module S3Dicts
|
(*
Author: Norbert Schirmer
Maintainer: Norbert Schirmer, norbert.schirmer at web de
License: LGPL
*)
(* Title: Compose.thy
Author: Norbert Schirmer, TU Muenchen
Copyright (C) 2006-2008 Norbert Schirmer
Some rights reserved, TU Muenchen
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of the
License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA
*)
section "Experiments on State Composition"
theory Compose imports "../HoareTotalProps" begin
text \<open>
We develop some theory to support state-space modular development of programs.
These experiments aim at the representation of state-spaces with records.
If we use \<open>statespaces\<close> instead we get this kind of compositionality for free.
\<close>
subsection \<open>Changing the State-Space\<close>
(* Lift a command on statespace 'b to work on statespace 'a *)
definition lift\<^sub>f:: "('S \<Rightarrow> 's) \<Rightarrow> ('S \<Rightarrow> 's \<Rightarrow> 'S) \<Rightarrow> ('s \<Rightarrow> 's) \<Rightarrow> ('S \<Rightarrow> 'S)"
where "lift\<^sub>f prj inject f = (\<lambda>S. inject S (f (prj S)))"
definition lift\<^sub>s:: "('S \<Rightarrow> 's) \<Rightarrow> 's set \<Rightarrow> 'S set"
where "lift\<^sub>s prj A = {S. prj S \<in> A}"
definition lift\<^sub>r:: "('S \<Rightarrow> 's) \<Rightarrow> ('S \<Rightarrow> 's \<Rightarrow> 'S) \<Rightarrow> ('s \<times> 's) set
\<Rightarrow> ('S \<times> 'S) set"
where
"lift\<^sub>r prj inject R = {(S,T). (prj S,prj T) \<in> R \<and> T=inject S (prj T)}"
primrec lift\<^sub>c:: "('S \<Rightarrow> 's) \<Rightarrow> ('S \<Rightarrow> 's \<Rightarrow> 'S) \<Rightarrow> ('s,'p,'f) com \<Rightarrow> ('S,'p,'f) com"
where
"lift\<^sub>c prj inject Skip = Skip" |
"lift\<^sub>c prj inject (Basic f) = Basic (lift\<^sub>f prj inject f)" |
"lift\<^sub>c prj inject (Spec r) = Spec (lift\<^sub>r prj inject r)" |
"lift\<^sub>c prj inject (Seq c\<^sub>1 c\<^sub>2) =
(Seq (lift\<^sub>c prj inject c\<^sub>1) (lift\<^sub>c prj inject c\<^sub>2))" |
"lift\<^sub>c prj inject (Cond b c\<^sub>1 c\<^sub>2) =
Cond (lift\<^sub>s prj b) (lift\<^sub>c prj inject c\<^sub>1) (lift\<^sub>c prj inject c\<^sub>2)" |
"lift\<^sub>c prj inject (While b c) =
While (lift\<^sub>s prj b) (lift\<^sub>c prj inject c)" |
"lift\<^sub>c prj inject (Call p) = Call p" |
"lift\<^sub>c prj inject (DynCom c) = DynCom (\<lambda>s. lift\<^sub>c prj inject (c (prj s)))" |
"lift\<^sub>c prj inject (Guard f g c) = Guard f (lift\<^sub>s prj g) (lift\<^sub>c prj inject c)" |
"lift\<^sub>c prj inject Throw = Throw" |
"lift\<^sub>c prj inject (Catch c\<^sub>1 c\<^sub>2) =
Catch (lift\<^sub>c prj inject c\<^sub>1) (lift\<^sub>c prj inject c\<^sub>2)"
lemma lift\<^sub>c_Skip: "(lift\<^sub>c prj inject c = Skip) = (c = Skip)"
by (cases c) auto
lemma lift\<^sub>c_Basic:
"(lift\<^sub>c prj inject c = Basic lf) = (\<exists>f. c = Basic f \<and> lf = lift\<^sub>f prj inject f)"
by (cases c) auto
lemma lift\<^sub>c_Spec:
"(lift\<^sub>c prj inject c = Spec lr) = (\<exists>r. c = Spec r \<and> lr = lift\<^sub>r prj inject r)"
by (cases c) auto
lemma lift\<^sub>c_Seq:
"(lift\<^sub>c prj inject c = Seq lc\<^sub>1 lc\<^sub>2) =
(\<exists> c\<^sub>1 c\<^sub>2. c = Seq c\<^sub>1 c\<^sub>2 \<and>
lc\<^sub>1 = lift\<^sub>c prj inject c\<^sub>1 \<and> lc\<^sub>2 = lift\<^sub>c prj inject c\<^sub>2 )"
by (cases c) auto
lemma lift\<^sub>c_Cond:
"(lift\<^sub>c prj inject c = Cond lb lc\<^sub>1 lc\<^sub>2) =
(\<exists>b c\<^sub>1 c\<^sub>2. c = Cond b c\<^sub>1 c\<^sub>2 \<and> lb = lift\<^sub>s prj b \<and>
lc\<^sub>1 = lift\<^sub>c prj inject c\<^sub>1 \<and> lc\<^sub>2 = lift\<^sub>c prj inject c\<^sub>2 )"
by (cases c) auto
lemma lift\<^sub>c_While:
"(lift\<^sub>c prj inject c = While lb lc') =
(\<exists>b c'. c = While b c' \<and> lb = lift\<^sub>s prj b \<and>
lc' = lift\<^sub>c prj inject c')"
by (cases c) auto
lemma lift\<^sub>c_Call:
"(lift\<^sub>c prj inject c = Call p) = (c = Call p)"
by (cases c) auto
lemma lift\<^sub>c_DynCom:
"(lift\<^sub>c prj inject c = DynCom lc) =
(\<exists>C. c=DynCom C \<and> lc = (\<lambda>s. lift\<^sub>c prj inject (C (prj s))))"
by (cases c) auto
lemma lift\<^sub>c_Guard:
"(lift\<^sub>c prj inject c = Guard f lg lc') =
(\<exists>g c'. c = Guard f g c' \<and> lg = lift\<^sub>s prj g \<and>
lc' = lift\<^sub>c prj inject c')"
by (cases c) auto
lemma lift\<^sub>c_Throw:
"(lift\<^sub>c prj inject c = Throw) = (c = Throw)"
by (cases c) auto
lemma lift\<^sub>c_Catch:
"(lift\<^sub>c prj inject c = Catch lc\<^sub>1 lc\<^sub>2) =
(\<exists> c\<^sub>1 c\<^sub>2. c = Catch c\<^sub>1 c\<^sub>2 \<and>
lc\<^sub>1 = lift\<^sub>c prj inject c\<^sub>1 \<and> lc\<^sub>2 = lift\<^sub>c prj inject c\<^sub>2 )"
by (cases c) auto
definition xstate_map:: "('S \<Rightarrow> 's) \<Rightarrow> ('S,'f) xstate \<Rightarrow> ('s,'f) xstate"
where
"xstate_map g x = (case x of
Normal s \<Rightarrow> Normal (g s)
| Abrupt s \<Rightarrow> Abrupt (g s)
| Fault f \<Rightarrow> Fault f
| Stuck \<Rightarrow> Stuck)"
lemma xstate_map_simps [simp]:
"xstate_map g (Normal s) = Normal (g s)"
"xstate_map g (Abrupt s) = Abrupt (g s)"
"xstate_map g (Fault f) = (Fault f)"
"xstate_map g Stuck = Stuck"
by (auto simp add: xstate_map_def)
lemma xstate_map_Normal_conv:
"xstate_map g S = Normal s = (\<exists>s'. S=Normal s' \<and> s = g s')"
by (cases S) auto
lemma xstate_map_Abrupt_conv:
"xstate_map g S = Abrupt s = (\<exists>s'. S=Abrupt s' \<and> s = g s')"
by (cases S) auto
lemma xstate_map_Fault_conv:
"xstate_map g S = Fault f = (S=Fault f)"
by (cases S) auto
lemma xstate_map_Stuck_conv:
"xstate_map g S = Stuck = (S=Stuck)"
by (cases S) auto
lemmas xstate_map_convs = xstate_map_Normal_conv xstate_map_Abrupt_conv
xstate_map_Fault_conv xstate_map_Stuck_conv
definition state:: "('s,'f) xstate \<Rightarrow> 's"
where
"state x = (case x of
Normal s \<Rightarrow> s
| Abrupt s \<Rightarrow> s
| Fault g \<Rightarrow> undefined
| Stuck \<Rightarrow> undefined)"
lemma state_simps [simp]:
"state (Normal s) = s"
"state (Abrupt s) = s"
by (auto simp add: state_def )
locale lift_state_space =
fixes project::"'S \<Rightarrow> 's"
fixes "inject"::"'S \<Rightarrow> 's \<Rightarrow> 'S"
fixes "project\<^sub>x"::"('S,'f) xstate \<Rightarrow> ('s,'f) xstate"
fixes "lift\<^sub>e"::"('s,'p,'f) body \<Rightarrow> ('S,'p,'f) body"
fixes lift\<^sub>c:: "('s,'p,'f) com \<Rightarrow> ('S,'p,'f) com"
fixes lift\<^sub>f:: "('s \<Rightarrow> 's) \<Rightarrow> ('S \<Rightarrow> 'S)"
fixes lift\<^sub>s:: "'s set \<Rightarrow> 'S set"
fixes lift\<^sub>r:: "('s \<times> 's) set \<Rightarrow> ('S \<times> 'S) set"
assumes proj_inj_commute: "\<And>S s. project (inject S s) = s"
defines "lift\<^sub>c \<equiv> Compose.lift\<^sub>c project inject"
defines "project\<^sub>x \<equiv> xstate_map project"
defines "lift\<^sub>e \<equiv> (\<lambda>\<Gamma> p. map_option lift\<^sub>c (\<Gamma> p))"
defines "lift\<^sub>f \<equiv> Compose.lift\<^sub>f project inject"
defines "lift\<^sub>s \<equiv> Compose.lift\<^sub>s project"
defines "lift\<^sub>r \<equiv> Compose.lift\<^sub>r project inject"
lemma (in lift_state_space) lift\<^sub>f_simp:
"lift\<^sub>f f \<equiv> \<lambda>S. inject S (f (project S))"
by (simp add: lift\<^sub>f_def Compose.lift\<^sub>f_def)
lemma (in lift_state_space) lift\<^sub>s_simp:
"lift\<^sub>s A \<equiv> {S. project S \<in> A}"
by (simp add: lift\<^sub>s_def Compose.lift\<^sub>s_def)
lemma (in lift_state_space) lift\<^sub>r_simp:
"lift\<^sub>r R \<equiv> {(S,T). (project S,project T) \<in> R \<and> T=inject S (project T)}"
by (simp add: lift\<^sub>r_def Compose.lift\<^sub>r_def)
(* Causes loop when instantiating locale
lemmas (in lift_state_space) lift\<^sub>f_simp = Compose.lift\<^sub>f_def
[of project "inject", folded lift\<^sub>f_def]
lemmas (in lift_state_space) lift\<^sub>s_simp = Compose.lift\<^sub>s_def
[of project, folded lift\<^sub>s_def]
lemmas (in lift_state_space) lift\<^sub>r_simp = Compose.lift\<^sub>r_def
[of project "inject", folded lift\<^sub>r_def]
*)
lemma (in lift_state_space) lift\<^sub>c_Skip_simp [simp]:
"lift\<^sub>c Skip = Skip"
by (simp add: lift\<^sub>c_def)
lemma (in lift_state_space) lift\<^sub>c_Basic_simp [simp]:
"lift\<^sub>c (Basic f) = Basic (lift\<^sub>f f)"
by (simp add: lift\<^sub>c_def lift\<^sub>f_def)
lemma (in lift_state_space) lift\<^sub>c_Spec_simp [simp]:
"lift\<^sub>c (Spec r) = Spec (lift\<^sub>r r)"
by (simp add: lift\<^sub>c_def lift\<^sub>r_def)
lemma (in lift_state_space) lift\<^sub>c_Seq_simp [simp]:
"lift\<^sub>c (Seq c\<^sub>1 c\<^sub>2) =
(Seq (lift\<^sub>c c\<^sub>1) (lift\<^sub>c c\<^sub>2))"
by (simp add: lift\<^sub>c_def)
lemma (in lift_state_space) lift\<^sub>c_Cond_simp [simp]:
"lift\<^sub>c (Cond b c\<^sub>1 c\<^sub>2) =
Cond (lift\<^sub>s b) (lift\<^sub>c c\<^sub>1) (lift\<^sub>c c\<^sub>2)"
by (simp add: lift\<^sub>c_def lift\<^sub>s_def)
lemma (in lift_state_space) lift\<^sub>c_While_simp [simp]:
"lift\<^sub>c (While b c) =
While (lift\<^sub>s b) (lift\<^sub>c c)"
by (simp add: lift\<^sub>c_def lift\<^sub>s_def)
lemma (in lift_state_space) lift\<^sub>c_Call_simp [simp]:
"lift\<^sub>c (Call p) = Call p"
by (simp add: lift\<^sub>c_def)
lemma (in lift_state_space) lift\<^sub>c_DynCom_simp [simp]:
"lift\<^sub>c (DynCom c) = DynCom (\<lambda>s. lift\<^sub>c (c (project s)))"
by (simp add: lift\<^sub>c_def)
lemma (in lift_state_space) lift\<^sub>c_Guard_simp [simp]:
"lift\<^sub>c (Guard f g c) = Guard f (lift\<^sub>s g) (lift\<^sub>c c)"
by (simp add: lift\<^sub>c_def lift\<^sub>s_def)
lemma (in lift_state_space) lift\<^sub>c_Throw_simp [simp]:
"lift\<^sub>c Throw = Throw"
by (simp add: lift\<^sub>c_def)
lemma (in lift_state_space) lift\<^sub>c_Catch_simp [simp]:
"lift\<^sub>c (Catch c\<^sub>1 c\<^sub>2) =
Catch (lift\<^sub>c c\<^sub>1) (lift\<^sub>c c\<^sub>2)"
by (simp add: lift\<^sub>c_def)
lemma (in lift_state_space) project\<^sub>x_def':
"project\<^sub>x s \<equiv> (case s of
Normal s \<Rightarrow> Normal (project s)
| Abrupt s \<Rightarrow> Abrupt (project s)
| Fault f \<Rightarrow> Fault f
| Stuck \<Rightarrow> Stuck)"
by (simp add: xstate_map_def project\<^sub>x_def)
lemma (in lift_state_space) lift\<^sub>e_def':
"lift\<^sub>e \<Gamma> p \<equiv> (case \<Gamma> p of Some bdy \<Rightarrow> Some (lift\<^sub>c bdy) | None \<Rightarrow> None)"
by (simp add: lift\<^sub>e_def map_option_case)
text \<open>
The problem is that @{term "(lift\<^sub>c project inject \<circ> \<Gamma>)"} is quite
a strong premise. The problem is that @{term "\<Gamma>"} is a function here.
A map would be better. We only have to lift those procedures in the domain
of @{term "\<Gamma>"}:
\<open>\<Gamma> p = Some bdy \<longrightarrow> \<Gamma>' p = Some lift\<^sub>c project inject bdy\<close>.
We then can com up with theorems that allow us to extend the domains
of @{term \<Gamma>} and preserve validity.
\<close>
lemma (in lift_state_space)
"{(S,T). \<exists>t. (project S,t) \<in> r \<and> T=inject S t}
\<subseteq> {(S,T). (project S,project T) \<in> r \<and> T=inject S (project T)}"
apply clarsimp
apply (rename_tac S t)
apply (simp add: proj_inj_commute)
done
lemma (in lift_state_space)
"{(S,T). (project S,project T) \<in> r \<and> T=inject S (project T)}
\<subseteq> {(S,T). \<exists>t. (project S,t) \<in> r \<and> T=inject S t}"
apply clarsimp
apply (rename_tac S T)
apply (rule_tac x="project T" in exI)
apply simp
done
lemma (in lift_state_space) lift_exec:
assumes exec_lc: "(lift\<^sub>e \<Gamma>)\<turnstile>\<langle>lc,s\<rangle> \<Rightarrow> t"
shows "\<And>c. \<lbrakk> lift\<^sub>c c = lc\<rbrakk> \<Longrightarrow>
\<Gamma>\<turnstile>\<langle>c,project\<^sub>x s\<rangle> \<Rightarrow> project\<^sub>x t"
using exec_lc
proof (induct)
case Skip thus ?case
by (auto simp add: project\<^sub>x_def lift\<^sub>c_Skip lift\<^sub>c_def intro: exec.Skip)
next
case Guard thus ?case
by (auto simp add: project\<^sub>x_def lift\<^sub>s_def Compose.lift\<^sub>s_def lift\<^sub>c_Guard lift\<^sub>c_def
intro: exec.Guard)
next
case GuardFault thus ?case
by (auto simp add: project\<^sub>x_def lift\<^sub>s_def Compose.lift\<^sub>s_def lift\<^sub>c_Guard lift\<^sub>c_def
intro: exec.GuardFault)
next
case FaultProp thus ?case
by (fastforce simp add: project\<^sub>x_def)
next
case Basic
thus ?case
by (fastforce simp add: project\<^sub>x_def lift\<^sub>c_Basic lift\<^sub>f_def Compose.lift\<^sub>f_def
lift\<^sub>c_def
proj_inj_commute
intro: exec.Basic)
next
case Spec
thus ?case
by (fastforce simp add: project\<^sub>x_def lift\<^sub>c_Spec lift\<^sub>f_def Compose.lift\<^sub>f_def
lift\<^sub>r_def Compose.lift\<^sub>r_def lift\<^sub>c_def
proj_inj_commute
intro: exec.Spec)
next
case (SpecStuck s r)
thus ?case
apply (simp add: project\<^sub>x_def)
apply (clarsimp simp add: lift\<^sub>c_Spec lift\<^sub>c_def)
apply (unfold lift\<^sub>r_def Compose.lift\<^sub>r_def)
apply (rule exec.SpecStuck)
apply (rule allI)
apply (erule_tac x="inject s t" in allE)
apply clarsimp
apply (simp add: proj_inj_commute)
done
next
case Seq
thus ?case
by (fastforce simp add: project\<^sub>x_def lift\<^sub>c_Seq lift\<^sub>c_def intro: exec.intros)
next
case CondTrue
thus ?case
by (auto simp add: project\<^sub>x_def lift\<^sub>s_def Compose.lift\<^sub>s_def lift\<^sub>c_Cond lift\<^sub>c_def
intro: exec.CondTrue)
next
case CondFalse
thus ?case
by (auto simp add: project\<^sub>x_def lift\<^sub>s_def Compose.lift\<^sub>s_def lift\<^sub>c_Cond lift\<^sub>c_def
intro: exec.CondFalse)
next
case WhileTrue
thus ?case
by (fastforce simp add: project\<^sub>x_def lift\<^sub>s_def Compose.lift\<^sub>s_def
lift\<^sub>c_While lift\<^sub>c_def
intro: exec.WhileTrue)
next
case WhileFalse
thus ?case
by (fastforce simp add: project\<^sub>x_def lift\<^sub>s_def Compose.lift\<^sub>s_def
lift\<^sub>c_While lift\<^sub>c_def
intro: exec.WhileFalse)
next
case Call
thus ?case
by (fastforce simp add:
project\<^sub>x_def lift\<^sub>c_Call lift\<^sub>f_def Compose.lift\<^sub>f_def lift\<^sub>c_def
lift\<^sub>e_def
intro: exec.Call)
next
case CallUndefined
thus ?case
by (fastforce simp add:
project\<^sub>x_def lift\<^sub>c_Call lift\<^sub>f_def Compose.lift\<^sub>f_def lift\<^sub>c_def
lift\<^sub>e_def
intro: exec.CallUndefined)
next
case StuckProp thus ?case
by (fastforce simp add: project\<^sub>x_def)
next
case DynCom
thus ?case
by (fastforce simp add:
project\<^sub>x_def lift\<^sub>c_DynCom lift\<^sub>f_def Compose.lift\<^sub>f_def lift\<^sub>c_def
intro: exec.DynCom)
next
case Throw thus ?case
by (fastforce simp add: project\<^sub>x_def lift\<^sub>c_Throw lift\<^sub>c_def intro: exec.Throw)
next
case AbruptProp thus ?case
by (fastforce simp add: project\<^sub>x_def)
next
case CatchMatch
thus ?case
by (fastforce simp add: project\<^sub>x_def lift\<^sub>c_Catch lift\<^sub>c_def intro: exec.CatchMatch)
next
case (CatchMiss c\<^sub>1 s t c\<^sub>2 c)
thus ?case
by (cases t)
(fastforce simp add: project\<^sub>x_def lift\<^sub>c_Catch lift\<^sub>c_def intro: exec.CatchMiss)+
qed
lemma (in lift_state_space) lift_exec':
assumes exec_lc: "(lift\<^sub>e \<Gamma>)\<turnstile>\<langle>lift\<^sub>c c,s\<rangle> \<Rightarrow> t"
shows "\<Gamma>\<turnstile>\<langle>c,project\<^sub>x s\<rangle> \<Rightarrow> project\<^sub>x t"
using lift_exec [OF exec_lc]
by simp
lemma (in lift_state_space) lift_valid:
assumes valid: "\<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A"
shows
"(lift\<^sub>e \<Gamma>)\<Turnstile>\<^bsub>/F\<^esub> (lift\<^sub>s P) (lift\<^sub>c c) (lift\<^sub>s Q),(lift\<^sub>s A)"
proof (rule validI)
fix s t
assume lexec:
"(lift\<^sub>e \<Gamma>)\<turnstile>\<langle>lift\<^sub>c c,Normal s\<rangle> \<Rightarrow> t"
assume lP: "s \<in> lift\<^sub>s P"
assume noFault: "t \<notin> Fault ` F"
show "t \<in> Normal ` lift\<^sub>s Q \<union> Abrupt ` lift\<^sub>s A"
proof -
from lexec
have "\<Gamma>\<turnstile> \<langle>c,project\<^sub>x (Normal s)\<rangle> \<Rightarrow> (project\<^sub>x t)"
by (rule lift_exec) (simp_all)
moreover
from lP have "project s \<in> P"
by (simp add: lift\<^sub>s_def Compose.lift\<^sub>s_def project\<^sub>x_def)
ultimately
have "project\<^sub>x t \<in> Normal ` Q \<union> Abrupt ` A"
using valid noFault
apply (clarsimp simp add: valid_def project\<^sub>x_def)
apply (cases t)
apply auto
done
thus ?thesis
apply (simp add: lift\<^sub>s_def Compose.lift\<^sub>s_def)
apply (cases t)
apply (auto simp add: project\<^sub>x_def)
done
qed
qed
lemma (in lift_state_space) lift_hoarep:
assumes deriv: "\<Gamma>,{}\<turnstile>\<^bsub>/F\<^esub> P c Q,A"
shows
"(lift\<^sub>e \<Gamma>),{}\<turnstile>\<^bsub>/F\<^esub> (lift\<^sub>s P) (lift\<^sub>c c) (lift\<^sub>s Q),(lift\<^sub>s A)"
apply (rule hoare_complete)
apply (insert hoare_sound [OF deriv])
apply (rule lift_valid)
apply (simp add: cvalid_def)
done
lemma (in lift_state_space) lift_hoarep':
"\<forall>Z. \<Gamma>,{}\<turnstile>\<^bsub>/F\<^esub> (P Z) c (Q Z),(A Z) \<Longrightarrow>
\<forall>Z. (lift\<^sub>e \<Gamma>),{}\<turnstile>\<^bsub>/F\<^esub> (lift\<^sub>s (P Z)) (lift\<^sub>c c)
(lift\<^sub>s (Q Z)),(lift\<^sub>s (A Z))"
apply (iprover intro: lift_hoarep)
done
lemma (in lift_state_space) lift_termination:
assumes termi: "\<Gamma>\<turnstile>c\<down>s"
shows "\<And>S. project\<^sub>x S = s \<Longrightarrow>
lift\<^sub>e \<Gamma> \<turnstile>(lift\<^sub>c c)\<down>S"
using termi
proof (induct)
case Skip thus ?case
by (clarsimp simp add: terminates.Skip project\<^sub>x_def xstate_map_convs)
next
case Basic thus ?case
by (fastforce simp add: project\<^sub>x_def xstate_map_convs intro: terminates.intros)
next
case Spec thus ?case
by (fastforce simp add: project\<^sub>x_def xstate_map_convs intro: terminates.intros)
next
case Guard thus ?case
by (auto simp add: project\<^sub>x_def xstate_map_convs intro: terminates.intros)
next
case GuardFault thus ?case
by (auto simp add: project\<^sub>x_def xstate_map_convs lift\<^sub>s_def Compose.lift\<^sub>s_def
intro: terminates.intros)
next
case Fault thus ?case by (clarsimp simp add: project\<^sub>x_def xstate_map_convs)
next
case (Seq c1 s c2)
have "project\<^sub>x S = Normal s" by fact
then obtain s' where S: "S=Normal s'" and s: "s = project s'"
by (auto simp add: project\<^sub>x_def xstate_map_convs)
from Seq have "lift\<^sub>e \<Gamma>\<turnstile>lift\<^sub>c c1 \<down> S"
by simp
moreover
{
fix w
assume exec_lc1: "lift\<^sub>e \<Gamma>\<turnstile>\<langle>lift\<^sub>c c1,Normal s'\<rangle> \<Rightarrow> w"
have "lift\<^sub>e \<Gamma>\<turnstile>lift\<^sub>c c2 \<down> w"
proof (cases w)
case (Normal w')
with lift_exec [where c=c1, OF exec_lc1] s
have "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow> Normal (project w')"
by (simp add: project\<^sub>x_def)
from Seq.hyps (3) [rule_format, OF this] Normal
show "lift\<^sub>e \<Gamma>\<turnstile>lift\<^sub>c c2 \<down> w"
by (auto simp add: project\<^sub>x_def xstate_map_convs)
qed (auto)
}
ultimately show ?case
using S s
by (auto intro: terminates.intros)
next
case CondTrue thus ?case
by (fastforce simp add: project\<^sub>x_def lift\<^sub>s_def Compose.lift\<^sub>s_def xstate_map_convs
intro: terminates.intros)
next
case CondFalse thus ?case
by (fastforce simp add: project\<^sub>x_def lift\<^sub>s_def Compose.lift\<^sub>s_def xstate_map_convs
intro: terminates.intros)
next
case (WhileTrue s b c)
have "project\<^sub>x S = Normal s" by fact
then obtain s' where S: "S=Normal s'" and s: "s = project s'"
by (auto simp add: project\<^sub>x_def xstate_map_convs)
from WhileTrue have "lift\<^sub>e \<Gamma>\<turnstile>lift\<^sub>c c \<down> S"
by simp
moreover
{
fix w
assume exec_lc: "lift\<^sub>e \<Gamma>\<turnstile>\<langle>lift\<^sub>c c,Normal s'\<rangle> \<Rightarrow> w"
have "lift\<^sub>e \<Gamma>\<turnstile>lift\<^sub>c (While b c) \<down> w"
proof (cases w)
case (Normal w')
with lift_exec [where c=c, OF exec_lc] s
have "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> \<Rightarrow> Normal (project w')"
by (simp add: project\<^sub>x_def)
from WhileTrue.hyps (4) [rule_format, OF this] Normal
show "lift\<^sub>e \<Gamma>\<turnstile>lift\<^sub>c (While b c) \<down> w"
by (auto simp add: project\<^sub>x_def xstate_map_convs)
qed (auto)
}
ultimately show ?case
using S s
by (auto intro: terminates.intros)
next
case WhileFalse thus ?case
by (fastforce simp add: project\<^sub>x_def lift\<^sub>s_def Compose.lift\<^sub>s_def xstate_map_convs
intro: terminates.intros)
next
case Call thus ?case
by (fastforce simp add: project\<^sub>x_def xstate_map_convs lift\<^sub>e_def
intro: terminates.intros)
next
case CallUndefined thus ?case
by (fastforce simp add: project\<^sub>x_def xstate_map_convs lift\<^sub>e_def
intro: terminates.intros)
next
case Stuck thus ?case
by (fastforce simp add: project\<^sub>x_def xstate_map_convs)
next
case DynCom thus ?case
by (fastforce simp add: project\<^sub>x_def xstate_map_convs
intro: terminates.intros)
next
case Throw thus ?case
by (fastforce simp add: project\<^sub>x_def xstate_map_convs
intro: terminates.intros)
next
case Abrupt thus ?case
by (fastforce simp add: project\<^sub>x_def xstate_map_convs
intro: terminates.intros)
next
case (Catch c1 s c2)
have "project\<^sub>x S = Normal s" by fact
then obtain s' where S: "S=Normal s'" and s: "s = project s'"
by (auto simp add: project\<^sub>x_def xstate_map_convs)
from Catch have "lift\<^sub>e \<Gamma>\<turnstile>lift\<^sub>c c1 \<down> S"
by simp
moreover
{
fix w
assume exec_lc1: "lift\<^sub>e \<Gamma>\<turnstile>\<langle>lift\<^sub>c c1,Normal s'\<rangle> \<Rightarrow> Abrupt w"
have "lift\<^sub>e \<Gamma>\<turnstile>lift\<^sub>c c2 \<down> Normal w"
proof -
from lift_exec [where c=c1, OF exec_lc1] s
have "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow> Abrupt (project w)"
by (simp add: project\<^sub>x_def)
from Catch.hyps (3) [rule_format, OF this]
show "lift\<^sub>e \<Gamma>\<turnstile>lift\<^sub>c c2 \<down> Normal w"
by (auto simp add: project\<^sub>x_def xstate_map_convs)
qed
}
ultimately show ?case
using S s
by (auto intro: terminates.intros)
qed
lemma (in lift_state_space) lift_termination':
assumes termi: "\<Gamma>\<turnstile>c\<down>project\<^sub>x S"
shows "lift\<^sub>e \<Gamma> \<turnstile>(lift\<^sub>c c)\<down>S"
using lift_termination [OF termi]
by iprover
lemma (in lift_state_space) lift_validt:
assumes valid: "\<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A"
shows "(lift\<^sub>e \<Gamma>)\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> (lift\<^sub>s P) (lift\<^sub>c c) (lift\<^sub>s Q),(lift\<^sub>s A)"
proof -
from valid
have "(lift\<^sub>e \<Gamma>)\<Turnstile>\<^bsub>/F\<^esub> (lift\<^sub>s P) (lift\<^sub>c c) (lift\<^sub>s Q),(lift\<^sub>s A)"
by (auto intro: lift_valid simp add: validt_def)
moreover
{
fix S
assume "S \<in> lift\<^sub>s P"
hence "project S \<in> P"
by (simp add: lift\<^sub>s_def Compose.lift\<^sub>s_def)
with valid have "\<Gamma>\<turnstile>c \<down> project\<^sub>x (Normal S)"
by (simp add: validt_def project\<^sub>x_def)
hence "lift\<^sub>e \<Gamma>\<turnstile>lift\<^sub>c c \<down> Normal S"
by (rule lift_termination')
}
ultimately show ?thesis
by (simp add: validt_def)
qed
lemma (in lift_state_space) lift_hoaret:
assumes deriv: "\<Gamma>,{}\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A"
shows
"(lift\<^sub>e \<Gamma>),{}\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (lift\<^sub>s P) (lift\<^sub>c c) (lift\<^sub>s Q),(lift\<^sub>s A)"
apply (rule hoaret_complete)
apply (insert hoaret_sound [OF deriv])
apply (rule lift_validt)
apply (simp add: cvalidt_def)
done
locale lift_state_space_ext = lift_state_space +
assumes inj_proj_commute: "\<And>S. inject S (project S) = S"
assumes inject_last: "\<And>S s t. inject (inject S s) t = inject S t"
(* \<exists>x. state t = inject (state s) x *)
lemma (in lift_state_space_ext) lift_exec_inject_same:
assumes exec_lc: "(lift\<^sub>e \<Gamma>)\<turnstile>\<langle>lc,s\<rangle> \<Rightarrow> t"
shows "\<And>c. \<lbrakk>lift\<^sub>c c = lc; t \<notin> (Fault ` UNIV) \<union> {Stuck}\<rbrakk> \<Longrightarrow>
state t = inject (state s) (project (state t))"
using exec_lc
proof (induct)
case Skip thus ?case
by (clarsimp simp add: inj_proj_commute)
next
case Guard thus ?case
by (clarsimp simp add: lift\<^sub>c_Guard lift\<^sub>c_def)
next
case GuardFault thus ?case
by simp
next
case FaultProp thus ?case by simp
next
case Basic thus ?case
by (clarsimp simp add: lift\<^sub>f_def Compose.lift\<^sub>f_def
proj_inj_commute lift\<^sub>c_Basic lift\<^sub>c_def)
next
case (Spec r) thus ?case
by (clarsimp simp add: Compose.lift\<^sub>r_def lift\<^sub>c_Spec lift\<^sub>c_def)
next
case SpecStuck
thus ?case by simp
next
case (Seq lc1 s s' lc2 t c)
have t: "t \<notin> Fault ` UNIV \<union> {Stuck}" by fact
have "lift\<^sub>c c = Seq lc1 lc2" by fact
then obtain c1 c2 where
c: "c = Seq c1 c2" and
lc1: "lc1 = lift\<^sub>c c1" and
lc2: "lc2 = lift\<^sub>c c2"
by (auto simp add: lift\<^sub>c_Seq lift\<^sub>c_def)
show ?case
proof (cases s')
case (Normal s'')
from Seq.hyps (2) [OF lc1 [symmetric]] this
have "s'' = inject s (project s'')"
by auto
moreover from Seq.hyps (4) [OF lc2 [symmetric]] Normal t
have "state t = inject s'' (project (state t))"
by auto
ultimately have "state t = inject (inject s (project s'')) (project (state t))"
by simp
then show ?thesis
by (simp add: inject_last)
next
case (Abrupt s'')
from Seq.hyps (2) [OF lc1 [symmetric]] this
have "s'' = inject s (project s'')"
by auto
moreover from Seq.hyps (4) [OF lc2 [symmetric]] Abrupt t
have "state t = inject s'' (project (state t))"
by auto
ultimately have "state t = inject (inject s (project s'')) (project (state t))"
by simp
then show ?thesis
by (simp add: inject_last)
next
case (Fault f)
with Seq
have "t = Fault f"
by (auto dest: Fault_end)
with t have False by simp
thus ?thesis ..
next
case Stuck
with Seq
have "t = Stuck"
by (auto dest: Stuck_end)
with t have False by simp
thus ?thesis ..
qed
next
case CondTrue thus ?case
by (clarsimp simp add: lift\<^sub>c_Cond lift\<^sub>c_def)
next
case CondFalse thus ?case
by (clarsimp simp add: lift\<^sub>c_Cond lift\<^sub>c_def)
next
case (WhileTrue s lb lc' s' t c)
have t: "t \<notin> Fault ` UNIV \<union> {Stuck}" by fact
have lw: "lift\<^sub>c c = While lb lc'" by fact
then obtain b c' where
c: "c = While b c'" and
lb: "lb = lift\<^sub>s b" and
lc: "lc' = lift\<^sub>c c'"
by (auto simp add: lift\<^sub>c_While lift\<^sub>s_def lift\<^sub>c_def)
show ?case
proof (cases s')
case (Normal s'')
from WhileTrue.hyps (3) [OF lc [symmetric]] this
have "s'' = inject s (project s'')"
by auto
moreover from WhileTrue.hyps (5) [OF lw] Normal t
have "state t = inject s'' (project (state t))"
by auto
ultimately have "state t = inject (inject s (project s'')) (project (state t))"
by simp
then show ?thesis
by (simp add: inject_last)
next
case (Abrupt s'')
from WhileTrue.hyps (3) [OF lc [symmetric]] this
have "s'' = inject s (project s'')"
by auto
moreover from WhileTrue.hyps (5) [OF lw] Abrupt t
have "state t = inject s'' (project (state t))"
by auto
ultimately have "state t = inject (inject s (project s'')) (project (state t))"
by simp
then show ?thesis
by (simp add: inject_last)
next
case (Fault f)
with WhileTrue
have "t = Fault f"
by (auto dest: Fault_end)
with t have False by simp
thus ?thesis ..
next
case Stuck
with WhileTrue
have "t = Stuck"
by (auto dest: Stuck_end)
with t have False by simp
thus ?thesis ..
qed
next
case WhileFalse thus ?case
by (clarsimp simp add: lift\<^sub>c_While inj_proj_commute)
next
case Call thus ?case
by (clarsimp simp add: inject_last lift\<^sub>c_Call lift\<^sub>e_def lift\<^sub>c_def)
next
case CallUndefined thus ?case by simp
next
case StuckProp thus ?case by simp
next
case DynCom
thus ?case
by (clarsimp simp add: lift\<^sub>c_DynCom lift\<^sub>c_def)
next
case Throw thus ?case
by (simp add: inj_proj_commute)
next
case AbruptProp thus ?case by (simp add: inj_proj_commute)
next
case (CatchMatch lc1 s s' lc2 t c)
have t: "t \<notin> Fault ` UNIV \<union> {Stuck}" by fact
have "lift\<^sub>c c = Catch lc1 lc2" by fact
then obtain c1 c2 where
c: "c = Catch c1 c2" and
lc1: "lc1 = lift\<^sub>c c1" and
lc2: "lc2 = lift\<^sub>c c2"
by (auto simp add: lift\<^sub>c_Catch lift\<^sub>c_def)
from CatchMatch.hyps (2) [OF lc1 [symmetric]] this
have "s' = inject s (project s')"
by auto
moreover
from CatchMatch.hyps (4) [OF lc2 [symmetric]] t
have "state t = inject s' (project (state t))"
by auto
ultimately have "state t = inject (inject s (project s')) (project (state t))"
by simp
then show ?case
by (simp add: inject_last)
next
case CatchMiss
thus ?case
by (clarsimp simp add: lift\<^sub>c_Catch lift\<^sub>c_def)
qed
lemma (in lift_state_space_ext) valid_inject_project:
assumes noFaultStuck:
"\<Gamma>\<turnstile>\<langle>c,Normal (project \<sigma>)\<rangle> \<Rightarrow>\<notin>(Fault ` UNIV \<union> {Stuck})"
shows "lift\<^sub>e \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> {\<sigma>} lift\<^sub>c c
{t. t=inject \<sigma> (project t)}, {t. t=inject \<sigma> (project t)}"
proof (rule validI)
fix s t
assume exec: "lift\<^sub>e \<Gamma>\<turnstile>\<langle>lift\<^sub>c c,Normal s\<rangle> \<Rightarrow> t"
assume P: "s \<in> {\<sigma>}"
assume noFault: "t \<notin> Fault ` F"
show "t \<in> Normal ` {t. t = inject \<sigma> (project t)} \<union>
Abrupt ` {t. t = inject \<sigma> (project t)}"
proof -
from lift_exec [OF exec]
have "\<Gamma>\<turnstile>\<langle>c,project\<^sub>x (Normal s)\<rangle> \<Rightarrow> project\<^sub>x t"
by simp
with noFaultStuck P have t: "t \<notin> Fault ` UNIV \<union> {Stuck}"
by (auto simp add: final_notin_def project\<^sub>x_def)
from lift_exec_inject_same [OF exec refl this] P
have "state t = inject \<sigma> (project (state t))"
by simp
with t show ?thesis
by (cases t) auto
qed
qed
lemma (in lift_state_space_ext) lift_exec_inject_same':
assumes exec_lc: "(lift\<^sub>e \<Gamma>)\<turnstile>\<langle>lift\<^sub>c c,S\<rangle> \<Rightarrow> T"
shows "\<And>c. \<lbrakk>T \<notin> (Fault ` UNIV) \<union> {Stuck}\<rbrakk> \<Longrightarrow>
state T = inject (state S) (project (state T))"
using lift_exec_inject_same [OF exec_lc]
by simp
lemma (in lift_state_space_ext) valid_lift_modifies:
assumes valid: "\<forall>s. \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> {s} c (Modif s),(ModifAbr s)"
shows "(lift\<^sub>e \<Gamma>)\<Turnstile>\<^bsub>/F\<^esub> {S} (lift\<^sub>c c)
{T. T \<in> lift\<^sub>s (Modif (project S)) \<and> T=inject S (project T)},
{T. T \<in> lift\<^sub>s (ModifAbr (project S)) \<and> T=inject S (project T)}"
proof (rule validI)
fix s t
assume exec: "lift\<^sub>e \<Gamma>\<turnstile>\<langle>lift\<^sub>c c,Normal s\<rangle> \<Rightarrow> t"
assume P: "s \<in> {S}"
assume noFault: "t \<notin> Fault ` F"
show "t \<in> Normal `
{t \<in> lift\<^sub>s (Modif (project S)).
t = inject S (project t)} \<union>
Abrupt `
{t \<in> lift\<^sub>s (ModifAbr (project S)).
t = inject S (project t)}"
proof -
from lift_exec [OF exec]
have "\<Gamma>\<turnstile> \<langle>c,project\<^sub>x (Normal s)\<rangle> \<Rightarrow> project\<^sub>x t"
by auto
moreover
from noFault have "project\<^sub>x t \<notin> Fault ` F"
by (cases "t") (auto simp add: project\<^sub>x_def)
ultimately
have "project\<^sub>x t \<in>
Normal ` (Modif (project s)) \<union> Abrupt ` (ModifAbr (project s))"
using valid [rule_format, of "(project s)"]
by (auto simp add: valid_def project\<^sub>x_def)
hence t: "t \<in> Normal ` lift\<^sub>s (Modif (project s)) \<union>
Abrupt ` lift\<^sub>s (ModifAbr (project s))"
by (cases t) (auto simp add: project\<^sub>x_def lift\<^sub>s_def Compose.lift\<^sub>s_def)
then have "t \<notin> Fault ` UNIV \<union> {Stuck}"
by (cases t) auto
from lift_exec_inject_same [OF exec _ this]
have "state t = inject (state (Normal s)) (project (state t))"
by simp
with t show ?thesis
using P by auto
qed
qed
lemma (in lift_state_space_ext) hoare_lift_modifies:
assumes deriv: "\<forall>\<sigma>. \<Gamma>,{}\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} c (Modif \<sigma>),(ModifAbr \<sigma>)"
shows "\<forall>\<sigma>. (lift\<^sub>e \<Gamma>),{}\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} (lift\<^sub>c c)
{T. T \<in> lift\<^sub>s (Modif (project \<sigma>)) \<and> T=inject \<sigma> (project T)},
{T. T \<in> lift\<^sub>s (ModifAbr (project \<sigma>)) \<and> T=inject \<sigma> (project T)}"
apply (rule allI)
apply (rule hoare_complete)
apply (rule valid_lift_modifies)
apply (rule allI)
apply (insert hoare_sound [OF deriv [rule_format]])
apply (simp add: cvalid_def)
done
lemma (in lift_state_space_ext) hoare_lift_modifies':
assumes deriv: "\<forall>\<sigma>. \<Gamma>,{}\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} c (Modif \<sigma>),(ModifAbr \<sigma>)"
shows "\<forall>\<sigma>. (lift\<^sub>e \<Gamma>),{}\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} (lift\<^sub>c c)
{T. T \<in> lift\<^sub>s (Modif (project \<sigma>)) \<and>
(\<exists>T'. T=inject \<sigma> T')},
{T. T \<in> lift\<^sub>s (ModifAbr (project \<sigma>)) \<and>
(\<exists>T'. T=inject \<sigma> T')}"
apply (rule allI)
apply (rule HoarePartialDef.conseq [OF hoare_lift_modifies [OF deriv]])
apply blast
done
subsection \<open>Renaming Procedures\<close>
primrec rename:: "('p \<Rightarrow> 'q) \<Rightarrow> ('s,'p,'f) com \<Rightarrow> ('s,'q,'f) com"
where
"rename N Skip = Skip" |
"rename N (Basic f) = Basic f" |
"rename N (Spec r) = Spec r" |
"rename N (Seq c\<^sub>1 c\<^sub>2) = (Seq (rename N c\<^sub>1) (rename N c\<^sub>2))" |
"rename N (Cond b c\<^sub>1 c\<^sub>2) = Cond b (rename N c\<^sub>1) (rename N c\<^sub>2)" |
"rename N (While b c) = While b (rename N c)" |
"rename N (Call p) = Call (N p)" |
"rename N (DynCom c) = DynCom (\<lambda>s. rename N (c s))" |
"rename N (Guard f g c) = Guard f g (rename N c)" |
"rename N Throw = Throw" |
"rename N (Catch c\<^sub>1 c\<^sub>2) = Catch (rename N c\<^sub>1) (rename N c\<^sub>2)"
lemma rename_Skip: "rename h c = Skip = (c=Skip)"
by (cases c) auto
lemma rename_Basic:
"(rename h c = Basic f) = (c=Basic f)"
by (cases c) auto
lemma rename_Spec:
"(rename h c = Spec r) = (c=Spec r)"
by (cases c) auto
lemma rename_Seq:
"(rename h c = Seq rc\<^sub>1 rc\<^sub>2) =
(\<exists> c\<^sub>1 c\<^sub>2. c = Seq c\<^sub>1 c\<^sub>2 \<and>
rc\<^sub>1 = rename h c\<^sub>1 \<and> rc\<^sub>2 = rename h c\<^sub>2 )"
by (cases c) auto
lemma rename_Cond:
"(rename h c = Cond b rc\<^sub>1 rc\<^sub>2) =
(\<exists>c\<^sub>1 c\<^sub>2. c = Cond b c\<^sub>1 c\<^sub>2 \<and> rc\<^sub>1 = rename h c\<^sub>1 \<and> rc\<^sub>2 = rename h c\<^sub>2 )"
by (cases c) auto
lemma rename_While:
"(rename h c = While b rc') = (\<exists>c'. c = While b c' \<and> rc' = rename h c')"
by (cases c) auto
lemma rename_Call:
"(rename h c = Call q) = (\<exists>p. c = Call p \<and> q=h p)"
by (cases c) auto
lemma rename_Guard:
"(rename h c = Guard f g rc') =
(\<exists>c'. c = Guard f g c' \<and> rc' = rename h c')"
by (cases c) auto
lemma rename_Throw:
"(rename h c = Throw) = (c = Throw)"
by (cases c) auto
lemma rename_Catch:
"(rename h c = Catch rc\<^sub>1 rc\<^sub>2) =
(\<exists>c\<^sub>1 c\<^sub>2. c = Catch c\<^sub>1 c\<^sub>2 \<and> rc\<^sub>1 = rename h c\<^sub>1 \<and> rc\<^sub>2 = rename h c\<^sub>2 )"
by (cases c) auto
lemma exec_rename_to_exec:
assumes \<Gamma>: "\<forall>p bdy. \<Gamma> p = Some bdy \<longrightarrow> \<Gamma>' (h p) = Some (rename h bdy)"
assumes exec: "\<Gamma>'\<turnstile>\<langle>rc,s\<rangle> \<Rightarrow> t"
shows "\<And>c. rename h c = rc\<Longrightarrow> \<exists>t'. \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t' \<and> (t'=Stuck \<or> t'=t)"
using exec
proof (induct)
case Skip thus ?case by (fastforce intro: exec.intros simp add: rename_Skip)
next
case Guard thus ?case by (fastforce intro: exec.intros simp add: rename_Guard)
next
case GuardFault thus ?case by (fastforce intro: exec.intros simp add: rename_Guard)
next
case FaultProp thus ?case by (fastforce intro: exec.intros)
next
case Basic thus ?case by (fastforce intro: exec.intros simp add: rename_Basic)
next
case Spec thus ?case by (fastforce intro: exec.intros simp add: rename_Spec)
next
case SpecStuck thus ?case by (fastforce intro: exec.intros simp add: rename_Spec)
next
case Seq thus ?case by (fastforce intro: exec.intros simp add: rename_Seq)
next
case CondTrue thus ?case by (fastforce intro: exec.intros simp add: rename_Cond)
next
case CondFalse thus ?case by (fastforce intro: exec.intros simp add: rename_Cond)
next
case WhileTrue thus ?case by (fastforce intro: exec.intros simp add: rename_While)
next
case WhileFalse thus ?case by (fastforce intro: exec.intros simp add: rename_While)
next
case (Call p rbdy s t)
have rbdy: "\<Gamma>' p = Some rbdy" by fact
have "rename h c = Call p" by fact
then obtain q where c: "c=Call q" and p: "p=h q"
by (auto simp add: rename_Call)
show ?case
proof (cases "\<Gamma> q")
case None
with c show ?thesis by (auto intro: exec.CallUndefined)
next
case (Some bdy)
from \<Gamma> [rule_format, OF this] p rbdy
have "rename h bdy = rbdy" by simp
with Call.hyps c Some
show ?thesis
by (fastforce intro: exec.intros)
qed
next
case (CallUndefined p s)
have undef: "\<Gamma>' p = None" by fact
have "rename h c = Call p" by fact
then obtain q where c: "c=Call q" and p: "p=h q"
by (auto simp add: rename_Call)
from undef p \<Gamma> have "\<Gamma> q = None"
by (cases "\<Gamma> q") auto
with p c show ?case
by (auto intro: exec.intros)
next
case StuckProp thus ?case by (fastforce intro: exec.intros)
next
case DynCom thus ?case by (fastforce intro: exec.intros simp add: rename_DynCom)
next
case Throw thus ?case by (fastforce intro: exec.intros simp add: rename_Throw)
next
case AbruptProp thus ?case by (fastforce intro: exec.intros)
next
case CatchMatch thus ?case by (fastforce intro: exec.intros simp add: rename_Catch)
next
case CatchMiss thus ?case by (fastforce intro: exec.intros simp add: rename_Catch)
qed
lemma exec_rename_to_exec':
assumes \<Gamma>: "\<forall>p bdy. \<Gamma> p = Some bdy \<longrightarrow> \<Gamma>' (N p) = Some (rename N bdy)"
assumes exec: "\<Gamma>'\<turnstile>\<langle>rename N c,s\<rangle> \<Rightarrow> t"
shows "\<exists>t'. \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t' \<and> (t'=Stuck \<or> t'=t)"
using exec_rename_to_exec [OF \<Gamma> exec]
by auto
lemma valid_to_valid_rename:
assumes \<Gamma>: "\<forall>p bdy. \<Gamma> p = Some bdy \<longrightarrow> \<Gamma>' (N p) = Some (rename N bdy)"
assumes valid: "\<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A"
shows "\<Gamma>'\<Turnstile>\<^bsub>/F\<^esub> P (rename N c) Q,A"
proof (rule validI)
fix s t
assume execr: "\<Gamma>'\<turnstile> \<langle>rename N c,Normal s\<rangle> \<Rightarrow> t"
assume P: "s \<in> P"
assume noFault: "t \<notin> Fault ` F"
show "t \<in> Normal ` Q \<union> Abrupt ` A"
proof -
from exec_rename_to_exec [OF \<Gamma> execr]
obtain t' where
exec: "\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> \<Rightarrow> t'" and t': "(t' = Stuck \<or> t' = t)"
by auto
with valid noFault P show ?thesis
by (auto simp add: valid_def)
qed
qed
lemma hoare_to_hoare_rename:
assumes \<Gamma>: "\<forall>p bdy. \<Gamma> p = Some bdy \<longrightarrow> \<Gamma>' (N p) = Some (rename N bdy)"
assumes deriv: "\<Gamma>,{}\<turnstile>\<^bsub>/F\<^esub> P c Q,A"
shows "\<Gamma>',{}\<turnstile>\<^bsub>/F\<^esub> P (rename N c) Q,A"
apply (rule hoare_complete)
apply (insert hoare_sound [OF deriv])
apply (rule valid_to_valid_rename)
apply (rule \<Gamma>)
apply (simp add: cvalid_def)
done
lemma hoare_to_hoare_rename':
assumes \<Gamma>: "\<forall>p bdy. \<Gamma> p = Some bdy \<longrightarrow> \<Gamma>' (N p) = Some (rename N bdy)"
assumes deriv: "\<forall>Z. \<Gamma>,{}\<turnstile>\<^bsub>/F\<^esub> (P Z) c (Q Z),(A Z)"
shows "\<forall>Z. \<Gamma>',{}\<turnstile>\<^bsub>/F\<^esub> (P Z) (rename N c) (Q Z),(A Z)"
apply rule
apply (rule hoare_to_hoare_rename [OF \<Gamma>])
apply (rule deriv[rule_format])
done
lemma terminates_to_terminates_rename:
assumes \<Gamma>: "\<forall>p bdy. \<Gamma> p = Some bdy \<longrightarrow> \<Gamma>' (N p) = Some (rename N bdy)"
assumes termi: "\<Gamma>\<turnstile> c \<down> s"
assumes noStuck: "\<Gamma>\<turnstile> \<langle>c,s\<rangle> \<Rightarrow>\<notin>{Stuck}"
shows "\<Gamma>'\<turnstile> rename N c \<down> s"
using termi noStuck
proof (induct)
case Skip thus ?case by (fastforce intro: terminates.intros)
next
case Basic thus ?case by (fastforce intro: terminates.intros)
next
case Spec thus ?case by (fastforce intro: terminates.intros)
next
case Guard thus ?case by (fastforce intro: terminates.intros
simp add: final_notin_def exec.intros)
next
case GuardFault thus ?case by (fastforce intro: terminates.intros)
next
case Fault thus ?case by (fastforce intro: terminates.intros)
next
case Seq
thus ?case
by (force intro!: terminates.intros exec.intros dest: exec_rename_to_exec [OF \<Gamma>]
simp add: final_notin_def)
next
case CondTrue thus ?case by (fastforce intro: terminates.intros
simp add: final_notin_def exec.intros)
next
case CondFalse thus ?case by (fastforce intro: terminates.intros
simp add: final_notin_def exec.intros)
next
case (WhileTrue s b c)
have s_in_b: "s \<in> b" by fact
have noStuck: "\<Gamma>\<turnstile> \<langle>While b c,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}" by fact
with s_in_b have "\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}"
by (auto simp add: final_notin_def intro: exec.intros)
with WhileTrue.hyps have "\<Gamma>'\<turnstile>rename N c \<down> Normal s"
by simp
moreover
{
fix t
assume exec_rc: "\<Gamma>'\<turnstile> \<langle>rename N c,Normal s\<rangle> \<Rightarrow> t"
have "\<Gamma>'\<turnstile> While b (rename N c) \<down> t"
proof -
from exec_rename_to_exec [OF \<Gamma> exec_rc] obtain t'
where exec_c: "\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> \<Rightarrow> t'" and t': "(t' = Stuck \<or> t' = t)"
by auto
with s_in_b noStuck obtain "t'=t" and "\<Gamma>\<turnstile> \<langle>While b c,t\<rangle> \<Rightarrow>\<notin>{Stuck}"
by (auto simp add: final_notin_def intro: exec.intros)
with exec_c WhileTrue.hyps
show ?thesis
by auto
qed
}
ultimately show ?case
using s_in_b
by (auto intro: terminates.intros)
next
case WhileFalse thus ?case by (fastforce intro: terminates.intros)
next
case (Call p bdy s)
have "\<Gamma> p = Some bdy" by fact
from \<Gamma> [rule_format, OF this]
have bdy': "\<Gamma>' (N p) = Some (rename N bdy)".
from Call have "\<Gamma>'\<turnstile>rename N bdy \<down> Normal s"
by (auto simp add: final_notin_def intro: exec.intros)
with bdy' have "\<Gamma>'\<turnstile>Call (N p) \<down> Normal s"
by (auto intro: terminates.intros)
thus ?case by simp
next
case (CallUndefined p s)
have "\<Gamma> p = None" "\<Gamma>\<turnstile> \<langle>Call p,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}" by fact+
hence False by (auto simp add: final_notin_def intro: exec.intros)
thus ?case ..
next
case Stuck thus ?case by (fastforce intro: terminates.intros)
next
case DynCom thus ?case by (fastforce intro: terminates.intros
simp add: final_notin_def exec.intros)
next
case Throw thus ?case by (fastforce intro: terminates.intros)
next
case Abrupt thus ?case by (fastforce intro: terminates.intros)
next
case (Catch c1 s c2)
have noStuck: "\<Gamma>\<turnstile> \<langle>Catch c1 c2,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}" by fact
hence "\<Gamma>\<turnstile> \<langle>c1,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}"
by (fastforce simp add: final_notin_def intro: exec.intros)
with Catch.hyps have "\<Gamma>'\<turnstile>rename N c1 \<down> Normal s"
by auto
moreover
{
fix t
assume exec_rc1:"\<Gamma>'\<turnstile> \<langle>rename N c1,Normal s\<rangle> \<Rightarrow> Abrupt t"
have "\<Gamma>'\<turnstile>rename N c2 \<down> Normal t"
proof -
from exec_rename_to_exec [OF \<Gamma> exec_rc1] obtain t'
where exec_c: "\<Gamma>\<turnstile> \<langle>c1,Normal s\<rangle> \<Rightarrow> t'" and "(t' = Stuck \<or> t' = Abrupt t)"
by auto
with noStuck have t': "t'=Abrupt t"
by (fastforce simp add: final_notin_def intro: exec.intros)
with exec_c noStuck have "\<Gamma>\<turnstile> \<langle>c2,Normal t\<rangle> \<Rightarrow>\<notin>{Stuck}"
by (auto simp add: final_notin_def intro: exec.intros)
with exec_c t' Catch.hyps
show ?thesis
by auto
qed
}
ultimately show ?case
by (auto intro: terminates.intros)
qed
lemma validt_to_validt_rename:
assumes \<Gamma>: "\<forall>p bdy. \<Gamma> p = Some bdy \<longrightarrow> \<Gamma>' (N p) = Some (rename N bdy)"
assumes valid: "\<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A"
shows "\<Gamma>'\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P (rename N c) Q,A"
proof -
from valid
have "\<Gamma>'\<Turnstile>\<^bsub>/F\<^esub> P (rename N c) Q,A"
by (auto intro: valid_to_valid_rename [OF \<Gamma>] simp add: validt_def)
moreover
{
fix s
assume "s \<in> P"
with valid obtain "\<Gamma>\<turnstile>c \<down> (Normal s)" "\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}"
by (auto simp add: validt_def valid_def final_notin_def)
from terminates_to_terminates_rename [OF \<Gamma> this]
have "\<Gamma>'\<turnstile>rename N c \<down> Normal s"
.
}
ultimately show ?thesis
by (simp add: validt_def)
qed
lemma hoaret_to_hoaret_rename:
assumes \<Gamma>: "\<forall>p bdy. \<Gamma> p = Some bdy \<longrightarrow> \<Gamma>' (N p) = Some (rename N bdy)"
assumes deriv: "\<Gamma>,{}\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A"
shows "\<Gamma>',{}\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (rename N c) Q,A"
apply (rule hoaret_complete)
apply (insert hoaret_sound [OF deriv])
apply (rule validt_to_validt_rename)
apply (rule \<Gamma>)
apply (simp add: cvalidt_def)
done
lemma hoaret_to_hoaret_rename':
assumes \<Gamma>: "\<forall>p bdy. \<Gamma> p = Some bdy \<longrightarrow> \<Gamma>' (N p) = Some (rename N bdy)"
assumes deriv: "\<forall>Z. \<Gamma>,{}\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (P Z) c (Q Z),(A Z)"
shows "\<forall>Z. \<Gamma>',{}\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (P Z) (rename N c) (Q Z),(A Z)"
apply rule
apply (rule hoaret_to_hoaret_rename [OF \<Gamma>])
apply (rule deriv[rule_format])
done
lemma lift\<^sub>c_whileAnno [simp]: "lift\<^sub>c prj inject (whileAnno b I V c) =
whileAnno (lift\<^sub>s prj b)
(lift\<^sub>s prj I) (lift\<^sub>r prj inject V) (lift\<^sub>c prj inject c)"
by (simp add: whileAnno_def)
lemma lift\<^sub>c_block [simp]: "lift\<^sub>c prj inject (block init bdy return c) =
block (lift\<^sub>f prj inject init) (lift\<^sub>c prj inject bdy)
(\<lambda>s. (lift\<^sub>f prj inject (return (prj s))))
(\<lambda>s t. lift\<^sub>c prj inject (c (prj s) (prj t)))"
by (simp add: block_def)
(*
lemma lift\<^sub>c_block [simp]: "lift\<^sub>c prj inject (block init bdy return c) =
block (lift\<^sub>f prj inject init) (lift\<^sub>c prj inject bdy)
(\<lambda>s t. inject s (return (prj s) (prj t)))
(\<lambda>s t. lift\<^sub>c prj inject (c (prj s) (prj t)))"
apply (simp add: block_def)
apply (simp add: lift\<^sub>f_def)
*)
lemma lift\<^sub>c_call [simp]: "lift\<^sub>c prj inject (call init p return c) =
call (lift\<^sub>f prj inject init) p
(\<lambda>s. (lift\<^sub>f prj inject (return (prj s))))
(\<lambda>s t. lift\<^sub>c prj inject (c (prj s) (prj t)))"
by (simp add: call_def lift\<^sub>c_block)
lemma rename_whileAnno [simp]: "rename h (whileAnno b I V c) =
whileAnno b I V (rename h c)"
by (simp add: whileAnno_def)
lemma rename_block [simp]: "rename h (block init bdy return c) =
block init (rename h bdy) return (\<lambda>s t. rename h (c s t))"
by (simp add: block_def)
lemma rename_call [simp]: "rename h (call init p return c) =
call init (h p) return (\<lambda>s t. rename h (c s t))"
by (simp add: call_def)
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.