text
stringlengths 0
3.34M
|
---|
------------------------------------------------------------------------
-- The Agda standard library
--
-- The basic code for equational reasoning with three relations:
-- equality, strict ordering and non-strict ordering.
------------------------------------------------------------------------
--
-- See `Data.Nat.Properties` or `Relation.Binary.Reasoning.PartialOrder`
-- for examples of how to instantiate this module.
{-# OPTIONS --without-K --safe #-}
open import Relation.Binary
module Relation.Binary.Reasoning.Base.Triple {a ℓ₁ ℓ₂ ℓ₃} {A : Set a}
{_≈_ : Rel A ℓ₁} {_≤_ : Rel A ℓ₂} {_<_ : Rel A ℓ₃}
(isPreorder : IsPreorder _≈_ _≤_)
(<-trans : Transitive _<_) (<-resp-≈ : _<_ Respects₂ _≈_) (<⇒≤ : _<_ ⇒ _≤_)
(<-≤-trans : Trans _<_ _≤_ _<_) (≤-<-trans : Trans _≤_ _<_ _<_)
where
open import Data.Product using (proj₁; proj₂)
open import Function using (case_of_; id)
open import Level using (Level; _⊔_; Lift; lift)
open import Relation.Binary.PropositionalEquality using (_≡_; refl; sym)
open import Relation.Nullary using (Dec; yes; no)
open import Relation.Nullary.Decidable using (True; toWitness)
open IsPreorder isPreorder
renaming
( reflexive to ≤-reflexive
; trans to ≤-trans
; ∼-resp-≈ to ≤-resp-≈
)
------------------------------------------------------------------------
-- A datatype to hide the current relation type
data _IsRelatedTo_ (x y : A) : Set (a ⊔ ℓ₁ ⊔ ℓ₂ ⊔ ℓ₃) where
strict : (x<y : x < y) → x IsRelatedTo y
nonstrict : (x≤y : x ≤ y) → x IsRelatedTo y
equals : (x≈y : x ≈ y) → x IsRelatedTo y
------------------------------------------------------------------------
-- Types that are used to ensure that the final relation proved by the
-- chain of reasoning can be converted into the required relation.
data IsStrict {x y} : x IsRelatedTo y → Set (a ⊔ ℓ₁ ⊔ ℓ₂ ⊔ ℓ₃) where
isStrict : ∀ x<y → IsStrict (strict x<y)
IsStrict? : ∀ {x y} (x≲y : x IsRelatedTo y) → Dec (IsStrict x≲y)
IsStrict? (strict x<y) = yes (isStrict x<y)
IsStrict? (nonstrict _) = no λ()
IsStrict? (equals _) = no λ()
extractStrict : ∀ {x y} {x≲y : x IsRelatedTo y} → IsStrict x≲y → x < y
extractStrict (isStrict x<y) = x<y
data IsEquality {x y} : x IsRelatedTo y → Set (a ⊔ ℓ₁ ⊔ ℓ₂ ⊔ ℓ₃) where
isEquality : ∀ x≈y → IsEquality (equals x≈y)
IsEquality? : ∀ {x y} (x≲y : x IsRelatedTo y) → Dec (IsEquality x≲y)
IsEquality? (strict _) = no λ()
IsEquality? (nonstrict _) = no λ()
IsEquality? (equals x≈y) = yes (isEquality x≈y)
extractEquality : ∀ {x y} {x≲y : x IsRelatedTo y} → IsEquality x≲y → x ≈ y
extractEquality (isEquality x≈y) = x≈y
------------------------------------------------------------------------
-- Reasoning combinators
infix -1 begin_ begin-strict_ begin-equality_
infixr 0 _<⟨_⟩_ _≤⟨_⟩_ _≈⟨_⟩_ _≈˘⟨_⟩_ _≡⟨_⟩_ _≡˘⟨_⟩_ _≡⟨⟩_
infix 1 _∎
begin_ : ∀ {x y} (r : x IsRelatedTo y) → x ≤ y
begin (strict x<y) = <⇒≤ x<y
begin (nonstrict x≤y) = x≤y
begin (equals x≈y) = ≤-reflexive x≈y
begin-strict_ : ∀ {x y} (r : x IsRelatedTo y) → {s : True (IsStrict? r)} → x < y
begin-strict_ r {s} = extractStrict (toWitness s)
begin-equality_ : ∀ {x y} (r : x IsRelatedTo y) → {s : True (IsEquality? r)} → x ≈ y
begin-equality_ r {s} = extractEquality (toWitness s)
_<⟨_⟩_ : ∀ (x : A) {y z} → x < y → y IsRelatedTo z → x IsRelatedTo z
x <⟨ x<y ⟩ strict y<z = strict (<-trans x<y y<z)
x <⟨ x<y ⟩ nonstrict y≤z = strict (<-≤-trans x<y y≤z)
x <⟨ x<y ⟩ equals y≈z = strict (proj₁ <-resp-≈ y≈z x<y)
_≤⟨_⟩_ : ∀ (x : A) {y z} → x ≤ y → y IsRelatedTo z → x IsRelatedTo z
x ≤⟨ x≤y ⟩ strict y<z = strict (≤-<-trans x≤y y<z)
x ≤⟨ x≤y ⟩ nonstrict y≤z = nonstrict (≤-trans x≤y y≤z)
x ≤⟨ x≤y ⟩ equals y≈z = nonstrict (proj₁ ≤-resp-≈ y≈z x≤y)
_≈⟨_⟩_ : ∀ (x : A) {y z} → x ≈ y → y IsRelatedTo z → x IsRelatedTo z
x ≈⟨ x≈y ⟩ strict y<z = strict (proj₂ <-resp-≈ (Eq.sym x≈y) y<z)
x ≈⟨ x≈y ⟩ nonstrict y≤z = nonstrict (proj₂ ≤-resp-≈ (Eq.sym x≈y) y≤z)
x ≈⟨ x≈y ⟩ equals y≈z = equals (Eq.trans x≈y y≈z)
_≈˘⟨_⟩_ : ∀ x {y z} → y ≈ x → y IsRelatedTo z → x IsRelatedTo z
x ≈˘⟨ x≈y ⟩ y∼z = x ≈⟨ Eq.sym x≈y ⟩ y∼z
_≡⟨_⟩_ : ∀ (x : A) {y z} → x ≡ y → y IsRelatedTo z → x IsRelatedTo z
x ≡⟨ x≡y ⟩ strict y<z = strict (case x≡y of λ where refl → y<z)
x ≡⟨ x≡y ⟩ nonstrict y≤z = nonstrict (case x≡y of λ where refl → y≤z)
x ≡⟨ x≡y ⟩ equals y≈z = equals (case x≡y of λ where refl → y≈z)
_≡˘⟨_⟩_ : ∀ x {y z} → y ≡ x → y IsRelatedTo z → x IsRelatedTo z
x ≡˘⟨ x≡y ⟩ y∼z = x ≡⟨ sym x≡y ⟩ y∼z
_≡⟨⟩_ : ∀ (x : A) {y} → x IsRelatedTo y → x IsRelatedTo y
x ≡⟨⟩ x≲y = x≲y
_∎ : ∀ x → x IsRelatedTo x
x ∎ = equals Eq.refl
|
module Main
import Data.Vect
readVectLen : (len : Nat) -> IO (Vect len String)
readVectLen Z = pure []
readVectLen (S k) = do x <- getLine
xs <- readVectLen k
pure (x :: xs)
data VectUnknown : Type -> Type where
MkVect : (len : Nat) -> Vect len a -> VectUnknown a
-- We can use implicit underscore notation because there is only one valid value for length in the below
readVect : IO (VectUnknown String)
readVect = do x <- getLine
if (x == "") then pure (MkVect _ [])
else do MkVect _ xs <- readVect
pure (MkVect _ (x :: xs))
readVectPair : IO (len ** Vect len String)
readVectPair = do x <- getLine
if (x == "") then pure (_ ** [])
else do (_ ** xs) <- readVectPair
pure (_ ** (x :: xs))
printVect : Show a => VectUnknown a -> IO ()
printVect (MkVect len xs) = putStrLn (show xs ++ " (length " ++ show len ++ ")")
-- We cannot use the below format to define VectUnknown because we need to state the length of the Vector
-- data MyVectUnknown = MyMkVect Nat Vect
zipInputs : IO ()
zipInputs = do putStrLn "Enter first vector (blank line to end):"
(len1 ** vec1) <- readVectPair
putStrLn "Enter second vector (blank line to end):"
(len2 ** vec2) <- readVectPair
case exactLength len1 vec2 of
Nothing => putStrLn "Vectors are of different lengths"
(Just vec2') => printLn (zip vec1 vec2')
|
[GOAL]
C : Type u_1
inst✝¹ : Category.{?u.28, u_1} C
inst✝ : Preadditive C
Y : C
X : SimplicialObject C
n b q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnbq : n + 1 = b + q
⊢ b < n + 1 + 1
[PROOFSTEP]
simp only [hnbq, Nat.lt_add_one_iff, le_add_iff_nonneg_right, zero_le]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
Y : C
X : SimplicialObject C
n b q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnbq : n + 1 = b + q
j : Fin (n + 1 + 1)
hj : n + 1 + 1 ≤ ↑j + q
⊢ (φ ≫ SimplicialObject.σ X { val := b, isLt := (_ : b < n + 1 + 1) }) ≫ SimplicialObject.δ X (Fin.succ j) = 0
[PROOFSTEP]
rw [assoc, SimplicialObject.δ_comp_σ_of_gt', Fin.pred_succ, v.comp_δ_eq_zero_assoc _ _ hj, zero_comp]
[GOAL]
case H
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
Y : C
X : SimplicialObject C
n b q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnbq : n + 1 = b + q
j : Fin (n + 1 + 1)
hj : n + 1 + 1 ≤ ↑j + q
⊢ Fin.succ { val := b, isLt := (_ : b < n + 1 + 1) } < Fin.succ j
[PROOFSTEP]
dsimp
[GOAL]
case H
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
Y : C
X : SimplicialObject C
n b q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnbq : n + 1 = b + q
j : Fin (n + 1 + 1)
hj : n + 1 + 1 ≤ ↑j + q
⊢ { val := b + 1, isLt := (_ : Nat.succ b < Nat.succ (n + 2)) } < Fin.succ j
[PROOFSTEP]
rw [Fin.lt_iff_val_lt_val, Fin.val_succ]
[GOAL]
case H
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
Y : C
X : SimplicialObject C
n b q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnbq : n + 1 = b + q
j : Fin (n + 1 + 1)
hj : n + 1 + 1 ≤ ↑j + q
⊢ ↑{ val := b + 1, isLt := (_ : Nat.succ b < Nat.succ (n + 2)) } < ↑j + 1
[PROOFSTEP]
linarith
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
Y : C
X : SimplicialObject C
n b q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnbq : n + 1 = b + q
j : Fin (n + 1 + 1)
hj : n + 1 + 1 ≤ ↑j + q
⊢ j ≠ 0
[PROOFSTEP]
intro hj'
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
Y : C
X : SimplicialObject C
n b q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnbq : n + 1 = b + q
j : Fin (n + 1 + 1)
hj : n + 1 + 1 ≤ ↑j + q
hj' : j = 0
⊢ False
[PROOFSTEP]
simp only [hnbq, add_comm b, add_assoc, hj', Fin.val_zero, zero_add, add_le_iff_nonpos_right, nonpos_iff_eq_zero,
add_eq_zero, false_and] at hj
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
n q : ℕ
i : Fin (n + 1)
hi : n + 1 ≤ ↑i + q
⊢ SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (n + 1) = 0
[PROOFSTEP]
revert i hi
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
n q : ℕ
⊢ ∀ (i : Fin (n + 1)), n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (n + 1) = 0
[PROOFSTEP]
induction' q with q hq
[GOAL]
case zero
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
n : ℕ
⊢ ∀ (i : Fin (n + 1)),
n + 1 ≤ ↑i + Nat.zero → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P Nat.zero) (n + 1) = 0
[PROOFSTEP]
intro i (hi : n + 1 ≤ i)
[GOAL]
case zero
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
n : ℕ
i : Fin (n + 1)
hi : n + 1 ≤ ↑i
⊢ SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P Nat.zero) (n + 1) = 0
[PROOFSTEP]
exfalso
[GOAL]
case zero.h
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
n : ℕ
i : Fin (n + 1)
hi : n + 1 ≤ ↑i
⊢ False
[PROOFSTEP]
linarith [Fin.is_lt i]
[GOAL]
case succ
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
n q : ℕ
hq : ∀ (i : Fin (n + 1)), n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (n + 1) = 0
⊢ ∀ (i : Fin (n + 1)),
n + 1 ≤ ↑i + Nat.succ q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P (Nat.succ q)) (n + 1) = 0
[PROOFSTEP]
intro i (hi : n + 1 ≤ i + q + 1)
[GOAL]
case succ
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
n q : ℕ
hq : ∀ (i : Fin (n + 1)), n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (n + 1) = 0
i : Fin (n + 1)
hi : n + 1 ≤ ↑i + q + 1
⊢ SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P (Nat.succ q)) (n + 1) = 0
[PROOFSTEP]
by_cases n + 1 ≤ (i : ℕ) + q
[GOAL]
case succ
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
n q : ℕ
hq : ∀ (i : Fin (n + 1)), n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (n + 1) = 0
i : Fin (n + 1)
hi : n + 1 ≤ ↑i + q + 1
⊢ SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P (Nat.succ q)) (n + 1) = 0
[PROOFSTEP]
by_cases n + 1 ≤ (i : ℕ) + q
[GOAL]
case pos
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
n q : ℕ
hq : ∀ (i : Fin (n + 1)), n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (n + 1) = 0
i : Fin (n + 1)
hi : n + 1 ≤ ↑i + q + 1
h : n + 1 ≤ ↑i + q
⊢ SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P (Nat.succ q)) (n + 1) = 0
[PROOFSTEP]
rw [P_succ, HomologicalComplex.comp_f, ← assoc, hq i h, zero_comp]
[GOAL]
case neg
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
n q : ℕ
hq : ∀ (i : Fin (n + 1)), n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (n + 1) = 0
i : Fin (n + 1)
hi : n + 1 ≤ ↑i + q + 1
h : ¬n + 1 ≤ ↑i + q
⊢ SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P (Nat.succ q)) (n + 1) = 0
[PROOFSTEP]
replace hi : n = i + q := by
obtain ⟨j, hj⟩ := le_iff_exists_add.mp hi
rw [← Nat.lt_succ_iff, Nat.succ_eq_add_one, hj, not_lt, add_le_iff_nonpos_right, nonpos_iff_eq_zero] at h
rw [← add_left_inj 1, hj, self_eq_add_right, h]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
n q : ℕ
hq : ∀ (i : Fin (n + 1)), n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (n + 1) = 0
i : Fin (n + 1)
hi : n + 1 ≤ ↑i + q + 1
h : ¬n + 1 ≤ ↑i + q
⊢ n = ↑i + q
[PROOFSTEP]
obtain ⟨j, hj⟩ := le_iff_exists_add.mp hi
[GOAL]
case intro
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
n q : ℕ
hq : ∀ (i : Fin (n + 1)), n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (n + 1) = 0
i : Fin (n + 1)
hi : n + 1 ≤ ↑i + q + 1
h : ¬n + 1 ≤ ↑i + q
j : ℕ
hj : ↑i + q + 1 = n + 1 + j
⊢ n = ↑i + q
[PROOFSTEP]
rw [← Nat.lt_succ_iff, Nat.succ_eq_add_one, hj, not_lt, add_le_iff_nonpos_right, nonpos_iff_eq_zero] at h
[GOAL]
case intro
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
n q : ℕ
hq : ∀ (i : Fin (n + 1)), n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (n + 1) = 0
i : Fin (n + 1)
hi : n + 1 ≤ ↑i + q + 1
j : ℕ
h : j = 0
hj : ↑i + q + 1 = n + 1 + j
⊢ n = ↑i + q
[PROOFSTEP]
rw [← add_left_inj 1, hj, self_eq_add_right, h]
[GOAL]
case neg
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
n q : ℕ
hq : ∀ (i : Fin (n + 1)), n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (n + 1) = 0
i : Fin (n + 1)
h : ¬n + 1 ≤ ↑i + q
hi : n = ↑i + q
⊢ SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P (Nat.succ q)) (n + 1) = 0
[PROOFSTEP]
rcases n with _ | n
[GOAL]
case neg.zero
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q : ℕ
hq :
∀ (i : Fin (Nat.zero + 1)),
Nat.zero + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.zero + 1) = 0
i : Fin (Nat.zero + 1)
h : ¬Nat.zero + 1 ≤ ↑i + q
hi : Nat.zero = ↑i + q
⊢ SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P (Nat.succ q)) (Nat.zero + 1) = 0
[PROOFSTEP]
fin_cases i
[GOAL]
case neg.zero.head
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q : ℕ
hq :
∀ (i : Fin (Nat.zero + 1)),
Nat.zero + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.zero + 1) = 0
h : ¬Nat.zero + 1 ≤ ↑{ val := 0, isLt := (_ : 0 < Nat.zero + 1) } + q
hi : Nat.zero = ↑{ val := 0, isLt := (_ : 0 < Nat.zero + 1) } + q
⊢ SimplicialObject.σ X { val := 0, isLt := (_ : 0 < Nat.zero + 1) } ≫
HomologicalComplex.Hom.f (P (Nat.succ q)) (Nat.zero + 1) =
0
[PROOFSTEP]
dsimp at h hi
[GOAL]
case neg.zero.head
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q : ℕ
hq :
∀ (i : Fin (Nat.zero + 1)),
Nat.zero + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.zero + 1) = 0
h : ¬0 + 1 ≤ 0 + q
hi : 0 = 0 + q
⊢ SimplicialObject.σ X { val := 0, isLt := (_ : 0 < Nat.zero + 1) } ≫
HomologicalComplex.Hom.f (P (Nat.succ q)) (Nat.zero + 1) =
0
[PROOFSTEP]
rw [show q = 0 by linarith]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q : ℕ
hq :
∀ (i : Fin (Nat.zero + 1)),
Nat.zero + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.zero + 1) = 0
h : ¬0 + 1 ≤ 0 + q
hi : 0 = 0 + q
⊢ q = 0
[PROOFSTEP]
linarith
[GOAL]
case neg.zero.head
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q : ℕ
hq :
∀ (i : Fin (Nat.zero + 1)),
Nat.zero + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.zero + 1) = 0
h : ¬0 + 1 ≤ 0 + q
hi : 0 = 0 + q
⊢ SimplicialObject.σ X { val := 0, isLt := (_ : 0 < Nat.zero + 1) } ≫
HomologicalComplex.Hom.f (P (Nat.succ 0)) (Nat.zero + 1) =
0
[PROOFSTEP]
change X.σ 0 ≫ (P 1).f 1 = 0
[GOAL]
case neg.zero.head
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q : ℕ
hq :
∀ (i : Fin (Nat.zero + 1)),
Nat.zero + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.zero + 1) = 0
h : ¬0 + 1 ≤ 0 + q
hi : 0 = 0 + q
⊢ SimplicialObject.σ X 0 ≫ HomologicalComplex.Hom.f (P 1) 1 = 0
[PROOFSTEP]
simp only [P_succ, HomologicalComplex.add_f_apply, comp_add, HomologicalComplex.id_f,
AlternatingFaceMapComplex.obj_d_eq, Hσ, HomologicalComplex.comp_f,
Homotopy.nullHomotopicMap'_f (c_mk 2 1 rfl) (c_mk 1 0 rfl), comp_id]
[GOAL]
case neg.zero.head
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q : ℕ
hq :
∀ (i : Fin (Nat.zero + 1)),
Nat.zero + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.zero + 1) = 0
h : ¬0 + 1 ≤ 0 + q
hi : 0 = 0 + q
⊢ SimplicialObject.σ X 0 ≫ HomologicalComplex.Hom.f (P 0) 1 +
(SimplicialObject.σ X 0 ≫
HomologicalComplex.Hom.f (P 0) 1 ≫
(Finset.sum Finset.univ fun i => (-1) ^ ↑i • SimplicialObject.δ X i) ≫
hσ' 0 0 1 (_ : ComplexShape.Rel c 1 0) +
SimplicialObject.σ X 0 ≫
HomologicalComplex.Hom.f (P 0) 1 ≫
hσ' 0 1 2 (_ : ComplexShape.Rel c 2 1) ≫
Finset.sum Finset.univ fun i => (-1) ^ ↑i • SimplicialObject.δ X i) =
0
[PROOFSTEP]
erw [hσ'_eq' (zero_add 0).symm, hσ'_eq' (add_zero 1).symm, comp_id, Fin.sum_univ_two, Fin.sum_univ_succ,
Fin.sum_univ_two]
[GOAL]
case neg.zero.head
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q : ℕ
hq :
∀ (i : Fin (Nat.zero + 1)),
Nat.zero + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.zero + 1) = 0
h : ¬0 + 1 ≤ 0 + q
hi : 0 = 0 + q
⊢ SimplicialObject.σ X 0 +
(SimplicialObject.σ X 0 ≫
HomologicalComplex.Hom.f (P 0) 1 ≫
((-1) ^ ↑0 • SimplicialObject.δ X 0 + (-1) ^ ↑1 • SimplicialObject.δ X 1) ≫
((-1) ^ 0 • SimplicialObject.σ X { val := 0, isLt := (_ : 0 < Nat.succ 0) }) +
SimplicialObject.σ X 0 ≫
HomologicalComplex.Hom.f (P 0) 1 ≫
((-1) ^ 1 • SimplicialObject.σ X { val := 1, isLt := (_ : 1 < Nat.succ 1) }) ≫
((-1) ^ ↑0 • SimplicialObject.δ X 0 +
((-1) ^ ↑(Fin.succ 0) • SimplicialObject.δ X (Fin.succ 0) +
(-1) ^ ↑(Fin.succ 1) • SimplicialObject.δ X (Fin.succ 1)))) =
0
[PROOFSTEP]
simp only [Fin.val_zero, pow_zero, pow_one, pow_add, one_smul, neg_smul, Fin.mk_one, Fin.val_succ, Fin.val_one,
Fin.succ_one_eq_two, P_zero, HomologicalComplex.id_f, Fin.val_two, pow_two, mul_neg, one_mul, neg_mul, neg_neg,
id_comp, add_comp, comp_add, Fin.mk_zero, neg_comp, comp_neg, Fin.succ_zero_eq_one]
[GOAL]
case neg.zero.head
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q : ℕ
hq :
∀ (i : Fin (Nat.zero + 1)),
Nat.zero + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.zero + 1) = 0
h : ¬0 + 1 ≤ 0 + q
hi : 0 = 0 + q
⊢ SimplicialObject.σ X 0 +
(SimplicialObject.σ X 0 ≫ SimplicialObject.δ X 0 ≫ SimplicialObject.σ X 0 +
-SimplicialObject.σ X 0 ≫ SimplicialObject.δ X 1 ≫ SimplicialObject.σ X 0 +
(-SimplicialObject.σ X 0 ≫ SimplicialObject.σ X 1 ≫ SimplicialObject.δ X 0 +
(SimplicialObject.σ X 0 ≫ SimplicialObject.σ X 1 ≫ SimplicialObject.δ X 1 +
-SimplicialObject.σ X 0 ≫ SimplicialObject.σ X 1 ≫ SimplicialObject.δ X 2))) =
0
[PROOFSTEP]
erw [SimplicialObject.δ_comp_σ_self, SimplicialObject.δ_comp_σ_self_assoc, SimplicialObject.δ_comp_σ_succ, comp_id,
SimplicialObject.δ_comp_σ_of_le X (show (0 : Fin 2) ≤ Fin.castSucc 0 by rw [Fin.castSucc_zero]),
SimplicialObject.δ_comp_σ_self_assoc, SimplicialObject.δ_comp_σ_succ_assoc]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q : ℕ
hq :
∀ (i : Fin (Nat.zero + 1)),
Nat.zero + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.zero + 1) = 0
h : ¬0 + 1 ≤ 0 + q
hi : 0 = 0 + q
⊢ 0 ≤ Fin.castSucc 0
[PROOFSTEP]
rw [Fin.castSucc_zero]
[GOAL]
case neg.zero.head
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q : ℕ
hq :
∀ (i : Fin (Nat.zero + 1)),
Nat.zero + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.zero + 1) = 0
h : ¬0 + 1 ≤ 0 + q
hi : 0 = 0 + q
⊢ SimplicialObject.σ X 0 +
(SimplicialObject.σ X 0 + -SimplicialObject.σ X 0 +
(-SimplicialObject.σ X 0 + (SimplicialObject.σ X 0 + -SimplicialObject.σ X 0))) =
0
[PROOFSTEP]
simp only [add_right_neg, add_zero, zero_add]
[GOAL]
case neg.succ
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q n : ℕ
hq :
∀ (i : Fin (Nat.succ n + 1)),
Nat.succ n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
i : Fin (Nat.succ n + 1)
h : ¬Nat.succ n + 1 ≤ ↑i + q
hi : Nat.succ n = ↑i + q
⊢ SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P (Nat.succ q)) (Nat.succ n + 1) = 0
[PROOFSTEP]
rw [← id_comp (X.σ i), ← (P_add_Q_f q n.succ : _ = 𝟙 (X.obj _)), add_comp, add_comp, P_succ]
[GOAL]
case neg.succ
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q n : ℕ
hq :
∀ (i : Fin (Nat.succ n + 1)),
Nat.succ n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
i : Fin (Nat.succ n + 1)
h : ¬Nat.succ n + 1 ≤ ↑i + q
hi : Nat.succ n = ↑i + q
⊢ (HomologicalComplex.Hom.f (P q) (Nat.succ n) ≫ SimplicialObject.σ X i) ≫
HomologicalComplex.Hom.f (P q ≫ (𝟙 (AlternatingFaceMapComplex.obj X) + Hσ q)) (Nat.succ n + 1) +
(HomologicalComplex.Hom.f (Q q) (Nat.succ n) ≫ SimplicialObject.σ X i) ≫
HomologicalComplex.Hom.f (P q ≫ (𝟙 (AlternatingFaceMapComplex.obj X) + Hσ q)) (Nat.succ n + 1) =
0
[PROOFSTEP]
have v : HigherFacesVanish q ((P q).f n.succ ≫ X.σ i) := (HigherFacesVanish.of_P q n).comp_σ hi
[GOAL]
case neg.succ
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q n : ℕ
hq :
∀ (i : Fin (Nat.succ n + 1)),
Nat.succ n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
i : Fin (Nat.succ n + 1)
h : ¬Nat.succ n + 1 ≤ ↑i + q
hi : Nat.succ n = ↑i + q
v : HigherFacesVanish q (HomologicalComplex.Hom.f (P q) (Nat.succ n) ≫ SimplicialObject.σ X i)
⊢ (HomologicalComplex.Hom.f (P q) (Nat.succ n) ≫ SimplicialObject.σ X i) ≫
HomologicalComplex.Hom.f (P q ≫ (𝟙 (AlternatingFaceMapComplex.obj X) + Hσ q)) (Nat.succ n + 1) +
(HomologicalComplex.Hom.f (Q q) (Nat.succ n) ≫ SimplicialObject.σ X i) ≫
HomologicalComplex.Hom.f (P q ≫ (𝟙 (AlternatingFaceMapComplex.obj X) + Hσ q)) (Nat.succ n + 1) =
0
[PROOFSTEP]
erw [← assoc, v.comp_P_eq_self, HomologicalComplex.add_f_apply, Preadditive.comp_add, comp_id, v.comp_Hσ_eq hi, assoc,
SimplicialObject.δ_comp_σ_succ_assoc, Fin.eta, decomposition_Q n q, sum_comp, sum_comp, Finset.sum_eq_zero, add_zero,
add_neg_eq_zero]
[GOAL]
case neg.succ
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q n : ℕ
hq :
∀ (i : Fin (Nat.succ n + 1)),
Nat.succ n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
i : Fin (Nat.succ n + 1)
h : ¬Nat.succ n + 1 ≤ ↑i + q
hi : Nat.succ n = ↑i + q
v : HigherFacesVanish q (HomologicalComplex.Hom.f (P q) (Nat.succ n) ≫ SimplicialObject.σ X i)
⊢ ∀ (x : Fin (n + 1)),
x ∈ Finset.filter (fun i => ↑i < q) Finset.univ →
((HomologicalComplex.Hom.f (P ↑x) (n + 1) ≫
SimplicialObject.δ X (Fin.succ (↑Fin.revPerm x)) ≫ SimplicialObject.σ X (↑Fin.revPerm x)) ≫
SimplicialObject.σ X i) ≫
HomologicalComplex.Hom.f (P q ≫ (𝟙 (AlternatingFaceMapComplex.obj X) + Hσ q)) (Nat.succ n + 1) =
0
[PROOFSTEP]
intro j hj
[GOAL]
case neg.succ
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q n : ℕ
hq :
∀ (i : Fin (Nat.succ n + 1)),
Nat.succ n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
i : Fin (Nat.succ n + 1)
h : ¬Nat.succ n + 1 ≤ ↑i + q
hi : Nat.succ n = ↑i + q
v : HigherFacesVanish q (HomologicalComplex.Hom.f (P q) (Nat.succ n) ≫ SimplicialObject.σ X i)
j : Fin (n + 1)
hj : j ∈ Finset.filter (fun i => ↑i < q) Finset.univ
⊢ ((HomologicalComplex.Hom.f (P ↑j) (n + 1) ≫
SimplicialObject.δ X (Fin.succ (↑Fin.revPerm j)) ≫ SimplicialObject.σ X (↑Fin.revPerm j)) ≫
SimplicialObject.σ X i) ≫
HomologicalComplex.Hom.f (P q ≫ (𝟙 (AlternatingFaceMapComplex.obj X) + Hσ q)) (Nat.succ n + 1) =
0
[PROOFSTEP]
simp only [true_and_iff, Finset.mem_univ, Finset.mem_filter] at hj
[GOAL]
case neg.succ
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q n : ℕ
hq :
∀ (i : Fin (Nat.succ n + 1)),
Nat.succ n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
i : Fin (Nat.succ n + 1)
h : ¬Nat.succ n + 1 ≤ ↑i + q
hi : Nat.succ n = ↑i + q
v : HigherFacesVanish q (HomologicalComplex.Hom.f (P q) (Nat.succ n) ≫ SimplicialObject.σ X i)
j : Fin (n + 1)
hj : ↑j < q
⊢ ((HomologicalComplex.Hom.f (P ↑j) (n + 1) ≫
SimplicialObject.δ X (Fin.succ (↑Fin.revPerm j)) ≫ SimplicialObject.σ X (↑Fin.revPerm j)) ≫
SimplicialObject.σ X i) ≫
HomologicalComplex.Hom.f (P q ≫ (𝟙 (AlternatingFaceMapComplex.obj X) + Hσ q)) (Nat.succ n + 1) =
0
[PROOFSTEP]
simp only [Nat.succ_eq_add_one] at hi
[GOAL]
case neg.succ
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q n : ℕ
hq :
∀ (i : Fin (Nat.succ n + 1)),
Nat.succ n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
i : Fin (Nat.succ n + 1)
h : ¬Nat.succ n + 1 ≤ ↑i + q
hi : n + 1 = ↑i + q
v : HigherFacesVanish q (HomologicalComplex.Hom.f (P q) (Nat.succ n) ≫ SimplicialObject.σ X i)
j : Fin (n + 1)
hj : ↑j < q
⊢ ((HomologicalComplex.Hom.f (P ↑j) (n + 1) ≫
SimplicialObject.δ X (Fin.succ (↑Fin.revPerm j)) ≫ SimplicialObject.σ X (↑Fin.revPerm j)) ≫
SimplicialObject.σ X i) ≫
HomologicalComplex.Hom.f (P q ≫ (𝟙 (AlternatingFaceMapComplex.obj X) + Hσ q)) (Nat.succ n + 1) =
0
[PROOFSTEP]
obtain ⟨k, hk⟩ := Nat.le.dest (Nat.lt_succ_iff.mp (Fin.is_lt j))
[GOAL]
case neg.succ.intro
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q n : ℕ
hq :
∀ (i : Fin (Nat.succ n + 1)),
Nat.succ n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
i : Fin (Nat.succ n + 1)
h : ¬Nat.succ n + 1 ≤ ↑i + q
hi : n + 1 = ↑i + q
v : HigherFacesVanish q (HomologicalComplex.Hom.f (P q) (Nat.succ n) ≫ SimplicialObject.σ X i)
j : Fin (n + 1)
hj : ↑j < q
k : ℕ
hk : ↑j + k = n
⊢ ((HomologicalComplex.Hom.f (P ↑j) (n + 1) ≫
SimplicialObject.δ X (Fin.succ (↑Fin.revPerm j)) ≫ SimplicialObject.σ X (↑Fin.revPerm j)) ≫
SimplicialObject.σ X i) ≫
HomologicalComplex.Hom.f (P q ≫ (𝟙 (AlternatingFaceMapComplex.obj X) + Hσ q)) (Nat.succ n + 1) =
0
[PROOFSTEP]
rw [add_comm] at hk
[GOAL]
case neg.succ.intro
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q n : ℕ
hq :
∀ (i : Fin (Nat.succ n + 1)),
Nat.succ n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
i : Fin (Nat.succ n + 1)
h : ¬Nat.succ n + 1 ≤ ↑i + q
hi : n + 1 = ↑i + q
v : HigherFacesVanish q (HomologicalComplex.Hom.f (P q) (Nat.succ n) ≫ SimplicialObject.σ X i)
j : Fin (n + 1)
hj : ↑j < q
k : ℕ
hk : k + ↑j = n
⊢ ((HomologicalComplex.Hom.f (P ↑j) (n + 1) ≫
SimplicialObject.δ X (Fin.succ (↑Fin.revPerm j)) ≫ SimplicialObject.σ X (↑Fin.revPerm j)) ≫
SimplicialObject.σ X i) ≫
HomologicalComplex.Hom.f (P q ≫ (𝟙 (AlternatingFaceMapComplex.obj X) + Hσ q)) (Nat.succ n + 1) =
0
[PROOFSTEP]
have hi' : i = Fin.castSucc ⟨i, by linarith⟩ := by
ext
simp only [Fin.castSucc_mk, Fin.eta]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q n : ℕ
hq :
∀ (i : Fin (Nat.succ n + 1)),
Nat.succ n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
i : Fin (Nat.succ n + 1)
h : ¬Nat.succ n + 1 ≤ ↑i + q
hi : n + 1 = ↑i + q
v : HigherFacesVanish q (HomologicalComplex.Hom.f (P q) (Nat.succ n) ≫ SimplicialObject.σ X i)
j : Fin (n + 1)
hj : ↑j < q
k : ℕ
hk : k + ↑j = n
⊢ ↑i < n + 1
[PROOFSTEP]
linarith
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q n : ℕ
hq :
∀ (i : Fin (Nat.succ n + 1)),
Nat.succ n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
i : Fin (Nat.succ n + 1)
h : ¬Nat.succ n + 1 ≤ ↑i + q
hi : n + 1 = ↑i + q
v : HigherFacesVanish q (HomologicalComplex.Hom.f (P q) (Nat.succ n) ≫ SimplicialObject.σ X i)
j : Fin (n + 1)
hj : ↑j < q
k : ℕ
hk : k + ↑j = n
⊢ i = Fin.castSucc { val := ↑i, isLt := (_ : ↑i < n + 1) }
[PROOFSTEP]
ext
[GOAL]
case h
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q n : ℕ
hq :
∀ (i : Fin (Nat.succ n + 1)),
Nat.succ n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
i : Fin (Nat.succ n + 1)
h : ¬Nat.succ n + 1 ≤ ↑i + q
hi : n + 1 = ↑i + q
v : HigherFacesVanish q (HomologicalComplex.Hom.f (P q) (Nat.succ n) ≫ SimplicialObject.σ X i)
j : Fin (n + 1)
hj : ↑j < q
k : ℕ
hk : k + ↑j = n
⊢ ↑i = ↑(Fin.castSucc { val := ↑i, isLt := (_ : ↑i < n + 1) })
[PROOFSTEP]
simp only [Fin.castSucc_mk, Fin.eta]
[GOAL]
case neg.succ.intro
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q n : ℕ
hq :
∀ (i : Fin (Nat.succ n + 1)),
Nat.succ n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
i : Fin (Nat.succ n + 1)
h : ¬Nat.succ n + 1 ≤ ↑i + q
hi : n + 1 = ↑i + q
v : HigherFacesVanish q (HomologicalComplex.Hom.f (P q) (Nat.succ n) ≫ SimplicialObject.σ X i)
j : Fin (n + 1)
hj : ↑j < q
k : ℕ
hk : k + ↑j = n
hi' : i = Fin.castSucc { val := ↑i, isLt := (_ : ↑i < n + 1) }
⊢ ((HomologicalComplex.Hom.f (P ↑j) (n + 1) ≫
SimplicialObject.δ X (Fin.succ (↑Fin.revPerm j)) ≫ SimplicialObject.σ X (↑Fin.revPerm j)) ≫
SimplicialObject.σ X i) ≫
HomologicalComplex.Hom.f (P q ≫ (𝟙 (AlternatingFaceMapComplex.obj X) + Hσ q)) (Nat.succ n + 1) =
0
[PROOFSTEP]
have eq :=
hq j.revPerm.succ
(by
simp only [← hk, Fin.revPerm_eq j hk.symm, Nat.succ_eq_add_one, Fin.succ_mk, Fin.val_mk]
linarith)
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q n : ℕ
hq :
∀ (i : Fin (Nat.succ n + 1)),
Nat.succ n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
i : Fin (Nat.succ n + 1)
h : ¬Nat.succ n + 1 ≤ ↑i + q
hi : n + 1 = ↑i + q
v : HigherFacesVanish q (HomologicalComplex.Hom.f (P q) (Nat.succ n) ≫ SimplicialObject.σ X i)
j : Fin (n + 1)
hj : ↑j < q
k : ℕ
hk : k + ↑j = n
hi' : i = Fin.castSucc { val := ↑i, isLt := (_ : ↑i < n + 1) }
⊢ Nat.succ n + 1 ≤ ↑(Fin.succ (↑Fin.revPerm j)) + q
[PROOFSTEP]
simp only [← hk, Fin.revPerm_eq j hk.symm, Nat.succ_eq_add_one, Fin.succ_mk, Fin.val_mk]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q n : ℕ
hq :
∀ (i : Fin (Nat.succ n + 1)),
Nat.succ n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
i : Fin (Nat.succ n + 1)
h : ¬Nat.succ n + 1 ≤ ↑i + q
hi : n + 1 = ↑i + q
v : HigherFacesVanish q (HomologicalComplex.Hom.f (P q) (Nat.succ n) ≫ SimplicialObject.σ X i)
j : Fin (n + 1)
hj : ↑j < q
k : ℕ
hk : k + ↑j = n
hi' : i = Fin.castSucc { val := ↑i, isLt := (_ : ↑i < n + 1) }
⊢ k + ↑j + 1 + 1 ≤ k + 1 + q
[PROOFSTEP]
linarith
[GOAL]
case neg.succ.intro
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q n : ℕ
hq :
∀ (i : Fin (Nat.succ n + 1)),
Nat.succ n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
i : Fin (Nat.succ n + 1)
h : ¬Nat.succ n + 1 ≤ ↑i + q
hi : n + 1 = ↑i + q
v : HigherFacesVanish q (HomologicalComplex.Hom.f (P q) (Nat.succ n) ≫ SimplicialObject.σ X i)
j : Fin (n + 1)
hj : ↑j < q
k : ℕ
hk : k + ↑j = n
hi' : i = Fin.castSucc { val := ↑i, isLt := (_ : ↑i < n + 1) }
eq : SimplicialObject.σ X (Fin.succ (↑Fin.revPerm j)) ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
⊢ ((HomologicalComplex.Hom.f (P ↑j) (n + 1) ≫
SimplicialObject.δ X (Fin.succ (↑Fin.revPerm j)) ≫ SimplicialObject.σ X (↑Fin.revPerm j)) ≫
SimplicialObject.σ X i) ≫
HomologicalComplex.Hom.f (P q ≫ (𝟙 (AlternatingFaceMapComplex.obj X) + Hσ q)) (Nat.succ n + 1) =
0
[PROOFSTEP]
rw [HomologicalComplex.comp_f, assoc, assoc, assoc, hi', SimplicialObject.σ_comp_σ_assoc, reassoc_of% eq, zero_comp,
comp_zero, comp_zero, comp_zero]
[GOAL]
case neg.succ.intro.H
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q n : ℕ
hq :
∀ (i : Fin (Nat.succ n + 1)),
Nat.succ n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
i : Fin (Nat.succ n + 1)
h : ¬Nat.succ n + 1 ≤ ↑i + q
hi : n + 1 = ↑i + q
v : HigherFacesVanish q (HomologicalComplex.Hom.f (P q) (Nat.succ n) ≫ SimplicialObject.σ X i)
j : Fin (n + 1)
hj : ↑j < q
k : ℕ
hk : k + ↑j = n
hi' : i = Fin.castSucc { val := ↑i, isLt := (_ : ↑i < n + 1) }
eq : SimplicialObject.σ X (Fin.succ (↑Fin.revPerm j)) ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
⊢ { val := ↑i, isLt := (_ : ↑i < n + 1) } ≤ ↑Fin.revPerm j
[PROOFSTEP]
simp only [Fin.revPerm_eq j hk.symm, Fin.le_iff_val_le_val, Fin.val_mk]
[GOAL]
case neg.succ.intro.H
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
q n : ℕ
hq :
∀ (i : Fin (Nat.succ n + 1)),
Nat.succ n + 1 ≤ ↑i + q → SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
i : Fin (Nat.succ n + 1)
h : ¬Nat.succ n + 1 ≤ ↑i + q
hi : n + 1 = ↑i + q
v : HigherFacesVanish q (HomologicalComplex.Hom.f (P q) (Nat.succ n) ≫ SimplicialObject.σ X i)
j : Fin (n + 1)
hj : ↑j < q
k : ℕ
hk : k + ↑j = n
hi' : i = Fin.castSucc { val := ↑i, isLt := (_ : ↑i < n + 1) }
eq : SimplicialObject.σ X (Fin.succ (↑Fin.revPerm j)) ≫ HomologicalComplex.Hom.f (P q) (Nat.succ n + 1) = 0
⊢ ↑i ≤ k
[PROOFSTEP]
linarith
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
n : ℕ
i : Fin (n + 1)
⊢ SimplicialObject.σ X i ≫ HomologicalComplex.Hom.f PInfty (n + 1) = 0
[PROOFSTEP]
rw [PInfty_f, σ_comp_P_eq_zero X i]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
n : ℕ
i : Fin (n + 1)
⊢ n + 1 ≤ ↑i + (n + 1)
[PROOFSTEP]
simp only [le_add_iff_nonneg_left, zero_le]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
n : ℕ
Δ' : SimplexCategory
θ : [n] ⟶ Δ'
hθ : ¬Mono θ
⊢ X.map θ.op ≫ HomologicalComplex.Hom.f PInfty n = 0
[PROOFSTEP]
rw [SimplexCategory.mono_iff_injective] at hθ
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
n : ℕ
Δ' : SimplexCategory
θ : [n] ⟶ Δ'
hθ : ¬Function.Injective ↑(SimplexCategory.Hom.toOrderHom θ)
⊢ X.map θ.op ≫ HomologicalComplex.Hom.f PInfty n = 0
[PROOFSTEP]
cases n
[GOAL]
case zero
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Δ' : SimplexCategory
θ : [Nat.zero] ⟶ Δ'
hθ : ¬Function.Injective ↑(SimplexCategory.Hom.toOrderHom θ)
⊢ X.map θ.op ≫ HomologicalComplex.Hom.f PInfty Nat.zero = 0
[PROOFSTEP]
exfalso
[GOAL]
case zero.h
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Δ' : SimplexCategory
θ : [Nat.zero] ⟶ Δ'
hθ : ¬Function.Injective ↑(SimplexCategory.Hom.toOrderHom θ)
⊢ False
[PROOFSTEP]
apply hθ
[GOAL]
case zero.h
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Δ' : SimplexCategory
θ : [Nat.zero] ⟶ Δ'
hθ : ¬Function.Injective ↑(SimplexCategory.Hom.toOrderHom θ)
⊢ Function.Injective ↑(SimplexCategory.Hom.toOrderHom θ)
[PROOFSTEP]
intro x y h
[GOAL]
case zero.h
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Δ' : SimplexCategory
θ : [Nat.zero] ⟶ Δ'
hθ : ¬Function.Injective ↑(SimplexCategory.Hom.toOrderHom θ)
x y : Fin (SimplexCategory.len [Nat.zero] + 1)
h : ↑(SimplexCategory.Hom.toOrderHom θ) x = ↑(SimplexCategory.Hom.toOrderHom θ) y
⊢ x = y
[PROOFSTEP]
fin_cases x
[GOAL]
case zero.h.head
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Δ' : SimplexCategory
θ : [Nat.zero] ⟶ Δ'
hθ : ¬Function.Injective ↑(SimplexCategory.Hom.toOrderHom θ)
y : Fin (SimplexCategory.len [Nat.zero] + 1)
h :
↑(SimplexCategory.Hom.toOrderHom θ) { val := 0, isLt := (_ : 0 < SimplexCategory.len [Nat.zero] + 1) } =
↑(SimplexCategory.Hom.toOrderHom θ) y
⊢ { val := 0, isLt := (_ : 0 < SimplexCategory.len [Nat.zero] + 1) } = y
[PROOFSTEP]
fin_cases y
[GOAL]
case zero.h.head.head
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Δ' : SimplexCategory
θ : [Nat.zero] ⟶ Δ'
hθ : ¬Function.Injective ↑(SimplexCategory.Hom.toOrderHom θ)
h :
↑(SimplexCategory.Hom.toOrderHom θ) { val := 0, isLt := (_ : 0 < SimplexCategory.len [Nat.zero] + 1) } =
↑(SimplexCategory.Hom.toOrderHom θ) { val := 0, isLt := (_ : 0 < SimplexCategory.len [Nat.zero] + 1) }
⊢ { val := 0, isLt := (_ : 0 < SimplexCategory.len [Nat.zero] + 1) } =
{ val := 0, isLt := (_ : 0 < SimplexCategory.len [Nat.zero] + 1) }
[PROOFSTEP]
rfl
[GOAL]
case succ
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Δ' : SimplexCategory
n✝ : ℕ
θ : [Nat.succ n✝] ⟶ Δ'
hθ : ¬Function.Injective ↑(SimplexCategory.Hom.toOrderHom θ)
⊢ X.map θ.op ≫ HomologicalComplex.Hom.f PInfty (Nat.succ n✝) = 0
[PROOFSTEP]
obtain ⟨i, α, h⟩ := SimplexCategory.eq_σ_comp_of_not_injective θ hθ
[GOAL]
case succ.intro.intro
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Δ' : SimplexCategory
n✝ : ℕ
θ : [Nat.succ n✝] ⟶ Δ'
hθ : ¬Function.Injective ↑(SimplexCategory.Hom.toOrderHom θ)
i : Fin (n✝ + 1)
α : [n✝] ⟶ Δ'
h : θ = SimplexCategory.σ i ≫ α
⊢ X.map θ.op ≫ HomologicalComplex.Hom.f PInfty (Nat.succ n✝) = 0
[PROOFSTEP]
rw [h, op_comp, X.map_comp, assoc, show X.map (SimplexCategory.σ i).op = X.σ i by rfl, σ_comp_PInfty, comp_zero]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Δ' : SimplexCategory
n✝ : ℕ
θ : [Nat.succ n✝] ⟶ Δ'
hθ : ¬Function.Injective ↑(SimplexCategory.Hom.toOrderHom θ)
i : Fin (n✝ + 1)
α : [n✝] ⟶ Δ'
h : θ = SimplexCategory.σ i ≫ α
⊢ X.map (SimplexCategory.σ i).op = SimplicialObject.σ X i
[PROOFSTEP]
rfl
|
[STATEMENT]
lemma K33_card:
assumes "K\<^bsub>3,3\<^esub> (mk_graph' G)" shows "ig_verts_cnt G = 6"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ig_verts_cnt G = 6
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. ig_verts_cnt G = 6
[PROOF STEP]
from assms
[PROOF STATE]
proof (chain)
picking this:
K\<^bsub>3,3\<^esub> (with_proj (mk_graph' G))
[PROOF STEP]
have "card (verts (mk_graph' G)) = 6"
[PROOF STATE]
proof (prove)
using this:
K\<^bsub>3,3\<^esub> (with_proj (mk_graph' G))
goal (1 subgoal):
1. card (verts (with_proj (mk_graph' G))) = 6
[PROOF STEP]
unfolding complete_bipartite_digraph_pair_def
[PROOF STATE]
proof (prove)
using this:
finite (pverts (mk_graph' G)) \<and> (\<exists>U V. pverts (mk_graph' G) = U \<union> V \<and> U \<inter> V = {} \<and> card U = 3 \<and> card V = 3 \<and> parcs (mk_graph' G) = U \<times> V \<union> V \<times> U)
goal (1 subgoal):
1. card (verts (with_proj (mk_graph' G))) = 6
[PROOF STEP]
by (auto simp: card_Un_disjoint)
[PROOF STATE]
proof (state)
this:
card (verts (with_proj (mk_graph' G))) = 6
goal (1 subgoal):
1. ig_verts_cnt G = 6
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
card (verts (with_proj (mk_graph' G))) = 6
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
card (verts (with_proj (mk_graph' G))) = 6
goal (1 subgoal):
1. ig_verts_cnt G = 6
[PROOF STEP]
using distinct_ig_verts
[PROOF STATE]
proof (prove)
using this:
card (verts (with_proj (mk_graph' G))) = 6
distinct (ig_verts ?G)
goal (1 subgoal):
1. ig_verts_cnt G = 6
[PROOF STEP]
by (auto simp: mkg'_simps distinct_card)
[PROOF STATE]
proof (state)
this:
ig_verts_cnt G = 6
goal:
No subgoals!
[PROOF STEP]
qed |
# Start by checking the byte-order.
ordered = 0x0123456789ABCDEF
@test 3512700564088504e-318 == reinterpret(Float64,ordered)
min_double64 = 0x0000000000000001
@test 5e-324 == reinterpret(Float64,min_double64)
max_double64 = 0x7fefffffffffffff
@test 1.7976931348623157e308 == reinterpret(Float64,max_double64)
# Start by checking the byte-order.
ordered = 0x01234567
@test float32(2.9988165487136453e-38) == reinterpret(Float32,ordered)
min_float32 = 0x00000001
@test float32(1.4e-45) == reinterpret(Float32,min_float32)
max_float32 = 0x7f7fffff
@test float32(3.4028234e38) == reinterpret(Float32,max_float32)
ordered = 0x0123456789ABCDEF
diy_fp = Grisu.Float(reinterpret(Float64,ordered))
@test 0x12 - 0x3FF - 52 == uint64(diy_fp.e)
# The 52 mantissa bits, plus the implicit 1 in bit 52 as a UINT64.
@test 0x0013456789ABCDEF== diy_fp.s
min_double64 = 0x0000000000000001
diy_fp = Grisu.Float(reinterpret(Float64,min_double64))
@test -0x3FF - 52 + 1 == uint64(diy_fp.e)
# This is a denormal so no hidden bit.
@test 1 == diy_fp.s
max_double64 = 0x7fefffffffffffff
diy_fp = Grisu.Float(reinterpret(Float64,max_double64))
@test 0x7FE - 0x3FF - 52 == uint64(diy_fp.e)
@test 0x001fffffffffffff== diy_fp.s
ordered = 0x01234567
diy_fp = Grisu.Float(reinterpret(Float32,ordered))
@test 0x2 - 0x7F - 23 == uint64(diy_fp.e)
# The 23 mantissa bits, plus the implicit 1 in bit 24 as a uint32_t.
@test 0xA34567 == uint64(diy_fp.s)
min_float32 = 0x00000001
diy_fp = Grisu.Float(reinterpret(Float32,min_float32))
@test -0x7F - 23 + 1 == uint64(diy_fp.e)
# This is a denormal so no hidden bit.
@test 1 == uint64(diy_fp.s)
max_float32 = 0x7f7fffff
diy_fp = Grisu.Float(reinterpret(Float32,max_float32))
@test 0xFE - 0x7F - 23 == uint64(diy_fp.e)
@test 0x00ffffff == uint64(diy_fp.s)
ordered = 0x0123456789ABCDEF
diy_fp = Grisu.normalize(Grisu.Float(reinterpret(Float64,ordered)))
@test 0x12 - 0x3FF - 52 - 11 == uint64(diy_fp.e)
@test 0x0013456789ABCDEF<< 11 == diy_fp.s
min_double64 = 0x0000000000000001
diy_fp = Grisu.normalize(Grisu.Float(reinterpret(Float64,min_double64)))
@test -0x3FF - 52 + 1 - 63 == uint64(diy_fp.e)
# This is a denormal so no hidden bit.
@test 0x8000000000000000== diy_fp.s
max_double64 = 0x7fefffffffffffff
diy_fp = Grisu.normalize(Grisu.Float(reinterpret(Float64,max_double64)))
@test 0x7FE - 0x3FF - 52 - 11 == uint64(diy_fp.e)
@test (0x001fffffffffffff<< 11) == diy_fp.s
min_double64 = 0x0000000000000001
@test Grisu.isdenormal(reinterpret(Float64,min_double64))
bits = 0x000FFFFFFFFFFFFF
@test Grisu.isdenormal(reinterpret(Float64,bits))
bits = 0x0010000000000000
@test !Grisu.isdenormal(reinterpret(Float64,bits))
min_float32 = 0x00000001
@test Grisu.isdenormal(reinterpret(Float32,min_float32))
bits = 0x007FFFFF
@test Grisu.isdenormal(reinterpret(Float32,bits))
bits = 0x00800000
@test !Grisu.isdenormal(reinterpret(Float32,bits))
diy_fp = Grisu.normalize(Grisu.Float(1.5))
boundary_minus, boundary_plus = Grisu.normalizedbound(1.5)
@test diy_fp.e == boundary_minus.e
@test diy_fp.e == boundary_plus.e
# 1.5 does not have a significand of the form 2^p (for some p).
# Therefore its boundaries are at the same distance.
@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s
@test (1 << 10) == diy_fp.s - boundary_minus.s
diy_fp = Grisu.normalize(Grisu.Float(1.0))
boundary_minus, boundary_plus = Grisu.normalizedbound(1.0)
@test diy_fp.e == boundary_minus.e
@test diy_fp.e == boundary_plus.e
# 1.0 does have a significand of the form 2^p (for some p).
# Therefore its lower boundary is twice as close as the upper boundary.
@test boundary_plus.s - diy_fp.s > diy_fp.s - boundary_minus.s
@test (1 << 9) == diy_fp.s - boundary_minus.s
@test (1 << 10) == boundary_plus.s - diy_fp.s
min_double64 = 0x0000000000000001
diy_fp = Grisu.normalize(Grisu.Float(reinterpret(Float64,min_double64)))
boundary_minus, boundary_plus = Grisu.normalizedbound(reinterpret(Float64,min_double64))
@test diy_fp.e == boundary_minus.e
@test diy_fp.e == boundary_plus.e
# min-value does not have a significand of the form 2^p (for some p).
# Therefore its boundaries are at the same distance.
@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s
# Denormals have their boundaries much closer.
@test (uint64(1) << 62) == diy_fp.s - boundary_minus.s
smallest_normal64 = 0x0010000000000000
diy_fp = Grisu.normalize(reinterpret(Float64,smallest_normal64))
boundary_minus, boundary_plus = Grisu.normalizedbound(reinterpret(Float64,smallest_normal64))
@test diy_fp.e == boundary_minus.e
@test diy_fp.e == boundary_plus.e
# Even though the significand is of the form 2^p (for some p), its boundaries
# are at the same distance. (This is the only exception).
@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s
@test (1 << 10) == diy_fp.s - boundary_minus.s
largest_denormal64 = 0x000FFFFFFFFFFFFF
diy_fp = Grisu.normalize(reinterpret(Float64,largest_denormal64))
boundary_minus, boundary_plus = Grisu.normalizedbound(reinterpret(Float64,largest_denormal64))
@test diy_fp.e == boundary_minus.e
@test diy_fp.e == boundary_plus.e
@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s
@test (1 << 11) == diy_fp.s - boundary_minus.s
max_double64 = 0x7fefffffffffffff
diy_fp = Grisu.normalize(reinterpret(Float64,max_double64))
boundary_minus, boundary_plus = Grisu.normalizedbound(reinterpret(Float64,max_double64))
@test diy_fp.e == boundary_minus.e
@test diy_fp.e == boundary_plus.e
# max-value does not have a significand of the form 2^p (for some p).
# Therefore its boundaries are at the same distance.
@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s
@test (1 << 10) == diy_fp.s - boundary_minus.s
kOne64 = uint64(1)
diy_fp = Grisu.normalize(Grisu.Float(float32(1.5)))
boundary_minus, boundary_plus = Grisu.normalizedbound(float32(1.5))
@test diy_fp.e == boundary_minus.e
@test diy_fp.e == boundary_plus.e
# 1.5 does not have a significand of the form 2^p (for some p).
# Therefore its boundaries are at the same distance.
@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s
# Normalization shifts the significand by 8 bits. Add 32 bits for the bigger
# data-type, and remove 1 because boundaries are at half a ULP.
@test (kOne64 << 39) == diy_fp.s - boundary_minus.s
diy_fp = Grisu.normalize(Grisu.Float(float32(1.0)))
boundary_minus, boundary_plus = Grisu.normalizedbound(float32(1.0))
@test diy_fp.e == boundary_minus.e
@test diy_fp.e == boundary_plus.e
# 1.0 does have a significand of the form 2^p (for some p).
# Therefore its lower boundary is twice as close as the upper boundary.
@test boundary_plus.s - diy_fp.s > diy_fp.s - boundary_minus.s
@test (kOne64 << 38) == diy_fp.s - boundary_minus.s
@test (kOne64 << 39) == boundary_plus.s - diy_fp.s
min_float32 = 0x00000001
diy_fp = Grisu.normalize(Grisu.Float(reinterpret(Float32,min_float32)))
boundary_minus, boundary_plus = Grisu.normalizedbound(reinterpret(Float32,min_float32))
@test diy_fp.e == boundary_minus.e
@test diy_fp.e == boundary_plus.e
# min-value does not have a significand of the form 2^p (for some p).
# Therefore its boundaries are at the same distance.
@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s
# Denormals have their boundaries much closer.
@test (kOne64 << 62) == diy_fp.s - boundary_minus.s
smallest_normal32 = 0x00800000
diy_fp = Grisu.normalize(Grisu.Float(reinterpret(Float32,smallest_normal32)))
boundary_minus, boundary_plus = Grisu.normalizedbound(reinterpret(Float32,smallest_normal32))
@test diy_fp.e == boundary_minus.e
@test diy_fp.e == boundary_plus.e
# Even though the significand is of the form 2^p (for some p), its boundaries
# are at the same distance. (This is the only exception).
@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s
@test (kOne64 << 39) == diy_fp.s - boundary_minus.s
largest_denormal32 = 0x007FFFFF
diy_fp = Grisu.normalize(Grisu.Float(reinterpret(Float32,largest_denormal32)))
boundary_minus, boundary_plus = Grisu.normalizedbound(reinterpret(Float32,largest_denormal32))
@test diy_fp.e == boundary_minus.e
@test diy_fp.e == boundary_plus.e
@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s
@test (kOne64 << 40) == diy_fp.s - boundary_minus.s
max_float32 = 0x7f7fffff
diy_fp = Grisu.normalize(Grisu.Float(reinterpret(Float32,max_float32)))
boundary_minus, boundary_plus = Grisu.normalizedbound(reinterpret(Float32,max_float32))
@test diy_fp.e == boundary_minus.e
@test diy_fp.e == boundary_plus.e
# max-value does not have a significand of the form 2^p (for some p).
# Therefore its boundaries are at the same distance.
@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s
@test (kOne64 << 39) == diy_fp.s - boundary_minus.s |
r=0.58
https://sandbox.dams.library.ucdavis.edu/fcrepo/rest/collection/sherry-lehmann/catalogs/d7ts3m/media/images/d7ts3m-014/svc:tesseract/full/full/0.58/default.jpg Accept:application/hocr+xml
|
[GOAL]
α : Type u_1
inst✝ : LinearOrderedSemifield α
r n : ℕ
⊢ ↑(choose n r) ≤ ↑(n ^ r) / ↑r !
[PROOFSTEP]
rw [le_div_iff']
[GOAL]
α : Type u_1
inst✝ : LinearOrderedSemifield α
r n : ℕ
⊢ ↑r ! * ↑(choose n r) ≤ ↑(n ^ r)
[PROOFSTEP]
norm_cast
[GOAL]
α : Type u_1
inst✝ : LinearOrderedSemifield α
r n : ℕ
⊢ r ! * choose n r ≤ n ^ r
[PROOFSTEP]
rw [← Nat.descFactorial_eq_factorial_mul_choose]
[GOAL]
α : Type u_1
inst✝ : LinearOrderedSemifield α
r n : ℕ
⊢ descFactorial n r ≤ n ^ r
[PROOFSTEP]
exact n.descFactorial_le_pow r
[GOAL]
α : Type u_1
inst✝ : LinearOrderedSemifield α
r n : ℕ
⊢ 0 < ↑r !
[PROOFSTEP]
exact_mod_cast r.factorial_pos
[GOAL]
α : Type u_1
inst✝ : LinearOrderedSemifield α
r n : ℕ
⊢ ↑((n + 1 - r) ^ r) / ↑r ! ≤ ↑(choose n r)
[PROOFSTEP]
rw [div_le_iff']
[GOAL]
α : Type u_1
inst✝ : LinearOrderedSemifield α
r n : ℕ
⊢ ↑((n + 1 - r) ^ r) ≤ ↑r ! * ↑(choose n r)
[PROOFSTEP]
norm_cast
[GOAL]
α : Type u_1
inst✝ : LinearOrderedSemifield α
r n : ℕ
⊢ (n + 1 - r) ^ r ≤ r ! * choose n r
[PROOFSTEP]
rw [← Nat.descFactorial_eq_factorial_mul_choose]
[GOAL]
α : Type u_1
inst✝ : LinearOrderedSemifield α
r n : ℕ
⊢ (n + 1 - r) ^ r ≤ descFactorial n r
[PROOFSTEP]
exact n.pow_sub_le_descFactorial r
[GOAL]
α : Type u_1
inst✝ : LinearOrderedSemifield α
r n : ℕ
⊢ 0 < ↑r !
[PROOFSTEP]
exact_mod_cast r.factorial_pos
|
# author Mauro Baresic
# email: [email protected]
import sys
import numpy as np
class MinDifference():
Cch = 1
Cde = 1
Cin = 1
m = 0
n = 0
R = ''
B = ''
D = None
def __init__(self,R,B):
self.R = R
self.B = B
self.m = len(R)
self.n = len(B)
self.D = np.zeros((self.m+1,self.n+1),dtype = np.int)
def calculate(self):
#self.D[(0,0)] = 0
for j in xrange(1,self.n+1):
self.D[(0,j)] = j
for i in xrange(1,self.m+1):
self.D[(i,0)] = i
for i in xrange(1,self.m+1):
for j in xrange(1,self.n+1):
self.D[(i,j)] = min((self.D[i-1,j] + self.Cde, self.D[(i,j-1)] + self.Cin, self.D[(i-1,j-1)] + self.compare(i-1,j-1)))
def compare(self, i, j):
if (i<0 or i> self.m or j<0 or j> self.n):
return
if (i>len(self.R)-1 or j>len(self.B)-1):
return
if (self.R[i] == self.B[j]):
return 0
else:
return self.Cch
def outputScreen(self):
if (self.D is None):
return
for i in xrange(self.m+1):
row = ''
for j in xrange(self.n+1):
row += str(self.D[i,j]) + '\t'
sys.stdout.write(row + '\n')
def outputFile(self, path):
if (self.D is None):
return
f = open(path,'w')
for i in xrange(self.m+1):
row = ''
for j in xrange(self.n+1):
row += str(self.D[i,j]) + '\t'
f.write(row + '\n')
f.close()
def reconstructMinPath(self):
pass
if __name__ == "__main__":
#path = sys.argv[1]
path = "podaci.txt"
f = open(path,'r')
rows = [row.strip() for row in f.readlines()]
f.close()
if (len(rows) != 2):
print "Use!"
sys.exit()
R = rows[0]
B = rows[1]
md = MinDifference(R,B)
md.calculate()
md.outputScreen()
|
State Before: K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
⊢ Respects (TM2.step M) (TM1.step (tr M)) TrCfg State After: K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
c₁ : Cfg₂
c₂ : TM1.Cfg Γ' Λ' σ
h : TrCfg c₁ c₂
⊢ match TM2.step M c₁ with
| some b₁ => ∃ b₂, TrCfg b₁ b₂ ∧ Reaches₁ (TM1.step (tr M)) c₂ b₂
| none => TM1.step (tr M) c₂ = none Tactic: intro c₁ c₂ h State Before: K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
c₁ : Cfg₂
c₂ : TM1.Cfg Γ' Λ' σ
h : TrCfg c₁ c₂
⊢ match TM2.step M c₁ with
| some b₁ => ∃ b₂, TrCfg b₁ b₂ ∧ Reaches₁ (TM1.step (tr M)) c₂ b₂
| none => TM1.step (tr M) c₂ = none State After: case mk
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
l : Option Λ
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
⊢ match TM2.step M { l := l, var := v, stk := S } with
| some b₁ =>
∃ b₂,
TrCfg b₁ b₂ ∧
Reaches₁ (TM1.step (tr M)) { l := Option.map normal l, var := v, Tape := Tape.mk' ∅ (addBottom L) } b₂
| none => TM1.step (tr M) { l := Option.map normal l, var := v, Tape := Tape.mk' ∅ (addBottom L) } = none Tactic: cases' h with l v S L hT State Before: case mk
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
l : Option Λ
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
⊢ match TM2.step M { l := l, var := v, stk := S } with
| some b₁ =>
∃ b₂,
TrCfg b₁ b₂ ∧
Reaches₁ (TM1.step (tr M)) { l := Option.map normal l, var := v, Tape := Tape.mk' ∅ (addBottom L) } b₂
| none => TM1.step (tr M) { l := Option.map normal l, var := v, Tape := Tape.mk' ∅ (addBottom L) } = none State After: case mk.none
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
⊢ match TM2.step M { l := none, var := v, stk := S } with
| some b₁ =>
∃ b₂,
TrCfg b₁ b₂ ∧
Reaches₁ (TM1.step (tr M)) { l := Option.map normal none, var := v, Tape := Tape.mk' ∅ (addBottom L) } b₂
| none => TM1.step (tr M) { l := Option.map normal none, var := v, Tape := Tape.mk' ∅ (addBottom L) } = none
case mk.some
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
l : Λ
⊢ match TM2.step M { l := some l, var := v, stk := S } with
| some b₁ =>
∃ b₂,
TrCfg b₁ b₂ ∧
Reaches₁ (TM1.step (tr M)) { l := Option.map normal (some l), var := v, Tape := Tape.mk' ∅ (addBottom L) } b₂
| none => TM1.step (tr M) { l := Option.map normal (some l), var := v, Tape := Tape.mk' ∅ (addBottom L) } = none Tactic: cases' l with l State Before: case mk.some
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
l : Λ
⊢ match TM2.step M { l := some l, var := v, stk := S } with
| some b₁ =>
∃ b₂,
TrCfg b₁ b₂ ∧
Reaches₁ (TM1.step (tr M)) { l := Option.map normal (some l), var := v, Tape := Tape.mk' ∅ (addBottom L) } b₂
| none => TM1.step (tr M) { l := Option.map normal (some l), var := v, Tape := Tape.mk' ∅ (addBottom L) } = none State After: case mk.some
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
l : Λ
⊢ ∃ b₂,
TrCfg (TM2.stepAux (M l) v S) b₂ ∧
Reaches₁ (TM1.step (tr M)) { l := some (normal l), var := v, Tape := Tape.mk' ∅ (addBottom L) } b₂ Tactic: simp only [TM2.step, Respects, Option.map_some'] State Before: case mk.some
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
l : Λ
⊢ ∃ b₂,
TrCfg (TM2.stepAux (M l) v S) b₂ ∧
Reaches₁ (TM1.step (tr M)) { l := some (normal l), var := v, Tape := Tape.mk' ∅ (addBottom L) } b₂ State After: case mk.some.intro.intro
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
l : Λ
b : ?m.734846
c : ?m.735219 b
r : Reaches (TM1.step (tr M)) (?m.735220 b) (?m.735221 b)
⊢ ∃ b₂,
TrCfg (TM2.stepAux (M l) v S) b₂ ∧
Reaches₁ (TM1.step (tr M)) { l := some (normal l), var := v, Tape := Tape.mk' ∅ (addBottom L) } b₂
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
l : Λ
⊢ ∃ b, ?m.735219 b ∧ Reaches (TM1.step (tr M)) (?m.735220 b) (?m.735221 b) Tactic: rsuffices ⟨b, c, r⟩ : ∃ b, _ ∧ Reaches (TM1.step (tr M)) _ _ State Before: K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
l : Λ
⊢ ∃ b,
TrCfg (TM2.stepAux (M l) v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (tr M (normal l)) v (Tape.mk' ∅ (addBottom L))) b State After: K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
l : Λ
⊢ ∃ b,
TrCfg (TM2.stepAux (M l) v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal (M l)) v (Tape.mk' ∅ (addBottom L))) b Tactic: simp only [tr] State Before: K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
l : Λ
⊢ ∃ b,
TrCfg (TM2.stepAux (M l) v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal (M l)) v (Tape.mk' ∅ (addBottom L))) b State After: K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
l : Λ
N : Stmt₂
⊢ ∃ b, TrCfg (TM2.stepAux N v S) b ∧ Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal N) v (Tape.mk' ∅ (addBottom L))) b Tactic: generalize M l = N State Before: K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
l : Λ
N : Stmt₂
⊢ ∃ b, TrCfg (TM2.stepAux N v S) b ∧ Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal N) v (Tape.mk' ∅ (addBottom L))) b State After: no goals Tactic: induction N using stmtStRec generalizing v S L hT with
| H₁ k s q IH => exact tr_respects_aux M hT s @IH
| H₂ a _ IH => exact IH _ hT
| H₃ p q₁ q₂ IH₁ IH₂ =>
unfold TM2.stepAux trNormal TM1.stepAux
simp only []
cases p v <;> [exact IH₂ _ hT; exact IH₁ _ hT]
| H₄ => exact ⟨_, ⟨_, hT⟩, ReflTransGen.refl⟩
| H₅ => exact ⟨_, ⟨_, hT⟩, ReflTransGen.refl⟩ State Before: case mk.none
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
⊢ match TM2.step M { l := none, var := v, stk := S } with
| some b₁ =>
∃ b₂,
TrCfg b₁ b₂ ∧
Reaches₁ (TM1.step (tr M)) { l := Option.map normal none, var := v, Tape := Tape.mk' ∅ (addBottom L) } b₂
| none => TM1.step (tr M) { l := Option.map normal none, var := v, Tape := Tape.mk' ∅ (addBottom L) } = none State After: no goals Tactic: constructor State Before: case mk.some.intro.intro
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
l : Λ
b : ?m.734846
c : ?m.735219 b
r : Reaches (TM1.step (tr M)) (?m.735220 b) (?m.735221 b)
⊢ ∃ b₂,
TrCfg (TM2.stepAux (M l) v S) b₂ ∧
Reaches₁ (TM1.step (tr M)) { l := some (normal l), var := v, Tape := Tape.mk' ∅ (addBottom L) } b₂ State After: no goals Tactic: exact ⟨b, c, TransGen.head' rfl r⟩ State Before: case H₁
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
l : Λ
k : K
s : StAct k
q : Stmt₂
IH :
∀ {v : σ} {S : (k : K) → List (Γ k)} (L : ListBlank ((k : K) → Option (Γ k))),
(∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))) →
∃ b,
TrCfg (TM2.stepAux q v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal q) v (Tape.mk' ∅ (addBottom L))) b
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
⊢ ∃ b,
TrCfg (TM2.stepAux (stRun s q) v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal (stRun s q)) v (Tape.mk' ∅ (addBottom L))) b State After: no goals Tactic: exact tr_respects_aux M hT s @IH State Before: case H₂
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
l : Λ
a : σ → σ
q✝ : Stmt₂
IH :
∀ {v : σ} {S : (k : K) → List (Γ k)} (L : ListBlank ((k : K) → Option (Γ k))),
(∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))) →
∃ b,
TrCfg (TM2.stepAux q✝ v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal q✝) v (Tape.mk' ∅ (addBottom L))) b
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
⊢ ∃ b,
TrCfg (TM2.stepAux (TM2.Stmt.load a q✝) v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal (TM2.Stmt.load a q✝)) v (Tape.mk' ∅ (addBottom L))) b State After: no goals Tactic: exact IH _ hT State Before: case H₃
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
l : Λ
p : σ → Bool
q₁ q₂ : Stmt₂
IH₁ :
∀ {v : σ} {S : (k : K) → List (Γ k)} (L : ListBlank ((k : K) → Option (Γ k))),
(∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))) →
∃ b,
TrCfg (TM2.stepAux q₁ v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal q₁) v (Tape.mk' ∅ (addBottom L))) b
IH₂ :
∀ {v : σ} {S : (k : K) → List (Γ k)} (L : ListBlank ((k : K) → Option (Γ k))),
(∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))) →
∃ b,
TrCfg (TM2.stepAux q₂ v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal q₂) v (Tape.mk' ∅ (addBottom L))) b
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
⊢ ∃ b,
TrCfg (TM2.stepAux (TM2.Stmt.branch p q₁ q₂) v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal (TM2.Stmt.branch p q₁ q₂)) v (Tape.mk' ∅ (addBottom L))) b State After: case H₃
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
l : Λ
p : σ → Bool
q₁ q₂ : Stmt₂
IH₁ :
∀ {v : σ} {S : (k : K) → List (Γ k)} (L : ListBlank ((k : K) → Option (Γ k))),
(∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))) →
∃ b,
TrCfg (TM2.stepAux q₁ v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal q₁) v (Tape.mk' ∅ (addBottom L))) b
IH₂ :
∀ {v : σ} {S : (k : K) → List (Γ k)} (L : ListBlank ((k : K) → Option (Γ k))),
(∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))) →
∃ b,
TrCfg (TM2.stepAux q₂ v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal q₂) v (Tape.mk' ∅ (addBottom L))) b
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
⊢ ∃ b,
TrCfg (bif p v then TM2.stepAux q₁ v S else TM2.stepAux q₂ v S) b ∧
Reaches (TM1.step (tr M))
(bif (fun x => p) (Tape.mk' ∅ (addBottom L)).head v then TM1.stepAux (trNormal q₁) v (Tape.mk' ∅ (addBottom L))
else TM1.stepAux (trNormal q₂) v (Tape.mk' ∅ (addBottom L)))
b Tactic: unfold TM2.stepAux trNormal TM1.stepAux State Before: case H₃
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
l : Λ
p : σ → Bool
q₁ q₂ : Stmt₂
IH₁ :
∀ {v : σ} {S : (k : K) → List (Γ k)} (L : ListBlank ((k : K) → Option (Γ k))),
(∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))) →
∃ b,
TrCfg (TM2.stepAux q₁ v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal q₁) v (Tape.mk' ∅ (addBottom L))) b
IH₂ :
∀ {v : σ} {S : (k : K) → List (Γ k)} (L : ListBlank ((k : K) → Option (Γ k))),
(∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))) →
∃ b,
TrCfg (TM2.stepAux q₂ v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal q₂) v (Tape.mk' ∅ (addBottom L))) b
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
⊢ ∃ b,
TrCfg (bif p v then TM2.stepAux q₁ v S else TM2.stepAux q₂ v S) b ∧
Reaches (TM1.step (tr M))
(bif (fun x => p) (Tape.mk' ∅ (addBottom L)).head v then TM1.stepAux (trNormal q₁) v (Tape.mk' ∅ (addBottom L))
else TM1.stepAux (trNormal q₂) v (Tape.mk' ∅ (addBottom L)))
b State After: case H₃
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
l : Λ
p : σ → Bool
q₁ q₂ : Stmt₂
IH₁ :
∀ {v : σ} {S : (k : K) → List (Γ k)} (L : ListBlank ((k : K) → Option (Γ k))),
(∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))) →
∃ b,
TrCfg (TM2.stepAux q₁ v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal q₁) v (Tape.mk' ∅ (addBottom L))) b
IH₂ :
∀ {v : σ} {S : (k : K) → List (Γ k)} (L : ListBlank ((k : K) → Option (Γ k))),
(∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))) →
∃ b,
TrCfg (TM2.stepAux q₂ v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal q₂) v (Tape.mk' ∅ (addBottom L))) b
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
⊢ ∃ b,
TrCfg (bif p v then TM2.stepAux q₁ v S else TM2.stepAux q₂ v S) b ∧
Reaches (TM1.step (tr M))
(bif p v then TM1.stepAux (trNormal q₁) v (Tape.mk' ∅ (addBottom L))
else TM1.stepAux (trNormal q₂) v (Tape.mk' ∅ (addBottom L)))
b Tactic: simp only [] State Before: case H₃
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
l : Λ
p : σ → Bool
q₁ q₂ : Stmt₂
IH₁ :
∀ {v : σ} {S : (k : K) → List (Γ k)} (L : ListBlank ((k : K) → Option (Γ k))),
(∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))) →
∃ b,
TrCfg (TM2.stepAux q₁ v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal q₁) v (Tape.mk' ∅ (addBottom L))) b
IH₂ :
∀ {v : σ} {S : (k : K) → List (Γ k)} (L : ListBlank ((k : K) → Option (Γ k))),
(∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))) →
∃ b,
TrCfg (TM2.stepAux q₂ v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal q₂) v (Tape.mk' ∅ (addBottom L))) b
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
⊢ ∃ b,
TrCfg (bif p v then TM2.stepAux q₁ v S else TM2.stepAux q₂ v S) b ∧
Reaches (TM1.step (tr M))
(bif p v then TM1.stepAux (trNormal q₁) v (Tape.mk' ∅ (addBottom L))
else TM1.stepAux (trNormal q₂) v (Tape.mk' ∅ (addBottom L)))
b State After: no goals Tactic: cases p v <;> [exact IH₂ _ hT; exact IH₁ _ hT] State Before: case H₄
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
l : Λ
l✝ : σ → Λ
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
⊢ ∃ b,
TrCfg (TM2.stepAux (TM2.Stmt.goto l✝) v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal (TM2.Stmt.goto l✝)) v (Tape.mk' ∅ (addBottom L))) b State After: no goals Tactic: exact ⟨_, ⟨_, hT⟩, ReflTransGen.refl⟩ State Before: case H₅
K : Type u_4
inst✝² : DecidableEq K
Γ : K → Type u_3
Λ : Type u_2
inst✝¹ : Inhabited Λ
σ : Type u_1
inst✝ : Inhabited σ
M : Λ → Stmt₂
l : Λ
v : σ
S : (k : K) → List (Γ k)
L : ListBlank ((k : K) → Option (Γ k))
hT : ∀ (k : K), ListBlank.map (proj k) L = ListBlank.mk (List.reverse (List.map some (S k)))
⊢ ∃ b,
TrCfg (TM2.stepAux TM2.Stmt.halt v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal TM2.Stmt.halt) v (Tape.mk' ∅ (addBottom L))) b State After: no goals Tactic: exact ⟨_, ⟨_, hT⟩, ReflTransGen.refl⟩ |
module Main
import Data.String
import Data.Vect
import System.REPL
infixr 5 .+.
data Schema = SString | SInt | (.+.) Schema Schema
SchemaType : Schema -> Type
SchemaType SString = String
SchemaType SInt = Int
SchemaType (x .+. y) = (SchemaType x, SchemaType y)
record DataStore where
constructor MkData
schema : Schema
size : Nat
items : Vect size (SchemaType schema)
addToStore : (d : DataStore) -> SchemaType (schema d) -> DataStore
addToStore (MkData schema size store) newitem = MkData schema _ (addToData store)
where
addToData : Vect oldsize (SchemaType schema) -> Vect (S oldsize) (SchemaType schema)
addToData [] = [newitem]
addToData (x :: xs) = x :: addToData xs
data Command : Schema -> Type where
Add : SchemaType schema -> Command schema
Get : Integer -> Command schema
Quit : Command schema
parseCommand : String -> String -> Maybe (Command schema)
parseCommand "add" rest = Just (Add (?parseBySchema rest))
parseCommand "get" val = case all isDigit (unpack val) of
False => Nothing
True => Just (Get (cast val))
parseCommand "quit" "" = Just Quit
parseCommand _ _ = Nothing
parse : (schema : Schema) -> (input : String) -> Maybe (Command schema)
parse schema input = case span (/= ' ') input of
(cmd, args) => parseCommand cmd (ltrim args)
getEntry : (pos : Integer) -> (store : DataStore) ->
Maybe (String, DataStore)
getEntry pos store
= let store_items = items store in
case integerToFin pos (size store) of
Nothing => Just ("Out of range\n", store)
Just id => Just (?display (index id (items store)) ++ "\n", store)
processInput : DataStore -> String -> Maybe (String, DataStore)
processInput store input
= case parse (schema store) input of
Nothing => Just ("Invalid command\n", store)
Just (Add item) =>
Just ("ID " ++ show (size store) ++ "\n", addToStore store item)
Just (Get pos) => getEntry pos store
Just Quit => Nothing
main : IO ()
main = replWith (MkData SString _ []) "Command: " processInput
|
Like so many things it depends who you ask. For some it refers to the entire workflow from the moment a need is identified through to the final payment and warranty administration for a service or item. Others describe it as online sourcing and purchasing of items from a catalogue. Wikipedia says: “E-procurement (electronic procurement, sometimes also known as supplier exchange) is the business-to-business or business-to-consumer or business-to-government purchase and sale of supplies, work, and services through the Internet as well as other information and networking systems, such as electronic data interchange and enterprise resource planning.
In this Blog the term e-Procurement is used to describe the workflows that relate to the external (Vendor and Contractor) facing processes required to purchase goods, services or construction over the internet.
In this very simplified description of the procurement process, the externally facing activities (elements 4, 5, 6) and the interface (element 3 and 7) between those and the internally facing activities are the areas that our software and services streamline.
As we draw near the end of 2011, there are many predictions around the IT industry trend for 2012. The recently published "Nucleus Research Top Ten Predictions 2012" places emphasis on the rise of cloud computing (prediction #2). According to the article, cloud computing was proven to be nearly five times more productive than the traditional development in 2011. Furthermore, the article also states, “When companies do have money to spend, their two main choices are technology and people. A recent Nucleus survey found technology is winning hands down, with 50 percent of US companies planning to increase their technology spend in 2012 [Nucleus Research l106, Nucleus 2012 IT spending survey, September 2011].” Thus, many firms will look into increasing their productivity via technology adoption next year.
So the trend is clear. Businesses are moving towards cloud computing to take advantage of its many benefits including increased productivity, cost savings, accountability and sustainability. In today’s construction industry, online document control, online planroom, and online bidding are examples of cloud computing technologies that are increasingly adopted.
A few years ago most bidders would not have pictured themselves submitting their construction bids online in a paperless environment. It represents a major change from decades of travelling to closings, faxing bid amendments, last minute decisions and all the drama that comes with it. Today, this green construction technology has finally arrived. Online bid submission has the double benefit of being a sustainable process along with the benefits of substantially improved efficiency. Supported with a complete document management system and audit trail, it ensures a complete record of who saw what documents and when. This combination greatly reduces the risk of costly bid related errors or omissions.
A great example of an early adopter of this technology is the city of Prince George in British Columbia, Canada. It leads the way in the electronic tendering of capital projects closing many of the projects that have utilized the recently introduced Owner Bid Management and Bid Submission applications within BidCentral. BidCentral is powered by PlanSource and is a suite of services that was designed specifically for the construction industry and is modeled after the processes that have long been accepted as industry standards. The City of Prince George procurement team and the bidders involved in the bidding process gave BidCentral very positive reviews and recognized it as the new construction procurement standard (view video).
Our company has been delivering Software as a Service (SaaS) since we were founded in 2000. At that time what we did was generally described as Application Service Provider (ASP). The latest iteration incorporates the more ethereal sounding ‘cloud computing’ reference. Whatever term you use the functionality consists of accessing software via the Internet rather than from your local computer or server. So, is this an effective way to acquire and use software applications?
Faster and less expensive implementation makes the new systems more digestible.
As a company that has been significantly ahead of the wave on this method of delivering useful functionality to the construction industry for many years we can easily agree with Mr. Fornes statements. We already deliver powerful solutions for the estimating community and are experiencing significant interest in some of the latest functionality we deliver online including planrooms, document control, onscreen takeoff, online bid submission and submittal management. The industry trend is definitely moving towards increased use of SaaS. |
export QBasedPolicy
using MacroTools: @forward
using Flux
using Setfield
"""
QBasedPolicy(;learner::Q, explorer::S)
Use a Q-`learner` to generate estimations of action values.
Then an `explorer` is applied on the estimations to select an action.
"""
Base.@kwdef mutable struct QBasedPolicy{Q<:AbstractLearner,E<:AbstractExplorer} <:
AbstractPolicy
learner::Q
explorer::E
end
Flux.functor(x::QBasedPolicy) = (learner = x.learner,), y -> @set x.learner = y.learner
(π::QBasedPolicy)(env) = π(env, ActionStyle(env))
(π::QBasedPolicy)(env, ::MinimalActionSet) = get_actions(env)[π.explorer(π.learner(env))]
(π::QBasedPolicy)(env, ::FullActionSet) =
get_actions(env)[π.explorer(π.learner(env), get_legal_actions_mask(env))]
RLBase.get_prob(p::QBasedPolicy, env) = get_prob(p, env, ActionStyle(env))
RLBase.get_prob(p::QBasedPolicy, env, ::MinimalActionSet) =
get_prob(p.explorer, p.learner(env))
RLBase.get_prob(p::QBasedPolicy, env, ::FullActionSet) =
get_prob(p.explorer, p.learner(env), get_legal_actions_mask(env))
@forward QBasedPolicy.learner RLBase.get_priority, RLBase.update!
function Flux.testmode!(p::QBasedPolicy, mode = true)
testmode!(p.learner, mode)
testmode!(p.explorer, mode)
end
|
-- {-# OPTIONS --cubical -vtc.lhs.split.partial:20 #-}
{-# OPTIONS --cubical #-}
module _ where
open import Agda.Primitive.Cubical
open import Agda.Builtin.Equality
postulate
X : Set
P : I → Set
p : P i1
module Test (A : Set) (i : I) (B : Set) where
j = i
R = P j
module Z (r s : A) where
a0 : I → Partial j R
a0 k with k
... | _ = \ { (j = i1) → p }
a : Partial j R
a (j = i1) = p
refining : ∀ (x y : A) → x ≡ y → A → Partial j R
refining x y refl = \ { _ (j = i1) → p }
refining-dot : ∀ (x y : A) → x ≡ y → A → Partial j R
refining-dot x .x refl = \ { _ (j = i1) → p }
refining-dot2 : ∀ (x y : A) → x ≡ y → A → Partial j R
refining-dot2 x .x refl z = \ { (i = i1) → p }
refining-cxt : A ≡ X → Partial j R
refining-cxt refl = \ { (j = i1) → p }
refining-cxt2 : B ≡ X → Partial j R
refining-cxt2 refl = \ { (j = i1) → p }
|
import Control.Monad.State
import Data.List
import Data.String
import Data.MSF.Trans
import Generics.Derive
import JSON
import Rhone.JS
import Web.Html
%default total
%language ElabReflection
record Item where
constructor MkI
id : Nat
todo : String
done : Bool
%runElab derive "Item" [Generic,Meta,Eq,FromJSON,ToJSON]
data Ev = New | Clear | Mark Bool | Hash
| Edit Nat | Abort Nat | Delete Nat | Upd Nat | Toggle Nat Bool
%runElab derive "Ev" [Generic,Eq]
new : ElemRef HTMLInputElement
new = Id Input "new-todo"
liId : Nat -> ElemRef HTMLLIElement
liId n = Id Li "item_\{show n}"
editId : Nat -> ElemRef HTMLInputElement
editId n = Id Input "edit_\{show n}"
itemView : Item -> Node Ev
itemView (MkI n lbl done) =
li [ ref (liId n), class (if done then "completed" else "") ]
[ div [ class "view" ]
[ input [ class "toggle", type CheckBox, checked done
, onChecked (Toggle n) ] []
, label [ onDblClick (Edit n) ] [ Text lbl ]
, button [ class "destroy", onClick (Delete n) ] [] ]
, input [ ref (editId n), class "edit", value lbl
, onEnterDown (Upd n), onEscDown (Abort n), onBlur (Upd n) ] [] ]
ST : Type
ST = List Item
newId : MonadState ST m => MSF m i Nat
newId = get >>^ (maybe 0 (S . id) . getAt 0)
mod : MonadState ST m => (i -> ST -> ST) -> MSF m i ()
mod f = arr f >>! modify
modAt : MonadState ST m => (i -> Item -> Item) -> MSF m (NP I [Nat,i]) ()
modAt f = mod $ \[n,v] => map (\t => if t.id == n then f v t else t)
newVal : LiftJSIO m => MSF m i (Event String)
newVal = valueOf new >>> runEffect (setValue new "") >>> trim ^>> isNot ""
countStr : Nat -> String
countStr 1 = "<strong>1</strong> item left"
countStr k = "<strong>\{show k}</strong> items left"
items : NP I [List Item, String] -> List (Node Ev)
items [is,"#/active"] = map itemView . filter (not . done) $ reverse is
items [is,"#/completed"] = map itemView . filter done $ reverse is
items [is,_] = map itemView $ reverse is
disp : MSF (StateT ST $ DomIO Ev JSIO) i ()
disp = get >>> fan
[ fan [id, windowHash] >>> arr items >>! innerHtmlAtN (Id Ul "todo-list")
, isNil ^>- [hiddenAt (Id Section "main"), hiddenAt (Id Footer "footer")]
, all done ^>> isChecked (Id Input "toggle-all")
, (not . any done) ^>> hiddenAt (Id Button "clear-completed")
, count (not . done) ^>> countStr ^>> innerHtml (Id Span "todo-count")
, encode ^>> setItemAt "todomvc-idris2" ]
>>> windowHash >>-
[ ifIs "#/active" "selected" >>> classAt (Id A "sel-active")
, ifIs "#/completed" "selected" >>> classAt (Id A "sel-completed")
, ifIs "#/" "selected" >>> classAt (Id A "sel-all") ]
update : MSF (StateT ST $ DomIO Ev JSIO) (NP I [Nat,String]) ()
update = bool (\[_,s] => null s) >>> collect
[ mod (\[i,_] => filter $ (/= i) . id)
, modAt (\s => {todo := s}) ]
controller : MSF (StateT ST $ DomIO Ev JSIO) Ev ()
controller = (toI . unSOP . from) ^>> collect
[ newVal ?>> [| MkI newId id (pure False) |] >>> mod (::) >>> disp
, mod (\_ => filter $ not . done) >>> disp
, mod (\[b] => map {done := b}) >>> disp
, disp
, fan [ hd >>^ liId, const "editing" ] >>> attribute_ "class"
, disp
, mod (\[i] => filter $ (/= i) . id) >>> disp
, hd >>> fan [id, editId ^>> value >>^ trim] >>> update >>> disp
, modAt (\b => {done := b}) >>> disp ]
ui : DomIO Ev JSIO (MSF (DomIO Ev JSIO) Ev (), JSIO ())
ui = do
setAttribute new (onEnterDown New)
setAttribute (Id Button "clear-completed") (onClick Clear)
setAttribute (Id Input "toggle-all") (onChecked Mark)
handleEvent Window (HashChange Hash)
ini <- liftJSIO (window >>= localStorage >>= (`getItem` "todomvc-idris2"))
pure (loopState (fromMaybe Nil $ ini >>= decodeMaybe) controller, pure ())
main : IO ()
main = runJS . ignore $ reactimateDomIni Hash "todo" ui
|
There’s an app for everything under the sun, and you can bet that there’s an app to help you get better with your golf spwing. Introducing the PGA Swing Guru App, one of the best apps in the industry and is one of the easiest golf swing analysis apps for the iPhone.
Providing an interactive tool that both golfing coaches and players can use, this golf swing app promises to transform you into a better golfer in no time at all. But you might be asking what sets the PGA Swing Guru App apart from other golf swing apps?
There are apps and there are apps. The PGA Swing Guru App is an app that can go the whole course with the rest of them. Filled chock-full of useful features, even the more advanced golfer will love the special features included in this app. The interactive feel that the PGA Swing Guru App boasts also gives users a more hands on and personal sensation when using the app. Just imagine having a trophy case of your own that will show you the challenges that you’ve passed using the PGA Swing Guru App.
Follow your coach, compete with yourselves, or give your friends something to think about. The PGA Swing Guru App lets you connect with other golfers around the world. Connect with the best PGA golf coaches using this app – and not just connect, you can also learn from the very best. You can find out what other players are saying about their games and the latest developments in the golfing world through social media offerings such as Twitter and Facebook.
Because of the great benefits and features that the PGA Swing Guru App provides, the app quickly warmed up to coaches, players and even fans of golf. The app is a paid app but the small price tag that comes with the app hasn’t hindered at all how golf lovers have quickly embraced the PGA Swing Guru App.
Whether you’re an aspiring golfer or just a fan of the game, you will get a lot out of the PGA Swing Guru App. There’s a small fee that you will have to pay for the app but that shouldn’t stop your from enjoying the wonderful features and benefits that come with this app. Invest in your game and keep up to date with PGA developments with the PGA Swing Guru App.
Find A Great Deal On A PGA Swing Guru Player Or Coach App! |
import algebra.comm_rings.basic
import algebra.comm_rings.ideals.basic
import algebra.comm_rings.ideals.instances
import algebra.comm_rings.ideals.identities
import algebra.comm_rings.instances.basic
namespace comm_ring
universes u v w
open set
open classical
def in_same_coset {R : Type u} [comm_ring R] (I: ideal R) : R → R → Prop := λ x y, x + -y ∈ I.body
notation x ` ≡ ` y ` mod ` I := in_same_coset I x y
lemma in_same_coset_refl {R : Type u} [comm_ring R] (I: ideal R) : ∀ x, x ≡ x mod I :=
begin
intros x,
have h : x + -x ∈ ↑I,
rw minus_inverse,
exact I.contains_zero,
exact h,
end
lemma in_same_coset_symm {R : Type u} [comm_ring R] (I: ideal R) : symmetric (in_same_coset I) :=
begin
intros x y hxy,
have h : y + -x ∈ ↑I,
rw ← minus_minus y,
rw ← minus_dis,
apply I.minus_closure,
rw add_comm,
exact hxy,
exact h,
end
lemma in_same_coset_trans {R : Type u} [comm_ring R] (I: ideal R) : transitive (in_same_coset I) :=
begin
intros x y z hxy hyz,
have hrw : x + -z = (x + -y) + (y + -z),
exact calc x + -z = (x + 0) + -z : by rw add_zero x
... = (x + -y) + (y +- z) : by {rw [←minus_inverse, add_comm y (-y)], simp [add_assoc]},
have h : x + -z ∈ ↑I,
rw hrw,
apply I.add_closure,
exact hxy,
exact hyz,
exact h,
end
lemma mod_respects_add {R : Type u} [comm_ring R] {I: ideal R}
: ∀ {x₁ x₂ y₁ y₂ : R} , (x₁ ≡ y₁ mod I) → (x₂ ≡ y₂ mod I) → ((x₁ + x₂) ≡ (y₁ + y₂) mod I) :=
begin
intros x₁ x₂ y₁ y₂ h₁ h₂,
have hrw : (x₁ + x₂) + -(y₁ + y₂) = (x₁ + -y₁) + (x₂ + -y₂),
exact calc (x₁ + x₂) + -(y₁ + y₂) = (x₁ + x₂) + (-y₁ + -y₂) : by rw minus_dis
... = x₁ + (x₂ + -y₁) + -y₂ : by simp [add_assoc]
... = x₁ + (-y₁ + x₂) + -y₂ : by simp [add_comm]
... = (x₁ + -y₁) + (x₂ + -y₂) : by simp [add_assoc],
have h : (x₁ + x₂) + -(y₁ + y₂) ∈ ↑I,
rw hrw,
apply I.add_closure,
exact h₁,
exact h₂,
exact h,
end
lemma mod_respects_mul {R : Type u} [comm_ring R] {I: ideal R}
: ∀ {x₁ x₂ y₁ y₂ : R} , (x₁ ≡ y₁ mod I) → (x₂ ≡ y₂ mod I) → ((x₁ * x₂) ≡ (y₁ * y₂) mod I) :=
begin
intros x₁ x₂ y₁ y₂ h₁ h₂,
have hrw : x₁ * x₂ + -(y₁ * y₂) = x₁ * (x₂ + -y₂) + (x₁ + -y₁) * y₂,
symmetry,
exact calc x₁ * (x₂ + -y₂) + (x₁ + -y₁) * y₂ = (x₁ * x₂ + x₁ * (-y₂)) + y₂ * (x₁ + -y₁) : by simp [mul_dis,mul_comm]
... = (x₁ * x₂ + x₁ * (-y₂)) + (x₁ * y₂ + (-y₁) *y₂) : by simp [mul_dis,mul_comm]
... = x₁ * x₂ + (x₁ * (-y₂) + x₁ * y₂) + (-y₁) * y₂ : by simp [add_assoc]
... = x₁ * x₂ + (x₁ * (-y₂ + y₂)) + ((-y₁) *y₂) : by simp [←mul_dis]
... = x₁ * x₂ + (-y₁) * y₂ : by simp [add_comm,minus_inverse,add_zero,mul_zero]
... = x₁ * x₂ + - (y₁ * y₂) : by rw [←minus_mul],
have h : x₁ * x₂ + -(y₁ * y₂) ∈ ↑I,
rw hrw,
apply I.add_closure,
apply I.mul_absorb,
exact h₂,
rw mul_comm,
apply I.mul_absorb,
exact h₁,
exact h,
end
lemma mod_respects_minus {R : Type u} [comm_ring R] {I: ideal R}
: ∀ {x y : R}, (x ≡ y mod I) → (-x ≡ -y mod I) :=
begin
intros x y hxy,
have h : -x + (-(-y)) ∈ ↑I,
rw ← minus_dis,
apply I.minus_closure,
exact hxy,
exact h,
end
def quotient_ring_setiod (R : Type u) [l:comm_ring R] (I: ideal R) : setoid R :=
{
r := λ x y, x ≡ y mod I,
iseqv := ⟨in_same_coset_refl I, in_same_coset_symm I, in_same_coset_trans I⟩,
}
def quotient_ring (R :Type u) [comm_ring R] (I : ideal R) : Type u := quotient (comm_ring.quotient_ring_setiod R I)
infixr `/ᵣ` : 25 := quotient_ring
def quotient_ring_mk {R : Type u} [comm_ring R] (I: ideal R) : R → R /ᵣ I := @quotient.mk R (quotient_ring_setiod R I)
infixr ` +ᵣ ` : 50 := λ x I , quotient_ring_mk I x
theorem quotient_ring_exists_rep {R: Type u} [comm_ring R] (I : ideal R) : ∀ q : R/ᵣ I, ∃ a : R, (a +ᵣ I) = q := @quotient.exists_rep R (quotient_ring_setiod R I)
theorem quotient_ring_sound {R: Type u} [comm_ring R] (I : ideal R) : ∀ {a b : R}, (a ≡ b mod I) → (a +ᵣ I) = (b +ᵣ I) := @quotient.sound R (quotient_ring_setiod R I)
theorem quotient_ring_exact {R: Type u} [comm_ring R] (I : ideal R) : ∀ {a b : R}, (a +ᵣ I) = (b +ᵣ I) → (a ≡ b mod I) := @quotient.exact R (quotient_ring_setiod R I)
def quotient_ring_one {R: Type u} [l:comm_ring R] (I:ideal R) : R /ᵣ I := l.one +ᵣ I
instance quotient_ring_has_one {R: Type u} [comm_ring R] (I:ideal R) : has_one (R /ᵣ I) := ⟨quotient_ring_one I⟩
theorem quotient_ring_concrete_char_of_one {R: Type u} [l:comm_ring R] (I:ideal R) : (l.one +ᵣ I) = 1 := rfl
def quotient_ring_zero {R: Type u} [l:comm_ring R] (I:ideal R) : R /ᵣ I := l.zero +ᵣ I
instance quotient_ring_has_zero {R: Type u} [comm_ring R] (I:ideal R) : has_zero (R /ᵣ I) := ⟨quotient_ring_zero I⟩
theorem quotient_ring_concrete_char_of_zero {R: Type u} [l:comm_ring R] (I:ideal R) : (l.zero +ᵣ I) = 0 := rfl
def quotient_ring_pre_add {R: Type u} [comm_ring R] (I:ideal R) : R → R → R /ᵣ I :=
λ a b, (a + b) +ᵣ I
lemma quotient_ring_pre_add_lifts {R: Type u} [comm_ring R] (I:ideal R)
: ∀ x₁ x₂ y₁ y₂, (x₁ ≡ y₁ mod I) → (x₂ ≡ y₂ mod I) → quotient_ring_pre_add I x₁ x₂ = quotient_ring_pre_add I y₁ y₂ :=
begin
intros x₁ x₂ y₁ y₂,
intros h₁ h₂,
apply quotient.sound,
apply mod_respects_add,
exact h₁,
exact h₂,
end
def quotient_ring_add {R: Type u} [comm_ring R] (I : ideal R) : (R /ᵣ I) → (R /ᵣ I) → R /ᵣ I :=
begin
apply quotient.lift₂,
exact quotient_ring_pre_add_lifts I,
end
instance quotient_ring_has_add {R: Type u} [comm_ring R] (I : ideal R) : has_add (R/ᵣI) := ⟨quotient_ring_add I⟩
theorem quotient_ring_concrete_char_of_add {R: Type u} [comm_ring R] (I : ideal R) : ∀ a b : R, (a +ᵣ I) + (b +ᵣ I) = ((a + b) +ᵣ I) :=
begin
intros a b,
refl,
end
def quotient_ring_pre_mul {R: Type u} [comm_ring R] (I:ideal R) : R → R → R /ᵣ I :=
λ a b, (a * b) +ᵣ I
lemma quotient_ring_pre_mul_lifts {R: Type u} [comm_ring R] (I:ideal R)
: ∀ x₁ x₂ y₁ y₂, (x₁ ≡ y₁ mod I) → (x₂ ≡ y₂ mod I) → quotient_ring_pre_mul I x₁ x₂ = quotient_ring_pre_mul I y₁ y₂ :=
begin
intros x₁ x₂ y₁ y₂,
intros h₁ h₂,
apply quotient.sound,
apply mod_respects_mul,
exact h₁,
exact h₂,
end
def quotient_ring.mul {R: Type u} [comm_ring R] (I : ideal R) : (R /ᵣ I) → (R /ᵣ I) → R /ᵣ I :=
begin
apply quotient.lift₂,
exact quotient_ring_pre_mul_lifts I,
end
instance quotient_ring_has_mul {R: Type u} [comm_ring R] (I : ideal R) : has_mul (R/ᵣI) := ⟨quotient_ring.mul I⟩
theorem quotient_ring_concrete_char_of_mul {R: Type u} [comm_ring R] (I : ideal R) : ∀ a b : R, (a +ᵣ I) * (b +ᵣ I) = ((a * b) +ᵣ I) :=
begin
intros a b,
refl,
end
def quotient_ring_pre_minus {R: Type u} [comm_ring R] (I : ideal R) : R → (R/ᵣI) :=
λ x : R, (-x) +ᵣ I
lemma quotient_ring_pre_minus_lifts {R: Type u} [comm_ring R] (I : ideal R) : ∀ x y, (x ≡ y mod I) → quotient_ring_pre_minus I x = quotient_ring_pre_minus I y :=
begin
intros x y hxy,
apply quotient.sound,
apply mod_respects_minus,
exact hxy,
end
def quotient_ring_minus {R: Type u} [comm_ring R] (I : ideal R) : (R /ᵣ I) → (R /ᵣ I) :=
begin
apply quotient.lift,
exact quotient_ring_pre_minus_lifts I,
end
instance quotient_ring_has_neg {R: Type u} [comm_ring R] (I : ideal R) : has_neg (R/ᵣI) := ⟨quotient_ring_minus I⟩
theorem quotient_ring_concrete_char_of_minus {R: Type u} [comm_ring R] (I : ideal R) : ∀ a : R, -(a +ᵣ I) = (-a +ᵣ I) :=
begin
intros a,
refl,
end
theorem quotient_ring_add_assoc {R: Type u} [comm_ring R] (I : ideal R) : ∀ q₁ q₂ q₃ : (R /ᵣ I), q₁ + (q₂ + q₃) = (q₁ + q₂) +q₃ :=
begin
intros q₁ q₂ q₃,
let r₁ := some (quotient_ring_exists_rep I q₁),
have hr₁ : (r₁ +ᵣ I) = q₁ := some_spec (quotient_ring_exists_rep I q₁),
let r₂ := some (quotient_ring_exists_rep I q₂),
have hr₂ : (r₂ +ᵣ I) = q₂ := some_spec (quotient_ring_exists_rep I q₂),
let r₃ := some (quotient_ring_exists_rep I q₃),
have hr₃ : (r₃ +ᵣ I) = q₃ := some_spec (quotient_ring_exists_rep I q₃),
rw [←hr₁,←hr₂,←hr₃],
simp [quotient_ring_concrete_char_of_add],
rw add_assoc,
end
theorem quotient_ring_add_comm {R: Type u} [comm_ring R] (I : ideal R) : ∀ q₁ q₂ : (R /ᵣ I), q₁ + q₂ = q₂ + q₁ :=
begin
intros q₁ q₂,
let r₁ := some (quotient_ring_exists_rep I q₁),
have hr₁ : (r₁ +ᵣ I) = q₁ := some_spec (quotient_ring_exists_rep I q₁),
let r₂ := some (quotient_ring_exists_rep I q₂),
have hr₂ : (r₂ +ᵣ I) = q₂ := some_spec (quotient_ring_exists_rep I q₂),
rw [←hr₁,←hr₂],
simp [quotient_ring_concrete_char_of_add],
rw add_comm,
end
theorem quotient_ring_mul_assoc {R: Type u} [comm_ring R] (I : ideal R) : ∀ q₁ q₂ q₃ : (R /ᵣ I), q₁ * (q₂ * q₃) = (q₁ * q₂) * q₃ :=
begin
intros q₁ q₂ q₃,
let r₁ := some (quotient_ring_exists_rep I q₁),
have hr₁ : (r₁ +ᵣ I) = q₁ := some_spec (quotient_ring_exists_rep I q₁),
let r₂ := some (quotient_ring_exists_rep I q₂),
have hr₂ : (r₂ +ᵣ I) = q₂ := some_spec (quotient_ring_exists_rep I q₂),
let r₃ := some (quotient_ring_exists_rep I q₃),
have hr₃ : (r₃ +ᵣ I) = q₃ := some_spec (quotient_ring_exists_rep I q₃),
rw [←hr₁,←hr₂,←hr₃],
simp [quotient_ring_concrete_char_of_mul],
rw mul_assoc,
end
theorem quotient_ring_mul_comm {R: Type u} [comm_ring R] (I : ideal R) : ∀ q₁ q₂ : (R /ᵣ I), q₁ * q₂ = q₂ * q₁ :=
begin
intros q₁ q₂,
let r₁ := some (quotient_ring_exists_rep I q₁),
have hr₁ : (r₁ +ᵣ I) = q₁ := some_spec (quotient_ring_exists_rep I q₁),
let r₂ := some (quotient_ring_exists_rep I q₂),
have hr₂ : (r₂ +ᵣ I) = q₂ := some_spec (quotient_ring_exists_rep I q₂),
rw [←hr₁,←hr₂],
simp [quotient_ring_concrete_char_of_mul],
rw mul_comm,
end
theorem quotient_ring_mul_dis {R: Type u} [comm_ring R] (I : ideal R) : ∀ q₁ q₂ q₃ : (R /ᵣ I), q₁ * (q₂ + q₃) = (q₁ * q₂) + (q₁ * q₃) :=
begin
intros q₁ q₂ q₃,
let r₁ := some (quotient_ring_exists_rep I q₁),
have hr₁ : (r₁ +ᵣ I) = q₁ := some_spec (quotient_ring_exists_rep I q₁),
let r₂ := some (quotient_ring_exists_rep I q₂),
have hr₂ : (r₂ +ᵣ I) = q₂ := some_spec (quotient_ring_exists_rep I q₂),
let r₃ := some (quotient_ring_exists_rep I q₃),
have hr₃ : (r₃ +ᵣ I) = q₃ := some_spec (quotient_ring_exists_rep I q₃),
rw [←hr₁,←hr₂,←hr₃],
simp [quotient_ring_concrete_char_of_mul,quotient_ring_concrete_char_of_add],
rw mul_dis,
end
theorem quotient_ring_mul_one {R: Type u} [comm_ring R] (I : ideal R) : ∀ q : (R /ᵣ I), q * 1 = q :=
begin
intro q,
let r := some (quotient_ring_exists_rep I q),
have hr : (r +ᵣ I) = q := some_spec (quotient_ring_exists_rep I q),
rw [←hr,←quotient_ring_concrete_char_of_one],
simp [quotient_ring_concrete_char_of_mul],
rw mul_one,
end
theorem quotient_ring_add_zero {R: Type u} [comm_ring R] (I : ideal R) : ∀ q : (R /ᵣ I), q + 0 = q :=
begin
intro q,
let r := some (quotient_ring_exists_rep I q),
have hr : (r +ᵣ I) = q := some_spec (quotient_ring_exists_rep I q),
rw [←hr,←quotient_ring_concrete_char_of_zero],
simp [quotient_ring_concrete_char_of_add],
rw add_zero,
end
theorem quotient_ring_minus_inverse {R: Type u} [comm_ring R] (I : ideal R) : ∀ q : (R /ᵣ I), q + -q = 0 :=
begin
intro q,
let r := some (quotient_ring_exists_rep I q),
have hr : (r +ᵣ I) = q := some_spec (quotient_ring_exists_rep I q),
rw [←hr,←quotient_ring_concrete_char_of_zero],
simp [quotient_ring_concrete_char_of_add, quotient_ring_concrete_char_of_minus],
rw minus_inverse,
end
instance quotient_ring_comm_ring {R: Type u} [comm_ring R] (I : ideal R) : comm_ring (R/ᵣI) :=
begin
split,
exact quotient_ring_add_assoc I,
exact quotient_ring_add_comm I,
exact quotient_ring_add_zero I,
exact quotient_ring_minus_inverse I,
exact quotient_ring_mul_assoc I,
exact quotient_ring_mul_comm I,
exact quotient_ring_mul_one I,
exact quotient_ring_mul_dis I,
end
def quot_ring_hom {R: Type u} [comm_ring R] (I : ideal R) : R →ᵣ (R/ᵣI) :=
{
map := λ x, x +ᵣ I,
prevs_mul := λ _ _, rfl,
prevs_add := λ _ _, rfl,
prevs_one := rfl,
}
theorem quotient_ring_concrete_char_of_quot_map {R: Type u} [comm_ring R] (I : ideal R)
: ∀ x : R, quot_ring_hom I x = (x +ᵣ I) :=
begin
intro,
refl,
end
theorem quotient_zero_implies_in_ideal {R: Type u} [comm_ring R] (I : ideal R)
: ∀ {x : R} , (x +ᵣ I) = 0 → x ∈ I.body :=
begin
intros x hx,
rw [←add_zero x,← minus_zero_zero],
have hrw : (x ≡ 0 mod I) = ((x +-0) ∈ I.body) := rfl,
rw ← hrw,
apply quotient_ring_exact,
exact hx,
end
theorem in_ideal_implies_quotient_zero {R: Type u} [comm_ring R] (I : ideal R)
: ∀ {x : R} , x ∈ I.body → (x +ᵣ I) = 0 :=
begin
intros x hx,
rw ← quotient_ring_concrete_char_of_zero,
apply quotient_ring_sound,
rw [←add_zero x,← minus_zero_zero] at hx,
exact hx,
end
theorem quot_ring_hom_kernel {R: Type u} [l:comm_ring R] (I : ideal R) : ker (quot_ring_hom I) = I :=
begin
apply ideal_equality,
apply subset_antisymmetric,
split,
intros x hx,
apply quotient_zero_implies_in_ideal,
apply zero_ideal_is_just_zero,
exact hx,
intros x hx,
have h₁: (x +ᵣ I) = 0,
apply in_ideal_implies_quotient_zero,
exact hx,
have h: (x +ᵣ I) ∈ (zero_ideal (R/ᵣI)).body,
rw h₁,
exact linear_combination.empty_sum,
exact h,
end
def quot_ring_universal_property {R: Type u} [lR:comm_ring R] (I : ideal R)
: (Σ (Q : Type u) [lQ:comm_ring Q], (@ring_hom R Q lR lQ)) → Prop
| ⟨Q,lQ,φ⟩ := (∀ r : R, r ∈ I.body → φ r = lQ.zero) ∧
(∀ pair : (Σ (Q : Type u) [lQ:comm_ring Q], (@ring_hom R Q lR lQ)),
(∀ r : R, r ∈ I.body → pair.2.2 r = pair.2.1.zero)
→ ∃! ψ : (@ring_hom Q pair.1 lQ pair.2.1) , pair.2.2 = (@ring_hom_comp R Q pair.1 lR lQ pair.2.1 ψ φ))
def quot_ring_app_lifts {R : Type u} {Q : Type v} [comm_ring R] (I : ideal R) (lQ:comm_ring Q) (φ : R →ᵣ Q) (hφvan : ∀ r : R , r ∈ I.body → φ r = 0)
: ∀ r₁ r₂ : R, (r₁ ≡ r₂ mod I) → φ r₁ = φ r₂ :=
begin
intros r₁ r₂ h₁₂,
have hrw : r₁ = r₂ + (r₁ + -r₂),
rw [add_comm r₁ (-r₂),add_assoc,minus_inverse],
rw [add_comm,add_zero],
rw hrw,
have trv : φ.map = ⇑φ := rfl,
rw [←trv,φ.prevs_add,trv, hφvan (r₁ + -r₂) h₁₂,add_zero],
end
def quot_ring_can_map {R : Type u} {Q : Type v} [comm_ring R] (I : ideal R) (lQ:comm_ring Q) (φ : R →ᵣ Q) (hφvan : ∀ r : R , r ∈ I.body → φ r = 0)
: (R/ᵣI) → Q :=
begin
apply quotient.lift,
exact quot_ring_app_lifts I lQ φ hφvan,
end
theorem quotient_ring_concrete_char_of_can_map {R : Type u} {Q : Type v} [comm_ring R] (I : ideal R) (lQ:comm_ring Q) (φ : R →ᵣ Q) (hφvan : ∀ r : R , r ∈ I.body → φ r = 0)
: ∀ x : R, quot_ring_can_map I lQ φ hφvan (x +ᵣ I) = φ x :=
begin
intro,
refl,
end
theorem quot_ring_can_map_prevs_add {R : Type u} {Q : Type v} [comm_ring R] (I : ideal R) (lQ:comm_ring Q) (φ : R →ᵣ Q) (hφvan : ∀ r : R , r ∈ I.body → φ r = 0)
: ∀ q₁ q₂ : (R/ᵣI), quot_ring_can_map I lQ φ hφvan (q₁ + q₂) = (quot_ring_can_map I lQ φ hφvan q₁) + (quot_ring_can_map I lQ φ hφvan q₂) :=
begin
intros q₁ q₂,
let r₁ := some (quotient_ring_exists_rep I q₁),
have hr₁ : (r₁ +ᵣ I) = q₁ := some_spec (quotient_ring_exists_rep I q₁),
let r₂ := some (quotient_ring_exists_rep I q₂),
have hr₂ : (r₂ +ᵣ I) = q₂ := some_spec (quotient_ring_exists_rep I q₂),
rw [←hr₁,←hr₂],
simp [quotient_ring_concrete_char_of_add I, quotient_ring_concrete_char_of_can_map],
exact φ.prevs_add r₁ r₂,
end
theorem quot_ring_can_map_prevs_mul {R : Type u} {Q : Type v} [comm_ring R] (I : ideal R) (lQ:comm_ring Q) (φ : R →ᵣ Q) (hφvan : ∀ r : R , r ∈ I.body → φ r = 0)
: ∀ q₁ q₂ : (R/ᵣI), quot_ring_can_map I lQ φ hφvan (q₁ * q₂) = (quot_ring_can_map I lQ φ hφvan q₁) * (quot_ring_can_map I lQ φ hφvan q₂) :=
begin
intros q₁ q₂,
let r₁ := some (quotient_ring_exists_rep I q₁),
have hr₁ : (r₁ +ᵣ I) = q₁ := some_spec (quotient_ring_exists_rep I q₁),
let r₂ := some (quotient_ring_exists_rep I q₂),
have hr₂ : (r₂ +ᵣ I) = q₂ := some_spec (quotient_ring_exists_rep I q₂),
rw [←hr₁,←hr₂],
simp [quotient_ring_concrete_char_of_mul I, quotient_ring_concrete_char_of_can_map],
exact φ.prevs_mul r₁ r₂,
end
theorem quot_ring_can_map_prevs_one {R : Type u} {Q : Type v} [comm_ring R] (I : ideal R) (lQ:comm_ring Q) (φ : R →ᵣ Q) (hφvan : ∀ r : R , r ∈ I.body → φ r = 0)
: quot_ring_can_map I lQ φ hφvan 1 = 1 :=
begin
simp [←quotient_ring_concrete_char_of_one,quotient_ring_concrete_char_of_can_map],
exact φ.prevs_one,
end
def quot_ring_can_hom {R : Type u} {Q : Type v} [comm_ring R] (I : ideal R) [lQ:comm_ring Q] (φ : R →ᵣ Q) (hφvan : ∀ r : R , r ∈ I.body → φ r = 0)
: ((R/ᵣI) →ᵣ Q) :=
{
map := quot_ring_can_map I lQ φ hφvan,
prevs_add := quot_ring_can_map_prevs_add I lQ φ hφvan,
prevs_mul := quot_ring_can_map_prevs_mul I lQ φ hφvan,
prevs_one := quot_ring_can_map_prevs_one I lQ φ hφvan,
}
theorem quotient_ring_satisfies_its_universal_property {R : Type u} [comm_ring R] (I :ideal R)
: quot_ring_universal_property I ⟨(R/ᵣI),comm_ring.quotient_ring_comm_ring I,quot_ring_hom I⟩ :=
begin
split,
intros x hx,
rw ← quot_ring_hom_kernel I at hx,
apply zero_ideal_is_just_zero,
exact hx,
intros pair hpair,
cases pair with Q rest,
cases rest with lQ φ,
resetI,
existsi (quot_ring_can_hom I φ hpair),
split,
apply ring_hom_equality,
refl,
intros φ' hφ',
apply ring_hom_equality_hack,
have trv₁ : ∀ x : R , φ x = φ' (x +ᵣ I),
simp at hφ',
intros x,
rw hφ',
refl,
apply funext,
intro q,
let r := some (quotient_ring_exists_rep I q),
have hr : (r +ᵣ I) = q := some_spec (quotient_ring_exists_rep I q),
rw ← hr,
simp,
rw ← trv₁ r,
refl,
end
lemma quotient_ring_comp_hom_id {R Q: Type u} [comm_ring R] [lQ : comm_ring Q] {I : ideal R} {q : R →ᵣ Q}
(Qup : quot_ring_universal_property I ⟨Q,lQ,q⟩) : ∀ φ : Q →ᵣ Q, q = (φ ∘ᵣ q) → φ = idᵣ :=
begin
intros φ hφ,
cases Qup with vanish abNon,
cases abNon ⟨Q,lQ,q⟩ vanish with ψ hψ,
dsimp at ψ,
dsimp at hψ,
cases hψ with hψ ψup,
have h₁ : φ = ψ,
apply ψup,
exact hφ,
have h₂ : idᵣ = ψ,
apply ψup,
symmetry,
exact id_hom_left_comp q,
rw [h₁,h₂],
end
theorem universal_property_chars_quotient_ring {R Q Q': Type u} [lR:comm_ring R] [lQ : comm_ring Q]
[lQ' : comm_ring Q'] {I : ideal R} (q : R →ᵣ Q) (q' : R →ᵣ Q')
: quot_ring_universal_property I ⟨Q,lQ,q⟩ → quot_ring_universal_property I ⟨Q',lQ',q'⟩
→ ∃! ψ : Q →ᵣ Q', q' = (ψ ∘ᵣ q) ∧ (ring_isomorphism ψ) :=
begin
intros upQ upQ',
cases upQ with vanish abNon,
cases upQ' with vanish' abNon',
cases abNon ⟨Q',lQ',q'⟩ vanish' with ψ hψ,
dsimp at ψ,
dsimp at hψ,
cases abNon' ⟨Q,lQ,q⟩ vanish with ψ' hψ',
dsimp at ψ',
dsimp at hψ',
cases hψ with hψ ψup,
cases hψ' with hψ' ψ'up,
existsi ψ,
split,
split,
exact hψ,
existsi ψ',
split,
apply quotient_ring_comp_hom_id ⟨vanish,abNon⟩,
rw [← ring_comp_assoc,← hψ,← hψ'],
apply quotient_ring_comp_hom_id ⟨vanish',abNon'⟩,
rw [← ring_comp_assoc,← hψ',← hψ],
intros ψint hψint,
apply ψup,
exact and.left hψint,
end
theorem first_ring_isomorphism_thm {R₁ : Type u} {R₂ : Type v} [comm_ring R₁] [comm_ring R₂] (φ : R₁ →ᵣ R₂)
: ∃ ψ : (R₁/ᵣ(ker φ)) →ᵣ Im φ, ring_isomorphism ψ :=
begin
have hφvanish : ∀ r : R₁, r ∈ (ker φ).body → im_trival_hom_in φ r = 0,
intros r hr,
apply val_injective,
apply zero_ideal_is_just_zero,
exact hr,
let ψ : (R₁/ᵣ(ker φ)) →ᵣ Im φ := quot_ring_can_hom (ker φ) (im_trival_hom_in φ) hφvanish,
have trv : ∀ r : R₁, (ψ (r+ᵣ ((ker φ) : ideal R₁))).val = φ r,
intro r,
have subtrv₁ : ψ = quot_ring_can_hom (ker φ) (im_trival_hom_in φ) hφvanish := rfl,
rw subtrv₁,
simp,
have subtrv₂ : quot_ring_can_hom (ker φ) (im_trival_hom_in φ) hφvanish (r +ᵣ ((ker φ) : ideal R₁))
= im_trival_hom_in φ r,
simp,
apply quotient_ring_concrete_char_of_can_map (ker φ),
exact hφvanish,
rw subtrv₂,
refl,
existsi ψ,
apply bijective_ring_hom_ring_iso,
split,
apply zero_kernel_injective,
apply ideal_equality,
apply subset_antisymmetric,
split,
intros q hq,
let r : R₁ := some (quotient_ring_exists_rep (ker φ) q),
have hr : (r +ᵣ ((ker φ):ideal R₁) ) = q:= some_spec (quotient_ring_exists_rep (ker φ) q),
simp at hr,
rw ← hr,
rw ← hr at hq,
rw elements_of_kernel at hq,
have hrkφ : φ r = 0,
rw ← trv,
simp,
rw hq,
refl,
have hq0 : (r +ᵣ ((ker φ) :ideal R₁)) = 0,
apply in_ideal_implies_quotient_zero,
rw elements_of_kernel,
assumption,
simp at hq0,
rw hq0,
apply linear_combination.empty_sum,
intros q hq,
rw elements_of_kernel,
rw zero_ideal_is_just_zero hq,
apply ring_hom_preserves_zero ψ,
intro y,
cases y.property with x hx,
existsi (x +ᵣ ((ker φ) : ideal R₁)),
apply val_injective,
rw trv,
symmetry,
assumption,
end
end comm_ring |
Staff - Lodge & Co.
Mr. Lodge started his firm in 1984 as a full business consulting firm in the area of management and accounting. He has provided management, financial and tax advisory services to various industries throughout the United States. He has had clients in the following areas: Co-Generation Power Facilities, Electronic Manufacturing, Real Estate, Construction, Trucking & Transportation, Mortgage Banking, Insurance, Entertainment, International Manufacturing, Call Centers, International Shipping Containers, Healthcare Staffing, Nursing Review Centers and several other business industries. MR. Lodge has a strong background in consolidated reporting for international companies. Since 1984 to present, Mr. Lodge continues to work with clients on various issues, providing them with full business mediation and dispute resolution, business consultations and coaching.. His background also includes forming new business entities for businesses into S Corps, C Corps, LLCs, Partnerships and reviewing the tax issues within each formation. Mr. Lodge has written a book and gives lectures on "Ethics In Business", he has written the book, "Ethically Thinking - It's Not That Hard" and continues to write about wealth business and taxes. He writes a blog on business and taxes and broadcasts a PodCast on the WBT PodCast Network. Mr. Lodge feels that teaching is a part of business.
Mr. Lodge is a Certified Mediator through the National Association of Certified Mediators. Nationally Certified Professional in Mediation.
SPEAKING ENGAGEMENTS: If you would like Mr. Lodge to speak on a business or tax subject to your group, send him an email at: [email protected] with specifics on what your organization is about and the topic you would like discussed.
Brenndy provides client relations services. If you have a problem or a question, call Brenndy. Brenndy has over several years in the tax preparation service business. She has a great working relation with our client, scheduling all appointments, follow-up with clients, and responding to clients needs as it relates to tax issues.
Christy has been with our firm for quite a few years. She provides our business clients with payroll services, monthly accounting and bookkeeping services, year end services for W-2 and 1099 preparation and distribution. Christy has a solid background in business accounting, from data entry through the preparation of income statements, balance sheets and statement of cash flows. |
(*************************************************************)
(* Copyright Dominique Larchey-Wendling [*] *)
(* *)
(* [*] Affiliation LORIA -- CNRS *)
(*************************************************************)
(* This file is distributed under the terms of the *)
(* CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT *)
(*************************************************************)
(* ** Euclidian division and Bezout's identity *)
Require Import List Arith Lia Permutation Extraction.
From Undecidability.Shared.Libs.DLW.Utils
Require Import utils_tac utils_list.
Set Implicit Arguments.
Section Euclid.
(* Simultaneous comparison and difference *)
Fixpoint cmp_sub x y : { z | z+y = x } + { x < y }.
Proof.
refine (match y as y' return { z | z+y' = x } + { x < y' } with
| 0 => inleft (exist _ x _)
| S y' => match x as x' return { z | z+_ = x' } + { x' < _ } with
| 0 => inright _
| S x' => match cmp_sub x' y' with
| inleft (exist _ z Hz) => inleft (exist _ z _)
| inright H => inright _
end
end
end); abstract lia.
Defined.
Definition euclid n d : d <> 0 -> { q : nat & { r | n = q*d+r /\ r < d } }.
Proof.
intros Hd; induction on n as euclid with measure n.
refine (match cmp_sub n d with
| inleft (exist _ z Hz) =>
match euclid z _ with
| existT _ q (exist _ r Hr) => existT _ (S q) (exist _ r _)
end
| inright H => existT _ 0 (exist _ n _)
end); abstract (simpl; lia).
Defined.
End Euclid.
Definition arem n d q j := j <= d /\ (n = 2*q*d+j \/ q <> 0 /\ n = 2*q*d-j).
Fact division_by_even n d : d <> 0 -> { q : nat & { j | arem n d q j } }.
Proof.
intros Hd.
destruct (@euclid n (2*d)) as (q & r & H1 & H2); try lia.
destruct (le_lt_dec r d) as [ Hr | Hr ].
+ exists q, r; split; auto; left.
rewrite H1; ring.
+ exists (S q), (2*d-r); split; lia.
Qed.
Fact own_multiple x p : x = p*x -> x = 0 \/ p = 1.
Proof.
destruct x as [ | x ].
+ left; trivial.
+ right.
destruct p as [ | [ | p ] ].
- simpl in H; discriminate.
- trivial.
- exfalso; revert H.
do 2 (rewrite mult_comm; simpl).
generalize (p*x); intros; lia.
Qed.
Fact mult_is_one p q : p*q = 1 -> p = 1 /\ q = 1.
Proof.
destruct p as [ | [ | p ] ].
+ simpl; discriminate.
+ simpl; lia.
+ rewrite mult_comm.
destruct q as [ | [ | q ] ].
- simpl; discriminate.
- simpl; lia.
- simpl; discriminate.
Qed.
Definition divides n k := exists p, k = p*n.
Section divides.
Infix "div" := divides (at level 70, no associativity).
Fact divides_refl x : x div x.
Proof. exists 1; simpl; lia. Qed.
Fact divides_anti x y : x div y -> y div x -> x = y.
Proof.
intros (p & H1) (q & H2).
rewrite H1, mult_assoc in H2.
apply own_multiple in H2.
destruct H2 as [ H2 | H2 ].
+ subst; rewrite mult_comm; auto.
+ apply mult_is_one in H2; destruct H2; subst; lia.
Qed.
Fact divides_trans x y z : x div y -> y div z -> x div z.
Proof.
intros (p & H1) (q & H2).
exists (q*p); rewrite <- mult_assoc, <- H1; auto.
Qed.
Fact divides_0 p : p div 0.
Proof. exists 0; auto. Qed.
Fact divides_0_inv p : 0 div p -> p = 0.
Proof. intros (?&?); subst; rewrite Nat.mul_0_r; auto. Qed.
Fact divides_1 p : 1 div p.
Proof. exists p; rewrite mult_comm; simpl; auto. Qed.
Fact divides_1_inv p : p div 1 -> p = 1.
Proof.
intros (q & Hq).
apply mult_is_one with q; auto.
Qed.
Fact divides_2_inv p : p div 2 -> p = 1 \/ p = 2.
Proof.
intros ([ | k ] & Hk); try discriminate.
destruct p as [ | [ | [|] ] ]; lia.
Qed.
Fact divides_mult p q k : p div q -> p div k*q.
Proof.
intros (r & ?); subst.
exists (k*r); rewrite mult_assoc; auto.
Qed.
Fact divides_mult_r p q k : p div q -> p div q*k.
Proof.
rewrite mult_comm; apply divides_mult; auto.
Qed.
Fact divides_mult_compat a b c d : a div b -> c div d -> a*c div b*d.
Proof.
intros (u & ?) (v & ?); exists (u*v); subst.
repeat rewrite mult_assoc; f_equal.
repeat rewrite <- mult_assoc; f_equal.
apply mult_comm.
Qed.
Fact divides_minus p q1 q2 : p div q1 -> p div q2 -> p div q1 - q2.
Proof.
intros (s1 & H1) (s2 & H2).
exists (s1 - s2).
rewrite Nat.mul_sub_distr_r; lia.
Qed.
Fact divides_plus p q1 q2 : p div q1 -> p div q2 -> p div q1+q2.
Proof.
intros (s1 & H1) (s2 & H2).
exists (s1 + s2).
rewrite Nat.mul_add_distr_r; lia.
Qed.
Fact divides_plus_inv p q1 q2 : p div q1 -> p div q1+q2 -> p div q2.
Proof.
intros H1 H2.
replace q2 with (q1+q2-q1) by lia.
apply divides_minus; auto.
Qed.
Fact divides_le p q : q <> 0 -> p div q -> p <= q.
Proof.
intros ? ([] & ?); subst; lia.
Qed.
Fact divides_mult_inv k p q : k <> 0 -> k*p div k*q -> p div q.
Proof.
intros H (n & Hn); exists n.
apply Nat.mul_cancel_r with (1 := H).
rewrite mult_comm, Hn; ring.
Qed.
Lemma divides_fact m p : 1 < p <= m -> p div fact m.
Proof.
intros (H1 & H2); induction H2.
+ destruct p; cbn. lia. unfold divides. exists (fact p). ring.
+ cbn. eauto using divides_plus, divides_mult.
Qed.
Lemma divides_mult_inv_l p q r : p * q div r -> p div r /\ q div r.
Proof.
intros []; split; subst.
- exists (x * q); ring.
- exists (x * p); ring.
Qed.
End divides.
Section gcd_lcm.
Infix "div" := divides (at level 70, no associativity).
Hint Resolve divides_0 divides_refl divides_mult divides_1 : core.
Definition is_gcd p q r := r div p /\ r div q /\ forall k, k div p -> k div q -> k div r.
Definition is_lcm p q r := p div r /\ q div r /\ forall k, p div k -> q div k -> r div k.
Fact is_gcd_sym p q r : is_gcd p q r -> is_gcd q p r.
Proof. intros (? & ? & ?); repeat split; auto. Qed.
Fact is_gcd_0l p : is_gcd 0 p p.
Proof. repeat split; auto. Qed.
Fact is_gcd_0r p : is_gcd p 0 p.
Proof. repeat split; auto. Qed.
Fact is_gcd_1l p : is_gcd 1 p 1.
Proof. repeat split; auto. Qed.
Fact is_gcd_1r p : is_gcd p 1 1.
Proof. repeat split; auto. Qed.
Fact is_gcd_modulus p q k r : p div k -> k <= q -> is_gcd p q r -> is_gcd p (q-k) r.
Proof.
intros (n & Hn) Hq (H1 & H2 & H3); subst.
split; auto.
split.
+ apply divides_minus; auto.
+ intros k H4 H5.
apply H3; auto.
replace q with (q - n*p + n*p) by lia.
apply divides_plus; auto.
Qed.
Fact is_gcd_minus p q r : p <= q -> is_gcd p q r -> is_gcd p (q-p) r.
Proof. intros H1; apply is_gcd_modulus; auto. Qed.
Hint Resolve divides_plus : core.
Fact is_gcd_moduplus p q k r : p div k -> is_gcd p q r -> is_gcd p (q+k) r.
Proof.
intros (n & Hn) (H1 & H2 & H3); subst.
repeat (split; auto).
intros k H4 H5.
apply H3; auto.
rewrite plus_comm in H5.
apply divides_plus_inv with (2 := H5); auto.
Qed.
Fact is_gcd_plus p q r : is_gcd p q r -> is_gcd p (q+p) r.
Proof. apply is_gcd_moduplus; auto. Qed.
Fact is_gcd_mult p q r n : is_gcd p (n*p+q) r <-> is_gcd p q r.
Proof.
split.
+ replace q with ((n*p+q)-n*p) at 2 by lia.
apply is_gcd_modulus; auto; lia.
+ rewrite plus_comm; apply is_gcd_moduplus; auto.
Qed.
Fact is_gcd_div p q : p div q -> is_gcd p q p.
Proof. intros (?&?); subst; split; auto. Qed.
Fact is_gcd_refl p : is_gcd p p p.
Proof. split; auto. Qed.
Fact is_gcd_fun p q r1 r2 : is_gcd p q r1 -> is_gcd p q r2 -> r1 = r2.
Proof. intros (?&?&?) (?&?&?); apply divides_anti; auto. Qed.
Fact is_lcm_0l p : is_lcm 0 p 0.
Proof. repeat split; auto. Qed.
Fact is_lcm_0r p : is_lcm p 0 0.
Proof. repeat split; auto. Qed.
Fact is_lcm_sym p q r : is_lcm p q r -> is_lcm q p r.
Proof. intros (?&?&?); repeat split; auto. Qed.
Fact is_lcm_fun p q r1 r2 : is_lcm p q r1 -> is_lcm p q r2 -> r1 = r2.
Proof. intros (?&?&?) (?&?&?); apply divides_anti; auto. Qed.
End gcd_lcm.
Section bezout.
Infix "div" := divides (at level 70, no associativity).
Hint Resolve is_gcd_0l is_gcd_0r is_lcm_0l is_lcm_0r divides_refl divides_mult divides_0 is_gcd_minus : core.
Section bezout_rel_prime.
(* A Bezout procedure with better extraction *)
Definition bezout_rel_prime_lt p q :
0 < p < q
-> is_gcd p q 1
-> { a : nat & { b | a*p+b*q = 1+p*q
/\ a <= q
/\ b <= p } }.
Proof.
induction on p q as bezout with measure q; intros (Hp & Hq) H.
refine (match @euclid q p _ with
| existT _ n (exist _ r H0) =>
match eq_nat_dec r 0 with
| left Hr => existT _ 1 (exist _ 1 _)
| right Hr => match @bezout r p Hq _ _ with
| existT _ a (exist _ b G0) =>
existT _ (b+n*p-n*a) (exist _ a _)
end
end
end); try lia.
+ destruct H0 as (H1 & H2).
subst r; rewrite plus_comm in H1; simpl in H1.
assert (is_gcd p q p) as H3.
{ apply is_gcd_div; subst; auto. }
rewrite (is_gcd_fun H3 H) in *.
simpl; lia.
+ replace r with (q-n*p) by lia.
apply is_gcd_sym, is_gcd_modulus; auto; lia.
+ destruct H0 as (H1 & H2).
destruct G0 as (H3 & H4 & H5).
split; [ | split ]; auto.
* rewrite H1, Nat.mul_sub_distr_r, (mult_comm _ p).
do 3 rewrite Nat.mul_add_distr_l.
rewrite (plus_comm _ (p*r)), (plus_assoc 1), (mult_comm p r), <- H3.
rewrite (mult_comm n a), (mult_comm p b), mult_assoc, mult_assoc.
assert (a*n*p <= p*n*p) as H6.
{ repeat (apply mult_le_compat; auto). }
revert H6; generalize (b*p) (a*r) (a*n*p) (p*n*p); intros; lia.
* rewrite H1; generalize (n*p) (n*a); intros; lia.
Defined.
Definition bezout_rel_prime p q : is_gcd p q 1 -> { a : nat & { b | a*p+b*q = 1+p*q } }.
Proof.
intros H.
destruct (eq_nat_dec p 0) as [ | Hp ].
{ subst; rewrite (is_gcd_fun (is_gcd_0l _) H); exists 0, 1; auto. }
destruct (eq_nat_dec q 0) as [ | Hq ].
{ subst; rewrite (is_gcd_fun (is_gcd_0r _) H); exists 1, 0; auto. }
destruct (lt_eq_lt_dec p q) as [ [ H1 | H1 ] | H1 ].
+ destruct bezout_rel_prime_lt with (2 := H)
as (a & b & H2 & _); try lia.
exists a, b; auto.
+ subst; rewrite (is_gcd_fun (is_gcd_refl _) H); exists 1, 1; auto.
+ destruct bezout_rel_prime_lt with (2 := is_gcd_sym H)
as (a & b & H2 & _); try lia.
exists b, a; rewrite (mult_comm p q); lia.
Defined.
Lemma bezout_nc p q : is_gcd p q 1 -> exists a b, a*p+b*q = 1+p*q.
Proof.
intros H.
destruct bezout_rel_prime with (1 := H) as (a & b & ?).
exists a, b; auto.
Qed.
Hint Resolve divides_1 : core.
Lemma bezout_sc p q a b m : a*p+b*q = 1 + m -> p div m \/ q div m -> is_gcd p q 1.
Proof.
intros H1 H2; do 2 (split; auto).
intros k H4 H5.
apply divides_plus_inv with m.
+ destruct H2 as [ H2 | H2 ];
apply divides_trans with (2 := H2); auto.
+ rewrite plus_comm, <- H1.
apply divides_plus; auto.
Qed.
End bezout_rel_prime.
(* We need the simple form of Bezout above to show this *)
Fact is_rel_prime_div p q k : is_gcd p q 1 -> p div q*k -> p div k.
Proof.
intros H1 (u & H2); subst.
destruct bezout_nc with (1 := H1) as (a & b & H3).
replace k with (k*(1+p*q) - k*p*q).
+ apply divides_minus.
- rewrite <- H3, Nat.mul_add_distr_l.
apply divides_plus.
* rewrite mult_assoc; auto.
* rewrite (mult_comm b), mult_assoc, (mult_comm k), H2.
rewrite mult_comm, mult_assoc; auto.
- rewrite mult_comm, mult_assoc; auto.
+ rewrite Nat.mul_add_distr_l, mult_assoc.
generalize (k*p*q); intros; lia.
Qed.
Fact is_rel_prime_div_r p q k : is_gcd p q 1 -> p div k*q -> p div k.
Proof. rewrite mult_comm; apply is_rel_prime_div. Qed.
Fact divides_is_gcd a b c : divides a b -> is_gcd b c 1 -> is_gcd a c 1.
Proof.
intros H1 H2; msplit 2; try apply divides_1.
intros k H3 H4.
apply H2; auto.
apply divides_trans with a; auto.
Qed.
Fact is_rel_prime_lcm p q : is_gcd p q 1 -> is_lcm p q (p*q).
Proof.
intros H.
repeat (split; auto).
rewrite mult_comm; auto.
intros k (u & ?) (v & ?); subst.
rewrite (mult_comm u).
apply divides_mult_compat; auto.
apply is_gcd_sym in H.
apply is_rel_prime_div with (1 := H) (k := u).
rewrite mult_comm, H1; auto.
Qed.
Hint Resolve divides_1 divides_mult_compat is_gcd_refl : core.
Fact is_gcd_0 p q : is_gcd p q 0 -> p = 0 /\ q = 0.
Proof.
intros ((a & Ha) & (b & Hb) & H).
subst; do 2 rewrite mult_0_r; auto.
Qed.
Fact is_gcd_rel_prime p q g : is_gcd p q g -> exists a b, p = a*g /\ q = b*g /\ is_gcd a b 1.
Proof.
destruct (eq_nat_dec g 0) as [ H0 | H0 ].
* intros H; subst.
apply is_gcd_0 in H; destruct H; subst.
exists 1, 1 ; simpl; auto.
* intros ((a & Ha) & (b & Hb) & H).
exists a, b; repeat (split; auto).
intros k H1 H2.
destruct (H (k*g)) as (d & Hd); subst.
+ do 2 rewrite (mult_comm _ g); auto.
+ do 2 rewrite (mult_comm _ g); auto.
+ rewrite mult_assoc in Hd.
replace g with (1*g) in Hd at 1 by (simpl; lia).
apply Nat.mul_cancel_r in Hd; auto.
symmetry in Hd.
apply mult_is_one in Hd.
destruct Hd; subst; auto.
Qed.
Fact is_lcm_mult p q l k : is_lcm p q l -> is_lcm (k*p) (k*q) (k*l).
Proof.
intros (H1 & H2 & H3); repeat (split; auto).
intros r (a & Ha) (b & Hb).
destruct (eq_nat_dec k 0) as [ Hk | Hk ].
+ subst; simpl; auto.
+ assert (a*p = b*q) as H4.
{ rewrite <- Nat.mul_cancel_r with (1 := Hk).
do 2 rewrite <- mult_assoc, (mult_comm _ k).
rewrite <- Hb; auto. }
rewrite Ha, mult_assoc, (mult_comm _ k), <- mult_assoc.
apply divides_mult_compat; auto.
apply H3; auto.
rewrite H4; auto.
Qed.
Theorem is_gcd_lcm_mult p q g l : is_gcd p q g -> is_lcm p q l -> p*q = g*l.
Proof.
destruct (eq_nat_dec g 0) as [ H0 | H0 ]; intros H1.
* subst; apply is_gcd_0 in H1.
destruct H1; subst; simpl; auto.
* destruct is_gcd_rel_prime with (1 := H1)
as (u & v & Hu & Hv & H2).
intros H3.
rewrite Hu, Hv, (mult_comm u), <- mult_assoc; f_equal.
rewrite (mult_comm u), (mult_comm v), <- mult_assoc, (mult_comm v).
apply is_lcm_fun with (2 := H3).
subst; rewrite (mult_comm u), (mult_comm v).
apply is_lcm_mult, is_rel_prime_lcm; auto.
Qed.
Theorem is_gcd_mult_lcm p q g l : g <> 0 -> is_gcd p q g -> g*l = p*q -> is_lcm p q l.
Proof.
intros H0 H1 H2.
destruct is_gcd_rel_prime with (1 := H1)
as (u & v & Hu & Hv & H3).
rewrite Hu, Hv, (mult_comm u), (mult_comm v).
replace l with (g*(u*v)).
+ apply is_lcm_mult, is_rel_prime_lcm; auto.
+ rewrite <- Nat.mul_cancel_r with (1 := H0).
rewrite (mult_comm l), H2, Hu, Hv,
(mult_comm u g), mult_assoc, mult_assoc; auto.
Qed.
(* if 1) p <= q
2) p = u*g
3) gcd p q = g
4) lcm p q = l
then A) gcd p (q-p) = g
B) lcm p (q-p) = l-u*p *)
Lemma is_lcm_minus p q g l u : p <= q -> p = u*g -> is_gcd p q g -> is_lcm p q l -> is_lcm p (q-p) (l-u*p).
Proof.
destruct (eq_nat_dec g 0) as [ H0 | H0 ].
+ intros _ _ H1 H2.
subst; apply is_gcd_0 in H1.
destruct H1; subst; simpl.
rewrite mult_0_r, Nat.sub_0_r; auto.
+ intros H1 H2 H3 H4.
apply is_gcd_mult_lcm with (1 := H0).
* apply is_gcd_minus; auto.
* do 2 rewrite Nat.mul_sub_distr_l.
rewrite <- (is_gcd_lcm_mult H3 H4).
f_equal.
rewrite H2 at 2.
rewrite mult_assoc, (mult_comm g); auto.
Qed.
(* if 1) p <= q
2) p = u*g
3) gcd p q = g
4) lcm p q = l
then A) gcd p (q-k*p) = g
B) lcm p (q-p) = l-k*u*p *)
Lemma is_lcm_modulus k p q g l u : k*p <= q -> p = u*g -> is_gcd p q g -> is_lcm p q l -> is_lcm p (q-k*p) (l-k*u*p).
Proof.
rewrite <- mult_assoc.
intros H1 H2 H3 H4. revert H1.
induction k as [ | k IHk ]; intros H1.
+ simpl; do 2 rewrite Nat.sub_0_r; auto.
+ replace (q - S k*p) with (q -k*p -p) by (simpl; lia).
replace (l - S k*(u*p)) with (l - k*(u*p) - u*p).
- apply is_lcm_minus with (g := g); auto.
* simpl in H1; lia.
* apply is_gcd_modulus; auto.
simpl in H1; lia.
* apply IHk; simpl in H1; lia.
- simpl; generalize (u*p) (k*(u*p)); intros; lia.
Qed.
(* if 1) p <= q
2) p = u*g
3) gcd p q = g
4) lcm p q = l
then A) gcd p (q+p) = g
B) lcm p (q+p) = l+u*p *)
Lemma is_lcm_plus p q g l u : p = u*g -> is_gcd p q g -> is_lcm p q l -> is_lcm p (q+p) (l+u*p).
Proof.
destruct (eq_nat_dec g 0) as [ H0 | H0 ].
+ intros _ H1 H2.
subst; apply is_gcd_0 in H1.
destruct H1; subst; simpl.
rewrite mult_0_r, Nat.add_0_r; auto.
+ intros H2 H3 H4.
apply is_gcd_mult_lcm with (1 := H0).
* apply is_gcd_plus; auto.
* do 2 rewrite Nat.mul_add_distr_l.
rewrite <- (is_gcd_lcm_mult H3 H4).
f_equal.
rewrite H2 at 2.
rewrite mult_assoc, (mult_comm g); auto.
Qed.
Lemma is_lcm_moduplus k p q g l u : p = u*g -> is_gcd p q g -> is_lcm p q l -> is_lcm p (q+k*p) (l+k*u*p).
Proof.
rewrite <- mult_assoc.
intros H2 H3 H4.
induction k as [ | k IHk ].
+ simpl; do 2 rewrite Nat.add_0_r; auto.
+ replace (q + S k*p) with (q +k*p +p) by (simpl; lia).
replace (l + S k*(u*p)) with (l + k*(u*p) + u*p) by (simpl; lia).
apply is_lcm_plus with (g := g); auto.
apply is_gcd_moduplus; auto.
Qed.
Section bezout_generalized.
(* TODO, write this FULLY specified Bezout with a better extraction, following bezout_rel_prime above *)
Definition bezout_generalized_lt p q :
0 < p < q
-> { a : nat
& { b : nat
& { g : nat
& { l : nat
& { u : nat
& { v : nat
| a*p+b*q = g + l
/\ is_gcd p q g
/\ is_lcm p q l
/\ p = u*g
/\ q = v*g
/\ a <= v
/\ b <= u } } } } } }.
Proof.
induction on p q as IH with measure q; intros (Hp & Hq).
destruct (@euclid q p) as (k & r & H1 & H2); try lia.
destruct (eq_nat_dec r 0) as [ Hr | Hr ].
+ exists 1, 1, p, (k*p), 1, k.
rewrite plus_comm in H1; simpl in H1.
subst; repeat split; simpl; auto.
destruct k; lia.
+ destruct (IH r _ Hq) as (a & b & g & l & u & v & H3 & H4 & H5 & H6 & H7 & H8 & H9); try lia.
exists (b+k*v-k*a), a, g, (l+k*v*p), v, (k*v+u).
apply is_gcd_sym in H4.
apply is_lcm_sym in H5.
rewrite plus_comm in H1.
assert (g <> 0) as Hg.
{ intro; subst g; apply is_gcd_0, proj1 in H4; lia. }
split.
{ rewrite H1, plus_assoc, Nat.mul_add_distr_l, <- H3.
rewrite Nat.mul_sub_distr_r, Nat.mul_add_distr_r.
rewrite mult_assoc, (mult_comm a k).
assert (k*a*p <= k*v*p) as G.
{ repeat (apply mult_le_compat; auto). }
revert G; generalize (b*p) (a*r) (k*a*p) (k*v*p); intros; lia. }
split.
{ rewrite H1; apply is_gcd_moduplus; auto. }
split.
{ rewrite H1; apply is_lcm_moduplus with g; auto. }
split; auto.
split.
{ rewrite H1, H6, H7, Nat.mul_add_distr_r, mult_assoc; lia. }
split; auto.
{ rewrite (plus_comm _ u), <- Nat.add_sub_assoc.
+ apply plus_le_compat; auto.
generalize (k*v) (k*a); intros; lia.
+ apply mult_le_compat; auto. }
Defined.
Hint Resolve is_gcd_sym is_lcm_sym : core.
Definition bezout_generalized p q : { a : nat
& { b : nat
& { g : nat
& { l : nat
| a*p+b*q = g + l
/\ is_gcd p q g
/\ is_lcm p q l } } } }.
Proof.
destruct (eq_nat_dec p 0) as [ | Hp ].
{ subst; exists 0, 1, q, 0; repeat (split; auto). }
destruct (eq_nat_dec q 0) as [ | Hq ].
{ subst; exists 1, 0, p, 0; repeat (split; auto). }
destruct (lt_eq_lt_dec p q) as [ [ H1 | H1 ] | H1 ].
+ destruct (@bezout_generalized_lt p q)
as (a & b & g & l & _ & _ & ? & ? & ? & _); try lia.
exists a, b, g, l; auto.
+ subst q; exists 1, 1, p, p.
repeat split; auto; lia.
+ destruct (@bezout_generalized_lt q p)
as (a & b & g & l & _ & _ & ? & ? & ? & _); try lia.
exists b, a, g, l; repeat (split; auto); lia.
Qed.
End bezout_generalized.
Section gcd_lcm.
Let gcd_full p q : sig (is_gcd p q).
Proof.
destruct (bezout_generalized p q) as (_ & _ & g & _ & _ & ? & _).
exists g; auto.
Qed.
Definition gcd p q := proj1_sig (gcd_full p q).
Fact gcd_spec p q : is_gcd p q (gcd p q).
Proof. apply (proj2_sig _). Qed.
Let lcm_full p q : sig (is_lcm p q).
Proof.
destruct (bezout_generalized p q) as (_ & _ & _ & l & _ & _ & ?).
exists l; auto.
Qed.
Definition lcm p q := proj1_sig (lcm_full p q).
Fact lcm_spec p q : is_lcm p q (lcm p q).
Proof. apply (proj2_sig _). Qed.
End gcd_lcm.
End bezout.
Section division.
Fact div_full q p : { n : nat & { r | q = n*p+r /\ (p <> 0 -> r < p) } }.
Proof.
case_eq p.
+ intro; exists 0, q; subst; split; auto; intros []; auto.
+ intros k H; destruct (@euclid q p) as (n & r & H1 & H2); try lia.
exists n, r; rewrite <- H; split; auto.
Qed.
Definition div q p := projT1 (div_full q p).
Definition rem q p := proj1_sig (projT2 (div_full q p)).
Fact div_rem_spec1 q p : q = div q p * p + rem q p.
Proof. apply (proj2_sig (projT2 (div_full q p))). Qed.
Fact div_rem_spec2 q p : p <> 0 -> rem q p < p.
Proof. apply (proj2_sig (projT2 (div_full q p))). Qed.
Fact rem_0 q : rem q 0 = q.
Proof.
generalize (div_rem_spec1 q 0).
rewrite mult_comm; auto.
Qed.
Fact div_rem_uniq p n1 r1 n2 r2 :
p <> 0 -> n1*p + r1 = n2*p + r2 -> r1 < p -> r2 < p -> n1 = n2 /\ r1 = r2.
Proof.
intros H1 H2 H3 H4.
assert (n1 = n2) as E.
destruct (lt_eq_lt_dec n1 n2) as [ [ H | ] | H ]; auto.
+ replace n2 with (n2-n1 + n1) in H2 by lia.
rewrite Nat.mul_add_distr_r in H2.
assert (1*p <= (n2-n1)*p) as H5.
{ apply mult_le_compat; lia. }
simpl in H5; lia.
+ replace n1 with (n1-n2 + n2) in H2 by lia.
rewrite Nat.mul_add_distr_r in H2.
assert (1*p <= (n1-n2)*p) as H5.
{ apply mult_le_compat; lia. }
simpl in H5; lia.
+ subst; lia.
Qed.
Fact div_prop q p n r : q = n*p+r -> r < p -> div q p = n.
Proof.
intros H1 H2.
apply (@div_rem_uniq p _ (rem q p) n r); auto.
+ lia.
+ rewrite <- H1; symmetry; apply div_rem_spec1.
+ apply div_rem_spec2; lia.
Qed.
Fact rem_prop q p n r : q = n*p+r -> r < p -> rem q p = r.
Proof.
intros H1 H2.
apply (@div_rem_uniq p (div q p) _ n r); auto.
+ lia.
+ rewrite <- H1; symmetry; apply div_rem_spec1.
+ apply div_rem_spec2; lia.
Qed.
Fact rem_idem q p : q < p -> rem q p = q.
Proof. apply rem_prop with 0; auto. Qed.
Fact rem_rem x m : rem (rem x m) m = rem x m.
Proof.
destruct (eq_nat_dec m 0).
+ subst; rewrite !rem_0; auto.
+ apply rem_idem, div_rem_spec2; auto.
Qed.
Fact is_gcd_rem p n a : is_gcd p n a <-> is_gcd p (rem n p) a.
Proof.
rewrite (div_rem_spec1 n p) at 1; apply is_gcd_mult.
Qed.
Fact rem_erase q n p r : q = n*p+r -> rem q p = rem r p.
Proof.
destruct (eq_nat_dec p 0) as [ | Hp ]; subst.
+ rewrite mult_comm, rem_0, rem_0; auto.
+ destruct (div_full r p) as (m & r' & H1 & H2).
specialize (H2 Hp).
rewrite rem_prop with r p m r'; auto.
intros; apply rem_prop with (n+m); auto.
rewrite Nat.mul_add_distr_r; lia.
Qed.
Fact divides_div q p : divides p q -> q = div q p * p.
Proof.
intros (k & Hk).
destruct (eq_nat_dec p 0) as [ Hp | Hp ].
+ subst; do 2 (rewrite mult_comm; simpl); auto.
+ rewrite (@div_prop q p k 0); lia.
Qed.
Fact divides_rem_eq q p : divides p q <-> rem q p = 0.
Proof.
destruct (eq_nat_dec p 0) as [ Hp | Hp ].
* subst; rewrite rem_0; split.
+ apply divides_0_inv.
+ intros; subst; apply divides_0.
* split.
+ intros (n & Hn).
apply rem_prop with n; lia.
+ intros H.
generalize (div_rem_spec1 q p).
exists (div q p); lia.
Qed.
Fact rem_of_0 p : rem 0 p = 0.
Proof.
destruct p.
+ apply rem_0.
+ apply rem_prop with 0; lia.
Qed.
Hint Resolve divides_0_inv : core.
Fact divides_dec q p : { k | q = k*p } + { ~ divides p q }.
Proof.
destruct (eq_nat_dec p 0) as [ Hp | Hp ].
+ destruct (eq_nat_dec q 0) as [ Hq | Hq ].
* left; subst; exists 1; auto.
* right; contradict Hq; subst; auto.
+ destruct (@euclid q p Hp) as (n & [ | r ] & H1 & H2).
* left; exists n; subst; rewrite plus_comm; auto.
* right; intros (m & Hm).
rewrite <- Nat.add_0_r in Hm.
rewrite Hm in H1.
destruct (div_rem_uniq _ _ Hp H1); lia.
Qed.
End division.
Section rem.
Variable (p : nat) (Hp : p <> 0).
Fact rem_plus_rem a b : rem (a+rem b p) p = rem (a+b) p.
Proof.
rewrite (div_rem_spec1 b p) at 2.
rewrite plus_assoc.
symmetry; apply rem_erase with (div (b) p); ring.
Qed.
Fact rem_mult_rem a b : rem (a*rem b p) p = rem (a*b) p.
Proof.
rewrite (div_rem_spec1 b p) at 2.
rewrite Nat.mul_add_distr_l, mult_assoc.
symmetry; apply rem_erase with (a*div b p); auto.
Qed.
Fact rem_diag : rem p p = 0.
Proof. apply rem_prop with 1; lia. Qed.
Fact rem_lt a : a < p -> rem a p = a.
Proof. apply rem_prop with 0; lia. Qed.
Fact rem_plus a b : rem (a+b) p = rem (rem a p + rem b p) p.
Proof.
rewrite (div_rem_spec1 a p) at 1.
rewrite (div_rem_spec1 b p) at 1.
apply rem_erase with (div a p + div b p).
ring.
Qed.
Fact rem_scal k a : rem (k*a) p = rem (k*rem a p) p.
Proof.
rewrite (div_rem_spec1 a p) at 1.
rewrite Nat.mul_add_distr_l.
apply rem_erase with (k*div a p).
ring.
Qed.
Fact rem_plus_div a b : divides p b -> rem a p = rem (a+b) p.
Proof.
intros (n & Hn); subst.
rewrite <- rem_plus_rem.
f_equal.
rewrite <- rem_mult_rem, rem_diag, Nat.mul_0_r, rem_of_0; lia.
Qed.
Fact div_eq_0 n : n < p -> div n p = 0.
Proof. intros; apply div_prop with n; lia. Qed.
Fact div_of_0 : div 0 p = 0.
Proof. apply div_eq_0; lia. Qed.
Fact div_ge_1 n : p <= n -> 1 <= div n p.
Proof.
intros H2.
rewrite (div_rem_spec1 n p) in H2.
generalize (div_rem_spec2 n Hp); intros H3.
destruct (div n p); lia.
Qed.
End rem.
Fact divides_rem_rem p q a : divides p q -> rem (rem a q) p = rem a p.
Proof.
destruct (eq_nat_dec p 0) as [ Hp | Hp ].
{ intros (k & ->); subst; rewrite mult_0_r.
repeat rewrite rem_0; auto. }
intros H.
generalize (div_rem_spec1 a q); intros H1.
destruct H as (k & ->).
rewrite H1 at 2.
rewrite plus_comm.
apply rem_plus_div; auto.
do 2 apply divides_mult.
apply divides_refl.
Qed.
Fact divides_rem_congr p q a b : divides p q -> rem a q = rem b q -> rem a p = rem b p.
Proof.
intros H1 H2.
rewrite <- (divides_rem_rem a H1),
<- (divides_rem_rem b H1).
f_equal; auto.
Qed.
Fact div_by_p_lt p n : 2 <= p -> n <> 0 -> div n p < n.
Proof.
intros H1 H2.
rewrite (div_rem_spec1 n p) at 2.
replace p with (2+(p-2)) at 3 by lia.
rewrite Nat.mul_add_distr_l.
generalize (div n p*(p-2)); intros x.
destruct (le_lt_dec p n) as [ Hp | Hp ].
+ apply div_ge_1 in Hp; lia.
+ rewrite rem_lt; lia.
Qed.
Section rem_2.
Fact rem_2_is_0_or_1 x : rem x 2 = 0 \/ rem x 2 = 1.
Proof. generalize (rem x 2) (@div_rem_spec2 x 2); intros; lia. Qed.
Fact rem_2_mult x y : rem (x*y) 2 = 1 <-> rem x 2 = 1 /\ rem y 2 = 1.
Proof.
generalize (rem_2_is_0_or_1 x) (rem_2_is_0_or_1 y).
do 2 rewrite <- rem_mult_rem, mult_comm.
intros [ H1 | H1 ] [ H2 | H2 ]; rewrite H1, H2; simpl; rewrite rem_lt; lia.
Qed.
Fact rem_2_fix_0 : rem 0 2 = 0.
Proof. apply rem_lt; lia. Qed.
Fact rem_2_fix_1 n : rem (2*n) 2 = 0.
Proof. apply divides_rem_eq; exists n; ring. Qed.
Fact rem_2_fix_2 n : rem (1+2*n) 2 = 1.
Proof.
rewrite <- rem_plus_rem,rem_2_fix_1, rem_lt; lia.
Qed.
Fact rem_2_lt n : rem n 2 < 2.
Proof. apply div_rem_spec2; lia. Qed.
Fact div_2_fix_0 : div 0 2 = 0.
Proof. apply div_of_0; lia. Qed.
Fact div_2_fix_1 n : div (2*n) 2 = n.
Proof. apply div_prop with 0; lia. Qed.
Fact div_2_fix_2 n : div (1+2*n) 2 = n.
Proof. apply div_prop with 1; lia. Qed.
Fact euclid_2_div n : n = rem n 2 + 2*div n 2 /\ (rem n 2 = 0 \/ rem n 2 = 1).
Proof.
generalize (div_rem_spec1 n 2) (@div_rem_spec2 n 2); intros; lia.
Qed.
Fact euclid_2 n : exists q, n = 2*q \/ n = 1+2*q.
Proof.
exists (div n 2).
generalize (div_rem_spec1 n 2) (@div_rem_spec2 n 2); intros; lia.
Qed.
End rem_2.
Local Hint Resolve divides_mult divides_mult_r divides_refl : core.
|
#ifndef SQL_PARSER_AST_SELECT_STMT_HPP
#define SQL_PARSER_AST_SELECT_STMT_HPP
#include "sql/ast/common.hpp"
#include "sql/ast/select_core.hpp"
#include <boost/optional.hpp>
#include <boost/spirit/home/x3/support/ast/position_tagged.hpp>
#include <vector>
namespace sql { namespace ast
{
namespace x3 = boost::spirit::x3;
struct ordering_term : x3::position_tagged {
expr expression;
direction_type direction;
};
typedef std::vector<ordering_term> ordering_term_list;
struct orderby_clause : x3::position_tagged {
ordering_term_list by;
bool dummy;
};
struct limit_clause : x3::position_tagged {
expr limit;
boost::optional<expr> offset;
};
// forward declaration
struct select_core;
struct select_stmt : x3::position_tagged
{
x3::forward_ast<select_core> core;
boost::optional<orderby_clause> ordering;
boost::optional<limit_clause> limits;
};
}}
#endif //SQL_PARSER_AST_SELECT_STMT_HPP
|
rm(list=ls())
library(ggplot2)
library(fpp2)
Sales_table <- read.table("~/SeniorStats/HW2/STA372_Homework2.dat.txt")
colnames(Sales_table) <- c("Time", "Quarter", "Sales")
Sales_table$LogSales <- log(Sales_table$Sales)
head(Sales_table)
figure <- ggplot()
figure <- figure + geom_point(aes(x=Sales_table$Time, y=Sales_table$Sales), color="Black")
figure <- figure + geom_line(aes(x=Sales_table$Time, y=Sales_table$Sales), linetype=1, color="Black")
figure <- figure + scale_y_continuous()
figure <- figure + ggtitle("Sales vs. Time") + xlab("Time") + ylab("Sales")
print(figure)
figure2 <- ggplot()
figure2 <- figure2 + geom_point(aes(x=Sales_table$Time, y=Sales_table$LogSales), color="Red")
figure2 <- figure2 + geom_line(aes(x=Sales_table$Time, y=Sales_table$LogSales), linetype=1, color="Red")
figure2 <- figure2 + scale_y_continuous()
figure2 <- figure2 + ggtitle("log(Sales) vs. Time") + xlab("Time") + ylab("log(Sales)")
print(figure2)
print("The log transformation stabilized the variance")
LogSales_time_series <- ts(Sales_table$LogSales, frequency = 4)
LogSales_time_series_components <- stl(LogSales_time_series, s.window =7)
plot(LogSales_time_series_components)
seasonal <- LogSales_time_series_components$time.series[,1]
Sales_table$LogA <- Sales_table$LogSales - seasonal
head(Sales_table)
figure3 <- ggplot()
figure3 <- figure3 + geom_point(aes(x=Sales_table$Time, y=Sales_table$LogA), color="Black")
figure3 <- figure3 + geom_line(aes(x=Sales_table$Time, y=Sales_table$LogA), linetype=1, color="Black")
figure3 <- figure3 + scale_y_continuous()
figure3 <- figure3 + ggtitle("Seasonally adjusted log(Sales)") + xlab("Time") + ylab("LogA")
print(figure3)
Sales_table$A <- exp(Sales_table$LogSales - seasonal)
head(Sales_table)
figure4 <- ggplot()
figure4 <- figure4 + geom_point(aes(x=Sales_table$Time, y=Sales_table$A), color="Black")
figure4 <- figure4 + geom_line(aes(x=Sales_table$Time, y=Sales_table$A), linetype=1, color="Black")
figure4 <- figure4 + scale_y_continuous()
figure4 <- figure4 + ggtitle("Seasonally adjusted Sales") + xlab("Time") + ylab("A")
print(figure4)
print("The stl decomposition procedure did a good job of seasonally adjusting sales") |
{-# LANGUAGE FlexibleContexts #-}
module Common
( splitMatrixOfSamples
, addOnesColumn
, getDimensions
, featureNormalize
, sigmoid
, sigmoidMatrix
, regularizeCost
, MinimizationOpts(..)
) where
import Numeric.LinearAlgebra.Data
( Matrix
, R
, Vector
, (|||)
, (¿)
, cmap
, cols
, flatten
, fromList
, fromLists
, matrix
, rows
, toList
, toLists
, tr'
)
import Numeric.LinearAlgebra (Container)
import Numeric.LinearAlgebra.Devel (foldVector)
data MinimizationOpts = MinimizationOpts
{ precision :: R
, tolerance :: R
, sizeOfFirstTrialStep :: R
} deriving (Eq)
splitMatrixOfSamples :: Matrix R -> (Matrix R, Vector R)
splitMatrixOfSamples mx =
let c = cols mx
in (mx ¿ [0 .. (c - 2)], flatten $ mx ¿ [(c - 1)])
addOnesColumn :: Matrix R -> Matrix R
addOnesColumn mx = matrix 1 (replicate (rows mx) 1) ||| mx
getDimensions :: Matrix R -> (Int, Int)
getDimensions mx = (rows mx, cols mx)
sigmoid :: R -> R
sigmoid z = 1 / (1 + exp (-1 * z))
sigmoidMatrix :: Container c R => c R -> c R
sigmoidMatrix = cmap sigmoid
regularizeCost :: Int -> Vector R -> R -> R -> R
regularizeCost m theta lambda cost =
let m' = fromIntegral m
regVal = (foldVector (\v accum -> (v ** 2) + accum) 0 theta)
in cost + ((regVal * lambda) / (3 * m'))
featureNormalize :: Matrix R -> Matrix R
featureNormalize mx =
let trMx = toLists $ tr' mx
normalizedTrMx =
zipWith
(\vals (mean, std) -> normalize mean std <$> vals)
trMx
(computeMeanAndStd <$> trMx)
in tr' $ fromLists normalizedTrMx
where
computeMean vals =
let (accum, n) = foldl (\(v', n') v -> (v + v', n' + 1)) (0, 0) vals
in (accum / n, n)
computeStd n mn vals =
let sumOfSquares =
foldl (\v' v -> ((v - mn) ** (2 :: Double)) + v') (0 :: Double) vals
in sqrt $ sumOfSquares / (n - 1)
computeMeanAndStd vals =
let (mean, n) = computeMean vals
std = computeStd n mean vals
in (mean, std)
normalize mean std val =
if std == 0
then mean
else (val - mean) / std
|
State Before: α : Type u_1
inst✝¹ : Preorder α
inst✝ : SuccOrder α
a b : α
n m : ℕ
h_eq : (succ^[n]) a = (succ^[m]) a
h_lt : n < m
⊢ IsMax ((succ^[n]) a) State After: α : Type u_1
inst✝¹ : Preorder α
inst✝ : SuccOrder α
a b : α
n m : ℕ
h_eq : (succ^[n]) a = (succ^[m]) a
h_lt : n < m
⊢ succ ((succ^[n]) a) ≤ (succ^[m]) a Tactic: refine' max_of_succ_le (le_trans _ h_eq.symm.le) State Before: α : Type u_1
inst✝¹ : Preorder α
inst✝ : SuccOrder α
a b : α
n m : ℕ
h_eq : (succ^[n]) a = (succ^[m]) a
h_lt : n < m
⊢ succ ((succ^[n]) a) ≤ (succ^[m]) a State After: α : Type u_1
inst✝¹ : Preorder α
inst✝ : SuccOrder α
a b : α
n m : ℕ
h_eq : (succ^[n]) a = (succ^[m]) a
h_lt : n < m
this : succ ((succ^[n]) a) = (succ^[n + 1]) a
⊢ succ ((succ^[n]) a) ≤ (succ^[m]) a Tactic: have : succ ((succ^[n]) a) = (succ^[n + 1]) a := by rw [Function.iterate_succ', comp] State Before: α : Type u_1
inst✝¹ : Preorder α
inst✝ : SuccOrder α
a b : α
n m : ℕ
h_eq : (succ^[n]) a = (succ^[m]) a
h_lt : n < m
this : succ ((succ^[n]) a) = (succ^[n + 1]) a
⊢ succ ((succ^[n]) a) ≤ (succ^[m]) a State After: α : Type u_1
inst✝¹ : Preorder α
inst✝ : SuccOrder α
a b : α
n m : ℕ
h_eq : (succ^[n]) a = (succ^[m]) a
h_lt : n < m
this : succ ((succ^[n]) a) = (succ^[n + 1]) a
⊢ (succ^[n + 1]) a ≤ (succ^[m]) a Tactic: rw [this] State Before: α : Type u_1
inst✝¹ : Preorder α
inst✝ : SuccOrder α
a b : α
n m : ℕ
h_eq : (succ^[n]) a = (succ^[m]) a
h_lt : n < m
this : succ ((succ^[n]) a) = (succ^[n + 1]) a
⊢ (succ^[n + 1]) a ≤ (succ^[m]) a State After: α : Type u_1
inst✝¹ : Preorder α
inst✝ : SuccOrder α
a b : α
n m : ℕ
h_eq : (succ^[n]) a = (succ^[m]) a
h_lt : n < m
this : succ ((succ^[n]) a) = (succ^[n + 1]) a
h_le : n + 1 ≤ m
⊢ (succ^[n + 1]) a ≤ (succ^[m]) a Tactic: have h_le : n + 1 ≤ m := Nat.succ_le_of_lt h_lt State Before: α : Type u_1
inst✝¹ : Preorder α
inst✝ : SuccOrder α
a b : α
n m : ℕ
h_eq : (succ^[n]) a = (succ^[m]) a
h_lt : n < m
this : succ ((succ^[n]) a) = (succ^[n + 1]) a
h_le : n + 1 ≤ m
⊢ (succ^[n + 1]) a ≤ (succ^[m]) a State After: no goals Tactic: exact Monotone.monotone_iterate_of_le_map succ_mono (le_succ a) h_le State Before: α : Type u_1
inst✝¹ : Preorder α
inst✝ : SuccOrder α
a b : α
n m : ℕ
h_eq : (succ^[n]) a = (succ^[m]) a
h_lt : n < m
⊢ succ ((succ^[n]) a) = (succ^[n + 1]) a State After: no goals Tactic: rw [Function.iterate_succ', comp] |
I am a bit bored with some of the florals I have and seems my regular place to get them does not carry the selection it used to. Sooo, I am on a hunt for a new vendor with some exciting selections. Around the shop you will notice I carry more than just pip berries.. I like a wide variety and like some unusual stuff.. everything from coleus and dusty miller to wild grassy picks.
This rustic looking floral is Pepper Grass and I am loving it in just about anything I put it in. It is a neat color.. going with the traditional burgundy, mustard and brown.. and also with some of the new reds and sage greens we are seeing. I have it in rusty pots and here it is in an old kettle.
These little Deacon Benches are back in stock and are a nice way to add some height to an arrangement. Made with pine that has a medium stain and a rusty star, they go with just about anything.
No matter how careful you are making candles and melts.. some wax always ends up on the counter. Usually, we scrape it off and that is what I use at the house in my warmers. But, I have been burning some candles and have decided to try something new. Now we are bagging our scraps and selling them for .50 an ounce. Our regular melts are $1 per ounce, so you are getting your wax at half the price. There is no telling what you will get.. but that is half the fun. So, while we have it, come try an assorted bag of scraps and enjoy fragrance at an unbeatable price.
For God so loved He gave.. |
using Test
using Base64, JSON
import IJulia
import IJulia: helpmode, error_content, docdict
@testset "errors" begin
content = error_content(UndefVarError(:a))
@test "UndefVarError" == content["ename"]
end
@testset "docdict" begin
@test haskey(docdict("import"), "text/plain")
@test haskey(docdict("sum"), "text/plain")
end
struct FriendlyData
name::AbstractString
end
@testset "Custom MIME types" begin
friend = FriendlyData("world")
FRIENDLY_MIME_TYPE = MIME"application/vnd.ijulia.friendly-text"
FRIENDLY_MIME = FRIENDLY_MIME_TYPE()
Base.Multimedia.istextmime(::FRIENDLY_MIME_TYPE) = true
Base.show(io, ::FRIENDLY_MIME_TYPE, x::FriendlyData) = write(io, "Hello, $(x.name)!")
IJulia.register_mime(FRIENDLY_MIME)
BINARY_MIME_TYPE = MIME"application/vnd.ijulia.friendly-binary"
BINARY_MIME = BINARY_MIME_TYPE()
Base.Multimedia.istextmime(::BINARY_MIME_TYPE) = false
Base.show(io, ::BINARY_MIME_TYPE, x::FriendlyData) = write(io, "Hello, $(x.name)!")
IJulia.register_mime(BINARY_MIME)
JSON_MIME_TYPE = MIME"application/vnd.ijulia.friendly-json"
JSON_MIME = JSON_MIME_TYPE()
Base.Multimedia.istextmime(::JSON_MIME_TYPE) = true
Base.show(io, ::JSON_MIME_TYPE, x::FriendlyData) = write(io, JSON.json(Dict("name" => x.name)))
IJulia.register_jsonmime(JSON_MIME)
FRIENDLY_MIME_TYPE_1 = MIME"application/vnd.ijulia.friendly-text-1"
FRIENDLY_MIME_TYPE_2 = MIME"application/vnd.ijulia.friendly-text-2"
FRIENDLY_MIME_1 = FRIENDLY_MIME_TYPE_1()
FRIENDLY_MIME_2 = FRIENDLY_MIME_TYPE_2()
FRIENDLY_MIME_TYPE_UNION = Union{FRIENDLY_MIME_TYPE_1, FRIENDLY_MIME_TYPE_2}
Base.Multimedia.istextmime(::FRIENDLY_MIME_TYPE_UNION) = true
Base.show(io, ::FRIENDLY_MIME_TYPE_UNION, x::FriendlyData) = write(io, "Hello, $(x.name)!")
IJulia.register_mime([FRIENDLY_MIME_1, FRIENDLY_MIME_2])
# We stringify then re-parse the dict so that JSONText's are parsed as
# actual JSON objects and we can index into them.
data = JSON.parse(JSON.json(IJulia.display_dict(friend)))
@test data[string(FRIENDLY_MIME)] == "Hello, world!"
@test data[string(BINARY_MIME)] == base64encode("Hello, world!")
@test data[string(JSON_MIME)]["name"] == "world"
@test data[string(FRIENDLY_MIME_1)] == "Hello, world!"
@test !haskey(data, string(FRIENDLY_MIME_2))
end
struct AngryData
thing::AbstractString
end
@testset "Render 1st available MIME in MIME-vector." begin
ANGRY_MIME_TYPE_1 = MIME"application/vnd.ijulia.angry-1"
ANGRY_MIME_1 = ANGRY_MIME_TYPE_1()
ANGRY_MIME_TYPE_2 = MIME"application/vnd.ijulia.angry-2"
ANGRY_MIME_2 = ANGRY_MIME_TYPE_2()
ANGRY_MIME_TYPE_3 = MIME"application/vnd.ijulia.angry-3"
ANGRY_MIME_3 = ANGRY_MIME_TYPE_3()
ANGRY_MIME_VECTOR = [ANGRY_MIME_1, ANGRY_MIME_2, ANGRY_MIME_3]
Base.Multimedia.istextmime(::Union{ANGRY_MIME_TYPE_1, ANGRY_MIME_TYPE_2, ANGRY_MIME_TYPE_3}) = true
Base.show(io, ::Union{ANGRY_MIME_TYPE_2, ANGRY_MIME_TYPE_3}, x::AngryData) = write(io, "I hate $(x.thing)!")
IJulia.register_mime(ANGRY_MIME_VECTOR)
broccoli = AngryData("broccoli")
@test IJulia._showable(ANGRY_MIME_VECTOR, broccoli)
@test !IJulia._showable(ANGRY_MIME_1, broccoli)
data = IJulia.display_dict(broccoli)
@test data[string(ANGRY_MIME_2)] == "I hate broccoli!"
@test !haskey(data, ANGRY_MIME_1)
@test !haskey(data, ANGRY_MIME_3)
end
|
One Day Excursion to St. Catherine Monastery from Dahab.
The monastery: Situated at the base of the mountain where Moses received the Ten Commandments, St Catherine's Monastery is one of the most famous in the world. Built between 527 and 565 AD, it is believed to be built around Moses' Burning Bush. The Monastery is named after St Catherine who was tortured and beheaded for her Christian beliefs. During your visit you will see chapel Greek Orthodox Church, the icons of worship and the famous Mosaic of Transfiguration.
Departure after breakfast from hotel for a 1 1/2 hours drive to one of the oldest monasteries, St. Catherine, which lies between two mountains at a height of 1570 meters. You will visit the Chapel of the Burning Bush, which was built over the tire roots of the Holy Thorne bush, where God spoke to Moses. You can also see the beautiful Byzantine mosaics and enjoy an amazing collection of icons. Driving back, through Dahab for 1 hour, a small city close to the sea shore, where you have the chance to do some shopping. |
[STATEMENT]
lemma lt_imp_ex_count_lt: "M < N \<Longrightarrow> \<exists>y. count M y < count N y"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. M < N \<Longrightarrow> \<exists>y. count M y < count N y
[PROOF STEP]
by (meson less_eq_multiset\<^sub>H\<^sub>O less_le_not_le) |
The unit was exceptionally clean and secure. I highly recommend Heartland Storage.
I am so glad your time with us was a good one. We strive to provide each and every client with a positive storage experience.
Very clean and courteous place. Highly recommend.
Very helpful with U-Haul selection and courteous service.
Welcome to Heartland Storage! Our Franklin, Indiana facility boasts all the services and amenities you need to make your next storage project as easy as possible. With truck rental, drive-up access, and heightened security, you can’t go wrong when you chose to store with Franklin’s premier storage facility.
We work hard to bring you everything you need to make your time on our property as enjoyable as possible. Drive-up, ground floor access means you can simply pull up to your unit and unload your vehicle. 24-hour access allows you to get into your unit on your own time without having to plan your schedule around our hours. Plus, we’re an authorized U-Haul dealer, so we have all the truck and trailer sizes you’ll need to get your move finished.
We want you to feel confident in the security our facility provides. That’s why we built our property with perimeter fencing and electronically controlled gate access to make sure only our tenants are able to get onto the grounds. We also have 24-hour video surveillance to keep a watchful eye on your unit at all times. Never worry about the safety of your belongings again when you store with Heartland Storage.
Our friendly, professional staff is always available to help and provide you with the highest level of customer service in the industry. Our office sells moving and packing supplies in case you discover you need anything. We offer low-cost insurance for out tenants and have onsite faxing and copying services. With the lowest prices in town, there’s no reason why you shouldn’t check out Heartland Storage for your next move or storage need. Give our staff a call to learn more about how we can help you out!
Although the office might be closed we will make every attempt to answer calls outside of the hours listed above. If we dont anwer we will call back ASAP. All of the calls to the office will be forwarded to one of our cell phones so we can assist our customers at any time. Thanks for your continued business!! |
"""
# Description
Rewrite an expression to remove all use of backticks.
# Arguments
1. `e::Any`: An expression.
# Return Values
1. `e::Any`: An expression in which backticks have been removed.
# Examples
```
julia> remove_backticks(:(`mean(a)`))
:(mean(a))
```
"""
function remove_backticks(@nospecialize(e::Any))
if isa(e, Expr) && e.head == :macrocall && isa(e.args[1], GlobalRef) && e.args[1].name == Symbol("@cmd")
Meta.parse(e.args[3])
elseif isa(e, Expr)
Expr(
e.head,
[remove_backticks(a) for a in e.args]...,
)
else
e
end
end
|
using MultipleScattering
using Base.Test
using Plots
@testset "Summary" begin
include("shapetests.jl")
include("particle_tests.jl")
include("time_simulation_tests.jl")
include("moments_tests.jl")
# test our discretised Fourier transforms
@testset "Fourier tranforms" begin
include("fourier_test.jl")
@test fourier_test()
end
@testset "Type stability" begin
# Define everything as a Float32
volfrac = 0.01f0
radius = 1.0f0
k_arr = collect(LinRange(0.01f0,1.0f0,100))
simulation = FrequencySimulation(volfrac,radius,k_arr)
@test typeof(simulation.response[1]) == Complex{Float32}
end
@testset "Single scatterer" begin
include("single_scatter.jl")
# Test against analytic solution
@test single_scatter_test()
end
@testset "Boundary conditions" begin
include("boundary_conditions.jl")
# Test boundary conditions for 4 particles with random properties and positions.
@test boundary_conditions_test()
end
@testset "Plot FrequencySimulation" begin
# Just run it to see if we have any errors (yes thats a very low bar)
volfrac = 0.01
radius = 2.0
k_arr = collect(LinRange(0.2,1.0,5))
simulation = FrequencySimulation(volfrac,radius,k_arr)
plot(simulation)
plot(simulation,0.2)
@test true
end
end
|
#pragma once
#include "Core/Pointers.h"
#include "Graphics/GraphicsResource.h"
#include "Graphics/TextureInfo.h"
#include <glad/gl.h>
#include <gsl/span>
#include <vector>
class Texture;
struct Viewport;
namespace Fb
{
enum class DepthStencilType
{
None,
Depth24Stencil8,
Depth32FStencil8
};
enum class Target
{
Framebuffer = GL_FRAMEBUFFER,
ReadFramebuffer = GL_READ_FRAMEBUFFER,
DrawFramebuffer = GL_DRAW_FRAMEBUFFER
};
enum class CubeFace
{
Front,
Back,
Top,
Bottom,
Left,
Right
};
struct Specification
{
GLsizei width = 0;
GLsizei height = 0;
GLsizei samples = 0;
bool cubeMap = false;
DepthStencilType depthStencilType = DepthStencilType::Depth24Stencil8;
gsl::span<const Tex::InternalFormat> colorAttachmentFormats;
bool operator==(const Specification& other) const;
};
struct Attachments
{
SPtr<Texture> depthStencilAttachment;
std::vector<SPtr<Texture>> colorAttachments;
};
Attachments generateAttachments(const Specification& specification);
}
namespace std
{
template<>
struct hash<Fb::Specification>
{
size_t operator()(const Fb::Specification& specification) const;
};
}
class Framebuffer : public GraphicsResource
{
public:
Framebuffer();
Framebuffer(const Framebuffer& other) = delete;
Framebuffer(Framebuffer&& other);
~Framebuffer();
Framebuffer& operator=(const Framebuffer& other) = delete;
Framebuffer& operator=(Framebuffer&& other);
private:
void move(Framebuffer&& other);
void release();
public:
using SpecificationType = Fb::Specification;
static SPtr<Framebuffer> create(const Fb::Specification& specification);
static const char* labelSuffix();
static void blit(Framebuffer& source, Framebuffer& destination, GLenum readBuffer, GLenum drawBuffer, GLbitfield mask, GLenum filter);
static void bindDefault(Fb::Target target = Fb::Target::Framebuffer);
void bind(Fb::Target target = Fb::Target::Framebuffer);
bool isBound(Fb::Target target = Fb::Target::Framebuffer) const;
const Fb::Attachments& getAttachments() const
{
return attachments;
}
const SPtr<Texture>& getDepthStencilAttachment() const;
SPtr<Texture> getColorAttachment(int index) const;
void setAttachments(Fb::Attachments newAttachments);
bool getViewport(Viewport& viewport) const;
bool isCubeMap() const;
void setActiveFace(Fb::CubeFace face);
private:
const SPtr<Texture>* getFirstValidAttachment() const;
Fb::Attachments attachments;
};
|
#include <gsl/gsl_combination.h>
#include <gsl/gsl_errno.h>
#include <stdio.h>
int mgsl_combination_fwrite(const char *filename, const gsl_combination *p)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_combination_fwrite(fp, p) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_combination_fread(const char *filename, gsl_combination *p)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_combination_fread(fp, p) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_combination_fprintf(const char *filename, const gsl_combination *p, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_combination_fprintf(fp, p, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_combination_fscanf(const char *filename, gsl_combination *p)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_combination_fscanf(fp, p) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
|
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
j : Fin (n + 2)
hj₁ : j ≠ 0
hj₂ : n + 2 ≤ ↑j + q
⊢ φ ≫ δ X j = 0
[PROOFSTEP]
obtain ⟨i, rfl⟩ := Fin.eq_succ_of_ne_zero hj₁
[GOAL]
case intro
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
i : Fin (n + 1)
hj₁ : Fin.succ i ≠ 0
hj₂ : n + 2 ≤ ↑(Fin.succ i) + q
⊢ φ ≫ δ X (Fin.succ i) = 0
[PROOFSTEP]
apply v i
[GOAL]
case intro
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
i : Fin (n + 1)
hj₁ : Fin.succ i ≠ 0
hj₂ : n + 2 ≤ ↑(Fin.succ i) + q
⊢ n + 1 ≤ ↑i + q
[PROOFSTEP]
simp only [Fin.val_succ] at hj₂
[GOAL]
case intro
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
i : Fin (n + 1)
hj₁ : Fin.succ i ≠ 0
hj₂ : n + 2 ≤ ↑i + 1 + q
⊢ n + 1 ≤ ↑i + q
[PROOFSTEP]
linarith
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish (q + 1) φ
j : Fin (n + 1)
hj : n + 1 ≤ ↑j + q
⊢ n + 1 ≤ ↑j + (q + 1)
[PROOFSTEP]
simpa only [← add_assoc] using le_add_right hj
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y Z : C
q n : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
f : Z ⟶ Y
j : Fin (n + 1)
hj : n + 1 ≤ ↑j + q
⊢ (f ≫ φ) ≫ δ X (Fin.succ j) = 0
[PROOFSTEP]
rw [assoc, v j hj, comp_zero]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
⊢ φ ≫ HomologicalComplex.Hom.f (Hσ q) (n + 1) =
-φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (n + 1)) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }
[PROOFSTEP]
have hnaq_shift : ∀ d : ℕ, n + d = a + d + q := by
intro d
rw [add_assoc, add_comm d, ← add_assoc, hnaq]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
⊢ ∀ (d : ℕ), n + d = a + d + q
[PROOFSTEP]
intro d
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
d : ℕ
⊢ n + d = a + d + q
[PROOFSTEP]
rw [add_assoc, add_comm d, ← add_assoc, hnaq]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
⊢ φ ≫ HomologicalComplex.Hom.f (Hσ q) (n + 1) =
-φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (n + 1)) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }
[PROOFSTEP]
rw [Hσ, Homotopy.nullHomotopicMap'_f (c_mk (n + 2) (n + 1) rfl) (c_mk (n + 1) n rfl), hσ'_eq hnaq (c_mk (n + 1) n rfl),
hσ'_eq (hnaq_shift 1) (c_mk (n + 2) (n + 1) rfl)]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
⊢ φ ≫
(HomologicalComplex.d (AlternatingFaceMapComplex.obj X) (n + 1) n ≫
((-1) ^ a • σ X { val := a, isLt := (_ : a < Nat.succ n) }) ≫
eqToHom (_ : X.obj (Opposite.op [n + 1]) = X.obj (Opposite.op [n + 1])) +
(((-1) ^ (a + 1) • σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) }) ≫
eqToHom (_ : X.obj (Opposite.op [n + 1 + 1]) = X.obj (Opposite.op [n + 2]))) ≫
HomologicalComplex.d (AlternatingFaceMapComplex.obj X) (n + 2) (n + 1)) =
-φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (n + 1)) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }
[PROOFSTEP]
simp only [AlternatingFaceMapComplex.obj_d_eq, eqToHom_refl, comp_id, comp_sum, sum_comp, comp_add]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
⊢ ((Finset.sum Finset.univ fun j =>
φ ≫ ((-1) ^ ↑j • δ X j) ≫ ((-1) ^ a • σ X { val := a, isLt := (_ : a < Nat.succ n) })) +
Finset.sum Finset.univ fun j =>
φ ≫ ((-1) ^ (a + 1) • σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) }) ≫ ((-1) ^ ↑j • δ X j)) =
-φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (n + 1)) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }
[PROOFSTEP]
simp only [comp_zsmul, zsmul_comp, ← assoc, ← mul_zsmul]
-- cleaning up the first sum
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
⊢ ((Finset.sum Finset.univ fun x =>
((-1) ^ a * (-1) ^ ↑x) • (φ ≫ δ X x) ≫ σ X { val := a, isLt := (_ : a < Nat.succ n) }) +
Finset.sum Finset.univ fun x =>
((-1) ^ ↑x * (-1) ^ (a + 1)) • (φ ≫ σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) }) ≫ δ X x) =
-(φ ≫ δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (n + 1)) }) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }
[PROOFSTEP]
rw [← Fin.sum_congr' _ (hnaq_shift 2).symm, Fin.sum_trunc]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
⊢ ((Finset.sum Finset.univ fun i =>
((-1) ^ a * (-1) ^ ↑(↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) i))) •
(φ ≫ δ X (↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) i))) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }) +
Finset.sum Finset.univ fun x =>
((-1) ^ ↑x * (-1) ^ (a + 1)) • (φ ≫ σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) }) ≫ δ X x) =
-(φ ≫ δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (n + 1)) }) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }
case hf
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
⊢ ∀ (j : Fin q),
((-1) ^ a * (-1) ^ ↑(↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.natAdd (a + 2) j))) •
(φ ≫ δ X (↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.natAdd (a + 2) j))) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) } =
0
[PROOFSTEP]
swap
[GOAL]
case hf
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
⊢ ∀ (j : Fin q),
((-1) ^ a * (-1) ^ ↑(↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.natAdd (a + 2) j))) •
(φ ≫ δ X (↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.natAdd (a + 2) j))) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) } =
0
[PROOFSTEP]
rintro ⟨k, hk⟩
[GOAL]
case hf.mk
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
⊢ ((-1) ^ a * (-1) ^ ↑(↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.natAdd (a + 2) { val := k, isLt := hk }))) •
(φ ≫ δ X (↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.natAdd (a + 2) { val := k, isLt := hk }))) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) } =
0
[PROOFSTEP]
suffices φ ≫ X.δ (⟨a + 2 + k, by linarith⟩ : Fin (n + 2)) = 0 by
simp only [this, Fin.natAdd_mk, Fin.castIso_mk, zero_comp, smul_zero]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
⊢ a + 2 + k < n + 2
[PROOFSTEP]
linarith
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
this : φ ≫ δ X { val := a + 2 + k, isLt := (_ : a + 2 + k < n + 2) } = 0
⊢ ((-1) ^ a * (-1) ^ ↑(↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.natAdd (a + 2) { val := k, isLt := hk }))) •
(φ ≫ δ X (↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.natAdd (a + 2) { val := k, isLt := hk }))) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) } =
0
[PROOFSTEP]
simp only [this, Fin.natAdd_mk, Fin.castIso_mk, zero_comp, smul_zero]
[GOAL]
case hf.mk
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
⊢ φ ≫ δ X { val := a + 2 + k, isLt := (_ : a + 2 + k < n + 2) } = 0
[PROOFSTEP]
convert v ⟨a + k + 1, by linarith⟩ (by rw [Fin.val_mk]; linarith)
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
⊢ a + k + 1 < n + 1
[PROOFSTEP]
linarith
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
⊢ n + 1 ≤ ↑{ val := a + k + 1, isLt := (_ : a + k + 1 < n + 1) } + q
[PROOFSTEP]
rw [Fin.val_mk]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
⊢ n + 1 ≤ a + k + 1 + q
[PROOFSTEP]
linarith
[GOAL]
case h.e'_2.h.e'_7.h.e'_5.h.e'_2
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
⊢ a + 2 + k = ↑(Fin.succ { val := a + k + 1, isLt := (_ : a + k + 1 < n + 1) })
[PROOFSTEP]
dsimp
[GOAL]
case h.e'_2.h.e'_7.h.e'_5.h.e'_2
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
⊢ a + 2 + k = a + k + 1 + 1
[PROOFSTEP]
linarith
-- cleaning up the second sum
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
⊢ ((Finset.sum Finset.univ fun i =>
((-1) ^ a * (-1) ^ ↑(↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) i))) •
(φ ≫ δ X (↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) i))) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }) +
Finset.sum Finset.univ fun x =>
((-1) ^ ↑x * (-1) ^ (a + 1)) • (φ ≫ σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) }) ≫ δ X x) =
-(φ ≫ δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (n + 1)) }) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }
[PROOFSTEP]
rw [← Fin.sum_congr' _ (hnaq_shift 3).symm, @Fin.sum_trunc _ _ (a + 3)]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
⊢ ((Finset.sum Finset.univ fun i =>
((-1) ^ a * (-1) ^ ↑(↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) i))) •
(φ ≫ δ X (↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) i))) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }) +
Finset.sum Finset.univ fun i =>
((-1) ^ ↑(↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) i)) * (-1) ^ (a + 1)) •
(φ ≫ σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) }) ≫
δ X (↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) i))) =
-(φ ≫ δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (n + 1)) }) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }
case hf
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
⊢ ∀ (j : Fin q),
((-1) ^ ↑(↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.natAdd (a + 3) j)) * (-1) ^ (a + 1)) •
(φ ≫ σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) }) ≫
δ X (↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.natAdd (a + 3) j)) =
0
[PROOFSTEP]
swap
[GOAL]
case hf
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
⊢ ∀ (j : Fin q),
((-1) ^ ↑(↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.natAdd (a + 3) j)) * (-1) ^ (a + 1)) •
(φ ≫ σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) }) ≫
δ X (↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.natAdd (a + 3) j)) =
0
[PROOFSTEP]
rintro ⟨k, hk⟩
[GOAL]
case hf.mk
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
⊢ ((-1) ^ ↑(↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.natAdd (a + 3) { val := k, isLt := hk })) * (-1) ^ (a + 1)) •
(φ ≫ σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) }) ≫
δ X (↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.natAdd (a + 3) { val := k, isLt := hk })) =
0
[PROOFSTEP]
rw [assoc, X.δ_comp_σ_of_gt', v.comp_δ_eq_zero_assoc, zero_comp, zsmul_zero]
[GOAL]
case hf.mk
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
⊢ Fin.succ { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } <
↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.natAdd (a + 3) { val := k, isLt := hk })
[PROOFSTEP]
simp only [Fin.lt_iff_val_lt_val]
[GOAL]
case hf.mk
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
⊢ ↑(Fin.succ { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) }) <
↑(↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.natAdd (a + 3) { val := k, isLt := hk }))
[PROOFSTEP]
dsimp [Fin.natAdd, Fin.castIso]
[GOAL]
case hf.mk
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
⊢ a + 1 + 1 < a + 3 + k
[PROOFSTEP]
linarith
[GOAL]
case hf.mk.hj₁
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
⊢ Fin.pred (↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.natAdd (a + 3) { val := k, isLt := hk }))
(_ : ↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.natAdd (a + 3) { val := k, isLt := hk }) = 0 → False) ≠
0
[PROOFSTEP]
intro h
[GOAL]
case hf.mk.hj₁
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
h :
Fin.pred (↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.natAdd (a + 3) { val := k, isLt := hk }))
(_ : ↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.natAdd (a + 3) { val := k, isLt := hk }) = 0 → False) =
0
⊢ False
[PROOFSTEP]
rw [Fin.pred_eq_iff_eq_succ, Fin.ext_iff] at h
[GOAL]
case hf.mk.hj₁
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
h : ↑(↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.natAdd (a + 3) { val := k, isLt := hk })) = ↑(Fin.succ 0)
⊢ False
[PROOFSTEP]
dsimp [Fin.castIso] at h
[GOAL]
case hf.mk.hj₁
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
h : a + 3 + k = 1
⊢ False
[PROOFSTEP]
linarith
[GOAL]
case hf.mk.hj₂
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
⊢ n + 2 ≤
↑(Fin.pred (↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.natAdd (a + 3) { val := k, isLt := hk }))
(_ : ↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.natAdd (a + 3) { val := k, isLt := hk }) = 0 → False)) +
q
[PROOFSTEP]
dsimp [Fin.castIso, Fin.pred]
[GOAL]
case hf.mk.hj₂
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
⊢ n + 2 ≤ a + 3 + k - 1 + q
[PROOFSTEP]
rw [Nat.add_right_comm, Nat.add_sub_assoc (by norm_num : 1 ≤ 3)]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
⊢ 1 ≤ 3
[PROOFSTEP]
norm_num
[GOAL]
case hf.mk.hj₂
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
k : ℕ
hk : k < q
⊢ n + 2 ≤ a + k + (3 - 1) + q
[PROOFSTEP]
linarith
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
⊢ ((Finset.sum Finset.univ fun i =>
((-1) ^ a * (-1) ^ ↑(↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) i))) •
(φ ≫ δ X (↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) i))) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }) +
Finset.sum Finset.univ fun i =>
((-1) ^ ↑(↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) i)) * (-1) ^ (a + 1)) •
(φ ≫ σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) }) ≫
δ X (↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) i))) =
-(φ ≫ δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (n + 1)) }) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }
[PROOFSTEP]
simp only [assoc]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
⊢ ((Finset.sum Finset.univ fun x =>
((-1) ^ a * (-1) ^ ↑(↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) x))) •
φ ≫
δ X (↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) x)) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }) +
Finset.sum Finset.univ fun x =>
((-1) ^ ↑(↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) x)) * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X (↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) x))) =
-φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (n + 1)) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }
[PROOFSTEP]
conv_lhs =>
congr
·rw [Fin.sum_univ_castSucc]
·rw [Fin.sum_univ_castSucc, Fin.sum_univ_castSucc]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
| (Finset.sum Finset.univ fun x =>
((-1) ^ a * (-1) ^ ↑(↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) x))) •
φ ≫
δ X (↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) x)) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }) +
Finset.sum Finset.univ fun x =>
((-1) ^ ↑(↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) x)) * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X (↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) x))
[PROOFSTEP]
congr
·rw [Fin.sum_univ_castSucc]
·rw [Fin.sum_univ_castSucc, Fin.sum_univ_castSucc]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
| (Finset.sum Finset.univ fun x =>
((-1) ^ a * (-1) ^ ↑(↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) x))) •
φ ≫
δ X (↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) x)) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }) +
Finset.sum Finset.univ fun x =>
((-1) ^ ↑(↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) x)) * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X (↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) x))
[PROOFSTEP]
congr
·rw [Fin.sum_univ_castSucc]
·rw [Fin.sum_univ_castSucc, Fin.sum_univ_castSucc]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
| (Finset.sum Finset.univ fun x =>
((-1) ^ a * (-1) ^ ↑(↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) x))) •
φ ≫
δ X (↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) x)) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }) +
Finset.sum Finset.univ fun x =>
((-1) ^ ↑(↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) x)) * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X (↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) x))
[PROOFSTEP]
congr
[GOAL]
case a
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
| Finset.sum Finset.univ fun x =>
((-1) ^ a * (-1) ^ ↑(↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) x))) •
φ ≫
δ X (↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) x)) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }
case a
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
| Finset.sum Finset.univ fun x =>
((-1) ^ ↑(↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) x)) * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X (↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) x))
[PROOFSTEP]
·rw [Fin.sum_univ_castSucc]
[GOAL]
case a
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
| Finset.sum Finset.univ fun x =>
((-1) ^ a * (-1) ^ ↑(↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) x))) •
φ ≫
δ X (↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) x)) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }
[PROOFSTEP]
rw [Fin.sum_univ_castSucc]
[GOAL]
case a
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
| Finset.sum Finset.univ fun x =>
((-1) ^ a * (-1) ^ ↑(↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) x))) •
φ ≫
δ X (↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) x)) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }
[PROOFSTEP]
rw [Fin.sum_univ_castSucc]
[GOAL]
case a
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
| Finset.sum Finset.univ fun x =>
((-1) ^ a * (-1) ^ ↑(↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) x))) •
φ ≫
δ X (↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) x)) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }
[PROOFSTEP]
rw [Fin.sum_univ_castSucc]
[GOAL]
case a
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
| Finset.sum Finset.univ fun x =>
((-1) ^ ↑(↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) x)) * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X (↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) x))
[PROOFSTEP]
·rw [Fin.sum_univ_castSucc, Fin.sum_univ_castSucc]
[GOAL]
case a
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
| Finset.sum Finset.univ fun x =>
((-1) ^ ↑(↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) x)) * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X (↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) x))
[PROOFSTEP]
rw [Fin.sum_univ_castSucc, Fin.sum_univ_castSucc]
[GOAL]
case a
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
| Finset.sum Finset.univ fun x =>
((-1) ^ ↑(↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) x)) * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X (↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) x))
[PROOFSTEP]
rw [Fin.sum_univ_castSucc, Fin.sum_univ_castSucc]
[GOAL]
case a
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
| Finset.sum Finset.univ fun x =>
((-1) ^ ↑(↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) x)) * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X (↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) x))
[PROOFSTEP]
rw [Fin.sum_univ_castSucc, Fin.sum_univ_castSucc]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
⊢ (Finset.sum Finset.univ fun i =>
((-1) ^ a *
(-1) ^ ↑(↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) (Fin.castSucc i)))) •
φ ≫
δ X (↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) (Fin.castSucc i))) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }) +
((-1) ^ a *
(-1) ^ ↑(↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) (Fin.last (a + 1))))) •
φ ≫
δ X (↑(Fin.castIso (_ : a + 2 + q = n + 2)) (Fin.castLE (_ : a + 2 ≤ a + 2 + q) (Fin.last (a + 1)))) ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) } +
((Finset.sum Finset.univ fun i =>
((-1) ^
↑(↑(Fin.castIso (_ : a + 3 + q = n + 3))
(Fin.castLE (_ : a + 3 ≤ a + 3 + q) (Fin.castSucc (Fin.castSucc i)))) *
(-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X
(↑(Fin.castIso (_ : a + 3 + q = n + 3))
(Fin.castLE (_ : a + 3 ≤ a + 3 + q) (Fin.castSucc (Fin.castSucc i))))) +
((-1) ^
↑(↑(Fin.castIso (_ : a + 3 + q = n + 3))
(Fin.castLE (_ : a + 3 ≤ a + 3 + q) (Fin.castSucc (Fin.last (a + 1))))) *
(-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X
(↑(Fin.castIso (_ : a + 3 + q = n + 3))
(Fin.castLE (_ : a + 3 ≤ a + 3 + q) (Fin.castSucc (Fin.last (a + 1))))) +
((-1) ^ ↑(↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) (Fin.last (a + 2)))) *
(-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X (↑(Fin.castIso (_ : a + 3 + q = n + 3)) (Fin.castLE (_ : a + 3 ≤ a + 3 + q) (Fin.last (a + 2))))) =
-φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (n + 1)) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }
[PROOFSTEP]
dsimp [Fin.castIso, Fin.castLE, Fin.castLT]
/- the purpose of the following `simplif` is to create three subgoals in order
to finish the proof -/
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
⊢ (Finset.sum Finset.univ fun i =>
((-1) ^ a * (-1) ^ ↑i) •
φ ≫
δ X { val := ↑i, isLt := (_ : ↑{ val := ↑i, isLt := (_ : ↑(Fin.castSucc i) < a + 2 + q) } < n + 2) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }) +
((-1) ^ a * (-1) ^ (a + 1)) •
φ ≫
δ X
{ val := a + 1,
isLt := (_ : ↑{ val := a + 1, isLt := (_ : ↑(Fin.last (a + 1)) < a + 2 + q) } < n + 2) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) } +
((Finset.sum Finset.univ fun i =>
((-1) ^ ↑i * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X
{ val := ↑i,
isLt :=
(_ : ↑{ val := ↑i, isLt := (_ : ↑(Fin.castSucc (Fin.castSucc i)) < a + 3 + q) } < n + 3) }) +
((-1) ^ (a + 1) * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X
{ val := a + 1,
isLt :=
(_ : ↑{ val := a + 1, isLt := (_ : ↑(Fin.castSucc (Fin.last (a + 1))) < a + 3 + q) } < n + 3) } +
((-1) ^ (a + 2) * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X
{ val := a + 2,
isLt := (_ : ↑{ val := a + 2, isLt := (_ : ↑(Fin.last (a + 2)) < a + 3 + q) } < n + 3) }) =
-φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (n + 1)) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }
[PROOFSTEP]
have simplif : ∀ a b c d e f : Y ⟶ X _[n + 1], b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f :=
by
intro a b c d e f h1 h2 h3
rw [add_assoc c d e, h2, add_zero, add_comm a, add_assoc, add_comm a, h3, add_zero, h1]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
⊢ ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
[PROOFSTEP]
intro a b c d e f h1 h2 h3
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a✝ q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a✝ + q
hnaq_shift : ∀ (d : ℕ), n + d = a✝ + d + q
a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])
h1 : b = f
h2 : d + e = 0
h3 : c + a = 0
⊢ a + b + (c + d + e) = f
[PROOFSTEP]
rw [add_assoc c d e, h2, add_zero, add_comm a, add_assoc, add_comm a, h3, add_zero, h1]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
simplif : ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
⊢ (Finset.sum Finset.univ fun i =>
((-1) ^ a * (-1) ^ ↑i) •
φ ≫
δ X { val := ↑i, isLt := (_ : ↑{ val := ↑i, isLt := (_ : ↑(Fin.castSucc i) < a + 2 + q) } < n + 2) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }) +
((-1) ^ a * (-1) ^ (a + 1)) •
φ ≫
δ X
{ val := a + 1,
isLt := (_ : ↑{ val := a + 1, isLt := (_ : ↑(Fin.last (a + 1)) < a + 2 + q) } < n + 2) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) } +
((Finset.sum Finset.univ fun i =>
((-1) ^ ↑i * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X
{ val := ↑i,
isLt :=
(_ : ↑{ val := ↑i, isLt := (_ : ↑(Fin.castSucc (Fin.castSucc i)) < a + 3 + q) } < n + 3) }) +
((-1) ^ (a + 1) * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X
{ val := a + 1,
isLt :=
(_ : ↑{ val := a + 1, isLt := (_ : ↑(Fin.castSucc (Fin.last (a + 1))) < a + 3 + q) } < n + 3) } +
((-1) ^ (a + 2) * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X
{ val := a + 2,
isLt := (_ : ↑{ val := a + 2, isLt := (_ : ↑(Fin.last (a + 2)) < a + 3 + q) } < n + 3) }) =
-φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (n + 1)) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }
[PROOFSTEP]
apply simplif
[GOAL]
case a
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
simplif : ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
⊢ ((-1) ^ a * (-1) ^ (a + 1)) •
φ ≫
δ X { val := a + 1, isLt := (_ : ↑{ val := a + 1, isLt := (_ : ↑(Fin.last (a + 1)) < a + 2 + q) } < n + 2) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) } =
-φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (n + 1)) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }
[PROOFSTEP]
rw [← pow_add, Odd.neg_one_pow, neg_smul, one_zsmul]
[GOAL]
case a
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
simplif : ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
⊢ Odd (a + (a + 1))
[PROOFSTEP]
exact ⟨a, by linarith⟩
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
simplif : ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
⊢ a + (a + 1) = 2 * a + 1
[PROOFSTEP]
linarith
[GOAL]
case a
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
simplif : ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
⊢ ((-1) ^ (a + 1) * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X
{ val := a + 1,
isLt :=
(_ : ↑{ val := a + 1, isLt := (_ : ↑(Fin.castSucc (Fin.last (a + 1))) < a + 3 + q) } < n + 3) } +
((-1) ^ (a + 2) * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X
{ val := a + 2, isLt := (_ : ↑{ val := a + 2, isLt := (_ : ↑(Fin.last (a + 2)) < a + 3 + q) } < n + 3) } =
0
[PROOFSTEP]
rw [X.δ_comp_σ_self' (Fin.castSucc_mk _ _ _).symm, X.δ_comp_σ_succ' (Fin.succ_mk _ _ _).symm]
[GOAL]
case a
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
simplif : ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
⊢ ((-1) ^ (a + 1) * (-1) ^ (a + 1)) • φ ≫ 𝟙 (X.obj (Opposite.op [n + 1])) +
((-1) ^ (a + 2) * (-1) ^ (a + 1)) • φ ≫ 𝟙 (X.obj (Opposite.op [n + 1])) =
0
[PROOFSTEP]
simp only [comp_id, pow_add _ (a + 1) 1, pow_one, mul_neg, mul_one, neg_mul, neg_smul, add_right_neg]
[GOAL]
case a
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
simplif : ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
⊢ ((Finset.sum Finset.univ fun i =>
((-1) ^ ↑i * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X
{ val := ↑i,
isLt := (_ : ↑{ val := ↑i, isLt := (_ : ↑(Fin.castSucc (Fin.castSucc i)) < a + 3 + q) } < n + 3) }) +
Finset.sum Finset.univ fun i =>
((-1) ^ a * (-1) ^ ↑i) •
φ ≫
δ X { val := ↑i, isLt := (_ : ↑{ val := ↑i, isLt := (_ : ↑(Fin.castSucc i) < a + 2 + q) } < n + 2) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }) =
0
[PROOFSTEP]
rw [← Finset.sum_add_distrib]
[GOAL]
case a
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
simplif : ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
⊢ (Finset.sum Finset.univ fun x =>
((-1) ^ ↑x * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X
{ val := ↑x,
isLt := (_ : ↑{ val := ↑x, isLt := (_ : ↑(Fin.castSucc (Fin.castSucc x)) < a + 3 + q) } < n + 3) } +
((-1) ^ a * (-1) ^ ↑x) •
φ ≫
δ X { val := ↑x, isLt := (_ : ↑{ val := ↑x, isLt := (_ : ↑(Fin.castSucc x) < a + 2 + q) } < n + 2) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }) =
0
[PROOFSTEP]
apply Finset.sum_eq_zero
[GOAL]
case a.h
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
simplif : ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
⊢ ∀ (x : Fin (a + 1)),
x ∈ Finset.univ →
((-1) ^ ↑x * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X
{ val := ↑x,
isLt := (_ : ↑{ val := ↑x, isLt := (_ : ↑(Fin.castSucc (Fin.castSucc x)) < a + 3 + q) } < n + 3) } +
((-1) ^ a * (-1) ^ ↑x) •
φ ≫
δ X { val := ↑x, isLt := (_ : ↑{ val := ↑x, isLt := (_ : ↑(Fin.castSucc x) < a + 2 + q) } < n + 2) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) } =
0
[PROOFSTEP]
rintro ⟨i, hi⟩ _
[GOAL]
case a.h.mk
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
simplif : ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
i : ℕ
hi : i < a + 1
a✝ : { val := i, isLt := hi } ∈ Finset.univ
⊢ ((-1) ^ ↑{ val := i, isLt := hi } * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X
{ val := ↑{ val := i, isLt := hi },
isLt :=
(_ :
↑{ val := ↑{ val := i, isLt := hi },
isLt := (_ : ↑(Fin.castSucc (Fin.castSucc { val := i, isLt := hi })) < a + 3 + q) } <
n + 3) } +
((-1) ^ a * (-1) ^ ↑{ val := i, isLt := hi }) •
φ ≫
δ X
{ val := ↑{ val := i, isLt := hi },
isLt :=
(_ :
↑{ val := ↑{ val := i, isLt := hi },
isLt := (_ : ↑(Fin.castSucc { val := i, isLt := hi }) < a + 2 + q) } <
n + 2) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) } =
0
[PROOFSTEP]
simp only
[GOAL]
case a.h.mk
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
simplif : ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
i : ℕ
hi : i < a + 1
a✝ : { val := i, isLt := hi } ∈ Finset.univ
⊢ ((-1) ^ i * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X
{ val := i,
isLt :=
(_ :
↑{ val := ↑{ val := i, isLt := hi },
isLt := (_ : ↑(Fin.castSucc (Fin.castSucc { val := i, isLt := hi })) < a + 3 + q) } <
n + 3) } +
((-1) ^ a * (-1) ^ i) •
φ ≫
δ X
{ val := i,
isLt :=
(_ :
↑{ val := ↑{ val := i, isLt := hi },
isLt := (_ : ↑(Fin.castSucc { val := i, isLt := hi }) < a + 2 + q) } <
n + 2) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) } =
0
[PROOFSTEP]
have hia : (⟨i, by linarith⟩ : Fin (n + 2)) ≤ Fin.castSucc (⟨a, by linarith⟩ : Fin (n + 1)) :=
by
rw [Fin.le_iff_val_le_val]
dsimp
linarith
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
simplif : ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
i : ℕ
hi : i < a + 1
a✝ : { val := i, isLt := hi } ∈ Finset.univ
⊢ i < n + 2
[PROOFSTEP]
linarith
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
simplif : ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
i : ℕ
hi : i < a + 1
a✝ : { val := i, isLt := hi } ∈ Finset.univ
⊢ a < n + 1
[PROOFSTEP]
linarith
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
simplif : ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
i : ℕ
hi : i < a + 1
a✝ : { val := i, isLt := hi } ∈ Finset.univ
⊢ { val := i, isLt := (_ : i < n + 2) } ≤ Fin.castSucc { val := a, isLt := (_ : a < n + 1) }
[PROOFSTEP]
rw [Fin.le_iff_val_le_val]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
simplif : ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
i : ℕ
hi : i < a + 1
a✝ : { val := i, isLt := hi } ∈ Finset.univ
⊢ ↑{ val := i, isLt := (_ : i < n + 2) } ≤ ↑(Fin.castSucc { val := a, isLt := (_ : a < n + 1) })
[PROOFSTEP]
dsimp
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
simplif : ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
i : ℕ
hi : i < a + 1
a✝ : { val := i, isLt := hi } ∈ Finset.univ
⊢ i ≤ a
[PROOFSTEP]
linarith
[GOAL]
case a.h.mk
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
simplif : ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
i : ℕ
hi : i < a + 1
a✝ : { val := i, isLt := hi } ∈ Finset.univ
hia : { val := i, isLt := (_ : i < n + 2) } ≤ Fin.castSucc { val := a, isLt := (_ : a < n + 1) }
⊢ ((-1) ^ i * (-1) ^ (a + 1)) •
φ ≫
σ X { val := a + 1, isLt := (_ : a + 1 < Nat.succ (n + 1)) } ≫
δ X
{ val := i,
isLt :=
(_ :
↑{ val := ↑{ val := i, isLt := hi },
isLt := (_ : ↑(Fin.castSucc (Fin.castSucc { val := i, isLt := hi })) < a + 3 + q) } <
n + 3) } +
((-1) ^ a * (-1) ^ i) •
φ ≫
δ X
{ val := i,
isLt :=
(_ :
↑{ val := ↑{ val := i, isLt := hi },
isLt := (_ : ↑(Fin.castSucc { val := i, isLt := hi }) < a + 2 + q) } <
n + 2) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) } =
0
[PROOFSTEP]
erw [δ_comp_σ_of_le X hia, add_eq_zero_iff_eq_neg, ← neg_zsmul]
[GOAL]
case a.h.mk
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
simplif : ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
i : ℕ
hi : i < a + 1
a✝ : { val := i, isLt := hi } ∈ Finset.univ
hia : { val := i, isLt := (_ : i < n + 2) } ≤ Fin.castSucc { val := a, isLt := (_ : a < n + 1) }
⊢ ((-1) ^ i * (-1) ^ (a + 1)) •
φ ≫ δ X { val := i, isLt := (_ : i < n + 2) } ≫ σ X { val := a, isLt := (_ : a < n + 1) } =
-((-1) ^ a * (-1) ^ i) •
φ ≫
δ X
{ val := i,
isLt :=
(_ :
↑{ val := ↑{ val := i, isLt := hi },
isLt := (_ : ↑(Fin.castSucc { val := i, isLt := hi }) < a + 2 + q) } <
n + 2) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) }
[PROOFSTEP]
congr 2
[GOAL]
case a.h.mk.e_a
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n a q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hnaq : n = a + q
hnaq_shift : ∀ (d : ℕ), n + d = a + d + q
simplif : ∀ (a b c d e f : Y ⟶ X.obj (Opposite.op [n + 1])), b = f → d + e = 0 → c + a = 0 → a + b + (c + d + e) = f
i : ℕ
hi : i < a + 1
a✝ : { val := i, isLt := hi } ∈ Finset.univ
hia : { val := i, isLt := (_ : i < n + 2) } ≤ Fin.castSucc { val := a, isLt := (_ : a < n + 1) }
⊢ (-1) ^ i * (-1) ^ (a + 1) = -((-1) ^ a * (-1) ^ i)
[PROOFSTEP]
ring
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
⊢ φ ≫ HomologicalComplex.Hom.f (Hσ q) (n + 1) = 0
[PROOFSTEP]
simp only [Hσ, Homotopy.nullHomotopicMap'_f (c_mk (n + 2) (n + 1) rfl) (c_mk (n + 1) n rfl)]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
⊢ φ ≫
(HomologicalComplex.d (AlternatingFaceMapComplex.obj X) (n + 1) n ≫
hσ' q n (n + 1) (_ : ComplexShape.Rel c (n + 1) n) +
hσ' q (n + 1) (n + 2) (_ : ComplexShape.Rel c (n + 2) (n + 1)) ≫
HomologicalComplex.d (AlternatingFaceMapComplex.obj X) (n + 2) (n + 1)) =
0
[PROOFSTEP]
rw [hσ'_eq_zero hqn (c_mk (n + 1) n rfl), comp_zero, zero_add]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
⊢ φ ≫
hσ' q (n + 1) (n + 2) (_ : ComplexShape.Rel c (n + 2) (n + 1)) ≫
HomologicalComplex.d (AlternatingFaceMapComplex.obj X) (n + 2) (n + 1) =
0
[PROOFSTEP]
by_cases hqn' : n + 1 < q
[GOAL]
case pos
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
hqn' : n + 1 < q
⊢ φ ≫
hσ' q (n + 1) (n + 2) (_ : ComplexShape.Rel c (n + 2) (n + 1)) ≫
HomologicalComplex.d (AlternatingFaceMapComplex.obj X) (n + 2) (n + 1) =
0
[PROOFSTEP]
rw [hσ'_eq_zero hqn' (c_mk (n + 2) (n + 1) rfl), zero_comp, comp_zero]
[GOAL]
case neg
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
hqn' : ¬n + 1 < q
⊢ φ ≫
hσ' q (n + 1) (n + 2) (_ : ComplexShape.Rel c (n + 2) (n + 1)) ≫
HomologicalComplex.d (AlternatingFaceMapComplex.obj X) (n + 2) (n + 1) =
0
[PROOFSTEP]
simp only [hσ'_eq (show n + 1 = 0 + q by linarith) (c_mk (n + 2) (n + 1) rfl), pow_zero, Fin.mk_zero, one_zsmul,
eqToHom_refl, comp_id, comp_sum, AlternatingFaceMapComplex.obj_d_eq]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
hqn' : ¬n + 1 < q
⊢ n + 1 = 0 + q
[PROOFSTEP]
linarith
[GOAL]
case neg
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
hqn' : ¬n + 1 < q
⊢ (Finset.sum Finset.univ fun j => φ ≫ σ X 0 ≫ ((-1) ^ ↑j • δ X j)) = 0
[PROOFSTEP]
rw [← Fin.sum_congr' _ (show 2 + (n + 1) = n + 1 + 2 by linarith), Fin.sum_trunc]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
hqn' : ¬n + 1 < q
⊢ 2 + (n + 1) = n + 1 + 2
[PROOFSTEP]
linarith
[GOAL]
case neg
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
hqn' : ¬n + 1 < q
⊢ (Finset.sum Finset.univ fun i =>
φ ≫
σ X 0 ≫
((-1) ^ ↑(↑(Fin.castIso (_ : 2 + (n + 1) = n + 1 + 2)) (Fin.castLE (_ : 2 ≤ 2 + (n + 1)) i)) •
δ X (↑(Fin.castIso (_ : 2 + (n + 1) = n + 1 + 2)) (Fin.castLE (_ : 2 ≤ 2 + (n + 1)) i)))) =
0
[PROOFSTEP]
simp only [Fin.sum_univ_castSucc, Fin.sum_univ_zero, zero_add, Fin.last, Fin.castLE_mk, Fin.castIso_mk, Fin.castSucc_mk]
[GOAL]
case neg
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
hqn' : ¬n + 1 < q
⊢ φ ≫ σ X 0 ≫ ((-1) ^ 0 • δ X { val := 0, isLt := (_ : 0 < n + 1 + 2) }) +
φ ≫ σ X 0 ≫ ((-1) ^ 1 • δ X { val := 1, isLt := (_ : 1 < n + 1 + 2) }) =
0
[PROOFSTEP]
simp only [Fin.mk_zero, Fin.val_zero, pow_zero, one_zsmul, Fin.mk_one, Fin.val_one, pow_one, neg_smul, comp_neg]
[GOAL]
case neg
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
hqn' : ¬n + 1 < q
⊢ φ ≫ σ X 0 ≫ δ X 0 + -φ ≫ σ X 0 ≫ δ X 1 = 0
[PROOFSTEP]
erw [δ_comp_σ_self, δ_comp_σ_succ, add_right_neg]
[GOAL]
case neg.hf
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
hqn' : ¬n + 1 < q
⊢ ∀ (j : Fin (n + 1)),
φ ≫
σ X 0 ≫
((-1) ^ ↑(↑(Fin.castIso (_ : 2 + (n + 1) = n + 1 + 2)) (Fin.natAdd 2 j)) •
δ X (↑(Fin.castIso (_ : 2 + (n + 1) = n + 1 + 2)) (Fin.natAdd 2 j))) =
0
[PROOFSTEP]
intro j
[GOAL]
case neg.hf
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
hqn' : ¬n + 1 < q
j : Fin (n + 1)
⊢ φ ≫
σ X 0 ≫
((-1) ^ ↑(↑(Fin.castIso (_ : 2 + (n + 1) = n + 1 + 2)) (Fin.natAdd 2 j)) •
δ X (↑(Fin.castIso (_ : 2 + (n + 1) = n + 1 + 2)) (Fin.natAdd 2 j))) =
0
[PROOFSTEP]
dsimp [Fin.castIso, Fin.castLE, Fin.castLT]
[GOAL]
case neg.hf
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
hqn' : ¬n + 1 < q
j : Fin (n + 1)
⊢ φ ≫ σ X 0 ≫ ((-1) ^ (2 + ↑j) • δ X { val := 2 + ↑j, isLt := (_ : ↑(Fin.natAdd 2 j) < n + 1 + 2) }) = 0
[PROOFSTEP]
rw [comp_zsmul, comp_zsmul, δ_comp_σ_of_gt', v.comp_δ_eq_zero_assoc, zero_comp, zsmul_zero]
[GOAL]
case neg.hf.H
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
hqn' : ¬n + 1 < q
j : Fin (n + 1)
⊢ Fin.succ 0 < { val := 2 + ↑j, isLt := (_ : ↑(Fin.natAdd 2 j) < n + 1 + 2) }
[PROOFSTEP]
simp only [Fin.lt_iff_val_lt_val]
[GOAL]
case neg.hf.H
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
hqn' : ¬n + 1 < q
j : Fin (n + 1)
⊢ ↑(Fin.succ 0) < 2 + ↑j
[PROOFSTEP]
dsimp [Fin.succ]
[GOAL]
case neg.hf.H
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
hqn' : ¬n + 1 < q
j : Fin (n + 1)
⊢ 0 + 1 < 2 + ↑j
[PROOFSTEP]
linarith
[GOAL]
case neg.hf.hj₁
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
hqn' : ¬n + 1 < q
j : Fin (n + 1)
⊢ Fin.pred { val := 2 + ↑j, isLt := (_ : ↑(Fin.natAdd 2 j) < n + 1 + 2) }
(_ : { val := 2 + ↑j, isLt := (_ : ↑(Fin.natAdd 2 j) < n + 1 + 2) } = 0 → False) ≠
0
[PROOFSTEP]
intro h
[GOAL]
case neg.hf.hj₁
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
hqn' : ¬n + 1 < q
j : Fin (n + 1)
h :
Fin.pred { val := 2 + ↑j, isLt := (_ : ↑(Fin.natAdd 2 j) < n + 1 + 2) }
(_ : { val := 2 + ↑j, isLt := (_ : ↑(Fin.natAdd 2 j) < n + 1 + 2) } = 0 → False) =
0
⊢ False
[PROOFSTEP]
simp only [Fin.pred, Fin.subNat, Fin.ext_iff, Nat.succ_add_sub_one, Fin.val_zero, add_eq_zero, false_and] at h
[GOAL]
case neg.hf.hj₂
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
hqn' : ¬n + 1 < q
j : Fin (n + 1)
⊢ n + 2 ≤
↑(Fin.pred { val := 2 + ↑j, isLt := (_ : ↑(Fin.natAdd 2 j) < n + 1 + 2) }
(_ : { val := 2 + ↑j, isLt := (_ : ↑(Fin.natAdd 2 j) < n + 1 + 2) } = 0 → False)) +
q
[PROOFSTEP]
simp only [Fin.pred, Fin.subNat, Nat.pred_eq_sub_one, Nat.succ_add_sub_one]
[GOAL]
case neg.hf.hj₂
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
hqn : n < q
hqn' : ¬n + 1 < q
j : Fin (n + 1)
⊢ n + 2 ≤ 1 + ↑j + q
[PROOFSTEP]
linarith
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
⊢ HigherFacesVanish (q + 1) (φ ≫ HomologicalComplex.Hom.f (𝟙 (AlternatingFaceMapComplex.obj X) + Hσ q) (n + 1))
[PROOFSTEP]
intro j hj₁
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
j : Fin (n + 1)
hj₁ : n + 1 ≤ ↑j + (q + 1)
⊢ (φ ≫ HomologicalComplex.Hom.f (𝟙 (AlternatingFaceMapComplex.obj X) + Hσ q) (n + 1)) ≫ δ X (Fin.succ j) = 0
[PROOFSTEP]
dsimp
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
j : Fin (n + 1)
hj₁ : n + 1 ≤ ↑j + (q + 1)
⊢ (φ ≫ (𝟙 (X.obj (Opposite.op [n + 1])) + HomologicalComplex.Hom.f (Hσ q) (n + 1))) ≫ δ X (Fin.succ j) = 0
[PROOFSTEP]
simp only [comp_add, add_comp, comp_id]
-- when n < q, the result follows immediately from the assumption
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
j : Fin (n + 1)
hj₁ : n + 1 ≤ ↑j + (q + 1)
⊢ φ ≫ δ X (Fin.succ j) + (φ ≫ HomologicalComplex.Hom.f (Hσ q) (n + 1)) ≫ δ X (Fin.succ j) = 0
[PROOFSTEP]
by_cases hqn : n < q
[GOAL]
case pos
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
j : Fin (n + 1)
hj₁ : n + 1 ≤ ↑j + (q + 1)
hqn : n < q
⊢ φ ≫ δ X (Fin.succ j) + (φ ≫ HomologicalComplex.Hom.f (Hσ q) (n + 1)) ≫ δ X (Fin.succ j) = 0
[PROOFSTEP]
rw [v.comp_Hσ_eq_zero hqn, zero_comp, add_zero, v j (by linarith)]
-- we now assume that n≥q, and write n=a+q
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
j : Fin (n + 1)
hj₁ : n + 1 ≤ ↑j + (q + 1)
hqn : n < q
⊢ n + 1 ≤ ↑j + q
[PROOFSTEP]
linarith
[GOAL]
case neg
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
j : Fin (n + 1)
hj₁ : n + 1 ≤ ↑j + (q + 1)
hqn : ¬n < q
⊢ φ ≫ δ X (Fin.succ j) + (φ ≫ HomologicalComplex.Hom.f (Hσ q) (n + 1)) ≫ δ X (Fin.succ j) = 0
[PROOFSTEP]
cases' Nat.le.dest (not_lt.mp hqn) with a ha
[GOAL]
case neg.intro
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
j : Fin (n + 1)
hj₁ : n + 1 ≤ ↑j + (q + 1)
hqn : ¬n < q
a : ℕ
ha : q + a = n
⊢ φ ≫ δ X (Fin.succ j) + (φ ≫ HomologicalComplex.Hom.f (Hσ q) (n + 1)) ≫ δ X (Fin.succ j) = 0
[PROOFSTEP]
rw [v.comp_Hσ_eq (show n = a + q by linarith), neg_comp, add_neg_eq_zero, assoc, assoc]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
j : Fin (n + 1)
hj₁ : n + 1 ≤ ↑j + (q + 1)
hqn : ¬n < q
a : ℕ
ha : q + a = n
⊢ n = a + q
[PROOFSTEP]
linarith
[GOAL]
case neg.intro
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
n q : ℕ
φ : Y ⟶ X.obj (Opposite.op [n + 1])
v : HigherFacesVanish q φ
j : Fin (n + 1)
hj₁ : n + 1 ≤ ↑j + (q + 1)
hqn : ¬n < q
a : ℕ
ha : q + a = n
⊢ φ ≫ δ X (Fin.succ j) =
φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (n + 1)) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ n) } ≫ δ X (Fin.succ j)
[PROOFSTEP]
cases' n with m hm
[GOAL]
case neg.intro.zero
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.zero + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.zero + 1)
hj₁ : Nat.zero + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.zero < q
ha : q + a = Nat.zero
⊢ φ ≫ δ X (Fin.succ j) =
φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.zero + 1)) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ Nat.zero) } ≫ δ X (Fin.succ j)
[PROOFSTEP]
simp only [Nat.eq_zero_of_add_eq_zero_left ha, Fin.eq_zero j, Fin.mk_zero, Fin.mk_one, δ_comp_σ_succ, comp_id]
[GOAL]
case neg.intro.zero
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.zero + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.zero + 1)
hj₁ : Nat.zero + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.zero < q
ha : q + a = Nat.zero
⊢ φ ≫ δ X (Fin.succ 0) = φ ≫ δ X { val := 0 + 1, isLt := (_ : 0 + 1 < Nat.zero + 2) }
[PROOFSTEP]
rfl
-- in the other case, we need to write n as m+1
-- then, we first consider the particular case j = a
[GOAL]
case neg.intro.succ
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
⊢ φ ≫ δ X (Fin.succ j) =
φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) } ≫ δ X (Fin.succ j)
[PROOFSTEP]
by_cases hj₂ : a = (j : ℕ)
[GOAL]
case pos
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : a = ↑j
⊢ φ ≫ δ X (Fin.succ j) =
φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) } ≫ δ X (Fin.succ j)
[PROOFSTEP]
simp only [hj₂, Fin.eta, δ_comp_σ_succ, comp_id]
[GOAL]
case pos
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : a = ↑j
⊢ φ ≫ δ X (Fin.succ j) = φ ≫ δ X { val := ↑j + 1, isLt := (_ : ↑j + 1 < Nat.succ m + 2) }
[PROOFSTEP]
rfl
-- now, we assume j ≠ a (i.e. a < j)
[GOAL]
case neg
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
⊢ φ ≫ δ X (Fin.succ j) =
φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) } ≫ δ X (Fin.succ j)
[PROOFSTEP]
have haj : a < j := (Ne.le_iff_lt hj₂).mp (by linarith)
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
⊢ a ≤ ↑j
[PROOFSTEP]
linarith
[GOAL]
case neg
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
⊢ φ ≫ δ X (Fin.succ j) =
φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) } ≫ δ X (Fin.succ j)
[PROOFSTEP]
have hj₃ := j.is_lt
[GOAL]
case neg
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
⊢ φ ≫ δ X (Fin.succ j) =
φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) } ≫ δ X (Fin.succ j)
[PROOFSTEP]
have ham : a ≤ m := by
by_contra h
rw [not_le, ← Nat.succ_le_iff] at h
linarith
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
⊢ a ≤ m
[PROOFSTEP]
by_contra h
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
h : ¬a ≤ m
⊢ False
[PROOFSTEP]
rw [not_le, ← Nat.succ_le_iff] at h
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
h : Nat.succ m ≤ a
⊢ False
[PROOFSTEP]
linarith
[GOAL]
case neg
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
⊢ φ ≫ δ X (Fin.succ j) =
φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) } ≫
σ X { val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) } ≫ δ X (Fin.succ j)
[PROOFSTEP]
rw [X.δ_comp_σ_of_gt', j.pred_succ]
[GOAL]
case neg
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
⊢ φ ≫ δ X (Fin.succ j) =
φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) } ≫
δ X j ≫
σ X
(Fin.castLT { val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) }
(_ : ↑{ val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) } < m + 1))
case neg
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
⊢ Fin.succ { val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) } < Fin.succ j
case neg
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
⊢ Fin.succ { val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) } < Fin.succ j
[PROOFSTEP]
swap
[GOAL]
case neg
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
⊢ Fin.succ { val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) } < Fin.succ j
[PROOFSTEP]
rw [Fin.lt_iff_val_lt_val]
[GOAL]
case neg
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
⊢ ↑(Fin.succ { val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) }) < ↑(Fin.succ j)
[PROOFSTEP]
simpa only [Fin.val_mk, Fin.val_succ, add_lt_add_iff_right] using haj
[GOAL]
case neg
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
⊢ φ ≫ δ X (Fin.succ j) =
φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) } ≫
δ X j ≫
σ X
(Fin.castLT { val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) }
(_ : ↑{ val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) } < m + 1))
[PROOFSTEP]
obtain _ | ham'' := ham.lt_or_eq
[GOAL]
case neg.inl
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
h✝ : a < m
⊢ φ ≫ δ X (Fin.succ j) =
φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) } ≫
δ X j ≫
σ X
(Fin.castLT { val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) }
(_ : ↑{ val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) } < m + 1))
[PROOFSTEP]
rw [← X.δ_comp_δ''_assoc]
[GOAL]
case neg.inl
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
h✝ : a < m
⊢ φ ≫ δ X (Fin.succ j) =
φ ≫
δ X (Fin.succ j) ≫
δ X
(Fin.castLT { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) }
(_ : ↑{ val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) } < m + 2)) ≫
σ X
(Fin.castLT { val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) }
(_ : ↑{ val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) } < m + 1))
case neg.inl.H
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
h✝ : a < m
⊢ { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) } ≤ Fin.castSucc j
[PROOFSTEP]
swap
[GOAL]
case neg.inl.H
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
h✝ : a < m
⊢ { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) } ≤ Fin.castSucc j
[PROOFSTEP]
rw [Fin.le_iff_val_le_val]
[GOAL]
case neg.inl.H
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
h✝ : a < m
⊢ ↑{ val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) } ≤ ↑(Fin.castSucc j)
[PROOFSTEP]
dsimp
[GOAL]
case neg.inl.H
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
h✝ : a < m
⊢ a + 1 ≤ ↑j
[PROOFSTEP]
linarith
[GOAL]
case neg.inl
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
h✝ : a < m
⊢ φ ≫ δ X (Fin.succ j) =
φ ≫
δ X (Fin.succ j) ≫
δ X
(Fin.castLT { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) }
(_ : ↑{ val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) } < m + 2)) ≫
σ X
(Fin.castLT { val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) }
(_ : ↑{ val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) } < m + 1))
[PROOFSTEP]
simp only [← assoc, v j (by linarith), zero_comp]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
h✝ : a < m
⊢ Nat.succ m + 1 ≤ ↑j + q
[PROOFSTEP]
linarith
[GOAL]
case neg.inr
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
ham'' : a = m
⊢ φ ≫ δ X (Fin.succ j) =
φ ≫
δ X { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) } ≫
δ X j ≫
σ X
(Fin.castLT { val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) }
(_ : ↑{ val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) } < m + 1))
[PROOFSTEP]
rw [X.δ_comp_δ_self'_assoc]
[GOAL]
case neg.inr
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
ham'' : a = m
⊢ φ ≫ δ X (Fin.succ j) =
φ ≫
δ X (Fin.succ j) ≫
δ X j ≫
σ X
(Fin.castLT { val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) }
(_ : ↑{ val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) } < m + 1))
case neg.inr.H
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
ham'' : a = m
⊢ { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) } = Fin.castSucc j
[PROOFSTEP]
swap
[GOAL]
case neg.inr.H
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
ham'' : a = m
⊢ { val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) } = Fin.castSucc j
[PROOFSTEP]
ext
[GOAL]
case neg.inr.H.h
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
ham'' : a = m
⊢ ↑{ val := a + 1, isLt := (_ : Nat.succ a < Nat.succ (Nat.succ m + 1)) } = ↑(Fin.castSucc j)
[PROOFSTEP]
dsimp
[GOAL]
case neg.inr.H.h
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
ham'' : a = m
⊢ a + 1 = ↑j
[PROOFSTEP]
linarith
[GOAL]
case neg.inr
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
ham'' : a = m
⊢ φ ≫ δ X (Fin.succ j) =
φ ≫
δ X (Fin.succ j) ≫
δ X j ≫
σ X
(Fin.castLT { val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) }
(_ : ↑{ val := a, isLt := (_ : a < Nat.succ (Nat.succ m)) } < m + 1))
[PROOFSTEP]
simp only [← assoc, v j (by linarith), zero_comp]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_2, u_1} C
inst✝ : Preadditive C
X : SimplicialObject C
Y : C
q a m : ℕ
φ : Y ⟶ X.obj (Opposite.op [Nat.succ m + 1])
v : HigherFacesVanish q φ
j : Fin (Nat.succ m + 1)
hj₁ : Nat.succ m + 1 ≤ ↑j + (q + 1)
hqn : ¬Nat.succ m < q
ha : q + a = Nat.succ m
hj₂ : ¬a = ↑j
haj : a < ↑j
hj₃ : ↑j < Nat.succ m + 1
ham : a ≤ m
ham'' : a = m
⊢ Nat.succ m + 1 ≤ ↑j + q
[PROOFSTEP]
linarith
|
function predict_new_rbf_deriv_deriv(a_all,a_layer1,x_new,obs,neurons,n_per_part,inds_all,x_old,vars,cc,var_seq)
layer1=zeros(obs,neurons)
for i=1:neurons
x1=copy(x_old[inds_all[n_per_part[i]+1:n_per_part[i+1]],:])
obs1=size(x1,1)
phi1 = calc_phi_deriv_deriv(x1,x_new,obs1,obs,cc,vars,var_seq)
# if sum(abs.(a_all[i,1:obs1]))>0
# layer1[:,i].=phi1*a_all[i,1:obs1]
# end
layer1[:,i].=phi1*a_all[i]
end
predl1=[layer1 ones(obs)]*a_layer1
return predl1
end |
{-
Homotopy colimits of graphs
-}
{-# OPTIONS --cubical --safe #-}
module Cubical.HITs.Colimit.Base where
open import Cubical.Core.Glue
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.Function
open import Cubical.Foundations.HLevels
open import Cubical.Foundations.Equiv
open import Cubical.Foundations.Isomorphism
open import Cubical.Data.Graph
-- Cones under a diagram
record Cocone ℓ {ℓd ℓv ℓe} {I : Graph ℓv ℓe} (F : Diag ℓd I) (X : Type ℓ)
: Type (ℓ-suc (ℓ-max ℓ (ℓ-max (ℓ-max ℓv ℓe) (ℓ-suc ℓd)))) where
field
leg : ∀ (j : Obj I) → F $ j → X
com : ∀ {j k} (f : Hom I j k) → leg k ∘ F <$> f ≡ leg j
postcomp : ∀ {ℓ'} {Y : Type ℓ'} → (X → Y) → Cocone ℓ' F Y
leg (postcomp h) j = h ∘ leg j
com (postcomp h) f = cong (h ∘_) (com f)
open Cocone public
-- Σ (Type ℓ) (Cocone ℓ F) forms a category:
module _ {ℓd ℓv ℓe} {I : Graph ℓv ℓe} {F : Diag ℓd I} where
private
-- the "lower star" functor
_* : ∀ {ℓ ℓ'} {X : Type ℓ} {Y : Type ℓ'} → (X → Y) → Cocone _ F X → Cocone _ F Y
(h *) C = postcomp C h
CoconeMor : ∀ {ℓ ℓ'} → Σ (Type ℓ) (Cocone ℓ F) → Σ (Type ℓ') (Cocone ℓ' F) → Type _
CoconeMor (X , C) (Y , D) = Σ[ h ∈ (X → Y) ] (h *) C ≡ D
idCoconeMor : ∀ {ℓ} (Cp : Σ (Type ℓ) (Cocone ℓ F)) → CoconeMor Cp Cp
idCoconeMor Cp = (λ x → x) , refl
compCoconeMor : ∀ {ℓ ℓ' ℓ''} {C : Σ (Type ℓ) (Cocone ℓ F)} {D : Σ (Type ℓ') (Cocone ℓ' F)}
{E : Σ (Type ℓ'') (Cocone ℓ'' F)}
→ CoconeMor D E → CoconeMor C D → CoconeMor C E
compCoconeMor (g , q) (f , p) = g ∘ f , (cong (g *) p) ∙ q
-- Universal cocones are initial objects in the category Σ (Type ℓ) (Cocone ℓ F)
module _ {ℓ ℓd ℓv ℓe} {I : Graph ℓv ℓe} {F : Diag ℓd I} {X : Type ℓ} where
isUniversalAt : ∀ ℓq → Cocone ℓ F X → Type (ℓ-max ℓ (ℓ-suc (ℓ-max ℓq (ℓ-max (ℓ-max ℓv ℓe) (ℓ-suc ℓd)))))
isUniversalAt ℓq C = ∀ (Y : Type ℓq) → isEquiv {A = (X → Y)} {B = Cocone ℓq F Y} (postcomp C)
-- (unfolding isEquiv, this ^ is equivalent to what one might expect:)
-- ∀ (Y : Type ℓ) (D : Cocone ℓ F Y) → isContr (Σ[ h ∈ (X → Y) ] (h *) C ≡ D)
-- (≡ isContr (CoconeMor (X , C) (Y , D)))
isPropIsUniversalAt : ∀ ℓq (C : Cocone ℓ F X) → isProp (isUniversalAt ℓq C)
isPropIsUniversalAt ℓq C = propPi (λ Y → isPropIsEquiv (postcomp C))
isUniversal : Cocone ℓ F X → Typeω
isUniversal C = ∀ ℓq → isUniversalAt ℓq C
-- Colimits are universal cocones
record isColimit {ℓ ℓd ℓv ℓe} {I : Graph ℓv ℓe} (F : Diag ℓd I) (X : Type ℓ) : Typeω where
field
cone : Cocone ℓ F X
univ : isUniversal cone
open isColimit public
module _ {ℓ ℓ' ℓd ℓv ℓe} {I : Graph ℓv ℓe} {F : Diag ℓd I} {X : Type ℓ} {Y : Type ℓ'} where
postcomp⁻¹ : isColimit F X → Cocone ℓ' F Y → (X → Y)
postcomp⁻¹ cl = invEq (_ , univ cl _ Y)
postcomp⁻¹-inv : (cl : isColimit F X) (D : Cocone ℓ' F Y) → (postcomp (cone cl) (postcomp⁻¹ cl D)) ≡ D
postcomp⁻¹-inv cl D = retEq (_ , univ cl _ Y) D
postcomp⁻¹-mor : (cl : isColimit F X) (D : Cocone ℓ' F Y) → CoconeMor (X , cone cl) (Y , D)
postcomp⁻¹-mor cl D = (postcomp⁻¹ cl D) , (postcomp⁻¹-inv cl D)
-- Colimits are unique
module _ {ℓ ℓ' ℓd ℓv ℓe} {I : Graph ℓv ℓe} {F : Diag ℓd I} {X : Type ℓ} {Y : Type ℓ'} where
uniqColimit : isColimit F X → isColimit F Y → X ≃ Y
uniqColimit cl cl'
= isoToEquiv (iso (fst fwd) (fst bwd)
(λ x i → fst (isContr→isProp (equiv-proof (univ cl' ℓ' Y) (cone cl'))
(compCoconeMor fwd bwd)
(idCoconeMor (Y , cone cl')) i) x)
(λ x i → fst (isContr→isProp (equiv-proof (univ cl ℓ X) (cone cl))
(compCoconeMor bwd fwd)
(idCoconeMor (X , cone cl)) i) x))
where fwd : CoconeMor (X , cone cl ) (Y , cone cl')
bwd : CoconeMor (Y , cone cl') (X , cone cl )
fwd = postcomp⁻¹-mor cl (cone cl')
bwd = postcomp⁻¹-mor cl' (cone cl)
-- Colimits always exist
data colim {ℓd ℓe ℓv} {I : Graph ℓv ℓe} (F : Diag ℓd I) : Type (ℓ-suc (ℓ-max (ℓ-max ℓv ℓe) (ℓ-suc ℓd))) where
colim-leg : ∀ (j : Obj I) → F $ j → colim F
colim-com : ∀ {j k} (f : Hom I j k) → colim-leg k ∘ F <$> f ≡ colim-leg j
module _ {ℓd ℓv ℓe} {I : Graph ℓv ℓe} {F : Diag ℓd I} where
colimCone : Cocone _ F (colim F)
leg colimCone = colim-leg
com colimCone = colim-com
colim-rec : ∀ {ℓ} {X : Type ℓ} → Cocone ℓ F X → (colim F → X)
colim-rec C (colim-leg j A) = leg C j A
colim-rec C (colim-com f i A) = com C f i A
colimIsColimit : isColimit F (colim F)
cone colimIsColimit = colimCone
univ colimIsColimit ℓq Y
= isoToIsEquiv record { fun = postcomp colimCone
; inv = colim-rec
; rightInv = λ C → refl
; leftInv = λ h → funExt (eq h) }
where eq : ∀ h (x : colim _) → colim-rec (postcomp colimCone h) x ≡ h x
eq h (colim-leg j A) = refl
eq h (colim-com f i A) = refl
|
Load LFindLoad.
From lfind Require Import LFind.
From QuickChick Require Import QuickChick.
From adtind Require Import goal33.
Derive Show for natural.
Derive Arbitrary for natural.
Instance Dec_Eq_natural : Dec_Eq natural.
Proof. dec_eq. Qed.
Lemma conj15eqsynthconj1_hyp: forall (lv0 : natural) (lv1 : natural) (lv2 : natural), (@eq natural (plus (mult lv0 lv2) lv0) (mult lv0 lv1)) -> (@eq natural (plus (mult lv0 lv1) lv2) (plus lv2 (mult lv0 (Succ lv2)))).
Admitted.
QuickChick conj15eqsynthconj1_hyp.
|
A function $f$ converges to $L$ at $a$ if and only if for every $\epsilon > 0$, there exists $\delta > 0$ such that for all $x$, if $x \neq a$ and $|x - a| < \delta$, then $|f(x) - L| < \epsilon$. |
# "Gillespie Algorithm"
> "In this blog post we will look at the grand-daddy of stochastic simulation methods: the Gillespie Algorithm (otherwise known as the stochastic simulation algorith SSA). If you have ever done any form of stochastic simulation you will owe a great deal of gratitude to the Gillespie algorithm which likely inspired the techniques you used."
- toc: true
- author: Lewis Cole (2020)
- branch: master
- badges: false
- comments: false
- categories: [Gillespie-Algorithm, Stochastic-Simulation-Algorithm, Computational-Statistics, Probability, Tau-Leaping, Master-Equation, Adaptive-Tau-Leaping]
- hide: false
- search_exclude: false
- image: https://github.com/lewiscoleblog/blog/raw/master/images/Gillespie/Gillespie.jpg
```python
#hide
import warnings
warnings.filterwarnings('ignore')
```
The Gillespie algorithm is one of the most historically important stochastic simulation algorithms ever created. At its heart the intuition behind it is very simple and it is re-assuring that it "works" - this is not always the case with stochastic simulation where the "obvious" idea can sometimes have unintended debilitating consequences.
The algorithm was first presented by Doob (and is sometimes refered to as the Doob-Gillespie algorithm) in the mid 1940s. It was implemented by Kendall in the 1950s. However it wasn't until the mid 1970s that Gillespie re-derived the method by studying physical systems that it became widely used. In publishing the method he essentially created the entire fields of systems biology and computational chemistry by opening the door to what is possible through stochastic simulation.
## Background
In this blog we will consider applying the Gillespie method to the area of chemical reaction kinetics, this is the application Gillespie originally had in mind. The concepts described will carry over to other applications.
Imagine we wish to model a particular chemical reaction. We could use a determistic approach to model the reaction, this will require setting up a family of coupled differential equations. In doing so we will essentially "ignore" any microscopic behaviour and look at the reaction system at a "high level". This can mean we miss out on a lot of the "detail" of the reaction which may be of interest to us. Further in some cases this approach may not even be applicable, for example to set up a differential equation we assume that we have large quantities of reactants that are perfectly mixed, this allows us to "average over" all reactants to create nice smooth dynamics. This may not reflect reality if there are only relatively few reactants in a system. An alternate approach is to use a stochastic "discrete event" model - this is where we model individual reactions seperately as discrete events occuring in time. This matches our physical intuition of how reactions occur: we wait until the reactants "bump" into each other in the right way before a reaction occurs. One way to summarise this mathematically is through the use of a "master equation".
In the sciences a master equation represents the time evolution properties of a multi-state jumping system, by which we mean a system that "jumps" between distinct states through time (in contrast a "diffusion system" varies gradually). The system in question being stochastic in nature we are concerned with observing how the state distribution varies over time, for example: with some initial condition what is the probability of finding the system in a particular state within the next X seconds/minutes/years? Of course the time units depend on the nature of the system (e.g. if we construct a master equation for predator/prey dynamics we are unlikely to be interested in microsecond timescales, however if looking at a chemical reaction we are unlikely to find a timescale in days useful.) If we want to display the master equation mathematically we use a transition rate matrix $A(t)$ - this can evolve in time or it can be static.
We can then express the master equation in the form:
$$ \frac{d\mathbf{P}_t}{dt} = A(t) \mathbf{P}_t $$
Where vector $\mathbf{P}_t$ represents the probability distribution of states at time t - obscured by notation is an initial condition. Those from a mathematical or probabilistic background will recognise this as a Kolmogorov backwards equation for jump processes. If we expand the notation a little such that $P_{ij}(s,t)$ represents the probability of the system being in state $i$ at time $s$ and state $j$ at time $t$ then we can note that the transition rate matrix satisfies:
\begin{align}
A_{ij}(t) &= \left[ \frac{\partial P_{ij}(t,u)}{du} \right]_{u=t} \\
A_{ij}(t) & \geq 0 \quad \quad \quad \quad \forall i \neq j \\
\sum_j A_{ij}(t) &= 0 \quad \quad \quad \quad \forall i
\end{align}
Further we can note that if there is a distribution $\pi$ such that:
$$ \pi_j A_{ij}(t) = \pi_i A_{ij}(t) $$
For all pairs of states $(i,j)$ then the process satisfies detailed balance and the process is a reversible Markov process.
## Gillespie Algorithm
The Gillespie algorithm is allows us to model the exact dynamics described by the master equation. In some (simple) cases we can solve the master equation analytically, but for complicated examples (e.g. say we have 50 different types of reaction occuring) this may not be feasible and so the Gillespie algorithm (or some sort of simulation method) is necessary. In pseudo code we can write down the Gillespie algorithm as:
1. **Initialization** - initialize the system, in the context of reaction kinetics this amounts to the setting up initial chemical concentrations
2. **Monte-Carlo** -
1. Randomly simulate the time to the next event
2. Given an event has occurred randomly select which event has occured
3. **Update** - based on 2. move the model time forward to the event time and update the state of the system
4. **Repeat** - Iterate through steps 2. and 3. until some stopping criteria is met
This essentially follows our intuition and there is no "technical trickery" such as fancy sampling methods, acceptance/rejection, etc. It is just a clean simple method - which is nice! Since we model by event as opposed to discretizing time steps this is an "exact" simulation method - meaning any trajectory simulated will follow the master equation dynamics exactly. However due to the random nature of any trajectory we will have to loop over these steps multiple times to find "typical" reaction paths (or whatever property we are trying to study).
## An Example
To illustrate the algorithm in action we will take a simple reaction. We will have following forward reaction
$$A + B \to AB$$
Where two monomers $A$ and $B$ react to form a dimer $AB$. The corresponding reverse reaction being:
$$AB \to A + B$$
We will denote the rate of the forward reaction to be $r_f$ and the rate of the backward reaction to be $r_f$. If we let the number of molecules present be denoted by: $N_A, N_B$ and $N_{AB}$ then the rate of any reaction occurring is:
$$R = r_f N_A N_B + r_b N_{AB}$$
Also given a reaction has occured the probability of the forward reaction having taken place is:
$$\mathbb{P}(A + B \to AB) = \frac{r_f N_A N_B}{R}$$
For a model such as this we typically want to remove any "path dependence" - the arrival of the next reaction event is independent of reactions that have occurred previously (given the concentration of reactants). To satisfy this constraint typically reactions events are taken to follow a Poisson process. Under this assumption the number of reactions occuring within a time period $\Delta T$ follows a $Poisson(R\Delta T)$ distribution. Moreover the time between reactions is then follows an exponential distribution. Thus if we sample $u \sim U[0,1]$ then we take the time until next reaction to be $\tau = \frac{1}{R}ln\left( \frac{1}{u} \right)$. (Note: here I have used that $U$ and $(1-U)$ have the same distribution).
A basic implementation of this can be seen below:
```python
# An implenetation of the Gillespie algorithm
# applied to a pair of reactions:
# A + B -> AB
# AB -> A + B
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Fix random seed for repeatability
np.random.seed(123)
###### Fix model parameters ######
N_A0 = 25 # Initial number of A molecules
N_B0 = 35 # Initial number of B molecules
N_AB0 = 5 # Initial number of AB molecules
rf = 2 # Forward reaction rate
rb = 1 # Backwards reaction rate
steps = 25 # Number of reactions per trajectory
cycles = 100 # Number of trajectories iterated over
# Set up holder arrays
T = np.zeros((cycles, steps+1))
N_A = np.zeros((cycles, steps+1))
N_B = np.zeros((cycles, steps+1))
N_AB = np.zeros((cycles, steps+1))
# Store initial conditions
N_A[:,0] = N_A0
N_B[:,0] = N_B0
N_AB[:,0] = N_AB0
###### Main Code Loop ######
for i in range(cycles):
for j in range(steps):
# Calculate updated overall reaction rate
R = rf * N_A[i,j] * N_B[i,j] + rb * N_AB[i,j]
# Calculate time to next reaction
u1 = np.random.random()
tau = 1/R * np.log(1/u1)
# Store reaction time
T[i, j+1] = T[i,j] + tau
# Select which reaction to occur
Rf = rf * N_A[i,j] * N_B[i,j] / R
u2 = np.random.random()
# Update populations
if u2 < Rf:
N_A[i,j+1] = N_A[i,j] - 1
N_B[i,j+1] = N_B[i,j] - 1
N_AB[i,j+1] = N_AB[i,j] + 1
else:
N_A[i,j+1] = N_A[i,j] + 1
N_B[i,j+1] = N_B[i,j] + 1
N_AB[i,j+1] = N_AB[i,j] - 1
# Calculate an average trajectory plot
ave_steps = 100
T_max = T.max()
# Set up average arrays
T_ave = np.linspace(0,T_max,ave_steps+1)
N_A_ave = np.zeros(ave_steps+1)
N_B_ave = np.zeros(ave_steps+1)
N_AB_ave = np.zeros(ave_steps+1)
N_A_ave[0] = N_A0
N_B_ave[0] = N_B0
N_AB_ave[0] = N_AB0
# Pass over average array entries
for i in range(1, ave_steps+1):
tmax = T_ave[i]
A_sum = 0
B_sum = 0
AB_sum = 0
t_count = 0
# Pass over each trajectory and step therein
for j in range(cycles):
for k in range(steps):
if T[j,k] <= tmax and T[j,k+1] > tmax:
t_count += 1
A_sum += N_A[j,k]
B_sum += N_B[j,k]
AB_sum += N_AB[j,k]
# Caclulate average - taking care if no samples observed
if t_count == 0:
N_A_ave[i] = N_A_ave[i-1]
N_B_ave[i] = N_B_ave[i-1]
N_AB_ave[i] = N_AB_ave[i-1]
else:
N_A_ave[i] = A_sum / t_count
N_B_ave[i] = B_sum / t_count
N_AB_ave[i] = AB_sum / t_count
###### Plot Trajectories ######
fig, axs = plt.subplots(3, 1, figsize=(10,20))
# Plot average trajectories
axs[0].plot(T_ave, N_A_ave, marker='', color='red', linewidth=1.9, alpha=0.9)
axs[0].set_title('Number A Molecules')
axs[0].set_ylim((0,35))
axs[0].set_xlim((0,0.125))
axs[1].plot(T_ave, N_B_ave, marker='', color='red', linewidth=1.9, alpha=0.9)
axs[1].set_title('Number B Molecules')
axs[1].set_ylim((0,35))
axs[1].set_xlim((0,0.125))
axs[2].plot(T_ave, N_AB_ave, marker='', color='red', linewidth=1.9, alpha=0.9)
axs[2].set_title('Number AB Molecules')
axs[2].set_xlabel("Time")
axs[2].set_ylim((0,35))
axs[2].set_xlim((0,0.125))
# Plot each simulated trajectory
for i in range(cycles):
axs[0].plot(T[i,:], N_A[i,:], marker='', color='grey', linewidth=0.6, alpha=0.3)
axs[1].plot(T[i,:], N_B[i,:], marker='', color='grey', linewidth=0.6, alpha=0.3)
axs[2].plot(T[i,:], N_AB[i,:], marker='', color='grey', linewidth=0.6, alpha=0.3)
plt.show()
```
In these plots we can see the various trajectories along with their average. If we increase the number of molecules and the number of trajectories we can get a "smoother" plot. Since we have the full evolution of the system we can also look at some other statistics, for example let's suppose we are interested in the distribution in the number of molecules of each type at time 0.5. We can also plot this using our samples:
```python
time = 0.025
N_A_time = np.zeros(cycles)
N_B_time = np.zeros(cycles)
N_AB_time = np.zeros(cycles)
for i in range(cycles):
for j in range(1, steps):
if T[i,j] => time and T[i,j-1] < time:
N_A_time[i] = N_A[i,j]
N_B_time[i] = N_B[i,j]
N_AB_time[i] = N_AB[i,j]
# If trajectory doesn't span far enough take latest observation
if T[i, steps] < time:
N_A_time[i] = N_A[i, steps]
N_B_time[i] = N_B[i, steps]
N_AB_time[i] = N_AB[i, steps]
plt.hist(N_A_time, density=True, bins=np.arange(35), label="A", color='lightgrey')
plt.hist(N_B_time, density=True, bins=np.arange(35), label="B", color='dimgrey')
plt.hist(N_AB_time, density=True, bins=np.arange(35), label="AB", color='red')
plt.legend()
plt.show()
```
If instead of a system of 2 reactions we instead wanted to look a system of a large number of reactions we could modify the method above quite simply. Instead of the calculation of $R$ (overall reaction rate) consisting of 2 terms it will consist of a larger number of terms depending on the nature of the individual reactions. The probability of selecting a particular reaction type would then equally be in proportion to their contribution to $R$.
We can also notice that there is nothing "special" about the method that means it only applies to reaction kinetics. For example: the example code above could equally be a "marriage and divorce model" for heterosexual couples: A representing women and B representing men, AB representing a marriage. Through defining the "reactions" slightly differently it doesn't take much modification to turn this into a infection model: for example there could be 3 states: susceptible to infection, infected and recovered (potentially with immunity) with transition rates between each of these states.
We can see then that the Gillespie algorithm is very flexible and allows us to model stochastic systems that may otherwise be mathematically intractable. Through the nature of the modelling procedure we can sample from the system exactly (upto the precision of floating point numbers within our computers!)
There is a downside to exact simulation however: it can be very slow! In the example above the speed isn't really an issue since the system is so simple. However if we were modelling many different reaction types (say the order of 100s) then to allow for adequate samples we will need to run many trajectories, this can quickly spiral into a very slow running code! Thankfully however the method has been adapted in many ways to combat this issue.
## Hybrid-Gillespie
We can note that calculating deterministic results from an ODE is (much) quicker than implementing the Gillespie simulation algorithm since there is no random element. However we notice that we do not have to model every reaction type using the same Gillespie approach. For example suppose we have one reaction type that is much slower than the others, say the order of 10 times slower. We could model this reaction via a determinstic ODE approach and simply rely on Gillespie for the more rapidly changing dynamics. Of course this is not applicable in every situation - as with any modelling or approximation used we should be sure that it is applicable to the situation at hand. For brevity we will not code an example of this here but it should be easy enough to modify the code above (for example by adding that molecule $A$ can "disappear" from the system with a rate 1/10 times the rate of the backward reaction).
## Tau Leaping
Tau leaping modifies the Gillespie methodology above, it sacrifices exact simulation in favour of an approximate simulation that is quicker to compute. The main idea behind tau-leaping is also intuitive: instead of modelling time to the next event we "jump" forward in time and then compute how many reactions we would expect to see within that time frame and updating the population amounts in one step. By updating the population amounts in one go we should be able to compute much faster. It should be clear that this is an approximation to the Gillespie algorithm. The size of the "leaps" determines how efficient the method is and how accurate the approximation is. If we make very large steps we can model many reactions per step which speeds up the implementation, however the simulation will also be less accurate since the populations will be updated less frequently. Conversely a very small leap size will mean many leaps will not see a reaction and so the algorithm will run more slowly, however this should result in dynamics very close to the Gillespie method. Often choosing the leap size requuires some trial and error.
we can write pseudo-code for the tau-leaping process as:
1. **Initialize** - Set initial conditions for the system and set leaping size
2. **Calculate event rates** - for each event types depending on state of the system
3. **Monte-Carlo** - for each event type sample number of events occuring within the leap
4. **Update** - Update system state based on number of events
5. **Repeat** - Repeat steps 2-4 until some stopping criteria is met
Recall: in the example above we used an exponential waiting time between reactions. This means the reactions occur as a poisson process - as a result the number of reactions occuring within a given timeframe will follow a poisson distribution. We also have to be careful to not allow a negative population (at least in the example presented - in other systems this may be reasonable).
We can modify our example above to use Tau-leaping as:
```python
# An implenetation of the Gillespie algorithm
# with tau leaping
# Applied to a pair of reactions:
# A + B -> AB
# AB -> A + B
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import poisson
%matplotlib inline
# Fix random seed for repeatability
np.random.seed(123)
###### Fix model parameters ######
N_A0 = 25 # Initial number of A molecules
N_B0 = 35 # Initial number of B molecules
N_AB0 = 5 # Initial number of AB molecules
rf = 2 # Forward reaction rate
rb = 1 # Backwards reaction rate
leap = 0.005 # Size of leaping steps
steps = 25 # Number of leaps per trajectory
cycles = 100 # Number of trajectories iterated over
# Set up holder arrays
T = np.arange(steps+1)*leap
N_A = np.zeros((cycles, steps+1))
N_B = np.zeros((cycles, steps+1))
N_AB = np.zeros((cycles, steps+1))
# Store initial conditions
N_A[:,0] = N_A0
N_B[:,0] = N_B0
N_AB[:,0] = N_AB0
###### Main Code Loop ######
for i in range(cycles):
for j in range(steps):
# Calculate updated reaction rates
Rf = rf * N_A[i,j] * N_B[i,j]
Rb = rb * N_AB[i,j]
# Calculate number of reactions by type
uf = np.random.random()
ub = np.random.random()
Nf = poisson.ppf(uf, Rf*leap)
Nb = poisson.ppf(ub, Rb*leap)
# Apply limits to prevent negative population
Limitf = min(N_A[i,j], N_B[i,j])
Limitb = N_AB[i,j]
Nf = min(Nf, Limitf)
Nb = min(Nb, Limitb)
# Update populations
N_A[i,j+1] = N_A[i,j] + Nb - Nf
N_B[i,j+1] = N_B[i,j] + Nb - Nf
N_AB[i,j+1] = N_AB[i,j] + Nf - Nb
# Calculate average arrays
N_A_ave = N_A.mean(axis=0)
N_B_ave = N_B.mean(axis=0)
N_AB_ave = N_AB.mean(axis=0)
###### Plot Trajectories ######
fig, axs = plt.subplots(3, 1, figsize=(10,20))
# Plot average trajectories
axs[0].plot(T, N_A_ave, marker='', color='red', linewidth=1.9, alpha=0.9)
axs[0].set_title('Number A Molecules')
axs[0].set_ylim((0,35))
axs[0].set_xlim((0,0.125))
axs[1].plot(T, N_B_ave, marker='', color='red', linewidth=1.9, alpha=0.9)
axs[1].set_title('Number B Molecules')
axs[1].set_ylim((0,35))
axs[1].set_xlim((0,0.125))
axs[2].plot(T, N_AB_ave, marker='', color='red', linewidth=1.9, alpha=0.9)
axs[2].set_title('Number AB Molecules')
axs[2].set_xlabel("Time")
axs[2].set_ylim((0,35))
axs[2].set_xlim((0,0.125))
# Plot each simulated trajectory
for i in range(cycles):
axs[0].plot(T[:], N_A[i,:], marker='', color='grey', linewidth=0.6, alpha=0.3)
axs[1].plot(T[:], N_B[i,:], marker='', color='grey', linewidth=0.6, alpha=0.3)
axs[2].plot(T[:], N_AB[i,:], marker='', color='grey', linewidth=0.6, alpha=0.3)
plt.show()
```
We can see here that even though the trajectories from tau-leaping are less exact the procedure has produced smoother average results for the same number of simulation steps (approximately the same running time).
And again we can look at the distribution at time=0.025:
```python
time = 0.025
N_A_time = np.zeros(cycles)
N_B_time = np.zeros(cycles)
N_AB_time = np.zeros(cycles)
for i in range(cycles):
for j in range(1, steps):
if T[j] >= time and T[j-1] < time:
N_A_time[i] = N_A[i,j]
N_B_time[i] = N_B[i,j]
N_AB_time[i] = N_AB[i,j]
# If trajectory doesn't span far enough take latest observation
if T[i, steps] < time:
N_A_time[i] = N_A[i, steps]
N_B_time[i] = N_B[i, steps]
N_AB_time[i] = N_AB[i, steps]
plt.hist(N_A_time, density=True, bins=np.arange(35), label="A", color='lightgrey')
plt.hist(N_B_time, density=True, bins=np.arange(35), label="B", color='dimgrey')
plt.hist(N_AB_time, density=True, bins=np.arange(35), label="AB", color='red')
plt.legend()
plt.show()
```
Here we can see improved distributions with (what appears to be) less noise. To justify this we would want to run more tests however.
Note: this is the most basic implementation of the tau-leaping procedure. In certain situations this needs to be manipulated to improve behaviour, for example if the poisson draw is often large enough to cause the population to go negative then a truncation procedure (or acceptance/rejection scheme) needs to be employed in such a way as to retain the average reaction rates. In this simple example we ignore this complication, there are some occasions where the number of $A$ molecules hits zero so there will be some bias in the estimates presented above.
## Adaptive Tau-Leaping
The "problem" with the tau-leaping method above is that it is very sensitive to the leap size. It is also possible that as the system evolves what started out as a "good" leap size becomes "bad" as the dynamics change. One possible solution to this is to use an "adaptive" method whereby the leap size varies depending on the dynamics. The main idea is to limit the leap sizes from being so large that the populations can reach an unfavourable state (e.g. negative population sizes) or jump to a state "too far away".
There are many ways to do this, one of the more popular was developed by Y. Cao and D. Gillespie in 2006. In order to describe the method we will need to introduce some notation. We let $\mathbf{X}_t = \left( X_t^i \right)_{i=1}^N$ to be a vector of population sizes at time t. We intorduce variables $v_{ij}$ to represent the change in component $i$ of the population when an event $j$ occurs - we will use $i$ indices to refer to components of the population vector and $j$ indices to refer to event types. $R_j(\mathbf{X}_t)$ is the rate of event $j$ with population $\mathbf{X}_t$. In this method we look to bound the relative shift in rates at each step by a parameter $\epsilon$.
In pseudo-code we can describe the process via:
1. **Initialize** - Set initial conditions for the population
2. **Calculate event rates** - $R_j$ for each event types depending on state of the system
3. **Calculate auxiliary variables** - for each state component $i$
\begin{align}
\mu_i &= \sum_j v_{ij} R_j \\
\sigma_j^2 &= \sum_j v_{ij}^2 R_j
\end{align}
4. **Select highest order event** - for each state component $i$, denote the rate of this event as $g_i$
5. **Calculate time step**
$$ \tau = min_i \left( min\left( \frac{max\left( \frac{\epsilon X_i}{g_i}, 1 \right)}{|\mu_i|} , \frac{max\left( \frac{\epsilon X_i}{g_i}, 1 \right)^2}{\sigma_j^2} \right) \right) $$
6. **Monte-Carlo** - for each event type sample number of events occuring within the leap step $\tau$
7. **Update** - Update system state based on number of events
8. **Repeat** - Repeat steps 2-7 until some stopping criteria is met
Step 4. involves selecting the highest order event - this essentially is the "most important" event that each $i$ is involved in. For very complex systems this may not be an obvious thing to do and will require more finesse. We can see that aside from steps 3-5 this is the exact same scheme as the previous example.
There are other adaptive leaping schemes that one could use each with different pros and cons.
We can modify the code above to use this scheme via:
```python
# An implenetation of the Gillespie algorithm
# With adaptive tau-leaping
# Applied to a pair of reactions:
# A + B -> AB
# AB -> A + B
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import poisson
%matplotlib inline
# Fix random seed for repeatability
np.random.seed(123)
###### Fix model parameters ######
N_A0 = 25 # Initial number of A molecules
N_B0 = 35 # Initial number of B molecules
N_AB0 = 5 # Initial number of AB molecules
rf = 2 # Forward reaction rate
rb = 1 # Backwards reaction rate
eps = 0.03 # Epsilon adaptive rate
steps = 25 # Number of reactions per trajectory
cycles = 100 # Number of trajectories iterated over
# Set up holder arrays
T = np.zeros((cycles, steps+1))
N_A = np.zeros((cycles, steps+1))
N_B = np.zeros((cycles, steps+1))
N_AB = np.zeros((cycles, steps+1))
# Store initial conditions
N_A[:,0] = N_A0
N_B[:,0] = N_B0
N_AB[:,0] = N_AB0
###### Main Code Loop ######
for i in range(cycles):
for j in range(steps):
# Calculate updated reaction rates
Rf = rf * N_A[i,j] * N_B[i,j]
Rb = rb * N_AB[i,j]
# Calculate auxiliary variables
mu_A = Rf - Rb
mu_B = Rf - Rb
mu_AB = Rb - Rf
sig2_A = Rf + Rb
sig2_B = Rf + Rb
sig2_AB = Rf + Rb
# Select highest order reactions
g_A = Rf
g_B = Rf
g_AB = Rb
# Caclulate internal maxima - taking care of divide by zero
if g_A == 0:
max_A = 1
else:
max_A = max(eps*N_A[i,j]/g_A,1)
if g_B == 0:
max_B = 1
else:
max_B = max(eps*N_B[i,j]/g_B, 1)
if g_AB == 0:
max_AB = 1
else:
max_AB = max(eps*N_AB[i,j]/g_AB, 1)
# Calculate minima for each component
min_A = min(max_A / abs(mu_A), max_A**2 / sig2_A)
min_B = min(max_B / abs(mu_B), max_B**2 / sig2_B)
min_AB = min(max_AB / abs(mu_AB), max_AB**2 / sig2_AB)
# Select tau leap size
leap = min(min_A, min_B, min_AB)
# Calculate number of reactions by type
uf = np.random.random()
ub = np.random.random()
Nf = poisson.ppf(uf, Rf*leap)
Nb = poisson.ppf(ub, Rb*leap)
# Apply limits to prevent negative population
Limitf = min(N_A[i,j], N_B[i,j])
Limitb = N_AB[i,j]
Nf = min(Nf, Limitf)
Nb = min(Nb, Limitb)
# Update populations and times
N_A[i,j+1] = N_A[i,j] + Nb - Nf
N_B[i,j+1] = N_B[i,j] + Nb - Nf
N_AB[i,j+1] = N_AB[i,j] + Nf - Nb
T[i,j+1] = T[i,j] + leap
# Calculate an average trajectory plot
ave_steps = 100
T_max = T.max()
# Set up average array holders
T_ave = np.linspace(0,T_max,ave_steps+1)
N_A_ave = np.zeros(ave_steps+1)
N_B_ave = np.zeros(ave_steps+1)
N_AB_ave = np.zeros(ave_steps+1)
N_A_ave[0] = N_A0
N_B_ave[0] = N_B0
N_AB_ave[0] = N_AB0
# Pass over average array entries
for i in range(1, ave_steps+1):
tmax = T_ave[i]
A_sum = 0
B_sum = 0
AB_sum = 0
t_count = 0
# Pass over each trajectory and step therein
for j in range(cycles):
for k in range(steps):
if T[j,k] <= tmax and T[j,k+1] > tmax:
t_count += 1
A_sum += N_A[j,k]
B_sum += N_B[j,k]
AB_sum += N_AB[j,k]
# Caclulate average - taking care if no samples observed
if t_count == 0:
N_A_ave[i] = N_A_ave[i-1]
N_B_ave[i] = N_B_ave[i-1]
N_AB_ave[i] = N_AB_ave[i-1]
else:
N_A_ave[i] = A_sum / t_count
N_B_ave[i] = B_sum / t_count
N_AB_ave[i] = AB_sum / t_count
###### Plot Trajectories ######
fig, axs = plt.subplots(3, 1, figsize=(10,20))
axs[0].plot(T_ave, N_A_ave, marker='', color='red', linewidth=1.9, alpha=0.9)
axs[0].set_title('Number A Molecules')
axs[0].set_ylim((0,35))
axs[0].set_xlim((0,0.125))
axs[1].plot(T_ave, N_B_ave, marker='', color='red', linewidth=1.9, alpha=0.9)
axs[1].set_title('Number B Molecules')
axs[1].set_ylim((0,35))
axs[1].set_xlim((0,0.125))
axs[2].plot(T_ave, N_AB_ave, marker='', color='red', linewidth=1.9, alpha=0.9)
axs[2].set_title('Number AB Molecules')
axs[2].set_xlabel("Time")
axs[2].set_ylim((0,35))
axs[2].set_xlim((0,0.125))
for i in range(cycles):
axs[0].plot(T[i,:], N_A[i,:], marker='', color='grey', linewidth=0.6, alpha=0.3)
axs[1].plot(T[i,:], N_B[i,:], marker='', color='grey', linewidth=0.6, alpha=0.3)
axs[2].plot(T[i,:], N_AB[i,:], marker='', color='grey', linewidth=0.6, alpha=0.3)
plt.show()
```
As with the previous tau-leaping algorithm there the trajectories are noticably less exact than the original Gillespie formulation. However owing to the variable time step the trajectories do appear slightly less granular than in the previous tau-leaping formulation. Again the average trajectory is smoother than in the original method for (approximately) the same amount of run-time.
Looking at the time=0.025 distributions once again:
```python
time = 0.025
N_A_time = np.zeros(cycles)
N_B_time = np.zeros(cycles)
N_AB_time = np.zeros(cycles)
for i in range(cycles):
for j in range(1, steps+1):
if T[i,j] >= time and T[i,j-1] < time:
N_A_time[i] = N_A[i,j]
N_B_time[i] = N_B[i,j]
N_AB_time[i] = N_AB[i,j]
if T[i, steps] < time:
N_A_time[i] = N_A[i, steps]
N_B_time[i] = N_B[i, steps]
N_AB_time[i] = N_AB[i, steps]
plt.hist(N_A_time, density=True, bins=np.arange(35), label="A", color='lightgrey')
plt.hist(N_B_time, density=True, bins=np.arange(35), label="B", color='dimgrey')
plt.hist(N_AB_time, density=True, bins=np.arange(35), label="AB", color='red')
plt.legend()
plt.show()
```
Again the distributions for a fixed time appear to have become less noisy.
In a small scale simple example such as this we would expect any "improvements" from a scheme like this to be minor, as we run more complicated examples we would expect a bigger performance differential.
## Conclusion
In this blog post we have seen 3 variations of the Gillespie algorithm: the original, tau-leaping and an adaptive tau leaping scheme. We have seen that the original variation produces exact simulations of a specified system, via tau leaping we have seen that we can approximate this and still get reasonable results in a quicker time. Which is important when dealing with more complicated and larger systems.
At this point we should also see the flexibility inherent in the Gillespie framework and why it has been applied in many different areas. We can also see that the algorithm is a "gateway" into agent-based schemes - instead of using a purely stochastic mechanism for selecting reaction types/times we could (for example) model individual molecules moving around in space and if they come within a certain radius of each other at a certain speed then a reaction occurs. This would turn the Gillespie algorithm into a full agent-based model for reaction kinetics (the benefit of doing this in most situations is likely slim to none however).
|
using LinearAlgebra: lmul!
using LinearAlgebra.BLAS: gemm!
"""
conv4(w, x; kwargs...)
Execute convolutions or cross-correlations using filters specified
with `w` over tensor `x`.
Currently KnetArray{Float32/64,4/5} and Array{Float32/64,4} are
supported as `w` and `x`. If `w` has dimensions `(W1,W2,...,I,O)` and
`x` has dimensions `(X1,X2,...,I,N)`, the result `y` will have
dimensions `(Y1,Y2,...,O,N)` where
Yi=1+floor((Xi+2*padding[i]-Wi)/stride[i])
Here `I` is the number of input channels, `O` is the number of output
channels, `N` is the number of instances, and `Wi,Xi,Yi` are spatial
dimensions. `padding` and `stride` are keyword arguments that can be
specified as a single number (in which case they apply to all
dimensions), or an array/tuple with entries for each spatial
dimension.
# Keywords
* `padding=0`: the number of extra zeros implicitly concatenated at the start and at the end of each dimension.
* `stride=1`: the number of elements to slide to reach the next filtering window.
* `upscale=1`: upscale factor for each dimension.
* `mode=0`: 0 for convolution and 1 for cross-correlation.
* `alpha=1`: can be used to scale the result.
* `handle`: handle to a previously created cuDNN context. Defaults to a Knet allocated handle.
"""
function conv4(w::KnetArray{T},x::KnetArray{T}; handle=cudnnhandle(), alpha=1,
o...) where {T} # padding=0, stride=1, upscale=1, mode=0
beta=0 # nonzero beta does not make sense when we create y
y = similar(x, cdims(w,x;o...))
(algo,workSpace) = conv4_algo(w, x, y; handle=handle, o...)
@cudnn(cudnnConvolutionForward,
(Cptr,Ptr{T},Cptr,Ptr{T},Cptr,Ptr{T},Cptr, UInt32,Cptr, Csize_t, Ptr{T},Cptr,Ptr{T}),
handle,Ref(T(alpha)),TD(x),x,FD(w),w,CD(w,x;o...),algo,workSpace,bytes(workSpace),Ref(T(beta)),TD(y),y)
return y
end
function conv4x(w::KnetArray{T},x::KnetArray{T},dy::KnetArray{T}; handle=cudnnhandle(), alpha=1,
o...) where {T} # padding=0, stride=1, upscale=1, mode=0
beta = 0
dx = similar(x)
(algo,workSpace) = conv4x_algo(w,x,dy,dx; handle=handle, o...)
if cudnnVersion >= 4000
@cudnn(cudnnConvolutionBackwardData,
(Cptr,Ptr{T},Cptr,Ptr{T},Cptr,Ptr{T},Cptr, UInt32,Cptr, Csize_t, Ptr{T},Cptr,Ptr{T}),
handle,Ref(T(alpha)),FD(w),w,TD(dy),dy,CD(w,x;o...),algo,workSpace,bytes(workSpace),Ref(T(beta)),TD(dx),dx)
elseif cudnnVersion >= 3000
@cudnn(cudnnConvolutionBackwardData_v3,
(Cptr,Ptr{T},Cptr,Ptr{T},Cptr,Ptr{T},Cptr, UInt32,Cptr, Csize_t, Ptr{T},Cptr,Ptr{T}),
handle,Ref(T(alpha)),FD(w),w,TD(dy),dy,CD(w,x;o...),algo,workSpace,bytes(workSpace),Ref(T(beta)),TD(dx),dx)
else
@cudnn(cudnnConvolutionBackwardData,
(Cptr,Ptr{T},Cptr,Ptr{T},Cptr,Ptr{T},Cptr, Ptr{T},Cptr,Ptr{T}),
handle,Ref(T(alpha)),FD(w),w,TD(dy),dy,CD(w,x;o...),Ref(T(beta)),TD(dx),dx)
end
return dx
end
function conv4w(w::KnetArray{T},x::KnetArray{T},dy::KnetArray{T}; handle=cudnnhandle(), alpha=1,
o...) where {T} # padding=0, stride=1, upscale=1, mode=0
beta = 0
dw = similar(w)
(algo,workSpace) = conv4w_algo(w,x,dy,dw;handle=handle,o...)
if cudnnVersion >= 4000
@cudnn(cudnnConvolutionBackwardFilter,
(Cptr,Ptr{T},Cptr,Ptr{T},Cptr,Ptr{T},Cptr, UInt32,Cptr, Csize_t, Ptr{T},Cptr,Ptr{T}),
handle,Ref(T(alpha)),TD(x),x,TD(dy),dy,CD(w,x;o...),algo,workSpace,bytes(workSpace),Ref(T(beta)),FD(dw),dw)
elseif cudnnVersion >= 3000
@cudnn(cudnnConvolutionBackwardFilter_v3,
(Cptr,Ptr{T},Cptr,Ptr{T},Cptr,Ptr{T},Cptr, UInt32,Cptr, Csize_t, Ptr{T},Cptr,Ptr{T}),
handle,Ref(T(alpha)),TD(x),x,TD(dy),dy,CD(w,x;o...),algo,workSpace,bytes(workSpace),Ref(T(beta)),FD(dw),dw)
else
@cudnn(cudnnConvolutionBackwardFilter,
(Cptr,Ptr{T},Cptr,Ptr{T},Cptr,Ptr{T},Cptr, Ptr{T},Cptr,Ptr{T}),
handle,Ref(T(alpha)),TD(x),x,TD(dy),dy,CD(w,x;o...),Ref(T(beta)),FD(dw),dw)
end
return dw
end
@primitive conv4(w,x; o...),dy conv4w(w,x,dy;o...) conv4x(w,x,dy;o...)
@zerograd conv4x(w,x,dy;o...)
@zerograd conv4w(w,x,dy;o...)
"""
pool(x; kwargs...)
Compute pooling of input values (i.e., the maximum or average of
several adjacent values) to produce an output with smaller height
and/or width.
Currently 4 or 5 dimensional KnetArrays with `Float32` or `Float64`
entries are supported. If `x` has dimensions `(X1,X2,...,I,N)`, the
result `y` will have dimensions `(Y1,Y2,...,I,N)` where
Yi=1+floor((Xi+2*padding[i]-window[i])/stride[i])
Here `I` is the number of input channels, `N` is the number of
instances, and `Xi,Yi` are spatial dimensions. `window`, `padding`
and `stride` are keyword arguments that can be specified as a single
number (in which case they apply to all dimensions), or an array/tuple
with entries for each spatial dimension.
# Keywords:
* `window=2`: the pooling window size for each dimension.
* `padding=0`: the number of extra zeros implicitly concatenated at the start and at the end of each dimension.
* `stride=window`: the number of elements to slide to reach the next pooling window.
* `mode=0`: 0 for max, 1 for average including padded values, 2 for average excluding padded values.
* `maxpoolingNanOpt=0`: Nan numbers are not propagated if 0, they are propagated if 1.
* `alpha=1`: can be used to scale the result.
* `handle`: Handle to a previously created cuDNN context. Defaults to a Knet allocated handle.
"""
function pool(x::KnetArray{T}; handle=cudnnhandle(), alpha=1,
o...) where {T} # window=2, padding=0, stride=window, mode=0, maxpoolingNanOpt=0
y = similar(x, pdims(x; o...))
beta = 0
@cudnn(cudnnPoolingForward,
(Cptr, Cptr, Ptr{T}, Cptr,Ptr{T},Ptr{T}, Cptr,Ptr{T}),
handle,PD(x;o...),Ref(T(alpha)),TD(x),x, Ref(T(beta)),TD(y),y)
return y
end
function poolx(x::KnetArray{T},y::KnetArray{T},dy::KnetArray{T}; handle=cudnnhandle(), alpha=1, mode=0,
o...) where {T} # window=2, padding=0, stride=window, maxpoolingNanOpt=0
if alpha!=1 && mode==0; error("Gradient of pool(alpha!=1,mode=0) broken in CUDNN"); end
dx = similar(x)
beta = 0
@cudnn(cudnnPoolingBackward,
(Cptr,Cptr,Ptr{T},Cptr,Ptr{T},Cptr,Ptr{T},Cptr,Ptr{T},Ptr{T},Cptr,Ptr{T}),
handle,PD(x;mode=mode,o...),Ref(T(alpha)),TD(y),y,TD(dy),dy,TD(x),x,Ref(T(beta)),TD(dx),dx)
return dx
end
@primitive pool(x;o...),dy,y poolx(x,y,dy;o...)
@zerograd poolx(x,y,dy;o...)
"""
Unpooling; `reverse` of pooling.
x == pool(unpool(x;o...); o...)
"""
function unpool(x; window=2, alpha=1, o...) # padding=0, stride=window, mode=0, maxpoolingNanOpt=0
w = prod(psize(window,x))
y = similar(x,updims(x; window=window, o...))
poolx(y,x,x.*w; o..., window=window, mode=1, alpha=1/alpha)
end
function unpoolx(dy; window=2, alpha=1, o...) # padding=0, stride=window, mode=0, maxpoolingNanOpt=0
w = prod(psize(window,dy))
pool(dy; o..., window=window, mode=1, alpha=1/alpha) * w
end
# @primitive unpool(x;o...),dy,y -pool(-dy;o...)
@primitive unpool(x;o...),dy,y unpoolx(dy;o...)
"""
y = deconv4(w, x; kwargs...)
Simulate 4-D deconvolution by using _transposed convolution_ operation. Its forward pass is equivalent to backward pass of a convolution (gradients with respect to input tensor). Likewise, its backward pass (gradients with respect to input tensor) is equivalent to forward pass of a convolution. Since it swaps forward and backward passes of convolution operation, padding and stride options belong to output tensor. See [this report](https://arxiv.org/abs/1603.07285) for further explanation.
Currently KnetArray{Float32/64,4} and Array{Float32/64,4} are
supported as `w` and `x`. If `w` has dimensions `(W1,W2,...,O,I)` and
`x` has dimensions `(X1,X2,...,I,N)`, the result `y` will have
dimensions `(Y1,Y2,...,O,N)` where
Yi = Wi+stride[i]*(Xi-1)-2*padding[i]
Here I is the number of input channels, O is the number of output channels, N is the number of instances, and Wi,Xi,Yi are spatial dimensions. padding and stride are keyword arguments that can be specified as a single number (in which case they apply to all dimensions), or an array/tuple with entries for each spatial dimension.
# Keywords
* `padding=0`: the number of extra zeros implicitly concatenated at the start and at the end of each dimension.
* `stride=1`: the number of elements to slide to reach the next filtering window.
* `mode=0`: 0 for convolution and 1 for cross-correlation.
* `alpha=1`: can be used to scale the result.
* `handle`: handle to a previously created cuDNN context. Defaults to a Knet allocated handle.
"""
function deconv4(w,x; o...)
y = similar(x,dcdims(w,x;o...))
return conv4x(w,y,x;o...)
end
function deconv4w(w,x,dy; o...)
return conv4w(w,dy,x;o...)
end
function deconv4x(w,x,dy; o...)
return conv4(w,dy;o...)
end
@primitive deconv4(w,x; o...),dy,y deconv4w(w,x,dy; o...) deconv4x(w,x,dy; o...)
@zerograd deconv4w(w,x,dy; o...)
@zerograd deconv4x(w,x,dy; o...)
# cudnn descriptors
mutable struct TD; ptr; end
TD(a::KnetArray{T}) where {T} = TD(T,size(a))
TD(T::Type, dims::Integer...) = TD(T, dims)
function TD(T::Type, dims)
d = Cptr[0]
@cudnn(cudnnCreateTensorDescriptor,(Ptr{Cptr},),d)
n = length(dims)
sz = [Cint(dims[i]) for i=n:-1:1]
st = similar(sz); st[n] = 1
for i=(n-1):-1:1; st[i] = st[i+1] * sz[i+1]; end
@cudnn(cudnnSetTensorNdDescriptor,
(Cptr,UInt32,Cint,Ptr{Cint},Ptr{Cint}),
d[1], DT(T), n, sz, st)
td = TD(d[1])
finalizer(x->@cudnn(cudnnDestroyTensorDescriptor,(Cptr,),x.ptr), td)
return td
end
mutable struct FD; ptr; end
FD(a::KnetArray{T}) where {T}=FD(T,size(a))
FD(T::Type, dims::Integer...) = FD(T,dims)
function FD(T::Type, dims)
d = Cptr[0]
@cudnn(cudnnCreateFilterDescriptor,(Ptr{Cptr},),d)
n = length(dims)
sz = [Cint(dims[i]) for i=n:-1:1]
if cudnnVersion >= 5000
@cudnn(cudnnSetFilterNdDescriptor,
(Cptr,UInt32,UInt32,Cint,Ptr{Cint}),
d[1], DT(T), 0, n, sz)
elseif cudnnVersion >= 4000
@cudnn(cudnnSetFilterNdDescriptor_v4,
(Cptr,UInt32,UInt32,Cint,Ptr{Cint}),
d[1], DT(T), 0, n, sz)
else
@cudnn(cudnnSetFilterNdDescriptor,
(Cptr,UInt32,Cint,Ptr{Cint}),
d[1], DT(T), n, sz)
end
fd = FD(d[1])
finalizer(x->@cudnn(cudnnDestroyFilterDescriptor,(Cptr,),x.ptr), fd)
return fd
end
mutable struct CD; ptr
function CD(w::KnetArray,x::KnetArray; padding=0, stride=1, upscale=1, mode=0)
d = Cptr[0]
@cudnn(cudnnCreateConvolutionDescriptor,(Ptr{Cptr},),d)
nd = ndims(x)-2
if cudnnVersion >= 4000
@cudnn(cudnnSetConvolutionNdDescriptor,
(Cptr,Cint,Ptr{Cint},Ptr{Cint},Ptr{Cint},UInt32,UInt32),
d[1],nd,cdsize(padding,nd),cdsize(stride,nd),cdsize(upscale,nd),mode,DT(x))
elseif cudnnVersion > 3000 # does not work when cudnnVersion==3000
@cudnn(cudnnSetConvolutionNdDescriptor_v3,
(Cptr,Cint,Ptr{Cint},Ptr{Cint},Ptr{Cint},UInt32,UInt32),
d[1],nd,cdsize(padding,nd),cdsize(stride,nd),cdsize(upscale,nd),mode,DT(x))
else
@cudnn(cudnnSetConvolutionNdDescriptor,
(Cptr,Cint,Ptr{Cint},Ptr{Cint},Ptr{Cint},UInt32),
d[1],nd,cdsize(padding,nd),cdsize(stride,nd),cdsize(upscale,nd),mode)
end
cd = new(d[1])
finalizer(x->@cudnn(cudnnDestroyConvolutionDescriptor,(Cptr,),x.ptr),cd)
return cd
end
end
mutable struct PD; ptr
function PD(x::KnetArray; window=2, padding=0, stride=window, mode=0, maxpoolingNanOpt=0)
d = Cptr[0]
@cudnn(cudnnCreatePoolingDescriptor,(Ptr{Cptr},),d)
nd = ndims(x)-2
if cudnnVersion >= 5000
@cudnn(cudnnSetPoolingNdDescriptor,
(Cptr,UInt32,UInt32,Cint,Ptr{Cint},Ptr{Cint},Ptr{Cint}),
d[1],mode,maxpoolingNanOpt,nd,cdsize(window,nd),cdsize(padding,nd),cdsize(stride,nd))
elseif cudnnVersion >= 4000
@cudnn(cudnnSetPoolingNdDescriptor_v4,
(Cptr,UInt32,UInt32,Cint,Ptr{Cint},Ptr{Cint},Ptr{Cint}),
d[1],mode,maxpoolingNanOpt,nd,cdsize(window,nd),cdsize(padding,nd),cdsize(stride,nd))
else
@cudnn(cudnnSetPoolingNdDescriptor,
(Cptr,UInt32,Cint,Ptr{Cint},Ptr{Cint},Ptr{Cint}),
d[1],mode,nd,cdsize(window,nd),cdsize(padding,nd),cdsize(stride,nd))
end
pd = new(d[1])
finalizer(x->@cudnn(cudnnDestroyPoolingDescriptor,(Cptr,),x.ptr), pd)
return pd
end
end
import Base: unsafe_convert
unsafe_convert(::Type{Cptr}, td::TD)=td.ptr
unsafe_convert(::Type{Cptr}, fd::FD)=fd.ptr
unsafe_convert(::Type{Cptr}, cd::CD)=cd.ptr
unsafe_convert(::Type{Cptr}, pd::PD)=pd.ptr
# fill and reverse Cint array with padding etc. for cudnn calls
function cdsize(w, nd)
if isa(w,Number)
fill(Cint(w),nd)
elseif length(w)==nd
[ Cint(w[nd-i+1]) for i=1:nd ]
else
throw(DimensionMismatch("$w $nd"))
end
end
# convert padding etc. size to an Int array of the right dimension
function psize(p, x)
nd = ndims(x)-2
if isa(p,Number)
fill(Int(p),nd)
elseif length(p)==nd
collect(Int,p)
else
throw(DimensionMismatch("psize: $p $nd"))
end
end
DT(::KnetArray{Float32})=Cint(0)
DT(::KnetArray{Float64})=Cint(1)
DT(::KnetArray{Float16})=Cint(2)
DT(::Type{Float32}) = Cint(0)
DT(::Type{Float64}) = Cint(1)
DT(::Type{Float16}) = Cint(2)
function cdims(w,x; padding=0, stride=1, o...)
N = ndims(x)
ntuple(N) do i
if i < N-1
pi = (if isa(padding,Number); padding; else padding[i]; end)
si = (if isa(stride,Number); stride; else stride[i]; end)
1 + div(size(x,i) - size(w,i) + 2*pi, si)
elseif i == N-1
size(w,N)
else # i == N
size(x,N)
end
end
end
function pdims(x; window=2, padding=0, stride=window, o...)
N = ndims(x)
ntuple(N) do i
if i < N-1
wi = (if isa(window,Number); window; else window[i]; end)
pi = (if isa(padding,Number); padding; else padding[i]; end)
si = (if isa(stride,Number); stride; else stride[i]; end)
1 + div(size(x,i) + 2*pi - wi, si)
else
size(x,i)
end
end
end
function dcdims(w,x; padding=0, stride=1, o...)
N = ndims(x)
@assert size(x,N-1) == size(w,N)
ntuple(N) do i
if i < N-1
pi = (if isa(padding,Number); padding; else padding[i]; end)
si = (if isa(stride,Number); stride; else stride[i]; end)
si*(size(x,i)-1) + size(w,i) - 2*pi
elseif i == N-1
size(w,N-1)
else
size(x,N)
end
end
end
function updims(x; window=2, padding=0, stride=window, o...)
window = psize(window,x)
stride = psize(stride,x)
padding = psize(padding,x)
N = ndims(x)
ntuple(N) do i
if i < N-1
(size(x,i)-1)*stride[i]+window[i]-2*padding[i]
else
size(x,i)
end
end
end
# convolution padding size that preserves the input size when filter size is odd and stride=1
padsize(w)=ntuple(i->div(size(w,i)-1,2), ndims(w)-2)
### CPU convolution using im2col from Mocha.jl
# w=Ww,Hw,Cx,Cy
# x=Wx,Hx,Cx,Nx
# y=Wy,Hy,Cy,Nx
# if we apply im2col to a single image:
# w2=(Ww*Hw*Cx),Cy ;; simple reshape
# x2=(Wy*Hy),(Ww*Hw*Cx)
# y2=(Wy*Hy),Cy ;; simple reshape after y2=x2*w2
function conv4(w::AbstractArray{T,4}, x::AbstractArray{T,4};
padding=0, stride=1, upscale=1, mode=0, alpha=1,
o...) where {T} # Ignoring handle, algo, workSpace, workSpaceSizeInBytes
if upscale != 1; throw(ArgumentError("CPU conv4 only supports upscale=1.")); end
if mode != 0 && mode != 1; throw(ArgumentError("conv4 only supports mode=0 or 1.")); end
Wx,Hx,Cx,Nx = size(x)
Ww,Hw,C1,C2 = size(w)
if Cx!=C1; throw(DimensionMismatch()); end
Wy,Hy,Cy,Ny = cdims(w,x;padding=padding,stride=stride)
# @assert Cy==C2 && Ny==Nx
y = similar(x, (Wy,Hy,Cy,Ny))
x2dims = im2col_dims(w,x,y)
x2 = similar(x, x2dims)
(p1,p2) = psize(padding,x)
(s1,s2) = psize(stride,x)
M,N,K,Y = Wy*Hy,Cy,Ww*Hw*Cx,Wy*Hy*Cy
alpha,beta,yidx = T(alpha),T(0),1
@inbounds for n in 1:Nx
im2col!(w, x, x2, n, p1, p2, s1, s2, mode)
gemm!('N','N',M,N,K,alpha,pointer(x2),pointer(w),beta,pointer(y,yidx))
yidx += Y
end
return y
end
function conv4w(w::AbstractArray{T,4},x::AbstractArray{T,4},dy::AbstractArray{T,4};
padding=0, stride=1, upscale=1, mode=0, alpha=1,
o...) where {T} # Ignoring handle, algo, workSpace, workSpaceSizeInBytes
# dw = x'*dy
Wx,Hx,Cx,Nx = size(x)
Ww,Hw,C1,C2 = size(w)
Wy,Hy,Cy,Ny = size(dy)
# if upscale != 1; throw(ArgumentError("CPU conv4 only supports upscale=1.")); end
# if mode != 0 && mode != 1; throw(ArgumentError("conv4 only supports mode=0 or 1.")); end
# @assert Cx==C1 && Cy==C2 && Ny==Nx
dw = zero(w)
x2dims = im2col_dims(w,x,dy)
x2 = similar(x, x2dims)
# op(A) is an m-by-k matrix, op(B) is a k-by-n matrix, C is an m-by-n matrix.
Y,M,N,K = Wy*Hy*Cy,Ww*Hw*Cx,Cy,Wy*Hy
alpha,beta = T(alpha),T(1)
(p1,p2) = psize(padding,x)
(s1,s2) = psize(stride,x)
dyi = 1
@inbounds for n in 1:Nx
im2col!(w, x, x2, n, p1, p2, s1, s2, mode)
gemm!('T','N',M,N,K,alpha,pointer(x2),pointer(dy,dyi),beta,pointer(dw))
dyi += Y
end
return dw
end
function conv4x(w::AbstractArray{T,4},x::AbstractArray{T,4},dy::AbstractArray{T,4};
padding=0, stride=1, upscale=1, mode=0, alpha=1,
o...) where {T} # Ignoring handle, algo, workSpace, workSpaceSizeInBytes
# dx = dy*w'
Wx,Hx,Cx,Nx = size(x)
Ww,Hw,C1,C2 = size(w)
Wy,Hy,Cy,Ny = size(dy)
# if upscale != 1; throw(ArgumentError("CPU conv4 only supports upscale=1.")); end
# if mode != 0 && mode != 1; throw(ArgumentError("conv4 only supports mode=0 or 1.")); end
@assert Cx==C1 && Cy==C2 && Ny==Nx
dx = similar(x)
x2dims = im2col_dims(w,x,dy)
x2 = similar(x, x2dims)
# op(A) is an m-by-k matrix, op(B) is a k-by-n matrix, C is an m-by-n matrix.
Y,M,N,K = Wy*Hy*Cy,Wy*Hy,Ww*Hw*Cx,Cy
alpha,beta = T(alpha),T(0)
(p1,p2) = psize(padding,x)
(s1,s2) = psize(stride,x)
dyi = 1
@inbounds for n in 1:Nx
gemm!('N','T',M,N,K,alpha,pointer(dy,dyi),pointer(w),beta,pointer(x2))
col2im!(w,dx,x2,n,p1,p2,s1,s2,mode)
dyi += Y
end
return dx
end
im2col_dims(w,x,y)=(size(y,1)*size(y,2), size(w,1)*size(w,2)*size(w,3))
# Functions from conv.cpp:
for (T,S) in ((Float32,32), (Float64,64)); @eval begin
function im2col!(w::AbstractArray{$T,4}, x::AbstractArray{$T,4}, x2::AbstractArray{$T,2},
n::Int, p1::Int, p2::Int, s1::Int, s2::Int, mode::Int)
Wx,Hx,Cx,Nx = size(x)
Ww,Hw,C1,C2 = size(w)
xn = pointer(x, Wx*Hx*Cx*(n-1)+1)
@knet8($("im2col$S"),
(Ptr{$T},Ptr{$T},Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint),
xn,x2,Wx,Hx,Cx,Ww,Hw,p1,p2,s1,s2,mode)
return x2
end
function col2im!(w::AbstractArray{$T,4}, x::AbstractArray{$T,4}, x2::AbstractArray{$T,2},
n::Int, p1::Int, p2::Int, s1::Int, s2::Int, mode::Int)
Wx,Hx,Cx,Nx = size(x)
Ww,Hw,C1,C2 = size(w)
xn = pointer(x, Wx*Hx*Cx*(n-1)+1)
@knet8($("col2im$S"),
(Ptr{$T},Ptr{$T},Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint),
x2,xn,Wx,Hx,Cx,Ww,Hw,p1,p2,s1,s2,mode)
return x
end
### CPU pooling from Mocha.jl
function pool(x::AbstractArray{$T,4}; window=2, padding=0, stride=window, mode=0, maxpoolingNanOpt=0, alpha=1, handle=nothing)
if maxpoolingNanOpt!=0; throw(ArgumentError("CPU pool only supports maxpoolingNanOpt=0")); end
Wx,Hx,Cx,Nx = size(x);
Wy,Hy,Cy,Ny = pdims(x;window=window,padding=padding,stride=stride)
y = similar(x, (Wy,Hy,Cy,Ny))
(w1,w2) = psize(window, x)
(p1,p2) = psize(padding, x)
(s1,s2) = psize(stride, x)
if mode == 0
@knet8($("max_pooling_fwd$S"),
(Ptr{$T},Ptr{$T},Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint),
x,y,Wx,Hx,Cx,Nx,Wy,Hy,w1,w2,p1,p2,s1,s2)
elseif mode == 1 || (mode == 2 && p1==p2==0)
@knet8($("mean_pooling_fwd$S"),
(Ptr{$T},Ptr{$T},Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint),
x,y,Wx,Hx,Cx,Nx,Wy,Hy,w1,w2,p1,p2,s1,s2)
else
throw(ArgumentError("mode $mode not supported by cpu pool"))
end
if alpha != 1; lmul!(alpha,y); end
return y
end
function poolx(x::AbstractArray{$T,4}, y::AbstractArray{$T,4}, dy::AbstractArray{$T,4};
window=2, padding=0, stride=window, mode=0, maxpoolingNanOpt=0, alpha=1, handle=nothing)
if maxpoolingNanOpt!=0; throw(ArgumentError("CPU pool only supports maxpoolingNanOpt=0")); end
Wx,Hx,Cx,Nx = size(x);
Wy,Hy,Cy,Ny = size(y);
dx = similar(x)
(w1,w2) = psize(window, x)
(p1,p2) = psize(padding, x)
(s1,s2) = psize(stride, x)
if mode == 0
if alpha != 1; y = y ./ alpha; end
@knet8($("max_pooling_bwd$S"),
(Ptr{$T},Ptr{$T},Ptr{$T},Ptr{$T},Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint),
x,y,dy,dx,Wx,Hx,Cx,Nx,Wy,Hy,w1,w2,p1,p2,s1,s2)
elseif mode == 1 || (mode == 2 && p1==p2==0)
@knet8($("mean_pooling_bwd$S"),
(Ptr{$T},Ptr{$T},Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint),
dx,dy,Wx,Hx,Cx,Nx,Wy,Hy,w1,w2,p1,p2,s1,s2)
else
throw(ArgumentError("mode $mode not supported by cpu pool"))
end
if alpha != 1; lmul!(alpha,dx); end
return dx
end
end;end
# Utilities to find a fast algorithm
struct cudnnConvolutionFwdAlgoPerf_t
algo::Cint
status::Cint
time::Cfloat
memory::Csize_t
determinism::Cint
mathType::Cint
r1::Cint; r2::Cint; r3::Cint
end
const CUDNN_MAX_FIND = 100 # How many times can we call FindAlgorithm
const requestedAlgoCount = 10
const returnedAlgoCount = Cint[0]
const perfResults = Array{cudnnConvolutionFwdAlgoPerf_t}(undef,requestedAlgoCount)
bytes(x::KnetArray{T}) where {T}=length(x)*sizeof(T)
const conv4_algos = Dict()
function conv4_algo(w::KnetArray{T}, x::KnetArray{T}, y::KnetArray{T}; handle=cudnnhandle(), o...) where {T}
global conv4_algos, requestedAlgoCount, returnedAlgoCount, perfResults
key = (T,size(w),size(x),o...)
if haskey(conv4_algos, key)
p = conv4_algos[key]
return (p.algo, cudnnWorkSpace(p.memory))
elseif length(conv4_algos) >= CUDNN_MAX_FIND
return (0, cudnnWorkSpace())
else
Knet.gc(); @dbg print('*')
@cudnn(cudnnFindConvolutionForwardAlgorithm,
(Cptr,Cptr,Cptr,Cptr,Cptr,Cint,Ptr{Cint},Cptr),
handle,TD(x),FD(w),CD(w,x;o...),TD(y),requestedAlgoCount,returnedAlgoCount,perfResults)
p = perfChoose(perfResults, returnedAlgoCount[1])
conv4_algos[key] = p
return (p.algo, cudnnWorkSpace(p.memory))
end
end
const conv4w_algos = Dict()
function conv4w_algo(w::KnetArray{T},x::KnetArray{T},dy::KnetArray{T},dw::KnetArray{T}; handle=cudnnhandle(), o...) where {T}
global conv4w_algos, requestedAlgoCount, returnedAlgoCount, perfResults
key = (T,size(w),size(x),o...)
if haskey(conv4w_algos, key)
p = conv4w_algos[key]
return (p.algo, cudnnWorkSpace(p.memory))
elseif length(conv4w_algos) >= CUDNN_MAX_FIND
return (0, cudnnWorkSpace())
else
Knet.gc(); @dbg print('*')
@cudnn(cudnnFindConvolutionBackwardFilterAlgorithm,
(Cptr,Cptr,Cptr,Cptr,Cptr,Cint,Ptr{Cint},Cptr),
handle,TD(x),TD(dy),CD(w,x;o...),FD(dw),requestedAlgoCount,returnedAlgoCount,perfResults)
p = perfChoose(perfResults, returnedAlgoCount[1])
conv4w_algos[key] = p
return (p.algo, cudnnWorkSpace(p.memory))
end
end
const conv4x_algos = Dict()
function conv4x_algo(w::KnetArray{T},x::KnetArray{T},dy::KnetArray{T},dx::KnetArray{T}; handle=cudnnhandle(), o...) where {T}
global conv4x_algos, requestedAlgoCount, returnedAlgoCount, perfResults
key = (T,size(w),size(x),o...)
if haskey(conv4x_algos, key)
p = conv4x_algos[key]
return (p.algo, cudnnWorkSpace(p.memory))
elseif length(conv4x_algos) >= CUDNN_MAX_FIND
return (0, cudnnWorkSpace())
else
Knet.gc(); @dbg print('*')
@cudnn(cudnnFindConvolutionBackwardDataAlgorithm,
(Cptr,Cptr,Cptr,Cptr,Cptr,Cint,Ptr{Cint},Cptr),
handle,FD(w),TD(dy),CD(w,x;o...),TD(dx),requestedAlgoCount,returnedAlgoCount,perfResults)
p = perfChoose(perfResults, returnedAlgoCount[1])
conv4x_algos[key] = p
return (p.algo, cudnnWorkSpace(p.memory))
end
end
CUDNN_WORKSPACE_MAXSIZE = 0 # Will be set to 20% of available gpu memory
function perfChoose(ps, n)
global CUDNN_WORKSPACE_MAXSIZE
if n==ps
warn("returnedAlgoCount==requestedAlgoCount")
end
if CUDNN_WORKSPACE_MAXSIZE == 0
CUDNN_WORKSPACE_MAXSIZE = div(gpufree(),5)
end
(ibest,mbest,tbest) = (0,CUDNN_WORKSPACE_MAXSIZE,Inf)
for i = 1:n
if ps[i].status == 0 && ps[i].memory < mbest && ps[i].time < tbest * 1.1
(ibest,mbest,tbest) = (i,ps[i].memory,ps[i].time)
end
end
if ibest == 0; error("No good algo found."); end
return ps[ibest]
end
# TODO: this assumes one workspace per gpu. What about streams?
const CUDNN_WORKSPACE = []
function cudnnWorkSpace(len=0;dev=gpu())
global CUDNN_WORKSPACE
if dev==-1; error("No cudnnWorkSpace for CPU"); end
i = dev+2
if isempty(CUDNN_WORKSPACE); resize!(CUDNN_WORKSPACE,gpuCount()+1); end
if !isassigned(CUDNN_WORKSPACE,i) || length(CUDNN_WORKSPACE[i]) < len
CUDNN_WORKSPACE[i]=KnetArray{UInt8}(undef,len);
end
return CUDNN_WORKSPACE[i]
end
|
State Before: R : Type u
a✝ b✝ : R
m n : ℕ
inst✝ : Semiring R
p q a b : R[X]
⊢ (a + b).toFinsupp = a.toFinsupp + b.toFinsupp State After: case ofFinsupp
R : Type u
a b✝ : R
m n : ℕ
inst✝ : Semiring R
p q b : R[X]
toFinsupp✝ : AddMonoidAlgebra R ℕ
⊢ ({ toFinsupp := toFinsupp✝ } + b).toFinsupp = { toFinsupp := toFinsupp✝ }.toFinsupp + b.toFinsupp Tactic: cases a State Before: case ofFinsupp
R : Type u
a b✝ : R
m n : ℕ
inst✝ : Semiring R
p q b : R[X]
toFinsupp✝ : AddMonoidAlgebra R ℕ
⊢ ({ toFinsupp := toFinsupp✝ } + b).toFinsupp = { toFinsupp := toFinsupp✝ }.toFinsupp + b.toFinsupp State After: case ofFinsupp.ofFinsupp
R : Type u
a b : R
m n : ℕ
inst✝ : Semiring R
p q : R[X]
toFinsupp✝¹ toFinsupp✝ : AddMonoidAlgebra R ℕ
⊢ ({ toFinsupp := toFinsupp✝¹ } + { toFinsupp := toFinsupp✝ }).toFinsupp =
{ toFinsupp := toFinsupp✝¹ }.toFinsupp + { toFinsupp := toFinsupp✝ }.toFinsupp Tactic: cases b State Before: case ofFinsupp.ofFinsupp
R : Type u
a b : R
m n : ℕ
inst✝ : Semiring R
p q : R[X]
toFinsupp✝¹ toFinsupp✝ : AddMonoidAlgebra R ℕ
⊢ ({ toFinsupp := toFinsupp✝¹ } + { toFinsupp := toFinsupp✝ }).toFinsupp =
{ toFinsupp := toFinsupp✝¹ }.toFinsupp + { toFinsupp := toFinsupp✝ }.toFinsupp State After: no goals Tactic: rw [← ofFinsupp_add] |
(*
Copyright (C) 2017 M.A.L. Marques
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*)
(* type: work_mgga_x *)
(* prefix:
mgga_x_tau_hcth_params *params;
assert(pt->params != NULL);
params = (mgga_x_tau_hcth_params * ) (pt->params);
*)
coeff_a := [0, 1, 0, -2, 0, 1]:
(* Equation (29) *)
gamX := 0.004:
ux := x -> gamX*x^2/(1 + gamX*x^2):
gxl := x -> add(params_a_cx_local [i]*ux(x)^(i-1), i=1..4):
gxnl := x -> add(params_a_cx_nlocal[i]*ux(x)^(i-1), i=1..4):
f := (rs, x, t, u) -> gxl(x) + gxnl(x)*mgga_series_w(coeff_a, 6, t):
|
import numpy as np
import cnf
class CnfEvaluator:
def __init__(self, formula: cnf.CnfFormula):
self._formula = formula
def evaluate(self, variable_instances: np.array):
satisfied_count = 0
for clause_idx in range(0, self._formula.clause_count):
for term_idx in range(0, 3):
variable = self._formula.logical_matrix[clause_idx, term_idx]
truth_value = variable_instances[abs(variable) - 1]
if variable < 0:
truth_value = not truth_value
if truth_value:
satisfied_count += 1
break
return satisfied_count
|
Load LFindLoad.
From lfind Require Import LFind.
From QuickChick Require Import QuickChick.
From adtind Require Import goal33.
Derive Show for natural.
Derive Arbitrary for natural.
Instance Dec_Eq_natural : Dec_Eq natural.
Proof. dec_eq. Qed.
Lemma conj14synthconj1 : forall (lv0 : natural) (lv1 : natural), (@eq natural (plus (mult lv0 lv1) lv1) (plus (mult lv0 lv1) lv1)).
Admitted.
QuickChick conj14synthconj1.
|
\chapter*{Introduction}
\label{chap_motivation}
Turbulence is very common in daily life, science and technology. Understanding its nature and increasing our prediction capability is crucial for many applications. One of the main engineering tasks is to calculate and predict the behaviors of turbulent flows. This is essentially done with numerical simulations, since experiments are much more expensive or sometimes even impossible. Exact simulations of turbulent flows without modeling are possible only in academic contexts and limited to simple cases due to huge computational demands. Approaches with turbulence models, i.e. approximate solutions, are used more often in industries. Some only calculate mean quantities, while others approximate only large scales and model the effects of small ones. However, they are not yet satisfactory, mainly due to their incapability of predicting several flow configurations, for instance flow separation. All fails due to the ignorance or crude modeling of small scales.
Small-scale turbulence is very important but not yet fully accessible. Despite advancements of computational resources and experimental techniques, having access to small-scale turbulence remains very challenging. Understanding its physics is the key to propose realistic models by parameterizing its effects on the large scales, reducing the simulation efforts to much coarser grids. The physical properties of the flow at small-scale are also important in many applications such as combustion or biology. Unfortunately, accessing those information remains very difficult. Progressing further in experimental tools is one solution but will take very long time. It requires also advancements of infrastructure to handle such tremendous amount of data. Theoretical models generating small scales from large ones could help to progress in another direction. However, as discussed later, such a model is difficult to build from turbulence theories. Despite many efforts, all theories are not yet satisfactory to fully model the behaviors of small scales.
This thesis approaches the problem of estimating small-scale information from a different perspective. Empirical models and learning algorithms are used to propose computational methods to reconstruct full-scale information from available sparse measurements. They are further adapted or developed from works in signal and image processing, taking into account the key similarities and differences between turbulence and natural images. This can be viewed as the inverse problem of seeking a higher information level out of available measurements.
Outcomes of this work may improve our understandings of turbulence by giving access to information that can not be directly measured. Further demonstrations of the empirical relation between scales are shown, demonstrating how far the model can reconstruct small scales given the large ones. This is beneficial for turbulence modeling, since models can be trained from available datasets and give access to small scales in new situations. Follow-up works may use those information and improve the prediction of large scales, avoiding the use of crude turbulence models.
This work is also beneficial for data compression or compressive sensing purposes. It deals with the quality of approximate reconstruction of physical quantities given a certain amount of measurements. This is directly connected to another active research domain of 3D data compression of large databases in fluid mechanics. This work characterizes the expected information level given a certain amount of measurements. Reversely, it also characterizes how many measurements are required for a certain level of desired information.
\subsection{Organization and contributions}
The following parts of the thesis will be organized as follows:
\textbf{Chapter 1}. \textit{Problem definition}: This chapter shortly reviews the importance of turbulence studies, especially the challenging problem of understanding and modeling small-scale turbulence. The shortage of research tools to access those information is addressed, leading to the main motivation of this thesis: \textit{to propose computational methods to reconstruct small scales from available measurements}. Two problems are addressed and solved in this thesis: estimating small scales from large scales; and fusing available measurements to access higher information level. For each problem, a spectrum of potential methods are reviewed/proposed and compared to facilitate the usage in new situations.
\textbf{Chapter 2 and 3}. \textit{Estimating small scales from large scales}: These two chapters tackle the problem of seeking a mapping function that permits to estimate small-scale information from measurements of large scales.
Chapter 2 discusses the family of regression models. It reviews conventional methods such as ordinary least squares and other regularized regression models such as ridge regression, LASSO and kernel methods. Parameter optimization via cross-validation is also discussed as the way to choose the optimal set of parameters for each model.
Chapter 3 introduces the approach based on \textit{dictionary learning} method, which generalizes principal component analysis to permit sparsity and redundancy properties. To find the mapping, coupled dictionaries are learned to represent large and small scales. When only large-scale information are accessible, its representation is estimated and then combined with the dictionary of small scales learned \textit{a priori} to reconstruct those unknown details.
\textbf{Chapter 4 and 5}. \textit{Fusion of complementary measurements}: These two chapters aim at proposing fusion models to combine information from multi-source measurements to estimate small-scale information. We will focus on the situation where two sources of measurements are available: the high-temporal-low-spatial and low-temporal-high-spatial resolution data.
Chapter 4 proposes a model to propagate small scales from the low-temporal-high-spatial planes to other instants in time. The model is based on a non-local means filter, where small scales are propagated in time based on the similarity between larger scales from different planes. The estimation is done using a patch-based overlapping approach.
Chapter 5 proposes a Bayesian fusion model to combine the measurements in space and time. This model is constructed based on a Bayesian framework where a prior knowledge about the flow can be introduced into the estimation. Bayesian estimators are used to find the most probable high-resolution fields given the measurements. The final model is a simplified version, leading to a linear fusion model. This model contains two important ingredients, the local structures of the flow and the statistical parameters learned from data to encode the flow physics.
\textbf{Chapter 6} compares performances of proposed models on various datasets. Detailed analyses are performed to demonstrate benefits of each models compared to simple interpolations. The configuration of complementary measurements in space and time are studied, which permit to investigate all proposed models.
This work has been resulted in the following publication:
\begin{quote}
\citet{van2015bayesian}. ``A Bayesian fusion model for space-time reconstruction of finely resolved velocities in turbulent flows from low resolution measurements''. In: \emph{Journal of Statistical Mechanics: Theory and Experiment} 2015.10, P10008.
\end{quote}
and has presented at the following international/national conferences:
\begin{itemize}
\item \emph{15th European Turbulence conference}, Delft, Netherlands (August 2015)
\item \emph{GDR Turbulence}, Grenoble, France (June 2015)
\end{itemize}
All codes to reproduce the results of this work are available at \url{https://github.com/linhvannguyen/PhDworks/} |
The unit factor of a polynomial with a leading coefficient is the unit factor of the leading coefficient if the polynomial is constant, and the unit factor of the rest of the polynomial otherwise. |
/- Test cases for cooper, from John Harrison's Handbook of Practical Logic and Automated Reasoning. -/
import .main
set_option profiler true
/- Theorems -/
open tactic lia
example : ∃ (x : int), x < 1 :=
by cooper
example : ∀ (x : int), ∃ (y : int), y = x + 1 :=
by cooper_vm
example : ∀ (x : int), ∃ (y : int), (2 * y ≤ x ∧ x < 2 * (y + 1)) :=
by cooper_vm
example : ∀ (y : int), ((∃ (d : int), y = 2 * d) → (∃ (c : int), y = 1 * c)) :=
by cooper_vm
example : ∀ (x y z : int), (2 * x + 1 = 2 * y) → 129 < x + y + z :=
by cooper_vm
example : ∃ (x y : int), 5 * x + 3 * y = 1 :=
by cooper_vm
example : ∃ (w x y z : int), 2 * w + 3 * x + 4 * y + 5 * z = 1 :=
by cooper_vm
example : ∀ (x y : int), 6 * x = 5 * y → ∃ d, y = 3 * d :=
by cooper_vm
example : ∀ (x : int), (¬(∃ m, x = 2 * m) ∧ (∃ m, x = 3 * m + 1))
↔ ((∃ m, x = 12 * m + 1) ∨ (∃ m, x = 12 * m + 7)) :=
by cooper_vm
-- example : ∃ (l : int), ∀ (x : int),
-- x ≥ l → ∃ (u v : int), u ≥ 0 ∧ v ≥ 0 ∧ x = 3 * u + 5 * v :=
-- by cooper_vm -- timeout
/- Nontheorems -/
--example : ∃ (x y z : int), 4 * x - 6 * y = 1 :=
--by cooper_vm
-- example : ∀ (x y : int), x ≤ y → ((2 * x) + 1) < 2 * y :=
-- by cooper_vm
-- example : ∀ (a b : int), ∃ (x : int), a < 20 * x /\ 20 * x < b :=
-- by cooper_vm
-- example : ∃ (y : int), ∀ x, 2 ≤ x + 5 * y ∧ 2 ≤ 13 * x - y ∧ x + 3 ≤ 0 :=
-- by cooper_vm
-- example : ∀ (x y : int), ¬(x = 0) → 5 * y + 1 ≤ 6 * x ∨ 6 * x + 1 ≤ 5 * y :=
-- by cooper_vm
-- example : ∀ (z : int), 3 ≤ z → ∃ (x y : int), x ≥ 0 ∧ y ≥ 0 ∧ 3 * x + 5 * y = z :=
-- by cooper_vm -- timeout
-- example : ∃ (a b : int), a ≥ 2 ∧ b ≥ 2 ∧ ((2 * b = a) ∨ (2 * b = 3 * a + 1)) ∧ (a = b) :=
-- by cooper_vm |
module Test.Crayons
import Crayons
%access export
main : IO ()
main = do
putStrLn $ bright "bright" <+> dim "dim" <+> underscore "underscore" <+> blink "blink"
putStrLn $ black "black" <+> red "red" <+> green "green" <+> yellow "yellow" <+> blue "blue" <+>
magenta "magenta" <+> cyan "cyan" <+> white "white"
putStrLn $ bgBlack "black" <+> bgRed "red" <+> bgGreen "green" <+> bgYellow "yellow" <+> bgBlue "blue" <+>
bgMagenta "magenta" <+> bgCyan "cyan" <+> bgWhite "white"
|
function [] = aps_spectrometer_PWV_meris(batchfile)
% aps_spectrometer_PWV_comparison(datelist)
% Scipt to load meris data, mask out clouds. The meris data is assumed to
% be structured in date folders. The batchfile contains the full path to the
% meris files in these folders. Note that the first line of the batchfile should read "files".
%
%
% INPUTS:
% batchfile A txt file containing the full path and file names of the
% meris data that needs to be processed. The first
% line of this file should read "files". The data
% should be structured in date folders.
% xlims Limits in the x-direction, either in degrees
% ylims Limits in the y-direction, either in degrees
% smpres The output resolution, either in degrees
% Units needs to be consistend with xlims and ylims.
%
%
% By David Bekaert - University of Leeds
% August 2014
fig_test = 1; % when 1 show the dem as debug figure
if nargin<1
fprintf('aps_spectrometer_PWV_meris(batchfile) \n')
error('myApp:argChk', ['Not enough input arguments...\n'])
end
smpres = getparm_aps('region_res',1); % in degrees
xlims = getparm_aps('region_lon_range',1);
ylims = getparm_aps('region_lat_range',1);
stamps_processed = getparm_aps('stamps_processed',1);
%% the actual scripting
%bounds for all ifgs in degrees or in meters
xmin = xlims(1);
xmax = xlims(2);
ymin = ylims(1);
ymax = ylims(2);
% getting the number of files to be processed
files = char(textread(batchfile,'%s','headerlines',1));
ndates = size(files,1);
% loading the date information
if strcmp(stamps_processed,'y')
ps = load(getparm_aps('ll_matfile',1));
ifgs_dates = ps.day;
fprintf('Stamps processed structure \n')
else
ifgday_matfile = getparm_aps('ifgday_matfile',1);
ifgs_dates = load(ifgday_matfile);
ifgs_dates = ifgs_dates.ifgday;
ifgs_dates = reshape(ifgs_dates,[],1);
ifgs_dates = unique(ifgs_dates);
end
fprintf(['Lon range: ' num2str(xmin) ' -- ' num2str(xmax) ' degrees\n'])
fprintf(['Lat range: ' num2str(ymin) ' -- ' num2str(ymax) ' degrees\n'])
fprintf(['Output resolution is assumed to be ' num2str(smpres) ' degrees \n'])
% extracting the dates from the filenames
for k=1:ndates
[path,filename_temp,ext_temp] = fileparts(files(k,:));
clear filename_temp ext_temp
[path_temp,date,ext_temp] = fileparts(path);
clear path_temp ext_temp
% save the paths as structures to allow for variable path lengths
pathlist{k} = path;
clear path
% saving the date information
datelist(k,:) =date;
clear date
end
%start loop here to calculate atmos correction for each date
fprintf('Starting the masking and writing of the PWV for each SAR date \n')
for n = 1:ndates
file = [files(n,:)];
outfile_watervapor = [pathlist{n} filesep datelist(n,:) '_ZPWV_nointerp.xyz'];
% get info on meris file from tif
tifinfo = geotiffinfo(file);
mer_xmin = tifinfo.CornerCoords.X(1);
mer_xmax = tifinfo.CornerCoords.X(2);
mer_ymin = tifinfo.CornerCoords.Y(3);
mer_ymax = tifinfo.CornerCoords.Y(1);
mer_cols = tifinfo.Width;
mer_rows = tifinfo.Height;
mer_x = (mer_xmax - mer_xmin)/mer_cols;
mer_y = (mer_ymax - mer_ymin)/mer_rows;
% read in tif
meris=imread(file,'tif');
%% Calculate wet delay if desired
%do masking, interpolating etc here.
%convert flag matrix to long list of binary numbers e.g. 1000010000010000
flagbin = dec2bin(meris(:,:,33));
%% Generating cloud mask
%take certain bits of binary numbers (e.g. second bit, 1=cloud), and reshape
%into matrix mask
cloud = bin2dec(flagbin(:,2));
cloudmat=reshape(cloud,mer_rows,mer_cols);
cloudmat(cloudmat==1)=NaN;
% turn ones (i.e. mask pixels) into NaNs so when we multiply masks together,
% NaNs will penetrate through the stack
pconf = bin2dec(flagbin(:,23));
pconfmat=reshape(pconf,mer_rows,mer_cols);
pconfmat(pconfmat==1)=NaN;
lowp = bin2dec(flagbin(:,24));
lowpmat=reshape(lowp,mer_rows,mer_cols);
lowpmat(lowpmat==1)=NaN;
maskmat= cloudmat .*pconfmat .*lowpmat;
maskmat(isnan(maskmat))=1;
%extend mask edges
se = strel('square', 3);
maskmat = imdilate(maskmat,se);
maskmat(maskmat==1)=NaN;
maskmat(maskmat==0)=1;
%% loading and masking of the data
%load water vapour
watervap=meris(:,:,14); % g/cm^2 water vapour
%mask out dodgy pixels
corwatervap = watervap .*maskmat;
%% mask water additional
%%% aditonal masking
% water mask
water = bin2dec(flagbin(:,3));
water=reshape(water,mer_rows,mer_cols);
%decrease water mask edges, to make sure we do not remove land points
se = strel('square', 3);
water_new = imerode(water,se);
water_new(water_new==1)=NaN;
water_new(water_new==0)=1;
clear water
corwatervap = corwatervap.*water_new;
%% saving the data
fid = fopen('out.bin','w');
corwatervap = corwatervap';
fwrite(fid,corwatervap,'real*4');
fclose(fid);
% do gmt resample and cut
xyz2grd_cmd = ['xyz2grd -R',num2str(mer_xmin),'/',num2str(mer_xmax),'/',num2str(mer_ymin),'/',num2str(mer_ymax),' -I',num2str(mer_cols),'+/',num2str(mer_rows),'+ out.bin -Gtmp.grd -F -ZTLf'];
[a,b] = system(xyz2grd_cmd);
% downsample and output without interpolation files
grdsmp_cmd = ['grdsample -R',num2str(xmin),'/',num2str(xmax),'/',num2str(ymin),'/',num2str(ymax),' -I',num2str(smpres),' -F tmp.grd -Gtmp_smp.grd'];
[a,b]=system(grdsmp_cmd);
grd2xyz_cmd = ['grd2xyz -R',num2str(xmin),'/',num2str(xmax),'/',num2str(ymin),'/',num2str(ymax),' tmp_smp.grd -bo >' outfile_watervapor];
[a,b]=system(grd2xyz_cmd);
% load gaussian and nointerp back in, combine, and output as outfile_gauss
% opening the data file (not-interpolated)
nointfid = fopen(outfile_watervapor,'r');
data_vector = fread(nointfid,'double');
fclose(nointfid);
% reshaping into the right n column matrix
data = reshape(data_vector,3,[])';
noint = data(:,3);
xy = data(:,[1:2]);
clear data data_vector
% figure; scatter3(xy(:,1),xy(:,2),noint,15,noint,'filled'); view(0,90); axis equal; axis tight
% writing out the date again as a binary table
data_write = [xy noint]';
clear noint xy
%output
fid = fopen(outfile_watervapor,'w');
fwrite(fid,data_write,'double');
fclose(fid);
clear data_write
fprintf([num2str(n) ' completed out of ' num2str(ndates) '\n'])
end
[a b] = system('!rm tmp.grd tmp.xyz out.bin tmp2.grd tmp_fil.grd tmp_smp.grd tmp_smp.xyz tmp_smp2.grd tmp_smp_fil.grd');
|
{-
This second-order term syntax was created from the following second-order syntax description:
syntax CommGroup | CG
type
* : 0-ary
term
unit : * | ε
add : * * -> * | _⊕_ l20
neg : * -> * | ⊖_ r40
theory
(εU⊕ᴸ) a |> add (unit, a) = a
(εU⊕ᴿ) a |> add (a, unit) = a
(⊕A) a b c |> add (add(a, b), c) = add (a, add(b, c))
(⊖N⊕ᴸ) a |> add (neg (a), a) = unit
(⊖N⊕ᴿ) a |> add (a, neg (a)) = unit
(⊕C) a b |> add(a, b) = add(b, a)
-}
module CommGroup.Syntax where
open import SOAS.Common
open import SOAS.Context
open import SOAS.Variable
open import SOAS.Families.Core
open import SOAS.Construction.Structure
open import SOAS.ContextMaps.Inductive
open import SOAS.Metatheory.Syntax
open import CommGroup.Signature
private
variable
Γ Δ Π : Ctx
α : *T
𝔛 : Familyₛ
-- Inductive term declaration
module CG:Terms (𝔛 : Familyₛ) where
data CG : Familyₛ where
var : ℐ ⇾̣ CG
mvar : 𝔛 α Π → Sub CG Π Γ → CG α Γ
ε : CG * Γ
_⊕_ : CG * Γ → CG * Γ → CG * Γ
⊖_ : CG * Γ → CG * Γ
infixl 20 _⊕_
infixr 40 ⊖_
open import SOAS.Metatheory.MetaAlgebra ⅀F 𝔛
CGᵃ : MetaAlg CG
CGᵃ = record
{ 𝑎𝑙𝑔 = λ where
(unitₒ ⋮ _) → ε
(addₒ ⋮ a , b) → _⊕_ a b
(negₒ ⋮ a) → ⊖_ a
; 𝑣𝑎𝑟 = var ; 𝑚𝑣𝑎𝑟 = λ 𝔪 mε → mvar 𝔪 (tabulate mε) }
module CGᵃ = MetaAlg CGᵃ
module _ {𝒜 : Familyₛ}(𝒜ᵃ : MetaAlg 𝒜) where
open MetaAlg 𝒜ᵃ
𝕤𝕖𝕞 : CG ⇾̣ 𝒜
𝕊 : Sub CG Π Γ → Π ~[ 𝒜 ]↝ Γ
𝕊 (t ◂ σ) new = 𝕤𝕖𝕞 t
𝕊 (t ◂ σ) (old v) = 𝕊 σ v
𝕤𝕖𝕞 (mvar 𝔪 mε) = 𝑚𝑣𝑎𝑟 𝔪 (𝕊 mε)
𝕤𝕖𝕞 (var v) = 𝑣𝑎𝑟 v
𝕤𝕖𝕞 ε = 𝑎𝑙𝑔 (unitₒ ⋮ tt)
𝕤𝕖𝕞 (_⊕_ a b) = 𝑎𝑙𝑔 (addₒ ⋮ 𝕤𝕖𝕞 a , 𝕤𝕖𝕞 b)
𝕤𝕖𝕞 (⊖_ a) = 𝑎𝑙𝑔 (negₒ ⋮ 𝕤𝕖𝕞 a)
𝕤𝕖𝕞ᵃ⇒ : MetaAlg⇒ CGᵃ 𝒜ᵃ 𝕤𝕖𝕞
𝕤𝕖𝕞ᵃ⇒ = record
{ ⟨𝑎𝑙𝑔⟩ = λ{ {t = t} → ⟨𝑎𝑙𝑔⟩ t }
; ⟨𝑣𝑎𝑟⟩ = refl
; ⟨𝑚𝑣𝑎𝑟⟩ = λ{ {𝔪 = 𝔪}{mε} → cong (𝑚𝑣𝑎𝑟 𝔪) (dext (𝕊-tab mε)) } }
where
open ≡-Reasoning
⟨𝑎𝑙𝑔⟩ : (t : ⅀ CG α Γ) → 𝕤𝕖𝕞 (CGᵃ.𝑎𝑙𝑔 t) ≡ 𝑎𝑙𝑔 (⅀₁ 𝕤𝕖𝕞 t)
⟨𝑎𝑙𝑔⟩ (unitₒ ⋮ _) = refl
⟨𝑎𝑙𝑔⟩ (addₒ ⋮ _) = refl
⟨𝑎𝑙𝑔⟩ (negₒ ⋮ _) = refl
𝕊-tab : (mε : Π ~[ CG ]↝ Γ)(v : ℐ α Π) → 𝕊 (tabulate mε) v ≡ 𝕤𝕖𝕞 (mε v)
𝕊-tab mε new = refl
𝕊-tab mε (old v) = 𝕊-tab (mε ∘ old) v
module _ (g : CG ⇾̣ 𝒜)(gᵃ⇒ : MetaAlg⇒ CGᵃ 𝒜ᵃ g) where
open MetaAlg⇒ gᵃ⇒
𝕤𝕖𝕞! : (t : CG α Γ) → 𝕤𝕖𝕞 t ≡ g t
𝕊-ix : (mε : Sub CG Π Γ)(v : ℐ α Π) → 𝕊 mε v ≡ g (index mε v)
𝕊-ix (x ◂ mε) new = 𝕤𝕖𝕞! x
𝕊-ix (x ◂ mε) (old v) = 𝕊-ix mε v
𝕤𝕖𝕞! (mvar 𝔪 mε) rewrite cong (𝑚𝑣𝑎𝑟 𝔪) (dext (𝕊-ix mε))
= trans (sym ⟨𝑚𝑣𝑎𝑟⟩) (cong (g ∘ mvar 𝔪) (tab∘ix≈id mε))
𝕤𝕖𝕞! (var v) = sym ⟨𝑣𝑎𝑟⟩
𝕤𝕖𝕞! ε = sym ⟨𝑎𝑙𝑔⟩
𝕤𝕖𝕞! (_⊕_ a b) rewrite 𝕤𝕖𝕞! a | 𝕤𝕖𝕞! b = sym ⟨𝑎𝑙𝑔⟩
𝕤𝕖𝕞! (⊖_ a) rewrite 𝕤𝕖𝕞! a = sym ⟨𝑎𝑙𝑔⟩
-- Syntax instance for the signature
CG:Syn : Syntax
CG:Syn = record
{ ⅀F = ⅀F
; ⅀:CS = ⅀:CompatStr
; mvarᵢ = CG:Terms.mvar
; 𝕋:Init = λ 𝔛 → let open CG:Terms 𝔛 in record
{ ⊥ = CG ⋉ CGᵃ
; ⊥-is-initial = record { ! = λ{ {𝒜 ⋉ 𝒜ᵃ} → 𝕤𝕖𝕞 𝒜ᵃ ⋉ 𝕤𝕖𝕞ᵃ⇒ 𝒜ᵃ }
; !-unique = λ{ {𝒜 ⋉ 𝒜ᵃ} (f ⋉ fᵃ⇒) {x = t} → 𝕤𝕖𝕞! 𝒜ᵃ f fᵃ⇒ t } } } }
-- Instantiation of the syntax and metatheory
open Syntax CG:Syn public
open CG:Terms public
open import SOAS.Families.Build public
open import SOAS.Syntax.Shorthands CGᵃ public
open import SOAS.Metatheory CG:Syn public
|
######################################################################
`is_element/P2` := (N::posint) -> (A::set) -> proc(u)
local n,A2,ab,ba,v,i;
global reason;
if not(type(u,table)) then
reason := [convert(procname,string),"u is not a table",u];
return false;
fi;
n := nops(A);
A2 := `list_elements/pairs`(A);
if {indices(u)} <> {op(A2)} then
reason := [convert(procname,string),"u is not indexed by pairs in A",u,A2];
return false;
fi;
for ab in A2 do
v := u[op(ab)];
if not(`is_element/R`(N)(v)) then
reason := [convert(procname,string),"u[a,b] is not in R^N",op(ab),v,N];
return false;
fi;
if simplify(add(v[i]^2,i=1..N) - 1) <> 0 then
reason := [convert(procname,string),"u[a,b] is not in S^(N-1)",op(ab),v,N];
return false;
fi;
od;
for ab in A2 do
ba := [ab[2],ab[1]];
if u[op(ab)] +~ u[op(ba)] <> [0$N] then
reason := [convert(procname,string),"u[a,b]+u[b,a] <> 0",op(ab),u[op(ab)],u[op(ba)],N];
return false;
fi;
od;
return true;
end:
`phi2/Fbar/P2` := (N::posint) -> (A::set) -> proc(x)
local A2,u,ab,a,b,f;
A2 := `list_elements/pairs`(A);
u := table();
for ab in A2 do
a,b := op(ab);
f := `normalise_2/F`(N)({a,b})(x[{op(ab)}]);
u[op(ab)] := combine(sqrt(2) *~ f[b]);
od:
return(eval(u));
end:
|
#!/usr/bin/env python3
############################################################################################
#
#
############################################################################################
import os
import cv2
import time
import math
import numpy as np
import pyrealsense2 as rs
from pathlib import Path
import sys
import tf2_ros
import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile
from rclpy.qos import qos_profile_sensor_data
from sensor_msgs.msg import PointCloud2, PointField
from std_msgs.msg import Header
from geometry_msgs.msg import TransformStamped
################################# CLASS INITIALIZATION #####################################
np.set_printoptions(threshold=sys.maxsize)
class RealsenseCamera:
'''
Abstraction of any RealsenseCamera. From https://github.com/ivomarvan/
samples_and_experiments/blob/master/Multiple_realsense_cameras/multiple_realsense_cameras.py
'''
_colorizer = rs.colorizer()
def __init__(
self,
serial_number :str,
name: str,
point_cloud_only: bool
):
self._serial_number = serial_number
self._name = name
self._pipeline = None
self._started = False
self._pc_only = point_cloud_only
self.__start_pipeline()
def __del__(self):
if self._started and not self._pipeline is None:
self._pipeline.stop()
def get_full_name(self):
return f'{self._name} ({self._serial_number})'
def __start_pipeline(self):
# Configure depth and color streams
self._pipeline = rs.pipeline()
config = rs.config()
if self._pc_only:
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
#self.decimate = rs.decimation_filter(1)
config.enable_device(self._serial_number)
start_attempt = False
while start_attempt == False:
try:
self._pipeline.start(config)
start_attempt = True
except RuntimeError:
print("Device not connected. Connect your Intel RealSense camera")
self._started = True
print(f'{self.get_full_name()} camera is ready.')
def get_frames(self) -> [rs.frame]:
'''
Return a frame do not care about type
'''
frameset = self._pipeline.wait_for_frames()
if frameset:
return [f for f in frameset]
else:
return []
def get_frameset(self) -> rs.frame:
return self._pipeline.wait_for_frames()
def get_depth_frame(self) -> rs.depth_frame:
frameset = self._pipeline.wait_for_frames()
return frameset.get_depth_frame()
@classmethod
def get_title(cls, frame: rs.frame, whole: bool) -> str:
# <pyrealsense2.video_stream_profile: Fisheye(2) 848x800 @ 30fps Y8>
profile_str = str(frame.profile)
first_space_pos = profile_str.find(' ')
whole_title = profile_str[first_space_pos + 1: -1]
if whole:
return whole_title
return whole_title.split(' ')[0]
@classmethod
def get_images_from_video_frames(cls, frames: [rs.frame]) -> ([(np.ndarray, rs.frame)] , [rs.frame], int, int):
'''
From all the frames, it selects those that can be easily interpreted as pictures.
Converts them to images and finds the maximum width and maximum height from all of them.
'''
max_width = -1
max_height = -1
img_frame_tuples = []
unused_frames = []
for frame in frames:
if frame.is_video_frame():
if frame.is_depth_frame():
img = np.asanyarray(RealsenseCamera._colorizer.process(frame).get_data())
else:
img = np.asanyarray(frame.get_data())
img = img[...,::-1].copy() # RGB<->BGR
max_height = max(max_height, img.shape[0])
max_width = max(max_width, img.shape[1])
img_frame_tuples.append((img,frame))
else:
unused_frames.append(frame)
return img_frame_tuples, unused_frames, max_width, max_height
class AllCamerasLoop:
'''
Take info from all connected cameras in the loop. From https://github.com/ivomarvan/
samples_and_experiments/blob/master/Multiple_realsense_cameras/multiple_realsense_cameras.py
'''
def __init__(self, point_cloud_only: False):
self._cameras = self.get_all_connected_cameras(point_cloud_only)
def get_frames(self) -> [rs.frame]:
'''
Return frames in given order.
'''
ret_frames = []
for camera in self._cameras:
frames = camera.get_frames()
if frames:
ret_frames += frames
return ret_frames
def get_depth_frames(self) -> [rs.depth_frame]:
ret_frames = []
for camera in self._cameras:
frame = camera.get_depth_frame()
if frame:
ret_frames.append(frame)
return ret_frames
def __get_window_name(self):
s = ''
for camera in self._cameras:
if s:
s += ', '
s += camera.get_full_name()
return s
def __get_connected_cameras_info(self, camera_name_suffix: str = 'T265') -> [(str, str)]:
'''
Return list of (serial number,names) conected devices.
Eventualy only fit given suffix (like T265, D415, ...)
(based on https://github.com/IntelRealSense/librealsense/issues/2332)
'''
ret_list = []
ctx = rs.context()
for d in ctx.devices:
serial_number = d.get_info(rs.camera_info.serial_number)
name = d.get_info(rs.camera_info.name)
if camera_name_suffix and not name.endswith(camera_name_suffix):
continue
ret_list.append((serial_number, name))
return ret_list
def get_all_connected_cameras(self, point_cloud_only: bool) -> [RealsenseCamera]:
cameras = self.__get_connected_cameras_info(camera_name_suffix=None)
return [RealsenseCamera(serial_number, name, point_cloud_only) for serial_number, name in cameras]
def run_loop(self):
stop = False
window = ImgWindow(name=self.__get_window_name())
while not stop:
frames = self.get_frames()
window.swow(self.__frames_interpreter.get_image_from_frames(frames))
stop = window.is_stopped()
class Publisher(Node):
time_it = False
# Initialization of the class
def __init__(self, multiple_cameras=False):
super().__init__('cloud_publisher')
# Initialize logs level
try:
log_level = int(os.environ['LOG_LEVEL'])
except:
log_level = 20
self.get_logger().info("LOG_LEVEL not defined, setting default: INFO")
# Initialize RealSense cameras
self.camera_loop = AllCamerasLoop(point_cloud_only=True)
# Initialize variables
qos = QoSProfile(depth=10)
pointcloud_topic = '/camera/cloud'
print(f"Publish pointcloud on topic {pointcloud_topic}")
self.point_cloud = rs.pointcloud()
self.mean_time = 0.0
self.n_data = 0
#node = rclpy.create_node('robot_depth_tf_broadcaster')
self.br = tf2_ros.StaticTransformBroadcaster(self)
# Create publisher
self.pc_pub = self.create_publisher(
PointCloud2,
pointcloud_topic,
qos)
self.pc_pub_rot = self.create_publisher(
PointCloud2,
"/camera/cloud_rot",
qos)
self.get_logger().info("Initializing process")
self.theta = 3.1416/6
self.xTransl = -0.5
self.RotTranslMat = np.matrix([[math.cos(self.theta), -math.sin(self.theta), 0, 0],
[math.sin(self.theta), math.cos(self.theta), 0, 0],
[0, 0, 1, self.xTransl],
[0, 0, 0, 1]])
self.RotMat = np.matrix([[1.0, .0, .0], [.0, math.cos(self.theta), -math.sin(self.theta)],
[.0, math.sin(self.theta), math.cos(self.theta)]
])
self.process()
#################################### MAIN METHODS ##########################################
def process(self):
while True:
self.depth_method()
def depth_method(self):
# Get the depth frame and publish the pointcloud and the reference frame transform
depth_frames = self.camera_loop.get_depth_frames()
#depth_frame = frames.get_depth_frame()
if time_it:
begin = time.time()
#depth_frame = self.decimate.process(depth_frame)
points = self.point_cloud.calculate(depth_frames[0])
v = points.get_vertices()
verts = np.asanyarray(v).view(np.float32).reshape(-1, 3)
verts_trans = np.transpose(verts.copy())
verts_trans[1, :] += self.xTransl
verts_rot = np.transpose(np.dot(self.RotMat, verts_trans))
pc_msg = self.point_cloud_message(verts, "depth_frame")
pc_msg_rot = self.point_cloud_message(verts_rot, "depth_frame")
self.pc_pub.publish(pc_msg)
self.pc_pub_rot.publish(pc_msg_rot)
self.publish_tf_transform
if time_it:
end = time.time()
if self.mean_time == 0.0:
self.mean_time = end - begin
self.n_data = 1
else:
self.mean_time = (self.mean_time * self.n_data + end - begin) / (self.n_data + 1)
self.n_data += 1
if self.n_data % 20 == 0:
self.get_logger().debug(f"Mean computing time: {self.mean_time:.3f}")
def publish_tf_transform(self):
self.br.sendTransform(self.tf_message_camera0(pc_msg.header.stamp))
def tf_message_camera0(self, stamp):
tf_msg = TransformStamped()
tf_msg.header.stamp = stamp
tf_msg.header.frame_id = "base_link"
quat = self.quaternion_from_euler(-1.5708, 0, -1.5708)
tf_msg.child_frame_id = "depth_frame"
tf_msg.transform.translation.x = 0.0
tf_msg.transform.translation.y = 0.0
tf_msg.transform.translation.z = 0.10
tf_msg.transform.rotation.x = quat[0]
tf_msg.transform.rotation.y = quat[1]
tf_msg.transform.rotation.z = quat[2]
tf_msg.transform.rotation.w = quat[3]
return tf_msg
def point_cloud_message(self, points, parent_frame):
""" Creates a point cloud message.
Args:
points: Nx3 array of xyz positions.
parent_frame: frame in which the point cloud is defined
Returns:
sensor_msgs/PointCloud2 message
From: https://github.com/SebastianGrans/ROS2-Point-Cloud-Demo/blob/master/pcd_demo/pcd_publisher/pcd_publisher_node.py
Code source:
https://gist.github.com/pgorczak/5c717baa44479fa064eb8d33ea4587e0
References:
http://docs.ros.org/melodic/api/sensor_msgs/html/msg/PointCloud2.html
http://docs.ros.org/melodic/api/sensor_msgs/html/msg/PointField.html
http://docs.ros.org/melodic/api/std_msgs/html/msg/Header.html
"""
# In a PointCloud2 message, the point cloud is stored as an byte
# array. In order to unpack it, we also include some parameters
# which desribes the size of each individual point.
ros_dtype = PointField.FLOAT32
dtype = np.float32
itemsize = np.dtype(dtype).itemsize # A 32-bit float takes 4 bytes.
data = points.astype(dtype).tobytes()
# The fields specify what the bytes represents. The first 4 bytes
# represents the x-coordinate, the next 4 the y-coordinate, etc.
fields = [PointField(
name=n, offset=i * itemsize, datatype=ros_dtype, count=1)
for i, n in enumerate('xyz')]
# The PointCloud2 message also has a header which specifies which
# coordinate frame it is represented in.
header = Header(stamp=self.get_clock().now().to_msg(), frame_id=parent_frame)
return PointCloud2(
header=header,
height=1,
width=points.shape[0],
is_dense=True,
is_bigendian=False,
fields=fields,
point_step=(itemsize * 3), # Every point consists of three float32s.
row_step=(itemsize * 3 * points.shape[0]),
data=data
)
@staticmethod
def quaternion_from_euler(yaw, pitch, roll):
#From http://docs.ros.org/en/jade/api/tf2/html/Quaternion_8h_source.html
half_yaw = yaw * 0.5
half_pitch = pitch * 0.5
half_roll = roll * 0.5
cos_yaw = math.cos(half_yaw);
sin_yaw = math.sin(half_yaw);
cos_pitch = math.cos(half_pitch);
sin_pitch = math.sin(half_pitch);
cos_roll = math.cos(half_roll);
sin_roll = math.sin(half_roll);
quat = (sin_roll * cos_pitch * cos_yaw - cos_roll * sin_pitch * sin_yaw, #x
cos_roll * sin_pitch * cos_yaw + sin_roll * cos_pitch * sin_yaw, #y
cos_roll * cos_pitch * sin_yaw - sin_roll * sin_pitch * cos_yaw, #z
cos_roll * cos_pitch * cos_yaw + sin_roll * sin_pitch * sin_yaw) #w
norm = math.sqrt(quat[0] * quat[0] + quat[1] * quat[1] + quat[2] * quat[2]
+ quat[3] * quat[3])
norm_quat = [entry / norm for entry in quat]
return norm_quat
def get_camera_extrinsics(self):
''' Method that gets the camera extrinsics for each camera serial number, from a yaml file
'''
return
################################# MAIN #############################################
def main(multiple_cameras=False):
rclpy.init()
publisher = Publisher(multiple_cameras=False)
try:
rclpy.spin(publisher)
except KeyboardInterrupt:
publisher.get_logger().info("Shutting down")
publisher.pipe.stop()
publisher.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
|
[STATEMENT]
lemma (in is_tm_cat_obj_prod) is_tm_cat_obj_coprod_op'[cat_op_intros]:
assumes "\<CC>' = op_cat \<CC>"
shows "op_ntcf \<pi> : A >\<^sub>C\<^sub>F\<^sub>.\<^sub>t\<^sub>m\<^sub>.\<^sub>\<Coprod> P : I \<mapsto>\<mapsto>\<^sub>C\<^sub>.\<^sub>t\<^sub>m\<^bsub>\<alpha>\<^esub> \<CC>'"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. op_ntcf \<pi> : A >\<^sub>C\<^sub>F\<^sub>.\<^sub>t\<^sub>m\<^sub>.\<^sub>\<Coprod> P : I \<mapsto>\<mapsto>\<^sub>C\<^sub>.\<^sub>t\<^sub>m\<^bsub>\<alpha>\<^esub> \<CC>'
[PROOF STEP]
unfolding assms
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. op_ntcf \<pi> : A >\<^sub>C\<^sub>F\<^sub>.\<^sub>t\<^sub>m\<^sub>.\<^sub>\<Coprod> P : I \<mapsto>\<mapsto>\<^sub>C\<^sub>.\<^sub>t\<^sub>m\<^bsub>\<alpha>\<^esub> op_cat \<CC>
[PROOF STEP]
by (rule is_tm_cat_obj_coprod_op) |
"""
Levels(:a => ["yes", "no"])
Return a copy of the table with specified levels and orders for categorical columns
allowing only changing the order of the column.
# Examples
```julia
Levels(:a => ["yes, "no"], :c => [1, 2, 4], :d => ["a", "b", "c"])
Levels("a" => ["yes", "no"], "c" => [1, 2, 4], ordered = ["a", "c"])
Levels(:a => ["yes", "no"], :c => [1, 2, 4], :d => [1, 23, 5, 7], ordered = [:a, :b, :c])
```
"""
struct Levels{K} <: Stateless
levelspec::K
ordered::Vector{Symbol}
end
Levels(pairs::Pair{Symbol}...; ordered=Symbol[]) =
Levels(NamedTuple(pairs), ordered)
Levels(pairs::Pair{K}...; ordered=K[]) where {K<:AbstractString} =
Levels(NamedTuple(Symbol(k) => v for (k,v) in pairs), Symbol.(ordered))
isrevertible(transform::Levels) = true
# when the col is already a categorical array and wanna change levels and order
_categorify(l::AbstractVector, x::CategoricalVector, o) =
categorical(x, levels=l, ordered=o), levels(x)
# when the col is normal array and want to change to categorical array
_categorify(l::AbstractVector, x::AbstractVector, o) =
categorical(x, levels=l, ordered=o), unwrap
# when the col is not need for change or convert back to normal array
_categorify(f::Function, x::AbstractVector, o) =
o ? (categorical(x, ordered=true), levels(x)) : (f.(x), f)
function apply(transform::Levels, table)
cols = Tables.columns(table)
names = Tables.columnnames(cols)
result = map(names) do nm
x = Tables.getcolumn(cols, nm)
l = get(transform.levelspec, nm, identity)
o = nm ∈ transform.ordered
_categorify(l, x, o)
end
categ = first.(result)
cache = last.(result)
𝒯 = (; zip(names, categ)...)
newtable = 𝒯 |> Tables.materializer(table)
newtable, cache
end
function revert(transform::Levels, newtable, cache)
cols = Tables.columns(newtable)
names = Tables.columnnames(cols)
ocols = map(zip(cache, names)) do (f, nm)
x = Tables.getcolumn(cols, nm)
c, _ = _categorify(f, x, false)
c
end
𝒯 = (; zip(names, ocols)...)
𝒯 |> Tables.materializer(newtable)
end |
Chiltern District Council aims to develop activities and improve access into local services for adults and older people. There are an incredible range of community groups and professional agencies that provide invaluable services across the district.
There are also a number of clubs in Chiltern specifically designed for people approaching or already retired, including several that provide a door to door service. Activities available include exercise, visits to places of interest, shopping trips, or simply tea and biscuits and a chance to socialise. For further details about these clubs contact the Community Team on 01494 732058.
A number of services are also available across the district. Find out what resources are available to develop new skills through adult and community education or see what support is available to you via the offsite links below. |
[STATEMENT]
lemma path_connectedin_Euclidean_complements:
assumes "closedin (Euclidean_space n) S" "closedin (Euclidean_space n) T"
"(subtopology (Euclidean_space n) S) homeomorphic_space (subtopology (Euclidean_space n) T)"
shows "path_connectedin (Euclidean_space n) (topspace(Euclidean_space n) - S)
\<longleftrightarrow> path_connectedin (Euclidean_space n) (topspace(Euclidean_space n) - T)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. path_connectedin (Euclidean_space n) (topspace (Euclidean_space n) - S) = path_connectedin (Euclidean_space n) (topspace (Euclidean_space n) - T)
[PROOF STEP]
by (meson Diff_subset assms isomorphic_homology_groups_Euclidean_complements isomorphic_homology_imp_path_connectedness path_connectedin_def) |
/*
@copyright Louis Dionne 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#include <boost/hana/detail/assert.hpp>
#include <boost/hana/detail/constexpr.hpp>
#include <boost/hana/integral.hpp>
#include <boost/hana/list/instance.hpp>
#include <boost/hana/range.hpp>
using namespace boost::hana;
using namespace literals;
int main() {
//! [main]
BOOST_HANA_CONSTEXPR_LAMBDA auto negative = [](auto x) {
return x < int_<0>;
};
BOOST_HANA_CONSTANT_ASSERT(
drop_while(negative, range(int_<-3>, int_<6>)) == range(int_<0>, int_<6>)
);
BOOST_HANA_CONSTANT_ASSERT(
drop_while(negative, list(1_c, -2_c, 4_c, 5_c)) == list(1_c, -2_c, 4_c, 5_c)
);
//! [main]
}
|
(* TODO: Port to new Collection Framework *)
section "Implementing Finite Automata using Labelled Transition Systems"
theory NFAByLTS
imports "../../Collections/ICF/Collections"
"../../Accessible_Impl"
"../Hopcroft_Minimisation"
"../NFAConstruct"
LTSSpec LTSGA NFASpec LTS_Impl TripleSetByMap LTSByTripleSetAQQ NFAGA
begin
subsection \<open> Locales for NFAs, DFAs \<close>
record nfa_props =
nfa_prop_is_complete_deterministic :: bool
nfa_prop_is_initially_connected :: bool
lemmas nfa_props_fields_def[code, simp] = nfa_props.defs(2)
abbreviation "nfa_props_trivial == nfa_props.fields False False"
abbreviation "nfa_props_connected det == nfa_props.fields det True"
abbreviation "nfa_props_dfa == nfa_props.fields True True"
type_synonym ('q_set, 'a_set, 'd) NFA_impl =
"'q_set \<times> 'a_set \<times> 'd \<times> 'q_set \<times> 'q_set \<times> nfa_props"
locale nfa_by_lts_defs =
s: StdSet s_ops (* Set operations on states *) +
l: StdSet l_ops (* Set operations on labels *) +
d: StdLTS d_ops (* An LTS *)
for s_ops::"('q::{automaton_states},'q_set,_) set_ops_scheme"
and l_ops::"('a,'a_set,_) set_ops_scheme"
and d_ops::"('q,'a,'d,_) lts_ops_scheme"
context nfa_by_lts_defs
begin
definition nfa_states :: "'q_set \<times> 'a_set \<times> 'd \<times> 'q_set \<times> 'q_set \<times> nfa_props \<Rightarrow> 'q_set" where
"nfa_states A = fst A"
lemma nfa_states_simp [simp]: "nfa_states (Q, A, D, I, F, flags) = Q" by (simp add: nfa_states_def)
definition nfa_labels :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> 'a_set" where
"nfa_labels A = fst (snd A)"
lemma nfa_labels_simp [simp]: "nfa_labels (Q, A, D, I, F, flags) = A" by (simp add: nfa_labels_def)
definition nfa_trans :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> 'd" where
"nfa_trans A = fst (snd (snd A))"
lemma nfa_trans_simp [simp]: "nfa_trans (Q, A, D, I, F, flags) = D" by (simp add: nfa_trans_def)
definition nfa_initial :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> 'q_set" where
"nfa_initial A = fst (snd (snd (snd A)))"
lemma nfa_initial_simp [simp]: "nfa_initial (Q, A, D, I, F, flags) = I" by (simp add: nfa_initial_def)
definition nfa_accepting :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> 'q_set" where
"nfa_accepting A = fst (snd (snd (snd (snd A))))"
lemma nfa_accepting_simp [simp]: "nfa_accepting (Q, A, D, I, F, flags) = F" by (simp add: nfa_accepting_def)
definition nfa_props :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> nfa_props" where
"nfa_props A = (snd (snd (snd (snd (snd A)))))"
lemma nfa_props_simp [simp]: "nfa_props (Q, A, D, I, F, flags) = flags" by (simp add: nfa_props_def)
fun nfa_set_props :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> nfa_props \<Rightarrow> ('q_set, 'a_set, 'd) NFA_impl" where
"nfa_set_props (Q, A, D, I, F, p) p' = (Q, A, D, I, F, p')"
lemmas nfa_selectors_def = nfa_accepting_def nfa_states_def nfa_labels_def nfa_trans_def nfa_initial_def
nfa_props_def
definition nfa_\<alpha> :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> ('q, 'a) NFA_rec" where
"nfa_\<alpha> A =
\<lparr> \<Q> = s.\<alpha> (nfa_states A),
\<Sigma> = l.\<alpha> (nfa_labels A),
\<Delta> = d.\<alpha> (nfa_trans A),
\<I> = s.\<alpha> (nfa_initial A),
\<F> = s.\<alpha> (nfa_accepting A) \<rparr>"
lemma nfa_\<alpha>_simp [simp] :
"\<Q> (nfa_\<alpha> A) = s.\<alpha> (nfa_states A) \<and>
\<Sigma> (nfa_\<alpha> A) = l.\<alpha> (nfa_labels A) \<and>
\<Delta> (nfa_\<alpha> A) = d.\<alpha> (nfa_trans A) \<and>
\<I> (nfa_\<alpha> A) = s.\<alpha> (nfa_initial A) \<and>
\<F> (nfa_\<alpha> A) = s.\<alpha> (nfa_accepting A)"
by (simp add: nfa_\<alpha>_def)
definition nfa_invar_no_props :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> bool" where
"nfa_invar_no_props A =
(s.invar (nfa_states A) \<and>
l.invar (nfa_labels A) \<and>
d.invar (nfa_trans A) \<and>
s.invar (nfa_initial A) \<and>
s.invar (nfa_accepting A))"
definition nfa_invar_weak :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> bool" where
"nfa_invar_weak A \<equiv> (nfa_invar_no_props A \<and> NFA (nfa_\<alpha> A))"
definition nfa_invar_props :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> bool" where
"nfa_invar_props A \<longleftrightarrow>
(nfa_prop_is_complete_deterministic (nfa_props A) \<longrightarrow> SemiAutomaton_is_complete_deterministic (nfa_\<alpha> A)) \<and>
(nfa_prop_is_initially_connected (nfa_props A) \<longrightarrow> SemiAutomaton_is_initially_connected (nfa_\<alpha> A))"
definition nfa_invar_weak2 :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> bool" where
"nfa_invar_weak2 A \<equiv> (nfa_invar_no_props A \<and> nfa_invar_props A)"
lemma nfa_props_trivial_OK:
"nfa_props A = nfa_props_trivial \<Longrightarrow> nfa_invar_props A"
unfolding nfa_invar_props_def by simp
lemma nfa_props_trivial_OK_simp[simp]:
"nfa_invar_props (Q, A, D, I, F, nfa_props_trivial)"
unfolding nfa_invar_props_def by simp
definition nfa_invar :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> bool" where
"nfa_invar A \<equiv> (nfa_invar_weak A \<and> nfa_invar_props A)"
lemma nfa_invar_alt_def :
"nfa_invar A = (nfa_invar_no_props A \<and> NFA (nfa_\<alpha> A) \<and> nfa_invar_props A)"
unfolding nfa_invar_def nfa_invar_weak_def by simp
lemma nfa_invar_full_def :
"nfa_invar A =
(set_op_invar s_ops (nfa_states A) \<and>
set_op_invar l_ops (nfa_labels A) \<and>
lts_op_invar d_ops (nfa_trans A) \<and>
set_op_invar s_ops (nfa_initial A) \<and>
set_op_invar s_ops (nfa_accepting A) \<and>
NFA (nfa_\<alpha> A) \<and>
(nfa_prop_is_complete_deterministic (nfa_props A) \<longrightarrow>
SemiAutomaton_is_complete_deterministic (nfa_\<alpha> A)) \<and>
(nfa_prop_is_initially_connected (nfa_props A) \<longrightarrow>
SemiAutomaton_is_initially_connected (nfa_\<alpha> A)))"
unfolding nfa_invar_alt_def nfa_invar_no_props_def nfa_invar_props_def
by simp
lemma nfa_invar_implies_DFA :
"nfa_invar A \<Longrightarrow> nfa_prop_is_complete_deterministic (nfa_props A) \<Longrightarrow> DFA (nfa_\<alpha> A)"
unfolding nfa_invar_alt_def DFA_alt_def nfa_invar_props_def by simp
lemma nfa_by_lts_correct [simp]:
"nfa nfa_\<alpha> nfa_invar"
unfolding nfa_def nfa_invar_alt_def
by simp
subsection \<open> Constructing Automata \<close>
definition nfa_construct_aux ::
"('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> 'q \<times> 'a list \<times> 'q \<Rightarrow>
('q_set, 'a_set, 'd) NFA_impl" where
"nfa_construct_aux = (\<lambda>(Q, A, D, I, F, props) (q1, l, q2).
(s.ins q1 (s.ins q2 Q),
foldl (\<lambda>s x. l.ins x s) A l,
foldl (\<lambda>d a. d.add q1 a q2 d) D l,
I, F, props))"
lemma nfa_construct_aux_correct :
fixes q1 q2
assumes invar: "nfa_invar_no_props A"
shows "nfa_invar_no_props (nfa_construct_aux A (q1, l, q2))"
"nfa_props (nfa_construct_aux A (q1, l, q2)) = nfa_props A"
"nfa_\<alpha> (nfa_construct_aux A (q1, l, q2)) =
construct_NFA_aux (nfa_\<alpha> A) (q1, l, q2)"
proof -
obtain QL AL DL IL FL p where A_eq[simp]: "A = (QL, AL, DL, IL, FL, p)" by (cases A, blast)
have AL_OK: "l.invar AL \<Longrightarrow>
l.invar (foldl (\<lambda>s x. l.ins x s) AL l) \<and>
l.\<alpha> (foldl (\<lambda>s x. l.ins x s) AL l) = l.\<alpha> AL \<union> set l"
by (induct l arbitrary: AL, simp_all add: l.correct)
have DL_OK : "d.invar DL \<Longrightarrow>
(d.invar (foldl (\<lambda>d a. d.add q1 a q2 d) DL l)) \<and>
d.\<alpha> (foldl (\<lambda>d a. d.add q1 a q2 d) DL l) =
d.\<alpha> DL \<union> {(q1, a, q2) |a. a \<in> set l}"
proof (induct l arbitrary: DL)
case Nil thus ?case by simp
next
case (Cons a l DL)
note ind_hyp = Cons(1)
note invar = Cons(2)
let ?DL' = "d.add q1 a q2 DL"
have DL'_props: "d.invar ?DL'" "d.\<alpha> ?DL' = insert (q1, a, q2) (d.\<alpha> DL)"
using d.lts_add_correct[OF invar, of q1 a q2] by simp_all
with ind_hyp[OF DL'_props(1)] show ?case by (auto simp add: DL'_props(2))
qed
from AL_OK DL_OK invar
show "nfa_\<alpha> (nfa_construct_aux A (q1, l, q2)) = construct_NFA_aux (nfa_\<alpha> A) (q1, l, q2)"
"nfa_invar_no_props (nfa_construct_aux A (q1, l, q2))"
"nfa_props (nfa_construct_aux A (q1, l, q2)) = nfa_props A"
by (simp_all add: nfa_construct_aux_def nfa_\<alpha>_def s.correct nfa_invar_no_props_def nfa_invar_def)
qed
fun nfa_construct_gen where
"nfa_construct_gen p (QL, AL, DL, IL, FL) =
foldl nfa_construct_aux
(s.from_list (QL @ IL @ FL),
l.from_list AL,
d.empty (),
s.from_list IL,
s.from_list FL, p) DL"
declare nfa_construct_gen.simps [simp del]
lemma nfa_construct_correct_gen :
fixes ll :: "'q list \<times> 'a list \<times> ('q \<times> 'a list \<times> 'q) list \<times> 'q list \<times> 'q list"
shows "nfa_invar_no_props (nfa_construct_gen p ll)"
"nfa_props (nfa_construct_gen p ll) = p"
"nfa_\<alpha> (nfa_construct_gen p ll) = NFA_construct ll"
proof -
obtain QL AL DL IL FL where l_eq[simp]: "ll = (QL, AL, DL, IL, FL)" by (cases ll, blast)
let ?A = "(s.from_list (QL @ IL @ FL), l.from_list AL, d.empty (), s.from_list IL, s.from_list FL, p)"
have A_invar: "nfa_invar_no_props ?A" unfolding nfa_invar_full_def
by (simp add: s.correct l.correct d.correct_common nfa_invar_no_props_def)
have A_\<alpha>: "nfa_\<alpha> ?A = \<lparr>\<Q> = set (QL @ IL @ FL), \<Sigma> = set AL, \<Delta> = {}, \<I> = set IL, \<F> = set FL\<rparr>"
by (simp add: nfa_\<alpha>_def s.correct d.correct_common l.correct)
{ fix A DL'
have " nfa_invar_no_props A \<Longrightarrow>
nfa_invar_no_props (foldl nfa_construct_aux A DL') \<and>
nfa_props (foldl nfa_construct_aux A DL') = nfa_props A \<and>
nfa_\<alpha> (foldl nfa_construct_aux A DL') =
foldl construct_NFA_aux (nfa_\<alpha> A) DL'"
proof (induct DL' arbitrary: A)
case Nil thus ?case by simp
next
case (Cons qlq DL')
note ind_hyp = Cons(1)
note invar_A = Cons(2)
let ?A' = "nfa_construct_aux A qlq"
obtain q1 l q2 where qlq_eq[simp]: "qlq = (q1, l, q2)" by (metis prod.exhaust)
note aux_correct = nfa_construct_aux_correct [of A q1 l q2, OF invar_A]
from ind_hyp[of ?A'] aux_correct
show ?case by simp
qed
} note step = this [of ?A DL]
with A_\<alpha> A_invar show "nfa_\<alpha> (nfa_construct_gen p ll) = NFA_construct ll"
and "nfa_invar_no_props (nfa_construct_gen p ll)"
and "nfa_props (nfa_construct_gen p ll) = p"
by (simp_all add: nfa_construct_gen.simps NFA_construct_fold_def d.correct_common
nfa_invar_alt_def nfa_props_trivial_OK)
qed
definition nfa_construct where
"nfa_construct = nfa_construct_gen nfa_props_trivial"
lemma nfa_construct_correct :
"nfa_from_list nfa_\<alpha> nfa_invar nfa_construct"
proof -
from nfa_construct_correct_gen [of nfa_props_trivial]
show ?thesis
unfolding nfa_construct_def
apply (intro nfa_from_list.intro nfa_by_lts_correct nfa_from_list_axioms.intro)
apply (simp_all add: nfa_invar_alt_def nfa_invar_props_def NFA_construct___is_well_formed)
done
qed
definition dfa_construct where
"dfa_construct = nfa_construct_gen (nfa_props.fields True False)"
lemma dfa_construct_correct :
"dfa_from_list nfa_\<alpha> nfa_invar dfa_construct"
proof -
from nfa_construct_correct_gen [of "(nfa_props.fields True False)"]
show ?thesis
unfolding dfa_construct_def
apply (intro dfa_from_list.intro nfa_by_lts_correct dfa_from_list_axioms.intro)
apply (simp_all add: nfa_invar_alt_def nfa_invar_props_def DFA_alt_def)
done
qed
subsection \<open> Destructing Automata \<close>
fun nfa_destruct :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> _" where
"nfa_destruct (Q, A, D, I, F, p) =
(s.to_list Q,
l.to_list A,
d.to_collect_list D,
s.to_list I,
s.to_list F)"
lemma nfa_destruct_correct :
"nfa_to_list nfa_\<alpha> nfa_invar nfa_destruct"
proof (intro nfa_to_list.intro nfa_by_lts_correct nfa_to_list_axioms.intro)
fix n
assume invar: "nfa_invar n"
obtain QL AL DL IL FL p where l_eq[simp]: "n = (QL, AL, DL, IL, FL, p)" by (cases n, blast)
from invar have invar_weak: "nfa_invar_no_props n" and wf: "NFA (nfa_\<alpha> n)"
unfolding nfa_invar_alt_def by simp_all
interpret NFA "nfa_\<alpha> n" by fact
have aux: "\<And>l::'a list. l \<noteq> [] \<Longrightarrow> (\<exists>a. a \<in> set l)" by auto
from invar_weak \<F>_consistent \<I>_consistent \<Delta>_consistent d.lts_to_collect_list_correct(1)[of DL]
d.lts_to_collect_list_correct(3)[of DL]
show "NFA_construct (nfa_destruct n) = nfa_\<alpha> n"
apply (simp add: nfa_\<alpha>_def NFA_construct_alt_def nfa_invar_no_props_def s.correct l.correct d.correct_common)
apply (auto simp add: set_eq_iff)
apply (metis aux)
apply (metis aux)
apply (metis)
done
qed
fun nfa_destruct_simple :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> _" where
"nfa_destruct_simple (Q, A, D, I, F, p) =
(s.to_list Q,
l.to_list A,
d.to_list D,
s.to_list I,
s.to_list F)"
lemma nfa_destruct_simple_correct :
"nfa_to_list_simple nfa_\<alpha> nfa_invar nfa_destruct_simple"
proof (intro nfa_to_list_simple.intro nfa_by_lts_correct nfa_to_list_simple_axioms.intro)
fix n
assume invar: "nfa_invar n"
obtain QL AL DL IL FL p where l_eq[simp]: "n = (QL, AL, DL, IL, FL, p)" by (cases n, blast)
from invar have invar_weak: "nfa_invar_no_props n" and wf: "NFA (nfa_\<alpha> n)"
unfolding nfa_invar_alt_def by simp_all
interpret NFA "nfa_\<alpha> n" by fact
have aux: "\<And>l::'a list. l \<noteq> [] \<Longrightarrow> (\<exists>a. a \<in> set l)" by auto
from invar_weak \<F>_consistent \<I>_consistent \<Delta>_consistent
show "NFA_construct_simple (nfa_destruct_simple n) = nfa_\<alpha> n"
apply (simp add: nfa_\<alpha>_def NFA_construct_alt_def
nfa_invar_no_props_def s.correct l.correct d.correct_common)
apply (auto simp add: set_eq_iff image_iff Bex_def)
done
qed
subsection \<open> Computing Statistics \<close>
fun nfa_states_no :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> _" where
"nfa_states_no (Q, A, D, I, F, p) = s.size Q"
fun nfa_labels_no :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> _" where
"nfa_labels_no (Q, A, D, I, F, p) = l.size A"
fun nfa_trans_no :: "_ \<Rightarrow> ('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> _" where
"nfa_trans_no it (Q, A, D, I, F, p) = iterate_size (it D)"
fun nfa_initial_no :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> _" where
"nfa_initial_no (Q, A, D, I, F, p) = s.size I"
fun nfa_final_no :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> _" where
"nfa_final_no (Q, A, D, I, F, p) = s.size F"
lemma nfa_stats_correct :
assumes it_OK: "lts_iterator d.\<alpha> d.invar it"
shows
"nfa_stats nfa_\<alpha> nfa_invar
nfa_states_no nfa_labels_no (nfa_trans_no it) nfa_initial_no nfa_final_no"
proof -
note it_OK' = iterate_size_correct[OF lts_iterator.lts_it_correct [OF it_OK]]
from it_OK' show ?thesis
by (simp add: nfa_stats_def nfa_stats_axioms_def s.correct l.correct
nfa_invar_full_def)
qed
subsection \<open> Acceptance \<close>
definition accept_nfa_impl :: "_ \<Rightarrow> _ \<Rightarrow> ('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> 'a list \<Rightarrow> _" where
"accept_nfa_impl s_it succ_it A w =
(\<not>(s.disjoint (is_reachable_breath_impl s.empty s.ins s_it succ_it
(nfa_trans A) w (nfa_initial A)) (nfa_accepting A)))"
lemma accept_nfa_impl_code :
"accept_nfa_impl s_it succ_it = (\<lambda>(Q, A, D, I, F, p) w.
(\<not> set_op_disjoint s_ops (foldl
(\<lambda>Q a. s_it Q (\<lambda>_. True)
(\<lambda>q. succ_it D q a (\<lambda>_. True)
(set_op_ins s_ops))
(set_op_empty s_ops ())) I w) F))"
unfolding accept_nfa_impl_def[abs_def] nfa_selectors_def snd_conv fst_conv
is_reachable_breath_impl_alt_def
by (simp add: fun_eq_iff split_def)
lemma accept_nfa_impl_correct :
assumes s_it: "set_iteratei s.\<alpha> s.invar s_it"
and succ_it: "lts_succ_it d.\<alpha> d.invar succ_it"
shows "nfa_accept nfa_\<alpha> nfa_invar (accept_nfa_impl s_it succ_it)"
proof (intro nfa_accept.intro nfa_by_lts_correct nfa_accept_axioms.intro)
fix n w
assume invar_n: "nfa_invar n"
from invar_n have
"s.invar (nfa_initial n)" "s.invar (nfa_accepting n)" "d.invar (nfa_trans n)"
"NFA (nfa_\<alpha> n)"
unfolding nfa_invar_full_def by simp_all
from is_reachable_breath_impl_correct [OF s.set_empty_axioms s.set_ins_axioms s_it succ_it,
OF `d.invar (nfa_trans n)` `s.invar (nfa_initial n)`, of w] `s.invar (nfa_accepting n)`
show "accept_nfa_impl s_it succ_it n w = NFA_accept (nfa_\<alpha> n) w"
unfolding accept_nfa_impl_def
by (simp add: s.correct NFA.NFA_accept_det_def[OF `NFA (nfa_\<alpha> n)`])
qed
definition accept_dfa_impl where
"accept_dfa_impl A w =
s.bex (nfa_initial A) (\<lambda>q. case (d.DLTS_reach_impl (nfa_trans A) q w) of None \<Rightarrow> False
| Some q' \<Rightarrow> s.memb q' (nfa_accepting A))"
lemma accept_dfa_impl_code :
"accept_dfa_impl = (\<lambda>(Q, A, D, I, F, p) w.
set_op_bex s_ops I
(\<lambda>q. case foldli w (\<lambda>q_opt. q_opt \<noteq> None)
(\<lambda>\<sigma> q_opt. lts_op_succ d_ops D (the q_opt) \<sigma>)
(Some q) of
None \<Rightarrow> False | Some q' \<Rightarrow> set_op_memb s_ops q' F))"
unfolding accept_dfa_impl_def[abs_def] nfa_selectors_def fst_conv snd_conv
d.DLTS_reach_impl_alt_def
by (simp add: fun_eq_iff split_def)
lemma accept_dfa_impl_correct :
shows "dfa_accept nfa_\<alpha> nfa_invar accept_dfa_impl"
proof (intro dfa_accept.intro nfa_by_lts_correct dfa_accept_axioms.intro)
fix n w
assume dfa_n: "DFA (nfa_\<alpha> n)" and invar_n: "nfa_invar n"
from invar_n have invar_IF: "s.invar (nfa_accepting n)" "s.invar (nfa_initial n)"
and invar_l: "d.invar (nfa_trans n)"
unfolding nfa_invar_full_def by simp_all
from dfa_n have \<i>_intro: "s.\<alpha> (nfa_initial n) = {\<i> (nfa_\<alpha> n)}"
using DetSemiAutomaton.\<I>_is_set_\<i> [of "nfa_\<alpha> n"]
by (simp add: DFA_alt_def3)
have \<delta>_intro: "(LTS_to_DLTS (d.\<alpha> (nfa_trans n))) = \<delta> (nfa_\<alpha> n)"
unfolding \<delta>_def by simp
from dfa_n have det_l: "LTS_is_deterministic (d.\<alpha> (nfa_trans n))"
unfolding DFA_alt_def SemiAutomaton_is_complete_deterministic_def LTS_is_complete_deterministic_def
by simp
show "accept_dfa_impl n w = NFA_accept (nfa_\<alpha> n) w"
unfolding accept_dfa_impl_def DFA.DFA_accept_alt_def [OF dfa_n]
by (simp add: s.correct invar_IF \<i>_intro d.DLTS_reach_impl_correct [OF invar_l det_l]
\<delta>_intro
split: option.split)
qed
definition accept_impl where
"accept_impl s_it succ_it A w =
(if (nfa_prop_is_complete_deterministic (nfa_props A)) then
(accept_dfa_impl A w) else (accept_nfa_impl s_it succ_it A w))"
lemma accept_impl_correct :
assumes s_it: "set_iteratei s.\<alpha> s.invar s_it"
and succ_it: "lts_succ_it d.\<alpha> d.invar succ_it"
shows "nfa_accept nfa_\<alpha> nfa_invar (accept_impl s_it succ_it)"
proof (intro nfa_accept.intro nfa_by_lts_correct nfa_accept_axioms.intro)
fix A w
assume invar_A: "nfa_invar A"
show "accept_impl s_it succ_it A w = NFA_accept (nfa_\<alpha> A) w"
proof (cases "nfa_prop_is_complete_deterministic (nfa_props A)")
case True note is_det = this
with nfa_invar_implies_DFA[OF invar_A]
have dfa_A: "DFA (nfa_\<alpha> A)" by simp
from dfa_accept.accept_correct[OF accept_dfa_impl_correct, OF invar_A dfa_A, of w] is_det
show ?thesis by (simp add: accept_impl_def)
next
case False note not_det = this
from nfa_accept.accept_correct[OF accept_nfa_impl_correct, OF s_it succ_it invar_A, of w] not_det
show ?thesis by (simp add: accept_impl_def)
qed
qed
subsection \<open> Remove states \<close>
fun remove_states_impl :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> 'q_set \<Rightarrow> ('q_set, 'a_set, 'd) NFA_impl" where
"remove_states_impl (Q, A, D, I, F, p) S =
(s.diff Q S, A,
d.filter (\<lambda>q. \<not>(s.memb q S)) (\<lambda>_. True) (\<lambda>q. \<not>(s.memb q S)) (\<lambda>_. True) D,
s.diff I S, s.diff F S, nfa_props_trivial)"
lemma remove_states_impl_correct :
"nfa_remove_states nfa_\<alpha> nfa_invar s.\<alpha> s.invar remove_states_impl"
proof (intro nfa_remove_states.intro nfa_remove_states_axioms.intro nfa_by_lts_correct)
fix n S
assume invar_S: "s.invar S"
assume invar: "nfa_invar n"
obtain QL AL DL IL FL p where l_eq[simp]: "n = (QL, AL, DL, IL, FL, p)" by (cases n, blast)
from invar have invar_no_props: "nfa_invar_no_props n" and wf: "NFA (nfa_\<alpha> n)"
and invar_props: "nfa_invar_props n"
unfolding nfa_invar_alt_def by simp_all
from invar_no_props invar_S invar_props
have "nfa_invar_no_props (remove_states_impl n S) \<and>
nfa_invar_props (remove_states_impl n S) \<and>
nfa_\<alpha> (remove_states_impl n S) = NFA_remove_states (nfa_\<alpha> n) (s.\<alpha> S)"
by (simp add: nfa_invar_props_def nfa_invar_no_props_def nfa_\<alpha>_def s.correct NFA_remove_states_full_def d.correct_common)
thus "nfa_\<alpha> (remove_states_impl n S) = NFA_remove_states (nfa_\<alpha> n) (s.\<alpha> S)"
"nfa_invar (remove_states_impl n S)"
unfolding nfa_invar_alt_def
using NFA_remove_states___is_well_formed[OF wf, of "s.\<alpha> S"]
by (simp_all add: NFA_remove_states___is_well_formed)
qed
subsection \<open> Rename states \<close>
fun rename_states_fixed_impl :: "_ \<Rightarrow> _ \<Rightarrow> bool \<Rightarrow> ('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> ('q_set2, 'a_set, 'd2) NFA_impl" where
"rename_states_fixed_impl im im2 det (Q, A, D, I, F, p) =
(im Q, A, im2 D, im I, im F, nfa_props.fields det (nfa_prop_is_initially_connected p))"
declare rename_states_fixed_impl.simps[simp del]
definition rename_states_impl :: "_ \<Rightarrow> _ \<Rightarrow> bool \<Rightarrow> ('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> ('q \<Rightarrow> 'q) \<Rightarrow> ('q_set2, 'a_set, 'd2) NFA_impl" where
"rename_states_impl im im2 det A f =
rename_states_fixed_impl (im f) (im2 (\<lambda>qaq::('q \<times> 'a \<times> 'q). (f (fst qaq), fst (snd qaq), f (snd (snd qaq)))))
det A"
lemma rename_states_impl_code :
"rename_states_impl im im2 det (Q, A, D, I, F, p) f =
(im f Q, A,
im2 (\<lambda>(q, a, q'). (f q, a, f q'))
D,
im f I, im f F,
nfa_props.fields det
(nfa_prop_is_initially_connected p))"
unfolding rename_states_impl_def rename_states_fixed_impl.simps split_def by simp
lemma rename_states_fixed_impl_correct :
assumes wf_target: "nfa_by_lts_defs s_ops' l_ops d_ops'"
and im_OK: "set_image s.\<alpha> s.invar (set_op_\<alpha> s_ops') (set_op_invar s_ops') im"
and im2_OK: "if det then dlts_rename_states_fixed d.\<alpha> d.invar (lts_op_\<alpha> d_ops') (lts_op_invar d_ops') im2 f
else lts_rename_states_fixed d.\<alpha> d.invar (lts_op_\<alpha> d_ops') (lts_op_invar d_ops') im2 f"
and invar: "nfa_invar n"
and det_OK: "det \<Longrightarrow> DFA (NFA_rename_states (nfa_\<alpha> n) f)"
shows "nfa_by_lts_defs.nfa_invar s_ops' l_ops d_ops' (rename_states_fixed_impl (im f) im2 det n)" (is ?T1)
"nfa_by_lts_defs.nfa_\<alpha> s_ops' l_ops d_ops' (rename_states_fixed_impl (im f) im2 det n) =
NFA_rename_states (nfa_\<alpha> n) f" (is ?T2)
proof -
obtain QL AL DL IL FL p where n_eq[simp]: "n = (QL, AL, DL, IL, FL, p)" by (cases n, blast)
interpret s': StdSet s_ops' using wf_target unfolding nfa_by_lts_defs_def by simp
interpret d': StdLTS d_ops' using wf_target unfolding nfa_by_lts_defs_def by simp
interpret im: set_image s.\<alpha> s.invar s'.\<alpha> s'.invar im by fact
from invar have invar_no_props: "nfa_invar_no_props n" and wf: "NFA (nfa_\<alpha> n)" and
invar_props: "nfa_invar_props n"
unfolding nfa_invar_alt_def by simp_all
interpret nfa_org: NFA "nfa_\<alpha> n" by fact
let ?nfa_\<alpha>' = "nfa_by_lts_defs.nfa_\<alpha> s_ops' l_ops d_ops'"
let ?nfa_invar_no_props' = "nfa_by_lts_defs.nfa_invar_no_props s_ops' l_ops d_ops'"
let ?nfa_invar' = "nfa_by_lts_defs.nfa_invar s_ops' l_ops d_ops'"
have image_trans_eq: "((\<lambda>qaq. (f (fst qaq), fst (snd qaq), f (snd (snd qaq)))) ` lts_op_\<alpha> d_ops DL) =
{(f s1, a, f s2) |s1 a s2. (s1, a, s2) \<in> lts_op_\<alpha> d_ops DL}"
by (auto simp add: image_iff Bex_def) metis+
have im2_OK': "lts_op_invar d_ops' (im2 DL) \<and>
lts_op_\<alpha> d_ops' (im2 DL) =
{(f s1, a, f s2) |s1 a s2. (s1, a, s2) \<in> lts_op_\<alpha> d_ops DL}"
proof (cases det)
case False
with im2_OK have im2_not_det: "lts_rename_states_fixed (lts_op_\<alpha> d_ops)
(lts_op_invar d_ops) (lts_op_\<alpha> d_ops')
(lts_op_invar d_ops') im2 f" by simp
from lts_image_fixed.lts_image_fixed_correct [OF
im2_not_det[unfolded lts_rename_states_fixed_def], of DL] invar_no_props
show ?thesis
unfolding nfa_invar_no_props_def image_trans_eq by simp
next
case True note det_eq_True = this
with im2_OK have im2_det: "dlts_rename_states_fixed (lts_op_\<alpha> d_ops)
(lts_op_invar d_ops) (lts_op_\<alpha> d_ops')
(lts_op_invar d_ops') im2 f" by simp
from det_OK[OF det_eq_True] have det_trans: "LTS_is_deterministic
{(f s1, a, f s2) |s1 a s2. (s1, a, s2) \<in> lts_op_\<alpha> d_ops DL}"
unfolding DFA_alt_def SemiAutomaton_is_complete_deterministic_def LTS_is_complete_deterministic_def
NFA_rename_states_full_def
by simp
from dlts_image_fixed.dlts_image_fixed_correct [OF
im2_det[unfolded dlts_rename_states_fixed_def], of DL] invar_no_props det_trans
show ?thesis
unfolding nfa_invar_no_props_def image_trans_eq by simp
qed
from invar_no_props im2_OK'
have "?nfa_invar_no_props' (rename_states_fixed_impl (im f) im2 det n) \<and>
?nfa_\<alpha>' (rename_states_fixed_impl (im f) im2 det n) = NFA_rename_states (nfa_\<alpha> n) f"
by (simp add: nfa_by_lts_defs.nfa_\<alpha>_def[OF wf_target]
nfa_by_lts_defs.nfa_invar_no_props_def [OF wf_target]
nfa_by_lts_defs.nfa_selectors_def [OF wf_target]
nfa_invar_no_props_def rename_states_fixed_impl.simps
s.correct NFA_rename_states_full_def d.correct_common
im.image_correct)
thus "?nfa_\<alpha>' (rename_states_fixed_impl (im f) im2 det n) = NFA_rename_states (nfa_\<alpha> n) f"
"?nfa_invar' (rename_states_fixed_impl (im f) im2 det n)"
unfolding nfa_by_lts_defs.nfa_invar_alt_def [OF wf_target]
using NFA_rename_states___is_well_formed[OF wf, of f]
SemiAutomaton_is_initially_connected___NFA_rename_states [of "nfa_\<alpha> n" f]
invar_props det_OK
apply (simp_all add: NFA_remove_states___is_well_formed)
apply (simp add: nfa_by_lts_defs.nfa_invar_props_def[OF wf_target])
apply (simp add: rename_states_fixed_impl.simps nfa_invar_props_def
nfa_by_lts_defs.nfa_invar_props_def[OF wf_target]
nfa_by_lts_defs.nfa_selectors_def[OF wf_target] DFA_alt_def)
done
qed
lemma rename_states_impl_correct :
assumes wf_target: "nfa_by_lts_defs s_ops' l_ops d_ops'"
assumes im_OK: "set_image s.\<alpha> s.invar (set_op_\<alpha> s_ops') (set_op_invar s_ops') im"
assumes im2_OK: "lts_image d.\<alpha> d.invar (lts_op_\<alpha> d_ops') (lts_op_invar d_ops') im2"
shows "nfa_rename_states nfa_\<alpha> nfa_invar
(nfa_by_lts_defs.nfa_\<alpha> s_ops' l_ops d_ops')
(nfa_by_lts_defs.nfa_invar s_ops' l_ops d_ops')
(rename_states_impl im im2 False)"
proof (intro nfa_rename_states.intro nfa_rename_states_axioms.intro
nfa_by_lts_defs.nfa_by_lts_correct)
show "nfa_by_lts_defs s_ops l_ops d_ops" by (fact nfa_by_lts_defs_axioms)
show "nfa_by_lts_defs s_ops' l_ops d_ops'" by (fact wf_target)
fix n f
assume invar: "nfa_invar n"
let ?res = "rename_states_impl im im2 False n f"
let ?nfa_\<alpha>' = "nfa_by_lts_defs.nfa_\<alpha> s_ops' l_ops d_ops'"
let ?nfa_invar' = "nfa_by_lts_defs.nfa_invar s_ops' l_ops d_ops'"
let ?f' = "(\<lambda>qaq. (f (fst qaq), fst (snd qaq), f (snd (snd qaq))))"
from rename_states_fixed_impl_correct[OF wf_target im_OK _ invar, of False "im2 ?f'" f]
im2_OK
show "?nfa_\<alpha>' ?res = NFA_rename_states (nfa_\<alpha> n) f"
"?nfa_invar' ?res"
by (simp_all add: lts_rename_states_fixed_def lts_image_alt_def rename_states_impl_def)
qed
lemma rename_states_impl_correct_dfa :
assumes wf_target: "nfa_by_lts_defs s_ops' l_ops d_ops'"
assumes im_OK: "set_image s.\<alpha> s.invar (set_op_\<alpha> s_ops') (set_op_invar s_ops') im"
assumes im2_OK: "dlts_image d.\<alpha> d.invar (lts_op_\<alpha> d_ops') (lts_op_invar d_ops') im2"
shows "dfa_rename_states nfa_\<alpha> nfa_invar
(nfa_by_lts_defs.nfa_\<alpha> s_ops' l_ops d_ops')
(nfa_by_lts_defs.nfa_invar s_ops' l_ops d_ops')
(rename_states_impl im im2 True)"
proof (intro dfa_rename_states.intro dfa_rename_states_axioms.intro
nfa_by_lts_defs.nfa_by_lts_correct)
show "nfa_by_lts_defs s_ops l_ops d_ops" by (fact nfa_by_lts_defs_axioms)
show "nfa_by_lts_defs s_ops' l_ops d_ops'" by (fact wf_target)
fix n f
assume invar: "nfa_invar n"
let ?res = "rename_states_impl im im2 True n f"
assume wf_res: "DFA (NFA_rename_states (nfa_\<alpha> n) f)"
let ?nfa_\<alpha>' = "nfa_by_lts_defs.nfa_\<alpha> s_ops' l_ops d_ops'"
let ?nfa_invar' = "nfa_by_lts_defs.nfa_invar s_ops' l_ops d_ops'"
let ?f' = "(\<lambda>qaq. (f (fst qaq), fst (snd qaq), f (snd (snd qaq))))"
from rename_states_fixed_impl_correct[OF wf_target im_OK _ invar, of True "im2 ?f'" f]
wf_res im2_OK
show "?nfa_\<alpha>' ?res = NFA_rename_states (nfa_\<alpha> n) f"
"?nfa_invar' ?res"
by (simp_all add: rename_states_impl_def dlts_image_alt_def
dlts_rename_states_fixed_def)
qed
lemma rename_states_impl_correct___self :
assumes im_OK: "set_image s.\<alpha> s.invar s.\<alpha> s.invar im"
shows "nfa_rename_states nfa_\<alpha> nfa_invar
nfa_\<alpha> nfa_invar
(rename_states_impl im d.image False)"
apply (rule rename_states_impl_correct)
apply (simp_all add: nfa_by_lts_defs_axioms im_OK d.lts_image_axioms)
done
lemma rename_states_impl_correct_dfa___self :
assumes im_OK: "set_image s.\<alpha> s.invar s.\<alpha> s.invar im"
shows "dfa_rename_states nfa_\<alpha> nfa_invar
nfa_\<alpha> nfa_invar
(rename_states_impl im d.image True)"
apply (rule rename_states_impl_correct_dfa)
apply (simp_all add: nfa_by_lts_defs_axioms im_OK d.lts_image_axioms dlts_image_sublocale)
done
subsection \<open> Rename labels \<close>
fun rename_labels_fixed_impl :: "_ \<Rightarrow> bool \<Rightarrow> ('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> _ \<Rightarrow> ('q_set, 'a2_set, 'd) NFA_impl" where
"rename_labels_fixed_impl im det (Q, A, D, I, F, p) A' =
(Q, A', im D, I, F, nfa_props.fields det (nfa_prop_is_initially_connected p))"
declare rename_labels_fixed_impl.simps[simp del]
definition rename_labels_impl_gen where
"rename_labels_impl_gen im det A A' (f::'a \<Rightarrow> 'a2) =
rename_labels_fixed_impl (im (\<lambda>qaq::('q \<times> 'a \<times> 'q). (fst qaq, f (fst (snd qaq)), snd (snd qaq))))
det A A'"
lemma rename_labels_impl_gen_code :
"rename_labels_impl_gen im det (Q, A, D, I, F, p) A' f =
(Q, A',
im (\<lambda>(q, a, q'). (q, f a, q'))
D, I, F,
nfa_props.fields det (nfa_prop_is_initially_connected p))"
unfolding rename_labels_fixed_impl.simps rename_labels_impl_gen_def split_def by simp
definition rename_labels_impl where
"rename_labels_impl im im2 det = (\<lambda>(Q, A, D, I, F) f.
rename_labels_impl_gen im det (Q, A, D, I, F) (im2 f A) f)"
lemma rename_labels_fixed_impl_correct :
fixes l_ops' :: "('a2, 'a2_set, _) set_ops_scheme"
assumes wf_target: "nfa_by_lts_defs s_ops l_ops' d_ops'"
assumes im_OK: "lts_rename_labels_fixed d.\<alpha> d.invar (lts_op_\<alpha> d_ops') (lts_op_invar d_ops') im f"
and invar: "nfa_invar n"
and A_OK : "set_op_invar l_ops' A" "set_op_\<alpha> l_ops' A = f ` \<Sigma> (nfa_\<alpha> n)"
and det_OK: "det \<Longrightarrow> DFA (SemiAutomaton_rename_labels (nfa_\<alpha> n) f)"
shows "nfa_by_lts_defs.nfa_invar s_ops l_ops' d_ops' (rename_labels_fixed_impl im det n A)" (is ?T1)
"nfa_by_lts_defs.nfa_\<alpha> s_ops l_ops' d_ops'(rename_labels_fixed_impl im det n A) =
SemiAutomaton_rename_labels (nfa_\<alpha> n) f" (is ?T2)
proof -
obtain QL AL DL IL FL p where n_eq[simp]: "n = (QL, AL, DL, IL, FL, p)" by (cases n, blast)
interpret d': StdLTS d_ops' using wf_target unfolding nfa_by_lts_defs_def by simp
from invar have invar_no_props: "nfa_invar_no_props n" and wf: "NFA (nfa_\<alpha> n)" and
invar_props: "nfa_invar_props n"
unfolding nfa_invar_alt_def by simp_all
interpret nfa_org: NFA "nfa_\<alpha> n" by fact
let ?nfa_\<alpha>' = "nfa_by_lts_defs.nfa_\<alpha> s_ops l_ops' d_ops'"
let ?nfa_invar_no_props' = "nfa_by_lts_defs.nfa_invar_no_props s_ops l_ops' d_ops'"
let ?nfa_invar' = "nfa_by_lts_defs.nfa_invar s_ops l_ops' d_ops'"
from invar_no_props A_OK
lts_image_fixed.lts_image_fixed_correct [OF im_OK[unfolded lts_rename_labels_fixed_def]]
have "?nfa_invar_no_props' (rename_labels_fixed_impl im det n A) \<and>
?nfa_\<alpha>' (rename_labels_fixed_impl im det n A) = SemiAutomaton_rename_labels (nfa_\<alpha> n) f"
apply (simp add: nfa_by_lts_defs.nfa_\<alpha>_def[OF wf_target]
nfa_\<alpha>_def
nfa_by_lts_defs.nfa_invar_no_props_def [OF wf_target]
nfa_by_lts_defs.nfa_selectors_def [OF wf_target]
nfa_invar_no_props_def rename_labels_fixed_impl.simps
s.correct SemiAutomaton_rename_labels_def d.correct_common)
apply (auto simp add: image_iff Bex_def)
done
thus "?nfa_\<alpha>' (rename_labels_fixed_impl im det n A) = SemiAutomaton_rename_labels (nfa_\<alpha> n) f"
"?nfa_invar' (rename_labels_fixed_impl im det n A)"
unfolding nfa_by_lts_defs.nfa_invar_alt_def [OF wf_target]
using NFA.NFA_rename_labels___is_well_formed[OF wf, of f]
SemiAutomaton_is_initially_connected___SemiAutomaton_rename_labels [of "nfa_\<alpha> n" f]
invar_props det_OK
apply (simp_all)
apply (simp add: nfa_by_lts_defs.nfa_invar_props_def[OF wf_target])
apply (simp add: rename_labels_fixed_impl.simps nfa_invar_props_def
nfa_by_lts_defs.nfa_invar_props_def[OF wf_target]
nfa_by_lts_defs.nfa_selectors_def[OF wf_target] DFA_alt_def)
done
qed
lemma rename_labels_impl_gen_correct :
fixes l_ops' :: "('a2, 'a2_set, _) set_ops_scheme"
assumes wf_target: "nfa_by_lts_defs s_ops l_ops' d_ops'"
assumes im_OK: "lts_image d.\<alpha> d.invar (lts_op_\<alpha> d_ops') (lts_op_invar d_ops') im"
shows "nfa_rename_labels_gen nfa_\<alpha> nfa_invar
(nfa_by_lts_defs.nfa_\<alpha> s_ops l_ops' d_ops')
(nfa_by_lts_defs.nfa_invar s_ops l_ops' d_ops')
(set_op_\<alpha> l_ops') (set_op_invar l_ops')
(rename_labels_impl_gen im False)"
proof (intro nfa_rename_labels_gen.intro nfa_rename_labels_gen_axioms.intro
nfa_by_lts_defs.nfa_by_lts_correct)
show "nfa_by_lts_defs s_ops l_ops d_ops" by (fact nfa_by_lts_defs_axioms)
show "nfa_by_lts_defs s_ops l_ops' d_ops'" by (fact wf_target)
interpret l': StdSet l_ops' using wf_target unfolding nfa_by_lts_defs_def by simp
interpret d': StdLTS d_ops' using wf_target unfolding nfa_by_lts_defs_def by simp
fix n A f
assume invar: "nfa_invar n"
assume A_OK: "l'.invar A" "l'.\<alpha> A = f ` \<Sigma> (nfa_\<alpha> n)"
let ?res = "rename_labels_impl_gen im False n A f"
let ?nfa_\<alpha>' = "nfa_by_lts_defs.nfa_\<alpha> s_ops l_ops' d_ops'"
let ?nfa_invar' = "nfa_by_lts_defs.nfa_invar s_ops l_ops' d_ops'"
let ?f' = "(\<lambda>qaq. (fst qaq, f (fst (snd qaq)), snd (snd qaq)))"
from rename_labels_fixed_impl_correct[OF wf_target _ invar A_OK, of "im ?f'" False] im_OK
show "?nfa_\<alpha>' ?res = SemiAutomaton_rename_labels (nfa_\<alpha> n) f"
"?nfa_invar' ?res"
by (simp_all add: rename_labels_impl_gen_def lts_image_alt_def
lts_rename_labels_fixed_def)
qed
lemma rename_labels_impl_correct :
fixes l_ops' :: "('a2, 'a2_set, _) set_ops_scheme"
assumes wf_target: "nfa_by_lts_defs s_ops l_ops' d_ops'"
assumes im_OK: "lts_image d.\<alpha> d.invar (lts_op_\<alpha> d_ops') (lts_op_invar d_ops') im"
assumes im2_OK: "set_image l.\<alpha> l.invar (set_op_\<alpha> l_ops') (set_op_invar l_ops') im2"
shows "nfa_rename_labels nfa_\<alpha> nfa_invar
(nfa_by_lts_defs.nfa_\<alpha> s_ops l_ops' d_ops')
(nfa_by_lts_defs.nfa_invar s_ops l_ops' d_ops')
(rename_labels_impl im im2 False)"
proof -
note labels_gen_OK = rename_labels_impl_gen_correct [OF wf_target im_OK]
let ?im2' = "\<lambda>(QL, AL, DL, IL, FL) f. im2 f AL"
have pre_OK: "\<And>n f. nfa_invar n \<Longrightarrow>
set_op_invar l_ops' (?im2' n f) \<and>
set_op_\<alpha> l_ops' (?im2' n f) = f ` \<Sigma> (nfa_\<alpha> n)"
using im2_OK
unfolding nfa_invar_full_def set_image_def nfa_invar_def
by auto
have post_OK: "(\<lambda>AA f. rename_labels_impl_gen im False AA ((\<lambda>(QL, AL, DL, IL, FL) f. im2 f AL) AA f) f) =
rename_labels_impl im im2 False"
unfolding rename_labels_impl_def by auto
from nfa_rename_labels_gen_impl[OF labels_gen_OK, of ?im2', OF pre_OK]
show ?thesis unfolding post_OK by simp
qed
lemma rename_labels_impl_correct___self :
assumes im_OK: "set_image l.\<alpha> l.invar l.\<alpha> l.invar im"
shows "nfa_rename_labels
nfa_\<alpha> nfa_invar
nfa_\<alpha> nfa_invar
(rename_labels_impl d.image im False)"
by (fact rename_labels_impl_correct [OF nfa_by_lts_defs_axioms d.lts_image_axioms im_OK])
end
subsection \<open> construct reachable NFA \<close>
locale NFA_construct_reachable_locale =
nfa_by_lts_defs s_ops l_ops d_ops +
qm: StdMap qm_ops (* The index max *)
for s_ops::"('q::{automaton_states},'q_set,_) set_ops_scheme"
and l_ops::"('a,'a_set,_) set_ops_scheme"
and d_ops::"('q,'a,'d,_) lts_ops_scheme"
and qm_ops :: "('i, 'q::{automaton_states}, 'm, _) map_ops_scheme" +
fixes a_\<alpha> :: "'as \<Rightarrow> 'a set" and a_invar :: "'as \<Rightarrow> bool"
and add_labels :: "bool \<Rightarrow> 'q \<Rightarrow> 'as \<Rightarrow> 'q \<Rightarrow> 'd \<Rightarrow> 'd"
and f :: "'q2 \<Rightarrow> 'i"
and ff :: "'q2_rep \<Rightarrow> 'i"
and q2_\<alpha> :: "'q2_rep \<Rightarrow> 'q2"
and q2_invar :: "'q2_rep \<Rightarrow> bool"
begin
definition state_map_\<alpha> where "state_map_\<alpha> \<equiv> (\<lambda>(qm, n::nat). qm.\<alpha> qm \<circ> f)"
definition state_map_invar where "state_map_invar \<equiv> (\<lambda>(qm, n). qm.invar qm \<and>
(\<forall>i q. qm.\<alpha> qm i = Some q \<longrightarrow> (\<exists>n' < n. q = states_enumerate n')))"
lemma state_map_extend_thm :
fixes n qm q
defines "qm'' \<equiv> qm.update_dj (f q) (states_enumerate n) qm"
assumes f_inj_on: "inj_on f S"
and invar_qm_n: "state_map_invar (qm, n)"
and q_in_S: "q \<in> S"
and q_nin_dom: "q \<notin> dom (state_map_\<alpha> (qm, n))"
and map_OK : "NFA_construct_reachable_map_OK S Map.empty {} (state_map_\<alpha> (qm, n))"
shows "state_map_invar (qm'', Suc n)"
"qm.\<alpha> qm'' = qm.\<alpha> qm(f q \<mapsto> states_enumerate n)"
"NFA_construct_reachable_map_OK S (state_map_\<alpha> (qm, n)) {q} (state_map_\<alpha> (qm'', Suc n))"
"S \<inter> dom (state_map_\<alpha> (qm'', Suc n)) = insert q ((dom (state_map_\<alpha> (qm, n))) \<inter> S)"
proof -
from invar_qm_n have invar_qm: "qm.invar qm" unfolding state_map_invar_def by simp
from q_nin_dom have fq_nin_dom_rm: "f q \<notin> dom (qm.\<alpha> qm)"
unfolding state_map_\<alpha>_def by (simp add: dom_def)
have qm''_props: "qm.invar qm''" "qm.\<alpha> qm'' = qm.\<alpha> qm(f q \<mapsto> states_enumerate n)"
using qm.update_dj_correct [OF invar_qm fq_nin_dom_rm]
by (simp_all add: qm''_def)
show "qm.\<alpha> qm'' = qm.\<alpha> qm(f q \<mapsto> states_enumerate n)" by (fact qm''_props(2))
show invar_qm''_n: "state_map_invar (qm'', Suc n)"
using invar_qm_n
by (simp add: state_map_invar_def qm''_props) (metis less_Suc_eq)
have rm''_q: "state_map_\<alpha> (qm'', Suc n) q = Some (states_enumerate n)"
unfolding state_map_\<alpha>_def by (simp add: qm''_props)
have dom_sub: "insert q (dom (state_map_\<alpha> (qm, n))) \<subseteq> dom (state_map_\<alpha> (qm'', Suc n))"
unfolding state_map_\<alpha>_def
by (simp add: subset_iff dom_def qm''_props o_def)
show dom_eq: "S \<inter> dom (state_map_\<alpha> (qm'', Suc n)) = insert q ((dom (state_map_\<alpha> (qm, n))) \<inter> S)"
(is "?ls = ?rs")
proof (intro set_eqI iffI)
fix q'
assume "q' \<in> ?rs"
with q_in_S dom_sub show "q' \<in> ?ls" by auto
next
fix q'
assume "q' \<in> ?ls"
hence q'_in_S: "q' \<in> S" and q'_in_dom: "q' \<in> dom (state_map_\<alpha> (qm'', Suc n))" by simp_all
from f_inj_on q_in_S q'_in_S have fqq'[simp]: "f q' = f q \<longleftrightarrow> q' = q"
unfolding inj_on_def by auto
from q'_in_dom have "q' = q \<or> q' \<in> (dom (state_map_\<alpha> (qm, n)))" unfolding state_map_\<alpha>_def
by (auto simp add: qm''_props o_def dom_def)
with q'_in_S show "q' \<in> ?rs" by auto
qed
have qm''_inj_on: "inj_on (state_map_\<alpha> (qm'', Suc n)) (S \<inter> dom (state_map_\<alpha> (qm'', Suc n)))"
proof (rule inj_onI)
fix q' q''
assume q'_in: "q' \<in> S \<inter> dom (state_map_\<alpha> (qm'', Suc n))"
assume q''_in: "q'' \<in> S \<inter> dom (state_map_\<alpha> (qm'', Suc n))"
assume state_map_\<alpha>_eq: "state_map_\<alpha> (qm'', Suc n) q' = state_map_\<alpha> (qm'', Suc n) q''"
{ fix q'''
assume in_dom: "q''' \<in> S \<inter> dom (state_map_\<alpha> (qm, n))"
from in_dom q_nin_dom have "q''' \<noteq> q" by auto
with f_inj_on q_in_S in_dom have f_q'''_neq: "f q''' \<noteq> f q"
unfolding inj_on_def by auto
have prop1: "state_map_\<alpha> (qm'', Suc n) q''' = state_map_\<alpha> (qm, n) q'''"
unfolding state_map_\<alpha>_def
by (simp add: o_def qm''_props f_q'''_neq)
from invar_qm_n in_dom obtain n' where "n' < n" and
"state_map_\<alpha> (qm, n) q''' = Some (states_enumerate n')"
unfolding state_map_invar_def dom_def state_map_\<alpha>_def by auto
with prop1 have prop2: "state_map_\<alpha> (qm'', Suc n) q''' \<noteq> state_map_\<alpha> (qm'', Suc n) q"
by (simp add: rm''_q states_enumerate_eq)
note prop1 prop2
} note qm''_\<alpha>_props = this
show "q' = q''"
proof (cases "q' = q")
case True note q'_eq[simp] = this
show ?thesis
proof (cases "q'' = q")
case True thus ?thesis by simp
next
case False with q''_in dom_eq
have "q'' \<in> S \<inter> (dom (state_map_\<alpha> (qm, n)))" by simp
with qm''_\<alpha>_props(2) [of q''] state_map_\<alpha>_eq have "False" by simp
thus ?thesis ..
qed
next
case False with q'_in dom_eq
have q'_in_dom_qm: "q' \<in> (S \<inter> dom (state_map_\<alpha> (qm, n)))" by simp
show ?thesis
proof (cases "q'' = q")
case True
with qm''_\<alpha>_props(2) [of q'] state_map_\<alpha>_eq q'_in_dom_qm have "False" by simp
thus ?thesis ..
next
case False with q''_in dom_eq
have q''_in_dom_qm: "q'' \<in> (S \<inter> dom (state_map_\<alpha> (qm, n)))" by simp
from map_OK have "inj_on (state_map_\<alpha> (qm, n)) (S \<inter> dom (state_map_\<alpha> (qm, n)))"
unfolding NFA_construct_reachable_map_OK_def by simp
with q''_in_dom_qm q'_in_dom_qm state_map_\<alpha>_eq qm''_\<alpha>_props(1) show ?thesis
unfolding inj_on_def by auto
qed
qed
qed
show map_OK': "NFA_construct_reachable_map_OK S (state_map_\<alpha> (qm, n)) {q} (state_map_\<alpha> (qm'', Suc n))"
proof
show "{q} \<subseteq> dom (state_map_\<alpha> (qm'', Suc n))"
by (simp add: rm''_q dom_def)
next
fix q' r'
assume "state_map_\<alpha> (qm, n) q' = Some r'"
with fq_nin_dom_rm show "state_map_\<alpha> (qm'', Suc n) q' = Some r'"
unfolding state_map_\<alpha>_def by (auto simp add: qm''_props dom_def)
next
show "inj_on (state_map_\<alpha> (qm'', Suc n)) (S \<inter> dom (state_map_\<alpha> (qm'', Suc n)))"
by (fact qm''_inj_on)
qed
qed
definition NFA_construct_reachable_init_impl where
"NFA_construct_reachable_init_impl I =
foldl (\<lambda>((qm, n), Is) q. ((qm.update_dj (ff q) (states_enumerate n) qm, Suc n),
s.ins_dj (states_enumerate n) Is))
((qm.empty (), 0), s.empty ()) I"
lemma NFA_construct_reachable_init_impl_correct :
fixes II D
defines "I \<equiv> map q2_\<alpha> II"
defines "S \<equiv> accessible (LTS_forget_labels D) (set I)"
assumes f_inj_on: "inj_on f S"
and dist_I: "distinct I"
and invar_I: "\<And>q. q \<in> set II \<Longrightarrow> q2_invar q"
and ff_OK: "\<And>q. q2_invar q \<Longrightarrow> q2_\<alpha> q \<in> S \<Longrightarrow> ff q = f (q2_\<alpha> q)"
shows
"RETURN (NFA_construct_reachable_init_impl II) \<le> \<Down>
((build_rel state_map_\<alpha> state_map_invar) \<times>\<^sub>r
(build_rel s.\<alpha> s.invar))
(SPEC (\<lambda>(rm, I').
NFA_construct_reachable_map_OK (accessible (LTS_forget_labels D) (set I)) Map.empty (set I) rm \<and>
I' = (the \<circ> rm) ` (set I)))"
proof -
let ?step = "(\<lambda>((qm, n), Is) q. ((qm.update_dj (ff q) (states_enumerate n) qm, Suc n),
s.ins_dj (states_enumerate n) Is))"
{ fix II
have invar_OK : "\<And>qm n Is qm' n' Is'.
set (map q2_\<alpha> II) \<subseteq> S \<Longrightarrow>
distinct (map q2_\<alpha> II) \<Longrightarrow>
\<forall>q\<in>set II. q2_invar q \<Longrightarrow>
dom (state_map_\<alpha> (qm, n)) \<inter> (set (map q2_\<alpha> II)) = {} \<Longrightarrow>
state_map_invar (qm, n) \<Longrightarrow>
s.invar Is \<Longrightarrow>
(\<And>q. q \<in> s.\<alpha> Is \<Longrightarrow> (\<exists>n' < n. q = states_enumerate n')) \<Longrightarrow>
NFA_construct_reachable_map_OK S Map.empty {} (state_map_\<alpha> (qm, n)) \<Longrightarrow>
((qm', n'), Is') = foldl ?step ((qm, n),Is) II \<Longrightarrow>
s.invar Is' \<and>
s.\<alpha> Is' = ((the \<circ> (state_map_\<alpha> (qm', n'))) ` (set (map q2_\<alpha> II))) \<union> s.\<alpha> Is \<and>
state_map_invar (qm', n') \<and>
NFA_construct_reachable_map_OK S (state_map_\<alpha> (qm, n)) (set (map q2_\<alpha> II)) (state_map_\<alpha> (qm', n'))"
proof (induct II)
case Nil thus ?case by (simp add: NFA_construct_reachable_map_OK_def)
next
case (Cons q II' qm n Is qm' n' Is')
from Cons(2) have q_in_S: "q2_\<alpha> q \<in> S" and II'_subset: "set (map q2_\<alpha> II') \<subseteq> S" by simp_all
from Cons(3) have q_nin_I': "q2_\<alpha> q \<notin> set (map q2_\<alpha> II')" and "distinct (map q2_\<alpha> II')" by simp_all
from Cons(4) have invar_q: "q2_invar q" and invar_II': "\<forall>q\<in>set II'. q2_invar q" by simp_all
note dom_qII'_dist = Cons(5)
note invar_qm_n = Cons(6)
note invar_Is = Cons(7)
note memb_Is = Cons(8)
note map_OK = Cons(9)
note fold_eq = Cons(10)
let ?I' = "map q2_\<alpha> II'"
define qm'' where "qm'' \<equiv> qm.update_dj (ff q) (states_enumerate n) qm"
define Is'' where "Is'' \<equiv> s.ins_dj (states_enumerate n) Is"
note ind_hyp = Cons(1) [OF II'_subset `distinct ?I'` invar_II',
of qm'' "Suc n" Is'' qm' n' Is']
from dom_qII'_dist have q_nin_dom: "q2_\<alpha> q \<notin> dom (state_map_\<alpha> (qm, n))" by auto
from state_map_extend_thm [OF f_inj_on invar_qm_n q_in_S q_nin_dom map_OK]
have invar_qm''_n: "state_map_invar (qm'', Suc n)" and
qm''_alpha: "map_op_\<alpha> qm_ops qm'' = map_op_\<alpha> qm_ops qm(ff q \<mapsto> states_enumerate n)" and
map_OK': "NFA_construct_reachable_map_OK S (state_map_\<alpha> (qm, n)) {q2_\<alpha> q} (state_map_\<alpha> (qm'', Suc n))" and
dom_eq: "S \<inter> dom (state_map_\<alpha> (qm'', Suc n)) = insert (q2_\<alpha> q) ((dom (state_map_\<alpha> (qm, n))) \<inter> S)"
using qm''_def[symmetric] ff_OK [OF invar_q q_in_S, symmetric]
by simp_all
have dom_II'_dist: "dom (state_map_\<alpha> (qm'', Suc n)) \<inter> set ?I' = {}"
proof -
from II'_subset have "dom (state_map_\<alpha> (qm'', Suc n)) \<inter> set (map q2_\<alpha> II') =
(S \<inter> dom (state_map_\<alpha> (qm'', Suc n))) \<inter> set (map q2_\<alpha> II')" by auto
hence step: "dom (state_map_\<alpha> (qm'', Suc n)) \<inter> set (map q2_\<alpha> II') =
insert (q2_\<alpha> q) ((dom (state_map_\<alpha> (qm, n))) \<inter> S) \<inter> set (map q2_\<alpha> II')"
unfolding dom_eq by simp
from dom_qII'_dist q_nin_I' show ?thesis unfolding step
by (auto simp add: set_eq_iff)
qed
have state_n_nin_Is: "states_enumerate n \<notin> s.\<alpha> Is"
proof (rule notI)
assume "states_enumerate n \<in> s.\<alpha> Is"
from memb_Is[OF this] show False
by (simp add: states_enumerate_eq)
qed
from state_n_nin_Is invar_Is
have Is''_props: "s.invar Is''" "s.\<alpha> Is'' = insert (states_enumerate n) (s.\<alpha> Is)"
by (simp_all add: Is''_def s.correct)
have state_n_nin_Is: "states_enumerate n \<notin> s.\<alpha> Is"
proof (rule notI)
assume "states_enumerate n \<in> s.\<alpha> Is"
from memb_Is[OF this] show False
by (simp add: states_enumerate_eq)
qed
from state_n_nin_Is invar_Is
have Is''_props: "s.invar Is''" "s.\<alpha> Is'' = insert (states_enumerate n) (s.\<alpha> Is)"
by (simp_all add: Is''_def s.correct)
have ind_hyp': "
s.invar Is' \<and>
s.\<alpha> Is' = (the \<circ> state_map_\<alpha> (qm', n')) ` set ?I' \<union> s.\<alpha> Is'' \<and>
state_map_invar (qm', n') \<and>
NFA_construct_reachable_map_OK S (state_map_\<alpha> (qm'', Suc n)) (set ?I') (state_map_\<alpha> (qm', n'))"
proof (rule ind_hyp [OF dom_II'_dist invar_qm''_n Is''_props(1)])
fix q
assume "q \<in> s.\<alpha> Is''"
with Is''_props(2) memb_Is show "\<exists>n'<Suc n. q = states_enumerate n'"
by auto (metis less_Suc_eq)
next
from map_OK'
show "NFA_construct_reachable_map_OK S Map.empty {} (state_map_\<alpha> (qm'', Suc n))"
unfolding NFA_construct_reachable_map_OK_def by simp
next
from fold_eq show "((qm', n'), Is') = foldl ?step ((qm'', Suc n), Is'') II'"
by (simp add: qm''_def Is''_def)
qed
show ?case proof (intro conjI)
show "s.invar Is'" "state_map_invar (qm', n')" by (simp_all add: ind_hyp')
next
from ind_hyp' qm''_alpha have "state_map_\<alpha> (qm', n') (q2_\<alpha> q) = Some (states_enumerate n)"
unfolding NFA_construct_reachable_map_OK_def state_map_\<alpha>_def
by (simp add: ff_OK[OF invar_q q_in_S])
thus "s.\<alpha> Is' = (the \<circ> state_map_\<alpha> (qm', n')) ` set (map q2_\<alpha> (q # II')) \<union> s.\<alpha> Is"
by (simp add: ind_hyp' Is''_props)
next
show "NFA_construct_reachable_map_OK S (state_map_\<alpha> (qm, n)) (set (map q2_\<alpha> (q # II')))
(state_map_\<alpha> (qm', n'))"
proof (rule NFA_construct_reachable_map_OK_trans [of _ _ "{q2_\<alpha> q}"
"state_map_\<alpha> (qm'', Suc n)" "set ?I'"])
show "set (map q2_\<alpha> (q # II')) \<subseteq> {q2_\<alpha> q} \<union> set ?I'" by auto
next
show "NFA_construct_reachable_map_OK S (state_map_\<alpha> (qm'', Suc n)) (set ?I')
(state_map_\<alpha> (qm', n'))"
using ind_hyp' by simp
next
show "NFA_construct_reachable_map_OK S (state_map_\<alpha> (qm, n)) {q2_\<alpha> q} (state_map_\<alpha> (qm'', Suc n))"
by (simp add: map_OK')
qed
qed
qed
} note ind_proof = this
have pre1 : "set (map q2_\<alpha> II) \<subseteq> S" unfolding S_def I_def by (rule accessible_subset_ws)
have pre2 : "distinct (map q2_\<alpha> II)" using dist_I[unfolded I_def] by simp
have pre3 : "\<forall>q\<in>set II. q2_invar q" using invar_I by simp
have pre4 : "dom (state_map_\<alpha> (qm.empty (), 0)) \<inter> set (map q2_\<alpha> II) = {}"
unfolding state_map_\<alpha>_def by (simp add: qm.correct o_def)
have pre5 : "state_map_invar (qm.empty (), 0)"
unfolding state_map_invar_def by (simp add: qm.correct)
have pre6 : "NFA_construct_reachable_map_OK S Map.empty {} (state_map_\<alpha> (qm.empty (), 0))"
unfolding NFA_construct_reachable_map_OK_def state_map_\<alpha>_def by (simp add: qm.correct o_def)
note ind_proof' = ind_proof [OF ]
obtain qm' n' Is' where res_eq: "NFA_construct_reachable_init_impl II = ((qm', n'), Is')" by (metis prod.exhaust)
note ind_proof' = ind_proof [OF pre1 pre2 pre3 pre4 pre5 _ _ pre6, of "s.empty ()" qm' n' Is',
folded NFA_construct_reachable_init_impl_def]
from ind_proof' show ?thesis
apply (rule_tac SPEC_refine_sv prod_rel_sv br_sv)+
apply (simp add: refine_hsimp
s.correct I_def res_eq S_def NFA_construct_reachable_map_OK_def in_br_conv)
done
qed
definition NFA_construct_reachable_impl_step_rel where
"NFA_construct_reachable_impl_step_rel =
build_rel (\<lambda>DS. {(a_\<alpha> as, q2_\<alpha> q') | as q'. (as, q') \<in> DS})
(\<lambda>DS. (\<forall>as q'. (as, q') \<in> DS \<longrightarrow> a_invar as \<and> q2_invar q') \<and>
(\<forall>as1 q1' as2 q2'. (as1, q1') \<in> DS \<and> (as2, q2') \<in> DS \<and>
(a_\<alpha> as1 = a_\<alpha> as2) \<and> (q2_\<alpha> q1' = q2_\<alpha> q2') \<longrightarrow> as1 = as2 \<and> q1' = q2'))"
definition NFA_construct_reachable_impl_step where
"NFA_construct_reachable_impl_step det DS qm0 n D0 q =
FOREACH (DS q) (\<lambda>(as, q') ((qm, n), DD', N). do {
let ((qm', n'), r') =
(let r'_opt = qm.lookup (ff q') qm in
if (r'_opt = None) then
((qm.update_dj (ff q') (states_enumerate n) qm, Suc n), states_enumerate n)
else
((qm, n), the r'_opt)
);
RETURN ((qm', n'), add_labels det (the (qm.lookup (ff q) qm0)) as r' DD', q' # N)
}) ((qm0, n), D0, [])"
lemma NFA_construct_reachable_impl_step_correct :
fixes D II
fixes q :: "'q2_rep"
defines "I \<equiv> map q2_\<alpha> II"
defines "S \<equiv> accessible (LTS_forget_labels D) (set I)"
assumes f_inj_on: "inj_on f S"
and ff_OK: "\<And>q. q2_invar q \<Longrightarrow> q2_\<alpha> q \<in> S \<Longrightarrow> ff q = f (q2_\<alpha> q)"
and d_add_OK: "dlts_add_label_set d.\<alpha> d.invar a_\<alpha> a_invar (add_labels True)"
"lts_add_label_set d.\<alpha> d.invar a_\<alpha> a_invar (add_labels False)"
and det_OK: "det \<Longrightarrow> LTS_is_deterministic D"
and DS'_OK: "\<And>q a q'. q \<in> S \<Longrightarrow> ((q, a, q') \<in> D) = (\<exists>as. a \<in> as \<and> (as, q') \<in> DS' q)"
and rm_eq: "rm = state_map_\<alpha> (qm0, n)"
and invar_qm0_n: "state_map_invar (qm0, n)"
and D0'_eq: "D0' = d.\<alpha> D0" "D0' = \<Delta> \<A>"
and invar_D0: "d.invar D0"
and rm_q: "rm (q2_\<alpha> q) = Some r"
and r_nin: "r \<notin> \<Q> \<A>"
and invar_q: "q2_invar q"
and q_in_S: "q2_\<alpha> q \<in> S"
and DS_OK: "(DS q, DS' (q2_\<alpha> q)) \<in> NFA_construct_reachable_impl_step_rel"
and weak_invar: "NFA_construct_reachable_abstract_impl_weak_invar I (l.\<alpha> A) FP D (rm, \<A>)"
notes refine_rel_defs[simp]
shows "NFA_construct_reachable_impl_step det DS qm0 n D0 q \<le>
\<Down> ((build_rel state_map_\<alpha> state_map_invar) \<times>\<^sub>r ((build_rel d.\<alpha> d.invar) \<times>\<^sub>r
(\<langle>build_rel q2_\<alpha> q2_invar\<rangle>list_rel)))
(NFA_construct_reachable_abstract_impl_step S DS' rm D0' (q2_\<alpha> q))"
unfolding NFA_construct_reachable_impl_step_def
NFA_construct_reachable_abstract_impl_step_def
using [[goals_limit = 1]]
apply (refine_rcg)
\<comment>\<open>preprocess goals\<close>
apply (subgoal_tac "inj_on (\<lambda>(as, q'). (a_\<alpha> as, q2_\<alpha> q')) (DS q)")
apply assumption
apply (insert DS_OK)[]
apply (simp add: inj_on_def Ball_def NFA_construct_reachable_impl_step_rel_def)
apply blast
\<comment>\<open>goal solved\<close>
apply (insert DS_OK)[]
apply (simp add: NFA_construct_reachable_impl_step_rel_def)
apply auto[]
\<comment>\<open>goal solved\<close>
apply (simp add: rm_eq D0'_eq invar_qm0_n invar_D0 refine_hsimp)
\<comment>\<open>goal solved\<close>
apply (clarify, simp add: refine_hsimp)+
apply (rename_tac it N as'' q'' qm n D' NN as' q')
apply (subgoal_tac "
RETURN
(let r'_opt = map_op_lookup qm_ops (ff q'') qm
in if r'_opt = None
then ((map_op_update_dj qm_ops (ff q'') (states_enumerate n) qm, Suc n), states_enumerate n)
else ((qm, n), the r'_opt))
\<le> \<Down> ((build_rel state_map_\<alpha> state_map_invar) \<times>\<^sub>r Id)
(SPEC (\<lambda>(rm', r').
NFA_construct_reachable_map_OK S (state_map_\<alpha> (qm, n)) {q2_\<alpha> q'} rm' \<and>
rm' (q2_\<alpha> q') = Some r'))")
apply assumption
apply (simp del: br_def prod_rel_def add: Let_def ff_OK pw_le_iff refine_pw_simps prod_rel_sv)
apply (simp)
apply (rule conjI)
apply (rule impI)
defer
apply (rule impI)
apply (erule exE)
apply (rename_tac r)
apply (simp)
defer
apply (clarify, simp)+
apply (rename_tac it N as'' q'' qm n D' NN r qm' n' as' q')
defer
using [[goals_limit = 10]]
proof -
fix it N as'' q' as' q'' qm n D'
assume aq'_in_it: "(as', q') \<in> it"
and aq''_in_it: "(as'', q'') \<in> it"
and it_subset: "it \<subseteq> DS q"
and a''_a'_eq: "a_\<alpha> as'' = a_\<alpha> as'"
and q''_q'_eq: "q2_\<alpha> q'' = q2_\<alpha> q'"
and q'_in_S: "q2_\<alpha> q' \<in> S"
let ?it' = "(\<lambda>(a, q'). (a_\<alpha> a, q2_\<alpha> q')) ` it"
assume invar_foreach: "NFA_construct_reachable_abstract_impl_foreach_invar S DS' rm D0' (q2_\<alpha> q) ?it'
(state_map_\<alpha> (qm, n), lts_op_\<alpha> d_ops D', N)"
and invar_qm_n: "state_map_invar (qm, n)"
and invar_D': "d.invar D'"
from aq'_in_it aq''_in_it it_subset DS_OK
have invar_q': "q2_invar q'" and invar_q'': "q2_invar q''"
and invar_as': "a_invar as'" and invar_as'': "a_invar as''"
by (auto simp add: NFA_construct_reachable_impl_step_rel_def)
from q'_in_S q''_q'_eq have q''_in_S: "q2_\<alpha> q'' \<in> S" by simp
from ff_OK[OF invar_q'' q''_in_S] q''_q'_eq have ff_q''_eq[simp]: "ff q'' = f (q2_\<alpha> q')" by simp
define D'' where "D'' \<equiv> DS' (q2_\<alpha> q) - ?it'"
from invar_foreach have
qm_OK: "NFA_construct_reachable_map_OK S rm (snd ` D'') (state_map_\<alpha> (qm, n))" and
set_N_eq: "set N = snd ` D''" and
D'_eq: "d.\<alpha> D' = D0' \<union>
{(the (state_map_\<alpha> (qm, n) (q2_\<alpha> q)), a, the (state_map_\<alpha> (qm, n) q')) | a as q'.
(as, q') \<in> D'' \<and> a \<in> as}"
unfolding NFA_construct_reachable_abstract_impl_foreach_invar.simps D''_def[symmetric]
by (simp_all add: Let_def)
{ \<comment>\<open>Consider the case that the map does not need to be extended\<close>
fix r
assume "qm.lookup (ff q'') qm = Some r"
with invar_qm_n qm_OK
show "NFA_construct_reachable_map_OK S (state_map_\<alpha> (qm, n)) {q2_\<alpha> q'} (state_map_\<alpha> (qm, n)) \<and>
state_map_\<alpha> (qm, n) (q2_\<alpha> q') = Some r"
by (simp add: state_map_\<alpha>_def qm.correct state_map_invar_def
NFA_construct_reachable_map_OK_def rm_eq dom_def)
}
{ \<comment>\<open>... and the case that the map needs to be extended.\<close>
assume "qm.lookup (ff q'') qm = None"
with invar_qm_n have q'_nin_dom: "q2_\<alpha> q' \<notin> dom (state_map_\<alpha> (qm, n))"
unfolding state_map_invar_def state_map_\<alpha>_def by (simp add: qm.correct dom_def)
from qm_OK have qm_OK':
"NFA_construct_reachable_map_OK S Map.empty {} (state_map_\<alpha> (qm, n))"
unfolding NFA_construct_reachable_map_OK_def by simp
define qm' where "qm' \<equiv> qm.update_dj (f (q2_\<alpha> q')) (states_enumerate n) qm"
from state_map_extend_thm [OF f_inj_on invar_qm_n q'_in_S q'_nin_dom qm_OK', folded qm'_def]
have invar_qm'_n: "state_map_invar (qm', Suc n)" and
qm'_alpha: "qm.\<alpha> qm' = qm.\<alpha> qm(f (q2_\<alpha> q') \<mapsto> states_enumerate n)" and
qm'_OK: "NFA_construct_reachable_map_OK S (state_map_\<alpha> (qm, n)) {q2_\<alpha> q'} (state_map_\<alpha> (qm', Suc n))"
by simp_all
from qm'_alpha have rm'_q': "state_map_\<alpha> (qm', Suc n) (q2_\<alpha> q') = Some (states_enumerate n)"
unfolding state_map_\<alpha>_def by simp
from invar_qm'_n qm'_OK rm'_q'
show "state_map_invar (map_op_update_dj qm_ops (ff q'') (states_enumerate n) qm, Suc n) \<and>
NFA_construct_reachable_map_OK S (state_map_\<alpha> (qm, n)) {q2_\<alpha> q'}
(state_map_\<alpha> (map_op_update_dj qm_ops (ff q'') (states_enumerate n) qm, Suc n)) \<and>
state_map_\<alpha> (map_op_update_dj qm_ops (ff q'') (states_enumerate n) qm, Suc n) (q2_\<alpha> q') =
Some (states_enumerate n)"
unfolding qm'_def[symmetric] ff_q''_eq by simp
}
{ \<comment>\<open>It remains to show that adding to the transition systems works. Here, a case distinction
depending on whether the input is weak deterministic, is needed.\<close>
fix r' qm' n'
assume r'_props: "(let r'_opt = map_op_lookup qm_ops (ff q'') qm
in if r'_opt = None
then ((map_op_update_dj qm_ops (ff q'')
(states_enumerate n) qm,
Suc n),
states_enumerate n)
else ((qm, n), the r'_opt)) =
((qm', n'), r')"
from qm_OK rm_q have r_intro1: "state_map_\<alpha> (qm, n) (q2_\<alpha> q) = Some r"
unfolding NFA_construct_reachable_map_OK_def by simp
from rm_q rm_eq have r_intro2: "qm.lookup (ff q) qm0 = Some r" using invar_qm0_n
unfolding state_map_\<alpha>_def state_map_invar_def
using ff_OK [OF invar_q q_in_S] by (simp add: qm.correct)
have "{(r, a, r') | a. a \<in> a_\<alpha> as'} \<union> d.\<alpha> D' = d.\<alpha> (add_labels det r as'' r' D') \<and>
d.invar (add_labels det r as'' r' D')"
proof (cases det)
case False
with lts_add_label_set.lts_add_label_set_correct[OF d_add_OK(2), OF invar_D' invar_as'', of r r']
show ?thesis by (auto simp add: a''_a'_eq)
next
case True note det_True[simp] = this
with det_OK have det_D: "LTS_is_deterministic D" by simp
{ fix a q'''
assume "a \<in> a_\<alpha> as''" "q''' \<noteq> r'"
from weak_invar obtain s where
rm_OK: "NFA_construct_reachable_map_OK S Map.empty (s \<union> set I \<union> {q'. \<exists>a q. q \<in> s \<and> (q, a, q') \<in> D}) rm" and
s_subset: "s \<subseteq> S" and
\<A>_eq: "\<A> = NFA_rename_states
\<lparr>\<Q> = s, \<Sigma> = set_op_\<alpha> l_ops A, \<Delta> = {qsq \<in> D. fst qsq \<in> s}, \<I> = set I,
\<F> = {q \<in> s. FP q}\<rparr>
(the \<circ> rm)"
unfolding NFA_construct_reachable_abstract_impl_weak_invar_def S_def[symmetric]
by blast
from r_nin
have r_nin_D0': "(r, a, q''') \<notin> D0'"
unfolding \<A>_eq D0'_eq(2) by (simp add: image_iff Ball_def) metis
{ fix as q''''
assume as_q''''_in_D'': "(as, q'''') \<in> D''"
and q'''_eq: "q''' = the (state_map_\<alpha> (qm, n) q'''')"
from as_q''''_in_D'' have "q'''' \<in> snd ` D''" by (simp add: image_iff Bex_def) blast
with qm_OK have "q'''' \<in> dom (state_map_\<alpha> (qm, n))"
unfolding NFA_construct_reachable_map_OK_def by (simp add: subset_iff)
with q'''_eq have qm_q''''_eq: "state_map_\<alpha> (qm, n) q'''' = Some q'''" by auto
from as_q''''_in_D'' have "(as, q'''') \<in> DS' (q2_\<alpha> q)"
unfolding D''_def by simp_all
with DS'_OK(1)[OF q_in_S, of a q'''']
have in_D1: "a \<in> as \<Longrightarrow> ((q2_\<alpha> q, a, q'''') \<in> D)" by metis
from aq'_in_it it_subset have "(as', q') \<in> DS q" by blast
with DS_OK have "(a_\<alpha> as', q2_\<alpha> q') \<in> DS' (q2_\<alpha> q)"
unfolding NFA_construct_reachable_impl_step_rel_def by auto
with DS'_OK(1)[OF q_in_S, of a "q2_\<alpha> q'"] `a \<in> a_\<alpha> as''` `a_\<alpha> as'' = a_\<alpha> as'`
have in_D2: "((q2_\<alpha> q, a, q2_\<alpha> q') \<in> D)" by metis
from `q''' \<noteq> r'` qm_q''''_eq r'_props invar_qm_n have q''''_neq: "q'''' \<noteq> q2_\<alpha> q'"
unfolding state_map_\<alpha>_def state_map_invar_def
by (auto simp add: qm.correct)
from in_D1 in_D2 q''''_neq det_D
have "a \<notin> as" unfolding LTS_is_deterministic_def by metis
}
hence "(r, a, q''') \<notin> d.\<alpha> D'"
by (simp add: D'_eq r_intro1 r_nin_D0')
} note d_add = this
from dlts_add_label_set.dlts_add_label_set_correct[OF d_add_OK(1), OF invar_D' invar_as'' d_add, of r']
show ?thesis by (auto simp add: a''_a'_eq)
qed
thus "{(the (state_map_\<alpha> (qm, n) (q2_\<alpha> q)), a, r') |a. a \<in> a_\<alpha> as'} \<union> d.\<alpha> D' =
d.\<alpha> (add_labels det (the (map_op_lookup qm_ops (ff q) qm0)) as'' r' D') \<and>
d.invar (add_labels det (the (map_op_lookup qm_ops (ff q) qm0)) as'' r' D') \<and>
q2_invar q'' "
unfolding r_intro1 r_intro2 option.sel ff_OK[OF invar_q]
by (simp add: invar_q'')
}
qed
definition NFA_construct_reachable_impl where
"NFA_construct_reachable_impl det S I A FP DS =
do {
let ((qm, n), Is) = NFA_construct_reachable_init_impl I;
(((qm, n), \<A>::('q_set, 'a_set, 'd) NFA_impl), _) \<leftarrow> WORKLISTT (\<lambda>_. True)
(\<lambda>((qm, n), AA) q.
if (s.memb (the (qm.lookup (ff q) qm)) (nfa_states AA)) then
(RETURN (((qm, n), AA), []))
else
do {
ASSERT (q2_invar q \<and> q2_\<alpha> q \<in> S);
((qm', n'), DD', N) \<leftarrow> NFA_construct_reachable_impl_step det DS qm n (nfa_trans AA) q;
RETURN (((qm', n'),
(s.ins_dj (the (qm.lookup (ff q) qm)) (nfa_states AA),
nfa_labels AA, DD', nfa_initial AA,
(if (FP q) then (s.ins_dj (the (qm.lookup (ff q) qm)))
(nfa_accepting AA) else (nfa_accepting AA)), nfa_props AA)), N)
}
) (((qm, n), (s.empty (), A, d.empty (), Is, s.empty (), nfa_props_connected det)), I);
RETURN \<A>
}"
lemma NFA_construct_reachable_impl_correct :
fixes D II det
defines "I \<equiv> map q2_\<alpha> II"
defines "invar' \<equiv> (\<lambda>A. nfa_invar_no_props A \<and> nfa_props A = nfa_props_connected det)"
defines "R \<equiv> build_rel nfa_\<alpha> invar'"
defines "R' \<equiv> build_rel state_map_\<alpha> state_map_invar"
defines "S \<equiv> accessible (LTS_forget_labels D) (set I)"
assumes f_inj_on: "inj_on f S"
and ff_OK: "\<And>q. q2_invar q \<Longrightarrow> q2_\<alpha> q \<in> S \<Longrightarrow> ff q = f (q2_\<alpha> q)"
and d_add_OK: "dlts_add_label_set d.\<alpha> d.invar a_\<alpha> a_invar (add_labels True)"
"lts_add_label_set d.\<alpha> d.invar a_\<alpha> a_invar (add_labels False)"
and det_OK: "det \<Longrightarrow> LTS_is_deterministic D"
and DS'_OK: "\<And>q a q'. q \<in> S \<Longrightarrow> ((q, a, q') \<in> D) = (\<exists>as. a \<in> as \<and> (as, q') \<in> DS' q)"
and dist_I: "distinct I"
and invar_I: "\<And>q. q \<in> set II \<Longrightarrow> q2_invar q"
and invar_A: "l.invar A"
and DS_OK: "\<And>q. q2_invar q \<Longrightarrow> q2_\<alpha> q \<in> S \<Longrightarrow> (DS q, DS' (q2_\<alpha> q)) \<in> NFA_construct_reachable_impl_step_rel"
and FFP_OK: "\<And>q. q2_invar q \<Longrightarrow> q2_\<alpha> q \<in> S \<Longrightarrow> FFP q \<longleftrightarrow> FP (q2_\<alpha> q)"
notes refine_rel_defs[simp]
shows "NFA_construct_reachable_impl det S II A FFP DS \<le>
\<Down>R (NFA_construct_reachable_abstract2_impl I (l.\<alpha> A) FP D DS')"
unfolding NFA_construct_reachable_impl_def NFA_construct_reachable_abstract2_impl_def WORKLISTT_def
using [[goals_limit = 14]]
apply (refine_rcg)
\<comment>\<open>preprocess goals\<close>
\<comment>\<open>initialisation is OK\<close>
apply (unfold I_def)
apply (rule NFA_construct_reachable_init_impl_correct)
apply (insert f_inj_on ff_OK dist_I invar_I)[4]
apply (simp_all add: S_def I_def)[4]
\<comment>\<open>goal solved\<close>
apply (subgoal_tac "single_valued (R' \<times>\<^sub>r R)")
apply assumption
apply (simp add: prod_rel_sv R'_def R_def del: prod_rel_def br_def)
\<comment>\<open>goal solved\<close>
apply (subgoal_tac "single_valued (build_rel q2_\<alpha> q2_invar)")
apply assumption
apply (simp del: br_def)
\<comment>\<open>goal solved\<close>
apply (simp add: R'_def R_def nfa_invar_weak2_def invar'_def
nfa_invar_no_props_def nfa_invar_props_def
s.correct d.correct_common invar_A)
\<comment>\<open>goal solved\<close>
using invar_I map_in_list_rel_conv apply blast
\<comment>\<open>goal solved\<close>
apply simp
\<comment>\<open>goal solved\<close>
apply simp
\<comment>\<open>goal solved\<close>
apply (clarify, simp)+
apply (rename_tac q rm \<A> qm n Qs As DD Is Fs p r)
defer
apply (simp add: prod_rel_sv R'_def R_def del: prod_rel_def br_def)
\<comment>\<open>goal solved\<close>
apply (simp del: br_def add: in_br_conv)
\<comment>\<open>goal solved\<close>
apply (simp add: in_br_conv I_def S_def)
\<comment>\<open>goal solved\<close>
(* apply clarify *)
(* apply (simp del: br_def add: in_br_conv S_def I_def R_def R'_def) *)
apply (subgoal_tac "\<And>x' x1 x2 x1a x1b x2a x2b s e s' e' x1c x2c x1d x1e x2d x2e.
\<lbrakk>(NFA_construct_reachable_init_impl II, x') \<in> br state_map_\<alpha> state_map_invar \<times>\<^sub>r br s.\<alpha> s.invar; x' = (x1, x2); x1a = (x1b, x2a); NFA_construct_reachable_init_impl II = (x1a, x2b); (s, s') \<in> R' \<times>\<^sub>r R;
(e, e') \<in> br q2_\<alpha> q2_invar; True; True; s' = (x1c, x2c); x1d = (x1e, x2d); s = (x1d, x2e);
e' \<in> dom x1c \<and> e' \<in> accessible (LTS_forget_labels D) (set (map q2_\<alpha> II)) \<and> NFA_construct_reachable_abstract_impl_weak_invar (map q2_\<alpha> II) (l.\<alpha> A) FP D (x1c, x2c); \<not> s.memb (the (qm.lookup (ff e) x1e)) (nfa_states x2e);
the (x1c e') \<notin> \<Q> x2c; q2_invar e \<and> q2_\<alpha> e \<in> S\<rbrakk>
\<Longrightarrow> NFA_construct_reachable_impl_step det DS x1e x2d (nfa_trans x2e) e
\<le> \<Down> (br state_map_\<alpha> state_map_invar \<times>\<^sub>r br d.\<alpha> d.invar \<times>\<^sub>r \<langle>br q2_\<alpha> q2_invar\<rangle>list_rel) (NFA_construct_reachable_abstract_impl_step (accessible (LTS_forget_labels D) (set (map q2_\<alpha> II))) DS' x1c (\<Delta> x2c) e')")
apply blast
apply (clarify, simp)
apply (rule_tac \<A> = "nfa_\<alpha> (ay, az, bm, bn, bo, bp)" in NFA_construct_reachable_impl_step_correct[simplified])
apply (metis I_def S_def f_inj_on image_set)
apply (metis ff_OK I_def S_def image_set)
using d_add_OK(1) apply blast
using d_add_OK(2) apply blast
using det_OK apply blast
apply (simp add: DS'_OK I_def S_def)
apply (simp add: in_br_conv R'_def)
apply (simp add: in_br_conv R'_def)
apply (simp add: R_def)
apply (simp add: in_br_conv R_def)
apply (simp add: R_def invar'_def nfa_by_lts_defs.nfa_invar_no_props_def nfa_by_lts_defs_axioms)
apply (subgoal_tac "\<And>x1b x2a x2b e e' x1c x2c x1e x2d aj ak al am an bf x1f x1ba ea e'a x1ca x2ca x1ea x2da ay az bm bn bo bp y ya.
\<lbrakk>state_map_invar (x1b, x2a) \<and> s.invar x2b; x1ba = x1b; ((x1e, x2d), x1c) \<in> R' \<and> ((aj, ak, al, am, an, bf), x2c) \<in> R; e' = q2_\<alpha> e; \<not> s.memb (the (qm.lookup (ff e) x1e)) aj; y \<notin> \<Q> x2c; x1f = state_map_\<alpha> (x1b, x2a);
NFA_construct_reachable_init_impl II = ((x1b, x2a), x2b); ((x1ea, x2da), x1ca) \<in> R' \<and> ((ay, az, bm, bn, bo, bp), x2ca) \<in> R; e'a = q2_\<alpha> ea; \<not> s.memb (the (qm.lookup (ff ea) x1ea)) ay; ya \<notin> \<Q> x2ca; x1c (q2_\<alpha> e) = Some y;
q2_invar e; q2_\<alpha> e \<in> S; x1ca (q2_\<alpha> ea) = Some ya; q2_invar ea; q2_\<alpha> ea \<in> S; q2_\<alpha> e \<in> accessible (LTS_forget_labels D) (q2_\<alpha> ` set II);
NFA_construct_reachable_abstract_impl_weak_invar (map q2_\<alpha> II) (l.\<alpha> A) FP D (x1c, x2c); q2_\<alpha> ea \<in> accessible (LTS_forget_labels D) (q2_\<alpha> ` set II);
NFA_construct_reachable_abstract_impl_weak_invar (map q2_\<alpha> II) (l.\<alpha> A) FP D (x1ca, x2ca)\<rbrakk>
\<Longrightarrow> x1ca (q2_\<alpha> ea) = Some ya") (* Maybe not \<open>Some ya\<close> but something like \<open>(qm.lookup (ff ea) x1ea)\<close> *)
apply blast
apply (clarify, simp add: R'_def R_def ff_OK state_map_\<alpha>_def)
apply blast
apply blast
apply (simp add: DS_OK)
apply (clarify, simp add: R_def)
apply (clarify)
apply (simp add: R_def R'_def)
apply (rename_tac x1b x2a x2b q q2 qm n Qs As D0 Is Fs ps v1 v2 v3 v4 v5 r)
apply (intro conjI impI)
apply (clarify)
apply (simp add: invar'_def nfa_invar_no_props_def nfa_selectors_def s.correct state_map_invar_def state_map_\<alpha>_def qm.correct)
defer
apply (simp add: invar'_def nfa_invar_no_props_def)
apply (intro conjI)
using s.ins_dj_correct(2) s.memb_correct apply blast
apply (rule_tac s.ins_dj_correct(2))
apply blast
defer
using FFP_OK apply blast
apply (simp add: invar'_def nfa_invar_no_props_def)
apply (intro conjI)
using FFP_OK apply blast
using FFP_OK apply blast
using FFP_OK apply blast
using FFP_OK apply blast
apply (simp add: ff_OK state_map_\<alpha>_def invar'_def nfa_invar_no_props_def state_map_invar_def qm.lookup_correct s.ins_dj_correct(1))
apply (simp add: invar'_def nfa_by_lts_defs.nfa_invar_no_props_def nfa_by_lts_defs_axioms s.ins_dj_correct(2) s.memb_correct)
apply (simp add: in_br_conv R_def)
apply (simp add: R_def R'_def invar'_def state_map_invar_def state_map_\<alpha>_def I_def S_def ff_OK nfa_invar_no_props_def nfa_by_lts_defs_axioms qm.lookup_correct s.memb_correct)
apply (clarify, simp add: R_def R'_def invar'_def state_map_invar_def state_map_\<alpha>_def I_def S_def ff_OK nfa_invar_no_props_def nfa_by_lts_defs_axioms qm.lookup_correct s.memb_correct)
defer
apply (clarify, simp add: R_def R'_def invar'_def state_map_invar_def state_map_\<alpha>_def I_def[symmetric] S_def ff_OK nfa_invar_no_props_def nfa_by_lts_defs_axioms qm.lookup_correct s.memb_correct)
proof-
fix x1b x2a x2b q qm n Qs As D0 Is Fs v1 v2 v3 v4 v5 r
assume asm:
"NFA_construct_reachable_init_impl II = ((x1b, x2a), x2b)"
"r \<notin> s.\<alpha> Qs"
"qm.\<alpha> qm (f (q2_\<alpha> q)) = Some r"
"q2_invar q" "q2_\<alpha> q \<in> accessible (LTS_forget_labels D) (q2_\<alpha> ` set II)"
"NFA_construct_reachable_abstract_impl_weak_invar I (l.\<alpha> A) FP D (qm.\<alpha> qm \<circ> f, nfa_\<alpha> (Qs, As, D0, Is, Fs, \<lparr>nfa_prop_is_complete_deterministic = det, nfa_prop_is_initially_connected = True\<rparr>))"
"FFP q"
"FP (q2_\<alpha> q)"
"qm.invar x1b \<and> (\<forall>i q. qm.\<alpha> x1b i = Some q \<longrightarrow> (\<exists>n'<x2a. q = states_enumerate n'))"
"s.invar x2b"
"qm.invar qm \<and> (\<forall>i q. qm.\<alpha> qm i = Some q \<longrightarrow> (\<exists>n'<n. q = states_enumerate n'))"
"qm.invar v2 \<and> (\<forall>i q. qm.\<alpha> v2 i = Some q \<longrightarrow> (\<exists>n'<v3. q = states_enumerate n'))"
"s.invar Qs" "d.invar v4" "list_all2 (\<lambda>x x'. x' = q2_\<alpha> x \<and> q2_invar x) v5 v1" "l.invar As" "d.invar D0" "s.invar Is" "s.invar Fs" "r \<in> s.\<alpha> Fs"
let ?A = "nfa_\<alpha> (Qs, As, D0, Is, Fs, \<lparr>nfa_prop_is_complete_deterministic = det, nfa_prop_is_initially_connected = True\<rparr>)"
have "NFA ?A"
unfolding nfa_\<alpha>_def NFA_def using asm
apply auto
unfolding FinSemiAutomaton_def
apply (intro conjI)
defer
unfolding FinSemiAutomaton_axioms_def
apply simp
unfolding NFA_axioms_def
apply (intro conjI)
apply simp
defer
apply simp
sorry
moreover have "\<Q> ?A = s.\<alpha> Qs" "\<F> ?A = s.\<alpha> Fs"
by simp+
ultimately show False
using asm(2, 20) NFA.\<F>_consistent[of ?A] by blast
next
fix x1b x2a x2b q qm n Qs As D0 Is Fs v1 v2 v3 v4 v5 r
assume asm:
"NFA_construct_reachable_init_impl II = ((x1b, x2a), x2b)" "r \<notin> s.\<alpha> Qs" "qm.\<alpha> qm (f (q2_\<alpha> q)) = Some r" "q2_invar q" "q2_\<alpha> q \<in> accessible (LTS_forget_labels D) (q2_\<alpha> ` set II)"
"NFA_construct_reachable_abstract_impl_weak_invar (map q2_\<alpha> II) (l.\<alpha> A) FP D (qm.\<alpha> qm \<circ> f, nfa_\<alpha> (Qs, As, D0, Is, Fs, \<lparr>nfa_prop_is_complete_deterministic = det, nfa_prop_is_initially_connected = True\<rparr>))"
"FFP q" "FP (q2_\<alpha> q)" "s.invar x2b" "d.invar v4" "list_all2 (\<lambda>x x'. x' = q2_\<alpha> x \<and> q2_invar x) v5 v1" "qm.invar x1b" "\<forall>i q. qm.\<alpha> x1b i = Some q \<longrightarrow> (\<exists>n'<x2a. q = states_enumerate n')" "qm.invar qm"
"\<forall>i q. qm.\<alpha> qm i = Some q \<longrightarrow> (\<exists>n'<n. q = states_enumerate n')" "s.invar Qs" "qm.invar v2" "\<forall>i q. qm.\<alpha> v2 i = Some q \<longrightarrow> (\<exists>n'<v3. q = states_enumerate n')" "l.invar As" "d.invar D0" "s.invar Is" "s.invar Fs"
from \<open>r \<notin> s.\<alpha> Qs\<close> have r_not_in_Fs:"r \<notin> s.\<alpha> Fs"
sorry
show "\<lparr>\<Q> = insert r (s.\<alpha> Qs), \<Sigma> = l.\<alpha> As, \<Delta> = d.\<alpha> v4, \<I> = s.\<alpha> Is, \<F> = insert r (s.\<alpha> Fs)\<rparr> =
nfa_\<alpha> (s.ins_dj r Qs, As, v4, Is, s.ins_dj r Fs, \<lparr>nfa_prop_is_complete_deterministic = det, nfa_prop_is_initially_connected = True\<rparr>)"
apply (unfold nfa_\<alpha>_def)
apply (simp add: s.ins_dj_correct)
using s.ins_dj_correct(1)[OF \<open>s.invar Fs\<close> r_not_in_Fs] apply auto
by (simp add: \<open>s.invar Qs\<close> \<open>r \<notin> s.\<alpha> Qs\<close> s.ins_dj_correct(1))+
qed
(*
\<comment>\<open>goal solved\<close>
apply clarify
apply (simp add: in_br_conv split: if_split)
apply auto[]
\<comment>\<open>goal solved\<close>
apply (simp add: in_br_conv)
\<comment>\<open>goal solved\<close>
defer
apply clarify
apply (simp)
apply (rename_tac q qm n Qs As D0 Is Fs ps r)
*)
(*
\<comment>\<open>step OK\<close>
apply (unfold I_def[symmetric])
apply (simp add: R'_def R_def)
apply (clarify, simp)+
apply (unfold I_def)
apply (rule_tac \<A> = "nfa_\<alpha> (ak, al, am, an, ao, bg)" in NFA_construct_reachable_impl_step_correct)
apply (unfold I_def[symmetric])
apply (simp_all add: invar'_def nfa_invar_no_props_def f_inj_on[unfolded S_def] ff_OK[unfolded S_def]
DS_OK[unfolded S_def] DS'_OK[unfolded S_def] d_add_OK det_OK) [17]
\<comment>\<open>goal solved\<close>
apply (simp add: prod_rel_sv R'_def R_def del: prod_rel_def br_def)
\<comment>\<open>goal solved\<close>
apply (simp del: br_def)
\<comment>\<open>goal solved\<close>
apply (clarify, simp split del: if_splits add: R'_def)+
apply (unfold S_def[symmetric] nfa_accepting_def snd_conv)
apply (rename_tac qm'' n'' bba q' \<A> qm n Qs As DD Is Fs p bga qm' n' D' bja r)
apply (unfold fst_conv)
defer
apply (simp del: br_def add: R_def)
\<comment>\<open>goal solved\<close>
apply simp
\<comment>\<open>goal solved\<close>
*)
(* using [[goals_limit = 6]] *)
(*
proof -
fix q rm \<A> qm n Qs As DD Is Fs p r
assume rm_q: "rm (q2_\<alpha> q) = Some r" and
in_R': "((qm, n), rm) \<in> R'" and
in_R: "((Qs, As, DD, Is, Fs, p), \<A>) \<in> R" and
invar_q: "q2_invar q" and
q_in: "q2_\<alpha> q \<in> accessible (LTS_forget_labels D) (q2_\<alpha> ` set II)"
from q_in have q_in_S: "q2_\<alpha> q \<in> S" unfolding S_def I_def by simp
from in_R' rm_q ff_OK[OF invar_q q_in_S] have "qm.lookup (ff q) qm = Some r"
unfolding R'_def by (simp add: state_map_invar_def state_map_\<alpha>_def qm.correct)
with in_R show "s.memb (the (qm.lookup (ff q) qm)) Qs = (r \<in> \<Q> \<A>)"
unfolding R_def by (simp add: invar'_def nfa_invar_no_props_def
nfa_selectors_def s.correct)
next
fix q qm n Qs As D0 Is Fs ps r
assume asm:
"\<not> s.memb (the (qm.lookup (ff q) qm)) Qs"
"r \<notin> s.\<alpha> Qs"
"state_map_\<alpha> (qm, n) (q2_\<alpha> q) = Some r"
"q2_invar q"
"q2_\<alpha> q \<in> accessible (LTS_forget_labels D) (q2_\<alpha> ` set II)"
"NFA_construct_reachable_abstract_impl_weak_invar (map q2_\<alpha> II) (l.\<alpha> A) FP D (state_map_\<alpha> (qm, n), nfa_\<alpha> (Qs, As, D0, Is, Fs, ps))"
"state_map_invar (qm, n)"
"invar' (Qs, As, D0, Is, Fs, ps)"
have map_I:"q2_\<alpha> ` set II = set I" using I_def by simp
have inj_on_f:"inj_on f (accessible (LTS_forget_labels D) (set I))"
using S_def f_inj_on by blast
have q2_1:"\<And>q. \<lbrakk>q2_invar q; q2_\<alpha> q \<in> accessible (LTS_forget_labels D) (set I)\<rbrakk> \<Longrightarrow> ff q = f (q2_\<alpha> q)"
by (simp add: S_def ff_OK)
have q2_2:"\<And>q. \<lbrakk>q2_invar q; q2_\<alpha> q \<in> accessible (LTS_forget_labels D) (set I)\<rbrakk> \<Longrightarrow> q2_invar q"
by simp
have q2_3:"\<And>q. \<lbrakk>q2_invar q; q2_\<alpha> q \<in> accessible (LTS_forget_labels D) (set I)\<rbrakk> \<Longrightarrow> q2_\<alpha> q \<in> accessible (LTS_forget_labels D) (set I)"
by simp
have add_lb:"dlts_add_label_set d.\<alpha> d.invar a_\<alpha> a_invar (add_labels True)"
"lts_add_label_set d.\<alpha> d.invar a_\<alpha> a_invar (add_labels False)"
using d_add_OK by blast+
have det:"det \<Longrightarrow> LTS_is_deterministic D"
using det_OK by blast
have acc:"\<And>q a q'. q \<in> accessible (LTS_forget_labels D) (set I) \<Longrightarrow> ((q, a, q') \<in> D) = (\<exists>as. a \<in> as \<and> (as, q') \<in> DS' q)"
"\<And>q a q'. q \<in> accessible (LTS_forget_labels D) (set I) \<Longrightarrow> q \<in> accessible (LTS_forget_labels D) (set I)"
by (simp add: DS'_OK S_def)
have invar_qm_n:"state_map_invar (qm, n)"
using asm(7) by blast
have D0_nfa: "d.\<alpha> D0 = \<Delta> (nfa_\<alpha> (Qs, As, D0, Is, Fs, ps))"
by simp
have invar_D0: "d.invar D0"
using asm(8) invar'_def nfa_invar_no_props_def by simp
note some_r=asm(3)
have r_not_in_Q:"r \<notin> \<Q> (nfa_\<alpha> (Qs, As, D0, Is, Fs, ps))"
by (simp add: asm(2))
have q2_acc:"q2_\<alpha> q \<in> accessible (LTS_forget_labels D) (set I)"
using asm(5,6) map_I by simp
have nfa_construct_mem:"(DS q, DS' (q2_\<alpha> q)) \<in> NFA_construct_reachable_impl_step_rel"
by (simp add: DS_OK S_def q2_acc asm(4))
have nfa_construct_invar:"NFA_construct_reachable_abstract_impl_weak_invar I (l.\<alpha> A) FP D (state_map_\<alpha> (qm, n), nfa_\<alpha> (Qs, As, D0, Is, Fs, ps))"
by (simp add: I_def asm(6))
from NFA_construct_reachable_impl_step_correct[of D II det DS' "state_map_\<alpha> (qm, n)" qm n "d.\<alpha> D0" D0 "nfa_\<alpha> (Qs, As, D0, Is, Fs, ps)" q r DS A FP]
have aux:"NFA_construct_reachable_impl_step det DS qm n D0 q
\<le> \<Down> (br state_map_\<alpha> state_map_invar \<times>\<^sub>r br d.\<alpha> d.invar \<times>\<^sub>r \<langle>br q2_\<alpha> q2_invar\<rangle>list_rel)
(NFA_construct_reachable_abstract_impl_step (accessible (LTS_forget_labels D) (set I)) DS' (state_map_\<alpha> (qm, n)) (d.\<alpha> D0) (q2_\<alpha> q))"
using D0_nfa DS'_OK I_def S_def asm(4) asm(6) d_add_OK(1) d_add_OK(2) det_OK f_inj_on ff_OK invar_D0 invar_qm_n nfa_construct_mem q2_acc r_not_in_Q some_r by blast
(*
have empty:"(br state_map_\<alpha> state_map_invar \<times>\<^sub>r br d.\<alpha> d.invar \<times>\<^sub>r \<langle>br q2_\<alpha> q2_invar\<rangle>list_rel) = {}"
apply simp
apply (intro impI allI)
apply (unfold state_map_invar_def)
apply (auto)
apply (rename_tac q1 q2 qm D n)
sorry
*)
note DS_OK_of_q=DS_OK[of q, simplified NFA_construct_reachable_impl_step_rel_def in_br_conv, OF asm(4) q2_acc[simplified S_def[symmetric]]]
show "NFA_construct_reachable_impl_step det DS qm n D0 q
\<le> \<Down> {} (NFA_construct_reachable_abstract_impl_step (accessible (LTS_forget_labels D) (q2_\<alpha> ` set II)) DS' (state_map_\<alpha> (qm, n)) (d.\<alpha> D0) (q2_\<alpha> q))"
apply (simp_all add: map_I)
apply (simp add: NFA_construct_reachable_abstract_impl_step_def)
apply (unfold NFA_construct_reachable_impl_step_def)
apply (refine_rcg)
defer
apply (subgoal_tac " DS' (q2_\<alpha> q) = (\<lambda>(as, q'). (a_\<alpha> as, q2_\<alpha> q')) ` DS q")
using DS_OK_of_q apply auto
defer
apply (auto simp add: inj_on_def)
proof-
assume
DS'_DS:"DS' (q2_\<alpha> q) = {(a_\<alpha> as, q2_\<alpha> q') |as q'. (as, q') \<in> DS q}" and
DS_invar:"\<forall>as q'. (as, q') \<in> DS q \<longrightarrow> a_invar as \<and> q2_invar q'" and
DS_inj_on_abs:"\<forall>as1 q1' as2 q2'. (as1, q1') \<in> DS q \<and> (as2, q2') \<in> DS q \<and> a_\<alpha> as1 = a_\<alpha> as2 \<and> q2_\<alpha> q1' = q2_\<alpha> q2' \<longrightarrow> as1 = as2 \<and> q1' = q2'"
let ?f = "\<lambda>(as, q'). (a_\<alpha> as, q2_\<alpha> q')"
from DS_inj_on_abs have "inj_on ?f (DS q)"
by (auto simp add: inj_on_def)
show False
sorry
qed
qed
*)
lemma NFA_construct_reachable_impl_alt_def :
"NFA_construct_reachable_impl det S I A FP DS =
do {
let ((qm, n), Is) = NFA_construct_reachable_init_impl I;
((_, \<A>), _) \<leftarrow> WORKLISTT (\<lambda>_. True)
(\<lambda>((qm, n), (Qs, As, DD, Is, Fs, p)) q. do {
let r = the (qm.lookup (ff q) qm);
if (s.memb r Qs) then
(RETURN (((qm, n), (Qs, As, DD, Is, Fs, p)), []))
else
do {
ASSERT (q2_invar q \<and> q2_\<alpha> q \<in> S);
((qm', n'), DD', N) \<leftarrow> NFA_construct_reachable_impl_step det DS qm n DD q;
RETURN (((qm', n'),
(s.ins_dj r Qs,
As, DD', Is,
(if (FP q) then (s.ins_dj r Fs) else Fs), p)), N)
}
}
) (((qm, n), (s.empty (), A, d.empty (), Is, s.empty (), nfa_props_connected det)), I);
RETURN \<A>
}"
unfolding NFA_construct_reachable_impl_def
apply (simp add: Let_def split_def)
apply (unfold nfa_selectors_def fst_conv snd_conv prod.collapse)
apply simp
done
schematic_goal NFA_construct_reachable_impl_code_aux:
fixes D_it :: "'q2_rep \<Rightarrow> (('as \<times> 'q2_rep),('m \<times> nat) \<times> 'd \<times> 'q2_rep list) set_iterator"
assumes D_it_OK[rule_format, refine_transfer]: "\<forall>q. q2_invar q \<longrightarrow> q2_\<alpha> q \<in> S \<longrightarrow> set_iterator (D_it q) (DS q)"
shows "RETURN ?f \<le> NFA_construct_reachable_impl det S I A FP DS"
unfolding NFA_construct_reachable_impl_alt_def WORKLISTT_def NFA_construct_reachable_impl_step_def
apply (unfold split_def snd_conv fst_conv prod.collapse)
apply (rule refine_transfer | assumption | erule conjE)+
done
definition (in nfa_by_lts_defs) NFA_construct_reachable_impl_code where
"NFA_construct_reachable_impl_code add_labels qm_ops det (ff::'q2_rep \<Rightarrow> 'i) I A FP D_it =
(let ((qm, n), Is) = foldl (\<lambda>((qm, n), Is) q. ((map_op_update_dj qm_ops (ff q) (states_enumerate n) qm, Suc n),
s.ins_dj (states_enumerate n) Is))
((map_op_empty qm_ops (), 0), s.empty ()) I;
((_, AA::('q_set, 'a_set, 'd) NFA_impl), _) = worklist (\<lambda>_. True)
(\<lambda>((qm, n), Qs, As, DD, Is, Fs, p) (q::'q2_rep).
let r = the (map_op_lookup qm_ops (ff q) qm)
in if set_op_memb s_ops r Qs then (((qm, n), Qs, As, DD, Is, Fs, p), [])
else let ((qm', n'), DD', N) = D_it q (\<lambda>_::(('m \<times> nat) \<times> 'd \<times> 'q2_rep list). True)
(\<lambda>(a, q') ((qm::'m, n::nat), DD'::'d, N::'q2_rep list).
let r'_opt = map_op_lookup qm_ops (ff q') qm;
((qm', n'), r') = if r'_opt = None then
let r'' = states_enumerate n in
((map_op_update_dj qm_ops (ff q') r'' qm, Suc n), r'')
else ((qm, n), the r'_opt)
in ((qm', n'), add_labels det r a r' DD', q' # N))
((qm, n), DD, [])
in (((qm', n'), set_op_ins_dj s_ops r Qs, As, DD', Is, if FP q then set_op_ins_dj s_ops r Fs else Fs,
p), N))
(((qm, n), set_op_empty s_ops (), A, lts_op_empty d_ops (), Is, set_op_empty s_ops (), nfa_props_connected det), I)
in AA)"
lemma NFA_construct_reachable_impl_code_correct:
fixes D_it :: "'q2_rep \<Rightarrow> (('as \<times> 'q2_rep),('m \<times> nat) \<times> 'd \<times> 'q2_rep list) set_iterator"
assumes D_it_OK: "\<forall>q. q2_invar q \<longrightarrow> q2_\<alpha> q \<in> S \<longrightarrow> set_iterator (D_it q) (DS q)"
shows "RETURN (NFA_construct_reachable_impl_code add_labels qm_ops det ff I A FP D_it) \<le>
NFA_construct_reachable_impl det S I A FP DS"
proof -
have rule: "\<And>f1 f2. \<lbrakk>RETURN f1 \<le> NFA_construct_reachable_impl det S I A FP DS; f1 = f2\<rbrakk> \<Longrightarrow>
RETURN f2 \<le> NFA_construct_reachable_impl det S I A FP DS" by simp
note aux_thm = NFA_construct_reachable_impl_code_aux[OF D_it_OK, of I det FP A]
note rule' = rule[OF aux_thm]
show ?thesis
apply (rule rule')
apply (simp add: NFA_construct_reachable_impl_code_def split_def Let_def NFA_construct_reachable_init_impl_def
cong: if_cong)
done
qed
lemma NFA_construct_reachable_impl_code_correct_full:
fixes D_it :: "'q2_rep \<Rightarrow> (('as \<times> 'q2_rep),('m \<times> nat) \<times> 'd \<times> 'q2_rep list) set_iterator"
fixes II D
defines "S \<equiv> accessible (LTS_forget_labels D) (set (map q2_\<alpha> II))"
assumes f_inj_on: "inj_on f S"
and ff_OK: "\<And>q. q2_invar q \<Longrightarrow> q2_\<alpha> q \<in> S \<Longrightarrow> ff q = f (q2_\<alpha> q)"
and d_add_OK: "dlts_add_label_set d.\<alpha> d.invar a_\<alpha> a_invar (add_labels True)"
"lts_add_label_set d.\<alpha> d.invar a_\<alpha> a_invar (add_labels False)"
and det_OK: "det \<Longrightarrow> LTS_is_deterministic D"
and DS_q_OK: "\<And>q a q'. q \<in> S \<Longrightarrow> ((q, a, q') \<in> D) = (\<exists>as. a \<in> as \<and> (as, q') \<in> DS_q q)"
"\<And>q as q'. q \<in> S \<Longrightarrow> (as, q') \<in> DS_q q \<Longrightarrow> as \<noteq> {}"
and dist_I: "distinct (map q2_\<alpha> II)"
and invar_I: "\<And>q. q \<in> set II \<Longrightarrow> q2_invar q"
and invar_A: "l.invar A"
and fin_S: "finite S"
and fin_D: "\<And>q. finite {(a, q'). (q, a, q') \<in> D}"
and D_it_OK: "\<And>q. q2_invar q \<Longrightarrow> q2_\<alpha> q \<in> S \<Longrightarrow> set_iterator_abs
(\<lambda>(as, q). (a_\<alpha> as, q2_\<alpha> q)) (\<lambda>(as, q). a_invar as \<and> q2_invar q) (D_it q) (DS_q (q2_\<alpha> q))"
and FFP_OK: "\<And>q. q2_invar q \<Longrightarrow> q2_\<alpha> q \<in> S \<Longrightarrow> FFP q \<longleftrightarrow> FP (q2_\<alpha> q)"
shows "NFA_isomorphic (NFA_construct_reachable (set (map q2_\<alpha> II)) (l.\<alpha> A) FP D)
(nfa_\<alpha> (NFA_construct_reachable_impl_code add_labels qm_ops det ff II A FFP D_it)) \<and>
nfa_invar_no_props (NFA_construct_reachable_impl_code add_labels qm_ops det ff II A FFP D_it) \<and>
nfa_props (NFA_construct_reachable_impl_code add_labels qm_ops det ff II A FFP D_it) =
nfa_props_connected det"
proof -
{ fix q
assume "q2_invar q" "q2_\<alpha> q \<in> S"
with D_it_OK[of q]
have it_abs: "set_iterator_abs (\<lambda>(as, q). (a_\<alpha> as, q2_\<alpha> q)) (\<lambda>(as, q). a_invar as \<and> q2_invar q)
(D_it q) (DS_q (q2_\<alpha> q))"
by simp
note set_iterator_abs_genord.remove_abs2 [OF it_abs[unfolded set_iterator_abs_def],
folded set_iterator_def]
}
then obtain DS where
DS_props: "\<forall>q. q2_invar q \<longrightarrow> q2_\<alpha> q \<in> S \<longrightarrow>
set_iterator (D_it q) (DS q) \<and> inj_on (\<lambda>(as, q'). (a_\<alpha> as, q2_\<alpha> q')) (DS q) \<and>
(\<lambda>(as, q'). (a_\<alpha> as, q2_\<alpha> q')) ` (DS q) = (DS_q (q2_\<alpha> q)) \<and>
(\<forall>(as, q') \<in> DS q. a_invar as \<and> q2_invar q')"
by metis
from DS_props have
D_it_OK': "\<And>q. q2_invar q \<Longrightarrow> q2_\<alpha> q \<in> S \<Longrightarrow> set_iterator (D_it q) (DS q)" and
inj_on_DS: "\<And>q. q2_invar q \<Longrightarrow> q2_\<alpha> q \<in> S \<Longrightarrow> inj_on (\<lambda>(as, q). (a_\<alpha> as, q2_\<alpha> q)) (DS q)" and
DS_q_alt_eq: "\<And>q. q2_invar q \<Longrightarrow> q2_\<alpha> q \<in> S \<Longrightarrow> (\<lambda>(as, q). (a_\<alpha> as, q2_\<alpha> q)) ` (DS q) = (DS_q (q2_\<alpha> q))" and
invar_DS_q: "\<And>q as q'. q2_invar q \<Longrightarrow> q2_\<alpha> q \<in> S \<Longrightarrow> (as, q') \<in> DS q \<Longrightarrow> a_invar as \<and> q2_invar q'"
by auto
from NFA_construct_reachable_impl_code_correct [of S D_it DS det II A FFP] D_it_OK'
have step1: "RETURN (NFA_construct_reachable_impl_code add_labels qm_ops det ff II A FFP D_it)
\<le> NFA_construct_reachable_impl det S II A FFP DS" by simp
{ fix q
assume q_props: "q2_invar q" "q2_\<alpha> q \<in> S"
from inj_on_DS[OF q_props] invar_DS_q[OF q_props]
have "(DS q, DS_q (q2_\<alpha> q)) \<in> NFA_construct_reachable_impl_step_rel"
unfolding NFA_construct_reachable_impl_step_rel_def
by (auto simp add: DS_q_alt_eq[OF q_props, symmetric] inj_on_def in_br_conv)
} note DS_in_step_rel = this
from NFA_construct_reachable_impl_correct [OF f_inj_on[unfolded S_def] ff_OK[unfolded S_def]
d_add_OK det_OK _ dist_I invar_I invar_A, of det DS_q DS FFP FP, folded S_def] FFP_OK DS_in_step_rel DS_q_OK
have step2: "NFA_construct_reachable_impl det S II A FFP DS \<le> \<Down>
(br nfa_\<alpha> (\<lambda>A. nfa_invar_no_props A \<and> nfa_props A = nfa_props_connected det))
(NFA_construct_reachable_abstract2_impl (map q2_\<alpha> II) (l.\<alpha> A) FP D DS_q)"
by simp
{ fix q
assume q_in_S: "q \<in> S"
from DS_q_OK(1)[OF q_in_S]
have "{(a, q'). (q, a, q') \<in> D} = \<Union> ((\<lambda>(as, q'). {(a, q') |a. a \<in> as}) ` (DS_q q))"
by (auto simp add: set_eq_iff Bex_def)
with fin_D[of q] have "finite (\<Union> ((\<lambda>(as, q'). {(a, q') |a. a \<in> as}) ` (DS_q q)))"
by simp
hence "finite ((\<lambda>(as, q'). {(a, q') |a. a \<in> as}) ` (DS_q q))"
by (rule finite_UnionD)
hence "finite (DS_q q)"
proof (rule finite_imageD)
show "inj_on (\<lambda>(as, q'). {(a, q') |a. a \<in> as}) (DS_q q)"
unfolding inj_on_def
proof (clarify)
fix as1 q1 as2 q2
assume in_DS_q1: "(as1, q1) \<in> DS_q q" and in_DS_q2: "(as2, q2) \<in> DS_q q" and
set_eq: "{(a, q1) |a. a \<in> as1} = {(a, q2) |a. a \<in> as2}"
from DS_q_OK(2) [OF q_in_S in_DS_q1] have "as1 \<noteq> {}" .
from DS_q_OK(2) [OF q_in_S in_DS_q2] have "as2 \<noteq> {}" .
from `as1 \<noteq> {}` `as2 \<noteq> {}` set_eq have q2_eq[simp]: "q2 = q1" by auto
from set_eq have "as1 = as2" by auto
thus "as1 = as2 \<and> q1 = q2" by simp
qed
qed
}
with NFA_construct_reachable_abstract2_impl_correct_full[of D "map q2_\<alpha> II" DS_q "l.\<alpha> A"
FP, folded S_def, OF fin_S] DS_q_OK
have step3: "NFA_construct_reachable_abstract2_impl (map q2_\<alpha> II) (set_op_\<alpha> l_ops A) FP D DS_q \<le> SPEC
(NFA_isomorphic (NFA_construct_reachable (set (map q2_\<alpha> II)) (set_op_\<alpha> l_ops A) FP D))"
by auto
note step1 also note step2 also note step3
finally have "RETURN (NFA_construct_reachable_impl_code add_labels qm_ops det ff II A FFP D_it) \<le> \<Down>
(br nfa_\<alpha> (\<lambda>A. nfa_invar_no_props A \<and> nfa_props A = nfa_props_connected det))
(SPEC (NFA_isomorphic (NFA_construct_reachable (set (map q2_\<alpha> II)) (l.\<alpha> A) FP D)))"
by simp
thus ?thesis
by (erule_tac RETURN_ref_SPECD) (simp_all add: in_br_conv)
qed
lemma NFA_construct_reachable_impl_code_correct___remove_unreachable:
fixes D_it :: "'q2_rep \<Rightarrow> (('as \<times> 'q2_rep),('m \<times> nat) \<times> 'd \<times> 'q2_rep list) set_iterator"
fixes II D
assumes f_inj_on: "inj_on f (\<Q> \<A>)"
and ff_OK: "\<And>q. q2_invar q \<Longrightarrow> q2_\<alpha> q \<in> (\<Q> \<A>) \<Longrightarrow> ff q = f (q2_\<alpha> q)"
and d_add_OK: "dlts_add_label_set d.\<alpha> d.invar a_\<alpha> a_invar (add_labels True)"
"lts_add_label_set d.\<alpha> d.invar a_\<alpha> a_invar (add_labels False)"
and DS_q_OK: "\<And>q a q'. q \<in> \<Q> \<A> \<Longrightarrow> ((q, a, q') \<in> \<Delta> \<A>) = (\<exists>as. a \<in> as \<and> (as, q') \<in> DS_q q)"
"\<And>q as q'. q \<in> \<Q> \<A> \<Longrightarrow> (as, q') \<in> DS_q q \<Longrightarrow> as \<noteq> {}"
and dist_I: "distinct (map q2_\<alpha> II)"
and invar_I: "\<And>q. q \<in> set II \<Longrightarrow> q2_invar q"
and invar_A: "l.invar A"
and I_OK: "set (map q2_\<alpha> II) = \<I> \<A>"
and A_OK: "l.\<alpha> A = \<Sigma> \<A>"
and D_it_OK: "\<And>q. q2_invar q \<Longrightarrow> q2_\<alpha> q \<in> \<Q> \<A> \<Longrightarrow> set_iterator_abs
(\<lambda>(as, q). (a_\<alpha> as, q2_\<alpha> q)) (\<lambda>(as, q). a_invar as \<and> q2_invar q) (D_it q) (DS_q (q2_\<alpha> q))"
and FP_OK: "\<And>q. q2_invar q \<Longrightarrow> q2_\<alpha> q \<in> \<Q> \<A> \<Longrightarrow> FP q \<longleftrightarrow> (q2_\<alpha> q) \<in> \<F> \<A>"
and wf_\<A>: "NFA \<A>"
and det_OK: "det \<Longrightarrow> DFA \<A>"
shows "nfa_invar (NFA_construct_reachable_impl_code add_labels qm_ops det ff II A FP D_it) \<and>
NFA_isomorphic_wf (nfa_\<alpha> (NFA_construct_reachable_impl_code add_labels qm_ops det ff II A FP D_it))
(NFA_remove_unreachable_states \<A>)"
proof -
interpret NFA \<A> by fact
define S where "S \<equiv> accessible (LTS_forget_labels (\<Delta> \<A>)) (set (map q2_\<alpha> II))"
from LTS_is_reachable_from_initial_finite I_OK have fin_S: "finite S" unfolding S_def by simp
from LTS_is_reachable_from_initial_subset I_OK have S_subset: "S \<subseteq> \<Q> \<A>" unfolding S_def by simp
from f_inj_on S_subset have f_inj_on': "inj_on f S" unfolding S_def by (rule subset_inj_on)
{ fix q
have "{(a, q'). (q, a, q') \<in> \<Delta> \<A>} = (\<lambda>(q,a,q'). (a,q')) ` {(q, a, q') | a q'. (q, a, q') \<in> \<Delta> \<A>}"
by (auto simp add: image_iff)
hence "finite {(a, q'). (q, a, q') \<in> \<Delta> \<A>}"
apply simp
apply (rule finite_imageI)
apply (rule finite_subset [OF _ finite_\<Delta>])
apply auto
done
} note fin_D = this
from det_OK have det_OK': "det \<Longrightarrow> LTS_is_deterministic (\<Delta> \<A>)"
unfolding DFA_alt_def SemiAutomaton_is_complete_deterministic_def LTS_is_complete_deterministic_def
by simp
let ?FP = "\<lambda>q. q \<in> \<F> \<A>"
let ?I = "map q2_\<alpha> II"
define code where "code \<equiv> NFA_construct_reachable_impl_code add_labels qm_ops det ff II A FP D_it"
from NFA_construct_reachable_impl_code_correct_full [of "\<Delta> \<A>" II, folded S_def,
OF f_inj_on' ff_OK d_add_OK _ _ _ dist_I invar_I invar_A fin_S fin_D, of det DS_q D_it FP,
where ?FP = ?FP,
OF _ _ det_OK' DS_q_OK(1)]
S_subset DS_q_OK(2) FP_OK D_it_OK
have step1:
"NFA_isomorphic (NFA_construct_reachable (set ?I) (l.\<alpha> A) ?FP (\<Delta> \<A>)) (nfa_\<alpha> code)"
"nfa_invar_no_props code"
"nfa_props code = nfa_props_connected det"
apply (simp_all add: subset_iff code_def[symmetric])
apply metis+
done
from NFA.NFA_remove_unreachable_states_implementation [OF wf_\<A> I_OK A_OK, of "?FP" "\<Delta> \<A>"]
have step2: "NFA_construct_reachable (set ?I) (l.\<alpha> A) ?FP (\<Delta> \<A>) =
NFA_remove_unreachable_states \<A>" by simp
from step1(1) step2 NFA_remove_unreachable_states___is_well_formed [OF wf_\<A>] have
step3: "NFA_isomorphic_wf (NFA_remove_unreachable_states \<A>) (nfa_\<alpha> code)"
by (simp add: NFA_isomorphic_wf_def)
from step3 have step4: "NFA (nfa_\<alpha> code)"
unfolding NFA_isomorphic_wf_alt_def by simp
have step5: "SemiAutomaton_is_initially_connected (nfa_\<alpha> code)"
proof -
have "SemiAutomaton_is_initially_connected (NFA_remove_unreachable_states \<A>)"
by (fact NFA.SemiAutomaton_is_initially_connected___NFA_remove_unreachable_states)
with SemiAutomaton_is_initially_connected___NFA_isomorphic_wf[OF step3]
show ?thesis by simp
qed
have step6: "det \<Longrightarrow> SemiAutomaton_is_complete_deterministic (nfa_\<alpha> code)"
proof -
assume det
with det_OK have "DFA \<A>" by simp
hence "DFA (NFA_remove_unreachable_states \<A>)" by (metis DFA___NFA_remove_unreachable_states)
with NFA_isomorphic_wf___DFA[OF step3] have "DFA (nfa_\<alpha> code)" by simp
thus "SemiAutomaton_is_complete_deterministic (nfa_\<alpha> code)"
unfolding DFA_alt_def by simp
qed
from step3 step1(2) step4 step6 show ?thesis
unfolding nfa_invar_alt_def code_def[symmetric]
apply (simp add: nfa_invar_props_def step1(3) step5)
apply (metis NFA_isomorphic_wf_sym)
done
qed
end
context nfa_by_lts_defs
begin
lemma NFA_construct_reachable_impl_code_correct_label_sets :
fixes qm_ops :: "('i, 'q::{automaton_states}, 'm, _) map_ops_scheme"
and q2_\<alpha> :: "'q2_rep \<Rightarrow> 'q2"
and q2_invar :: "'q2_rep \<Rightarrow> bool"
and a_\<alpha> :: "'as \<Rightarrow> 'a set"
and a_invar :: "'as \<Rightarrow> bool"
assumes "StdMap qm_ops"
and add_labels_OK: "lts_add_label_set d.\<alpha> d.invar a_\<alpha> a_invar (add_labels False)"
"dlts_add_label_set d.\<alpha> d.invar a_\<alpha> a_invar (add_labels True)"
shows "nfa_dfa_construct_label_sets nfa_\<alpha> nfa_invar l.\<alpha> l.invar q2_\<alpha> q2_invar a_\<alpha> a_invar
(NFA_construct_reachable_impl_code add_labels qm_ops)"
proof (intro nfa_dfa_construct_label_sets.intro nfa_by_lts_correct nfa_dfa_construct_label_sets_axioms.intro)
fix \<A>:: "('q2, 'a) NFA_rec" and f :: "'q2 \<Rightarrow> 'i" and ff I A FP DS_q det
fix D_it :: "'q2_rep \<Rightarrow> (('as \<times> 'q2_rep),('m \<times> nat) \<times> 'd \<times> 'q2_rep list) set_iterator"
assume wf_\<A>: "NFA \<A>"
and det_OK: "det \<Longrightarrow> DFA \<A>"
and f_inj_on: "inj_on f (\<Q> \<A>)"
and f_OK: "\<And>q. q2_invar q \<Longrightarrow> q2_\<alpha> q \<in> (\<Q> \<A>) \<Longrightarrow> ff q = f (q2_\<alpha> q)"
and dist_I: "distinct (map q2_\<alpha> I)"
and invar_I: "\<And>q. q \<in> set I \<Longrightarrow> q2_invar q"
and I_OK: "q2_\<alpha> ` set I = \<I> \<A>"
and invar_A: "set_op_invar l_ops A"
and A_OK: "set_op_\<alpha> l_ops A = \<Sigma> \<A>"
and FP_OK: "\<And>q. q2_invar q \<Longrightarrow> q2_\<alpha> q \<in> \<Q> \<A> \<Longrightarrow> FP q = (q2_\<alpha> q \<in> \<F> \<A>)"
and D_it_OK: "\<And>q. q2_invar q \<Longrightarrow> q2_\<alpha> q \<in> \<Q> \<A> \<Longrightarrow> set_iterator_abs
(\<lambda>(as, q). (a_\<alpha> as, q2_\<alpha> q)) (\<lambda>(as, q). a_invar as \<and> q2_invar q) (D_it q)
(DS_q (q2_\<alpha> q))"
and DS_OK: "\<And>q a q'. q \<in> \<Q> \<A> \<Longrightarrow> ((q, a, q') \<in> \<Delta> \<A>) = (\<exists>as. a \<in> as \<and> (as, q') \<in> DS_q q)"
"\<And>q as q'. q \<in> \<Q> \<A> \<Longrightarrow> (as, q') \<in> DS_q q \<Longrightarrow> as \<noteq> {}"
interpret reach: NFA_construct_reachable_locale s_ops l_ops d_ops qm_ops a_\<alpha> a_invar add_labels f ff q2_\<alpha> q2_invar
using nfa_by_lts_defs_axioms add_labels_OK `StdMap qm_ops`
unfolding NFA_construct_reachable_locale_def nfa_by_lts_defs_def by simp
note correct = reach.NFA_construct_reachable_impl_code_correct___remove_unreachable
[OF f_inj_on f_OK, of DS_q, OF _ _ _ _ _ _ dist_I invar_I invar_A _ A_OK _ _ wf_\<A>, of D_it FP det]
show "nfa_invar (NFA_construct_reachable_impl_code add_labels qm_ops det ff I A FP D_it) \<and>
NFA_isomorphic_wf (nfa_\<alpha> (NFA_construct_reachable_impl_code add_labels qm_ops det ff I A FP D_it))
(NFA_remove_unreachable_states \<A>)"
apply (rule_tac correct)
apply (simp_all add: I_OK FP_OK reach.NFA_construct_reachable_impl_step_rel_def DS_OK D_it_OK
add_labels_OK lts_add_label_set_sublocale det_OK)
done
qed
lemma NFA_construct_reachable_impl_code_correct :
fixes qm_ops :: "('i, 'q::{automaton_states}, 'm, _) map_ops_scheme"
and q2_\<alpha> :: "'q2_rep \<Rightarrow> 'q2"
and q2_invar :: "'q2_rep \<Rightarrow> bool"
assumes qm_OK: "StdMap qm_ops" and
d_add_OK: "lts_dlts_add d.\<alpha> d.invar d_add"
shows "NFASpec.nfa_dfa_construct nfa_\<alpha> nfa_invar l.\<alpha> l.invar q2_\<alpha> q2_invar
(NFA_construct_reachable_impl_code d_add qm_ops)"
apply (intro nfa_dfa_construct_default NFA_construct_reachable_impl_code_correct_label_sets assms)
apply (insert d_add_OK)
apply (simp_all add: lts_add_label_set_def dlts_add_label_set_def lts_dlts_add_def lts_add_def dlts_add_def)
done
lemma NFA_construct_reachable_impl_code_correct_no_enc:
assumes qm_OK: "StdMap qm_ops"
and d_add_OK: "lts_dlts_add d.\<alpha> d.invar d_add"
shows "NFASpec.nfa_dfa_construct_no_enc nfa_\<alpha> nfa_invar l.\<alpha> l.invar
(NFA_construct_reachable_impl_code d_add qm_ops)"
by (intro NFAGA.nfa_dfa_construct_no_enc_default NFA_construct_reachable_impl_code_correct d_add_OK qm_OK)
subsection \<open> normalise \<close>
definition nfa_normalise_impl where
"nfa_normalise_impl d_add qm_ops sl_it = (\<lambda>(Q::'q_set, A::'a_set, D::'d, I::'q_set, F::'q_set, p).
(if (nfa_prop_is_initially_connected p) then (Q, A, D, I, F, p) else
NFA_construct_reachable_impl_code d_add qm_ops (nfa_prop_is_complete_deterministic p)
id (s.to_list I) A (\<lambda>q. s.memb q F) (sl_it D)))"
lemma nfa_normalise_correct :
assumes qm_OK: "StdMap qm_ops"
and d_add_OK: "lts_dlts_add d.\<alpha> d.invar d_add"
and ls_it_OK: "lts_succ_label_it d.\<alpha> d.invar sl_it"
shows "nfa_normalise nfa_\<alpha> nfa_invar (nfa_normalise_impl d_add qm_ops sl_it)"
proof (intro nfa_normalise.intro nfa_normalise_axioms.intro nfa_by_lts_correct)
fix n
assume invar: "nfa_invar n"
obtain Q A D I F p where n_eq[simp]: "n = (Q, A, D, I, F, p)" by (metis prod.exhaust)
from invar have nfa_n: "NFA (nfa_\<alpha> n)" unfolding nfa_invar_full_def by simp
have dfa_n: "nfa_prop_is_complete_deterministic p \<Longrightarrow> DFA (nfa_\<alpha> n)"
using nfa_invar_implies_DFA[OF invar] by simp
have connected_n: "nfa_prop_is_initially_connected p \<Longrightarrow> SemiAutomaton_is_initially_connected (nfa_\<alpha> n)"
using invar unfolding nfa_invar_full_def by simp
have "nfa_invar (nfa_normalise_impl d_add qm_ops sl_it n) \<and>
NFA_isomorphic_wf
(nfa_\<alpha> (nfa_normalise_impl d_add qm_ops sl_it n))
(NFA_remove_unreachable_states (nfa_\<alpha> n))"
proof (cases "nfa_prop_is_initially_connected p")
case True note conn = this
from connected_n[OF conn] have idem: "NFA_remove_unreachable_states (nfa_\<alpha> n) = (nfa_\<alpha> n)"
using NFA_remove_unreachable_states_no_change[OF nfa_n] by simp
with invar show ?thesis
apply (simp add: nfa_normalise_impl_def conn)
apply (simp add: NFA_isomorphic_wf_refl nfa_invar_alt_def)
done
next
case False note not_conn = this
note ls_it' = lts_succ_label_it.lts_succ_label_it_correct [OF ls_it_OK, of D]
from invar have invars: "s.invar Q \<and> l.invar A \<and> d.invar D \<and> s.invar I \<and> s.invar F"
unfolding nfa_invar_full_def by simp
note const_OK = NFA_construct_reachable_impl_code_correct_no_enc [OF qm_OK d_add_OK]
note correct = nfa_dfa_construct_no_enc.nfa_dfa_construct_no_enc_correct
[OF const_OK, of "nfa_\<alpha> n" "nfa_prop_is_complete_deterministic p" id
"s.to_list I" A "\<lambda>q. s.memb q F" "sl_it D"]
with nfa_n dfa_n ls_it' show ?thesis
by (simp_all add: s.correct set_iterator_def nfa_normalise_impl_def not_conn invars)
qed
thus "nfa_invar (nfa_normalise_impl d_add qm_ops sl_it n)"
"NFA_isomorphic_wf
(nfa_\<alpha> (nfa_normalise_impl d_add qm_ops sl_it n))
(NFA_remove_unreachable_states (nfa_\<alpha> n))" by simp_all
qed
subsection \<open> Reverse \<close>
definition nfa_reverse_impl :: "_ \<Rightarrow> ('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> ('q_set, 'a_set, 'd) NFA_impl" where
"nfa_reverse_impl rf = (\<lambda>(Q, A, D, I, F, p). (Q, A, rf D, F, I, nfa_props_trivial))"
lemma nfa_reverse_impl_correct :
fixes l_ops' :: "('a2, 'a2_set, _) set_ops_scheme"
assumes wf_target: "nfa_by_lts_defs s_ops l_ops d_ops'"
assumes rf_OK: "lts_reverse d.\<alpha> d.invar (lts_op_\<alpha> d_ops') (lts_op_invar d_ops') rf"
shows "nfa_reverse nfa_\<alpha> nfa_invar
(nfa_by_lts_defs.nfa_\<alpha> s_ops l_ops d_ops')
(nfa_by_lts_defs.nfa_invar s_ops l_ops d_ops')
(nfa_reverse_impl rf)"
proof (intro nfa_reverse.intro nfa_reverse_axioms.intro
nfa_by_lts_defs.nfa_by_lts_correct)
show "nfa_by_lts_defs s_ops l_ops d_ops" by (fact nfa_by_lts_defs_axioms)
show "nfa_by_lts_defs s_ops l_ops d_ops'" by (intro nfa_by_lts_defs_axioms wf_target)
fix n
assume invar: "nfa_invar n"
obtain QL AL DL IL FL p where n_eq[simp]: "n = (QL, AL, DL, IL, FL, p)" by (cases n, blast)
from invar have invar_no_props: "nfa_invar_no_props n" and wf: "NFA (nfa_\<alpha> n)" and
invar_props: "nfa_invar_no_props n"
unfolding nfa_invar_alt_def by simp_all
let ?nfa_\<alpha>' = "nfa_by_lts_defs.nfa_\<alpha> s_ops l_ops d_ops'"
let ?nfa_invar_no_props' = "nfa_by_lts_defs.nfa_invar_no_props s_ops l_ops d_ops'"
let ?nfa_invar' = "nfa_by_lts_defs.nfa_invar s_ops l_ops d_ops'"
from invar_no_props rf_OK
have "?nfa_invar_no_props' (nfa_reverse_impl rf n) \<and>
?nfa_\<alpha>' (nfa_reverse_impl rf n) = NFA_reverse (nfa_\<alpha> n)"
apply (simp add: nfa_by_lts_defs.nfa_invar_no_props_def[OF wf_target]
nfa_by_lts_defs.nfa_\<alpha>_def [OF wf_target]
nfa_by_lts_defs.nfa_selectors_def[OF wf_target]
nfa_invar_no_props_def
nfa_reverse_impl_def NFA_reverse_def
s.correct NFA_rename_states_def d.correct_common lts_reverse_def)
apply auto
done
with wf
show "?nfa_\<alpha>' (nfa_reverse_impl rf n) = NFA_reverse (nfa_\<alpha> n)"
"?nfa_invar' (nfa_reverse_impl rf n)"
unfolding nfa_by_lts_defs.nfa_invar_alt_def[OF wf_target]
apply (simp_all add: NFA_reverse___is_well_formed)
apply (simp add: nfa_reverse_impl_def
nfa_by_lts_defs.nfa_invar_props_def[OF wf_target]
nfa_by_lts_defs.nfa_selectors_def[OF wf_target])
done
qed
subsection \<open> Complement \<close>
definition nfa_complement_impl :: "('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> ('q_set, 'a_set, 'd) NFA_impl" where
"nfa_complement_impl = (\<lambda>(Q, A, D, I, F, p). (Q, A, D, I, s.diff Q F, p))"
lemma nfa_complement_impl_correct :
shows "nfa_complement nfa_\<alpha> nfa_invar nfa_complement_impl"
proof (intro nfa_complement.intro nfa_complement_axioms.intro)
show "nfa nfa_\<alpha> nfa_invar" by simp
fix n
assume invar: "nfa_invar n"
obtain QL AL DL IL FL p where n_eq: "n = (QL, AL, DL, IL, FL, p)" by (cases n, blast)
from invar have invar_no_props: "nfa_invar_no_props n" and wf: "NFA (nfa_\<alpha> n)" and
invar_props: "nfa_invar_props n"
unfolding nfa_invar_alt_def by simp_all
from invar_no_props
have invar_no_props': "nfa_invar_no_props (nfa_complement_impl n)" and
\<alpha>_eq: "nfa_\<alpha> (nfa_complement_impl n) = DFA_complement (nfa_\<alpha> n)"
by (simp_all add: nfa_invar_no_props_def nfa_\<alpha>_def n_eq
DFA_complement_def nfa_complement_impl_def
s.correct NFA_rename_states_def d.correct_common lts_reverse_def)
show "nfa_\<alpha> (nfa_complement_impl n) = DFA_complement (nfa_\<alpha> n)" by (fact \<alpha>_eq)
from invar_props have invar_props': "nfa_invar_props (nfa_complement_impl n)"
apply (simp add: nfa_invar_props_def \<alpha>_eq DFA_complement_alt_def)
apply (simp add: nfa_complement_impl_def n_eq)
done
from wf
show "nfa_invar (nfa_complement_impl n)"
unfolding nfa_invar_alt_def \<alpha>_eq
by (simp_all add: DFA_complement___is_well_formed invar_no_props' invar_props')
qed
subsection \<open> Boolean combinations \<close>
definition product_iterator where
"product_iterator (it_1::'q1 \<Rightarrow> ('a \<times> 'q1, '\<sigma>) set_iterator)
(it_2::'q2 \<Rightarrow> 'a \<Rightarrow> ('q2, '\<sigma>) set_iterator) = (\<lambda>(q1, q2).
set_iterator_image (\<lambda>((a, q1'), q2'). (a, (q1', q2'))) (set_iterator_product (it_1 q1)
(\<lambda>aq. it_2 q2 (fst aq))))"
lemma product_iterator_alt_def :
"product_iterator it_1 it_2 =
(\<lambda>(q1, q2) c f. it_1 q1 c (\<lambda>(a,q1'). it_2 q2 a c (\<lambda>q2'. f (a, q1', q2'))))"
unfolding product_iterator_def set_iterator_image_alt_def set_iterator_product_def
by (auto simp add: split_def)
lemma product_iterator_correct :
fixes D1 :: "('q1 \<times> 'a \<times> 'q1) set"
fixes D2 :: "('q2 \<times> 'a \<times> 'q2) set"
assumes it_1_OK: "set_iterator (it_1 q1) {(a, q1'). (q1, a, q1') \<in> D1}"
and it_2_OK: "\<And>a. set_iterator (it_2 q2 a) {q2'. (q2, a, q2') \<in> D2}"
shows "set_iterator (product_iterator it_1 it_2 (q1, q2))
{(a, (q1', q2')). ((q1, q2), a, (q1', q2')) \<in> LTS_product D1 D2}"
proof -
from it_2_OK have it_2_OK':
"\<And>aq. set_iterator (((it_2 q2) \<circ> fst) aq) {q2'. (q2, (fst aq), q2') \<in> D2}" by simp
note thm_1 = set_iterator_product_correct [where ?it_a = "it_1 q1" and
?it_b = "(it_2 q2) \<circ> fst", OF it_1_OK it_2_OK']
let ?f = "\<lambda>((a, q1'), q2'). (a, (q1', q2'))"
have inj_on_f: "\<And>S. inj_on ?f S"
unfolding inj_on_def by auto
note thm_2 = set_iterator_image_correct [OF thm_1 inj_on_f]
let ?Sigma = "(SIGMA a:{(a, q1'). (q1, a, q1') \<in> D1}. {q2'. (q2, fst a, q2') \<in> D2})"
have "?f ` ?Sigma = {(a, (q1', q2')). ((q1, q2), a, (q1', q2')) \<in> LTS_product D1 D2}"
by (auto simp add: image_iff)
with thm_2 show ?thesis by (simp add: product_iterator_def o_def)
qed
definition bool_comb_impl_aux where
"bool_comb_impl_aux const det f it_1 it_2 I I' FP FP' =
(\<lambda>A' bc AA1 AA2. const (det AA1 AA2) f (List.product (I AA1) (I' AA2)) A'
(\<lambda>(q1', q2'). bc (FP AA1 q1') (FP' AA2 q2')) (product_iterator (it_1 AA1) (it_2 AA2)))"
lemma bool_comb_impl_aux_correct :
assumes const_OK: "nfa_dfa_construct_no_enc \<alpha>3 invar3 \<alpha>_s invar_s const"
and nfa_1_OK: "nfa \<alpha>1 invar1"
and nfa_2_OK: "nfa \<alpha>2 invar2"
and f_inj_on: "\<And>n1 n2. inj_on f (\<Q> (\<alpha>1 n1) \<times> \<Q> (\<alpha>2 n2))"
and I1_OK: "\<And>n1. invar1 n1 \<Longrightarrow> distinct (I1 n1) \<and> set (I1 n1) = \<I> (\<alpha>1 n1)"
and I2_OK: "\<And>n2. invar2 n2 \<Longrightarrow> distinct (I2 n2) \<and> set (I2 n2) = \<I> (\<alpha>2 n2)"
and FP1_OK: "\<And>n1 q. invar1 n1 \<Longrightarrow> q \<in> \<Q> (\<alpha>1 n1) \<Longrightarrow> FP1 n1 q \<longleftrightarrow> (q \<in> \<F> (\<alpha>1 n1))"
and FP2_OK: "\<And>n2 q. invar2 n2 \<Longrightarrow> q \<in> \<Q> (\<alpha>2 n2) \<Longrightarrow> FP2 n2 q \<longleftrightarrow> (q \<in> \<F> (\<alpha>2 n2))"
and det_OK: "\<And>n1 n2. invar1 n1 \<Longrightarrow> invar2 n2 \<Longrightarrow> det n1 n2 \<Longrightarrow> DFA (\<alpha>1 n1) \<and> DFA (\<alpha>2 n2)"
and it_1_OK: "\<And>n1 q. invar1 n1 \<Longrightarrow> set_iterator (it_1 n1 q) {(a, q'). (q, a, q') \<in> \<Delta> (\<alpha>1 n1)}"
and it_2_OK: "\<And>n2 q a. invar2 n2 \<Longrightarrow> set_iterator (it_2 n2 q a)
{q'. (q, a, q') \<in> \<Delta> (\<alpha>2 n2)}"
shows "nfa_bool_comb_gen \<alpha>1 invar1 \<alpha>2 invar2 \<alpha>3 invar3 \<alpha>_s invar_s
(bool_comb_impl_aux const det f it_1 it_2 I1 I2 FP1 FP2)"
proof (intro nfa_bool_comb_gen.intro nfa_1_OK nfa_2_OK nfa_bool_comb_gen_axioms.intro)
from const_OK show "nfa \<alpha>3 invar3" unfolding nfa_dfa_construct_no_enc_def by simp
fix n1 n2 as bc
assume invar_1: "invar1 n1"
and invar_2: "invar2 n2"
and invar_s: "invar_s as"
and as_OK: "\<alpha>_s as = \<Sigma> (\<alpha>1 n1) \<inter> \<Sigma> (\<alpha>2 n2)"
let ?AA' = "bool_comb_NFA bc (\<alpha>1 n1) (\<alpha>2 n2)"
have f_inj_on': "inj_on f (\<Q> ?AA')" using f_inj_on by (simp add: bool_comb_NFA_def)
from invar_1 invar_2 nfa_1_OK nfa_2_OK have AA'_wf: "NFA ?AA'"
apply (rule_tac NFA.bool_comb_NFA___is_well_formed)
apply (simp_all add: nfa_def)
done
from det_OK[OF invar_1 invar_2] have AA'_wf': "det n1 n2 \<Longrightarrow> DFA ?AA'"
apply (rule_tac DFA.bool_comb_DFA___is_well_formed)
apply (simp_all)
done
let ?II = "List.product (I1 n1) (I2 n2)"
have dist_II: "distinct ?II" and set_II: "set ?II = \<I> ?AA'"
apply (intro List.distinct_product)
apply (insert I1_OK[OF invar_1] I2_OK[OF invar_2])
apply (simp_all)
done
from as_OK have as_OK': "\<alpha>_s as = \<Sigma> ?AA'" by simp
let ?FP = "(\<lambda>(q1', q2'). bc (FP1 n1 q1') (FP2 n2 q2'))"
from FP1_OK[OF invar_1] FP2_OK[OF invar_2]
have FP_OK: "\<And>q. q \<in> \<Q> ?AA' \<Longrightarrow> ?FP q = (q \<in> \<F> ?AA')" by auto
let ?D_it = "product_iterator (it_1 n1) (it_2 n2)"
from product_iterator_correct [where ?it_1.0 = "it_1 n1" and ?it_2.0 = "it_2 n2",
OF it_1_OK[OF invar_1] it_2_OK[OF invar_2]]
have D_it_OK: "\<And>q. set_iterator (product_iterator (it_1 n1) (it_2 n2) q)
{(a, q'). (q, a, q') \<in> \<Delta> ?AA'}"
by (case_tac q) (simp add: split_def)
note construct_correct = nfa_dfa_construct_no_enc.nfa_dfa_construct_no_enc_correct [where det = "det n1 n2", OF const_OK
AA'_wf AA'_wf' f_inj_on' dist_II set_II, OF _ invar_s as_OK' FP_OK D_it_OK]
thus "invar3 (bool_comb_impl_aux const det f it_1 it_2 I1 I2 FP1 FP2 as bc n1 n2) \<and>
NFA_isomorphic_wf (\<alpha>3 (bool_comb_impl_aux const det f it_1 it_2 I1 I2 FP1 FP2 as bc n1 n2))
(efficient_bool_comb_NFA bc (\<alpha>1 n1) (\<alpha>2 n2))"
by (simp_all add: bool_comb_impl_aux_def efficient_bool_comb_NFA_def)
qed
lemma bool_comb_impl_aux_correct_same :
assumes const_OK: "nfa_dfa_construct_no_enc \<alpha>2 invar2 \<alpha>_s invar_s const"
and nfa_OK: "nfa \<alpha> invar"
and f_inj_on: "\<And>n1 n2. inj_on f (\<Q> (\<alpha> n1) \<times> \<Q> (\<alpha> n2))"
and I_OK: "\<And>n. invar n \<Longrightarrow> distinct (I n) \<and> set (I n) = \<I> (\<alpha> n)"
and FP_OK: "\<And>n q. invar n \<Longrightarrow> q \<in> \<Q> (\<alpha> n) \<Longrightarrow> FP n q \<longleftrightarrow> (q \<in> \<F> (\<alpha> n))"
and det_OK: "\<And>n1 n2. invar n1 \<Longrightarrow> invar n2 \<Longrightarrow> det n1 n2 \<Longrightarrow> DFA (\<alpha> n1) \<and> DFA (\<alpha> n2)"
and it_1_OK: "\<And>n1 q. invar n1 \<Longrightarrow> set_iterator (it_1 n1 q) {(a, q'). (q, a, q') \<in> \<Delta> (\<alpha> n1)}"
and it_2_OK: "\<And>n2 q a. invar n2 \<Longrightarrow> set_iterator (it_2 n2 q a) {q'. (q, a, q') \<in> \<Delta> (\<alpha> n2)}"
shows "nfa_bool_comb_gen \<alpha> invar \<alpha> invar \<alpha>2 invar2 \<alpha>_s invar_s
(bool_comb_impl_aux const det f it_1 it_2 I I FP FP)"
apply (rule bool_comb_impl_aux_correct)
apply (rule const_OK)
apply (rule nfa_OK)
apply (rule nfa_OK)
apply (rule f_inj_on)
apply (rule I_OK, simp)
apply (rule I_OK, simp)
apply (rule FP_OK, simp_all)
apply (rule FP_OK, simp_all)
apply (rule det_OK, simp_all)
apply (rule it_1_OK, simp)
apply (rule it_2_OK, simp)
done
definition bool_comb_gen_impl :: "
_ \<Rightarrow> _ \<Rightarrow> _ \<Rightarrow> _ \<Rightarrow> _ \<Rightarrow> _ \<Rightarrow> ('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> ('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> ('q_set, 'a_set, 'd) NFA_impl" where
"bool_comb_gen_impl d_add qm_ops it_1 it_2 A' bc A1 A2 =
bool_comb_impl_aux (NFA_construct_reachable_impl_code d_add qm_ops)
(\<lambda>A1 A2. nfa_prop_is_complete_deterministic (nfa_props A1) \<and>
nfa_prop_is_complete_deterministic (nfa_props A2))
id
(\<lambda>A. it_1 (nfa_trans A)) (\<lambda>A. it_2 (nfa_trans A))
(\<lambda>A. (s.to_list (nfa_initial A))) (\<lambda>A. (s.to_list (nfa_initial A)))
(\<lambda>A q. s.memb q (nfa_accepting A))
(\<lambda>A q. s.memb q (nfa_accepting A)) A' bc A1 A2"
schematic_goal bool_comb_gen_impl_code :
"bool_comb_gen_impl d_add qm_ops it_1 it_2 A' bc (Q1, A1, D1, I1, F1, p1) (Q2, A2, D2, I2, F2, p2) = ?XXX"
unfolding bool_comb_gen_impl_def bool_comb_impl_aux_def product_iterator_alt_def
nfa_selectors_def snd_conv fst_conv
by (rule refl)+
lemma bool_comb_gen_impl_correct :
assumes qm_ops_OK: "StdMap qm_ops"
and d_add_OK: "lts_dlts_add d.\<alpha> d.invar d_add"
and it_1_OK: "lts_succ_label_it d.\<alpha> d.invar it_1"
and it_2_OK: "lts_succ_it d.\<alpha> d.invar it_2"
shows "nfa_bool_comb_gen_same nfa_\<alpha> nfa_invar l.\<alpha> l.invar
(bool_comb_gen_impl d_add qm_ops it_1 it_2)"
proof (intro nfa_bool_comb_gen_same.intro nfa_bool_comb_gen.intro nfa_by_lts_correct
nfa_bool_comb_gen_axioms.intro)
fix a1 a2 as bc
assume invar_1: "nfa_invar a1"
and invar_2: "nfa_invar a2"
and invar_s: "l.invar as"
and as_OK: "l.\<alpha> as = \<Sigma> (nfa_\<alpha> a1) \<inter> \<Sigma> (nfa_\<alpha> a2)"
note it_1_OK' = lts_succ_label_it.lts_succ_label_it_correct [OF it_1_OK]
note it_2_OK' = lts_succ_it.lts_succ_it_correct [OF it_2_OK]
note const_OK = NFA_construct_reachable_impl_code_correct_no_enc [OF qm_ops_OK d_add_OK]
note correct = nfa_bool_comb_gen.bool_comb_correct_aux [OF bool_comb_impl_aux_correct_same,
where as = as and bc=bc, OF const_OK nfa_by_lts_correct]
show "nfa_invar (bool_comb_gen_impl d_add qm_ops it_1 it_2 as bc a1 a2) \<and>
NFA_isomorphic_wf
(nfa_\<alpha> (bool_comb_gen_impl d_add qm_ops it_1 it_2 as bc a1 a2))
(efficient_bool_comb_NFA bc (nfa_\<alpha> a1) (nfa_\<alpha> a2))"
unfolding bool_comb_gen_impl_def
proof (rule correct)
show "nfa_invar a1" by fact
next
show "nfa_invar a2" by fact
next
show "l.invar as" by fact
next
show "l.\<alpha> as = \<Sigma> (nfa_\<alpha> a1) \<inter> \<Sigma> (nfa_\<alpha> a2)" by fact
next
fix n1 n2
show "inj_on id (\<Q> (nfa_\<alpha> n1) \<times> \<Q> (nfa_\<alpha> n2))" by simp
next
fix n1
assume invar_n1: "nfa_invar n1"
hence invar': "nfa_invar_no_props n1" by (simp add: nfa_invar_alt_def)
from invar'
show "distinct (set_op_to_list s_ops (nfa_initial n1)) \<and>
set (set_op_to_list s_ops (nfa_initial n1)) = \<I> (nfa_\<alpha> n1)"
unfolding nfa_invar_no_props_def by (simp add: s.correct)
{ fix q
from it_1_OK' [of "nfa_trans n1" q] invar'
show "set_iterator (it_1 (nfa_trans n1) q)
{(a, q'). (q, a, q') \<in> \<Delta> (nfa_\<alpha> n1)}"
unfolding nfa_invar_no_props_def by simp
}
{ fix q a
from it_2_OK' [of "nfa_trans n1" q] invar'
show "set_iterator (it_2 (nfa_trans n1) q a) {q'. (q, a, q') \<in> \<Delta> (nfa_\<alpha> n1)}"
unfolding nfa_invar_no_props_def by simp
}
{ fix q
assume "q \<in> \<Q> (nfa_\<alpha> n1)"
with invar' show "s.memb q (nfa_accepting n1) = (q \<in> \<F> (nfa_\<alpha> n1))"
unfolding nfa_invar_no_props_def by (simp add: s.correct)
}
next
fix n1 n2
assume "nfa_invar n1" "nfa_invar n2"
"nfa_prop_is_complete_deterministic (nfa_props n1) \<and>
nfa_prop_is_complete_deterministic (nfa_props n2)"
thus "DFA (nfa_\<alpha> n1) \<and> DFA (nfa_\<alpha> n2)" by (simp add: nfa_invar_implies_DFA)
qed
qed
definition bool_comb_impl where
"bool_comb_impl d_add qm_ops it_1 it_2 bc A1 A2 =
bool_comb_gen_impl d_add qm_ops it_1 it_2 (nfa_labels A1) bc A1 A2"
schematic_goal bool_comb_impl_code :
"bool_comb_impl d_add qm_ops it_1 it_2 bc (Q1, A1, D1, I1, F1, p1) (Q2, A2, D2, I2, F2, p2) = ?XXX"
unfolding bool_comb_impl_def nfa_selectors_def snd_conv fst_conv
by (rule refl)
lemma bool_comb_impl_correct :
assumes qm_ops_OK: "StdMap qm_ops"
and d_add_OK: "lts_dlts_add d.\<alpha> d.invar d_add"
and it_1_OK: "lts_succ_label_it d.\<alpha> d.invar it_1"
and it_2_OK: "lts_succ_it d.\<alpha> d.invar it_2"
shows "nfa_bool_comb_same nfa_\<alpha> nfa_invar (bool_comb_impl d_add qm_ops it_1 it_2)"
proof (intro nfa_bool_comb_same.intro nfa_bool_comb.intro nfa_by_lts_correct
nfa_bool_comb_axioms.intro)
fix n1 n2 bc
assume invar_n1: "nfa_invar n1"
and invar_n2: "nfa_invar n2"
and labels_eq: "\<Sigma> (nfa_\<alpha> n1) = \<Sigma> (nfa_\<alpha> n2)"
from invar_n1 have invar_labels: "l.invar (nfa_labels n1)"
unfolding nfa_invar_alt_def nfa_invar_no_props_def by simp
have labels_eq: "l.\<alpha> (nfa_labels n1) = \<Sigma> (nfa_\<alpha> n1) \<inter> \<Sigma> (nfa_\<alpha> n2)"
using labels_eq unfolding nfa_\<alpha>_def by simp
note bool_comb_gen_OK = bool_comb_gen_impl_correct [OF qm_ops_OK d_add_OK it_1_OK it_2_OK]
note rule = nfa_bool_comb_gen.bool_comb_correct [OF bool_comb_gen_OK[unfolded nfa_bool_comb_gen_same_def]]
from rule[OF invar_n1 invar_n2 invar_labels labels_eq, of bc]
show "nfa_invar (bool_comb_impl d_add qm_ops it_1 it_2 bc n1 n2) \<and>
NFA_isomorphic_wf
(nfa_\<alpha> (bool_comb_impl d_add qm_ops it_1 it_2 bc n1 n2))
(efficient_bool_comb_NFA bc (nfa_\<alpha> n1) (nfa_\<alpha> n2))"
unfolding bool_comb_impl_def by simp
qed
subsection \<open> right quotient \<close>
definition right_quotient_map_lookup where
"right_quotient_map_lookup m_ops m q =
(case (map_op_lookup m_ops q m) of
None \<Rightarrow> s.empty ()
| Some S \<Rightarrow> S)"
definition right_quotient_map_build ::
"('q, 'q_set, 'm, _) map_ops_scheme \<Rightarrow>
('q \<times> 'a \<times> 'q, 'm) set_iterator \<Rightarrow> 'm"where
"right_quotient_map_build m_ops it =
it (\<lambda>_. True) (\<lambda>(q, a, q') m.
let S = right_quotient_map_lookup m_ops m q' in
let S' = s.ins q S in
(map_op_update m_ops q' S' m))
(map_op_empty m_ops ())"
lemma right_quotient_map_build_correct :
fixes m_ops it
defines "m \<equiv> right_quotient_map_build m_ops it"
assumes m_ops_OK: "StdMap m_ops"
and it_OK: "set_iterator it D"
shows "map_op_invar m_ops m \<and>
s.invar (right_quotient_map_lookup m_ops m q) \<and>
s.\<alpha> (right_quotient_map_lookup m_ops m q) =
{q'. \<exists>a. (q', a, q) \<in> D}"
proof -
interpret m: StdMap m_ops by fact
let ?I = "\<lambda>D m. \<forall>q.
m.invar m \<and>
s.invar (right_quotient_map_lookup m_ops m q) \<and>
s.\<alpha> (right_quotient_map_lookup m_ops m q) =
{q'. \<exists>a. (q', a, q) \<in> D}"
note it_rule = set_iterator_no_cond_rule_insert_P [OF it_OK, where ?I = ?I]
have "?I D m"
unfolding m_def right_quotient_map_build_def
proof (rule it_rule)
show "\<forall>q. m.invar (m.empty ()) \<and> s.invar (right_quotient_map_lookup m_ops (m.empty ()) q) \<and> s.\<alpha> (right_quotient_map_lookup m_ops (m.empty ()) q) = {q'. \<exists>a. (q', a, q) \<in> {}}"
by (simp add: right_quotient_map_lookup_def s.correct m.correct)
next
show "\<And>\<sigma>. \<forall>q. m.invar \<sigma> \<and> s.invar (right_quotient_map_lookup m_ops \<sigma> q) \<and> s.\<alpha> (right_quotient_map_lookup m_ops \<sigma> q) = {q'. \<exists>a. (q', a, q) \<in> D} \<Longrightarrow>
\<forall>q. m.invar \<sigma> \<and> s.invar (right_quotient_map_lookup m_ops \<sigma> q) \<and> s.\<alpha> (right_quotient_map_lookup m_ops \<sigma> q) = {q'. \<exists>a. (q', a, q) \<in> D}"
by simp
next
fix D' m qaq
assume asm: "qaq \<in> D - D'" "\<forall>q. m.invar m \<and> s.invar (right_quotient_map_lookup m_ops m q) \<and> s.\<alpha> (right_quotient_map_lookup m_ops m q) = {q'. \<exists>a. (q', a, q) \<in> D'}" "D' \<subseteq> D"
obtain q a q' where qaq_eq[simp]: "qaq = (q, a, q')" by (metis prod.exhaust)
from asm(1) have qaq_in_D: "(q,a,q') \<in> D" and qaq_nin_D': "(q,a,q') \<notin> D'" by simp_all
from asm(2) have
invar_m: "m.invar m" and
ind_hyp_invar[simp]: "\<And>q. s.invar (right_quotient_map_lookup m_ops m q)" and
ind_hyp_\<alpha>[simp]: "\<And>q. s.\<alpha> (right_quotient_map_lookup m_ops m q) = {q'. \<exists>a. (q', a, q) \<in> D'}"
by simp_all
note D'_subset = asm(3)
define m' where "m' \<equiv> map_op_update m_ops q' (s.ins q (right_quotient_map_lookup m_ops m q')) m"
have invar_m': "m.invar m'" by (simp add: m.correct invar_m m'_def)
have lookup_m': "\<And>q''. map_op_lookup m_ops q'' m' =
(if (q'' = q') then Some (s.ins q (right_quotient_map_lookup m_ops m q')) else
map_op_lookup m_ops q'' m)"
unfolding m'_def by (simp add: invar_m m.correct)
have map_lookup_m': "\<And>q''. right_quotient_map_lookup m_ops m' q'' =
(if (q'' = q') then (s.ins q (right_quotient_map_lookup m_ops m q')) else
right_quotient_map_lookup m_ops m q'')"
by (simp add: lookup_m' right_quotient_map_lookup_def)
show "\<forall>q. m.invar ((case qaq of (q, a) \<Rightarrow> case a of (a, q') \<Rightarrow> \<lambda>m. let S = right_quotient_map_lookup m_ops m q'; S' = s.ins q S in m.update q' S' m) m) \<and>
s.invar (right_quotient_map_lookup m_ops ((case qaq of (q, a) \<Rightarrow> case a of (a, q') \<Rightarrow> \<lambda>m. let S = right_quotient_map_lookup m_ops m q'; S' = s.ins q S in m.update q' S' m) m) q) \<and>
s.\<alpha> (right_quotient_map_lookup m_ops ((case qaq of (q, a) \<Rightarrow> case a of (a, q') \<Rightarrow> \<lambda>m. let S = right_quotient_map_lookup m_ops m q'; S' = s.ins q S in m.update q' S' m) m) q) =
{q'. \<exists>a. (q', a, q) \<in> insert qaq D'}"
apply (rule allI, rename_tac q'')
apply (case_tac "q'' = q'")
apply (simp_all add: m'_def[symmetric])
apply (simp_all add: map_lookup_m' s.correct invar_m'
split: option.split )
apply (auto)
done
qed
thus ?thesis by simp
qed
definition right_quotient_lists_impl ::
"('q, 'q_set, 'm, _) map_ops_scheme \<Rightarrow>
('q, 'a, 'm, 'd) lts_filter_it \<Rightarrow>
('a \<Rightarrow> bool) \<Rightarrow>
('q_set \<times> 'a_set \<times> 'd \<times> 'q_set \<times> 'q_set \<times> nfa_props) \<Rightarrow>
('q_set \<times> 'a_set \<times> 'd \<times> 'q_set \<times> 'q_set \<times> nfa_props)"
where
"right_quotient_lists_impl m_ops it AP AA =
(let m = right_quotient_map_build m_ops
(it (\<lambda>_. True) AP (\<lambda>_. True) (\<lambda>_. True) (nfa_trans AA)) in
let F = s.accessible_restrict_code
(\<lambda>q. s.to_list (right_quotient_map_lookup m_ops m q)) (s.empty ()) (s.to_list (nfa_accepting AA)) in
(nfa_states AA, nfa_labels AA, nfa_trans AA,
nfa_initial AA, F, nfa_props AA))"
lemma right_quotient_lists_impl_code :
"right_quotient_lists_impl m_ops it AP (Q, A, D, I, F, p) =
(let m = it (\<lambda>_. True) AP (\<lambda>_. True) (\<lambda>_. True) D (\<lambda>_. True)
(\<lambda>(q, a, q') m.
let S = case map_op_lookup m_ops q' m of None \<Rightarrow> set_op_empty s_ops () | Some S \<Rightarrow> S
in map_op_update m_ops q' (set_op_ins s_ops q S) m)
(map_op_empty m_ops ());
F = fst (worklist (\<lambda>s. True)
(\<lambda>s e. if set_op_memb s_ops e s then (s, [])
else (set_op_ins s_ops e s,
case_option [] (set_op_to_list s_ops) (map_op_lookup m_ops e m)))
(set_op_empty s_ops (), set_op_to_list s_ops F))
in (Q, A, D, I, F, p))"
proof -
have "s.to_list (s.empty ()) = []"
using s.to_list_correct [of "s.empty ()"]
by (simp add: s.empty_correct)
hence "\<And>q m. s.to_list (right_quotient_map_lookup m_ops m q) =
(case map_op_lookup m_ops q m of None \<Rightarrow> [] | Some S \<Rightarrow> set_op_to_list s_ops S)"
unfolding right_quotient_map_lookup_def
by (simp split: option.split)
thus ?thesis
unfolding right_quotient_lists_impl_def right_quotient_map_build_def
nfa_selectors_def snd_conv fst_conv right_quotient_map_lookup_def
by (simp add: s.accessible_restrict_code_def[abs_def] split_def
cong: if_cong)
qed
lemma right_quotient_lists_impl_correct :
assumes m_ops_OK: "StdMap m_ops"
and it_OK: "lts_filter_it d.\<alpha> d.invar it"
shows "nfa_right_quotient_lists nfa_\<alpha> nfa_invar nfa_\<alpha> nfa_invar (right_quotient_lists_impl m_ops it)"
proof (intro nfa_right_quotient_lists.intro nfa_by_lts_correct
nfa_right_quotient_lists_axioms.intro)
fix n AP
assume invar_n: "nfa_invar n"
from invar_n have invars:
"s.invar (nfa_states n)"
"l.invar (nfa_labels n)"
"d.invar (nfa_trans n)"
"s.invar (nfa_initial n)"
"s.invar (nfa_accepting n)"
unfolding nfa_invar_full_def by simp_all
define it' where "it' \<equiv> it (\<lambda>_. True) AP (\<lambda>_. True) (\<lambda>_. True) (nfa_trans n)"
define m where "m \<equiv> right_quotient_map_build m_ops it'"
define R where "R \<equiv> {(q, q'). \<exists>a. (q', a, q) \<in> lts_op_\<alpha> d_ops (nfa_trans n) \<and> AP a}"
define F where "F \<equiv> s.accessible_restrict_code
(\<lambda>q. s.to_list (right_quotient_map_lookup m_ops m q)) (s.empty ())
(s.to_list (nfa_accepting n))"
from invars lts_filter_it.lts_filter_it_correct [OF it_OK, of "nfa_trans n"
"\<lambda>_. True" AP "\<lambda>_. True" "\<lambda>_. True"]
have it'_OK: "set_iterator it' {(q, a, q'). (q, a, q') \<in> d.\<alpha> (nfa_trans n) \<and> AP a}"
unfolding it'_def by simp
note m_OK = right_quotient_map_build_correct [OF m_ops_OK it'_OK, folded m_def]
have fin_R: "finite R"
proof -
have R_eq: "R = (\<lambda>(q,a,q'). (q', q)) ` {(q,a,q'). (q,a,q') \<in> d.\<alpha> (nfa_trans n) \<and> AP a}"
unfolding R_def by (auto simp add: image_iff)
show "finite R"
apply (unfold R_eq)
apply (rule finite_imageI)
apply (rule finite_subset [of _ "d.\<alpha> (nfa_trans n)"])
apply (auto simp add: invars)
done
qed
have fin_S: "finite (accessible R (s.\<alpha> (nfa_accepting n)))"
apply (rule accessible_finite___args_finite)
apply (simp_all add: invars fin_R)
done
from s.accessible_restrict_code_correct [
where succ_list = "(\<lambda>q. s.to_list (right_quotient_map_lookup m_ops m q))" and
rs = "s.empty ()" and wl = "s.to_list (nfa_accepting n)"
and R=R, folded F_def] m_OK invar_n fin_S
have F_OK: "s.invar F \<and> s.\<alpha> F = accessible R (s.\<alpha> (nfa_accepting n))"
by (simp add: s.correct LTS_forget_labels_pred_def R_def accessible_restrict_empty
nfa_invar_full_def)
from invar_n F_OK
have "nfa_invar_no_props (right_quotient_lists_impl m_ops it AP n) \<and>
((nfa_\<alpha> (right_quotient_lists_impl m_ops it AP n)) =
(NFA_right_quotient_lists (nfa_\<alpha> n) {a. AP a}))"
unfolding right_quotient_lists_impl_def
apply (simp add: m_def[symmetric] F_def[symmetric] R_def[symmetric] it'_def[symmetric])
apply (simp add: nfa_invar_no_props_def nfa_invar_full_def NFA.NFA_right_quotient_lists_alt_def
nfa_\<alpha>_def R_def[symmetric])
done
with invar_n
show "nfa_invar (right_quotient_lists_impl m_ops it AP n) \<and>
NFA_isomorphic_wf (nfa_\<alpha> (right_quotient_lists_impl m_ops it AP n))
(NFA_right_quotient_lists (nfa_\<alpha> n) {a. AP a})"
apply (simp add: m_def[symmetric] F_def[symmetric]
nfa_invar_alt_def NFA_right_quotient___is_well_formed
NFA_isomorphic_wf_refl)
apply (simp add: nfa_invar_props_def right_quotient_lists_impl_def
NFA_right_quotient_alt_def)
done
qed
end
subsection \<open> determinise \<close>
definition determinise_next_state ::
"('q, 'q_set, _) set_ops_scheme \<Rightarrow> ('q,'q_set) set_iterator \<Rightarrow>
('q \<Rightarrow> ('q,'q_set) set_iterator) \<Rightarrow> 'q_set" where
"determinise_next_state s_ops it_S it_D =
(set_iterator_product it_S it_D) (\<lambda>_. True) (\<lambda>(_,q') S. set_op_ins s_ops q' S) (set_op_empty s_ops ())"
schematic_goal determinise_next_state_code :
"determinise_next_state s_ops it_S it_D = ?XXXX"
unfolding determinise_next_state_def set_iterator_product_def
by (rule refl)
lemma determinise_next_state_correct :
assumes s_ops_OK: "StdSet s_ops"
and it_S_OK: "set_iterator it_S S"
and it_D_OK: "\<And>q. set_iterator (it_D q) {q'. (q, a, q') \<in> D}"
shows "set_op_invar s_ops (determinise_next_state s_ops it_S it_D) \<and>
set_op_\<alpha> s_ops (determinise_next_state s_ops it_S it_D) = {q' . \<exists>q. q \<in> S \<and> (q, a, q') \<in> D}"
proof -
interpret s: StdSet s_ops by fact
have "(SIGMA aa:S. {q'. (aa, a, q') \<in> D}) = {(q, q') . q \<in> S \<and> (q, a, q') \<in> D}" by auto
with set_iterator_product_correct [where it_a = it_S and it_b = it_D,
OF it_S_OK it_D_OK]
have comb_OK: "set_iterator (set_iterator_product it_S it_D)
{(q, q') . q \<in> S \<and> (q, a, q') \<in> D}" by simp
have res_eq: "{q' . \<exists>q. q \<in> S \<and> (q, a, q') \<in> D} = snd ` {(q, q') . q \<in> S \<and> (q, a, q') \<in> D}"
by (auto simp add: image_iff)
show ?thesis
unfolding determinise_next_state_def res_eq
apply (rule set_iterator_no_cond_rule_insert_P [OF comb_OK,
where I = "\<lambda>S \<sigma>. s.invar \<sigma> \<and> s.\<alpha> \<sigma> = snd ` S"])
apply (auto simp add: s.correct image_iff Ball_def)
done
qed
definition determinise_iterator where
"determinise_iterator s_ops it_A it_S it_D =
set_iterator_image (\<lambda>a. (a, determinise_next_state s_ops it_S (\<lambda>q. it_D q a))) it_A"
lemma determinise_iterator_code :
"determinise_iterator s_ops it_A it_S it_D =
(\<lambda>c f. it_A c (\<lambda>x. f (x, it_S (\<lambda>_. True) (\<lambda>a. it_D a x (\<lambda>_. True)
(set_op_ins s_ops)) (set_op_empty s_ops ()))))"
unfolding determinise_iterator_def determinise_next_state_code set_iterator_image_alt_def
by simp
lemma determinise_iterator_correct :
fixes D :: "('q \<times> 'a \<times> 'q) set"
assumes it_A_OK: "set_iterator it_A A"
shows "set_iterator (determinise_iterator s_ops it_A it_S it_D)
((\<lambda>a. (a, determinise_next_state s_ops it_S (\<lambda>q. it_D q a))) ` A)"
unfolding determinise_iterator_def
apply (rule set_iterator_image_correct [OF it_A_OK])
apply (simp_all add: inj_on_def)
done
definition determinise_impl_aux where
"determinise_impl_aux const s_ops ff it_A it_D it_S I A FP =
(\<lambda>AA. const (ff AA) [I AA] (A AA)
(FP AA) (\<lambda>S. determinise_iterator s_ops (it_A AA) (it_S S) (it_D AA)))"
lemma (in nfa_by_lts_defs) determinise_impl_aux_correct :
fixes ss_ops :: "('q2::{automaton_states}, 'q2_set, _) set_ops_scheme"
and \<alpha> :: "'org_nfa \<Rightarrow> ('q2, 'a) NFA_rec"
assumes const_OK: "NFASpec.dfa_construct nfa_\<alpha> nfa_invar l.\<alpha> l.invar (set_op_\<alpha> ss_ops) (set_op_invar ss_ops) const"
and nfa_OK: "nfa \<alpha> invar"
and ss_ops_OK: "StdSet ss_ops"
and FP_OK: "\<And>n q. invar n \<Longrightarrow> set_op_invar ss_ops q \<Longrightarrow>
set_op_\<alpha> ss_ops q \<subseteq> \<Q> (\<alpha> n) \<Longrightarrow> FP n q = (set_op_\<alpha> ss_ops q \<inter> \<F> (\<alpha> n) \<noteq> {})"
and I_OK: "\<And>n. invar n \<Longrightarrow> set_op_invar ss_ops (I n) \<and> set_op_\<alpha> ss_ops (I n) = \<I> (\<alpha> n)"
and A_OK: "\<And>n. invar n \<Longrightarrow> set_op_invar l_ops (A n) \<and> set_op_\<alpha> l_ops (A n) = \<Sigma> (\<alpha> n)"
and it_A_OK: "\<And>n. invar n \<Longrightarrow> set_iterator (it_A n) (\<Sigma> (\<alpha> n))"
and it_S_OK: "\<And>S. set_op_invar ss_ops S \<Longrightarrow> set_iterator (it_S S) (set_op_\<alpha> ss_ops S)"
and it_D_OK: "\<And>n q a. invar n \<Longrightarrow> a \<in> \<Sigma> (\<alpha> n) \<Longrightarrow>
set_iterator (it_D n q a) {q'. (q, a, q') \<in> \<Delta> (\<alpha> n)}"
and ff_OK: "\<And>n. invar n \<Longrightarrow>
(\<exists>f. inj_on f {q. q \<subseteq> \<Q> (\<alpha> n)} \<and>
(\<forall>q. set_op_invar ss_ops q \<and> set_op_\<alpha> ss_ops q \<subseteq> \<Q> (\<alpha> n) \<longrightarrow> ff n q = f (set_op_\<alpha> ss_ops q)))"
shows "nfa_determinise \<alpha> invar nfa_\<alpha> nfa_invar
(determinise_impl_aux const ss_ops ff it_A it_D it_S I A FP)"
proof (intro nfa_determinise.intro nfa_OK nfa_by_lts_correct nfa_determinise_axioms.intro)
fix n
assume invar_n: "invar n"
let ?AA' = "determinise_NFA (\<alpha> n)"
let ?D_it = "\<lambda>S. determinise_iterator ss_ops (it_A n) (it_S S) (it_D n)"
from invar_n nfa_OK have AA'_wf: "DFA ?AA'"
apply (rule_tac determinise_NFA___DFA)
apply (simp add: nfa_def)
done
{ fix q
assume invar_q: "set_op_invar ss_ops q"
and q_subset: "set_op_\<alpha> ss_ops q \<in> \<Q> (determinise_NFA (\<alpha> n))"
let ?DS = "(\<lambda>a. (a, determinise_next_state ss_ops (it_S q) (\<lambda>q. it_D n q a))) ` \<Sigma> (\<alpha> n)"
from determinise_iterator_correct [OF it_A_OK, OF invar_n, of ss_ops "it_S q" "it_D n"]
have D_it_OK: "set_iterator (?D_it q) ?DS" by simp
note it_S_OK' = it_S_OK [OF invar_q]
{ fix a
assume a_in: "a \<in> \<Sigma> (\<alpha> n)"
from determinise_next_state_correct [OF ss_ops_OK it_S_OK', of "\<lambda>q. it_D n q a" a, OF it_D_OK,
OF invar_n a_in]
have "set_op_invar ss_ops (determinise_next_state ss_ops (it_S q) (\<lambda>q. it_D n q a))"
"set_op_\<alpha> ss_ops (determinise_next_state ss_ops (it_S q) (\<lambda>q. it_D n q a)) =
{q'. \<exists>qa. qa \<in> set_op_\<alpha> ss_ops q \<and> (qa, a, q') \<in> \<Delta> (\<alpha> n)}" by simp_all
} note det_next_state_eval = this
have "set_iterator_abs (\<lambda>(a, q'). (a, set_op_\<alpha> ss_ops q'))
(\<lambda>(a, q'). set_op_invar ss_ops q')
(determinise_iterator ss_ops (it_A n) (it_S q) (it_D n))
{(a, q'). (set_op_\<alpha> ss_ops q, a, q') \<in> \<Delta> (determinise_NFA (\<alpha> n))}"
apply (rule set_iterator_abs_I2)
apply (rule D_it_OK)
apply (insert q_subset)
apply (auto simp add: image_iff det_next_state_eval Bex_def)
done
} note D_it_OK' = this
from ff_OK[OF invar_n] obtain f where f_props:
"inj_on f {q. q \<subseteq> \<Q> (\<alpha> n)}"
"\<And>q. set_op_invar ss_ops q \<Longrightarrow> set_op_\<alpha> ss_ops q \<subseteq> \<Q> (\<alpha> n) \<Longrightarrow> ff n q = f (set_op_\<alpha> ss_ops q)"
by blast
note construct_correct = dfa_construct.dfa_construct_correct [OF const_OK AA'_wf,
where ?I= "[I n]" and ?A="A n" and ?FP="FP n" and ?ff="ff n" and ?f=f and ?D_it = ?D_it,
OF _ _ _ _ _ _ _ _ D_it_OK']
show "nfa_invar (determinise_impl_aux const ss_ops ff it_A it_D it_S I A FP n) \<and>
NFA_isomorphic_wf (nfa_\<alpha> (determinise_impl_aux const ss_ops ff it_A it_D it_S I A FP n))
(efficient_determinise_NFA (\<alpha> n))"
unfolding determinise_impl_aux_def efficient_determinise_NFA_def
apply (rule_tac construct_correct)
apply (simp_all add: I_OK[OF invar_n] A_OK[OF invar_n] FP_OK[OF invar_n]
f_props determinise_NFA_full_def ff_OK[OF invar_n])
done
qed
definition set_encode_rename :: "('a \<Rightarrow> nat) \<Rightarrow> 'a set \<Rightarrow> nat" where
"set_encode_rename f S = set_encode (f ` S)"
lemma set_encode_rename_eq:
assumes fin: "finite S"
and f_inj_on: "inj_on f S"
and sub: "A \<subseteq> S" "B \<subseteq> S"
shows "set_encode_rename f A = set_encode_rename f B \<longleftrightarrow> A = B"
proof -
from sub f_inj_on have f_inj_on': "inj_on f (A \<union> B)"
by (simp add: inj_on_def Ball_def subset_iff)
from fin sub have fin': "finite A" "finite B" by (metis finite_subset)+
from inj_on_Un_image_eq_iff[OF f_inj_on']
fin' set_encode_eq [of "f ` A" "f ` B"] show ?thesis
by (simp add: set_encode_rename_def)
qed
definition set_encode_rename_map ::
"('q, nat, 'm, _) map_ops_scheme \<Rightarrow> ('q, 'm \<times> nat) set_iterator \<Rightarrow> 'm" where
"set_encode_rename_map m_ops it =
fst (it (\<lambda>_. True) (\<lambda>q (m, n). (map_op_update_dj m_ops q n m, 2*n)) (map_op_empty m_ops (), 1))"
lemma set_encode_rename_map_correct :
fixes m_ops :: "('q, nat, 'm, _) map_ops_scheme"
and it :: "('q, 'm \<times> nat) set_iterator"
defines "m \<equiv> set_encode_rename_map m_ops it"
assumes it_OK: "set_iterator it S"
and m_ops_OK: "StdMap m_ops"
shows "\<exists>f. inj_on f S \<and> map_op_invar m_ops m \<and>
(dom (map_op_\<alpha> m_ops m) = S) \<and>
(\<forall>q\<in>S. (map_op_\<alpha> m_ops m) q = Some (2 ^ (f q)))"
proof -
interpret m: StdMap m_ops by fact
let ?I = "\<lambda>S (m, n).
\<exists>f n'. inj_on f S \<and> map_op_invar m_ops m \<and>
(dom (map_op_\<alpha> m_ops m) = S) \<and>
(\<forall>q\<in>S. (map_op_\<alpha> m_ops m) q = Some (2 ^ (f q))) \<and>
(\<forall>q\<in>S. f q < n') \<and> (n = 2 ^ n')"
obtain m' n where m_eq':
"it (\<lambda>_. True) (\<lambda>q (m, n). (map_op_update_dj m_ops q n m, 2*n)) (map_op_empty m_ops (), 1) = (m', n)"
by (rule prod.exhaust)
have "?I S ((it (\<lambda>_. True) (\<lambda>q (m, n). (map_op_update_dj m_ops q n m, 2*n)) (map_op_empty m_ops (), 1)))"
proof (rule set_iterator_no_cond_rule_insert_P[OF it_OK, of ?I])
show "case (m.empty (), 1) of (m, n) \<Rightarrow> \<exists>f n'. inj_on f {} \<and> m.invar m \<and> dom (m.\<alpha> m) = {} \<and> (\<forall>q\<in>{}. m.\<alpha> m q = Some (2 ^ f q)) \<and> (\<forall>q\<in>{}. f q < n') \<and> n = 2 ^ n'"
apply (simp add: m.correct)
apply (rule exI [where x = 0])
apply simp
done
next
show "\<And>\<sigma>. case \<sigma> of (m, n) \<Rightarrow> \<exists>f n'. inj_on f S \<and> m.invar m \<and> dom (m.\<alpha> m) = S \<and> (\<forall>q\<in>S. m.\<alpha> m q = Some (2 ^ f q)) \<and> (\<forall>q\<in>S. f q < n') \<and> n = 2 ^ n' \<Longrightarrow>
case \<sigma> of (m, n) \<Rightarrow> \<exists>f n'. inj_on f S \<and> m.invar m \<and> dom (m.\<alpha> m) = S \<and> (\<forall>q\<in>S. m.\<alpha> m q = Some (2 ^ f q)) \<and> (\<forall>q\<in>S. f q < n') \<and> n = 2 ^ n'"
by simp
next
fix S' and mn::"'m \<times> nat" and q
assume asm: "q \<in> S - S'" "case mn of (m, n) \<Rightarrow> \<exists>f n'. inj_on f S' \<and> m.invar m \<and> dom (m.\<alpha> m) = S' \<and> (\<forall>q\<in>S'. m.\<alpha> m q = Some (2 ^ f q)) \<and> (\<forall>q\<in>S'. f q < n') \<and> n = 2 ^ n'" "S' \<subseteq> S"
note q_in = asm(1)
note ind_hyp = asm(2)
note S'_subset = asm(3)
obtain m n where mn_eq[simp]: "mn = (m, n)" by (rule prod.exhaust)
from ind_hyp obtain f n' where f_props: "
inj_on f S' \<and>
map_op_invar m_ops m \<and>
dom (map_op_\<alpha> m_ops m) = S' \<and> (\<forall>q\<in>S'. map_op_\<alpha> m_ops m q = Some (2 ^ f q)) \<and>
(\<forall>q\<in>S'. f q < n') \<and> (n = 2 ^ n')"
by auto
let ?f' = "\<lambda>q'. if q' = q then n' else f q'"
from f_props q_in
show "case case mn of (m, n) \<Rightarrow> (m.update_dj q n m, 2 * n) of
(m, n) \<Rightarrow> \<exists>f n'. inj_on f (insert q S') \<and> m.invar m \<and> dom (m.\<alpha> m) = insert q S' \<and> (\<forall>q\<in>insert q S'. m.\<alpha> m q = Some (2 ^ f q)) \<and> (\<forall>q'\<in>insert q S'. f q' < n') \<and> n = 2 ^ n'"
apply (simp add: m.correct)
apply (rule exI[where x = ?f'])
apply (simp add: image_iff Ball_def)
apply (intro conjI)
apply (simp add: inj_on_def)
apply (metis order_less_irrefl)
apply (rule exI [where x = "Suc n'"])
apply (simp)
apply (metis less_SucI)
done
qed
with m_eq' show ?thesis
apply (simp add: m_def set_encode_rename_map_def)
apply metis
done
qed
definition set_encode_rename_impl ::
"('q, nat, 'm, _) map_ops_scheme \<Rightarrow> 'm \<Rightarrow> ('q, nat) set_iterator \<Rightarrow> nat" where
"set_encode_rename_impl m_ops m it =
(it (\<lambda>_. True) (\<lambda>q n. n + the (map_op_lookup m_ops q m)) 0)"
lemma set_encode_rename_impl_correct:
assumes invar_m: "map_op_invar m_ops m"
and f_inj_on: "inj_on f S"
and m_ops_OK: "StdMap m_ops"
and m_prop: "\<And>q. q \<in> S \<Longrightarrow> (map_op_\<alpha> m_ops m) q = Some (2 ^ (f q))"
and it_OK: "set_iterator it S"
shows "set_encode_rename_impl m_ops m it = set_encode_rename f S"
proof -
interpret m: StdMap m_ops by fact
let ?I = "\<lambda>S n. n = set_encode_rename f S"
show ?thesis
unfolding set_encode_rename_impl_def
proof (rule set_iterator_no_cond_rule_insert_P[OF it_OK, of ?I])
fix S' n q
assume q_in: "q \<in> S - S'" and
n_eq: "n = set_encode_rename f S'" and
S'_subset: "S' \<subseteq> S"
from it_OK have "finite S" by (rule set_iterator_finite)
with S'_subset have "finite S'" by (metis finite_subset)
hence fin_f_S': "finite (f ` S')" by (rule finite_imageI)
from q_in f_inj_on S'_subset
have fq_nin: "f q \<notin> f ` S'" by (simp add: image_iff Ball_def subset_iff inj_on_def) metis
from set_encode_insert [OF fin_f_S' fq_nin]
have enc_insert: "set_encode (insert (f q) (f ` S')) = 2 ^ f q + set_encode (f ` S')" .
from q_in m_prop[of q] invar_m have m_q_eq: "map_op_lookup m_ops q m = Some (2 ^ (f q))"
by (simp add: m.correct)
show "n + the (map_op_lookup m_ops q m) = set_encode_rename f (insert q S')"
by (simp add: set_encode_rename_def m_q_eq enc_insert n_eq)
qed (simp_all add: set_encode_rename_def)
qed
context nfa_by_lts_defs
begin
definition determinise_impl where
"determinise_impl d_add qm_ops m_ops it_S it_S2 it_q it_A it_D n =
(if (nfa_prop_is_initially_connected (nfa_props n) \<and>
nfa_prop_is_complete_deterministic (nfa_props n)) then n else
(determinise_impl_aux
(NFA_construct_reachable_impl_code d_add qm_ops True)
s_ops
(\<lambda>n q. set_encode_rename_impl m_ops
(set_encode_rename_map m_ops (it_S2 (nfa_states n)))
(it_q q))
(\<lambda>n. it_A (nfa_labels n))
(\<lambda>n. it_D (nfa_trans n))
it_S
nfa_initial
nfa_labels
(\<lambda>n q. \<not>(s.disjoint q (nfa_accepting n))) n))"
lemma determinise_impl_code:
"determinise_impl d_add qm_ops m_ops it_S it_S2 it_q it_A it_D (Q1, A1, D1, I1, F1, p1) =
(if nfa_prop_is_initially_connected p1 \<and>
nfa_prop_is_complete_deterministic p1
then (Q1, A1, D1, I1, F1, p1)
else let re_map = (fst (it_S2 Q1 (\<lambda>_. True)
(\<lambda>q (m, n). (map_op_update_dj m_ops q n m, 2 * n))
(map_op_empty m_ops (), 1))) in
NFA_construct_reachable_impl_code
d_add qm_ops True
(\<lambda>q. it_q q (\<lambda>_. True)
(\<lambda>q n. n +
the (map_op_lookup m_ops q re_map))
0)
[I1] A1 (\<lambda>q. \<not> set_op_disjoint s_ops q F1)
(\<lambda>S c f.
it_A A1 c
(\<lambda>x. f (x, it_S S (\<lambda>_. True)
(\<lambda>a.
it_D D1 a x (\<lambda>_. True) (set_op_ins s_ops))
(set_op_empty s_ops ())))))"
unfolding determinise_impl_def determinise_impl_aux_def
nfa_selectors_def
determinise_iterator_code snd_conv fst_conv
set_encode_rename_impl_def set_encode_rename_map_def
by simp_all
lemma determinise_impl_correct :
assumes it_S_OK: "set_iteratei s.\<alpha> s.invar it_S"
and it_S2_OK: "set_iteratei s.\<alpha> s.invar it_S2"
and it_q_OK: "set_iteratei s.\<alpha> s.invar it_q"
and it_A_OK: "set_iteratei l.\<alpha> l.invar it_A"
and it_D_OK: "lts_succ_it d.\<alpha> d.invar it_D"
and d_add_OK: "lts_dlts_add d.\<alpha> d.invar d_add"
and qm_ops_OK: "StdMap qm_ops"
and m_ops_OK: "StdMap m_ops"
shows "nfa_determinise nfa_\<alpha> nfa_invar nfa_\<alpha> nfa_invar
(determinise_impl d_add qm_ops m_ops it_S it_S2 it_q it_A it_D)"
(is "nfa_determinise nfa_\<alpha> nfa_invar nfa_\<alpha> nfa_invar ?code")
proof (intro nfa_determinise.intro nfa_by_lts_correct
nfa_determinise_axioms.intro)
fix a
assume invar_a: "nfa_invar a"
show "nfa_invar (?code a) \<and>
NFA_isomorphic_wf (nfa_\<alpha> (?code a))
(efficient_determinise_NFA (nfa_\<alpha> a))"
proof (cases "nfa_prop_is_initially_connected (nfa_props a) \<and>
nfa_prop_is_complete_deterministic (nfa_props a)")
case True note is_already_dfa = this
from invar_a is_already_dfa have wf_a:
"DFA (nfa_\<alpha> a)"
"SemiAutomaton_is_initially_connected (nfa_\<alpha> a)"
unfolding nfa_invar_alt_def nfa_invar_props_def by (simp_all add: DFA_alt_def)
from efficient_determinise_NFA_already_det[OF wf_a]
show ?thesis by (simp add: determinise_impl_def is_already_dfa invar_a)
next
case False note is_not_dfa = this
note it_A_OK' = set_iteratei.iteratei_rule[OF it_A_OK]
note it_S_OK' = set_iteratei.iteratei_rule[OF it_S_OK]
note it_S2_OK' = set_iteratei.iteratei_rule[OF it_S2_OK]
{ fix Q
assume invar_Q: "s.invar Q"
define m where "m \<equiv> set_encode_rename_map m_ops (it_S2 Q)"
from invar_Q have fin_Q: "finite (s.\<alpha> Q)" by simp
from set_encode_rename_map_correct [OF it_S2_OK', OF invar_Q m_ops_OK,folded m_def]
obtain f where f_props: "inj_on f (s.\<alpha> Q)"
"map_op_invar m_ops m"
"dom (map_op_\<alpha> m_ops m) = s.\<alpha> Q"
"\<And>q. q\<in>s.\<alpha> Q \<Longrightarrow> map_op_\<alpha> m_ops m q = Some (2 ^ f q)"
by auto
{ fix S
assume "s.invar S" "s.\<alpha> S \<subseteq> s.\<alpha> Q"
with f_props set_encode_rename_impl_correct [of m_ops m f "s.\<alpha> S" "it_q S"]
have " set_encode_rename_impl m_ops m (it_q S) = set_encode_rename f (set_op_\<alpha> s_ops S)"
by (simp add: m_ops_OK subset_iff set_iteratei.iteratei_rule[OF it_q_OK] inj_on_def)
} note rename_impl_OK = this
have "\<exists>f. inj_on f {q. q \<subseteq> s.\<alpha> Q} \<and>
(\<forall>S. s.invar S \<and> s.\<alpha> S \<subseteq> s.\<alpha> Q \<longrightarrow>
set_encode_rename_impl m_ops m (it_q S) =
f (s.\<alpha> S))"
apply (rule exI [where x ="set_encode_rename f"])
apply (simp add: rename_impl_OK inj_on_def set_encode_rename_eq
set_encode_rename_eq [OF fin_Q f_props(1)])
done
} note ff_OK = this
note aux_rule = nfa_determinise.determinise_correct_aux [OF determinise_impl_aux_correct,
OF _ nfa_by_lts_correct]
show ?thesis
apply (simp add: determinise_impl_def is_not_dfa)
apply (rule aux_rule)
apply (simp_all add: s.StdSet_axioms invar_a it_S_OK')
apply (rule nfa_dfa_construct_sublocale_dfa)
apply (rule NFA_construct_reachable_impl_code_correct [OF qm_ops_OK d_add_OK])
apply (simp_all add: nfa_invar_full_def s.correct it_A_OK')
apply (insert it_D_OK) []
apply (simp add: lts_succ_it_def)
apply (rule ff_OK)
apply (simp)
done
qed
qed
subsection \<open> Emptyness Check \<close>
definition language_is_empty_impl ::
"(('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> ('q_set, 'a_set, 'd) NFA_impl) \<Rightarrow>
('q_set, 'a_set, 'd) NFA_impl \<Rightarrow> bool" where
"language_is_empty_impl norm n = (s.isEmpty (nfa_accepting (norm n)))"
lemma language_is_empty_impl_code :
"language_is_empty_impl norm n =
(let (Q, A, D, I, F, p) = norm n in s.isEmpty F)"
unfolding language_is_empty_impl_def
by (case_tac "norm n") simp
lemma language_is_empty_impl_correct :
assumes norm_OK: "nfa_normalise nfa_\<alpha> nfa_invar norm"
shows "nfa_language_is_empty nfa_\<alpha> nfa_invar (language_is_empty_impl norm)"
proof (intro nfa_language_is_empty.intro
nfa_language_is_empty_axioms.intro nfa_by_lts_correct)
fix n
assume invar_n: "nfa_invar n"
from nfa_normalise.normalise_correct[OF norm_OK, OF invar_n]
have invar_norm: "nfa_invar (norm n)" and
iso: "NFA_isomorphic_wf (nfa_\<alpha> (norm n)) (NFA_remove_unreachable_states (nfa_\<alpha> n))"
by simp_all
from invar_norm have NFA_norm: "NFA (nfa_\<alpha> (norm n))" unfolding nfa_invar_alt_def by simp
from iso have conn_norm: "SemiAutomaton_is_initially_connected (nfa_\<alpha> (norm n))"
by (metis SemiAutomaton_is_initially_connected___NFA_isomorphic_wf
SemiAutomaton_is_initially_connected___NFA_remove_unreachable_states)
from iso have L_eq: "\<L> (nfa_\<alpha> (norm n)) = \<L> (nfa_\<alpha> n)"
by (metis NFA_isomorphic_wf_\<L> NFA_remove_unreachable_states_\<L>)
from NFA.NFA_is_empty_\<L>[OF NFA_norm conn_norm, unfolded L_eq] invar_norm
show "language_is_empty_impl norm n = (\<L> (nfa_\<alpha> n) = {})"
unfolding language_is_empty_impl_def
apply (cases "norm n")
apply (simp add: nfa_\<alpha>_def nfa_invar_alt_def nfa_invar_no_props_def s.correct)
done
qed
subsection \<open> Hopcroft \<close>
definition (in -) Hopcroft_class_map_\<alpha>_impl where
"Hopcroft_class_map_\<alpha>_impl pim l u =
map (\<lambda>i. the (pim i)) [l..<Suc u]"
lemma (in -) Hopcroft_class_map_\<alpha>_impl_correct :
"set (Hopcroft_class_map_\<alpha>_impl pim l u) =
class_map_\<alpha> (pm, pim) (l, u)"
unfolding Hopcroft_class_map_\<alpha>_impl_def class_map_\<alpha>_def
by (auto simp add: image_iff Bex_def)
lemma (in -) upt_simps2 :
"[i..<j] = (if (i < j) then i # [Suc i..<j] else [])"
by (induct j) simp_all
lemma (in -) Hopcroft_class_map_\<alpha>_impl_code [code] :
"Hopcroft_class_map_\<alpha>_impl pim l u =
(if (l \<le> u) then
(the (pim l) # (Hopcroft_class_map_\<alpha>_impl pim (Suc l) u))
else [])"
unfolding Hopcroft_class_map_\<alpha>_impl_def
by (simp add: upt_simps2)
end
print_locale Hopcroft_impl_locale
locale nfa_by_lts_hop = nfa: nfa_by_lts_defs s_ops l_ops d_ops +
hop: Hopcroft_impl_locale s_ops s2_\<alpha> s2_invar sm_ops im_ops pm_ops pim_ops iM_ops sm_it cm_it pre_it pre_it2 iM_it
for s_ops :: "('q::{automaton_states}, 'q_set, _) set_ops_scheme"
and l_ops :: "('l, 'l_set, _) set_ops_scheme"
and d_ops :: "('q, 'l, 'd, _) lts_ops_scheme"
and s2_\<alpha> :: "'q_set2 \<Rightarrow> 'q set" and s2_invar
and sm_ops :: "('q, nat, 'sm, _) map_ops_scheme"
and im_ops :: "(nat, nat \<times> nat, 'im, _) map_ops_scheme"
and pm_ops :: "('q, nat, 'pm, _) map_ops_scheme"
and pim_ops :: "(nat, 'q, 'pim, _) map_ops_scheme"
and iM_ops :: "(nat, nat, 'iM, _) map_ops_scheme"
and sm_it :: "'q_set \<Rightarrow> ('q, 'sm) set_iterator"
and cm_it :: "'q_set \<Rightarrow> ('q, ('pm \<times> 'pim) \<times> nat) set_iterator"
and pre_it :: "'q_set2 \<Rightarrow> ('q, 'iM \<times> 'pm \<times> 'pim) set_iterator"
and pre_it2 :: "'q_set2 \<Rightarrow> ('q, ('q \<times> nat) list) set_iterator"
and iM_it :: "'iM \<Rightarrow> (nat \<times> nat, ('im \<times> 'sm \<times> nat) \<times> ('l \<times> nat) list) set_iterator"
begin
definition Hopcroft_minimise_impl where
"Hopcroft_minimise_impl rev_emp rev_add rev_get_succs rev_cleanup s_image_rename d_it d_image_rename AA =
(let AL = (nfa.l.to_list (nfa_by_lts_defs.nfa_labels AA)) in
let rv_D = rev_cleanup (ltsga_reverse rev_emp rev_add d_it (nfa_by_lts_defs.nfa_trans AA)) in
let pre_fun = (\<lambda>a pim (l, u).
rev_get_succs rv_D (Hopcroft_class_map_\<alpha>_impl (\<lambda>i. hop.pim.lookup i pim) l u) a) in
let ((_, sm, _), _) = hop.Hopcroft_code (nfa_by_lts_defs.nfa_states AA) (nfa_by_lts_defs.nfa_accepting AA) AL pre_fun in
nfa.rename_states_impl s_image_rename d_image_rename True AA (\<lambda>q. states_enumerate (the (hop.sm.lookup q sm))))"
schematic_goal Hopcroft_minimise_impl_code :
"Hopcroft_minimise_impl rev_emp rev_add rev_get_succs rev_cleanup s_image_rename d_it d_image_rename
(Q, A, D, I, F, p) = ?XXX"
unfolding Hopcroft_minimise_impl_def nfa.nfa_selectors_def fst_conv snd_conv
by (rule refl)
lemma Hopcroft_minimise_impl_correct :
fixes d_ops' :: "('q, 'l, 'd', _) lts_ops_scheme"
and succ_it :: "('q,'l,'q_set,'d'') lts_succ_it"
and rev_cleanup :: "'lts1 \<Rightarrow> 'lts2"
assumes wf_target: "nfa_by_lts_defs s_ops' l_ops d_ops'"
and s_image_rename_OK: "set_image nfa.s.\<alpha> nfa.s.invar (set_op_\<alpha> s_ops') (set_op_invar s_ops') s_image_rename"
and d_image_rename_OK: "dlts_image nfa.d.\<alpha> nfa.d.invar (lts_op_\<alpha> d_ops') (lts_op_invar d_ops') d_image_rename"
and d_it_OK: "lts_iterator nfa.d.\<alpha> nfa.d.invar d_it"
and rev_emp_OK: "lts_empty rev_\<alpha> rev_invar rev_emp"
and rev_add_OK: "lts_add rev_\<alpha> rev_invar rev_add"
and rev_get_succs_OK: "lts_get_succ_set rev2_\<alpha> rev2_invar s2_\<alpha> s2_invar rev_get_succs"
and rev_cleanup_OK: "lts_copy rev_\<alpha> rev_invar rev2_\<alpha> rev2_invar rev_cleanup"
shows "dfa_minimise
(nfa_by_lts_defs.nfa_\<alpha> s_ops l_ops d_ops)
(nfa_by_lts_defs.nfa_invar s_ops l_ops d_ops)
(nfa_by_lts_defs.nfa_\<alpha> s_ops' l_ops d_ops')
(nfa_by_lts_defs.nfa_invar s_ops' l_ops d_ops')
(Hopcroft_minimise_impl rev_emp rev_add rev_get_succs rev_cleanup s_image_rename d_it d_image_rename)"
proof (intro dfa_minimise.intro nfa_by_lts_defs.nfa_by_lts_correct
dfa_minimise_axioms.intro)
from nfa.nfa_by_lts_defs_axioms show "nfa_by_lts_defs s_ops l_ops d_ops" .
from wf_target show "nfa_by_lts_defs s_ops' l_ops d_ops'" .
(* from wf_target show "nfa (nfa_by_lts_defs.nfa_\<alpha> s_ops' l_ops d_ops') *)
(* (nfa_by_lts_defs.nfa_invar s_ops' l_ops d_ops')" *)
(* by (rule_tac nfa_by_lts_defs.nfa_by_lts_correct) *)
fix AA
assume invar_AA: "nfa.nfa_invar AA"
and DFA_AA: "DFA (nfa.nfa_\<alpha> AA)"
and AA_initially_connected: "SemiAutomaton_is_initially_connected (nfa.nfa_\<alpha> AA)"
from invar_AA have invar_no_props_AA: "nfa.nfa_invar_no_props AA" by (simp add: nfa.nfa_invar_alt_def)
let ?AA' = "(Hopcroft_minimise_impl rev_emp rev_add rev_get_succs rev_cleanup s_image_rename d_it d_image_rename) AA"
let ?AL = "nfa.l.to_list (nfa.nfa_labels AA)"
have AL_OK: "distinct ?AL" "set ?AL = \<Sigma> (nfa.nfa_\<alpha> AA)"
using invar_no_props_AA by (simp_all add: nfa.nfa_invar_no_props_def nfa.l.correct)
define rv where "rv \<equiv> rev_cleanup (ltsga_reverse rev_emp rev_add d_it (nfa.nfa_trans AA))"
from ltsga_reverse_correct [OF rev_emp_OK rev_add_OK d_it_OK]
have rv_OK: "lts_reverse nfa.d.\<alpha> nfa.d.invar rev_\<alpha> rev_invar (ltsga_reverse rev_emp rev_add d_it)" .
from lts_reverse.lts_reverse_correct[OF rv_OK, of "nfa.nfa_trans AA"]
lts_copy.copy_correct [OF rev_cleanup_OK]
have rev_d_props: "rev2_invar rv"
"rev2_\<alpha> rv = {(v', e, v) |v e v'. (v, e, v') \<in> nfa.d.\<alpha> (nfa.nfa_trans AA)}"
using invar_no_props_AA
by (simp_all add: nfa.nfa_invar_no_props_def rv_def)
define pre_fun where "pre_fun \<equiv> (\<lambda>a pim (l, u).
rev_get_succs rv (Hopcroft_class_map_\<alpha>_impl (\<lambda>i. hop.pim.lookup i pim) l u) a)"
{ fix a pim u l
note rev_get_succs_correct = lts_get_succ_set.lts_get_succ_set_correct [OF rev_get_succs_OK]
from rev_d_props
have "s2_invar (pre_fun a pim (l, u)) \<and>
s2_\<alpha> (pre_fun a pim (l, u)) =
{q. \<exists>q'. (q, a, q') \<in> \<Delta> (nfa.nfa_\<alpha> AA) \<and>
q' \<in> {the (map_op_lookup pim_ops i pim) |i. l \<le> i \<and> i \<le> u}}"
unfolding pre_fun_def
apply (simp add: rev_get_succs_correct Hopcroft_class_map_\<alpha>_impl_correct[of _ _ _ pm]
class_map_\<alpha>_def)
apply auto
done
} note pre_fun_OK = this
define rename_map where "rename_map \<equiv> hop.Hopcroft_code_rename_map (nfa.nfa_states AA) (nfa.nfa_accepting AA) ?AL pre_fun"
define rename_fun where "rename_fun \<equiv> (\<lambda>q. states_enumerate (the (hop.sm.lookup q rename_map)))::('q \<Rightarrow> 'q)"
have Q_OK: "(nfa.nfa_states AA, \<Q> (nfa.nfa_\<alpha> AA)) \<in> hop.s_rel" and
F_OK: "(nfa.nfa_accepting AA, \<F> (nfa.nfa_\<alpha> AA)) \<in> hop.s_rel"
using invar_no_props_AA by (simp_all add: nfa.nfa_invar_no_props_def hop.s_rel_def in_br_conv)
from hop.Hopcroft_code_correct_rename_fun [OF Q_OK F_OK DFA_AA AL_OK pre_fun_OK,
folded rename_map_def]
have "hop.sm.invar rename_map"
"dom (hop.sm.\<alpha> rename_map) = \<Q> (nfa.nfa_\<alpha> AA)" and
rename_fun_OK: "NFA_is_strong_equivalence_rename_fun (nfa.nfa_\<alpha> AA) rename_fun"
unfolding rename_fun_def
by auto
from nfa.rename_states_impl_correct_dfa [OF wf_target s_image_rename_OK d_image_rename_OK]
have rename_states_OK: "dfa_rename_states nfa.nfa_\<alpha> nfa.nfa_invar (nfa_by_lts_defs.nfa_\<alpha> s_ops' l_ops d_ops')
(nfa_by_lts_defs.nfa_invar s_ops' l_ops d_ops')
(nfa_by_lts_defs.rename_states_impl s_image_rename d_image_rename True)" by simp
from merge_NFA_minimise [OF DFA_AA AA_initially_connected rename_fun_OK]
have rename_is_minimal: "NFA_isomorphic_wf (NFA_rename_states (nfa.nfa_\<alpha> AA) rename_fun) (NFA_minimise (nfa.nfa_\<alpha> AA))"
by simp
have AA'_alt_def: "?AA' = nfa.rename_states_impl s_image_rename d_image_rename True AA rename_fun"
unfolding Hopcroft_minimise_impl_def rename_fun_def rename_map_def pre_fun_def rv_def
hop.Hopcroft_code_rename_map_def
by (simp add: Let_def split_def)
from DFA_AA rename_is_minimal invar_AA
dfa_rename_states.dfa_rename_states_correct [OF rename_states_OK, of AA rename_fun]
have "nfa_by_lts_defs.nfa_invar s_ops' l_ops d_ops' ?AA'"
"nfa_by_lts_defs.nfa_\<alpha> s_ops' l_ops d_ops' ?AA' = NFA_rename_states (nfa.nfa_\<alpha> AA) rename_fun"
by (simp_all add: NFA_isomorphic_wf___minimise DFA_alt_def DFA_is_minimal_def
nfa.nfa_invar_def AA'_alt_def)
with rename_is_minimal show
"nfa_by_lts_defs.nfa_invar s_ops' l_ops d_ops' ?AA' \<and>
NFA_isomorphic_wf (nfa_by_lts_defs.nfa_\<alpha> s_ops' l_ops d_ops' ?AA') (NFA_minimise (nfa.nfa_\<alpha> AA))"
by simp
qed
end
text \<open> It remains to implement the operations for the reversed transition system \<close>
locale Hopcroft_lts =
m: StdMap m_ops +
m2: StdMap m2_ops +
s: StdSet s_ops +
s2: StdSet s2_ops +
mm: StdMap mm_ops +
un: set_union_list "set_op_\<alpha> s2_ops" "set_op_invar s2_ops" "set_op_\<alpha> s2_ops" "set_op_invar s2_ops" un_list +
cp: set_copy "set_op_\<alpha> s_ops" "set_op_invar s_ops" "set_op_\<alpha> s2_ops" "set_op_invar s2_ops" copy +
m_it: map_iteratei "map_op_\<alpha> m_ops" "map_op_invar m_ops" m_it +
mm_it: map_iteratei "map_op_\<alpha> mm_ops" "map_op_invar mm_ops" mm_it
for m_ops::"('q,'mm,'m1,_) map_ops_scheme"
and m2_ops::"('q,'s2 option array,'m2,_) map_ops_scheme"
and mm_ops::"(nat,'s, 'mm,_) map_ops_scheme"
and s_ops::"(nat,'s,_) set_ops_scheme"
and s2_ops::"(nat,'s2,_) set_ops_scheme"
and copy :: "'s \<Rightarrow> 's2"
and m_it :: "'m1 \<Rightarrow> ('q \<times> 'mm, 'm2) set_iterator"
and mm_it :: "'mm \<Rightarrow> (nat \<times> 's, 's2 option array) set_iterator"
and un_list
begin
lemma ts_impl : "tsbm_defs m_ops mm_ops s_ops"
unfolding tsbm_defs_def
by (simp add: m.StdMap_axioms s.StdSet_axioms mm.StdMap_axioms)
definition "hopcroft_lts_\<alpha> \<equiv> ltsbm_AQQ_defs.ltsbm_\<alpha>(tsbm_defs.tsbm_\<alpha> m_ops mm_ops s_ops)"
definition "hopcroft_lts_invar \<equiv> ltsbm_AQQ_defs.ltsbm_invar(tsbm_defs.tsbm_invar m_ops mm_ops s_ops)"
lemma ts2_impl : "tsbm_defs m2_ops iam_ops s2_ops"
unfolding tsbm_defs_def
by (simp add: m2.StdMap_axioms s2.StdSet_axioms iam.StdMap_axioms)
definition "hopcroft_lts_\<alpha>2 \<equiv> ltsbm_AQQ_defs.ltsbm_\<alpha>(tsbm_defs.tsbm_\<alpha> m2_ops iam_ops s2_ops)"
definition "hopcroft_lts_invar2 \<equiv> ltsbm_AQQ_defs.ltsbm_invar(tsbm_defs.tsbm_invar m2_ops iam_ops s2_ops)"
lemma hopcroft_lts_\<alpha>_alt_def :
"hopcroft_lts_\<alpha> m1 = {(w, v, v').
\<exists>m2 s3.
map_op_\<alpha> m_ops m1 v = Some m2 \<and>
map_op_\<alpha> mm_ops m2 w = Some s3 \<and>
v' \<in> set_op_\<alpha> s_ops s3}"
unfolding hopcroft_lts_\<alpha>_def ltsbm_AQQ_defs.ltsbm_\<alpha>_def[abs_def]
tsbm_defs.tsbm_\<alpha>_def[OF ts_impl]
by (auto simp add: image_iff)
lemma hopcroft_lts_\<alpha>2_alt_def :
"hopcroft_lts_\<alpha>2 m1 = {(w, v, v').
\<exists>m2 s3.
map_op_\<alpha> m2_ops m1 v = Some m2 \<and>
map_op_\<alpha> iam_ops m2 w = Some s3 \<and>
v' \<in> set_op_\<alpha> s2_ops s3}"
unfolding hopcroft_lts_\<alpha>2_def ltsbm_AQQ_defs.ltsbm_\<alpha>_def[abs_def]
tsbm_defs.tsbm_\<alpha>_def[OF ts2_impl]
by (auto simp add: image_iff)
definition hopcroft_lts_copy where
"hopcroft_lts_copy m =
m_it m (\<lambda>_. True) (\<lambda>(a, mm) m2.
m2.update a (
mm_it mm (\<lambda>_. True) (\<lambda>(q, s) mm2.
iam.update q (copy s) mm2) (iam.empty ())) m2) (m2.empty ())"
lemma hopcroft_lts_copy_correct :
"lts_copy hopcroft_lts_\<alpha> hopcroft_lts_invar hopcroft_lts_\<alpha>2 hopcroft_lts_invar2
hopcroft_lts_copy"
proof
fix l1
assume invar_l1: "hopcroft_lts_invar l1"
define inner_it where "inner_it \<equiv> \<lambda>mm. mm_it mm iam_invar
(\<lambda>(q, s). map_op_update iam_ops q (copy s))
(map_op_empty iam_ops ())"
have inner_it_intro: "\<And>mm. mm_it mm iam_invar
(\<lambda>(q, s). map_op_update iam_ops q (copy s))
(map_op_empty iam_ops ()) = inner_it mm"
unfolding inner_it_def by simp
have "hopcroft_lts_\<alpha>2 (hopcroft_lts_copy l1) = hopcroft_lts_\<alpha> l1 \<and>
hopcroft_lts_invar2 (hopcroft_lts_copy l1)"
unfolding hopcroft_lts_copy_def inner_it_intro
proof (rule m_it.iterate_rule_insert_P [where I =
"\<lambda>d m2. hopcroft_lts_\<alpha>2 m2 = {(q, a, q'). (q, a, q') \<in> hopcroft_lts_\<alpha> l1 \<and> a \<in> d} \<and>
hopcroft_lts_invar2 m2 \<and> dom (m2.\<alpha> m2) = d"])
from invar_l1 show "m.invar l1"
unfolding hopcroft_lts_invar_def ltsbm_AQQ_defs.ltsbm_invar_def tsbm_defs.tsbm_invar_alt_def[OF ts_impl]
by simp
next
show "hopcroft_lts_\<alpha>2 (m2.empty ()) = {(q, a, q'). (q, a, q') \<in> hopcroft_lts_\<alpha> l1 \<and> a \<in> {}} \<and> hopcroft_lts_invar2 (m2.empty ()) \<and> dom (m2.\<alpha> (m2.empty ())) = {}"
unfolding hopcroft_lts_invar2_def ltsbm_AQQ_defs.ltsbm_invar_def
tsbm_defs.tsbm_invar_alt_def[OF ts2_impl]
by (simp add: hopcroft_lts_\<alpha>2_alt_def m2.correct)
next
fix k v it \<sigma>
assume asm:"k \<in> dom (m.\<alpha> l1) - it" "m.\<alpha> l1 k = Some v" "it \<subseteq> dom (m.\<alpha> l1)" "hopcroft_lts_\<alpha>2 \<sigma> = {(q, a, q'). (q, a, q') \<in> hopcroft_lts_\<alpha> l1 \<and> a \<in> it} \<and> hopcroft_lts_invar2 \<sigma> \<and> dom (m2.\<alpha> \<sigma>) = it"
from asm(1) have k_nin_it: "k \<notin> it" by simp
note l1_k_eq = asm(2)
note it_subset = asm(3)
note ind_hyp = asm(4)
from ind_hyp k_nin_it
have "k \<notin> dom (map_op_\<alpha> m2_ops \<sigma>)" by simp
hence mm_k_eq: "m2.\<alpha> \<sigma> k = None" by auto
from ind_hyp have invar2_hop_mm: "hopcroft_lts_invar2 \<sigma>" by simp
hence invar_mm: "m2.invar \<sigma>"
unfolding hopcroft_lts_invar2_def ltsbm_AQQ_defs.ltsbm_invar_def
tsbm_defs.tsbm_invar_alt_def[OF ts2_impl]
by simp
from invar_l1 l1_k_eq
have invar_v: "mm.invar v \<and>
(\<forall>w s3. mm.\<alpha> v w = Some s3 \<longrightarrow> s.invar s3)"
unfolding hopcroft_lts_invar_def ltsbm_AQQ_defs.ltsbm_invar_def
tsbm_defs.tsbm_invar_alt_def[OF ts_impl]
by simp
define inner_it_val where "inner_it_val \<equiv> {(q, k, q') | q q'.
\<exists>s3. iam.\<alpha> (inner_it v) q = Some s3 \<and>
q' \<in> s2.\<alpha> s3}"
have inner_it_OK: "iam.invar (inner_it v) \<and>
(\<forall>w s3. iam.\<alpha> (inner_it v) w = Some s3 \<longrightarrow>
s2.invar s3) \<and>
inner_it_val = {(q, a, q'). a = k \<and> (q, a, q') \<in> hopcroft_lts_\<alpha> l1}"
unfolding inner_it_def inner_it_val_def
proof (rule mm_it.iterate_rule_insert_P [where I = "\<lambda>d a.
iam.invar a \<and>
(\<forall>w s3. iam.\<alpha> a w = Some s3 \<longrightarrow> s2.invar s3) \<and>
(\<forall>q q'. (\<exists>s3. iam.\<alpha> a q = Some s3 \<and> q' \<in> s2.\<alpha> s3) =
(q \<in> d \<and> (q, k, q') \<in> hopcroft_lts_\<alpha> l1))"])
show "mm.invar v"
using invar_v by simp
next
show "iam.invar (iam.empty ()) \<and> (\<forall>w s3. iam.\<alpha> (iam.empty ()) w = Some s3 \<longrightarrow> s2.invar s3) \<and> (\<forall>q q'. (\<exists>s3. iam.\<alpha> (iam.empty ()) q = Some s3 \<and> q' \<in> s2.\<alpha> s3) = (q \<in> {} \<and> (q, k, q') \<in> hopcroft_lts_\<alpha> l1))"
by (simp add: iam.correct)
next
fix ka va it \<sigma>
assume "ka \<in> dom (mm.\<alpha> v) - it" "mm.\<alpha> v ka = Some va" "it \<subseteq> dom (mm.\<alpha> v)"
"iam.invar \<sigma> \<and> (\<forall>w s3. iam.\<alpha> \<sigma> w = Some s3 \<longrightarrow> s2.invar s3) \<and> (\<forall>q q'. (\<exists>s3. iam.\<alpha> \<sigma> q = Some s3 \<and> q' \<in> s2.\<alpha> s3) = (q \<in> it \<and> (q, k, q') \<in> hopcroft_lts_\<alpha> l1))"
then show "iam.invar ((case (ka, va) of (q, s) \<Rightarrow> iam.update q (copy s)) \<sigma>) \<and>
(\<forall>w s3. iam.\<alpha> ((case (ka, va) of (q, s) \<Rightarrow> iam.update q (copy s)) \<sigma>) w = Some s3 \<longrightarrow> s2.invar s3) \<and>
(\<forall>q q'. (\<exists>s3. iam.\<alpha> ((case (ka, va) of (q, s) \<Rightarrow> iam.update q (copy s)) \<sigma>) q = Some s3 \<and> q' \<in> s2.\<alpha> s3) = (q \<in> insert ka it \<and> (q, k, q') \<in> hopcroft_lts_\<alpha> l1))"
apply (intro conjI allI)
apply (auto simp add: hopcroft_lts_\<alpha>_alt_def l1_k_eq)
using invar_v cp.copy_correct(2) apply (simp add: iam.correct split: if_splits)
apply blast
apply (simp add: s2.correct iam.correct)
apply force
apply (simp add: s2.correct iam.correct split: if_splits)
using cp.copy_correct(1) invar_v apply blast
apply blast
apply (auto simp add: s2.correct iam.correct cp.copy_correct(1) invar_v)
done
next
show "\<And>\<sigma>. iam.invar \<sigma> \<and> (\<forall>w s3. iam.\<alpha> \<sigma> w = Some s3 \<longrightarrow> s2.invar s3) \<and> (\<forall>q q'. (\<exists>s3. iam.\<alpha> \<sigma> q = Some s3 \<and> q' \<in> s2.\<alpha> s3) = (q \<in> dom (mm.\<alpha> v) \<and> (q, k, q') \<in> hopcroft_lts_\<alpha> l1)) \<Longrightarrow>
iam.invar \<sigma> \<and> (\<forall>w s3. iam.\<alpha> \<sigma> w = Some s3 \<longrightarrow> s2.invar s3) \<and> {(q, k, q') |q q'. \<exists>s3. iam.\<alpha> \<sigma> q = Some s3 \<and> q' \<in> s2.\<alpha> s3} = {a. case a of (q, aa, q') \<Rightarrow> aa = k \<and> (q, aa, q') \<in> hopcroft_lts_\<alpha> l1}"
apply (intro conjI allI impI)
apply blast
apply blast
apply (auto simp add: hopcroft_lts_\<alpha>_alt_def l1_k_eq)
done
qed
from invar2_hop_mm
have \<alpha>_new: "hopcroft_lts_\<alpha>2 (map_op_update m2_ops k (inner_it v) \<sigma>) =
hopcroft_lts_\<alpha>2 \<sigma> \<union> inner_it_val"
unfolding hopcroft_lts_\<alpha>2_alt_def inner_it_val_def
hopcroft_lts_invar2_def ltsbm_AQQ_defs.ltsbm_invar_def
tsbm_defs.tsbm_invar_alt_def[OF ts2_impl]
by (simp add: m2.correct set_eq_iff all_conj_distrib mm_k_eq)
from ind_hyp
show "hopcroft_lts_\<alpha>2 ((case (k, v) of (a, mm) \<Rightarrow> m2.update a (inner_it mm)) \<sigma>) = {(q, a, q'). (q, a, q') \<in> hopcroft_lts_\<alpha> l1 \<and> a \<in> insert k it} \<and>
hopcroft_lts_invar2 ((case (k, v) of (a, mm) \<Rightarrow> m2.update a (inner_it mm)) \<sigma>) \<and> dom (m2.\<alpha> ((case (k, v) of (a, mm) \<Rightarrow> m2.update a (inner_it mm)) \<sigma>)) = insert k it"
unfolding hopcroft_lts_invar2_def ltsbm_AQQ_defs.ltsbm_invar_def
tsbm_defs.tsbm_invar_alt_def[OF ts2_impl]
apply (simp add: m2.correct invar_mm \<alpha>_new inner_it_OK)
apply auto
done
next
fix \<sigma>
assume "hopcroft_lts_\<alpha>2 \<sigma> = {(q, a, q'). (q, a, q') \<in> hopcroft_lts_\<alpha> l1 \<and> a \<in> dom (m.\<alpha> l1)} \<and> hopcroft_lts_invar2 \<sigma> \<and> dom (m2.\<alpha> \<sigma>) = dom (m.\<alpha> l1)"
thus "hopcroft_lts_\<alpha>2 \<sigma> = hopcroft_lts_\<alpha> l1 \<and> hopcroft_lts_invar2 \<sigma>"
by (auto simp add: hopcroft_lts_\<alpha>_alt_def)
qed
thus "hopcroft_lts_\<alpha>2 (hopcroft_lts_copy l1) = hopcroft_lts_\<alpha> l1"
"hopcroft_lts_invar2 (hopcroft_lts_copy l1)" by simp_all
qed
definition "hopcroft_lts_empty \<equiv> m.empty"
lemma hopcroft_lts_empty_correct :
"lts_empty hopcroft_lts_\<alpha> hopcroft_lts_invar hopcroft_lts_empty"
using ltsbm_AQQ_defs.ltsbm_empty_correct[OF
tsbm_defs.tsbm_empty_correct[OF ts_impl,
unfolded tsbm_defs.tsbm_empty_def[OF ts_impl],
folded hopcroft_lts_\<alpha>_def hopcroft_lts_invar_def hopcroft_lts_empty_def]]
unfolding hopcroft_lts_\<alpha>_def[symmetric] hopcroft_lts_invar_def[symmetric] .
definition "hopcroft_lts_add \<equiv> ltsbm_AQQ_defs.ltsbm_add(
tsbm_defs.tsbm_add m_ops mm_ops s_ops)"
lemma hopcroft_lts_add_alt_def :
"hopcroft_lts_add = (\<lambda>q a v' l.
case map_op_lookup m_ops a l of
None \<Rightarrow>
map_op_update m_ops a (mm.sng q (set_op_sng s_ops v')) l
| Some m2 \<Rightarrow>
(case mm.lookup q m2 of
None \<Rightarrow>
map_op_update m_ops a
(mm.update q (set_op_sng s_ops v') m2) l
| Some s3 \<Rightarrow>
map_op_update m_ops a
(mm.update q (set_op_ins s_ops v' s3) m2) l))"
unfolding hopcroft_lts_add_def tsbm_defs.tsbm_add_def[OF ts_impl, abs_def]
ltsbm_AQQ_defs.ltsbm_add_def[abs_def]
by simp
lemma hopcroft_lts_add_correct :
"lts_add hopcroft_lts_\<alpha> hopcroft_lts_invar hopcroft_lts_add"
using ltsbm_AQQ_defs.ltsbm_add_correct[OF
tsbm_defs.tsbm_add_correct[OF ts_impl,
unfolded tsbm_defs.tsbm_empty_def[OF ts_impl],
folded hopcroft_lts_\<alpha>_def hopcroft_lts_invar_def]]
unfolding hopcroft_lts_\<alpha>_def[symmetric] hopcroft_lts_add_def
hopcroft_lts_invar_def[symmetric] .
definition "hopcroft_lts_get_succ_set l vs a =
(case m2.lookup a l of None \<Rightarrow> s2.empty ()
| Some im \<Rightarrow> un_list (List.map_filter (\<lambda>q. iam.lookup q im) vs))"
lemma hopcroft_lts_get_succ_set_correct :
"lts_get_succ_set hopcroft_lts_\<alpha>2 hopcroft_lts_invar2 s2.\<alpha> s2.invar hopcroft_lts_get_succ_set"
proof
fix l vs a
assume invar_l: "hopcroft_lts_invar2 l"
have "s2.invar (hopcroft_lts_get_succ_set l vs a) \<and>
s2.\<alpha> (hopcroft_lts_get_succ_set l vs a) =
{v'. \<exists>v. v \<in> set vs \<and> (v, a, v') \<in> hopcroft_lts_\<alpha>2 l}" (is "?P1 \<and> ?P2")
proof (cases "m2.lookup a l")
case None
with invar_l
show ?thesis
by (simp add: hopcroft_lts_get_succ_set_def s2.correct hopcroft_lts_\<alpha>2_alt_def
hopcroft_lts_invar2_def ltsbm_AQQ_defs.ltsbm_invar_def
tsbm_defs.tsbm_invar_def[OF ts2_impl] m2.correct)
next
case (Some im) note l_a_eq = this
define l' where "l' \<equiv> List.map_filter (\<lambda>q. iam.lookup q im) vs"
from invar_l l_a_eq
have invar_im : "iam.invar im"
and l'_OK: "\<forall>s1\<in>set l'. s2.invar s1"
unfolding l'_def set_map_filter hopcroft_lts_invar2_def ltsbm_AQQ_defs.ltsbm_invar_def
tsbm_defs.tsbm_invar_alt_def[OF ts2_impl]
apply (auto simp add: m2.correct iam.correct)
apply (metis option.collapse)
done
from invar_l l_a_eq un.union_list_correct[OF l'_OK] invar_im
show ?thesis
apply (simp add: l'_def hopcroft_lts_get_succ_set_def s2.correct hopcroft_lts_\<alpha>2_alt_def
hopcroft_lts_invar2_def ltsbm_AQQ_defs.ltsbm_invar_def iam.correct
tsbm_defs.tsbm_invar_def[OF ts2_impl] m2.correct set_map_filter)
apply fastforce
done
qed
thus "?P1" "?P2" by simp_all
qed
end
end
|
MODULE CONSTANTS
use, intrinsic :: iso_fortran_env, dp=>real64 !define the size of our double precision numbers
REAL(dp), parameter :: C = 2.99792458D+10 !Speed of light in cgs
REAL(dp), PARAMETER :: K_BOLTZ = 1.38065040D-16 ! Boltzmann constant cgs
REAL(dp), PARAMETER :: HP = 6.62606896D-27 !Planck constant in cgs
REAL(dp), PARAMETER :: REDUCED_PLANCK=1.054571628d-27
REAL(dp), PARAMETER :: MH = 1.67262164D-24 !H nucleus mass in cgs
REAL(dp), PARAMETER :: AMU=1.66053892d-24 !atomic mass unit in cgs
REAL(dp), PARAMETER :: PI = 3.141592654
REAL(dp), PARAMETER :: K_BOLTZ_SI=1.38d-23 !Boltzmann constant SI
REAL(dp), PARAMETER :: PC=3.086d18 !parsec in cgs
REAL(dp), PARAMETER :: au=2.063d5 !1 AU in cgs
REAL(dp), PARAMETER :: KM=1.d5 !kilometre in cgs
REAL(dp), PARAMETER :: SECONDS_PER_YEAR=3.16d7
REAL(dp), PARAMETER :: T_CMB=2.73
REAL(dp), PARAMETER :: EV = 1.60217646D-12 ! electron volt in erg
REAL(dp), PARAMETER :: GRAV_G = 6.674d-8 !gravitational constant in cgs
REAL(dp), PARAMETER :: SB_CONST=5.6704d-5 !Stefan Boltzmann constant in cgs
!Error codes for python wrap
INTEGER, PARAMETER :: PARAMETER_READ_ERROR=-1
INTEGER, PARAMETER :: PHYSICS_INIT_ERROR=-2
INTEGER, PARAMETER :: CHEM_INIT_ERROR=-3
INTEGER, PARAMETER :: INT_UNRECOVERABLE_ERROR=-4
INTEGER, PARAMETER :: INT_TOO_MANY_FAILS_ERROR=-5
CONTAINS
!Hold over from heating branch
SUBROUTINE pair_insertion_sort(array)
REAL(dp), INTENT(inout) :: array(:)
INTEGER :: i,j,last
REAL(dp) :: t1,t2
last=size(array)
DO i=2,last-1,2
t1=min(array(i),array(i+1))
t2=max(array(i),array(i+1))
j=i-1
DO while((j.ge.1).and.(array(j).gt.t2))
array(j+2)=array(j)
j=j-1
ENDDO
array(j+2)=t2
DO while((j.ge.1).and.(array(j).gt.t1))
array(j+1)=array(j)
j=j-1
ENDDO
array(j+1)=t1
END DO
IF(mod(last,2).eq.0)then
t1=array(last)
DO j=last-1,1,-1
IF (array(j).le.t1) exit
array(j+1)=array(j)
END DO
array(j+1)=t1
ENDIF
END SUBROUTINE pair_insertion_sort
END MODULE CONSTANTS |
function rotate(pos, instr)
alefbet = "abcdefghijklmnopqrstuvwxyz"
res = ""
for c in instr
isup = isuppercase(c)
orgpos = findfirst(lowercase(c), alefbet)
if orgpos == nothing
res = res * c
else
newpos = (orgpos + pos) % 26
if newpos == 0
newpos = 26
end
newletter = !isup ? alefbet[newpos] : uppercase(alefbet[newpos])
res = res * newletter
end
end
if instr isa String
return res
else
return res[1]
end
end |
! License
! -------
! This file is part of the JAMS Fortran package, distributed under the MIT License.
!
! Copyright (c) 2016 Matthias Cuntz - mc (at) macu (dot) de
!
! 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.
module mo_qhull
use mo_kind, only: i4, dp
implicit none
PUBLIC :: qhull ! convex hull calculation from number of points
integer(i4) :: qhull_f
external :: qhull_f
contains
function qhull(points, flags, outfile)
implicit none
real(dp), dimension(:,:), intent(in) :: points
character(len=*), optional :: flags
character(len=*), optional :: outfile
integer(i4) :: qhull
character(len=250) :: iflags
#ifdef __pgiFortran__
character(len=299) :: ioutfile
#else
character(len=1024) :: ioutfile
#endif
if (present(flags)) then
iflags = trim(flags)
else
iflags = "qhull FS Fv n"
endif
if (present(outfile)) then
ioutfile = trim(outfile)
else
ioutfile = "qhull.out"
endif
qhull = qhull_f(trim(iflags), trim(ioutfile), size(points,1), size(points,2), points)
end function qhull
end module mo_qhull
|
!! SR103454: fixed in 6.2 build 6230
!!
!! WRONG RESULT FROM SOURCED ALLOCATION
!!
!! The following example yields the incorrect result and exits abnormally
!! at the 'STOP 2' statement. This is with NAG 6.2 (6228) and 6.1 (6149)
!!
module foo_mod
type, public :: any_scalar
class(*), allocatable :: value
end type
interface any_scalar
procedure any_scalar_value
end interface
type, public :: foo
class(*), allocatable :: x
contains
procedure :: set
end type
contains
!! User-defined constructor.
function any_scalar_value(value) result(obj)
class(*), intent(in) :: value
type(any_scalar) :: obj
allocate(obj%value, source=value)
end function any_scalar_value
subroutine set(this, value)
class(foo), intent(inout) :: this
class(*), intent(in) :: value
allocate(this%x, source=any_scalar(value)) ! <== VALUES NOT BEING ASSIGNED CORRECTLY
select type (x => this%x)
type is (any_scalar)
call check(x)
class default
stop 1
end select
end subroutine
subroutine check(x)
type(any_scalar), intent(in) :: x
select type (v => x%value)
type is (character(*))
if (v /= 'bizbat') stop 2 ! <== EXISTS HERE WITH INCORRECT VALUE
class default
stop 3
end select
end subroutine
end module
use foo_mod
type(foo) :: p
call p%set('bizbat')
end
|
A diving course is the start of a lifelong adventure! Everyone with normal health can learn to dive. Diving is fun and relaxing as it’s on the same time is exiting and thrilling.
H2O in Lund offers PADI courses at all levels from beginner level to Instructor level courses. We also offer technical dive courses for example DSAT Tec deep.
At H2O in Lund we will help you to become a self-sufficient and safe diver, we therefore include two days of extra diving upon finishing the new beginner diving course – Open Water Diver. We believe that those extra supervised diving gives you a lot of additional comfort and experience. After successfully completing the entry-level course, you’ll receive a PADI Open Water Diver certificate, the world’s most widely recognized diving certificate. This entitles you to rent equipment and participate in dive excursions all over the world.
If you want to continue your dive education we offer may special courses such as deep diver, wreck diver and underwater photographer, as a PADI Five star IDC center we also leadership and instructor courses. |
using BinaryProvider # requires BinaryProvider 0.3.0 or later
# Example taken from
# https://github.com/JuliaIO/ImageMagick.jl/blob/sd/binaryprovider/deps/build.jl
dependencies = [
"build_Zlib.v1.2.11.jl",
"build_GEOS.v3.6.2.jl",
"build_PROJ.v4.9.3.jl",
]
for elem in dependencies
# it's a bit faster to run the build in an anonymous module instead of
# starting a new julia process
m = Module(:__anon__)
Core.eval(m, :(Main.include($(joinpath(@__DIR__, elem)))))
end
# Parse some basic command-line arguments
const verbose = "--verbose" in ARGS
const prefix = Prefix(get([a for a in ARGS if a != "--verbose"], 1, joinpath(@__DIR__, "usr")))
products = [
LibraryProduct(prefix, String["libgdal"], :libgdal),
ExecutableProduct(prefix, "gdalinfo", :gdalinfo_path),
ExecutableProduct(prefix, "gdalwarp", :gdalwarp_path),
ExecutableProduct(prefix, "gdal_translate", :gdal_translate_path),
ExecutableProduct(prefix, "ogr2ogr", :ogr2ogr_path),
ExecutableProduct(prefix, "ogrinfo", :ogrinfo_path),
]
# Download binaries from hosted location
bin_prefix = "https://github.com/JuliaGeo/GDALBuilder/releases/download/v2.2.4-1"
# Listing of files generated by BinaryBuilder:
download_info = Dict(
Linux(:aarch64, :glibc) => ("$bin_prefix/GDAL.aarch64-linux-gnu.tar.gz", "6d7dd617273b257e4e81357352b5b4e76afe42116a12d44b92114797519c1b38"),
Linux(:armv7l, :glibc, :eabihf) => ("$bin_prefix/GDAL.arm-linux-gnueabihf.tar.gz", "6cb4f535fdad9a1a947c05575929c9dd8bf419c926f75d75ed45f3b19fdddc3f"),
Linux(:i686, :glibc) => ("$bin_prefix/GDAL.i686-linux-gnu.tar.gz", "447ccbe09390a55f640498a8539aee3f910678f14e63ee9904ce3df8477a0652"),
Windows(:i686) => ("$bin_prefix/GDAL.i686-w64-mingw32.tar.gz", "bbb2f9f1abe6dd39fa9c35c08f24dc09fd9aa5ae794ff9b2a47dcd4795ea1b4c"),
Linux(:powerpc64le, :glibc) => ("$bin_prefix/GDAL.powerpc64le-linux-gnu.tar.gz", "932dd4e0a0fed47590647f5c83a4530372b21b006ae06cbcb06394adbc16cdb9"),
MacOS(:x86_64) => ("$bin_prefix/GDAL.x86_64-apple-darwin14.tar.gz", "e40180d7df9c45656e5cf6e33ce5621c0c8f610c4cd7d509da896b687268ac9f"),
Linux(:x86_64, :glibc) => ("$bin_prefix/GDAL.x86_64-linux-gnu.tar.gz", "e513b91d713c0bb3292adc8359a4e055d94e397a679438fb3cad71d4ef6bb80a"),
Windows(:x86_64) => ("$bin_prefix/GDAL.x86_64-w64-mingw32.tar.gz", "41b3b12ac2d83b2a37251dfe5ee9181dcf492d1b053fb247fbee8e23c659892a"),
)
# Install unsatisfied or updated dependencies:
unsatisfied = any(!satisfied(p; verbose=verbose) for p in products)
if haskey(download_info, platform_key())
url, tarball_hash = download_info[platform_key()]
if unsatisfied || !isinstalled(url, tarball_hash; prefix=prefix)
# Download and install binaries
install(url, tarball_hash; prefix=prefix, force=true, verbose=verbose)
end
elseif unsatisfied
# If we don't have a BinaryProvider-compatible .tar.gz to download, complain.
# Alternatively, you could attempt to install from a separate provider,
# build from source or something even more ambitious here.
error("Your platform $(triplet(platform_key())) is not supported by this package!")
end
# Write out a deps.jl file that will contain mappings for our products
write_deps_file(joinpath(@__DIR__, "deps.jl"), products)
|
[STATEMENT]
lemma approx_SReal_mult_cancel_zero:
fixes a x :: hypreal
assumes "a \<in> \<real>" "a \<noteq> 0" "a * x \<approx> 0" shows "x \<approx> 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. x \<approx> 0
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. x \<approx> 0
[PROOF STEP]
have "inverse a \<in> HFinite"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. inverse a \<in> HFinite
[PROOF STEP]
using Reals_inverse SReal_subset_HFinite assms(1)
[PROOF STATE]
proof (prove)
using this:
?a \<in> \<real> \<Longrightarrow> inverse ?a \<in> \<real>
\<real> \<subseteq> HFinite
a \<in> \<real>
goal (1 subgoal):
1. inverse a \<in> HFinite
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
inverse a \<in> HFinite
goal (1 subgoal):
1. x \<approx> 0
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
inverse a \<in> HFinite
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
inverse a \<in> HFinite
goal (1 subgoal):
1. x \<approx> 0
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
inverse a \<in> HFinite
a \<in> \<real>
a \<noteq> 0
a * x \<approx> 0
goal (1 subgoal):
1. x \<approx> 0
[PROOF STEP]
by (auto dest: approx_mult2 simp add: mult.assoc [symmetric])
[PROOF STATE]
proof (state)
this:
x \<approx> 0
goal:
No subgoals!
[PROOF STEP]
qed |
State Before: l : Type u_1
R : Type u_2
inst✝² : DecidableEq l
inst✝¹ : CommRing R
inst✝ : Fintype l
⊢ J l R ⬝ J l R = -1 State After: l : Type u_1
R : Type u_2
inst✝² : DecidableEq l
inst✝¹ : CommRing R
inst✝ : Fintype l
⊢ fromBlocks (0 ⬝ 0 + (-1) ⬝ 1) (0 ⬝ (-1) + (-1) ⬝ 0) (1 ⬝ 0 + 0 ⬝ 1) (1 ⬝ (-1) + 0 ⬝ 0) = -1 Tactic: rw [J, fromBlocks_multiply] State Before: l : Type u_1
R : Type u_2
inst✝² : DecidableEq l
inst✝¹ : CommRing R
inst✝ : Fintype l
⊢ fromBlocks (0 ⬝ 0 + (-1) ⬝ 1) (0 ⬝ (-1) + (-1) ⬝ 0) (1 ⬝ 0 + 0 ⬝ 1) (1 ⬝ (-1) + 0 ⬝ 0) = -1 State After: l : Type u_1
R : Type u_2
inst✝² : DecidableEq l
inst✝¹ : CommRing R
inst✝ : Fintype l
⊢ fromBlocks (-1) 0 0 (-1) = -1 Tactic: simp only [Matrix.zero_mul, Matrix.neg_mul, zero_add, neg_zero, Matrix.one_mul, add_zero] State Before: l : Type u_1
R : Type u_2
inst✝² : DecidableEq l
inst✝¹ : CommRing R
inst✝ : Fintype l
⊢ fromBlocks (-1) 0 0 (-1) = -1 State After: no goals Tactic: rw [← neg_zero, ← Matrix.fromBlocks_neg, ← fromBlocks_one] |
(* Title: HOL/HOLCF/IOA/meta_theory/Sequence.thy
Author: Olaf Müller
Sequences over flat domains with lifted elements.
*)
theory Sequence
imports Seq
begin
default_sort type
type_synonym 'a Seq = "'a lift seq"
consts
Consq ::"'a => 'a Seq -> 'a Seq"
Filter ::"('a => bool) => 'a Seq -> 'a Seq"
Map ::"('a => 'b) => 'a Seq -> 'b Seq"
Forall ::"('a => bool) => 'a Seq => bool"
Last ::"'a Seq -> 'a lift"
Dropwhile ::"('a => bool) => 'a Seq -> 'a Seq"
Takewhile ::"('a => bool) => 'a Seq -> 'a Seq"
Zip ::"'a Seq -> 'b Seq -> ('a * 'b) Seq"
Flat ::"('a Seq) seq -> 'a Seq"
Filter2 ::"('a => bool) => 'a Seq -> 'a Seq"
abbreviation
Consq_syn ("(_/>>_)" [66,65] 65) where
"a>>s == Consq a$s"
notation (xsymbols)
Consq_syn ("(_\<leadsto>_)" [66,65] 65)
(* list Enumeration *)
syntax
"_totlist" :: "args => 'a Seq" ("[(_)!]")
"_partlist" :: "args => 'a Seq" ("[(_)?]")
translations
"[x, xs!]" == "x>>[xs!]"
"[x!]" == "x>>nil"
"[x, xs?]" == "x>>[xs?]"
"[x?]" == "x>>CONST bottom"
defs
Consq_def: "Consq a == LAM s. Def a ## s"
Filter_def: "Filter P == sfilter$(flift2 P)"
Map_def: "Map f == smap$(flift2 f)"
Forall_def: "Forall P == sforall (flift2 P)"
Last_def: "Last == slast"
Dropwhile_def: "Dropwhile P == sdropwhile$(flift2 P)"
Takewhile_def: "Takewhile P == stakewhile$(flift2 P)"
Flat_def: "Flat == sflat"
Zip_def:
"Zip == (fix$(LAM h t1 t2. case t1 of
nil => nil
| x##xs => (case t2 of
nil => UU
| y##ys => (case x of
UU => UU
| Def a => (case y of
UU => UU
| Def b => Def (a,b)##(h$xs$ys))))))"
Filter2_def: "Filter2 P == (fix$(LAM h t. case t of
nil => nil
| x##xs => (case x of UU => UU | Def y => (if P y
then x##(h$xs)
else h$xs))))"
declare andalso_and [simp]
declare andalso_or [simp]
subsection "recursive equations of operators"
subsubsection "Map"
lemma Map_UU: "Map f$UU =UU"
by (simp add: Map_def)
lemma Map_nil: "Map f$nil =nil"
by (simp add: Map_def)
lemma Map_cons: "Map f$(x>>xs)=(f x) >> Map f$xs"
by (simp add: Map_def Consq_def flift2_def)
subsubsection {* Filter *}
lemma Filter_UU: "Filter P$UU =UU"
by (simp add: Filter_def)
lemma Filter_nil: "Filter P$nil =nil"
by (simp add: Filter_def)
lemma Filter_cons:
"Filter P$(x>>xs)= (if P x then x>>(Filter P$xs) else Filter P$xs)"
by (simp add: Filter_def Consq_def flift2_def If_and_if)
subsubsection {* Forall *}
lemma Forall_UU: "Forall P UU"
by (simp add: Forall_def sforall_def)
lemma Forall_nil: "Forall P nil"
by (simp add: Forall_def sforall_def)
lemma Forall_cons: "Forall P (x>>xs)= (P x & Forall P xs)"
by (simp add: Forall_def sforall_def Consq_def flift2_def)
subsubsection {* Conc *}
lemma Conc_cons: "(x>>xs) @@ y = x>>(xs @@y)"
by (simp add: Consq_def)
subsubsection {* Takewhile *}
lemma Takewhile_UU: "Takewhile P$UU =UU"
by (simp add: Takewhile_def)
lemma Takewhile_nil: "Takewhile P$nil =nil"
by (simp add: Takewhile_def)
lemma Takewhile_cons:
"Takewhile P$(x>>xs)= (if P x then x>>(Takewhile P$xs) else nil)"
by (simp add: Takewhile_def Consq_def flift2_def If_and_if)
subsubsection {* DropWhile *}
lemma Dropwhile_UU: "Dropwhile P$UU =UU"
by (simp add: Dropwhile_def)
lemma Dropwhile_nil: "Dropwhile P$nil =nil"
by (simp add: Dropwhile_def)
lemma Dropwhile_cons:
"Dropwhile P$(x>>xs)= (if P x then Dropwhile P$xs else x>>xs)"
by (simp add: Dropwhile_def Consq_def flift2_def If_and_if)
subsubsection {* Last *}
lemma Last_UU: "Last$UU =UU"
by (simp add: Last_def)
lemma Last_nil: "Last$nil =UU"
by (simp add: Last_def)
lemma Last_cons: "Last$(x>>xs)= (if xs=nil then Def x else Last$xs)"
apply (simp add: Last_def Consq_def)
apply (cases xs)
apply simp_all
done
subsubsection {* Flat *}
lemma Flat_UU: "Flat$UU =UU"
by (simp add: Flat_def)
lemma Flat_nil: "Flat$nil =nil"
by (simp add: Flat_def)
lemma Flat_cons: "Flat$(x##xs)= x @@ (Flat$xs)"
by (simp add: Flat_def Consq_def)
subsubsection {* Zip *}
lemma Zip_unfold:
"Zip = (LAM t1 t2. case t1 of
nil => nil
| x##xs => (case t2 of
nil => UU
| y##ys => (case x of
UU => UU
| Def a => (case y of
UU => UU
| Def b => Def (a,b)##(Zip$xs$ys)))))"
apply (rule trans)
apply (rule fix_eq2)
apply (rule Zip_def)
apply (rule beta_cfun)
apply simp
done
lemma Zip_UU1: "Zip$UU$y =UU"
apply (subst Zip_unfold)
apply simp
done
lemma Zip_UU2: "x~=nil ==> Zip$x$UU =UU"
apply (subst Zip_unfold)
apply simp
apply (cases x)
apply simp_all
done
lemma Zip_nil: "Zip$nil$y =nil"
apply (subst Zip_unfold)
apply simp
done
lemma Zip_cons_nil: "Zip$(x>>xs)$nil= UU"
apply (subst Zip_unfold)
apply (simp add: Consq_def)
done
lemma Zip_cons: "Zip$(x>>xs)$(y>>ys)= (x,y) >> Zip$xs$ys"
apply (rule trans)
apply (subst Zip_unfold)
apply simp
apply (simp add: Consq_def)
done
lemmas [simp del] =
sfilter_UU sfilter_nil sfilter_cons
smap_UU smap_nil smap_cons
sforall2_UU sforall2_nil sforall2_cons
slast_UU slast_nil slast_cons
stakewhile_UU stakewhile_nil stakewhile_cons
sdropwhile_UU sdropwhile_nil sdropwhile_cons
sflat_UU sflat_nil sflat_cons
szip_UU1 szip_UU2 szip_nil szip_cons_nil szip_cons
lemmas [simp] =
Filter_UU Filter_nil Filter_cons
Map_UU Map_nil Map_cons
Forall_UU Forall_nil Forall_cons
Last_UU Last_nil Last_cons
Conc_cons
Takewhile_UU Takewhile_nil Takewhile_cons
Dropwhile_UU Dropwhile_nil Dropwhile_cons
Zip_UU1 Zip_UU2 Zip_nil Zip_cons_nil Zip_cons
section "Cons"
lemma Consq_def2: "a>>s = (Def a)##s"
apply (simp add: Consq_def)
done
lemma Seq_exhaust: "x = UU | x = nil | (? a s. x = a >> s)"
apply (simp add: Consq_def2)
apply (cut_tac seq.nchotomy)
apply (fast dest: not_Undef_is_Def [THEN iffD1])
done
lemma Seq_cases:
"!!P. [| x = UU ==> P; x = nil ==> P; !!a s. x = a >> s ==> P |] ==> P"
apply (cut_tac x="x" in Seq_exhaust)
apply (erule disjE)
apply simp
apply (erule disjE)
apply simp
apply (erule exE)+
apply simp
done
(*
fun Seq_case_tac s i = rule_tac x",s)] Seq_cases i
THEN hyp_subst_tac i THEN hyp_subst_tac (i+1) THEN hyp_subst_tac (i+2);
*)
(* on a>>s only simp_tac, as full_simp_tac is uncomplete and often causes errors *)
(*
fun Seq_case_simp_tac s i = Seq_case_tac s i THEN Asm_simp_tac (i+2)
THEN Asm_full_simp_tac (i+1)
THEN Asm_full_simp_tac i;
*)
lemma Cons_not_UU: "a>>s ~= UU"
apply (subst Consq_def2)
apply simp
done
lemma Cons_not_less_UU: "~(a>>x) << UU"
apply (rule notI)
apply (drule below_antisym)
apply simp
apply (simp add: Cons_not_UU)
done
lemma Cons_not_less_nil: "~a>>s << nil"
apply (simp add: Consq_def2)
done
lemma Cons_not_nil: "a>>s ~= nil"
apply (simp add: Consq_def2)
done
lemma Cons_not_nil2: "nil ~= a>>s"
apply (simp add: Consq_def2)
done
lemma Cons_inject_eq: "(a>>s = b>>t) = (a = b & s = t)"
apply (simp only: Consq_def2)
apply (simp add: scons_inject_eq)
done
lemma Cons_inject_less_eq: "(a>>s<<b>>t) = (a = b & s<<t)"
apply (simp add: Consq_def2)
done
lemma seq_take_Cons: "seq_take (Suc n)$(a>>x) = a>> (seq_take n$x)"
apply (simp add: Consq_def)
done
lemmas [simp] =
Cons_not_nil2 Cons_inject_eq Cons_inject_less_eq seq_take_Cons
Cons_not_UU Cons_not_less_UU Cons_not_less_nil Cons_not_nil
subsection "induction"
lemma Seq_induct:
"!! P. [| adm P; P UU; P nil; !! a s. P s ==> P (a>>s)|] ==> P x"
apply (erule (2) seq.induct)
apply defined
apply (simp add: Consq_def)
done
lemma Seq_FinitePartial_ind:
"!! P.[|P UU;P nil; !! a s. P s ==> P(a>>s) |]
==> seq_finite x --> P x"
apply (erule (1) seq_finite_ind)
apply defined
apply (simp add: Consq_def)
done
lemma Seq_Finite_ind:
"!! P.[| Finite x; P nil; !! a s. [| Finite s; P s|] ==> P (a>>s) |] ==> P x"
apply (erule (1) Finite.induct)
apply defined
apply (simp add: Consq_def)
done
(* rws are definitions to be unfolded for admissibility check *)
(*
fun Seq_induct_tac s rws i = rule_tac x",s)] Seq_induct i
THEN (REPEAT_DETERM (CHANGED (Asm_simp_tac (i+1))))
THEN simp add: rws) i;
fun Seq_Finite_induct_tac i = erule Seq_Finite_ind i
THEN (REPEAT_DETERM (CHANGED (Asm_simp_tac i)));
fun pair_tac s = rule_tac p",s)] PairE
THEN' hyp_subst_tac THEN' Simp_tac;
*)
(* induction on a sequence of pairs with pairsplitting and simplification *)
(*
fun pair_induct_tac s rws i =
rule_tac x",s)] Seq_induct i
THEN pair_tac "a" (i+3)
THEN (REPEAT_DETERM (CHANGED (Simp_tac (i+1))))
THEN simp add: rws) i;
*)
(* ------------------------------------------------------------------------------------ *)
subsection "HD,TL"
lemma HD_Cons [simp]: "HD$(x>>y) = Def x"
apply (simp add: Consq_def)
done
lemma TL_Cons [simp]: "TL$(x>>y) = y"
apply (simp add: Consq_def)
done
(* ------------------------------------------------------------------------------------ *)
subsection "Finite, Partial, Infinite"
lemma Finite_Cons [simp]: "Finite (a>>xs) = Finite xs"
apply (simp add: Consq_def2 Finite_cons)
done
lemma FiniteConc_1: "Finite (x::'a Seq) ==> Finite y --> Finite (x@@y)"
apply (erule Seq_Finite_ind, simp_all)
done
lemma FiniteConc_2:
"Finite (z::'a Seq) ==> !x y. z= x@@y --> (Finite x & Finite y)"
apply (erule Seq_Finite_ind)
(* nil*)
apply (intro strip)
apply (rule_tac x="x" in Seq_cases, simp_all)
(* cons *)
apply (intro strip)
apply (rule_tac x="x" in Seq_cases, simp_all)
apply (rule_tac x="y" in Seq_cases, simp_all)
done
lemma FiniteConc [simp]: "Finite(x@@y) = (Finite (x::'a Seq) & Finite y)"
apply (rule iffI)
apply (erule FiniteConc_2 [rule_format])
apply (rule refl)
apply (rule FiniteConc_1 [rule_format])
apply auto
done
lemma FiniteMap1: "Finite s ==> Finite (Map f$s)"
apply (erule Seq_Finite_ind, simp_all)
done
lemma FiniteMap2: "Finite s ==> ! t. (s = Map f$t) --> Finite t"
apply (erule Seq_Finite_ind)
apply (intro strip)
apply (rule_tac x="t" in Seq_cases, simp_all)
(* main case *)
apply auto
apply (rule_tac x="t" in Seq_cases, simp_all)
done
lemma Map2Finite: "Finite (Map f$s) = Finite s"
apply auto
apply (erule FiniteMap2 [rule_format])
apply (rule refl)
apply (erule FiniteMap1)
done
lemma FiniteFilter: "Finite s ==> Finite (Filter P$s)"
apply (erule Seq_Finite_ind, simp_all)
done
(* ----------------------------------------------------------------------------------- *)
subsection "Conc"
lemma Conc_cong: "!! x::'a Seq. Finite x ==> ((x @@ y) = (x @@ z)) = (y = z)"
apply (erule Seq_Finite_ind, simp_all)
done
lemma Conc_assoc: "(x @@ y) @@ z = (x::'a Seq) @@ y @@ z"
apply (rule_tac x="x" in Seq_induct, simp_all)
done
lemma nilConc [simp]: "s@@ nil = s"
apply (induct s)
apply simp
apply simp
apply simp
apply simp
done
(* should be same as nil_is_Conc2 when all nils are turned to right side !! *)
lemma nil_is_Conc: "(nil = x @@ y) = ((x::'a Seq)= nil & y = nil)"
apply (rule_tac x="x" in Seq_cases)
apply auto
done
lemma nil_is_Conc2: "(x @@ y = nil) = ((x::'a Seq)= nil & y = nil)"
apply (rule_tac x="x" in Seq_cases)
apply auto
done
(* ------------------------------------------------------------------------------------ *)
subsection "Last"
lemma Finite_Last1: "Finite s ==> s~=nil --> Last$s~=UU"
apply (erule Seq_Finite_ind, simp_all)
done
lemma Finite_Last2: "Finite s ==> Last$s=UU --> s=nil"
apply (erule Seq_Finite_ind, simp_all)
apply fast
done
(* ------------------------------------------------------------------------------------ *)
subsection "Filter, Conc"
lemma FilterPQ: "Filter P$(Filter Q$s) = Filter (%x. P x & Q x)$s"
apply (rule_tac x="s" in Seq_induct, simp_all)
done
lemma FilterConc: "Filter P$(x @@ y) = (Filter P$x @@ Filter P$y)"
apply (simp add: Filter_def sfiltersconc)
done
(* ------------------------------------------------------------------------------------ *)
subsection "Map"
lemma MapMap: "Map f$(Map g$s) = Map (f o g)$s"
apply (rule_tac x="s" in Seq_induct, simp_all)
done
lemma MapConc: "Map f$(x@@y) = (Map f$x) @@ (Map f$y)"
apply (rule_tac x="x" in Seq_induct, simp_all)
done
lemma MapFilter: "Filter P$(Map f$x) = Map f$(Filter (P o f)$x)"
apply (rule_tac x="x" in Seq_induct, simp_all)
done
lemma nilMap: "nil = (Map f$s) --> s= nil"
apply (rule_tac x="s" in Seq_cases, simp_all)
done
lemma ForallMap: "Forall P (Map f$s) = Forall (P o f) s"
apply (rule_tac x="s" in Seq_induct)
apply (simp add: Forall_def sforall_def)
apply simp_all
done
(* ------------------------------------------------------------------------------------ *)
subsection "Forall"
lemma ForallPForallQ1: "Forall P ys & (! x. P x --> Q x)
--> Forall Q ys"
apply (rule_tac x="ys" in Seq_induct)
apply (simp add: Forall_def sforall_def)
apply simp_all
done
lemmas ForallPForallQ =
ForallPForallQ1 [THEN mp, OF conjI, OF _ allI, OF _ impI]
lemma Forall_Conc_impl: "(Forall P x & Forall P y) --> Forall P (x @@ y)"
apply (rule_tac x="x" in Seq_induct)
apply (simp add: Forall_def sforall_def)
apply simp_all
done
lemma Forall_Conc [simp]:
"Finite x ==> Forall P (x @@ y) = (Forall P x & Forall P y)"
apply (erule Seq_Finite_ind, simp_all)
done
lemma ForallTL1: "Forall P s --> Forall P (TL$s)"
apply (rule_tac x="s" in Seq_induct)
apply (simp add: Forall_def sforall_def)
apply simp_all
done
lemmas ForallTL = ForallTL1 [THEN mp]
lemma ForallDropwhile1: "Forall P s --> Forall P (Dropwhile Q$s)"
apply (rule_tac x="s" in Seq_induct)
apply (simp add: Forall_def sforall_def)
apply simp_all
done
lemmas ForallDropwhile = ForallDropwhile1 [THEN mp]
(* only admissible in t, not if done in s *)
lemma Forall_prefix: "! s. Forall P s --> t<<s --> Forall P t"
apply (rule_tac x="t" in Seq_induct)
apply (simp add: Forall_def sforall_def)
apply simp_all
apply (intro strip)
apply (rule_tac x="sa" in Seq_cases)
apply simp
apply auto
done
lemmas Forall_prefixclosed = Forall_prefix [rule_format]
lemma Forall_postfixclosed:
"[| Finite h; Forall P s; s= h @@ t |] ==> Forall P t"
apply auto
done
lemma ForallPFilterQR1:
"((! x. P x --> (Q x = R x)) & Forall P tr) --> Filter Q$tr = Filter R$tr"
apply (rule_tac x="tr" in Seq_induct)
apply (simp add: Forall_def sforall_def)
apply simp_all
done
lemmas ForallPFilterQR = ForallPFilterQR1 [THEN mp, OF conjI, OF allI]
(* ------------------------------------------------------------------------------------- *)
subsection "Forall, Filter"
lemma ForallPFilterP: "Forall P (Filter P$x)"
apply (simp add: Filter_def Forall_def forallPsfilterP)
done
(* holds also in other direction, then equal to forallPfilterP *)
lemma ForallPFilterPid1: "Forall P x --> Filter P$x = x"
apply (rule_tac x="x" in Seq_induct)
apply (simp add: Forall_def sforall_def Filter_def)
apply simp_all
done
lemmas ForallPFilterPid = ForallPFilterPid1 [THEN mp]
(* holds also in other direction *)
lemma ForallnPFilterPnil1: "!! ys . Finite ys ==>
Forall (%x. ~P x) ys --> Filter P$ys = nil "
apply (erule Seq_Finite_ind, simp_all)
done
lemmas ForallnPFilterPnil = ForallnPFilterPnil1 [THEN mp]
(* holds also in other direction *)
lemma ForallnPFilterPUU1: "~Finite ys & Forall (%x. ~P x) ys
--> Filter P$ys = UU "
apply (rule_tac x="ys" in Seq_induct)
apply (simp add: Forall_def sforall_def)
apply simp_all
done
lemmas ForallnPFilterPUU = ForallnPFilterPUU1 [THEN mp, OF conjI]
(* inverse of ForallnPFilterPnil *)
lemma FilternPnilForallP [rule_format]: "Filter P$ys = nil -->
(Forall (%x. ~P x) ys & Finite ys)"
apply (rule_tac x="ys" in Seq_induct)
(* adm *)
apply (simp add: Forall_def sforall_def)
(* base cases *)
apply simp
apply simp
(* main case *)
apply simp
done
(* inverse of ForallnPFilterPUU *)
lemma FilternPUUForallP:
assumes "Filter P$ys = UU"
shows "Forall (%x. ~P x) ys & ~Finite ys"
proof
show "Forall (%x. ~P x) ys"
proof (rule classical)
assume "\<not> ?thesis"
then have "Filter P$ys ~= UU"
apply (rule rev_mp)
apply (induct ys rule: Seq_induct)
apply (simp add: Forall_def sforall_def)
apply simp_all
done
with assms show ?thesis by contradiction
qed
show "~ Finite ys"
proof
assume "Finite ys"
then have "Filter P$ys ~= UU"
by (rule Seq_Finite_ind) simp_all
with assms show False by contradiction
qed
qed
lemma ForallQFilterPnil:
"!! Q P.[| Forall Q ys; Finite ys; !!x. Q x ==> ~P x|]
==> Filter P$ys = nil"
apply (erule ForallnPFilterPnil)
apply (erule ForallPForallQ)
apply auto
done
lemma ForallQFilterPUU:
"!! Q P. [| ~Finite ys; Forall Q ys; !!x. Q x ==> ~P x|]
==> Filter P$ys = UU "
apply (erule ForallnPFilterPUU)
apply (erule ForallPForallQ)
apply auto
done
(* ------------------------------------------------------------------------------------- *)
subsection "Takewhile, Forall, Filter"
lemma ForallPTakewhileP [simp]: "Forall P (Takewhile P$x)"
apply (simp add: Forall_def Takewhile_def sforallPstakewhileP)
done
lemma ForallPTakewhileQ [simp]:
"!! P. [| !!x. Q x==> P x |] ==> Forall P (Takewhile Q$x)"
apply (rule ForallPForallQ)
apply (rule ForallPTakewhileP)
apply auto
done
lemma FilterPTakewhileQnil [simp]:
"!! Q P.[| Finite (Takewhile Q$ys); !!x. Q x ==> ~P x |]
==> Filter P$(Takewhile Q$ys) = nil"
apply (erule ForallnPFilterPnil)
apply (rule ForallPForallQ)
apply (rule ForallPTakewhileP)
apply auto
done
lemma FilterPTakewhileQid [simp]:
"!! Q P. [| !!x. Q x ==> P x |] ==>
Filter P$(Takewhile Q$ys) = (Takewhile Q$ys)"
apply (rule ForallPFilterPid)
apply (rule ForallPForallQ)
apply (rule ForallPTakewhileP)
apply auto
done
lemma Takewhile_idempotent: "Takewhile P$(Takewhile P$s) = Takewhile P$s"
apply (rule_tac x="s" in Seq_induct)
apply (simp add: Forall_def sforall_def)
apply simp_all
done
lemma ForallPTakewhileQnP [simp]:
"Forall P s --> Takewhile (%x. Q x | (~P x))$s = Takewhile Q$s"
apply (rule_tac x="s" in Seq_induct)
apply (simp add: Forall_def sforall_def)
apply simp_all
done
lemma ForallPDropwhileQnP [simp]:
"Forall P s --> Dropwhile (%x. Q x | (~P x))$s = Dropwhile Q$s"
apply (rule_tac x="s" in Seq_induct)
apply (simp add: Forall_def sforall_def)
apply simp_all
done
lemma TakewhileConc1:
"Forall P s --> Takewhile P$(s @@ t) = s @@ (Takewhile P$t)"
apply (rule_tac x="s" in Seq_induct)
apply (simp add: Forall_def sforall_def)
apply simp_all
done
lemmas TakewhileConc = TakewhileConc1 [THEN mp]
lemma DropwhileConc1:
"Finite s ==> Forall P s --> Dropwhile P$(s @@ t) = Dropwhile P$t"
apply (erule Seq_Finite_ind, simp_all)
done
lemmas DropwhileConc = DropwhileConc1 [THEN mp]
(* ----------------------------------------------------------------------------------- *)
subsection "coinductive characterizations of Filter"
lemma divide_Seq_lemma:
"HD$(Filter P$y) = Def x
--> y = ((Takewhile (%x. ~P x)$y) @@ (x >> TL$(Dropwhile (%a.~P a)$y)))
& Finite (Takewhile (%x. ~ P x)$y) & P x"
(* FIX: pay attention: is only admissible with chain-finite package to be added to
adm test and Finite f x admissibility *)
apply (rule_tac x="y" in Seq_induct)
apply (simp add: adm_subst [OF _ adm_Finite])
apply simp
apply simp
apply (case_tac "P a")
apply simp
apply blast
(* ~ P a *)
apply simp
done
lemma divide_Seq: "(x>>xs) << Filter P$y
==> y = ((Takewhile (%a. ~ P a)$y) @@ (x >> TL$(Dropwhile (%a.~P a)$y)))
& Finite (Takewhile (%a. ~ P a)$y) & P x"
apply (rule divide_Seq_lemma [THEN mp])
apply (drule_tac f="HD" and x="x>>xs" in monofun_cfun_arg)
apply simp
done
lemma nForall_HDFilter:
"~Forall P y --> (? x. HD$(Filter (%a. ~P a)$y) = Def x)"
unfolding not_Undef_is_Def [symmetric]
apply (induct y rule: Seq_induct)
apply (simp add: Forall_def sforall_def)
apply simp_all
done
lemma divide_Seq2: "~Forall P y
==> ? x. y= (Takewhile P$y @@ (x >> TL$(Dropwhile P$y))) &
Finite (Takewhile P$y) & (~ P x)"
apply (drule nForall_HDFilter [THEN mp])
apply safe
apply (rule_tac x="x" in exI)
apply (cut_tac P1="%x. ~ P x" in divide_Seq_lemma [THEN mp])
apply auto
done
lemma divide_Seq3: "~Forall P y
==> ? x bs rs. y= (bs @@ (x>>rs)) & Finite bs & Forall P bs & (~ P x)"
apply (drule divide_Seq2)
(*Auto_tac no longer proves it*)
apply fastforce
done
lemmas [simp] = FilterPQ FilterConc Conc_cong
(* ------------------------------------------------------------------------------------- *)
subsection "take_lemma"
lemma seq_take_lemma: "(!n. seq_take n$x = seq_take n$x') = (x = x')"
apply (rule iffI)
apply (rule seq.take_lemma)
apply auto
done
lemma take_reduction1:
" ! n. ((! k. k < n --> seq_take k$y1 = seq_take k$y2)
--> seq_take n$(x @@ (t>>y1)) = seq_take n$(x @@ (t>>y2)))"
apply (rule_tac x="x" in Seq_induct)
apply simp_all
apply (intro strip)
apply (case_tac "n")
apply auto
apply (case_tac "n")
apply auto
done
lemma take_reduction:
"!! n.[| x=y; s=t; !! k. k<n ==> seq_take k$y1 = seq_take k$y2|]
==> seq_take n$(x @@ (s>>y1)) = seq_take n$(y @@ (t>>y2))"
apply (auto intro!: take_reduction1 [rule_format])
done
(* ------------------------------------------------------------------
take-lemma and take_reduction for << instead of =
------------------------------------------------------------------ *)
lemma take_reduction_less1:
" ! n. ((! k. k < n --> seq_take k$y1 << seq_take k$y2)
--> seq_take n$(x @@ (t>>y1)) << seq_take n$(x @@ (t>>y2)))"
apply (rule_tac x="x" in Seq_induct)
apply simp_all
apply (intro strip)
apply (case_tac "n")
apply auto
apply (case_tac "n")
apply auto
done
lemma take_reduction_less:
"!! n.[| x=y; s=t;!! k. k<n ==> seq_take k$y1 << seq_take k$y2|]
==> seq_take n$(x @@ (s>>y1)) << seq_take n$(y @@ (t>>y2))"
apply (auto intro!: take_reduction_less1 [rule_format])
done
lemma take_lemma_less1:
assumes "!! n. seq_take n$s1 << seq_take n$s2"
shows "s1<<s2"
apply (rule_tac t="s1" in seq.reach [THEN subst])
apply (rule_tac t="s2" in seq.reach [THEN subst])
apply (rule lub_mono)
apply (rule seq.chain_take [THEN ch2ch_Rep_cfunL])
apply (rule seq.chain_take [THEN ch2ch_Rep_cfunL])
apply (rule assms)
done
lemma take_lemma_less: "(!n. seq_take n$x << seq_take n$x') = (x << x')"
apply (rule iffI)
apply (rule take_lemma_less1)
apply auto
apply (erule monofun_cfun_arg)
done
(* ------------------------------------------------------------------
take-lemma proof principles
------------------------------------------------------------------ *)
lemma take_lemma_principle1:
"!! Q. [|!! s. [| Forall Q s; A s |] ==> (f s) = (g s) ;
!! s1 s2 y. [| Forall Q s1; Finite s1; ~ Q y; A (s1 @@ y>>s2)|]
==> (f (s1 @@ y>>s2)) = (g (s1 @@ y>>s2)) |]
==> A x --> (f x)=(g x)"
apply (case_tac "Forall Q x")
apply (auto dest!: divide_Seq3)
done
lemma take_lemma_principle2:
"!! Q. [|!! s. [| Forall Q s; A s |] ==> (f s) = (g s) ;
!! s1 s2 y. [| Forall Q s1; Finite s1; ~ Q y; A (s1 @@ y>>s2)|]
==> ! n. seq_take n$(f (s1 @@ y>>s2))
= seq_take n$(g (s1 @@ y>>s2)) |]
==> A x --> (f x)=(g x)"
apply (case_tac "Forall Q x")
apply (auto dest!: divide_Seq3)
apply (rule seq.take_lemma)
apply auto
done
(* Note: in the following proofs the ordering of proof steps is very
important, as otherwise either (Forall Q s1) would be in the IH as
assumption (then rule useless) or it is not possible to strengthen
the IH apply doing a forall closure of the sequence t (then rule also useless).
This is also the reason why the induction rule (nat_less_induct or nat_induct) has to
to be imbuilt into the rule, as induction has to be done early and the take lemma
has to be used in the trivial direction afterwards for the (Forall Q x) case. *)
lemma take_lemma_induct:
"!! Q. [|!! s. [| Forall Q s; A s |] ==> (f s) = (g s) ;
!! s1 s2 y n. [| ! t. A t --> seq_take n$(f t) = seq_take n$(g t);
Forall Q s1; Finite s1; ~ Q y; A (s1 @@ y>>s2) |]
==> seq_take (Suc n)$(f (s1 @@ y>>s2))
= seq_take (Suc n)$(g (s1 @@ y>>s2)) |]
==> A x --> (f x)=(g x)"
apply (rule impI)
apply (rule seq.take_lemma)
apply (rule mp)
prefer 2 apply assumption
apply (rule_tac x="x" in spec)
apply (rule nat.induct)
apply simp
apply (rule allI)
apply (case_tac "Forall Q xa")
apply (force intro!: seq_take_lemma [THEN iffD2, THEN spec])
apply (auto dest!: divide_Seq3)
done
lemma take_lemma_less_induct:
"!! Q. [|!! s. [| Forall Q s; A s |] ==> (f s) = (g s) ;
!! s1 s2 y n. [| ! t m. m < n --> A t --> seq_take m$(f t) = seq_take m$(g t);
Forall Q s1; Finite s1; ~ Q y; A (s1 @@ y>>s2) |]
==> seq_take n$(f (s1 @@ y>>s2))
= seq_take n$(g (s1 @@ y>>s2)) |]
==> A x --> (f x)=(g x)"
apply (rule impI)
apply (rule seq.take_lemma)
apply (rule mp)
prefer 2 apply assumption
apply (rule_tac x="x" in spec)
apply (rule nat_less_induct)
apply (rule allI)
apply (case_tac "Forall Q xa")
apply (force intro!: seq_take_lemma [THEN iffD2, THEN spec])
apply (auto dest!: divide_Seq3)
done
lemma take_lemma_in_eq_out:
"!! Q. [| A UU ==> (f UU) = (g UU) ;
A nil ==> (f nil) = (g nil) ;
!! s y n. [| ! t. A t --> seq_take n$(f t) = seq_take n$(g t);
A (y>>s) |]
==> seq_take (Suc n)$(f (y>>s))
= seq_take (Suc n)$(g (y>>s)) |]
==> A x --> (f x)=(g x)"
apply (rule impI)
apply (rule seq.take_lemma)
apply (rule mp)
prefer 2 apply assumption
apply (rule_tac x="x" in spec)
apply (rule nat.induct)
apply simp
apply (rule allI)
apply (rule_tac x="xa" in Seq_cases)
apply simp_all
done
(* ------------------------------------------------------------------------------------ *)
subsection "alternative take_lemma proofs"
(* --------------------------------------------------------------- *)
(* Alternative Proof of FilterPQ *)
(* --------------------------------------------------------------- *)
declare FilterPQ [simp del]
(* In general: How to do this case without the same adm problems
as for the entire proof ? *)
lemma Filter_lemma1: "Forall (%x.~(P x & Q x)) s
--> Filter P$(Filter Q$s) =
Filter (%x. P x & Q x)$s"
apply (rule_tac x="s" in Seq_induct)
apply (simp add: Forall_def sforall_def)
apply simp_all
done
lemma Filter_lemma2: "Finite s ==>
(Forall (%x. (~P x) | (~ Q x)) s
--> Filter P$(Filter Q$s) = nil)"
apply (erule Seq_Finite_ind, simp_all)
done
lemma Filter_lemma3: "Finite s ==>
Forall (%x. (~P x) | (~ Q x)) s
--> Filter (%x. P x & Q x)$s = nil"
apply (erule Seq_Finite_ind, simp_all)
done
lemma FilterPQ_takelemma: "Filter P$(Filter Q$s) = Filter (%x. P x & Q x)$s"
apply (rule_tac A1="%x. True" and
Q1="%x.~(P x & Q x)" and x1="s" in
take_lemma_induct [THEN mp])
(* better support for A = %x. True *)
apply (simp add: Filter_lemma1)
apply (simp add: Filter_lemma2 Filter_lemma3)
apply simp
done
declare FilterPQ [simp]
(* --------------------------------------------------------------- *)
(* Alternative Proof of MapConc *)
(* --------------------------------------------------------------- *)
lemma MapConc_takelemma: "Map f$(x@@y) = (Map f$x) @@ (Map f$y)"
apply (rule_tac A1="%x. True" and x1="x" in
take_lemma_in_eq_out [THEN mp])
apply auto
done
ML {*
fun Seq_case_tac ctxt s i =
res_inst_tac ctxt [(("x", 0), s)] @{thm Seq_cases} i
THEN hyp_subst_tac ctxt i THEN hyp_subst_tac ctxt (i+1) THEN hyp_subst_tac ctxt (i+2);
(* on a>>s only simp_tac, as full_simp_tac is uncomplete and often causes errors *)
fun Seq_case_simp_tac ctxt s i =
Seq_case_tac ctxt s i
THEN asm_simp_tac ctxt (i+2)
THEN asm_full_simp_tac ctxt (i+1)
THEN asm_full_simp_tac ctxt i;
(* rws are definitions to be unfolded for admissibility check *)
fun Seq_induct_tac ctxt s rws i =
res_inst_tac ctxt [(("x", 0), s)] @{thm Seq_induct} i
THEN (REPEAT_DETERM (CHANGED (asm_simp_tac ctxt (i+1))))
THEN simp_tac (ctxt addsimps rws) i;
fun Seq_Finite_induct_tac ctxt i =
etac @{thm Seq_Finite_ind} i
THEN (REPEAT_DETERM (CHANGED (asm_simp_tac ctxt i)));
fun pair_tac ctxt s =
res_inst_tac ctxt [(("p", 0), s)] @{thm PairE}
THEN' hyp_subst_tac ctxt THEN' asm_full_simp_tac ctxt;
(* induction on a sequence of pairs with pairsplitting and simplification *)
fun pair_induct_tac ctxt s rws i =
res_inst_tac ctxt [(("x", 0), s)] @{thm Seq_induct} i
THEN pair_tac ctxt "a" (i+3)
THEN (REPEAT_DETERM (CHANGED (simp_tac ctxt (i+1))))
THEN simp_tac (ctxt addsimps rws) i;
*}
end
|
function [class, Simil] = classifier(data, ideals, y)
% INPUT:
%
% data = datamatrix
% ideals = idealvectors
% y(1) = p-value in similarity measure
% y(2) = alpha value for OWA weights
% y(3) = used owa aggregator
%
%
% OUTPUT:
%
% class = column vector of the classes in which the samples are classified
% Simil = similarity values for each class
[nc, v_dim] = size(ideals);
d_dim = size(data,1);
Simil = zeros(d_dim, nc);
if nargin==2
y = [1, 1, 1];
end
for j = 1 : nc
Ideal = repmat(ideals(j,:),d_dim,1);
if y(3) == 1 %Using OWA with Linguistic quantifier 1
w=owaw1(v_dim,y(2));
tmpmatrix=(1-abs(data.^y(1)-Ideal.^y(1))).^(1/y(1));
Simil(:,j)=owamatrix(tmpmatrix,w);
elseif y(3) == 2 %Using OWA with Linguistic quantifier 2
w=owaw2(v_dim,y(2));
tmpmatrix=(1-abs(data.^y(1)-Ideal.^y(1))).^(1/y(1));
Simil(:,j)=owamatrix(tmpmatrix,w);
elseif y(3) == 3 %Using OWA with Linguistic quantifier 3
w=owaw3(v_dim,y(2));
tmpmatrix=(1-abs(data.^y(1)-Ideal.^y(1))).^(1/y(1));
Simil(:,j)=owamatrix(tmpmatrix,w);
elseif y(3) == 4 %Using OWA with Linguistic quantifier 4
w=owaw4(v_dim,y(2));
tmpmatrix=(1-abs(data.^y(1)-Ideal.^y(1))).^(1/y(1));
Simil(:,j)=owamatrix(tmpmatrix,w);
elseif y(3) == 5 %O'Hagan's method
tmpmatrix=(1-abs(data.^y(1)-Ideal.^y(1))).^(1/y(1));
weights=Ohaganw(v_dim,y(2));
index= 1;
w=weights(index,:);
Simil(:,j)=owamatrix(tmpmatrix,w);
end
end
[simil_val, class] = max(Simil');
class=class'; |
#@ Not autoload
with(LinearAlgebra):
p := 2;
chromatic_n_max := 4; # NB degree(v[4]) = 30, degree(v[5]) = 62
chromatic_s_max := 20;
unprotect('v','m','t');
unassign('v','m','t');
v[0] := p;
m[0] := 1;
t[0] := 1;
protect('v','m','t');
# On BP_* we use a lexicographic ordering with v[1] >> v[2] >> v[3] >> ... >> 1.
# This seems to be the best order except that we really want to treat v[0]
# as a variable with v[0] >> v[1], so any monomial multiplied by p comes
# after all the bare monomials. Then the terms p^t * monomial in any
# given degree have order type omega, and the terms after any given term
# span an invariant ideal.
BP_vars := plex(seq(v[i],i=1..chromatic_n_max));
# On the other hand, it might be better to use some kind of order that treats
# the powers v[n]^(p^m) in a special way. This might import more information
# from the chromatic spectral sequence into the ordering. One option would be
# like
# .. v[1]^(p^2) >> v[2]^(p^2) >> .. >> v[1]^p >> v[2]^p >> .. v[1] >> v[2] >> ...
# On BP_*BP we use a lexicographic ordering with
# v[1] >> v[2] >> .... >> t[1] >> t[2] >> ... >> 1
# This privileges the ideal J = (t[1],...,t[k]); note that BP_*BP/J is
# the Hopf algebroid whose Ext calculates \pi_*(T(k)).
# Again, it might be better to use some kind of order that treats
# the powers t[n]^(p^m) in a special way. This might import more information
# from the May spectral sequence into the ordering.
BPBP_vars := plex(seq(v[i],i=1..chromatic_n_max),seq(t[i],i=1..chromatic_n_max));
# The cobar complex involves variables t[n,s] corresponding to the copy of
# t[n] in the s'th tensor factor. We use the ordering with
# v[1] >> v[2] >> ... >> t[1,1] >> t[2,1] >> ... >> t[1,2] >> t[2,2] >> ...
# so the variables from each tensor factor dominate those from the next tensor
# factor. It is not clear whether this is the best choice.
BP_cobar_vars :=
plex(op(BPBP_vars),seq(seq(t[i,j],i=1..chromatic_n_max),j=1..chromatic_s_max));
BP_cmp := (a,b) -> TestOrder(a,b,BP_vars):
BPBP_cmp := (a,b) -> TestOrder(a,b,BPBP_vars):
BP_cobar_cmp := (a,b) -> TestOrder(a,b,BP_cobar_vars):
BP_degree := (u) -> degree(subs(BP_degree_rule,u),e);
# Basis for Z[v[i] : i >= n] in degree d
BP_basis := proc(d::integer,n::posint := 1)
option remember;
local m,r,i;
m := 2*p^n-2;
r := floor(d/m);
if d < 0 or modp(d,2*p-2) <> 0 then
return [];
elif d = 0 then
return [1];
elif r = 0 then
return [];
else
map(op,[seq(v[n]^i *~ BP_basis(d-m*i,n+1),i=0..r)]);
fi;
end:
# Basis for Z[m[i] : i >= n] in degree d
HBP_basis := proc(d::integer,n::posint := 1)
eval(subs(v = m,BP_basis(d,n)));
end:
# Basis for Z[t[i] : i >= n] in degree d
T_basis := proc(d::integer,n::posint := 1)
eval(subs(v = t,BP_basis(d,n)));
end:
# Basis for Z[v[i] : i >= n] in degree <= d
BP_lower_basis := proc(d::integer,n::posint := 1)
option remember;
local m,r,i;
m := 2*p^n-2;
r := floor(d/m);
if d < 0 or modp(d,2*p-2) <> 0 then
return [];
elif r = 0 then
return [1];
else
map(op,[seq(v[n]^i *~ BP_lower_basis(d-m*i,n+1),i=0..r)]);
fi;
end:
# Basis for Z[m[i] : i >= n] in degree d
HBP_lower_basis := proc(d::integer,n::posint := 1)
eval(subs(v = m,BP_lower_basis(d,n)));
end:
# Basis for Z[t[i] : i >= n] in degree d
T_lower_basis := proc(d::integer,n::posint := 1)
eval(subs(v = t,BP_lower_basis(d,n)));
end:
# Basis for BP_*BP in degree d
BPBP_basis := proc(d::integer)
local B,m,u,v;
B := NULL;
for u in BP_lower_basis(d) do
m := d - BP_degree(u);
for v in T_basis(m) do
B := B,(u*v);
od;
od;
return [B];
end:
# Basis for the s-fold tensor power of Z[t_1,t_2,...] in degree d
# The copy of t[i] in the j'th tensor factor is represented by t[i,j]
T_power_basis := proc(s::nonnegint,d::integer)
local B,m,R1,R2,u,v;
if s = 0 then return `if`(d = 0,[1],[]); fi;
R1 := {seq(t[n] = t[n,1],n=1..chromatic_n_max)};
R2 := {seq(seq(t[n,i] = t[n,i+1],i=1..s-1),n=1..chromatic_n_max)};
B := NULL;
for u in subs(R1,T_lower_basis(d)) do
m := d - BP_degree(u);
for v in subs(R2,T_power_basis(s-1,m)) do
B := B,(u*v);
od;
od;
return [B];
end:
# Basis for the s-fold tensor power of the augmentation ideal in
# Z[t_1,t_2,...] in degree d
T_reduced_power_basis := proc(s::nonnegint,d::integer)
local B,m,R1,R2,u,v;
if s = 0 then return `if`(d = 0,[1],[]); fi;
R1 := {seq(t[n] = t[n,1],n=1..chromatic_n_max)};
R2 := {seq(seq(t[n,i] = t[n,i+1],i=1..s-1),n=1..chromatic_n_max)};
B := NULL;
for u in subs(R1,T_lower_basis(d)) do
if u <> 1 then
m := d - BP_degree(u);
for v in subs(R2,T_reduced_power_basis(s-1,m)) do
B := B,(u*v);
od;
fi;
od;
return [B];
end:
BP_cobar_basis := (s,d) ->
[seq(seq(seq(a*b,a in BP_basis(i)),b in T_reduced_power_basis(s,d-i)),i=0..d)];
# Hazewinkel generators in terms of log coefficients
vm := proc(n::nonnegint)
option remember;
if n = 0 then
return p;
else
return expand(p*m[n] - add(m[k]*vm(n-k)^(p^k),k=1..n-1));
fi;
end:
# Log coefficients in terms of Hazewinkel generators
# This is inefficient; should use Ravenel's formulae instead
mv := proc(n::nonnegint)
local err;
option remember;
if n = 0 then return 1; fi;
err := vm(n) - v[n];
err := expand(subs({seq(m[i] = mv(i),i=1..n-1)},err));
return rhs(solve(err=0,{m[n]})[1]);
end:
# Right unit map on the log coefficients
eta_m := (k) -> add(m[i] * t[k-i]^(p^i),i=0..k);
# Right unit map on the Hazewinkel generators
eta_v := proc(k::posint,s::nonnegint)
option remember;
local u,R;
if nargs = 1 then
u := expand(subs({seq(m[i] = eta_m(i),i=1..k)},vm(k)));
u := expand(subs({seq(m[i] = mv(i),i=1..k)},u));
return u;
else
if s = 0 then
return v[k];
elif s = 1 then
u := expand(subs({seq(m[i] = eta_m(i),i=1..k)},vm(k)));
u := expand(subs({seq(m[i] = mv(i),i=1..k)},u));
u := subs({seq(t[i] = t[i,1],i=1..chromatic_n_max)},u);
return u;
else
u := eta_v(k,s-1);
R := { seq(seq(t[i,j] = t[i,j+1],i=1..chromatic_n_max),j=1..s-1),
seq(v[i] = eta_v(i,1),i=1..chromatic_n_max) };
u := subs(R,u);
return u;
fi;
fi;
end:
# Hopf algebroid coproduct on the generators t[n]
psi_t := proc(n)
local a,b;
option remember;
if n = 0 then return 1; fi;
a := add(add(mv(i)*t[j,1]^(p^i)*t[n-i-j,2]^(p^(i+j)),j=0..n-i),i=0..n);
b := add(mv(i)*psi_t(n-i)^(p^i),i=1..n);
a := subs({t[0,1]=1,t[0,2]=1},a);
b := subs({t[0,1]=1,t[0,2]=1},b);
return expand(a - b);
end:
d_BP_cobar_rule := proc(s,i)
local R0,R1,R2,R3;
if i = 0 then
R0 := {seq(t[j]=t[j,1],j=1..chromatic_n_max)};
R1 := {seq(t[j]=t[j,2],j=1..chromatic_n_max)};
R2 := {seq(seq(t[j,k]=t[j,k+1],k=1..s),j=1..chromatic_n_max)};
return
{seq(v[j] = expand(subs(R0,eta_v(j))),j=1..chromatic_n_max),op(R1),op(R2)};
else
R0 := {seq(t[j,1]=t[j,i],j=1..chromatic_n_max),
seq(t[j,2]=t[j,i+1],j=1..chromatic_n_max),
seq(v[j] = eta_v(j,i-1),j=1..chromatic_n_max)};
R1 := {seq(seq(t[j,k]=t[j,k+1],k=i+1..s),j=1..chromatic_n_max)};
R2 := {seq(t[j,i] = subs(R0,psi_t(j)),j=1..chromatic_n_max)};
if i = 1 then
R3 := {seq(t[j] = expand(subs(R0,psi_t(j))),j=1..chromatic_n_max)};
else
R3 := {seq(t[j] = t[j,1],j=1..chromatic_n_max)};
fi;
return {op(R1),op(R2),op(R3)};
fi;
end:
d_BP_cobar := (s) -> (u) ->
expand(add((-1)^i * subs(d_BP_cobar_rule(s,i),u),i=0..s+1));
d_BP_cobar_matrix := proc(s,d)
local B1,B2,cf;
B1 := BP_cobar_basis(s,d);
B2 := BP_cobar_basis(s+1,d);
cf := proc(u)
local sol;
sol := solve({coeffs(u - add(c[i]*B2[i],i=1..nops(B2)),indets(B2))});
subs(sol,[seq(c[i],i=1..nops(B2))]);
end;
Transpose(Matrix(map(cf,map(d_BP_cobar(s),B1))));
end:
BP_cobar_cycles := proc(s,d)
local M;
M := d_BP_cobar_matrix(s,d);
map(u -> Transpose(Vector(BP_cobar_basis(s,d))) . u,NullSpace(M));
end:
mu_BP_cobar := (s1,s2) -> proc(a,b)
local i,b0;
b0 := b;
for i from 0 to s1-1 do
b0 := expand(subs(d_BP_cobar_rule(s2+i,0),b0));
od:
return expand(a * b0);
end:
analyse_BP := proc(p_,n_)
global p,chromatic_n_max;
if nargs > 0 then p := p_; fi;
if nargs > 1 then chromatic_n_max := n_; fi;
vm(chromatic_n_max);
mv(chromatic_n_max);
eta_v(chromatic_n_max);
psi_t(chromatic_n_max);
NULL;
end:
analyse_BP_cobar := proc(s::nonnegint,d::integer)
local i,R,R0,B1,B2,n1,n2,M,L0,P0,x,x1,L,P,Q,nx,LB2,y,HB,HE,T,U,L1,K,Ki;
global BP_cobar_data;
if d + s >= 2*(p^(chromatic_n_max + 1) - 1) then
error("chromatic_n_max is too small");
fi;
if s > chromatic_s_max then
error("chromatic_s_max is too small");
fi;
R := table():
if s = 0 then
if d = 0 then
R["chain_basis"] := [1];
R["chain_rank"] := 1;
R["cycle_basis"] := [1];
R["cycle_rank"] := 1;
R["boundary_basis"] := [];
R["boundary_rank"] := 0;
R["pivot_data"] := [[1,infinity]];
R["non_cycle_basis"] := [];
R["homology_basis"] := [1];
R["homology_exponents"] := [infinity];
else
R["chain_basis"] := BP_cobar_basis(0,d);
R["chain_rank"] := nops(R["chain_basis"]);
R["cycle_basis"] := [];
R["cycle_rank"] := 0;
R["boundary_basis"] := [];
R["boundary_rank"] := 0;
R["pivot_data"] := [];
R["non_cycle_basis"] := R["chain_basis"];
R["homology_basis"] := [];
R["homology_exponents"] := [];
fi;
BP_cobar_data[s,d] := eval(R);
return eval(R);
fi;
if type(BP_cobar_data[s-1,d+1],table) then
R0 := BP_cobar_data[s-1,d+1];
B1 := R0["non_cycle_basis"];
else
B1 := BP_cobar_basis(s-1,s+d):
fi;
B2 := BP_cobar_basis(s,s+d):
n1 := nops(B1);
n2 := nops(B2);
R["chain_basis"] := B2;
R["chain_rank"] := n2;
if n2 = 0 then
R["cycle_basis"] := [];
R["cycle_rank"] := 0;
R["boundary_basis"] := [];
R["boundary_rank"] := 0;
R["pivot_data"] := [];
R["non_cycle_basis"] := [];
R["homology_basis"] := [];
R["homology_exponents"] := [];
BP_cobar_data[s,d] := eval(R);
return eval(R);
fi;
M := Transpose(Matrix(map(coeff_list,map(d_BP_cobar(s-1),B1),B2)));
L0,P0,x := op(Zpl_reduce(Transpose(M),p)):
L := Transpose(L0):
P := Transpose(P0):
nx := nops(x):
R["cycle_rank"] := nx;
LB2 := convert(L0.Vector(B2),list):
R["boundary_basis"] := [seq(LB2[i],i=1..nx)];
R["cycle_basis"] := [seq(LB2[i]/p^x[i][2],i=1..nx)];
R["pivot_data"] := x;
y := sort([op({seq(i,i=1..n2)} minus {seq(x[i][1],i=1..nx)})]);
R["non_cycle_basis"] := [seq(B2[i],i in y)];
HB := [];
HE := [];
for i from 1 to nx do
if x[i][2] > 0 then
HB := [op(HB),R["cycle_basis"][i]];
HE := [op(HE),p^x[i][2]];
fi;
od;
R["homology_basis"] := HB;
R["homology_exponents"] := HE;
T := <IdentityMatrix(nx)|Matrix(nx,n1-nx)>;
U := Matrix(nx,n2):
for i from 1 to nx do U[i,x[i][1]] := 1; od:
L1 := U.L.Transpose(T);
Q := P.Transpose(T).(1/L1).U;
K := <SubMatrix(L,1..n2,1..nx)|Matrix(n2,n2-nx)>;
y := sort([op({seq(i,i=1..n2)} minus {seq(x[i][1],i=1..nx)})]);
for i from 1 to n2 - nx do
K[y[i],nx+i] := 1;
od:
Ki := 1/K;
BP_cobar_data[s,d] := eval(R);
return eval(R);
end:
BP_set_p := proc(p_)
global p,v,BP_degree_rule,BP_basis,BP_lower_basis,vm,mv,eta_v,psi_t;
p := p_;
unprotect('v');
v[0] := p;
protect('v');
BP_degree_rule := {
seq(v[n] = e^(2*(p^n-1)) * v[n],n=1..chromatic_n_max),
seq(t[n] = e^(2*(p^n-1)) * t[n],n=1..chromatic_n_max),
seq(seq(t[n,i] = e^(2*(p^n-1)) * t[n,i],n=1..chromatic_n_max),i=1..chromatic_s_max)
}:
forget(BP_basis);
forget(BP_lower_basis);
forget(vm);
forget(mv);
forget(eta_v);
forget(psi_t);
NULL;
end:
save_BP_data := proc()
local file;
file := sprintf("%s/BP_%d.m",data_dir,p);
save(p,chromatic_n_max,chromatic_s_max,vm,mv,eta_v,psi_t,BP_basis,BP_lower_basis,file);
end:
load_BP_data := proc(p)
local file;
file := sprintf("%s/BP_%d.m",data_dir,p);
load(file);
end:
save_BP_cobar_data := proc()
local file;
file := sprintf("%s/BP_cobar_data_%d.m",data_dir,p);
save(BP_cobar_data,file);
end:
load_BP_cobar_data := proc(p)
local file;
file := sprintf("%s/BP_cobar_data_%d.m",data_dir,p);
load(file);
end:
|
function i4mat_write ( output_filename, m, n, table )
%*****************************************************************************80
%
%% I4MAT_WRITE writes an I4MAT file.
%
% Discussion:
%
% An I4MAT is an array of I4's.
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 26 June 2010
%
% Author:
%
% John Burkardt
%
% Parameters:
%
% Input, string OUTPUT_FILENAME, the output filename.
%
% Input, integer M, the spatial dimension.
%
% Input, integer N, the number of points.
%
% Input, integer TABLE(M,N), the points.
%
%
% Open the file.
%
output_unit = fopen ( output_filename, 'wt' );
if ( output_unit < 0 )
fprintf ( 1, '\n' );
fprintf ( 1, 'I4MAT_WRITE - Error!\n' );
fprintf ( 1, ' Could not open the output file.\n' );
error ( 'I4MAT_WRITE - Error!' );
end
%
% Write the data.
%
for j = 1 : n
for i = 1 : m
fprintf ( output_unit, ' %12d', round ( table(i,j) ) );
end
fprintf ( output_unit, '\n' );
end
%
% Close the file.
%
fclose ( output_unit );
return
end
|
module Polymorphic where
import Data.Complex
import Data.Ratio
import Prelude hiding (product)
stringLength :: String -> Int
stringLength x = case x of
[] -> 0
(x:xs) -> 1 + stringLength xs
integerListLength :: [Integer] -> Int
integerListLength x = case x of
[] -> 0
(x:xs) -> 1 + integerListLength xs
-- | A polymorphic length function
polymorphicLength :: [a] -> Int
polymorphicLength list = case list of
[] -> 0
_ : xs -> 1 + polymorphicLength xs
-- | A polymorphic reverse function
reverseOf :: [a] -> [a]
reverseOf xs = case xs of
[] -> []
c: cs -> reverseOf cs ++ [c]
-- | A polymorphic isPalindrome function
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome xs
| null xs = True
| xs == reverseOf xs = True
| otherwise = False
-- | A polymorphic list equality function
listEqual :: (Eq a) => [a] -> [a] -> Bool
listEqual list1 list2 = case (list1, list2) of
([], []) -> True
([], _ ) -> False
(_ , []) -> False
(x: xs, y: ys) -> (x == y) && (xs `listEqual` ys)
isMonotonicallyIncreasing :: (Ord a) => [a] -> Bool
isMonotonicallyIncreasing list = case list of
[] -> True
[x] -> True
i1: i2: is | i1 <= i2 -> isMonotonicallyIncreasing (i2: is)
| otherwise -> False
normaliseVector :: (Floating a) => [a] -> [a]
normaliseVector vector = divideByScalar vector (norm vector)
divideByScalar :: (Fractional a) => [a] -> a -> [a]
divideByScalar vector' scalar = case vector' of
[] -> []
f: fs -> (f / scalar): divideByScalar fs scalar
norm :: (Floating a) => [a] -> a
norm vector' = sqrt (sumSqr vector')
where
sumSqr :: (Num a) => [a] -> a
sumSqr vector'' = case vector'' of
[] -> 0
f: fs -> f*f + sumSqr fs
reallyPolymorphicLength :: (Integral b) => [a] -> b
reallyPolymorphicLength list = case list of
[] -> 0
_: xs -> 1 + reallyPolymorphicLength xs
printLargestAsString :: (Ord a, Show a) => [a] -> String
printLargestAsString list =
"The largest element in the list is " ++ show (maximum list)
rationalZero :: Ratio Integer
floatZero :: Float
doubleZero :: Double
complexZero :: Complex Double
rationalZero = 0
floatZero = 0.0
doubleZero = 0.0
complexZero = mkPolar 0.0 0.0
product :: undefined -- TODO
product = undefined -- TODO
|
/-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Term
import Lean.Elab.BindersUtil
import Lean.Elab.PatternVar
import Lean.Elab.Quotation.Util
import Lean.Parser.Do
-- HACK: avoid code explosion until heuristics are improved
set_option compiler.reuse false
namespace Lean.Elab.Term
open Lean.Parser.Term
open Meta
open TSyntax.Compat
private def getDoSeqElems (doSeq : Syntax) : List Syntax :=
if doSeq.getKind == ``Parser.Term.doSeqBracketed then
doSeq[1].getArgs.toList.map fun arg => arg[0]
else if doSeq.getKind == ``Parser.Term.doSeqIndent then
doSeq[0].getArgs.toList.map fun arg => arg[0]
else
[]
private def getDoSeq (doStx : Syntax) : Syntax :=
doStx[1]
@[builtin_term_elab liftMethod] def elabLiftMethod : TermElab := fun stx _ =>
throwErrorAt stx "invalid use of `(<- ...)`, must be nested inside a 'do' expression"
/-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/
private def liftMethodDelimiter (k : SyntaxNodeKind) : Bool :=
k == ``Parser.Term.do ||
k == ``Parser.Term.doSeqIndent ||
k == ``Parser.Term.doSeqBracketed ||
k == ``Parser.Term.termReturn ||
k == ``Parser.Term.termUnless ||
k == ``Parser.Term.termTry ||
k == ``Parser.Term.termFor
/-- Given `stx` which is a `letPatDecl`, `letEqnsDecl`, or `letIdDecl`, return true if it has binders. -/
private def letDeclArgHasBinders (letDeclArg : Syntax) : Bool :=
let k := letDeclArg.getKind
if k == ``Parser.Term.letPatDecl then
false
else if k == ``Parser.Term.letEqnsDecl then
true
else if k == ``Parser.Term.letIdDecl then
-- letIdLhs := ident >> checkWsBefore "expected space before binders" >> many (ppSpace >> letIdBinder)) >> optType
let binders := letDeclArg[1]
binders.getNumArgs > 0
else
false
/-- Return `true` if the given `letDecl` contains binders. -/
private def letDeclHasBinders (letDecl : Syntax) : Bool :=
letDeclArgHasBinders letDecl[0]
/-- Return true if we should generate an error message when lifting a method over this kind of syntax. -/
private def liftMethodForbiddenBinder (stx : Syntax) : Bool :=
let k := stx.getKind
if k == ``Parser.Term.fun || k == ``Parser.Term.matchAlts ||
k == ``Parser.Term.doLetRec || k == ``Parser.Term.letrec then
-- It is never ok to lift over this kind of binder
true
-- The following kinds of `let`-expressions require extra checks to decide whether they contain binders or not
else if k == ``Parser.Term.let then
letDeclHasBinders stx[1]
else if k == ``Parser.Term.doLet then
letDeclHasBinders stx[2]
else if k == ``Parser.Term.doLetArrow then
letDeclArgHasBinders stx[2]
else
false
private partial def hasLiftMethod : Syntax → Bool
| Syntax.node _ k args =>
if liftMethodDelimiter k then false
-- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a
-- bit slower
else if k == ``Parser.Term.liftMethod then true
else args.any hasLiftMethod
| _ => false
structure ExtractMonadResult where
m : Expr
returnType : Expr
expectedType : Expr
private def mkUnknownMonadResult : MetaM ExtractMonadResult := do
let u ← mkFreshLevelMVar
let v ← mkFreshLevelMVar
let m ← mkFreshExprMVar (← mkArrow (mkSort (mkLevelSucc u)) (mkSort (mkLevelSucc v)))
let returnType ← mkFreshExprMVar (mkSort (mkLevelSucc u))
return { m, returnType, expectedType := mkApp m returnType }
private partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do
let some expectedType := expectedType? | mkUnknownMonadResult
let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do
let .app m returnType := type | return none
try
let bindInstType ← mkAppM ``Bind #[m]
discard <| Meta.synthInstance bindInstType
return some { m, returnType, expectedType }
catch _ =>
return none
let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do
match (← extractStep? type) with
| some r => return r
| none =>
let typeNew ← whnfCore type
if typeNew != type then
extract? typeNew
else
if typeNew.getAppFn.isMVar then
mkUnknownMonadResult
else match (← unfoldDefinition? typeNew) with
| some typeNew => extract? typeNew
| none => return none
match (← extract? expectedType) with
| some r => return r
| none => throwError "invalid `do` notation, expected type is not a monad application{indentExpr expectedType}\nYou can use the `do` notation in pure code by writing `Id.run do` instead of `do`, where `Id` is the identity monad."
namespace Do
abbrev Var := Syntax -- TODO: should be `Ident`
/-- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/
structure Alt (σ : Type) where
ref : Syntax
vars : Array Var
patterns : Syntax
rhs : σ
deriving Inhabited
/--
Auxiliary datastructure for representing a `do` code block, and compiling "reassignments" (e.g., `x := x + 1`).
We convert `Code` into a `Syntax` term representing the:
- `do`-block, or
- the visitor argument for the `forIn` combinator.
We say the following constructors are terminals:
- `break`: for interrupting a `for x in s`
- `continue`: for interrupting the current iteration of a `for x in s`
- `return e`: for returning `e` as the result for the whole `do` computation block
- `action a`: for executing action `a` as a terminal
- `ite`: if-then-else
- `match`: pattern matching
- `jmp` a goto to a join-point
We say the terminals `break`, `continue`, `action`, and `return` are "exit points"
Note that, `return e` is not equivalent to `action (pure e)`. Here is an example:
```
def f (x : Nat) : IO Unit := do
if x == 0 then
return ()
IO.println "hello"
```
Executing `#eval f 0` will not print "hello". Now, consider
```
def g (x : Nat) : IO Unit := do
if x == 0 then
pure ()
IO.println "hello"
```
The `if` statement is essentially a noop, and "hello" is printed when we execute `g 0`.
- `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`).
The field `stx` is the actual `doElem`,
`vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block.
`vars` is an array since we have declarations such as `let (a, b) := s`.
- `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`).
- `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow.
- `seq a k` executes action `a`, ignores its result, and then executes `k`.
We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`.
A code block `C` is well-formed if
- For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and
`ps.size == as.size` -/
inductive Code where
| decl (xs : Array Var) (doElem : Syntax) (k : Code)
| reassign (xs : Array Var) (doElem : Syntax) (k : Code)
/-- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/
| joinpoint (name : Name) (params : Array (Var × Bool)) (body : Code) (k : Code)
| seq (action : Syntax) (k : Code)
| action (action : Syntax)
| break (ref : Syntax)
| continue (ref : Syntax)
| return (ref : Syntax) (val : Syntax)
/-- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/
| ite (ref : Syntax) (h? : Option Var) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code)
| match (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optMotive : Syntax) (alts : Array (Alt Code))
| jmp (ref : Syntax) (jpName : Name) (args : Array Syntax)
deriving Inhabited
def Code.getRef? : Code → Option Syntax
| .decl _ doElem _ => doElem
| .reassign _ doElem _ => doElem
| .joinpoint .. => none
| .seq a _ => a
| .action a => a
| .break ref => ref
| .continue ref => ref
| .return ref _ => ref
| .ite ref .. => ref
| .match ref .. => ref
| .jmp ref .. => ref
abbrev VarSet := RBMap Name Syntax Name.cmp
/-- A code block, and the collection of variables updated by it. -/
structure CodeBlock where
code : Code
uvars : VarSet := {} -- set of variables updated by `code`
private def varSetToArray (s : VarSet) : Array Var :=
s.fold (fun xs _ x => xs.push x) #[]
private def varsToMessageData (vars : Array Var) : MessageData :=
MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.getId.simpMacroScopes)) " "
partial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData :=
let us := MessageData.ofList <| (varSetToArray codeBlock.uvars).toList.map MessageData.ofSyntax
let rec loop : Code → MessageData
| .decl xs _ k => m!"let {varsToMessageData xs} := ...\n{loop k}"
| .reassign xs _ k => m!"{varsToMessageData xs} := ...\n{loop k}"
| .joinpoint n ps body k => m!"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\n{loop k}"
| .seq e k => m!"{e}\n{loop k}"
| .action e => e
| .ite _ _ _ c t e => m!"if {c} then {indentD (loop t)}\nelse{loop e}"
| .jmp _ j xs => m!"jmp {j.simpMacroScopes} {xs.toList}"
| .break _ => m!"break {us}"
| .continue _ => m!"continue {us}"
| .return _ v => m!"return {v} {us}"
| .match _ _ ds _ alts =>
m!"match {ds} with"
++ alts.foldl (init := m!"") fun acc alt => acc ++ m!"\n| {alt.patterns} => {loop alt.rhs}"
loop codeBlock.code
/-- Return true if the give code contains an exit point that satisfies `p` -/
partial def hasExitPointPred (c : Code) (p : Code → Bool) : Bool :=
let rec loop : Code → Bool
| .decl _ _ k => loop k
| .reassign _ _ k => loop k
| .joinpoint _ _ b k => loop b || loop k
| .seq _ k => loop k
| .ite _ _ _ _ t e => loop t || loop e
| .match _ _ _ _ alts => alts.any (loop ·.rhs)
| .jmp .. => false
| c => p c
loop c
def hasExitPoint (c : Code) : Bool :=
hasExitPointPred c fun _ => true
def hasReturn (c : Code) : Bool :=
hasExitPointPred c fun
| .return .. => true
| _ => false
def hasTerminalAction (c : Code) : Bool :=
hasExitPointPred c fun
| .action _ => true
| _ => false
def hasBreakContinue (c : Code) : Bool :=
hasExitPointPred c fun
| .break _ => true
| .continue _ => true
| _ => false
def hasBreakContinueReturn (c : Code) : Bool :=
hasExitPointPred c fun
| .break _ => true
| .continue _ => true
| .return _ _ => true
| _ => false
def mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax → m Code) : m Code := withRef e <| withFreshMacroScope do
let y ← `(y)
let doElem ← `(doElem| let y ← $e:term)
-- Add elaboration hint for producing sane error message
let y ← `(ensure_expected_type% "type mismatch, result value" $y)
let k ← mkCont y
return .decl #[y] doElem k
/-- Convert `action _ e` instructions in `c` into `let y ← e; jmp _ jp (xs y)`. -/
partial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Var) : MacroM Code :=
let rec loop : Code → MacroM Code
| .decl xs stx k => return .decl xs stx (← loop k)
| .reassign xs stx k => return .reassign xs stx (← loop k)
| .joinpoint n ps b k => return .joinpoint n ps (← loop b) (← loop k)
| .seq e k => return .seq e (← loop k)
| .ite ref x? h c t e => return .ite ref x? h c (← loop t) (← loop e)
| .match ref g ds t alts => return .match ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← loop alt.rhs) })
| .action e => mkAuxDeclFor e fun y =>
let ref := e
-- We jump to `jp` with xs **and** y
let jmpArgs := xs.push y
return Code.jmp ref jp jmpArgs
| c => return c
loop code
structure JPDecl where
name : Name
params : Array (Var × Bool)
body : Code
def attachJP (jpDecl : JPDecl) (k : Code) : Code :=
Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k
def attachJPs (jpDecls : Array JPDecl) (k : Code) : Code :=
jpDecls.foldr attachJP k
def mkFreshJP (ps : Array (Var × Bool)) (body : Code) : TermElabM JPDecl := do
let ps ← if ps.isEmpty then
let y ← `(y)
pure #[(y.raw, false)]
else
pure ps
-- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by
-- the "do" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp`
-- We will remove this hack when we re-implement the compiler frontend in Lean.
let name ← mkFreshUserName `__do_jp
pure { name := name, params := ps, body := body }
def addFreshJP (ps : Array (Var × Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do
let jp ← mkFreshJP ps body
modify fun (jps : Array JPDecl) => jps.push jp
pure jp.name
def insertVars (rs : VarSet) (xs : Array Var) : VarSet :=
xs.foldl (fun rs x => rs.insert x.getId x) rs
def eraseVars (rs : VarSet) (xs : Array Var) : VarSet :=
xs.foldl (·.erase ·.getId) rs
def eraseOptVar (rs : VarSet) (x? : Option Var) : VarSet :=
match x? with
| none => rs
| some x => rs.insert x.getId x
/-- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/
def mkSimpleJmp (ref : Syntax) (rs : VarSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do
let xs := varSetToArray rs
let jp ← addFreshJP (xs.map fun x => (x, true)) c
if xs.isEmpty then
let unit ← ``(Unit.unit)
return Code.jmp ref jp #[unit]
else
return Code.jmp ref jp xs
/-- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value.
The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh`
is a fresh variable created by this method. -/
def mkJmp (ref : Syntax) (rs : VarSet) (val : Syntax) (mkJPBody : Syntax → MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do
let xs := varSetToArray rs
let args := xs.push val
let yFresh ← withRef ref `(y)
let ps := xs.map fun x => (x, true)
let ps := ps.push (yFresh, false)
let jpBody ← liftMacroM <| mkJPBody yFresh
let jp ← addFreshJP ps jpBody
return Code.jmp ref jp args
/-- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path. -/
partial def pullExitPointsAux (rs : VarSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code :=
match c with
| .decl xs stx k => return .decl xs stx (← pullExitPointsAux (eraseVars rs xs) k)
| .reassign xs stx k => return .reassign xs stx (← pullExitPointsAux (insertVars rs xs) k)
| .joinpoint j ps b k => return .joinpoint j ps (← pullExitPointsAux rs b) (← pullExitPointsAux rs k)
| .seq e k => return .seq e (← pullExitPointsAux rs k)
| .ite ref x? o c t e => return .ite ref x? o c (← pullExitPointsAux (eraseOptVar rs x?) t) (← pullExitPointsAux (eraseOptVar rs x?) e)
| .match ref g ds t alts => return .match ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) })
| .jmp .. => return c
| .break ref => mkSimpleJmp ref rs (.break ref)
| .continue ref => mkSimpleJmp ref rs (.continue ref)
| .return ref val => mkJmp ref rs val (fun y => return .return ref y)
| .action e =>
-- We use `mkAuxDeclFor` because `e` is not pure.
mkAuxDeclFor e fun y =>
let ref := e
mkJmp ref rs y (fun yFresh => return .action (← ``(Pure.pure $yFresh)))
/--
Auxiliary operation for adding new variables to the collection of updated variables in a CodeBlock.
When a new variable is not already in the collection, but is shadowed by some declaration in `c`,
we create auxiliary join points to make sure we preserve the semantics of the code block.
Example: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it
with the reassignment `x := x + 1`. We first use `pullExitPoints` to create
```
let jp (x!1) := return x!1;
print x;
let x := 10;
jmp jp x
```
and then we add the reassignment
```
x := x + 1
let jp (x!1) := return x!1;
print x;
let x := 10;
jmp jp x
```
Note that we created a fresh variable `x!1` to avoid accidental name capture.
As another example, consider
```
print x;
let x := 10
y := y + 1;
return x;
```
We transform it into
```
let jp (y x!1) := return x!1;
print x;
let x := 10
y := y + 1;
jmp jp y x
```
and then we add the reassignment as in the previous example.
We need to include `y` in the jump, because each exit point is implicitly returning the set of
update variables.
We implement the method as follows. Let `us` be `c.uvars`, then
1- for each `return _ y` in `c`, we create a join point
`let j (us y!1) := return y!1`
and replace the `return _ y` with `jmp us y`
2- for each `break`, we create a join point
`let j (us) := break`
and replace the `break` with `jmp us`.
3- Same as 2 for `continue`.
-/
def pullExitPoints (c : Code) : TermElabM Code := do
if hasExitPoint c then
let (c, jpDecls) ← (pullExitPointsAux {} c).run #[]
return attachJPs jpDecls c
else
return c
partial def extendUpdatedVarsAux (c : Code) (ws : VarSet) : TermElabM Code :=
let rec update (c : Code) : TermElabM Code := do
match c with
| .joinpoint j ps b k => return .joinpoint j ps (← update b) (← update k)
| .seq e k => return .seq e (← update k)
| .match ref g ds t alts =>
if alts.any fun alt => alt.vars.any fun x => ws.contains x.getId then
-- If a pattern variable is shadowing a variable in ws, we `pullExitPoints`
pullExitPoints c
else
return .match ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← update alt.rhs) })
| .ite ref none o c t e => return .ite ref none o c (← update t) (← update e)
| .ite ref (some h) o cond t e =>
if ws.contains h.getId then
-- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints`
pullExitPoints c
else
return Code.ite ref (some h) o cond (← update t) (← update e)
| .reassign xs stx k => return .reassign xs stx (← update k)
| .decl xs stx k => do
if xs.any fun x => ws.contains x.getId then
-- One the declared variables is shadowing a variable in `ws`
pullExitPoints c
else
return .decl xs stx (← update k)
| c => return c
update c
/--
Extend the set of updated variables. It assumes `ws` is a super set of `c.uvars`.
We **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`.
See discussion at `pullExitPoints`.
-/
partial def extendUpdatedVars (c : CodeBlock) (ws : VarSet) : TermElabM CodeBlock := do
if ws.any fun x _ => !c.uvars.contains x then
-- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed)
pure { code := (← extendUpdatedVarsAux c.code ws), uvars := ws }
else
pure { c with uvars := ws }
private def union (s₁ s₂ : VarSet) : VarSet :=
s₁.fold (·.insert ·) s₂
/--
Given two code blocks `c₁` and `c₂`, make sure they have the same set of updated variables.
Let `ws` the union of the updated variables in `c₁‵ and ‵c₂`.
We use `extendUpdatedVars c₁ ws` and `extendUpdatedVars c₂ ws`
-/
def homogenize (c₁ c₂ : CodeBlock) : TermElabM (CodeBlock × CodeBlock) := do
let ws := union c₁.uvars c₂.uvars
let c₁ ← extendUpdatedVars c₁ ws
let c₂ ← extendUpdatedVars c₂ ws
pure (c₁, c₂)
/--
Extending code blocks with variable declarations: `let x : t := v` and `let x : t ← v`.
We remove `x` from the collection of updated varibles.
Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables
declared by it. It is an array because we have let-declarations that declare multiple variables.
Example: `let (x, y) := t`
-/
def mkVarDeclCore (xs : Array Var) (stx : Syntax) (c : CodeBlock) : CodeBlock := {
code := Code.decl xs stx c.code,
uvars := eraseVars c.uvars xs
}
/--
Extending code blocks with reassignments: `x : t := v` and `x : t ← v`.
Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables
declared by it. It is an array because we have let-declarations that declare multiple variables.
Example: `(x, y) ← t`
-/
def mkReassignCore (xs : Array Var) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do
let us := c.uvars
let ws := insertVars us xs
-- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`.
-- See discussion at `pullExitPoints`
let code ← if xs.any fun x => !us.contains x.getId then extendUpdatedVarsAux c.code ws else pure c.code
pure { code := .reassign xs stx code, uvars := ws }
def mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock :=
{ c with code := .seq action c.code }
def mkTerminalAction (action : Syntax) : CodeBlock :=
{ code := .action action }
def mkReturn (ref : Syntax) (val : Syntax) : CodeBlock :=
{ code := .return ref val }
def mkBreak (ref : Syntax) : CodeBlock :=
{ code := .break ref }
def mkContinue (ref : Syntax) : CodeBlock :=
{ code := .continue ref }
def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do
let x? := optIdent.getOptional?
let (thenBranch, elseBranch) ← homogenize thenBranch elseBranch
return {
code := .ite ref x? optIdent cond thenBranch.code elseBranch.code,
uvars := thenBranch.uvars,
}
private def mkUnit : MacroM Syntax :=
``((⟨⟩ : PUnit))
private def mkPureUnit : MacroM Syntax :=
``(pure PUnit.unit)
def mkPureUnitAction : MacroM CodeBlock := do
return mkTerminalAction (← mkPureUnit)
def mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do
let thenBranch ← mkPureUnitAction
return { c with code := .ite (← getRef) none mkNullNode cond thenBranch.code c.code }
def mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optMotive : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do
-- nary version of homogenize
let ws := alts.foldl (union · ·.rhs.uvars) {}
let alts ← alts.mapM fun alt => do
let rhs ← extendUpdatedVars alt.rhs ws
return { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code }
return { code := .match ref genParam discrs optMotive alts, uvars := ws }
/-- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`.
This method assumes `terminal` is a terminal -/
def concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Var) (k : CodeBlock) : TermElabM CodeBlock := do
unless hasTerminalAction terminal.code do
throwErrorAt kRef "`do` element is unreachable"
let (terminal, k) ← homogenize terminal k
let xs := varSetToArray k.uvars
let y ← match y? with | some y => pure y | none => `(y)
let ps := xs.map fun x => (x, true)
let ps := ps.push (y, false)
let jpDecl ← mkFreshJP ps k.code
let jp := jpDecl.name
let terminal ← liftMacroM <| convertTerminalActionIntoJmp terminal.code jp xs
return { code := attachJP jpDecl terminal, uvars := k.uvars }
def getLetIdDeclVar (letIdDecl : Syntax) : Var :=
letIdDecl[0]
-- support both regular and syntax match
def getPatternVarsEx (pattern : Syntax) : TermElabM (Array Var) :=
getPatternVars pattern <|>
Quotation.getPatternVars pattern
def getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Var) :=
getPatternsVars patterns <|>
Quotation.getPatternsVars patterns
def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Var) := do
let pattern := letPatDecl[0]
getPatternVarsEx pattern
def getLetEqnsDeclVar (letEqnsDecl : Syntax) : Var :=
letEqnsDecl[0]
def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Var) := do
let arg := letDecl[0]
if arg.getKind == ``Parser.Term.letIdDecl then
return #[getLetIdDeclVar arg]
else if arg.getKind == ``Parser.Term.letPatDecl then
getLetPatDeclVars arg
else if arg.getKind == ``Parser.Term.letEqnsDecl then
return #[getLetEqnsDeclVar arg]
else
throwError "unexpected kind of let declaration"
def getDoLetVars (doLet : Syntax) : TermElabM (Array Var) :=
-- leading_parser "let " >> optional "mut " >> letDecl
getLetDeclVars doLet[2]
def getHaveIdLhsVar (optIdent : Syntax) : TermElabM Var :=
if optIdent.isNone then
`(this)
else
pure optIdent[0]
def getDoHaveVars (doHave : Syntax) : TermElabM (Array Var) := do
-- doHave := leading_parser "have " >> Term.haveDecl
-- haveDecl := leading_parser haveIdDecl <|> letPatDecl <|> haveEqnsDecl
let arg := doHave[1][0]
if arg.getKind == ``Parser.Term.haveIdDecl then
-- haveIdDecl := leading_parser atomic (haveIdLhs >> " := ") >> termParser
-- haveIdLhs := optional (ident >> many (ppSpace >> letIdBinder)) >> optType
return #[← getHaveIdLhsVar arg[0]]
else if arg.getKind == ``Parser.Term.letPatDecl then
getLetPatDeclVars arg
else if arg.getKind == ``Parser.Term.haveEqnsDecl then
-- haveEqnsDecl := leading_parser haveIdLhs >> matchAlts
return #[← getHaveIdLhsVar arg[0]]
else
throwError "unexpected kind of have declaration"
def getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Var) := do
-- letRecDecls is an array of `(group (optional attributes >> letDecl))`
let letRecDecls := doLetRec[1][0].getSepArgs
let letDecls := letRecDecls.map fun p => p[2]
let mut allVars := #[]
for letDecl in letDecls do
let vars ← getLetDeclVars letDecl
allVars := allVars ++ vars
return allVars
-- ident >> optType >> leftArrow >> termParser
def getDoIdDeclVar (doIdDecl : Syntax) : Var :=
doIdDecl[0]
-- termParser >> leftArrow >> termParser >> optional (" | " >> termParser)
def getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Var) := do
let pattern := doPatDecl[0]
getPatternVarsEx pattern
-- leading_parser "let " >> optional "mut " >> (doIdDecl <|> doPatDecl)
def getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Var) := do
let decl := doLetArrow[2]
if decl.getKind == ``Parser.Term.doIdDecl then
return #[getDoIdDeclVar decl]
else if decl.getKind == ``Parser.Term.doPatDecl then
getDoPatDeclVars decl
else
throwError "unexpected kind of `do` declaration"
def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Var) := do
let arg := doReassign[0]
if arg.getKind == ``Parser.Term.letIdDecl then
return #[getLetIdDeclVar arg]
else if arg.getKind == ``Parser.Term.letPatDecl then
getLetPatDeclVars arg
else
throwError "unexpected kind of reassignment"
def mkDoSeq (doElems : Array Syntax) : Syntax :=
mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode <| doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]]
/--
If the given syntax is a `doIf`, return an equivalent `doIf` that has an `else` but no `else if`s or `if let`s. -/
private def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with
| `(doElem|if $_:doIfProp then $_ else $_) => pure none
| `(doElem|if $cond:doIfCond then $t $[else if $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do
let mut e := e?.getD (← `(doSeq|pure PUnit.unit))
let mut eIsSeq := true
for (cond, t) in Array.zip (conds.reverse.push cond) (ts.reverse.push t) do
e ← if eIsSeq then pure e else `(doSeq|$e:doElem)
e ← match cond with
| `(doIfCond|let $pat := $d) => `(doElem| match $d:term with | $pat:term => $t | _ => $e)
| `(doIfCond|let $pat ← $d) => `(doElem| match ← $d with | $pat:term => $t | _ => $e)
| `(doIfCond|$cond:doIfProp) => `(doElem| if $cond:doIfProp then $t else $e)
| _ => `(doElem| if $(Syntax.missing) then $t else $e)
eIsSeq := false
return some e
| _ => pure none
structure DoIfView where
ref : Syntax
optIdent : Syntax
cond : Syntax
thenBranch : Syntax
elseBranch : Syntax
/-- This method assumes `expandDoIf?` is not applicable. -/
private def mkDoIfView (doIf : Syntax) : DoIfView := {
ref := doIf
optIdent := doIf[1][0]
cond := doIf[1][1]
thenBranch := doIf[3]
elseBranch := doIf[5][1]
}
/--
We use `MProd` instead of `Prod` to group values when expanding the
`do` notation. `MProd` is a universe monomorphic product.
The motivation is to generate simpler universe constraints in code
that was not written by the user.
Note that we are not restricting the macro power since the
`Bind.bind` combinator already forces values computed by monadic
actions to be in the same universe.
-/
private def mkTuple (elems : Array Syntax) : MacroM Syntax := do
if elems.size == 0 then
mkUnit
else if elems.size == 1 then
return elems[0]!
else
elems.extract 0 (elems.size - 1) |>.foldrM (init := elems.back) fun elem tuple =>
``(MProd.mk $elem $tuple)
/-- Return `some action` if `doElem` is a `doExpr <action>`-/
def isDoExpr? (doElem : Syntax) : Option Syntax :=
if doElem.getKind == ``Parser.Term.doExpr then
some doElem[0]
else
none
/--
Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term
```
let a_1 := x.1
let x := x.2
let a_2 := x.1
let x := x.2
...
let a_n := x.1
let a_{n+1} := x.2
body
```
Special cases
- `uvars := #[]` => `body`
- `uvars := #[a]` => `let a := x; body`
We use this method when expanding the `for-in` notation.
-/
private def destructTuple (uvars : Array Var) (x : Syntax) (body : Syntax) : MacroM Syntax := do
if uvars.size == 0 then
return body
else if uvars.size == 1 then
`(let $(uvars[0]!):ident := $x; $body)
else
destruct uvars.toList x body
where
destruct (as : List Var) (x : Syntax) (body : Syntax) : MacroM Syntax := do
match as with
| [a, b] => `(let $a:ident := $x.1; let $b:ident := $x.2; $body)
| a :: as => withFreshMacroScope do
let rest ← destruct as (← `(x)) body
`(let $a:ident := $x.1; let x := $x.2; $rest)
| _ => unreachable!
/-!
The procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term.
We use this method to convert
1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of
`CodeBlock` never contains `break` nor `continue`. Moreover, the collection
of updated variables is not packed into the result.
Thus, we have two kinds of exit points
- `Code.action e` which is converted into `e`
- `Code.return _ e` which is converted into `pure e`
We use `Kind.regular` for this case.
2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate
a `Syntax` term representing a function for the `xs.forIn` combinator.
a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term
has type `m (ForInStep (Option α × σ))`, where `a : α`, and the `σ` is the type
of the tuple of variables reassigned by `b`.
We use `Kind.forInWithReturn` for this case
b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated
`Syntax` term has type `m (ForInStep σ)`.
We use `Kind.forIn` for this case.
3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`).
The generated `Syntax` term for `c` must inform whether `c` "exited" using `Code.action`, `Code.return`,
`Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information.
For example, the auxiliary type `DoResultPBC α σ` is used for a code block that exits with `Code.action`,
**and** `Code.break`/`Code.continue`, `α` is the type of values produced by the exit `action`, and
`σ` is the type of the tuple of reassigned variables.
The type `DoResult α β σ` is usedf for code blocks that exit with
`Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `β` is the type of the returned values.
We don't use `DoResult α β σ` for all cases because:
a) The elaborator would not be able to infer all type parameters without extra annotations. For example,
if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `β`.
b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`),
but we don't want to consider "unreachable" cases.
We do not distinguish between cases that contain `break`, but not `continue`, and vice versa.
When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`,
and `b/c` for a code block that contains `Code.break _` or `Code.continue _`.
- `a`: `Kind.regular`, type `m (α × σ)`
- `r`: `Kind.regular`, type `m (α × σ)`
Note that the code that pattern matches on the result will behave differently in this case.
It produces `return a` for this case, and `pure a` for the previous one.
- `b/c`: `Kind.nestedBC`, type `m (DoResultBC σ)`
- `a` and `r`: `Kind.nestedPR`, type `m (DoResultPR α β σ)`
- `a` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)`
- `r` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)`
Again the code that pattern matches on the result will behave differently in this case and
the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for
this case, and `pure a` for the previous case.
- `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC α β σ)`
Here is the recipe for adding new combinators with nested `do`s.
Example: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m α → m α`
1- Convert `doSeq` into `codeBlock : CodeBlock`
2- Create term `term` using `mkNestedTerm code m uvars a r bc` where
`code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`,
`m` is a `Syntax` representing the Monad, and
`a` is true if `code` contains `Code.action _`,
`r` is true if `code` contains `Code.return _ _`,
`bc` is true if `code` contains `Code.break _` or `Code.continue _`.
Remark: for combinators such as `repeat` that take a single `doSeq`, all
arguments, but `m`, are extracted from `codeBlock`.
3- Create the term `repeat $term`
4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc`
-/
/--
Helper method for annotating `term` with the raw syntax `ref`.
We use this method to implement finer-grained term infos for `do`-blocks.
We use `withRef term` to make sure the synthetic position for the `with_annotate_term` is equal
to the one for `term`. This is important for producing error messages when there is a type mismatch.
Consider the following example:
```
opaque f : IO Nat
def g : IO String := do
f
```
There is at type mismatch at `f`, but it is detected when elaborating the expanded term
containing the `with_annotate_term .. f`. The current `getRef` when this `annotate` is invoked
is not necessarily `f`. Actually, it is the whole `do`-block. By using `withRef` we ensure
the synthetic position for the `with_annotate_term ..` is equal to `term`.
Recall that synthetic positions are used when generating error messages.
-/
def annotate [Monad m] [MonadRef m] [MonadQuotation m] (ref : Syntax) (term : Syntax) : m Syntax :=
withRef term <| `(with_annotate_term $ref $term)
namespace ToTerm
inductive Kind where
| regular
| forIn
| forInWithReturn
| nestedBC
| nestedPR
| nestedSBC
| nestedPRBC
instance : Inhabited Kind := ⟨Kind.regular⟩
def Kind.isRegular : Kind → Bool
| .regular => true
| _ => false
structure Context where
/-- Syntax to reference the monad associated with the do notation. -/
m : Syntax
/-- Syntax to reference the result of the monadic computation performed by the do notation. -/
returnType : Syntax
uvars : Array Var
kind : Kind
abbrev M := ReaderT Context MacroM
def mkUVarTuple : M Syntax := do
let ctx ← read
mkTuple ctx.uvars
def returnToTerm (val : Syntax) : M Syntax := do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| .regular => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (MProd.mk $val $u))
| .forIn => ``(Pure.pure (ForInStep.done $u))
| .forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk (some $val) $u)))
| .nestedBC => unreachable!
| .nestedPR => ``(Pure.pure (DoResultPR.«return» $val $u))
| .nestedSBC => ``(Pure.pure (DoResultSBC.«pureReturn» $val $u))
| .nestedPRBC => ``(Pure.pure (DoResultPRBC.«return» $val $u))
def continueToTerm : M Syntax := do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| .regular => unreachable!
| .forIn => ``(Pure.pure (ForInStep.yield $u))
| .forInWithReturn => ``(Pure.pure (ForInStep.yield (MProd.mk none $u)))
| .nestedBC => ``(Pure.pure (DoResultBC.«continue» $u))
| .nestedPR => unreachable!
| .nestedSBC => ``(Pure.pure (DoResultSBC.«continue» $u))
| .nestedPRBC => ``(Pure.pure (DoResultPRBC.«continue» $u))
def breakToTerm : M Syntax := do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| .regular => unreachable!
| .forIn => ``(Pure.pure (ForInStep.done $u))
| .forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk none $u)))
| .nestedBC => ``(Pure.pure (DoResultBC.«break» $u))
| .nestedPR => unreachable!
| .nestedSBC => ``(Pure.pure (DoResultSBC.«break» $u))
| .nestedPRBC => ``(Pure.pure (DoResultPRBC.«break» $u))
def actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| .regular => if ctx.uvars.isEmpty then pure action else ``(Bind.bind $action fun y => Pure.pure (MProd.mk y $u))
| .forIn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u))
| .forInWithReturn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u)))
| .nestedBC => unreachable!
| .nestedPR => ``(Bind.bind $action fun y => (Pure.pure (DoResultPR.«pure» y $u)))
| .nestedSBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultSBC.«pureReturn» y $u)))
| .nestedPRBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.«pure» y $u)))
def seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do
if action.getKind == ``Parser.Term.doDbgTrace then
let msg := action[1]
`(dbg_trace $msg; $k)
else if action.getKind == ``Parser.Term.doAssert then
let cond := action[1]
`(assert! $cond; $k)
else
let action ← withRef action ``(($action : $((←read).m) PUnit))
``(Bind.bind $action (fun (_ : PUnit) => $k))
def declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do
let kind := decl.getKind
if kind == ``Parser.Term.doLet then
let letDecl := decl[2]
`(let $letDecl:letDecl; $k)
else if kind == ``Parser.Term.doLetRec then
let letRecToken := decl[0]
let letRecDecls := decl[1]
return mkNode ``Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k]
else if kind == ``Parser.Term.doLetArrow then
let arg := decl[2]
if arg.getKind == ``Parser.Term.doIdDecl then
let id := arg[0]
let type := expandOptType id arg[1]
let doElem := arg[3]
-- `doElem` must be a `doExpr action`. See `doLetArrowToCode`
match isDoExpr? doElem with
| some action =>
let action ← withRef action `(($action : $((← read).m) $type))
``(Bind.bind $action (fun ($id:ident : $type) => $k))
| none => Macro.throwErrorAt decl "unexpected kind of `do` declaration"
else
Macro.throwErrorAt decl "unexpected kind of `do` declaration"
else if kind == ``Parser.Term.doHave then
-- The `have` term is of the form `"have " >> haveDecl >> optSemicolon termParser`
let args := decl.getArgs
let args := args ++ #[mkNullNode /- optional ';' -/, k]
return mkNode `Lean.Parser.Term.«have» args
else
Macro.throwErrorAt decl "unexpected kind of `do` declaration"
def reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do
match reassign with
| `(doElem| $x:ident := $rhs) => `(let $x:ident := ensure_type_of% $x $(quote "invalid reassignment, value") $rhs; $k)
| `(doElem| $e:term := $rhs) => `(let $e:term := ensure_type_of% $e $(quote "invalid reassignment, value") $rhs; $k)
| _ =>
-- Note that `doReassignArrow` is expanded by `doReassignArrowToCode
Macro.throwErrorAt reassign "unexpected kind of `do` reassignment"
def mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do
if optIdent.isNone then
``(if $cond then $thenBranch else $elseBranch)
else
let h := optIdent[0]
``(if $h:ident : $cond then $thenBranch else $elseBranch)
def mkJoinPoint (j : Name) (ps : Array (Syntax × Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do
let pTypes ← ps.mapM fun ⟨id, useTypeOf⟩ => do if useTypeOf then `(type_of% $id) else `(_)
let ps := ps.map (·.1)
/-
We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`.
By elaborating `$k` first, we "learn" more about `$body`'s type.
For example, consider the following example `do` expression
```
def f (x : Nat) : IO Unit := do
if x > 0 then
IO.println "x is not zero" -- Error is here
IO.mkRef true
```
it is expanded into
```
def f (x : Nat) : IO Unit := do
let jp (u : Unit) : IO _ :=
IO.mkRef true;
if x > 0 then
IO.println "not zero"
jp ()
else
jp ()
```
If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit → IO (IO.Ref Bool)`.
Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit → IO Unit`.
Then, we get the expected type mismatch error at `IO.mkRef true`. -/
`(let_delayed $(← mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((← read).m) _ := $body; $k)
def mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax :=
Syntax.mkApp (mkIdentFrom ref j) args
partial def toTerm (c : Code) : M Syntax := do
let term ← go c
if let some ref := c.getRef? then
annotate ref term
else
return term
where
go (c : Code) : M Syntax := do
match c with
| .return ref val => withRef ref <| returnToTerm val
| .continue ref => withRef ref continueToTerm
| .break ref => withRef ref breakToTerm
| .action e => actionTerminalToTerm e
| .joinpoint j ps b k => mkJoinPoint j ps (← toTerm b) (← toTerm k)
| .jmp ref j args => return mkJmp ref j args
| .decl _ stx k => declToTerm stx (← toTerm k)
| .reassign _ stx k => reassignToTerm stx (← toTerm k)
| .seq stx k => seqToTerm stx (← toTerm k)
| .ite ref _ o c t e => withRef ref <| do mkIte o c (← toTerm t) (← toTerm e)
| .match ref genParam discrs optMotive alts =>
let mut termAlts := #[]
for alt in alts do
let rhs ← toTerm alt.rhs
let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref "|", mkNullNode #[alt.patterns], mkAtomFrom alt.ref "=>", rhs]
termAlts := termAlts.push termAlt
let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts]
return mkNode `Lean.Parser.Term.«match» #[mkAtomFrom ref "match", genParam, optMotive, discrs, mkAtomFrom ref "with", termMatchAlts]
def run (code : Code) (m : Syntax) (returnType : Syntax) (uvars : Array Var := #[]) (kind := Kind.regular) : MacroM Syntax :=
toTerm code { m, returnType, kind, uvars }
/-- Given
- `a` is true if the code block has a `Code.action _` exit point
- `r` is true if the code block has a `Code.return _ _` exit point
- `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point
generate Kind. See comment at the beginning of the `ToTerm` namespace. -/
def mkNestedKind (a r bc : Bool) : Kind :=
match a, r, bc with
| true, false, false => .regular
| false, true, false => .regular
| false, false, true => .nestedBC
| true, true, false => .nestedPR
| true, false, true => .nestedSBC
| false, true, true => .nestedSBC
| true, true, true => .nestedPRBC
| false, false, false => unreachable!
def mkNestedTerm (code : Code) (m : Syntax) (returnType : Syntax) (uvars : Array Var) (a r bc : Bool) : MacroM Syntax := do
ToTerm.run code m returnType uvars (mkNestedKind a r bc)
/-- Given a term `term` produced by `ToTerm.run`, pattern match on its result.
See comment at the beginning of the `ToTerm` namespace.
- `a` is true if the code block has a `Code.action _` exit point
- `r` is true if the code block has a `Code.return _ _` exit point
- `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point
The result is a sequence of `doElem` -/
def matchNestedTermResult (term : Syntax) (uvars : Array Var) (a r bc : Bool) : MacroM (List Syntax) := do
let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo)
let u ← mkTuple uvars
match a, r, bc with
| true, false, false =>
if uvars.isEmpty then
return toDoElems (← `(do $term:term))
else
return toDoElems (← `(do let r ← $term:term; $u:term := r.2; pure r.1))
| false, true, false =>
if uvars.isEmpty then
return toDoElems (← `(do let r ← $term:term; return r))
else
return toDoElems (← `(do let r ← $term:term; $u:term := r.2; return r.1))
| false, false, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| .break u => $u:term := u; break
| .continue u => $u:term := u; continue)
| true, true, false => toDoElems <$>
`(do let r ← $term:term;
match r with
| .pure a u => $u:term := u; pure a
| .return b u => $u:term := u; return b)
| true, false, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| .pureReturn a u => $u:term := u; pure a
| .break u => $u:term := u; break
| .continue u => $u:term := u; continue)
| false, true, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| .pureReturn a u => $u:term := u; return a
| .break u => $u:term := u; break
| .continue u => $u:term := u; continue)
| true, true, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| .pure a u => $u:term := u; pure a
| .return a u => $u:term := u; return a
| .break u => $u:term := u; break
| .continue u => $u:term := u; continue)
| false, false, false => unreachable!
end ToTerm
def isMutableLet (doElem : Syntax) : Bool :=
let kind := doElem.getKind
(kind == ``doLetArrow || kind == ``doLet || kind == ``doLetElse)
&&
!doElem[1].isNone
namespace ToCodeBlock
structure Context where
ref : Syntax
/-- Syntax representing the monad associated with the do notation. -/
m : Syntax
/-- Syntax to reference the result of the monadic computation performed by the do notation. -/
returnType : Syntax
mutableVars : VarSet := {}
insideFor : Bool := false
abbrev M := ReaderT Context TermElabM
def withNewMutableVars {α} (newVars : Array Var) (mutable : Bool) (x : M α) : M α :=
withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x
def checkReassignable (xs : Array Var) : M Unit := do
let throwInvalidReassignment (x : Name) : M Unit :=
throwError "`{x.simpMacroScopes}` cannot be mutated, only variables declared using `let mut` can be mutated. If you did not intent to mutate but define `{x.simpMacroScopes}`, consider using `let {x.simpMacroScopes}` instead"
let ctx ← read
for x in xs do
unless ctx.mutableVars.contains x.getId do
throwInvalidReassignment x.getId
def checkNotShadowingMutable (xs : Array Var) : M Unit := do
let throwInvalidShadowing (x : Name) : M Unit :=
throwError "mutable variable `{x.simpMacroScopes}` cannot be shadowed"
let ctx ← read
for x in xs do
if ctx.mutableVars.contains x.getId then
withRef x <| throwInvalidShadowing x.getId
def withFor {α} (x : M α) : M α :=
withReader (fun ctx => { ctx with insideFor := true }) x
structure ToForInTermResult where
uvars : Array Var
term : Syntax
def mkForInBody (_ : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do
let ctx ← read
let uvars := forInBody.uvars
let uvars := varSetToArray uvars
let term ← liftMacroM <| ToTerm.run forInBody.code ctx.m ctx.returnType uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn)
return ⟨uvars, term⟩
def ensureInsideFor : M Unit :=
unless (← read).insideFor do
throwError "invalid `do` element, it must be inside `for`"
def ensureEOS (doElems : List Syntax) : M Unit :=
unless doElems.isEmpty do
throwError "must be last element in a `do` sequence"
variable (baseId : Name) in
private partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax → StateT (List Syntax) M Syntax
| stx@(Syntax.node i k args) =>
if k == choiceKind then do
-- choice node: check that lifts are consistent
let alts ← stx.getArgs.mapM (expandLiftMethodAux inQuot inBinder · |>.run [])
let (_, lifts) := alts[0]!
unless alts.all (·.2 == lifts) do
throwErrorAt stx "cannot lift `(<- ...)` over inconsistent syntax variants, consider lifting out the binding manually"
modify (· ++ lifts)
return .node i k (alts.map (·.1))
else if liftMethodDelimiter k then
return stx
else if k == ``Parser.Term.liftMethod && !inQuot then withFreshMacroScope do
if inBinder then
throwErrorAt stx "cannot lift `(<- ...)` over a binder, this error usually happens when you are trying to lift a method nested in a `fun`, `let`, or `match`-alternative, and it can often be fixed by adding a missing `do`"
let term := args[1]!
let term ← expandLiftMethodAux inQuot inBinder term
-- keep name deterministic across choice branches
let id ← mkIdentFromRef (.num baseId (← get).length)
let auxDoElem : Syntax ← `(doElem| let $id:ident ← $term:term)
modify fun s => s ++ [auxDoElem]
return id
else do
let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot
let inBinder := inBinder || (!inQuot && liftMethodForbiddenBinder stx)
let args ← args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot) inBinder)
return Syntax.node i k args
| stx => return stx
def expandLiftMethod (doElem : Syntax) : M (List Syntax × Syntax) := do
if !hasLiftMethod doElem then
return ([], doElem)
else
let baseId ← withFreshMacroScope (MonadQuotation.addMacroScope `__do_lift)
let (doElem, doElemsNew) ← (expandLiftMethodAux baseId false false doElem).run []
return (doElemsNew, doElem)
def checkLetArrowRHS (doElem : Syntax) : M Unit := do
let kind := doElem.getKind
if kind == ``Parser.Term.doLetArrow ||
kind == ``Parser.Term.doLet ||
kind == ``Parser.Term.doLetRec ||
kind == ``Parser.Term.doHave ||
kind == ``Parser.Term.doReassign ||
kind == ``Parser.Term.doReassignArrow then
throwErrorAt doElem "invalid kind of value `{kind}` in an assignment"
/-- Generate `CodeBlock` for `doReturn` which is of the form
```
"return " >> optional termParser
```
`doElems` is only used for sanity checking. -/
def doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do
ensureEOS doElems
let argOpt := doReturn[1]
let arg ← if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0]
return mkReturn (← getRef) arg
structure Catch where
x : Syntax
optType : Syntax
codeBlock : CodeBlock
def getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : VarSet :=
let ws := tryCode.uvars
let ws := catches.foldl (init := ws) fun ws alt => union alt.codeBlock.uvars ws
let ws := match finallyCode? with
| none => ws
| some c => union c.uvars ws
ws
def tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code → Bool) : Bool :=
p tryCode.code ||
catches.any (fun «catch» => p «catch».codeBlock.code) ||
match finallyCode? with
| none => false
| some finallyCode => p finallyCode.code
mutual
/-- "Concatenate" `c` with `doSeqToCode doElems` -/
partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock :=
match doElems with
| [] => pure c
| nextDoElem :: _ => do
let k ← doSeqToCode doElems
let ref := nextDoElem
concat c ref none k
/-- Generate `CodeBlock` for `doLetArrow; doElems`
`doLetArrow` is of the form
```
"let " >> optional "mut " >> (doIdDecl <|> doPatDecl)
```
where
```
def doIdDecl := leading_parser ident >> optType >> leftArrow >> doElemParser
def doPatDecl := leading_parser termParser >> leftArrow >> doElemParser >> optional (" | " >> doSeq)
```
-/
partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do
let decl := doLetArrow[2]
if decl.getKind == ``Parser.Term.doIdDecl then
let y := decl[0]
checkNotShadowingMutable #[y]
let doElem := decl[3]
let k ← withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems)
match isDoExpr? doElem with
| some _ => return mkVarDeclCore #[y] doLetArrow k
| none =>
checkLetArrowRHS doElem
let c ← doSeqToCode [doElem]
match doElems with
| [] => pure c
| kRef::_ => concat c kRef y k
else if decl.getKind == ``Parser.Term.doPatDecl then
let pattern := decl[0]
let doElem := decl[2]
let optElse := decl[3]
if optElse.isNone then withFreshMacroScope do
let auxDo ← if isMutableLet doLetArrow then
`(do let%$doLetArrow __discr ← $doElem; let%$doLetArrow mut $pattern:term := __discr)
else
`(do let%$doLetArrow __discr ← $doElem; let%$doLetArrow $pattern:term := __discr)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
else
let contSeq ← if isMutableLet doLetArrow then
let vars ← (← getPatternVarsEx pattern).mapM fun var => `(doElem| let mut $var := $var)
pure (vars ++ doElems.toArray)
else
pure doElems.toArray
let contSeq := mkDoSeq contSeq
let elseSeq := optElse[1]
let auxDo ← `(do let%$doLetArrow __discr ← $doElem; match%$doLetArrow __discr with | $pattern:term => $contSeq | _ => $elseSeq)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo)
else
throwError "unexpected kind of `do` declaration"
partial def doLetElseToCode (doLetElse : Syntax) (doElems : List Syntax) : M CodeBlock := do
-- "let " >> optional "mut " >> termParser >> " := " >> termParser >> checkColGt >> " | " >> doSeq
let pattern := doLetElse[2]
let val := doLetElse[4]
let elseSeq := doLetElse[6]
let contSeq ← if isMutableLet doLetElse then
let vars ← (← getPatternVarsEx pattern).mapM fun var => `(doElem| let mut $var := $var)
pure (vars ++ doElems.toArray)
else
pure doElems.toArray
let contSeq := mkDoSeq contSeq
let auxDo ← `(do let __discr := $val; match __discr with | $pattern:term => $contSeq | _ => $elseSeq)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo)
/-- Generate `CodeBlock` for `doReassignArrow; doElems`
`doReassignArrow` is of the form
```
(doIdDecl <|> doPatDecl)
```
-/
partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do
let decl := doReassignArrow[0]
if decl.getKind == ``Parser.Term.doIdDecl then
let doElem := decl[3]
let y := decl[0]
let auxDo ← `(do let r ← $doElem; $y:ident := r)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
else if decl.getKind == ``Parser.Term.doPatDecl then
let pattern := decl[0]
let doElem := decl[2]
let optElse := decl[3]
if optElse.isNone then withFreshMacroScope do
let auxDo ← `(do let __discr ← $doElem; $pattern:term := __discr)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
else
throwError "reassignment with `|` (i.e., \"else clause\") is not currently supported"
else
throwError "unexpected kind of `do` reassignment"
/-- Generate `CodeBlock` for `doIf; doElems`
`doIf` is of the form
```
"if " >> optIdent >> termParser >> " then " >> doSeq
>> many (group (try (group (" else " >> " if ")) >> optIdent >> termParser >> " then " >> doSeq))
>> optional (" else " >> doSeq)
``` -/
partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do
let view := mkDoIfView doIf
let thenBranch ← doSeqToCode (getDoSeqElems view.thenBranch)
let elseBranch ← doSeqToCode (getDoSeqElems view.elseBranch)
let ite ← mkIte view.ref view.optIdent view.cond thenBranch elseBranch
concatWith ite doElems
/-- Generate `CodeBlock` for `doUnless; doElems`
`doUnless` is of the form
```
"unless " >> termParser >> "do " >> doSeq
``` -/
partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do
let cond := doUnless[1]
let doSeq := doUnless[3]
let body ← doSeqToCode (getDoSeqElems doSeq)
let unlessCode ← liftMacroM <| mkUnless cond body
concatWith unlessCode doElems
/-- Generate `CodeBlock` for `doFor; doElems`
`doFor` is of the form
```
def doForDecl := leading_parser termParser >> " in " >> withForbidden "do" termParser
def doFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq
```
-/
partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do
let doForDecls := doFor[1].getSepArgs
if doForDecls.size > 1 then
/-
Expand
```
for x in xs, y in ys do
body
```
into
```
let s := toStream ys
for x in xs do
match Stream.next? s with
| none => break
| some (y, s') =>
s := s'
body
```
-/
-- Extract second element
let doForDecl := doForDecls[1]!
unless doForDecl[0].isNone do
throwErrorAt doForDecl[0] "the proof annotation here has not been implemented yet"
let y := doForDecl[1]
let ys := doForDecl[3]
let doForDecls := doForDecls.eraseIdx 1
let body := doFor[3]
withFreshMacroScope do
/- Recall that `@` (explicit) disables `coeAtOutParam`.
We used `@` at `Stream` functions to make sure `resultIsOutParamSupport` is not used. -/
let toStreamApp ← withRef ys `(@toStream _ _ _ $ys)
let auxDo ←
`(do let mut s := $toStreamApp:term
for $doForDecls:doForDecl,* do
match @Stream.next? _ _ _ s with
| none => break
| some ($y, s') =>
s := s'
do $body)
doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)
else withRef doFor do
let h? := if doForDecls[0]![0].isNone then none else some doForDecls[0]![0][0]
let x := doForDecls[0]![1]
withRef x <| checkNotShadowingMutable (← getPatternVarsEx x)
let xs := doForDecls[0]![3]
let forElems := getDoSeqElems doFor[3]
let forInBodyCodeBlock ← withFor (doSeqToCode forElems)
let ⟨uvars, forInBody⟩ ← mkForInBody x forInBodyCodeBlock
let ctx ← read
-- semantic no-op that replaces the `uvars`' position information (which all point inside the loop)
-- with that of the respective mutable declarations outside the loop, which allows the language
-- server to identify them as conceptually identical variables
let uvars := uvars.map fun v => ctx.mutableVars.findD v.getId v
let uvarsTuple ← liftMacroM do mkTuple uvars
if hasReturn forInBodyCodeBlock.code then
let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody
let optType ← `(Option $((← read).returnType))
let forInTerm ← if let some h := h? then
annotate doFor
(← `(for_in'% $(xs) (MProd.mk (none : $optType) $uvarsTuple) fun $x $h (r : MProd $optType _) => let r := r.2; $forInBody))
else
annotate doFor
(← `(for_in% $(xs) (MProd.mk (none : $optType) $uvarsTuple) fun $x (r : MProd $optType _) => let r := r.2; $forInBody))
let auxDo ← `(do let r ← $forInTerm:term;
$uvarsTuple:term := r.2;
match r.1 with
| none => Pure.pure (ensure_expected_type% "type mismatch, `for`" PUnit.unit)
| some a => return ensure_expected_type% "type mismatch, `for`" a)
doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)
else
let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody
let forInTerm ← if let some h := h? then
annotate doFor (← `(for_in'% $(xs) $uvarsTuple fun $x $h r => $forInBody))
else
annotate doFor (← `(for_in% $(xs) $uvarsTuple fun $x r => $forInBody))
if doElems.isEmpty then
let auxDo ← `(do let r ← $forInTerm:term;
$uvarsTuple:term := r;
Pure.pure (ensure_expected_type% "type mismatch, `for`" PUnit.unit))
doSeqToCode <| getDoSeqElems (getDoSeq auxDo)
else
let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
/-- Generate `CodeBlock` for `doMatch; doElems` -/
partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do
let ref := doMatch
let genParam := doMatch[1]
let optMotive := doMatch[2]
let discrs := doMatch[3]
let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt`
let matchAlts ← matchAlts.foldlM (init := #[]) fun result matchAlt => return result ++ (← liftMacroM <| expandMatchAlt matchAlt)
let alts ← matchAlts.mapM fun matchAlt => do
let patterns := matchAlt[1][0]
let vars ← getPatternsVarsEx patterns.getSepArgs
withRef patterns <| checkNotShadowingMutable vars
let rhs := matchAlt[3]
let rhs ← doSeqToCode (getDoSeqElems rhs)
pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock }
let matchCode ← mkMatch ref genParam discrs optMotive alts
concatWith matchCode doElems
/--
Generate `CodeBlock` for `doTry; doElems`
```
def doTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally
def doCatch := leading_parser "catch " >> binderIdent >> optional (":" >> termParser) >> darrow >> doSeq
def doCatchMatch := leading_parser "catch " >> doMatchAlts
def doFinally := leading_parser "finally " >> doSeq
```
-/
partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do
let tryCode ← doSeqToCode (getDoSeqElems doTry[1])
let optFinally := doTry[3]
let catches ← doTry[2].getArgs.mapM fun catchStx : Syntax => do
if catchStx.getKind == ``Parser.Term.doCatch then
let x := catchStx[1]
if x.isIdent then
withRef x <| checkNotShadowingMutable #[x]
let optType := catchStx[2]
let c ← doSeqToCode (getDoSeqElems catchStx[4])
return { x := x, optType := optType, codeBlock := c : Catch }
else if catchStx.getKind == ``Parser.Term.doCatchMatch then
let matchAlts := catchStx[1]
let x ← `(ex)
let auxDo ← `(do match ex with $matchAlts)
let c ← doSeqToCode (getDoSeqElems (getDoSeq auxDo))
return { x := x, codeBlock := c, optType := mkNullNode : Catch }
else
throwError "unexpected kind of `catch`"
let finallyCode? ← if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1])
if catches.isEmpty && finallyCode?.isNone then
throwError "invalid `try`, it must have a `catch` or `finally`"
let ctx ← read
let ws := getTryCatchUpdatedVars tryCode catches finallyCode?
let uvars := varSetToArray ws
let a := tryCatchPred tryCode catches finallyCode? hasTerminalAction
let r := tryCatchPred tryCode catches finallyCode? hasReturn
let bc := tryCatchPred tryCode catches finallyCode? hasBreakContinue
let toTerm (codeBlock : CodeBlock) : M Syntax := do
let codeBlock ← liftM $ extendUpdatedVars codeBlock ws
liftMacroM <| ToTerm.mkNestedTerm codeBlock.code ctx.m ctx.returnType uvars a r bc
let term ← toTerm tryCode
let term ← catches.foldlM (init := term) fun term «catch» => do
let catchTerm ← toTerm «catch».codeBlock
if catch.optType.isNone then
annotate doTry (← ``(MonadExcept.tryCatch $term (fun $(«catch».x):ident => $catchTerm)))
else
let type := «catch».optType[1]
annotate doTry (← ``(tryCatchThe $type $term (fun $(«catch».x):ident => $catchTerm)))
let term ← match finallyCode? with
| none => pure term
| some finallyCode => withRef optFinally do
unless finallyCode.uvars.isEmpty do
throwError "`finally` currently does not support reassignments"
if hasBreakContinueReturn finallyCode.code then
throwError "`finally` currently does `return`, `break`, nor `continue`"
let finallyTerm ← liftMacroM <| ToTerm.run finallyCode.code ctx.m ctx.returnType {} ToTerm.Kind.regular
annotate doTry (← ``(tryFinally $term $finallyTerm))
let doElemsNew ← liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc
doSeqToCode (doElemsNew ++ doElems)
partial def doSeqToCode : List Syntax → M CodeBlock
| [] => do liftMacroM mkPureUnitAction
| doElem::doElems => withIncRecDepth <| withRef doElem do
checkMaxHeartbeats "`do`-expander"
match (← liftMacroM <| expandMacro? doElem) with
| some doElem => doSeqToCode (doElem::doElems)
| none =>
match (← liftMacroM <| expandDoIf? doElem) with
| some doElem => doSeqToCode (doElem::doElems)
| none =>
let (liftedDoElems, doElem) ← expandLiftMethod doElem
if !liftedDoElems.isEmpty then
doSeqToCode (liftedDoElems ++ [doElem] ++ doElems)
else
let ref := doElem
let k := doElem.getKind
if k == ``Parser.Term.doLet then
let vars ← getDoLetVars doElem
checkNotShadowingMutable vars
mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems)
else if k == ``Parser.Term.doHave then
let vars ← getDoHaveVars doElem
checkNotShadowingMutable vars
mkVarDeclCore vars doElem <$> (doSeqToCode doElems)
else if k == ``Parser.Term.doLetRec then
let vars ← getDoLetRecVars doElem
checkNotShadowingMutable vars
mkVarDeclCore vars doElem <$> (doSeqToCode doElems)
else if k == ``Parser.Term.doReassign then
let vars ← getDoReassignVars doElem
checkReassignable vars
let k ← doSeqToCode doElems
mkReassignCore vars doElem k
else if k == ``Parser.Term.doLetArrow then
doLetArrowToCode doElem doElems
else if k == ``Parser.Term.doLetElse then
doLetElseToCode doElem doElems
else if k == ``Parser.Term.doReassignArrow then
doReassignArrowToCode doElem doElems
else if k == ``Parser.Term.doIf then
doIfToCode doElem doElems
else if k == ``Parser.Term.doUnless then
doUnlessToCode doElem doElems
else if k == ``Parser.Term.doFor then withFreshMacroScope do
doForToCode doElem doElems
else if k == ``Parser.Term.doMatch then
doMatchToCode doElem doElems
else if k == ``Parser.Term.doTry then
doTryToCode doElem doElems
else if k == ``Parser.Term.doBreak then
ensureInsideFor
ensureEOS doElems
return mkBreak ref
else if k == ``Parser.Term.doContinue then
ensureInsideFor
ensureEOS doElems
return mkContinue ref
else if k == ``Parser.Term.doReturn then
doReturnToCode doElem doElems
else if k == ``Parser.Term.doDbgTrace then
return mkSeq doElem (← doSeqToCode doElems)
else if k == ``Parser.Term.doAssert then
return mkSeq doElem (← doSeqToCode doElems)
else if k == ``Parser.Term.doNested then
let nestedDoSeq := doElem[1]
doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems)
else if k == ``Parser.Term.doExpr then
let term := doElem[0]
if doElems.isEmpty then
return mkTerminalAction term
else
return mkSeq term (← doSeqToCode doElems)
else
throwError "unexpected do-element of kind {doElem.getKind}:\n{doElem}"
end
def run (doStx : Syntax) (m : Syntax) (returnType : Syntax) : TermElabM CodeBlock :=
(doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m, returnType }
end ToCodeBlock
@[builtin_term_elab «do»] def elabDo : TermElab := fun stx expectedType? => do
tryPostponeIfNoneOrMVar expectedType?
let bindInfo ← extractBind expectedType?
let m ← Term.exprToSyntax bindInfo.m
let returnType ← Term.exprToSyntax bindInfo.returnType
let codeBlock ← ToCodeBlock.run stx m returnType
let stxNew ← liftMacroM <| ToTerm.run codeBlock.code m returnType
trace[Elab.do] stxNew
withMacroExpansion stx stxNew <| elabTermEnsuringType stxNew bindInfo.expectedType
end Do
builtin_initialize registerTraceClass `Elab.do
private def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do
let stx := stx.setKind newKind
withRef stx `(do $stx:doElem)
@[builtin_macro Lean.Parser.Term.termFor]
def expandTermFor : Macro := toDoElem ``Parser.Term.doFor
@[builtin_macro Lean.Parser.Term.termTry]
def expandTermTry : Macro := toDoElem ``Parser.Term.doTry
@[builtin_macro Lean.Parser.Term.termUnless]
def expandTermUnless : Macro := toDoElem ``Parser.Term.doUnless
@[builtin_macro Lean.Parser.Term.termReturn]
def expandTermReturn : Macro := toDoElem ``Parser.Term.doReturn
end Lean.Elab.Term
|
{-# OPTIONS --universe-polymorphism #-}
open import Categories.Category
module Categories.Object.Coproducts {o ℓ e} (C : Category o ℓ e) where
open Category C
open import Level
import Categories.Object.Initial as Initial
import Categories.Object.BinaryCoproducts as BinaryCoproducts
open Initial C
open BinaryCoproducts C
-- this should really be 'FiniteCoproducts', no?
record Coproducts : Set (o ⊔ ℓ ⊔ e) where
field
initial : Initial
binary : BinaryCoproducts |
function [varargout] = read_nex5(filename, varargin)
% READ_NEX5 reads header or data from a Nex Technologies *.nex5 file,
% which is a file containing action-potential (spike) timestamps and waveforms
% (spike channels), event timestamps (event channels), and continuous
% variable data (continuous A/D channels).
%
% LFP and spike waveform data that is returned by this function is
% expressed in microVolt.
%
% Use as
% [hdr] = read_nex5(filename)
% [dat] = read_nex5(filename, ...)
% [dat1, dat2, dat3, hdr] = read_nex5(filename, ...)
%
% Optional arguments should be specified in key-value pairs and can be
% header structure with header information
% feedback 0 or 1
% tsonly 0 or 1, read only the timestamps and not the waveforms
% channel number, or list of numbers (that will result in multiple outputs)
% begsample number (for continuous only)
% endsample number (for continuous only)
%
% See also READ_NEX5_HEADER
%
% Copyright (C) 2020 Robert Oostenveld, Alex Kirillov
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$
% parse the optional input arguments
hdr = ft_getopt(varargin, 'header');
channel = ft_getopt(varargin, 'channel');
feedback = ft_getopt(varargin, 'feedback', false);
tsonly = ft_getopt(varargin, 'tsonly', false);
begsample = ft_getopt(varargin, 'begsample', 1);
endsample = ft_getopt(varargin, 'endsample', inf);
% start with empty return values and empty data
varargout = {};
if isempty(hdr)
if feedback, fprintf('reading header from %s\n', filename); end
hdr = read_nex5_header(filename);
if hdr.FileHeader.NumVars<1
ft_error('no channels present in file');
end
end
% use Matlab for automatic byte-ordering
fid = fopen_or_error(filename, 'r', 'ieee-le');
for i=1:length(channel)
chan = channel(i);
vh = hdr.VarHeader(chan);
clear buf
status = fseek(fid, vh.DataOffset, 'bof');
if status < 0; ft_error('error with fseek'); end
switch vh.Type
case 0
% Neurons, only timestamps
buf.ts = Nex5ReadTimestamps(fid, vh);
case 1
% Events, only timestamps
buf.ts = Nex5ReadTimestamps(fid, vh);
case 2
% Interval variables
buf.begs = Nex5ReadTimestamps(fid, vh);
buf.ends = Nex5ReadTimestamps(fid, vh);
case 3
% Waveform variables
buf.ts = Nex5ReadTimestamps(fid, vh);
if ~tsonly
if vh.ContDataType == 0
buf.dat = fread(fid, [vh.NumberOfDataPoints vh.Count], 'int16');
else
buf.dat = fread(fid, [vh.NumberOfDataPoints vh.Count], 'float32');
end
% convert the AD values to miliVolt, subsequently convert from miliVolt to microVolt
buf.dat = (buf.dat * vh.ADtoUnitsCoefficient + vh.UnitsOffset) * 1000;
end
case 4
% Population vector
ft_error('population vectors are not supported');
case 5
% Continuously recorded variables
buf.ts = Nex5ReadTimestamps(fid, vh);
if vh.ContIndexOfFirstPointInFragmentDataType == 0
buf.indx = fread(fid, [1 vh.Count], 'uint32');
else
buf.indx = fread(fid, [1 vh.Count], 'uint64');
end
if vh.Count>1 && (begsample~=1 || endsample~=inf)
ft_error('reading selected samples from multiple AD segments is not supported');
end
if ~tsonly
numsamples = min(endsample - begsample + 1, vh.NumberOfDataPoints);
status = fseek(fid, (begsample-1)*2, 'cof');
if status < 0; ft_error('error with fseek'); end
if vh.ContDataType == 0
buf.dat = fread(fid, [1 numsamples], 'int16');
else
buf.dat = fread(fid, [1 numsamples], 'float32');
end
% convert the AD values to miliVolt, subsequently convert from milliVolt to microVolt
buf.dat = (buf.dat * vh.ADtoUnitsCoefficient + vh.UnitsOffset) * 1000;
end
case 6
% Markers
buf.ts = Nex5ReadTimestamps(fid, vh);
for j=1:vh.NumberOfMarkerFields
buf.MarkerNames{j,1} = fread(fid, [1 64], 'uint8=>char');
if vh.MarkerDataType == 0
for k=1:vh.Count
buf.MarkerValues{j,k} = fread(fid, [1 vh.MarkerLength], 'uint8=>char');
end
else
buf.MarkerValues{j} = fread(fid, vh.Count, 'uint32');
end
end
otherwise
ft_error('incorrect channel type');
end % switch channel type
% return the data of this channel
varargout{i} = buf;
end % for channel
% always return the header as last
varargout{end+1} = hdr;
fclose(fid);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction to read nex5 timestamps
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ts = Nex5ReadTimestamps(fid, varHeader)
if varHeader.TimestampDataType == 0
ts = fread(fid, [1 varHeader.Count], 'int32');
else
ts = fread(fid, [1 varHeader.Count], 'int64');
end
end
|
Require Export Basics.
Require Export EnvLibA.
Require Export RelLibA.
Require Export Coq.Program.Equality.
Require Import Coq.Init.Specif.
Require Import Coq.Arith.PeanoNat.
Require Import Omega.
Require Import Coq.Lists.List.
Require Import StaticSemA.
Require Import DynamicSemA.
Require Import TRInductA.
Require Import WeakenA.
Require Import IdModTypeA.
Import ListNotations.
Module TSoundness (IdT: IdModType) <: IdModType.
Definition Id := IdT.Id.
Definition IdEqDec := IdT.IdEqDec.
Definition IdEq := IdT.IdEq.
Definition W := IdT.W.
Definition Loc_PI := IdT.Loc_PI.
Definition BInit := IdT.BInit.
Definition WP := IdT.WP.
Module WeakenI := Weaken IdT.
Export WeakenI.
(** type soundness *)
Definition SoundExp (fenv: funEnv) (env: valEnv)
(e: Exp) (t: VTyp) (n: W)
:= sigT2 (fun v: Value => ValueTyping v t)
(fun v: Value => sigT (fun n': W =>
EClosure fenv env (Conf Exp n e)
(Conf Exp n' (Val v)))).
Definition SoundPrms (fenv: funEnv) (env: valEnv)
(ps: Prms) (pt: PTyp) (n: W)
:= sigT (fun es: list Exp =>
sigT2 (isValueList2T es)
(fun vs: list Value =>
prod (PrmsTyping emptyE emptyE emptyE (PS es) pt)
(sigT (fun n': W =>
PrmsClosure fenv env (Conf Prms n ps)
(Conf Prms n' (PS es)))))).
Definition SoundFun (env: valEnv) (tenv: valTC)
(f: Fun) (t: VTyp) (n: W)
:= match f with FC fenv' fps e0 e1 x i =>
fps = tenv ->
match i with
| 0 => SoundExp fenv' env e0 t n
| S j => SoundExp ((x, FC fenv' fps e0 e1 x j) :: fenv')
env e1 t n
end
end.
Definition SoundQFun (fenv: funEnv) (env: valEnv)
(tenv: valTC) (q: QFun) (t: VTyp) (n: W)
:= sigT2 (fun f: Fun => SoundFun env tenv f t n)
(fun f: Fun => forall n':W, QFClosure fenv (Conf QFun n' q)
(Conf QFun n' (QF f))).
(*************************************************************)
Definition FunSoundness :=
fun (f: Fun) (ft: FTyp)
(k: FunTyping f ft) =>
forall env: valEnv,
MatchEnvsT ValueTyping env (extParType ft) ->
forall n: W, SoundFun env (extParType ft) f (extRetType ft) n.
Definition QFunSoundness :=
fun (ftenv: funTC) (fenv: funEnv)
(q: QFun) (ft: FTyp)
(k: QFunTyping ftenv fenv q ft) =>
MatchEnvsT FunTyping fenv ftenv ->
forall env: valEnv,
MatchEnvsT ValueTyping env (extParType ft) ->
forall n: W,
SoundQFun fenv env (extParType ft) q (extRetType ft) n.
Definition ExpSoundness :=
fun (ftenv: funTC) (tenv: valTC) (fenv: funEnv)
(e: Exp) (t: VTyp)
(k: ExpTyping ftenv tenv fenv e t) =>
MatchEnvsT FunTyping fenv ftenv ->
forall env: valEnv,
MatchEnvsT ValueTyping env tenv ->
forall n: W, SoundExp fenv env e t n.
Definition PrmsSoundness :=
fun (ftenv: funTC) (tenv: valTC) (fenv: funEnv)
(ps: Prms) (pt: PTyp)
(k: PrmsTyping ftenv tenv fenv ps pt) =>
MatchEnvsT FunTyping fenv ftenv ->
forall env: valEnv,
MatchEnvsT ValueTyping env tenv ->
forall n: W, SoundPrms fenv env ps pt n.
Definition ExpTypingSound_rect :=
ExpTyping_str_rect FunSoundness QFunSoundness
ExpSoundness PrmsSoundness.
Lemma ExpEval :
forall (ftenv: funTC) (tenv: valTC) (fenv: funEnv)
(e: Exp) (t: VTyp)
(k: ExpTyping ftenv tenv fenv e t),
ExpSoundness ftenv tenv fenv e t k.
Proof.
eapply ExpTypingSound_rect.
- (** base Par_SSL *)
unfold Par_SSL, ExpSoundness.
constructor.
- (** step Par_SSL *)
unfold Par_SSL, ExpSoundness.
intros.
constructor.
+ assumption.
+ assumption.
+ assumption.
- (** base Par_SSA *)
unfold Par_SSA, FunSoundness.
constructor.
- (** step Par_SSA *)
unfold Par_SSA, FunSoundness.
intros.
constructor.
+ assumption.
+ assumption.
+ assumption.
- (** Par_SSB *)
unfold Par_SSB, Par_SSA, FunSoundness.
intros.
econstructor.
(* eapply (Forall2BT_split FunTyping _
fenv0 fenv1 ftenv0 ftenv1 x f t). *)
+ exact m0.
+ exact m1.
+ exact k.
+ assumption.
+ assumption.
+ assumption.
+ assumption.
+ assumption.
- (** base Par_F *)
unfold FunSoundness, ExpSoundness, SoundFun.
intros.
simpl in *.
specialize (X m env X0 n).
exact X.
- (** step Par_F *)
unfold FunSoundness, ExpSoundness, SoundFun, SoundExp.
intros.
clear H.
eapply updateFEnvLemma with (x:= x)
(v1:= FC fenv tenv e0 e1 x n) (v2:= FT tenv t) in m.
specialize (X m env X1 n0).
assumption.
assumption.
- (** Par_Q - QF *)
unfold QFunSoundness, FunSoundness, SoundQFun.
intros.
destruct ft.
intros.
constructor 1 with (x:=f).
* eapply X.
exact X1.
* constructor.
- (** Par_Q - FId *)
unfold QFunSoundness, Par_SSB, FunSoundness, Par_SSA, SoundQFun.
intros.
destruct ft.
simpl.
inversion X; subst.
clear X.
simpl in *.
constructor 1 with (x:=f).
+ eapply X4.
exact X1.
+ clear X2 X3 X4.
constructor.
constructor.
constructor.
inversion m; subst.
(* rewrite H0. *)
eapply ExRelValTNone with (venv:=ls1) in H.
* eapply override_simpl3 with (env0:=(x,f)::ls3) in H.
rewrite H0.
rewrite <- H at 1.
simpl.
destruct (IdT.IdEqDec x x).
{- auto. }
{- intuition n. }
(* * apply (FT prs_type ret_type). *)
* eassumption.
(** Par_E *)
- (* modify *)
unfold ExpSoundness, SoundExp.
intros ftenv tenv fenv T1 T2 VT1 VT2 XF q H H0 env H0' n.
inversion H; subst.
destruct v.
destruct v.
inversion H1; subst.
subst T.
simpl in H2.
destruct H2.
constructor 1 with (x:=cst T2 (b_eval _ _ XF n v)).
+ constructor.
* reflexivity.
* constructor.
+ inversion H; subst.
* inversion H1; subst.
subst T.
simpl in H2.
clear H2.
constructor 1 with (x:=b_exec _ _ XF n v).
eapply StepIsEClos.
constructor.
+ inversion X; subst.
eapply ExTDefNatT with (venv:=env) (T:=T1) in X0.
* destruct X0 as [v k].
constructor 1 with (x:= cst T2 (b_eval _ _ XF n v)).
econstructor.
{- constructor. }
{- econstructor. }
{- constructor 1 with (x:=b_exec _ _ XF n v).
econstructor.
econstructor.
econstructor.
eassumption.
eapply StepIsEClos.
constructor. }
* assumption.
* assumption.
* reflexivity.
- (* return *)
unfold ExpSoundness, SoundExp.
intros G ftenv tenv fenv q t H H0 env H0' n.
inversion H; subst.
+ constructor 1 with (x:=v).
* assumption.
* constructor 1 with (x:=n).
econstructor.
{- econstructor. }
{- constructor. }
+ inversion X; subst.
eapply ExTDefVal with (venv:=env) in X0.
* destruct X0 as [v k1 k2].
constructor 1 with (x:=v).
{- assumption. }
{- constructor 1 with (x:=n).
econstructor.
+ constructor.
constructor.
eassumption.
+ eapply StepIsEClos.
constructor.
}
* auto.
- (* bindN *)
unfold ExpSoundness, SoundExp.
intros ftenv tenv fenv e1 e2 t1 t2.
intros k1 k2 IH1 IH2.
intros H0 env H0' n.
specialize (IH1 H0 env H0' n).
destruct IH1 as [v0 k3 H2].
destruct H2 as [n0 H2].
specialize (IH2 H0 env H0' n0).
destruct IH2 as [v2 k4 H3].
destruct H3 as [n2 H3].
constructor 1 with (x:=v2).
+ auto.
+ constructor 1 with (x:=n2).
eapply (EClosConcat fenv env).
* instantiate (1 := Conf Exp n0 (BindN (Val v0) e2)).
apply BindN_extended_congruence.
assumption.
* econstructor.
{- econstructor. }
{- assumption. }
- (* BindS *)
unfold ExpSoundness, SoundExp.
intros ftenv tenv fenv x e1 e2 t1 t2.
intros k1 k2 IH1 IH2.
intros H0 env H0' n.
specialize (IH1 H0 env H0' n).
destruct IH1 as [v1 k3 H1].
destruct H1 as [n0 H1].
specialize (IH2 H0 ((x, v1) :: env)).
cut (MatchEnvsT ValueTyping ((x, v1) :: env) ((x, t1) :: tenv)).
+ intro.
specialize (IH2 X n0).
destruct IH2 as [v2 k4 H2].
destruct H2 as [n1 H2].
constructor 1 with (x:=v2).
* assumption.
* constructor 1 with (x:=n1).
eapply EClosConcat.
{- instantiate (1:= (Conf Exp n0 (BindS x (Val v1) e2))).
apply BindS_extended_congruence.
assumption.
}
{- eapply EClosConcat.
+ eapply StepIsEClos.
econstructor.
+ eapply EClosConcat.
* eapply BindMS_extended_congruence.
{- reflexivity. }
{- reflexivity. }
{- rewrite app_nil_l.
eassumption.
}
* eapply StepIsEClos.
constructor.
}
+ apply updateVEnvLemma.
* assumption.
* assumption.
- (* BindMS *)
unfold ExpSoundness, SoundExp.
intros ftenv ftenvP ftenv' tenv tenvP tenv' fenv fenvP fenv' envP e t.
intros k1 k2 k3 E1 E2 E3 k4 IH.
intros H0 env H0' n.
eapply (overrideVEnvLemma envP env tenvP tenv k1) in H0'.
eapply (overrideFEnvLemma fenvP fenv ftenvP ftenv k3) in H0.
cut (FEnvTyping fenv' ftenv').
+ cut (EnvTyping (envP ++ env) tenv').
* intros H1' H1.
specialize (IH H1 (envP ++ env) H1' n).
destruct IH as [v k5 H2].
destruct H2 as [n1 H2].
constructor 1 with (x:=v).
{- auto. }
{- constructor 1 with (x:=n1).
eapply (EClosConcat fenv env).
+ eapply BindMS_extended_congruence.
* reflexivity.
* reflexivity.
* rewrite <- E3.
eassumption.
+ eapply StepIsEClos.
constructor.
}
* rewrite E1.
assumption.
+ rewrite E2.
rewrite E3.
assumption.
- (* Apply *)
unfold QFunSoundness, PrmsSoundness, ExpSoundness, SoundExp.
intros ftenv tenv fps fenv q ps pt t.
intros E1 k1 k2 k3 IH1 IH2.
intros H0 env H0' n.
cut (sigT (fun n' : W =>
(sigT (fun f: Fun =>
sigT2 (fun es: list Exp => isValueListT es)
(fun es: list Exp => prod
(EClosure fenv env (Conf Exp n (Apply q ps))
(Conf Exp n' (Apply (QF f) (PS es))))
(sigT2 (fun v : Value =>
sigT (fun n'' : W =>
EClosure fenv env
(Conf Exp n' (Apply (QF f) (PS es)))
(Conf Exp n'' (Val v))))
(fun v: Value => ValueTyping v t))))))).
intros.
+ destruct X as [n1 X].
destruct X as [f X].
destruct X as [vls k4 X].
destruct X as [H1 X].
destruct X as [v X k5].
destruct X as [n2 H2].
constructor 1 with (x:=v).
* assumption.
* constructor 1 with (x:=n2).
eapply EClosConcat.
{- eassumption. }
{- eassumption. }
+ inversion E1; subst.
clear H.
specialize (IH2 H0 env H0' n).
unfold SoundPrms in IH2.
destruct IH2 as [es H2].
destruct H2 as [vs k6 H2].
destruct H2 as [k7 H2].
destruct H2 as [n1 H2].
specialize (IH1 H0).
specialize (IH1 (mkVEnv fps vs)).
eapply matchListsAux02_T with (vs:=vs) in k7.
* eapply prmsTypingAux_T in k7 as k9.
{- unfold SoundQFun, SoundFun in IH1.
unfold SoundExp in IH1.
specialize (IH1 k9 n1).
destruct IH1 as [f H3 H1].
specialize (H1 n).
constructor 1 with (x:=n1).
constructor 1 with (x:=f).
constructor 1 with (x:=es).
+ eapply isValueList2IsValueT.
eassumption.
+ split.
* eapply EClosConcat.
{- instantiate (1:=(Conf Exp n (Apply (QF f) ps))).
eapply Apply2_extended_congruence.
assumption. }
{- eapply Apply1_extended_congruence.
assumption. }
* assert (length fps = length vs) as H5.
{- eapply prmsAux2.
eassumption. }
{- inversion k2; subst.
inversion H1; subst.
destruct f.
inversion X; subst.
specialize (H3 eq_refl).
destruct H3 as [v k8 HF].
destruct HF as [n2 HF].
constructor 1 with (x:=v).
constructor 1 with (x:=n2).
econstructor.
eapply Apply_EStep0.
eassumption.
assumption.
reflexivity.
eapply EClosConcat.
eapply BindMS_extended_congruence.
reflexivity.
reflexivity.
eapply (weaken fenv0 fenv (mkVEnv fps vs) env) in HF.
eassumption.
apply StepIsEClos.
constructor.
assumption.
specialize (H3 eq_refl).
destruct H3 as [v k8 HF].
destruct HF as [n3 HF].
constructor 1 with (x:=v).
constructor 1 with (x:=n3).
econstructor.
eapply Apply_EStep1.
eassumption.
assumption.
reflexivity.
eapply EClosConcat.
eapply BindMS_extended_congruence.
reflexivity.
reflexivity.
eapply (weaken _ fenv _ env) in HF.
eassumption.
apply StepIsEClos.
constructor.
assumption.
inversion X0.
destruct f.
inversion X; subst.
assert (findE ls1 x = None).
eapply ExRelValTNone in H.
exact H.
(* exact (FT fps t). *)
exact X1.
inversion H1; subst.
inversion X3; subst.
eapply override_simpl3 with (env0:=(x,f0)::ls3) in H4.
inversion X4; subst.
rewrite <- H4 in H6.
rewrite find_simpl0 in H6.
inversion H6; subst.
inversion X0; subst.
specialize (H3 eq_refl).
destruct H3 as [v k8 HF].
destruct HF as [n3 HF].
constructor 1 with (x:=v).
constructor 1 with (x:=n3).
econstructor.
eapply Apply_EStep0.
eassumption.
assumption.
reflexivity.
eapply EClosConcat.
eapply BindMS_extended_congruence.
reflexivity.
reflexivity.
eapply (weaken fenv0 _ _ env) in HF.
eassumption.
apply StepIsEClos.
constructor.
assumption.
specialize (H3 eq_refl).
destruct H3 as [v k8 HF].
destruct HF as [n3 HF].
constructor 1 with (x:=v).
constructor 1 with (x:=n3).
econstructor.
eapply Apply_EStep1.
eassumption.
assumption.
reflexivity.
eapply EClosConcat.
eapply BindMS_extended_congruence.
reflexivity.
reflexivity.
eapply (weaken _ (ls1 ++
(x, FC fenv0 fps e0 e1 x0 (S n2)) :: ls3) _ env) in HF.
eassumption.
apply StepIsEClos.
constructor.
assumption.
}
}
{- eapply prmsAux2.
eassumption. }
* assumption.
- (* Val *)
unfold ExpSoundness, SoundExp.
intros.
constructor 1 with (x:=v).
+ assumption.
+ constructor 1 with (x:=n).
constructor.
- (* IFThenElse *)
unfold ExpSoundness, SoundExp.
intros.
specialize (X X2 env X3 n).
destruct X as [v K X].
destruct X as [n' X].
specialize (X0 X2 env X3 n').
destruct X0 as [v0 K0 X0].
destruct X0 as [n0 X0].
specialize (X1 X2 env X3 n').
destruct X1 as [v1 K1 X1].
destruct X1 as [n1 X1].
inversion K; subst.
subst T.
destruct v as [T v].
destruct v.
unfold Bool in H.
unfold vtyp in H.
simpl in H.
inversion H; subst.
destruct v.
+ constructor 1 with (x:=v0).
assumption.
constructor 1 with (x:=n0).
eapply EClosConcat.
instantiate (1:=Conf Exp n'
(IfThenElse (Val (existT ValueI bool (Cst bool true))) e2 e3)).
eapply IfThenElse_extended_congruence.
eassumption.
econstructor.
econstructor.
eassumption.
+ constructor 1 with (x:=v1).
assumption.
constructor 1 with (x:=n1).
eapply EClosConcat.
eapply IfThenElse_extended_congruence.
eassumption.
econstructor.
econstructor.
eassumption.
- (** Par_P *)
unfold Par_SSL, ExpSoundness, PrmsSoundness, SoundExp.
intros.
dependent induction X.
constructor 1 with (x:=nil).
constructor 1 with (x:=nil).
constructor.
simpl.
auto.
split.
constructor.
constructor.
constructor 1 with (x:=n).
constructor.
(**)
clear X.
specialize (p0 X0 env X1 n).
destruct p0 as [v k1 X2].
destruct X2 as [n1 H].
inversion m; subst.
specialize (IHX X2).
specialize (IHX X0 env X1 n1).
destruct IHX as [es IHX].
destruct IHX as [vs k2 IHX].
destruct IHX as [k3 IHX].
destruct IHX as [n2 k4].
constructor 1 with (x:=(Val v::es)).
constructor 1 with (x:=v::vs).
constructor.
eapply IsValueList2T.
simpl.
inversion k2; subst.
auto.
split.
constructor.
constructor.
constructor.
assumption.
inversion k3; subst.
assumption.
constructor 1 with (x:=n2).
eapply PrmsConcat.
eapply Pars_extended_congruence2.
eassumption.
eapply Pars_extended_congruence1.
assumption.
Defined.
(************************************************************************)
Definition FunTypingSound_rect :=
FunTyping_str_rect FunSoundness QFunSoundness
ExpSoundness PrmsSoundness.
Lemma FunEval :
forall (f: Fun) (ft: FTyp)
(k: FunTyping f ft),
FunSoundness f ft k.
Proof.
eapply FunTypingSound_rect.
- (** base Par_SSL *)
unfold Par_SSL, ExpSoundness.
constructor.
- (** step Par_SSL *)
unfold Par_SSL, ExpSoundness.
intros.
constructor.
+ assumption.
+ assumption.
+ assumption.
- (** base Par_SSA *)
unfold Par_SSA, FunSoundness.
constructor.
- (** step Par_SSA *)
unfold Par_SSA, FunSoundness.
intros.
constructor.
+ assumption.
+ assumption.
+ assumption.
- (** Par_SSB *)
unfold Par_SSB, Par_SSA, FunSoundness.
intros.
econstructor.
(* eapply (Forall2BT_split FunTyping _
fenv0 fenv1 ftenv0 ftenv1 x f t). *)
+ exact m0.
+ exact m1.
+ exact k.
+ assumption.
+ assumption.
+ assumption.
+ assumption.
+ assumption.
- (** base Par_F *)
unfold FunSoundness, ExpSoundness, SoundFun.
intros.
simpl in *.
specialize (X m env X0 n).
exact X.
- (** step Par_F *)
unfold FunSoundness, ExpSoundness, SoundFun, SoundExp.
intros.
clear H.
eapply updateFEnvLemma with (x:= x)
(v1:= FC fenv tenv e0 e1 x n) (v2:= FT tenv t) in m.
specialize (X m env X1 n0).
assumption.
assumption.
- (** Par_Q - QF *)
unfold QFunSoundness, FunSoundness, SoundQFun.
intros.
destruct ft.
intros.
constructor 1 with (x:=f).
* eapply X.
exact X1.
* constructor.
- (** Par_Q - FId *)
unfold QFunSoundness, Par_SSB, FunSoundness, Par_SSA, SoundQFun.
intros.
destruct ft.
simpl.
inversion X; subst.
clear X.
simpl in *.
constructor 1 with (x:=f).
+ eapply X4.
exact X1.
+ clear X2 X3 X4.
constructor.
constructor.
constructor.
inversion m; subst.
(* rewrite H0. *)
eapply ExRelValTNone with (venv:=ls1) in H.
* eapply override_simpl3 with (env0:=(x,f)::ls3) in H.
rewrite H0.
rewrite <- H at 1.
simpl.
destruct (IdT.IdEqDec x x).
{- auto. }
{- intuition n. }
(* apply (FT prs_type ret_type). *)
* eassumption.
(** Par_E *)
- (* modify *)
unfold ExpSoundness, SoundExp.
intros ftenv tenv fenv T1 T2 VT1 VT2 XF q H H0 env H0' n.
inversion H; subst.
destruct v.
destruct v.
inversion H1; subst.
subst T.
simpl in H2.
destruct H2.
constructor 1 with (x:=cst T2 (b_eval _ _ XF n v)).
+ constructor.
* reflexivity.
* constructor.
+ inversion H; subst.
* inversion H1; subst.
subst T.
simpl in H2.
clear H2.
constructor 1 with (x:=b_exec _ _ XF n v).
eapply StepIsEClos.
constructor.
+ inversion X; subst.
eapply ExTDefNatT with (venv:=env) (T:=T1) in X0.
* destruct X0 as [v k].
constructor 1 with (x:= cst T2 (b_eval _ _ XF n v)).
econstructor.
{- constructor. }
{- econstructor. }
{- constructor 1 with (x:=b_exec _ _ XF n v).
econstructor.
econstructor.
econstructor.
eassumption.
eapply StepIsEClos.
constructor. }
* assumption.
* assumption.
* reflexivity.
- (* return *)
unfold ExpSoundness, SoundExp.
intros G ftenv tenv fenv q t H H0 env H0' n.
inversion H; subst.
+ constructor 1 with (x:=v).
* assumption.
* constructor 1 with (x:=n).
econstructor.
{- econstructor. }
{- constructor. }
+ inversion X; subst.
eapply ExTDefVal with (venv:=env) in X0.
* destruct X0 as [v k1 k2].
constructor 1 with (x:=v).
{- assumption. }
{- constructor 1 with (x:=n).
econstructor.
+ constructor.
constructor.
eassumption.
+ eapply StepIsEClos.
constructor.
}
* auto.
- (* bindN *)
unfold ExpSoundness, SoundExp.
intros ftenv tenv fenv e1 e2 t1 t2.
intros k1 k2 IH1 IH2.
intros H0 env H0' n.
specialize (IH1 H0 env H0' n).
destruct IH1 as [v0 k3 H2].
destruct H2 as [n0 H2].
specialize (IH2 H0 env H0' n0).
destruct IH2 as [v2 k4 H3].
destruct H3 as [n2 H3].
constructor 1 with (x:=v2).
+ auto.
+ constructor 1 with (x:=n2).
eapply (EClosConcat fenv env).
* instantiate (1 := Conf Exp n0 (BindN (Val v0) e2)).
apply BindN_extended_congruence.
assumption.
* econstructor.
{- econstructor. }
{- assumption. }
- (* BindS *)
unfold ExpSoundness, SoundExp.
intros ftenv tenv fenv x e1 e2 t1 t2.
intros k1 k2 IH1 IH2.
intros H0 env H0' n.
specialize (IH1 H0 env H0' n).
destruct IH1 as [v1 k3 H1].
destruct H1 as [n0 H1].
specialize (IH2 H0 ((x, v1) :: env)).
cut (MatchEnvsT ValueTyping ((x, v1) :: env) ((x, t1) :: tenv)).
+ intro.
specialize (IH2 X n0).
destruct IH2 as [v2 k4 H2].
destruct H2 as [n1 H2].
constructor 1 with (x:=v2).
* assumption.
* constructor 1 with (x:=n1).
eapply EClosConcat.
{- instantiate (1:= (Conf Exp n0 (BindS x (Val v1) e2))).
apply BindS_extended_congruence.
assumption.
}
{- eapply EClosConcat.
+ eapply StepIsEClos.
econstructor.
+ eapply EClosConcat.
* eapply BindMS_extended_congruence.
{- reflexivity. }
{- reflexivity. }
{- rewrite app_nil_l.
eassumption.
}
* eapply StepIsEClos.
constructor.
}
+ apply updateVEnvLemma.
* assumption.
* assumption.
- (* BindMS *)
unfold ExpSoundness, SoundExp.
intros ftenv ftenvP ftenv' tenv tenvP tenv' fenv fenvP fenv' envP e t.
intros k1 k2 k3 E1 E2 E3 k4 IH.
intros H0 env H0' n.
eapply (overrideVEnvLemma envP env tenvP tenv k1) in H0'.
eapply (overrideFEnvLemma fenvP fenv ftenvP ftenv k3) in H0.
cut (FEnvTyping fenv' ftenv').
+ cut (EnvTyping (envP ++ env) tenv').
* intros H1' H1.
specialize (IH H1 (envP ++ env) H1' n).
destruct IH as [v k5 H2].
destruct H2 as [n1 H2].
constructor 1 with (x:=v).
{- auto. }
{- constructor 1 with (x:=n1).
eapply (EClosConcat fenv env).
+ eapply BindMS_extended_congruence.
* reflexivity.
* reflexivity.
* rewrite <- E3.
eassumption.
+ eapply StepIsEClos.
constructor.
}
* rewrite E1.
assumption.
+ rewrite E2.
rewrite E3.
assumption.
- (* Apply *)
unfold QFunSoundness, PrmsSoundness, ExpSoundness, SoundExp.
intros ftenv tenv fps fenv q ps pt t.
intros E1 k1 k2 k3 IH1 IH2.
intros H0 env H0' n.
cut (sigT (fun n' : W =>
(sigT (fun f: Fun =>
sigT2 (fun es: list Exp => isValueListT es)
(fun es: list Exp => prod
(EClosure fenv env (Conf Exp n (Apply q ps))
(Conf Exp n' (Apply (QF f) (PS es))))
(sigT2 (fun v : Value =>
sigT (fun n'' : W =>
EClosure fenv env
(Conf Exp n' (Apply (QF f) (PS es)))
(Conf Exp n'' (Val v))))
(fun v: Value => ValueTyping v t))))))).
intros.
+ destruct X as [n1 X].
destruct X as [f X].
destruct X as [vls k4 X].
destruct X as [H1 X].
destruct X as [v X k5].
destruct X as [n2 H2].
constructor 1 with (x:=v).
* assumption.
* constructor 1 with (x:=n2).
eapply EClosConcat.
{- eassumption. }
{- eassumption. }
+ inversion E1; subst.
clear H.
specialize (IH2 H0 env H0' n).
unfold SoundPrms in IH2.
destruct IH2 as [es H2].
destruct H2 as [vs k6 H2].
destruct H2 as [k7 H2].
destruct H2 as [n1 H2].
specialize (IH1 H0).
specialize (IH1 (mkVEnv fps vs)).
eapply matchListsAux02_T with (vs:=vs) in k7.
* eapply prmsTypingAux_T in k7 as k9.
{- unfold SoundQFun, SoundFun in IH1.
unfold SoundExp in IH1.
specialize (IH1 k9 n1).
destruct IH1 as [f H3 H1].
specialize (H1 n).
constructor 1 with (x:=n1).
constructor 1 with (x:=f).
constructor 1 with (x:=es).
+ eapply isValueList2IsValueT.
eassumption.
+ split.
* eapply EClosConcat.
{- instantiate (1:=(Conf Exp n (Apply (QF f) ps))).
eapply Apply2_extended_congruence.
assumption. }
{- eapply Apply1_extended_congruence.
assumption. }
* assert (length fps = length vs) as H5.
{- eapply prmsAux2.
eassumption. }
{- inversion k2; subst.
inversion H1; subst.
destruct f.
inversion X; subst.
specialize (H3 eq_refl).
destruct H3 as [v k8 HF].
destruct HF as [n2 HF].
constructor 1 with (x:=v).
constructor 1 with (x:=n2).
econstructor.
eapply Apply_EStep0.
eassumption.
assumption.
reflexivity.
eapply EClosConcat.
eapply BindMS_extended_congruence.
reflexivity.
reflexivity.
eapply (weaken fenv0 fenv (mkVEnv fps vs) env) in HF.
eassumption.
apply StepIsEClos.
constructor.
assumption.
specialize (H3 eq_refl).
destruct H3 as [v k8 HF].
destruct HF as [n3 HF].
constructor 1 with (x:=v).
constructor 1 with (x:=n3).
econstructor.
eapply Apply_EStep1.
eassumption.
assumption.
reflexivity.
eapply EClosConcat.
eapply BindMS_extended_congruence.
reflexivity.
reflexivity.
eapply (weaken _ fenv _ env) in HF.
eassumption.
apply StepIsEClos.
constructor.
assumption.
inversion X0.
destruct f.
inversion X; subst.
assert (findE ls1 x = None).
eapply ExRelValTNone in H.
exact H.
(* exact (FT fps t).*)
exact X1.
inversion H1; subst.
inversion X3; subst.
eapply override_simpl3 with (env0:=(x,f0)::ls3) in H4.
inversion X4; subst.
rewrite <- H4 in H6.
rewrite find_simpl0 in H6.
inversion H6; subst.
inversion X0; subst.
specialize (H3 eq_refl).
destruct H3 as [v k8 HF].
destruct HF as [n3 HF].
constructor 1 with (x:=v).
constructor 1 with (x:=n3).
econstructor.
eapply Apply_EStep0.
eassumption.
assumption.
reflexivity.
eapply EClosConcat.
eapply BindMS_extended_congruence.
reflexivity.
reflexivity.
eapply (weaken fenv0 _ _ env) in HF.
eassumption.
apply StepIsEClos.
constructor.
assumption.
specialize (H3 eq_refl).
destruct H3 as [v k8 HF].
destruct HF as [n3 HF].
constructor 1 with (x:=v).
constructor 1 with (x:=n3).
econstructor.
eapply Apply_EStep1.
eassumption.
assumption.
reflexivity.
eapply EClosConcat.
eapply BindMS_extended_congruence.
reflexivity.
reflexivity.
eapply (weaken _ (ls1 ++
(x, FC fenv0 fps e0 e1 x0 (S n2)) :: ls3) _ env) in HF.
eassumption.
apply StepIsEClos.
constructor.
assumption.
}
}
{- eapply prmsAux2.
eassumption. }
* assumption.
- (* Val *)
unfold ExpSoundness, SoundExp.
intros.
constructor 1 with (x:=v).
+ assumption.
+ constructor 1 with (x:=n).
constructor.
- (* IFThenElse *)
unfold ExpSoundness, SoundExp.
intros.
specialize (X X2 env X3 n).
destruct X as [v K X].
destruct X as [n' X].
specialize (X0 X2 env X3 n').
destruct X0 as [v0 K0 X0].
destruct X0 as [n0 X0].
specialize (X1 X2 env X3 n').
destruct X1 as [v1 K1 X1].
destruct X1 as [n1 X1].
inversion K; subst.
subst T.
destruct v as [T v].
destruct v.
unfold Bool in H.
unfold vtyp in H.
simpl in H.
inversion H; subst.
destruct v.
+ constructor 1 with (x:=v0).
assumption.
constructor 1 with (x:=n0).
eapply EClosConcat.
instantiate (1:=Conf Exp n'
(IfThenElse (Val (existT ValueI bool (Cst bool true))) e2 e3)).
eapply IfThenElse_extended_congruence.
eassumption.
econstructor.
econstructor.
eassumption.
+ constructor 1 with (x:=v1).
assumption.
constructor 1 with (x:=n1).
eapply EClosConcat.
eapply IfThenElse_extended_congruence.
eassumption.
econstructor.
econstructor.
eassumption.
- (** Par_P *)
unfold Par_SSL, ExpSoundness, PrmsSoundness, SoundExp.
intros.
dependent induction X.
constructor 1 with (x:=nil).
constructor 1 with (x:=nil).
constructor.
simpl.
auto.
split.
constructor.
constructor.
constructor 1 with (x:=n).
constructor.
(**)
clear X.
specialize (p0 X0 env X1 n).
destruct p0 as [v k1 X2].
destruct X2 as [n1 H].
inversion m; subst.
specialize (IHX X2).
specialize (IHX X0 env X1 n1).
destruct IHX as [es IHX].
destruct IHX as [vs k2 IHX].
destruct IHX as [k3 IHX].
destruct IHX as [n2 k4].
constructor 1 with (x:=(Val v::es)).
constructor 1 with (x:=v::vs).
constructor.
eapply IsValueList2T.
simpl.
inversion k2; subst.
auto.
split.
constructor.
constructor.
constructor.
assumption.
inversion k3; subst.
assumption.
constructor 1 with (x:=n2).
eapply PrmsConcat.
eapply Pars_extended_congruence2.
eassumption.
eapply Pars_extended_congruence1.
assumption.
Defined.
(*********************************************************************)
Definition QFunTypingSound_rect :=
QFunTyping_str_rect FunSoundness QFunSoundness
ExpSoundness PrmsSoundness.
Lemma QFunEval :
forall (ftenv: funTC) (fenv: funEnv)
(q: QFun) (ft: FTyp)
(k: QFunTyping ftenv fenv q ft),
QFunSoundness ftenv fenv q ft k.
Proof.
eapply QFunTypingSound_rect.
- (** base Par_SSL *)
unfold Par_SSL, ExpSoundness.
constructor.
- (** step Par_SSL *)
unfold Par_SSL, ExpSoundness.
intros.
constructor.
+ assumption.
+ assumption.
+ assumption.
- (** base Par_SSA *)
unfold Par_SSA, FunSoundness.
constructor.
- (** step Par_SSA *)
unfold Par_SSA, FunSoundness.
intros.
constructor.
+ assumption.
+ assumption.
+ assumption.
- (** Par_SSB *)
unfold Par_SSB, Par_SSA, FunSoundness.
intros.
econstructor.
(* eapply (Forall2BT_split FunTyping _
fenv0 fenv1 ftenv0 ftenv1 x f t). *)
+ exact m0.
+ exact m1.
+ exact k.
+ assumption.
+ assumption.
+ assumption.
+ assumption.
+ assumption.
- (** base Par_F *)
unfold FunSoundness, ExpSoundness, SoundFun.
intros.
simpl in *.
specialize (X m env X0 n).
exact X.
- (** step Par_F *)
unfold FunSoundness, ExpSoundness, SoundFun, SoundExp.
intros.
clear H.
eapply updateFEnvLemma with (x:= x)
(v1:= FC fenv tenv e0 e1 x n) (v2:= FT tenv t) in m.
specialize (X m env X1 n0).
assumption.
assumption.
- (** Par_Q - QF *)
unfold QFunSoundness, FunSoundness, SoundQFun.
intros.
destruct ft.
intros.
constructor 1 with (x:=f).
* eapply X.
exact X1.
* constructor.
- (** Par_Q - FId *)
unfold QFunSoundness, Par_SSB, FunSoundness, Par_SSA, SoundQFun.
intros.
destruct ft.
simpl.
inversion X; subst.
clear X.
simpl in *.
constructor 1 with (x:=f).
+ eapply X4.
exact X1.
+ clear X2 X3 X4.
constructor.
constructor.
constructor.
inversion m; subst.
(* rewrite H0. *)
eapply ExRelValTNone with (venv:=ls1) in H.
* eapply override_simpl3 with (env0:=(x,f)::ls3) in H.
rewrite H0.
rewrite <- H at 1.
simpl.
destruct (IdT.IdEqDec x x).
{- auto. }
{- intuition n. }
(* apply (FT prs_type ret_type). *)
* eassumption.
(** Par_E *)
- (* modify *)
unfold ExpSoundness, SoundExp.
intros ftenv tenv fenv T1 T2 VT1 VT2 XF q H H0 env H0' n.
inversion H; subst.
destruct v.
destruct v.
inversion H1; subst.
subst T.
simpl in H2.
destruct H2.
constructor 1 with (x:=cst T2 (b_eval _ _ XF n v)).
+ constructor.
* reflexivity.
* constructor.
+ inversion H; subst.
* inversion H1; subst.
subst T.
simpl in H2.
clear H2.
constructor 1 with (x:=b_exec _ _ XF n v).
eapply StepIsEClos.
constructor.
+ inversion X; subst.
eapply ExTDefNatT with (venv:=env) (T:=T1) in X0.
* destruct X0 as [v k].
constructor 1 with (x:= cst T2 (b_eval _ _ XF n v)).
econstructor.
{- constructor. }
{- econstructor. }
{- constructor 1 with (x:=b_exec _ _ XF n v).
econstructor.
econstructor.
econstructor.
eassumption.
eapply StepIsEClos.
constructor. }
* assumption.
* assumption.
* reflexivity.
- (* return *)
unfold ExpSoundness, SoundExp.
intros G ftenv tenv fenv q t H H0 env H0' n.
inversion H; subst.
+ constructor 1 with (x:=v).
* assumption.
* constructor 1 with (x:=n).
econstructor.
{- econstructor. }
{- constructor. }
+ inversion X; subst.
eapply ExTDefVal with (venv:=env) in X0.
* destruct X0 as [v k1 k2].
constructor 1 with (x:=v).
{- assumption. }
{- constructor 1 with (x:=n).
econstructor.
+ constructor.
constructor.
eassumption.
+ eapply StepIsEClos.
constructor.
}
* auto.
- (* bindN *)
unfold ExpSoundness, SoundExp.
intros ftenv tenv fenv e1 e2 t1 t2.
intros k1 k2 IH1 IH2.
intros H0 env H0' n.
specialize (IH1 H0 env H0' n).
destruct IH1 as [v0 k3 H2].
destruct H2 as [n0 H2].
specialize (IH2 H0 env H0' n0).
destruct IH2 as [v2 k4 H3].
destruct H3 as [n2 H3].
constructor 1 with (x:=v2).
+ auto.
+ constructor 1 with (x:=n2).
eapply (EClosConcat fenv env).
* instantiate (1 := Conf Exp n0 (BindN (Val v0) e2)).
apply BindN_extended_congruence.
assumption.
* econstructor.
{- econstructor. }
{- assumption. }
- (* BindS *)
unfold ExpSoundness, SoundExp.
intros ftenv tenv fenv x e1 e2 t1 t2.
intros k1 k2 IH1 IH2.
intros H0 env H0' n.
specialize (IH1 H0 env H0' n).
destruct IH1 as [v1 k3 H1].
destruct H1 as [n0 H1].
specialize (IH2 H0 ((x, v1) :: env)).
cut (MatchEnvsT ValueTyping ((x, v1) :: env) ((x, t1) :: tenv)).
+ intro.
specialize (IH2 X n0).
destruct IH2 as [v2 k4 H2].
destruct H2 as [n1 H2].
constructor 1 with (x:=v2).
* assumption.
* constructor 1 with (x:=n1).
eapply EClosConcat.
{- instantiate (1:= (Conf Exp n0 (BindS x (Val v1) e2))).
apply BindS_extended_congruence.
assumption.
}
{- eapply EClosConcat.
+ eapply StepIsEClos.
econstructor.
+ eapply EClosConcat.
* eapply BindMS_extended_congruence.
{- reflexivity. }
{- reflexivity. }
{- rewrite app_nil_l.
eassumption.
}
* eapply StepIsEClos.
constructor.
}
+ apply updateVEnvLemma.
* assumption.
* assumption.
- (* BindMS *)
unfold ExpSoundness, SoundExp.
intros ftenv ftenvP ftenv' tenv tenvP tenv' fenv fenvP fenv' envP e t.
intros k1 k2 k3 E1 E2 E3 k4 IH.
intros H0 env H0' n.
eapply (overrideVEnvLemma envP env tenvP tenv k1) in H0'.
eapply (overrideFEnvLemma fenvP fenv ftenvP ftenv k3) in H0.
cut (FEnvTyping fenv' ftenv').
+ cut (EnvTyping (envP ++ env) tenv').
* intros H1' H1.
specialize (IH H1 (envP ++ env) H1' n).
destruct IH as [v k5 H2].
destruct H2 as [n1 H2].
constructor 1 with (x:=v).
{- auto. }
{- constructor 1 with (x:=n1).
eapply (EClosConcat fenv env).
+ eapply BindMS_extended_congruence.
* reflexivity.
* reflexivity.
* rewrite <- E3.
eassumption.
+ eapply StepIsEClos.
constructor.
}
* rewrite E1.
assumption.
+ rewrite E2.
rewrite E3.
assumption.
- (* Apply *)
unfold QFunSoundness, PrmsSoundness, ExpSoundness, SoundExp.
intros ftenv tenv fps fenv q ps pt t.
intros E1 k1 k2 k3 IH1 IH2.
intros H0 env H0' n.
cut (sigT (fun n' : W =>
(sigT (fun f: Fun =>
sigT2 (fun es: list Exp => isValueListT es)
(fun es: list Exp => prod
(EClosure fenv env (Conf Exp n (Apply q ps))
(Conf Exp n' (Apply (QF f) (PS es))))
(sigT2 (fun v : Value =>
sigT (fun n'' : W =>
EClosure fenv env
(Conf Exp n' (Apply (QF f) (PS es)))
(Conf Exp n'' (Val v))))
(fun v: Value => ValueTyping v t))))))).
intros.
+ destruct X as [n1 X].
destruct X as [f X].
destruct X as [vls k4 X].
destruct X as [H1 X].
destruct X as [v X k5].
destruct X as [n2 H2].
constructor 1 with (x:=v).
* assumption.
* constructor 1 with (x:=n2).
eapply EClosConcat.
{- eassumption. }
{- eassumption. }
+ inversion E1; subst.
clear H.
specialize (IH2 H0 env H0' n).
unfold SoundPrms in IH2.
destruct IH2 as [es H2].
destruct H2 as [vs k6 H2].
destruct H2 as [k7 H2].
destruct H2 as [n1 H2].
specialize (IH1 H0).
specialize (IH1 (mkVEnv fps vs)).
eapply matchListsAux02_T with (vs:=vs) in k7.
* eapply prmsTypingAux_T in k7 as k9.
{- unfold SoundQFun, SoundFun in IH1.
unfold SoundExp in IH1.
specialize (IH1 k9 n1).
destruct IH1 as [f H3 H1].
specialize (H1 n).
constructor 1 with (x:=n1).
constructor 1 with (x:=f).
constructor 1 with (x:=es).
+ eapply isValueList2IsValueT.
eassumption.
+ split.
* eapply EClosConcat.
{- instantiate (1:=(Conf Exp n (Apply (QF f) ps))).
eapply Apply2_extended_congruence.
assumption. }
{- eapply Apply1_extended_congruence.
assumption. }
* assert (length fps = length vs) as H5.
{- eapply prmsAux2.
eassumption. }
{- inversion k2; subst.
inversion H1; subst.
destruct f.
inversion X; subst.
specialize (H3 eq_refl).
destruct H3 as [v k8 HF].
destruct HF as [n2 HF].
constructor 1 with (x:=v).
constructor 1 with (x:=n2).
econstructor.
eapply Apply_EStep0.
eassumption.
assumption.
reflexivity.
eapply EClosConcat.
eapply BindMS_extended_congruence.
reflexivity.
reflexivity.
eapply (weaken fenv0 fenv (mkVEnv fps vs) env) in HF.
eassumption.
apply StepIsEClos.
constructor.
assumption.
specialize (H3 eq_refl).
destruct H3 as [v k8 HF].
destruct HF as [n3 HF].
constructor 1 with (x:=v).
constructor 1 with (x:=n3).
econstructor.
eapply Apply_EStep1.
eassumption.
assumption.
reflexivity.
eapply EClosConcat.
eapply BindMS_extended_congruence.
reflexivity.
reflexivity.
eapply (weaken _ fenv _ env) in HF.
eassumption.
apply StepIsEClos.
constructor.
assumption.
inversion X0.
destruct f.
inversion X; subst.
assert (findE ls1 x = None).
eapply ExRelValTNone in H.
exact H.
(* exact (FT fps t). *)
exact X1.
inversion H1; subst.
inversion X3; subst.
eapply override_simpl3 with (env0:=(x,f0)::ls3) in H4.
inversion X4; subst.
rewrite <- H4 in H6.
rewrite find_simpl0 in H6.
inversion H6; subst.
inversion X0; subst.
specialize (H3 eq_refl).
destruct H3 as [v k8 HF].
destruct HF as [n3 HF].
constructor 1 with (x:=v).
constructor 1 with (x:=n3).
econstructor.
eapply Apply_EStep0.
eassumption.
assumption.
reflexivity.
eapply EClosConcat.
eapply BindMS_extended_congruence.
reflexivity.
reflexivity.
eapply (weaken fenv0 _ _ env) in HF.
eassumption.
apply StepIsEClos.
constructor.
assumption.
specialize (H3 eq_refl).
destruct H3 as [v k8 HF].
destruct HF as [n3 HF].
constructor 1 with (x:=v).
constructor 1 with (x:=n3).
econstructor.
eapply Apply_EStep1.
eassumption.
assumption.
reflexivity.
eapply EClosConcat.
eapply BindMS_extended_congruence.
reflexivity.
reflexivity.
eapply (weaken _ (ls1 ++
(x, FC fenv0 fps e0 e1 x0 (S n2)) :: ls3) _ env) in HF.
eassumption.
apply StepIsEClos.
constructor.
assumption.
}
}
{- eapply prmsAux2.
eassumption. }
* assumption.
- (* Val *)
unfold ExpSoundness, SoundExp.
intros.
constructor 1 with (x:=v).
+ assumption.
+ constructor 1 with (x:=n).
constructor.
- (* IFThenElse *)
unfold ExpSoundness, SoundExp.
intros.
specialize (X X2 env X3 n).
destruct X as [v K X].
destruct X as [n' X].
specialize (X0 X2 env X3 n').
destruct X0 as [v0 K0 X0].
destruct X0 as [n0 X0].
specialize (X1 X2 env X3 n').
destruct X1 as [v1 K1 X1].
destruct X1 as [n1 X1].
inversion K; subst.
subst T.
destruct v as [T v].
destruct v.
unfold Bool in H.
unfold vtyp in H.
simpl in H.
inversion H; subst.
destruct v.
+ constructor 1 with (x:=v0).
assumption.
constructor 1 with (x:=n0).
eapply EClosConcat.
instantiate (1:=Conf Exp n'
(IfThenElse (Val (existT ValueI bool (Cst bool true))) e2 e3)).
eapply IfThenElse_extended_congruence.
eassumption.
econstructor.
econstructor.
eassumption.
+ constructor 1 with (x:=v1).
assumption.
constructor 1 with (x:=n1).
eapply EClosConcat.
eapply IfThenElse_extended_congruence.
eassumption.
econstructor.
econstructor.
eassumption.
- (** Par_P *)
unfold Par_SSL, ExpSoundness, PrmsSoundness, SoundExp.
intros.
dependent induction X.
constructor 1 with (x:=nil).
constructor 1 with (x:=nil).
constructor.
simpl.
auto.
split.
constructor.
constructor.
constructor 1 with (x:=n).
constructor.
(**)
clear X.
specialize (p0 X0 env X1 n).
destruct p0 as [v k1 X2].
destruct X2 as [n1 H].
inversion m; subst.
specialize (IHX X2).
specialize (IHX X0 env X1 n1).
destruct IHX as [es IHX].
destruct IHX as [vs k2 IHX].
destruct IHX as [k3 IHX].
destruct IHX as [n2 k4].
constructor 1 with (x:=(Val v::es)).
constructor 1 with (x:=v::vs).
constructor.
eapply IsValueList2T.
simpl.
inversion k2; subst.
auto.
split.
constructor.
constructor.
constructor.
assumption.
inversion k3; subst.
assumption.
constructor 1 with (x:=n2).
eapply PrmsConcat.
eapply Pars_extended_congruence2.
eassumption.
eapply Pars_extended_congruence1.
assumption.
Defined.
(*************************************************************************)
Definition PrmsTypingSound_rect :=
PrmsTyping_str_rect FunSoundness QFunSoundness
ExpSoundness PrmsSoundness.
Lemma PrmsEval :
forall (ftenv: funTC) (tenv: valTC) (fenv: funEnv)
(ps: Prms) (pt: PTyp)
(k: PrmsTyping ftenv tenv fenv ps pt),
PrmsSoundness ftenv tenv fenv ps pt k.
Proof.
eapply PrmsTypingSound_rect.
- (** base Par_SSL *)
unfold Par_SSL, ExpSoundness.
constructor.
- (** step Par_SSL *)
unfold Par_SSL, ExpSoundness.
intros.
constructor.
+ assumption.
+ assumption.
+ assumption.
- (** base Par_SSA *)
unfold Par_SSA, FunSoundness.
constructor.
- (** step Par_SSA *)
unfold Par_SSA, FunSoundness.
intros.
constructor.
+ assumption.
+ assumption.
+ assumption.
- (** Par_SSB *)
unfold Par_SSB, Par_SSA, FunSoundness.
intros.
econstructor.
(* eapply (Forall2BT_split FunTyping _
fenv0 fenv1 ftenv0 ftenv1 x f t). *)
+ exact m0.
+ exact m1.
+ exact k.
+ assumption.
+ assumption.
+ assumption.
+ assumption.
+ assumption.
- (** base Par_F *)
unfold FunSoundness, ExpSoundness, SoundFun.
intros.
simpl in *.
specialize (X m env X0 n).
exact X.
- (** step Par_F *)
unfold FunSoundness, ExpSoundness, SoundFun, SoundExp.
intros.
clear H.
eapply updateFEnvLemma with (x:= x)
(v1:= FC fenv tenv e0 e1 x n) (v2:= FT tenv t) in m.
specialize (X m env X1 n0).
assumption.
assumption.
- (** Par_Q - QF *)
unfold QFunSoundness, FunSoundness, SoundQFun.
intros.
destruct ft.
intros.
constructor 1 with (x:=f).
* eapply X.
exact X1.
* constructor.
- (** Par_Q - FId *)
unfold QFunSoundness, Par_SSB, FunSoundness, Par_SSA, SoundQFun.
intros.
destruct ft.
simpl.
inversion X; subst.
clear X.
simpl in *.
constructor 1 with (x:=f).
+ eapply X4.
exact X1.
+ clear X2 X3 X4.
constructor.
constructor.
constructor.
inversion m; subst.
(* rewrite H0. *)
eapply ExRelValTNone with (venv:=ls1) in H.
* eapply override_simpl3 with (env0:=(x,f)::ls3) in H.
rewrite H0.
rewrite <- H at 1.
simpl.
destruct (IdT.IdEqDec x x).
{- auto. }
{- intuition n. }
(* apply (FT prs_type ret_type). *)
* eassumption.
(** Par_E *)
- (* modify *)
unfold ExpSoundness, SoundExp.
intros ftenv tenv fenv T1 T2 VT1 VT2 XF q H H0 env H0' n.
inversion H; subst.
destruct v.
destruct v.
inversion H1; subst.
subst T.
simpl in H2.
destruct H2.
constructor 1 with (x:=cst T2 (b_eval _ _ XF n v)).
+ constructor.
* reflexivity.
* constructor.
+ inversion H; subst.
* inversion H1; subst.
subst T.
simpl in H2.
clear H2.
constructor 1 with (x:=b_exec _ _ XF n v).
eapply StepIsEClos.
constructor.
+ inversion X; subst.
eapply ExTDefNatT with (venv:=env) (T:=T1) in X0.
* destruct X0 as [v k].
constructor 1 with (x:= cst T2 (b_eval _ _ XF n v)).
econstructor.
{- constructor. }
{- econstructor. }
{- constructor 1 with (x:=b_exec _ _ XF n v).
econstructor.
econstructor.
econstructor.
eassumption.
eapply StepIsEClos.
constructor. }
* assumption.
* assumption.
* reflexivity.
- (* return *)
unfold ExpSoundness, SoundExp.
intros G ftenv tenv fenv q t H H0 env H0' n.
inversion H; subst.
+ constructor 1 with (x:=v).
* assumption.
* constructor 1 with (x:=n).
econstructor.
{- econstructor. }
{- constructor. }
+ inversion X; subst.
eapply ExTDefVal with (venv:=env) in X0.
* destruct X0 as [v k1 k2].
constructor 1 with (x:=v).
{- assumption. }
{- constructor 1 with (x:=n).
econstructor.
+ constructor.
constructor.
eassumption.
+ eapply StepIsEClos.
constructor.
}
* auto.
- (* bindN *)
unfold ExpSoundness, SoundExp.
intros ftenv tenv fenv e1 e2 t1 t2.
intros k1 k2 IH1 IH2.
intros H0 env H0' n.
specialize (IH1 H0 env H0' n).
destruct IH1 as [v0 k3 H2].
destruct H2 as [n0 H2].
specialize (IH2 H0 env H0' n0).
destruct IH2 as [v2 k4 H3].
destruct H3 as [n2 H3].
constructor 1 with (x:=v2).
+ auto.
+ constructor 1 with (x:=n2).
eapply (EClosConcat fenv env).
* instantiate (1 := Conf Exp n0 (BindN (Val v0) e2)).
apply BindN_extended_congruence.
assumption.
* econstructor.
{- econstructor. }
{- assumption. }
- (* BindS *)
unfold ExpSoundness, SoundExp.
intros ftenv tenv fenv x e1 e2 t1 t2.
intros k1 k2 IH1 IH2.
intros H0 env H0' n.
specialize (IH1 H0 env H0' n).
destruct IH1 as [v1 k3 H1].
destruct H1 as [n0 H1].
specialize (IH2 H0 ((x, v1) :: env)).
cut (MatchEnvsT ValueTyping ((x, v1) :: env) ((x, t1) :: tenv)).
+ intro.
specialize (IH2 X n0).
destruct IH2 as [v2 k4 H2].
destruct H2 as [n1 H2].
constructor 1 with (x:=v2).
* assumption.
* constructor 1 with (x:=n1).
eapply EClosConcat.
{- instantiate (1:= (Conf Exp n0 (BindS x (Val v1) e2))).
apply BindS_extended_congruence.
assumption.
}
{- eapply EClosConcat.
+ eapply StepIsEClos.
econstructor.
+ eapply EClosConcat.
* eapply BindMS_extended_congruence.
{- reflexivity. }
{- reflexivity. }
{- rewrite app_nil_l.
eassumption.
}
* eapply StepIsEClos.
constructor.
}
+ apply updateVEnvLemma.
* assumption.
* assumption.
- (* BindMS *)
unfold ExpSoundness, SoundExp.
intros ftenv ftenvP ftenv' tenv tenvP tenv' fenv fenvP fenv' envP e t.
intros k1 k2 k3 E1 E2 E3 k4 IH.
intros H0 env H0' n.
eapply (overrideVEnvLemma envP env tenvP tenv k1) in H0'.
eapply (overrideFEnvLemma fenvP fenv ftenvP ftenv k3) in H0.
cut (FEnvTyping fenv' ftenv').
+ cut (EnvTyping (envP ++ env) tenv').
* intros H1' H1.
specialize (IH H1 (envP ++ env) H1' n).
destruct IH as [v k5 H2].
destruct H2 as [n1 H2].
constructor 1 with (x:=v).
{- auto. }
{- constructor 1 with (x:=n1).
eapply (EClosConcat fenv env).
+ eapply BindMS_extended_congruence.
* reflexivity.
* reflexivity.
* rewrite <- E3.
eassumption.
+ eapply StepIsEClos.
constructor.
}
* rewrite E1.
assumption.
+ rewrite E2.
rewrite E3.
assumption.
- (* Apply *)
unfold QFunSoundness, PrmsSoundness, ExpSoundness, SoundExp.
intros ftenv tenv fps fenv q ps pt t.
intros E1 k1 k2 k3 IH1 IH2.
intros H0 env H0' n.
cut (sigT (fun n' : W =>
(sigT (fun f: Fun =>
sigT2 (fun es: list Exp => isValueListT es)
(fun es: list Exp => prod
(EClosure fenv env (Conf Exp n (Apply q ps))
(Conf Exp n' (Apply (QF f) (PS es))))
(sigT2 (fun v : Value =>
sigT (fun n'' : W =>
EClosure fenv env
(Conf Exp n' (Apply (QF f) (PS es)))
(Conf Exp n'' (Val v))))
(fun v: Value => ValueTyping v t))))))).
intros.
+ destruct X as [n1 X].
destruct X as [f X].
destruct X as [vls k4 X].
destruct X as [H1 X].
destruct X as [v X k5].
destruct X as [n2 H2].
constructor 1 with (x:=v).
* assumption.
* constructor 1 with (x:=n2).
eapply EClosConcat.
{- eassumption. }
{- eassumption. }
+ inversion E1; subst.
clear H.
specialize (IH2 H0 env H0' n).
unfold SoundPrms in IH2.
destruct IH2 as [es H2].
destruct H2 as [vs k6 H2].
destruct H2 as [k7 H2].
destruct H2 as [n1 H2].
specialize (IH1 H0).
specialize (IH1 (mkVEnv fps vs)).
eapply matchListsAux02_T with (vs:=vs) in k7.
* eapply prmsTypingAux_T in k7 as k9.
{- unfold SoundQFun, SoundFun in IH1.
unfold SoundExp in IH1.
specialize (IH1 k9 n1).
destruct IH1 as [f H3 H1].
specialize (H1 n).
constructor 1 with (x:=n1).
constructor 1 with (x:=f).
constructor 1 with (x:=es).
+ eapply isValueList2IsValueT.
eassumption.
+ split.
* eapply EClosConcat.
{- instantiate (1:=(Conf Exp n (Apply (QF f) ps))).
eapply Apply2_extended_congruence.
assumption. }
{- eapply Apply1_extended_congruence.
assumption. }
* assert (length fps = length vs) as H5.
{- eapply prmsAux2.
eassumption. }
{- inversion k2; subst.
inversion H1; subst.
destruct f.
inversion X; subst.
specialize (H3 eq_refl).
destruct H3 as [v k8 HF].
destruct HF as [n2 HF].
constructor 1 with (x:=v).
constructor 1 with (x:=n2).
econstructor.
eapply Apply_EStep0.
eassumption.
assumption.
reflexivity.
eapply EClosConcat.
eapply BindMS_extended_congruence.
reflexivity.
reflexivity.
eapply (weaken fenv0 fenv (mkVEnv fps vs) env) in HF.
eassumption.
apply StepIsEClos.
constructor.
assumption.
specialize (H3 eq_refl).
destruct H3 as [v k8 HF].
destruct HF as [n3 HF].
constructor 1 with (x:=v).
constructor 1 with (x:=n3).
econstructor.
eapply Apply_EStep1.
eassumption.
assumption.
reflexivity.
eapply EClosConcat.
eapply BindMS_extended_congruence.
reflexivity.
reflexivity.
eapply (weaken _ fenv _ env) in HF.
eassumption.
apply StepIsEClos.
constructor.
assumption.
inversion X0.
destruct f.
inversion X; subst.
assert (findE ls1 x = None).
eapply ExRelValTNone in H.
exact H.
(* exact (FT fps t).*)
exact X1.
inversion H1; subst.
inversion X3; subst.
eapply override_simpl3 with (env0:=(x,f0)::ls3) in H4.
inversion X4; subst.
rewrite <- H4 in H6.
rewrite find_simpl0 in H6.
inversion H6; subst.
inversion X0; subst.
specialize (H3 eq_refl).
destruct H3 as [v k8 HF].
destruct HF as [n3 HF].
constructor 1 with (x:=v).
constructor 1 with (x:=n3).
econstructor.
eapply Apply_EStep0.
eassumption.
assumption.
reflexivity.
eapply EClosConcat.
eapply BindMS_extended_congruence.
reflexivity.
reflexivity.
eapply (weaken fenv0 _ _ env) in HF.
eassumption.
apply StepIsEClos.
constructor.
assumption.
specialize (H3 eq_refl).
destruct H3 as [v k8 HF].
destruct HF as [n3 HF].
constructor 1 with (x:=v).
constructor 1 with (x:=n3).
econstructor.
eapply Apply_EStep1.
eassumption.
assumption.
reflexivity.
eapply EClosConcat.
eapply BindMS_extended_congruence.
reflexivity.
reflexivity.
eapply (weaken _ (ls1 ++
(x, FC fenv0 fps e0 e1 x0 (S n2)) :: ls3) _ env) in HF.
eassumption.
apply StepIsEClos.
constructor.
assumption.
}
}
{- eapply prmsAux2.
eassumption. }
* assumption.
- (* Val *)
unfold ExpSoundness, SoundExp.
intros.
constructor 1 with (x:=v).
+ assumption.
+ constructor 1 with (x:=n).
constructor.
- (* IFThenElse *)
unfold ExpSoundness, SoundExp.
intros.
specialize (X X2 env X3 n).
destruct X as [v K X].
destruct X as [n' X].
specialize (X0 X2 env X3 n').
destruct X0 as [v0 K0 X0].
destruct X0 as [n0 X0].
specialize (X1 X2 env X3 n').
destruct X1 as [v1 K1 X1].
destruct X1 as [n1 X1].
inversion K; subst.
subst T.
destruct v as [T v].
destruct v.
unfold Bool in H.
unfold vtyp in H.
simpl in H.
inversion H; subst.
destruct v.
+ constructor 1 with (x:=v0).
assumption.
constructor 1 with (x:=n0).
eapply EClosConcat.
instantiate (1:=Conf Exp n'
(IfThenElse (Val (existT ValueI bool (Cst bool true))) e2 e3)).
eapply IfThenElse_extended_congruence.
eassumption.
econstructor.
econstructor.
eassumption.
+ constructor 1 with (x:=v1).
assumption.
constructor 1 with (x:=n1).
eapply EClosConcat.
eapply IfThenElse_extended_congruence.
eassumption.
econstructor.
econstructor.
eassumption.
- (** Par_P *)
unfold Par_SSL, ExpSoundness, PrmsSoundness, SoundExp.
intros.
dependent induction X.
constructor 1 with (x:=nil).
constructor 1 with (x:=nil).
constructor.
simpl.
auto.
split.
constructor.
constructor.
constructor 1 with (x:=n).
constructor.
(**)
clear X.
specialize (p0 X0 env X1 n).
destruct p0 as [v k1 X2].
destruct X2 as [n1 H].
inversion m; subst.
specialize (IHX X2).
specialize (IHX X0 env X1 n1).
destruct IHX as [es IHX].
destruct IHX as [vs k2 IHX].
destruct IHX as [k3 IHX].
destruct IHX as [n2 k4].
constructor 1 with (x:=(Val v::es)).
constructor 1 with (x:=v::vs).
constructor.
eapply IsValueList2T.
simpl.
inversion k2; subst.
auto.
split.
constructor.
constructor.
constructor.
assumption.
inversion k3; subst.
assumption.
constructor 1 with (x:=n2).
eapply PrmsConcat.
eapply Pars_extended_congruence2.
eassumption.
eapply Pars_extended_congruence1.
assumption.
Defined.
(***********************************************************************)
(** not used *)
Definition SoundExpT (fenv: funEnv) (env: valEnv)
(e: Exp) (t: VTyp) (n: W)
(k: SoundExp fenv env e t n) : SoundExp fenv env e t n := k.
Definition SoundPrmsT (fenv: funEnv) (env: valEnv)
(ps: Prms) (pt: PTyp) (n: W)
(k: SoundPrms fenv env ps pt n) :
SoundPrms fenv env ps pt n := k.
Definition SoundFunT (f: Fun) (ft: FTyp) (n: W)
(k0: FunTyping f ft)
(env: valEnv)
(k: SoundFun env (extParType ft) f (extRetType ft) n) :
SoundFun env (extParType ft) f (extRetType ft) n := k.
Definition SoundQFunT (ftenv: funTC) (fenv: funEnv)
(q: QFun) (ft: FTyp) (n: W)
(k0: QFunTyping ftenv fenv q ft)
(env: valEnv)
(k: SoundQFun fenv env (extParType ft) q (extRetType ft) n) :
SoundQFun fenv env (extParType ft) q (extRetType ft) n := k.
(***)
Definition FunSoundnessO :=
fun (f: Fun) (ft: FTyp)
(k: FunTyping f ft) =>
match ft with FT tenv t =>
forall env: valEnv,
MatchEnvsT ValueTyping env tenv ->
forall n: W, SoundFun env tenv f t n
end.
Definition QFunSoundnessO :=
fun (ftenv: funTC) (fenv: funEnv)
(q: QFun) (ft: FTyp)
(k: QFunTyping ftenv fenv q ft) =>
match ft with FT tenv t =>
MatchEnvsT FunTyping fenv ftenv ->
forall env: valEnv,
MatchEnvsT ValueTyping env tenv ->
forall n: W, SoundQFun fenv env tenv q t n
end.
End TSoundness.
|
it does it all the time on the road.
It's the air passing through the incorrectly fitted tail sniffer Lambda sensor.
hi tim, im told your the man to see. i have a horrible noise coming from the car but recently i been told its the exhaust which is a custom built from powerflow. could you view a video and tell me what you think.
I am getting TRACS OFF and ABC sensor showing intermittently - Is this something you have come across ? Should I be worried or shall I just ignore drive it to Devon at the weekend and check it out with you at some later date ??
Cheers - Oh and engine mount made it oh so smooth ..
hello mate got told you are running a 400bhp volvo i have a v70r fwd manual i have an engine in my garden i want big power from just wanted to know the route you took. cheers frank.
Wombat Bomb thought you might have some useful advice re IPD front anti-roll bars: http://www.vpcuk.org/forums/showthread.php?t=28159.
If you have a few moments I would appreciate your thoughts. |
using Spark
sc = SparkContext(master="local")
path = string("file:///", ENV["SPARK_HOME"], "/README.md")
txt = text_file(sc, path)
# Normally we would use a flatmap, but currently only has map_partitions
|
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TypeFamilies #-}
module Plotting where
import Data.List (sort)
import qualified Data.Vector as Vector
import Graphics.Rendering.Chart.Easy
import Statistics.Sample (meanVariance)
{-# ANN module "HLint: ignore Reduce duplication" #-}
errBars :: Double -> Vector.Vector Double -> (Double, Double)
errBars k xs = (mean, k * stdDev)
where
(mean, var) = meanVariance xs
stdDev = sqrt var
anytimeEval :: ([(a, Double)] -> Double) -> [(a, Double)] -> [Int] -> [Double]
anytimeEval f xs ns = map eval (filter (<= length xs) ns)
where
eval n = f (take n xs)
anytimePlot :: String -> String -> [Int] -> [(String, [Double])] -> EC (Layout LogValue LogValue) ()
anytimePlot x_title y_title ns inputs = do
let xLabelShow = map (show . ceiling)
let yLabelShow = map show
let generatePlot (algName, ys) = plot $ line algName [zip (map fromIntegral ns) (map LogValue ys)]
mapM_ generatePlot inputs
layout_x_axis . laxis_generate .= autoScaledLogAxis (loga_labelf .~ xLabelShow $ def)
layout_y_axis . laxis_generate .= autoScaledLogAxis (loga_labelf .~ yLabelShow $ def)
layout_x_axis . laxis_title .= x_title
layout_y_axis . laxis_title .= y_title
oneShotPlot :: String -> String -> [(String, [(Double, (Double, Double))])] -> EC (Layout LogValue LogValue) ()
oneShotPlot x_title y_title inputs = do
let xLabelShow = map (show . ceiling)
let yLabelShow = map show
let processPoint (x, (y, dy)) = symErrPoint (LogValue x) (LogValue y) 0 (LogValue dy)
let generatePlot (algName, ps) = do
plot $ points algName $ map (\(x, (y, _)) -> (LogValue x, LogValue y)) ps
plot $ return (def & plot_errbars_values .~ map processPoint ps)
mapM_ generatePlot inputs
layout_x_axis . laxis_generate .= autoScaledLogAxis (loga_labelf .~ xLabelShow $ def)
layout_y_axis . laxis_generate .= autoScaledLogAxis (loga_labelf .~ yLabelShow $ def)
layout_x_axis . laxis_title .= x_title
layout_y_axis . laxis_title .= y_title
errorbarPlot ::
String ->
String ->
[(String, [(Double, [Double])])] ->
EC (Layout LogValue LogValue) ()
errorbarPlot x_title y_title inputs = do
let xLabelShow = map (show . ceiling)
let yLabelShow = map show
let makeBars (x, ys) = ErrPoint (ErrValue x' x' x') (ErrValue ymin y ymax)
where
x' = LogValue x
y = LogValue $ sum ys / fromIntegral (length ys)
sorted = sort ys
n = length ys
ymin = LogValue $ sorted !! (n `div` 4)
ymax = LogValue $ sorted !! (n * 3 `div` 4)
let generatePlot (algName, ps) = do
plot $ liftEC $ do
-- ensure error bars are the same color as the points
(color : _) <- liftCState $ use colors
plot_errbars_values .= map makeBars ps
plot_errbars_line_style . line_color .= color
plot $ points algName $
map (\(x, ys) -> (LogValue x, LogValue (sum ys / fromIntegral (length ys)))) ps
mapM_ generatePlot inputs
layout_x_axis . laxis_generate .= autoScaledLogAxis (loga_labelf .~ xLabelShow $ def)
layout_y_axis . laxis_generate .= autoScaledLogAxis (loga_labelf .~ yLabelShow $ def)
layout_x_axis . laxis_title .= x_title
layout_y_axis . laxis_title .= y_title
|
#include <random>
#include <math.h>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <cml/cml.h>
#include <framework/misc.h>
#include <framework/vector.h>
namespace fs = boost::filesystem;
// Our global random number generator.
static std::mt19937 rng;
namespace fw {
float distance_between_line_and_point(vector const &start,
vector const &direction, vector const &point) {
// see: http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/
vector end = start + direction;
float u = (point[0] - start[0]) * (end[0] - start[0])
+ (point[1] - start[1]) * (end[1] - start[1])
+ (point[2] - start[2]) * (end[2] - start[2]);
// this is the point on the line closest to 'point'
vector point_on_line = start + (direction * u);
// therefore, the distance is just the length of the (point - point_line_to) vector.
vector vector_to_point = point - point_on_line;
return vector_to_point.length();
}
// Gets the distance between the given line segment and point. This is different to
// distance_between_line_and_point, which looks at an infinite line, where as this one only looks
// at the given line *segment*.
float distance_between_line_segment_and_point(vector const &start,
vector const &end, vector const &point) {
// see: http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/
float u = (point[0] - start[0]) * (end[0] - start[0])
+ (point[1] - start[1]) * (end[1] - start[1])
+ (point[2] - start[2]) * (end[2] - start[2]);
if (u < 0.0f)
u = 0.0f;
if (u > 1.0f)
u = 1.0f;
// this is the point on the line closest to 'point'
vector point_on_line = start + ((end - start) * u);
// therefore, the distance is just the length of the (point - point_line_to) vector.
vector vector_to_point = point - point_on_line;
return vector_to_point.length();
}
// Returns the angle, in radians, between a and b
float angle_between(vector const &a, vector const &b) {
vector lhs = a;
vector rhs = b;
float cosangle = cml::dot(lhs.normalize(), rhs.normalize());
return acos(cosangle);
}
fw::vector point_plane_intersect(vector const &plane_pt,
vector const &plane_normal, vector const &p_start, vector const &p_dir) {
// see: http://local.wasp.uwa.edu.au/~pbourke/geometry/planeline/
vector end = p_start + p_dir;
float numerator = cml::dot(plane_normal, plane_pt - p_start);
float denominator = cml::dot(plane_normal, end - p_start);
float u = numerator / denominator;
return p_start + (p_dir * u);
}
float random() {
return static_cast<float>(rng()) / static_cast<float>(rng.max());
}
void random_initialize() {
std::random_device rd;
rng.seed(rd());
}
fw::vector get_direction_to(fw::vector const &from, fw::vector const &to,
float wrap_x, float wrap_z) {
fw::vector dir = to - from;
// if we're not wrapping, the direction is just the "simple" direction
if (wrap_x == 0 && wrap_z == 0)
return dir;
// otherwise, we'll also try in the various other directions and return the shortest one
for (int z = -1; z <= 1; z++) {
for (int x = -1; x <= 1; x++) {
fw::vector another_to(to[0] + (x * wrap_x), to[1], to[2] + (z * wrap_z));
fw::vector another_dir = another_to - from;
if (another_dir.length_squared() < dir.length_squared())
dir = another_dir;
}
}
return dir;
}
// Calculates the distance between 'from' and 'to', taking into consideration the fact that
// the world wraps at (wrap_x, wrap_z).
float calculate_distance(fw::vector const &from, fw::vector const &to,
float wrap_x, float wrap_z) {
return (get_direction_to(from, to, wrap_x, wrap_z).length());
}
}
|
Require Import Crypto.Arithmetic.PrimeFieldTheorems.
Require Import Crypto.Specific.solinas64_2e495m31_9limbs.Synthesis.
(* TODO : change this to field once field isomorphism happens *)
Definition carry :
{ carry : feBW_loose -> feBW_tight
| forall a, phiBW_tight (carry a) = (phiBW_loose a) }.
Proof.
Set Ltac Profiling.
Time synthesize_carry ().
Show Ltac Profile.
Time Defined.
Print Assumptions carry.
|
/*
Copyright (c) 2010-2012, Paul Houx - All rights reserved.
This code is intended for use with the Cinder C++ library: http://libcinder.org
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "Conversions.h"
#include <boost/algorithm/string.hpp>
#include <boost/tokenizer.hpp>
#include <map>
#include <sstream>
using namespace ci;
using namespace std;
Color Conversions::toColor( uint32_t hex )
{
float r = ( ( hex & 0x00FF0000 ) >> 16 ) / 255.0f;
float g = ( ( hex & 0x0000FF00 ) >> 8 ) / 255.0f;
float b = ( ( hex & 0x000000FF ) ) / 255.0f;
return Color( r, g, b );
}
ColorA Conversions::toColorA( uint32_t hex )
{
float a = ( ( hex & 0xFF000000 ) >> 24 ) / 255.0f;
float r = ( ( hex & 0x00FF0000 ) >> 16 ) / 255.0f;
float g = ( ( hex & 0x0000FF00 ) >> 8 ) / 255.0f;
float b = ( ( hex & 0x000000FF ) ) / 255.0f;
return ColorA( r, g, b, a );
}
int Conversions::toInt( const std::string &str )
{
int x;
std::istringstream i( str );
if( !( i >> x ) )
throw std::exception();
return x;
}
float Conversions::toFloat( const std::string &str )
{
float x;
std::istringstream i( str );
if( !( i >> x ) )
throw std::exception();
return x;
}
double Conversions::toDouble( const std::string &str )
{
double x;
std::istringstream i( str );
if( !( i >> x ) )
throw std::exception();
return x;
}
//
void Conversions::mergeNames( ci::DataSourceRef hyg, ci::DataSourceRef ciel )
{
// read star names
std::string stars = loadString( ciel );
std::vector<std::string> tokens;
std::map<uint32_t, std::string> names;
std::vector<std::string> lines;
// boost::algorithm::split( lines, stars, boost::is_any_of("\r\n"), boost::token_compress_on );
lines = ci::split( stars, "\r\n", true );
std::vector<std::string>::iterator itr;
for( itr = lines.begin(); itr != lines.end(); ++itr ) {
std::string line = boost::trim_copy( *itr );
if( line.empty() )
continue;
if( line.substr( 0, 1 ) == ";" )
continue;
try {
uint32_t hr = Conversions::toInt( itr->substr( 0, 9 ) );
boost::algorithm::split( tokens, itr->substr( 9 ), boost::is_any_of( ";" ), boost::token_compress_off );
names.insert( std::pair<uint32_t, std::string>( hr, tokens[0] ) );
}
catch( ... ) {
}
}
// merge star names with HYG
stars = loadString( hyg );
boost::algorithm::split( lines, stars, boost::is_any_of( "\n\r" ), boost::token_compress_on );
for( itr = lines.begin(); itr != lines.end(); ++itr ) {
std::string line = boost::trim_copy( *itr );
boost::algorithm::split( tokens, line, boost::is_any_of( ";" ), boost::token_compress_off );
if( tokens.size() >= 4 && !tokens[4].empty() ) {
try {
uint32_t hr = Conversions::toInt( tokens[3] );
if( !names[hr].empty() ) {
tokens[6] = names[hr];
}
}
catch( ... ) {
}
}
*itr = boost::algorithm::join( tokens, ";" );
}
stars = boost::algorithm::join( lines, "\r\n" );
DataTargetPathRef target = writeFile( hyg->getFilePath() );
OStreamRef stream = target->getStream();
stream->write( stars );
}
|
[STATEMENT]
lemma len_greater_imp_nonempty[simp]: "length l > x \<Longrightarrow> l\<noteq>[]"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. x < length l \<Longrightarrow> l \<noteq> []
[PROOF STEP]
by auto |
The stage structure is different from other games in the series . After the introduction level , the player can only choose between three Robot Masters . Defeating Cold Man unlocks Burner Man and Pirate Man ; defeating Astro Man unlocks Dynamo Man , Tengu Man , and Pirate Man ; and defeating Ground Man unlocks Magic Man and Tengu Man . Clearing one of these unlocked stages opens the way to a security room where the player must destroy a series of crystals with obtained Robot Master weapons . Bypassing all eight crystals opens the way to the fortress stages . In a similar fashion to previous installments in the series , enemies often drop bolts after they are destroyed , and these can be exchanged for various restorative items and upgrades . However , unlike in Mega Man 7 the security cavern offers a way to obtain large amounts of bolts without having to repeatedly visit stages . Some upgrades are unique to either character , such as Mega Man 's ability to call on his dog Rush to search for items , or an adaptor for Bass to combine with his wolf Treble to temporarily fly . Also distributed throughout the introduction and Robot Master levels are a collection of 100 data CDs that contain information on many prominent characters in the series . Most of the CDs are hidden either behind obstacles that need to be destroyed with a special weapon or accessed with a character @-@ specific ability , making it impossible to collect them all on a single playthrough . CDs collected in each playthrough are permanently placed in a database and remain unlocked after beating the game . Saved games are used in place of the series ' traditional password system .
|
theorem brouwer: fixes f :: "'a::euclidean_space \<Rightarrow> 'a" assumes S: "compact S" "convex S" "S \<noteq> {}" and contf: "continuous_on S f" and fim: "f ` S \<subseteq> S" obtains x where "x \<in> S" and "f x = x" |
.ds TL "X Clients"
.NH "X Windows Clients"
.PP
This chapter introduces the clients and utilities
included with X Windows for \*(CO.
.PP
.II client
.II utility
.II application
Strictly speaking, a
.I client
is a program that registers with, and runs under, the X server.
``Client'' often is used as a synonym for the term
.IR application .
This manual uses the term
.I utility
to refer to a program that helps you to manage and run the X Window System
itself; and the term
.I client
to refer to a program with which you can perform some task under
the X Window System (e.g., edit a file or play a game).
.PP
This chapter introduces the utilities and clients
included with X Windows for \*(CO.
It then gives examples of how to modify an application's appearance or
behavior by changing its resources.
.SH "X Utilities"
.PP
.II utility
.II "X^utilities"
A utility helps you to run the X Window System itself.
X Windows for \*(CO includes utilities to help run every aspect of the X system.
The following introduces them by category.
.Sh "Bit Maps"
.PP
.II "bit map"
A
.I "bit map"
is an image that is composed of black and white pixels within a defined space.
X uses bit maps extensively; for example, the shapes of the mouse cursor,
fonts of alphabetic characters, buttons, and icons are all bit maps.
.PP
.II xlogo32
X stores a bit map in the form of a array.
For example, the file
.BR /usr/X11/include/X11/bitmaps/xlogo32 ,
which is a bit map of the X logo, consists of the following:
.DM
#define xlogo32_width 32
#define xlogo32_height 32
static char xlogo32_bits[] = {
0xff, 0x00, 0x00, 0xc0, 0xfe, 0x01, 0x00, 0xc0, 0xfc, 0x03, 0x00, 0x60,
0xf8, 0x07, 0x00, 0x30, 0xf8, 0x07, 0x00, 0x18, 0xf0, 0x0f, 0x00, 0x0c,
0xe0, 0x1f, 0x00, 0x06, 0xc0, 0x3f, 0x00, 0x06, 0xc0, 0x3f, 0x00, 0x03,
0x80, 0x7f, 0x80, 0x01, 0x00, 0xff, 0xc0, 0x00, 0x00, 0xfe, 0x61, 0x00,
0x00, 0xfe, 0x31, 0x00, 0x00, 0xfc, 0x33, 0x00, 0x00, 0xf8, 0x1b, 0x00,
0x00, 0xf0, 0x0d, 0x00, 0x00, 0xf0, 0x0e, 0x00, 0x00, 0x60, 0x1f, 0x00,
0x00, 0xb0, 0x3f, 0x00, 0x00, 0x98, 0x7f, 0x00, 0x00, 0x98, 0x7f, 0x00,
0x00, 0x0c, 0xff, 0x00, 0x00, 0x06, 0xfe, 0x01, 0x00, 0x03, 0xfc, 0x03,
0x80, 0x01, 0xfc, 0x03, 0xc0, 0x00, 0xf8, 0x07, 0xc0, 0x00, 0xf0, 0x0f,
0x60, 0x00, 0xe0, 0x1f, 0x30, 0x00, 0xe0, 0x1f, 0x18, 0x00, 0xc0, 0x3f,
0x0c, 0x00, 0x80, 0x7f, 0x06, 0x00, 0x00, 0xff};
.DE
The manifest constants
.B xlogo32_width
and
.B xlogo32_height
give the width and height of the image, in pixels.
The zero-bits within the array represent white pixels, whereas the non-zero
bits represent black pixels.
.PP
If you wish, you can draw new bit maps or edit existing bitmaps.
X Windows for \*(CO includes the following tools for working with
bit maps:
.DS
.ta 0.5i 1.5i
\fBbitmap\fR Bit map editor
\fBatobm\fR Convert ASCII to an X bit-mapped image
\fBbmtoa\fR Convert an X bit-mapped image to ASCII
.DE
.II bitmap
.B bitmap
is a bit-map editor.
With it you can draw a bit-mapped image using the mouse.
It also has tools for copying or inverting regions of the bit map,
drawing geometric shapes, rotating bit maps, and the like.
.PP
.B bmtoa
converts a bit map to an ASCII format that you can edit with an ordinary
text editor.
For example, the command
.DM
bmtoa /usr/X11/include/X11/bitmaps/xlogo32
.DE
turns the bit map shown above into the following:
.DM
########----------------------##
-########---------------------##
--########-------------------##-
---########-----------------##--
---########----------------##---
----########--------------##----
-----########------------##-----
------########-----------##-----
------########----------##------
-------########--------##-------
--------########------##--------
---------########----##---------
---------########---##----------
----------########--##----------
-----------#######-##-----------
------------#####-##------------
------------####-###------------
-------------##-#####-----------
------------##-#######----------
-----------##--########---------
-----------##--########---------
----------##----########--------
---------##------########-------
--------##--------########------
-------##---------########------
------##-----------########-----
------##------------########----
-----##--------------########---
----##---------------########---
---##-----------------########--
--##-------------------########-
-##---------------------########
.DE
By default,
.B bmtoa
represents a white pixel with a hyphen `-' and a black pixel with a
pound sign `#'.
.PP
Finally,
.B atobm
turns an ASCII image into a bit map that X can use.
You could, for example, use a text editor to edit the image generated by
.BR bmtoa ,
then use
.BR atobm
to re-compile the image into bit-map format.
.PP
.II xsetroot
As a side note, you can use a bit map to ``tile'' the root window of your
screen \(em simply invoke the command
.B xsetroot
with its option
.BR bitmap .
For example, the command
.DM
xsetroot -bitmap /usr/X11/include/X11/bitmaps/xlogo32
.DE
tiles the root window with the X logo.
.Sh "Colors"
.PP
.II color
X Windows for \*(CO includes the following utilities for manipulating colors:
.DS
.ta 0.5i 1.5i
\fBshowrgb\fR Un-compile an RGB color-name data base
\fBxcmsdb\fR Manipulate xlib screen-color characterization data
\fBxstdcmap\fR X standard color-map utility
.DE
.II showrgb
.B showrgb
names the colors that the server recognizes.
.II rgb.txt
The file
.B /usr/X11/lib/rgb.txt
gives an example of its output,
and also shows colors that the X color server recognizes by default.
.PP
.II xcmsdb
.II xstdcmap
.B xcmsdb
and
.B xstdcmap
let you display and manipulate color information
within widgets and the server.
Using these utilities requires a detailed knowledge of X internals.
For details, see the entry in the Lexicon for each utility.
.Sh "Fonts"
.PP
.II font
A
.I font
is a set of bit-mapped images that form the letters of the alphabet
and commonly used punctuation marks.
X Windows for \*(CO includes the following utilities for manipulating text
fonts:
.DS
.ta 0.5i 1.5i
\fBbdftopcf\fR Generate a PCF font from a BDF file
.\" \fBfs\fR X font server
.\" \fBfsinfo\fR Display information about a font server
.\" \fBfslsfonts\fR Display a list of available fonts
.\" \fBfstobdf\fR BDF font generator
\fBmkfontdir\fR Create file fonts.dir from directory of font files
.\" \fBshowfont\fR Dump a font for the X font server
\fBxfd\fR Display all the characters in an X font
\fBxfontsel\fR Interactively select X11 fonts
\fBxlsfonts\fR List fonts being used on a server
.DE
.\"Because fonts vary in so many ways \(em for example,
.\"by style, weight, slant, size, and character set \(em a set of fonts for X
.\"can consume quite a bit of disk space.
.\".II fs
.\"Rather than have each machine reproduce all fonts, the X system uses the
.\"utility
.\".BR fs ,
.\"which is a font server.
.\".B fs
.\"receives requests for fonts from all of the X systems on a network, and returns
.\"the font in question.
.\".II "font^scalable"
.\".B fs
.\"can also turn a scalable font, which is kept in the form of a logical
.\"description rather than a bit map, into a normal set of bit-mapped images
.\"at a requested size, and return the bit-mapped font to the requester.
.\".PP
.\"Because X Windows for \*(CO does not yet support networking, you probably
.\"seldom need to invoke
.\".BR fs .
.\"You will need to do so, however, if you wish to change fonts on the fly,
.\"rather than just use the fonts that are invoked when the server comes up.
.\".PP
.\".II fsinfo
.\".II fslsfonts
.\".II showfont
.\".B fsinfo
.\"gives information about the font server to which your server is connected.
.\".B fslsfonts
.\"displays the fonts available to the font sever.
.\".B showfont
.\"displays a font via the font server.
.\"Normally, these utilities do
.\"nothing because you normally will not be running a font server.
.\".PP
.II Xconfig
.II FontPath
X reads fonts from the directories named in its
.BR FontPath ,
which is set in the file
.BR /usr/X11/lib/Xconfig .
.II fonts.dir
Each directory in the
.B FontPath
contains a file named
.BR fonts.dir ,
which gives the full, 14-part name of each font in the directory
and the file that holds it.
This is done because font files normally are compressed, and uncompressing
and searching all of the files in a directory to see if a given font was
available would be unacceptably time-consuming.
Thus, when you copy a new font into a font directory, you must modify
.BR fonts.dir ,
or X will not be able to find the font.
.II mkfontdir
The utility
.B mkfontdir
reads the fonts in a given font directory and rebuilds
.BR fonts.dir
automatically.
.PP
.II xlsfonts
The utility
.B xlsfonts
displays the full, 14-part of each font that is currently available to the
X server.
.PP
.II xfontsel
The utility
.B xfontsel
lets you select a font interactively.
It uses a series of 14 drop-down menus to help you build a font name, based
on the fonts that are available to your system.
The Lexicon entry for this utility also explains just what the elements of
a font name mean.
.PP
.II bdftopcf
.II "font^bitmap distribution format"
.II "font^portable compiled format"
.II "bitmap distribution format"
.II "portable compiled format"
.II BDF
.II PCF
Fonts can be encoded in a number of different ways.
X Windows for \*(CO uses fonts that are in the portable compiled format
(PCF).
Fonts, however, often are shipped in the bitmap distribution format (BDF).
The utility
.B bdftopcf
converts a BDF font into PCF so you can use it on your system.
.PP
.II xfd
Finally, the utility
.B xfd
displays a font.
For example, the command
.DM
xfd -fd 6x10 -center
.DE
displays the font kept in file
.BR /usr/X11/lib/fonts/misc/6x10.pcf.Z .
When you click on a cell of the display,
.B xfd
displays detailed information about the character in that cell.
For an example of a displayed font (albeit a special font), see the entry for
.B xfd
in this manual's Lexicon.
.Sh "Manipulating the Console"
.PP
The following utilities let you modify the console's appearance:
.DS
.ta 0.5i 1.5i
\fBxrefresh\fR Refresh all or part of an X screen
\fBxset\fR Set preferences for the display
\fBxsetroot\fR Set preferences for the root window
.DE
.II xrefresh
.B xrefresh
redraws a given window or the entire screen, whichever you prefer.
You can use this to redraw a window or the screen, should it become
cluttered with stuff from other, non-X processes, or should it somehow
become confused.
.PP
.II xsetroot
.II "root window"
.II "screen^background"
.B xsetroot
lets you modify the appearance of the root window \(em that is, the window
that forms the background of the screen.
You can change the window to a solid color, a pair of stippled colors, a gray
scale, or tile it with a bit-mapped image.
It also lets you change the mouse cursor that is displayed against the
root window.
.PP
.II xset
Finally, the utility
.B xset
lets you set parameters for the display, and for other input devices.
For example,
.B xset
lets you set the acceleration rate for the mouse, and the loudness of both
the key click and the bell.
To set the key click to 50% of its maximum volume, type:
.DM
xset c 50
.DE
Note that not every computer lets you reset the volume of the keyclick or bell.
For details, see the Lexicon entry for
.BR xset .
.Sh "Programming Tools"
.PP
X Windows for \*(CO includes the following tools for remaking X utilities:
.DS
.ta 0.5i 1.5i
\fBimake\fR C preprocessor interface to the \fBmake\fR utility
\fBmakedepend\fR Create dependencies in \fBmakefile\fRs
\fBmkdirhier\fR Make a directory hierarchy
\fBxmkmf\fR Create a \fBMakefile\fR from an \fBImakefile\fR
.DE
None of these tools interact with the X server; if you wish,
you can use them with your ordinary, character-based applications as well
as on X applications.
.PP
.II make
.II imake
.B imake
is a superset of the \*(CO utility
.BR make .
It understands a more complex set of dependencies than those encompassed by
.BR make 's
grammar.
These dependencies include widgets, operating system, and microprocessor.
.B imake
reads an
.BR Imakefile ,
which contains dependencies plus C-preprocessor directives.
You can define constants on the
.B imake
command line to determine what the resulting program will look like.
Note that you will seldom, if ever, need to invoke
.B imake
directly.
Usually, you will invoke it via the script
.BR xmkmf ,
which is described below.
.PP
.II makedepend
.B makedepend
reads a set of C source files and header files, and builds a table of
dependencies from them.
From this table, you can construct a
.B makefile
or an
.BR Imakefile .
.PP
.II mkdirhier
.B mkdirhier
creates a directory hierarchy.
That is, if the parent directories of a target directory do not exist,
.B mkdirhier
creates them first, then creates the directory you requested.
.PP
Finally,
.II xmkmf
.B xmkmf
is a script that invokes
.B imake
to build
.B Makefile
from an
.BR Imakefile .
It passes appropriate arguments to
.B imake
to ensure that it builds a
.B Makefile
that runs correctly on your system.
.PP
These utilities are discussed at greater length in the next chapter.
.Sh "Resources and Properties"
.PP
The following utilities help you examine and manage resources and properties:
.DS
.ta 0.5i 1.5i
\fBappres\fR List an application's resource data base
\fBeditres\fR Resource editor for X Toolkit applications
\fBlistres\fR List resources in widgets
\fBviewres\fR Graphical class browser for \fBXt\fR
\fBxprop\fR Display the X server's properties
\fBxrdb\fR Read/set the X server's resource data base
.DE
.II resource
.II appres
.B appres
prints on the standard output the resources that an application uses.
The following gives a portion of the output of the command
.BR "appres XTerm" :
.DM
*VT100*color2: green
*VT100*font5: 9x15
*VT100*color6: cyan
...
*VT100*font1: nil2
*VT100*font4: 7x13
*VT100*color5: magenta
*tekMenu*vtshow*Label: Show VT Window
...
*tekMenu*tektext3*Label: #3 Size Characters
*tekMenu.Label: Tek Options
*fontMenu*font5*Label: Large
*fontMenu*font6*Label: Huge
*fontMenu*font2*Label: Tiny
...
*mainMenu.Label: Main Options
*vtMenu*hardreset*Label: Do Full Reset
*vtMenu*scrollbar*Label: Enable Scrollbar
*vtMenu*scrollkey*Label: Scroll to Bottom on Key Press
*vtMenu*scrollttyoutput*Label: Scroll to Bottom on Tty Output
...
*vtMenu*autolinefeed*Label: Enable Auto Linefeed
*vtMenu*altscreen*Label: Show Alternate Screen
*vtMenu*appcursor*Label: Enable Application Cursor Keys
*vtMenu*softreset*Label: Do Soft Reset
*vtMenu*appkeypad*Label: Enable Application Keypad
...
*tek4014*fontSmall: 6x10
.DE
Resources are discussed in more detail below.
.PP
.B editres
is an interactive program that lets you edit an application's resources
on the fly.
By selecting options from buttons and menus, you can add or delete resources
from an application, or change a resource's value, then view the result and
dump the altered resources into a file.
In effect,
.B editres
gives you a way to edit an application's resource file interactively.
Playing with
.B editres
is a good way to learn about resources.
.PP
.II listres
.B listres
lists resources used in a widget.
For example
.DM
listres -all
.DE
prints information about all known widgets.
.PP
.II property^definition
.II xprop
In the context of X, the term
.I property
means a string that holds information about an application,
such as its color or the size of its window.
Properties are stored within the server,
so they can be read by all other clients, including the window manager.
.B xprop
displays the properties associated with a given client.
The following gives the output of
.B xprop
when invoked for the X client
.BR xclock :
.DM
WM_STATE(WM_STATE):
window state: Normal
icon window: 0x0
WM_PROTOCOLS(ATOM): protocols WM_DELETE_WINDOW
WM_CLASS(STRING) = "xclock", "XClock"
WM_HINTS(WM_HINTS):
Client accepts input or input focus: False
Initial state is Normal State.
bitmap id # to use for icon: 0x1000001
bitmap id # of mask for icon: 0x1000003
WM_NORMAL_HINTS(WM_SIZE_HINTS):
user specified location: 15, 26
user specified size: 135 by 141
window gravity: NorthWest
WM_CLIENT_MACHINE(STRING) = "chelm"
WM_COMMAND(STRING) = { "xclock", "-geometry", "135x141+15+26", \e
"-fg", "blue", "-chime", "-update", "1" }
WM_ICON_NAME(STRING) = "xclock"
WM_NAME(STRING) = "xclock"
.DE
.II xrdb
.II RESOURCE_MANAGER
.II SCREEN_RESOURCES
Finally, the utility
.B xrdb
reads and sets the X server's resource data base.
It manipulates the contents of the properties
.B RESOURCE_MANAGER
and
.BR SCREEN_RESOURCES .
Applications read these properties to obtain resources that
are common to all resources under a given server.
Note that the contents of these properties usually override what an application
may read from its defaults file.
These properties are also read by applications that do not normally read
a defaults file (e.g.,
.BR xbiff ),
and so can be used to modify them.
.PP
.B xrdb
is of particular use in a networked environment.
It lets you embed resources within your machine's server, so that every
client that appears on your machine, regardless of the machine it originates
from, conforms to the way you want it to appear.
This spares you from having to store a defaults file on every
machine from which you might invoke a client.
.PP
.B xrdb
is invoked by default by the X display manager
.BR xdm ,
which is not included with X Windows for \*(CO.
If you wish to set defaults with
.BR xrdb ,
you should call it from within the file
.BR $HOME/.xinitrc .
The next sections gives some examples of how to use
.B xrdb
to set resources.
.Sh "System Monitoring"
.PP
The following utilities help you keep an eye on your system:
.DS
.ta 0.5i 1.5i
\fBxauth\fR Display/edit authorization information
\fBxdpyinfo\fR Display information about an X server
\fBxev\fR Print contents of X events
\fBxlsatoms\fR List atoms defined on server
\fBxlsclients\fR List client applications running on a display
\fBxwininfo\fR Display information about a window
.DE
.II xauth
.B xauth
lets you create or edit an authorization file.
This file determines who from what system can execute what clients on your
system.
This utility is used mainly in networked environments, where the
question of system security becomes very important.
.PP
.II xdpyinfo
.B xdpyinfo
displays information about the X server running on your system.
The following gives a portion of its output:
.DM
name of display: :0.0
version number: 11.0
vendor string: Ready-to-Run Software, Inc.
vendor release number: 5000
maximum request size: 262140 bytes
motion buffer size: 0
bitmap unit, bit order, padding: 8, MSBFirst, 32
.DE
If your server were handling more than one display, information would be
shown for each.
.PP
.II event
An
.I event
is something that occurs on your system that sends a signal to the X server.
For example, the mouse sliding on your desk is an event, because the server
must reposition the mouse cursor.
Events are generated every time you press a mouse button,
press a key on the keyboard, or in any other way interact with your system.
.II xev
The X utility
.B xev
displays a small window on the screen, and then displays information about
every events received by the server.
.PP
.II atom
In the context of X, an
.I atom
is an elemental portion of the server that is available to clients.
For example, properties are atoms, as are the names of fonts, some static
strings, and other information.
.II xlsatoms
The X utility
.B xlsatoms
lists your server's atoms.
The following gives a portion of its output:
.DM
1 PRIMARY
2 SECONDARY
3 ARC
4 ATOM
...
9 CUT_BUFFER0
...
126 -Misc-Fixed-Medium-R-Normal--10-100-75-75-C-60-ISO8859-1
127 EditresComm
...
134 -Misc-Fixed-Bold-R-Normal--13-120-75-75-C-80-ISO8859-1
.DE
.II xlsclients
The utility
.B xlsclients
displays information about all of the clients currently running under your
server.
.PP
.II xwininfo
Finally,
.B xwininfo
displays information about a window.
The following gives a sample of its output:
.DM
xwininfo: Window id: 0x1000009 "xclock"
.sp \n(pDu
Absolute upper-left X: 18
Absolute upper-left Y: 29
Relative upper-left X: 0
Relative upper-left Y: 0
Width: 135
Height: 141
Depth: 1
Visual Class: StaticGray
Border width: 0
Class: InputOutput
...
Corners: +18+29 -647+29 -647-430 +18-430
-geometry 135x141+15+26
.DE
.Sh "Miscellaneous Utilities"
.PP
The following utilities do not fit neatly into any of the above categories.
These miscellaneous utilities, however, include some of the most useful and
interesting programs shipped with X Windows for \*(CO:
.DS
.ta 0.5i 1.5i
\fBresize\fR Set environmental variables to show window size
\fBsessreg\fR Manage utmp/wtmp entries for non-init clients
\fBstartx\fR Initiate an X session
\fBtwm\fR Tab Window Manager for the X Window System
\fBxclipboard\fR Hold multiple selections for later retrieval
\fBxcmstest\fR XCMS test program
\fBxcutsel\fR Copy text between the cut buffer and the primary selection
\fBxinit\fR Initiate the X Window System
\fBxkill\fR Kill an X client
\fBxmodmap\fR Modify X keymaps
.DE
.II startx
.II twm
.II xinit
.BR startx ,
.BR twm ,
and
.B xinit
were introduced in the previous chapter.
.PP
.II resize
The utility
.B resize
reads the size of the current
.B xvt
window, then prints onto the standard output
a shell script that, when run, sets the environmental variables
.B ROWS
and
.B COLUMNS
to reflect the size of the window.
These variables can be read by programs that run within that window,
such as screen editors, so they can size themselves properly.
.II MicroEMACS
.II vi
Note that most \*(CO programs, such as MicroEMACS and
.BR vi ,
cannot yet resize themselves.
.PP
.II sessreg
.II utmp
.B sessreg
assists with logging within the system file
.B /etc/utmp
all X clients that run under the X server.
It does nothing unless you have enabled process logging.
.PP
.II xclipboard
.II cut
.II paste
X includes a system-wide facility for cutting and pasting text.
With this, you can cut text from one window and paste it into another.
Normally, X has only one buffer into which you can store cut text.
The utility
.B xclipboard
stores an indefinite number of text ``cuttings'', and retrieve them for
repasting an indefinite number of times.
For more information on cutting and pasting, see the entry for
.B xclipboard
in this manual's Lexicon.
.PP
.II property^PRIMARY
.II PRIMARY
Earlier releases of X did not use the property
.B PRIMARY
to store cut text; rather, they stored cuttings only in a cut buffer.
If you cut and paste text between an up-to-date X client and an older one,
you may find that the older one does not reset the property
.B PRIMARY
correctly, and thus does not produce what you think it will when you cut
text under it.
.II xcutsel
.B xcutsel
copies text between a cut buffer and the property
.BR PRIMARY ,
to help keep different generations of applications synchronized.
All of the utilities and clients included with X Windows for \*(CO support
the latest implementation of X; therefore, you should not need this
utility unless you import an obsolete application from elsewhere.
.PP
.II xkill
.B xkill
kills an X program.
Note that a killed program often leaves debris in memory and on the file
system, so you should use
.B xkill
only in the direst extremity.
.PP
.II xmodmap
.II "keyboard^mapping"
The X server has its own internal keyboard mapping.
For most users, this does not create a problem, because both they
and the X server use the default U.S. keyboard mapping; however, if
you have used the \*(CO driver
.B nkb
to load a foreign keyboard or to customize a keyboard to your preferences,
this behavior of the server's can create serious difficulty.
The utility
.B xmodmap
lets you modify the mappings that the X server recognizes for the keyboard
and the mouse.
With this program, you can (for example) exchange the left mouse button with
the right mouse button, switch the
.B <ctrl>
key with the
.B <CapsLock>
key, and perform other tasks to help your system work as you prefer.
The file
.B /usr/X11/lib/.Xmodmap.ger
gives an example script that remaps the keyboard for X; in this case,
it remaps the keyboard to the German standard.
For details, see the entry for
.B xmodmap
in this manual's Lexicon.
.PP
This concludes our introduction of the utilities included with
X Windows for \*(CO.
The next section introduces clients.
.SH Clients
.PP
.II client
X Windows for \*(CO includes a selection of
\fIclients\fR \(em that is, programs that run under the X server and let
you do something that is not necessarily related to the running of X itself.
It is in the wealth of clients available for it that the true power, and
usefulness, of X becomes apparent.
.Sh "Games"
.PP
.II games
The following are just for fun:
.DS
.ta 0.5i 1.5i
\fBico\fR Animate an icosahedron or other polyhedron
\fBmaze\fR Create and solve a random maze
\fBpuzzle\fR The X scrambled-number game
\fBxeyes\fR Display two roving eyes
\fBxgas\fR Animated simulation of an ideal gas
\fBxtetris\fR Wildly amusing implementation of Tetris
.DE
.II ico
.B ico
draws a polyhedron, and bounces it around the screen.
The object can be either a wire-frame outline, or solid.
Note that unless you have a very robust system, the animation will
be rather jerky, and
.B ico
will ``suck up'' practically all of your system's computation cycles.
.PP
.II maze
.B maze
draws, and then solves, a random maze.
You cannot play this game interactively,
but it does appear exciting on the screen.
.PP
.II puzzle
.B puzzle
implements a scrambled-tile game.
It displays a window divided into 16 cells.
Fifteen of the cells contain numbered tiles, the 16th is empty.
Clicking one button scrambles the tiles.
When you click a tile, it (or its row or column) slides into the empty cell,
if possible; by maneuvering the tiles, you can un-scramble them.
When you give up, you can click another button and have
.B puzzle
un-scramble itself.
.PP
.II xeyes
.B xeyes
displays a pair of ``eyes'' on the screen.
The pupils of the ``eyes'' move to follow the mouse cursor around the screen.
.PP
.II xgas
.B xgas
models the random motion of gas molecules in a heated, divided chamber.
By setting command-line options, you can set parameters of the molecules'
movement, such as the degree of randomness with which they bounce off the
chamber's walls.
By dragging sliders, you can change the temperature of either of the
two sides of the chamber.
.PP
.II xtetris
Finally,
.B xtetris
is a implements the popular game Tetris.
.Sh "Observing the System"
.PP
In addition to the utilities that help you monitor the operation of X itself,
X Windows for \*(CO also includes two clients to help you observe your
\*(CO system:
.DS
.ta 0.5i 1.5i
\fBxbiff\fR Notify the user that mail has arrived
\fBxload\fR Display your system's load average
.DE
.II xbiff
.B xbiff
displays a bit map of an old-fashioned mailbox.
When you receive mail, the flag on the mailbox pops up.
.PP
.II xload
.B xload
displays a histogram \(em that is, a bar graph \(em
that shows the load on your system.
Every few seconds,
it measures activity on your system and adds a new bar to the graph.
You can use client to measure roughly how much in the way of system
resources a given program consumes.
.Sh "Pretty Pictures"
.PP
The following clients show some of the graphics capabilities of X:
.DS
.ta 0.5i 1.5i
\fBxlogo\fR Display the X Window System logo
\fBxmag\fR Magnify a part of the screen
\fBxgc\fR X graphics demonstration
.DE
.II xlogo
.B xlogo
simply displays the X logo in a window.
This is not a bit-mapped image, because when you resize the window, the
X logo changes size to match it.
.PP
.II xmag
.B xmag
magnifies part of the screen.
It translates each pixel of the magnified portion of the screen into a cell
in a grid.
With
.BR xmag ,
you can see exactly how an image is built of a pixel map.
.PP
.II xgc
Finally,
.B xgc
demonstrates X graphics.
It displays a screen with a great number of buttons and sliders on it.
By pressing buttons, you can construct images and play with X's graphics
capabilities.
Playing with
.B xgc
is a good way to learn about X graphics.
.Sh "Timepieces"
.PP
X helps you keep track of the time:
.DS
.ta 0.5i 1.5i
\fBoclock\fR Display an analogue clock
\fBxclock\fR Display a clock
.DE
.II xclock
.II oclock
Both of these clients display a clock on the screen, which
displays the time as your system understands it.
These clients differ mainly in the shape of their windows, and in the fact that
.B xclock
offers some extra features \(em it can display a digital clock,
and ``chime'' on the hour and half-hour, if you wish.
Most users permanently display either
.B oclock
or
.B xclock
on their X screen.
.Sh "Tools"
.PP
Finally, the following clients do not fall into any of the above categories.
These include some of the most useful and interesting of the X programs
included with X Windows for \*(CO:
.DS
.ta 0.5i 1.5i
\fBxcalc\fR Scientific calculator for X
\fBxedit\fR Simple text editor for X
\fBxpr\fR Print a dump of an X window
\fBxterm\fR Terminal emulator for X
\fBxvt\fR VT100 emulator
\fBxwd\fR Dump an image of an X window
\fBxwud\fR Un-dump a window image
.DE
.II xcalc
.II "Texas Instruments"
.II "Hewlett-Packard"
.II calculator
.B xcalc
displays a picture of a scientific calculator, either a
Texas Instruments 30 or a Hewlett-Packard 10C, whichever you prefer.
You can use the mouse to press the buttons on the calculator and so perform
computations, just as with a real calculator.
The virtual calculator implements most of the features of a real
scientific calculator \(em although clicking virtual buttons with a mouse
is more difficult than pressing real buttons with your fingers.
.PP
.II xedit
.B xedit
is a simple text editor for X.
Its default keystrokes closely resemble those used by \*(ME,
with the exception that
.B xedit
supports only one window and buffer at a time.
(Of course, under X this is not much of a restriction, because you can
invoke multiple
.B xedit
sessions and cut-and-paste among the windows.)
.PP
.II xvt
.II VT-100
.B xvt
emulated a DEC VT-100 terminal.
It opens a window, logs into your system from it via a pseudo-tty,
while emluating a VT-100 terminal.
Normally, you will run a shell in this window, although you can invoke
.B xvt
to run a \*(CO program (such as an editor or a data-entry program)
instead of shell \(em just as if you were logging in from another terminal.
On a networked X system, you can have, on one screen, multiple
.B xvt
windows, each logged into a different system.
You can also use X's cut-and-paste facility to cut text from one terminal
window and paste it into another.
.PP
.II xterm
.B xterm
is an expanded \(em and more robust \(em version of
.BR xvt .
It emulates a Tektronix terminal as well as a VT-100.
It also includes a number of features that let you set colors and features
more easily.
Note that unlike
.BR xvt ,
.B xterm
emulates the VT-100's graphics characters; thus, you can display such
\*(CO programs as
.B vsh
and have them appear the same (or almost the same) as they do when shown
through the ordinary, non-X console interface.
.PP
.II xwd
.II xwud
.B xwd
dumps an image of a window into a file.
You can select a window by name, or dump the root window \(em which, in effect,
saves an image of the entire screen (including menus).
The program
.B xwud
un-dumps a dumped image, by displaying it in a window.
.PP
.II xpr
.B xpr
prints an image dumped by
.BR xwd .
By default, it generates PostScript, although you can instruct it to generate
code for a variety of other printers as well.
.PP
For what it's worth, the images in this manual were captured with
.BR xwd ,
then post-processed with
.BR xpr .
The PostScript output of
.B xpr
was edited slightly by hand, then patched into the manual's
.B troff
sources by using a set of specially written
.B troff
macros.
.SH "Customizing X Programs"
.PP
As noted in the previous chapter, you can customize an X application through
any of three ways:
(1) by setting command-line options, (2) by modifying its defaults file, or
(3) by modifying the X server's resource data base.
.PP
.II resource
The Lexicon entry for an application describes the command-line options that
are available with that application.
These work in exactly the same way as with any other \*(CO application,
and are largely self-explanatory.
Methods 2 and 3, however, depend upon setting
.IR resources ,
which can be rather tricky.
.Sh "Resources"
.PP
.II widget
As explained in the previous chapter, most X applications are constructed
in whole or in part from
.IR widgets .
A widget bundles a a graphical image with a routine that
invokes an action when a selected event occur.
For example, a widget may dictate that when a button (the graphical
image) is clicked (the event), a menu appears (the invoked action).
.PP
.II "widget class"
Widgets often are built out of other widgets.
A widget that comprises part of one or more other widgets is called a
.IR "widget class" .
.PP
.II resource^definition
A
.I resource
is an aspect of a widget, such as its color, size, or shape.
The syntax of a resource string mirrors the structure of a widget, as follows:
.DS
\fB[\fIapp\^\fB]*|.[\fIclass\fB*|.[...*|. ...]]*|.[\fIresource\^\fB]:\fIvalue\fR
.DE
.I app
names the application in question.
If no application is named and the resource is in the X server's resource
data base, then it applies to all applications.
If, however, no application is named and the resource is in an application's
defaults file, the resource applies only to the application in question.
.PP
.I class
names a widget class.
A widget class can itself be built out of other widget classes, so a
resource string can be an indefinite number of classes.
.PP
.I resource
names the particular resource being set.
.PP
Finally,
.I value
gives the value to which you are setting
.IR resource .
This can be a Boolean setting (\fBTrue\fR or \fBFalse\fR), a number, or a
string, depending on the aspect being modified.
.PP
The elements of a resource are linked by either a period `.' or an asterisk `*'.
A period binds tightly:
that is, no widget classes can intervene between two classes named in the
resource.
An asterisk binds loosely:
that is, an indefinite number of widget classes can come between the two
widget classes so named.
.PP
.II XCalc
For example, the following gives two lines from the file
.BR /usr/X11/lib/app-defaults/XCalc :
.DM
*Font: -*-helvetica-medium-r-normal--*-100-*-*-*-*-*-*
*bevel.screen.LCD.Font: -*-helvetica-bold-r-normal--*-120-*-*-*-*-*-*
.DE
The first line sets the
.B Font
for every widget (as indicated by the single preceding asterisk)
to ten-point Helvetica medium.
The second line overrides this default to set the
.B Font
within the widget
.B bevel.screen.LCD
(which is the liquid-crystal display within calculator's ``screen'')
to 12-point Helvetica bold.
A
.B Font
widget naturally must be set to a string.
.PP
The following gives two more resources from
.BR XCalc :
.DM
*ti.bevel.screen.LCD.width: 108
*hp.bevel.screen.LCD.width: 180
.DE
The first line sets the width of the virtual liquid-crystal display for the
Texas Instruments calculator; the second gives the same for the
Hewlett-Packard calculator.
Here, the use of the period to bind tightly the classes of widget
ensures that the dimensions are exactly on the correct virtual calculator.
As you can see, a
.B width
resource requires a dimension, usually pixels.
.Sh "Modifying Applications"
.PP
Before we begin, the following examples involve editing files that define
how X functions.
Before you edit any file, \fImake a backup copy!\fR
.II cul-de-sac
This will let you back out of any \fIcul-de-sac\fR you may get yourself into
through error or mishap.
.PP
.II xbiff
To begin, you will recall that the client
.B xbiff
displays on the screen a small window that contains
a bit map of an old-fashioned mailbox.
When new mail arrives, the bit map changes to one with the flag popped up
that is displayed in reverse video.
.PP
X Windows for \*(CO comes with many bit-mapped images that you can use
with existing applications.
.II mailfull
.II mailempty
Two, named
.B mailfull
and
.BR mailempty ,
respectively show a full and empty mail in-tray, much like you may have
on your desk.
Suppose, for the sake of argument, that you wanted to use these bit-mapped
images in place of the default mailboxes.
You can do this by resetting the appropriate resources, and commanding
.B xbiff
to use them instead of its built-in defaults.
.PP
The first step is to check the Lexicon entry for
.BR xbiff .
Among other things, this names the resources that
.BR xbiff
uses.
This entry shows, among many others, the following resources:
.IP "\fBfullPixmap(\fRclass \fBPixmap)\fR"
Name the bit map to display when mail arrives.
.IP "\fBfullPixmapMask(\fRclass \fBPixmapMask)\fR"
Name the mask for the bit map to display when mail arrives.
.IP "\fBemptyPixmap(\fRclass \fBPixmap)\fR"
Name the bit map to display when no new mail is present.
.IP "\fBemptyPixmapMask(\fRclass \fBPixmapMask)\fR"
Name the mask for the bit map to display when no new mail is present.
.PP
.II PixMap
These look like the ones we need to modify.
The first part of each entry names the widget; its class is given in
parentheses.
.PP
The next step is to write the resources that we want to use.
These are as follows:
.DM
xbiff*fullPixmap:mailfull
xbiff*fullPixmapMask:mailfullmsk
xbiff*emptyPixmap:mailempty
xbiff*emptyPixmapMask:mailemptymsk
.DE
The prefix
.B xbiff
indicates that these settings are to apply only to this application.
The asterisk `*' means that an indefinite number of widget classes can
occur between the name of the application and the widget in which we are
interested; this spares us the trouble of having to build the entire
widget tree \(em and having to rebuild the tree should the designers of
.B xbiff
decide in the future to insert another layer or two into the widget hierarchy.
Finally, value names the file in directory
.B /usr/X11/include/X11/bitmaps
that holds the bit map we want.
.PP
.B xbiff
does not read a defaults file out of
.BR /usr/X11/lib/app-defaults ;
but we can still make
.B xbiff
use our new resources by using the X utility
.B xrdb
to load them into the X server's resources data base.
We save these resources into a file \(em we will use the conventional file
\fB$HOME/.Xdefaults\fR,
although the name of this file doesn't really matter \(em then type the
following command:
.DM
xrdb -merge < $HOME/.Xdefaults
.DE
This command merges the contents of
.B $HOME/.Xdefaults
into the X server's resource data base.
So, the next time you invoke
.BR xbiff ,
you see:
.PH 1 1 \*(XD/xbiffnew.eps
instead of the old-fashioned mailbox.
.PP
To extend this example, the documentation for
.B xbiff
also mentions the following two resources:
.IP "\fBshapeWindow(\fRclass \fBShapeWindow)\fR"
Specify whether to shape the window to the
.B fullPixmapMask
and
.BR emptyPixmapMask .
The default is false.
.IP "\fBflip(\fRclass \fBFlip)\fR"
Invert the image when new mail arrives.
The default is true.
.PP
To change these defaults, insert the following lines into
.BR $HOME/.Xdefaults :
.DM
xbiff*shapeWindow:True
xbiff*flip:False
.DE
Then, type:
.DM
xrdb -merge < $HOME/.Xdefaults
.DE
The next time you invoke
.BR xbiff ,
its window will be shaped that of the bit-mapped mask; and it will not
pop into reverse video when mail arrives.
.PP
If an application uses a defaults file, you can simply edit that file to
change a resource.
For example, the application
.B xclock
reads the defaults file
.BR /usr/X11/lib/app-defaults/XClock ,
which consists of exactly one line:
.DM
XClock.input: false
.DE
Note that because this resource is in a defaults file, the resource
.DM
*input: false
.DE
would behave exactly the same.
If you wanted, for whatever reason, to permit a user to type input into
.BR xclock ,
edit this line to read:
.DM
XClock.input: true
.DE
As noted earlier, the resources in the X server's resource data base
take precedence over the contents of a defaults file.
For example, the X client
.B xgas
reads the default file
.BR /usr/X11/lib/app-defaults/XGas ,
which (among many others) contains the following resource:
.DM
*quit.label: Quit
.DE
This resource defines the text that appears on the ``quit'' button.
If you decide that you want this button to be labelled
.BR FOO ,
you can insert the following resource into
.BR $HOME/.Xdefaults:
.DM
xgas*quit.label:FOO
.DE
Then, type the command:
.DM
xrdb -merge < $HOME/.Xdefaults
.DE
The next time you invoke
.BR xgas ,
the ``quit'' button will be labelled
.BR FOO ,
thus overriding the setting in
.BR XGas .
.Sh "Modifying a Font Resource"
.PP
.II resource^font
.II font^choose
Fonts are an important aspect of X.
A font incorporates textual information; thus, a well-selected font
can make your system much more useful.
.PP
For example, the defaults file
.B /usr/X11/lib/app-defaults/XTerm
sets a number of different fonts for using in different situations.
The default font is called
.BR fixed .
If you wish to change this to a larger font, try the following:
.IP \(bu 0.3i
.B cd
to directory
.BR /usr/X11/lib/fonts .
This directory holds the fonts available to the X system.
These are kept two sub-directories:
.B misc
and
.BR 75dpi .
The former holds ``miscellaneous'' fonts, such as the
.B cursor
font; the latter holds fancier fonts built in a 75 dots-per-inch format.
Most of the commonly used fonts are in
.BR misc .
.IP \(bu
.B cd
to
.BR misc .
Read file
.BR fonts.alias .
This gives the commonly used aliases for fonts used on the system.
As you can see, the font named
.B fixed
is actually the font:
.DM
-misc-fixed-medium-r-semicondensed--13-120-75-75-c-60-iso8859-1
.DE
When you look further in
.BR fonts.alias ,
you will see that this is the same as the font named
.BR 6x13 .
The alias indicates that the font is 13 pixels high and 6 pixels wide.
(For information on how to interpret the full, 14-field font name,
see the Lexicon entry for
.BR xfontsel .)
To select a larger font, pick one whose height is greater than 13 pixels
or whose width is greater than six.
For example, the font whose alias is
.B 8x13
is the same height as the
.B fixed
font, but is two pixels wider.
.IP \(bu
Close
.BR fonts.alias .
Then edit your
.B .Xdefaults
file to insert the following entry:
.DM
xvt*font:8x13
.DE
This sets the font resource for
.B xvt
to the font with the alias
.BR 8x13 .
.IP \(bu
Type:
.DM
xrdb -merge < $HOME/.Xdefaults
.DE
This merges your new resource setting into the X server's
resource data base.
.PP
That's all there is to it.
The next time you invoke
.BR xvt ,
it will use font
.BR 8x13 ,
which is slightly larger and more legible.
Because the geometry of the
.B xvt
window is set to 80\(mu25 (that, 80 columns by 25 rows), the window will be
resized automatically to use the new font.
.PP
Note, by the way, that an
.B xvt
window using the
.B 8x13
font will not completely fit onto a 640\(mu480 screen \(em the last column
slips off the right edge of the screen.
If you find this to be a real problem, try using a narrower font.
.SH "Where To Go From Here"
.PP
This concludes our introduction to X applications and how to customize them.
We could only scratch the surface of resources, widgets, and the
internals of X; however, we hope that you now know enough to make minor
modifications to your system, and to begin to learn more about X.
.PP
For more information on a given application, see its entry in the Lexicon.
The books referenced in the introduction will also give you more information.
.PP
The next chapter discusses how to recompile X applications under
X Windows for \*(CO.
|
[STATEMENT]
lemma fixes ps:: partstate
and s::state
assumes "vars a \<subseteq> dom ps" "ps \<preceq> part s"
shows emb_update2: "emb (ps(x \<mapsto> paval a ps)) s = (emb ps s)(x := aval a (emb ps s))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. emb (ps(x \<mapsto> paval a ps)) s = (emb ps s)(x := aval a (emb ps s))
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
vars a \<subseteq> dom ps
ps \<preceq> part s
goal (1 subgoal):
1. emb (ps(x \<mapsto> paval a ps)) s = (emb ps s)(x := aval a (emb ps s))
[PROOF STEP]
unfolding emb_def
[PROOF STATE]
proof (prove)
using this:
vars a \<subseteq> dom ps
ps \<preceq> part s
goal (1 subgoal):
1. (\<lambda>v. case (ps(x \<mapsto> paval a ps)) v of None \<Rightarrow> s v | Some r \<Rightarrow> r) = (\<lambda>v. case ps v of None \<Rightarrow> s v | Some r \<Rightarrow> r)(x := aval a (\<lambda>v. case ps v of None \<Rightarrow> s v | Some r \<Rightarrow> r))
[PROOF STEP]
apply auto
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>vars a \<subseteq> dom ps; ps \<preceq> part s\<rbrakk> \<Longrightarrow> (\<lambda>v. case if v = x then Some (paval a ps) else ps v of None \<Rightarrow> s v | Some r \<Rightarrow> r) = (\<lambda>v. case ps v of None \<Rightarrow> s v | Some r \<Rightarrow> r)(x := aval a (\<lambda>v. case ps v of None \<Rightarrow> s v | Some r \<Rightarrow> r))
[PROOF STEP]
apply (rule ext)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>v. \<lbrakk>vars a \<subseteq> dom ps; ps \<preceq> part s\<rbrakk> \<Longrightarrow> (case if v = x then Some (paval a ps) else ps v of None \<Rightarrow> s v | Some r \<Rightarrow> r) = ((\<lambda>v. case ps v of None \<Rightarrow> s v | Some r \<Rightarrow> r)(x := aval a (\<lambda>v. case ps v of None \<Rightarrow> s v | Some r \<Rightarrow> r))) v
[PROOF STEP]
apply(case_tac "v=x")
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>v. \<lbrakk>vars a \<subseteq> dom ps; ps \<preceq> part s; v = x\<rbrakk> \<Longrightarrow> (case if v = x then Some (paval a ps) else ps v of None \<Rightarrow> s v | Some r \<Rightarrow> r) = ((\<lambda>v. case ps v of None \<Rightarrow> s v | Some r \<Rightarrow> r)(x := aval a (\<lambda>v. case ps v of None \<Rightarrow> s v | Some r \<Rightarrow> r))) v
2. \<And>v. \<lbrakk>vars a \<subseteq> dom ps; ps \<preceq> part s; v \<noteq> x\<rbrakk> \<Longrightarrow> (case if v = x then Some (paval a ps) else ps v of None \<Rightarrow> s v | Some r \<Rightarrow> r) = ((\<lambda>v. case ps v of None \<Rightarrow> s v | Some r \<Rightarrow> r)(x := aval a (\<lambda>v. case ps v of None \<Rightarrow> s v | Some r \<Rightarrow> r))) v
[PROOF STEP]
apply(simp add: paval_aval)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>v. \<lbrakk>vars a \<subseteq> dom ps; ps \<preceq> part s; v \<noteq> x\<rbrakk> \<Longrightarrow> (case if v = x then Some (paval a ps) else ps v of None \<Rightarrow> s v | Some r \<Rightarrow> r) = ((\<lambda>v. case ps v of None \<Rightarrow> s v | Some r \<Rightarrow> r)(x := aval a (\<lambda>v. case ps v of None \<Rightarrow> s v | Some r \<Rightarrow> r))) v
[PROOF STEP]
by (simp) |
%maincheck.m
%check whether an earthquake is followed by an equal or bigger sized
%eq in a certain distance
%Last change 11/95 Alexander Allmann
%
%TODO Delete, it was error-full -CGR
global newcat err derr;
newcat=a;
n=0; %counter
n1=0;
mcut1=5; %default for magnitudes of interest
mcut2=5; %default for magnitudes of eqs following first event
dist=30; %distance in which programs looks for following events
tcut1=30; %time intervall in which program searches for other events
err=2;derr=2;
newcat=newcat.Magnitude>mcut1;
backnewcat=newcat;
eqtime=clustime(); %onset time of earthquakes
for i=1:newcat.Count
tmp=find((eqtime-eqtime(i))>0 & (eqtime - eqtime(i))<tcut1);
if ~isempty(tmp)
tmp2=newcat.subset(tmp);
tmp3=find(tmp2(:,6)>=newcat(i,6));
if ~isempty(tmp3)
newcat=[newcat.subset(i);tmp2(tmp3,:)];
[dist1, dist2] = distance(1,1,2:newcat.Count);
tmp4=dist1<dist;
if ~isempty(tmp4)
n=n+1;
if length(tmp4)>1
n1=n1+1; %more than one bigger event follows in sequence
end
end
newcat=backnewcat;
end
end
end
n
n1
|
Require Import Logic.Axiom.LEM.
Require Import Logic.Fol.Syntax.
Require Import Logic.Set.Set.
Require Import Logic.Set.Incl.
Require Import Logic.Set.Elem.
Require Import Logic.Set.Equal.
Require Import Logic.Lang1.Syntax.
Require Import Logic.Lang1.Context.
Require Import Logic.Lang1.SemanCtx.
Require Import Logic.Lang1.Semantics.
Require Import Logic.Lang1.Environment.
Open Scope Set_Incl_scope.
(* Theorem 'extensionality' expressed in set theory abstract syntax. *)
(* This formulation is correct provided the variables names n m p are distinct. *)
Definition extensionalityF (n m p:nat) : Formula :=
All n (All m (Iff (Equ n m) (All p (Iff (Elem p n) (Elem p m))))).
(* Theorem 'doubleIncl' expressed in set theory abstract syntax. *)
(* This formulation is correct provided the variables names n m are distinct. *)
Definition doubleInclF (n m:nat) : Formula :=
All n (All m (Iff (Equ n m) (And (Sub n m) (Sub m n)))).
Import Semantics.
(* Evaluating extensionalityF in any environment 'yields' the theorem. *)
Lemma evalExtensionalityF : LEM -> forall (e:Env) (n m p:nat),
m <> n ->
p <> m ->
p <> n ->
eval e (extensionalityF n m p)
<->
forall (x y:set), x == y <-> forall (z:set), z :: x <-> z :: y.
Proof.
intros L e n m p Hmn Hpm Hpn. unfold extensionalityF. rewrite evalAll.
split; intros H x.
- intros y.
remember (H x) as H' eqn:E. clear E. clear H. rewrite evalAll in H'.
remember (H' y) as H eqn:E. clear E. clear H'.
rewrite evalIff in H. rewrite evalEqu in H. rewrite evalAll in H.
remember (bind e n x) as e1 eqn:E1. rewrite bindDiff in H.
rewrite bindSame in H. rewrite E1 in H. rewrite bindSame in H.
destruct H as [H1 H2]. split; intros H.
+ intros z. remember (H1 H z) as H' eqn:E. clear E. clear H.
rewrite <- E1 in H'. remember (bind e1 m y) as e2 eqn:E2.
rewrite evalIff in H'. rewrite evalElem in H'. rewrite evalElem in H'.
rewrite bindSame in H'. rewrite bindDiff in H'. rewrite bindDiff in H'.
rewrite E2 in H'. rewrite bindSame in H'. rewrite bindDiff in H'.
rewrite E1 in H'. rewrite bindSame in H'.
{ assumption. }
{ assumption. }
{ assumption. }
{ assumption. }
{ assumption. }
+ apply H2. intros z. rewrite <- E1. remember (bind e1 m y) as e2 eqn:E2.
rewrite evalIff, evalElem, evalElem, bindSame, bindDiff, bindDiff, E2.
rewrite bindSame, bindDiff, E1, bindSame.
{ apply H. }
{ assumption. }
{ assumption. }
{ assumption. }
{ assumption. }
+ assumption.
+ assumption.
+ assumption.
- rewrite evalAll. intros y.
remember (bind e n x) as e1 eqn:E1. remember (bind e1 m y) as e2 eqn:E2.
rewrite evalIff, evalEqu, evalAll, E2, bindSame, bindDiff, E1, bindSame.
destruct (H x y) as [H1 H2]. clear H. split; intros H'.
+ intros z. rewrite <- E1, <- E2, evalIff, evalElem, evalElem, bindSame.
rewrite bindDiff, bindDiff, E2, bindSame, bindDiff, E1, bindSame.
apply H1.
{ assumption. }
{ assumption. }
{ assumption. }
{ assumption. }
{ assumption. }
+ apply H2. intros z. remember (H' z) as H eqn:E. clear E. clear H'.
rewrite <- E1 in H. rewrite <- E2 in H. rewrite evalIff in H.
rewrite evalElem in H. rewrite evalElem in H. rewrite bindSame in H.
rewrite bindDiff in H. rewrite bindDiff in H. rewrite E2 in H.
rewrite bindSame in H. rewrite bindDiff in H. rewrite E1 in H.
rewrite bindSame in H.
{ assumption. }
{ assumption. }
{ assumption. }
{ assumption. }
{ assumption. }
+ assumption.
+ assumption.
+ assumption.
Qed.
Import SemanCtx.
Lemma evalExtensionalityFCtx : LEM -> forall (G:Context) (n m p:nat),
n <> m ->
n <> p ->
m <> p ->
G :- (extensionalityF n m p) >>
forall (x y:set), x == y <-> forall (z:set), z :: x <-> z :: y.
Proof.
intros L G n m p H1 H2 H3. unfold extensionalityF.
apply evalAll. intros x. apply evalAll. intros y.
apply evalIff; try assumption.
- apply evalEqu; try assumption.
+ apply FindS. assumption. apply FindZ.
+ apply FindZ.
- apply evalAll. intros z. apply evalIff; try assumption.
+ apply evalElem; try (apply FindZ).
apply FindS; try assumption. apply FindS; try assumption.
apply FindZ.
+ apply evalElem; try (apply FindZ).
apply FindS; try assumption. apply FindZ.
Qed.
Import Semantics.
(* Evaluating doubleInclF in any environment 'yields' the theorem doubleIncl. *)
Lemma evalDoubleInclF : LEM -> forall (e:Env) (n m:nat),
m <> n ->
eval e (doubleInclF n m)
<->
forall (x y:set), x == y <-> (x <= y) /\ (y <= x).
Proof.
intros L e n m Hmn. unfold doubleInclF. rewrite evalAll. split; intros H x.
- intros y. remember (H x) as H' eqn:E. clear E. clear H.
rewrite evalAll in H'. remember (H' y) as H eqn:E. clear E. clear H'.
remember (bind e n x) as e1 eqn:E1.
rewrite evalIff in H. rewrite evalEqu in H. rewrite evalAnd in H.
rewrite evalSub in H. rewrite evalSub in H. rewrite bindSame in H.
rewrite bindDiff in H. rewrite E1 in H. rewrite bindSame in H.
+ assumption.
+ assumption.
+ assumption.
+ assumption.
+ assumption.
- rewrite evalAll. intros y.
remember (bind e n x) as e1 eqn:E1.
rewrite evalIff, evalEqu, evalAnd, evalSub, evalSub, bindSame.
rewrite bindDiff, E1, bindSame.
+ apply H.
+ assumption.
+ assumption.
+ assumption.
+ assumption.
Qed.
Import SemanCtx.
Lemma evalDoubleInclFCtx : LEM -> forall (G:Context) (n m:nat),
n <> m ->
G :- (doubleInclF n m) >>
forall (x y:set), x == y <-> (x <= y) /\ (y <= x).
Proof.
intros L G n m H1. unfold doubleInclF.
apply evalAll. intros x. apply evalAll. intros y.
apply evalIff; try assumption.
- apply evalEqu; try assumption.
+ apply FindS; try assumption. apply FindZ.
+ apply FindZ.
- apply evalAnd; try assumption.
+ apply evalSub.
{ apply FindS; try assumption. apply FindZ. }
{ apply FindZ. }
+ apply evalSub.
{ apply FindZ. }
{ apply FindS; try assumption. apply FindZ. }
Qed.
|
Formal statement is: lemma csqrt_unique: "w\<^sup>2 = z \<Longrightarrow> 0 < Re w \<or> Re w = 0 \<and> 0 \<le> Im w \<Longrightarrow> csqrt z = w" Informal statement is: If $w$ is a complex number such that $w^2 = z$ and $w$ is in the first or fourth quadrant, then $w$ is the principal square root of $z$. |
# syntax: proto3
using ProtoBuf
import ProtoBuf.meta
mutable struct Empty <: ProtoType
Empty(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct Empty
export Empty
|
You are currently connected to the website www.buyfollowersbysms.com, published by Conseil NR, SASU, registered capital: 1000 €, registered RCS of Caen: 799 530 936, registered office: 35 rue du Général Leclerc, 14790 Verson, : +33811382283, email: [email protected], Intracommunity VAT number: FR 03 799530936, editor and editor: Nicolas Robine.
The Site is hosted by OVH, registered office: 2 rue Kellermann BP 80157, 59053 Roubaix Cedex 1, telephone: 0820698765.
"Bot": software having the property of interacting with computer servers.
"Client" means any person, whether natural or legal, under private law or public law, registered on the Site.
«Content»: data of any kind published by the Client on its Profile and targeted by a Pack.
"Follower": Bot appearing on the Profile of the Social Network on which the Customer is registered as a Registered.
"Registered" means a natural or legal person, whether private or public, subscribing to the services of a Social Network.
"Profile": personal account subscribed by a Client on Social Network.
"Social Network": a community website, particularly accessible at URLs www.instagram.com, www.twitter.com and www.facebook.com, as well as the sub-sites, mirror sites, portals and URL variations relating thereto.
"Conseil NR": Conseil NR, SASU, taken as publisher of the Site.
"Internet user" means any person, whether natural or legal, under private or public law, connecting to the Site.
"Like": mention "I like" / "J'aime" added on the Profile of the Client by a Bot.
"Pack": set of Likes and / or Followers.
"Site": Web site accessible at the URL www.buyfollowersbysms.com, as well as sub-sites, mirror sites, portals and URL variations relating thereto.
When registering on the Site, this acceptance will be confirmed by ticking the box corresponding to the following sentence: "I acknowledge having read and accepted the general conditions of sale and use". The Internet user recognizes by the same fact to have taken full knowledge and accept them without restriction.
Ticking the above box will be deemed to have the same value as a handwritten signature on the part of the Customer. The Internet User acknowledges the evidentiary value of Council NR's automatic registration systems and, except for the contrary, waives the right to challenge them in the event of a dispute.
These general terms and conditions are applicable to the relations between the parties to the exclusion of all other conditions, and in particular those of the Client.
Acceptance of the present general conditions assumes on the part of the Internet users that they have the legal capacity necessary for this, or failing that they have the authorization of a guardian or curator if they are incapable , Their legal representative if they are minors, or if they hold a mandate if they are acting on behalf of a legal person.
Customers may purchase Packs on the Site for their Social Networks.
In order to place an order, Internet users may select one or more Packs on the Site.
Once the order is made, the Customer is informed by Allopass of the final price of his Pack. If their order suits them, the Internet users can validate it.
Once the order has been validated, Customers will be asked to enter their shipping and billing details and will be invited to make their payment by being redirected to this effect on the Allopass secure payment interface.
Once the payment actually received by Allopass and confirmed by the latter to Conseil NR, the latter undertakes to acknowledge receipt to the Customer by electronic means, within a maximum period of 24 hours. Within the same period, Conseil NR agrees to send the Customer an e-mail summarizing the order and confirming the processing, including all the information relating to it.
The Packs are delivered directly to the relevant Profile of the Customer within 72 hours from the perfect receipt of the price of the order.
The delivery of the Packs is subcontracted to the low-cost provider of Conseil NR. Consequently, these general conditions are governed by the rules of subcontracting laid down by Law No. 75-1334 of 31 December 1975 on subcontracting.
The Customer declares having received from the Conseil NR all the explanations and clarifications useful to enable him to use the Packs.
The Client acknowledges that his needs and the Packs proposed by Conseil NR are in adequacy and that he has taken out the contract knowingly and has all the necessary information enabling him to produce free and informed consent.
The Customer is solely responsible for the authorizations and declarations relating to the use of the Packs.
The Client declares that he has the necessary rights and authorizations for this purpose. If necessary, the Client declares that he has carried out any necessary steps, such as requests for authorizations and administrative declarations.
The absence of such declarations and authorizations shall in no case affect the validity of this contract. In particular, the Client will be required to pay Council NR sums due in respect of Pack orders.
The Client guarantees Council NR against any recourse that would be taken against him in case of default of such declarations and authorizations.
The Client must keep his Profile open and active throughout the duration of this contract. Similarly, the Client must not remove from its Profile the Contents targeted by the Packs.
Conseil NR would not be held responsible in the event of the deletion of the Customer Profile or the withdrawal of the Client's Content.
The prices applicable are those displayed on the Site at the time of the order. These prices may be changed at any time by Conseil NR or Allopass. The displayed prices are only valid on the day of the order and do not have effect for the future.
Prices quoted are in euros, all taxes included.
The Customer can pay by Allopass and SMS surtaxé.
Allopass will send or make available to the Customer a receipt electronically after each payment. The Customer expressly agrees to receive invoices electronically.
Any amount not paid at maturity will give rise, automatically and without formal notice, to the application of penalties for delay calculated on the basis of a rate equal to 3 times the legal interest rate, Penalty shall prejudice the payment of principal sums due.
In addition, any delay in payment will result in invoicing the defaulting Customer for a recovery charge of EUR 40, immediate repayment of all sums remaining due whatever the agreed deadlines, plus an indemnity of 20% of the amount as a penalty clause, as well as the possibility of terminating the contract unilaterally to the Customer's fault.
The Site's customer service is available Monday through Friday, from 9:00 am to 12:00 pm and from 2:00 pm to 4:00 pm at the following non-surcharged telephone number: 0811382283, by e-mail to: [email protected] or by post to the address indicated In Article 1 of these terms and conditions. In the latter two cases, Conseil NR undertakes to provide a response within 24 working hours.
In accordance with the legislation in force in the field of distance selling, the Client having the status of consumer has a period of seven clear days to exercise his right of withdrawal without having to justify reasons or to pay penalties, With the exception of return costs. The consumer may derogate from this time limit in the event that he can not move and where at the same time he would need to call for an immediate benefit necessary for his living conditions. In this case, he would continue to exercise his right of withdrawal without having to justify reasons or pay penalties.
The period mentioned in the preceding paragraph runs from receipt for the goods or acceptance of the offer for the provision of services. Where the seven-day period expires on a Saturday, a Sunday or a holiday or non-working day, it shall be extended to the next working day.
Where the right of withdrawal is exercised, the trader is obliged to reimburse the consumer for all the sums paid, as soon as possible and at the latest within thirty days following the date on which the right was exercised. Beyond that, the amount due shall automatically be paid interest at the legal rate in force. This reimbursement is made by any means of payment. The consumer who has exercised his right of withdrawal may, however, opt for a different method of reimbursement on the professional's proposal.
The right of withdrawal may not be exercised for contracts for the supply of services the performance of which began before the end of the seven-day period.
The Consumer Customer may terminate the contract by registered letter with acknowledgment of receipt if the delivery date of the goods exceeds seven days. The Customer will then be reimbursed the sums committed by him at the time of the order.
This clause shall not apply if the delay in delivery is due to force majeure. In such a case, the Customer undertakes not to prosecute NR Council and waives the right to resolve the sale provided for in this article.
Conseil NR undertakes to take the necessary care and diligence to supply Quality Packs in accordance with the specifications of these general conditions. Conseil NR is only liable for an obligation relating to the services covered by this contract.
For the purposes of these general terms and conditions, any prejudice, limitation or disturbance of the Service due to fire, epidemic, explosion, earthquake, fluctuations of the band Failure of the access provider, failure of transmission networks, collapse of installations, unlawful or fraudulent use of passwords, codes or references provided to the Client, computer hacking, a fault Security imputable to the host of the Site or the developers, flood, power outage, war, embargo, law, injunction, demand or requirement of any government, requisition, Strike, boycott, or other circumstances beyond the reasonable control of Council NR. In such circumstances, Council NR shall be exempted from the performance of its obligations within the limit of such impediment, limitation or inconvenience.
For the purposes of these General Terms and Conditions, any fault on the part of the Customer or any of its servants, fault, negligence, omission or failure on the part of the Customer, On its Site, any unauthorized disclosure or use of the password, both of the Site and the Customer Profile, of the Customer's codes and references, as well as the information of incorrect information or the lack of updating of such information in His personal space. The use of any technical process, such as robots, or automatic requests, the implementation of which contravenes the letter or the spirit of the present general conditions of sale will also be considered as a fault of the Client.
In case of impossible access to the Site, due to technical problems of all kinds, the Customer can not claim any damage and can not claim any compensation. The unavailability, even prolonged and without any limitation period, of one or more online services can not constitute a prejudice to the Customers and can in no way give rise to the award of damages from Council NR.
The hypertext links present on the Site may refer to other websites. The responsibility of Conseil NR can not be engaged if the content of these sites contravenes the legislation in force. Similarly, the responsibility of Conseil NR can not be engaged if the visit, by the Internet user, of one of these sites, was causing him a prejudice.
In the absence of any legal or regulatory provisions to the contrary, the liability of Conseil NR is limited to the direct, personal and certain prejudice suffered by the Customer and related to the default in question. Consequently, Conseil NR can not be held liable for indirect damages, such as loss of data, commercial damage, loss of orders, damage to the image, trade disturbances and loss of profits or loss. Customers. In the same way and within the same limits, the amount of damages charged to Council NR can not in any event exceed the price of the Pack ordered.
The content (texts, images, diagrams ...), the structure and the software implemented for the operation of the Site are protected by the copyright and the right of the databases. Any representation or reproduction in whole or in part made without the consent of Conseil NR or its successors or successors in title constitutes a violation of Books I and III of the Code of the intellectual property and will be liable to prosecution. The same shall apply to translation, adaptation or transformation, arrangement or reproduction by any art or process.
The information published on this Site is for information only, without guarantee of accuracy. Conseil NR can not be held responsible for any omission, inaccuracy or any error contained in this information which would be the cause of direct or indirect damage caused to the Internet user.
These terms and conditions may be amended at any time by Conseil NR. The general conditions applicable to the Customer are those in force on the day of its order or its connection on this Site, any new connection to the personal space taking acceptance of the new general conditions, if necessary.
Any disputes which may arise in connection with the execution of these general conditions shall, before any legal action, be submitted to the Conseil NR for a friendly settlement.
The failure of the NR Council to exercise its rights hereunder shall in no case be interpreted as a waiver of the said rights. |
/-
Copyright (c) 2022 Alex Kontorovich and Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alex Kontorovich, Heather Macbeth
-/
import measure_theory.measure.haar
import measure_theory.group.fundamental_domain
import algebra.group.opposite
/-!
# Haar quotient measure
In this file, we consider properties of fundamental domains and measures for the action of a
subgroup of a group `G` on `G` itself.
## Main results
* `measure_theory.is_fundamental_domain.smul_invariant_measure_map `: given a subgroup `Γ` of a
topological group `G`, the pushforward to the coset space `G ⧸ Γ` of the restriction of a both
left- and right-invariant measure on `G` to a fundamental domain `𝓕` is a `G`-invariant measure
on `G ⧸ Γ`.
* `measure_theory.is_fundamental_domain.is_mul_left_invariant_map `: given a normal subgroup `Γ` of
a topological group `G`, the pushforward to the quotient group `G ⧸ Γ` of the restriction of
a both left- and right-invariant measure on `G` to a fundamental domain `𝓕` is a left-invariant
measure on `G ⧸ Γ`.
Note that a group `G` with Haar measure that is both left and right invariant is called
**unimodular**.
-/
open set measure_theory topological_space measure_theory.measure
open_locale pointwise nnreal
variables {G : Type*} [group G] [measurable_space G] [topological_space G]
[topological_group G] [borel_space G]
{μ : measure G}
{Γ : subgroup G}
/-- Measurability of the action of the topological group `G` on the left-coset space `G/Γ`. -/
@[to_additive "Measurability of the action of the additive topological group `G` on the left-coset
space `G/Γ`."]
instance quotient_group.has_measurable_smul [measurable_space (G ⧸ Γ)] [borel_space (G ⧸ Γ)] :
has_measurable_smul G (G ⧸ Γ) :=
{ measurable_const_smul := λ g, (continuous_const_smul g).measurable,
measurable_smul_const := λ x, (quotient_group.continuous_smul₁ x).measurable }
variables {𝓕 : set G} (h𝓕 : is_fundamental_domain Γ.opposite 𝓕 μ)
include h𝓕
variables [countable Γ] [measurable_space (G ⧸ Γ)] [borel_space (G ⧸ Γ)]
/-- The pushforward to the coset space `G ⧸ Γ` of the restriction of a both left- and right-
invariant measure on `G` to a fundamental domain `𝓕` is a `G`-invariant measure on `G ⧸ Γ`. -/
@[to_additive "The pushforward to the coset space `G ⧸ Γ` of the restriction of a both left- and
right-invariant measure on an additive topological group `G` to a fundamental domain `𝓕` is a
`G`-invariant measure on `G ⧸ Γ`."]
lemma measure_theory.is_fundamental_domain.smul_invariant_measure_map
[μ.is_mul_left_invariant] [μ.is_mul_right_invariant] :
smul_invariant_measure G (G ⧸ Γ) (measure.map quotient_group.mk (μ.restrict 𝓕)) :=
{ measure_preimage_smul :=
begin
let π : G → G ⧸ Γ := quotient_group.mk,
have meas_π : measurable π :=
continuous_quotient_mk.measurable,
have 𝓕meas : null_measurable_set 𝓕 μ := h𝓕.null_measurable_set,
intros g A hA,
have meas_πA : measurable_set (π ⁻¹' A) := measurable_set_preimage meas_π hA,
rw [measure.map_apply meas_π hA,
measure.map_apply meas_π (measurable_set_preimage (measurable_const_smul g) hA),
measure.restrict_apply₀' 𝓕meas, measure.restrict_apply₀' 𝓕meas],
set π_preA := π ⁻¹' A,
have : (quotient_group.mk ⁻¹' ((λ (x : G ⧸ Γ), g • x) ⁻¹' A)) = has_mul.mul g ⁻¹' π_preA,
{ ext1, simp },
rw this,
have : μ (has_mul.mul g ⁻¹' π_preA ∩ 𝓕) = μ (π_preA ∩ has_mul.mul (g⁻¹) ⁻¹' 𝓕),
{ transitivity μ (has_mul.mul g ⁻¹' (π_preA ∩ has_mul.mul g⁻¹ ⁻¹' 𝓕)),
{ rw preimage_inter,
congr,
rw [← preimage_comp, comp_mul_left, mul_left_inv],
ext,
simp, },
rw measure_preimage_mul, },
rw this,
have h𝓕_translate_fundom : is_fundamental_domain Γ.opposite (g • 𝓕) μ := h𝓕.smul_of_comm g,
rw [h𝓕.measure_set_eq h𝓕_translate_fundom meas_πA, ← preimage_smul_inv], refl,
rintros ⟨γ, γ_in_Γ⟩,
ext,
have : π (x * (mul_opposite.unop γ)) = π (x) := by simpa [quotient_group.eq'] using γ_in_Γ,
simp [(•), this],
end }
/-- Assuming `Γ` is a normal subgroup of a topological group `G`, the pushforward to the quotient
group `G ⧸ Γ` of the restriction of a both left- and right-invariant measure on `G` to a
fundamental domain `𝓕` is a left-invariant measure on `G ⧸ Γ`. -/
@[to_additive "Assuming `Γ` is a normal subgroup of an additive topological group `G`, the
pushforward to the quotient group `G ⧸ Γ` of the restriction of a both left- and right-invariant
measure on `G` to a fundamental domain `𝓕` is a left-invariant measure on `G ⧸ Γ`."]
lemma measure_theory.is_fundamental_domain.is_mul_left_invariant_map [subgroup.normal Γ]
[μ.is_mul_left_invariant] [μ.is_mul_right_invariant] :
(measure.map (quotient_group.mk' Γ) (μ.restrict 𝓕)).is_mul_left_invariant :=
{ map_mul_left_eq_self := begin
intros x,
apply measure.ext,
intros A hA,
obtain ⟨x₁, _⟩ := @quotient.exists_rep _ (quotient_group.left_rel Γ) x,
haveI := h𝓕.smul_invariant_measure_map,
convert measure_preimage_smul x₁ ((measure.map quotient_group.mk) (μ.restrict 𝓕)) A using 1,
rw [← h, measure.map_apply],
{ refl, },
{ exact measurable_const_mul _, },
{ exact hA, },
end }
variables [t2_space (G ⧸ Γ)] [second_countable_topology (G ⧸ Γ)] (K : positive_compacts (G ⧸ Γ))
/-- Given a normal subgroup `Γ` of a topological group `G` with Haar measure `μ`, which is also
right-invariant, and a finite volume fundamental domain `𝓕`, the pushforward to the quotient
group `G ⧸ Γ` of the restriction of `μ` to `𝓕` is a multiple of Haar measure on `G ⧸ Γ`. -/
@[to_additive "Given a normal subgroup `Γ` of an additive topological group `G` with Haar measure
`μ`, which is also right-invariant, and a finite volume fundamental domain `𝓕`, the pushforward
to the quotient group `G ⧸ Γ` of the restriction of `μ` to `𝓕` is a multiple of Haar measure on
`G ⧸ Γ`."]
lemma measure_theory.is_fundamental_domain.map_restrict_quotient [subgroup.normal Γ]
[measure_theory.measure.is_haar_measure μ] [μ.is_mul_right_invariant]
(h𝓕_finite : μ 𝓕 < ⊤) : measure.map (quotient_group.mk' Γ) (μ.restrict 𝓕)
= (μ (𝓕 ∩ (quotient_group.mk' Γ) ⁻¹' K)) • (measure_theory.measure.haar_measure K) :=
begin
let π : G →* G ⧸ Γ := quotient_group.mk' Γ,
have meas_π : measurable π := continuous_quotient_mk.measurable,
have 𝓕meas : null_measurable_set 𝓕 μ := h𝓕.null_measurable_set,
haveI : is_finite_measure (μ.restrict 𝓕) :=
⟨by { rw [measure.restrict_apply₀' 𝓕meas, univ_inter], exact h𝓕_finite }⟩,
-- the measure is left-invariant, so by the uniqueness of Haar measure it's enough to show that
-- it has the stated size on the reference compact set `K`.
haveI : (measure.map (quotient_group.mk' Γ) (μ.restrict 𝓕)).is_mul_left_invariant :=
h𝓕.is_mul_left_invariant_map,
rw [measure.haar_measure_unique (measure.map (quotient_group.mk' Γ) (μ.restrict 𝓕)) K,
measure.map_apply meas_π, measure.restrict_apply₀' 𝓕meas, inter_comm],
exact K.is_compact.measurable_set,
end
/-- Given a normal subgroup `Γ` of a topological group `G` with Haar measure `μ`, which is also
right-invariant, and a finite volume fundamental domain `𝓕`, the quotient map to `G ⧸ Γ` is
measure-preserving between appropriate multiples of Haar measure on `G` and `G ⧸ Γ`. -/
@[to_additive measure_preserving_quotient_add_group.mk' "Given a normal subgroup `Γ` of an additive
topological group `G` with Haar measure `μ`, which is also right-invariant, and a finite volume
fundamental domain `𝓕`, the quotient map to `G ⧸ Γ` is measure-preserving between appropriate
multiples of Haar measure on `G` and `G ⧸ Γ`."]
lemma measure_preserving_quotient_group.mk' [subgroup.normal Γ]
[measure_theory.measure.is_haar_measure μ] [μ.is_mul_right_invariant]
(h𝓕_finite : μ 𝓕 < ⊤) (c : ℝ≥0) (h : μ (𝓕 ∩ (quotient_group.mk' Γ) ⁻¹' K) = c) :
measure_preserving
(quotient_group.mk' Γ)
(μ.restrict 𝓕)
(c • (measure_theory.measure.haar_measure K)) :=
{ measurable := continuous_quotient_mk.measurable,
map_eq := by rw [h𝓕.map_restrict_quotient K h𝓕_finite, h]; refl }
|
You Only Live Twice was a great success , receiving positive reviews and grossing over $ 111 million in worldwide box office .
|
!--------------------------------------------------------------------------------
! Copyright (c) 2018 Peter Grünberg Institut, Forschungszentrum Jülich, Germany
! This file is part of FLEUR and available as free software under the conditions
! of the MIT license as expressed in the LICENSE file in more detail.
!--------------------------------------------------------------------------------
MODULE m_genNewNocoInp
CONTAINS
SUBROUTINE genNewNocoInp(input,atoms,noco,nococonv,nococonv_new)
USE m_juDFT
USE m_types
USE m_constants
!USE m_rwnoco
IMPLICIT NONE
TYPE(t_input),INTENT(IN) :: input
TYPE(t_atoms),INTENT(IN) :: atoms
TYPE(t_noco),INTENT(IN) :: noco
TYPE(t_nococonv),INTENT(IN) :: nococonv
TYPE(t_nococonv),INTENT(INOUT) :: nococonv_new
INTEGER :: iAtom, iType
REAL :: alphdiff
IF (.NOT.noco%l_mperp) THEN
CALL juDFT_error ("genNewNocoInp without noco%l_mperp" ,calledby ="genNewNocoInp")
END IF
iAtom = 1
DO iType = 1, atoms%ntype
IF (noco%l_ss) THEN
alphdiff = 2.0*pi_const*(nococonv%qss(1)*atoms%taual(1,iAtom) + &
nococonv%qss(2)*atoms%taual(2,iAtom) + &
nococonv%qss(3)*atoms%taual(3,iAtom) )
nococonv_new%alph(iType) = nococonv_new%alph(iType) - alphdiff
DO WHILE (nococonv_new%alph(iType) > +pi_const)
nococonv_new%alph(iType)= nococonv_new%alph(iType) - 2.0*pi_const
END DO
DO WHILE (nococonv_new%alph(iType) < -pi_const)
nococonv_new%alph(iType)= nococonv_new%alph(iType) + 2.0*pi_const
END DO
ELSE
nococonv_new%alph(iType) = nococonv_new%alph(iType)
END IF
iatom= iatom + atoms%neq(iType)
END DO
CALL judft_error("BUG:noco-write feature not implemented at present")
OPEN (24,file='nocoinp',form='formatted', status='unknown')
REWIND (24)
!CALL rw_noco_write(atoms,noco_new, input)
CLOSE (24)
END SUBROUTINE genNewNocoInp
END MODULE m_genNewNocoInp
|
section "Sequents"
theory Sequents
imports Formula
begin
type_synonym sequent = "formula list"
definition
evalS :: "[model,vbl => object,formula list] => bool" where
"evalS M phi fs \<longleftrightarrow> (? f : set fs . evalF M phi f = True)"
lemma evalS_nil[simp]: "evalS M phi [] = False"
by(simp add: evalS_def)
lemma evalS_cons[simp]: "evalS M phi (A # Gamma) = (evalF M phi A | evalS M phi Gamma)"
by(simp add: evalS_def)
lemma evalS_append: "evalS M phi (Gamma @ Delta) = (evalS M phi Gamma | evalS M phi Delta)"
by(force simp add: evalS_def)
lemma evalS_equiv[rule_format]: "(equalOn (freeVarsFL Gamma) f g) --> (evalS M f Gamma = evalS M g Gamma)"
apply (induct Gamma, simp, rule)
apply(simp add: freeVarsFL_cons)
apply(drule_tac equalOn_UnD)
apply(blast dest: evalF_equiv)
done
definition
modelAssigns :: "[model] => (vbl => object) set" where
"modelAssigns M = { phi . range phi <= objects M }"
lemma modelAssignsI: "range f <= objects M \<Longrightarrow> f : modelAssigns M"
by(simp add: modelAssigns_def)
lemma modelAssignsD: "f : modelAssigns M \<Longrightarrow> range f <= objects M"
by(simp add: modelAssigns_def)
definition
validS :: "formula list => bool" where
"validS fs \<longleftrightarrow> (! M . ! phi : modelAssigns M . evalS M phi fs = True)"
subsection "Rules"
type_synonym rule = "sequent * (sequent set)"
definition
concR :: "rule => sequent" where
"concR = (%(conc,prems). conc)"
definition
premsR :: "rule => sequent set" where
"premsR = (%(conc,prems). prems)"
definition
mapRule :: "(formula => formula) => rule => rule" where
"mapRule = (%f (conc,prems) . (map f conc,(map f) ` prems))"
lemma mapRuleI: "[| A = map f a; B = (map f) ` b |] ==> (A,B) = mapRule f (a,b)"
by(simp add: mapRule_def)
\<comment> \<open>FIXME tjr would like symmetric\<close>
subsection "Deductions"
(*FIXME. I don't see why plain Pow_mono is rejected.*)
lemmas Powp_mono [mono] = Pow_mono [to_pred pred_subset_eq]
inductive_set
deductions :: "rule set => formula list set"
for rules :: "rule set"
(******
* Given a set of rules,
* 1. Given a rule conc/prem(i) in rules,
* and the prem(i) are deductions from rules,
* then conc is a deduction from rules.
* 2. can derive permutation of any deducible formula list.
* (supposed to be multisets not lists).
******)
where
inferI: "[| (conc,prems) : rules;
prems : Pow(deductions(rules))
|] ==> conc : deductions(rules)"
(*
perms "[| permutation conc' conc;
conc' : deductions(rules)
|] ==> conc : deductions(rules)"
*)
lemma mono_deductions: "[| A <= B |] ==> deductions(A) <= deductions(B)"
apply(best intro: deductions.inferI elim: deductions.induct) done
(*lemmas deductionsMono = mono_deductions*)
(*
-- "tjr following should be subsetD?"
lemmas deductionSubsetI = mono_deductions[THEN subsetD]
thm deductionSubsetI
*)
(******
* (f : formula -> formula) extended structurally over rules, deductions etc...
* (((If f maps rules into themselves then can consider mapping derivation trees.)))
* (((Is the asm necessary - think not?)))
* The mapped deductions from the rules are same as
* the deductions from the mapped rules.
*
* WHY:
*
* map f `` deductions rules <= deductions (mapRule f `` rules) (this thm)
* <= deductions rules (closed)
*
* If rules are closed under f then so are deductions.
* Can take f = (subst u v) and have application to exercise #1.
*
* Q: maybe also make f dual mapping, (what about quantifier side conditions...?).
******)
(*
lemma map_deductions: "map f ` deductions rules <= deductions (mapRule f ` rules)"
apply(rule subsetI)
apply (erule_tac imageE, simp)
apply(erule deductions.induct)
apply(blast intro: deductions.inferI mapRuleI)
done
lemma deductionsCloseRules: "! (conc,prems) : S . prems <= deductions R --> conc : deductions R ==> deductions (R Un S) = deductions R"
apply(rule equalityI)
prefer 2
apply(rule mono_deductions) apply blast
apply(rule subsetI)
apply (erule_tac deductions.induct, simp) apply(erule conjE) apply(thin_tac "prems \<subseteq> deductions (R \<union> S)")
apply(erule disjE)
apply(rule inferI) apply assumption apply force
apply blast
done
*)
subsection "Basic Rule sets"
definition
"Axioms = { z. ? p vs. z = ([FAtom Pos p vs,FAtom Neg p vs],{}) }"
definition
"Conjs = { z. ? A0 A1 Delta Gamma. z = (FConj Pos A0 A1#Gamma @ Delta,{A0#Gamma,A1#Delta}) }"
definition
"Disjs = { z. ? A0 A1 Gamma. z = (FConj Neg A0 A1#Gamma,{A0#A1#Gamma}) }"
definition
"Alls = { z. ? A x Gamma. z = (FAll Pos A#Gamma,{instanceF x A#Gamma}) & x ~: freeVarsFL (FAll Pos A#Gamma) }"
definition
"Exs = { z. ? A x Gamma. z = (FAll Neg A#Gamma,{instanceF x A#Gamma})}"
definition
"Weaks = { z. ? A Gamma. z = (A#Gamma,{Gamma})}"
definition
"Contrs = { z. ? A Gamma. z = (A#Gamma,{A#A#Gamma})}"
definition
"Cuts = { z. ? C Delta Gamma. z = (Gamma @ Delta,{C#Gamma,FNot C#Delta})}"
definition
"Perms = { z. ? Gamma Gamma' . z = (Gamma,{Gamma'}) & Gamma <~~> Gamma'}"
definition
"DAxioms = { z. ? p vs. z = ([FAtom Neg p vs,FAtom Pos p vs],{}) }"
lemma AxiomI: "[| Axioms <= A |] ==> [FAtom Pos p vs,FAtom Neg p vs] : deductions(A)"
apply(rule deductions.inferI)
apply(auto simp add: Axioms_def) done
lemma DAxiomsI: "[| DAxioms <= A |] ==> [FAtom Neg p vs,FAtom Pos p vs] : deductions(A)"
apply(rule deductions.inferI)
apply(auto simp add: DAxioms_def) done
lemma DisjI: "[| A0#A1#Gamma : deductions(A); Disjs <= A |] ==> (FConj Neg A0 A1#Gamma) : deductions(A)"
apply(rule deductions.inferI)
apply(auto simp add: Disjs_def) done
lemma ConjI: "[| (A0#Gamma) : deductions(A); (A1#Delta) : deductions(A); Conjs <= A |] ==> FConj Pos A0 A1#Gamma @ Delta : deductions(A)"
apply(rule_tac prems="{A0#Gamma,A1#Delta}" in deductions.inferI)
apply(auto simp add: Conjs_def) apply force done
lemma AllI: "[| instanceF w A#Gamma : deductions(R); w ~: freeVarsFL (FAll Pos A#Gamma); Alls <= R |] ==> (FAll Pos A#Gamma) : deductions(R)"
apply(rule_tac prems="{instanceF w A#Gamma}" in deductions.inferI)
apply(auto simp add: Alls_def) done
lemma ExI: "[| instanceF w A#Gamma : deductions(R); Exs <= R |] ==> (FAll Neg A#Gamma) : deductions(R)"
apply(rule_tac prems = "{instanceF w A#Gamma}" in deductions.inferI)
apply(auto simp add: Exs_def) done
lemma WeakI: "[| Gamma : deductions R; Weaks <= R |] ==> A#Gamma : deductions(R)"
apply(rule_tac prems="{Gamma}" in deductions.inferI)
apply(auto simp add: Weaks_def) done
lemma ContrI: "[| A#A#Gamma : deductions R; Contrs <= R |] ==> A#Gamma : deductions(R)"
apply(rule_tac prems="{A#A#Gamma}" in deductions.inferI)
apply(auto simp add: Contrs_def) done
lemma PermI: "[| Gamma' : deductions R; Gamma <~~> Gamma'; Perms <= R |] ==> Gamma : deductions(R)"
apply(rule_tac prems="{Gamma'}" in deductions.inferI)
apply(auto simp add: Perms_def) done
subsection "Derived Rules"
lemma WeakI1: "[| Gamma : deductions(A); Weaks <= A |] ==> (Delta @ Gamma) : deductions(A)"
apply (induct Delta, simp)
apply(auto intro: WeakI) done
lemma WeakI2: "[| Gamma : deductions(A); Perms <= A; Weaks <= A |] ==> (Gamma @ Delta) : deductions(A)"
apply(blast intro: PermI perm_append_swap WeakI1) done
lemma SATAxiomI: "[| Axioms <= A; Weaks <= A; Perms <= A; forms = [FAtom Pos n vs,FAtom Neg n vs] @ Gamma |] ==> forms : deductions(A)"
apply(simp only:)
apply(blast intro: WeakI2 AxiomI)
done
lemma DisjI1: "[| (A1#Gamma) : deductions(A); Disjs <= A; Weaks <= A |] ==> FConj Neg A0 A1#Gamma : deductions(A)"
apply(blast intro: DisjI WeakI)
done
lemma DisjI2: "!!A. [| (A0#Gamma) : deductions(A); Disjs <= A; Weaks <= A; Perms <= A |] ==> FConj Neg A0 A1#Gamma : deductions(A)"
apply(rule DisjI)
apply(rule PermI[OF _ perm.swap])
apply(rule WeakI)
.
\<comment> \<open>FIXME the following 4 lemmas could all be proved for the standard rule sets using monotonicity as below\<close>
\<comment> \<open>we keep proofs as in original, but they are slightly ugly, and do not state what is intuitively happening\<close>
lemma perm_tmp4: "Perms \<subseteq> R \<Longrightarrow> A @ (a # list) @ (a # list) : deductions R \<Longrightarrow> (a # a # A) @ list @ list : deductions R"
apply (rule PermI, auto)
apply(simp add: perm_count_conv count_append) done
lemma weaken_append[rule_format]: "Contrs <= R ==> Perms <= R ==> !A. A @ Gamma @ Gamma : deductions(R) --> A @ Gamma : deductions(R)"
apply (induct_tac Gamma, simp, rule) apply rule
apply(drule_tac x="a#a#A" in spec)
apply(erule_tac impE)
apply(rule perm_tmp4) apply(assumption, assumption)
apply(thin_tac "A @ (a # list) @ a # list \<in> deductions R")
apply simp
apply(frule_tac ContrI) apply assumption
apply(thin_tac "a # a # A @ list \<in> deductions R")
apply(rule PermI) apply assumption
apply(simp add: perm_count_conv count_append)
by assumption
\<comment> \<open>FIXME horrible\<close>
lemma ListWeakI: "Perms <= R ==> Contrs <= R ==> x # Gamma @ Gamma : deductions(R) ==> x # Gamma : deductions(R)"
by(rule weaken_append[of R "[x]" Gamma, simplified])
lemma ConjI': "[| (A0#Gamma) : deductions(A); (A1#Gamma) : deductions(A); Contrs <= A; Conjs <= A; Perms <= A |] ==> FConj Pos A0 A1#Gamma : deductions(A)"
apply(rule ListWeakI, assumption, assumption)
apply(rule ConjI) .
subsection "Standard Rule Sets For Predicate Calculus"
definition
PC :: "rule set" where
"PC = Union {Perms,Axioms,Conjs,Disjs,Alls,Exs,Weaks,Contrs,Cuts}"
definition
CutFreePC :: "rule set" where
"CutFreePC = Union {Perms,Axioms,Conjs,Disjs,Alls,Exs,Weaks,Contrs}"
lemma rulesInPCs: "Axioms <= PC" "Axioms <= CutFreePC"
"Conjs <= PC" "Conjs <= CutFreePC"
"Disjs <= PC" "Disjs <= CutFreePC"
"Alls <= PC" "Alls <= CutFreePC"
"Exs <= PC" "Exs <= CutFreePC"
"Weaks <= PC" "Weaks <= CutFreePC"
"Contrs <= PC" "Contrs <= CutFreePC"
"Perms <= PC" "Perms <= CutFreePC"
"Cuts <= PC"
"CutFreePC <= PC"
by(auto simp: PC_def CutFreePC_def)
subsection "Monotonicity for CutFreePC deductions"
\<comment> \<open>these lemmas can be used to replace complicated permutation reasoning above\<close>
\<comment> \<open>essentially if x is a deduction, and set x subset set y, then y is a deduction\<close>
definition
inDed :: "formula list => bool" where
"inDed xs \<longleftrightarrow> xs : deductions CutFreePC"
lemma perm: "! xs ys. xs <~~> ys --> (inDed xs = inDed ys)"
apply(subgoal_tac "! xs ys. xs <~~> ys --> inDed xs --> inDed ys")
apply (blast intro: perm_sym, clarify)
apply(simp add: inDed_def)
apply (rule PermI, assumption)
apply(rule perm_sym) apply assumption
by(blast intro!: rulesInPCs)
lemma contr: "! x xs. inDed (x#x#xs) --> inDed (x#xs)"
apply(simp add: inDed_def)
apply(blast intro!: ContrI rulesInPCs)
done
lemma weak: "! x xs. inDed xs --> inDed (x#xs)"
apply(simp add: inDed_def)
apply(blast intro!: WeakI rulesInPCs)
done
lemma inDed_mono[simplified inDed_def]: "inDed x ==> set x <= set y ==> inDed y"
using perm_weak_contr_mono[OF perm contr weak] .
end
|
theory WellTypedExp
imports WTMiscEnv
begin
(*
####################################
P1. expression syntax
####################################
*)
(* expressions *)
datatype p_const =
UnitConst
| IConst int
| BConst bool
| FixConst
(* arrays *)
| EmptyArrayConst
| ExtArrayConst
| ReadConst
| WriteConst
(* pairs *)
| UnpackConst
(* channels *)
| NewChanConst
| SendConst
| RecvConst
| ForkConst
datatype p_op =
I2Op "int \<Rightarrow> int \<Rightarrow> int"
| I1Op "int \<Rightarrow> int"
| C2Op "int \<Rightarrow> int \<Rightarrow> bool"
| C1Op "int \<Rightarrow> bool"
| R2Op "bool \<Rightarrow> bool \<Rightarrow> bool"
| R1Op "bool \<Rightarrow> bool"
datatype var_type =
VarType string
| LocType string string
datatype p_exp =
ConstExp p_const
| OpExp p_op
| VarExp var_type
| PairExp p_exp p_exp
| IfExp p_exp p_exp p_exp
| LamExp string p_exp
| AppExp p_exp p_exp
fun bin_const where
"bin_const ExtArrayConst = True"
| "bin_const ReadConst = True"
| "bin_const WriteConst = True"
| "bin_const SendConst = True"
| "bin_const c = False"
fun is_value :: "p_exp \<Rightarrow> bool" where
"is_value (ConstExp c) = True"
| "is_value (OpExp xop) = True"
| "is_value (VarExp (LocType x y)) = True"
| "is_value (PairExp v1 v2) = (is_value v1 \<and> is_value v2)"
| "is_value (LamExp x e) = True"
| "is_value (AppExp (ConstExp c) v) = (bin_const c \<and> is_value v)"
| "is_value other = False"
fun is_sexp :: "p_exp \<Rightarrow> bool" where
"is_sexp (ConstExp c) = True"
| "is_sexp (OpExp xop) = True"
| "is_sexp (VarExp (VarType x)) = False"
| "is_sexp (VarExp (LocType x y)) = True"
| "is_sexp (PairExp v1 v2) = (is_value v1 \<and> is_value v2)"
| "is_sexp (LamExp x e) = True"
| "is_sexp (AppExp (ConstExp FixConst) (LamExp x e)) = True"
| "is_sexp (AppExp (ConstExp c) v) = (bin_const c \<and> is_value v)"
| "is_sexp other = False"
fun free_vars :: "p_exp \<Rightarrow> string set" where
"free_vars (ConstExp c) = {}"
| "free_vars (OpExp xop) = {}"
| "free_vars (VarExp v) = (case v of
VarType x \<Rightarrow> {x}
| other \<Rightarrow> {}
)"
| "free_vars (PairExp e1 e2) = free_vars e1 \<union> free_vars e2"
| "free_vars (IfExp e1 e2 e3) = free_vars e1 \<union> free_vars e2 \<union> free_vars e3"
| "free_vars (LamExp x e) = free_vars e - {x}"
| "free_vars (AppExp e1 e2) = free_vars e1 \<union> free_vars e2"
fun ref_vars :: "p_exp \<Rightarrow> string set" where
"ref_vars (ConstExp c) = {}"
| "ref_vars (OpExp xop) = {}"
| "ref_vars (VarExp v) = (case v of
VarType x \<Rightarrow> {}
| LocType x y \<Rightarrow> {x, y}
)"
| "ref_vars (PairExp e1 e2) = ref_vars e1 \<union> ref_vars e2"
| "ref_vars (IfExp e1 e2 e3) = ref_vars e1 \<union> ref_vars e2 \<union> ref_vars e3"
| "ref_vars (LamExp x e) = ref_vars e"
| "ref_vars (AppExp e1 e2) = ref_vars e1 \<union> ref_vars e2"
fun res_vars :: "p_exp \<Rightarrow> res_id set" where
"res_vars (ConstExp c) = {}"
| "res_vars (OpExp xop) = {}"
| "res_vars (VarExp v) = (case v of
VarType x \<Rightarrow> {Var x}
| LocType x y \<Rightarrow> {Loc y}
)"
| "res_vars (PairExp e1 e2) = res_vars e1 \<union> res_vars e2"
| "res_vars (IfExp e1 e2 e3) = res_vars e1 \<union> res_vars e2 \<union> res_vars e3"
| "res_vars (LamExp x e) = res_vars e - {Var x}"
| "res_vars (AppExp e1 e2) = res_vars e1 \<union> res_vars e2"
definition non_prim_vars where
"non_prim_vars env e = { x | x. non_prim_entry env x \<and> x \<in> res_vars e }"
definition env_vars :: "(string \<Rightarrow> 'a option) \<Rightarrow> string set" where
"env_vars env = { x | x. env x \<noteq> None }"
definition use_env_vars where
"use_env_vars r_s = { x | x. r_s x \<noteq> NoPerm }"
definition own_env_vars where
"own_env_vars r_s = { x | x. r_s x = OwnPerm }"
(*
####################################
P4. type system for expressions
####################################
*)
definition pure_fun where
"pure_fun t1 t2 r = FunTy t1 t2 UsePerm r"
fun const_type :: "p_const \<Rightarrow> p_type set" where
"const_type UnitConst = {UnitTy}"
| "const_type (IConst i) = {IntTy}"
| "const_type (BConst b) = {BoolTy}"
| "const_type FixConst = {pure_fun (pure_fun t t (req_type t)) t Prim | t. fun_ty t \<and> unlim t}"
(* arrays: since t is unlim and arrays are unlim, no functions require ownership.
pairs are affine because they are only needed once. *)
| "const_type EmptyArrayConst = {pure_fun UnitTy (ArrayTy t) Prim | t. unlim t}"
| "const_type ExtArrayConst = {pure_fun (ArrayTy t) (FunTy t (ArrayTy t) OwnPerm Ref) Prim | t. unlim t}"
| "const_type ReadConst = {pure_fun (ArrayTy t) (pure_fun IntTy t Ref) Prim | t. unlim t}"
| "const_type WriteConst = {pure_fun (ArrayTy t) (FunTy (PairTy IntTy t OwnPerm) UnitTy OwnPerm Ref) Prim | t. unlim t}"
(* pairs: a reusable pair must be constructed from unlimited values + requires ownership of both its elements,
however permissions-wise it is treated like a var.
- an affine pair can be constructed from anything, and also requires ownership of both its elements
- for unpacking, the pair is assumed to be owned, whatever is put in *)
| "const_type UnpackConst = {FunTy (PairTy t1 t2 r) (FunTy (FunTy t1 (FunTy t2 tx r (as_aff r')) r (as_aff r')) tx r' (as_aff r)) r Prim | t1 t2 tx r r'. leq_perm r r'}"
(* channels: all uses of a channel use up ownership *)
| "const_type NewChanConst = {pure_fun UnitTy (PairTy (ChanTy t SEnd) (ChanTy t REnd) OwnPerm) Prim | t. True}"
| "const_type SendConst = {pure_fun (ChanTy t SEnd) (FunTy t UnitTy r Ref) Prim | t r. is_own r}"
| "const_type RecvConst = {pure_fun (ChanTy t REnd) t Prim | t. True }"
| "const_type ForkConst = {FunTy (FunTy UnitTy UnitTy UsePerm a) UnitTy r Prim | a r. is_own r}"
fun op_type :: "p_op \<Rightarrow> p_type" where
"op_type (I2Op xop) = pure_fun IntTy (pure_fun IntTy IntTy Prim) Prim"
| "op_type (I1Op xop) = pure_fun IntTy IntTy Prim"
| "op_type (C2Op xop) = pure_fun IntTy (pure_fun IntTy BoolTy Prim) Prim"
| "op_type (C1Op xop) = pure_fun IntTy BoolTy Prim"
| "op_type (R2Op xop) = pure_fun BoolTy (pure_fun BoolTy BoolTy Prim) Prim"
| "op_type (R1Op xop) = pure_fun BoolTy BoolTy Prim"
definition app_req where
"app_req rx1 rx2 r tau r_ex = (if req_type tau = Prim then empty_use_env else
diff_use_env (comp_use_env rx1 rx2) (comp_use_env (comp_use_env rx1 (lift_use_env rx2 r)) r_ex))"
definition pair_req where
"pair_req rx r_ex tau = (if req_type tau = Prim then empty_use_env else diff_use_env rx r_ex)"
fun safe_type where
"safe_type tau OwnPerm = True"
| "safe_type tau UsePerm = unlim tau"
| "safe_type tau NoPerm = False"
fun safe_type_x where
"safe_type_x tau OwnPerm = True"
| "safe_type_x tau UsePerm = unlim tau"
| "safe_type_x tau NoPerm = (req_type tau = Prim)"
fun safe_pair_aff where
"safe_pair_aff a NoPerm = False"
| "safe_pair_aff a UsePerm = (a \<noteq> Aff)"
| "safe_pair_aff a OwnPerm = True"
fun aff_leq where
"aff_leq Prim r = True"
| "aff_leq Ref NoPerm = False"
| "aff_leq Ref r = True"
| "aff_leq Aff OwnPerm = True"
| "aff_leq Aff r = False"
fun res_name where
"res_name (VarType x) = Var x"
| "res_name (LocType x y) = Loc x"
fun owner_name where
"owner_name (VarType x) = Var x"
| "owner_name (LocType x y) = Loc y"
fun value_req where
"value_req (VarType x) tau tau_x = True"
| "value_req (LocType x y) tau tau_x = (req_type tau = Ref \<and> req_type tau_x = Ref)"
fun well_typed :: "pt_env \<Rightarrow> perm_use_env \<Rightarrow> p_exp \<Rightarrow> p_type \<Rightarrow> perm_use_env \<Rightarrow> perm_use_env \<Rightarrow> bool" where
"well_typed env r_s1 (ConstExp c) tau r_s2 rx = (tau \<in> const_type c \<and> leq_use_env r_s2 r_s1 \<and> leq_use_env rx r_s2)"
| "well_typed env r_s1 (OpExp xop) tau r_s2 rx = (tau = op_type xop \<and> leq_use_env r_s2 r_s1 \<and> leq_use_env rx r_s2)"
| "well_typed env r_s1 (VarExp v) tau r_s2 rx = (\<exists> r_ex tau_x. env (res_name v) = Some tau \<and> env (owner_name v) = Some tau_x \<and> value_req v tau tau_x \<and>
leq_use_env (ereq_use_env (owner_name v) tau_x) r_s1 \<and> leq_use_env r_s2 (diff_use_env r_s1 (comp_use_env (ereq_use_env (owner_name v) tau_x) r_ex)) \<and>
leq_use_env rx r_s2 \<and> leq_use_env r_ex r_s1 \<and> leq_use_env (diff_use_env (ereq_use_env (owner_name v) tau_x) (comp_use_env (ereq_use_env (owner_name v) tau_x) r_ex)) rx)"
| "well_typed env r_s1 (PairExp e1 e2) tau r_sf rf = (\<exists> t1 t2 r r_s2 r_s3 rx1 rx2 r_ex. tau = PairTy t1 t2 r \<and>
well_typed env r_s1 e1 t1 r_s2 rx1 \<and> well_typed env r_s2 e2 t2 r_s3 rx2 \<and>
leq_use_env (lift_use_env rx1 r) r_s3 \<and> leq_use_env (lift_use_env rx2 r) r_s3 \<and> aff_leq (max_aff (req_type t1) (req_type t2)) r \<and>
disj_use_env (lift_use_env rx1 r) (lift_use_env rx2 r) \<and>
leq_use_env r_sf (diff_use_env r_s3 r_ex) \<and> leq_use_env rf r_sf \<and> leq_use_env r_ex r_s1 \<and>
leq_use_env (pair_req (comp_use_env (lift_use_env rx1 r) (lift_use_env rx2 r)) r_ex tau) rf
)"
| "well_typed env r_s1 (IfExp e1 e2 e3) tau r_s3 rx = (\<exists> rx' r_s2 rx1 rx2.
well_typed env r_s1 e1 BoolTy r_s2 rx' \<and> well_typed env r_s2 e2 tau r_s3 rx1 \<and> well_typed env r_s2 e3 tau r_s3 rx2 \<and>
rx = comp_use_env rx1 rx2)"
| "well_typed env r_s1 (LamExp x e) tau r_s2 rf = (\<exists> t1 t2 r a rx r_end r_s' r_ex. tau = FunTy t1 t2 r a \<and>
well_typed (add_env env (Var x) t1) (add_use_env rx (Var x) r) e t2 r_s' r_end \<and> aff_use_env rx a \<and>
leq_use_env rx r_s1 \<and> leq_use_env r_s2 (diff_use_env r_s1 r_ex) \<and> leq_use_env rf r_s2 \<and>
leq_use_env r_ex r_s1 \<and> leq_use_env (diff_use_env rx r_ex) rf)"
| "well_typed env r_s1 (AppExp e1 e2) tau r_sf rx = (\<exists> t1 r a r_s2 rx1 rx2 r_s3 r_ex.
well_typed env r_s1 e1 (FunTy t1 tau r a) r_s2 rx1 \<and> well_typed env r_s2 e2 t1 r_s3 rx2 \<and>
leq_use_env r_sf (diff_use_env r_s3 (comp_use_env (comp_use_env rx1 (lift_use_env rx2 r)) r_ex)) \<and>
leq_use_env (comp_use_env rx1 (lift_use_env rx2 r)) r_s3 \<and>
disj_use_env rx1 (lift_use_env rx2 r) \<and> leq_use_env rx r_sf \<and>
leq_use_env r_ex r_s1 \<and> leq_use_env (app_req rx1 rx2 r tau r_ex) rx
)"
(* - expression lemmas *)
lemma value_is_sexp: "is_value e \<Longrightarrow> is_sexp e"
apply (case_tac e)
apply (auto)
apply (case_tac x3)
apply (auto)
apply (case_tac x71)
apply (auto)
apply (case_tac x1)
apply (auto)
done
lemma e2_sexp: "\<lbrakk> is_sexp (AppExp e1 e2) \<rbrakk> \<Longrightarrow> is_sexp e2"
apply (case_tac e1)
apply (auto)
apply (case_tac e2)
apply (auto)
apply (case_tac x3)
apply (auto)
apply (case_tac x71)
apply (auto)
apply (case_tac x1a)
apply (auto)
done
end |
{-
Mapping cones or the homotopy cofiber/cokernel
-}
{-# OPTIONS --cubical --no-import-sorts --safe #-}
module Cubical.HITs.MappingCones.Base where
open import Cubical.Foundations.Prelude
private
variable
ℓ ℓ' ℓ'' : Level
data Cone {X : Type ℓ} {Y : Type ℓ'} (f : X → Y) : Type (ℓ-max ℓ ℓ') where
inj : Y → Cone f
hub : Cone f
spoke : (x : X) → hub ≡ inj (f x)
-- the attachment of multiple mapping cones
data Cones {X : Type ℓ} {Y : Type ℓ'} (A : Type ℓ'') (f : A → X → Y) : Type (ℓ-max (ℓ-max ℓ ℓ') ℓ'') where
inj : Y → Cones A f
hub : A → Cones A f
spoke : (a : A) (x : X) → hub a ≡ inj (f a x)
|
module GeoPhyInv
# required packages
using ParallelStencil
using Distances
using TimerOutputs
using LinearMaps
using Ipopt
using Optim, LineSearches
using DistributedArrays
using Calculus
using ProgressMeter
using Distributed
using SharedArrays
using Printf
using DataFrames
using SparseArrays
using Interpolations
using OrderedCollections
using CSV
using Statistics
using LinearAlgebra
using Random
using ImageFiltering
using NamedArrays
using Test
using AxisArrays
using Distributions
using StatsBase
using InteractiveUtils
using RecipesBase
using ColorSchemes
using FFTW
using HDF5
using SpecialFunctions
using DSP
using CUDA
using CUDA.CUSPARSE
CUDA.allowscalar(false)
include("params.jl")
# This type is extensively used to create named arrays with Symbols
NamedStack{T} =
NamedArray{T,1,Array{T,1},Tuple{OrderedCollections.OrderedDict{Symbol,Int64}}}
# a module with some util methods
include("Utils/Utils.jl")
include("Interpolation/Interpolation.jl")
# some structs used for multiple dispatch throughout this package
include("types.jl")
export Srcs, Recs, SSrcs
export FdtdAcoustic, FdtdElastic, FdtdAcousticBorn, AcousticBorn, ElasticBorn, FdtdAcousticVisco
# mutable data type for seismic medium + related methods
include("media/core.jl")
export Medium
# source-receiver geometry
include("ageom/core.jl")
export AGeom, AGeomss
#
include("database/core.jl")
# store records
include("records/core.jl")
export Records
# mutable data type for storing time-domain source wavelets
include("srcwav/wavelets.jl")
export ricker, ormsby
include("srcwav/core.jl")
export SrcWav
"""
Initialize the package with ParallelStencil, giving access to its main functionality.
```julia
@init_parallel_stencil(ndims, use_gpu, datatype, order)
```
# Arguments
* `ndims::Int`: the number of dimensions used for the stencil computations 2D or 3D
* `use_gpu::Bool` : use GPU for stencil computations or not
* `datatype`: the type of numbers used by field arrays (e.g. Float32 or Float64)
* `order::Int ∈ [2,4,6,8]` : order of the finite-difference stencil
"""
macro init_parallel_stencil(ndims::Int, use_gpu::Bool, datatype, order)
quote
# using ParallelStencil
# ParallelStencil.is_initialized() && ParallelStencil.@reset_parallel_stencil()
# ParallelStencil.@init_parallel_stencil(CUDA, $datatype, $ndims)
@eval GeoPhyInv begin
_fd.ndims = $ndims
@assert _fd.ndims ∈ [2, 3]
_fd.order = $order
@assert _fd.order ∈ [2, 4, 6, 8]
_fd.use_gpu = $use_gpu
_fd.datatype = $datatype
@assert _fd.datatype ∈ [Float32, Float64]
# extend by more points as we increase order, not sure if that is necessary!!!
_fd.npml = 20 + ($order - 1)
_fd.npextend = 20 + ($order - 1) # determines exmedium
ParallelStencil.is_initialized() && ParallelStencil.@reset_parallel_stencil()
# check whether 2D or 3D, and initialize ParallelStencils accordingly
@static if $use_gpu
# using CUDA
ParallelStencil.@init_parallel_stencil(CUDA, $datatype, $ndims)
else
ParallelStencil.@init_parallel_stencil(Threads, $datatype, $ndims)
end
include(
joinpath(
dirname(pathof(GeoPhyInv)),
"fdtd",
string("diff", $ndims, "D.jl"),
),
)
# define structs for wavefields in 2D/3D
include(joinpath(dirname(pathof(GeoPhyInv)), "fields.jl"))
export Fields
include(joinpath(dirname(pathof(GeoPhyInv)), "fdtd", "core.jl"))
include(joinpath(dirname(pathof(GeoPhyInv)), "born", "core.jl"))
nothing
end
end
end
export @init_parallel_stencil
export SeisForwExpt
# export update from GeoPhyInv, as it is commonly used
export update, update!
# # include modules (note: due to dependencies, order is important!)
# include("Operators.jl")
# include("Smooth.jl")
# include("IO.jl")
# include("Coupling.jl")
# include("fwi/fwi.jl")
# include("Poisson/Poisson.jl")
include("plots.jl")
# padarray,
# padarray!,
# SeisInvExpt,
# LS,
# LS_prior,
# Migr,
# Migr_FD
# # export the Expt for Poisson
# const PoissonExpt=GeoPhyInv.Poisson.ParamExpt
# export PoissonExpt
# mod!(a::PoissonExpt, b, c) = GeoPhyInv.Poisson.mod!(a, b, c)
# mod!(a::PoissonExpt, b) = GeoPhyInv.Poisson.mod!(a, b)
# mod!(a::PoissonExpt) = GeoPhyInv.Poisson.mod!(a)
# operator_Born(a::PoissonExpt, b) = GeoPhyInv.Poisson.operator_Born(a, b)
end # module
|
lemma null_sets_translation: assumes "N \<in> null_sets lborel" shows "{x. x - a \<in> N} \<in> null_sets lborel" |
Require Import Basics.
Require Import Types.
Require Import TruncType.
Require Import Colimits.Pushout Truncations.Core HIT.SetCone.
Local Open Scope path_scope.
Section AssumingUA.
Context `{ua:Univalence}.
(** We will now prove that for sets, epis and surjections are equivalent.*)
Definition isepi {X Y} `(f:X->Y) := forall Z: HSet,
forall g h: Y -> Z, g o f = h o f -> g = h.
Definition isepi_funext {X Y : Type} (f : X -> Y)
:= forall Z : HSet, forall g0 g1 : Y -> Z, g0 o f == g1 o f -> g0 == g1.
Definition isepi' {X Y} `(f : X -> Y) :=
forall (Z : HSet) (g : Y -> Z), Contr { h : Y -> Z | g o f = h o f }.
Lemma equiv_isepi_isepi' {X Y} f : @isepi X Y f <~> @isepi' X Y f.
Proof.
unfold isepi, isepi'.
apply (@equiv_functor_forall' _ _ _ _ _ (equiv_idmap _)); intro Z.
apply (@equiv_functor_forall' _ _ _ _ _ (equiv_idmap _)); intro g.
unfold equiv_idmap; simpl.
refine (transitivity (@equiv_sig_ind _ (fun h : Y -> Z => g o f = h o f) (fun h => g = h.1)) _).
(** TODO(JasonGross): Can we do this entirely by chaining equivalences? *)
apply equiv_iff_hprop.
{ intro hepi.
refine {| center := (g; idpath) |}.
intro xy; specialize (hepi xy).
apply path_sigma_uncurried.
exists hepi.
apply path_ishprop. }
{ intros hepi xy.
exact (ap pr1 ((contr (g; 1))^ @ contr xy)). }
Defined.
Definition equiv_isepi_isepi_funext {X Y : Type} (f : X -> Y)
: isepi f <~> isepi_funext f.
Proof.
apply equiv_iff_hprop.
- intros e ? g0 g1 h.
apply equiv_path_arrow.
apply e.
by apply path_arrow.
- intros e ? g0 g1 p.
apply path_arrow.
apply e.
by apply equiv_path_arrow.
Defined.
Section cones.
Lemma isepi'_contr_cone `{Funext} {A B : HSet} (f : A -> B) : isepi' f -> Contr (setcone f).
Proof.
intros hepi.
exists (setcone_point _).
pose (alpha1 := @pglue A B Unit f (const_tt _)).
pose (tot:= { h : B -> setcone f & tr o push o inl o f = h o f }).
transparent assert (l : tot).
{ simple refine (tr o _ o inl; _).
{ refine push. }
{ refine idpath. } }
pose (r := (@const B (setcone f) (setcone_point _); (ap (fun f => @tr 0 _ o f) (path_forall _ _ alpha1))) : tot).
subst tot.
assert (X : l = r).
{ let lem := constr:(fun X push' => hepi (Build_HSet (setcone f)) (tr o push' o @inl _ X)) in
pose (lem _ push).
refine (path_contr l r). }
subst l r.
pose (I0 b := ap10 (X ..1) b).
refine (Trunc_ind _ _).
pose (fun a : B + Unit => (match a as a return setcone_point _ = tr (push a) with
| inl a' => (I0 a')^
| inr tt => idpath
end)) as I0f.
refine (Pushout_ind _ (fun a' => I0f (inl a')) (fun u => (I0f (inr u))) _).
simpl. subst alpha1. intros.
unfold setcone_point.
subst I0. simpl.
pose (X..2) as p. simpl in p.
rewrite (transport_precompose f _ _ X..1) in p.
assert (H':=concat (ap (fun x => ap10 x a) p) (ap10_ap_postcompose tr (path_arrow (pushl o f) (pushr o const_tt _) pglue) _)).
rewrite ap10_path_arrow in H'.
clear p.
(** Apparently [pose; clearbody] is only ~.8 seconds, while [pose proof] is ~4 seconds? *)
pose (concat (ap10_ap_precompose f (X ..1) a)^ H') as p.
clearbody p.
simpl in p.
rewrite p.
rewrite transport_paths_Fr.
apply concat_Vp.
Qed.
End cones.
Lemma issurj_isepi {X Y} (f:X->Y): IsSurjection f -> isepi f.
Proof.
intros sur ? ? ? ep. apply path_forall. intro y.
specialize (sur y). pose (center (merely (hfiber f y))).
apply (Trunc_rec (n:=-1) (A:=(sig (fun x : X => f x = y))));
try assumption.
intros [x p]. set (p0:=apD10 ep x).
transitivity (g (f x)).
- by apply ap.
- transitivity (h (f x));auto with path_hints. by apply ap.
Qed.
Corollary issurj_isepi_funext {X Y} (f:X->Y) : IsSurjection f -> isepi_funext f.
Proof.
intro s.
apply equiv_isepi_isepi_funext.
by apply issurj_isepi.
Defined.
(** Old-style proof using polymorphic Omega. Needs resizing for the isepi proof to live in the
same universe as X and Y (the Z quantifier is instantiated with an HSet at a level higher)
<<
Lemma isepi_issurj {X Y} (f:X->Y): isepi f -> issurj f.
Proof.
intros epif y.
set (g :=fun _:Y => Unit_hp).
set (h:=(fun y:Y => (hp (hexists (fun _ : Unit => {x:X & y = (f x)})) _ ))).
assert (X1: g o f = h o f ).
- apply path_forall. intro x. apply path_equiv_biimp_rec;[|done].
intros _ . apply min1. exists tt. by (exists x).
- specialize (epif _ g h).
specialize (epif X1). clear X1.
set (p:=apD10 epif y).
apply (@minus1Trunc_map (sig (fun _ : Unit => sig (fun x : X => y = f x)))).
+ intros [ _ [x eq]].
exists x.
by symmetry.
+ apply (transport hproptype p tt).
Defined.
>> *)
Section isepi_issurj.
Context {X Y : HSet} (f : X -> Y) (Hisepi : isepi f).
Definition epif := equiv_isepi_isepi' _ Hisepi.
Definition fam (c : setcone f) : HProp.
Proof.
pose (fib y := hexists (fun x : X => f x = y)).
apply (fun f => @Trunc_rec _ _ HProp _ f c).
refine (Pushout_rec HProp fib (fun _ => Unit_hp) (fun x => _)).
(** Prove that the truncated sigma is equivalent to Unit *)
pose (contr_inhabited_hprop (fib (f x)) (tr (x; idpath))) as i.
apply path_hprop. simpl. simpl in i.
apply (equiv_contr_unit).
Defined.
Lemma isepi_issurj : IsSurjection f.
Proof.
intros y.
pose (i := isepi'_contr_cone _ epif).
assert (X0 : forall x : setcone f, fam x = fam (setcone_point f)).
{ intros. apply contr_dom_equiv. apply i. }
specialize (X0 (tr (push (inl y)))). simpl in X0.
exact (transport Contr (ap trunctype_type X0)^ _).
Defined.
End isepi_issurj.
Lemma isepi_isequiv X Y (f : X -> Y) `{IsEquiv _ _ f}
: isepi f.
Proof.
intros ? g h H'.
apply ap10 in H'.
apply path_forall.
intro x.
transitivity (g (f (f^-1 x))).
- by rewrite eisretr.
- transitivity (h (f (f^-1 x))).
* apply H'.
* by rewrite eisretr.
Qed.
End AssumingUA.
|
function [post nlZ dnlZ] = infFITC_EP(hyp, mean, cov, lik, x, y)
% FITC-EP approximation to the posterior Gaussian process. The function is
% equivalent to infEP with the covariance function:
% Kt = Q + G; G = diag(g); g = diag(K-Q); Q = Ku'*inv(Kuu + snu2*eye(nu))*Ku;
% where Ku and Kuu are covariances w.r.t. to inducing inputs xu and
% snu2 = sn2/1e6 is the noise of the inducing inputs. We fixed the standard
% deviation of the inducing inputs snu to be a one per mil of the measurement
% noise's standard deviation sn. In case of a likelihood without noise
% parameter sn2, we simply use snu2 = 1e-6.
% For details, see The Generalized FITC Approximation, Andrew Naish-Guzman and
% Sean Holden, NIPS, 2007.
%
% The implementation exploits the Woodbury matrix identity
% inv(Kt) = inv(G) - inv(G)*Ku'*inv(Kuu+Ku*inv(G)*Ku')*Ku*inv(G)
% in order to be applicable to large datasets. The computational complexity
% is O(n nu^2) where n is the number of data points x and nu the number of
% inducing inputs in xu.
% The posterior N(f|h,Sigma) is given by h = m+mu with mu = nn + P'*gg and
% Sigma = inv(inv(K)+diag(W)) = diag(d) + P'*R0'*R'*R*R0*P. Here, we use the
% site parameters: b,w=$b,\pi$=tnu,ttau, P=$P'$, nn=$\nu$, gg=$\gamma$
%
% The function takes a specified covariance function (see covFunctions.m) and
% likelihood function (see likFunctions.m), and is designed to be used with
% gp.m and in conjunction with covFITC.
%
% The inducing points can be specified through 1) the 2nd covFITC parameter or
% by 2) providing a hyp.xu hyperparameters. Note that 2) has priority over 1).
% In case 2) is provided and derivatives dnlZ are requested, there will also be
% a dnlZ.xu field allowing to optimise w.r.t. to the inducing points xu. However
% the derivatives dnlZ.xu can only be computed for one of the following eight
% covariance functions: cov{Matern|PP|RQ|SE}{iso|ard}.
%
% Copyright (c) by Hannes Nickisch, 2013-10-29.
%
% See also INFMETHODS.M, COVFITC.M.
persistent last_ttau last_tnu % keep tilde parameters between calls
tol = 1e-4; max_sweep = 20; min_sweep = 2; % tolerance to stop EP iterations
inf = 'infEP';
cov1 = cov{1}; if isa(cov1, 'function_handle'), cov1 = func2str(cov1); end
if ~strcmp(cov1,'covFITC'); error('Only covFITC supported.'), end % check cov
if isfield(hyp,'xu'), cov{3} = hyp.xu; end % hyp.xu is provided, replace cov{3}
[diagK,Kuu,Ku] = feval(cov{:}, hyp.cov, x); % evaluate covariance matrix
if ~isempty(hyp.lik) % hard coded inducing inputs noise
sn2 = exp(2*hyp.lik(end)); snu2 = 1e-6*sn2; % similar to infFITC
else
snu2 = 1e-6;
end
[n, D] = size(x); nu = size(Kuu,1);
m = feval(mean{:}, hyp.mean, x); % evaluate the mean vector
rot180 = @(A) rot90(rot90(A)); % little helper functions
chol_inv = @(A) rot180(chol(rot180(A))')\eye(nu); % chol(inv(A))
R0 = chol_inv(Kuu+snu2*eye(nu)); % initial R, used for refresh O(nu^3)
V = R0*Ku; d0 = diagK-sum(V.*V,1)'; % initial d, needed for refresh O(n*nu^2)
% A note on naming: variables are given short but descriptive names in
% accordance with Rasmussen & Williams "GPs for Machine Learning" (2006): mu
% and s2 are mean and variance, nu and tau are natural parameters. A leading t
% means tilde, a subscript _ni means "not i" (for cavity parameters), or _n
% for a vector of cavity parameters.
% marginal likelihood for ttau = tnu = zeros(n,1); equals n*log(2) for likCum*
nlZ0 = -sum(feval(lik{:}, hyp.lik, y, m, diagK, inf));
if any(size(last_ttau) ~= [n 1]) % find starting point for tilde parameters
ttau = zeros(n,1); % initialize to zero if we have no better guess
tnu = zeros(n,1);
[d,P,R,nn,gg] = epfitcRefresh(d0,Ku,R0,V, ttau,tnu); % compute initial repres.
nlZ = nlZ0;
else
ttau = last_ttau; % try the tilde values from previous call
tnu = last_tnu;
[d,P,R,nn,gg] = epfitcRefresh(d0,Ku,R0,V, ttau,tnu); % compute initial repres.
nlZ = epfitcZ(d,P,R,nn,gg,ttau,tnu,d0,R0,Ku,y,lik,hyp,m,inf);
if nlZ > nlZ0 % if zero is better ..
ttau = zeros(n,1); % .. then initialize with zero instead
tnu = zeros(n,1);
[d,P,R,nn,gg] = epfitcRefresh(d0,Ku,R0,V, ttau,tnu); % initial repres.
nlZ = nlZ0;
end
end
nlZ_old = Inf; sweep = 0; % converged, max. sweeps or min. sweeps?
while (abs(nlZ-nlZ_old) > tol && sweep < max_sweep) || sweep<min_sweep
nlZ_old = nlZ; sweep = sweep+1;
for i = randperm(n) % iterate EP updates (in random order) over examples
pi = P(:,i); t = R*(R0*pi); % temporary variables
sigmai = d(i) + t'*t; mui = nn(i) + pi'*gg; % post moments O(nu^2)
tau_ni = 1/sigmai-ttau(i); % first find the cavity distribution ..
nu_ni = mui/sigmai+m(i)*tau_ni-tnu(i); % .. params tau_ni and nu_ni
% compute the desired derivatives of the indivdual log partition function
[lZ, dlZ, d2lZ] = feval(lik{:}, hyp.lik, y(i), nu_ni/tau_ni, 1/tau_ni, inf);
ttaui = -d2lZ /(1+d2lZ/tau_ni);
ttaui = max(ttaui,0); % enforce positivity i.e. lower bound ttau by zero
tnui = ( dlZ + (m(i)-nu_ni/tau_ni)*d2lZ )/(1+d2lZ/tau_ni);
[d,P(:,i),R,nn,gg,ttau,tnu] = ... % update representation
epfitcUpdate(d,P(:,i),R,nn,gg, ttau,tnu,i,ttaui,tnui, m,d0,Ku,R0);
end
% recompute since repeated rank-one updates can destroy numerical precision
[d,P,R,nn,gg] = epfitcRefresh(d0,Ku,R0,V, ttau,tnu);
[nlZ,nu_n,tau_n] = epfitcZ(d,P,R,nn,gg,ttau,tnu,d0,R0,Ku,y,lik,hyp,m,inf);
end
if sweep == max_sweep
warning('maximum number of sweeps reached in function infEP')
end
last_ttau = ttau; last_tnu = tnu; % remember for next call
post.sW = sqrt(ttau); % unused for FITC_EP prediction with gp.m
dd = 1./(d0+1./ttau);
alpha = tnu./(1+d0.*ttau);
RV = R*V; R0tV = R0'*V;
alpha = alpha - (RV'*(RV*alpha)).*dd; % long alpha vector for ordinary infEP
post.alpha = R0tV*alpha; % alpha = R0'*V*inv(Kt+diag(1./ttau))*(tnu./ttau)
B = R0tV.*repmat(dd',nu,1); L = B*R0tV'; B = B*RV';
post.L = B*B' - L; % L = -R0'*V*inv(Kt+diag(1./ttau))*V'*R0
if nargout>2 % do we want derivatives?
dnlZ = hyp; % allocate space for derivatives
RVdd = RV.*repmat(dd',nu,1);
for i=1:length(hyp.cov)
[ddiagK,dKuu,dKu] = feval(cov{:}, hyp.cov, x, [], i); % eval cov derivatives
dA = 2*dKu'-R0tV'*dKuu; % dQ = dA*R0tV
w = sum(dA.*R0tV',2); v = ddiagK-w; % w = diag(dQ); v = diag(dK)-diag(dQ);
z = dd'*(v+w) - sum(RVdd.*RVdd,1)*v - sum(sum( (RVdd*dA)'.*(R0tV*RVdd') ));
dnlZ.cov(i) = (z - alpha'*(alpha.*v) - (alpha'*dA)*(R0tV*alpha))/2;
end
for i = 1:numel(hyp.lik) % likelihood hypers
dlik = feval(lik{:}, hyp.lik, y, nu_n./tau_n, 1./tau_n, inf, i);
dnlZ.lik(i) = -sum(dlik);
if i==numel(hyp.lik)
% since snu2 is a fixed fraction of sn2, there is a covariance-like term
% in the derivative as well
v = sum(R0tV.*R0tV,1)';
z = sum(sum( (RVdd*R0tV').^2 )) - sum(RVdd.*RVdd,1)*v;
z = z + post.alpha'*post.alpha - alpha'*(v.*alpha);
dnlZ.lik(i) = dnlZ.lik(i) + snu2*z;
end
end
[junk,dlZ] = feval(lik{:}, hyp.lik, y, nu_n./tau_n, 1./tau_n, inf);% mean hyps
for i = 1:numel(hyp.mean)
dm = feval(mean{:}, hyp.mean, x, i);
dnlZ.mean(i) = -dlZ'*dm;
end
if isfield(hyp,'xu') % derivatives w.r.t. inducing points xu
xu = cov{3};
cov = cov{2}; % get the non FITC part of the covariance function
Kpu = cov_deriv_sq_dist(cov,hyp.cov,xu,x); % d K(xu,x ) / d D^2
Kpuu = cov_deriv_sq_dist(cov,hyp.cov,xu); % d K(xu,xu) / d D^2
if iscell(cov), covstr = cov{1}; else covstr = cov; end
if ~ischar(covstr), covstr = func2str(covstr); end
if numel(strfind(covstr,'iso'))>0 % characteristic length scale
e = 2*exp(-2*hyp.cov(1));
else
e = 2*exp(-2*hyp.cov(1:D));
end
B = (R0'*R0)*Ku;
W = ttau;
t = W./(1+W.*d0);
diag_dK = alpha.*alpha + sum(RVdd.*RVdd,1)' - t;
v = diag_dK+t; % BdK = B * ( dnlZ/dK - diag(diag(dnlZ/dK)) )
BdK = (B*alpha)*alpha' - B.*repmat(v',nu,1);
BdK = BdK + (B*RVdd')*RVdd;
A = Kpu.*BdK; C = Kpuu.*(BdK*B'); C = diag(sum(C,2)-sum(A,2)) - C;
dnlZ.xu = A*x*diag(e) + C*xu*diag(e); % bring in data and inducing points
end
end
% refresh the representation of the posterior from initial and site parameters
% to prevent possible loss of numerical precision after many epfitcUpdates
% effort is O(n*nu^2) provided that nu<n
function [d,P,R,nn,gg] = epfitcRefresh(d0,P0,R0,R0P0, w,b)
nu = size(R0,1); % number of inducing points
rot180 = @(A) rot90(rot90(A)); % little helper functions
chol_inv = @(A) rot180(chol(rot180(A))')\eye(nu); % chol(inv(A))
t = 1./(1+d0.*w); % temporary variable O(n)
d = d0.*t; % O(n)
P = repmat(t',nu,1).*P0; % O(n*nu)
T = repmat((w.*t)',nu,1).*R0P0; % temporary variable O(n*nu^2)
R = chol_inv(eye(nu)+R0P0*T'); % O(n*nu^3)
nn = d.*b; % O(n)
gg = R0'*(R'*(R*(R0P0*(t.*b)))); % O(n*nu)
% compute the marginal likelihood approximation
% effort is O(n*nu^2) provided that nu<n
function [nlZ,nu_n,tau_n] = ...
epfitcZ(d,P,R,nn,gg,ttau,tnu, d0,R0,P0, y,lik,hyp,m,inf)
T = (R*R0)*P; % temporary variable
diag_sigma = d + sum(T.*T,1)'; mu = nn + P'*gg; % post moments O(n*nu^2)
tau_n = 1./diag_sigma-ttau; % compute the log marginal likelihood
nu_n = mu./diag_sigma-tnu+m.*tau_n; % vectors of cavity parameters
lZ = feval(lik{:}, hyp.lik, y, nu_n./tau_n, 1./tau_n, inf);
nu = size(gg,1);
U = (R0*P0)'.*repmat(1./sqrt(d0+1./ttau),1,nu);
L = chol(eye(nu)+U'*U);
ld = 2*sum(log(diag(L))) + sum(log(1+d0.*ttau));
t = T*tnu; tnu_Sigma_tnu = tnu'*(d.*tnu) + t'*t;
nlZ = ld/2 -sum(lZ) -tnu_Sigma_tnu/2 ...
-(nu_n-m.*tau_n)'*((ttau./tau_n.*(nu_n-m.*tau_n)-2*tnu)./(ttau+tau_n))/2 ...
+sum(tnu.^2./(tau_n+ttau))/2-sum(log(1+ttau./tau_n))/2;
% update the representation of the posterior to reflect modification of the site
% parameters by w(i) <- wi and b(i) <- bi
% effort is O(nu^2)
% Pi = P(:,i) is passed instead of P to prevent allocation of a new array
function [d,Pi,R,nn,gg,w,b] = ...
epfitcUpdate(d,Pi,R,nn,gg, w,b, i,wi,bi, m,d0,P0,R0)
dwi = wi-w(i); dbi = bi-b(i);
hi = nn(i) + m(i) + Pi'*gg; % posterior mean of site i O(nu)
t = 1+dwi*d(i);
d(i) = d(i)/t; % O(1)
nn(i) = d(i)*bi; % O(1)
r = 1+d0(i)*w(i);
r = r*r/dwi + r*d0(i);
v = R*(R0*P0(:,i));
r = 1/(r+v'*v);
if r>0
R = cholupdate(R,sqrt( r)*R'*v,'-');
else
R = cholupdate(R,sqrt(-r)*R'*v,'+');
end
gg = gg + ((dbi-dwi*(hi-m(i)))/t)*(R0'*(R'*(R*(R0*Pi)))); % O(nu^2)
w(i) = wi; b(i) = bi; % update site parameters O(1)
Pi = Pi/t; % O(nu)
|
(*
* 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 WordAbstract
imports L2Defs ExecConcrete
begin
definition [simplified]: "INT_MAX \<equiv> (2 :: int) ^ 31 - 1"
definition [simplified]: "INT_MIN \<equiv> - ((2 :: int) ^ 31)"
definition [simplified]: "UINT_MAX \<equiv> (2 :: nat) ^ 32 - 1"
definition [simplified]: "SHORT_MAX \<equiv> (2 :: int) ^ 15 - 1"
definition [simplified]: "SHORT_MIN \<equiv> - ((2 :: int) ^ 15)"
definition [simplified]: "USHORT_MAX \<equiv> (2 :: nat) ^ 16 - 1"
definition [simplified]: "CHAR_MAX \<equiv> (2 :: int) ^ 7 - 1"
definition [simplified]: "CHAR_MIN \<equiv> - ((2 :: int) ^ 7)"
definition [simplified]: "UCHAR_MAX \<equiv> (2 :: nat) ^ 8 - 1"
definition "WORD_MAX x \<equiv> ((2 ^ (len_of x - 1) - 1) :: int)"
definition "WORD_MIN x \<equiv> (- (2 ^ (len_of x - 1)) :: int)"
definition "UWORD_MAX x \<equiv> ((2 ^ (len_of x)) - 1 :: nat)"
lemma WORD_values [simplified]:
"WORD_MAX (TYPE(8 signed)) = (2 ^ 7 - 1)"
"WORD_MAX (TYPE(16 signed)) = (2 ^ 15 - 1)"
"WORD_MAX (TYPE(32 signed)) = (2 ^ 31 - 1)"
"WORD_MIN (TYPE(8 signed)) = - (2 ^ 7)"
"WORD_MIN (TYPE(16 signed)) = - (2 ^ 15)"
"WORD_MIN (TYPE(32 signed)) = - (2 ^ 31)"
"UWORD_MAX (TYPE(8)) = (2 ^ 8 - 1)"
"UWORD_MAX (TYPE(16)) = (2 ^ 16 - 1)"
"UWORD_MAX (TYPE(32)) = (2 ^ 32 - 1)"
by (auto simp: WORD_MAX_def WORD_MIN_def UWORD_MAX_def)
lemmas WORD_values_add1 =
WORD_values [THEN arg_cong [where f="\<lambda>x. x + 1"],
simplified semiring_norm, simplified numeral_One]
lemmas WORD_values_minus1 =
WORD_values [THEN arg_cong [where f="\<lambda>x. x - 1"],
simplified semiring_norm, simplified numeral_One nat_numeral]
lemmas [L1unfold] =
WORD_values [symmetric]
WORD_values_add1 [symmetric]
WORD_values_minus1 [symmetric]
(* These are added to the Polish simps after translation *)
lemma WORD_MAX_simps:
"WORD_MAX TYPE(32) = INT_MAX"
"WORD_MAX TYPE(16) = SHORT_MAX"
"WORD_MAX TYPE(8) = CHAR_MAX"
by (auto simp: INT_MAX_def SHORT_MAX_def CHAR_MAX_def WORD_MAX_def)
lemma WORD_MIN_simps:
"WORD_MIN TYPE(32) = INT_MIN"
"WORD_MIN TYPE(16) = SHORT_MIN"
"WORD_MIN TYPE(8) = CHAR_MIN"
by (auto simp: INT_MIN_def SHORT_MIN_def CHAR_MIN_def WORD_MIN_def)
lemma UWORD_MAX_simps:
"UWORD_MAX TYPE(32) = UINT_MAX"
"UWORD_MAX TYPE(16) = USHORT_MAX"
"UWORD_MAX TYPE(8) = UCHAR_MAX"
by (auto simp: UINT_MAX_def USHORT_MAX_def UCHAR_MAX_def UWORD_MAX_def)
lemma WORD_signed_to_unsigned [simp]:
"WORD_MAX TYPE('a signed) = WORD_MAX TYPE('a::len)"
"WORD_MIN TYPE('a signed) = WORD_MIN TYPE('a::len)"
"UWORD_MAX TYPE('a signed) = UWORD_MAX TYPE('a::len)"
by (auto simp: WORD_MAX_def WORD_MIN_def UWORD_MAX_def)
lemma INT_MIN_MAX_lemmas [simp]:
"unat (u :: word32) \<le> UINT_MAX"
"sint (s :: sword32) \<le> INT_MAX"
"INT_MIN \<le> sint (s :: sword32)"
"INT_MIN \<le> INT_MAX"
"INT_MIN \<le> sint (s :: sword32)"
"INT_MIN \<le> INT_MAX"
"INT_MIN \<le> 0"
"0 \<le> INT_MAX"
"\<not> (sint (s :: sword32) > INT_MAX)"
"\<not> (INT_MIN > sint (s :: sword32))"
"\<not> (unat (u :: word32) > UINT_MAX)"
unfolding UINT_MAX_def INT_MAX_def INT_MIN_def
using sint_range_size [where w=s, simplified word_size, simplified]
unat_lt2p [where 'a=32, simplified]
zle_add1_eq_le [where z=INT_MAX, symmetric]
less_eq_Suc_le not_less_eq_eq
unat_lt2p [where x=u]
by auto
(*
* The following set of theorems allow us to discharge simple
* equalities involving INT_MIN, INT_MAX and UINT_MAX without
* the constants being unfolded in the final output.
*
* For example:
*
* (4 < INT_MAX) becomes True
* (x < INT_MAX) remains (x < INT_MAX)
*)
lemma INT_MIN_comparisons [simp]:
"\<lbrakk> a \<le> - (2 ^ (len_of TYPE('a) - 1)) \<rbrakk> \<Longrightarrow> a \<le> WORD_MIN (TYPE('a::len))"
"a < - (2 ^ (len_of TYPE('a) - 1)) \<Longrightarrow> a < WORD_MIN (TYPE('a::len))"
"a \<ge> - (2 ^ (len_of TYPE('a) - 1)) \<Longrightarrow> a \<ge> WORD_MIN (TYPE('a::len))"
"a > - (2 ^ (len_of TYPE('a) - 1)) \<Longrightarrow> a \<ge> WORD_MIN (TYPE('a::len))"
by (auto simp: WORD_MIN_def)
lemma INT_MAX_comparisons [simp]:
"a \<le> (2 ^ (len_of TYPE('a) - 1)) - 1 \<Longrightarrow> a \<le> WORD_MAX (TYPE('a::len))"
"a < (2 ^ (len_of TYPE('a) - 1)) - 1 \<Longrightarrow> a < WORD_MAX (TYPE('a::len))"
"a \<ge> (2 ^ (len_of TYPE('a) - 1)) - 1 \<Longrightarrow> a \<ge> WORD_MAX (TYPE('a::len))"
"a > (2 ^ (len_of TYPE('a) - 1)) - 1 \<Longrightarrow> a \<ge> WORD_MAX (TYPE('a::len))"
by (auto simp: WORD_MAX_def)
lemma UINT_MAX_comparisons [simp]:
"x \<le> (2 ^ (len_of TYPE('a))) - 1 \<Longrightarrow> x \<le> UWORD_MAX (TYPE('a::len))"
"x < (2 ^ (len_of TYPE('a))) - 1 \<Longrightarrow> x \<le> UWORD_MAX (TYPE('a::len))"
"x \<ge> (2 ^ (len_of TYPE('a))) - 1 \<Longrightarrow> x \<ge> UWORD_MAX (TYPE('a::len))"
"x > (2 ^ (len_of TYPE('a))) - 1 \<Longrightarrow> x > UWORD_MAX (TYPE('a::len))"
by (auto simp: UWORD_MAX_def)
(*
* This definition is used when we are trying to introduce a new type
* in the program text: it simply states that introducing a given
* abstraction is desired in the current context.
*)
definition "introduce_typ_abs_fn f \<equiv> True"
declare introduce_typ_abs_fn_def [simp]
lemma introduce_typ_abs_fn:
"introduce_typ_abs_fn f"
by simp
(*
* Show that a binary operator "X" (of type "'a \<Rightarrow> 'a \<Rightarrow> bool") is an
* abstraction (over function f) of "X'".
*
* For example, (a \<le>\<^sub>i\<^sub>n\<^sub>t b) could be an abstraction of (a \<le>\<^sub>w\<^sub>3\<^sub>2 b)
* over the abstraction function "unat".
*)
definition
abstract_bool_binop :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> ('c \<Rightarrow> 'a)
\<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> ('c \<Rightarrow> 'c \<Rightarrow> bool) \<Rightarrow> bool"
where
"abstract_bool_binop P f X X' \<equiv> \<forall>a b. P (f a) (f b) \<longrightarrow> (X' a b = X (f a) (f b))"
(* Show that a binary operator "X" (of type "'a \<Rightarrow> 'a \<Rightarrow> 'b") abstracts "X'". *)
definition
abstract_binop :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> ('c \<Rightarrow> 'a)
\<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> 'a) \<Rightarrow> ('c \<Rightarrow> 'c \<Rightarrow> 'c) \<Rightarrow> bool"
where
"abstract_binop P f X X' \<equiv> \<forall>a b. P (f a) (f b) \<longrightarrow> (f (X' a b) = X (f a) (f b))"
(* The value "a" is the abstract version of "b" under precondition "P". *)
definition "abstract_val P a f b \<equiv> P \<longrightarrow> (a = f b)"
(* The variable "a" is the abstracted version of the variable "b". *)
definition "abs_var a f b \<equiv> abstract_val True a f b"
declare abstract_bool_binop_def [simp]
declare abstract_binop_def [simp]
declare abstract_val_def [simp]
declare abs_var_def [simp]
lemma abstract_val_trivial:
"abstract_val True (f b) f b"
by simp
lemma abstract_binop_is_abstract_val:
"abstract_binop P f X X' = (\<forall>a b. abstract_val (P (f a) (f b)) (X (f a) (f b)) f (X' a b))"
by auto
lemma abstract_expr_bool_binop:
"\<lbrakk> abstract_bool_binop E f X X';
introduce_typ_abs_fn f;
abstract_val P a f a';
abstract_val Q b f b' \<rbrakk> \<Longrightarrow>
abstract_val (P \<and> Q \<and> E a b) (X a b) id (X' a' b')"
by clarsimp
lemma abstract_expr_binop:
"\<lbrakk> abstract_binop E f X X';
abstract_val P a f a';
abstract_val Q b f b' \<rbrakk> \<Longrightarrow>
abstract_val (P \<and> Q \<and> E a b) (X a b) f (X' a' b')"
by clarsimp
lemma unat_abstract_bool_binops:
"abstract_bool_binop (\<lambda>_ _. True) (unat :: ('a::len) word \<Rightarrow> nat) (op <) (op <)"
"abstract_bool_binop (\<lambda>_ _. True) (unat :: ('a::len) word \<Rightarrow> nat) (op \<le>) (op \<le>)"
"abstract_bool_binop (\<lambda>_ _. True) (unat :: ('a::len) word \<Rightarrow> nat) (op =) (op =)"
by (auto simp: word_less_nat_alt word_le_nat_alt eq_iff)
lemmas unat_mult_simple = iffD1 [OF unat_mult_lem [unfolded word_bits_len_of]]
lemma le_to_less_plus_one:
"((a::nat) \<le> b) = (a < b + 1)"
by arith
lemma unat_abstract_binops:
"abstract_binop (\<lambda>a b. a + b \<le> UWORD_MAX TYPE('a::len)) (unat :: 'a word \<Rightarrow> nat) (op +) (op +)"
"abstract_binop (\<lambda>a b. a * b \<le> UWORD_MAX TYPE('a)) (unat :: 'a word \<Rightarrow> nat) (op * ) (op * )"
"abstract_binop (\<lambda>a b. a \<ge> b) (unat :: 'a word \<Rightarrow> nat) (op -) (op -)"
"abstract_binop (\<lambda>a b. True) (unat :: 'a word \<Rightarrow> nat) (op div) (op div)"
"abstract_binop (\<lambda>a b. True) (unat :: 'a word \<Rightarrow> nat) (op mod) (op mod)"
by (auto simp: unat_plus_if' unat_div unat_mod UWORD_MAX_def le_to_less_plus_one
WordAbstract.unat_mult_simple word_bits_def unat_sub word_le_nat_alt)
lemma snat_abstract_bool_binops:
"abstract_bool_binop (\<lambda>_ _. True) (sint :: ('a::len) signed word \<Rightarrow> int) (op <) (word_sless)"
"abstract_bool_binop (\<lambda>_ _. True) (sint :: 'a signed word \<Rightarrow> int) (op \<le>) (word_sle)"
"abstract_bool_binop (\<lambda>_ _. True) (sint :: 'a signed word \<Rightarrow> int) (op =) (op =)"
by (auto simp: word_sless_def word_sle_def less_le)
lemma snat_abstract_binops:
"abstract_binop (\<lambda>a b. WORD_MIN TYPE('a::len) \<le> a + b \<and> a + b \<le> WORD_MAX TYPE('a)) (sint :: 'a signed word \<Rightarrow> int) (op +) (op +)"
"abstract_binop (\<lambda>a b. WORD_MIN TYPE('a) \<le> a * b \<and> a * b \<le> WORD_MAX TYPE('a)) (sint :: 'a signed word \<Rightarrow> int) (op *) (op *)"
"abstract_binop (\<lambda>a b. WORD_MIN TYPE('a) \<le> a - b \<and> a - b \<le> WORD_MAX TYPE('a)) (sint :: 'a signed word \<Rightarrow> int) (op -) (op -)"
"abstract_binop (\<lambda>a b. WORD_MIN TYPE('a) \<le> a sdiv b \<and> a sdiv b \<le> WORD_MAX TYPE('a)) (sint :: 'a signed word \<Rightarrow> int) (op sdiv) (op sdiv)"
"abstract_binop (\<lambda>a b. WORD_MIN TYPE('a) \<le> a smod b \<and> a smod b \<le> WORD_MAX TYPE('a)) (sint :: 'a signed word \<Rightarrow> int) (op smod) (op smod)"
by (auto simp: signed_arith_sint word_size WORD_MIN_def WORD_MAX_def)
lemma abstract_val_signed_unary_minus:
"\<lbrakk> abstract_val P r sint r' \<rbrakk> \<Longrightarrow>
abstract_val (P \<and> (- r) \<le> WORD_MAX TYPE('a)) (- r) sint ( - (r' :: ('a :: len) signed word))"
apply clarsimp
using sint_range_size [where w=r']
apply -
apply (subst signed_arith_sint)
apply (clarsimp simp: word_size WORD_MAX_def)
apply simp
done
lemma abstract_val_unsigned_unary_minus:
"\<lbrakk> abstract_val P r unat r' \<rbrakk> \<Longrightarrow>
abstract_val P (if r = 0 then 0 else UWORD_MAX TYPE('a::len) + 1 - r) unat ( - (r' :: 'a word))"
by (clarsimp simp: unat_minus' word_size unat_eq_zero UWORD_MAX_def)
lemmas abstract_val_signed_ops [simplified simp_thms] =
abstract_expr_bool_binop [OF snat_abstract_bool_binops(1)]
abstract_expr_bool_binop [OF snat_abstract_bool_binops(2)]
abstract_expr_bool_binop [OF snat_abstract_bool_binops(3)]
abstract_expr_binop [OF snat_abstract_binops(1)]
abstract_expr_binop [OF snat_abstract_binops(2)]
abstract_expr_binop [OF snat_abstract_binops(3)]
abstract_expr_binop [OF snat_abstract_binops(4)]
abstract_expr_binop [OF snat_abstract_binops(5)]
abstract_val_signed_unary_minus
lemmas abstract_val_unsigned_ops [simplified simp_thms] =
abstract_expr_bool_binop [OF unat_abstract_bool_binops(1)]
abstract_expr_bool_binop [OF unat_abstract_bool_binops(2)]
abstract_expr_bool_binop [OF unat_abstract_bool_binops(3)]
abstract_expr_binop [OF unat_abstract_binops(1)]
abstract_expr_binop [OF unat_abstract_binops(2)]
abstract_expr_binop [OF unat_abstract_binops(3)]
abstract_expr_binop [OF unat_abstract_binops(4)]
abstract_expr_binop [OF unat_abstract_binops(5)]
abstract_val_unsigned_unary_minus
lemma mod_less:
"(a :: nat) < c \<Longrightarrow> a mod b < c"
by (metis less_trans mod_less_eq_dividend order_leE)
lemma abstract_val_ucast:
"\<lbrakk> introduce_typ_abs_fn (unat :: ('a::len) word \<Rightarrow> nat);
abstract_val P v unat v' \<rbrakk>
\<Longrightarrow> abstract_val (P \<and> v \<le> nat (WORD_MAX TYPE('a)))
(int v) sint (ucast (v' :: 'a word) :: 'a signed word)"
apply (clarsimp simp: uint_nat [symmetric])
apply (subst sint_eq_uint)
apply (rule not_msb_from_less)
apply (clarsimp simp: word_less_nat_alt unat_ucast WORD_MAX_def le_to_less_plus_one)
apply (subst (asm) nat_diff_distrib)
apply simp
apply clarsimp
apply clarsimp
apply (metis of_nat_numeral nat_numeral nat_power_eq of_nat_0_le_iff)
apply (clarsimp simp: uint_up_ucast is_up)
done
lemma abstract_val_scast:
"\<lbrakk> introduce_typ_abs_fn (sint :: ('a::len) signed word \<Rightarrow> int);
abstract_val P C' sint C \<rbrakk>
\<Longrightarrow> abstract_val (P \<and> 0 \<le> C') (nat C') unat (scast (C :: ('a::len) signed word) :: ('a::len) word)"
apply (clarsimp simp: down_cast_same [symmetric] is_down unat_ucast)
apply (subst sint_eq_uint)
apply (clarsimp simp: word_msb_sint)
apply (clarsimp simp: unat_def [symmetric])
apply (subst word_unat.norm_Rep [symmetric])
apply clarsimp
done
lemma abstract_val_scast_upcast:
"\<lbrakk> len_of TYPE('a::len) \<le> len_of TYPE('b::len);
abstract_val P C' sint C \<rbrakk>
\<Longrightarrow> abstract_val P (C') sint (scast (C :: 'a signed word) :: 'b signed word)"
by (clarsimp simp: down_cast_same [symmetric] sint_up_scast is_up)
lemma abstract_val_scast_downcast:
"\<lbrakk> len_of TYPE('b) < len_of TYPE('a::len);
abstract_val P C' sint C \<rbrakk>
\<Longrightarrow> abstract_val P (sbintrunc ((len_of TYPE('b::len) - 1)) C') sint (scast (C :: 'a signed word) :: 'b signed word)"
apply (clarsimp simp: scast_def word_of_int_def sint_uint bintrunc_mod2p [symmetric])
apply (subst bintrunc_sbintrunc_le)
apply clarsimp
apply (subst Abs_word_inverse)
apply (metis len_signed uint word_ubin.eq_norm)
apply clarsimp
done
lemma abstract_val_ucast_upcast:
"\<lbrakk> len_of TYPE('a::len) \<le> len_of TYPE('b::len);
abstract_val P C' unat C \<rbrakk>
\<Longrightarrow> abstract_val P (C') unat (ucast (C :: 'a word) :: 'b word)"
by (clarsimp simp: is_up unat_ucast_upcast)
lemma abstract_val_ucast_downcast:
"\<lbrakk> len_of TYPE('b::len) < len_of TYPE('a::len);
abstract_val P C' unat C \<rbrakk>
\<Longrightarrow> abstract_val P (C' mod (UWORD_MAX TYPE('b) + 1)) unat (ucast (C :: 'a word) :: 'b word)"
apply (clarsimp simp: scast_def word_of_int_def sint_uint UWORD_MAX_def)
unfolding ucast_def unat_def
apply (subst int_word_uint)
apply (metis (hide_lams, mono_tags) uint_mod uint_power_lower
unat_def unat_mod unat_power_lower)
done
(*
* The pair A/C are a valid abstraction/concrete-isation function pair,
* under the precondition's P and Q.
*)
definition
"valid_typ_abs_fn (P :: 'a \<Rightarrow> bool) (Q :: 'a \<Rightarrow> bool) (A :: 'c \<Rightarrow> 'a) (C :: 'a \<Rightarrow> 'c) \<equiv>
(\<forall>v. P v \<longrightarrow> A (C v) = v) \<and> (\<forall>v. Q (A v) \<longrightarrow> C (A v) = v)"
declare valid_typ_abs_fn_def [simp]
lemma valid_typ_abs_fn_id:
"valid_typ_abs_fn \<top> \<top> id id"
by clarsimp
lemma valid_typ_abs_fn_unit:
"valid_typ_abs_fn \<top> \<top> id (id :: unit \<Rightarrow> unit)"
by clarsimp
lemma valid_typ_abs_fn_unat:
"valid_typ_abs_fn (\<lambda>v. v \<le> UWORD_MAX TYPE('a::len)) \<top> (unat :: 'a word \<Rightarrow> nat) (of_nat :: nat \<Rightarrow> 'a word)"
by (clarsimp simp: unat_of_nat_eq UWORD_MAX_def le_to_less_plus_one)
lemma valid_typ_abs_fn_sint:
"valid_typ_abs_fn (\<lambda>v. WORD_MIN TYPE('a::len) \<le> v \<and> v \<le> WORD_MAX TYPE('a)) \<top> (sint :: 'a signed word \<Rightarrow> int) (of_int :: int \<Rightarrow> 'a signed word)"
by (clarsimp simp: sint_of_int_eq WORD_MIN_def WORD_MAX_def)
lemma valid_typ_abs_fn_tuple:
"\<lbrakk> valid_typ_abs_fn P_a Q_a abs_a conc_a; valid_typ_abs_fn P_b Q_b abs_b conc_b \<rbrakk> \<Longrightarrow>
valid_typ_abs_fn (\<lambda>(a, b). P_a a \<and> P_b b) (\<lambda>(a, b). Q_a a \<and> Q_b b) (map_prod abs_a abs_b) (map_prod conc_a conc_b)"
by clarsimp
lemma introduce_typ_abs_fn_tuple:
"\<lbrakk> introduce_typ_abs_fn abs_a; introduce_typ_abs_fn abs_b \<rbrakk> \<Longrightarrow>
introduce_typ_abs_fn (map_prod abs_a abs_b)"
by clarsimp
definition [simp]:
"corresTA P rx ex A C \<equiv> corresXF (\<lambda>s. s) (\<lambda>r s. rx r) (\<lambda>r s. ex r) P A C"
lemma corresTA_L2_gets:
"\<lbrakk> \<And>s. abstract_val (Q s) (C s) rx (C' s) \<rbrakk> \<Longrightarrow>
corresTA Q rx ex (L2_gets (\<lambda>s. C s) n) (L2_gets (\<lambda>s. C' s) n)"
apply (monad_eq simp: L2_defs corresXF_def)
done
lemma corresTA_L2_modify:
"\<lbrakk> \<And>s. abstract_val (P s) (m s) id (m' s) \<rbrakk> \<Longrightarrow>
corresTA P rx ex (L2_modify (\<lambda>s. m s)) (L2_modify (\<lambda>s. m' s))"
by (monad_eq simp: L2_modify_def corresXF_def)
lemma corresTA_L2_throw:
"\<lbrakk> abstract_val Q C ex C' \<rbrakk> \<Longrightarrow>
corresTA (\<lambda>_. Q) rx ex (L2_throw C n) (L2_throw C' n)"
apply (monad_eq simp: L2_defs corresXF_def)
done
lemma corresTA_L2_skip:
"corresTA \<top> rx ex L2_skip L2_skip"
apply (monad_eq simp: L2_defs corresXF_def)
done
lemma corresTA_L2_fail:
"corresTA \<top> rx ex L2_fail L2_fail"
by (clarsimp simp: L2_defs corresXF_def)
lemma corresTA_L2_seq':
fixes L' :: "('s, 'e + 'c1) nondet_monad"
fixes R' :: "'c1 \<Rightarrow> ('s, 'e + 'c2) nondet_monad"
fixes L :: "('s, 'ea + 'a1) nondet_monad"
fixes R :: "'a1 \<Rightarrow> ('s, 'ea + 'a2) nondet_monad"
shows
"\<lbrakk> corresTA P rx1 ex L L';
\<And>r. corresTA (Q (rx1 r)) rx2 ex (R (rx1 r)) (R' r) \<rbrakk> \<Longrightarrow>
corresTA P rx2 ex
(L2_seq L (\<lambda>r. L2_seq (L2_guard (\<lambda>s. Q r s)) (\<lambda>_. R r)))
(L2_seq L' (\<lambda>r. R' r))"
apply atomize
apply (clarsimp simp: L2_seq_def L2_guard_def)
apply (erule corresXF_join [where P'="\<lambda>x y s. rx1 y = x"])
apply (monad_eq simp: corresXF_def split: sum.splits)
apply clarsimp
apply (rule hoareE_TrueI)
apply simp
done
lemma corresTA_L2_seq:
"\<lbrakk> introduce_typ_abs_fn rx1;
corresTA P (rx1 :: 'a \<Rightarrow> 'b) ex L L';
\<And>r r'. abs_var r rx1 r' \<Longrightarrow> corresTA (\<lambda>s. Q r s) rx2 ex (\<lambda>s. R r s) (\<lambda>s. R' r' s) \<rbrakk> \<Longrightarrow>
corresTA P rx2 ex (L2_seq L (\<lambda>r. L2_seq (L2_guard (\<lambda>s. Q r s)) (\<lambda>_ s. R r s))) (L2_seq L' (\<lambda>r s. R' r s))"
by (rule corresTA_L2_seq', simp+)
lemma corresTA_L2_seq_unit:
fixes L' :: "('s, 'e + unit) nondet_monad"
fixes R' :: "unit \<Rightarrow> ('s, 'e + 'r) nondet_monad"
fixes L :: "('s, 'ea + unit) nondet_monad"
fixes R :: "('s, 'ea + 'ra) nondet_monad"
shows
"\<lbrakk> corresTA P id ex L L';
corresTA Q rx ex (\<lambda>s. R s) (\<lambda>s. R' () s) \<rbrakk> \<Longrightarrow>
corresTA P rx ex
(L2_seq L (\<lambda>r. L2_seq (L2_guard Q) (\<lambda>r s. R s)))
(L2_seq L' (\<lambda>r s. R' r s))"
by (rule corresTA_L2_seq', simp+)
lemma corresTA_L2_catch':
fixes L' :: "('s, 'e1 + 'c) nondet_monad"
fixes R' :: "'e1 \<Rightarrow> ('s, 'e2 + 'c) nondet_monad"
fixes L :: "('s, 'e1a + 'ca) nondet_monad"
fixes R :: "'e1a \<Rightarrow> ('s, 'e2a + 'ca) nondet_monad"
shows
"\<lbrakk> corresTA P rx ex1 L L';
\<And>r. corresTA (Q (ex1 r)) rx ex2 (R (ex1 r)) (R' r) \<rbrakk> \<Longrightarrow>
corresTA P rx ex2 (L2_catch L (\<lambda>r. L2_seq (L2_guard (\<lambda>s. Q r s)) (\<lambda>_. R r))) (L2_catch L' (\<lambda>r. R' r))"
apply atomize
apply (clarsimp simp: L2_seq_def L2_catch_def L2_guard_def)
apply (erule corresXF_except [where P'="\<lambda>x y s. ex1 y = x"])
apply (monad_eq simp: corresXF_def split: sum.splits cong: rev_conj_cong)
apply clarsimp
apply (rule hoareE_TrueI)
apply simp
done
lemma corresTA_L2_catch:
"\<lbrakk> introduce_typ_abs_fn ex1;
corresTA P rx ex1 L L';
\<And>r r'. abs_var r ex1 r' \<Longrightarrow> corresTA (Q r) rx ex2 (R r) (R' r') \<rbrakk> \<Longrightarrow>
corresTA P rx ex2 (L2_catch L (\<lambda>r. L2_seq (L2_guard (\<lambda>s. Q r s)) (\<lambda>_. R r))) (L2_catch L' (\<lambda>r. R' r))"
by (rule corresTA_L2_catch', simp+)
lemma corresTA_L2_while:
assumes init_corres: "abstract_val Q i rx i'"
and cond_corres: "\<And>r r' s. abs_var r rx r'
\<Longrightarrow> abstract_val (G r s) (C r s) id (C' r' s)"
and body_corres: "\<And>r r'. abs_var r rx r'
\<Longrightarrow> corresTA (P r) rx ex (B r) (B' r')"
shows "corresTA (\<lambda>_. Q) rx ex
(L2_guarded_while (\<lambda>r s. G r s) (\<lambda>r s. C r s) (\<lambda>r. L2_seq (L2_guard (\<lambda>s. P r s)) (\<lambda>_. B r)) i x)
(L2_while (\<lambda>r s. C' r s) B' i' x)"
proof -
note body_corres' =
corresXF_guarded_while_body [OF body_corres [unfolded corresTA_def]]
have init_corres':
"Q \<Longrightarrow> i = rx i'"
using init_corres
by simp
show ?thesis
apply (clarsimp simp: L2_defs guardE_def [symmetric] returnOk_liftE [symmetric])
apply (rule corresXF_assume_pre)
apply (rule corresXF_guarded_while [where P="\<lambda>r s. G (rx r) s"])
apply (cut_tac r'=x in body_corres, simp)
apply (monad_eq simp: guardE_def corresXF_def split: sum.splits)
apply (insert cond_corres)[1]
apply clarsimp
apply clarsimp
apply (rule hoareE_TrueI)
apply (clarsimp simp: init_corres)
apply (insert init_corres)[1]
apply (clarsimp)
apply (clarsimp simp: init_corres')
done
qed
lemma corresTA_L2_guard:
"\<lbrakk> \<And>s. abstract_val (Q s) (G s) id (G' s) \<rbrakk>
\<Longrightarrow> corresTA \<top> rx ex (L2_guard (\<lambda>s. G s \<and> Q s)) (L2_guard (\<lambda>s. G' s))"
apply (monad_eq simp: L2_defs corresXF_def)
done
lemma corresTA_L2_spec:
"(\<And>s t. abstract_val (Q s) (P s t) id (P' s t)) \<Longrightarrow>
corresTA Q rx ex (L2_spec {(s, t). P s t}) (L2_spec {(s, t). P' s t})"
apply (monad_eq simp: L2_defs corresXF_def in_liftE split: sum.splits)
apply (erule exI)
done
lemma corresTA_L2_condition:
"\<lbrakk> corresTA P rx ex L L';
corresTA Q rx ex R R';
\<And>s. abstract_val (T s) (C s) id (C' s) \<rbrakk>
\<Longrightarrow> corresTA T rx ex
(L2_condition (\<lambda>s. C s)
(L2_seq (L2_guard P) (\<lambda>_. L))
(L2_seq (L2_guard Q) (\<lambda>_. R))
) (L2_condition (\<lambda>s. C' s) L' R')"
apply atomize
apply (monad_eq simp: L2_defs corresXF_def Ball_def split: sum.splits)
apply force
done
(* Backup rule to corresTA_L2_call. Converts the return type of the function call. *)
lemma corresTA_L2_call':
"\<lbrakk> corresTA P f1 x1 A B;
valid_typ_abs_fn Q1 Q1' f1 f1';
valid_typ_abs_fn Q2 Q2' f2 f2'
\<rbrakk> \<Longrightarrow>
corresTA (\<lambda>s. P s) f2 x2
(L2_seq (L2_call A) (\<lambda>ret. (L2_seq (L2_guard (\<lambda>_. Q1' ret)) (\<lambda>_. L2_gets (\<lambda>_. f2 (f1' ret)) [''ret'']))))
(L2_call B)"
apply (clarsimp simp: L2_defs L2_call_def corresXF_def)
apply (monad_eq split: sum.splits)
apply (rule conjI)
apply metis
apply clarsimp
apply blast
done
lemma corresTA_L2_call:
"\<lbrakk> corresTA P rx ex A B \<rbrakk> \<Longrightarrow>
corresTA P rx ex' (L2_call A) (L2_call B)"
apply (clarsimp simp: L2_defs L2_call_def corresXF_def)
apply (monad_eq split: sum.splits)
apply fastforce
done
lemma corresTA_measure_call:
"\<lbrakk> monad_mono B; \<And>m. corresTA P rx id (A m) (B m) \<rbrakk> \<Longrightarrow>
corresTA P rx id (measure_call A) (measure_call B)"
by (simp add: corresXF_measure_call)
lemma corresTA_L2_unknown:
"corresTA \<top> rx ex (L2_unknown x) (L2_unknown x)"
apply (monad_eq simp: L2_defs corresXF_def)
done
lemma corresTA_L2_call_exec_concrete:
"\<lbrakk> corresTA P rx id A B \<rbrakk> \<Longrightarrow>
corresTA (\<lambda>s. \<forall>s'. s = st s' \<longrightarrow> P s') rx id
(exec_concrete st (L2_call A))
(exec_concrete st (L2_call B))"
apply (clarsimp simp: L2_defs L2_call_def corresXF_def)
apply (monad_eq split: sum.splits)
apply fastforce
done
lemma corresTA_L2_call_exec_abstract:
"\<lbrakk> corresTA P rx id A B \<rbrakk> \<Longrightarrow>
corresTA (\<lambda>s. P (st s)) rx id
(exec_abstract st (L2_call A))
(exec_abstract st (L2_call B))"
apply (clarsimp simp: L2_defs L2_call_def corresXF_def)
apply (monad_eq split: sum.splits)
apply fastforce
done
(* More backup rules for calls. *)
lemma corresTA_L2_call_exec_concrete':
"\<lbrakk> corresTA P f1 x1 A B;
valid_typ_abs_fn Q1 Q1' f1 f1';
valid_typ_abs_fn Q2 Q2' f2 f2'
\<rbrakk> \<Longrightarrow>
corresTA (\<lambda>s. \<forall>s'. s = st s' \<longrightarrow> P s') f2 x2
(L2_seq (exec_concrete st (L2_call A)) (\<lambda>ret. (L2_seq (L2_guard (\<lambda>_. Q1' ret)) (\<lambda>_. L2_gets (\<lambda>_. f2 (f1' ret)) [''ret'']))))
(exec_concrete st (L2_call B))"
apply (clarsimp simp: L2_defs L2_call_def corresXF_def)
apply (monad_eq split: sum.splits)
apply (rule conjI)
apply clarsimp
apply metis
apply clarsimp
apply blast
done
lemma corresTA_L2_call_exec_abstract':
"\<lbrakk> corresTA P f1 x1 A B;
valid_typ_abs_fn Q1 Q1' f1 f1';
valid_typ_abs_fn Q2 Q2' f2 f2'
\<rbrakk> \<Longrightarrow>
corresTA (\<lambda>s. P (st s)) f2 x2
(L2_seq (exec_abstract st (L2_call A)) (\<lambda>ret. (L2_seq (L2_guard (\<lambda>_. Q1' ret)) (\<lambda>_. L2_gets (\<lambda>_. f2 (f1' ret)) [''ret'']))))
(exec_abstract st (L2_call B))"
apply (clarsimp simp: L2_defs L2_call_def corresXF_def)
apply (monad_eq split: sum.splits)
apply (rule conjI)
apply metis
apply clarsimp
apply blast
done
lemma abstract_val_fun_app:
"\<lbrakk> abstract_val Q b id b'; abstract_val P a id a' \<rbrakk> \<Longrightarrow>
abstract_val (P \<and> Q) (f $ (a $ b)) f (a' $ b')"
by simp
lemma corresTA_precond_to_guard:
"corresTA (\<lambda>s. P s) rx ex A A' \<Longrightarrow> corresTA \<top> rx ex (L2_seq (L2_guard (\<lambda>s. P s)) (\<lambda>_. A)) A'"
apply (monad_eq simp: corresXF_def L2_defs split: sum.splits)
done
lemma corresTA_precond_to_asm:
"\<lbrakk> \<And>s. P s \<Longrightarrow> corresTA \<top> rx ex A A' \<rbrakk> \<Longrightarrow> corresTA P rx ex A A'"
by (clarsimp simp: corresXF_def)
lemma L2_guard_true: "L2_seq (L2_guard \<top>) A = A ()"
by (monad_eq simp: L2_defs)
lemma corresTA_simp_trivial_guard:
"corresTA P rx ex (L2_seq (L2_guard \<top>) A) C \<equiv> corresTA P rx ex (A ()) C"
by (simp add: L2_guard_true)
definition "L2_assume P \<equiv> condition P (returnOk ()) (selectE {})"
lemma L2_assume_alt_def:
"L2_assume P = (\<lambda>s. (if P s then {(Inr (), s)} else {}, False))"
by (monad_eq simp: L2_assume_def selectE_def)
lemma corresTA_assume_values:
"\<lbrakk> abstract_val P a f a'; corresTA \<top> rx ex X X' \<rbrakk>
\<Longrightarrow> corresTA \<top> rx ex (L2_seq (L2_assume (\<lambda>s. P \<longrightarrow> (\<exists>a'. a = f a'))) (\<lambda>_. X)) X'"
apply (monad_eq simp: corresXF_def L2_defs L2_assume_alt_def split: sum.splits)
apply force
done
lemma corresTA_extract_preconds_of_call_init:
"\<lbrakk> corresTA (\<lambda>s. P) rx ex A A' \<rbrakk> \<Longrightarrow> corresTA (\<lambda>s. P \<and> True) rx ex A A'"
by simp
lemma corresTA_extract_preconds_of_call_step:
"\<lbrakk> corresTA (\<lambda>s. (abs_var a f a' \<and> R) \<and> C) rx ex A A'; abstract_val Y a f a' \<rbrakk>
\<Longrightarrow> corresTA (\<lambda>s. R \<and> (Y \<and> C)) rx ex A A'"
by (clarsimp simp: corresXF_def)
lemma corresTA_extract_preconds_of_call_final:
"\<lbrakk> corresTA (\<lambda>s. (abs_var a f a') \<and> C) rx ex A A'; abstract_val Y a f a' \<rbrakk>
\<Longrightarrow> corresTA (\<lambda>s. (Y \<and> C)) rx ex A A'"
by (clarsimp simp: corresXF_def)
lemma corresTA_extract_preconds_of_call_final':
"\<lbrakk> corresTA (\<lambda>s. True \<and> C) rx ex A A' \<rbrakk>
\<Longrightarrow> corresTA (\<lambda>s. C) rx ex A A'"
by (clarsimp simp: corresXF_def)
lemma corresTA_case_prod:
"\<lbrakk> introduce_typ_abs_fn rx1;
introduce_typ_abs_fn rx2;
abstract_val (Q x) x (map_prod rx1 rx2) x';
\<And>a b a' b'. \<lbrakk> abs_var a rx1 a'; abs_var b rx2 b' \<rbrakk>
\<Longrightarrow> corresTA (P a b) rx ex (M a b) (M' a' b') \<rbrakk> \<Longrightarrow>
corresTA (\<lambda>s. case x of (a, b) \<Rightarrow> P a b s \<and> Q (a, b)) rx ex (case x of (a, b) \<Rightarrow> M a b) (case x' of (a, b) \<Rightarrow> M' a b)"
apply clarsimp
apply (rule corresXF_assume_pre)
apply (clarsimp simp: split_def map_prod_def)
done
lemma abstract_val_case_prod:
"\<lbrakk> abstract_val True r (map_prod f g) r';
\<And>a b a' b'. \<lbrakk> abs_var a f a'; abs_var b g b' \<rbrakk>
\<Longrightarrow> abstract_val (P a b) (M a b) h (M' a' b') \<rbrakk>
\<Longrightarrow> abstract_val (P (fst r) (snd r))
(case r of (a, b) \<Rightarrow> M a b) h
(case r' of (a, b) \<Rightarrow> M' a b)"
apply (case_tac r, case_tac r')
apply (clarsimp simp: map_prod_def)
done
lemma abstract_val_case_prod_fun_app:
"\<lbrakk> abstract_val True r (map_prod f g) r';
\<And>a b a' b'. \<lbrakk> abs_var a f a'; abs_var b g b' \<rbrakk>
\<Longrightarrow> abstract_val (P a b) (M a b s) h (M' a' b' s) \<rbrakk>
\<Longrightarrow> abstract_val (P (fst r) (snd r))
((case r of (a, b) \<Rightarrow> M a b) s) h
((case r' of (a, b) \<Rightarrow> M' a b) s)"
apply (case_tac r, case_tac r')
apply (clarsimp simp: map_prod_def)
done
lemma abstract_val_of_nat:
"abstract_val (r \<le> UWORD_MAX TYPE('a::len)) r unat (of_nat r :: 'a word)"
by (clarsimp simp: unat_of_nat_eq UWORD_MAX_def le_to_less_plus_one)
lemma abstract_val_of_int:
"abstract_val (WORD_MIN TYPE('a::len) \<le> r \<and> r \<le> WORD_MAX TYPE('a)) r sint (of_int r :: 'a signed word)"
by (clarsimp simp: sint_of_int_eq WORD_MIN_def WORD_MAX_def)
lemma abstract_val_tuple:
"\<lbrakk> abstract_val P a absL a';
abstract_val Q b absR b' \<rbrakk> \<Longrightarrow>
abstract_val (P \<and> Q) (a, b) (map_prod absL absR) (a', b')"
by clarsimp
lemma abstract_val_func:
"\<lbrakk> abstract_val P a id a'; abstract_val Q b id b' \<rbrakk>
\<Longrightarrow> abstract_val (P \<and> Q) (f a b) id (f a' b')"
by simp
lemma abstract_val_conj:
"\<lbrakk> abstract_val P a id a';
abstract_val Q b id b' \<rbrakk> \<Longrightarrow>
abstract_val (P \<and> (a \<longrightarrow> Q)) (a \<and> b) id (a' \<and> b')"
apply clarsimp
apply blast
done
lemma abstract_val_disj:
"\<lbrakk> abstract_val P a id a';
abstract_val Q b id b' \<rbrakk> \<Longrightarrow>
abstract_val (P \<and> (\<not> a \<longrightarrow> Q)) (a \<or> b) id (a' \<or> b')"
apply clarsimp
apply blast
done
lemma abstract_val_unwrap:
"\<lbrakk> introduce_typ_abs_fn f; abstract_val P a f b \<rbrakk>
\<Longrightarrow> abstract_val P a id (f b)"
by simp
lemma abstract_val_uint:
"\<lbrakk> introduce_typ_abs_fn unat; abstract_val P x unat x' \<rbrakk>
\<Longrightarrow> abstract_val P (int x) id (uint x')"
by (clarsimp simp: uint_nat)
lemma corresTA_L2_recguard:
"corresTA (\<lambda>s. P s) rx ex A A' \<Longrightarrow>
corresTA \<top> rx ex (L2_recguard m (L2_seq (L2_guard (\<lambda>s. P s)) (\<lambda>_. A))) (L2_recguard m A')"
by (monad_eq simp: corresXF_def L2_defs split: sum.splits)
lemma corresTA_recguard_0:
"corresTA st rx ex (L2_recguard 0 A) C"
by (clarsimp simp: L2_recguard_def corresXF_def)
lemma abstract_val_lambda:
"\<lbrakk> \<And>v. abstract_val (P v) (a v) id (a' v) \<rbrakk> \<Longrightarrow>
abstract_val (\<forall>v. P v) (\<lambda>v. a v) id (\<lambda>v. a' v)"
by auto
(* Rules for translating simpl wrappers. *)
lemma corresTA_call_L1:
"abstract_val True arg_xf id arg_xf' \<Longrightarrow>
corresTA \<top> id id
(L2_call_L1 arg_xf gs ret_xf l1body)
(L2_call_L1 arg_xf' gs ret_xf l1body)"
apply (unfold corresTA_def abstract_val_def id_def)
apply (subst (asm) simp_thms)
apply (erule subst)
apply (rule corresXF_id[simplified id_def])
done
lemma abstract_val_call_L1_args:
"abstract_val P x id x' \<Longrightarrow> abstract_val P y id y' \<Longrightarrow>
abstract_val P (x and y) id (x' and y')"
by simp
lemma abstract_val_call_L1_arg:
"abs_var x id x' \<Longrightarrow> abstract_val P (\<lambda>s. f s = x) id (\<lambda>s. f s = x')"
by simp
(* Variable abstraction *)
lemma abstract_val_abs_var [consumes 1]:
"\<lbrakk> abs_var a f a' \<rbrakk> \<Longrightarrow> abstract_val True a f a'"
by (clarsimp simp: fun_upd_def split: if_splits)
lemma abstract_val_abs_var_concretise [consumes 1]:
"\<lbrakk> abs_var a A a'; introduce_typ_abs_fn A; valid_typ_abs_fn PA PC A (C :: 'a \<Rightarrow> 'c) \<rbrakk>
\<Longrightarrow> abstract_val (PC a) (C a) id a'"
by (clarsimp simp: fun_upd_def split: if_splits)
lemma abstract_val_abs_var_give_up [consumes 1]:
"\<lbrakk> abs_var a id a' \<rbrakk> \<Longrightarrow> abstract_val True (A a) A a'"
by (clarsimp simp: fun_upd_def split: if_splits)
(* Misc *)
lemma len_of_word_comparisons [L2opt]:
"len_of TYPE(32) \<le> len_of TYPE(32)"
"len_of TYPE(16) \<le> len_of TYPE(32)"
"len_of TYPE( 8) \<le> len_of TYPE(32)"
"len_of TYPE(16) \<le> len_of TYPE(16)"
"len_of TYPE( 8) \<le> len_of TYPE(16)"
"len_of TYPE( 8) \<le> len_of TYPE( 8)"
"len_of TYPE(16) < len_of TYPE(32)"
"len_of TYPE( 8) < len_of TYPE(32)"
"len_of TYPE( 8) < len_of TYPE(16)"
"len_of TYPE('a::len signed) = len_of TYPE('a)"
"(len_of TYPE('a) = len_of TYPE('a)) = True"
by auto
lemma scast_ucast_simps [simp, L2opt]:
"\<lbrakk> len_of TYPE('b) \<le> len_of TYPE('a); len_of TYPE('c) \<le> len_of TYPE('b) \<rbrakk> \<Longrightarrow>
(scast (ucast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = ucast a"
"\<lbrakk> len_of TYPE('c) \<le> len_of TYPE('a); len_of TYPE('c) \<le> len_of TYPE('b) \<rbrakk> \<Longrightarrow>
(scast (ucast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = ucast a"
"\<lbrakk> len_of TYPE('a) \<le> len_of TYPE('b); len_of TYPE('c) \<le> len_of TYPE('b) \<rbrakk> \<Longrightarrow>
(scast (ucast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = ucast a"
"\<lbrakk> len_of TYPE('a) \<le> len_of TYPE('b) \<rbrakk> \<Longrightarrow>
(scast (scast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = scast a"
"\<lbrakk> len_of TYPE('b) \<le> len_of TYPE('a); len_of TYPE('c) \<le> len_of TYPE('b) \<rbrakk> \<Longrightarrow>
(ucast (scast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = scast a"
"\<lbrakk> len_of TYPE('c) \<le> len_of TYPE('a); len_of TYPE('c) \<le> len_of TYPE('b) \<rbrakk> \<Longrightarrow>
(ucast (scast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = scast a"
"\<lbrakk> len_of TYPE('a) \<le> len_of TYPE('b); len_of TYPE('c) \<le> len_of TYPE('b) \<rbrakk> \<Longrightarrow>
(ucast (scast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = scast a"
"\<lbrakk> len_of TYPE('c) \<le> len_of TYPE('b) \<rbrakk> \<Longrightarrow>
(ucast (ucast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = ucast a"
"\<lbrakk> len_of TYPE('a) \<le> len_of TYPE('b) \<rbrakk> \<Longrightarrow>
(ucast (ucast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = ucast a"
"\<lbrakk> len_of TYPE('a) \<le> len_of TYPE('b) \<rbrakk> \<Longrightarrow>
(scast (scast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = scast a"
by (auto simp: is_up is_down
scast_ucast_1 scast_ucast_3 scast_ucast_4
ucast_scast_1 ucast_scast_3 ucast_scast_4
scast_scast_a scast_scast_b
ucast_ucast_a ucast_ucast_b)
declare len_signed [L2opt]
lemmas [L2opt] = zero_sle_ucast_up
lemma zero_sle_ucast_WORD_MAX [L2opt]:
"(0 <=s ((ucast (b::('a::len) word)) :: ('a::len) signed word))
= (uint b \<le> WORD_MAX (TYPE('a)))"
by (clarsimp simp: WORD_MAX_def zero_sle_ucast)
lemmas [L2opt] =
is_up is_down unat_ucast_upcast sint_ucast_eq_uint
lemmas [L2opt] =
ucast_down_add scast_down_add
ucast_down_minus scast_down_minus
ucast_down_mult scast_down_mult
(*
* Setup word abstraction rules.
*)
named_theorems word_abs
(* Common word abstraction rules. *)
lemmas [word_abs] =
corresTA_L2_gets
corresTA_L2_modify
corresTA_L2_throw
corresTA_L2_skip
corresTA_L2_fail
corresTA_L2_seq
corresTA_L2_seq_unit
corresTA_L2_catch
corresTA_L2_while
corresTA_L2_guard
corresTA_L2_spec
corresTA_L2_condition
corresTA_L2_unknown
corresTA_L2_recguard
corresTA_case_prod
corresTA_L2_call_exec_concrete'
corresTA_L2_call_exec_concrete
corresTA_L2_call_exec_abstract'
corresTA_L2_call_exec_abstract
corresTA_L2_call'
corresTA_L2_call
corresTA_measure_call
corresTA_call_L1
lemmas [word_abs] =
abstract_val_tuple
abstract_val_conj
abstract_val_disj
abstract_val_case_prod
abstract_val_trivial
abstract_val_of_int
abstract_val_of_nat
abstract_val_call_L1_arg
abstract_val_call_L1_args
abstract_val_abs_var_give_up
abstract_val_abs_var_concretise
abstract_val_abs_var
lemmas word_abs_base [word_abs] =
valid_typ_abs_fn_id [where 'a="'a::c_type"]
valid_typ_abs_fn_id [where 'a="bool"]
valid_typ_abs_fn_id [where 'a="c_exntype"]
valid_typ_abs_fn_tuple
valid_typ_abs_fn_unit
valid_typ_abs_fn_sint
valid_typ_abs_fn_unat
len_of_word_comparisons
(*
* Signed word abstraction rules: sword32 \<rightarrow> int
*)
lemmas word_abs_sword32 =
abstract_val_signed_ops
abstract_val_scast
abstract_val_scast_upcast
abstract_val_scast_downcast
abstract_val_unwrap [where f=sint]
introduce_typ_abs_fn [where f="sint :: (sword32 \<Rightarrow> int)"]
introduce_typ_abs_fn [where f="sint :: (sword16 \<Rightarrow> int)"]
introduce_typ_abs_fn [where f="sint :: (sword8 \<Rightarrow> int)"]
(*
* Unsigned word abstraction rules: word32 \<rightarrow> nat
*)
lemmas word_abs_word32 =
abstract_val_unsigned_ops
abstract_val_uint
abstract_val_ucast
abstract_val_ucast_upcast
abstract_val_ucast_downcast
abstract_val_unwrap [where f=unat]
introduce_typ_abs_fn [where f="unat :: (word32 \<Rightarrow> nat)"]
introduce_typ_abs_fn [where f="unat :: (word16 \<Rightarrow> nat)"]
introduce_typ_abs_fn [where f="unat :: (word8 \<Rightarrow> nat)"]
(* 'a \<rightarrow> 'a *)
lemmas word_abs_default =
introduce_typ_abs_fn [where f="id :: ('a::c_type \<Rightarrow> 'a)"]
introduce_typ_abs_fn [where f="id :: (bool \<Rightarrow> bool)"]
introduce_typ_abs_fn [where f="id :: (c_exntype \<Rightarrow> c_exntype)"]
introduce_typ_abs_fn [where f="id :: (unit \<Rightarrow> unit)"]
introduce_typ_abs_fn_tuple
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.