text
stringlengths 0
3.34M
|
---|
module SQLite3.Direct
import CUtils
import Control.Monad.Either
import Control.Monad.Trans
import Data.Buffer
import SQLite3.Bindings
import Syntax.WithProof
import public Data.List.Quantifiers
import public SQLite3.Constants
export
record Handle where
constructor MkHandle
phandle : Ptr PrimHandle
export
record LibError where
constructor MkLibError
code : ResultCode
msg : String
export
Show LibError where
show err = show err.code <+> ": " <+> show err.msg
export
data Error : Type where
ALibError : LibError -> Error
GenericError : String -> Error
ImpossibleError : String -> Error
export
Show Error where
show (ALibError err) = "Library Error: " <+> show err
show (GenericError msg) = msg
show (ImpossibleError msg) = "IMPOSSIBLE ERROR: " <+> msg
mk_lib_error : HasIO m => Handle -> ResultCode -> m LibError
mk_lib_error handle code = do
msg <- primIO $ sqlite3_errmsg handle.phandle
pure $ MkLibError code msg
return_error : MonadError Error m => HasIO m => Handle -> ResultCode -> m a
return_error handle code = mk_lib_error handle code >>= throwError . ALibError
process_result_code : MonadError Error m => HasIO m => (rc : Int) -> m ResultCode
process_result_code rc = do
case ResultCode.from_raw rc of
Just x => pure x
Nothing => throwError $ ImpossibleError $ "got unknown error code: " <+> show rc
check_lib_error' : MonadError Error m => HasIO m => Handle -> Int -> m ()
check_lib_error' handle rc = do
process_result_code rc >>= \case
Ok => pure ()
code => return_error handle code
check_lib_error : MonadError Error m => HasIO m => Handle -> m ()
check_lib_error handle = do
rc <- primIO $ sqlite3_errcode handle.phandle
check_lib_error' handle rc
export
open_file : HasIO m => (path : String) -> m (Either Error Handle)
open_file path = runEitherT {m} $ do
pphandle <- remember <$> malloc sizeof_ptr
rc <- primIO $ sqlite3_open path pphandle
handle <- MkHandle <$> join_ptr pphandle
check_lib_error' handle rc
pure handle
export
close : HasIO m => Handle -> m (Either Error ())
close handle = runEitherT {m} $ do
rc <- primIO $ sqlite3_close handle.phandle
check_lib_error' handle rc
export
record Stmt where
constructor MkStmt
pstmt : Ptr PrimStmt
export
prepare : HasIO m => Handle -> (zsql : String) -> m (Either Error Stmt)
prepare handle zsql = runEitherT {m} $ do
ppstmt <- remember <$> malloc sizeof_ptr
rc <- primIO $ sqlite3_prepare_v2 handle.phandle zsql (-1) ppstmt nullptr
pstmt <- join_ptr ppstmt
check_lib_error' handle rc
pure $ MkStmt pstmt
||| returns True if succeeds
||| returns False if done
export
step : HasIO m => Handle -> Stmt -> m (Either Error Bool)
step handle stmt = runEitherT {m} $ do
rc <- primIO $ sqlite3_step stmt.pstmt
process_result_code rc >>= \case
Row => pure True
Done => pure False
code => return_error handle code
export
reset : HasIO m => Handle -> Stmt -> m (Either Error ())
reset handle stmt = runEitherT {m} $ do
rc <- primIO $ sqlite3_step stmt.pstmt
check_lib_error' handle rc
export
finalize : HasIO m => Handle -> Stmt -> m (Either Error ())
finalize handle stmt = runEitherT {m} $ do
rc <- primIO $ sqlite3_finalize stmt.pstmt
check_lib_error' handle rc
check_column_lib_error : MonadError Error m => HasIO m => Handle -> m ()
check_column_lib_error handle = do
rc <- primIO $ sqlite3_errcode handle.phandle
process_result_code rc >>= \case
Row => pure ()
code => throwError $ GenericError $ "unexpected code: " <+> show code
export
column_count : HasIO m => Handle -> Stmt -> m (Either Error Nat)
column_count handle stmt = runEitherT {m} $ do
x <- primIO $ sqlite3_column_count stmt.pstmt
check_column_lib_error handle
pure $ cast x
export
column_int : HasIO m => Handle -> Stmt -> (col : Nat) -> m (Either Error Int32)
column_int handle stmt col = runEitherT {m} $ do
x <- primIO $ sqlite3_column_int stmt.pstmt (cast col)
check_column_lib_error handle
pure x
export
column_int64 : HasIO m => Handle -> Stmt -> (col : Nat) -> m (Either Error Int64)
column_int64 handle stmt col = runEitherT {m} $ do
x <- primIO $ sqlite3_column_int64 stmt.pstmt (cast col)
check_column_lib_error handle
pure x
export
column_double : HasIO m => Handle -> Stmt -> (col : Nat) -> m (Either Error Double)
column_double handle stmt col = runEitherT {m} $ do
x <- primIO $ sqlite3_column_double stmt.pstmt (cast col)
check_column_lib_error handle
pure x
public export
record Blob where
constructor MkBlob
ptr : AnyPtr
size : Int
export
column_blob : HasIO m => Handle -> Stmt -> (col : Nat) -> m (Either Error Blob)
column_blob handle stmt col = runEitherT {m} $ do
let col' = cast col
x <- primIO $ sqlite3_column_blob stmt.pstmt col'
check_column_lib_error handle
size <- primIO $ sqlite3_column_bytes stmt.pstmt col'
check_column_lib_error handle
pure $ MkBlob x size
export
column_text : HasIO m => Handle -> Stmt -> (col : Nat) -> m (Either Error String)
column_text handle stmt col = runEitherT {m} $ do
x <- primIO $ sqlite3_column_text stmt.pstmt (cast col)
check_column_lib_error handle
pure x
export
column_type : HasIO m => Handle -> Stmt -> (col : Nat) -> m (Either Error DataType)
column_type handle stmt col = runEitherT {m} $ do
x <- primIO $ sqlite3_column_type stmt.pstmt (cast col)
check_column_lib_error handle
case DataType.from_raw x of
Just t => pure t
Nothing => throwError $ ImpossibleError $ "unknown data type: " <+> show x
export
interface ReadColumn a where
get : HasIO m => Handle -> Stmt -> (col : Nat) -> m (Either Error a)
concrete_type : ConcreteType
export
ReadColumn String where
get = column_text
concrete_type = AText
export
ReadColumn Int64 where
get = column_int64
concrete_type = AInteger
export
ReadColumn Int32 where
get = column_int
concrete_type = AInteger
export
ReadColumn Double where
get = column_double
concrete_type = AFloat
export
ReadColumn Blob where
get = column_blob
concrete_type = ABlob
public export
beta : Bool -> Type -> Type
beta False a = a
beta True a = Maybe a
check_get_column_error : MonadError Error m => (col : Nat) -> (got : ConcreteType) -> (expect : ConcreteType) -> m ()
check_get_column_error col got expect =
unless (expect == got) $ do
throwError $ GenericError $
"expecting " <+> show expect <+> " but got " <+> show got <+> " at column " <+> show col
export
get_column : HasIO m => Handle -> Stmt
-> (a : Type) -> {auto prf : ReadColumn a}
-> (allow_null : Bool) -> (allow_cast : Bool)
-> (col : Nat)
-> m (Either Error (beta allow_null a))
get_column handle stmt a False allow_cast col = runEitherT {m} $ do
MkEitherT (column_type handle stmt col) >>= \case
ANull => throwError $ GenericError $
"expected non-null " <+> show (concrete_type @{prf}) <+> " but encountered NULL at column " <+> show col
Concrete t => do
check_get_column_error col t (concrete_type @{prf})
MkEitherT $ get handle stmt col
get_column handle stmt a True allow_cast col = runEitherT {m} $ do
MkEitherT (column_type handle stmt col) >>= \case
ANull => pure Nothing
Concrete t => do
check_get_column_error col t (concrete_type @{prf})
map Just $ MkEitherT $ get handle stmt col
public export
data Column : Type -> Type where
A : (a : Type)
-> {default False cast : Bool}
-> {default False null : Bool}
-> {auto prf : ReadColumn a}
-> Column (beta null a)
get_row' : HasIO m => Handle -> Stmt -> Nat -> {xs : _} -> All Column xs -> m (Either Error (HList xs))
get_row' handle stmt col [] = runEitherT {m} $ pure []
get_row' handle stmt col (A type {cast} {null} {prf} :: next) = runEitherT {m} $ do
x <- MkEitherT $ get_column handle stmt type {prf} null cast col
xs <- MkEitherT $ get_row' handle stmt (S col) next
pure (x :: xs)
export
get_row : HasIO m => Handle -> Stmt -> {xs : _} -> All Column xs -> m (Either Error (HList xs))
get_row handle stmt = get_row' handle stmt Z
||| step then get_row
export
read_row : HasIO m => Handle -> Stmt -> {xs : _} -> All Column xs -> m (Either Error (HList xs))
read_row handle stmt columns = runEitherT {m} $ do
True <- MkEitherT $ step handle stmt
| False => throwError $ GenericError $ "already reached the end"
MkEitherT $ get_row handle stmt columns
|
module Miscellaneous.InstanceLoop where
open import Type
postulate A : TYPE
postulate B : TYPE
postulate C : TYPE
instance
postulate ab : ⦃ A ⦄ → B
instance
postulate ba : ⦃ B ⦄ → A
postulate a : A
test-a : B
test-a = ab
|
\documentclass[11pt, twoside]{article}
\usepackage{holtex}
\makeindex
\begin{document}
\input{HOLexampleOne}
\tableofcontents
\cleardoublepage
\HOLpagestyle
% ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
\section{example1 Theory}
\index{example1 Theory@\textbf {example1 Theory}}
\begin{flushleft}
\textbf{Built:} \HOLexampleOneDate \\[2pt]
\textbf{Parent Theories:} aclDrules
\end{flushleft}
% ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
\subsection{Datatypes}
\index{example1 Theory@\textbf {example1 Theory}!Datatypes}
% .....................................
\HOLexampleOneDatatypes
% No definitions
\subsection{Theorems}
\index{example1 Theory@\textbf {example1 Theory}!Theorems}
% .....................................
\HOLexampleOneTheorems
\HOLindex
\end{document} |
Formal statement is: lemma norm_triangle_eq: fixes x y :: "'a::real_inner" shows "norm (x + y) = norm x + norm y \<longleftrightarrow> norm x *\<^sub>R y = norm y *\<^sub>R x" Informal statement is: For any two vectors $x$ and $y$, we have $||x + y|| = ||x|| + ||y||$ if and only if $||x||y = ||y||x$. |
macro custom(expr)
(Meta.isexpr(expr, :call, 3) && expr.args[1] === :~) ||
error("incorrect macro usage")
quote
$(esc(expr.args[2])) = 0.0
end
end
macro mymodel1(ex)
# check if expression was modified by the DynamicPPL "compiler"
if ex == :(y ~ Uniform())
return esc(:(x ~ Normal()))
else
return esc(:(z ~ Exponential()))
end
end
struct MyModelStruct{T}
x::T
end
Base.:~(x, y::MyModelStruct) = y.x
macro mymodel2(ex)
# check if expression was modified by the DynamicPPL "compiler"
if ex == :(y ~ Uniform())
# Just returns 42
return :(4 ~ MyModelStruct(42))
else
return :(return -1)
end
end
@testset "compiler.jl" begin
@testset "model macro" begin
@model function testmodel_comp(x, y)
s ~ InverseGamma(2,3)
m ~ Normal(0,sqrt(s))
x ~ Normal(m, sqrt(s))
y ~ Normal(m, sqrt(s))
return x, y
end
testmodel_comp(1.0, 1.2)
# check if drawing from the prior works
@model function testmodel01(x = missing)
x ~ Normal()
return x
end
f0_mm = testmodel01()
@test mean(f0_mm() for _ in 1:1000) ≈ 0. atol=0.1
# Test #544
@model function testmodel02(x = missing)
if x === missing
x = Vector{Float64}(undef, 2)
end
x[1] ~ Normal()
x[2] ~ Normal()
return x
end
f0_mm = testmodel02()
@test all(x -> isapprox(x, 0; atol = 0.1), mean(f0_mm() for _ in 1:1000))
@model function testmodel03(x = missing)
x ~ Bernoulli(0.5)
return x
end
f01_mm = testmodel03()
@test mean(f01_mm() for _ in 1:1000) ≈ 0.5 atol=0.1
# test if we get the correct return values
@model function testmodel1(x1, x2)
s ~ InverseGamma(2,3)
m ~ Normal(0,sqrt(s))
x1 ~ Normal(m, sqrt(s))
x2 ~ Normal(m, sqrt(s))
return x1, x2
end
f1_mm = testmodel1(1., 10.)
@test f1_mm() == (1, 10)
# alternatives with keyword arguments
testmodel1kw(; x1, x2) = testmodel1(x1, x2)
f1_mm = testmodel1kw(x1 = 1., x2 = 10.)
@test f1_mm() == (1, 10)
@model function testmodel2(; x1, x2)
s ~ InverseGamma(2,3)
m ~ Normal(0,sqrt(s))
x1 ~ Normal(m, sqrt(s))
x2 ~ Normal(m, sqrt(s))
return x1, x2
end
f1_mm = testmodel2(x1=1., x2=10.)
@test f1_mm() == (1, 10)
@info "Testing the compiler's ability to catch bad models..."
# Test for assertions in observe statements.
@model function brokentestmodel_observe1(x1, x2)
s ~ InverseGamma(2,3)
m ~ Normal(0,sqrt(s))
x1 ~ Normal(m, sqrt(s))
x2 ~ x1 + 2
return x1, x2
end
btest = brokentestmodel_observe1(1., 2.)
@test_throws ArgumentError btest()
@model function brokentestmodel_observe2(x)
s ~ InverseGamma(2,3)
m ~ Normal(0,sqrt(s))
x = Vector{Float64}(undef, 2)
x ~ [Normal(m, sqrt(s)), 2.0]
return x
end
btest = brokentestmodel_observe2([1., 2.])
@test_throws ArgumentError btest()
# Test for assertions in assume statements.
@model function brokentestmodel_assume1()
s ~ InverseGamma(2,3)
m ~ Normal(0,sqrt(s))
x1 ~ Normal(m, sqrt(s))
x2 ~ x1 + 2
return x1, x2
end
btest = brokentestmodel_assume1()
@test_throws ArgumentError btest()
@model function brokentestmodel_assume2()
s ~ InverseGamma(2,3)
m ~ Normal(0,sqrt(s))
x = Vector{Float64}(undef, 2)
x ~ [Normal(m, sqrt(s)), 2.0]
return x
end
btest = brokentestmodel_assume2()
@test_throws ArgumentError btest()
# Test missing input arguments
@model function testmodel_missing1(x)
x ~ Bernoulli(0.5)
return x
end
@test_throws MethodError testmodel_missing1()
# Test missing initialization for vector observation turned parameter
@model function testmodel_missing2(x)
x[1] ~ Bernoulli(0.5)
return x
end
@test_throws MethodError testmodel_missing2(missing)()
# Test use of internal names
@model function testmodel_missing3(x)
x[1] ~ Bernoulli(0.5)
global varinfo_ = __varinfo__
global sampler_ = __sampler__
global model_ = __model__
global context_ = __context__
global rng_ = __rng__
global lp = getlogp(__varinfo__)
return x
end
model = testmodel_missing3([1.0])
varinfo = VarInfo(model)
@test getlogp(varinfo) == lp
@test varinfo_ isa AbstractVarInfo
@test model_ === model
@test sampler_ === SampleFromPrior()
@test context_ === DefaultContext()
@test rng_ isa Random.AbstractRNG
# disable warnings
@model function testmodel_missing4(x)
x[1] ~ Bernoulli(0.5)
global varinfo_ = __varinfo__
global sampler_ = __sampler__
global model_ = __model__
global context_ = __context__
global rng_ = __rng__
global lp = getlogp(__varinfo__)
return x
end false
lpold = lp
model = testmodel_missing4([1.0])
varinfo = VarInfo(model)
@test getlogp(varinfo) == lp == lpold
# test DPPL#61
@model function testmodel_missing5(z)
m ~ Normal()
z[1:end] ~ MvNormal(fill(m, length(z)), 1.0)
return m
end
model = testmodel_missing5(rand(10))
@test all(z -> isapprox(z, 0; atol = 0.2), mean(model() for _ in 1:1000))
# test Turing#1464
@model function gdemo(x)
s ~ InverseGamma(2, 3)
m ~ Normal(0, sqrt(s))
for i in eachindex(x)
x[i] ~ Normal(m, sqrt(s))
end
end
x = [1.0, missing]
VarInfo(gdemo(x))
@test ismissing(x[2])
# https://github.com/TuringLang/Turing.jl/issues/1464#issuecomment-731153615
vi = VarInfo(gdemo(x))
@test haskey(vi.metadata, :x)
vi = VarInfo(gdemo(x))
@test haskey(vi.metadata, :x)
end
@testset "nested model" begin
function makemodel(p)
@model function testmodel(x)
x[1] ~ Bernoulli(p)
global lp = getlogp(__varinfo__)
return x
end
return testmodel
end
model = makemodel(0.5)([1.0])
varinfo = VarInfo(model)
@test getlogp(varinfo) == lp
end
@testset "user-defined variable name" begin
@model f1() = x ~ NamedDist(Normal(), :y)
@model f2() = x ~ NamedDist(Normal(), @varname(y[2][:,1]))
@model f3() = x ~ NamedDist(Normal(), @varname(y[1]))
vi1 = VarInfo(f1())
vi2 = VarInfo(f2())
vi3 = VarInfo(f3())
@test haskey(vi1.metadata, :y)
@test vi1.metadata.y.vns[1] == VarName(:y)
@test haskey(vi2.metadata, :y)
@test vi2.metadata.y.vns[1] == VarName(:y, ((2,), (Colon(), 1)))
@test haskey(vi3.metadata, :y)
@test vi3.metadata.y.vns[1] == VarName(:y, ((1,),))
end
@testset "custom tilde" begin
@model demo() = begin
$(@custom m ~ Normal())
return m
end
model = demo()
@test all(iszero(model()) for _ in 1:1000)
end
@testset "docstring" begin
"This is a test"
@model function demo(x)
m ~ Normal()
x ~ Normal(m, 1)
end
s = @doc(demo)
@test string(s) == "This is a test\n"
# Verify that adding docstring didn't completely break execution of model
m = demo(0.)
@test m() isa Float64
end
@testset "type annotations" begin
@model function demo_without(x)
x ~ Normal()
end
@test isempty(VarInfo(demo_without(0.0)))
@model function demo_with(x::Real)
x ~ Normal()
end
@test isempty(VarInfo(demo_with(0.0)))
end
@testset "macros within model" begin
# Macro expansion
@model function demo1()
@mymodel1(y ~ Uniform())
end
@test haskey(VarInfo(demo1()), @varname(x))
# Interpolation
# Will fail if:
# 1. Compiler expands `y ~ Uniform()` before expanding the macros
# => returns -1.
# 2. `@mymodel` is expanded before entire `@model` has been
# expanded => errors since `MyModelStruct` is not a distribution,
# and hence `tilde_observe` errors.
@model function demo2()
$(@mymodel2(y ~ Uniform()))
end
@test demo2()() == 42
end
end
|
/-
Copyright (c) 2022 Jujian Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jujian Zhang
! This file was ported from Lean 3 source module group_theory.divisible
! leanprover-community/mathlib commit 0a0ec35061ed9960bf0e7ffb0335f44447b58977
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.GroupTheory.Subgroup.Pointwise
import Mathlib.GroupTheory.QuotientGroup
import Mathlib.Algebra.Group.Pi
/-!
# Divisible Group and rootable group
In this file, we define a divisible add monoid and a rootable monoid with some basic properties.
## Main definition
* `DivisibleBy A α`: An additive monoid `A` is said to be divisible by `α` iff for all `n ≠ 0 ∈ α`
and `y ∈ A`, there is an `x ∈ A` such that `n • x = y`. In this file, we adopt a constructive
approach, i.e. we ask for an explicit `div : A → α → A` function such that `div a 0 = 0` and
`n • div a n = a` for all `n ≠ 0 ∈ α`.
* `RootableBy A α`: A monoid `A` is said to be rootable by `α` iff for all `n ≠ 0 ∈ α` and `y ∈ A`,
there is an `x ∈ A` such that `x^n = y`. In this file, we adopt a constructive approach, i.e. we
ask for an explicit `root : A → α → A` function such that `root a 0 = 1` and `(root a n)ⁿ = a` for
all `n ≠ 0 ∈ α`.
## Main results
For additive monoids and groups:
* `divisibleByOfSMulRightSurj` : the constructive definition of divisiblity is implied by
the condition that `n • x = a` has solutions for all `n ≠ 0` and `a ∈ A`.
* `smul_right_surj_of_divisibleBy` : the constructive definition of divisiblity implies
the condition that `n • x = a` has solutions for all `n ≠ 0` and `a ∈ A`.
* `Prod.divisibleBy` : `A × B` is divisible for any two divisible additive monoids.
* `Pi.divisibleBy` : any product of divisble additive monoids is divisible.
* `AddGroup.divisibleByIntOfDivisibleByNat` : for additive groups, int divisiblity is implied
by nat divisiblity.
* `AddGroup.divisibleByNatOfDivisibleByInt` : for additive groups, nat divisiblity is implied
by int divisiblity.
* `AddCommGroup.divisibleByIntOfSmulTopEqTop`: the constructive definition of divisiblity
is implied by the condition that `n • A = A` for all `n ≠ 0`.
* `AddCommGroup.smul_top_eq_top_of_divisibleBy_int`: the constructive definition of divisiblity
implies the condition that `n • A = A` for all `n ≠ 0`.
* `divisibleByIntOfCharZero` : any field of characteristic zero is divisible.
* `QuotientAddGroup.divisibleBy` : quotient group of divisible group is divisible.
* `Function.Surjective.divisibleBy` : if `A` is divisible and `A →+ B` is surjective, then `B`
is divisible.
and their multiplicative counterparts:
* `rootableByOfPowLeftSurj` : the constructive definition of rootablity is implied by the
condition that `xⁿ = y` has solutions for all `n ≠ 0` and `a ∈ A`.
* `pow_left_surj_of_rootableBy` : the constructive definition of rootablity implies the
condition that `xⁿ = y` has solutions for all `n ≠ 0` and `a ∈ A`.
* `Prod.rootableBy` : any product of two rootable monoids is rootable.
* `Pi.rootableBy` : any product of rootable monoids is rootable.
* `Group.rootableByIntOfRootableByNat` : in groups, int rootablity is implied by nat
rootablity.
* `Group.rootableByNatOfRootableByInt` : in groups, nat rootablity is implied by int
rootablity.
* `QuotientGroup.rootableBy` : quotient group of rootable group is rootable.
* `Function.Surjective.rootableBy` : if `A` is rootable and `A →* B` is surjective, then `B` is
rootable.
TODO: Show that divisibility implies injectivity in the category of `AddCommGroup`.
-/
open Pointwise
section AddMonoid
variable (A α : Type _) [AddMonoid A] [SMul α A] [Zero α]
/--
An `AddMonoid A` is `α`-divisible iff `n • x = a` has a solution for all `n ≠ 0 ∈ α` and `a ∈ A`.
Here we adopt a constructive approach where we ask an explicit `div : A → α → A` function such that
* `div a 0 = 0` for all `a ∈ A`
* `n • div a n = a` for all `n ≠ 0 ∈ α` and `a ∈ A`.
-/
class DivisibleBy where
div : A → α → A
div_zero : ∀ a, div a 0 = 0
div_cancel : ∀ {n : α} (a : A), n ≠ 0 → n • div a n = a
#align divisible_by DivisibleBy
end AddMonoid
section Monoid
variable (A α : Type _) [Monoid A] [Pow A α] [Zero α]
/-- A `Monoid A` is `α`-rootable iff `xⁿ = a` has a solution for all `n ≠ 0 ∈ α` and `a ∈ A`.
Here we adopt a constructive approach where we ask an explicit `root : A → α → A` function such that
* `root a 0 = 1` for all `a ∈ A`
* `(root a n)ⁿ = a` for all `n ≠ 0 ∈ α` and `a ∈ A`.
-/
@[to_additive]
class RootableBy where
root : A → α → A
root_zero : ∀ a, root a 0 = 1
root_cancel : ∀ {n : α} (a : A), n ≠ 0 → root a n ^ n = a
#align rootable_by RootableBy
@[to_additive smul_right_surj_of_divisibleBy]
theorem pow_left_surj_of_rootableBy [RootableBy A α] {n : α} (hn : n ≠ 0) :
Function.Surjective (fun a => a ^ n : A → A) := fun x =>
⟨RootableBy.root x n, RootableBy.root_cancel _ hn⟩
#align pow_left_surj_of_rootable_by pow_left_surj_of_rootableBy
#align smul_right_surj_of_divisible_by smul_right_surj_of_divisibleBy
/--
A `Monoid A` is `α`-rootable iff the `pow _ n` function is surjective, i.e. the constructive version
implies the textbook approach.
-/
@[to_additive divisibleByOfSMulRightSurj
"An `AddMonoid A` is `α`-divisible iff `n • _` is a surjective function, i.e. the constructive
version implies the textbook approach."]
noncomputable def rootableByOfPowLeftSurj
(H : ∀ {n : α}, n ≠ 0 → Function.Surjective (fun a => a ^ n : A → A)) : RootableBy A α where
root a n := @dite _ (n = 0) (Classical.dec _) (fun _ => (1 : A)) fun hn => (H hn a).choose
root_zero _ := by classical exact dif_pos rfl
root_cancel a hn := by
dsimp only
rw [dif_neg hn]
exact (H hn a).choose_spec
#align rootable_by_of_pow_left_surj rootableByOfPowLeftSurj
#align divisible_by_of_smul_right_surj divisibleByOfSMulRightSurj
section Pi
variable {ι β : Type _} (B : ι → Type _) [∀ i : ι, Pow (B i) β]
variable [Zero β] [∀ i : ι, Monoid (B i)] [∀ i, RootableBy (B i) β]
@[to_additive]
instance Pi.rootableBy : RootableBy (∀ i, B i) β where
root x n i := RootableBy.root (x i) n
root_zero _x := funext fun _i => RootableBy.root_zero _
root_cancel _x hn := funext fun _i => RootableBy.root_cancel _ hn
#align pi.rootable_by Pi.rootableBy
#align pi.divisible_by Pi.divisibleBy
end Pi
section Prod
variable {β B B' : Type _} [Pow B β] [Pow B' β]
variable [Zero β] [Monoid B] [Monoid B'] [RootableBy B β] [RootableBy B' β]
@[to_additive]
instance Prod.rootableBy : RootableBy (B × B') β where
root p n := (RootableBy.root p.1 n, RootableBy.root p.2 n)
root_zero _p := Prod.ext (RootableBy.root_zero _) (RootableBy.root_zero _)
root_cancel _p hn := Prod.ext (RootableBy.root_cancel _ hn) (RootableBy.root_cancel _ hn)
#align prod.rootable_by Prod.rootableBy
#align prod.divisible_by Prod.divisibleBy
end Prod
end Monoid
namespace AddCommGroup
variable (A : Type _) [AddCommGroup A]
theorem smul_top_eq_top_of_divisibleBy_int [DivisibleBy A ℤ] {n : ℤ} (hn : n ≠ 0) :
n • (⊤ : AddSubgroup A) = ⊤ :=
AddSubgroup.map_top_of_surjective _ fun a => ⟨DivisibleBy.div a n, DivisibleBy.div_cancel _ hn⟩
#align add_comm_group.smul_top_eq_top_of_divisible_by_int AddCommGroup.smul_top_eq_top_of_divisibleBy_int
/-- If for all `n ≠ 0 ∈ ℤ`, `n • A = A`, then `A` is divisible.
-/
noncomputable def divisibleByIntOfSmulTopEqTop
(H : ∀ {n : ℤ} (_hn : n ≠ 0), n • (⊤ : AddSubgroup A) = ⊤) : DivisibleBy A ℤ where
div a n :=
if hn : n = 0 then 0 else (show a ∈ n • (⊤ : AddSubgroup A) by rw [H hn]; trivial).choose
div_zero a := dif_pos rfl
div_cancel a hn := by
simp_rw [dif_neg hn]
generalize_proofs h1
exact h1.choose_spec.2
#align add_comm_group.divisible_by_int_of_smul_top_eq_top AddCommGroup.divisibleByIntOfSmulTopEqTop
end AddCommGroup
instance (priority := 100) divisibleByIntOfCharZero {𝕜} [DivisionRing 𝕜] [CharZero 𝕜] :
DivisibleBy 𝕜 ℤ where
div q n := q / n
div_zero q := by norm_num
div_cancel {n} q hn := by
rw [zsmul_eq_mul, (Int.cast_commute n _).eq, div_mul_cancel q (Int.cast_ne_zero.mpr hn)]
#align divisible_by_int_of_char_zero divisibleByIntOfCharZero
namespace Group
variable (A : Type _) [Group A]
open Int in
/-- A group is `ℤ`-rootable if it is `ℕ`-rootable.
-/
@[to_additive "An additive group is `ℤ`-divisible if it is `ℕ`-divisible."]
def rootableByIntOfRootableByNat [RootableBy A ℕ] : RootableBy A ℤ where
root a z :=
match z with
| (n : ℕ) => RootableBy.root a n
| -[n+1] => (RootableBy.root a (n + 1))⁻¹
root_zero a := RootableBy.root_zero a
root_cancel {n} a hn := by
induction n
· change RootableBy.root a _ ^ _ = a
norm_num
rw [RootableBy.root_cancel]
rw [Int.ofNat_eq_coe] at hn
exact_mod_cast hn
· change (RootableBy.root a _)⁻¹ ^ _ = a
norm_num
rw [RootableBy.root_cancel]
norm_num
#align group.rootable_by_int_of_rootable_by_nat Group.rootableByIntOfRootableByNat
#align add_group.divisible_by_int_of_divisible_by_nat AddGroup.divisibleByIntOfDivisibleByNat
/-- A group is `ℕ`-rootable if it is `ℤ`-rootable
-/
@[to_additive "An additive group is `ℕ`-divisible if it `ℤ`-divisible."]
def rootableByNatOfRootableByInt [RootableBy A ℤ] : RootableBy A ℕ where
root a n := RootableBy.root a (n : ℤ)
root_zero a := RootableBy.root_zero a
root_cancel {n} a hn := by
-- Porting note: replaced `norm_num`
simpa only [zpow_coe_nat] using RootableBy.root_cancel a (show (n : ℤ) ≠ 0 by exact_mod_cast hn)
#align group.rootable_by_nat_of_rootable_by_int Group.rootableByNatOfRootableByInt
#align add_group.divisible_by_nat_of_divisible_by_int AddGroup.divisibleByNatOfDivisibleByInt
end Group
section Hom
-- Porting note: reordered variables to fix `to_additive` on `QuotientGroup.rootableBy`
variable {A B α : Type _}
variable [Zero α] [Monoid A] [Monoid B] [Pow A α] [Pow B α] [RootableBy A α]
variable (f : A → B)
/--
If `f : A → B` is a surjective homomorphism and `A` is `α`-rootable, then `B` is also `α`-rootable.
-/
@[to_additive
"If `f : A → B` is a surjective homomorphism and `A` is `α`-divisible, then `B` is also
`α`-divisible."]
noncomputable def Function.Surjective.rootableBy (hf : Function.Surjective f)
(hpow : ∀ (a : A) (n : α), f (a ^ n) = f a ^ n) : RootableBy B α :=
rootableByOfPowLeftSurj _ _ fun {n} hn x =>
let ⟨y, hy⟩ := hf x
⟨f <| RootableBy.root y n,
(by rw [← hpow (RootableBy.root y n) n, RootableBy.root_cancel _ hn, hy] : _ ^ n = x)⟩
#align function.surjective.rootable_by Function.Surjective.rootableByₓ
#align function.surjective.divisible_by Function.Surjective.divisibleByₓ
@[to_additive DivisibleBy.surjective_smul]
theorem RootableBy.surjective_pow (A α : Type _) [Monoid A] [Pow A α] [Zero α] [RootableBy A α]
{n : α} (hn : n ≠ 0) : Function.Surjective fun a : A => a ^ n := fun a =>
⟨RootableBy.root a n, RootableBy.root_cancel a hn⟩
#align rootable_by.surjective_pow RootableBy.surjective_pow
#align divisible_by.surjective_smul DivisibleBy.surjective_smul
end Hom
section Quotient
variable (α : Type _) {A : Type _} [CommGroup A] (B : Subgroup A)
/-- Any quotient group of a rootable group is rootable. -/
@[to_additive "Any quotient group of a divisible group is divisible"]
noncomputable instance QuotientGroup.rootableBy [RootableBy A ℕ] : RootableBy (A ⧸ B) ℕ :=
QuotientGroup.mk_surjective.rootableBy _ fun _ _ => rfl
#align quotient_group.rootable_by QuotientGroup.rootableBy
#align quotient_add_group.divisible_by QuotientAddGroup.divisibleBy
end Quotient
|
\documentclass{beamer}
\mode<presentation>
{
\usetheme{Berkeley}
\usecolortheme{crane}
\setbeamercovered{transparent}
% or whatever (possibly just delete it)
}
\usepackage[english]{babel}
% or whatever
\usepackage[latin1]{inputenc}
% or whatever
\usepackage{times}
\usepackage[T1]{fontenc}
% Or whatever. Note that the encoding and the font should match. If T1
% does not look nice, try deleting the line with the fontenc.
\usepackage{natbib}
\usepackage{minted}
\usepackage{graphicx}
\graphicspath{{assets/figures/}}
\DeclareGraphicsExtensions{.pdf,.png,.jpg}
\title{DeeBee}
\subtitle{Implementation of a Relational Database Query-Processing System}
\author{Hawk Weisman}
\institute[Allegheny College] % (optional, but mostly needed)
{Department of Computer Science\\Allegheny College
}
\date{December 8th, 2014}
\subject{Compilers, Databases}
% This is only inserted into the PDF information catalog. Can be left
% out.
% Delete this, if you do not want the table of contents to pop up at
% the beginning of each subsection:
\AtBeginSubsection[]
{
\begin{frame}<beamer>{Outline}
\tableofcontents[currentsection,currentsubsection]
\end{frame}
}
% If you wish to uncover everything in a step-wise fashion, uncomment
% the following command:
%\beamerdefaultoverlayspecification{<+->}
%\addbibresource{assets/final.bib}
\begin{document}
\begin{frame}
\titlepage
\end{frame}
\begin{frame}{Outline}
\tableofcontents
% You might wish to add the option [pausesections]
\end{frame}
% Structuring a talk is a difficult task and the following structure
% may not be suitable. Here are some rules that apply for this
% solution:
% - Exactly two or three sections (other than the summary).
% - At *most* three subsections per section.
% - Talk about 30s to 2min per frame. So there should be between about
% 15 and 30 frames, all told.
% - A conference audience is likely to know very little of what you
% are going to talk about. So *simplify*!
% - In a 20min talk, getting the main ideas across is hard
% enough. Leave out details, even if it means being less precise than
% you think necessary.
% - If you omit details that are vital to the proof/implementation,
% just say so once. Everybody will be happy with that.
\section{Introduction}
\begin{frame}{Introduction}
\begin{itemize}
\item Query processing: \pause
\begin{itemize}
\item An application of many concepts from compilers \pause
\item Vital to today's world (databases are everywhere) \pause
\end{itemize}
\item DeeBee: \pause
\begin{itemize}
\item A very small relational database (\textless 1500 LoC) \pause
\item Implements a subset of the Structured Query Language \pause
\item For educational purposes only (don't use this in production) \pause
\item Written in the Scala programming language
\end{itemize}
\end{itemize}
\end{frame}
\section{Background}
\subsection{Relational Databases}
\begin{frame}{What is a relational database?}
\begin{itemize}
\item ``The primary data model for commercial data-processing applications.''~\citep[page 39]{silberschatz2010database} \pause
\item A database consists of multiple tables of values, called \alert{relations}~\citep{silberschatz2010database,harrington2009relational,garcia2000database} \pause
\item A relation consists of:~\citep{silberschatz2010database,harrington2009relational,garcia2000database} \pause
\begin{itemize}
\item a set of rows, or \alert{tuples}
\item a set of columns, or \alert{attributes}
\end{itemize} \pause
\item So how does this relate to compilers?
\end{itemize}
\end{frame}
\subsection{Query Languages}
\begin{frame}{What is a query language?}
\begin{itemize}
\item Users and client software interact with databases through \alert{query languages}~\citep{silberschatz2010database,harrington2009relational,garcia2000database} \pause
\item These are \alert{domain-specific languages} for accessing and modifying the database \pause
\item Query languages are \alert{declarative} rather than \alert{imperative}~\citep{silberschatz2010database,harrington2009relational,garcia2000database} \pause
\item Just like other programming languages, query languages must be parsed, analyzed, and compiled or interpreted.~\citep{silberschatz2010database,harrington2009relational,garcia2000database}
\end{itemize}
\end{frame}
\begin{frame}{SQL}
\begin{itemize}
\item SQL is the \alert{Structured Query Language}. \pause
\item It is the query language used by most modern RDBMSs \pause
\item SQL consists of two components: \pause
\begin{itemize}
\item \alert{Data definition language} (DDL): defines the structure of the database~\citep{silberschatz2010database,harrington2009relational}
\begin{itemize} \pause
\item creating and deleting tables
\item adding relationships between tables
\item et cetera
\end{itemize}
\item \alert{Data manipulation language} (DML): accesses and modifies data stored in the database~\citep{silberschatz2010database,harrington2009relational} \pause
\begin{itemize}
\item selecting rows
\item adding, deleting, and modifying rows
\item et cetera
\end{itemize} \pause
\end{itemize}
\item SQL = DDL + DML
\end{itemize}
\end{frame}
\begin{frame}[fragile]{SQL Examples}
\begin{example}[SQL CREATE TABLE statement (schema)]
\begin{minted}[gobble=8,fontsize=\footnotesize]{SQL}
CREATE TABLE Writers (
id INTEGER NOT NULL PRIMARY KEY,
first_name VARCHAR(15) NOT NULL,
middle_name VARCHAR(15),
last_name VARCHAR(15) NOT NULL,
birth_date VARCHAR(10) NOT NULL,
death_date VARCHAR(10),
country_of_origin VARCHAR(20) NOT NULL
);
\end{minted}
\end{example}
\end{frame}
\begin{frame}[fragile]{SQL Examples}
\begin{example}[SQL SELECT statement]
\begin{minted}[gobble=8,fontsize=\footnotesize]{SQL}
SELECT * FROM test;
SELECT test1, test2 FROM test;
SELECT * FROM test WHERE test1 = 9 AND test2 = 5;
SELECT * FROM test LIMIT 5;
\end{minted}
\end{example} \pause
\begin{example}[SQL DELETE statement]
\begin{minted}[gobble=8,fontsize=\footnotesize]{SQL}
DELETE FROM test WHERE test2 > 3 LIMIT 100;
\end{minted}
\end{example} \pause
\begin{example}[SQL INSERT statement]
\begin{minted}[gobble=8,fontsize=\footnotesize]{SQL}
INSERT INTO test VALUES (
1, 'a string', 2, 'another string'
);
\end{minted}
\end{example}
\end{frame}
\subsection{Query Processing}
\begin{frame}{Steps in Query Evaluation}
\begin{figure}
\includegraphics[width=\linewidth]{QueryProcessing}
\caption{Steps in query processing~\citep[583]{silberschatz2010database}.}
\end{figure}
\end{frame}
\begin{frame}{Query Processing}
\begin{itemize}
\item A query processor is essentially a compiler! \pause
\item Some stages in the query evaluation process correspond directly to those in compilation: \pause
\begin{itemize}
\item Parsing \pause
\item Semantic analysis \pause
\item IR generation (Relational algebra expression) \pause
\item Optimization \pause
\end{itemize}
\end{itemize}
\end{frame}
\section{DeeBee}
\subsection{Design}
\begin{frame}{Design Overview}
\begin{itemize}
\item DeeBee implements a subset of SQL \pause
\item Chosen to balance functionality with time constraints \pause
\begin{itemize}
\item \texttt{SELECT} statements \pause
\begin{itemize}
\item Projections (\texttt{SELECT a, b FROM ...}) \pause
\item Filtering by predicates (\texttt{SELECT * FROM table WHERE ...}) \pause
\item Nested predicates (\texttt{WHERE ... AND ... }) \pause
\item \texttt{LIMIT} clauses \pause
\item No \texttt{JOIN}s \pause
\end{itemize}
\item \texttt{INSERT} statements \pause
\item \texttt{DELETE} statements \pause
\begin{itemize}
\item \texttt{WHERE} and \texttt{LIMIT} clauses \pause
\item Same implementation as \texttt{SELECT} \pause
\end{itemize}
\item \texttt{CREATE TABLE} and \texttt{DROP TABLE} statements \pause
\begin{itemize}
\item No \texttt{CHECK} constraints \pause
\item No \texttt{TRIGGER}s
\end{itemize}
\end{itemize}
\end{itemize}
\end{frame}
\begin{frame}{Architecture}
\begin{itemize}
\item The \alert{actors} model~\citep{gupta2012akka,haller2012integration,agha1985actors} \pause
\begin{itemize}
\item A construct for concurrent programming \pause
\item Actors communicate through \alert{message passing} \pause
\item Messages are: \pause
\begin{itemize}
\item Immutable \pause
\item Asynchronous \pause
\item Anonynous (decoupled) \pause
\end{itemize}
\item Actors enqueue recieved messages and respond to them in order \pause
\end{itemize}
\item {Essentially, an actor is a \alert{state machine} with a \alert{mailbox}} \pause
\item Advantages: \pause
\begin{itemize}
\item Fault tolerance (loose coupling) \pause
\item Scalability \pause
\item Concurrency \pause
\item Event-driven (good for databases) \pause
\end{itemize}
\item In Scala, the Actors model is provided by the \alert{Akka} framework
\end{itemize}
\end{frame}
\begin{frame}{Architecture}
\begin{itemize}
\item In DeeBee: \pause
\begin{itemize}
\item tables
\item databases
\item frontends (connections into the database) \pause
\end{itemize}
\item ...are all represented by actors \pause
\item A database actor is responsible for: \pause
\begin{itemize}
\item dispatching queries to its' tables \pause
\item sending query results to the querying entity \pause
\item creating and deleting table actors \pause
\end{itemize}
\item A table actor is responsible for: \pause
\begin{itemize}
\item recieving queries \pause
\item (possibly) updating its' state \pause
\item responding with query results or errors
\end{itemize}
\end{itemize}
\end{frame}
\begin{frame}{Query Processing}
\begin{itemize}
\item SQL queries are internally represented using an \alert{abstract syntax tree} (AST) \pause
\item Connection actors recieve \alert{query strings}, parse them, and send the AST to the database actor \pause
\item Database actor either: \pause
\begin{itemize}
\item processes DDL queries by creating/deleting tables \pause
\item dispatches DML queries to the target child table \pause
\end{itemize}
\item Queries are \alert{interpreted} (not compiled) against a context
\end{itemize}
\end{frame}
\subsection{Implementation}
\subsubsection{Query Parsing}
\begin{frame}{Parser Combinators}
\begin{itemize}
\item DeeBee's query processor parses queries using \alert{combinator parsing}~\citep{moors2008parser,swierstra2001combinator,fokker1995functional,odersky2008programming} \pause
\item This is a functional-programming approach to text parsing \pause
\begin{itemize}
\item A \alert{parser} is a function which accepts some strings and rejects others \pause
\item A \alert{parser-combinator} is a higher-order function which takes as input two or more parsers and returns combined parser \pause
\item By repeatedly combining simpler parsers into more complex ones, a \alert{recursive-descent parser} can be created \end{itemize}
\end{itemize}
\end{frame}
\begin{frame}[fragile]{Parser Combinators in Scala}
\begin{itemize}
\item Scala's parsing library follows the philosophy of \alert{embedded DSLs}~\citep{ghosh2010dsls,hofer2008polymorphic,moors2008parser,odersky2008programming} \pause
\item It allows parsers to be specified in \alert{BNF-like} syntax \pause
\begin{example}[Combinator Parsing in Scala]
\begin{minted}[
gobble=8,
%firstline=115,
%lastline=121,
fontsize=\footnotesize
]{scala}
def inPlaceConstraint: Parser[Constraint] =
("not" ~ "null") ^^^ Not_Null
| ("primary" ~ "key") ^^^ Primary_Key
| "unique" ^^^ Unique
\end{minted}
\end{example}
\end{itemize}
\end{frame}
\begin{frame}[fragile]{Packrat Parsing}
\begin{itemize}
\item \alert{Packrat parsers} add a memoization facility~\cite{jonnalagedda2009packrat,frost2008parser} \pause
\begin{itemize}
\item Guarantees unlimited lookahead and linear parse time \pause
\item Allows parsing of left-recursive grammars \pause
\end{itemize}
\item Parser functions are replaced by lazily-evaluated values \pause
\begin{example}[Combinator Parsing in Scala]
\begin{minted}[
%firstline=115,
%lastline=121,
fontsize=\footnotesize
]{scala}
lazy val expression: P[Expr[_]] =
("(" ~> comparison <~ ")") ^^{
case c: Comparison => new ParenComparison(c)
}
| comparison
| literal
| identifier
lazy val comparison: P[Comparison] =
expression ~ operator ~ expression ^^ {
case lhs ~ op ~ rhs => Comparison(lhs, op, rhs)
}
\end{minted}
\end{example}
\end{itemize}
\end{frame}
\subsection{Parsing Demo}
\subsection{Query Processing}
\begin{frame}{Query Processing}
\begin{itemize}
\item DeeBee queries are \alert{interpreted} \pause
\item Interpretation is \alert{contextualized} against a database \pause
\begin{itemize}
\item \alert{Type checking} \pause
\begin{itemize}
\item In a compiler, context is preceeding program statements \pause
\item In DBMS, context is the schema of the target table \pause
\end{itemize}
\item \alert{Predicate interpretation} \pause
\begin{itemize}
\item Convert AST nodes to Scala partial functions \pause
\item Nested predicates are constructed from leaves to roots \pause
\end{itemize}
\item \alert{Constraints validation} \pause
\begin{itemize}
\item Ensure queries don't violate table constraints \pause
\item Uniqueness \pause
\item Not null \pause
\item Type constraints \pause
\item Eventually, this will be deferrable for transaction processing
\end{itemize}
\end{itemize}
\end{itemize}
\end{frame}
\subsection{Query Processing Demo}
% All of the following is optional and typically not needed.
\appendix
\section<presentation>*{\appendixname}
\subsection<presentation>*{References}
\begin{frame}[allowframebreaks]
\frametitle{References}
%\nocite{*}
\bibliography{assets/final}{}
\bibliographystyle{plain}
\end{frame}
\end{document}
|
import laurent_measures.basic
import laurent_measures.aux_lemmas
import analysis.special_functions.pow
import laurent_measures.thm69
open nnreal laurent_measures aux_thm69
open_locale nnreal
noncomputable theory
section slm
-- This is the same as before, from here to...
-- parameter {p : ℝ≥0}
/-- This is the same `r` as before. -/
-- def r : ℝ≥0 := 2⁻¹ ^ (p:ℝ)
-- lemma r_pos : 0 < r :=
-- suffices 0 < (2 : ℝ≥0)⁻¹ ^ (p : ℝ), by simpa [r],
-- rpow_pos (nnreal.inv_pos.mpr zero_lt_two)
-- lemma r_lt_one [fact(0 < p)] : r < 1 :=
-- begin
-- refine rpow_lt_one zero_le' (half_lt_self one_ne_zero) _,
-- rw nnreal.coe_pos,
-- exact fact.out _
-- end
variables {r : ℝ≥0} [fact (0 < r)] [fact (r < 1)]
local notation `ℒ` := laurent_measures r
variables {S : Fintype}
-- /-- Let `F : ℒ S` be a Laurent measure. `laurent_measures.d` chooses a bound `d ∈ ℤ` for `F`,
-- such that, for all `s : S`, the sequence `F s` is zero from `d-1` and below. -/
-- def laurent_measures.d (F : ℒ S) : ℤ :=
-- (exists_bdd_filtration (fact.out _ : 0 < r) (fact.out _ : r < 1) F).some
-- lemma lt_d_eq_zero (F : ℒ S) (s : S) (n : ℤ) :
-- n < F.d → F s n = 0 :=
-- (exists_bdd_filtration (fact.out _ : 0 < r) (fact.out _ : r < 1) F).some_spec s n
-- ... here!
section new_stuff
/-- Simpler Laurent measures? -/
structure slm (r : ℝ≥0) (S : Fintype) :=
(to_fun : S → ℤ → ℤ)
(d : ℤ)
(summable' : ∀ s, summable (λ n : ℕ, ∥to_fun s n∥₊ * r ^ n))
(zero_lt_d : ∀ s n, n < d → to_fun s n = 0)
/-- A "usual" Laurent Measure `F : ℒ S` gives rise to a Simple Laurent Measure of type `slm S`. -/
def _root_.laurent_measures.to_slm (F : ℒ S) : slm r S :=
{ to_fun := F.to_fun,
d := F.d,
zero_lt_d := λ n s, lt_d_eq_zero F _ _,
summable' := begin
refine λ s, summable_coe.mp _,
convert ((@int_summable_iff _ _ _ _ _ (λ (n : ℤ), ∥F.to_fun s n∥ * r ^ n)).mp _).1,
{ convert summable_coe.mpr (F.summable' s),
simp }
end }
/-- A Simple Laurent Measure `F : slm S` "usual" Laurent Measure of type `ℒ S`. -/
-- The "main" input is `int_summable_iff`, proving that a series over `ℤ` is summable if and only
-- if both its restrictions to `ℕ` and to "`-ℕ`" are summable.
def slm.to_laurent_measures {r : ℝ≥0} (F : slm r S) : laurent_measures r S :=
{ to_fun := F.to_fun,
summable' := begin
refine λ s, summable_coe.mp _,
convert ((@int_summable_iff _ _ _ _ _ (λ (n : ℤ), ∥F.to_fun s n∥ * r ^ n)).mpr _),
{ simp },
{ refine ⟨_, summable_of_eventually_zero (λ (n : ℤ), ∥F.to_fun s n∥ * ↑r ^ n) F.d (λ n nd, _)⟩,
{ convert summable_coe.mpr (F.summable' s), },
{ simp [F.zero_lt_d s n nd] } }
end }
lemma slm_lm_to_fun_eq {r : ℝ≥0} (F : slm r S) : F.to_fun = F.to_laurent_measures.to_fun := rfl
lemma lm_slm_to_fun_eq (F : ℒ S) : F.to_fun = F.to_slm.to_fun := rfl
end new_stuff
end slm
|
Require Import refocusing_substitutions.
Require Import Setoid.
Module Arith_Lang <: RED_LANG.
Parameter var_name : Set.
Inductive term' : Set :=
| num : nat -> term'
| plus : term' -> term' -> term'
| times: term' -> term' -> term'
| var : var_name -> term'.
Definition term := term'.
Inductive value' : Set :=
| v_num : nat -> value'.
Definition value := value'.
Inductive redex' : Set :=
| r_plus : value -> value -> redex'
| r_times : value -> value -> redex'
| r_var : var_name -> redex'.
Definition redex := redex'.
Definition value_to_term (v : value) : term :=
match v with
| v_num v' => num v'
end.
Coercion value_to_term : value >-> term.
Lemma value_to_term_injective : forall v v', value_to_term v = value_to_term v' -> v = v'.
Proof.
intros v v0; case v; case v0; simpl; intros; try discriminate; injection H;
intros; subst; auto.
Qed.
Definition redex_to_term (r : redex) : term :=
match r with
| r_plus m n => plus (m:term) (n:term)
| r_times m n => times (m:term) (n:term)
| r_var x => var x
end.
Coercion redex_to_term : redex >-> term.
Lemma redex_to_term_injective : forall r r', redex_to_term r = redex_to_term r' -> r = r'.
Proof with auto.
intros r r0; case r; case r0; intros; try discriminate; injection H; intros;
try (rewrite (value_to_term_injective _ _ H1); rewrite (value_to_term_injective _ _ H0))...
rewrite H0...
Qed.
Parameter env : var_name -> nat.
Inductive elem_context' : Set :=
| plus_r : term -> elem_context'
| plus_l : value -> elem_context'
| times_r : term -> elem_context'
| times_l : value -> elem_context'.
Definition elem_context := elem_context'.
Definition context := list elem_context.
Definition empty : context := nil.
Definition atom_plug (t : term) (ec : elem_context) :=
match ec with
| plus_r t' => plus t t'
| plus_l v => plus (v:term) t
| times_r t' =>times t t'
| times_l v => times (v:term) t
end.
Definition compose (c0 c1 : context) : context := app c0 c1.
Definition plug (t : term) (c : context) : term := fold_left atom_plug c t.
Lemma plug_compose : forall c1 c2 r, plug r (compose c1 c2) = plug (plug r c1) c2.
Proof.
induction c1; simpl; auto.
Qed.
Definition contract (r : redex) : option term :=
match r with
| r_plus (v_num n) (v_num m) => Some (num (n+m))
| r_times (v_num n) (v_num m) => Some (num (n*m))
| r_var x => Some (num (env x))
end.
Lemma decompose : forall t : term, (exists v : value, t = v) \/
(exists r : redex, exists c : context, plug r c = t).
Proof with auto.
induction t; simpl.
left; exists (v_num n); auto.
right; elim IHt1; intros.
destruct H as [v1 H]; subst.
elim IHt2; intros.
destruct H as [v2 H]; subst.
exists (r_plus v1 v2); exists empty; simpl...
destruct H as [r [c H]]; exists r; exists (compose c (plus_l v1 :: empty)); rewrite plug_compose; simpl; subst; auto.
destruct H as [r [c H]]; exists r; exists (compose c (plus_r t2 :: empty)); rewrite plug_compose; simpl; subst; auto.
right; elim IHt1; intros.
destruct H as [v1 H]; subst.
elim IHt2; intros.
destruct H as [v2 H]; subst.
exists (r_times v1 v2); exists empty; simpl...
destruct H as [r [c H]]; exists r; exists (compose c (times_l v1 :: empty)); rewrite plug_compose; simpl; subst; auto.
destruct H as [r [c H]]; exists r; exists (compose c (times_r t2 :: empty)); rewrite plug_compose; simpl; subst; auto.
right; exists (r_var v); exists empty; simpl...
Qed.
Inductive decomp : Set :=
| d_val : value -> decomp
| d_red : redex -> context -> decomp.
Inductive interm_dec : Set :=
| in_red : redex -> interm_dec
| in_val : value -> interm_dec
| in_term: term -> elem_context -> interm_dec.
Definition decomp_to_term (d : decomp) : term :=
match d with
| d_val v => value_to_term v
| d_red r c0 => plug (redex_to_term r) c0
end.
Definition only_empty (t : term) : Prop := forall t' c, plug t' c = t -> c = empty.
Definition only_trivial (t : term) : Prop := forall t' c, plug t' c = t -> c = empty \/ exists v, t' = value_to_term v.
Lemma value_trivial : forall v : value, only_trivial (value_to_term v).
Proof.
intros v t c; left; generalize dependent t; induction c; simpl in *; auto;
destruct v; destruct a; destruct c; intros; simpl in *; try discriminate H; discriminate (IHc _ H).
Qed.
Lemma redex_trivial : forall r : redex, only_trivial (redex_to_term r).
Proof.
intros r t c; generalize dependent t; induction c; intros; [left; auto | right]; destruct a;( simpl in *;
destruct (IHc _ H) as [H0 | [v0 H0]]; subst;[ destruct r; inversion H; subst;
match goal with [ |- exists u, _ ?v = _ u ] => exists v; reflexivity end | destruct v0; discriminate]).
Qed.
Lemma value_redex : forall (v : value) (r : redex), value_to_term v <> redex_to_term r.
Proof.
destruct v; destruct r; intro; discriminate.
Qed.
Lemma ot_subt : forall t t0 ec, only_trivial t -> atom_plug t0 ec = t -> exists v, t0 = value_to_term v.
Proof with auto.
intros; destruct (H t0 (ec :: nil)) as [H1 | [v H1]]...
discriminate.
exists v...
Qed.
Ltac ot_v t ec :=
match goal with
| [Hot : (only_trivial ?H1) |- _] => destruct (ot_subt _ t ec Hot) as [?v HV]; [auto | subst t]
end.
Ltac mlr rv :=
match goal with [ |- (exists v, ?H1 = value_to_term v) \/ (exists r, ?H1 = redex_to_term r)] =>
match rv with
| (?v : value) => left; exists v
| (?r : redex) => right; exists r
end; simpl; auto
end.
Lemma trivial_val_red : forall t : term, only_trivial t ->
(exists v : value, t = value_to_term v) \/ (exists r : redex, t = redex_to_term r).
Proof with auto.
destruct t; intros.
mlr (v_num n).
ot_v t1 (plus_r t2); ot_v t2 (plus_l v); mlr (r_plus v v0).
ot_v t1 (times_r t2); ot_v t2 (times_l v); mlr (r_times v v0).
mlr (r_var v).
Qed.
End Arith_Lang.
Module Arith_Sem <: RED_SEM Arith_Lang.
Definition term := Arith_Lang.term.
Definition value := Arith_Lang.value.
Definition redex := Arith_Lang.redex.
Definition context := Arith_Lang.context.
Definition empty := Arith_Lang.empty.
Definition decomp := Arith_Lang.decomp.
Definition d_val := Arith_Lang.d_val.
Definition d_red := Arith_Lang.d_red.
Definition value_to_term : value -> term := Arith_Lang.value_to_term.
Definition redex_to_term : redex -> term := Arith_Lang.redex_to_term.
Definition decomp_to_term : (decomp -> term) := Arith_Lang.decomp_to_term.
Definition plug : term -> context -> term := Arith_Lang.plug.
Definition compose : context -> context -> context := Arith_Lang.compose.
Definition contract : redex -> option term := Arith_Lang.contract.
Definition interm_dec := Arith_Lang.interm_dec.
Definition in_red := Arith_Lang.in_red.
Definition in_val := Arith_Lang.in_val.
Definition in_term := Arith_Lang.in_term.
Definition r_var := Arith_Lang.r_var.
Definition num := Arith_Lang.num.
Definition var := Arith_Lang.var.
Definition var_name := Arith_Lang.var_name.
Definition plus_r := Arith_Lang.plus_r.
Definition plus_l := Arith_Lang.plus_l.
Definition plus := Arith_Lang.plus.
Definition v_num := Arith_Lang.v_num.
Definition times := Arith_Lang.times.
Definition times_r := Arith_Lang.times_r.
Definition times_l := Arith_Lang.times_l.
Definition r_plus := Arith_Lang.r_plus.
Definition r_times := Arith_Lang.r_times.
Coercion value_to_term : value >-> term.
Coercion redex_to_term : redex >-> term.
Inductive dec' : term -> context -> decomp -> Prop :=
| t_var : forall (x : var_name) (c : context), dec' (var x) c (d_red (r_var x) c)
| t_num : forall (n : nat) (c : context) (d : decomp),
decctx' (v_num n) c d -> dec' (num n) c d
| t_plus: forall (t0 t1 : term) (c : context) (d : decomp),
dec' t0 (plus_r t1 :: c) d -> dec' (plus t0 t1) c d
| t_mul : forall (t0 t1 : term) (c : context) (d : decomp),
dec' t0 (times_r t1 :: c) d -> dec' (times t0 t1) c d
with decctx' : value -> context -> decomp -> Prop :=
| c_empty : forall (v : value), decctx' v empty (d_val v)
| c_plus_r: forall (v : value) (t : term) (c : context) (d : decomp),
dec' t (plus_l v :: c) d -> decctx' v (plus_r t :: c) d
| c_plus_l: forall (v v0 : value) (c : context), decctx' v (plus_l v0 :: c) (d_red (r_plus v0 v) c)
| c_mul_r : forall (v : value) (t : term) (c : context) (d : decomp),
dec' t (times_l v :: c) d -> decctx' v (times_r t :: c) d
| c_mul_l : forall (v v0 : value) (c : context), decctx' v (times_l v0 :: c) (d_red (r_times v0 v) c).
Definition dec := dec'.
Definition decctx := decctx'.
Scheme dec_Ind := Induction for dec' Sort Prop
with decctx_Ind := Induction for decctx' Sort Prop.
(** dec is left inverse of plug *)
Lemma dec_correct : forall t c d, dec t c d -> decomp_to_term d = plug t c.
Proof.
induction 1 using dec_Ind with
(P := fun t c d (H : dec t c d) => decomp_to_term d = plug t c)
(P0:= fun v c d (H : decctx v c d) => decomp_to_term d = plug v c); simpl; auto.
Qed.
(** A redex in context will only ever be reduced to itself *)
Lemma dec_redex_self : forall (r : redex) (c : context), dec (redex_to_term r) c (d_red r c).
Proof.
intro; case r; intros; constructor; destruct v; destruct v0; repeat constructor.
Qed.
Lemma dec_plug : forall c c0 t d, dec (plug t c) c0 d -> dec t (compose c c0) d.
Proof with auto.
induction c; intros; simpl in *; auto; destruct a;
assert (hh := IHc _ _ _ H); inversion hh; subst; auto;
destruct v; inversion H4; subst; inversion H1; subst...
Qed.
Lemma dec_plug_rev : forall c c0 t d, dec t (compose c c0) d -> dec (plug t c) c0 d.
Proof with auto.
induction c; intros; simpl in *; auto; destruct a;
try (destruct v); apply IHc; repeat constructor...
Qed.
Inductive decempty : term -> decomp -> Prop :=
| d_intro : forall (t : term) (d : decomp), dec t empty d -> decempty t d.
Inductive iter : decomp -> value -> Prop :=
| i_val : forall (v : value), iter (d_val v) v
| i_red : forall (r : redex) (t : term) (c : context) (d : decomp) (v : value),
contract r = Some t -> decempty (plug t c) d -> iter d v -> iter (d_red r c) v.
Inductive eval : term -> value -> Prop :=
| e_intro : forall (t : term) (d : decomp) (v : value), decempty t d -> iter d v -> eval t v.
Definition decompose := Arith_Lang.decompose.
End Arith_Sem.
Module Arith_Ref_Lang <: RED_REF_LANG.
Module R := Arith_Lang.
Definition dec_term (t : R.term) : R.interm_dec :=
match t with
| Arith_Lang.var vname => R.in_red (Arith_Lang.r_var vname)
| Arith_Lang.num n => R.in_val (Arith_Lang.v_num n)
| Arith_Lang.plus n m => R.in_term n (Arith_Lang.plus_r m)
| Arith_Lang.times n m => R.in_term n (Arith_Lang.times_r m)
end.
Definition dec_context : R.elem_context -> R.value -> R.interm_dec :=
fun (ec : R.elem_context) (v : R.value) => match ec with
| Arith_Lang.plus_r n => R.in_term n (Arith_Lang.plus_l v)
| Arith_Lang.plus_l v' => R.in_red (Arith_Lang.r_plus v' v)
| Arith_Lang.times_r n => R.in_term n (Arith_Lang.times_l v)
| Arith_Lang.times_l v' => R.in_red (Arith_Lang.r_times v' v)
end.
Inductive subterm_one_step : R.term -> R.term -> Prop :=
| st_1 : forall t t0 ec (DECT : t = R.atom_plug t0 ec), subterm_one_step t0 t.
Lemma wf_st1 : well_founded subterm_one_step.
Proof.
prove_st_wf.
Qed.
Definition subterm_order := clos_trans_n1 R.term subterm_one_step.
Notation " a <| b " := (subterm_order a b) (at level 40).
Definition wf_sto : well_founded subterm_order := wf_clos_trans_r _ _ wf_st1.
(* Inductive elem_context_one_step : R.elem_context -> R.elem_context -> Prop :=
| ec_1 : forall ec ec0 v t (DECEC : dec_context ec v = R.in_term t ec0),
elem_context_one_step ec0 ec.
Ltac wf_ec_step :=
constructor; match goal with
| [ |- forall u (T:?eco u _), Acc ?eco u ] => intros y T; inversion T as [ec ec0 ?t ?v ?Hcc]; subst ec ec0; clear T
end; match goal with
| [ Hcc : dec_context _ _ = R.in_term _ ?cc |- Acc ?eco ?cc] => inversion Hcc; subst; clear Hcc
end.
Ltac prove_ec_wf := intro a; destruct a; repeat wf_ec_step.
Lemma wf_ec1 : well_founded elem_context_one_step.
Proof.
prove_ec_wf.
Qed.
Definition ec_order := clos_trans_1n _ elem_context_one_step.
Notation " a <: b " := (ec_order a b) (at level 40).
Definition wf_eco : well_founded ec_order := wf_clos_trans_l _ _ wf_ec1.*)
Definition ec_order (ec0 ec1 : R.elem_context) : Prop :=
match ec0, ec1 with
| R.plus_l _, R.plus_r _ => True
| R.times_l _, R.times_r _ => True
| _, _ => False
end.
Notation " a <: b " := (ec_order a b) (at level 40).
Lemma wf_eco : well_founded ec_order.
Proof.
prove_ec_wf.
Qed.
Lemma dec_term_red_empty : forall t r, dec_term t = R.in_red r -> R.only_empty t.
Proof.
intros t r H; destruct t; inversion H; subst; intros t c; generalize t; induction c; intros;
simpl in *; auto; clear H; assert (ht := IHc _ H0); subst c; destruct a; inversion H0.
Qed.
Lemma dec_term_val_empty : forall t v, dec_term t = R.in_val v -> R.only_empty t.
Proof.
intros t v H; destruct t; inversion H; subst; intros t c; generalize t; induction c; intros;
simpl in *; auto; clear H; assert (ht := IHc _ H0); subst c; destruct a; inversion H0.
Qed.
Lemma dec_term_term_top : forall t t' ec, dec_term t = R.in_term t' ec -> forall ec', ~ ec <: ec'.
Proof.
intros t t' ec H ec' H0; destruct t; inversion H; subst; destruct ec'; inversion H0.
Qed.
Lemma dec_context_red_bot : forall ec v r, dec_context ec v = R.in_red r -> forall ec', ~ec' <: ec.
Proof.
intros ec v r H ec' H0; destruct ec; inversion H; subst; destruct ec'; inversion H0.
Qed.
Lemma dec_context_val_bot : forall ec v v0, dec_context ec v = R.in_val v0 -> forall ec', ~ec' <: ec.
Proof.
intros ec v r H ec' H0; destruct ec; inversion H; subst; destruct ec'; inversion H0.
Qed.
Lemma dec_context_term_next : forall ec v t ec', dec_context ec v = R.in_term t ec' -> ec' <: ec /\ forall ec'', ec'' <: ec -> ~ec' <: ec''.
Proof.
intros; destruct ec; inversion H; subst; repeat constructor; intros; destruct ec''; inversion H0; intro; inversion H1.
Qed.
Lemma dec_term_correct : forall t, match dec_term t with
| R.in_red r => R.redex_to_term r = t
| R.in_val v => R.value_to_term v = t
| R.in_term t' ec => R.atom_plug t' ec = t
end.
Proof.
destruct t; simpl; auto.
Qed.
Lemma dec_context_correct : forall ec v, match dec_context ec v with
| R.in_red r => R.redex_to_term r = R.atom_plug (R.value_to_term v) ec
| R.in_val v0 => R.value_to_term v0 = R.atom_plug (R.value_to_term v) ec
| R.in_term t ec' => R.atom_plug t ec' = R.atom_plug (R.value_to_term v) ec
end.
Proof.
destruct ec; simpl; auto.
Qed.
Ltac inj_vr := match goal with
| [Hv : R.value_to_term _ = R.value_to_term _ |- _] => apply R.value_to_term_injective in Hv
| [Hr : R.redex_to_term _ = R.redex_to_term _ |- _] => apply R.redex_to_term_injective in Hr
| [ |- _] => idtac
end.
Lemma ec_order_antisym : forall ec ec0, ec <: ec0 -> ~ec0 <: ec.
Proof.
destruct ec; destruct ec0; intros H H0; inversion H; inversion H0.
Qed.
Lemma dec_ec_ord : forall t0 t1 ec0 ec1, R.atom_plug t0 ec0 = R.atom_plug t1 ec1 -> ec0 <: ec1 \/ ec1 <: ec0 \/ (t0 = t1 /\ ec0 = ec1).
Proof.
destruct ec0; destruct ec1; intros; inversion H; inj_vr; subst; simpl in *; auto.
Qed.
Lemma elem_context_det : forall t0 t1 ec0 ec1, ec0 <: ec1 -> R.atom_plug t0 ec0 = R.atom_plug t1 ec1 ->
exists v, t1 = R.value_to_term v.
Proof.
destruct ec0; destruct ec1; intros; inversion H; inversion H0; subst; exists v; auto.
Qed.
End Arith_Ref_Lang.
Module Arith_Ref_Sem_Auto <: RED_REF_SEM Arith_Lang := RedRefSem Arith_Ref_Lang.
Module Arith_Ref_Sem <: RED_REF_SEM Arith_Lang.
Definition term := Arith_Lang.term.
Definition value := Arith_Lang.value.
Definition redex := Arith_Lang.redex.
Definition context := Arith_Lang.context.
Definition empty := Arith_Lang.empty.
Definition decomp := Arith_Lang.decomp.
Definition elem_context := Arith_Lang.elem_context.
Definition d_val := Arith_Lang.d_val.
Definition d_red := Arith_Lang.d_red.
Definition value_to_term : value -> term := Arith_Lang.value_to_term.
Definition redex_to_term : redex -> term := Arith_Lang.redex_to_term.
Definition decomp_to_term : (decomp -> term) := Arith_Lang.decomp_to_term.
Definition atom_plug := Arith_Lang.atom_plug.
Definition plug : term -> context -> term := Arith_Lang.plug.
Definition compose : context -> context -> context := Arith_Lang.compose.
Definition contract : redex -> option term := Arith_Lang.contract.
Definition interm_dec := Arith_Lang.interm_dec.
Definition in_red := Arith_Lang.in_red.
Definition in_val := Arith_Lang.in_val.
Definition in_term := Arith_Lang.in_term.
Coercion value_to_term : value >-> term.
Coercion redex_to_term : redex >-> term.
(** Functions specifying atomic steps of induction on terms and contexts -- needed to avoid explicit induction on terms and contexts in construction of the AM *)
Definition dec_term : term -> interm_dec :=
fun (t : term) => match t with
| Arith_Lang.var vname => in_red (Arith_Lang.r_var vname)
| Arith_Lang.num n => in_val (Arith_Lang.v_num n)
| Arith_Lang.plus n m => in_term n (Arith_Lang.plus_r m)
| Arith_Lang.times n m => in_term n (Arith_Lang.times_r m)
end.
Definition dec_context : elem_context -> value -> interm_dec :=
fun (ec : elem_context) (v : value) => match ec with
| Arith_Lang.plus_r n => in_term n (Arith_Lang.plus_l v)
| Arith_Lang.plus_l v' => in_red (Arith_Lang.r_plus v' v)
| Arith_Lang.times_r n => in_term n (Arith_Lang.times_l v)
| Arith_Lang.times_l v' => in_red (Arith_Lang.r_times v' v)
end.
Lemma dec_term_value : forall (v:value), dec_term (v:term) = in_val v.
Proof.
destruct v; simpl; auto.
Qed.
Hint Resolve dec_term_value.
Lemma dec_term_correct : forall t, match dec_term t with
| in_red r => redex_to_term r = t
| in_val v => value_to_term v = t
| in_term t0 c0 => atom_plug t0 c0 = t
end.
Proof.
intro t; case t; intros; simpl; auto.
Qed.
Lemma dec_context_correct : forall c v, match dec_context c v with
| in_red r => redex_to_term r = atom_plug (value_to_term v) c
| in_val v0 => value_to_term v0 = atom_plug (value_to_term v) c
| in_term t c0 => atom_plug t c0 = atom_plug (value_to_term v) c
end.
Proof.
destruct c; intros; simpl; auto.
Qed.
(** A decomposition function specified in terms of the atomic functions above *)
Inductive dec : term -> context -> decomp -> Prop :=
| d_dec : forall (t : term) (c : context) (r : redex),
dec_term t = in_red r -> dec t c (d_red r c)
| d_v : forall (t : term) (c : context) (v : value) (d : decomp),
dec_term t = in_val v -> decctx v c d -> dec t c d
| d_term : forall (t t0 : term) (c : context) (ec : elem_context) (d : decomp),
dec_term t = in_term t0 ec -> dec t0 (ec :: c) d -> dec t c d
with decctx : value -> context -> decomp -> Prop :=
| dc_end : forall (v : value), decctx v empty (d_val v)
| dc_dec : forall (v : value) (ec : elem_context) (c : context) (r : redex),
dec_context ec v = in_red r -> decctx v (ec :: c) (d_red r c)
| dc_val : forall (v v0 : value) (ec : elem_context) (c : context) (d : decomp),
dec_context ec v = in_val v0 -> decctx v0 c d -> decctx v (ec :: c) d
| dc_term : forall (v : value) (ec ec0 : elem_context) (c : context) (t : term) (d : decomp),
dec_context ec v = in_term t ec0 -> dec t (ec0 :: c) d -> decctx v (ec :: c) d.
Scheme dec_Ind := Induction for dec Sort Prop
with decctx_Ind := Induction for decctx Sort Prop.
Lemma dec_red_ref : forall t c d, Arith_Sem.dec t c d <-> dec t c d.
Proof with eauto.
intros; split; intro.
induction H using Arith_Sem.dec_Ind with
(P := fun t c d (H : Arith_Sem.dec t c d) => dec t c d)
(P0:= fun v c d (H : Arith_Sem.decctx v c d) => decctx v c d);
[ constructor | econstructor 2 | econstructor 3 | econstructor 3 | constructor
| econstructor 4 | constructor | econstructor 4 | constructor]; simpl...
induction H using dec_Ind with
(P := fun t c d (H : dec t c d) => Arith_Sem.dec t c d)
(P0:= fun v c d (H : decctx v c d) => Arith_Sem.decctx v c d);
try (destruct t; inversion e; subst; constructor); auto; try constructor;
destruct ec; inversion e; subst; constructor...
Qed.
Module RS : RED_SEM Arith_Lang with Definition dec := dec.
Definition dec := dec.
Inductive decempty : term -> decomp -> Prop :=
| d_intro : forall (t : term) (d : decomp), dec t empty d -> decempty t d.
Inductive iter : decomp -> value -> Prop :=
| i_val : forall (v : value), iter (d_val v) v
| i_red : forall (r : redex) (t : term) (c : context) (d : decomp) (v : value),
contract r = Some t -> decempty (plug t c) d -> iter d v -> iter (d_red r c) v.
Inductive eval : term -> value -> Prop :=
| e_intro : forall (t : term) (d : decomp) (v : value), decempty t d -> iter d v -> eval t v.
Lemma dec_redex_self : forall (r : redex) (c : context), dec (redex_to_term r) c (d_red r c).
Proof.
intros; rewrite <- dec_red_ref; apply Arith_Sem.dec_redex_self.
Qed.
(** dec is left inverse of plug *)
Lemma dec_correct : forall t c d, dec t c d -> decomp_to_term d = plug t c.
Proof.
intros; apply Arith_Sem.dec_correct; rewrite dec_red_ref; auto.
Qed.
Lemma dec_plug : forall c c0 t d, dec (plug t c) c0 d -> dec t (compose c c0) d.
Proof.
intros; rewrite <- dec_red_ref; apply Arith_Sem.dec_plug; rewrite dec_red_ref; auto.
Qed.
Lemma dec_plug_rev : forall c c0 t d, dec t (compose c c0) d -> dec (plug t c) c0 d.
Proof.
intros; rewrite <- dec_red_ref; apply Arith_Sem.dec_plug_rev; rewrite dec_red_ref; auto.
Qed.
Definition decompose := Arith_Sem.decompose.
End RS.
Lemma iter_red_ref : forall d v, Arith_Sem.iter d v <-> RS.iter d v.
Proof.
intros; split; intro; induction H; try constructor;
constructor 2 with t d; auto; constructor;
[ inversion_clear H0; rewrite <- dec_red_ref | inversion_clear D_EM; rewrite dec_red_ref]; auto.
Qed.
Lemma eval_red_ref : forall t v, Arith_Sem.eval t v <-> RS.eval t v.
Proof.
intros; split; intro; inversion_clear H; constructor 1 with d.
constructor; inversion_clear H0; rewrite <- dec_red_ref; auto.
rewrite <- iter_red_ref; auto.
constructor; inversion_clear D_EM; rewrite dec_red_ref; auto.
rewrite iter_red_ref; auto.
Qed.
Lemma dec_val_self : forall v c d, dec (Arith_Lang.value_to_term v) c d <-> decctx v c d.
Proof.
split; intro.
destruct v; inversion H; inversion H0; subst; auto.
assert (hh := dec_term_value v); econstructor; eauto.
Qed.
End Arith_Ref_Sem.
Module Arith_PE_Sem <: PE_REF_SEM Arith_Lang.
Module Red_Sem := Arith_Ref_Sem.
Lemma dec_context_not_val : forall (v v0 : Arith_Lang.value) (ec : Arith_Lang.elem_context), ~Red_Sem.dec_context ec v = Arith_Lang.in_val v0.
Proof.
destruct ec; intros; simpl; intro; discriminate.
Qed.
Hint Resolve dec_context_not_val.
Definition dec_term_value := Red_Sem.dec_term_value.
End Arith_PE_Sem.
Module EAM := ProperEAMachine Arith_Lang Arith_Ref_Sem.
Module PEM := ProperPEMachine Arith_Lang Arith_PE_Sem.
Module EAArithMachine <: ABSTRACT_MACHINE.
Definition term := Arith_Lang.term.
Definition value := Arith_Lang.value.
Definition redex := Arith_Lang.redex.
Definition context := Arith_Lang.context.
Definition num := Arith_Lang.num.
Definition plus := Arith_Lang.plus.
Definition times := Arith_Lang.times.
Definition var := Arith_Lang.var.
Definition v_num := Arith_Lang.v_num.
Definition r_plus := Arith_Lang.r_plus.
Definition r_times:= Arith_Lang.r_times.
Definition r_var := Arith_Lang.r_var.
Definition empty := Arith_Lang.empty.
Definition plus_r := Arith_Lang.plus_r.
Definition plus_l := Arith_Lang.plus_l.
Definition times_r := Arith_Lang.times_r.
Definition times_l := Arith_Lang.times_l.
Definition value_to_term : value -> term := Arith_Lang.value_to_term.
Definition redex_to_term : redex -> term := Arith_Lang.redex_to_term.
Coercion value_to_term : value >-> term.
Coercion redex_to_term : redex >-> term.
Definition contract := Arith_Lang.contract.
Definition plug := Arith_Lang.plug.
Definition compose := Arith_Lang.compose.
Definition decomp := Arith_Lang.decomp.
Definition d_val := Arith_Lang.d_val.
Definition d_red := Arith_Lang.d_red.
Definition configuration := EAM.configuration.
Definition c_init := EAM.c_init.
Definition c_eval := EAM.c_eval.
Definition c_apply := EAM.c_apply.
Definition c_final := EAM.c_final.
Definition var_name := Arith_Lang.var_name.
Definition env := Arith_Lang.env.
Inductive transition' : configuration -> configuration -> Prop :=
| t_init : forall t : term, transition' (c_init t) (c_eval t empty)
| t_val : forall (v : value) (c : context), transition' (c_eval (v:term) c) (c_apply c v)
| t_plus : forall (t s : term) (c : context), transition' (c_eval (plus t s) c) (c_eval t (plus_r s :: c))
| t_times: forall (t s : term) (c : context), transition' (c_eval (times t s) c) (c_eval t (times_r s :: c))
| t_var : forall (x : var_name) (c : context), transition' (c_eval (var x) c) (c_eval (num (env x)) c)
| t_empty : forall v : value, transition' (c_apply empty v) (c_final v)
| t_plus_r : forall (t : term) (v : value) (c : context), transition' (c_apply (plus_r t :: c) v) (c_eval t (plus_l v :: c))
| t_plus_l : forall (v v0 : value) (c : context) (t : term),
contract (r_plus v0 v) = Some t -> transition' (c_apply (plus_l v0 :: c) v) (c_eval t c)
| t_times_r: forall (t : term) (v : value) (c : context), transition' (c_apply (times_r t :: c) v) (c_eval t (times_l v :: c))
| t_times_l: forall (v v0 : value) (c : context) (t : term),
contract (r_times v0 v) = Some t -> transition' (c_apply (times_l v0 :: c) v) (c_eval t c).
Definition transition := transition'.
Inductive trans_close : configuration -> configuration -> Prop :=
| one_step : forall (c0 c1 : configuration), transition c0 c1 -> trans_close c0 c1
| multi_step : forall (c0 c1 c2 : configuration), transition c0 c1 -> trans_close c1 c2 -> trans_close c0 c2.
Inductive eval : term -> value -> Prop :=
| e_intro : forall (t : term) (v : value), trans_close (c_init t) (c_final v) -> eval t v.
Lemma trEA_M : forall w w' : configuration, EAM.transition w w' -> transition w w'.
Proof with eauto.
intros w w' H; inversion H; subst;
try (destruct ec; inversion DC; subst; constructor; auto);
try constructor; destruct t; inversion DT; subst; try constructor.
inversion CONTR; subst; constructor.
cutrewrite (Arith_Lang.num n = value_to_term (Arith_Lang.v_num n)); [constructor | auto].
Qed.
Hint Resolve trEA_M.
Lemma tcEA_M : forall w w' : configuration, EAM.AM.trans_close w w' -> trans_close w w'.
Proof with eauto.
intros w w' H; induction H; subst; [ constructor 1 | econstructor 2]...
Qed.
Lemma evalEA_M : forall t v, EAM.AM.eval t v -> eval t v.
Proof.
intros t v H; inversion H; constructor; apply tcEA_M; auto.
Qed.
Hint Resolve evalEA_M.
Lemma trM_EA : forall w w' : configuration, transition w w' -> EAM.AM.transition w w'.
Proof with eauto.
intros w w' H; inversion H; subst; econstructor; simpl...
Qed.
Hint Resolve trM_EA.
Lemma tcM_EA : forall w w' : configuration, trans_close w w' -> EAM.AM.trans_close w w'.
Proof with eauto.
induction 1; [ constructor 1 | econstructor 2]...
Qed.
Lemma evalM_EA : forall t v, eval t v -> EAM.AM.eval t v.
Proof.
intros t v H; inversion H; constructor; apply tcM_EA; auto.
Qed.
Hint Resolve evalM_EA.
Theorem ArithMachineCorrect : forall (t : term) (v : value), Arith_Sem.eval t v <-> eval t v.
Proof with auto.
intros; rewrite Arith_Ref_Sem.eval_red_ref; rewrite EAM.eval_apply_correct; split...
Qed.
End EAArithMachine.
Module PEArithMachine <: ABSTRACT_MACHINE.
Definition term := Arith_Lang.term.
Definition value := Arith_Lang.value.
Definition redex := Arith_Lang.redex.
Definition context := Arith_Lang.context.
Definition num := Arith_Lang.num.
Definition plus := Arith_Lang.plus.
Definition times := Arith_Lang.times.
Definition var := Arith_Lang.var.
Definition v_num := Arith_Lang.v_num.
Definition r_plus := Arith_Lang.r_plus.
Definition r_times:= Arith_Lang.r_times.
Definition r_var := Arith_Lang.r_var.
Definition empty := Arith_Lang.empty.
Definition plus_r := Arith_Lang.plus_r.
Definition plus_l := Arith_Lang.plus_l.
Definition times_r := Arith_Lang.times_r.
Definition times_l := Arith_Lang.times_l.
Definition value_to_term : value -> term := Arith_Lang.value_to_term.
Definition redex_to_term : redex -> term := Arith_Lang.redex_to_term.
Coercion value_to_term : value >-> term.
Coercion redex_to_term : redex >-> term.
Definition contract := Arith_Lang.contract.
Definition plug := Arith_Lang.plug.
Definition compose := Arith_Lang.compose.
Definition decomp := Arith_Lang.decomp.
Definition d_val := Arith_Lang.d_val.
Definition d_red := Arith_Lang.d_red.
Definition configuration := PEM.configuration.
Definition c_init := PEM.c_init.
Definition c_eval := PEM.c_eval.
Definition c_final := PEM.c_final.
Definition var_name := Arith_Lang.var_name.
Definition env := Arith_Lang.env.
Inductive transition' : configuration -> configuration -> Prop :=
| t_init : forall t : term, transition' (c_init t) (c_eval t empty)
| t_plus : forall (t s : term) (c : context), transition' (c_eval (plus t s) c) (c_eval t (plus_r s :: c))
| t_times: forall (t s : term) (c : context), transition' (c_eval (times t s) c) (c_eval t (times_r s :: c))
| t_var : forall (x : var_name) (c : context), transition' (c_eval (var x) c) (c_eval (num (env x)) c)
| t_empty : forall v : value, transition' (c_eval (v:term) empty) (c_final v)
| t_plus_r : forall (t : term) (v : value) (c : context), transition' (c_eval (v:term) (plus_r t :: c)) (c_eval t (plus_l v :: c))
| t_plus_l : forall (v v0 : value) (c : context) (t : term),
contract (r_plus v0 v) = Some t -> transition' (c_eval (v:term) (plus_l v0 :: c)) (c_eval t c)
| t_times_r: forall (t : term) (v : value) (c : context), transition' (c_eval (v:term) (times_r t :: c)) (c_eval t (times_l v :: c))
| t_times_l: forall (v v0 : value) (c : context) (t : term),
contract (r_times v0 v) = Some t -> transition' (c_eval (v:term) (times_l v0 :: c)) (c_eval t c).
Definition transition := transition'.
Inductive trans_close : configuration -> configuration -> Prop :=
| one_step : forall (c0 c1 : configuration), transition c0 c1 -> trans_close c0 c1
| multi_step : forall (c0 c1 c2 : configuration), transition c0 c1 -> trans_close c1 c2 -> trans_close c0 c2.
Inductive eval : term -> value -> Prop :=
| e_intro : forall (t : term) (v : value), trans_close (c_init t) (c_final v) -> eval t v.
Lemma trPE_M : forall w w' : configuration, PEM.transition w w' -> transition w w'.
Proof with eauto.
assert (numeq : forall (n : nat), Arith_Lang.num n = value_to_term (Arith_Lang.v_num n))...
intros w w' H; inversion H; subst;
try constructor; destruct t; inversion DT; subst; try constructor.
inversion CONTR; subst; constructor.
rewrite numeq; constructor.
destruct ec; inversion DC; subst; destruct v; inversion CONTR; subst; rewrite numeq; constructor...
destruct ec; inversion DC; subst; rewrite numeq; constructor...
Qed.
Hint Resolve trPE_M.
Lemma tcPE_M : forall w w' : configuration, PEM.AM.trans_close w w' -> trans_close w w'.
Proof with eauto.
intros w w' H; induction H; subst; [ constructor 1 | econstructor 2]...
Qed.
Lemma evalPE_M : forall t v, PEM.AM.eval t v -> eval t v.
Proof.
intros t v H; inversion H; constructor; apply tcPE_M; auto.
Qed.
Hint Resolve evalPE_M.
Lemma trM_PE : forall w w' : configuration, transition w w' -> PEM.AM.transition w w'.
Proof with eauto.
intros w w' H; inversion H; subst; econstructor; simpl...
Qed.
Hint Resolve trM_PE.
Lemma tcM_PE : forall w w' : configuration, trans_close w w' -> PEM.AM.trans_close w w'.
Proof with eauto.
induction 1; [ constructor 1 | econstructor 2]...
Qed.
Lemma evalM_PE : forall t v, eval t v -> PEM.AM.eval t v.
Proof.
intros t v H; inversion H; constructor; apply tcM_PE; auto.
Qed.
Hint Resolve evalM_PE.
Theorem ArithMachineCorrect : forall (t : term) (v : value), Arith_Sem.eval t v <-> eval t v.
Proof with auto.
intros t v; rewrite Arith_Ref_Sem.eval_red_ref; rewrite PEM.push_enter_correct; split...
Qed.
End PEArithMachine.
|
/-
Copyright (c) 2021 Chris Birkbeck. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Birkbeck
-/
import group_theory.index
import group_theory.quotient_group
import group_theory.subgroup.pointwise
import group_theory.group_action.conj_act
/-!
# Commensurability for subgroups
This file defines commensurability for subgroups of a group `G`. It then goes on to prove that
commensurability defines an equivalence relation and finally defines the commensurator of a subgroup
of `G`.
## Main definitions
* `commensurable`: defines commensurability for two subgroups `H`, `K` of `G`
* `commensurator`: defines the commensurator of a subgroup `H` of `G`.
## Implementation details
We define the commensurator of a subgroup `H` of `G` by first defining it as a subgroup of
`(conj_act G)`, which we call commensurator' and then taking the pre-image under
the map `G → (conj_act G)` to obtain our commensurator as a subgroup of `G`.
-/
variables {G : Type*} [group G]
/--Two subgroups `H K` of `G` are commensurable if `H ⊓ K` has finite index in both `H` and `K` -/
def commensurable (H K : subgroup G) : Prop :=
H.relindex K ≠ 0 ∧ K.relindex H ≠ 0
namespace commensurable
open_locale pointwise
@[refl] protected lemma refl (H : subgroup G) : commensurable H H := by
simp [commensurable]
lemma comm {H K : subgroup G} : commensurable H K ↔ commensurable K H := and.comm
@[symm] lemma symm {H K : subgroup G} : commensurable H K → commensurable K H := and.symm
@[trans] lemma trans {H K L : subgroup G} (hhk : commensurable H K) (hkl : commensurable K L) :
commensurable H L :=
⟨subgroup.relindex_ne_zero_trans hhk.1 hkl.1, subgroup.relindex_ne_zero_trans hkl.2 hhk.2⟩
/--Equivalence of `K/H ⊓ K` with `gKg⁻¹/gHg⁻¹ ⊓ gKg⁻¹`-/
def quot_conj_equiv (H K : subgroup G) (g : conj_act G) :
K ⧸ (H.subgroup_of K) ≃ (g • K).1 ⧸ ((g • H).subgroup_of (g • K)) :=
quotient.congr (K.equiv_smul g).to_equiv (λ a b, by { rw [←quotient.eq', ←quotient.eq',
quotient_group.eq', quotient_group.eq', subgroup.mem_subgroup_of, subgroup.mem_subgroup_of,
mul_equiv.to_equiv_eq_coe, mul_equiv.coe_to_equiv, ←mul_equiv.map_inv, ←mul_equiv.map_mul,
subgroup.equiv_smul_apply_coe, subgroup.smul_mem_pointwise_smul_iff] })
lemma commensurable_conj {H K : subgroup G} (g : conj_act G) :
commensurable H K ↔ commensurable (g • H) (g • K) :=
and_congr (not_iff_not.mpr (eq.congr_left (cardinal.to_nat_congr (quot_conj_equiv H K g))))
(not_iff_not.mpr (eq.congr_left (cardinal.to_nat_congr (quot_conj_equiv K H g))))
lemma commensurable_inv (H : subgroup G) (g : conj_act G) :
commensurable (g • H) H ↔ commensurable H (g⁻¹ • H) :=
by rw [commensurable_conj, inv_smul_smul]
/-- For `H` a subgroup of `G`, this is the subgroup of all elements `g : conj_aut G`
such that `commensurable (g • H) H` -/
def commensurator' (H : subgroup G) : subgroup (conj_act G) :=
{ carrier := {g : conj_act G | commensurable (g • H) H},
one_mem' := by rw [set.mem_set_of_eq, one_smul],
mul_mem' := λ a b ha hb, by
{ rw [set.mem_set_of_eq, mul_smul],
exact trans ((commensurable_conj a).mp hb) ha },
inv_mem' := λ a ha, by rwa [set.mem_set_of_eq, comm, ←commensurable_inv] }
/-- For `H` a subgroup of `G`, this is the subgroup of all elements `g : G`
such that `commensurable (g H g⁻¹) H` -/
def commensurator (H : subgroup G) : subgroup G :=
(commensurator' H).comap (conj_act.to_conj_act.to_monoid_hom)
@[simp] lemma commensurator'_mem_iff (H : subgroup G) (g : conj_act G) :
g ∈ (commensurator' H) ↔ commensurable (g • H) H := iff.rfl
@[simp] lemma commensurator_mem_iff (H : subgroup G) (g : G) :
g ∈ (commensurator H) ↔ commensurable (conj_act.to_conj_act g • H) H := iff.rfl
lemma eq {H K : subgroup G} (hk : commensurable H K) :
commensurator H = commensurator K :=
subgroup.ext (λ x, let hx := (commensurable_conj x).1 hk in
⟨λ h, hx.symm.trans (h.trans hk), λ h, hx.trans (h.trans hk.symm)⟩)
end commensurable
|
import os
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
NAMES = np.array([
"MNIST",
"KMNIST",
"FashionMNIST",
"CIFAR10",
"CIFAR100",
# "TinyImageNet200",
])
EXISTS = np.array([os.path.exists(e) for e in NAMES])
NAMES = NAMES[EXISTS]
for name in NAMES:
# load images and labels
trn_images = np.load(f'{name}/train_images.npy')
trn_labels = np.load(f'{name}/train_labels.npy')
tst_images = np.load(f'{name}/test_images.npy')
tst_labels = np.load(f'{name}/test_labels.npy')
# just flatten images
trn_images = trn_images.reshape(trn_images.shape[0], -1)
tst_images = tst_images.reshape(tst_images.shape[0], -1)
# run k-NN classifier
knn = KNeighborsClassifier(
n_neighbors = 3,
weights = 'distance',
algorithm = 'auto',
n_jobs = -1,
)
knn.fit(trn_images, trn_labels)
print(f'{name} : ACC={knn.score(tst_images, tst_labels):.4f}')
|
The CPO Summit is the premium forum bringing elite buyers and sellers together. As an invitation-only event, taking place behind closed doors, the Summit offers solution providers and procurement executives an intimate environment for a focused discussion of key new drivers shaping the industry.
The marcus evans CPO Summit is the best in its class. Connecting quality suppliers with procurement executives is a "win win". The presentations were educational and informative. I highly recommend the CPO Summit.
One of the best events I have attended in 25 years. Intimate setting; this venue led to great relationship building and networking. Every aspect of event was flawless. Thank you for hosting.
I liked the format of the Summit. The one-on-one meetings, along with the informal networking opportunities, provided valuable time with delegates.
Well organized. Great quality of attendees.
Overall event was very well structured and ran professionally. Topics covered very pertinent to today's challenges in supply chain management and where the future is headed. |
{-# OPTIONS --without-K --safe #-}
open import Categories.Category
module Categories.Category.Duality {o ℓ e} (C : Category o ℓ e) where
open import Relation.Binary.PropositionalEquality using (_≡_; refl)
open import Categories.Category.Cartesian
open import Categories.Category.Cocartesian
open import Categories.Category.Complete
open import Categories.Category.Complete.Finitely
open import Categories.Category.Cocomplete
open import Categories.Category.Cocomplete.Finitely
open import Categories.Object.Duality
open import Categories.Diagram.Duality
open import Categories.Functor
private
module C = Category C
open C
coCartesian⇒Cocartesian : Cartesian C.op → Cocartesian C
coCartesian⇒Cocartesian Car = record
{ initial = op⊤⇒⊥ C terminal
; coproducts = record
{ coproduct = coProduct⇒Coproduct C product
}
}
where open Cartesian Car
Cocartesian⇒coCartesian : Cocartesian C → Cartesian C.op
Cocartesian⇒coCartesian Co = record
{ terminal = ⊥⇒op⊤ C initial
; products = record
{ product = Coproduct⇒coProduct C coproduct
}
}
where open Cocartesian Co
coComplete⇒Cocomplete : ∀ {o′ ℓ′ e′} → Complete o′ ℓ′ e′ C.op → Cocomplete o′ ℓ′ e′ C
coComplete⇒Cocomplete Com F = coLimit⇒Colimit C (Com F.op)
where module F = Functor F
Cocomplete⇒coComplete : ∀ {o′ ℓ′ e′} → Cocomplete o′ ℓ′ e′ C → Complete o′ ℓ′ e′ C.op
Cocomplete⇒coComplete Coc F = Colimit⇒coLimit C (Coc F.op)
where module F = Functor F
coFinitelyComplete⇒FinitelyCocomplete : FinitelyComplete C.op → FinitelyCocomplete C
coFinitelyComplete⇒FinitelyCocomplete FC = record
{ cocartesian = coCartesian⇒Cocartesian cartesian
; coequalizer = λ f g → coEqualizer⇒Coequalizer C (equalizer f g)
}
where open FinitelyComplete FC
FinitelyCocomplete⇒coFinitelyComplete : FinitelyCocomplete C → FinitelyComplete C.op
FinitelyCocomplete⇒coFinitelyComplete FC = record
{ cartesian = Cocartesian⇒coCartesian cocartesian
; equalizer = λ f g → Coequalizer⇒coEqualizer C (coequalizer f g)
}
where open FinitelyCocomplete FC
module DualityConversionProperties where
private
op-involutive : Category.op C.op ≡ C
op-involutive = refl
coCartesian⇔Cocartesian : ∀(coCartesian : Cartesian C.op)
→ Cocartesian⇒coCartesian (coCartesian⇒Cocartesian coCartesian)
≡ coCartesian
coCartesian⇔Cocartesian _ = refl
coFinitelyComplete⇔FinitelyCocomplete : ∀(coFinComplete : FinitelyComplete C.op) →
FinitelyCocomplete⇒coFinitelyComplete
(coFinitelyComplete⇒FinitelyCocomplete coFinComplete) ≡ coFinComplete
coFinitelyComplete⇔FinitelyCocomplete _ = refl
|
||| Various tests of automatically-generated eliminators, to show that
||| the compiler doesn't barf and that they can be used for proving
||| things.
module ElimTest
import Data.Vect
import Data.So
import Control.WellFounded
import Data.Nat.DivMod.IteratedSubtraction
import Pruviloj.Core
import Pruviloj.Derive.Eliminators
import Derive.TestDefs
%default total
mkName : String -> TTName
mkName n = NS (UN n) ["ElimTest"]
mutual
data U : Type where
UNIT : U
PI : (t : U) -> (el t -> U) -> U
el : U -> Type
el UNIT = ()
el (PI ty ret) = (x : el ty) -> (el $ ret x)
mutual
data Even : Nat -> Type where
EvenZ : Even Z
EvenS : Odd n -> Even (S n)
data Odd : Nat -> Type where
OddN : Even n -> Odd (S n)
forEffect : ()
forEffect = %runElab (do deriveElim `{Vect} (mkName "vectElim")
deriveElim `{Bool} (mkName "boolElim")
deriveElim `{List} (mkName "listElim")
deriveElim `{So} (mkName "soElim")
deriveElim `{Void} (mkName "voidElim")
deriveElim `{Nat} (mkName "natElim")
deriveElim `{LTE} (mkName "lteElim")
deriveElim `{LT'} (mkName "ltElim")
deriveElim `{(=)} (mkName "wrongEqElim")
deriveElim `{U} (mkName "uElim")
deriveElim `{W} (mkName "wElim")
deriveElim `{Unit} (mkName "unitElim")
deriveElim `{Even} (mkName "evenElim")
deriveElim `{Odd} (mkName "oddElim")
deriveElim `{Accessible} (mkName "accElim")
search)
||| Simple function computed using an eliminator
rev : List a -> List a
rev {a} xs = listElim a xs (const $ List a) [] (\y, _, ys => ys ++ [y])
||| Simple proof by induction using a generated eliminator
total
plusIsAssociative : (x,y,z : Nat) -> plus x (plus y z) = plus (plus x y) z
plusIsAssociative = \x,y,z => natElim x (\n => plus n (plus y z) = plus (plus n y) z) Refl (\n, ih => cong ih)
||| The "shape" of the underlying tree for Nat encoded as a W-type
WNatStep : Bool -> Type
WNatStep b = if b then () else Void
||| Nats, as a W-type
WNat : Type
WNat = W Bool WNatStep
||| Zero (it has no predecessors!)
WZ : WNat
WZ = Sup False void
||| Succ (it has a single predecessor, thus ()!)
wS : WNat -> WNat
wS n = Sup True (const n)
||| The induction principle for Nat, here expressed on Nat encoded as W-types.
|||
||| Note that this only works for this particular encoding of the
||| Nat. A separate, equivalent encoding would not work due to W-types
||| being basically useless in intensional type theory. Nevertheless,
||| it demonstrates that the generated eliminators can be used.
indWNat : (P : WNat -> Type) -> P WZ -> ((n : WNat) -> P n -> P (wS n)) -> (n : WNat) -> P n
indWNat P z s n = wElim Bool WNatStep n P
(\b => boolElim b
(\b' => (f : WNatStep b' -> WNat) ->
((x : WNatStep b') -> P (f x)) ->
P (Sup b' f))
(\f, _ => rewrite voidFunext f void in z)
(\f, ih => rewrite unitFunext f in s (f ()) (ih ())))
where
||| Functional extensionality that uses unsafe features to get it
||| to actually compute. This is evil and perhaps even inconsistent:
||| replace with a postulate for sanity. But it lets addition of WNat go.
funext : (f, g : a -> b) -> ((x : a) -> f x = g x) -> f = g
funext {a} {b} f g fun = really_believe_me (Refl {A=a->b} {x=f})
voidFunext : (f, g : Void -> a) -> f = g
voidFunext = \f,g => funext f g (\x => voidElim x (const (f x = g x)))
unitEta : (x : ()) -> x = ()
unitEta () = Refl
unitFunext : (f : () -> a) -> f = \x => f ()
unitFunext = \f => funext f (\x => f ()) (\x => cong (unitEta x))
addWNat : WNat -> WNat -> WNat
addWNat x y = indWNat (const WNat) y (\_, m => wS m) x
||| Recover the induction principle over well-founded relations from the generated one
accInd' : {rel : a -> a -> Type} -> {P : a -> Type} ->
(step : (x : a) -> ((y : a) -> rel y x -> P y) -> P x) ->
(z : a) -> Accessible rel z -> P z
accInd' {a} {rel} {P} step z acc =
accElim a rel z acc (\x, _ => P x) (\y, acc', ih => step y ih)
|
open import Relation.Nullary using (¬_)
module AKS.Fin where
open import AKS.Nat using (ℕ; _+_; _<_)
record Fin (n : ℕ) : Set where
constructor Fin✓
field
i : ℕ
i<n : i < n
¬Fin0 : ¬ (Fin 0)
¬Fin0 ()
from< : ∀ {i n} → i < n → Fin n
from< {i} i<n = Fin✓ i i<n
|
# Libraries
library(tidyverse)
#library(patchwork)
#library(hrbrthemes)
#library(circlize)
library(networkD3)
library(dplyr)
par(cex = 0.90, mar = c(0, 0, 0, 0))
#mat <- read.csv(file = 'final.csv',row.names = 1, header= TRUE)
# Define the "data" for the digram is "matrix" from above
data <- read.csv(file = 'cvd-os-ints-prot.csv',row.names = 1, header= TRUE)
data
# Reshape data to long format
data_long <- data %>%
rownames_to_column %>%
gather(key = 'key', value = 'value', -rowname) %>%
filter(value > 0)
colnames(data_long) <- c("source", "target", "value")
data_long$target <- paste(data_long$target, " ", sep="")
# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodes <- data.frame(name=c(as.character(data_long$source),
as.character(data_long$target)) %>%
unique()
)
# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
data_long$IDsource=match(data_long$source, nodes$name)-1
data_long$IDtarget=match(data_long$target, nodes$name)-1
# Prepare colour scale (7-class Blues, 7-class Greens, 7-class YlOrRd)
ColourScal ='d3.scaleOrdinal() .range(["#084594","#2171b5","#4292c6",
"#6baed6","#9ecae1","#c6dbef","#238b45","#41ab5d","#74c476","#b10026", "#fc4e2a","#ffffb2"])'
# Make the Network
##### set "iterations=0" to avoid automatic assignment of the box order
sankeyNetwork(Links = data_long, Nodes = nodes,
Source = "IDsource", Target = "IDtarget",
Value = "value", NodeID = "name",
sinksRight=FALSE, colourScale=ColourScal,
nodeWidth=40, fontSize=13, nodePadding=20,
iterations=0
)
|
!##############################################################################
!# ****************************************************************************
!# <name> elemdbg2d_test1 </name>
!# ****************************************************************************
!#
!# <purpose>
!# </purpose>
!##############################################################################
module elemdbg2d_test1
use fsystem
use genoutput
use paramlist
use storage
use cubature
use matrixfilters
use vectorfilters
use bcassembly
use bcassemblybase
use linearalgebra
use dofmapping
use basicgeometry
use triangulation
use element
use spatialdiscretisation
use transformation
use elementpreprocessing
use linearsystemscalar
use linearsystemblock
use discretebc
use scalarpde
use pprocerror
use stdoperators
use meshmodification
use ucd
use spdiscprojection
use convection
use collection
use sortstrategybase
use sortstrategy
use bilinearformevaluation
use linearformevaluation
use linearsolver
use statistics
use elemdbg2d_callback
use elemdbg2d_sd_aux
use disto2d_aux
implicit none
contains
! ***************************************************************************
!<subroutine>
subroutine elemdbg2d_1(rparam, sConfigSection, itest)
type(t_parlist), intent(INOUT) :: rparam
character(LEN=*), intent(IN) :: sConfigSection
integer, intent(IN) :: itest
!<description>
!</description>
!</subroutine>
type(t_boundary) :: rboundary
type(t_triangulation) :: rtriangulation
type(t_blockDiscretisation) :: rdiscretisation
type(t_linearForm) :: rlinform
type(t_matrixBlock) :: rmatrix
type(t_vectorBlock), target :: rvecSol, rvecRhs, rvectmp
type(t_boundaryRegion) :: rboundaryRegion
type(t_discreteBC), target :: rdiscreteBC
type(t_linsolNode), pointer :: p_rsolver, p_rprecond
type(t_matrixBlock), dimension(1) :: Rmatrices
type(t_errorScVec) :: rerror
integer :: NLMIN,NLMAX,ierror,ilvl
real(DP), dimension(:,:), allocatable, target :: Derror
real(DP), dimension(:,:), allocatable, target :: Dtimer
integer, dimension(:,:), allocatable :: Istat
integer :: isolver, ioutput, nmaxiter,ccubature,idistType,idistLevel,idistLvl
integer(I32) :: celement, cprimaryelement, cshape
real(DP) :: ddist, depsRel, depsAbs, drelax, daux1, daux2, daux3, daux4, daux5, ddist2
character(LEN=32) :: selement,sprimaryelement,scubature
type(t_bilinearForm) :: rform
integer :: iucd
type(t_ucdexport) :: rexport
real(DP) :: dnu,dbeta1,dbeta2,dupsam,dgamma
integer :: istabil, isolution, ifillin, clocalh
type(t_convStreamlineDiffusion) :: rconfigSD
type(t_jumpStabilisation) :: rconfigEOJ
type(t_collection) :: rcollect
integer, dimension(:), allocatable :: p_Iedges, p_Itemp
integer :: iedge,ibc,nedgecount
type(t_vectorBlock) :: rvelocityVector
type(t_blockDiscretisation) :: rdiscretisationVel
character(len=SYS_STRLEN) :: spredir, sucddir
type(t_blockSortStrategy) :: rsortStrategy
type(t_scalarCubatureInfo) :: rcubatureInfo
type(t_timer) :: rtimer
! Fetch sytem variables
if (.not. sys_getenv_string("PREDIR", spredir)) spredir = './pre'
if (.not. sys_getenv_string("UCDDIR", sucddir)) sucddir = './ucd'
! Fetch minimum and maximum levels
call parlst_getvalue_int(rparam, sConfigSection, 'NLMIN', NLMIN, -1)
call parlst_getvalue_int(rparam, sConfigSection, 'NLMAX', NLMAX, -1)
if((NLMIN .lt. 1) .or. (NLMAX .lt. NLMIN)) then
call output_line('Invalid NLMIN/NLMAX parameters',&
OU_CLASS_ERROR, OU_MODE_STD, 'elemdbg2d_1')
call sys_halt()
end if
! Fetch mesh distortion type
call parlst_getvalue_int(rparam, sConfigSection, 'IDISTTYPE', idistType, 0)
! Fetch mesh distortion level
call parlst_getvalue_int(rparam, sConfigSection, 'IDISTLEVEL', idistLevel, 0)
! Fetch mesh distortion parameters
call parlst_getvalue_double(rparam, sConfigSection, 'DMESHDISTORT', ddist, 0.1_DP)
call parlst_getvalue_double(rparam, sConfigSection, 'DMESHDISTORT2', ddist2, 0.0_DP)
! Fetch element and cubature rule
call parlst_getvalue_string(rparam, sConfigSection, 'SELEMENT', selement, '')
call parlst_getvalue_string(rparam, sConfigSection, 'SCUBATURE', scubature, '')
! Fetch desired solution
call parlst_getvalue_int(rparam, sConfigSection, 'ISOLUTION', isolution, 0)
! Fetch solver type
call parlst_getvalue_int(rparam, sConfigSection, 'ISOLVER', isolver, 0)
! Fetch solver output level
call parlst_getvalue_int(rparam, sConfigSection, 'IOUTPUT', ioutput, 0)
! Fetch maximum number of iterations
call parlst_getvalue_int(rparam, sConfigSection, 'NMAXITER', nmaxiter, 100)
! Fetch solver tolerances
call parlst_getvalue_double(rparam, sConfigSection, 'DEPSABS', depsAbs, 1E-11_DP)
call parlst_getvalue_double(rparam, sConfigSection, 'DEPSREL', depsRel, 1E-8_DP)
! Fetch problem parameters
call parlst_getvalue_double(rparam, sConfigSection, 'DNU', dnu, 1.0_DP)
call parlst_getvalue_double(rparam, sConfigSection, 'DBETA1', dbeta1, 0.0_DP)
call parlst_getvalue_double(rparam, sConfigSection, 'DBETA2', dbeta2, 0.0_DP)
! Fetch stabilisation parameters
call parlst_getvalue_int(rparam, sConfigSection, 'ISTABIL', istabil, 0)
call parlst_getvalue_int(rparam, sConfigSection, 'CLOCALH', clocalh, 0)
call parlst_getvalue_double(rparam, sConfigSection, 'DUPSAM', dupsam, 1.0_DP)
call parlst_getvalue_double(rparam, sConfigSection, 'DGAMMA', dgamma, 0.01_DP)
! Fetch relaxation parameter for CG-SSOR
call parlst_getvalue_double(rparam, sConfigSection, 'DRELAX', drelax, 1.2_DP)
! Fetch fill-in level for ILU(k) preconditioner
call parlst_getvalue_int(rparam, sConfigSection, 'IFILLIN', ifillin, 0)
! UCD export
call parlst_getvalue_int(rparam, sConfigSection, 'IUCD', iucd, 0)
! Parse element and cubature
celement = elem_igetID(selement)
ccubature = cub_igetID(scubature)
! Get primary element
cprimaryelement = elem_getPrimaryElement(celement)
sprimaryelement = elem_getName(cprimaryelement)
! Get the shape of the element
cshape = elem_igetShape(celement)
! Allocate arrays
allocate(Derror(2,NLMIN:NLMAX))
allocate(Dtimer(5,NLMIN:NLMAX))
allocate(Istat(5,NLMIN:NLMAX))
call output_separator(OU_SEP_STAR)
call output_line('ELEMENT-DEBUGGER: 2D TEST #1')
call output_line('============================')
! Print out that we are going to do:
select case(itest)
case(201)
call output_line('System.............: L2-projection')
case(202)
call output_line('System.............: Poisson')
case(203)
call output_line('System.............: Convection-Diffusion')
call output_line('DNU................: ' // trim(sys_sdEP(dnu,20,12)))
call output_line('DBETA1.............: ' // trim(sys_sdEP(dbeta1,20,12)))
call output_line('DBETA2.............: ' // trim(sys_sdEP(dbeta2,20,12)))
select case(istabil)
case(0)
call output_line('Stabilisation......: none')
case(1)
call output_line('Stabilisation......: Streamline-Diffusion')
call output_line('DUPSAM.............: ' // trim(sys_sdEP(dupsam,20,12)))
case(2)
call output_line('Stabilisation......: Jump-Stabilisation')
call output_line('DGAMMA.............: ' // trim(sys_sdEP(dgamma,20,12)))
case(3)
call output_line('Stabilisation......: Streamline-Diffusion (kernel)')
call output_line('DUPSAM.............: ' // trim(sys_sdEP(dupsam,20,12)))
call output_line('CLOCALH............: ' // trim(sys_si(clocalh,4)))
case default
call output_line('Invalid ISTABIL parameter', &
OU_CLASS_ERROR, OU_MODE_STD, 'elemdbg2d_1')
call sys_halt()
end select
case default
call output_line('Invalid ITEST parameter', &
OU_CLASS_ERROR, OU_MODE_STD, 'elemdbg2d_1')
call sys_halt()
end select
select case(isolution)
case(0)
call output_line('Solution...........: u(x,y) = sin(pi*x) * sin(pi*y)')
case(1)
call output_line('Solution...........: u(x,y) = x')
case(2)
call output_line('Solution...........: u(x,y) = y')
case(3)
call output_line('Solution...........: u(x,y) = 16*x*(1-x)*y*(1-y)')
case default
call output_line('Invalid ISOLUTION parameter', &
OU_CLASS_ERROR, OU_MODE_STD, 'elemdbg2d_1')
call sys_halt()
end select
select case(cshape)
case(BGEOM_SHAPE_TRIA)
call output_line('Coarse Mesh........: TRIA.tri')
case(BGEOM_SHAPE_QUAD)
call output_line('Coarse Mesh........: QUAD.tri')
case default
call output_line('Element is not a valid 2D element!', &
OU_CLASS_ERROR, OU_MODE_STD, 'elemdbg2d_1')
call sys_halt()
end select
call output_line('NLMIN..............: ' // trim(sys_siL(NLMIN,4)))
call output_line('NLMAX..............: ' // trim(sys_siL(NLMAX,4)))
select case(idistType)
case(0)
! no distortion => nothing else to print
case(1)
call output_line('Distortion Type....: index-based')
case(2)
call output_line('Distortion Type....: X-line-wise index-based')
case(3)
call output_line('Distortion Type....: Y-line-wise index-based')
case default
call output_line('Invalid IDISTTYPE parameter', &
OU_CLASS_ERROR, OU_MODE_STD, 'elemdbg2d_1')
call sys_halt()
end select
if(idistType .ne. 0) then
call output_line('Distortion Level...: ' // trim(sys_siL(idistLevel,4)))
call output_line('Mesh Distortion....: ' // trim(sys_sdL(ddist,8)))
end if
if((idistType .ge. 2) .and. (idistType .le. 3)) then
call output_line('Mesh Distortion 2..: ' // trim(sys_sdL(ddist2,8)))
end if
#ifdef USE_LARGEINT
call output_line('Element............: ' // trim(selement) // &
' (ID=' // trim(sys_siL(int(celement,I64),12)) // ')')
call output_line('Primary element....: ' // trim(sprimaryelement) // &
' (ID=' // trim(sys_siL(int(cprimaryelement,I64),12)) // ')')
#else
call output_line('Element............: ' // trim(selement) // &
' (ID=' // trim(sys_siL(celement,12)) // ')')
call output_line('Primary element....: ' // trim(sprimaryelement) // &
' (ID=' // trim(sys_siL(cprimaryelement,12)) // ')')
#endif
call output_line('Cubature rule......: ' // trim(scubature) // &
' (ID=' // trim(sys_siL(ccubature,12)) // ')')
select case(isolver)
case(0)
call output_line('Solver.............: UMFPACK4')
case(1)
call output_line('Solver.............: CG-SSOR')
call output_line('Relaxation.........: ' // trim(sys_sdL(drelax,8)))
case(2)
call output_line('Solver.............: BiCGStab-ILU(k)')
if(ifillin .lt. 0) then
call output_line('IFILLIN must not be less than 0', &
OU_CLASS_ERROR, OU_MODE_STD, 'elemdbg3d_1')
call sys_halt()
end if
call output_line('Allowed Fill-In....: ' // trim(sys_siL(ifillin,4)))
case default
call output_line('Invalid ISOLVER parameter', &
OU_CLASS_ERROR, OU_MODE_STD, 'elemdbg2d_1')
call sys_halt()
end select
call output_line('Output Level.......: ' // trim(sys_siL(ioutput,4)))
call output_line('Maximum Iter.......: ' // trim(sys_siL(nmaxiter,12)))
call output_line('Absolute EPS.......: ' // trim(sys_sdEP(depsAbs,20,12)))
call output_line('Relative EPS.......: ' // trim(sys_sdEP(depsRel,20,12)))
call output_lbrk()
! Copy important parameters into quick-access arrays of the collection,
! these ones are needed by the callback functions.
rcollect%IquickAccess(1) = itest
rcollect%IquickAccess(2) = isolution
rcollect%DquickAccess(1) = dnu
rcollect%DquickAccess(2) = dbeta1
rcollect%DquickAccess(3) = dbeta2
! Read in parametrisation
select case(cshape)
case(BGEOM_SHAPE_TRIA)
call boundary_read_prm(rboundary, trim(spredir) // '/TRIA.prm')
case(BGEOM_SHAPE_QUAD)
call boundary_read_prm(rboundary, trim(spredir) // '/QUAD.prm')
end select
! Loop over all levels
do ilvl = NLMIN, NLMAX
call output_line('Processing Level ' // trim(sys_siL(ilvl,4)) // '...')
! Start time measurement
call stat_startTimer(rtimer,STAT_TIMERSHORT)
! Now read in the basic triangulation.
select case(cshape)
case(BGEOM_SHAPE_TRIA)
call tria_readTriFile2D (rtriangulation, trim(spredir) // '/TRIA.tri', rboundary)
case(BGEOM_SHAPE_QUAD)
call tria_readTriFile2D (rtriangulation, trim(spredir) // '/QUAD.tri', rboundary)
end select
if(idistLevel .le. 0) then
idistLvl = max(1,ilvl-idistLevel)
else
idistLvl = idistLevel
end if
if((idistLvl .le. ilvl) .and. (idistType .ne. 0)) then
! Refine up to distortion level
call tria_quickRefine2LevelOrdering (idistLvl-1, rtriangulation,rboundary)
! Distort the mesh
select case(idistType)
case (1)
! index-based distortion
call meshmod_disturbMesh (rtriangulation, ddist)
case (2)
! X-line-wise index-based distortion
call disto2d_distortQuadLineX(rtriangulation, ddist, ddist2)
case (3)
! Y-line-wise index-based distortion
call disto2d_distortQuadLineY(rtriangulation, ddist, ddist2)
end select
! Refine up to current level
if(idistLvl .lt. ilvl) then
call tria_quickRefine2LevelOrdering (ilvl-idistLvl, rtriangulation,rboundary)
end if
else
! Refine up to current level
call tria_quickRefine2LevelOrdering (ilvl-1, rtriangulation,rboundary)
end if
! And create information about adjacencies and everything one needs from
! a triangulation.
call tria_initStandardMeshFromRaw (rtriangulation,rboundary)
! Stop time measurement
call stat_stopTimer(rtimer)
Dtimer(1,ilvl) = rtimer%delapsedReal
! Start time measurement
call stat_clearTimer(rtimer)
call stat_startTimer(rtimer,STAT_TIMERSHORT)
! Set up discretisation
call spdiscr_initBlockDiscr (rdiscretisation,1,rtriangulation, rboundary)
call spdiscr_initDiscr_simple (rdiscretisation%RspatialDiscr(1), &
celement, rtriangulation, rboundary)
! Set up a cubature info structure
call spdiscr_createDefCubStructure(&
rdiscretisation%RspatialDiscr(1), rcubatureInfo, int(ccubature,I32))
! Create matrix structure
call lsysbl_createMatBlockByDiscr(rdiscretisation, rmatrix)
if ((itest .eq. 203) .and. (istabil .eq. 2)) then
! Extended matrix stencil
call bilf_createMatrixStructure(rdiscretisation%RspatialDiscr(1),&
LSYSSC_MATRIX9,rmatrix%RmatrixBlock(1,1),&
cconstrType=BILF_MATC_EDGEBASED)
else
call bilf_createMatrixStructure(rdiscretisation%RspatialDiscr(1),&
LSYSSC_MATRIX9,rmatrix%RmatrixBlock(1,1))
end if
! Create vectors
call lsysbl_createVecBlockIndMat(rmatrix, rvecSol, .true.)
call lsysbl_createVecBlockIndMat(rmatrix, rvecRhs, .true.)
call lsysbl_createVecBlockIndMat(rmatrix, rvecTmp, .true.)
! Set up discrete BCs
if(itest .ne. 201) then
call bcasm_initDiscreteBC(rdiscreteBC)
call boundary_createRegion(rboundary,1,0,rboundaryRegion)
call bcasm_newDirichletBConRealBD (rdiscretisation,1,&
rboundaryRegion,rdiscreteBC,getBoundaryValues2D,rcollect)
! Assign BCs
rmatrix%p_rdiscreteBC => rdiscreteBC
rvecSol%p_rdiscreteBC => rdiscreteBC
rvecRhs%p_rdiscreteBC => rdiscreteBC
end if
! Store statistics
Istat(1,ilvl) = rmatrix%NEQ
Istat(2,ilvl) = rmatrix%rmatrixBlock(1,1)%NA
Istat(3,ilvl) = rtriangulation%NVT
Istat(4,ilvl) = rtriangulation%NMT
Istat(5,ilvl) = rtriangulation%NEL
! Stop time measurement
call stat_stopTimer(rtimer)
Dtimer(2,ilvl) = rtimer%delapsedReal
! Start time measurement
call stat_clearTimer(rtimer)
call stat_startTimer(rtimer,STAT_TIMERSHORT)
! Assemble system
select case(itest)
case(201)
! Assemble Mass matrix
call stdop_assembleSimpleMatrix(rmatrix%RmatrixBlock(1,1), &
DER_FUNC2D, DER_FUNC2D,&
rcubatureInfo=rcubatureInfo)
case(202)
! Assemble Laplace matrix
call stdop_assembleLaplaceMatrix(rmatrix%RmatrixBlock(1,1),&
rcubatureInfo=rcubatureInfo)
case(203)
! Assemble Laplace matrix
call stdop_assembleLaplaceMatrix(rmatrix%RmatrixBlock(1,1),.true.,dnu,&
rcubatureInfo=rcubatureInfo)
! Stabilisation?
select case (istabil)
case (0)
! Assemble convective operator, sum up to the Laplace operator
rform%itermcount = 2
rform%Idescriptors(1,1) = DER_DERIV_X
rform%Idescriptors(2,1) = DER_FUNC
rform%Idescriptors(1,2) = DER_DERIV_Y
rform%Idescriptors(2,2) = DER_FUNC
rform%Dcoefficients(1) = dbeta1
rform%Dcoefficients(2) = dbeta2
call bilf_buildMatrixScalar (rform,.false.,rmatrix%RmatrixBlock(1,1),&
rcubatureInfo)
case (1)
! Assemble the convection directly including the stabilisation
rconfigSD%dupsam = dupsam
rconfigSD%dnu = dnu
call elemdbg2d_sd (dbeta1,dbeta2,rconfigSD,rmatrix%RmatrixBlock(1,1))
case (2)
! Assemble convective operator, sum up to the Laplace operator
rform%itermcount = 2
rform%Idescriptors(1,1) = DER_DERIV_X
rform%Idescriptors(2,1) = DER_FUNC
rform%Idescriptors(1,2) = DER_DERIV_Y
rform%Idescriptors(2,2) = DER_FUNC
rform%Dcoefficients(1) = dbeta1
rform%Dcoefficients(2) = dbeta2
call bilf_buildMatrixScalar (rform,.false.,rmatrix%RmatrixBlock(1,1),&
rcubatureInfo)
! Assemble the jump stabilisation
rconfigEOJ%dgamma = dgamma
rconfigEOJ%dgammastar = dgamma
rconfigEOJ%dnu = dnu
call conv_JumpStabilisation2d (rconfigEOJ, CONV_MODMATRIX, rmatrix%RmatrixBlock(1,1))
! Subtract the boundary edges from the matrix.
rconfigEOJ%dtheta = -1.0_DP
allocate (p_Iedges(rtriangulation%NMT))
allocate (p_Itemp(rtriangulation%NMT))
! Loop over the edges and boundary components
do ibc = 1,boundary_igetNBoundComp(rboundary)
do iedge = 1,boundary_igetNsegments(rboundary, ibc)
! Get a region identifying that boundary edge
call boundary_createRegion(rboundary,ibc,iedge,rboundaryRegion)
! Get triangulation edges on that boundary edge
call bcasm_getEdgesInBdRegion (rtriangulation,rboundaryRegion, &
nedgecount, p_Iedges, p_Itemp)
! Subtract the jump
call conv_JumpStabilisation2d(rconfigEOJ,CONV_MODMATRIX,rmatrix%RmatrixBlock(1,1), &
InodeList=p_Iedges(1:nedgecount))
end do
end do
deallocate (p_Iedges,p_Itemp)
rconfigEOJ%dtheta = 1.0_DP
case (3)
! Prepare a velocity field resembling our convection
call spdiscr_initBlockDiscr (rdiscretisationVel,2,rtriangulation, rboundary)
call spdiscr_duplicateDiscrSc (rdiscretisation%RspatialDiscr(1), &
rdiscretisationVel%RspatialDiscr(1), .true.)
call spdiscr_duplicateDiscrSc (rdiscretisation%RspatialDiscr(1), &
rdiscretisationVel%RspatialDiscr(2), .true.)
! Create the velocity vector
call lsysbl_createVectorBlock (rdiscretisationVel,rvelocityVector)
call lsyssc_clearVector (rvelocityVector%RvectorBlock(1),dbeta1)
call lsyssc_clearVector (rvelocityVector%RvectorBlock(2),dbeta2)
! Assemble the convection using the kernel stabilisation
rconfigSD%dupsam = dupsam
rconfigSD%dnu = dnu
rconfigSD%clocalh = clocalh
call conv_streamlineDiffusionBlk2d ( &
rvelocityVector, rvelocityVector, 1.0_DP, 0.0_DP,&
rconfigSD, CONV_MODMATRIX,rmatrix)
! Release all that temporary stuff.
call lsysbl_releaseVector (rvelocityVector)
call spdiscr_releaseBlockDiscr (rdiscretisationVel)
end select
end select
! Assemble RHS vector
rlinform%itermCount = 1
rlinform%Idescriptors(1) = DER_FUNC2D
call linf_buildVectorScalar (rlinform,.true.,rvecRhs%RvectorBlock(1),&
rcubatureInfo,coeff_RHS2D,rcollect)
! In any case except for L2-projection, filter the system
if(itest .ne. 201) then
! Implement BCs
call vecfil_discreteBCrhs (rvecRhs)
call vecfil_discreteBCsol (rvecsol)
call matfil_discreteBC (rmatrix)
end if
! Stop time measurement
call stat_stopTimer(rtimer)
Dtimer(3,ilvl) = rtimer%delapsedReal
! Start time measurement
call stat_clearTimer(rtimer)
call stat_startTimer(rtimer,STAT_TIMERSHORT)
! Set up the solver
select case(isolver)
case (0)
! UMFPACK solver
call linsol_initUMFPACK4(p_rsolver)
case (1)
! CG-SSOR[1.2] solver
nullify(p_rprecond)
call linsol_initSSOR(p_rprecond,drelax)
call linsol_initCG(p_rsolver, p_rprecond)
case (2)
! BiCGStab-ILU(k) solver with RCMK
nullify(p_rprecond)
call linsol_initMILUs1x1(p_rprecond,ifillin,0.0_DP)
call linsol_initBiCGStab(p_rsolver, p_rprecond)
! Calculate a RCMK permutation
call sstrat_initBlockSorting (rsortStrategy,rdiscretisation)
call sstrat_initRevCuthillMcKee(rsortStrategy%p_Rstrategies(1),rmatrix%RmatrixBlock(1,1))
! Attach the sorting strategy
call lsysbl_setSortStrategy (rmatrix,rsortStrategy,rsortStrategy)
call lsysbl_setSortStrategy (rvecSol,rsortStrategy)
call lsysbl_setSortStrategy (rvecRhs,rsortStrategy)
! Permute matrix and vectors
call lsysbl_sortMatrix(rmatrix,.true.)
call lsysbl_sortVector(rvecSol,.true., rvecTmp%RvectorBlock(1))
call lsysbl_sortVector(rvecRhs,.true., rvecTmp%RvectorBlock(1))
end select
p_rsolver%ioutputLevel = ioutput
p_rsolver%depsRel = depsRel
p_rsolver%depsAbs = depsAbs
p_rsolver%nmaxiterations = nmaxiter
Rmatrices = (/rmatrix/)
call linsol_setMatrices(p_rsolver,Rmatrices)
call linsol_initStructure (p_rsolver, ierror)
if (ierror .ne. LINSOL_ERR_NOERROR) stop
call linsol_initData (p_rsolver, ierror)
if (ierror .ne. LINSOL_ERR_NOERROR) stop
! Solve the system
call linsol_solveAdaptively (p_rsolver,rvecSol,rvecRhs,rvecTmp)
! If necessary, unsort the solution vector
call lsyssc_sortVector (rvecSol%RvectorBlock(1), .false., rvecTmp%RvectorBlock(1))
! Stop time measurement
call stat_stopTimer(rtimer)
Dtimer(4,ilvl) = rtimer%delapsedReal
! Start time measurement
call stat_clearTimer(rtimer)
call stat_startTimer(rtimer,STAT_TIMERSHORT)
! Calculate the errors to the reference function
rerror%p_RvecCoeff => rvecSol%RvectorBlock(1:1)
rerror%p_DerrorL2 => Derror(1:1,ilvl)
rerror%p_DerrorH1 => Derror(2:2,ilvl)
call pperr_scalarVec(rerror, getReferenceFunction2D, rcollect, rcubatureInfo)
! Print the errors
call output_line('Errors (L2/H1): ' // &
trim(sys_sdEP(Derror(1,ilvl),20,12)) // &
trim(sys_sdEP(Derror(2,ilvl),20,12)))
! Do we perform UCD output?
if (iucd .gt. 0) then
! What type of output?
select case(iucd)
case (1)
call ucd_startGMV (rexport,UCD_FLAG_STANDARD,rtriangulation,&
trim(sucddir) // '/sol2d_' // trim(sys_siL(ilvl,5)) // '.gmv')
case (2)
call ucd_startVTK (rexport,UCD_FLAG_STANDARD,rtriangulation,&
trim(sucddir) // '/sol2d_' // trim(sys_siL(ilvl,5)) // '.vtk')
end select
! Project the solution to the vertices
call ucd_addVectorByVertex (rexport,'sol',UCD_VAR_STANDARD, rvecSol%RvectorBlock(1))
! Write and release ucd
call ucd_write (rexport)
call ucd_release (rexport)
end if
! Stop time measurement
call stat_stopTimer(rtimer)
Dtimer(5,ilvl) = rtimer%delapsedReal
! Clean up this level
call linsol_doneData (p_rsolver)
call linsol_doneStructure (p_rsolver)
call linsol_releaseSolver (p_rsolver)
call lsysbl_releaseVector (rvecTmp)
call lsysbl_releaseVector (rvecSol)
call lsysbl_releaseVector (rvecRhs)
call lsysbl_releaseMatrix (rmatrix)
call sstrat_doneBlockSorting (rsortStrategy)
call bcasm_releaseDiscreteBC (rdiscreteBC)
call spdiscr_releaseBlockDiscr(rdiscretisation)
call tria_done (rtriangulation)
end do ! ilvl
! Release the domain
call boundary_release (rboundary)
! Print some statistics
call output_separator(OU_SEP_MINUS)
call output_line('Level NEQ NNZE NVT' // &
' NMT NEL')
do ilvl = NLMIN, NLMAX
call output_line(trim(sys_si(ilvl,5)) // &
trim(sys_si(Istat(1,ilvl),12)) // &
trim(sys_si(Istat(2,ilvl),12)) // &
trim(sys_si(Istat(3,ilvl),12)) // &
trim(sys_si(Istat(4,ilvl),12)) // &
trim(sys_si(Istat(5,ilvl),12)))
end do ! ilvl
! Print out the L2- and H1-errors on each level
call output_separator(OU_SEP_MINUS)
call output_line('Level L2-error H1-error')
do ilvl = NLMIN, NLMAX
call output_line(trim(sys_si(ilvl,5)) // ' ' // &
trim(sys_sdEP(Derror(1,ilvl),20,12)) // &
trim(sys_sdEP(Derror(2,ilvl),20,12)))
end do ! ilvl
! Print out the L2- and H1- factors for each level pair
if(NLMAX .gt. NLMIN) then
call output_separator(OU_SEP_MINUS)
call output_line('Level L2-factor H1-factor')
do ilvl = NLMIN+1, NLMAX
! avoid division by zero here
daux1 = 0.0_DP
daux2 = 0.0_DP
if(abs(Derror(1,ilvl)) .gt. SYS_EPSREAL_DP) &
daux1 = Derror(1,ilvl-1)/Derror(1,ilvl)
if(abs(Derror(2,ilvl)) .gt. SYS_EPSREAL_DP) &
daux2 = Derror(2,ilvl-1)/Derror(2,ilvl)
! print out the factors
call output_line(trim(sys_si(ilvl,5)) // ' ' // &
trim(sys_sdEP(daux1,20,12)) // &
trim(sys_sdEP(daux2,20,12)))
end do ! ilvl
end if
#ifdef USE_TIMER
! Print out the time measurements for each level
call output_separator(OU_SEP_MINUS)
call output_line('Level CPU_Tria CPU_Discr CPU_Assem' // &
' CPU_Solve CPU_Post')
do ilvl = NLMIN, NLMAX
call output_line(trim(sys_si(ilvl,5)) // &
trim(sys_sdEP(Dtimer(1,ilvl),12,4)) // &
trim(sys_sdEP(Dtimer(2,ilvl),12,4)) // &
trim(sys_sdEP(Dtimer(3,ilvl),12,4)) // &
trim(sys_sdEP(Dtimer(4,ilvl),12,4)) // &
trim(sys_sdEP(Dtimer(5,ilvl),12,4)))
end do ! ilvl
! Print out the timing factors for each level pair
if(NLMAX .gt. NLMIN) then
call output_separator(OU_SEP_MINUS)
call output_line('Level Tria-fact Discr-fact Assem-fact' // &
' Solve-fact Post-fact')
do ilvl = NLMIN+1, NLMAX
! avoid division by zero here
daux1 = 0.0_DP
daux2 = 0.0_DP
daux3 = 0.0_DP
daux4 = 0.0_DP
daux5 = 0.0_DP
if(abs(Dtimer(1,ilvl-1)) .gt. SYS_EPSREAL_DP) &
daux1 = Dtimer(1,ilvl)/Dtimer(1,ilvl-1)
if(abs(Dtimer(2,ilvl-1)) .gt. SYS_EPSREAL_DP) &
daux2 = Dtimer(2,ilvl)/Dtimer(2,ilvl-1)
if(abs(Dtimer(3,ilvl-1)) .gt. SYS_EPSREAL_DP) &
daux3 = Dtimer(3,ilvl)/Dtimer(3,ilvl-1)
if(abs(Dtimer(4,ilvl-1)) .gt. SYS_EPSREAL_DP) &
daux4 = Dtimer(4,ilvl)/Dtimer(4,ilvl-1)
if(abs(Dtimer(5,ilvl-1)) .gt. SYS_EPSREAL_DP) &
daux5 = Dtimer(5,ilvl)/Dtimer(5,ilvl-1)
! print out the factors
call output_line(trim(sys_si(ilvl,5)) // &
trim(sys_sdEP(daux1,12,4)) // &
trim(sys_sdEP(daux2,12,4)) // &
trim(sys_sdEP(daux3,12,4)) // &
trim(sys_sdEP(daux4,12,4)) // &
trim(sys_sdEP(daux5,12,4)))
end do ! ilvl
end if
#endif
! Deallocate arrays
deallocate(Istat)
deallocate(Dtimer)
deallocate(Derror)
end subroutine
end module
|
Daniel says “I am an artist who loves books. I enjoy sculpting and repurposing discarded books. My work has been acquired by many collectors from around the world and has been published in many different newspapers, magazines and books.
Daniel Lai, a self-taught artist of Chinese descent from Kuala Lumpur, Malaysia, was granted US citizenship through extraordinary ability in the field of fine art and arts management in 2014.
His educational background reflects a diversity of interests that influences his work. Daniel has a PhD in sociology (2015) from University of Tennessee, an MA in art history (2006) from Montclair State University, and a BA in linguistics (2003) from Montclair State University. |
Require Export Arith.EqNat.
Require Export Arith.Lt.
Require Export Arith.Compare_dec.
Require Export List.
Require Import String.
Require Import TacticsSF.
Require Import TacticsCPDT.
Require Export Process.
Require Import Bool.
(* ============================================================================= *)
Inductive type : Set :=
| TChannel : session -> type
| TSingleton : token -> type
with message : Set :=
| MInp : type -> message
| MOut : type -> message
with session : Set :=
(* general purpose *)
| SEpsilon : session
| SPrefix : message -> session -> session
| SUnion : session -> session -> session
| SSeq : session -> session -> session
| SRep : session -> session
| SDual : session -> session
(* sink *)
| SSink : session
(* uni-forwarder *)
| SFwd : session -> session
| SInOut : session
| SInOut1 : session -> session
(* abp *)
| SToks : session -> session
| SNack : session -> token -> session -> token -> session
| SNack1 : session -> token -> session -> token -> session
| SAck : session -> token -> session
| SAck1 : session -> token -> session
| SAck2 : session -> token -> session
(* abp_send *)
| SSend : bool -> session (* a fresh channel for passing args *)
(* a channel for passing args where the token has been passed *)
| SSend1 : bool -> session -> session -> session
(* a channel for passing args where the token and "inp" channel has been
passed, and "err1" is next *)
| SSend2 : bool -> session -> session
(* abp_recv *)
| SRecv : bool -> session (* a fresh channel for passing args *)
(* a channel for passing args where err2 has been passed.
need bool to bind i, 1st session for s, and 2nd session for t *)
| SRecv1 : bool -> session -> session -> session
(* abp_lossy *)
| SLossy : session (* a fresh channel for passing args *)
(* a channel for passing args where err1 has been passed.
need to bind s and t: 1st param is s, 2nd is t *)
| SLossy1 : session -> session -> session
.
Inductive terminates : session -> Prop :=
| TMEpsilon : terminates SEpsilon
| TMUnion1 : forall s1 s2, terminates s1 -> terminates (SUnion s1 s2)
| TMUnion2 : forall s1 s2, terminates s2 -> terminates (SUnion s1 s2)
| TMSeq : forall s1 s2, terminates s1 -> terminates s2 -> terminates (SSeq s1 s2)
| TMRep : forall s, terminates s -> terminates (SRep s)
| TMDual : forall s, terminates s -> terminates (SDual s).
Definition m_dual (m:message) : message :=
match m with
| MInp a => MOut a
| MOut a => MInp a
end.
(* ============================================================================= *)
Require Import String.
Definition string_of_bool (b:bool) := if b then "true"%string else "false"%string.
Definition bool_of_string (s:string) :=
match s with
| "false"%string => false
| _ => true
end.
Definition string_of_negb_string (s:string) :=
string_of_bool (negb (bool_of_string s)).
Definition token_of_negb_token (tok:token) :=
match tok with
| Token s => Token (string_of_negb_string s)
end.
Definition token_of_bool (b : bool) := Token (string_of_bool b).
Reserved Notation "s -- m --> t" (no associativity, at level 90).
Inductive transition : session -> message -> session -> Prop :=
(* general purpose *)
| TRPrefix : forall s m, (SPrefix m s) --m--> s
| TRUnion1 : forall s1 s2 t1 m, s1 --m--> t1 -> (SUnion s1 s2) --m--> t1
| TRUnion2 : forall s1 s2 t2 m, s2 --m--> t2 -> (SUnion s1 s2) --m--> t2
| TRSeq1 : forall s1 s2 t1 m, s1 --m--> t1 -> (SSeq s1 s2) --m--> (SSeq t1 s2)
| TRSeq2 : forall s1 s2 t2 m, terminates s1 -> s2 --m--> t2 -> (SSeq s1 s2) --m--> t2
| TRRep : forall s t m, s --m--> t -> (SRep s) --m--> (SSeq t (SRep s))
| TRDual : forall s t m, s --m--> t -> (SDual s) --(m_dual m)--> (SDual t)
(* sink *)
| TRSink : forall s, SSink --(MInp (TChannel s))--> SSink
(* uni-forwarder *)
| TRFwd : forall s, SFwd s --(MInp (TChannel s))--> SFwd s
| TRInOut : forall s, SInOut --(MInp (TChannel s))--> SInOut1 s
| TRInOut1 : forall s, SInOut1 s --(MInp (TChannel (SDual s)))--> SEpsilon
(* abp *)
| TRToks : forall s s' tok, s --(MInp (TSingleton tok))--> s' ->
SToks s --(MInp (TSingleton tok))--> SToks s'
| TRAckA : forall s bit, SAck s bit --(MOut (TSingleton bit))--> SAck1 s bit
| TRAck1A : forall s bit tok,
SAck1 s bit --(MOut (TSingleton tok))--> SAck s bit
| TRAckB : forall s bit, SAck s bit --(MInp (TSingleton bit))--> SAck s bit
| TRAckC : forall s tok s' bit, s --(MInp (TSingleton tok))--> s' ->
SAck s bit --(MOut (TSingleton (token_of_negb_token bit)))--> SAck2 s bit
| TRAck2A : forall s tok s' bit, s --(MInp (TSingleton tok))--> s' ->
SAck2 s bit --(MOut (TSingleton tok))-->
SNack s tok s' (token_of_negb_token bit)
| TRNackA : forall s tok s' bit, s --(MInp (TSingleton tok))--> s'
-> SNack s tok s' bit --(MOut (TSingleton bit))--> SNack1 s tok s' bit
| TRNack1A : forall s tok s' bit, s --(MInp (TSingleton tok))--> s'
-> SNack1 s tok s' bit --(MOut (TSingleton tok))--> SNack s tok s' bit
| TRNackB : forall s tok s' bit, SNack s tok s' bit
--(MInp (TSingleton (token_of_negb_token bit)))--> SNack s tok s' bit
| TRNackC : forall s tok s' bit, SNack s tok s' bit
--(MInp (TSingleton bit))--> SAck s' bit
(* abp_send *)
| TRSendA : forall i k r r', r --(MInp (TSingleton k))--> r' ->
SSend i --(MInp (TSingleton k))-->
SSend1 i r' (SNack r k r' (token_of_bool i))
| TRSendB : forall i k r r', r --(MInp (TSingleton k))--> r' ->
SSend i --(MInp (TSingleton k))-->
SSend1 i r' (SAck r (token_of_bool (negb i)))
| TRSend1A : forall i r' s, SSend1 i r' s --(MInp (TChannel (SToks r')))-->
SSend2 i s
| TRSend2A : forall i s, SSend2 i s --(MInp (TChannel s))--> SEpsilon
(* abp_recv *)
| TRRecvA : forall i k r s t, s = (SNack r k t (token_of_bool (negb i))) ->
SRecv i --(MInp (TChannel (SDual s)))--> SRecv1 i s t
| TRRecvB : forall i s t, s = (SAck t (token_of_bool (negb i))) ->
SRecv i --(MInp (TChannel (SDual s)))--> SRecv1 i s t
| TRRecv1A : forall i s t,
SRecv1 i s t --(MInp (TChannel (SDual (SToks (t)))))--> SEpsilon
(* abp_lossy *)
| TRLossyA : forall i r s t, s = (SAck r (token_of_bool i)) ->
t = (SAck r (token_of_bool i)) ->
SLossy --(MInp (TChannel (SDual s)))--> SLossy1 s t
| TRLossyB : forall i r k r' s t, s = (SNack r k r' (token_of_bool i)) ->
t = (SNack r k r' (token_of_bool i)) ->
SLossy --(MInp (TChannel (SDual s)))--> SLossy1 s t
| TRLossyC : forall i r k r' s t, s = (SNack r k r' (token_of_bool (negb i))) ->
t = (SAck r (token_of_bool i)) ->
SLossy --(MInp (TChannel (SDual s)))--> SLossy1 s t
| TRLossyD : forall i r k r' s t, s = (SNack r k r' (token_of_bool i)) ->
t = (SAck r' (token_of_bool i)) ->
SLossy --(MInp (TChannel (SDual s)))--> SLossy1 s t
| TRLossy1A : forall s t,
SLossy1 s t --(MInp (TChannel t))--> SEpsilon
where "s -- m --> t" := (transition s m t).
(* ============================================================================= *)
Scheme
message_session_type_rec := Induction for message Sort Set
with session_message_type_rec := Induction for session Sort Set
with type_session_message_rec := Induction for type Sort Set.
Lemma type_dec : forall x y : type, {x = y} + {~ (x = y)}.
Proof.
Ltac destruct_top_level :=
repeat
match goal with
| [ |- forall x : _ , ( { _ } + { _ } ) ] =>
let i := fresh "i" in intro i; destruct i
| [ |- forall x : _ , _ ] => intro
end.
Ltac decide_arg_eq_aux E F :=
match E with
| F => left; reflexivity
| ?P ?X =>
match F with
| ?Q ?Y =>
cut ({X = Y} + {X <> Y});
[| apply token_dec || apply bool_dec || intuition];
let i := fresh "i" in let n := fresh "n" in intro i; destruct i as [?|n]; [subst; auto | right; contradict n; injection n; intros; subst; reflexivity];
decide_arg_eq_aux P Q
end
| _ => right; crush
end.
Ltac decide_arg_eq :=
match goal with
| [ |- { ?P = ?Q } + { _ } ] => decide_arg_eq_aux P Q
end.
intros x.
eapply type_session_message_rec
with
(P := fun m1:message => forall m2:message, {m1=m2} + {m1<>m2} )
(P0 := fun s1:session => forall s2:session, {s1=s2} + {s1<>s2} )
(P1 := fun rho1:type => forall rho2:type, {rho1=rho2} + {rho1<>rho2} ); clear x;
destruct_top_level;
decide_arg_eq.
Qed.
(* ============================================================================= *)
Lemma m_dual_is_dual :
forall m, m_dual (m_dual m) = m.
Proof.
destruct m; intuition.
Qed.
(* ============================================================================= *)
Reserved Notation "|-st rho" (no associativity, at level 90).
Inductive stateless : type -> Prop :=
| STChannel : forall s, (forall m t, s --m--> t -> s = t) -> stateless (TChannel s)
| STToken : forall k, stateless (TSingleton k)
where "|-st rho" := (stateless rho).
(* ============================================================================= *)
Definition session_always (s1 s2 : session) : Prop :=
forall m t, s1 --m--> t -> t = s2.
(* ============================================================================= *)
Definition ctx_elt : Set := (prod value type).
Require Import MSets.MSetWeakList.
Require Import MSets.MSetProperties.
Require Import Structures.Equalities.
Require Import MSets.MSetInterface.
Module ctx_elt_as_DT <: DecidableType.
Definition t : Type := ctx_elt.
Definition eq : t -> t -> Prop := @eq t.
Lemma eq_dec : forall a b : ctx_elt, {a = b} + {a <> b}.
Proof.
decide equality.
destruct (type_dec b0 t0); [rewrite <- e; clear e|]; intuition.
Qed.
Definition eq_equiv : Equivalence eq := @eq_equivalence ctx_elt.
End ctx_elt_as_DT.
(* Removed for Coq 8.3: "with Module E := ctx_elt_as_DT" *)
Module CTX : WSets with Module E := ctx_elt_as_DT :=
MSetWeakList.Make ctx_elt_as_DT.
Module CTXFacts := MSets.MSetFacts.WFacts CTX.
Module CTXProperties := MSets.MSetProperties.WProperties CTX.
Definition ctx := CTX.t.
Definition ctx_replace (u : value) (old new : type) (G : ctx) : ctx :=
CTX.add (u, new) (CTX.remove (u, old) G).
(* ============================================================================= *)
Inductive fresh_for_ctx : value -> ctx -> Prop :=
| FContext :
forall u G,
free_value u
->
(forall v sigma, ~ CTX.In (v, sigma) G \/ ~ free_ids_value u = free_ids_value v)
->
fresh_for_ctx u G
| FToken : forall (k : token) G, fresh_for_ctx k G.
(* ============================================================================= *)
Definition free_values_in_context (G : ctx) (P : proc) : Prop :=
forall u, In u (free_values_proc P) -> exists sigma, CTX.In (u, sigma) G.
(* ============================================================================= *)
Reserved Notation "G |-wf" (no associativity, at level 90).
Inductive wellformed_ctx : ctx -> Prop :=
| WFCtx :
forall G,
(forall u rho, CTX.In (u, rho) G -> free_value u)
->
(forall u rho sigma, CTX.In (u, rho) G -> CTX.In (u, sigma) G -> rho = sigma)
->
(forall x,
(forall rho, ~ CTX.In (ValVariable (Var (Free x)), rho) G) \/
((forall rho, ~ CTX.In (ValName (Nm (Free x)), rho) G) /\
(forall rho, ~ CTX.In (ValName (CoNm (Free x)), rho) G)))
->
G |-wf
where "G |-wf" := (wellformed_ctx G).
(* ============================================================================= *)
Inductive partition : ctx -> ctx -> ctx -> Prop :=
| Partition : forall G GL GR,
(CTX.eq G (CTX.union GL GR))
->
G |-wf
->
(forall u rho, (~ CTX.In (u, rho) GL) \/ (~ CTX.In (u, rho) GR) \/ ( |-st rho ))
->
partition G GL GR.
Notation "G |-part GL (+) GR" := (partition G GL GR) (no associativity, at level 90).
(* ============================================================================= *)
Reserved Notation "G |-v u : rho" (no associativity, at level 90, u at next level).
(* lookup_value only finds values with Free in them, not Bound. *)
Inductive lookup_value : ctx -> value -> type -> Prop :=
| LContext : forall u rho G, G |-wf -> (CTX.In (u, rho) G) -> G |-v u : rho
| LToken : forall (k : token) G, G |-wf -> G |-v k : (TSingleton k)
where "G |-v u : rho" := (lookup_value G u rho).
(* ============================================================================= *)
Lemma wellformed_lookup_is_free :
forall G u rho,
(G |-wf) -> (G |-v u : rho) ->
((free_value u) \/ (exists k:token, u = k)).
Proof.
intros G u rho Hwf Hlu_u.
inversion Hlu_u; [left; subst | right; exists k; intuition].
inversion Hwf; subst.
eapply H1; eauto.
Qed.
(* ============================================================================= *)
Lemma prod_eq_elim_fst :
forall A B (x1 x2 : A) (y1 y2:B), (x1, y1) = (x2, y2) -> x1 = x2.
Proof.
intros.
replace x1 with (fst (x1, y1)); intuition.
replace x2 with (fst (x2, y2)); intuition.
rewrite <- H; auto.
Qed.
Lemma prod_eq_elim_snd :
forall A B (x1 x2 : A) (y1 y2:B), (x1, y1) = (x2, y2) -> y1 = y2.
Proof.
intros.
replace y1 with (snd (x1, y1)); intuition.
replace y2 with (snd (x2, y2)); intuition.
rewrite <- H; auto.
Qed.
(* ============================================================================= *)
Lemma list_add_4 :
forall a1 a2 G, CTX.In a1 (CTX.add a2 G) -> ~ CTX.In a1 G -> a1 = a2.
Proof.
intros.
destruct (CTX.E.eq_dec a1 a2); subst; auto.
contradict H0.
eapply CTXFacts.add_3; eauto.
Qed.
(* ============================================================================= *)
Reserved Notation "G |-p P" (no associativity, at level 90).
Inductive typed : ctx -> proc -> Prop :=
| TypPrefixInput :
forall G u P s L,
(G |-v u : TChannel s)
->
(* The following condition controls free_values when there are no transitions from s. *)
free_values_in_context G P
->
(forall G' rho t x,
~ (In x L)
->
(transition s (MInp rho) t)
->
G' = (CTX.add (ValVariable (Var (Free x)), rho)
(ctx_replace u (TChannel s) (TChannel t)
G))
->
(G' |-p (open_proc x 0 P)))
->
(G |-p (u ? ; P))
| TypPrefixOutput :
forall G G' G'' u v P s rho t,
(transition s (MOut rho) t)
->
(u <> v \/ |-st rho)
->
(G |-v u : TChannel s)
->
(G |-v v : rho)
->
(G' = CTX.remove (v, rho) G \/ (G' = G /\ |-st rho))
->
G'' = ctx_replace u (TChannel s) (TChannel t) G'
->
G'' |-p P
->
G |-p (u ! v ; P)
| TypPar :
forall G GL GR P Q,
G |-part GL (+) GR
->
GL |-p P
->
GR |-p Q
->
G |-p (P ||| Q)
| TypSum : forall G P Q, G |-p P -> G |-p Q -> G |-p P +++ Q
| TypIsEq :
forall G P u v K L,
G |-v u : TSingleton K
->
G |-v v : TSingleton L
->
free_values_in_context G P
->
(K = L -> G |-p P)
->
G |-p (IsEq u v P)
| TypIsNotEq :
forall G P u v K L,
G |-v u : TSingleton K
->
G |-v v : TSingleton L
->
free_values_in_context G P
->
(K <> L -> G |-p P)
->
G |-p (IsNotEq u v P)
| TypNew :
forall G P s L,
(forall x G',
~ (In x L)
->
G' = (CTX.add (ValName (Nm (Free x)), TChannel s)
(CTX.add (ValName (CoNm (Free x)), TChannel (SDual s))
G))
->
G' |-p open_proc x 0 P)
->
G |-p (New P)
| TypRep :
forall G G' P,
G |-wf
->
CTX.Subset G' G
->
(forall u rho, CTX.In (u, rho) G' -> |-st rho)
->
G' |-p P
->
G |-p (Rep P)
| TypZero : forall G, G |-wf -> G |-p Zero
where "G |-p P" := (typed G P).
(* ============================================================================= *)
Inductive dual_types : type -> type -> Prop :=
| DTLeft : forall s, dual_types (TChannel s) (TChannel (SDual s))
| DTRight : forall s, dual_types (TChannel (SDual s)) (TChannel s).
Inductive dual_types_transition : type -> type -> message -> type -> type -> Prop :=
| DTTLeft : forall s m t, (transition s m t) -> dual_types_transition (TChannel s) (TChannel (SDual s)) m (TChannel t) (TChannel (SDual t))
| DTTRight : forall s m t, (transition s (m_dual m) t) -> dual_types_transition (TChannel (SDual s)) (TChannel s) m (TChannel (SDual t)) (TChannel t).
Definition ctx_matched_names (G1 : CTX.t) : Prop :=
forall nm1 nm2 rho sigma,
dual_name nm1 = nm2
->
CTX.In (ValName nm1, rho) G1
->
CTX.In (ValName nm2, sigma) G1
->
dual_types rho sigma.
Inductive is_free_name : value -> Prop :=
| ISNm : forall i, is_free_name (ValName (Nm (Free i)))
| ISCoNm : forall i, is_free_name (ValName (CoNm (Free i))).
Definition all_free_names (G1 : CTX.t) : Prop :=
forall u rho, CTX.In (u, rho) G1 -> is_free_name u.
Definition names_channel_types (G1 : CTX.t) : Prop :=
forall v rho, CTX.In (v, rho) G1 -> exists s, rho = TChannel s.
Definition balanced (G1 : CTX.t) : Prop :=
ctx_matched_names G1
/\
all_free_names G1
/\
names_channel_types G1.
(* ============================================================================= *)
Definition mk_vis_value_type (a : type) : vis_value :=
match a with
| TChannel s => VVChan
| TSingleton k => VVToken k
end.
Inductive mk_obs_msg : name -> message -> obs -> Prop :=
| MVOMNmInp : forall f a, mk_obs_msg (Nm (Free f)) (MInp a) (VOInteract VDInp f (mk_vis_value_type a))
| MVOMNmOut : forall f a, mk_obs_msg (Nm (Free f)) (MOut a) (VOInteract VDOut f (mk_vis_value_type a))
| MVOMCoNmInp : forall f a, mk_obs_msg (CoNm (Free f)) (MOut a) (VOInteract VDInp f (mk_vis_value_type a))
| MVOMCoNmOut : forall f a, mk_obs_msg (CoNm (Free f)) (MInp a) (VOInteract VDOut f (mk_vis_value_type a)).
(* ============================================================================= *)
Inductive ctx_preservation : CTX.t -> CTX.t -> obs -> Prop :=
| CPNoInteraction :
forall G1 G2,
CTX.eq
G2
G1
->
ctx_preservation G1 G2 VONone
| CPInteraction :
forall G1 G2 nm1 nm2 s m t vv,
dual_name nm1 = nm2
->
CTX.In (ValName nm1, TChannel s) G1
->
CTX.In (ValName nm2, TChannel (SDual s)) G1
->
(transition s m t)
->
CTX.eq
G2
(ctx_replace (ValName nm1) (TChannel s) (TChannel t)
((ctx_replace (ValName nm2) (TChannel (SDual s)) (TChannel (SDual t)) G1)))
->
mk_obs_msg nm1 m vv
->
ctx_preservation G1 G2 vv.
(* ============================================================================= *)
Definition message_type (m : message) : type :=
match m with
| MInp a => a
| MOut a => a
end.
Inductive obs_msg_match : obs -> message -> vis_dir -> Prop :=
| VIMMInpInp : forall f vv s, obs_msg_match (VOInteract VDInp f vv) (MInp s) VDInp
| VIMMInpOut : forall f vv s, obs_msg_match (VOInteract VDInp f vv) (MOut s) VDOut
| VIMMOutInp : forall f vv s, obs_msg_match (VOInteract VDOut f vv) (MOut s) VDInp
| VIMMOutOut : forall f vv s, obs_msg_match (VOInteract VDOut f vv) (MInp s) VDOut.
(* The first session type in dual_types_transition2 is the one on which input is occurring. *)
Inductive dual_types_transition2 : type -> type -> type -> type -> type -> Prop :=
| DTT2Left : forall s a t, (transition s (MInp a) t) -> dual_types_transition2 (TChannel s) (TChannel (SDual s)) a (TChannel t) (TChannel (SDual t))
| DTT2Right : forall s a t, (transition s (MOut a) t) -> dual_types_transition2 (TChannel (SDual s)) (TChannel s) a (TChannel (SDual t)) (TChannel t).
(* ============================================================================= *)
Inductive traces : free_id -> list obs -> session -> Prop :=
| TRCNil : forall f s, traces f nil s
| TRCCons : forall f vo vos s m t, (transition s m t) -> mk_obs_msg (Nm (Free f)) m vo -> traces f vos t -> traces f (vo :: vos) s.
Definition project (f : free_id) (vos : list obs) : list obs := filter (is_obs_free_id f) vos.
|
lemma higher_deriv_uminus: assumes "f holomorphic_on S" "open S" and z: "z \<in> S" shows "(deriv ^^ n) (\<lambda>w. -(f w)) z = - ((deriv ^^ n) f z)" |
theory week02B_demo imports Main begin
section{* Propositional logic *}
subsection{* Basic rules *}
text{* \<and> *}
thm conjI
thm conjunct2
thm conjE
text{* \<or> *}
thm disjI1
thm disjI2
thm disjE
text{* \<longrightarrow> *}
thm impI impE
subsection{* Examples *}
text{* a simple backward step: *}
lemma "A \<and> B" thm conjI
apply(rule conjI)
oops
text{* a simple backward proof: *}
lemma "B \<and> A \<longrightarrow> A \<and> B"
(*TODO*)
apply(rule impI)
apply(rule conjI)
apply(erule conjE)
apply assumption
apply(erule conjE)
apply assumption
done
lemma "(A \<or> B) \<longrightarrow> (B \<or> A)"
(*TODO*)
apply(rule impI)
apply(erule disjE)
apply(rule disjI2)
apply assumption
apply(rule disjI1)
apply assumption
done
lemma "\<lbrakk> B \<longrightarrow> C; A \<longrightarrow> B \<rbrakk> \<Longrightarrow> A \<longrightarrow> C"
sorry
thm notI notE
lemma "\<not>A \<or> \<not>B \<Longrightarrow> \<not>(A \<and> B)"
(*TODO*)
apply(erule disjE)
apply(rule notI)
apply(erule notE)
apply(erule conjE)
apply assumption
apply(rule notI)
apply(erule notE)
apply(erule conjE)
apply assumption
done
text {* Case distinctions *}
lemma "P \<or> \<not>P"
apply (case_tac "P")
oops
thm FalseE
lemma "(\<not>P \<longrightarrow> False) \<longrightarrow> P"
oops
text{* Explicit backtracking: *}
lemma "\<lbrakk> P \<and> Q; A \<and> B \<rbrakk> \<Longrightarrow> A"
apply(erule conjE)
back
apply(assumption)
done
text {* UGLY! EVIL! AVOID! *}
text{* Implicit backtracking: chaining with , *}
lemma "\<lbrakk> P \<and> Q; A \<and> B \<rbrakk> \<Longrightarrow> A"
apply (erule conjE, assumption)
done
text{* OR: use rule_tac or erule_tac to instantiate the schematic variables of the rule *}
lemma "\<lbrakk> P \<and> Q; A \<and> B \<rbrakk> \<Longrightarrow> A"
apply (erule_tac P=A and Q=B in conjE)
apply assumption
done
text {* more rules *}
text{* \<and> *}
thm conjunct1 conjunct2
text{* \<or> *}
thm disjCI
lemma our_own_disjCI: "(\<not>Q \<longrightarrow> P) \<Longrightarrow> P \<or> Q"
(*TODO (with case_tac) *)
apply(case_tac Q)
apply(rule disjI2)
apply assumption
apply(rule disjI1)
apply(erule impE)
apply assumption
apply assumption
done
text{* \<longrightarrow> *}
thm mp
text{* = (iff) *}
thm iffI iffE iffD1 iffD2
text{* Equality *}
thm refl sym trans
text{* \<not> *}
thm notI notE
text{* Contradictions *}
thm FalseE ccontr classical excluded_middle
-- {* more rules *}
text {* defer and prefer *}
lemma "(A \<or> A) = (A \<and> A)"
apply (rule iffI)
prefer 2
defer
sorry
text{* classical propositional logic: *}
lemma Pierce: "((A \<longrightarrow> B) \<longrightarrow> A) \<longrightarrow> A"
apply (rule impI)
apply (rule classical)
apply (erule impE)
apply (rule impI)
apply (erule notE)
apply assumption
apply assumption
done
text {* Exercises *}
lemma "A \<and> B \<longrightarrow> A \<longrightarrow> B"
oops
lemma "A \<longrightarrow> (B \<or> C) \<longrightarrow> (\<not> A \<or> \<not> B) \<longrightarrow> C"
oops
lemma"((A \<longrightarrow> B) \<and> (B \<longrightarrow> A)) = (A = B)"
oops
lemma "(A \<longrightarrow> (B \<and> C)) \<longrightarrow> (A \<longrightarrow> C)"
oops
end |
(**
Author: Peter Lammich
Inspired by Rene Neumann's DFS-Framework and Nested DFS formalization
**)
section \<open>Nested DFS using Standard Invariants Approach\<close>
theory NDFS_SI
imports
CAVA_Automata.Automata_Impl
CAVA_Automata.Lasso
NDFS_SI_Statistics
CAVA_Base.CAVA_Code_Target
begin
text \<open>
Implementation of a nested DFS algorithm for accepting cycle detection
using the refinement framework. The algorithm uses the improvement of
Holzmann et al.~\cite{HPY97}, i.e., it reports a cycle if the inner
DFS finds a path back to
the stack of the outer DFS. Moreover, an early cycle detection optimization is
implemented~\cite{SE05}, i.e., the outer DFS may already report a cycle on
a back-edge involving an accepting node.
The algorithm returns a witness in case that an accepting cycle is detected.
The design approach to this algorithm is to first establish invariants of a
generic DFS-Algorithm, which are then used to instantiate the concrete
nested DFS-algorithm for B\"uchi emptiness check. This formalization can be
seen as a predecessor of the formalization of
Gabow's algorithm~\cite{La14_ITP}, where this technique has been
further developed.
\<close>
subsection "Tools for DFS Algorithms"
subsubsection "Invariants"
definition "gen_dfs_pre E U S V u0 \<equiv>
E``U \<subseteq> U \<comment> \<open>Upper bound is closed under transitions\<close>
\<and> finite U \<comment> \<open>Upper bound is finite\<close>
\<and> V \<subseteq> U \<comment> \<open>Visited set below upper bound\<close>
\<and> u0 \<in> U \<comment> \<open>Start node in upper bound\<close>
\<and> E``(V-S) \<subseteq> V \<comment> \<open>Visited nodes closed under reachability, or on stack\<close>
\<and> u0\<notin>V \<comment> \<open>Start node not yet visited\<close>
\<and> S \<subseteq> V \<comment> \<open>Stack is visited\<close>
\<and> (\<forall>v\<in>S. (v,u0)\<in>(E\<inter>S\<times>UNIV)\<^sup>*) \<comment> \<open>\<open>u0\<close> reachable from stack, only over stack\<close>
"
definition "gen_dfs_var U \<equiv> finite_psupset U"
definition "gen_dfs_fe_inv E U S V0 u0 it V brk \<equiv>
(\<not>brk \<longrightarrow> E``(V-S) \<subseteq> V) \<comment> \<open>Visited set closed under reachability\<close>
\<and> E``{u0} - it \<subseteq> V \<comment> \<open>Successors of \<open>u0\<close> visited\<close>
\<and> V0 \<subseteq> V \<comment> \<open>Visited set increasing\<close>
\<and> V \<subseteq> V0 \<union> (E - UNIV\<times>S)\<^sup>* `` (E``{u0} - it - S) \<comment> \<open>All visited nodes reachable\<close>
"
definition "gen_dfs_post E U S V0 u0 V brk \<equiv>
(\<not>brk \<longrightarrow> E``(V-S) \<subseteq> V) \<comment> \<open>Visited set closed under reachability\<close>
\<and> u0 \<in> V \<comment> \<open>\<open>u0\<close> visited\<close>
\<and> V0 \<subseteq> V \<comment> \<open>Visited set increasing\<close>
\<and> V \<subseteq> V0 \<union> (E - UNIV\<times>S)\<^sup>* `` {u0} \<comment> \<open>All visited nodes reachable\<close>
"
definition "gen_dfs_outer E U V0 it V brk \<equiv>
V0 \<subseteq> U \<comment> \<open>Start nodes below upper bound\<close>
\<and> E``U \<subseteq> U \<comment> \<open>Upper bound is closed under transitions\<close>
\<and> finite U \<comment> \<open>Upper bound is finite\<close>
\<and> V \<subseteq> U \<comment> \<open>Visited set below upper bound\<close>
\<and> (\<not>brk \<longrightarrow> E``V \<subseteq> V) \<comment> \<open>Visited set closed under reachability\<close>
\<and> (V0 - it \<subseteq> V) \<comment> \<open>Start nodes already iterated over are visited\<close>"
subsubsection "Invariant Preservation"
lemma gen_dfs_outer_initial:
assumes "finite (E\<^sup>*``V0)"
shows "gen_dfs_outer E (E\<^sup>*``V0) V0 V0 {} brk"
using assms unfolding gen_dfs_outer_def
by (auto intro: rev_ImageI)
lemma gen_dfs_pre_initial:
assumes "gen_dfs_outer E U V0 it V False"
assumes "v0\<in>U - V"
shows "gen_dfs_pre E U {} V v0"
using assms unfolding gen_dfs_pre_def gen_dfs_outer_def
apply auto
done
lemma fin_U_imp_wf:
assumes "finite U"
shows "wf (gen_dfs_var U)"
using assms unfolding gen_dfs_var_def by auto
lemma gen_dfs_pre_imp_wf:
assumes "gen_dfs_pre E U S V u0"
shows "wf (gen_dfs_var U)"
using assms unfolding gen_dfs_pre_def gen_dfs_var_def by auto
lemma gen_dfs_pre_imp_fin:
assumes "gen_dfs_pre E U S V u0"
shows "finite (E `` {u0})"
apply (rule finite_subset[where B="U"])
using assms unfolding gen_dfs_pre_def
by auto
text \<open>Inserted \<open>u0\<close> on stack and to visited set\<close>
lemma gen_dfs_pre_imp_fe:
assumes "gen_dfs_pre E U S V u0"
shows "gen_dfs_fe_inv E U (insert u0 S) (insert u0 V) u0
(E``{u0}) (insert u0 V) False"
using assms unfolding gen_dfs_pre_def gen_dfs_fe_inv_def
apply auto
done
lemma gen_dfs_fe_inv_pres_visited:
assumes "gen_dfs_pre E U S V u0"
assumes "gen_dfs_fe_inv E U (insert u0 S) (insert u0 V) u0 it V' False"
assumes "t\<in>it" "it\<subseteq>E``{u0}" "t\<in>V'"
shows "gen_dfs_fe_inv E U (insert u0 S) (insert u0 V) u0 (it-{t}) V' False"
using assms unfolding gen_dfs_fe_inv_def
apply auto
done
lemma gen_dfs_upper_aux:
assumes "(x,y)\<in>E'\<^sup>*"
assumes "(u0,x)\<in>E"
assumes "u0\<in>U"
assumes "E'\<subseteq>E"
assumes "E``U \<subseteq> U"
shows "y\<in>U"
using assms
by induct auto
lemma gen_dfs_fe_inv_imp_var:
assumes "gen_dfs_pre E U S V u0"
assumes "gen_dfs_fe_inv E U (insert u0 S) (insert u0 V) u0 it V' False"
assumes "t\<in>it" "it\<subseteq>E``{u0}" "t\<notin>V'"
shows "(V',V) \<in> gen_dfs_var U"
using assms unfolding gen_dfs_fe_inv_def gen_dfs_pre_def gen_dfs_var_def
apply (clarsimp simp add: finite_psupset_def)
apply (blast dest: gen_dfs_upper_aux)
done
lemma gen_dfs_fe_inv_imp_pre:
assumes "gen_dfs_pre E U S V u0"
assumes "gen_dfs_fe_inv E U (insert u0 S) (insert u0 V) u0 it V' False"
assumes "t\<in>it" "it\<subseteq>E``{u0}" "t\<notin>V'"
shows "gen_dfs_pre E U (insert u0 S) V' t"
using assms unfolding gen_dfs_fe_inv_def gen_dfs_pre_def
apply clarsimp
apply (intro conjI)
apply (blast dest: gen_dfs_upper_aux)
apply blast
apply blast
apply blast
apply clarsimp
apply (rule rtrancl_into_rtrancl[where b=u0])
apply (auto intro: rev_subsetD[OF _ rtrancl_mono[where r="E \<inter> S \<times> UNIV"]]) []
apply blast
done
lemma gen_dfs_post_imp_fe_inv:
assumes "gen_dfs_pre E U S V u0"
assumes "gen_dfs_fe_inv E U (insert u0 S) (insert u0 V) u0 it V' False"
assumes "t\<in>it" "it\<subseteq>E``{u0}" "t\<notin>V'"
assumes "gen_dfs_post E U (insert u0 S) V' t V'' cyc"
shows "gen_dfs_fe_inv E U (insert u0 S) (insert u0 V) u0 (it-{t}) V'' cyc"
using assms unfolding gen_dfs_fe_inv_def gen_dfs_post_def gen_dfs_pre_def
apply clarsimp
apply (intro conjI)
apply blast
apply blast
apply blast
apply (erule order_trans)
apply simp
apply (rule conjI)
apply (erule order_trans[
where y="insert u0 (V \<union> (E - UNIV \<times> insert u0 S)\<^sup>*
`` (E `` {u0} - it - insert u0 S))"])
apply blast
apply (cases cyc)
apply simp
apply blast
apply simp
apply blast
done
lemma gen_dfs_post_aux:
assumes 1: "(u0,x)\<in>E"
assumes 2: "(x,y)\<in>(E - UNIV \<times> insert u0 S)\<^sup>*"
assumes 3: "S\<subseteq>V" "x\<notin>V"
shows "(u0, y) \<in> (E - UNIV \<times> S)\<^sup>*"
proof -
from 1 3 have "(u0,x)\<in>(E - UNIV \<times> S)" by blast
also have "(x,y)\<in>(E - UNIV \<times> S)\<^sup>*"
apply (rule_tac rev_subsetD[OF 2 rtrancl_mono])
by auto
finally show ?thesis .
qed
lemma gen_dfs_fe_imp_post_brk:
assumes "gen_dfs_pre E U S V u0"
assumes "gen_dfs_fe_inv E U (insert u0 S) (insert u0 V) u0 it V' True"
assumes "it\<subseteq>E``{u0}"
shows "gen_dfs_post E U S V u0 V' True"
using assms unfolding gen_dfs_pre_def gen_dfs_fe_inv_def gen_dfs_post_def
apply clarify
apply (intro conjI)
apply simp
apply simp
apply simp
apply clarsimp
apply (blast intro: gen_dfs_post_aux)
done
lemma gen_dfs_fe_inv_imp_post:
assumes "gen_dfs_pre E U S V u0"
assumes "gen_dfs_fe_inv E U (insert u0 S) (insert u0 V) u0 {} V' cyc"
assumes "cyc\<longrightarrow>cyc'"
shows "gen_dfs_post E U S V u0 V' cyc'"
using assms unfolding gen_dfs_pre_def gen_dfs_fe_inv_def gen_dfs_post_def
apply clarsimp
apply (intro conjI)
apply blast
apply (auto intro: gen_dfs_post_aux) []
done
lemma gen_dfs_pre_imp_post_brk:
assumes "gen_dfs_pre E U S V u0"
shows "gen_dfs_post E U S V u0 (insert u0 V) True"
using assms unfolding gen_dfs_pre_def gen_dfs_post_def
apply auto
done
subsubsection "Consequences of Postcondition"
lemma gen_dfs_post_imp_reachable:
assumes "gen_dfs_pre E U S V0 u0"
assumes "gen_dfs_post E U S V0 u0 V brk"
shows "V \<subseteq> V0 \<union> E\<^sup>*``{u0}"
using assms unfolding gen_dfs_post_def gen_dfs_pre_def
apply clarsimp
apply (blast intro: rev_subsetD[OF _ rtrancl_mono])
done
lemma gen_dfs_post_imp_complete:
assumes "gen_dfs_pre E U {} V0 u0"
assumes "gen_dfs_post E U {} V0 u0 V False"
shows "V0 \<union> E\<^sup>*``{u0} \<subseteq> V"
using assms unfolding gen_dfs_post_def gen_dfs_pre_def
apply clarsimp
apply (blast dest: Image_closed_trancl)
done
lemma gen_dfs_post_imp_eq:
assumes "gen_dfs_pre E U {} V0 u0"
assumes "gen_dfs_post E U {} V0 u0 V False"
shows "V = V0 \<union> E\<^sup>*``{u0}"
using gen_dfs_post_imp_reachable[OF assms] gen_dfs_post_imp_complete[OF assms]
by blast
lemma gen_dfs_post_imp_below_U:
assumes "gen_dfs_pre E U S V0 u0"
assumes "gen_dfs_post E U S V0 u0 V False"
shows "V \<subseteq> U"
using assms unfolding gen_dfs_pre_def gen_dfs_post_def
apply clarsimp
apply (blast intro: rev_subsetD[OF _ rtrancl_mono] dest: Image_closed_trancl)
done
lemma gen_dfs_post_imp_outer:
assumes "gen_dfs_outer E U V0 it Vis0 False"
assumes "gen_dfs_post E U {} Vis0 v0 Vis False"
assumes "v0 \<in> it" "it \<subseteq> V0" "v0 \<notin> Vis0"
shows "gen_dfs_outer E U V0 (it - {v0}) Vis False"
proof -
{
assume "v0 \<in> it" "it \<subseteq> V0" "V0 \<subseteq> U" "E `` U \<subseteq> U"
hence "E\<^sup>* `` {v0} \<subseteq> U"
by (metis (full_types) empty_subsetI insert_subset rtrancl_reachable_induct subset_trans)
} note AUX=this
show ?thesis
using assms
unfolding gen_dfs_outer_def gen_dfs_post_def
using AUX
by auto
qed
lemma gen_dfs_outer_already_vis:
assumes "v0 \<in> it" "it \<subseteq> V0" "v0 \<in> V"
assumes "gen_dfs_outer E U V0 it V False"
shows "gen_dfs_outer E U V0 (it - {v0}) V False"
using assms
unfolding gen_dfs_outer_def
by auto
subsection "Abstract Algorithm"
subsubsection \<open>Inner (red) DFS\<close>
text \<open>A witness of the red algorithm is a node on the stack and a path
to this node\<close>
type_synonym 'v red_witness = "('v list \<times> 'v) option"
text \<open>Prepend node to red witness\<close>
fun prep_wit_red :: "'v \<Rightarrow> 'v red_witness \<Rightarrow> 'v red_witness" where
"prep_wit_red v None = None"
| "prep_wit_red v (Some (p,u)) = Some (v#p,u)"
text \<open>
Initial witness for node \<open>u\<close> with onstack successor \<open>v\<close>
\<close>
definition red_init_witness :: "'v \<Rightarrow> 'v \<Rightarrow> 'v red_witness" where
"red_init_witness u v = Some ([u],v)"
definition red_dfs where
"red_dfs E onstack V u \<equiv>
REC\<^sub>T (\<lambda>D (V,u). do {
let V=insert u V;
NDFS_SI_Statistics.vis_red_nres;
\<comment> \<open>Check whether we have a successor on stack\<close>
brk \<leftarrow> FOREACH\<^sub>C (E``{u}) (\<lambda>brk. brk=None)
(\<lambda>t _.
if t\<in>onstack then
RETURN (red_init_witness u t)
else
RETURN None
)
None;
\<comment> \<open>Recurse for successors\<close>
case brk of
None \<Rightarrow>
FOREACH\<^sub>C (E``{u}) (\<lambda>(V,brk). brk=None)
(\<lambda>t (V,_).
if t\<notin>V then do {
(V,brk) \<leftarrow> D (V,t);
RETURN (V,prep_wit_red u brk)
} else RETURN (V,None))
(V,None)
| _ \<Rightarrow> RETURN (V,brk)
}) (V,u)
"
datatype 'v blue_witness =
NO_CYC \<comment> \<open>No cycle detected\<close>
| REACH "'v" "'v list" \<comment> \<open>Path from current start node to node on
stack, path contains accepting node.\<close>
(* REACH u p: u is on stack, p is non-empty path from u0 to u, a node
in u or p is accepting *)
| CIRC "'v list" "'v list" \<comment> \<open>@{text "CIRI pr pl"}: Lasso found from
current start node.\<close>
text \<open>Prepend node to witness\<close>
primrec prep_wit_blue :: "'v \<Rightarrow> 'v blue_witness \<Rightarrow> 'v blue_witness" where
"prep_wit_blue u0 NO_CYC = NO_CYC"
| "prep_wit_blue u0 (REACH u p) = (
if u0=u then
CIRC [] (u0#p)
else
REACH u (u0#p)
)"
| "prep_wit_blue u0 (CIRC pr pl) = CIRC (u0#pr) pl"
text \<open>Initialize blue witness\<close>
fun init_wit_blue :: "'v \<Rightarrow> 'v red_witness \<Rightarrow> 'v blue_witness" where
"init_wit_blue u0 None = NO_CYC"
| "init_wit_blue u0 (Some (p,u)) = (
if u=u0 then
CIRC [] p
else REACH u p)"
definition init_wit_blue_early :: "'v \<Rightarrow> 'v \<Rightarrow> 'v blue_witness"
where "init_wit_blue_early s t \<equiv> if s=t then CIRC [] [s] else REACH t [s]"
text \<open>Extract result from witness\<close>
term lasso_ext
definition "extract_res cyc
\<equiv> (case cyc of
CIRC pr pl \<Rightarrow> Some (pr,pl)
| _ \<Rightarrow> None)"
subsubsection \<open>Outer (Blue) DFS\<close>
definition blue_dfs
:: "('a,_) b_graph_rec_scheme \<Rightarrow> ('a list \<times> 'a list) option nres"
where
"blue_dfs G \<equiv> do {
NDFS_SI_Statistics.start_nres;
(_,_,cyc) \<leftarrow> FOREACHc (g_V0 G) (\<lambda>(_,_,cyc). cyc=NO_CYC)
(\<lambda>v0 (blues,reds,_). do {
if v0 \<notin> blues then do {
(blues,reds,_,cyc) \<leftarrow> REC\<^sub>T (\<lambda>D (blues,reds,onstack,s). do {
let blues=insert s blues;
let onstack=insert s onstack;
let s_acc = s \<in> bg_F G;
NDFS_SI_Statistics.vis_blue_nres;
(blues,reds,onstack,cyc) \<leftarrow>
FOREACH\<^sub>C ((g_E G)``{s}) (\<lambda>(_,_,_,cyc). cyc=NO_CYC)
(\<lambda>t (blues,reds,onstack,cyc).
if t \<in> onstack \<and> (s_acc \<or> t \<in> bg_F G) then (
RETURN (blues,reds,onstack, init_wit_blue_early s t)
) else if t\<notin>blues then do {
(blues,reds,onstack,cyc) \<leftarrow> D (blues,reds,onstack,t);
RETURN (blues,reds,onstack,(prep_wit_blue s cyc))
} else do {
NDFS_SI_Statistics.match_blue_nres;
RETURN (blues,reds,onstack,cyc)
})
(blues,reds,onstack,NO_CYC);
(reds,cyc) \<leftarrow>
if cyc=NO_CYC \<and> s_acc then do {
(reds,rcyc) \<leftarrow> red_dfs (g_E G) onstack reds s;
RETURN (reds, init_wit_blue s rcyc)
} else RETURN (reds,cyc);
let onstack=onstack - {s};
RETURN (blues,reds,onstack,cyc)
}) (blues,reds,{},v0);
RETURN (blues, reds, cyc)
} else do {
RETURN (blues, reds, NO_CYC)
}
}) ({},{},NO_CYC);
NDFS_SI_Statistics.stop_nres;
RETURN (extract_res cyc)
}
"
concrete_definition blue_dfs_fe uses blue_dfs_def
is "blue_dfs G \<equiv> do {
NDFS_SI_Statistics.start_nres;
(_,_,cyc) \<leftarrow> ?FE;
NDFS_SI_Statistics.stop_nres;
RETURN (extract_res cyc)
}"
concrete_definition blue_dfs_body uses blue_dfs_fe_def
is "_ \<equiv> FOREACHc (g_V0 G) (\<lambda>(_,_,cyc). cyc=NO_CYC)
(\<lambda>v0 (blues,reds,_). do {
if v0\<notin>blues then do {
(blues,reds,_,cyc) \<leftarrow> REC\<^sub>T ?B (blues,reds,{},v0);
RETURN (blues, reds, cyc)
} else do {RETURN (blues, reds, NO_CYC)}
}) ({},{},NO_CYC)"
thm blue_dfs_body_def
subsection "Correctness"
text \<open>Additional invariant to be maintained between calls of red dfs\<close>
definition "red_dfs_inv E U reds onstack \<equiv>
E``U \<subseteq> U \<comment> \<open>Upper bound is closed under transitions\<close>
\<and> finite U \<comment> \<open>Upper bound is finite\<close>
\<and> reds \<subseteq> U \<comment> \<open>Red set below upper bound\<close>
\<and> E``reds \<subseteq> reds \<comment> \<open>Red nodes closed under reachability\<close>
\<and> E``reds \<inter> onstack = {} \<comment> \<open>No red node with edge to stack\<close>
"
lemma red_dfs_inv_initial:
assumes "finite (E\<^sup>*``V0)"
shows "red_dfs_inv E (E\<^sup>*``V0) {} {}"
using assms unfolding red_dfs_inv_def
apply (auto intro: rev_ImageI)
done
text \<open>Correctness of the red DFS.\<close>
theorem red_dfs_correct:
fixes v0 u0 :: 'v
assumes PRE:
"red_dfs_inv E U reds onstack"
"u0\<in>U"
"u0\<notin>reds"
shows "red_dfs E onstack reds u0
\<le> SPEC (\<lambda>(reds',cyc). case cyc of
Some (p,v) \<Rightarrow> v\<in>onstack \<and> p\<noteq>[] \<and> path E u0 p v
| None \<Rightarrow>
red_dfs_inv E U reds' onstack
\<and> u0\<in>reds'
\<and> reds' \<subseteq> reds \<union> E\<^sup>* `` {u0}
)"
proof -
let ?dfs_red = "
REC\<^sub>T (\<lambda>D (V,u). do {
let V=insert u V;
NDFS_SI_Statistics.vis_red_nres;
\<comment> \<open>Check whether we have a successor on stack\<close>
brk \<leftarrow> FOREACH\<^sub>C (E``{u}) (\<lambda>brk. brk=None)
(\<lambda>t _. if t\<in>onstack then
RETURN (red_init_witness u t)
else RETURN None)
None;
\<comment> \<open>Recurse for successors\<close>
case brk of
None \<Rightarrow>
FOREACH\<^sub>C (E``{u}) (\<lambda>(V,brk). brk=None)
(\<lambda>t (V,_).
if t\<notin>V then do {
(V,brk) \<leftarrow> D (V,t);
RETURN (V,prep_wit_red u brk)
} else RETURN (V,None))
(V,None)
| _ \<Rightarrow> RETURN (V,brk)
}) (V,u)
"
let "REC\<^sub>T ?body ?init" = "?dfs_red"
define pre where "pre = (\<lambda>S (V,u0). gen_dfs_pre E U S V u0 \<and> E``V \<inter> onstack = {})"
define post where "post = (\<lambda>S (V0,u0) (V,cyc). gen_dfs_post E U S V0 u0 V (cyc\<noteq>None)
\<and> (case cyc of None \<Rightarrow> E``V \<inter> onstack = {}
| Some (p,v) \<Rightarrow> v\<in>onstack \<and> p\<noteq>[] \<and> path E u0 p v))
"
define fe_inv where "fe_inv = (\<lambda>S V0 u0 it (V,cyc).
gen_dfs_fe_inv E U S V0 u0 it V (cyc\<noteq>None)
\<and> (case cyc of None \<Rightarrow> E``V \<inter> onstack = {}
| Some (p,v) \<Rightarrow> v\<in>onstack \<and> p\<noteq>[] \<and> path E u0 p v))
"
from PRE have GENPRE: "gen_dfs_pre E U {} reds u0"
unfolding red_dfs_inv_def gen_dfs_pre_def
by auto
with PRE have PRE': "pre {} (reds,u0)"
unfolding pre_def red_dfs_inv_def
by auto
have IMP_POST: "SPEC (post {} (reds,u0))
\<le> SPEC (\<lambda>(reds',cyc). case cyc of
Some (p,v) \<Rightarrow> v\<in>onstack \<and> p\<noteq>[] \<and> path E u0 p v
| None \<Rightarrow>
red_dfs_inv E U reds' onstack
\<and> u0\<in>reds'
\<and> reds' \<subseteq> reds \<union> E\<^sup>* `` {u0})"
apply (clarsimp split: option.split)
apply (intro impI conjI allI)
apply simp_all
proof -
fix reds' p v
assume "post {} (reds,u0) (reds',Some (p,v))"
thus "v\<in>onstack" and "p\<noteq>[]" and "path E u0 p v"
unfolding post_def by auto
next
fix reds'
assume "post {} (reds, u0) (reds', None)"
hence GPOST: "gen_dfs_post E U {} reds u0 reds' False"
and NS: "E``reds' \<inter> onstack = {}"
unfolding post_def by auto
from GPOST show "u0\<in>reds'" unfolding gen_dfs_post_def by auto
show "red_dfs_inv E U reds' onstack"
unfolding red_dfs_inv_def
apply (intro conjI)
using GENPRE[unfolded gen_dfs_pre_def]
apply (simp_all) [2]
apply (rule gen_dfs_post_imp_below_U[OF GENPRE GPOST])
using GPOST[unfolded gen_dfs_post_def] apply simp
apply fact
done
from GPOST show "reds' \<subseteq> reds \<union> E\<^sup>* `` {u0}"
unfolding gen_dfs_post_def by auto
qed
{
fix \<sigma> S
assume INV0: "pre S \<sigma>"
have "REC\<^sub>T ?body \<sigma>
\<le> SPEC (post S \<sigma>)"
apply (rule RECT_rule_arb[where
pre="pre" and
V="gen_dfs_var U <*lex*> {}" and
arb="S"
])
apply refine_mono
using INV0[unfolded pre_def] apply (auto intro: gen_dfs_pre_imp_wf) []
apply fact
apply (rename_tac D S u)
apply (intro refine_vcg)
(* First foreach loop, checking for onstack-successor*)
apply (rule_tac I="\<lambda>it cyc.
(case cyc of None \<Rightarrow> (E``{b} - it) \<inter> onstack = {}
| Some (p,v) \<Rightarrow> (v\<in>onstack \<and> p\<noteq>[] \<and> path E b p v))"
in FOREACHc_rule)
apply (auto simp add: pre_def gen_dfs_pre_imp_fin) []
apply auto []
apply (auto
split: option.split
simp: red_init_witness_def intro: path1) []
apply (intro refine_vcg)
(* Second foreach loop, iterating over sucessors *)
apply (rule_tac I="fe_inv (insert b S) (insert b a) b" in
FOREACHc_rule
)
apply (auto simp add: pre_def gen_dfs_pre_imp_fin) []
apply (auto simp add: pre_def fe_inv_def gen_dfs_pre_imp_fe) []
apply (intro refine_vcg)
(* Recursive call *)
apply (rule order_trans)
apply (rprems)
apply (clarsimp simp add: pre_def fe_inv_def)
apply (rule gen_dfs_fe_inv_imp_pre, assumption+) []
apply (auto simp add: pre_def fe_inv_def intro: gen_dfs_fe_inv_imp_var) []
apply (clarsimp simp add: pre_def post_def fe_inv_def
split: option.split_asm prod.split_asm
) []
apply (blast intro: gen_dfs_post_imp_fe_inv)
apply (blast intro: gen_dfs_post_imp_fe_inv path_prepend)
apply (auto simp add: pre_def post_def fe_inv_def
intro: gen_dfs_fe_inv_pres_visited) []
apply (auto simp add: pre_def post_def fe_inv_def
intro: gen_dfs_fe_inv_imp_post) []
apply (auto simp add: pre_def post_def fe_inv_def
intro: gen_dfs_fe_imp_post_brk) []
apply (auto simp add: pre_def post_def fe_inv_def
intro: gen_dfs_pre_imp_post_brk) []
apply (auto simp add: pre_def post_def fe_inv_def
intro: gen_dfs_pre_imp_post_brk) []
done
} note GEN=this
note GEN[OF PRE']
also note IMP_POST
finally show ?thesis
unfolding red_dfs_def .
qed
text \<open>Main theorem: Correctness of the blue DFS\<close>
theorem blue_dfs_correct:
fixes G :: "('v,_) b_graph_rec_scheme"
assumes "b_graph G"
assumes finitely_reachable: "finite ((g_E G)\<^sup>* `` g_V0 G)"
shows "blue_dfs G \<le> SPEC (\<lambda>r.
case r of None \<Rightarrow> (\<forall>L. \<not>b_graph.is_lasso_prpl G L)
| Some L \<Rightarrow> b_graph.is_lasso_prpl G L)"
proof -
interpret b_graph G by fact
let ?A = "bg_F G"
let ?E = "g_E G"
let ?V0 = "g_V0 G"
let ?U = "?E\<^sup>*``?V0"
define add_inv where "add_inv = (\<lambda>blues reds onstack.
\<not>(\<exists>v\<in>(blues-onstack)\<inter>?A. (v,v)\<in>?E\<^sup>+) \<comment> \<open>No cycles over finished, accepting states\<close>
\<and> reds \<subseteq> blues \<comment> \<open>Red nodes are also blue\<close>
\<and> reds \<inter> onstack = {} \<comment> \<open>No red nodes on stack\<close>
\<and> red_dfs_inv ?E ?U reds onstack)"
define cyc_post where "cyc_post = (\<lambda>blues reds onstack u0 cyc. (case cyc of
NO_CYC \<Rightarrow> add_inv blues reds onstack
| REACH u p \<Rightarrow>
path ?E u0 p u
\<and> u \<in> onstack-{u0}
\<and> insert u (set p) \<inter> ?A \<noteq> {}
| CIRC pr pl \<Rightarrow> \<exists>v.
pl\<noteq>[]
\<and> path ?E v pl v
\<and> path ?E u0 pr v
\<and> set pl \<inter> ?A \<noteq> {}
))"
define pre where "pre = (\<lambda>(blues,reds,onstack,u::'v).
gen_dfs_pre ?E ?U onstack blues u \<and> add_inv blues reds onstack)"
define post where "post = (\<lambda>(blues0,reds0::'v set,onstack0,u0) (blues,reds,onstack,cyc).
onstack = onstack0
\<and> gen_dfs_post ?E ?U onstack0 blues0 u0 blues (cyc\<noteq>NO_CYC)
\<and> cyc_post blues reds onstack u0 cyc)"
define fe_inv where "fe_inv = (\<lambda>blues0 u0 onstack0 it (blues,reds,onstack,cyc).
onstack=onstack0
\<and> gen_dfs_fe_inv ?E ?U onstack0 blues0 u0 it blues (cyc\<noteq>NO_CYC)
\<and> cyc_post blues reds onstack u0 cyc)"
define outer_inv where "outer_inv = (\<lambda>it (blues,reds,cyc).
case cyc of
NO_CYC \<Rightarrow>
add_inv blues reds {}
\<and> gen_dfs_outer ?E ?U ?V0 it blues False
| CIRC pr pl \<Rightarrow> \<exists>v0\<in>?V0. \<exists>v.
pl\<noteq>[]
\<and> path ?E v pl v
\<and> path ?E v0 pr v
\<and> set pl \<inter> ?A \<noteq> {}
| _ \<Rightarrow> False)"
have OUTER_INITIAL: "outer_inv V0 ({}, {}, NO_CYC)"
unfolding outer_inv_def add_inv_def
using finitely_reachable
apply (auto intro: red_dfs_inv_initial gen_dfs_outer_initial)
done
{
fix onstack blues u0 reds
assume "pre (blues,reds,onstack,u0)"
hence "fe_inv (insert u0 blues) u0 (insert u0 onstack) (?E``{u0})
(insert u0 blues,reds,insert u0 onstack,NO_CYC)"
unfolding fe_inv_def add_inv_def cyc_post_def
apply clarsimp
apply (intro conjI)
apply (simp add: pre_def gen_dfs_pre_imp_fe)
apply (auto simp: pre_def add_inv_def) []
apply (auto simp: pre_def add_inv_def) []
apply (auto simp: pre_def add_inv_def gen_dfs_pre_def) []
apply (auto simp: pre_def add_inv_def) []
apply (unfold pre_def add_inv_def red_dfs_inv_def gen_dfs_pre_def) []
apply clarsimp
apply blast
done
} note PRE_IMP_FE = this
have [simp]: "\<And>u cyc. prep_wit_blue u cyc = NO_CYC \<longleftrightarrow> cyc=NO_CYC"
by (case_tac cyc) auto
{
fix blues0 reds0 onstack0 and u0::'v and
blues reds onstack blues' reds' onstack'
cyc it t
assume PRE: "pre (blues0,reds0,onstack0,u0)"
assume FEI: "fe_inv (insert u0 blues0) u0 (insert u0 onstack0)
it (blues,reds,onstack,NO_CYC)"
assume IT: "t\<in>it" "it\<subseteq>?E``{u0}" "t\<notin>blues"
assume POST: "post (blues,reds,onstack, t) (blues',reds',onstack',cyc)"
note [simp del] = path_simps
have "fe_inv (insert u0 blues0) u0 (insert u0 onstack0) (it-{t})
(blues',reds',onstack',prep_wit_blue u0 cyc)"
unfolding fe_inv_def
using PRE FEI IT POST
unfolding fe_inv_def post_def pre_def
apply (clarsimp)
apply (intro allI impI conjI)
apply (blast intro: gen_dfs_post_imp_fe_inv)
unfolding cyc_post_def
apply (auto split: blue_witness.split_asm simp: path_simps)
done
} note FE_INV_PRES=this
{
fix blues reds onstack u0
assume "pre (blues,reds,onstack,u0)"
hence "u0\<in>?E\<^sup>*``?V0"
unfolding pre_def gen_dfs_pre_def by auto
} note PRE_IMP_REACH = this
{
fix blues0 reds0 onstack0 u0 blues reds onstack
assume A: "pre (blues0,reds0,onstack0,u0)"
"fe_inv (insert u0 blues0) u0 (insert u0 onstack0)
{} (blues,reds,onstack,NO_CYC)"
"u0\<in>?A"
have "u0\<notin>reds" using A
unfolding fe_inv_def add_inv_def pre_def cyc_post_def
apply auto
done
} note FE_IMP_RED_PRE = this
{
fix blues0 reds0 onstack0 u0 blues reds onstack rcyc reds'
assume PRE: "pre (blues0,reds0,onstack0,u0)"
assume FEI: "fe_inv (insert u0 blues0) u0 (insert u0 onstack0)
{} (blues,reds,onstack,NO_CYC)"
assume ACC: "u0\<in>?A"
assume SPECR: "case rcyc of
Some (p,v) \<Rightarrow> v\<in>onstack \<and> p\<noteq>[] \<and> path ?E u0 p v
| None \<Rightarrow>
red_dfs_inv ?E ?U reds' onstack
\<and> u0\<in>reds'
\<and> reds' \<subseteq> reds \<union> ?E\<^sup>* `` {u0}"
have "post (blues0,reds0,onstack0,u0)
(blues,reds',onstack - {u0},init_wit_blue u0 rcyc)"
unfolding post_def add_inv_def cyc_post_def
apply (clarsimp)
apply (intro conjI)
proof goal_cases
from PRE FEI show OS0[symmetric]: "onstack - {u0} = onstack0"
by (auto simp: pre_def fe_inv_def add_inv_def gen_dfs_pre_def)
from PRE FEI have "u0\<in>onstack"
unfolding pre_def gen_dfs_pre_def fe_inv_def gen_dfs_fe_inv_def
by auto
from PRE FEI
show POST: "gen_dfs_post ?E (?E\<^sup>* `` ?V0) onstack0 blues0 u0 blues
(init_wit_blue u0 rcyc \<noteq> NO_CYC)"
by (auto simp: pre_def fe_inv_def intro: gen_dfs_fe_inv_imp_post)
case 3
from FEI have [simp]: "onstack=insert u0 onstack0"
unfolding fe_inv_def by auto
from FEI have "u0\<in>blues" unfolding fe_inv_def gen_dfs_fe_inv_def by auto
show ?case
apply (cases rcyc)
apply (simp_all add: split_paired_all)
proof -
assume [simp]: "rcyc=None"
show "(\<forall>v\<in>(blues - (onstack0 - {u0})) \<inter> ?A. (v, v) \<notin> ?E\<^sup>+) \<and>
reds' \<subseteq> blues \<and>
reds' \<inter> (onstack0 - {u0}) = {} \<and>
red_dfs_inv ?E (?E\<^sup>* `` ?V0) reds' (onstack0 - {u0})"
proof (intro conjI)
from SPECR have RINV: "red_dfs_inv ?E ?U reds' onstack"
and "u0\<in>reds'"
and REDS'R: "reds' \<subseteq> reds \<union> ?E\<^sup>*``{u0}"
by auto
from RINV show
RINV': "red_dfs_inv ?E (?E\<^sup>* `` ?V0) reds' (onstack0 - {u0})"
unfolding red_dfs_inv_def by auto
from RINV'[unfolded red_dfs_inv_def] have
REDS'CL: "?E``reds' \<subseteq> reds'"
and DJ': "?E `` reds' \<inter> (onstack0 - {u0}) = {}" by auto
from RINV[unfolded red_dfs_inv_def] have
DJ: "?E `` reds' \<inter> (onstack) = {}" by auto
show "reds' \<subseteq> blues"
proof
fix v assume "v\<in>reds'"
with REDS'R have "v\<in>reds \<or> (u0,v)\<in>?E\<^sup>*" by blast
thus "v\<in>blues" proof
assume "v\<in>reds"
moreover with FEI have "reds\<subseteq>blues"
unfolding fe_inv_def add_inv_def cyc_post_def by auto
ultimately show ?thesis ..
next
from POST[unfolded gen_dfs_post_def OS0] have
CL: "?E `` (blues - (onstack0 - {u0})) \<subseteq> blues" and "u0\<in>blues"
by auto
from PRE FEI have "onstack0 \<subseteq> blues"
unfolding pre_def fe_inv_def gen_dfs_pre_def gen_dfs_fe_inv_def
by auto
assume "(u0,v)\<in>?E\<^sup>*"
thus "v\<in>blues"
proof (cases rule: rtrancl_last_visit[where S="onstack - {u0}"])
case no_visit
thus "v\<in>blues" using \<open>u0\<in>blues\<close> CL
by induct (auto elim: rtranclE)
next
case (last_visit_point u)
then obtain uh where "(u0,uh)\<in>?E\<^sup>*" and "(uh,u)\<in>?E"
by (metis tranclD2)
with REDS'CL DJ' \<open>u0\<in>reds'\<close> have "uh\<in>reds'"
by (auto dest: Image_closed_trancl)
with DJ' \<open>(uh,u)\<in>?E\<close> \<open>u \<in> onstack - {u0}\<close> have False
by simp blast
thus ?thesis ..
qed
qed
qed
show "\<forall>v\<in>(blues - (onstack0 - {u0})) \<inter> ?A. (v, v) \<notin> ?E\<^sup>+"
proof
fix v
assume A: "v \<in> (blues - (onstack0 - {u0})) \<inter> ?A"
show "(v,v)\<notin>?E\<^sup>+" proof (cases "v=u0")
assume "v\<noteq>u0"
with A have "v\<in>(blues - (insert u0 onstack)) \<inter> ?A" by auto
with FEI show ?thesis
unfolding fe_inv_def add_inv_def cyc_post_def by auto
next
assume [simp]: "v=u0"
show ?thesis proof
assume "(v,v)\<in>?E\<^sup>+"
then obtain uh where "(u0,uh)\<in>?E\<^sup>*" and "(uh,u0)\<in>?E"
by (auto dest: tranclD2)
with REDS'CL DJ \<open>u0\<in>reds'\<close> have "uh\<in>reds'"
by (auto dest: Image_closed_trancl)
with DJ \<open>(uh,u0)\<in>?E\<close> \<open>u0 \<in> onstack\<close> show False by blast
qed
qed
qed
show "reds' \<inter> (onstack0 - {u0}) = {}"
proof (rule ccontr)
assume "reds' \<inter> (onstack0 - {u0}) \<noteq> {}"
then obtain v where "v\<in>reds'" and "v\<in>onstack0" and "v\<noteq>u0" by auto
from \<open>v\<in>reds'\<close> REDS'R have "v\<in>reds \<or> (u0,v)\<in>?E\<^sup>*"
by auto
thus False proof
assume "v\<in>reds"
with FEI[unfolded fe_inv_def add_inv_def cyc_post_def]
\<open>v\<in>onstack0\<close>
show False by auto
next
assume "(u0,v)\<in>?E\<^sup>*"
with \<open>v\<noteq>u0\<close> obtain uh where "(u0,uh)\<in>?E\<^sup>*" and "(uh,v)\<in>?E"
by (auto elim: rtranclE)
with REDS'CL DJ \<open>u0\<in>reds'\<close> have "uh\<in>reds'"
by (auto dest: Image_closed_trancl)
with DJ \<open>(uh,v)\<in>?E\<close> \<open>v \<in> onstack0\<close> show False by simp blast
qed
qed
qed
next
fix u p
assume [simp]: "rcyc = Some (p,u)"
show "
(u = u0 \<longrightarrow> p \<noteq> [] \<and> path ?E u0 p u0 \<and> set p \<inter> ?A \<noteq> {}) \<and>
(u \<noteq> u0 \<longrightarrow>
path ?E u0 p u \<and> u \<in> onstack0 \<and> (u \<in> ?A \<or> set p \<inter> ?A \<noteq> {}))"
proof (intro conjI impI)
from SPECR \<open>u0\<in>?A\<close> show
"u\<noteq>u0 \<Longrightarrow> u\<in>onstack0"
"p\<noteq>[]"
"path ?E u0 p u"
"u=u0 \<Longrightarrow> path ?E u0 p u0"
"set p \<inter> F \<noteq> {}"
"u \<in> F \<or> set p \<inter> F \<noteq> {}"
by (auto simp: neq_Nil_conv path_simps)
qed
qed
qed
} note RED_IMP_POST = this
{
fix blues0 reds0 onstack0 u0 blues reds onstack and cyc :: "'v blue_witness"
assume PRE: "pre (blues0,reds0,onstack0,u0)"
and FEI: "fe_inv (insert u0 blues0) u0 (insert u0 onstack0)
{} (blues,reds,onstack,NO_CYC)"
and FC[simp]: "cyc=NO_CYC"
and NCOND: "u0\<notin>?A"
from PRE FEI have OS0: "onstack0 = onstack - {u0}"
by (auto simp: pre_def fe_inv_def add_inv_def gen_dfs_pre_def) []
from PRE FEI have "u0\<in>onstack"
unfolding pre_def gen_dfs_pre_def fe_inv_def gen_dfs_fe_inv_def
by auto
with OS0 have OS1: "onstack = insert u0 onstack0" by auto
have "post (blues0,reds0,onstack0,u0) (blues,reds,onstack - {u0},NO_CYC)"
apply (clarsimp simp: post_def cyc_post_def) []
apply (intro conjI impI)
apply (simp add: OS0)
using PRE FEI apply (auto
simp: pre_def fe_inv_def intro: gen_dfs_fe_inv_imp_post) []
using FEI[unfolded fe_inv_def cyc_post_def] unfolding add_inv_def
apply clarsimp
apply (intro conjI)
using NCOND apply auto []
apply auto []
apply (clarsimp simp: red_dfs_inv_def, blast) []
done
} note NCOND_IMP_POST=this
{
fix blues0 reds0 onstack0 u0 blues reds onstack it
and cyc :: "'v blue_witness"
assume PRE: "pre (blues0,reds0,onstack0,u0)"
and FEI: "fe_inv (insert u0 blues0) u0 (insert u0 onstack0)
it (blues,reds,onstack,cyc)"
and NC: "cyc\<noteq>NO_CYC"
and IT: "it\<subseteq>?E``{u0}"
from PRE FEI have OS0: "onstack0 = onstack - {u0}"
by (auto simp: pre_def fe_inv_def add_inv_def gen_dfs_pre_def) []
from PRE FEI have "u0\<in>onstack"
unfolding pre_def gen_dfs_pre_def fe_inv_def gen_dfs_fe_inv_def
by auto
with OS0 have OS1: "onstack = insert u0 onstack0" by auto
have "post (blues0,reds0,onstack0,u0) (blues,reds,onstack - {u0},cyc)"
apply (clarsimp simp: post_def) []
apply (intro conjI impI)
apply (simp add: OS0)
using PRE FEI IT NC apply (auto
simp: pre_def fe_inv_def intro: gen_dfs_fe_imp_post_brk) []
using FEI[unfolded fe_inv_def] NC
unfolding cyc_post_def
apply (auto split: blue_witness.split simp: OS1) []
done
} note BREAK_IMP_POST = this
{
fix blues0 reds0 onstack0 and u0::'v and
blues reds onstack cyc it t
assume PRE: "pre (blues0,reds0,onstack0,u0)"
assume FEI: "fe_inv (insert u0 blues0) u0 (insert u0 onstack0)
it (blues,reds,onstack,NO_CYC)"
assume IT: "it\<subseteq>?E``{u0}" "t\<in>it"
assume T_OS: "t \<in> onstack"
assume U0ACC: "u0\<in>F \<or> t\<in>F"
from T_OS have TIB: "t \<in> blues" using PRE FEI
by (auto simp add: fe_inv_def pre_def gen_dfs_fe_inv_def gen_dfs_pre_def)
have "fe_inv (insert u0 blues0) u0 (insert u0 onstack0) (it - {t})
(blues,reds,onstack,init_wit_blue_early u0 t)"
unfolding fe_inv_def
apply (clarsimp simp: it_step_insert_iff[OF IT])
apply (intro conjI)
using PRE FEI apply (simp add: fe_inv_def pre_def)
(* TODO: This is a generic early-break condition. However, it requires
t \<in> V. Do we really need such a strict invar in case of break? *)
using FEI TIB apply (auto simp add: fe_inv_def gen_dfs_fe_inv_def) []
unfolding cyc_post_def init_wit_blue_early_def
using IT T_OS U0ACC apply (auto simp: path_simps) []
done
} note EARLY_DET_OPT = this
{
fix \<sigma>
assume INV0: "pre \<sigma>"
have "REC\<^sub>T (blue_dfs_body G) \<sigma> \<le> SPEC (post \<sigma>)"
apply (intro refine_vcg
RECT_rule[where pre="pre"
and V="gen_dfs_var ?U <*lex*> {}"]
)
apply (unfold blue_dfs_body_def, refine_mono) []
apply (blast intro!: fin_U_imp_wf finitely_reachable)
apply (rule INV0)
(* Body *)
apply (simp (no_asm) only: blue_dfs_body_def)
apply (refine_rcg refine_vcg)
(* Foreach loop *)
apply (rule_tac
I="fe_inv (insert bb a) bb (insert bb ab)"
in FOREACHc_rule')
apply (auto simp add: pre_def gen_dfs_pre_imp_fin) []
apply (blast intro: PRE_IMP_FE)
apply (intro refine_vcg)
(* Early detection of cycles *)
apply (blast intro: EARLY_DET_OPT)
(* Recursive call *)
apply (rule order_trans)
apply (rprems)
apply (clarsimp simp add: pre_def fe_inv_def cyc_post_def)
apply (rule gen_dfs_fe_inv_imp_pre, assumption+) []
apply (auto simp add: pre_def fe_inv_def intro: gen_dfs_fe_inv_imp_var) []
apply (auto intro: FE_INV_PRES) []
apply (auto simp add: pre_def post_def fe_inv_def
intro: gen_dfs_fe_inv_pres_visited) []
apply (intro refine_vcg)
(* Nested DFS call *)
apply (rule order_trans)
apply (rule red_dfs_correct[where U="?E\<^sup>* `` ?V0"])
apply (auto simp add: fe_inv_def add_inv_def cyc_post_def) []
apply (auto intro: PRE_IMP_REACH) []
apply (auto dest: FE_IMP_RED_PRE) []
apply (intro refine_vcg)
apply clarsimp
apply (rule RED_IMP_POST, assumption+) []
apply (clarsimp, blast intro: NCOND_IMP_POST) []
apply (intro refine_vcg)
apply simp
apply (clarsimp, blast intro: BREAK_IMP_POST) []
done
} note GEN=this
{
fix v0 it blues reds
assume "v0 \<in> it" "it \<subseteq> V0" "v0 \<notin> blues"
"outer_inv it (blues, reds, NO_CYC)"
hence "pre (blues, reds, {}, v0)"
unfolding pre_def outer_inv_def
by (auto intro: gen_dfs_pre_initial)
} note OUTER_IMP_PRE = this
{
fix v0 it blues0 reds0 blues reds onstack cyc
assume "v0 \<in> it" "it \<subseteq> V0" "v0 \<notin> blues0"
"outer_inv it (blues0, reds0, NO_CYC)"
"post (blues0, reds0, {}, v0) (blues, reds, onstack, cyc)"
hence "outer_inv (it - {v0}) (blues, reds, cyc)"
unfolding post_def outer_inv_def cyc_post_def
by (fastforce split: blue_witness.split intro: gen_dfs_post_imp_outer)
} note POST_IMP_OUTER = this
{
fix v0 it blues reds
assume "v0 \<in> it" "it \<subseteq> V0" "outer_inv it (blues, reds, NO_CYC)"
"v0 \<in> blues"
hence "outer_inv (it - {v0}) (blues, reds, NO_CYC)"
unfolding outer_inv_def
by (auto intro: gen_dfs_outer_already_vis)
} note OUTER_ALREX = this
{
fix it blues reds cyc
assume "outer_inv it (blues, reds, cyc)" "cyc \<noteq> NO_CYC"
hence "case extract_res cyc of
None \<Rightarrow> \<forall>L. \<not> is_lasso_prpl L
| Some x \<Rightarrow> is_lasso_prpl x"
unfolding outer_inv_def extract_res_def is_lasso_prpl_def
is_lasso_prpl_pre_def
apply (cases cyc)
apply auto
done
} note IMP_POST_CYC = this
{ fix "pr" pl blues reds
assume ADD_INV: "add_inv blues reds {}"
assume GEN_INV: "gen_dfs_outer E (E\<^sup>* `` V0) V0 {} blues False"
assume LASSO: "is_lasso_prpl (pr, pl)"
from LASSO[unfolded is_lasso_prpl_def is_lasso_prpl_pre_def]
obtain v0 va where
"v0\<in>V0" "pl\<noteq>[]" and
PR: "path E v0 pr va" and PL: "path E va pl va" and
F: "set pl \<inter> F \<noteq> {}"
by auto
from F obtain pl1 vf pl2 where [simp]: "pl=pl1@vf#pl2" and "vf\<in>F"
by (fastforce simp: in_set_conv_decomp)
from PR PL have "path E v0 (pr@pl1) vf" "path E vf (vf#pl2@pl1) vf"
by (auto simp: path_simps)
hence "(v0,vf)\<in>E\<^sup>*" and "(vf,vf)\<in>E\<^sup>+"
by (auto dest: path_is_rtrancl path_is_trancl)
from GEN_INV \<open>v0\<in>V0\<close> \<open>(v0,vf)\<in>E\<^sup>*\<close> have "vf\<in>blues"
unfolding gen_dfs_outer_def
apply (clarsimp)
by (metis Image_closed_trancl rev_ImageI rev_subsetD)
from ADD_INV[unfolded add_inv_def] \<open>vf\<in>blues\<close> \<open>vf\<in>F\<close> \<open>(vf,vf)\<in>E\<^sup>+\<close>
have False by auto
} note IMP_POST_NOCYC_AUX = this
{
fix blues reds cyc
assume "outer_inv {} (blues, reds, cyc)"
hence "case extract_res cyc of
None \<Rightarrow> \<forall>L. \<not> is_lasso_prpl L
| Some x \<Rightarrow> is_lasso_prpl x"
apply (cases cyc)
apply (simp_all add: IMP_POST_CYC)
unfolding outer_inv_def extract_res_def
apply (auto intro: IMP_POST_NOCYC_AUX)
done
} note IMP_POST_NOCYC = this
show ?thesis
unfolding blue_dfs_fe.refine blue_dfs_body.refine
apply (refine_rcg
FOREACHc_rule[where I=outer_inv]
refine_vcg
)
apply (simp add: finitely_reachable finite_V0)
apply (rule OUTER_INITIAL)
apply (rule order_trans[OF GEN])
apply (clarsimp, blast intro: OUTER_IMP_PRE)
apply (clarsimp, blast intro: POST_IMP_OUTER)
apply (clarsimp, blast intro: OUTER_ALREX)
apply (clarsimp, blast intro: IMP_POST_NOCYC)
apply (clarsimp, blast intro: IMP_POST_CYC)
done
qed
subsection "Refinement"
subsubsection \<open>Setup for Custom Datatypes\<close>
text \<open>This effort can be automated, but currently, such an automation is
not yet implemented\<close>
abbreviation "red_wit_rel R \<equiv> \<langle>\<langle>\<langle>R\<rangle>list_rel,R\<rangle>prod_rel\<rangle>option_rel"
abbreviation "i_red_wit I \<equiv> \<langle>\<langle>\<langle>I\<rangle>\<^sub>ii_list,I\<rangle>\<^sub>ii_prod\<rangle>\<^sub>ii_option"
abbreviation "blue_wit_rel \<equiv> (Id::(_ blue_witness \<times> _) set)"
consts i_blue_wit :: interface
lemmas [autoref_rel_intf] = REL_INTFI[of blue_wit_rel i_blue_wit]
term init_wit_blue_early
lemma [autoref_itype]:
"NO_CYC ::\<^sub>i i_blue_wit"
"(=) ::\<^sub>i i_blue_wit \<rightarrow>\<^sub>i i_blue_wit \<rightarrow>\<^sub>i i_bool"
"init_wit_blue ::\<^sub>i I \<rightarrow>\<^sub>i i_red_wit I \<rightarrow>\<^sub>i i_blue_wit"
"init_wit_blue_early ::\<^sub>i I \<rightarrow>\<^sub>i I \<rightarrow>\<^sub>i i_blue_wit"
"prep_wit_blue ::\<^sub>i I \<rightarrow>\<^sub>i i_blue_wit \<rightarrow>\<^sub>i i_blue_wit"
"red_init_witness ::\<^sub>i I \<rightarrow>\<^sub>i I \<rightarrow>\<^sub>i i_red_wit I"
"prep_wit_red ::\<^sub>i I \<rightarrow>\<^sub>i i_red_wit I \<rightarrow>\<^sub>i i_red_wit I"
"extract_res ::\<^sub>i i_blue_wit \<rightarrow>\<^sub>i \<langle>\<langle>\<langle>I\<rangle>\<^sub>ii_list, \<langle>I\<rangle>\<^sub>ii_list\<rangle>\<^sub>ii_prod\<rangle>\<^sub>ii_option"
"red_dfs ::\<^sub>i \<langle>I\<rangle>\<^sub>ii_slg \<rightarrow>\<^sub>i \<langle>I\<rangle>\<^sub>ii_set \<rightarrow>\<^sub>i \<langle>I\<rangle>\<^sub>ii_set \<rightarrow>\<^sub>i I
\<rightarrow>\<^sub>i \<langle>\<langle>\<langle>I\<rangle>\<^sub>ii_set, i_red_wit I\<rangle>\<^sub>ii_prod\<rangle>\<^sub>ii_nres"
"blue_dfs ::\<^sub>i i_bg i_unit I
\<rightarrow>\<^sub>i \<langle>\<langle>\<langle>\<langle>I\<rangle>\<^sub>ii_list, \<langle>I\<rangle>\<^sub>ii_list\<rangle>\<^sub>ii_prod\<rangle>\<^sub>ii_option\<rangle>\<^sub>ii_nres"
by auto
context begin interpretation autoref_syn .
term lasso_rel_ext
lemma autoref_wit[autoref_rules_raw]:
"(NO_CYC,NO_CYC)\<in>blue_wit_rel"
"((=), (=)) \<in> blue_wit_rel \<rightarrow> blue_wit_rel \<rightarrow> bool_rel"
"\<And>R. PREFER_id R
\<Longrightarrow> (init_wit_blue, init_wit_blue) \<in> R \<rightarrow> red_wit_rel R \<rightarrow> blue_wit_rel"
"\<And>R. PREFER_id R
\<Longrightarrow> (init_wit_blue_early, init_wit_blue_early) \<in> R \<rightarrow> R \<rightarrow> blue_wit_rel"
"\<And>R. PREFER_id R
\<Longrightarrow> (prep_wit_blue,prep_wit_blue)\<in>R \<rightarrow> blue_wit_rel \<rightarrow> blue_wit_rel"
"\<And>R. PREFER_id R
\<Longrightarrow> (red_init_witness, red_init_witness) \<in> R\<rightarrow>R\<rightarrow>red_wit_rel R"
"\<And>R. PREFER_id R
\<Longrightarrow> (prep_wit_red,prep_wit_red) \<in> R \<rightarrow> red_wit_rel R \<rightarrow> red_wit_rel R"
"\<And>R. PREFER_id R
\<Longrightarrow> (extract_res,extract_res)
\<in> blue_wit_rel \<rightarrow> \<langle>\<langle>R\<rangle>list_rel\<times>\<^sub>r\<langle>R\<rangle>list_rel\<rangle>option_rel"
by (simp_all)
subsubsection \<open>Actual Refinement\<close>
term red_dfs
term "map2set_rel (rbt_map_rel ord)"
term rbt_set_rel
schematic_goal red_dfs_refine_aux: "(?f::?'c, red_dfs::(('a::linorder \<times> _) set\<Rightarrow>_)) \<in> ?R"
supply [autoref_tyrel] = ty_REL[where 'a="'a set" and R="\<langle>Id\<rangle>dflt_rs_rel"]
unfolding red_dfs_def[abs_def]
apply (autoref (trace,keep_goal))
done
concrete_definition impl_red_dfs uses red_dfs_refine_aux
lemma impl_red_dfs_autoref[autoref_rules]:
fixes R :: "('a\<times>'a::linorder) set"
assumes "PREFER_id R"
shows "(impl_red_dfs, red_dfs) \<in>
\<langle>R\<rangle>slg_rel \<rightarrow> \<langle>R\<rangle>dflt_rs_rel \<rightarrow> \<langle>R\<rangle>dflt_rs_rel \<rightarrow> R
\<rightarrow> \<langle>\<langle>R\<rangle>dflt_rs_rel \<times>\<^sub>r red_wit_rel R\<rangle>nres_rel"
using assms impl_red_dfs.refine by simp
thm autoref_itype(1-10)
schematic_goal code_red_dfs_aux:
shows "RETURN ?c \<le> impl_red_dfs E onstack V u"
unfolding impl_red_dfs_def
by (refine_transfer (post) the_resI)
concrete_definition code_red_dfs uses code_red_dfs_aux
prepare_code_thms code_red_dfs_def
declare code_red_dfs.refine[refine_transfer]
export_code code_red_dfs checking SML
schematic_goal red_dfs_hash_refine_aux: "(?f::?'c, red_dfs::(('a::hashable \<times> _) set\<Rightarrow>_)) \<in> ?R"
supply [autoref_tyrel] = ty_REL[where 'a="'a set" and R="\<langle>Id\<rangle>hs.rel"]
unfolding red_dfs_def[abs_def]
apply (autoref (trace,keep_goal))
done
concrete_definition impl_red_dfs_hash uses red_dfs_hash_refine_aux
thm impl_red_dfs_hash.refine
lemma impl_red_dfs_hash_autoref[autoref_rules]:
fixes R :: "('a\<times>'a::hashable) set"
assumes "PREFER_id R"
shows "(impl_red_dfs_hash, red_dfs) \<in>
\<langle>R\<rangle>slg_rel \<rightarrow> \<langle>R\<rangle>hs.rel \<rightarrow> \<langle>R\<rangle>hs.rel \<rightarrow> R
\<rightarrow> \<langle>\<langle>R\<rangle>hs.rel \<times>\<^sub>r red_wit_rel R\<rangle>nres_rel"
using assms impl_red_dfs_hash.refine by simp
schematic_goal code_red_dfs_hash_aux:
shows "RETURN ?c \<le> impl_red_dfs_hash E onstack V u"
unfolding impl_red_dfs_hash_def
by (refine_transfer (post) the_resI)
concrete_definition code_red_dfs_hash uses code_red_dfs_hash_aux
prepare_code_thms code_red_dfs_hash_def
declare code_red_dfs_hash.refine[refine_transfer]
export_code code_red_dfs_hash checking SML
schematic_goal red_dfs_ahs_refine_aux: "(?f::?'c, red_dfs::(('a::hashable \<times> _) set\<Rightarrow>_)) \<in> ?R"
supply [autoref_tyrel] = ty_REL[where 'a="'a::hashable set" and R="\<langle>Id\<rangle>ahs.rel"]
unfolding red_dfs_def[abs_def]
apply (autoref (trace,keep_goal))
done
concrete_definition impl_red_dfs_ahs uses red_dfs_ahs_refine_aux
lemma impl_red_dfs_ahs_autoref[autoref_rules]:
fixes R :: "('a\<times>'a::hashable) set"
assumes "PREFER_id R"
shows "(impl_red_dfs_ahs, red_dfs) \<in>
\<langle>R\<rangle>slg_rel \<rightarrow> \<langle>R\<rangle>ahs.rel \<rightarrow> \<langle>R\<rangle>ahs.rel \<rightarrow> R
\<rightarrow> \<langle>\<langle>R\<rangle>ahs.rel \<times>\<^sub>r red_wit_rel R\<rangle>nres_rel"
using assms impl_red_dfs_ahs.refine by simp
schematic_goal code_red_dfs_ahs_aux:
shows "RETURN ?c \<le> impl_red_dfs_ahs E onstack V u"
unfolding impl_red_dfs_ahs_def
by (refine_transfer the_resI)
concrete_definition code_red_dfs_ahs uses code_red_dfs_ahs_aux
prepare_code_thms code_red_dfs_ahs_def
declare code_red_dfs_ahs.refine[refine_transfer]
export_code code_red_dfs_ahs checking SML
(*abbreviation "blue_dfs_annot E A u \<equiv> blue_dfs E (A:::\<^sub>r\<langle>Id\<rangle>fun_set_rel) u"*)
schematic_goal blue_dfs_refine_aux: "(?f::?'c, blue_dfs::('a::linorder b_graph_rec\<Rightarrow>_)) \<in> ?R"
supply [autoref_tyrel] =
ty_REL[where 'a="'a" and R="Id"]
ty_REL[where 'a="'a set" and R="\<langle>Id\<rangle>dflt_rs_rel"]
unfolding blue_dfs_def[abs_def]
apply (autoref (trace,keep_goal))
done
concrete_definition impl_blue_dfs uses blue_dfs_refine_aux
thm impl_blue_dfs.refine
lemma impl_blue_dfs_autoref[autoref_rules]:
fixes R :: "('a \<times> 'a::linorder) set"
assumes "PREFER_id R"
shows "(impl_blue_dfs, blue_dfs)
\<in> bg_impl_rel_ext unit_rel R
\<rightarrow> \<langle>\<langle>\<langle>R\<rangle>list_rel \<times>\<^sub>r \<langle>R\<rangle>list_rel\<rangle>Relators.option_rel\<rangle>nres_rel"
using assms impl_blue_dfs.refine by simp
schematic_goal code_blue_dfs_aux:
shows "RETURN ?c \<le> impl_blue_dfs G"
unfolding impl_blue_dfs_def
apply (refine_transfer (post) the_resI
order_trans[OF det_RETURN code_red_dfs.refine])
done
concrete_definition code_blue_dfs uses code_blue_dfs_aux
prepare_code_thms code_blue_dfs_def
declare code_blue_dfs.refine[refine_transfer]
export_code code_blue_dfs checking SML
schematic_goal blue_dfs_hash_refine_aux: "(?f::?'c, blue_dfs::('a::hashable b_graph_rec\<Rightarrow>_)) \<in> ?R"
supply [autoref_tyrel] =
ty_REL[where 'a="'a" and R="Id"]
ty_REL[where 'a="'a::hashable set" and R="\<langle>Id\<rangle>hs.rel"]
unfolding blue_dfs_def[abs_def]
using [[autoref_trace_failed_id]]
apply (autoref (trace,keep_goal))
done
concrete_definition impl_blue_dfs_hash uses blue_dfs_hash_refine_aux
lemma impl_blue_dfs_hash_autoref[autoref_rules]:
fixes R :: "('a \<times> 'a::hashable) set"
assumes "PREFER_id R"
shows "(impl_blue_dfs_hash, blue_dfs) \<in> bg_impl_rel_ext unit_rel R
\<rightarrow> \<langle>\<langle>\<langle>R\<rangle>list_rel \<times>\<^sub>r \<langle>R\<rangle>list_rel\<rangle>Relators.option_rel\<rangle>nres_rel"
using assms impl_blue_dfs_hash.refine by simp
schematic_goal code_blue_dfs_hash_aux:
shows "RETURN ?c \<le> impl_blue_dfs_hash G"
unfolding impl_blue_dfs_hash_def
apply (refine_transfer the_resI
order_trans[OF det_RETURN code_red_dfs_hash.refine])
done
concrete_definition code_blue_dfs_hash uses code_blue_dfs_hash_aux
prepare_code_thms code_blue_dfs_hash_def
declare code_blue_dfs_hash.refine[refine_transfer]
export_code code_blue_dfs_hash checking SML
schematic_goal blue_dfs_ahs_refine_aux: "(?f::?'c, blue_dfs::('a::hashable b_graph_rec\<Rightarrow>_)) \<in> ?R"
supply [autoref_tyrel] =
ty_REL[where 'a="'a" and R="Id"]
ty_REL[where 'a="'a::hashable set" and R="\<langle>Id\<rangle>ahs.rel"]
unfolding blue_dfs_def[abs_def]
apply (autoref (trace,keep_goal))
done
concrete_definition impl_blue_dfs_ahs uses blue_dfs_ahs_refine_aux
lemma impl_blue_dfs_ahs_autoref[autoref_rules]:
fixes R :: "('a \<times> 'a::hashable) set"
assumes "MINOR_PRIO_TAG 5"
assumes "PREFER_id R"
shows "(impl_blue_dfs_ahs, blue_dfs) \<in> bg_impl_rel_ext unit_rel R
\<rightarrow> \<langle>\<langle>\<langle>R\<rangle>list_rel \<times>\<^sub>r \<langle>R\<rangle>list_rel\<rangle>Relators.option_rel\<rangle>nres_rel"
using assms impl_blue_dfs_ahs.refine by simp
thm impl_blue_dfs_ahs_def
schematic_goal code_blue_dfs_ahs_aux:
shows "RETURN ?c \<le> impl_blue_dfs_ahs G"
unfolding impl_blue_dfs_ahs_def
apply (refine_transfer the_resI
order_trans[OF det_RETURN code_red_dfs_ahs.refine])
done
concrete_definition code_blue_dfs_ahs uses code_blue_dfs_ahs_aux
prepare_code_thms code_blue_dfs_ahs_def
declare code_blue_dfs_ahs.refine[refine_transfer]
export_code code_blue_dfs_ahs checking SML
text \<open>Correctness theorem\<close>
theorem code_blue_dfs_correct:
assumes G: "b_graph G" "finite ((g_E G)\<^sup>* `` g_V0 G)"
assumes REL: "(Gi,G)\<in>bg_impl_rel_ext unit_rel Id"
shows "RETURN (code_blue_dfs Gi) \<le> SPEC (\<lambda>r.
case r of None \<Rightarrow> \<forall>prpl. \<not>b_graph.is_lasso_prpl G prpl
| Some L \<Rightarrow> b_graph.is_lasso_prpl G L)"
proof -
note code_blue_dfs.refine
also note impl_blue_dfs.refine[param_fo, OF REL, THEN nres_relD]
also note blue_dfs_correct[OF G]
finally show ?thesis by (simp cong: option.case_cong)
qed
theorem code_blue_dfs_correct':
assumes G: "b_graph G" "finite ((g_E G)\<^sup>* `` g_V0 G)"
assumes REL: "(Gi,G)\<in>bg_impl_rel_ext unit_rel Id"
shows "case code_blue_dfs Gi of
None \<Rightarrow> \<forall>prpl. \<not>b_graph.is_lasso_prpl G prpl
| Some L \<Rightarrow> b_graph.is_lasso_prpl G L"
using code_blue_dfs_correct[OF G REL]
by simp
theorem code_blue_dfs_hash_correct:
assumes G: "b_graph G" "finite ((g_E G)\<^sup>* `` g_V0 G)"
assumes REL: "(Gi,G)\<in>bg_impl_rel_ext unit_rel Id"
shows "RETURN (code_blue_dfs_hash Gi) \<le> SPEC (\<lambda>r.
case r of None \<Rightarrow> \<forall>prpl. \<not>b_graph.is_lasso_prpl G prpl
| Some L \<Rightarrow> b_graph.is_lasso_prpl G L)"
proof -
note code_blue_dfs_hash.refine
also note impl_blue_dfs_hash.refine[param_fo, OF REL, THEN nres_relD]
also note blue_dfs_correct[OF G]
finally show ?thesis by (simp cong: option.case_cong)
qed
theorem code_blue_dfs_hash_correct':
assumes G: "b_graph G" "finite ((g_E G)\<^sup>* `` g_V0 G)"
assumes REL: "(Gi,G)\<in>bg_impl_rel_ext unit_rel Id"
shows "case code_blue_dfs_hash Gi of
None \<Rightarrow> \<forall>prpl. \<not>b_graph.is_lasso_prpl G prpl
| Some L \<Rightarrow> b_graph.is_lasso_prpl G L"
using code_blue_dfs_hash_correct[OF G REL]
by simp
theorem code_blue_dfs_ahs_correct:
assumes G: "b_graph G" "finite ((g_E G)\<^sup>* `` g_V0 G)"
assumes REL: "(Gi,G)\<in>bg_impl_rel_ext unit_rel Id"
shows "RETURN (code_blue_dfs_ahs Gi) \<le> SPEC (\<lambda>r.
case r of None \<Rightarrow> \<forall>prpl. \<not>b_graph.is_lasso_prpl G prpl
| Some L \<Rightarrow> b_graph.is_lasso_prpl G L)"
proof -
note code_blue_dfs_ahs.refine
also note impl_blue_dfs_ahs.refine[param_fo, OF REL, THEN nres_relD]
also note blue_dfs_correct[OF G]
finally show ?thesis by (simp cong: option.case_cong)
qed
theorem code_blue_dfs_ahs_correct':
assumes G: "b_graph G" "finite ((g_E G)\<^sup>* `` g_V0 G)"
assumes REL: "(Gi,G)\<in>bg_impl_rel_ext unit_rel Id"
shows "case code_blue_dfs_ahs Gi of
None \<Rightarrow> \<forall>prpl. \<not>b_graph.is_lasso_prpl G prpl
| Some L \<Rightarrow> b_graph.is_lasso_prpl G L"
using code_blue_dfs_ahs_correct[OF G REL]
by simp
text \<open>Export for benchmarking\<close>
schematic_goal acc_of_list_impl_hash:
notes [autoref_tyrel] =
ty_REL[where 'a="nat set" and R="\<langle>nat_rel\<rangle>iam_set_rel"]
shows "(?f::?'c,\<lambda>l::nat list.
let s=(set l):::\<^sub>r\<langle>nat_rel\<rangle>iam_set_rel
in (\<lambda>x::nat. x\<in>s)
) \<in> ?R"
apply (autoref (keep_goal))
done
concrete_definition acc_of_list_impl_hash uses acc_of_list_impl_hash
export_code acc_of_list_impl_hash checking SML
definition "code_blue_dfs_nat
\<equiv> code_blue_dfs :: _ \<Rightarrow> (nat list \<times> _) option"
definition "code_blue_dfs_hash_nat
\<equiv> code_blue_dfs_hash :: _ \<Rightarrow> (nat list \<times> _) option"
definition "code_blue_dfs_ahs_nat
\<equiv> code_blue_dfs_ahs :: _ \<Rightarrow> (nat list \<times> _) option"
definition "succ_of_list_impl_int \<equiv>
succ_of_list_impl o map (\<lambda>(u,v). (nat_of_integer u, nat_of_integer v))"
definition "acc_of_list_impl_hash_int \<equiv>
acc_of_list_impl_hash o map nat_of_integer"
export_code
code_blue_dfs_nat
code_blue_dfs_hash_nat
code_blue_dfs_ahs_nat
succ_of_list_impl_int
acc_of_list_impl_hash_int
nat_of_integer
integer_of_nat
lasso_ext
in SML module_name HPY_new_hash
file \<open>nested_dfs_hash.sml\<close>
end
|
If $f$ is a polynomial function, then there exists a constant $M$ such that for all $z$ with $|z| > M$, we have $|f(z)| \leq e |z|^{n+1}$. |
From mathcomp Require Import all_ssreflect.
Require Import vds_sort.
Require Import Coq.Sorting.Permutation.
Section Define.
Inductive color : Type := Red | Black.
Inductive tree : Type :=
| E : tree
| T : color -> tree -> nat -> tree -> tree.
Definition empty := E.
Fixpoint flatten t :=
match t with
| E => [::]
| T _ l v r => flatten l ++ (v :: flatten r)
end.
End Define.
Section Query.
Fixpoint member (n : nat) (t : tree) : bool :=
match t with
| E => false
| T _ l v r => if n < v
then member n l
else if n == v then true
else member n r
end.
Lemma member_in t n : member n t -> n \in (flatten t).
Proof.
elim: t => [|c l IHl v r IHr] //=.
case: ifP => Hlt.
move => H. rewrite mem_cat IHl. by rewrite orTb. exact.
case: ifP => Heq. move => H {H}.
by rewrite mem_cat in_cons Heq //= orbT.
move => H. rewrite mem_cat in_cons IHr. by rewrite orbA orbT. exact.
Qed.
Fixpoint height t : nat :=
match t with
| E => 0
| T _ l _ r => 1 + max (height l) (height r)
end.
Fixpoint tree_size t : nat :=
match t with
| E => 0
| T _ l _ r => 1 + tree_size l + tree_size r
end.
Lemma tree_sizeK t : tree_size t = size (flatten t).
Proof.
elim: t => [| c l IHl v r IHr] //=.
rewrite size_cat //= IHl IHr. rewrite -[in RHS]addn1.
by rewrite addnA -[in LHS]addnA [in LHS]addnC.
Qed.
End Query.
(* tactic written by Jacques Garrigue *)
Ltac decompose_rewrite :=
let H := fresh "H" in
move/andP=>[] || (move=>H; try rewrite H; try rewrite (eqP H)).
Section Insert.
Definition balanceL c l v r :=
match c, l with
| Black, T Red (T Red a x b) y c
| Black, T Red a x (T Red b y c)
=> T Red (T Black a x b) y (T Black c v r)
| _, _ => T c l v r
end.
Definition balanceR c l v r :=
match c, r with
| Black, T Red (T Red b y c) z d
| Black, T Red b y (T Red c z d)
=> T Red (T Black l v b) y (T Black c z d)
| _, _ => T c l v r
end.
Fixpoint ins x t :=
match t with
| E => T Red E x E
| T c l v r as s =>
if x < v
then balanceL c (ins x l) v r
else if x > v
then balanceR c l v (ins x r)
else s
end.
Definition insert x t :=
match ins x t with
| E => E (* impossible *)
| T _ l v r => T Black l v r
end.
Fixpoint is_redblack (t : tree) ctxt bh :=
match t with
| E => bh == 0
| T c l _ r =>
match c, ctxt with
| Red, Red => false (* red child can't have red parent *)
| Red, Black => is_redblack l Red bh && is_redblack r Red bh
| Black, _ => (bh > 0) && is_redblack l Black (bh.-1) && is_redblack r Black (bh.-1)
end
end.
Definition nearly_redblack (t : tree) bh :=
match t with
| T Red l _ r => is_redblack l Black bh && is_redblack r Black bh
| _ => is_redblack t Black bh
end.
Lemma is_redblack_red_black t n : is_redblack t Red n -> is_redblack t Black n.
Proof.
elim: t => [| c l IHl v r IHr] //=. case: c => //=.
Qed.
Lemma is_redblack_nearly_redblack c t n : is_redblack t c n ->
nearly_redblack t n.
Proof.
case: c; elim: t => [| tc l IHl v r IHr] //=; case: tc => //=.
move/andP => [Hl Hr]. by rewrite !is_redblack_red_black.
Qed.
Lemma balanceL_black_is_redblack l r v n :
nearly_redblack l n -> is_redblack r Black n ->
is_redblack (balanceL Black l v r) Black n.+1.
Proof.
case: l => [| [] [| [] lll llval llr] lval [| [] lrl lrval lrr]] //=;
repeat decompose_rewrite => //=;
try (by rewrite !is_redblack_red_black).
move/eqP in H1. by rewrite -!H1 !is_redblack_red_black.
Qed.
Lemma balanceR_black_is_redblack l r v n :
is_redblack l Black n -> nearly_redblack r n ->
is_redblack (balanceR Black l v r) Black n.+1.
Proof.
case: r => [| [] [| [] rll rlval rlr] rval [| [] rrl rrval rrr]] //=;
repeat decompose_rewrite => //=;
try (by rewrite !is_redblack_red_black).
move/eqP in H2. by rewrite -!H2 !is_redblack_red_black.
Qed.
Lemma ins_is_redblack (t : tree) x n :
(is_redblack t Black n -> nearly_redblack (ins x t) n) /\
(is_redblack t Red n -> is_redblack (ins x t) Black n).
Proof.
elim: t n => [| c l IHl v r IHr] n //.
rewrite //=. split => -> //.
have ins_black: (is_redblack (T Black l v r) Black n -> is_redblack (ins x (T Black l v r)) Black n).
{ rewrite {3}[Black]lock /= -lock => /andP [/andP [/prednK <- Hl] Hr].
case: ifP => _.
rewrite balanceL_black_is_redblack //; by apply IHl.
case: ifP => _. rewrite balanceR_black_is_redblack //; by apply IHr.
rewrite //=. rewrite succnK in Hl. rewrite succnK in Hr. by rewrite Hl Hr. }
split; case: c => //.
specialize IHl with n. specialize IHr with n.
move: IHl => [IHl_b IHl_r]. move: IHr => [IHr_b IHr_r].
move=> /= /andP [Hl Hr] //=.
case: ifP => _ //=. rewrite IHl_r. by rewrite is_redblack_red_black. exact.
case: ifP => _ //=. rewrite IHr_r. by rewrite is_redblack_red_black. exact.
rewrite !is_redblack_red_black; exact.
move/ins_black => H. by apply: (is_redblack_nearly_redblack Black).
Qed.
Lemma insert_is_redblack (t : tree) x n :
is_redblack t Red n -> exists n', is_redblack (insert x t) Red n'.
Proof.
exists (if (ins x t) is T Red _ _ _ then n.+1 else n).
move/(proj2 (ins_is_redblack t x n)): H.
rewrite /insert => //=. destruct ins => //=.
case: c => //= /andP [Hd1 Hd2].
by rewrite !is_redblack_red_black.
Qed.
End Insert.
Section BST.
Definition is_bst t := sorted (flatten t).
Lemma empty_is_bst : is_bst empty.
Proof. exact. Qed.
Fixpoint tree_all (pred : nat -> bool) t :=
match t with
| E => true
| T _ l v r => pred v && tree_all pred l && tree_all pred r
end.
Lemma tree_allK pred t : tree_all pred t = all pred (flatten t).
Proof.
elim: t => [| c l IHl v r IHr] //=.
by rewrite all_cat //= IHl IHr andbCA andbA.
Qed.
Fixpoint is_bst_rec (t : tree) :=
match t with
| E => true
| T _ l v r => is_bst_rec l && is_bst_rec r && tree_all (leq^~ v) l &&
tree_all [eta leq v] r
end.
Lemma is_bst_is_bst_rec : is_bst =1 is_bst_rec.
Proof.
rewrite /eqfun. move => t. elim: t => [| c l IHl v r IHr] //=.
rewrite -IHl -IHr /is_bst /= -sorted_cat_cons_e.
rewrite -sorted_cons_e. rewrite !tree_allK. rewrite -!andbA.
case: (all (leq^~ v) (flatten l)) => //=. by rewrite !andbF.
Qed.
Lemma balanceLK c l v r : flatten (balanceL c l v r) = flatten l ++ v :: flatten r.
Proof.
rewrite /balanceL; case c => //=;
case: l => [| [] [| [] lll llval llr] lval [| [] lrl lrval lrr]] //=;
try rewrite -!cat_cons; try rewrite !catA; try exact.
by rewrite -!catA cat_cons.
Qed.
Lemma balanceRK c l v r : flatten (balanceR c l v r) = flatten l ++ v :: flatten r.
Proof.
rewrite /balanceR; case c => //=;
case: r => [| [] [| [] rll rlval rlr] rval [| [] rrl rrval rrr]] //=;
try rewrite -!cat_cons; try rewrite !catA; try exact.
by rewrite -!catA cat_cons.
Qed.
Lemma insK x (t : tree) : is_bst t -> flatten (ins x t) = seq_insert x (flatten t).
Proof.
elim: t => [| c l IHl v r IHr] //=. move => H.
case Hlt: (x < v). rewrite balanceLK insert_cat_cons_l. rewrite IHl //=.
rewrite is_bst_is_bst_rec. rewrite is_bst_is_bst_rec /= -!andbA in H.
by move/and4P: H => [-> _ _ _]. by rewrite /is_bst in H.
by rewrite Hlt.
rewrite ltnNge leq_eqVlt Hlt orbF. case Heq: (x == v) => //=.
by rewrite (eqP Heq) insert_same.
rewrite balanceRK insert_cat_cons_r. rewrite IHr //=.
rewrite is_bst_is_bst_rec. rewrite is_bst_is_bst_rec /= -!andbA in H.
by move/and4P: H => [_ -> _ _]. by rewrite /is_bst in H.
by rewrite ltnNge leq_eqVlt Hlt Heq.
Qed.
Lemma insertK x (t : tree) : is_bst t -> flatten (insert x t) = seq_insert x (flatten t).
Proof.
move => H. rewrite /insert -insK. by case: ins. exact.
Qed.
Lemma insert_is_bst x t : is_bst t -> is_bst (insert x t).
Proof.
move => H. rewrite /is_bst. rewrite insertK. apply: sorted_insert.
by rewrite /is_bst in H. exact.
Qed.
Lemma tree_all_geq_trans t x y : tree_all (geq^~ x) t -> y <= x -> tree_all (geq^~ y) t.
Proof.
elim: t => [| c l IHl v r IHr] //=. rewrite -andbA.
move/and3P => [Hxv Hl Hr] Hyx. rewrite IHl; try (rewrite IHr); try exact.
rewrite !andbT. apply: leq_trans. apply: Hyx. apply: Hxv.
Qed.
Lemma tree_all_leq_trans t x y : tree_all (leq^~ x) t -> x <= y -> tree_all (leq^~ y) t.
Proof.
elim: t => [| c l IHl v r IHr] //=. rewrite -andbA.
move/and3P => [Hvx Hl Hr] Hxy. rewrite IHl; try (rewrite IHr); try exact.
rewrite !andbT. apply: leq_trans. apply: Hvx. apply: Hxy.
Qed.
Lemma balanceL_is_bst c l r x : is_bst_rec l -> is_bst_rec r -> tree_all (leq^~ x) l -> tree_all (geq^~ x) r -> is_bst_rec (balanceL c l x r).
Proof.
rewrite /balanceL. case: c => //=; case: l => [| [] [| [] lll llval llr] lval [| [] lrl lrval lrr]] //=; repeat decompose_rewrite; try exact.
by rewrite (@tree_all_geq_trans r x lrval).
by rewrite (@tree_all_geq_trans r x lval).
by rewrite (@tree_all_geq_trans r x lval).
by rewrite (@tree_all_geq_trans r x lval).
rewrite (@tree_all_leq_trans lll llval lrval).
rewrite (@tree_all_leq_trans llr lval lrval) //=.
rewrite (@tree_all_geq_trans r x lrval) //= !andbT.
all: (try apply: leq_trans; try apply: H7; try apply: H10; try exact).
Qed.
Lemma balanceR_is_bst c l r x : is_bst_rec l -> is_bst_rec r -> tree_all (leq^~ x) l -> tree_all (geq^~ x) r -> is_bst_rec (balanceR c l x r).
Proof.
rewrite /balanceR. case: c => //=; case: r => [| [] [| [] rll rlval rlr] rval [| [] rrl rrval rrr]] //=; repeat decompose_rewrite; try exact.
by rewrite (@tree_all_leq_trans l x rval).
by rewrite (@tree_all_leq_trans l x rlval).
rewrite (@tree_all_leq_trans l x rlval).
rewrite (@tree_all_geq_trans rrl rval rlval).
rewrite (@tree_all_geq_trans rrr rval rlval) //=. rewrite !andbT.
apply: leq_trans. apply: H8. apply: H11. all: try exact.
rewrite (@tree_all_leq_trans l x rlval).
rewrite (@tree_all_geq_trans rrl rval rlval).
rewrite (@tree_all_geq_trans rrr rval rlval) //= !andbT.
apply: leq_trans. apply: H8. apply: H11. all: try exact.
by rewrite (@tree_all_leq_trans l x rval).
Qed.
Lemma tree_all_balanceL pred c l r v : tree_all pred l && tree_all pred r &&
pred v = tree_all pred (balanceL c l v r).
Proof.
rewrite /balanceL. case: c => //=; case: l => [| [] [| [] lll llval llr] lval [| [] lrl lrval lrr]] //=;
repeat decompose_rewrite; try (rewrite !andbT); try (rewrite andbC);
try (rewrite -!andbA); try exact;
case: (pred v) => //=; try (by rewrite !andbF). by rewrite andbCA.
case: (pred lval) => //=; case: (pred lrval) => //=; case: (pred llval) => //=.
by rewrite !andbF.
Qed.
Lemma tree_all_balanceR pred c l r v : tree_all pred l && tree_all pred r &&
pred v = tree_all pred (balanceR c l v r).
Proof.
rewrite /balanceR. case: c => //=; case: r => [| [] [| [] rll rlval rlr] rval [| [] rrl rrval rrr]] //=; repeat decompose_rewrite;
try (rewrite !andbT); try (rewrite andbC);
try (rewrite -!andbA); try exact; case: (pred v) => //=;
try (case: (pred rval) => //=; case: (pred rlval) => //=);
try (by rewrite !andbF).
by rewrite andbCA.
Qed.
Lemma tree_all_ins pred t x : tree_all pred t && pred x = tree_all pred (ins x t).
Proof.
elim: t => [| c l IHl v r IHr] //=. by rewrite !andbT.
case: ifP => H; try (case: ifP => H'); try (rewrite -tree_all_balanceL -IHl);
try (rewrite -tree_all_balanceR -IHr);
case pv: (pred v) => //=; case px: (pred x) => //=; try (by rewrite !andbT); try (by rewrite !andbF).
by rewrite pv andbT.
have He: (v == x). apply: negbNE. by rewrite neq_ltn H H'.
by rewrite -(eqP He) pv in px.
by rewrite pv. by rewrite pv.
Qed.
Lemma ins_is_bst (t : tree) x : is_bst_rec t -> is_bst_rec (ins x t).
Proof.
elim: t => [| c l IHl v r IHr] //=.
rewrite -!andbA. move/and4P => [Hl Hr Hleq Hgeq].
case: ifP => Hlt.
apply: balanceL_is_bst; try exact. by apply: IHl.
by rewrite -tree_all_ins Hleq //= leq_eqVlt Hlt orbT.
case: ifP => Hlt'. apply: balanceR_is_bst; try exact. by apply: IHr.
rewrite -tree_all_ins. rewrite ltnNge in Hlt. move/negbFE in Hlt.
by rewrite /geq //= Hlt Hgeq.
by rewrite //= Hl Hr Hleq Hgeq.
Qed.
Lemma insert_is_bst_rec (t : tree) x : is_bst_rec t -> is_bst_rec (insert x t).
Proof.
move/(ins_is_bst t x). rewrite /insert => //=.
destruct ins => //=.
Qed.
End BST.
Section Membership.
Lemma all_gt_not_in x s : all [eta ltn x] s -> x \notin s.
Proof.
elim: s => [| h s IHs] //=. move/andP => [Hltn Hs].
rewrite in_cons negb_or. rewrite IHs. by rewrite neq_ltn Hltn.
exact.
Qed.
Lemma all_geq_gt_trans x y s : all [eta leq y] s -> x < y -> all [eta ltn x] s.
Proof.
elim: s => [| h s IHs] //=. move => /andP [Hyh Hy] Hxy.
rewrite IHs. rewrite andbT. apply: leq_trans. apply: Hxy. apply: Hyh. exact.
exact.
Qed.
Lemma all_lt_not_in x s : all (ltn^~ x) s -> x \notin s.
Proof.
elim: s => [| h s IHs] //=. move/andP => [Hltn Hs].
rewrite in_cons negb_or. rewrite IHs. by rewrite neq_ltn Hltn orbT.
exact.
Qed.
Lemma all_leq_lt_trans x y s : all (leq^~ x) s -> x < y -> all (ltn^~ y) s.
Proof.
elim: s => [| h s IHs] //=. move => /andP [Hyh Hy] Hxy.
rewrite IHs. rewrite andbT. apply: leq_ltn_trans. apply: Hyh. apply: Hxy.
exact. exact.
Qed.
Lemma memberK x t : (is_bst_rec t) -> member x t = (x \in (flatten t)).
Proof.
elim: t => [| c l IHl v r IHr] //=.
rewrite -!andbA. move/and4P => [Hl Hr Hleq Hgeq].
case: ifP => x_lt_v. rewrite mem_cat IHl.
have not_r: member x r = false.
{ apply/negbTE. rewrite tree_allK in Hgeq. rewrite IHr.
apply: all_gt_not_in. apply: all_geq_gt_trans. apply: Hgeq. exact.
exact. }
rewrite in_cons. rewrite -IHr. rewrite not_r orbF.
have neq_xv: (x == v) = false. apply/negbTE. by rewrite neq_ltn x_lt_v.
by rewrite neq_xv orbF. exact. exact.
case: ifP => Heq_xv. by rewrite mem_cat in_cons Heq_xv orbC.
rewrite mem_cat IHr.
have not_l: member x l = false.
{ apply/negbTE. rewrite tree_allK in Hleq. rewrite IHl.
apply: all_lt_not_in. apply: all_leq_lt_trans. apply: Hleq.
rewrite ltn_neqAle. by rewrite eq_sym negbT //= leqNgt x_lt_v. exact. }
rewrite in_cons. rewrite -IHl. by rewrite not_l //= Heq_xv.
exact. exact.
Qed.
End Membership.
Section TreeSort.
Fixpoint build_tree s :=
match s with
| [::] => E
| h :: t => insert h (build_tree t)
end.
Definition tree_sort s := flatten (build_tree s).
Lemma bst_sorted (t : tree) : is_bst_rec t = sorted (flatten t).
Proof. by rewrite -is_bst_is_bst_rec /is_bst. Qed.
Lemma tree_sort_sorted s : sorted (tree_sort s).
Proof.
rewrite /tree_sort. rewrite -bst_sorted.
elim: s => [| h s IHs] //=. by apply: insert_is_bst_rec.
Qed.
End TreeSort. |
module MaxHelpingHandCustomPlanets
using ..Ahorn, Maple
@mapdef Effect "MaxHelpingHand/CustomPlanets" CustomPlanets(only::String="*", exclude::String="", count::Number=32, color::String="", scrollx::Number=1.0, scrolly::Number=1.0,
speedx::Number=0.0, speedy::Number=0.0, directory::String="MaxHelpingHand/customplanets/bigstars", animationDelay::Number=0.1)
placements = CustomPlanets
function Ahorn.canFgBg(effect::CustomPlanets)
return true, true
end
function Ahorn.editingOptions(effect::CustomPlanets)
return Dict{String, Any}(
"directory" => String[
"MaxHelpingHand/customplanets/bigstars",
"MaxHelpingHand/customplanets/smallstars",
"MaxHelpingHand/customplanets/bigplanets",
"MaxHelpingHand/customplanets/smallplanets",
"MaxHelpingHand/customplanets/rainbowstars"
]
)
end
end
|
@testset "$TEST $G" begin
g = Network(10)
@test graphtype(g) == Network
@test digraphtype(g) == DiNetwork
@test edgetype(g) == IndexedEdge
@test vertextype(g) == Int
g = DiNetwork(10)
@test graphtype(g) == Network
@test digraphtype(g) == DiNetwork
@test edgetype(g) == IndexedEdge
@test vertextype(g) == Int
end # testset
|
Formal statement is: lemma discrete_subset_disconnected: fixes S :: "'a::topological_space set" fixes t :: "'b::real_normed_vector set" assumes conf: "continuous_on S f" and no: "\<And>x. x \<in> S \<Longrightarrow> \<exists>e>0. \<forall>y. y \<in> S \<and> f y \<noteq> f x \<longrightarrow> e \<le> norm (f y - f x)" shows "f ` S \<subseteq> {y. connected_component_set (f ` S) y = {y}}" Informal statement is: If $f$ is a continuous function from a set $S$ to a normed vector space $V$ such that for every $x \in S$, there exists an $\epsilon > 0$ such that for all $y \in S$ with $f(y) \neq f(x)$, we have $\epsilon \leq \|f(y) - f(x)\|$, then the image of $f$ is a discrete set. |
Formal statement is: lemma open_cbox_convex: fixes x :: "'a::euclidean_space" assumes x: "x \<in> box a b" and y: "y \<in> cbox a b" and e: "0 < e" "e \<le> 1" shows "(e *\<^sub>R x + (1 - e) *\<^sub>R y) \<in> box a b" Informal statement is: If $x$ and $y$ are in the closed box $[a,b]$ and $0 < e \leq 1$, then $e x + (1-e) y$ is in the open box $(a,b)$. |
Formal statement is: lemma contour_integrable_negatepath: assumes \<gamma>: "valid_path \<gamma>" and pi: "(\<lambda>z. f (- z)) contour_integrable_on \<gamma>" shows "f contour_integrable_on (uminus \<circ> \<gamma>)" Informal statement is: If $f$ is contour-integrable on $\gamma$, then $f$ is contour-integrable on $-\gamma$. |
Formal statement is: lemma power_eq_1_iff: fixes w :: "'a::real_normed_div_algebra" shows "w ^ n = 1 \<Longrightarrow> norm w = 1 \<or> n = 0" Informal statement is: If $w^n = 1$, then either $w$ has norm 1 or $n = 0$. |
#' @export
Prepare.strata.data <- function (data) {
#data in frame like Scallopsurveydata
if(any(names(data) %in% 'STRATA.ID')) data$Strata <- data$STRATA.ID
if(any(names(data) %in% 'strat')) data$Strata <- data$strat
w <- regexpr("_", names(data))
wincr <- attr(w, "match.length") - 1
wincr[wincr < 0] <- 0
if(any(w>0)){ ii = which(w>0); substring(names(data)[ii], w[ii], w[ii] + wincr[ii]) <- "."}
names(data)[charmatch("time", names(data))] <- "Time"
oldClass(data) <- c("data.frame", "strata.data")
data
}
|
Formal statement is: lemma differentiable_on_polynomial_function: fixes f :: "_ \<Rightarrow> 'a::euclidean_space" shows "polynomial_function f \<Longrightarrow> f differentiable_on S" Informal statement is: If $f$ is a polynomial function, then $f$ is differentiable on $S$. |
Bern Nix – guitar
|
[STATEMENT]
lemma (in Module) ex_extensionTr:"\<lbrakk>R module N; free_generator R M H;
f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1;
g \<in> mHom R (mdl M (fgs R M H1)) N;
x \<in> fgs R M H1 \<minusplus> (fgs R M {h})\<rbrakk> \<Longrightarrow>
\<exists>k1\<in> fgs R M H1. \<exists>k2\<in>fgs R M {h}. x = k1 \<plusminus> k2 \<and>
(THE y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub>
(monofun R M N f H h h2)) = g k1 \<plusminus>\<^bsub>N\<^esub> (monofun R M N f H h k2)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}\<rbrakk> \<Longrightarrow> \<exists>k1\<in>fgs R M H1. \<exists>k2\<in>fgs R M {h}. x = k1 \<plusminus> k2 \<and> (THE y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2) = g k1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h k2
[PROOF STEP]
apply (frule free_generator_sub)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M\<rbrakk> \<Longrightarrow> \<exists>k1\<in>fgs R M H1. \<exists>k2\<in>fgs R M {h}. x = k1 \<plusminus> k2 \<and> (THE y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2) = g k1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h k2
[PROOF STEP]
apply (frule sSum_eq[THEN sym, of N H H1 h], assumption+, simp,
simp)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}\<rbrakk> \<Longrightarrow> \<exists>k1\<in>fgs R M H1. \<exists>k2\<in>fgs R M {h}. x = k1 \<plusminus> k2 \<and> (THE y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2) = g k1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h k2
[PROOF STEP]
apply (subgoal_tac "\<exists>!y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and>
y = g h1 \<plusminus>\<^bsub>N\<^esub> (monofun R M N f H h h2)",
subgoal_tac "\<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and>
(THE y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and>
y = g h1 \<plusminus>\<^bsub>N\<^esub> (monofun R M N f H h h2)) = g h1 \<plusminus>\<^bsub>N\<^esub> (monofun R M N f H h h2)")
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}; \<exists>!y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> (THE y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2) = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2\<rbrakk> \<Longrightarrow> \<exists>k1\<in>fgs R M H1. \<exists>k2\<in>fgs R M {h}. x = k1 \<plusminus> k2 \<and> (THE y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2) = g k1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h k2
2. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}; \<exists>!y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2\<rbrakk> \<Longrightarrow> \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> (THE y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2) = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2
3. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}\<rbrakk> \<Longrightarrow> \<exists>!y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2
[PROOF STEP]
prefer 2
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}; \<exists>!y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2\<rbrakk> \<Longrightarrow> \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> (THE y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2) = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2
2. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}; \<exists>!y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> (THE y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2) = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2\<rbrakk> \<Longrightarrow> \<exists>k1\<in>fgs R M H1. \<exists>k2\<in>fgs R M {h}. x = k1 \<plusminus> k2 \<and> (THE y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2) = g k1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h k2
3. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}\<rbrakk> \<Longrightarrow> \<exists>!y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2
[PROOF STEP]
apply (rule theI')
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}; \<exists>!y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2\<rbrakk> \<Longrightarrow> \<exists>!xa. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> xa = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2
2. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}; \<exists>!y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> (THE y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2) = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2\<rbrakk> \<Longrightarrow> \<exists>k1\<in>fgs R M H1. \<exists>k2\<in>fgs R M {h}. x = k1 \<plusminus> k2 \<and> (THE y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2) = g k1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h k2
3. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}\<rbrakk> \<Longrightarrow> \<exists>!y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2
[PROOF STEP]
apply simp
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}; \<exists>!y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> (THE y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2) = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2\<rbrakk> \<Longrightarrow> \<exists>k1\<in>fgs R M H1. \<exists>k2\<in>fgs R M {h}. x = k1 \<plusminus> k2 \<and> (THE y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2) = g k1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h k2
2. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}\<rbrakk> \<Longrightarrow> \<exists>!y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2
[PROOF STEP]
apply (thin_tac " \<exists>!y. \<exists>h1\<in>fgs R M H1.
\<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2")
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> (THE y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2) = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2\<rbrakk> \<Longrightarrow> \<exists>k1\<in>fgs R M H1. \<exists>k2\<in>fgs R M {h}. x = k1 \<plusminus> k2 \<and> (THE y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2) = g k1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h k2
2. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}\<rbrakk> \<Longrightarrow> \<exists>!y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2
[PROOF STEP]
apply blast
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}\<rbrakk> \<Longrightarrow> \<exists>!y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2
[PROOF STEP]
apply (rule ex_ex1I)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}\<rbrakk> \<Longrightarrow> \<exists>y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2
2. \<And>y ya. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> ya = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2\<rbrakk> \<Longrightarrow> y = ya
[PROOF STEP]
apply (thin_tac "fgs R M (insert h H1) = fgs R M H1 \<minusplus> (fgs R M {h})")
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M\<rbrakk> \<Longrightarrow> \<exists>y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2
2. \<And>y ya. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> ya = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2\<rbrakk> \<Longrightarrow> y = ya
[PROOF STEP]
apply (cut_tac fgs_sub_carrier[of H1], cut_tac fgs_sub_carrier[of "{h}"])
[PROOF STATE]
proof (prove)
goal (4 subgoals):
1. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M H1 \<subseteq> carrier M; fgs R M {h} \<subseteq> carrier M\<rbrakk> \<Longrightarrow> \<exists>y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2
2. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M H1 \<subseteq> carrier M\<rbrakk> \<Longrightarrow> {h} \<subseteq> carrier M
3. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M\<rbrakk> \<Longrightarrow> H1 \<subseteq> carrier M
4. \<And>y ya. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> ya = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2\<rbrakk> \<Longrightarrow> y = ya
[PROOF STEP]
apply (simp add:set_sum)
[PROOF STATE]
proof (prove)
goal (4 subgoals):
1. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; \<exists>ha\<in>fgs R M H1. \<exists>k\<in>fgs R M {h}. x = ha \<plusminus> k; H \<subseteq> carrier M; fgs R M H1 \<subseteq> carrier M; fgs R M {h} \<subseteq> carrier M\<rbrakk> \<Longrightarrow> \<exists>y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2
2. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M H1 \<subseteq> carrier M\<rbrakk> \<Longrightarrow> {h} \<subseteq> carrier M
3. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M\<rbrakk> \<Longrightarrow> H1 \<subseteq> carrier M
4. \<And>y ya. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> ya = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2\<rbrakk> \<Longrightarrow> y = ya
[PROOF STEP]
apply (erule bexE)+
[PROOF STATE]
proof (prove)
goal (4 subgoals):
1. \<And>ha k. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; H \<subseteq> carrier M; fgs R M H1 \<subseteq> carrier M; fgs R M {h} \<subseteq> carrier M; ha \<in> fgs R M H1; k \<in> fgs R M {h}; x = ha \<plusminus> k\<rbrakk> \<Longrightarrow> \<exists>y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2
2. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M H1 \<subseteq> carrier M\<rbrakk> \<Longrightarrow> {h} \<subseteq> carrier M
3. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M\<rbrakk> \<Longrightarrow> H1 \<subseteq> carrier M
4. \<And>y ya. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> ya = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2\<rbrakk> \<Longrightarrow> y = ya
[PROOF STEP]
apply (frule subsetD[of H "carrier M" h], assumption+)
[PROOF STATE]
proof (prove)
goal (4 subgoals):
1. \<And>ha k. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; H \<subseteq> carrier M; fgs R M H1 \<subseteq> carrier M; fgs R M {h} \<subseteq> carrier M; ha \<in> fgs R M H1; k \<in> fgs R M {h}; x = ha \<plusminus> k; h \<in> carrier M\<rbrakk> \<Longrightarrow> \<exists>y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2
2. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M H1 \<subseteq> carrier M\<rbrakk> \<Longrightarrow> {h} \<subseteq> carrier M
3. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M\<rbrakk> \<Longrightarrow> H1 \<subseteq> carrier M
4. \<And>y ya. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> ya = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2\<rbrakk> \<Longrightarrow> y = ya
[PROOF STEP]
apply (frule_tac x = k in monofun_mem[of N h H _ f], assumption+)
[PROOF STATE]
proof (prove)
goal (4 subgoals):
1. \<And>ha k. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; H \<subseteq> carrier M; fgs R M H1 \<subseteq> carrier M; fgs R M {h} \<subseteq> carrier M; ha \<in> fgs R M H1; k \<in> fgs R M {h}; x = ha \<plusminus> k; h \<in> carrier M; monofun R M N f H h k \<in> carrier N\<rbrakk> \<Longrightarrow> \<exists>y. \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2
2. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M H1 \<subseteq> carrier M\<rbrakk> \<Longrightarrow> {h} \<subseteq> carrier M
3. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M\<rbrakk> \<Longrightarrow> H1 \<subseteq> carrier M
4. \<And>y ya. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> ya = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2\<rbrakk> \<Longrightarrow> y = ya
[PROOF STEP]
apply blast
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M H1 \<subseteq> carrier M\<rbrakk> \<Longrightarrow> {h} \<subseteq> carrier M
2. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M\<rbrakk> \<Longrightarrow> H1 \<subseteq> carrier M
3. \<And>y ya. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> ya = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2\<rbrakk> \<Longrightarrow> y = ya
[PROOF STEP]
apply (rule subsetI, simp, simp add:subsetD,
rule subset_trans[of H1 H "carrier M"], assumption+)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>y ya. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; x \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2; \<exists>h1\<in>fgs R M H1. \<exists>h2\<in>fgs R M {h}. x = h1 \<plusminus> h2 \<and> ya = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2\<rbrakk> \<Longrightarrow> y = ya
[PROOF STEP]
apply ((erule bexE)+, (erule conjE)+, simp)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>y ya h1 h1a h2 h2a. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; h1 \<plusminus> h2 \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}; h1 \<in> fgs R M H1; h1a \<in> fgs R M H1; h2 \<in> fgs R M {h}; h2a \<in> fgs R M {h}; h1a \<plusminus> h2a = h1 \<plusminus> h2; y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2; x = h1 \<plusminus> h2; ya = g h1a \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2a\<rbrakk> \<Longrightarrow> g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2 = g h1a \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2a
[PROOF STEP]
apply (frule_tac ?x1.0 = h1a and ?x2.0 = h1 and ?y1.0 = h2a and ?y2.0 = h2
in sSum_unique[of N H H1 h], assumption+, simp, assumption+)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>y ya h1 h1a h2 h2a. \<lbrakk>R module N; free_generator R M H; f \<in> H \<rightarrow> carrier N; H1 \<subseteq> H; h \<in> H; h \<notin> H1; g \<in> mHom R (mdl M (fgs R M H1)) N; h1 \<plusminus> h2 \<in> fgs R M H1 \<minusplus> fgs R M {h}; H \<subseteq> carrier M; fgs R M (insert h H1) = fgs R M H1 \<minusplus> fgs R M {h}; h1 \<in> fgs R M H1; h1a \<in> fgs R M H1; h2 \<in> fgs R M {h}; h2a \<in> fgs R M {h}; h1a \<plusminus> h2a = h1 \<plusminus> h2; y = g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2; x = h1 \<plusminus> h2; ya = g h1a \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2a; h1a = h1 \<and> h2a = h2\<rbrakk> \<Longrightarrow> g h1 \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2 = g h1a \<plusminus>\<^bsub>N\<^esub> monofun R M N f H h h2a
[PROOF STEP]
apply ((erule conjE)+, simp)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
Require Import Crypto.Arithmetic.PrimeFieldTheorems.
Require Import Crypto.Specific.solinas32_2e489m21_19limbs.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.
|
Formal statement is: lemma Lim_dist_ubound: assumes "\<not>(trivial_limit net)" and "(f \<longlongrightarrow> l) net" and "eventually (\<lambda>x. dist a (f x) \<le> e) net" shows "dist a l \<le> e" Informal statement is: If $f$ converges to $l$ and $f$ is eventually within $e$ of $a$, then $l$ is within $e$ of $a$. |
{-# OPTIONS --without-K --safe #-}
module Definition.Typed.Consequences.Consistency where
open import Definition.Untyped
open import Definition.Typed
open import Definition.Typed.Properties
open import Definition.Typed.EqRelInstance
open import Definition.LogicalRelation
open import Definition.LogicalRelation.Irrelevance
open import Definition.LogicalRelation.ShapeView
open import Definition.LogicalRelation.Fundamental.Reducibility
open import Tools.Embedding
open import Tools.Empty
open import Tools.Product
import Tools.PropositionalEquality as PE
zero≢one′ : ∀ {Γ l} ([ℕ] : Γ ⊩⟨ l ⟩ℕ ℕ)
→ Γ ⊩⟨ l ⟩ zero ≡ suc zero ∷ ℕ / ℕ-intr [ℕ] → ⊥
zero≢one′ (noemb x) (ιx (ℕₜ₌ .(suc _) .(suc _) d d′ k≡k′ (sucᵣ x₁))) =
zero≢suc (whnfRed*Term (redₜ d) zeroₙ)
zero≢one′ (noemb x) (ιx (ℕₜ₌ .zero .zero d d′ k≡k′ zeroᵣ)) =
zero≢suc (PE.sym (whnfRed*Term (redₜ d′) sucₙ))
zero≢one′ (noemb x) (ιx (ℕₜ₌ k k′ d d′ k≡k′ (ne (neNfₜ₌ neK neM k≡m)))) =
zero≢ne neK (whnfRed*Term (redₜ d) zeroₙ)
zero≢one′ (emb 0<1 [ℕ]) (ιx n) = zero≢one′ [ℕ] n
-- Zero cannot be judgmentally equal to one.
zero≢one : ∀ {Γ} → Γ ⊢ zero ≡ suc zero ∷ ℕ → ⊥
zero≢one 0≡1 =
let [ℕ] , [0≡1] = reducibleEqTerm 0≡1
in zero≢one′ (ℕ-elim [ℕ]) (irrelevanceEqTerm [ℕ] (ℕ-intr (ℕ-elim [ℕ])) [0≡1])
|
#redirect E Street
|
/*---
Flow*: A Verification Tool for Cyber-Physical Systems.
Authors: Xin Chen, Sriram Sankaranarayanan, and Erika Abraham.
Email: Xin Chen <[email protected]> if you have questions or comments.
The code is released as is under the GNU General Public License (GPL).
---*/
#ifndef INCLUDE_H_
#define INCLUDE_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <cmath>
#include <mpfr.h>
#include <vector>
#include <string>
#include <list>
#include <iostream>
#include <cassert>
#include <map>
#include <time.h>
#include <algorithm>
#include <gsl/gsl_poly.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <glpk.h>
const int normal_precision = 53;
const int high_precision = 256;
#define MAX_REFINEMENT_STEPS 49
#define MAX_DYN_REF 49
#define MAX_WIDTH 1e-12
#define THRESHOLD_HIGH 1e-12
#define THRESHOLD_LOW 1e-20
#define STOP_RATIO 0.99
#define ABS_STOP_RATIO 0.99
#define PN 15 // the number of digits printed
#define INVALID -1e10
#define UNBOUNDED 1e10
#define DC_THRESHOLD_SEARCH 1e-6
#define DC_THRESHOLD_IMPROV 0.9
#define ID_PRE 0
#define QR_PRE 1
#define UNIFORM 0
#define MULTI 1
#define LAMBDA_DOWN 0.5
#define LAMBDA_UP 1.1
#define NAME_SIZE 100
#define UNSAFE -1
#define SAFE 0
#define UNKNOWN 1
#define COMPLETED_UNSAFE 1
#define COMPLETED_SAFE 2
#define COMPLETED_UNKNOWN 3
#define UNCOMPLETED_SAFE 4
#define UNCOMPLETED_UNSAFE 5
#define UNCOMPLETED_UNKNOWN 6
#define PLOT_GNUPLOT 0
#define PLOT_MATLAB 1
#define PLOT_INTERVAL 0
#define PLOT_OCTAGON 1
#define PLOT_GRID 2
#define INTERVAL_AGGREG 0
#define PARA_AGGREG 1
#define PCA_AGGREG 2
#define MSG_SIZE 100
#define NUM_LENGTH 50
#define ONLY_PICARD 1
#define LOW_DEGREE 2
#define HIGH_DEGREE 3
#define NONPOLY_TAYLOR 4
#define LTI 5
#define LTV 6
#define ONLY_PICARD_SYMB 7
#define NONPOLY_TAYLOR_SYMB 8
#define POLY_DYN 1
#define NONPOLY_DYN 2
#define LTI_DYN 3
#define LTV_DYN 4
#define REFINEMENT_PREC 1e-5
#define RESET_COLOR "\033[0m"
#define BLACK_COLOR "\033[30m"
#define RED_COLOR "\033[31m"
#define GREEN_COLOR "\033[32m"
#define BLUE_COLOR "\033[34m"
#define BOLD_FONT "\e[1m"
const char str_pi_up[] = "3.14159265358979323846264338327950288419716939937511";
const char str_pi_lo[] = "3.14159265358979323846264338327950288419716939937510";
const char outputDir[] = "./outputs/";
const char imageDir[] = "./images/";
const char counterexampleDir[] = "./counterexamples/";
const char local_var_name[] = "local_var_";
const char str_prefix_taylor_picard[] = "taylor picard { ";
const char str_prefix_taylor_remainder[] = "taylor remainder { ";
const char str_prefix_taylor_polynomial[] = "taylor polynomial { ";
const char str_prefix_center[] = "nonpolynomial center { ";
const char str_prefix_combination_picard[] = "combination picard { ";
const char str_prefix_combination_remainder[] = "combination remainder { ";
const char str_prefix_combination_polynomial[] = "combination polynomial { ";
const char str_prefix_univariate_polynomial[] = "univariate polynomial { ";
const char str_prefix_multivariate_polynomial[] = "multivariate polynomial { ";
const char str_prefix_expression[] = "expression { ";
const char str_prefix_matrix[] = "matrix { ";
const char str_suffix[] = " }";
const char str_counterexample_dumping_name_suffix[] = ".counterexample";
extern int lineNum;
extern void parseODE();
#endif /* INCLUDE_H_ */
|
lemma retract_of_homotopically_trivial: assumes ts: "T retract_of S" and hom: "\<And>f g. \<lbrakk>continuous_on U f; f ` U \<subseteq> S; continuous_on U g; g ` U \<subseteq> S\<rbrakk> \<Longrightarrow> homotopic_with_canon (\<lambda>x. True) U S f g" and "continuous_on U f" "f ` U \<subseteq> T" and "continuous_on U g" "g ` U \<subseteq> T" shows "homotopic_with_canon (\<lambda>x. True) U T f g" |
[STATEMENT]
lemma ssubst_insert_if:
"finite V \<Longrightarrow>
ssubst t (insert i V) F = (if i \<in> V then ssubst t V F
else subst i (F i) (ssubst t V F))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. finite V \<Longrightarrow> ssubst t (insert i V) F = (if i \<in> V then ssubst t V F else subst i (F i) (ssubst t V F))
[PROOF STEP]
by (simp add: ssubst_insert insert_absorb) |
State Before: α : Type u_1
β : Type ?u.731158
γ : Type ?u.731161
δ : Type ?u.731164
ι : Type ?u.731167
R : Type ?u.731170
R' : Type ?u.731173
m0 : MeasurableSpace α
inst✝² : MeasurableSpace β
inst✝¹ : MeasurableSpace γ
μ μ₁ μ₂ μ₃ ν ν' ν₁ ν₂ : Measure α
s s' t : Set α
inst✝ : SigmaFinite μ
hs : MeasurableSet s
⊢ ↑↑(restrict μ (⋃ (i : ℕ), spanningSets μ i)) s = ↑↑μ s State After: no goals Tactic: rw [iUnion_spanningSets, restrict_univ] |
Further disagreements existed about the design and character of the new building . Facsimile reconstruction , while feasible , was not seriously contemplated . There was a general agreement that the new building should also have a cultural as well as commercial purpose . While the Jewish Community of Zagreb envisioned a modern design reminiscent of the original synagogue , the Bet Israel advocated building a replica of the original synagogue 's facade , perceiving it as having a powerful symbolism . Opinions of architects , urban planners , and art historians were also divided along similar lines .
|
The queue function on the website is the estimated time before a slot is available to search for tickets, based on the length of time patrons at the front of the queue are taking to complete their transaction. At the beginning of the onsale, patrons have spent only a minute or so on their transaction, even if it's incomplete, and therefore the average wait time is very low. As patrons take the usual four or five minutes to complete transactions, the wait time will go up as the number of people in the queue ahead of you is multiplied by the time to complete transactions. Obviously, as you get closer to the front of the queue, the time will typically drop but may vary. Once you reach the front of the queue, the system will look for tickets for you. There is, however, no guarantee that patrons in front of you in the queue may not have exhausted the allocation. Please don't be concerned about variations in the wait time, this is part of the normal functioning of the website and doesn't affect your place in that queue. |
import algebra.group.defs
universe u
def incl {α : Type u} [has_mul α] (a b : α) : Prop :=
∃ c, a * c = b
infix ` ≼ `:50 := incl
instance {α : Type u} [has_mul α] : has_mul (option α) :=
⟨option.lift_or_get (*)⟩
@[simp] lemma none_mul {α : Type u} [has_mul α] (a : option α) : none * a = a :=
by cases a; refl
@[simp] lemma mul_none {α : Type u} [has_mul α] (a : option α) : a * none = a :=
by cases a; refl
@[simp] lemma some_mul_some {α : Type u} [has_mul α] (a b : α) :
some a * some b = some (a * b) := rfl
instance option.comm_semigroup {α : Type u} [comm_semigroup α] : comm_semigroup (option α) := {
mul_assoc := begin
intros a b c,
cases a,
{ rw [none_mul, none_mul], },
cases b,
{ rw [none_mul, mul_none], },
cases c,
{ rw [mul_none, mul_none], },
rw [some_mul_some, some_mul_some, some_mul_some, some_mul_some, mul_assoc],
end,
mul_comm := begin
intros a b,
cases a,
{ rw [none_mul, mul_none], },
cases b,
{ rw [none_mul, mul_none], },
rw [some_mul_some, some_mul_some, mul_comm],
end,
..option.has_mul,
}
@[simp] lemma none_incl {α : Type u} [comm_semigroup α] (a : option α) : none ≼ a :=
⟨a, none_mul a⟩
@[simp, refl] lemma incl_refl {α : Type u} [monoid α] (a : α) : a ≼ a :=
⟨1, mul_one a⟩
@[simp, trans] lemma incl_trans {α : Type u} [semigroup α] (a b c : α) :
a ≼ b → b ≼ c → a ≼ c :=
begin
rintro ⟨d, rfl⟩ ⟨e, rfl⟩,
refine ⟨d * e, _⟩,
rw mul_assoc,
end
@[simp] lemma option.some_incl_some {α : Type u} [monoid α] {a b : α} :
some a ≼ some b ↔ a ≼ b :=
begin
split,
{ rintro ⟨c, hc⟩,
cases c,
cases hc, refl,
refine ⟨c, _⟩, cases hc, refl, },
{ rintro ⟨c, hc⟩,
refine ⟨some c, _⟩, rw ← hc, refl, },
end
class resource_algebra (α : Type u) extends comm_semigroup α :=
(valid : set α)
(core : α → option α)
(core_mul_self (a : α) {ca : α} : core a = some ca → ca * a = a)
(core_core (a : α) {ca : α} : core a = some ca → core ca = some ca)
(core_mono_some (a b : α) {ca : α} : core a = some ca → a ≼ b → ∃ cb, core b = some cb)
(core_mono (a b : α) {ca : α} : core a = some ca → a ≼ b → core a ≼ core b)
(valid_mul (a b : α) : valid (a * b) → valid a)
prefix `✓ `:40 := resource_algebra.valid
structure frame {α : Type u} [resource_algebra α] (a : α) :=
(val : α)
(prop : ✓ val * a)
def resource_algebra.can_update
{α : Type u} [resource_algebra α] (a : α) (b : set α) : Prop :=
∀ f : frame a, ∃ f' : frame f.val, f'.val ∈ b
infixr ` ↝ᵣₐ `:25 := resource_algebra.can_update
lemma can_update_iff {α : Type u} [resource_algebra α] (a : α) (b : set α) :
a ↝ᵣₐ b ↔ ∀ f : α, ✓ f * a → ∃ f' ∈ b, ✓ f' * f :=
begin
split,
{ intros h f hf,
obtain ⟨f', hf'⟩ := h ⟨f, hf⟩,
exact ⟨f'.val, hf', f'.prop⟩, },
{ intros h f,
obtain ⟨f', hf₁, hf₂⟩ := h f.val f.prop,
exact ⟨⟨f', hf₂⟩, hf₁⟩, },
end
|
[STATEMENT]
lemma eqButUIDf_not_UID':
assumes eq1: "eqButUIDf frds frds1"
and uid: "(uid,uid') \<notin> {(UID1,UID2), (UID2,UID1)}"
shows "uid \<in>\<in> frds uid' \<longleftrightarrow> uid \<in>\<in> frds1 uid'"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
from uid
[PROOF STATE]
proof (chain)
picking this:
(uid, uid') \<notin> {(UID1, UID2), (UID2, UID1)}
[PROOF STEP]
have "(uid' = UID1 \<and> uid \<noteq> UID2)
\<or> (uid' = UID2 \<and> uid \<noteq> UID1)
\<or> (uid' \<notin> {UID1,UID2})" (is "?u1 \<or> ?u2 \<or> ?n12")
[PROOF STATE]
proof (prove)
using this:
(uid, uid') \<notin> {(UID1, UID2), (UID2, UID1)}
goal (1 subgoal):
1. uid' = UID1 \<and> uid \<noteq> UID2 \<or> uid' = UID2 \<and> uid \<noteq> UID1 \<or> uid' \<notin> {UID1, UID2}
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
uid' = UID1 \<and> uid \<noteq> UID2 \<or> uid' = UID2 \<and> uid \<noteq> UID1 \<or> uid' \<notin> {UID1, UID2}
goal (1 subgoal):
1. (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
uid' = UID1 \<and> uid \<noteq> UID2 \<or> uid' = UID2 \<and> uid \<noteq> UID1 \<or> uid' \<notin> {UID1, UID2}
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
uid' = UID1 \<and> uid \<noteq> UID2 \<or> uid' = UID2 \<and> uid \<noteq> UID1 \<or> uid' \<notin> {UID1, UID2}
goal (1 subgoal):
1. (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
proof (elim disjE)
[PROOF STATE]
proof (state)
goal (3 subgoals):
1. uid' = UID1 \<and> uid \<noteq> UID2 \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
2. uid' = UID2 \<and> uid \<noteq> UID1 \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
3. uid' \<notin> {UID1, UID2} \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
assume "?u1"
[PROOF STATE]
proof (state)
this:
uid' = UID1 \<and> uid \<noteq> UID2
goal (3 subgoals):
1. uid' = UID1 \<and> uid \<noteq> UID2 \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
2. uid' = UID2 \<and> uid \<noteq> UID1 \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
3. uid' \<notin> {UID1, UID2} \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
uid' = UID1 \<and> uid \<noteq> UID2
goal (3 subgoals):
1. uid' = UID1 \<and> uid \<noteq> UID2 \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
2. uid' = UID2 \<and> uid \<noteq> UID1 \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
3. uid' \<notin> {UID1, UID2} \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
uid' = UID1 \<and> uid \<noteq> UID2
[PROOF STEP]
have "uid \<in>\<in> remove1 UID2 (frds uid') \<longleftrightarrow> uid \<in>\<in> remove1 UID2 (frds1 uid')"
[PROOF STATE]
proof (prove)
using this:
uid' = UID1 \<and> uid \<noteq> UID2
goal (1 subgoal):
1. (uid \<in>\<in> remove1 UID2 (frds uid')) = (uid \<in>\<in> remove1 UID2 (frds1 uid'))
[PROOF STEP]
using eq1
[PROOF STATE]
proof (prove)
using this:
uid' = UID1 \<and> uid \<noteq> UID2
eqButUIDf frds frds1
goal (1 subgoal):
1. (uid \<in>\<in> remove1 UID2 (frds uid')) = (uid \<in>\<in> remove1 UID2 (frds1 uid'))
[PROOF STEP]
unfolding eqButUIDf_def
[PROOF STATE]
proof (prove)
using this:
uid' = UID1 \<and> uid \<noteq> UID2
eqButUIDl UID2 (frds UID1) (frds1 UID1) \<and> eqButUIDl UID1 (frds UID2) (frds1 UID2) \<and> (\<forall>uid. uid \<noteq> UID1 \<and> uid \<noteq> UID2 \<longrightarrow> frds uid = frds1 uid)
goal (1 subgoal):
1. (uid \<in>\<in> remove1 UID2 (frds uid')) = (uid \<in>\<in> remove1 UID2 (frds1 uid'))
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
(uid \<in>\<in> remove1 UID2 (frds uid')) = (uid \<in>\<in> remove1 UID2 (frds1 uid'))
goal (3 subgoals):
1. uid' = UID1 \<and> uid \<noteq> UID2 \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
2. uid' = UID2 \<and> uid \<noteq> UID1 \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
3. uid' \<notin> {UID1, UID2} \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
uid' = UID1 \<and> uid \<noteq> UID2
(uid \<in>\<in> remove1 UID2 (frds uid')) = (uid \<in>\<in> remove1 UID2 (frds1 uid'))
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
uid' = UID1 \<and> uid \<noteq> UID2
(uid \<in>\<in> remove1 UID2 (frds uid')) = (uid \<in>\<in> remove1 UID2 (frds1 uid'))
goal (1 subgoal):
1. (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
(uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
goal (2 subgoals):
1. uid' = UID2 \<and> uid \<noteq> UID1 \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
2. uid' \<notin> {UID1, UID2} \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. uid' = UID2 \<and> uid \<noteq> UID1 \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
2. uid' \<notin> {UID1, UID2} \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
assume "?u2"
[PROOF STATE]
proof (state)
this:
uid' = UID2 \<and> uid \<noteq> UID1
goal (2 subgoals):
1. uid' = UID2 \<and> uid \<noteq> UID1 \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
2. uid' \<notin> {UID1, UID2} \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
uid' = UID2 \<and> uid \<noteq> UID1
goal (2 subgoals):
1. uid' = UID2 \<and> uid \<noteq> UID1 \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
2. uid' \<notin> {UID1, UID2} \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
uid' = UID2 \<and> uid \<noteq> UID1
[PROOF STEP]
have "uid \<in>\<in> remove1 UID1 (frds uid') \<longleftrightarrow> uid \<in>\<in> remove1 UID1 (frds1 uid')"
[PROOF STATE]
proof (prove)
using this:
uid' = UID2 \<and> uid \<noteq> UID1
goal (1 subgoal):
1. (uid \<in>\<in> remove1 UID1 (frds uid')) = (uid \<in>\<in> remove1 UID1 (frds1 uid'))
[PROOF STEP]
using eq1
[PROOF STATE]
proof (prove)
using this:
uid' = UID2 \<and> uid \<noteq> UID1
eqButUIDf frds frds1
goal (1 subgoal):
1. (uid \<in>\<in> remove1 UID1 (frds uid')) = (uid \<in>\<in> remove1 UID1 (frds1 uid'))
[PROOF STEP]
unfolding eqButUIDf_def
[PROOF STATE]
proof (prove)
using this:
uid' = UID2 \<and> uid \<noteq> UID1
eqButUIDl UID2 (frds UID1) (frds1 UID1) \<and> eqButUIDl UID1 (frds UID2) (frds1 UID2) \<and> (\<forall>uid. uid \<noteq> UID1 \<and> uid \<noteq> UID2 \<longrightarrow> frds uid = frds1 uid)
goal (1 subgoal):
1. (uid \<in>\<in> remove1 UID1 (frds uid')) = (uid \<in>\<in> remove1 UID1 (frds1 uid'))
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
(uid \<in>\<in> remove1 UID1 (frds uid')) = (uid \<in>\<in> remove1 UID1 (frds1 uid'))
goal (2 subgoals):
1. uid' = UID2 \<and> uid \<noteq> UID1 \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
2. uid' \<notin> {UID1, UID2} \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
uid' = UID2 \<and> uid \<noteq> UID1
(uid \<in>\<in> remove1 UID1 (frds uid')) = (uid \<in>\<in> remove1 UID1 (frds1 uid'))
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
uid' = UID2 \<and> uid \<noteq> UID1
(uid \<in>\<in> remove1 UID1 (frds uid')) = (uid \<in>\<in> remove1 UID1 (frds1 uid'))
goal (1 subgoal):
1. (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
(uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
goal (1 subgoal):
1. uid' \<notin> {UID1, UID2} \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. uid' \<notin> {UID1, UID2} \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
assume "?n12"
[PROOF STATE]
proof (state)
this:
uid' \<notin> {UID1, UID2}
goal (1 subgoal):
1. uid' \<notin> {UID1, UID2} \<Longrightarrow> (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
uid' \<notin> {UID1, UID2}
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
uid' \<notin> {UID1, UID2}
goal (1 subgoal):
1. (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
using eq1
[PROOF STATE]
proof (prove)
using this:
uid' \<notin> {UID1, UID2}
eqButUIDf frds frds1
goal (1 subgoal):
1. (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
unfolding eqButUIDf_def
[PROOF STATE]
proof (prove)
using this:
uid' \<notin> {UID1, UID2}
eqButUIDl UID2 (frds UID1) (frds1 UID1) \<and> eqButUIDl UID1 (frds UID2) (frds1 UID2) \<and> (\<forall>uid. uid \<noteq> UID1 \<and> uid \<noteq> UID2 \<longrightarrow> frds uid = frds1 uid)
goal (1 subgoal):
1. (uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
(uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
(uid \<in>\<in> frds uid') = (uid \<in>\<in> frds1 uid')
goal:
No subgoals!
[PROOF STEP]
qed |
[STATEMENT]
lemma in_zmset_conv_pos_neg_disj: "x \<in>#\<^sub>z M \<longleftrightarrow> x \<in># mset_pos M \<or> x \<in># mset_neg M"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (x \<in>#\<^sub>z M) = (x \<in># mset_pos M \<or> x \<in># mset_neg M)
[PROOF STEP]
by (metis count_mset_pos in_diff_zcount mem_zmset_of mset_pos_neg_partition nat_code(2) not_in_iff zcount_ne_zero_iff) |
function ShowDMMWindow(dmm, dmm_conf, rev_state_dict, refresh_cnt, base)
CImGui.Begin("GDM8246 Digital Multimeter")
# DRAW DISPLAY INFO
draw_dmm_info("Secondary", " Primary")
draw_dmm_info(dmm_conf.secondary, "mV ",
dmm_conf.primary, "V")
CImGui.Text(" ")
CImGui.SameLine()
draw_dmm_info("RANG:", dmm_conf.range,
"FCT:", dmm_conf.crt_func)
# DRAW BUTTONS
draw_dmm_info(" DC mV ", " AC mV ", " DIODE ",
" REL ", " COMP ", " ", " SET ")
CImGui.Button(" DCV ") && begin
if dmm_conf.shift_btn.state == false
set_sense_func(dmm, dmm_conf.crt_chan, "DCV")
else
# set the range to mV??????
#set_sense_func(dmm, dmm_conf.crt_chan, "DCV")
end
end
CImGui.SameLine(),CImGui.Button(" ACV ")&& begin
if dmm_conf.shift_btn.state == false
set_sense_func(dmm, dmm_conf.crt_chan, "ACV")
else
# set the range to mV??????
#set_sense_func(dmm, dmm_conf.crt_chan, "DCV")
end
end
CImGui.SameLine(),CImGui.Button(" OHM ") && begin
if dmm_conf.shift_btn.state == false
set_sense_func(dmm, dmm_conf.crt_chan, "OHM")
else
set_sense_func(dmm, dmm_conf.crt_chan, "DIODE")
end
end
CImGui.SameLine(),CImGui.Button(" CONT ")
CImGui.SameLine(),CImGui.Button(" MAX/MIN")
CImGui.SameLine(),CImGui.Button(" UP ") && begin
#this should increase reange on current function
end
CImGui.SameLine()
# # hack for AUTO/MAN toggle button
if dmm_conf.auto_btn.state == false
CImGui.PushID(1)
CImGui.PushStyleColor(CImGui.ImGuiCol_Button, CImGui.HSV(dmm_conf.auto_btn.off_color...))
CImGui.PushStyleColor(CImGui.ImGuiCol_ButtonHovered, CImGui.HSV(dmm_conf.auto_btn.hover_color...))
CImGui.PushStyleColor(CImGui.ImGuiCol_ButtonActive, CImGui.HSV(dmm_conf.auto_btn.off_color...))
CImGui.Button(" MAN ") && begin
dmm_conf.auto_btn.state = !dmm_conf.auto_btn.state
# toggle autorange on
end
else
CImGui.PushID(1)
CImGui.PushStyleColor(CImGui.ImGuiCol_Button, CImGui.HSV(dmm_conf.auto_btn.on_color...))
CImGui.PushStyleColor(CImGui.ImGuiCol_ButtonHovered, CImGui.HSV(dmm_conf.auto_btn.hover_color...))
CImGui.PushStyleColor(CImGui.ImGuiCol_ButtonActive, CImGui.HSV(dmm_conf.auto_btn.on_color...))
CImGui.Button(" AUTO ") && begin
dmm_conf.auto_btn.state = !dmm_conf.auto_btn.state
# toggle autorange off
end
end
CImGui.PopStyleColor(3)
CImGui.PopID()
CImGui.Text(" HI ")
CImGui.SameLine(), CImGui.Text(" LO ")
CImGui.SameLine(), CImGui.Text(" REF OHM ")
CImGui.SameLine(), CImGui.Text(" RS232 ")
CImGui.SameLine(), CImGui.Text(" GPIB ")
CImGui.SameLine(), CImGui.Text(" ")
CImGui.SameLine(), CImGui.Text(" ENTER ")
CImGui.Text(" DC 20A ")
CImGui.SameLine(), CImGui.Text(" AC 20A ")
CImGui.SameLine(), CImGui.Text("Hz/Ripple")
CImGui.SameLine(), CImGui.Text(" dBm ")
CImGui.SameLine(), CImGui.Text(" AUTOHOLD")
CImGui.SameLine(), CImGui.Text(" ")
CImGui.SameLine(), CImGui.Text(" LOCAL ")
CImGui.Button(" DCA ") && begin
if dmm_conf.shift_btn.state == false
set_sense_func(dmm, dmm_conf.crt_chan, "DCA")
else
set_sense_func(dmm, dmm_conf.crt_chan, "DCA20")
end
end
CImGui.SameLine(),CImGui.Button(" ACA ") && begin
if dmm_conf.shift_btn.state == false
set_sense_func(dmm, dmm_conf.crt_chan, "ACA")
else
set_sense_func(dmm, dmm_conf.crt_chan, "ACA20")
end
end
CImGui.SameLine(),CImGui.Button(" AC+DC ") && begin
if dmm_conf.shift_btn.state == false
set_sense_func(dmm, dmm_conf.crt_chan, "RIPPLE")
else
@warn "not implemented yet"
#set_sense_func(dmm, dmm_conf.crt_chan, "ACA20")
end
end
CImGui.SameLine(),CImGui.Button(" CAP ")
CImGui.SameLine(),CImGui.Button(" HOLD ")
CImGui.SameLine(),CImGui.Button(" DOWN ") && begin
#this should decrease range on current function
end
CImGui.SameLine()
# Draw SHIFT
dmm_conf.shift_btn, pressed = draw_toggle_button(dmm_conf.shift_btn)
# Draw REFRESH
CImGui.SameLine()
dmm_conf.refresh_btn, pressed = draw_toggle_button(dmm_conf.refresh_btn)
dmm_conf.refresh_btn.state && @async update_dmm_conf!(dmm_conf, dmm, refresh_cnt, base)
CImGui.End()
return dmm_conf
end
|
We offer affordable and fair ecommerce website design packages are designed by our team of professional web designers and developers to bring ease of use, functionality and stunning looks to your online store.
Open source is Golden. We specialize in designing and developing ecommerce shopping carts using the following shopping cart options.
We work closely with all of our clients to ensure your website meets all your requirements and exceeds all of your expectations.
We understand yours is a continuous project, thus give you support all the time, upgrade your store. We do not leave you alone, we grow together.
You can start selling online within 3days. We have different packages for ecommerce, starting from Ksh60,000. |
A new development designed by the architects Ron and Jim Vari, 33rd Street Square acknowledges both past and present in rapidly changing Bridgeport. The cutouts and big modular panels give the place a contemporary feel, while the red-brick construction recalls the neighborhood’s traditional housing.
The development (at 33rd Street and South Parnell Avenue) also positions every unit to take advantage of the two best local views: the fireworks over U.S. Cellular Field and the city skyline. Each of the 11 units has one upper-floor terrace looking south and another looking north. “You’re never going to want to go inside all summer,” says Jennifer Liu, an Atland Realty agent selling units in the building.
The spaces inside are roomy and bathed in light from a two-story gridwork of windows; in most of them, an overlook from one floor to another also helps light reach the lower level. At presstime, three units remained at 33rd Street Square, all ready for occupancy. The lowest-cost unit is a 2,800-square-foot three-bedroom unit priced at $559,000; at the upper end, a 3,400-square-foot corner unit with dramatic cutouts and light wells is priced at $675,000. |
||| Axioms and propsitions for primitive types with an
||| `Ord` implementation.
module Data.Prim.Ord
import public Data.Trichotomy
%default total
||| Similar to `Either` but with erased fields.
public export
data Either0 : Type -> Type -> Type where
Left0 : (0 v : a) -> Either0 a b
Right0 : (0 v : b) -> Either0 a b
||| We often don't trust values of type `a === b`, as they might
||| have been magically crafted using `believe_me` or `assert_total`
||| followed by `idris_crash`. If a value of another type follows
||| from a (potentially) magically crafted one, we only want the
||| second value to reduce at compile time, if the first value
||| reduces to `Refl`. Otherwise, we risk blowing up the compiler
||| in an absurd context.
export
strictRefl : (0 prf : a === b) -> Lazy c -> c
strictRefl Refl x = x
--------------------------------------------------------------------------------
-- Interface
--------------------------------------------------------------------------------
||| This interface is a witness that the given primitive type
||| comes with a relation `lt`, with `lt` being a strict total order.
||| We typically define the following aliases
||| (or name the relation accordingly):
|||
||| `m < n` := lt m n
||| `m > n` := lt n m
||| `m <= n` := Either (lt m n) (m === n)
||| `m >= n` := Either (lt n m) (n === m)
||| `m /= n` := Either (lt m n) (lt n m)
|||
||| The following axioms must hold:
||| 1. (<) is transitive: From `k < m` and `m < n` follows `k < n`.
|||
||| 2. Trichotomy: For all values `m` and `n` exactly one of the
||| following holds: `m < n`, `m === n`, or `n < m`.
|||
||| It is in the nature of a primitive that we can't proof these axioms
||| in Idris itself. We must therefore assume that they hold on all backends,
||| and it is the responsibility of programmers implementing
||| interface `Total` to make sure that the axioms actually hold.
public export
interface Total (0 a : Type) (0 lt : a -> a -> Type) | lt where
||| Axiom I: `<` is transitive.
0 transLT : {k,m,n : a} -> lt k m -> lt m n -> lt k n
||| Axiom II: Trichotomy of `<`, `===`, and `>`.
trichotomy : (m,n : a) -> Trichotomy lt m n
||| Tests if the first value is strictly less than the second or not
export
testLT : Total a lt => (x,y : a) -> Either0 (lt x y) (Either (lt y x) (y === x))
testLT x y = case trichotomy {lt} x y of
LT p _ _ => Left0 p
EQ _ p _ => Right0 (Right $ sym p)
GT _ _ p => Right0 (Left p)
||| Tests if the first value is strictly greater than the second or not
export
testGT : Total a lt => (x,y : a) -> Either0 (lt y x) (Either (lt x y) (x === y))
testGT x y = case trichotomy {lt} x y of
GT _ _ p => Left0 p
LT p _ _ => Right0 (Left p)
EQ _ p _ => Right0 (Right p)
||| Tests if the two values are provably equal or not
export
testEQ : Total a lt => (x,y : a) -> Either0 (x === y) (Either (lt x y) (lt y x))
testEQ x y = case trichotomy {lt} x y of
EQ _ p _ => Left0 p
LT p _ _ => Right0 (Left p)
GT _ _ p => Right0 (Right p)
--------------------------------------------------------------------------------
-- Corollaries
--------------------------------------------------------------------------------
||| `<` is irreflexive.
export
0 irrefl : Total a lt => Not (lt m m)
irrefl x = case trichotomy m m of
LT y _ f => f y
EQ f _ _ => f x
GT f _ y => f y
--------------------------------------------------------------------------------
-- Transitivities
--------------------------------------------------------------------------------
namespace LT
||| This is an alias for `transLT`
export
0 trans : Total a lt => lt k m -> lt m n -> lt k n
trans = transLT
||| `k === m` and `m /= n` implies `k /= n`.
export
0 trans_EQ_NEQ : Total a lt
=> k === m
-> Either (lt m n) (lt n m)
-> Either (lt k n) (lt n k)
trans_EQ_NEQ eqv neq = rewrite eqv in neq
||| `k === m` and `m /= n` implies `k /= n`.
export
0 trans_NEQ_EQ : Total a lt
=> Either (lt k m) (lt m k)
-> m === n
-> Either (lt k n) (lt n k)
trans_NEQ_EQ neq eqv = rewrite (sym eqv) in neq
||| `k < m` and `m === n` implies `k < n`
export
0 trans_LT_EQ : Total a lt => lt k m -> m === n -> lt k n
trans_LT_EQ p eqv = rewrite sym eqv in p
||| `k === m` and `m < n` implies `k < n`
export
0 trans_EQ_LT : Total a lt => k === m -> lt m n -> lt k n
trans_EQ_LT eqv q = rewrite eqv in q
||| `k <= m` and `m < n` implies `k < n`
export
0 trans_LTE_LT : Total a lt => Either (lt k m) (k === m) -> lt m n -> lt k n
trans_LTE_LT x y = either (`trans` y) (`trans_EQ_LT` y) x
||| `k < m` and `m <= n` implies `k < n`
export
0 trans_LT_LTE : Total a lt => lt k m -> Either (lt m n) (m === n) -> lt k n
trans_LT_LTE x = either (trans x) (trans_LT_EQ x)
||| `k > m` and `m === n` implies `k > n`
export
0 trans_GT_EQ : Total a lt => lt m k -> m === n -> lt n k
trans_GT_EQ p eqv = rewrite sym eqv in p
||| `k === m` and `m > n` implies `k > n`
export
0 trans_EQ_GT : Total a lt => k === m -> lt n m -> lt n k
trans_EQ_GT eqv q = rewrite eqv in q
||| `k >= m` and `m > n` implies `k > n`
export
0 trans_GTE_GT : Total a lt => Either (lt m k) (m === k) -> lt n m -> lt n k
trans_GTE_GT x y = either (trans y) (\v => trans_EQ_GT (sym v) y) x
||| `k > m` and `m >= n` implies `k > n`
export
0 trans_GT_GTE : Total a lt => lt m k -> Either (lt n m) (n === m) -> lt n k
trans_GT_GTE x (Left y) = trans y x
trans_GT_GTE x (Right y) = trans_GT_EQ x (sym y)
namespace LTE
||| `<=` is reflexive.
export
0 refl : Total a lt => Either (lt m m) (m === m)
refl = Right Refl
||| `<=` is transitive.
export
0 trans : Total a lt
=> Either (lt k m) (k === m)
-> Either (lt m n) (m === n)
-> Either (lt k n) (k === n)
trans (Left x) y = Left (trans_LT_LTE x y)
trans (Right x) (Left y) = Left (trans_EQ_LT x y)
trans (Right x) (Right y) = Right (trans x y)
||| `<=` is antisymmetric.
export
0 antisym : Total a lt
=> Either (lt m n) (m === n)
-> Either (lt n m) (m === n)
-> m === n
antisym (Right x) _ = x
antisym (Left x) (Right y) = y
antisym (Left x) (Left y) = void (irrefl $ trans x y)
||| `k <= m` and `m === n` implies `k <= n`
export
0 trans_LTE_EQ : Total a lt
=> Either (lt k m) (k === m)
-> m === n
-> Either (lt k n) (k === n)
trans_LTE_EQ lte eq = trans lte (Right eq)
||| `k === m` and `m <= n` implies `(k <= n)`
export
0 trans_EQ_LTE : Total a lt
=> k === m
-> Either (lt m n) (m === n)
-> Either (lt k n) (k === n)
trans_EQ_LTE eq lte = trans (Right eq) lte
namespace GTE
||| `>=` is transitive.
export
0 trans : Total a lt
=> Either (lt m k) (m === k)
-> Either (lt n m) (n === m)
-> Either (lt n k) (n === k)
trans (Left x) y = Left (trans_GT_GTE x y)
trans (Right x) (Left y) = Left (trans_EQ_GT (sym x) y)
trans (Right x) (Right y) = Right (trans y x)
||| `>=` is antisymmetric.
export
0 antisym : Total a lt
=> Either (lt n m) (m === n)
-> Either (lt m n) (m === n)
-> m === n
antisym (Right x) _ = x
antisym (Left x) (Right y) = y
antisym (Left x) (Left y) = void (irrefl $ trans x y)
||| `k >= m` and `m === n` implies `k >= n`
export
0 trans_GTE_EQ : Total a lt
=> Either (lt m k) (m === k)
-> m === n
-> Either (lt n k) (n === k)
trans_GTE_EQ gte eq = trans gte (Right $ sym eq)
||| `k === m` and `m <= n` implies `(k <= n)`
export
0 trans_EQ_GTE : Total a lt
=> k === m
-> Either (lt n m) (n === m)
-> Either (lt n k) (n === k)
trans_EQ_GTE eq gte = trans (Right $ sym eq) gte
--------------------------------------------------------------------------------
-- Conversions
--------------------------------------------------------------------------------
||| `m < n` implies `Not (m > n)`.
export
0 LT_not_GT : Total a lt => lt m n -> Not (lt n m)
LT_not_GT isLT isGT = case trichotomy m n of
LT _ _ g => g isGT
EQ _ _ g => g isGT
GT f _ _ => f isLT
||| `m < n` implies `Not (m === n)`.
export
0 LT_not_EQ : Total a lt => lt m n -> Not (m === n)
LT_not_EQ isLT isEQ = case trichotomy m n of
LT _ g _ => g isEQ
EQ f _ _ => f isLT
GT _ g _ => g isEQ
||| `m < n` implies `Not (m >= n)`.
export
0 LT_not_GTE : Total a lt => lt m n -> Not (Either (lt n m) (n === m))
LT_not_GTE l = either (LT_not_GT l) (\e => LT_not_EQ l (sym e))
||| `Not (m < n)` implies `m >= n`.
export
0 Not_LT_to_GTE : Total a lt => Not (lt m n) -> Either (lt n m) (n === m)
Not_LT_to_GTE f = case trichotomy m n of
LT x _ _ => void (f x)
EQ _ x _ => Right (sym x)
GT _ _ x => Left x
||| `m === n` implies `Not (m < n)`.
export
0 EQ_not_LT : Total a lt => m === n -> Not (lt m n)
EQ_not_LT = flip LT_not_EQ
||| `m === n` implies `Not (m > n)`.
export
0 EQ_not_GT : Total a lt => m === n -> Not (lt n m)
EQ_not_GT isEQ = EQ_not_LT (sym isEQ)
||| `m === n` implies `Not (m /= n)`.
export
0 EQ_not_NEQ : Total a lt => m === n -> Not (Either (lt m n) (lt n m))
EQ_not_NEQ isEQ = either (EQ_not_LT isEQ) (EQ_not_GT isEQ)
||| `Not (m < n)` implies `m /= n`.
export
0 Not_EQ_to_NEQ : Total a lt => Not (m === n) -> Either (lt m n) (lt n m)
Not_EQ_to_NEQ f = case trichotomy m n of
LT x _ _ => Left x
EQ _ x _ => void (f x)
GT _ _ x => Right x
||| `m > n` implies `Not (m < n)`.
export
0 GT_not_LT : Total a lt => lt n m -> Not (lt m n)
GT_not_LT = LT_not_GT
||| `m > n` implies `Not (m === n)`.
export
0 GT_not_EQ : Total a lt => lt n m -> Not (m === n)
GT_not_EQ = flip EQ_not_GT
||| `m > n` implies `Not (m <= n)`.
export
0 GT_not_LTE : Total a lt => lt n m -> Not (Either (lt m n) (m === n))
GT_not_LTE gt = either (GT_not_LT gt) (GT_not_EQ gt)
||| `Not (m > n)` implies `m <= n`.
export
0 Not_GT_to_LTE : Total a lt => Not (lt n m) -> Either (lt m n) (m === n)
Not_GT_to_LTE f = case trichotomy m n of
LT x _ _ => Left x
EQ _ x _ => Right x
GT _ _ x => void (f x)
||| `m <= n` implies `Not (m > n)`.
export
0 LTE_not_GT : Total a lt => (Either (lt m n) (m === n)) -> Not (lt n m)
LTE_not_GT = either LT_not_GT EQ_not_GT
||| `Not (m <= n)` implies `m > n`.
export
0 Not_LTE_to_GT : Total a lt => Not (Either (lt m n) (m === n)) -> lt n m
Not_LTE_to_GT f = case trichotomy m n of
LT x _ _ => void (f $ Left x)
EQ _ x _ => void (f $ Right x)
GT _ _ x => x
||| `m <= n` and `m >= n` implies `m === n`.
export
0 LTE_and_GTE_to_EQ : Total a lt
=> Either (lt m n) (m === n)
-> Either (lt n m) (n === m)
-> m === n
LTE_and_GTE_to_EQ (Left x) (Right y) = sym y
LTE_and_GTE_to_EQ (Right x) _ = x
LTE_and_GTE_to_EQ (Left x) (Left y) = void (LT_not_GT x y)
||| `m <= n` and `m /= n` implies `m < n`.
export
0 LTE_and_NEQ_to_LT : Total a lt
=> Either (lt m n) (m === n)
-> Either (lt m n) (lt n m)
-> lt m n
LTE_and_NEQ_to_LT (Left x) _ = x
LTE_and_NEQ_to_LT (Right _) (Left x) = x
LTE_and_NEQ_to_LT (Right x) (Right y) = void (EQ_not_GT x y)
||| `m /= n` implies `Not (m === n)`.
export
0 NEQ_not_EQ : Total a lt => Either (lt m n) (lt n m) -> Not (m === n)
NEQ_not_EQ = either LT_not_EQ GT_not_EQ
||| `Not (m /= n)` implies `m === n`.
export
0 Not_NEQ_to_EQ : Total a lt => Not (Either (lt m n) (lt n m)) -> m === n
Not_NEQ_to_EQ f = case trichotomy m n of
LT x _ _ => void (f $ Left x)
EQ _ x _ => x
GT _ _ x => void (f $ Right x)
||| `m /= n` and `m <= n` implies `m < n`.
export
0 NEQ_and_LTE_to_LT : Total a lt
=> Either (lt m n) (lt n m)
-> Either (lt m n) (m === n)
-> lt m n
NEQ_and_LTE_to_LT = flip LTE_and_NEQ_to_LT
||| `m /= n` and `m <= n` implies `m < n`.
export
0 NEQ_and_GTE_to_GT : Total a lt
=> Either (lt m n) (lt n m)
-> Either (lt n m) (n === m)
-> lt n m
NEQ_and_GTE_to_GT (Right x) _ = x
NEQ_and_GTE_to_GT (Left _) (Left y) = y
NEQ_and_GTE_to_GT (Left x) (Right y) = void (GT_not_EQ x y)
||| `m >= n` implies `Not (m < n)`.
export
0 GTE_not_LT : Total a lt => Either (lt n m) (n === m) -> Not (lt m n)
GTE_not_LT = either GT_not_LT EQ_not_GT
||| `Not (m >= n)` implies `m < n`.
export
0 Not_GTE_to_LT : Total a lt => Not (Either (lt n m) (n === m)) -> lt m n
Not_GTE_to_LT f = case trichotomy m n of
LT x _ _ => x
EQ _ x _ => void (f $ Right (sym x))
GT _ _ x => void (f $ Left x)
||| `m >= n` and `m <= n` implies `m === n`.
export
0 GTE_and_LTE_to_EQ : Total a lt
=> Either (lt n m) (n === m)
-> Either (lt m n) (m === n)
-> m === n
GTE_and_LTE_to_EQ = flip LTE_and_GTE_to_EQ
||| `m >= n` and `m /= n` implies `m > n`.
export
0 GTE_and_NEQ_to_GT : Total a lt
=> Either (lt n m) (n === m)
-> Either (lt m n) (lt n m)
-> lt n m
GTE_and_NEQ_to_GT = flip NEQ_and_GTE_to_GT
|
Require Import Maps.
Require Import AST.
Require Import Integers.
Require Import Values.
Require Import Memory.
Require Import Events.
Require Import Smallstep.
Require Import Globalenvs.
Require Import Linking.
Require Import CoqlibC.
Require Import sflib.
Require Import ModSem Mod Skeleton LinkingC.
Definition program := list Mod.t.
|
import logic
universe u
variable α : Type u
variable β : Type u
/- axiome d'extensionnalité -/
axiom set_ext {α} (E F : set α) : (∀x:α, ( E x ↔ F x )) → E = F
/- La réciproque découle de la définition de l'égalité -/
theorem set_ext_rec {α} {E F : set α} : E = F → (∀x, ( E x ↔ F x )) :=
(fun eq_E_F : (E = F) ,
(fun x: α,
iff.intro
(fun h_x_in_E : E x,
eq.rec h_x_in_E eq_E_F
)
(fun h_x_in_F : F x,
eq.rec h_x_in_F (eq.symm eq_E_F)
)
)
)
/- Axiome de séparation : l'ensemble des éléments d'un ensemble vérifiant une propriété existe -/
def sep (p : α → Prop) (s : set α) : set α :=
(fun a : α,
(s a) ∧ (p a)
)
/- On peut toujours construire un ensemble vide -/
def empty_set {α} : (set α) :=
(fun (a:α), false)
/- On peut toujours construire un singleton à partir d'une variable -/
def singl {α}: (α -> set α) :=
(fun (a:α),
(fun (b:α),
a=b
)
)
example (a : α) : singl a a :=
rfl
/- L'appartenance au singleton se réduit à l'égalité à l'élément du signleton -/
example (a x : α): singl a x -> a = x :=
(fun h : singl a x,
h
)
/- On peut toujours construire un ensemble à partir d'une liste -/
def list_set {α}: (list α -> set α)
| list.nil := empty_set
| (list.cons a l) := (fun x:α, (a=x) ∨ (list_set l x) )
/-
Definition de la notion de sous ensemble
s1 est un sous ensemble de s2
-/
def subset {α} (s₁ s₂ : set α) :=
∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂
theorem subset_exp {α} {E F : set α} : subset E F <-> ∀ ⦃x:α⦄, x ∈ E → x ∈ F :=
iff.intro
(fun h : subset E F, h)
(fun h : ∀ ⦃a⦄, a ∈ E → a ∈ F, h)
theorem reciproc_subset_is_eq (a b : set α) : (subset a b) /\ (subset b a) <-> (a = b) :=
iff.intro
(fun h : (subset a b) /\ (subset b a),
have h0 : ∀ x : α, a x <-> b x :=
(fun x : α,
have h1 : ∀ y:α, a y -> b y := subset_exp.mp h.left,
have h2 : ∀ y:α, b y -> a y := subset_exp.mpr h.right,
have h11 : a x -> b x := h1 x,
have h22 : b x -> a x := h2 x,
have h3 : a x <-> b x := iff.intro h11 h22,
h3
),
set_ext a b h0
)
(fun h : a = b,
have h0 : (∀x, ( a x ↔ b x )) := set_ext_rec h,
and.intro
(fun x : α,
(h0 x).mp
)
(fun x : α,
(h0 x).mpr
)
)
/- Une condition suffisante pour qu'un singleton soit un sous ensemble de E est que l'élément appartienne à E -/
example (a : α) (E : set α) : E a -> (subset (singl a) E) :=
(fun h : E a,
(fun x : α,
(fun h_a_x : a = x ,
eq.rec h h_a_x
)
)
)
/- Une condition suffisante pour qu'un singleton soit un sous ensemble d'un singleton est que les 2 éléments soient égaux -/
example (a b : α) : a = b -> (subset (singl a) (singl b)) :=
(fun h : a = b,
(fun x : α,
(fun h_a_x : a = x ,
eq.symm (eq.rec h h_a_x)
)
)
)
/- Définition de l'U entre sous ensembles -/
def U {α} (s1 s2 : set α) : set α :=
(fun a: α,
s1 a ∨ s2 a
)
theorem U_assoc (a b c : set α) : (U a (U b c)) = (U (U a b) c):=
set_ext
(U a (U b c))
(U (U a b) c)
(fun x : α,
iff.intro
(fun h: (U a (U b c)) x,
have h2 : a x ∨ b x ∨ c x := h,
or.assoc.mpr h2
)
(fun h: (U (U a b) c) x,
have h2 : (a x ∨ b x) ∨ c x := h,
or.assoc.mp h2
)
)
theorem U_com (a b : set α) : U a b = U b a:=
set_ext
(U a b)
(U b a)
(fun x : α,
iff.intro
(fun h: U a b x,
have h2 : a x ∨ b x := h,
or.comm.mp h2
)
(fun h: U b a x,
have h2 : b x ∨ a x := h,
or.comm.mp h2
)
)
theorem U_id (a b : set α) : (U a a) = a:=
set_ext
(U a a)
(a)
(fun x : α,
iff.intro
(fun h: U a a x,
have h2 : a x ∨ a x := h,
or.elim
h2
id
id
)
(fun h: a x,
have h2 : a x := h,
or.intro_left (a x) h2
)
)
theorem U_empty (a b : set α) : (U a empty_set) = a:=
set_ext
(U a empty_set)
(a)
(fun x : α,
iff.intro
(fun h: U a empty_set x,
have h2 : a x ∨ false := h,
or.elim
h2
id
false.elim
)
(fun h: a x,
have h2 : a x := h,
or.intro_left (false) h2
)
)
/- Définition de l'intersection entre sous ensembles -/
def I {α} (s1 s2 : set α) : set α :=
(fun a : α,
(s1 a) ∧ (s2 a)
)
theorem I_assoc (a b c : set α) : (I a (I b c)) = (I (I a b) c):=
set_ext
(I a (I b c))
(I (I a b) c)
(fun x : α,
iff.intro
(fun h: (I a (I b c)) x,
have h2 : a x ∧ b x ∧ c x := h,
and.assoc.mpr h2
)
(fun h: (I (I a b) c) x,
have h2 : (a x ∧ b x) ∧ c x := h,
and.assoc.mp h2
)
)
theorem I_com (a b : set α) : I a b = I b a:=
set_ext
(I a b)
(I b a)
(fun x : α,
iff.intro
(fun h: I a b x,
have h2 : a x ∧ b x := h,
and.comm.mp h2
)
(fun h: I b a x,
have h2 : b x ∧ a x := h,
and.comm.mp h2
)
)
theorem I_id (a b : set α) : (I a a) = a:=
set_ext
(I a a)
(a)
(fun x : α,
iff.intro
(fun h: I a a x,
have h2 : a x ∧ a x := h,
and.left h2
)
(fun h: a x,
have h2 : a x := h,
and.intro h2 h2
)
)
theorem I_empty (a b : set α) : (I a empty_set) = empty_set:=
set_ext
(I a empty_set)
(empty_set)
(fun x : α,
iff.intro
(fun h: I a empty_set x,
have h2 : a x ∧ false := h,
and.right h2
)
false.elim
)
theorem I_dist_over_U (a b c : set α) : (I a (U b c)) = (U (I a b) (I a c)):=
set_ext
(I a (U b c))
(U (I a b) (I a c))
(fun x : α,
iff.intro
(fun h: (I a (U b c)) x,
have h2 : a x ∧ (b x ∨ c x) := h,
dist_and_over_or.mp h2
)
(fun h: (U (I a b) (I a c)) x,
have h2 : a x ∧ b x ∨ a x ∧ c x := h,
dist_and_over_or.mpr h2
)
)
theorem U_dist_over_I (a b c : set α) : (U a (I b c)) = (I (U a b) (U a c)):=
set_ext
(U a (I b c))
(I (U a b) (U a c))
(fun x : α,
iff.intro
(fun h: (U a (I b c)) x,
have h2 : a x ∨ (b x ∧ c x) := h,
dist_or_over_and.mp h2
)
(fun h: (I (U a b) (U a c)) x,
have h2 : (a x ∨ b x) ∧ (a x ∨ c x) := h,
dist_or_over_and.mpr h2
)
)
example (a b : set α) : (subset a b) ↔ (I a b) = a :=
iff.intro
(fun h : subset a b,
set_ext
(I a b)
a
(fun x : α,
iff.intro
(fun h_Iab : I a b x,
have h : a x ∧ b x := h_Iab,
and.left h
)
(fun h_a : a x,
have h_b : b x := h h_a,
and.intro h_a h_b
)
)
)
(fun h : (I a b) = a,
(fun x : α,
(fun ha : a x,
have h_Iab_eq_a : (∀x, ( (I a b) x ↔ a x )) :=
set_ext_rec
h
,
have h_Iab_eq_a_x : (I a b) x ↔ a x := h_Iab_eq_a x,
have h_Iab : a x ∧ b x := h_Iab_eq_a_x.mpr ha,
and.right h_Iab
)
)
)
example (a b : set α) : (subset a b) ↔ (U a b) = b :=
iff.intro
(fun h : subset a b,
set_ext
(U a b)
b
(fun x : α,
iff.intro
(fun h_Uab : U a b x,
have h1 : a x ∨ b x := h_Uab,
or.elim
h1
(fun ha: a x, h ha)
id
)
(fun h_b : b x,
or.intro_right (a x) h_b
)
)
)
(fun h : (U a b) = b,
(fun x : α,
(fun ha : a x,
have h_Uab_eq_b : (∀x, ( (U a b) x ↔ b x )) :=
set_ext_rec
h
,
have h_Uab_eq_b_x : (U a b) x ↔ b x := h_Uab_eq_b x,
have h_Uab : a x ∨ b x := or.intro_left (b x) ha,
h_Uab_eq_b_x.mp h_Uab
)
)
)
example (a b : set α) : a = b -> (U a b) = (I a b) :=
(fun h : a = b ,
set_ext
(U a b)
(I a b)
(fun x : α,
iff.intro
(fun h_uab : (U a b) x,
have h2 : a x ∨ b x := h_uab,
or.elim
h2
(fun h_ax : a x,
have h_bx : b x := eq.rec h_ax h,
and.intro h_ax h_bx
)
(fun h_bx : b x,
have h_ax : a x := eq.rec h_bx (eq.symm h),
and.intro h_ax h_bx
)
)
(fun h_iab : (I a b) x,
have h2 : a x ∧ b x := h_iab,
or.intro_left (b x) (and.left h2)
)
)
)
/- Définition de la différence entre sous ensembles -/
def diff (s t : set α) : set α :=
(fun a : α,
(s a) ∧ (¬ (t a) )
)
/- Définition de l'ensemble des sous ensembles -/
def powerset (s : set α) : set (set α) :=
(fun t : set α,
subset t s
)
/- Définition du complémentaire -/
def C {α} (s1 s2 : set α) : set α :=
(fun a: α,
(¬ (s1 a)) ∧ s2 a
)
/- Le complémentaire du complémentaire d'un ensemble est lui même -/
example (a b : set α) : subset a b -> C (C a b) b = a :=
(fun h_sab : subset a b,
set_ext
(C (C a b) b)
a
(fun x : α,
iff.intro
(fun h_CCa : C (C a b) b x,
have h_CCa_x : ((a x → false) ∧ b x → false) ∧ b x := h_CCa,
have h1 : (a x → false) ∧ b x → false := and.left h_CCa,
show a x, from
classical.by_contradiction
(fun hna : ¬ (a x) ,
h1 ( and.intro hna (and.right h_CCa_x) )
)
)
(fun ha : a x,
have hb : b x := h_sab ha,
have hnna : ¬ (¬ a x) := dne.mpr ha,
and.intro (dne_intro (b x) hnna) hb
)
)
)
/- 1ere loi de morgan -/
example (e a b : set α) : subset a e -> subset b e -> C (U a b) e = I (C a e)(C b e) :=
(fun hae : subset a e,
(fun hbe : subset b e,
set_ext
(C (U a b) e)
(I (C a e)(C b e))
(fun x : α,
iff.intro
(fun h_CUabe : C (U a b) e x,
have hex : e x := and.right h_CUabe,
have hnbx : ¬ b x := and.right (dist_neg_over_or.mp (and.left h_CUabe)),
have hnax : ¬ a x := and.left (dist_neg_over_or.mp (and.left h_CUabe)),
and.intro (and.intro hnax hex) (and.intro hnbx hex)
)
(fun hI_Cae_Cbe : I (C a e)(C b e) x,
have hex : e x := and.right (and.right hI_Cae_Cbe),
have hnax : ¬ (a x) := and.left(and.left hI_Cae_Cbe),
have hnbx : ¬ (b x) := and.left (and.right hI_Cae_Cbe),
have hnabx : ¬ (a x ∨ b x) := dist_neg_over_or.mpr (and.intro hnax hnbx),
and.intro hnabx hex
)
)
)
)
/- 2eme loi de morgan -/
example (e a b : set α) : subset a e -> subset b e -> C (I a b) e = U (C a e)(C b e) :=
(fun hae : subset a e,
(fun hbe : subset b e,
set_ext
(C (I a b) e)
(U (C a e)(C b e))
(fun x : α,
iff.intro
(fun h_CIabe : C (I a b) e x,
have hex : e x := and.right h_CIabe,
have hna_or_nbx : ¬ a x ∨ ¬ b x := (dist_neg_over_and (and.left h_CIabe)),
or.elim
hna_or_nbx
(fun hnax : ¬ a x ,
or.intro_left ((b x → false) ∧ e x) (and.intro hnax hex)
)
(fun hnbx : ¬ b x ,
or.intro_right ((a x → false) ∧ e x) (and.intro hnbx hex)
)
)
(fun hU_Cae_Cbe : U (C a e)(C b e) x,
or.elim
hU_Cae_Cbe
(fun h_Cae : (a x → false) ∧ e x,
and.intro
(dne_intro (b x) (and.left h_Cae))
(and.right h_Cae)
)
(fun h_Cbe : (b x → false) ∧ e x,
and.intro
(dne_lintro (a x) (and.left h_Cbe))
(and.right h_Cbe)
)
)
)
)
)
/- une structure de paire qui va être la base des produits cartésiens-/
structure pair (α : Type u) :=
intro :: (first : α) (second : α)
def pair_eq {α} (a b : pair α) : Prop :=
(a.first = b.first) ∧ (a.second = b.second)
example ( a b c d : α ) : pair_eq (pair.intro a b) (pair.intro c d) ↔ (a=c) ∧ (b=d):=
iff.intro
(fun heq : pair_eq (pair.intro a b) (pair.intro c d),
heq
)
(fun ha_ac_and_bd : (a=c) ∧ (b=d),
ha_ac_and_bd
)
/- Un ensemble construit à partir de deux ensembles : le produit cartésien -/
def pair_set {α} (a b : set α) : set (pair α) :=
(fun hp : pair α,
(a hp.first) ∧ (b hp.second)
)
example (a a1 b b1 : set α) : subset a1 a /\ subset b1 b -> subset (pair_set a1 b1) (pair_set a b):=
(fun h : subset a1 a /\ subset b1 b,
(fun hp : pair α,
(fun hpab : (pair_set a1 b1) hp ,
have ha1 : a hp.first := h.left hpab.left,
have hb1 : b hp.second := h.right hpab.right,
and.intro ha1 hb1
)
)
) |
module Inigo.Async.SubtleCrypto.Example
import Inigo.Async.Promise
import Inigo.Async.SubtleCrypto.SubtleCrypto
-- Can be tested in a browser with:
-- idris2 SubtleCrypto/Example.idr --cg node -o testcrypto && cat build/exec/testcrypto | pbcopy
signAndVerify : Promise ()
signAndVerify =
do
let keyAlgo = (KeyECDSA P256)
let algo = (ECDSA Sha256)
(pub, priv) <- generateKey keyAlgo (Sign <&> Verify)
privEnc <- exportKey priv
privImp <- importKey keyAlgo Sign privEnc
signature <- sign algo privImp "hello world"
pubEnc <- exportKey pub
pubImp <- importKey keyAlgo Verify pubEnc
success <- verify algo pubImp signature "hello world"
log ("Success: " ++ show success)
hashPassword : Promise ()
hashPassword =
do
salt <- getRand 8
let algo = (PBKDF2 Sha256 salt 10000)
hashed <- hash algo "my password"
log ("Hashed: " ++ hashed)
main : IO ()
main =
resolve hashPassword (\_ => pure ()) (\_ => pure ())
|
# GraphHopper Directions API
#
# You use the GraphHopper Directions API to add route planning, navigation and route optimization to your software. E.g. the Routing API has turn instructions and elevation data and the Route Optimization API solves your logistic problems and supports various constraints like time window and capacity restrictions. Also it is possible to get all distances between all locations with our fast Matrix API.
#
# OpenAPI spec version: 1.0.0
#
# Generated by: https://github.com/swagger-api/swagger-codegen.git
#' MatrixResponse Class
#'
#' @field distances
#' @field times
#' @field weights
#' @field info
#'
#' @importFrom R6 R6Class
#' @importFrom jsonlite fromJSON toJSON
#' @export
MatrixResponse <- R6::R6Class(
'MatrixResponse',
public = list(
`distances` = NULL,
`times` = NULL,
`weights` = NULL,
`info` = NULL,
initialize = function(`distances`, `times`, `weights`, `info`){
if (!missing(`distances`)) {
stopifnot(is.list(`distances`), length(`distances`) != 0)
lapply(`distances`, function(x) stopifnot(R6::is.R6(x)))
self$`distances` <- `distances`
}
if (!missing(`times`)) {
stopifnot(is.list(`times`), length(`times`) != 0)
lapply(`times`, function(x) stopifnot(R6::is.R6(x)))
self$`times` <- `times`
}
if (!missing(`weights`)) {
stopifnot(is.list(`weights`), length(`weights`) != 0)
lapply(`weights`, function(x) stopifnot(R6::is.R6(x)))
self$`weights` <- `weights`
}
if (!missing(`info`)) {
stopifnot(R6::is.R6(`info`))
self$`info` <- `info`
}
},
toJSON = function() {
MatrixResponseObject <- list()
if (!is.null(self$`distances`)) {
MatrixResponseObject[['distances']] <- lapply(self$`distances`, function(x) x$toJSON())
}
if (!is.null(self$`times`)) {
MatrixResponseObject[['times']] <- lapply(self$`times`, function(x) x$toJSON())
}
if (!is.null(self$`weights`)) {
MatrixResponseObject[['weights']] <- lapply(self$`weights`, function(x) x$toJSON())
}
if (!is.null(self$`info`)) {
MatrixResponseObject[['info']] <- self$`info`$toJSON()
}
MatrixResponseObject
},
fromJSON = function(MatrixResponseJson) {
MatrixResponseObject <- jsonlite::fromJSON(MatrixResponseJson)
if (!is.null(MatrixResponseObject$`distances`)) {
self$`distances` <- lapply(MatrixResponseObject$`distances`, function(x) {
distancesObject <- Numeric$new()
distancesObject$fromJSON(jsonlite::toJSON(x, auto_unbox = TRUE))
distancesObject
})
}
if (!is.null(MatrixResponseObject$`times`)) {
self$`times` <- lapply(MatrixResponseObject$`times`, function(x) {
timesObject <- Numeric$new()
timesObject$fromJSON(jsonlite::toJSON(x, auto_unbox = TRUE))
timesObject
})
}
if (!is.null(MatrixResponseObject$`weights`)) {
self$`weights` <- lapply(MatrixResponseObject$`weights`, function(x) {
weightsObject <- Numeric$new()
weightsObject$fromJSON(jsonlite::toJSON(x, auto_unbox = TRUE))
weightsObject
})
}
if (!is.null(MatrixResponseObject$`info`)) {
infoObject <- ResponseInfo$new()
infoObject$fromJSON(jsonlite::toJSON(MatrixResponseObject$info, auto_unbox = TRUE))
self$`info` <- infoObject
}
},
toJSONString = function() {
sprintf(
'{
"distances": [%s],
"times": [%s],
"weights": [%s],
"info": %s
}',
lapply(self$`distances`, function(x) paste(x$toJSON(), sep=",")),
lapply(self$`times`, function(x) paste(x$toJSON(), sep=",")),
lapply(self$`weights`, function(x) paste(x$toJSON(), sep=",")),
self$`info`$toJSON()
)
},
fromJSONString = function(MatrixResponseJson) {
MatrixResponseObject <- jsonlite::fromJSON(MatrixResponseJson)
self$`distances` <- lapply(MatrixResponseObject$`distances`, function(x) Numeric$new()$fromJSON(jsonlite::toJSON(x, auto_unbox = TRUE)))
self$`times` <- lapply(MatrixResponseObject$`times`, function(x) Numeric$new()$fromJSON(jsonlite::toJSON(x, auto_unbox = TRUE)))
self$`weights` <- lapply(MatrixResponseObject$`weights`, function(x) Numeric$new()$fromJSON(jsonlite::toJSON(x, auto_unbox = TRUE)))
ResponseInfoObject <- ResponseInfo$new()
self$`info` <- ResponseInfoObject$fromJSON(jsonlite::toJSON(MatrixResponseObject$info, auto_unbox = TRUE))
}
)
)
|
\chapter{Word order}\label{ch:3}
This chapter reviews different accounts of word order which have been proposed in the \ac{PandP} framework. In the \ac{PandP} approach, linguistic universals or common structural features that are found across languages are explained by a set of finite \textit{principles}. On the other hand, linguistic variation can be explained by different parameters, with which a particular language is set. The ultimate goal in the \ac{PandP} framework is to find such principles and parameters that are unique to human language.
As explained in Chapter \ref{ex:1}, the universal approach to \ac{CS} is advocated in this monograph, which views that both monolingual and bilingual grammars are subject to the same grammatical principles. Thus, an account of \ac{OV}-\ac{VO} variation in \ac{CS} will be also based on existing theories and proposals on \ac{OV} and \ac{VO} orders in the linguistics literatures.
To begin with, I provide a brief overview of different approaches to word order in the \ac{PandP} theory and support a derivational approach proposed by \citet{Kayne1994}, who argues that both \ac{OV} and \ac{VO} orders share the same underlying \ac{VO} order and \ac{OV} order is derived from \ac{VO} via object movement. This idea will be taken up to describe \ac{OV} order in Korean and Japanese in contrast with \ac{VO} order of English, and \ac{OV}-\ac{VO} contrast between Korean/Japanese and English is argued to be due to different feature specifications on the functional category \textit{v}: while \textit{v} in Korean and Japanese is specified for \ac{EPP}, which triggers object movement, \textit{v} in English lacks \ac{EPP}. Also I propose that the Korean light verb \textit{ha} and Japanese light verb \textit{su} represent the functional category \textit{v}, but English-type light verbs characterize another functional category, Asp(ect), which is projected between \textit{v} and V. The intricate interplay between \textit{v} and A\textsc{sp} will be explained further in the feature inheritance system in Chapter \ref{ch:4}.
\section{Non-derivational approach}\label{ch3:sect:3.1}
In early generative grammar, word order was stipulated according to phrase structure rules. With the advent of the notion of \textit{parameters} \citep{Chomsky1976}, which may vary from one language to another, it was assumed that languages were parameterized according to the directionality of a head: heads may precede or follow its complement (e.g. \citealt{Chomsky1981}, \citealt{Stowell1981}). In English, for instance, all heads normally precede their complements, as exhibited in \REF{ex:43}.
\ea\label{ex:43}\ea
close the door
\ex on the table
\ex an argument with Bibi
\ex curious about Bibi \z
\z
The verbal head \textit{close} precedes its complement \textit{the door} in (\ref{ex:43}a), the prepositional head \textit{on} precedes its complement \textit{the table} in (\ref{ex:43}b), the nominal head \textit{argument} precedes its complement \textit{with Bibi} in (\ref{ex:43}c), and the adjectival head \textit{curious} precedes its complement \textit{about Bibi} in (\ref{ex:43}d). Contrary to the \textit{head-initial} structure in English, Korean shows \textit{head-final} structure, in which all heads uniformly follow their complements and reflect a mirror image of English word order. Korean counterparts to the examples in \REF{ex:43} are provided in \REF{ex:44}.
\ea\label{ex:44}\ea
\gll mwun-ul tat-ala \\
door-\textsc{acc} close-\textsc{imp} \\
\glt `close the door'
\ex \gll takca (wi)-ey \\
table top-\textsc{loc} \\
\glt `on the table'
\ex \gll Bibi wa-(uy) encayng \\
Bibi with-\textsc{gen} argument
\\
\glt `an argument with Bibi'
\ex \gll Bibi eytayhay kwungkumha-ta \\
Bibi about curious-\textsc{decl} \\
\glt `curious about Bibi'
\z \z
Under the head parameter approach, the \ac{VO} sequence reflects head-initial structure where the verbal head precedes its complement/direct object. The \ac{OV} order, on the contrary, exhibits head-final structure where the verbal head follows its complement. (\ref{ex:45}a) and (\ref{ex:45}b) represent the syntactic structure of \ac{VO} and \ac{OV}, respectively.
\ea\label{ex:45}
\begin{tabular}[t]{llll}
a. &
\begin{forest}
[VP[V][OBJ]]
\end{forest} &
b. &
\begin{forest}
[VP[OBJ][V]]
\end{forest}
\end{tabular}
\z
In a given language, heads may consistently occur either in the initial position or in the final position within a phrase, regardless of their category, as in English and Korean/Japanese, respectively.\footnote{\textrm{Japanese also exhibits head-final structure, similar to Korean.}} However, the positioning of a head may also vary with respect to its complement. For instance, in Chinese, the verbal head precedes its complement, but the nominal head follows its complement \citep{Huang1982}. Similarly, in Dutch and German, verbs canonically follow their complements, but other heads are arguably positioned before their complements in their canonical order (\citealt{Koster1975}).
One may argue that this is due to the fact that the directionality parameter can be set differently for different heads: in Chinese, for example, the verbal head has the head-initial setting of the parameter, but the nominal head is equipped with the head-final setting. Although the (category-specific) head parameter approach may be descriptively adequate to explain various word order patterns found within a language as well as across languages, it is still problematic. As \citet{Dryer1992} notes, “disharmonic” systems or languages exhibiting a mix of head-initial and head-final orders in fact outnumber harmonic ones or languages with a more rigid word order in the world, thus it raises questions regarding the role of parameter setting in these languages and across languages.
While Dryer’s criticism is concerned with the surface order parameterized by the head parameter, which does not seem to be uniform, the head directionality parameter was identified either as a surface structure condition or a deep structure condition in the Government and Binding theory. At the surface structure level, the directionality parameter was stated over Case assignment. For instance, \citet{Koopman1984} and \citet{Travis1984} argue that Case assignment is directional, which is parameterized differently from language to language. At the deep structure, the directionality parameter was formulated in terms of the directionality of government \citep{Kayne1983} or theta-role assignment (\citealt{Koopman1984,Travis1984}), which was considered to be parameterizable at that time. Under these views, the head-initial vs head-final structure in (\ref{ex:45}a) and (\ref{ex:45}b) can be restated that the verbal head governs/Case-assigns/theta-role assigns the object to the right in the former and to the left in the latter, which is subject to parametric variation.
Whether the head directionality is parameterized at the surface structure or the deep structure, such parameterization cannot be sustained in modern syntactic frameworks such as minimalist syntax (\citealt{Epsteinetal1996}). With the introduction of the Minimalist Program, the notion of government, which played an essential role in Government and Binding theory, has been abolished, thus the directionality of government is no longer expressible. In addition, Case is no longer viewed to be assigned by a head, but is restated as feature matching between a probe (a functional head) and a goal. Most importantly, the notion of parameters was restricted by \citet{Borer1984} to ``the idiosyncratic properties of lexical items'' where lexical items are equivalent to grammatical elements such as inflection. This idea was endorsed by Chomsky in the Minimalist Program, which \citet{Baker2008} calls \textit{The Borer-Chomsky Conjecture} \REF{ex:BorChomCon}.
\ea\label{ex:BorChomCon} \textbf{The Borer-Chomsky Conjecture} \\
All parameters of variation are attributable to differences in the features of particular items (e.g. the functional heads) in the lexicon.
\z
In other words, parametric variation is confined to morphosyntactic features of functional categories. As a result, the directionality parameter cannot be stated over theta-role assignment either, since theta-roles are assigned by lexical categories and the old head parameter has been modified by setting parameters on functional heads rather than lexical heads. As we will see in subsequent chapters, the Borer-Chomsky Conjecture in \REF{ex:BorChomCon} will be one of the most important theoretical notions that are adopted in this monograph to explain \ac{OV}-\ac{VO} variation across languages as well as in \ac{CS}.
\section{Derivational approach}\label{ch3:sect:3.2}
With the postulation of deep structure vs surface structure in generative linguistics, linguists started to postulate the possibility to derive surface structure from its deep structure via transformations in order to explain various sentence types. \citet{Bach1962} proposed the \ac{VO} order of German is derived from \ac{OV} via a transformation. This suggests that \ac{OV} and \ac{VO} orders may share the same underlying structure, which is in this case \ac{OV}. \citet{Bach1968} extended this idea and proposed the Universal Base Hypothesis, which states that all languages have identical deep structures and surface structures are derived via language-specific transformation. Such a transformational approach can explain unexpected/exceptional word orders besides the orders of cross-linguistic tendencies, which the head parameter approach fails to describe: ``Languages are consistent at Deep Structure in having head-initial or head-final characteristics, but transformations may give rise to surface inconsistencies'' \citep[4]{Svenonius2000}.
\largerpage%longdistance
However, due to poor understanding of the exact nature of the so-called lan\-guage-specific transformations (e.g. What triggers transformations? What constrains them?), the Universal Base Hypothesis faced criticism and was not in vogue for a long time. Yet, transformational grammar has become considerably more restrictive and principled over the years, and the idea that all languages have the same underlying structure has been revived, especially with the advent of the Minimalist Program.
Researchers who adopt a derivational approach to deriving \ac{OV} vs \ac{VO} order are roughly divided into two groups; one who argues that \ac{OV} is derived from \ac{VO} (e.g. \citealt{Kayne1994}) and another who argues that \ac{VO} is derived from \ac{OV} (e.g. \citealt{Haider1992}). There are also a small number of scholars who also take an intermediary position between these two competing views, claiming that surface word order can be base-generated, as the head parameter approach suggests, or one order can be derived from the other (e.g. \citealt{Vicente2004}). However, as discussed earlier, the head parameter approach is no longer formulable on minimalist assumptions due to the fact that it has lost its theoretical foundations, and the hybrid approach combining the head parameter approach and the derivational approach does not provide any substantial advantage over a pure derivational approach. Thus, I will not discuss the hybrid approach here and will review the two competing views on deriving \ac{OV} and \ac{VO} order in the following sub-sections, namely (i) \ac{OV} is derived from \ac{VO} and (ii) \ac{VO} is derived from \ac{OV}.
\subsection{OV is derived from VO}\label{ch3:sect:3.2.1}
\largerpage%longdistance
In his seminal work, \textit{The Antisymmetry of Syntax}, \citet{Kayne1994} proposes, among other things, that the sequence of Specifier-Head-Complement is the universal order in all languages, which is imposed by \ac{UG}. He argues that:
\begin{quote}
If \ac{UG} unfailingly imposes \textsc{s-h-c} order, there cannot be any directionality parameter in the standard sense of the term. The difference between so-called head-initial languages and so-called head-final languages cannot be due to a parametric setting whereby complement positions in the latter type precede their associated heads. Instead, we must think of word order variation in terms of different combinations of movements. \\
\hspace*{\fill} (\citealt[47]{Kayne1994})
\end{quote}
According to Kayne, \ac{UG} only allows the ({Spec})-Head-Complement sequence underlyingly, and the surface Complement-Head order must be derived from it. This proposal is part and parcel of his \acf{LCA}, which states that asymmetric c-command invariably maps into linear precedence, and word order is determined by hierarchical syntactic structure. Kayne further argues that surface \ac{OV} order is derived from its underlying \ac{VO} structure via object movement; the object raises to the left of the position where the verb ends up (1994: 48). He does not specify where exactly the object raises in the structure, but it is argued to move leftward past the verbal head into some specifier position. On this view, languages exhibiting either \ac{OV} or \ac{VO} as their canonical word order have the universal \ac{VO} structure underlyingly, and \ac{OV} languages (e.g. Korean, Japanese) invariably involve object movement to a position to the left of the verb (\citealt{Kayne2003}).
However, researchers note that the object may also move from its base position in \ac{VO} languages . In Scandinavian languages, for instance, objects can move clause-internally to a position outside \ac{VP}, which is referred to as \textit{object shift} (\citealt{Holmberg1986}). The relevant examples are provided in \REF{ex:47} and \REF{ex:48} below.
\ea\label{ex:47}
\glllll nemandinn las ekki bókina {} {} {} {} Icelandic \\
studenten laeste ikke bogen {} {} {} {} Danish\\
naemingurin las ikki bókina {} {} {} {} Faroese\\
studenten läste inte boken {} {} {} {} Swedish \\
student-the read not book-the {~~~~~~} {} {} {} \\
\glt `The student didn't read the book.'
\ex\label{ex:48} \glllll nemandinn las \textbf{hana}$_i$ ekki t$_i$ {} {} {} Icelandic \\
studenten laeste \textbf{den}$_i$ ikke t$_i$ {} {} {} Danish\\
naemingurin las \textbf{hana}$_i$ ikki t$_i$ {} {} {} Faroese\\
studenten läste \textbf{den}$_i$ inte t$_i$ {} {} {} Swedish \\
student-the read it not {} {~~~~~~~~} {} {} \\
\glt `The student didn't read the book.' adopted from \citet{Thrainsson1996}
\z
\largerpage[2]
In \REF{ex:47} the full \ac{NP} object follows the verb and negation.\footnote{The object can appear between the verb and the negation in Icelandic, similar to (\ref{ex:47}a), whereas this is not possible in the other languages.} But when the object is realized as an unstressed definite pronoun as in \REF{ex:48}, it precedes negation (and adverbs) but follows the subject and the verb. It is generally agreed in the literature that the pronominal object in \REF{ex:48} has moved out of its base position into a position outside the \ac{VP} along with verb movement, and the landing site of the shifted object is argued to be Spec, AgrOP, a specifier position of a functional projection outside the \ac{VP} (\citealt{Deprez1989,JonasBobaljik1993,Ferguson1996,Thrainsson1996}).\footnote{Assuming that a sentential adverb or the negation is adjoined to \ac{VP}, some researchers propose an alternative analysis that the object in object shift constructions in \REF{ex:48} moves to a \ac{VP} adjoined position, as in \REF{ex:fn27} (\citealt{Holmberg1986,HolmbergPlatzack1995}).
\ea\label{ex:fn27}
~[\textsubscript{VP} OBJ\textit{\textsubscript{i}} [\textsubscript{VP} AdvP [ V t\textit{\textsubscript{i}} ]
\zlast}
\clearpage
The derivation in \REF{ex:49} illustrates object shift in \ac{VO} languages.
\ea \label{ex:49}
\begin{forest}
[AgrOP [OBJ\textsubscript{i}, name = tgt]
[VP [AdvP]
[VP [V] [t$_i$, name = src]]]]
\draw[->,dashed] (src) to[out=south,in=south] (tgt);
\end{forest}
\z
In \REF{ex:49} the object moves out of its post-verbal base position, whish results in surface \ac{OV} order in \ac{VO} languages. Chomsky initially identifies AgrO (Agreement Object) as a functional category that triggers object shift. If the (Case) feature on AgrO is strong, it triggers object shift, resulting in \ac{OV} order whenever the verb does not raise to a position higher than the landing site of the shifted object. If the (Case) feature of AgrO is weak, the object remains in situ, therefore the underlying \ac{VO} order surfaces. In other words, the \ac{OV}-\ac{VO} distinction results from \textit{overt} vs \textit{covert} object movement due to the strong vs weak feature on a functional head above \ac{VP}.
Chomsky argues that syntactic movement is a result of feature checking. Only functional categories could arguably host strong features, thus, a strong feature on a functional head triggers overt movement in the derivation, while weak features of a functional head do not trigger overt syntactic operations, thus movement is covert.\footnote{\textrm{(Overt) object movement, (overt) object raising, and object shift are used interchangeably in this monograph.}} According to Chomsky, the term \textit{features} refers to the properties of language that enter into two interface levels, \acf{PF} and \acf{LF}, and the computational system that generates them (2000: 91).\footnote{\textrm{Chomsky adopts Aristotle’s view of language as sound with meaning and argues that I(nternal)-language, which is a hierarchically structured expression (syntax), provides instructions to the thought system (or the Conceptual-Intentional system or semantics) and the sound system (or the Articulatory-Perceptual system or phonology). This is often called the Y-model in the field of generative linguistics.} }
The motivation for AgrO (along with AgrS(ubject)) was that objects (and subjects) may agree with the finite verb in heavily inflected languages like Xhosa (\ref{ex:50}a) or Quechua (\ref{ex:50}b).
\ea\label{ex:50}\ea
\gll u-mama u-ya-wu-phek-a um-ngqsuaho \\
1a-mother 1a-\textsc{pres}-3-cook-\textsc{asp} 3-samp \\
\hfill Xhosa
\glt ‘Mother cooks samp.’
\ex \gll \textit{pro} riku-wa-rqa-nki \textit{pro} \\
{} see-1\textsc{sg}-\textsc{past}-2 {}
\\
\hfill Quechua
\glt `You saw me.' \citep{DenDikken2016}
\z
\z
Chomsky later replaced AgrO with \textit{v} (\citeyear{Chomsky1995,Chomsky1998}).\footnote{\label{fn:30}According to Chomsky, \textit{v} has two sub-types,\textit{v} and \textit{v}*. While \textit{v} heads intransitive constructions and does not assign (accusative) Case, \textit{v}* \textrm{heads transitive constructions and assigns (accusative) Case. Under this view, it is} \textit{v}* \textrm{, not} \textrm{\textit{v}}\textrm{, which has a strong feature and triggers object shift. I will not distinguish} \textrm{\textit{v}} \textrm{and} \textrm{\textit{v}}\textrm{\textsuperscript{*}} \textrm{in this monograph for the sake of simplicity.}} In addition, strong vs weak features are formulated in different terms, as is the presence vs the absence of the \ac{EPP} feature; while a functional category with the \ac{EPP} feature triggers an overt syntactic operation, a functional category lacking the \ac{EPP} feature does not do so. The term \textit{\ac{EPP}} stands for the \textit{\acl{EPP}}, which originally demanded simply that a clause must have a subject \citep{Chomsky1982}. Since the nineties, generative linguists have extensively subscribed to the view that subjects originate as Specifiers of \textit{v}P/\acp{VP} (\ac{VP} internal subject hypothesis). Under this view, the \ac{EPP} requires that the subject that is base-generated at Spec, \textit{v}P raises to Spec, \ac{TP}. Chomsky reformulates the \ac{EPP} as a morphological property of T with a strong (D-) feature, which forces Spec, \ac{TP} to be lexicalized by raising an element. The \ac{EPP} feature was considered as an independent feature on T, triggering syntactic movement of a phrase to its specifier position. However, the application of the \ac{EPP} feature has been extended, and Chomsky started using the term \textit{\ac{EPP} feature} to refer the property of a functional head that triggers overt syntactic movement to its specifier position in general.\footnote{There have been attempts to eliminate the \ac{EPP} (e.g. \citealt{Boskovic2002,GrohmannEtAl2000}), yet the \ac{EPP} is widely assumed and in practice in current generative syntax.}
Although the structure in \REF{ex:49} was originally proposed for object shift in \ac{VO} languages, we can extend this analysis to \ac{OV} languages as well, such as Korean and Japanese. Following Kayne’s derivarational approach that surface \ac{OV} order is derived from its underlying \ac{VO} order in \ac{OV} languages, it is likely that the mechanism that is responsible for object shift in \ac{VO} languages is similar to, or even quite possibly identical to the mechanism that is responsible for the derivation of \ac{OV} order from \ac{VO} order in \ac{OV} languages; what is common is that the object leaves its base-generated position and raises to a position higher than the verb both in object shift in \ac{VO} languages and \ac{OV} languages. Thus, one can say that the landing site for the derived object proposed for object shift in \REF{ex:49} is also a possible landing site for the moved object for \ac{OV} languages, which is endorsed by \citet{Kayne2003} and many others.\footnote{\citet{Ochi2009}, for instance, proposes that the \ac{DP} object overtly raises to Spec, \textit{v}P from its underlying position inside the \ac{VP} in Japanese.} On this assumption, the contrast between \ac{OV} languages (e.g. Korean and Japanese) and \ac{VO} languages (e.g. English) can be also explained on the hypothesis that while the \ac{EPP} feature on \textit{v} triggers object raising in \ac{OV} languages, in \ac{VO} languages, the \ac{EPP} feature is absent on \textit{v}.\footnote{In
all Scandinavian languages, indefinite quantified negative objects move to a pre-verbal position, which \citet{Christensen2004} calls \textsc{neg}-shift, showing that \ac{VO} languages may also exhibit \ac{OV} order on the surface.
\ea\label{ex:fn33}
\glll a. {*} jeg har faktisk [\textsubscript{NegP} {} [\textsubscript{\textit{v}P} set \uline{ingenting} ]] {\ldots} {\ldots og det har du heller ikke}.\\
b. {} jeg har faktisk [\textsubscript{NegP} \uline{ingenting}$_i$ [\textsubscript{\textit{v}P} set t$_i$ ]] {\ldots} {\ldots and that have you neither not}\\
{} {} ~I have actually {} nothing {} seen {} {}\\\hfill Danish\vspace*{-\baselineskip}
\glt `I haven't actually seen anything and neither have you.' (\citealt[1, (1)]{Christensen2004})
\z
The fact that \ac{VO} languages may also exhibit \ac{OV} order as in Scandinavian languages shown above seems to suggest that the \ac{EPP} property on \textit{v} may not be entirely absent in all \ac{VO} languages, especially under the assumption that the mechanisms responsible for object shift in \ac{OV} languages and \ac{VO} languages are alike or even identical, as I assumed in this monograph. Under this approach, the key difference of object movement between \ac{OV} and \ac{VO} languages is that the object moves along with verb movement in \ac{VO} languages. However, movement of the bare quantified object in \REF{ex:fn33} differs from object shift, which depends on verb movement, and the object is generally assumed to move to Spec, NegP (\citealt{Haegeman1995,HaegemanZanuttini1991,Jonsson1996,Kayne1998,Platzack1998,Rognvaldsson1987,Sells2000,Svenonius2002}). \citet{Christensen2004} argues that this movement is driven by the \ac{EPP} of an uninterpretable feature [\textit{u}Quant] on C (more precisely, the Fin head) via Spec, \textit{v}P as an escape hatch. Taking these lines of thought together, it is reasonable to assume that the mechanisms responsible for object shift in \ac{OV} and \ac{VO} languages are not identical and the \ac{EPP} on \textit{v} is absent in \ac{VO} languages altogether and object shift is triggered by something else in \ac{VO} languages. I will leave this for future research.
} The tree structures in \REF{ex:51} illustrate overt vs covert object movement, triggered by the [+\ac{EPP}] vs [$-$\ac{EPP}] features on \textit{v}. One cautionary note made here is that $\pm$ features indicate the presence and the absence of the features, which does not imply that features are binary.
\newpage
\ea\label{ex:51}\adjustbox{width=0.9\textwidth}{
\begin{tabular}[t]{llll}
a. & \textsc{ov} languages & b. & \textsc{vo} languages \\ && \\
& \begin{forest}
[\textit{v}P,s sep=12mm [OBJ$_i$,name=tgt]
[\textit{v}’,s sep=2mm [\textit{v}\\{[+\textsc{epp}]}]
[VP [V][t$_i$,name=src]]]]
\draw[->, dashed] (src) to[in=south,out=south west] (tgt);
\end{forest}
& & \begin{forest}
[\textit{v}P, s sep=6mm [\textit{v}\\{[-\textsc{epp}]}]
[VP[V][OBJ]]]
\end{forest}
\end{tabular} }
\z
In this monograph, I adopt the original proposal on \textit{v} by Chomsky in the Minimalist Program, in which \textit{v} is regarded as a Case-checking/assigning light verb.\footnote{This view is also shared by \citet{HaleKeyser1993}, who consider that light verbs are \textit{i} and lexical verbs are V.} I assume that \textit{v} is one of possible functional categories that represent a light verb and besides \textit{v}, other verbal functional categories can or may correspond to light verbs. Also the precise syntax of light verbs differs across languages (\citealt{Adger2003,Butt2003}). Based on this, I propose that Korean/Japanese light verbs and English light verbs represent different functional categories in the structure, and their syntax also differs, as described in \REF{ex:52} and \REF{ex:53}.
\ea\label{ex:52}
\ea The Korean and Japanese light verbs \textit{ha} and \textit{su} in the [bare verbal noun + \textit{ha/su}] construction lexicalize the functional category \textit{v}.
\ex In English, \textit{v} is never overtly lexicalized (cf \citealt[351]{Chomsky1995}). Instead, English light verbs represent a different functional category, A\textsc{spect}, which is projected between \textit{v} and V.\footnote{The presence of the functional category \ac{ASP} between \textit{v} and V was also proposed by \citet{Richardson2003} for Russian and by \citet{Travis2000,Travis2010} as a general \ac{VP} structure across languages.}
\z
\ex\label{ex:53}
\begin{tabular}[t]{ll}
a. & Korean and Japanese \\
& \begin{forest}
[\textit{v}P [SUB]
[\textit{v}$'$ [\textit{v}\textsuperscript{[+\textsc{epp}]} \\ \textit{ha}\textsuperscript{KR}/\textit{su}\textsuperscript{JP}]
[A\textsc{sp}P [A\textsc{sp} \\ $\varnothing$]
[VP [V][OBJ] ]]] ]
\end{forest}
\\
b. & English \\
& \begin{forest}
[\textit{v}P [SUB]
[\textit{v}$'$ [\textit{v}\textsuperscript{[-\textsc{epp}]} \\ $\varnothing$ ]
[A\textsc{sp}P [A\textsc{sp} \\ LV\textsuperscript{ENG}]
[VP [V][OBJ] ]]] ]
\end{forest}
\end{tabular}
\z
In (\ref{ex:53}a) the Korean light verb \textit{ha} and the Japanese light verb \textit{su} lexicalize \textit{v}, which takes the \ac{ASP} as its complement in which the underlying order is \textit{ha}-V-O in Korean and \textit{su}-V-O in Japanese. However, surface order is O-V-\textit{ha} in Korean and O-V-\textit{su} in Japanese, as indicated in \REF{ex:54}. The surface \ac{OV}-\textit{ha}/\textit{su} order in Korean and Japanese is derived from the underlying \textit{ha}/\textit{su}-\ac{VO} order via two steps: (i) First, the object raises to Spec, \ac{ASP}, which results in \ac{OV} order within \ac{ASP}, as in \REF{ex:55}. After that, (ii) the entire \ac{ASP} raises to Spec, \textit{v}P, yielding \ac{OV}-\textit{ha}/\textit{su} order, as in \REF{ex:56}. Both of these movements, object movement and \ac{ASP} raising, are a consequence of feature specifications on \textit{v} and valuation of these features in a derivation, which will be discussed in detail in Chapter \ref{ch:4}.
\ea\label{ex:54}
\ea{
\gll ~~nemwu manh-un ton-ul sopi hayss-eyo \\
~~too much-\textsc{rel} money-\textsc{acc} spend \textsc{do}.\textsc{past}{}-\textsc{decl} \\} \hfill Korean
\glt ~~`He spent too much money.'
\ex[*]{\gll hayss-eyo nemwu manh-un ton-ul sopi \\
\textsc{do}.\textsc{past}{}-\textsc{decl} too much-\textsc{rel} money-\textsc{acc} spend \\}
\ex{ \gll ~~ichi-mon daisu-no mondai-o saiten site \\
~~one-\textsc{clf} algebra-\textsc{gen} question-\textsc{acc} mark \textsc{do} \\} \hfill Japanese
\glt ~~`You mark one algebra question.'
\ex[*]{\gll site ichi-mon daisu-no mondai-o saiten \\
\textsc{do} one-\textsc{clf} algebra-\textsc{gen} question-\textsc{acc} mark \\}
\z
\ex\label{ex:55}
\begin{forest}
[\textit{v}P, s sep = 45mm [\textit{v} {=} \textit{ha}\textsuperscript{KR}/\textit{su}\textsuperscript{JP}]
[A\textsc{sp}P [OBJ$_i$, name=tgt]
[A\textsc{sp}P [A\textsc{sp} \\ $\varnothing$]
[VP [V][t$_i$,name=src]]]]]
\draw[->,dashed] (src) to [in=south,out=south west] (tgt);
\end{forest}
\ex\label{ex:56}
\begin{forest}
[\textit{v}P
[A\textsc{sp}P$_k$,name=tgt [\textbf{OBJ}$_i$]
[A\textsc{sp}P [A\textsc{sp} \\ $\varnothing$]
[VP [V][t$_i$]]]]
[\textit{v}$'$[\textit{v} {=} \textit{\textbf{ha}}\textsuperscript{KR}/\textit{\textbf{su}}\textsuperscript{JP}][t$_k$,name=src]]
]
\draw[->,dashed] (src) to [in=south east,out=south west] (tgt);
\end{forest}
\z
Before we discuss the structure of English light verbs in (\ref{ex:53}b) where light verbs exemplify the functional category \ac{ASP}, let me say a few words about aspect. The term \textit{aspect} here refers to the properties of the event-structural organization of a verb phrase, and various terms, such \textit{lexical aspect}, \textit{semantic aspect}, \textit{situational aspect}, \textit{inner aspect}, \textit{event structure}, \textit{Aktionsart}, have been proposed in the literature, referring to \citegen{Vendler1957} classification of verb types: states, activities, achievements, and accomplishments.\footnote{This is distinguished from \textit{grammatical aspect}, which has also been referred to as \textit{viewpoint aspect} or \textit{outer aspect} or \textit{morphological aspect}.} In the past, the event structure of a verb phrase was typically considered to belong to semantics, not syntax. However, as \citet[18]{TennyPustejovsky2000} point out, event structure has been directly encoded in syntax as well with recent developments in syntactic theory, especially with the articulation of extended \ac{VP}s and functional projections. Although researchers have different opinions about where an aspect node is projected in the syntax, such as above \textit{v}P/\ac{VP} \citep{Borer1998}, on \textit{v}P/AgrOP (\citealt{RitterRosen2000}), or between \textit{v}P and \ac{VP} (\citealt{Richardson2003,Travis2000,Travis2010}; cf \citealt{Ramchand2008}), it is generally agreed that an aspect node is a functional category of the extended verbal projection.
The presence of the functional category \ac{ASP} between \textit{v} and V, as proposed in \REF{ex:53}, was also suggested by \citet{Richardson2003} for Russian and by \citet{Travis2000,Travis2010} as a general \ac{VP} structure across languages. Richardson assumes that \ac{VP}s in Russian per se are not an aspectual domain and argues that with the projection of \ac{ASP} above \ac{VP}, the event structure of the \ac{VP} is calculated.\footnote{\textrm{However, Richardson also argues that there are inherently telic verbs in Russian, and A}\textrm{\textsc{sp}}\textrm{P can sometimes merge in a derivation with a telicity feature whose value is not set, therefore having uninterpretable aspectual feature (2003: 59).}} Richardson’s event structure is illustrated in \REF{ex:57} below.
\ea\label{ex:57}
\begin{forest}
[\textit{v}P [~~~]
[A\textsc{sp}P [~~~] [VP]]{ \draw (.east) node[right]{ $\rightarrow$ Semeantic aspect/event structure}; }
] { \draw (.east) node[right]{ $\rightarrow$ Light verb phrase}; }
\end{forest}
\z
\citet{Travis2000} also provides morphological and syntactic evidence from languages like Tagalog and Navajo, where an aspectual morpheme may appear between the two verbs (V\textsubscript{1} and V\textsubscript{2}) in reduplication, and proposes the layered \ac{VP} structure in \REF{ex:58}.
\ea\label{ex:58}
\begin{forest}
[V$_1$P [SUB]
[V$_1'$ [V$_1$]
[A\textsc{sp}P [~~~]
[A\textsc{sp}' [A\textsc{sp}]
[V$_2$P [OBJ]
[V$_2'$ [V$_2$][PP]]]]]]]
\end{forest}
\z
\largerpage[-1]
Travis assumes the \ac{VP} structure is layered as in \citet{Larson1988}, in which the direct object merges at [Spec, \ac{VP}] while the indirect object that is headed by a preposition appears as the complement of the verb in double object constructions. Within the layered \ac{VP} in \REF{ex:58}, there is a functional category \ac{ASP} between V\textsubscript{1} and V\textsubscript{2}. Though V\textsubscript{1} seems to correspond to \textit{v}, Travis claims that both V\textsubscript{1} and V\textsubscript{2} are lexical categories, following the more restricted distinction between lexical and functional categories; only lexical categories introduce arguments (\citealt{Abney1987}). Travis states that “V\textsubscript{1,} although lexical, is closer to a light verb” (\citeyear[12]{Travis2000}).
Returning to the structure in (\ref{ex:53}b), now I proceed to explain why English-type light verbs are analyzed as lexical roots corresponding to the functional category \ac{ASP} rather than lexicalizing the verbal head V in \ac{VP}, which was discussed in \citet{DenDikkenShim2011}. Aktionsart or the event structure of a \ac{VP} is not an inherent property of a verb but is normally determined jointly by the verbal head and its complement (\citealt{Dowty1979,Tenny1994,VanVoorst1988,Verkuyl1972,Verkuyl1993}). For instance, while \textit{he ate an apple} is categorized as an accomplishment in Vendler’s term, having both an initial and an end point, \textit{he ate apples}, with a bare-plural object, is categorized as an activity, which is not bounded terminally. However, in a light verb construction with the light verb \textit{take}, for instance, the aspectual properties of the verb phrase are not decided by the light verb and its complement combined. Instead the aspectual constitution of the light verb + complement combination is the same as that of the corresponding ‘simple’ verb construction where the light verb’s complement is used as a verb. In \REF{ex:59}, for example, the object of \textit{take} is systematically an indefinite singular \ac{NP} (e.g. \textit{a look}, \textit{a walk}, \textit{a bath}, \textit{a decision}), but the aspectual properties of the \ac{VP} are not constant. In (\ref{ex:59}a-c) \textit{take}-\acp{LVC} (e.g. \textit{take a look}, \textit{take a walk}, \textit{take a bath}) denote activities or atelic, which is compatible with a durative temporal \textit{for}{}-phrase. On the other hand, \textit{take} \textit{a} \textit{decision} in (\ref{ex:59}d) indicates accomplishment or telic, thus incompatible with a \textit{for}-phrase, and an \textit{in}-phrase is an appropriate time-frame adverbial. Such different aspectual properties among \textit{take}-\acp{LVC}, (\ref{ex:59}a-c) vs (\ref{ex:59}s), are in fact in concert with the aspectual class of their corresponding simple verb constructions as shown in \REF{ex:60}: the \ac{VP}s in (\ref{ex:60}a-c) are atelic whereas the \ac{VP} in (\ref{ex:60}d) is telic.
\ea\label{ex:59}
\ea I took a look at it for/*in two seconds.
\ex I took a walk for/*in half an hour.
\ex I took a bath for/*in an hour.
\ex I took a decision in/*for one minute.
\z
\ex \label{ex:60}
\ea I looked at it for/*in two seconds.
\ex I walked for/*in half an hour.
\ex I bathed for/*in an hour.
\ex I decided in/*for one minute.
\z
\z
\largerpage[-1]
What is particularly interesting here is the fact that the verb \textit{walk} in (\ref{ex:60}b) can be made compatible with an \textit{in}-phrase by adding an event-delimiting \ac{PP} in the complement of \textit{walk} such as \textit{around the block} as in (\ref{ex:61}a). Likewise, the effect of the \ac{PP} is the same both in the corresponding in the light verb case, as a comparison of (\ref{ex:61}a) and (\ref{ex:61}b) shows.\footnote{\textrm{It seems that the the aspectual properties may not be the same between (\ref{ex:61}a) and (\ref{ex:61}b) if the tense is changed into future:} \textrm{(i) I will walk around the block in five minutes}\textrm{(ii) I will talk a walk around the block in five minutes} While both (i) and (ii) can mean the speaker will begin to walk around the block in five minutes, there is an additional ‘telic’ meaning in (i), in which the event of walking will be terminated in five minutes. While this was not shared by all four native speakers of English that I consulted, the speaker who suggested this possibility mentioned that in order to get this additional reading, there should be a prosodic emphasis in speech, which indicates that the informational structure may not be the same. While I maintain that English light verbs do not contribute to the event structure, some researchers have argued that light verbs may contribute to the event structure based on languages other than English such as Hindi (\citealt{Mohanan2006}). }
\newpage
\ea\label{ex:61}
\ea I walked around the block in five minutes.
\ex I took a walk around the block in five minutes
\z
\z
We see that the aspect properties of \textit{take} light verb constructions are entirely a function of the aspect properties of the nominal and its complement. The light verb itself takes no controlling part in this. On the assumption that Aktionsart is determined compositionally by material contained in the lexical projection of the predicate head, this informs us that in light verb constructions, the light verb is not contained in the lexical projection of the predicate head.\footnote{\textrm{I consider \ac{VP} to be the domain of aspect computation by assuming that \ac{VP} has [Asp] feature. This assumption will play an important role in Chapter 4 where the \textit{v} -A}\textrm{\textsc{sp}} \textrm{structure in Korean and Japanese is developed in great detail under the feature inheritance system.}} In effect, it tells us that the light verb itself is not the predicate head: instead the noun heading the light verb’s complement is. But of course the light verb does have a close relationship with that noun: \textit{take} selects \textit{a} \textit{walk}. So the light verb must be merged directly with the projection of the noun.\footnote{\textrm{This idea will be} \textrm{reflected in the tree structure later where \ac{ASP}} \textrm{lexicalized by an English light verb directly takes the \ac{DP} object phrase as its complement without there being the projection of \ac{VP} in (\ref{ex:67}).}} This is guaranteed if the light verb realizes \ac{ASP}, the functional head that takes the lexical projection of the predicate head as its complement. The light verb itself does not participate in the determination of the aspectual properties. Rather, it lexicalizes the functional head by whose complement these properties are determined. It is this on this basis that I propose that English-type light verbs lexicalize \ac{ASP}.
\subsection{VO is derived from OV}\label{ch3:sect:3.2.2}
While the view that \ac{VO} is the underlying order for \ac{OV} (à la Kayne) has prevailed in generative syntax, a small number of researchers proposed an opposite view that \ac{VO} order is derived from \ac{OV} order, based on an observation of peculiar properties about word orders across languages. Cross-linguistic data show that not only the direct object but also other verbal complements precede the verb in \ac{OV} languages while they follow the verb in \ac{VO} languages, as presented in \REF{ex:62}. In (\ref{ex:62}a), the direct object \textit{Joa}, the indirect object \textit{a present} and the prepositional phrase \textit{to her house} all follow the verb \textit{sent} in a \ac{VO} language like English whereas they all precede the verb in \ac{OV} languages such as in Korean (\ref{ex:62}b) or Japanese (\ref{ex:62}c).
\ea\label{ex:62}\ea Bibi sent Joa a present to her house.
\ex \gll Bibi-ka Joa-eykey senmwul-ul cip-ulo ponay-ess-ta \\
Bibi-\textsc{nom} Joa-\textsc{dat} present-\textsc{acc} house-\textsc{loc} send-\textsc{past-decl} \\
\newpage
\ex \gll Bibi-ka Joa-ni purezento-o ie-ni okuta-ta \\
Bibi-\textsc{nom} Joa-\textsc{dat} present-\textsc{acc} house-\textsc{loc} send-\textsc{past} \\
\glt ‘Bibi sent Joa a present to (her) house.’
\z \z
The placement of verbal complements with respect to the verb in \REF{ex:62} can be predicted by Kayne's theory: it is a result of raising verbal complements out of \ac{VP} in the case of \ac{OV} languages while such movement does not happen in \ac{VO} languages. In addition to Korean and Japanese, which are typologically unrelated to English, Germanic \ac{OV} languages such as German and Dutch also support Kayne’s prediction that verbal complements precede the verb in \ac{OV} languages, as in \REF{ex:63} and \REF{ex:64}, respectively.
\ea\label{ex:63} \gll \ldots daß sie jedem ein Paket an seine Privatadresse schicken werden \\
\ldots that they everybody a package to his home.address send will \\ \hfill German
\glt `\ldots that they will send everybody a package to his home address.’ \citep{Haider1992}
\ex\label{ex:64}
\ea \gll \ldots~ dat Jan het boek aan Marie gaf \\
\ldots~ that John the book to Mary gave \\ \hfill Dutch
\glt `\ldots~ that John gave the book to Mary.'
\ex \gll \ldots~ dat Jan de doos op de tafel zette \\
\ldots~ that John the box on the table put \\
\glt `\ldots~ that John put the book on the table.' \citep{Barbiers2000}
\z
\z
The fact that all verbal complements precede the verb in various \ac{OV} languages can be explained as a result of multiple application of raising to the left to the verb in Kayne’s approach.\footnote{Marcel den Dikken (p.c.) points out that the \ac{PP} in (\ref{ex:64}b) can optionally surface to the right of the verb in Dutch (and to some extent in German as well). Also \ac{CP} complements generally must appear to the right of the verb in Dutch and German. The fact that \ac{PP} complements and \ac{CP} complements surface to the right of the verb in Dutch and German can be accounted for by the object shift-based analysis: \ac{PP}s and \acp{CP} do not have a Case feature to check against AgrO and hence are expected to stay in situ.} However, \citet{Haider1992,Haider2000} addresses peculiar properties found in German which challenge Kayne’s analysis. \citet{Haider1992} observed that the linear order of preverbal arguments in German is the same as that of postverbal arguments in English; in \REF{ex:63} the complements of the verb are ordered with respect to one another in the following order both in German and English: \acf{IO} - \acf{DO} - \acf{PP}.\footnote{The linear order of \ac{IO}-\ac{DO}-\ac{PP} is also observed in Korean and Japanese in (\ref{ex:62}b, c) and Dutch in \REF{ex:64}. In addition, \citet[183]{Barbiers2000} shows that in double object constructions, the only allowed order is \ac{IO}-\ac{DO} both in Dutch and English.
\ea
\gllll a. {} dat Jan {\longrule} Marie het boek gaf. \\
a.$'$ {} that John gave Mary the book {\longrule} \\
b. * dat Jan {\longrule} het boek Marie gaf \\
b$'$. * that John gave the book Mary \\
\zlast
}
If we assume that the ordering of the arguments inside the \ac{VP} in English is the underlying structure, as \citet{Kayne1994} claims, one must provide further explanation of how this initial order must be preserved after a series of movement operations in German, which is lacking in his proposal. There are proposals in the literature to explain order preservation along with object shift in Scandinavian languages where the initial order inside the \ac{VP} is preserved after the object raises. \citet{FoxPesetsky2005}, for instance, propose a mapping mechanism between syntax and phonology, which determines the linear ordering of words. Such linearization is restricted by two constraints; (a) the relative ordering of words is fixed at the end of each phase (or spell-out domain) and (b) ordering established in an earlier phase may not be revised or contradicted in a later phase. According to their proposal, the fact that the initial order V-\ac{IO}-\ac{DO}-\ac{PP} within the \ac{VP} is preserved can be explained by a combination of object shift and \ac{VP}-remnant movement. Although their proposal accounts for order preservation along with object shift in Scandinavian languages where the verb still precedes the object after the object raises as exemplified in \REF{ex:47}, it fails to describe order preservation in \ac{OV} languages where the initial order starts as \ac{VO} but ends up in \ac{OV}.
To account for the same linear order effect in German and English, Haider proposes as an alternative view that \ac{VO} is derived from \ac{OV} via V head movement, which keeps the underlying order of the verbal arguments intact after transformation \REF{ex:65}.
\ea\label{ex:65}
\ea ~[ IO [ DO [ PP V ]]]
\ex ~[ V\textit{\textsubscript{i}} [ IO t\textit{\textsubscript{i$''$}} [ DO t\textit{\textsubscript{i$'$}} [ PP t\textit{\textsubscript{i}} ]]]]
\z
\z
The structure in (\ref{ex:65}a) is the head-final structure where V takes all of its complements to the left.\footnote{\citet{Haider1992} allows V to take its \ac{PP} argument to the right under his own theory, which does not concern us here.} According to Haider, the head-final structure in (\ref{ex:65}a), which he calls the right-branching structure, is the only structure that \ac{UG} allows: the structural build-up of phrases is universally right branching (Basic Branching Constraint: \citealt{Haider1992,Haider2000}). On this proposal, the head-initial structure is not allowed by \ac{UG} and \ac{VO} order is derived from leftward movement of the verb as shown in (\ref{ex:65}b).\footnote{However, linguists implement different mechanisms to derive \ac{VO} from \ac{OV}, either via head movement (raising V to the left of its complements: \citealt{Barbiers2000,Haider1992,Haider2000}) or phrasal movement (remnant \ac{VP} movement: \citealt{Taraldsen2000}).} What is also different between (\ref{ex:65}a) and (\ref{ex:65}b) is that the \ac{VP} structure in \ac{OV} languages is simpler than that of \ac{VO} languages, which shows a Larsonian \ac{VP} shell structure.
In the Minimalist Program, \textit{v} (and its variants) is a place where light verbs appear. On the other hand, \textit{v} has no special status in Haider’s proposal; it is one of the V positions in the shell structure of complex head-initial \ac{VP} and \textit{v} is entirely absent in \ac{OV} languages. Thus, it is not clear where a light verb is projected in an \ac{OV} language in (\ref{ex:65}a), which has a simple \ac{VP} structure. Since this monograph aims to investigate the role of light verbs in Korean-English and Japanese-English \ac{CS} in relation to deriving \ac{OV} and \ac{VO} orders, I will not consider Haider’s model where the position of light verbs of \ac{OV} languages is not identified in the syntax.\footnote{\citet{Haider2013} argues that \ac{OV} and \ac{VO} orders are not complementary and there is a third category which is underspecified for directionality (Type III), based on the diachronic Germanic word order split between \ac{OV} and \ac{VO} orders. As reported in Chapter 2, the distribution of \ac{OV} and \ac{VO} orders is not also perfectly complementary in Korean-English and Japanese-English \ac{CS}. It is especially true in light verb constructions with heavy/lexical verbs, which may alternate between \ac{OV} and \ac{VO} orders (Chapter \ref{ch:5}), and Haider’s proposal might be handy to account for this fact. However, as the reasons stated above, I will not follow this direction in this monograph. I thank the anonymous reviewer who referred to this work.}
\section{Minimalist approach}\label{ch3:sect:3.3}
\largerpage%longdistance
Generative linguists agree on the view that one of the most fundamental aspects of human language is its hierarchical structure. Yet, how hierarchical structure built with lexical items is mapped into a linear sequence is still a matter of debate \citep{Barrie2012}. \citet{Kayne1994} proposes that not only the hierarchical structure but also the linear order of combined words is established in syntax, as expressed in the \ac{LCA}: asymmetric c-command invariably maps into linear precedence and word order is determined by hierarchical syntactic structure. In the Minimalist Program, on the other hand, Chomsky proposes the bare phrase structure where structure is built via \textit{Merge}, which takes two lexical items ${\alpha}$ and ${\beta}$ and the linear order between them is unspecified but decided later at the syntax-\ac{PF} (Phonetic Form) interface. In other words, structure is built up hierarchically but actual word order is established after syntax when the lexical items are spelled out/pronounced. Yet, it is not clear how the linearization procedures occurs. Chomsky does not discuss it any further for it is beyond the syntax.
\largerpage%longdistance
Nonetheless, Chomsky accepts Kayne’s idea of the universal head-complement order (\acs{SVO}) and any deviation from this results from movement (\citeyear{Chomsky1995}: 340). Yet, the core idea of the \ac{LCA} seems to be incompatible with the bare phrase structure. Chomsky writes, ``the bare theory structure lacks much of the structure of the standard X-bar theory that plays a crucial role in Kayne’s analysis'' (\citeyear{Chomsky2015}: 208): there are no bar levels and no distinction between lexical items and heads projected from them (\citeyear{Chomsky2015}: 228). As mentioned earlier, the \ac{LCA} dictates that there exists an inherent asymmetry among lexical items. Under this view, it is not clear how a symmetric structure (between ${\alpha}$ and ${\beta}$) is converted into an ordered string in the bare phrase structure (\citealt{Zwart2011}).\footnote{Zwart proposes that Merge itself yields an ordered pair rather than an unordered set, which is expressed in his \textit{structure-to-order conversion}: The structure-to-order coversion is a correspondence rule, and (i) reads that the two lexical items ${\alpha}$ and ${\beta}$ are ordered as ${\alpha}$-${\beta}$.
\ea Structure-to-order conversion ~~~~~~~~~~ (\citealt[101]{Zwart2011}) \\
\textless ${\alpha}$, ${\beta}$ \textgreater = /${\alpha}$, ${\beta}$/
\zlast
}
To accommodate the \ac{LCA} in the bare phrase structure, the \ac{LCA} has been re-analyzed as an operation that applies to \ac{PF} and the violation of the \ac{LCA} (e.g. symmetric relations between two lexical items) must be eliminated before the structure is spelled out at \ac{PF} (\citealt{Chomsky1995,Moro2000}). One way to turn a symmetric relation between two lexical items into an asymmetric relation is to move (or the term \textit{internal merge} in the Minimalist Program) one lexical item, which leaves a trace. The trace of the moved element, which has no phonological value, is ignored/deleted at \ac{PF}, thus does not violate the \ac{LCA}: only a moved element, not the trace of it, is spelled out at \ac{PF}.
Depending on the branch of Minimalism one chooses to employ, one could choose between these two approaches to Merge: either (a) Merge itself imposes a linear order (as well as the hierarchical order) on the constituents it combines or (b) Merge imposes the hierarchical order but not the linear order \citep{OsborneEtAl2011}. Between these two options, the first one is more compatible with Kayne’s take on deriving word order.
In this monograph, I adopt general assumptions shared in the minimalist work. Although I assume that structure is built via Merge between two lexical items, I will not commit myself to the bare phrase structure in this monograph, but continue to use tree structure as in the X-bar theory. There are a few reasons to do so. First, it is for expository/notational purposes. Following the minimalist view that the locus of linguistic variation is due to different morphological features of a functional category rather than a lexical category (the Borer-Chomsky Conjecture), it is easy for me to explain if a clear distinction is made between the projection of functional categories (such as C, T, \textit{v}, \ac{ASP}) and that of lexical categories. In addition, if word order/linear order is regarded entirely as the property of \ac{PF}/phonology, as assumed in the bare phrase structure, it is not clear how parametric variations such as word order can be explained in terms of morphological features of functional categories, which should not play a role at \ac{PF}. Yet, the assumption that structure is built via Merge, which takes two lexical items, will be reflected in syntactic trees and this has a consequence in representation by dispensing an unnecessary projection of syntactic categories. For instance, the structure in \REF{ex:66}, which is repeated from (\ref{ex:53}b), where an English light verb directly lexicalizes \ac{ASP}, not V, thus leaving the V head empty, is simplified into the structure in \REF{ex:67} in which the empty V head is not projected. Instead, the light verb and the object merge, which is depicted in the structure where \ac{ASP} takes the \ac{DP}/\ac{NP} object as its complement.
\largerpage
\ea\label{ex:66}
\begin{forest}
[\textit{v}P [SUB]
[\textit{v}$'$ [\textit{v}\textsuperscript{[-\textsc{epp}]} \\ $\varnothing$ ]
[A\textsc{sp}P [A\textsc{sp} \\ LV\textsuperscript{ENG}]
[VP [V][OBJ] ]]] ]\end{forest}
\ex\label{ex:67} \textit{v}P structure with an English light verb ~~~~ (final version) \\
\begin{forest}
[\textit{v}P [SUB]
[\textit{v}$'$ [\textit{v}\textsuperscript{[-\textsc{epp}]} \\ $\varnothing$ ]
[A\textsc{sp}P [A\textsc{sp} \\ LV\textsuperscript{ENG}]
[OBJ] ]]]\end{forest}
\z
\clearpage
But notice that the functional category \textit{v} is empty in \REF{ex:67} and still projected. Likewise, when the functional category \ac{ASP} is null, it will be projected as well, as illustrated in \REF{ex:68}, which represents the underlying \textit{v}P structure with an English heavy verb.
\ea\label{ex:68} \textit{v}P structure with an English heavy verb \\
\begin{forest}
[\textit{v}P [SUB]
[\textit{v}$'$ [\textit{v}\textsuperscript{[-\textsc{epp}]} \\ $\varnothing$ ]
[A\textsc{sp}P [A\textsc{sp} \\$\varnothing$]
[VP [ HV\textsuperscript{ENG}][OBJ] ]]] ]\end{forest}
\z
In Chapter \ref{ch:4}, the special status of these two functional categories, \textit{v} and A\textsc{sp,} will be discussed in detail in the phase theory where \textit{v} is defined as a phase head and features are passed down from \textit{v} to \ac{ASP} via feature inheritance. And it will be argued that how features are specified on \textit{v} and valued via feature inheritance will lead to \ac{OV} and \ac{VO} variation in monolingual and bilingual grammars alike.
One final comment is in order. Although I take Kayne’s approach that the sequence of Specifier-Head-Complement is the universal order in all languages, I adopt the minimalist take on it: the \ac{LCA} is a constraint at \ac{PF}. This will provide an important set up for the next chapter, which introduces \textit{\acl{FI}}.
\subsection{Chapter summary and conclusion}\label{ch3:sect:3.4}
This chapter provided a short overview of different approaches to word order, with particular focus on \ac{OV} and \ac{VO} orders. After a close examination of different approaches to \ac{OV} and \ac{VO} orders, I have adopted Kayne’s proposal that both \ac{OV} and \ac{VO} languages have the same underlying \ac{VO} order and \ac{OV} order is derived from \ac{VO} by object movement to the left of the verb.
I have also proposed the syntax of light verbs in Korean, Japanese, and English, where Korean light verb \textit{ha} and the Japanese light verb \textit{su} represent the functional category \textit{v} whereas English light verbs exemplify the functional category \ac{ASP} as illustrated below.
\ea\label{ex:69}
\begin{tabular}[t]{ll}
a. & Korean and Japanese \\
& \begin{forest}
[\textit{v}P [SUB]
[\textit{v}$'$ [\textit{v}\textsuperscript{[+\textsc{epp}]} \\ \textit{ha}\textsuperscript{KR}/\textit{su}\textsuperscript{JP}]
[A\textsc{sp}P [A\textsc{sp} \\ $\varnothing$]
[VP [V][OBJ] ]]] ]
\end{forest}
\\
b. & English \\
& \begin{forest}
[\textit{v}P [SUB]
[\textit{v}$'$ [\textit{v}\textsuperscript{[-\textsc{epp}]} \\ $\varnothing$ ]
[A\textsc{sp}P [A\textsc{sp} \\ LV\textsuperscript{ENG}]
[VP [V][OBJ] ]]] ]
\end{forest}
\end{tabular}
\z
While the underlying \ac{VO} order remains in English (\ref{ex:69}b) in a syntactic derivation, the object raises to the left of the verb, targeting Spec, \ac{ASP} in Korean and Japanese (\ref{ex:69}a), resulting in \ac{OV} order within \ac{ASP}. After the object moves to Spec, \ac{ASP}, the entire \ac{ASP} moves to Spec, \textit{v}P, as a result of which the surface order of O-V-\textit{ha} in Korean and O-V-\textit{su} in Japanese is derived (recall the structures in \REF{ex:55} and \REF{ex:56} for this). I have argued that both object movement and \ac{ASP} raising in Korean and Japanese are due to feature specifications on \textit{v}, which are different from feature specifications on \textit{v} in English. Yet, I have not shown how \textit{v}’s features are different in Korean/Japanese and English, and will discuss this in next chapter.
|
<a href="https://colab.research.google.com/github/mella30/Deep-Learning-with-Tensorflow-2/blob/main/Course3-Probabilistic_Deep_Learning_with_Tensorflow2/week_3_Programming_Assignment.ipynb" target="_parent"></a>
# Programming Assignment
## RealNVP for the LSUN bedroom dataset
### Instructions
In this notebook, you will develop the RealNVP normalising flow architecture from scratch, including the affine coupling layers, checkerboard and channel-wise masking, and combining into a multiscale architecture. You will train the normalising flow on a subset of the LSUN bedroom dataset.
Some code cells are provided for you in the notebook. You should avoid editing provided code, and make sure to execute the cells in order to avoid unexpected errors. Some cells begin with the line:
`#### GRADED CELL ####`
Don't move or edit this first line - this is what the automatic grader looks for to recognise graded cells. These cells require you to write your own code to complete them, and are automatically graded when you submit the notebook. Don't edit the function name or signature provided in these cells, otherwise the automatic grader might not function properly.
### How to submit
Complete all the tasks you are asked for in the worksheet. When you have finished and are happy with your code, press the **Submit Assignment** button at the top of this notebook.
### Let's get started!
We'll start running some imports, and loading the dataset. Do not edit the existing imports in the following cell. If you would like to make further Tensorflow imports, you should add them here.
```python
#### PACKAGE IMPORTS ####
# Run this cell first to import all required packages. Do not make any imports elsewhere in the notebook
import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import Image
from tensorflow.keras import Model, Input
from tensorflow.keras.layers import Conv2D, BatchNormalization
from tensorflow.keras.optimizers import Adam
tfd = tfp.distributions
tfb = tfp.bijectors
# If you would like to make further imports from tensorflow, add them here
from tensorflow.keras import layers
from tensorflow.keras.regularizers import l2
```
#### The LSUN Bedroom Dataset
In this assignment, you will use a subset of the [LSUN dataset](https://www.yf.io/p/lsun). This is a large-scale image dataset with 10 scene and 20 object categories. A subset of the LSUN bedroom dataset has been provided, and has already been downsampled and preprocessed into smaller, fixed-size images.
* F. Yu, A. Seff, Y. Zhang, S. Song, T. Funkhouser and J. Xia. "LSUN: Construction of a Large-scale Image Dataset using Deep Learning with Humans in the Loop". [arXiv:1506.03365](https://arxiv.org/abs/1506.03365), 10 Jun 2015
Your goal is to develop the RealNVP normalising flow architecture using bijector subclassing, and use it to train a generative model of the LSUN bedroom data subset. For full details on the RealNVP model, refer to the original paper:
* L. Dinh, J. Sohl-Dickstein and S. Bengio. "Density estimation using Real NVP". [arXiv:1605.08803](https://arxiv.org/abs/1605.08803), 27 Feb 2017.
#### Import the data
The dataset required for this project can be downloaded from the following link:
https://drive.google.com/file/d/1scbDZrn5pkRjF_CeZp66uHVQC9o1gIsg/view?usp=sharing
You should upload this file to Drive for use in this Colab notebook. It is recommended to unzip it on Drive, which can be done using the `zipfile` package:
>```
import zipfile
with zipfile.ZipFile("/path/to/lsun_bedroom.zip","r") as zip_ref:
zip_ref.extractall('lsun_bedroom_data')
```
```python
# Run this cell to connect to your Drive folder
from google.colab import drive
drive.mount('/content/gdrive')
```
Mounted at /content/gdrive
```python
# unpack data
import zipfile
with zipfile.ZipFile("/content/gdrive/MyDrive/Datasets/lsun_bedroom.zip","r") as zip_ref:
zip_ref.extractall('lsun_bedroom_data')
```
#### Load the dataset
The following functions will be useful for loading and preprocessing the dataset. The subset you will use for this assignment consists of 10,000 training images, 1000 validation images and 1000 test images.
The images have been downsampled to 32 x 32 x 3 in order to simplify the training process.
```python
# Functions for loading and preprocessing the images
def load_image(filepath):
raw_img = tf.io.read_file(filepath)
img_tensor_int = tf.image.decode_jpeg(raw_img, channels=3)
img_tensor_flt = tf.image.convert_image_dtype(img_tensor_int, tf.float32)
img_tensor_flt = tf.image.resize(img_tensor_flt, [32, 32])
img_tensor_flt = tf.image.random_flip_left_right(img_tensor_flt)
return img_tensor_flt, img_tensor_flt
def load_dataset(split):
train_list_ds = tf.data.Dataset.list_files('/content/lsun_bedroom_data/{}/*.jpg'.format(split), shuffle=False)
train_ds = train_list_ds.map(load_image)
return train_ds
```
```python
# Load the training, validation and testing datasets splits
train_ds = load_dataset('train')
val_ds = load_dataset('val')
test_ds = load_dataset('test')
```
```python
# Shuffle the datasets
shuffle_buffer_size = 1000
train_ds = train_ds.shuffle(shuffle_buffer_size)
val_ds = val_ds.shuffle(shuffle_buffer_size)
test_ds = test_ds.shuffle(shuffle_buffer_size)
```
```python
# Display a few examples
n_img = 4
f, axs = plt.subplots(n_img, n_img, figsize=(14, 14))
for k, image in enumerate(train_ds.take(n_img**2)):
i = k // n_img
j = k % n_img
axs[i, j].imshow(image[0])
axs[i, j].axis('off')
f.subplots_adjust(wspace=0.01, hspace=0.03)
```
```python
# Batch the Dataset objects
batch_size = 64
train_ds = train_ds.batch(batch_size)
val_ds = val_ds.batch(batch_size)
test_ds = test_ds.batch(batch_size)
```
### Affine coupling layer
We will begin the development of the RealNVP architecture with the core bijector that is called the _affine coupling layer_. This bijector can be described as follows: suppose that $x$ is a $D$-dimensional input, and let $d<D$. Then the output $y$ of the affine coupling layer is given by the following equations:
$$
\begin{align}
y_{1:d} &= x_{1:d} \tag{1}\\
y_{d+1:D} &= x_{d+1:D}\odot \exp(s(x_{1:d})) + t(x_{1:d}), \tag{2}
\end{align}
$$
where $s$ and $t$ are functions from $\mathbb{R}^d\rightarrow\mathbb{R}^{D-d}$, and define the log-scale and shift operations on the vector $x_{d+1:D}$ respectively.
The log of the Jacobian determinant for this layer is given by $\sum_{j}s(x_{1:d})_j$.
The inverse operation can be easily computed as
$$
\begin{align}
x_{1:d} &= y_{1:d}\tag{3}\\
x_{d+1:D} &= \left(y_{d+1:D} - t(y_{1:d})\right)\odot \exp(-s(y_{1:d})),\tag{4}
\end{align}
$$
In practice, we will implement equations $(1)$ and $(2)$ using a binary mask $b$:
$$
\begin{align}
\text{Forward pass:}\qquad y &= b\odot x + (1-b)\odot\left(x\odot\exp(s(b\odot x)) + t(b\odot x)\right),\tag{5}\\
\text{Inverse pass:}\qquad x &= b\odot y + (1-b)\odot\left(y - t(b\odot x) \odot\exp( -s(b\odot x))\right).\tag{6}
\end{align}
$$
Our inputs $x$ will be a batch of 3-dimensional Tensors with `height`, `width` and `channels` dimensions. As in the original architecture, we will use both spatial 'checkerboard' masks and channel-wise masks:
```python
# Run this cell to download and view a figure to illustrate the checkerboard and binary masks
!wget -q -O binary_masks.png --no-check-certificate "https://docs.google.com/uc?export=download&id=1d_cBjyPGm8i0l5GsRSspPoAlxiPo3HGt"
Image("binary_masks.png", width=800)
```
<center>Figure 1. Spatial checkerboard mask (left) and channel-wise mask (right). From the original paper.</center>
#### Custom model for log-scale and shift
You should now create a custom model for the shift and log-scale parameters that are used in the affine coupling layer bijector. We will use a convolutional residual network, with two residual blocks and a final convolutional layer. Using the functional API, build the model according to the following specifications:
* The function takes the `input_shape` and `filters` as arguments
* The model should use the `input_shape` in the function argument to set the shape in the Input layer (call this layer `h0`).
* The first hidden layer should be a Conv2D layer with number of filters set by the `filters` argument, and a ReLU activation
* The second hidden layer should be a BatchNormalization layer
* The third hidden layer should be a Conv2D layer with the same number of filters as the input `h0` to the model, and a ReLU activation
* The fourth hidden layer should be a BatchNormalization layer
* The fifth hidden layer should be the sum of the fourth hidden layer output and the inputs `h0`. Call this layer `h1`
* The sixth hidden layer should be a Conv2D layer with filters set by the `filters` argument, and a ReLU activation
* The seventh hidden layer should be a BatchNormalization layer
* The eighth hidden layer should be a Conv2D layer with the same number of filters as `h1` (and `h0`), and a ReLU activation
* The ninth hidden layer should be a BatchNormalization layer
* The tenth hidden layer should be the sum of the ninth hidden layer output and `h1`
* The eleventh hidden layer should be a Conv2D layer with the number of filters equal to twice the number of channels of the model input, and a linear activation. Call this layer `h2`
* The twelfth hidden layer should split `h2` into two equal-sized Tensors along the final channel axis. These two Tensors are the shift and log-scale Tensors, and should each have the same shape as the model input
* The final layer should then apply the `tanh` nonlinearity to the log_scale Tensor. The outputs to the model should then be the list of Tensors `[shift, log_scale]`
All Conv2D layers should use a 3x3 kernel size, `"SAME"` padding and an $l2$ kernel regularizer with regularisation coefficient of `5e-5`.
_Hint: use_ `tf.split` _with arguments_ `num_or_size_splits=2, axis=-1` _to create the output Tensors_.
In total, the network should have 14 layers (including the `Input` layer).
```python
#### GRADED CELL ####
# Complete the following function.
# Make sure to not change the function name or arguments.
def get_conv_resnet(input_shape, filters):
"""
This function should build a CNN ResNet model according to the above specification,
using the functional API. The function takes input_shape as an argument, which should be
used to specify the shape in the Input layer, as well as a filters argument, which
should be used to specify the number of filters in (some of) the convolutional layers.
Your function should return the model.
"""
h0 = layers.Input(shape=input_shape)
h = layers.Conv2D(filters=filters, kernel_size=(3,3), padding="same", kernel_regularizer=l2(5e-5), activation="relu")(h0)
h = layers.BatchNormalization()(h)
h = layers.Conv2D(filters=input_shape[-1], kernel_size=(3,3), padding="same", kernel_regularizer=l2(5e-5), activation="relu")(h)
h = layers.BatchNormalization()(h)
h1 = layers.Add()([h0, h])
h = layers.Conv2D(filters=filters, kernel_size=(3,3), padding="same", kernel_regularizer=l2(5e-5), activation="relu")(h1)
h = layers.BatchNormalization()(h)
h = layers.Conv2D(filters=input_shape[-1], kernel_size=(3,3), padding="same", kernel_regularizer=l2(5e-5), activation="relu")(h)
h = layers.BatchNormalization()(h)
h = layers.Add()([h1, h])
h2 = layers.Conv2D(filters=2*input_shape[-1], kernel_size=(3,3), padding="same", kernel_regularizer=l2(5e-5), activation="linear")(h)
shift, log_scale = layers.Lambda(lambda t: tf.split(t, num_or_size_splits=2, axis=-1))(h2)
log_scale = layers.Activation(activation="tanh")(log_scale)
model = Model(inputs=h0, outputs=[shift, log_scale])
return model
```
```python
# Test your function and print the model summary
conv_resnet = get_conv_resnet((32, 32, 3), 32)
conv_resnet.summary()
```
Model: "model"
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
input_1 (InputLayer) [(None, 32, 32, 3)] 0
__________________________________________________________________________________________________
conv2d (Conv2D) (None, 32, 32, 32) 896 input_1[0][0]
__________________________________________________________________________________________________
batch_normalization (BatchNorma (None, 32, 32, 32) 128 conv2d[0][0]
__________________________________________________________________________________________________
conv2d_1 (Conv2D) (None, 32, 32, 3) 867 batch_normalization[0][0]
__________________________________________________________________________________________________
batch_normalization_1 (BatchNor (None, 32, 32, 3) 12 conv2d_1[0][0]
__________________________________________________________________________________________________
add (Add) (None, 32, 32, 3) 0 input_1[0][0]
batch_normalization_1[0][0]
__________________________________________________________________________________________________
conv2d_2 (Conv2D) (None, 32, 32, 32) 896 add[0][0]
__________________________________________________________________________________________________
batch_normalization_2 (BatchNor (None, 32, 32, 32) 128 conv2d_2[0][0]
__________________________________________________________________________________________________
conv2d_3 (Conv2D) (None, 32, 32, 3) 867 batch_normalization_2[0][0]
__________________________________________________________________________________________________
batch_normalization_3 (BatchNor (None, 32, 32, 3) 12 conv2d_3[0][0]
__________________________________________________________________________________________________
add_1 (Add) (None, 32, 32, 3) 0 add[0][0]
batch_normalization_3[0][0]
__________________________________________________________________________________________________
conv2d_4 (Conv2D) (None, 32, 32, 6) 168 add_1[0][0]
__________________________________________________________________________________________________
lambda (Lambda) [(None, 32, 32, 3), 0 conv2d_4[0][0]
__________________________________________________________________________________________________
activation (Activation) (None, 32, 32, 3) 0 lambda[0][1]
==================================================================================================
Total params: 3,974
Trainable params: 3,834
Non-trainable params: 140
__________________________________________________________________________________________________
You can also inspect your model architecture graphically by running the following cell. It should look something like the following:
```python
# Run this cell to download and view an example model plot
!wget -q -O model_plot.png --no-check-certificate "https://docs.google.com/uc?export=download&id=1I9MhFGquwyHsJlDgO8hItXnMqAvc5cQg"
Image("model_plot.png", width=1400)
```
```python
# Plot the model graph
tf.keras.utils.plot_model(conv_resnet, show_layer_names=False, rankdir='LR')
```
```python
# Check the output shapes are as expected
print(conv_resnet(tf.random.normal((1, 32, 32, 3)))[0].shape)
print(conv_resnet(tf.random.normal((1, 32, 32, 3)))[1].shape)
```
(1, 32, 32, 3)
(1, 32, 32, 3)
#### Binary masks
Now that you have a shift and log-scale model built, we will now implement the affine coupling layer. We will first need functions to create the binary masks $b$ as described above. The following function creates the spatial 'checkerboard' mask.
It takes a rank-2 `shape` as input, which correspond to the `height` and `width` dimensions, as well as an `orientation` argument (an integer equal to `0` or `1`) that determines which way round the zeros and ones are entered into the Tensor.
```python
# Function to create the checkerboard mask
def checkerboard_binary_mask(shape, orientation=0):
height, width = shape[0], shape[1]
height_range = tf.range(height)
width_range = tf.range(width)
height_odd_inx = tf.cast(tf.math.mod(height_range, 2), dtype=tf.bool)
width_odd_inx = tf.cast(tf.math.mod(width_range, 2), dtype=tf.bool)
odd_rows = tf.tile(tf.expand_dims(height_odd_inx, -1), [1, width])
odd_cols = tf.tile(tf.expand_dims(width_odd_inx, 0), [height, 1])
checkerboard_mask = tf.math.logical_xor(odd_rows, odd_cols)
if orientation == 1:
checkerboard_mask = tf.math.logical_not(checkerboard_mask)
return tf.cast(tf.expand_dims(checkerboard_mask, -1), tf.float32)
```
This function creates a rank-3 Tensor to mask the `height`, `width` and `channels` dimensions of the input. We can take a look at this checkerboard mask for some example inputs below. In order to make the Tensors easier to inspect, we will squeeze out the single channel dimension (which is always 1 for this mask).
```python
# Run the checkerboard_binary_mask function to see an example
# NB: we squeeze the shape for easier viewing. The full shape is (4, 4, 1)
tf.squeeze(checkerboard_binary_mask((4, 4), orientation=0))
```
<tf.Tensor: shape=(4, 4), dtype=float32, numpy=
array([[0., 1., 0., 1.],
[1., 0., 1., 0.],
[0., 1., 0., 1.],
[1., 0., 1., 0.]], dtype=float32)>
```python
# The `orientation` should be 0 or 1, and determines which way round the binary entries are
tf.squeeze(checkerboard_binary_mask((4, 4), orientation=1))
```
<tf.Tensor: shape=(4, 4), dtype=float32, numpy=
array([[1., 0., 1., 0.],
[0., 1., 0., 1.],
[1., 0., 1., 0.],
[0., 1., 0., 1.]], dtype=float32)>
You should now complete the following function to create a channel-wise mask. This function takes a single integer `num_channels` as an input, as well as an `orientation` argument, similar to above. You can assume that the `num_channels` integer is even.
The function should return a rank-3 Tensor with singleton entries for `height` and `width`. In the channel axis, the first `num_channels // 2` entries should be zero (for `orientation=0`) and the final `num_channels // 2` entries should be one (for `orientation=0`). The zeros and ones should be reversed for `orientation=1`. The `dtype` of the returned Tensor should be `tf.float32`.
```python
#### GRADED CELL ####
# Complete the following function.
# Make sure to not change the function name or arguments.
def channel_binary_mask(num_channels, orientation=0):
"""
This function takes an integer num_channels and orientation (0 or 1) as
arguments. It should create a channel-wise binary mask with
dtype=tf.float32, according to the above specification.
The function should then return the binary mask.
"""
if orientation == 0:
return tf.concat([tf.zeros((1,1, num_channels//2), dtype=tf.float32),
tf.ones((1,1, num_channels - num_channels//2), dtype=tf.float32)], axis=-1)
return tf.concat([tf.ones((1,1, num_channels//2), dtype=tf.float32),
tf.zeros((1,1, num_channels - num_channels//2), dtype=tf.float32)], axis=-1)
```
```python
# Run your function to see an example channel-wise binary mask
channel_binary_mask(6, orientation=0)
```
<tf.Tensor: shape=(1, 1, 6), dtype=float32, numpy=array([[[0., 0., 0., 1., 1., 1.]]], dtype=float32)>
```python
#### GRADED CELL ####
# Complete the following functions.
# Make sure to not change the function names or arguments.
def forward(x, b, shift_and_log_scale_fn):
"""
This function takes the input Tensor x, binary mask b and callable
shift_and_log_scale_fn as arguments.
This function should implement the forward transformation in equation (5)
and return the output Tensor y, which will have the same shape as x
"""
shift, log_scale = shift_and_log_scale_fn(b * x)
return b * x + (1 - b) * (x * tf.math.exp(log_scale) + shift)
def inverse(y, b, shift_and_log_scale_fn):
"""
This function takes the input Tensor x, binary mask b and callable
shift_and_log_scale_fn as arguments.
This function should implement the forward transformation in equation (5)
and return the output Tensor y, which will have the same shape as x
"""
shift, log_scale = shift_and_log_scale_fn(b * y)
return b * y + (1 - b) * ((y - shift) * tf.math.exp(-log_scale))
```
The new bijector class also requires the `log_det_jacobian` methods to be implemented. Recall that the log of the Jacobian determinant of the forward transformation is given by $\sum_{j}s(x_{1:d})_j$, where $s$ is the log-scale function of the affine coupling layer.
You should now complete the following functions to define the `forward_log_det_jacobian` and `inverse_log_det_jacobian` methods of the affine coupling layer bijector.
* Both functions `forward_log_det_jacobian` and `inverse_log_det_jacobian` takes an input Tensor `x` (or `y`), a rank-3 binary mask `b`, and the `shift_and_log_scale_fn` callable
* These arguments are the same as the description for the `forward` and `inverse` functions
* The `forward_log_det_jacobian` function should implement the log of the Jacobian determinant for the transformation $(5)$
* The `inverse_log_det_jacobian` function should implement the log of the Jacobian determinant for the transformation $(6)$
* Both functions should reduce sum over the last three axes of the input Tensor (`height`, `width` and `channels`)
```python
#### GRADED CELL ####
# Complete the following functions.
# Make sure to not change the function names or arguments.
def forward_log_det_jacobian(x, b, shift_and_log_scale_fn):
"""
This function takes the input Tensor x, binary mask b and callable
shift_and_log_scale_fn as arguments.
This function should compute and return the log of the Jacobian determinant
of the forward transformation in equation (5)
"""
_, log_scale = shift_and_log_scale_fn(b * x)
return tf.reduce_sum((1 - b) * log_scale, axis=[-1,-2,-3])
def inverse_log_det_jacobian(y, b, shift_and_log_scale_fn):
"""
This function takes the input Tensor y, binary mask b and callable
shift_and_log_scale_fn as arguments.
This function should compute and return the log of the Jacobian determinant
of the forward transformation in equation (6)
"""
_s_log_scale = shift_and_log_scale_fn(b * y)
return -tf.reduce_sum((1 - b) * log_scale, axis=[-1,-2,-3])
```
You are now ready to create the coupling layer bijector, using bijector subclassing. You should complete the class below to define the `AffineCouplingLayer`.
* You should complete the initialiser `__init__`, and the internal class method `_get_mask`
* The `_forward`, `_inverse`, `_forward_log_det_jacobian` and `_inverse_log_det_jacobian` methods are completed for you using the functions you have written above. Do not modify these methods
* The initialiser takes the `shift_and_log_scale_fn` callable, `mask_type` string (either `"checkerboard"` or `"channel"`, `orientation` (integer, either `0` or `1`) as required arguments, and allows for extra keyword arguments
* The required arguments should be set as class attributes in the initialiser (note that the `shift_and_log_scale_fn` attribute is being used in the `_forward`, `_inverse`, `_forward_log_det_jacobian` and `_inverse_log_det_jacobian` methods)
* The initialiser should call the base class initialiser, and pass in any extra keyword arguments
* The class should have a required number of event dimensions equal to 3
* The internal method `_get_mask` takes a `shape` as an argument, which is the shape of an input Tensor
* This method should use the `checkerboard_binary_mask` and `channel_binary_mask` functions above, as well as the `mask_type` and `orientation` arguments passed to the initialiser to compute and return the required binary mask
* This method is used in each of the `_forward`, `_inverse`, `_forward_log_det_jacobian` and `_inverse_log_det_jacobian` methods
```python
#### GRADED CELL ####
# Complete the following class.
# Make sure to not change the class or method names or arguments.
class AffineCouplingLayer(tfb.Bijector):
"""
Class to implement the affine coupling layer.
Complete the __init__ and _get_mask methods according to the instructions above.
"""
def __init__(self, shift_and_log_scale_fn, mask_type, orientation, **kwargs):
"""
The class initialiser takes the shift_and_log_scale_fn callable, mask_type,
orientation and possibly extra keywords arguments. It should call the
base class initialiser, passing any extra keyword arguments along.
It should also set the required arguments as class attributes.
"""
super(AffineCouplingLayer, self).__init__(forward_min_event_ndims=3, **kwargs)
self.shift_and_log_scale_fn = shift_and_log_scale_fn
self.mask_type = mask_type
self.orientation = orientation
def _get_mask(self, shape):
"""
This internal method should use the binary mask functions above to compute
and return the binary mask, according to the arguments passed in to the
initialiser.
"""
if self.mask_type == "channel":
return channel_binary_mask(shape[-1], self.orientation)
return checkerboard_binary_mask(shape[1:], self.orientation)
def _forward(self, x):
b = self._get_mask(x.shape)
return forward(x, b, self.shift_and_log_scale_fn)
def _inverse(self, y):
b = self._get_mask(y.shape)
return inverse(y, b, self.shift_and_log_scale_fn)
def _forward_log_det_jacobian(self, x):
b = self._get_mask(x.shape)
return forward_log_det_jacobian(x, b, self.shift_and_log_scale_fn)
def _inverse_log_det_jacobian(self, y):
b = self._get_mask(y.shape)
return inverse_log_det_jacobian(y, b, self.shift_and_log_scale_fn)
```
```python
# Test your function by creating an instance of the AffineCouplingLayer class
affine_coupling_layer = AffineCouplingLayer(conv_resnet, 'channel', orientation=1,
name='affine_coupling_layer')
```
```python
# The following should return a Tensor of the same shape as the input
affine_coupling_layer.forward(tf.random.normal((16, 32, 32, 3))).shape
```
TensorShape([16, 32, 32, 3])
```python
# The following should compute a log_det_jacobian for each event in the batch
affine_coupling_layer.forward_log_det_jacobian(tf.random.normal((16, 32, 32, 3)), event_ndims=3).shape
```
TensorShape([16])
#### Combining the affine coupling layers
In the affine coupling layer, part of the input remains unchanged in the transformation $(5)$. In order to allow transformation of all of the input, several coupling layers are composed, with the orientation of the mask being reversed in subsequent layers.
```python
# Run this cell to download and view a sketch of the affine coupling layers
!wget -q -O alternating_masks.png --no-check-certificate "https://docs.google.com/uc?export=download&id=1r1vASfLOW3kevxRzFUXhCtHN8dzldHve"
Image("alternating_masks.png", width=800)
```
<center>Figure 2. RealNVP alternates the orientation of masks from one affine coupling layer to the next. From the original paper.</center>
Our model design will be similar to the original architecture; we will compose three affine coupling layers with checkerboard masking, followed by a batch normalization bijector (`tfb.BatchNormalization` is a built-in bijector), followed by a squeezing operation, followed by three more affine coupling layers with channel-wise masking and a final batch normalization bijector.
The squeezing operation divides the spatial dimensions into 2x2 squares, and reshapes a Tensor of shape `(H, W, C)` into a Tensor of shape `(H // 2, W // 2, 4 * C)` as shown in Figure 1.
The squeezing operation is also a bijective operation, and has been provided for you in the class below.
```python
# Bijector class for the squeezing operation
class Squeeze(tfb.Bijector):
def __init__(self, name='Squeeze', **kwargs):
super(Squeeze, self).__init__(forward_min_event_ndims=3, is_constant_jacobian=True,
name=name, **kwargs)
def _forward(self, x):
input_shape = x.shape
height, width, channels = input_shape[-3:]
y = tfb.Reshape((height // 2, 2, width // 2, 2, channels), event_shape_in=(height, width, channels))(x)
y = tfb.Transpose(perm=[0, 2, 1, 3, 4])(y)
y = tfb.Reshape((height // 2, width // 2, 4 * channels),
event_shape_in=(height // 2, width // 2, 2, 2, channels))(y)
return y
def _inverse(self, y):
input_shape = y.shape
height, width, channels = input_shape[-3:]
x = tfb.Reshape((height, width, 2, 2, channels // 4), event_shape_in=(height, width, channels))(y)
x = tfb.Transpose(perm=[0, 2, 1, 3, 4])(x)
x = tfb.Reshape((2 * height, 2 * width, channels // 4),
event_shape_in=(height, 2, width, 2, channels // 4))(x)
return x
def _forward_log_det_jacobian(self, x):
return tf.constant(0., x.dtype)
def _inverse_log_det_jacobian(self, y):
return tf.constant(0., y.dtype)
def _forward_event_shape_tensor(self, input_shape):
height, width, channels = input_shape[-3], input_shape[-2], input_shape[-1]
return height // 2, width // 2, 4 * channels
def _inverse_event_shape_tensor(self, output_shape):
height, width, channels = output_shape[-3], output_shape[-2], output_shape[-1]
return height * 2, width * 2, channels // 4
```
You can see the effect of the squeezing operation on some example inputs in the cells below. In the forward transformation, each spatial dimension is halved, whilst the channel dimension is multiplied by 4. The opposite happens in the inverse transformation.
```python
# Test the Squeeze bijector
squeeze = Squeeze()
squeeze(tf.ones((10, 32, 32, 3))).shape
```
TensorShape([10, 16, 16, 12])
```python
# Test the inverse operation
squeeze.inverse(tf.ones((10, 4, 4, 96))).shape
```
TensorShape([10, 8, 8, 24])
We can now construct a block of coupling layers according to the architecture described above. You should complete the following function to chain together the bijectors that we have constructed, to form a bijector that performs the following operations in the forward transformation:
* Three `AffineCouplingLayer` bijectors with `"checkerboard"` masking with orientations `0, 1, 0` respectively
* A `BatchNormalization` bijector
* A `Squeeze` bijector
* Three more `AffineCouplingLayer` bijectors with `"channel"` masking with orientations `0, 1, 0` respectively
* Another `BatchNormalization` bijector
The function takes the following arguments:
* `shift_and_log_scale_fns`: a list or tuple of six conv_resnet models
* The first three models in this list are used in the three coupling layers with checkerboard masking
* The last three models in this list are used in the three coupling layers with channel masking
* `squeeze`: an instance of the `Squeeze` bijector
_NB: at this point, we would like to point out that we are following the exposition in the original paper, and think of the forward transformation as acting on the input image. Note that this is in contrast to the convention of using the forward transformation for sampling, and the inverse transformation for computing log probs._
```python
#### GRADED CELL ####
# Complete the following function.
# Make sure to not change the function name or arguments.
def realnvp_block(shift_and_log_scale_fns, squeeze):
"""
This function takes a list or tuple of six conv_resnet models, and an
instance of the Squeeze bijector.
The function should construct the chain of bijectors described above,
using the conv_resnet models in the coupling layers.
The function should then return the chained bijector.
"""
block = [AffineCouplingLayer(shift_and_log_scale_fns[0], 'checkerboard', orientation=0),
AffineCouplingLayer(shift_and_log_scale_fns[1], 'checkerboard', orientation=1),
AffineCouplingLayer(shift_and_log_scale_fns[2], 'checkerboard', orientation=0),
tfb.BatchNormalization(),
squeeze,
AffineCouplingLayer(shift_and_log_scale_fns[3], 'channel', orientation=0),
AffineCouplingLayer(shift_and_log_scale_fns[4], 'channel', orientation=1),
AffineCouplingLayer(shift_and_log_scale_fns[5], 'channel', orientation=0),
tfb.BatchNormalization()
]
return tfb.Chain(list(reversed(block)))
```
```python
# Run your function to create an instance of the bijector
checkerboard_fns = []
for _ in range(3):
checkerboard_fns.append(get_conv_resnet((32, 32, 3), 512))
channel_fns = []
for _ in range(3):
channel_fns.append(get_conv_resnet((16, 16, 12), 512))
block = realnvp_block(checkerboard_fns + channel_fns, squeeze)
```
```python
# Test the bijector on a dummy input
block.forward(tf.random.normal((10, 32, 32, 3))).shape
```
TensorShape([10, 16, 16, 12])
#### Multiscale architecture
The final component of the RealNVP is the multiscale architecture. The squeeze operation reduces the spatial dimensions but increases the channel dimensions. After one of the blocks of coupling-squeeze-coupling that you have implemented above, half of the dimensions are factored out as latent variables, while the other half is further processed through subsequent layers. This results in latent variables that represent different scales of features in the model.
```python
# Run this cell to download and view a sketch of the multiscale architecture
!wget -q -O multiscale.png --no-check-certificate "https://docs.google.com/uc?export=download&id=19Sc6PKbc8Bi2DoyupHZxHvB3m6tw-lki"
Image("multiscale.png", width=700)
```
<center>Figure 3. RealNVP creates latent variables at different scales by factoring out half of the dimensions at each scale. From the original paper.</center>
The final scale does not use the squeezing operation, and instead applies four affine coupling layers with alternating checkerboard masks.
The multiscale architecture for two latent variable scales is implemented for you in the following bijector.
```python
# Bijector to implement the multiscale architecture
class RealNVPMultiScale(tfb.Bijector):
def __init__(self, **kwargs):
super(RealNVPMultiScale, self).__init__(forward_min_event_ndims=3, **kwargs)
# First level
shape1 = (32, 32, 3) # Input shape
shape2 = (16, 16, 12) # Shape after the squeeze operation
shape3 = (16, 16, 6) # Shape after factoring out the latent variable
self.conv_resnet1 = get_conv_resnet(shape1, 64)
self.conv_resnet2 = get_conv_resnet(shape1, 64)
self.conv_resnet3 = get_conv_resnet(shape1, 64)
self.conv_resnet4 = get_conv_resnet(shape2, 128)
self.conv_resnet5 = get_conv_resnet(shape2, 128)
self.conv_resnet6 = get_conv_resnet(shape2, 128)
self.squeeze = Squeeze()
self.block1 = realnvp_block([self.conv_resnet1, self.conv_resnet2,
self.conv_resnet3, self.conv_resnet4,
self.conv_resnet5, self.conv_resnet6], self.squeeze)
# Second level
self.conv_resnet7 = get_conv_resnet(shape3, 128)
self.conv_resnet8 = get_conv_resnet(shape3, 128)
self.conv_resnet9 = get_conv_resnet(shape3, 128)
self.conv_resnet10 = get_conv_resnet(shape3, 128)
self.coupling_layer1 = AffineCouplingLayer(self.conv_resnet7, 'checkerboard', 0)
self.coupling_layer2 = AffineCouplingLayer(self.conv_resnet8, 'checkerboard', 1)
self.coupling_layer3 = AffineCouplingLayer(self.conv_resnet9, 'checkerboard', 0)
self.coupling_layer4 = AffineCouplingLayer(self.conv_resnet10, 'checkerboard', 1)
self.block2 = tfb.Chain([self.coupling_layer4, self.coupling_layer3,
self.coupling_layer2, self.coupling_layer1])
def _forward(self, x):
h1 = self.block1.forward(x)
z1, h2 = tf.split(h1, 2, axis=-1)
z2 = self.block2.forward(h2)
return tf.concat([z1, z2], axis=-1)
def _inverse(self, y):
z1, z2 = tf.split(y, 2, axis=-1)
h2 = self.block2.inverse(z2)
h1 = tf.concat([z1, h2], axis=-1)
return self.block1.inverse(h1)
def _forward_log_det_jacobian(self, x):
log_det1 = self.block1.forward_log_det_jacobian(x, event_ndims=3)
h1 = self.block1.forward(x)
_, h2 = tf.split(h1, 2, axis=-1)
log_det2 = self.block2.forward_log_det_jacobian(h2, event_ndims=3)
return log_det1 + log_det2
def _inverse_log_det_jacobian(self, y):
z1, z2 = tf.split(y, 2, axis=-1)
h2 = self.block2.inverse(z2)
log_det2 = self.block2.inverse_log_det_jacobian(z2, event_ndims=3)
h1 = tf.concat([z1, h2], axis=-1)
log_det1 = self.block1.inverse_log_det_jacobian(h1, event_ndims=3)
return log_det1 + log_det2
def _forward_event_shape_tensor(self, input_shape):
height, width, channels = input_shape[-3], input_shape[-2], input_shape[-1]
return height // 4, width // 4, 16 * channels
def _inverse_event_shape_tensor(self, output_shape):
height, width, channels = output_shape[-3], output_shape[-2], output_shape[-1]
return 4 * height, 4 * width, channels // 16
```
```python
# Create an instance of the multiscale architecture
multiscale_bijector = RealNVPMultiScale()
```
#### Data preprocessing bijector
We will also preprocess the image data before sending it through the RealNVP model. To do this, for a Tensor $x$ of pixel values in $[0, 1]^D$, we transform $x$ according to the following:
$$
T(x) = \text{logit}\left(\alpha + (1 - 2\alpha)x\right),\tag{7}
$$
where $\alpha$ is a parameter, and the logit function is the inverse of the sigmoid function, and is given by
$$
\text{logit}(p) = \log (p) - \log (1 - p).
$$
You should now complete the following function to construct this bijector from in-built bijectors from the bijectors module.
* The function takes the parameter `alpha` as an input, which you can assume to take a small positive value ($\ll0.5$)
* The function should construct and return a bijector that computes $(7)$ in the forward pass
```python
#### GRADED CELL ####
# Complete the following function.
# Make sure to not change the function name or arguments.
def get_preprocess_bijector(alpha):
"""
This function should create a chained bijector that computes the
transformation T in equation (7) above.
This can be computed using in-built bijectors from the bijectors module.
Your function should then return the chained bijector.
"""
return tfb.Chain([tfb.Invert(tfb.Sigmoid()),
tfb.Shift(alpha),
tfb.Scale(1 - 2 * alpha)])
```
```python
# Create an instance of the preprocess bijector
preprocess = get_preprocess_bijector(0.05)
```
#### Train the RealNVP model
Finally, we will use our RealNVP model to train
We will use the following model class to help with the training process.
```python
# Helper class for training
class RealNVPModel(Model):
def __init__(self, **kwargs):
super(RealNVPModel, self).__init__(**kwargs)
self.preprocess = get_preprocess_bijector(0.05)
self.realnvp_multiscale = RealNVPMultiScale()
self.bijector = tfb.Chain([self.realnvp_multiscale, self.preprocess])
def build(self, input_shape):
output_shape = self.bijector(tf.expand_dims(tf.zeros(input_shape[1:]), axis=0)).shape
self.base = tfd.Independent(tfd.Normal(loc=tf.zeros(output_shape[1:]), scale=1.),
reinterpreted_batch_ndims=3)
self._bijector_variables = (
list(self.bijector.variables))
self.flow = tfd.TransformedDistribution(
distribution=self.base,
bijector=tfb.Invert(self.bijector),
)
super(RealNVPModel, self).build(input_shape)
def call(self, inputs, training=None, **kwargs):
return self.flow
def sample(self, batch_size):
sample = self.base.sample(batch_size)
return self.bijector.inverse(sample)
```
```python
# Create an instance of the RealNVPModel class
realnvp_model = RealNVPModel()
realnvp_model.build((1, 32, 32, 3))
```
```python
# Compute the number of variables in the model
print("Total trainable variables:")
print(sum([np.prod(v.shape) for v in realnvp_model.trainable_variables]))
```
Total trainable variables:
315180
Note that the model's `call` method returns the `TransformedDistribution` object. Also, we have set up our datasets to return the input image twice as a 2-tuple. This is so we can train our model with negative log-likelihood as normal.
```python
# Define the negative log-likelihood loss function
def nll(y_true, y_pred):
return -y_pred.log_prob(y_true)
```
It is recommended to use the GPU accelerator hardware on Colab to train this model, as it can take some time to train. Note that it is not required to train the model in order to pass this assignment. For optimal results, a larger model should be trained for longer.
```python
# Compile and train the model
optimizer = Adam()
realnvp_model.compile(loss=nll, optimizer=Adam())
realnvp_model.fit(train_ds, validation_data=val_ds, epochs=10)
```
Epoch 1/10
938/938 [==============================] - 387s 392ms/step - loss: 213.6944 - val_loss: -3272.2449
Epoch 2/10
938/938 [==============================] - 363s 387ms/step - loss: -4292.1904 - val_loss: -5019.3613
Epoch 3/10
938/938 [==============================] - 364s 388ms/step - loss: -5596.1196 - val_loss: -5903.5815
Epoch 4/10
938/938 [==============================] - 363s 387ms/step - loss: -6373.9087 - val_loss: -6692.9321
Epoch 5/10
938/938 [==============================] - 364s 387ms/step - loss: -6852.5996 - val_loss: -7120.7026
Epoch 6/10
938/938 [==============================] - 363s 387ms/step - loss: -7192.7466 - val_loss: -7292.8345
Epoch 7/10
938/938 [==============================] - 364s 388ms/step - loss: -7274.7817 - val_loss: -7627.1870
Epoch 8/10
938/938 [==============================] - 364s 388ms/step - loss: -7667.7085 - val_loss: -7847.4912
Epoch 9/10
938/938 [==============================] - 363s 387ms/step - loss: -7834.7275 - val_loss: -7753.6006
Epoch 10/10
938/938 [==============================] - 363s 387ms/step - loss: -7931.5469 - val_loss: -8150.2329
<keras.callbacks.History at 0x7f7e35489890>
```python
# Evaluate the model
realnvp_model.evaluate(test_ds)
```
157/157 [==============================] - 25s 151ms/step - loss: -8143.5366
-8143.53662109375
#### Generate some samples
```python
# Sample from the model
samples = realnvp_model.sample(8).numpy()
```
/usr/local/lib/python3.7/dist-packages/keras/engine/base_layer.py:2215: UserWarning: `layer.apply` is deprecated and will be removed in a future version. Please use `layer.__call__` method instead.
warnings.warn('`layer.apply` is deprecated and '
```python
# Display the samples
n_img = 8
f, axs = plt.subplots(2, n_img // 2, figsize=(14, 7))
for k, image in enumerate(samples):
i = k % 2
j = k // 2
axs[i, j].imshow(image[0])
axs[i, j].axis('off')
f.subplots_adjust(wspace=0.01, hspace=0.03)
```
Congratulations on completing this programming assignment! In the next week of the course we will look at the variational autoencoder.
|
[STATEMENT]
lemma neq_fun_alt:
assumes "s \<noteq> (t::'a \<Rightarrow> 'b)"
obtains x where "s x \<noteq> t x" and "\<And>y. s y \<noteq> t y \<Longrightarrow> x \<le> y"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>x. \<lbrakk>s x \<noteq> t x; \<And>y. s y \<noteq> t y \<Longrightarrow> x \<le> y\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. (\<And>x. \<lbrakk>s x \<noteq> t x; \<And>y. s y \<noteq> t y \<Longrightarrow> x \<le> y\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
from assms ext[of s t]
[PROOF STATE]
proof (chain)
picking this:
s \<noteq> t
(\<And>x. s x = t x) \<Longrightarrow> s = t
[PROOF STEP]
have "\<exists>x. s x \<noteq> t x"
[PROOF STATE]
proof (prove)
using this:
s \<noteq> t
(\<And>x. s x = t x) \<Longrightarrow> s = t
goal (1 subgoal):
1. \<exists>x. s x \<noteq> t x
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
\<exists>x. s x \<noteq> t x
goal (1 subgoal):
1. (\<And>x. \<lbrakk>s x \<noteq> t x; \<And>y. s y \<noteq> t y \<Longrightarrow> x \<le> y\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
with exists_least_iff[of "\<lambda>x. s x \<noteq> t x"]
[PROOF STATE]
proof (chain)
picking this:
(\<exists>n. s n \<noteq> t n) = (\<exists>n. s n \<noteq> t n \<and> (\<forall>m<n. \<not> s m \<noteq> t m))
\<exists>x. s x \<noteq> t x
[PROOF STEP]
obtain x where x1: "s x \<noteq> t x" and x2: "\<And>y. y < x \<Longrightarrow> s y = t y"
[PROOF STATE]
proof (prove)
using this:
(\<exists>n. s n \<noteq> t n) = (\<exists>n. s n \<noteq> t n \<and> (\<forall>m<n. \<not> s m \<noteq> t m))
\<exists>x. s x \<noteq> t x
goal (1 subgoal):
1. (\<And>x. \<lbrakk>s x \<noteq> t x; \<And>y. y < x \<Longrightarrow> s y = t y\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
s x \<noteq> t x
?y < x \<Longrightarrow> s ?y = t ?y
goal (1 subgoal):
1. (\<And>x. \<lbrakk>s x \<noteq> t x; \<And>y. s y \<noteq> t y \<Longrightarrow> x \<le> y\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. thesis
[PROOF STEP]
proof
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. s ?x \<noteq> t ?x
2. \<And>y. s y \<noteq> t y \<Longrightarrow> ?x \<le> y
[PROOF STEP]
from x1
[PROOF STATE]
proof (chain)
picking this:
s x \<noteq> t x
[PROOF STEP]
show "s x \<noteq> t x"
[PROOF STATE]
proof (prove)
using this:
s x \<noteq> t x
goal (1 subgoal):
1. s x \<noteq> t x
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
s x \<noteq> t x
goal (1 subgoal):
1. \<And>y. s y \<noteq> t y \<Longrightarrow> x \<le> y
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>y. s y \<noteq> t y \<Longrightarrow> x \<le> y
[PROOF STEP]
fix y
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>y. s y \<noteq> t y \<Longrightarrow> x \<le> y
[PROOF STEP]
assume "s y \<noteq> t y"
[PROOF STATE]
proof (state)
this:
s y \<noteq> t y
goal (1 subgoal):
1. \<And>y. s y \<noteq> t y \<Longrightarrow> x \<le> y
[PROOF STEP]
with x2[of y]
[PROOF STATE]
proof (chain)
picking this:
y < x \<Longrightarrow> s y = t y
s y \<noteq> t y
[PROOF STEP]
have "\<not> y < x"
[PROOF STATE]
proof (prove)
using this:
y < x \<Longrightarrow> s y = t y
s y \<noteq> t y
goal (1 subgoal):
1. \<not> y < x
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
\<not> y < x
goal (1 subgoal):
1. \<And>y. s y \<noteq> t y \<Longrightarrow> x \<le> y
[PROOF STEP]
thus "x \<le> y"
[PROOF STATE]
proof (prove)
using this:
\<not> y < x
goal (1 subgoal):
1. x \<le> y
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
x \<le> y
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
thesis
goal:
No subgoals!
[PROOF STEP]
qed |
# Copyright (c) 2018-2021, Carnegie Mellon University
# See LICENSE for details
#F PolyDTT( <dtt-nonterminal> )
#F Parameters: <nonterminal for a (optionally skew) DCT or DST of type 1--8>
#F Definition: Let <t> be an (otionally skew) DCT or DST of type 1--8. Then
#F Transform( "PolyDTT", <t> ) represents the (n x n)-matrix
#F obtained from dividing every row in <t> by its first
#F entry.
#F This transform is called the polynomial version of
#F the DCT or DST.
#F Note: The transpose of PolyDTT(<t>) is
#F TPolyDTT(<t>^T).
#F Example: PolyDTT(DCT2(8)).
#F
Class(PolyDTT, NonTerminal, rec(
_short_print := true,
abbrevs := [ nt -> Checked(IsNonTerminal(nt),
ObjId(nt) in
[ DCT1, DCT3, DCT5, DCT7, # PolyDTT(T)=T for these
DCT2, DCT4, DCT6, DCT8,
DST1, DST2, DST3, DST4,
DST5, DST6, DST7, DST8,
SkewDTT],
[ Copy(nt) ]
)],
dims := self >> self.params[1].dimensions,
terminate := self >> Mat(PolynomialDTT(MatSPL(TerminateSPL(self.params[1])))),
isReal := True
));
Class(fr, Exp, rec(
ev := self >> let(
m := self.args[1].ev(),
i := self.args[2].ev(),
r := self.args[3].ev(),
Cond(i mod 2 = 0, (r + 2 * Int(i/2)) / m,
i mod 2 = 1, (2 - r + 2 * Int(i/2)) / m))));
#F Rules
#F -----
RulesFor(PolyDTT, rec(
PolyDTT_ToNormal := rec(
isApplicable := P -> ObjId(P[1]) in [DCT1, DCT3, DCT5, DCT7],
allChildren := P -> [P[1]],
rule := P -> P[1]
),
#F PolyDTT_Base2: (base case for non-skew DTTs of size 2)
#F
#F pDCT2_2 = F_2
#F pDCT4_2 = F_2 * [[1, -1], [0, sqrt(2)]]
#F pDCT6_2 = [ [ 1, 1 ], [ 1, -2 ] ]
#F pDCT8_2 = [ [ 1, cos(2*pi/5) ], [ 1, cos(4*pi/5) ] ]
#F pDST4_2 = F_2 * [[1, 1], [0, sqrt(2)]]
#F
#F Pueschel/Moura: Discrete Cosine and Sine Transforms, in preparation
#F
PolyDTT_Base2 := rec (
info := "pDTT_2 -> F_2",
isApplicable := P -> Rows(P[1]) = 2 and ObjId(P[1]) <> SkewDTT,
allChildren := P -> [[ ]],
rule := (P, C) -> let(nt := ObjId(P[1]), Cond(
nt = DCT2, F(2),
nt = DCT4, F(2) * Mat([[1, -1], [0,sqrt(2)]]),
nt = DCT6, Mat([[1,1], [1,-2]]),
nt = DCT8, Mat([[1,2*CosPi(2/5)], [1,2*CosPi(4/5)]]),
nt = DST2, F(2),
nt = DST3, F(2) * Diag([1, sqrt(2)]),
nt = DST4, F(2) * Mat([[1, 1], [0, sqrt(2)]]),
nt = DST5, Mat([[1,2*CosPi(2/5)], [1,2*CosPi(4/5)]]),
nt = DST6, Mat([[1,2*CosPi(1/5)], [1,2*CosPi(3/5)]]),
nt = DST7, Mat([[1,2*CosPi(1/5)], [1,2*CosPi(3/5)]]),
nt = DST8, Mat([[1,2], [1,-1]]),
Error("unrecognized <L.symbol>"))
)
),
PolyDTT_SkewBase2 := rec (
info := "pDTT_2 -> F_2",
isApplicable := P -> Rows(P[1]) = 2 and ObjId(P[1]) = SkewDTT and
ObjId(P[1].params[1]) = DST3,
allChildren := P -> [[ ]],
rule := (P, C) -> let(skewnt := ObjId(P[1].params[1]), r := P[1].params[2],
Cond(
skewnt = DST3, F(2) * Diag(1, 2*CosPi(r/2)),
Error("unrecognized <L.symbol>"))
)
),
PolyDTT_SkewDST3_CT := rec(
isApplicable := P -> ObjId(P[1]) = SkewDTT and
ObjId(P[1].params[1]) = DST3 and
Rows(P[1]) > 2 and not IsPrime(Rows(P[1])),
allChildren := P -> let(
N := Rows(P[1].params[1]), r := P[1].params[2],
List(DivisorPairs(N), d->
let(i := Ind(d[2]),
ri := fr(d[2], i, r),
[ PolyDTT(SkewDTT(DST3(d[1]), ri)),
PolyDTT(SkewDTT(DST3(d[2]), r)) ]))),
rule := (P,C) -> let(
MN := Rows(P[1]), N := Rows(C[1]), M := Rows(C[2]),
r := P[1].params[2],
i := C[1].root.params.params[2].args[2],
K(MN, N) *
IterDirectSum(i, i.range, C[1]) *
Tensor(C[2], I(N)) *
B_DST3_U(MN, M)
)
)
));
|
module CatenableList
%default total
%access private
public export
interface CatenableList (c : Type -> Type) where
empty : c a
isEmpty : c a -> Bool
cons : a -> c a -> c a
snoc : c a -> a -> c a
(++) : c a -> c a -> c a
head : c a -> a
tail : c a -> c a
|
(*
Author: Norbert Schirmer
Maintainer: Norbert Schirmer, norbert.schirmer at web de
License: LGPL
*)
(* Title: AlternativeSmallStep.thy
Author: Norbert Schirmer, TU Muenchen
Copyright (C) 2006-2008 Norbert Schirmer
Some rights reserved, TU Muenchen
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of the
License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA
*)
section \<open>Alternative Small Step Semantics\<close>
theory AlternativeSmallStep imports HoareTotalDef
begin
text \<open>
This is the small-step semantics, which is described and used in my PhD-thesis \cite{Schirmer-PhD}.
It decomposes the statement into a list of statements and finally executes the head.
So the redex is always the head of the list. The equivalence between termination
(based on the big-step semantics) and the absence of infinite computations in
this small-step semantics follows the same lines of reasoning as for
the new small-step semantics. However, it is technically more involved since
the configurations are more complicated. Thats why I switched to the new small-step
semantics in the "main trunk". I keep this alternative version and the important
proofs in this theory, so that one can compare both approaches.
\<close>
subsection \<open>Small-Step Computation: \<open>\<Gamma>\<turnstile>(cs, css, s) \<rightarrow> (cs', css', s')\<close>\<close>
type_synonym ('s,'p,'f) continuation = "('s,'p,'f) com list \<times> ('s,'p,'f) com list"
type_synonym ('s,'p,'f) config =
"('s,'p,'f)com list \<times> ('s,'p,'f)continuation list \<times> ('s,'f) xstate"
inductive "step"::"[('s,'p,'f) body,('s,'p,'f) config,('s,'p,'f) config] \<Rightarrow> bool"
("_\<turnstile> (_ \<rightarrow>/ _)" [81,81,81] 100)
for \<Gamma>::"('s,'p,'f) body"
where
Skip: "\<Gamma>\<turnstile>(Skip#cs,css,Normal s) \<rightarrow> (cs,css,Normal s)"
| Guard: "s\<in>g \<Longrightarrow> \<Gamma>\<turnstile>(Guard f g c#cs,css,Normal s) \<rightarrow> (c#cs,css,Normal s)"
| GuardFault: "s\<notin>g \<Longrightarrow> \<Gamma>\<turnstile>(Guard f g c#cs,css,Normal s) \<rightarrow> (cs,css,Fault f)"
| FaultProp: "\<Gamma>\<turnstile>(c#cs,css,Fault f) \<rightarrow> (cs,css,Fault f)"
| FaultPropBlock: "\<Gamma>\<turnstile>([],(nrms,abrs)#css,Fault f) \<rightarrow> (nrms,css,Fault f)"
(* FaultPropBlock: "\<Gamma>\<turnstile>([],cs#css,Fault) \<rightarrow> ([],css,Fault)"*)
| AbruptProp: "\<Gamma>\<turnstile>(c#cs,css,Abrupt s) \<rightarrow> (cs,css,Abrupt s)"
| ExitBlockNormal:
"\<Gamma>\<turnstile>([],(nrms,abrs)#css,Normal s) \<rightarrow> (nrms,css,Normal s)"
| ExitBlockAbrupt:
"\<Gamma>\<turnstile>([],(nrms,abrs)#css,Abrupt s) \<rightarrow> (abrs,css,Normal s)"
| Basic: "\<Gamma>\<turnstile>(Basic f#cs,css,Normal s) \<rightarrow> (cs,css,Normal (f s))"
| Spec: "(s,t) \<in> r \<Longrightarrow> \<Gamma>\<turnstile>(Spec r#cs,css,Normal s) \<rightarrow> (cs,css,Normal t)"
| SpecStuck: "\<forall>t. (s,t) \<notin> r \<Longrightarrow> \<Gamma>\<turnstile>(Spec r#cs,css,Normal s) \<rightarrow> (cs,css,Stuck)"
| Seq: "\<Gamma>\<turnstile>(Seq c\<^sub>1 c\<^sub>2#cs,css,Normal s) \<rightarrow> (c\<^sub>1#c\<^sub>2#cs,css,Normal s)"
| CondTrue: "s\<in>b \<Longrightarrow> \<Gamma>\<turnstile>(Cond b c\<^sub>1 c\<^sub>2#cs,css,Normal s) \<rightarrow> (c\<^sub>1#cs,css,Normal s)"
| CondFalse: "s\<notin>b \<Longrightarrow> \<Gamma>\<turnstile>(Cond b c\<^sub>1 c\<^sub>2#cs,css,Normal s) \<rightarrow> (c\<^sub>2#cs,css,Normal s)"
| WhileTrue: "\<lbrakk>s\<in>b\<rbrakk>
\<Longrightarrow>
\<Gamma>\<turnstile>(While b c#cs,css,Normal s) \<rightarrow> (c#While b c#cs,css,Normal s)"
| WhileFalse: "\<lbrakk>s\<notin>b\<rbrakk>
\<Longrightarrow>
\<Gamma>\<turnstile>(While b c#cs,css,Normal s) \<rightarrow> (cs,css,Normal s)"
| Call: "\<Gamma> p=Some bdy \<Longrightarrow>
\<Gamma>\<turnstile>(Call p#cs,css,Normal s) \<rightarrow> ([bdy],(cs,Throw#cs)#css,Normal s)"
| CallUndefined: "\<Gamma> p=None \<Longrightarrow>
\<Gamma>\<turnstile>(Call p#cs,css,Normal s) \<rightarrow> (cs,css,Stuck)"
| StuckProp: "\<Gamma>\<turnstile>(c#cs,css,Stuck) \<rightarrow> (cs,css,Stuck)"
| StuckPropBlock: "\<Gamma>\<turnstile>([],(nrms,abrs)#css,Stuck) \<rightarrow> (nrms,css,Stuck)"
| DynCom: "\<Gamma>\<turnstile>(DynCom c#cs,css,Normal s) \<rightarrow> (c s#cs,css,Normal s)"
| Throw: "\<Gamma>\<turnstile>(Throw#cs,css,Normal s) \<rightarrow> (cs,css,Abrupt s)"
| Catch: "\<Gamma>\<turnstile>(Catch c\<^sub>1 c\<^sub>2#cs,css,Normal s) \<rightarrow> ([c\<^sub>1],(cs,c\<^sub>2#cs)#css,Normal s)"
lemmas step_induct = step.induct [of _ "(c,css,s)" "(c',css',s')", split_format (complete),
case_names
Skip Guard GuardFault FaultProp FaultPropBlock AbruptProp ExitBlockNormal ExitBlockAbrupt
Basic Spec SpecStuck Seq CondTrue CondFalse WhileTrue WhileFalse Call CallUndefined
StuckProp StuckPropBlock DynCom Throw Catch, induct set]
inductive_cases step_elim_cases [cases set]:
"\<Gamma>\<turnstile>(c#cs,css,Fault f) \<rightarrow> u"
"\<Gamma>\<turnstile>([],css,Fault f) \<rightarrow> u"
"\<Gamma>\<turnstile>(c#cs,css,Stuck) \<rightarrow> u"
"\<Gamma>\<turnstile>([],css,Stuck) \<rightarrow> u"
"\<Gamma>\<turnstile>(c#cs,css,Abrupt s) \<rightarrow> u"
"\<Gamma>\<turnstile>([],css,Abrupt s) \<rightarrow> u"
"\<Gamma>\<turnstile>([],css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Skip#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Guard f g c#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Basic f#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Spec r#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Seq c1 c2#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Cond b c1 c2#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(While b c#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Call p#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(DynCom c#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Throw#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Catch c1 c2#cs,css,s) \<rightarrow> u"
inductive_cases step_Normal_elim_cases [cases set]:
"\<Gamma>\<turnstile>(c#cs,css,Fault f) \<rightarrow> u"
"\<Gamma>\<turnstile>([],css,Fault f) \<rightarrow> u"
"\<Gamma>\<turnstile>(c#cs,css,Stuck) \<rightarrow> u"
"\<Gamma>\<turnstile>([],css,Stuck) \<rightarrow> u"
"\<Gamma>\<turnstile>([],(nrms,abrs)#css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>([],(nrms,abrs)#css,Abrupt s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Skip#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Guard f g c#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Basic f#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Spec r#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Seq c1 c2#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Cond b c1 c2#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(While b c#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Call p#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(DynCom c#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Throw#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Catch c1 c2#cs,css,Normal s) \<rightarrow> u"
abbreviation
"step_rtrancl" :: "[('s,'p,'f) body,('s,'p,'f) config,('s,'p,'f) config] \<Rightarrow> bool"
("_\<turnstile> (_ \<rightarrow>\<^sup>*/ _)" [81,81,81] 100)
where
"\<Gamma>\<turnstile>cs0 \<rightarrow>\<^sup>* cs1 == (step \<Gamma>)\<^sup>*\<^sup>* cs0 cs1"
abbreviation
"step_trancl" :: "[('s,'p,'f) body,('s,'p,'f) config,('s,'p,'f) config] \<Rightarrow> bool"
("_\<turnstile> (_ \<rightarrow>\<^sup>+/ _)" [81,81,81] 100)
where
"\<Gamma>\<turnstile>cs0 \<rightarrow>\<^sup>+ cs1 == (step \<Gamma>)\<^sup>+\<^sup>+ cs0 cs1"
subsubsection \<open>Structural Properties of Small Step Computations\<close>
lemma Fault_app_steps: "\<Gamma>\<turnstile>(cs@xs,css,Fault f) \<rightarrow>\<^sup>* (xs,css,Fault f)"
proof (induct cs)
case Nil thus ?case by simp
next
case (Cons c cs)
have "\<Gamma>\<turnstile>(c#cs@xs, css, Fault f) \<rightarrow>\<^sup>* (xs, css, Fault f)"
proof -
have "\<Gamma>\<turnstile>(c#cs@xs, css, Fault f) \<rightarrow> (cs@xs, css, Fault f)"
by (rule step.FaultProp)
also
have "\<Gamma>\<turnstile>(cs@xs, css, Fault f) \<rightarrow>\<^sup>* (xs, css, Fault f)"
by (rule Cons.hyps)
finally show ?thesis .
qed
thus ?case
by simp
qed
lemma Stuck_app_steps: "\<Gamma>\<turnstile>(cs@xs,css,Stuck) \<rightarrow>\<^sup>* (xs,css,Stuck)"
proof (induct cs)
case Nil thus ?case by simp
next
case (Cons c cs)
have "\<Gamma>\<turnstile>(c#cs@xs, css, Stuck) \<rightarrow>\<^sup>* (xs, css, Stuck)"
proof -
have "\<Gamma>\<turnstile>(c#cs@xs, css, Stuck) \<rightarrow> (cs@xs, css, Stuck)"
by (rule step.StuckProp)
also
have "\<Gamma>\<turnstile>(cs@xs, css, Stuck) \<rightarrow>\<^sup>* (xs, css, Stuck)"
by (rule Cons.hyps)
finally show ?thesis .
qed
thus ?case
by simp
qed
text \<open>We can only append commands inside a block, if execution does not
enter or exit a block.
\<close>
lemma app_step:
assumes step: "\<Gamma>\<turnstile>(cs,css,s) \<rightarrow> (cs',css',t)"
shows "css=css' \<Longrightarrow> \<Gamma>\<turnstile>(cs@xs,css,s) \<rightarrow> (cs'@xs,css',t)"
using step
apply induct
apply (simp_all del: fun_upd_apply,(blast intro: step.intros)+)
done
text \<open>We can append whole blocks, without interfering with the actual
block. Outer blocks do not influence execution of
inner blocks.\<close>
lemma app_css_step:
assumes step: "\<Gamma>\<turnstile>(cs,css,s) \<rightarrow> (cs',css',t)"
shows "\<Gamma>\<turnstile>(cs,css@xs,s) \<rightarrow> (cs',css'@xs,t)"
using step
apply induct
apply (simp_all del: fun_upd_apply,(blast intro: step.intros)+)
done
ML \<open>
ML_Thms.bind_thm ("trancl_induct3", Split_Rule.split_rule @{context}
(Rule_Insts.read_instantiate @{context}
[((("a", 0), Position.none), "(ax, ay, az)"),
((("b", 0), Position.none), "(bx, by, bz)")] []
@{thm tranclp_induct}));
\<close>
lemma app_css_steps:
assumes step: "\<Gamma>\<turnstile>(cs,css,s) \<rightarrow>\<^sup>+ (cs',css',t)"
shows "\<Gamma>\<turnstile>(cs,css@xs,s) \<rightarrow>\<^sup>+ (cs',css'@xs,t)"
apply(rule trancl_induct3 [OF step])
apply (rule app_css_step [THEN tranclp.r_into_trancl [of "step \<Gamma>"]],assumption)
apply(blast intro:app_css_step tranclp_trans)
done
lemma step_Cons':
assumes step: "\<Gamma>\<turnstile>(ccs,css,s) \<rightarrow> (cs',css',t)"
shows
"\<And>c cs. ccs=c#cs \<Longrightarrow> \<exists>css''. css'=css''@css \<and>
(if css''=[] then \<exists>p. cs'=p@cs
else (\<exists>pnorm pabr. css''=[(pnorm@cs,pabr@cs)]))"
using step
by induct force+
lemma step_Cons:
assumes step: "\<Gamma>\<turnstile>(c#cs,css,s) \<rightarrow> (cs',css',t)"
shows "\<exists>pcss. css'=pcss@css \<and>
(if pcss=[] then \<exists>ps. cs'=ps@cs
else (\<exists>pcs_normal pcs_abrupt. pcss=[(pcs_normal@cs,pcs_abrupt@cs)]))"
using step_Cons' [OF step]
by blast
lemma step_Nil':
assumes step: "\<Gamma>\<turnstile>(cs,asscss,s) \<rightarrow> (cs',css',t)"
shows
"\<And>ass. \<lbrakk>cs=[]; asscss=ass@css; ass\<noteq>Nil\<rbrakk> \<Longrightarrow>
css'=tl ass@css \<and>
(case s of
Abrupt s' \<Rightarrow> cs'=snd (hd ass) \<and> t=Normal s'
| _ \<Rightarrow> cs'=fst (hd ass) \<and> t=s)"
using step
by (induct) (fastforce simp add: neq_Nil_conv)+
lemma step_Nil:
assumes step: "\<Gamma>\<turnstile>([],ass@css,s) \<rightarrow> (cs',css',t)"
assumes ass_not_Nil: "ass\<noteq>[]"
shows "css'=tl ass@css \<and>
(case s of
Abrupt s' \<Rightarrow> cs'=snd (hd ass) \<and> t=Normal s'
| _ \<Rightarrow> cs'=fst (hd ass) \<and> t=s)"
using step_Nil' [OF step _ _ ass_not_Nil]
by simp
lemma step_Nil'':
assumes step: "\<Gamma>\<turnstile>([],(pcs_normal,pcs_abrupt)#pcss@css,s) \<rightarrow> (cs',pcss@css,t)"
shows "(case s of
Abrupt s' \<Rightarrow> cs'=pcs_abrupt \<and> t=Normal s'
| _ \<Rightarrow> cs'=pcs_normal \<and> t=s)"
using step_Nil' [OF step, where ass ="(pcs_normal,pcs_abrupt)#pcss" and css="css"]
by (auto split: xstate.splits)
lemma drop_suffix_css_step':
assumes step: "\<Gamma>\<turnstile>(cs,cssxs,s) \<rightarrow> (cs',css'xs,t)"
shows "\<And>css css' xs. \<lbrakk>cssxs = css@xs; css'xs=css'@xs\<rbrakk>
\<Longrightarrow> \<Gamma>\<turnstile>(cs,css,s) \<rightarrow> (cs',css',t)"
using step
apply induct
apply (fastforce intro: step.intros)+
done
lemma drop_suffix_css_step:
assumes step: "\<Gamma>\<turnstile>(cs,pcss@css,s) \<rightarrow> (cs',pcss'@css,t)"
shows "\<Gamma>\<turnstile>(cs,pcss,s) \<rightarrow> (cs',pcss',t)"
using step by (blast intro: drop_suffix_css_step')
lemma drop_suffix_hd_css_step':
assumes step: "\<Gamma>\<turnstile> (pcs,css,s) \<rightarrow> (cs',css'css,t)"
shows "\<And>p ps cs pnorm pabr. \<lbrakk>pcs=p#ps@cs; css'css=(pnorm@cs,pabr@cs)#css\<rbrakk>
\<Longrightarrow> \<Gamma>\<turnstile> (p#ps,css,s) \<rightarrow> (cs',(pnorm,pabr)#css,t)"
using step
by induct (force intro: step.intros)+
lemma drop_suffix_hd_css_step'':
assumes step: "\<Gamma>\<turnstile> (p#ps@cs,css,s) \<rightarrow> (cs',(pnorm@cs,pabr@cs)#css,t)"
shows "\<Gamma>\<turnstile> (p#ps,css,s) \<rightarrow> (cs',(pnorm,pabr)#css,t)"
using drop_suffix_hd_css_step' [OF step]
by auto
lemma drop_suffix_hd_css_step:
assumes step: "\<Gamma>\<turnstile> (p#ps@cs,css,s) \<rightarrow> (cs',[(pnorm@ps@cs,pabr@ps@cs)]@css,t)"
shows "\<Gamma>\<turnstile> (p#ps,css,s) \<rightarrow> (cs',[(pnorm@ps,pabr@ps)]@css,t)"
proof -
from step drop_suffix_hd_css_step'' [of _ p ps cs css s cs' "pnorm@ps" "pabr@ps" t]
show ?thesis
by auto
qed
lemma drop_suffix':
assumes step: "\<Gamma>\<turnstile>(csxs,css,s) \<rightarrow> (cs'xs,css',t)"
shows "\<And>xs cs cs'. \<lbrakk>css=css'; csxs=cs@xs; cs'xs = cs'@xs; cs\<noteq>[] \<rbrakk>
\<Longrightarrow> \<Gamma>\<turnstile>(cs,css,s) \<rightarrow> (cs',css,t)"
using step
apply induct
apply (fastforce intro: step.intros simp add: neq_Nil_conv)+
done
lemma drop_suffix:
assumes step: "\<Gamma>\<turnstile>(c#cs@xs,css,s) \<rightarrow> (cs'@xs,css,t)"
shows "\<Gamma>\<turnstile>(c#cs,css,s) \<rightarrow> (cs',css,t)"
by(rule drop_suffix' [OF step _ _ _]) auto
lemma drop_suffix_same_css_step:
assumes step: "\<Gamma>\<turnstile>(cs@xs,css,s) \<rightarrow> (cs'@xs,css,t)"
assumes not_Nil: "cs\<noteq>[]"
shows "\<Gamma>\<turnstile>(cs,xss,s) \<rightarrow> (cs',xss,t)"
proof-
from drop_suffix' [OF step _ _ _ not_Nil]
have "\<Gamma>\<turnstile>(cs,css,s) \<rightarrow> (cs',css,t)"
by auto
with drop_suffix_css_step [of _ cs "[]" css s cs' "[]" t]
have "\<Gamma>\<turnstile> (cs, [], s) \<rightarrow> (cs', [], t)"
by auto
from app_css_step [OF this]
show ?thesis
by auto
qed
lemma Cons_change_css_step:
assumes step: "\<Gamma>\<turnstile> (cs,css,s) \<rightarrow> (cs',css'@css,t)"
shows "\<Gamma>\<turnstile> (cs,xss,s) \<rightarrow> (cs',css'@xss,t)"
proof -
from step
drop_suffix_css_step [where cs=cs and pcss="[]" and css=css and s=s
and cs'=cs' and pcss'=css' and t=t]
have "\<Gamma>\<turnstile> (cs, [], s) \<rightarrow> (cs', css', t)"
by auto
from app_css_step [where xs=xss, OF this]
show ?thesis
by auto
qed
lemma Nil_change_css_step:
assumes step: "\<Gamma>\<turnstile>([],ass@css,s) \<rightarrow> (cs',ass'@css,t)"
assumes ass_not_Nil: "ass\<noteq>[]"
shows "\<Gamma>\<turnstile>([],ass@xss,s) \<rightarrow> (cs',ass'@xss,t)"
proof -
from step drop_suffix_css_step [of _ "[]" ass css s cs' ass' t]
have "\<Gamma>\<turnstile> ([], ass, s) \<rightarrow> (cs', ass', t)"
by auto
from app_css_step [where xs=xss, OF this]
show ?thesis
by auto
qed
subsubsection \<open>Equivalence between Big and Small-Step Semantics\<close>
lemma exec_impl_steps:
assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t"
shows "\<And>cs css. \<Gamma>\<turnstile>(c#cs,css,s) \<rightarrow>\<^sup>* (cs,css,t)"
using exec
proof (induct)
case Skip thus ?case by (blast intro: step.Skip)
next
case Guard thus ?case by (blast intro: step.Guard rtranclp_trans)
next
case GuardFault thus ?case by (blast intro: step.GuardFault)
next
case FaultProp thus ?case by (blast intro: step.FaultProp)
next
case Basic thus ?case by (blast intro: step.Basic)
next
case Spec thus ?case by (blast intro: step.Spec)
next
case SpecStuck thus ?case by (blast intro: step.SpecStuck)
next
case Seq thus ?case by (blast intro: step.Seq rtranclp_trans)
next
case CondTrue thus ?case by (blast intro: step.CondTrue rtranclp_trans)
next
case CondFalse thus ?case by (blast intro: step.CondFalse rtranclp_trans)
next
case WhileTrue thus ?case by (blast intro: step.WhileTrue rtranclp_trans)
next
case WhileFalse thus ?case by (blast intro: step.WhileFalse)
next
case (Call p bdy s s' cs css)
have bdy: "\<Gamma> p = Some bdy" by fact
have steps_body: "\<Gamma>\<turnstile>([bdy],(cs,Throw#cs)#css,Normal s) \<rightarrow>\<^sup>*
([],(cs,Throw#cs)#css, s')" by fact
show ?case
proof (cases s')
case (Normal s'')
note steps_body
also from Normal have "\<Gamma>\<turnstile>([],(cs,Throw#cs)#css, s') \<rightarrow> (cs,css,s')"
by (auto intro: step.intros)
finally show ?thesis
using bdy
by (blast intro: step.Call rtranclp_trans)
next
case (Abrupt s'')
with steps_body
have "\<Gamma>\<turnstile>([bdy],(cs,Throw#cs)#css,Normal s) \<rightarrow>\<^sup>*
([],(cs,Throw#cs)#css, Abrupt s'')" by simp
also have "\<Gamma>\<turnstile>([],(cs,Throw#cs)#css, Abrupt s'') \<rightarrow> (Throw#cs,css,Normal s'')"
by (rule ExitBlockAbrupt)
also have "\<Gamma>\<turnstile>(Throw#cs,css,Normal s'') \<rightarrow> (cs,css,Abrupt s'')"
by (rule Throw)
finally show ?thesis
using bdy Abrupt
by (auto intro: step.Call rtranclp_trans)
next
case Fault
note steps_body
also from Fault have "\<Gamma>\<turnstile>([],(cs,Throw#cs)#css, s') \<rightarrow> (cs,css,s')"
by (auto intro: step.intros)
finally show ?thesis
using bdy
by (blast intro: step.Call rtranclp_trans)
next
case Stuck
note steps_body
also from Stuck have "\<Gamma>\<turnstile>([],(cs,Throw#cs)#css, s') \<rightarrow> (cs,css,s')"
by (auto intro: step.intros)
finally show ?thesis
using bdy
by (blast intro: step.Call rtranclp_trans)
qed
next
case (CallUndefined p s cs css)
have undef: "\<Gamma> p = None" by fact
hence "\<Gamma>\<turnstile>(Call p # cs, css, Normal s) \<rightarrow> (cs, css, Stuck)"
by (rule step.CallUndefined)
thus ?case ..
next
case StuckProp thus ?case by (blast intro: step.StuckProp rtrancl_trans)
next
case DynCom thus ?case by (blast intro: step.DynCom rtranclp_trans)
next
case Throw thus ?case by (blast intro: step.Throw)
next
case AbruptProp thus ?case by (blast intro: step.AbruptProp)
next
case (CatchMatch c\<^sub>1 s s' c\<^sub>2 s'' cs css)
have steps_c1: "\<Gamma>\<turnstile>([c\<^sub>1],(cs,c\<^sub>2#cs)#css,Normal s) \<rightarrow>\<^sup>*
([],(cs,c\<^sub>2#cs)#css,Abrupt s')" by fact
also
have "\<Gamma>\<turnstile>([],(cs,c\<^sub>2#cs)#css,Abrupt s') \<rightarrow> (c\<^sub>2#cs,css,Normal s')"
by (rule ExitBlockAbrupt)
also
have steps_c2: "\<Gamma>\<turnstile>(c\<^sub>2#cs,css,Normal s') \<rightarrow>\<^sup>* (cs,css,s'')" by fact
finally
show "\<Gamma>\<turnstile>(Catch c\<^sub>1 c\<^sub>2 # cs, css, Normal s) \<rightarrow>\<^sup>* (cs, css, s'')"
by (blast intro: step.Catch rtranclp_trans)
next
case (CatchMiss c\<^sub>1 s s' c\<^sub>2 cs css)
assume notAbr: "\<not> isAbr s'"
have steps_c1: "\<Gamma>\<turnstile>([c\<^sub>1],(cs,c\<^sub>2#cs)#css,Normal s) \<rightarrow>\<^sup>* ([],(cs,c\<^sub>2#cs)#css,s')" by fact
show "\<Gamma>\<turnstile>(Catch c\<^sub>1 c\<^sub>2 # cs, css, Normal s) \<rightarrow>\<^sup>* (cs, css, s')"
proof (cases s')
case (Normal w)
with steps_c1
have "\<Gamma>\<turnstile>([c\<^sub>1],(cs,c\<^sub>2#cs)#css,Normal s) \<rightarrow>\<^sup>* ([],(cs,c\<^sub>2#cs)#css,Normal w)"
by simp
also
have "\<Gamma>\<turnstile>([],(cs,c\<^sub>2#cs)#css,Normal w) \<rightarrow> (cs,css,Normal w)"
by (rule ExitBlockNormal)
finally show ?thesis using Normal
by (auto intro: step.Catch rtranclp_trans)
next
case Abrupt with notAbr show ?thesis by simp
next
case (Fault f)
with steps_c1
have "\<Gamma>\<turnstile>([c\<^sub>1],(cs,c\<^sub>2#cs)#css,Normal s) \<rightarrow>\<^sup>* ([],(cs,c\<^sub>2#cs)#css,Fault f)"
by simp
also
have "\<Gamma>\<turnstile>([],(cs,c\<^sub>2#cs)#css,Fault f) \<rightarrow> (cs,css,Fault f)"
by (rule FaultPropBlock)
finally show ?thesis using Fault
by (auto intro: step.Catch rtranclp_trans)
next
case Stuck
with steps_c1
have "\<Gamma>\<turnstile>([c\<^sub>1],(cs,c\<^sub>2#cs)#css,Normal s) \<rightarrow>\<^sup>* ([],(cs,c\<^sub>2#cs)#css,Stuck)"
by simp
also
have "\<Gamma>\<turnstile>([],(cs,c\<^sub>2#cs)#css,Stuck) \<rightarrow> (cs,css,Stuck)"
by (rule StuckPropBlock)
finally show ?thesis using Stuck
by (auto intro: step.Catch rtranclp_trans)
qed
qed
inductive "execs"::"[('s,'p,'f) body,('s,'p,'f) com list,
('s,'p,'f) continuation list,
('s,'f) xstate,('s,'f) xstate] \<Rightarrow> bool"
("_\<turnstile> \<langle>_,_,_\<rangle> \<Rightarrow> _" [50,50,50,50,50] 50)
for \<Gamma>:: "('s,'p,'f) body"
where
Nil: "\<Gamma>\<turnstile>\<langle>[],[],s\<rangle> \<Rightarrow> s"
| ExitBlockNormal: "\<Gamma>\<turnstile>\<langle>nrms,css,Normal s\<rangle> \<Rightarrow> t
\<Longrightarrow>
\<Gamma>\<turnstile>\<langle>[],(nrms,abrs)#css,Normal s\<rangle> \<Rightarrow> t"
| ExitBlockAbrupt: "\<Gamma>\<turnstile>\<langle>abrs,css,Normal s\<rangle> \<Rightarrow> t
\<Longrightarrow>
\<Gamma>\<turnstile>\<langle>[],(nrms,abrs)#css,Abrupt s\<rangle> \<Rightarrow> t"
| ExitBlockFault: "\<Gamma>\<turnstile>\<langle>nrms,css,Fault f\<rangle> \<Rightarrow> t
\<Longrightarrow>
\<Gamma>\<turnstile>\<langle>[],(nrms,abrs)#css,Fault f\<rangle> \<Rightarrow> t"
| ExitBlockStuck: "\<Gamma>\<turnstile>\<langle>nrms,css,Stuck\<rangle> \<Rightarrow> t
\<Longrightarrow>
\<Gamma>\<turnstile>\<langle>[],(nrms,abrs)#css,Stuck\<rangle> \<Rightarrow> t"
| Cons: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t; \<Gamma>\<turnstile>\<langle>cs,css,t\<rangle> \<Rightarrow> u\<rbrakk>
\<Longrightarrow>
\<Gamma>\<turnstile>\<langle>c#cs,css,s\<rangle> \<Rightarrow> u"
inductive_cases execs_elim_cases [cases set]:
"\<Gamma>\<turnstile>\<langle>[],css,s\<rangle> \<Rightarrow> t"
"\<Gamma>\<turnstile>\<langle>c#cs,css,s\<rangle> \<Rightarrow> t"
ML \<open>
ML_Thms.bind_thm ("converse_rtrancl_induct3", Split_Rule.split_rule @{context}
(Rule_Insts.read_instantiate @{context}
[((("a", 0), Position.none), "(cs, css, s)"),
((("b", 0), Position.none), "(cs', css', t)")] []
@{thm converse_rtranclp_induct}));
\<close>
lemma execs_Fault_end:
assumes execs: "\<Gamma>\<turnstile>\<langle>cs,css,s\<rangle> \<Rightarrow> t" shows "s=Fault f\<Longrightarrow> t=Fault f"
using execs
by (induct) (auto dest: Fault_end)
lemma execs_Stuck_end:
assumes execs: "\<Gamma>\<turnstile>\<langle>cs,css,s\<rangle> \<Rightarrow> t" shows "s=Stuck \<Longrightarrow> t=Stuck"
using execs
by (induct) (auto dest: Stuck_end)
theorem steps_impl_execs:
assumes steps: "\<Gamma>\<turnstile>(cs,css,s) \<rightarrow>\<^sup>* ([],[],t)"
shows "\<Gamma>\<turnstile>\<langle>cs,css,s\<rangle> \<Rightarrow> t"
using steps
proof (induct rule: converse_rtrancl_induct3 [consumes 1])
show "\<Gamma>\<turnstile>\<langle>[],[],t\<rangle> \<Rightarrow> t" by (rule execs.Nil)
next
fix cs css s cs' css' w
assume step: "\<Gamma>\<turnstile>(cs,css, s) \<rightarrow> (cs',css', w)"
assume execs: "\<Gamma>\<turnstile>\<langle>cs',css',w\<rangle> \<Rightarrow> t"
from step
show "\<Gamma>\<turnstile>\<langle>cs,css,s\<rangle> \<Rightarrow> t"
proof (cases)
case (Catch c1 c2 cs s)
with execs obtain t' where
exec_c1: "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow> t'" and
execs_rest: "\<Gamma>\<turnstile>\<langle>[],(cs, c2 # cs) # css,t'\<rangle> \<Rightarrow> t"
by (clarsimp elim!: execs_elim_cases)
have "\<Gamma>\<turnstile>\<langle>Catch c1 c2 # cs,css,Normal s\<rangle> \<Rightarrow> t"
proof (cases t')
case (Normal t'')
with exec_c1 have "\<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s\<rangle> \<Rightarrow> t'"
by (auto intro: exec.CatchMiss)
moreover
from execs_rest Normal have "\<Gamma>\<turnstile>\<langle>cs,css,t'\<rangle> \<Rightarrow> t"
by (cases) auto
ultimately show ?thesis
by (rule execs.Cons)
next
case (Abrupt t'')
from execs_rest Abrupt have "\<Gamma>\<turnstile>\<langle>c2#cs,css,Normal t''\<rangle> \<Rightarrow> t"
by (cases) auto
then obtain v where
exec_c2: "\<Gamma>\<turnstile>\<langle>c2,Normal t''\<rangle> \<Rightarrow> v" and
rest: "\<Gamma>\<turnstile>\<langle>cs,css,v\<rangle> \<Rightarrow> t"
by cases
from exec_c1 Abrupt exec_c2
have "\<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s\<rangle> \<Rightarrow> v"
by - (rule exec.CatchMatch, auto)
from this rest
show ?thesis
by (rule execs.Cons)
next
case (Fault f)
with exec_c1 have "\<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s\<rangle> \<Rightarrow> Fault f"
by (auto intro: exec.intros)
moreover from execs_rest Fault have "\<Gamma>\<turnstile>\<langle>cs,css,Fault f\<rangle> \<Rightarrow> t"
by (cases) auto
ultimately show ?thesis
by (rule execs.Cons)
next
case Stuck
with exec_c1 have "\<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s\<rangle> \<Rightarrow> Stuck"
by (auto intro: exec.intros)
moreover from execs_rest Stuck have "\<Gamma>\<turnstile>\<langle>cs,css,Stuck\<rangle> \<Rightarrow> t"
by (cases) auto
ultimately show ?thesis
by (rule execs.Cons)
qed
with Catch show ?thesis by simp
next
case (Call p bdy cs s)
have bdy: "\<Gamma> p = Some bdy" by fact
from Call execs obtain t' where
exec_body: "\<Gamma>\<turnstile>\<langle>bdy,Normal s\<rangle> \<Rightarrow> t'" and
execs_rest:
"\<Gamma>\<turnstile>\<langle>[],(cs,Throw#cs)#css ,t'\<rangle> \<Rightarrow> t"
by (clarsimp elim!: execs_elim_cases)
have "\<Gamma>\<turnstile>\<langle>Call p # cs,css,Normal s\<rangle> \<Rightarrow> t"
proof (cases t')
case (Normal t'')
with exec_body bdy
have "\<Gamma>\<turnstile>\<langle>Call p ,Normal s\<rangle> \<Rightarrow> Normal t''"
by (auto intro: exec.intros)
moreover
from execs_rest Normal
have "\<Gamma>\<turnstile>\<langle>cs,css ,Normal t''\<rangle> \<Rightarrow> t"
by cases auto
ultimately show ?thesis by (rule execs.Cons)
next
case (Abrupt t'')
with exec_body bdy
have "\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow> Abrupt t''"
by (auto intro: exec.intros)
moreover
from execs_rest Abrupt have
"\<Gamma>\<turnstile>\<langle>Throw # cs,css,Normal t''\<rangle> \<Rightarrow> t"
by (cases) auto
then obtain v where v: "\<Gamma>\<turnstile>\<langle>Throw,Normal t''\<rangle> \<Rightarrow> v" "\<Gamma>\<turnstile>\<langle>cs,css,v\<rangle> \<Rightarrow> t"
by (clarsimp elim!: execs_elim_cases)
moreover from v have "v=Abrupt t''"
by (auto elim: exec_Normal_elim_cases)
ultimately
show ?thesis by (auto intro: execs.Cons)
next
case (Fault f)
with exec_body bdy have "\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow> Fault f"
by (auto intro: exec.intros)
moreover from execs_rest Fault have "\<Gamma>\<turnstile>\<langle>cs,css,Fault f\<rangle> \<Rightarrow> t"
by (cases) (auto elim: execs_elim_cases dest: Fault_end)
ultimately
show ?thesis by (rule execs.Cons)
next
case Stuck
with exec_body bdy have "\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow> Stuck"
by (auto intro: exec.intros)
moreover from execs_rest Stuck have "\<Gamma>\<turnstile>\<langle>cs,css,Stuck\<rangle> \<Rightarrow> t"
by (cases) (auto elim: execs_elim_cases dest: Stuck_end)
ultimately
show ?thesis by (rule execs.Cons)
qed
with Call show ?thesis by simp
qed (insert execs,
(blast intro:execs.intros exec.intros elim!: execs_elim_cases)+)
qed
theorem steps_impl_exec:
assumes steps: "\<Gamma>\<turnstile>([c],[],s) \<rightarrow>\<^sup>* ([],[],t)"
shows "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t"
using steps_impl_execs [OF steps]
by (blast elim: execs_elim_cases)
corollary steps_eq_exec: "\<Gamma>\<turnstile>([c],[],s) \<rightarrow>\<^sup>* ([],[],t) = \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t"
by (blast intro: steps_impl_exec exec_impl_steps)
subsection \<open>Infinite Computations: \<open>inf \<Gamma> cs css s\<close>\<close>
definition inf ::
"[('s,'p,'f) body,('s,'p,'f) com list,('s,'p,'f) continuation list,('s,'f) xstate]
\<Rightarrow> bool"
where "inf \<Gamma> cs css s = (\<exists>f. f 0 = (cs,css,s) \<and> (\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f(Suc i)))"
lemma not_infI: "\<lbrakk>\<And>f. \<lbrakk>f 0 = (cs,css,s); \<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)\<rbrakk> \<Longrightarrow> False\<rbrakk>
\<Longrightarrow> \<not>inf \<Gamma> cs css s"
by (auto simp add: inf_def)
subsection \<open>Equivalence of Termination and Absence of Infinite Computations\<close>
inductive "terminatess":: "[('s,'p,'f) body,('s,'p,'f) com list,
('s,'p,'f) continuation list,('s,'f) xstate] \<Rightarrow> bool"
("_\<turnstile>_,_ \<Down> _" [60,20,60] 89)
for \<Gamma>::"('s,'p,'f) body"
where
Nil: "\<Gamma>\<turnstile>[],[]\<Down>s"
| ExitBlockNormal: "\<Gamma>\<turnstile>nrms,css\<Down>Normal s
\<Longrightarrow>
\<Gamma>\<turnstile>[],(nrms,abrs)#css\<Down>Normal s"
| ExitBlockAbrupt: "\<Gamma>\<turnstile>abrs,css\<Down>Normal s
\<Longrightarrow>
\<Gamma>\<turnstile>[],(nrms,abrs)#css\<Down>Abrupt s"
| ExitBlockFault: "\<Gamma>\<turnstile>nrms,css\<Down>Fault f
\<Longrightarrow>
\<Gamma>\<turnstile>[],(nrms,abrs)#css\<Down>Fault f"
| ExitBlockStuck: "\<Gamma>\<turnstile>nrms,css\<Down>Stuck
\<Longrightarrow>
\<Gamma>\<turnstile>[],(nrms,abrs)#css\<Down>Stuck"
| Cons: "\<lbrakk>\<Gamma>\<turnstile>c\<down>s; (\<forall>t. \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t \<longrightarrow> \<Gamma>\<turnstile>cs,css\<Down>t)\<rbrakk>
\<Longrightarrow>
\<Gamma>\<turnstile>c#cs,css\<Down>s"
inductive_cases terminatess_elim_cases [cases set]:
"\<Gamma>\<turnstile>[],css\<Down>t"
"\<Gamma>\<turnstile>c#cs,css\<Down>t"
lemma terminatess_Fault: "\<And>cs. \<Gamma>\<turnstile>cs,css\<Down>Fault f"
proof (induct css)
case Nil
show "\<Gamma>\<turnstile>cs,[]\<Down>Fault f"
proof (induct cs)
case Nil show "\<Gamma>\<turnstile>[],[]\<Down>Fault f" by (rule terminatess.Nil)
next
case (Cons c cs)
thus ?case
by (auto intro: terminatess.intros terminates.intros dest: Fault_end)
qed
next
case (Cons d css)
have hyp: "\<And>cs. \<Gamma>\<turnstile>cs,css\<Down>Fault f" by fact
obtain nrms abrs where d: "d=(nrms,abrs)" by (cases d) auto
have "\<Gamma>\<turnstile>cs,(nrms,abrs)#css\<Down>Fault f"
proof (induct cs)
case Nil
show "\<Gamma>\<turnstile>[],(nrms, abrs) # css\<Down>Fault f"
by (rule terminatess.ExitBlockFault) (rule hyp)
next
case (Cons c cs)
have hyp1: "\<Gamma>\<turnstile>cs,(nrms, abrs) # css\<Down>Fault f" by fact
show "\<Gamma>\<turnstile>c#cs,(nrms, abrs)#css\<Down>Fault f"
by (auto intro: hyp1 terminatess.Cons terminates.intros dest: Fault_end)
qed
with d show ?case by simp
qed
lemma terminatess_Stuck: "\<And>cs. \<Gamma>\<turnstile>cs,css\<Down>Stuck"
proof (induct css)
case Nil
show "\<Gamma>\<turnstile>cs,[]\<Down>Stuck"
proof (induct cs)
case Nil show "\<Gamma>\<turnstile>[],[]\<Down>Stuck" by (rule terminatess.Nil)
next
case (Cons c cs)
thus ?case
by (auto intro: terminatess.intros terminates.intros dest: Stuck_end)
qed
next
case (Cons d css)
have hyp: "\<And>cs. \<Gamma>\<turnstile>cs,css\<Down>Stuck" by fact
obtain nrms abrs where d: "d=(nrms,abrs)" by (cases d) auto
have "\<Gamma>\<turnstile>cs,(nrms,abrs)#css\<Down>Stuck"
proof (induct cs)
case Nil
show "\<Gamma>\<turnstile>[],(nrms, abrs) # css\<Down>Stuck"
by (rule terminatess.ExitBlockStuck) (rule hyp)
next
case (Cons c cs)
have hyp1: "\<Gamma>\<turnstile>cs,(nrms, abrs) # css\<Down>Stuck" by fact
show "\<Gamma>\<turnstile>c#cs,(nrms, abrs)#css\<Down>Stuck"
by (auto intro: hyp1 terminatess.Cons terminates.intros dest: Stuck_end)
qed
with d show ?case by simp
qed
lemma Basic_terminates: "\<Gamma>\<turnstile>Basic f \<down> t"
by (cases t) (auto intro: terminates.intros)
lemma step_preserves_terminations:
assumes step: "\<Gamma>\<turnstile>(cs,css,s) \<rightarrow> (cs',css',t)"
shows "\<Gamma>\<turnstile>cs,css\<Down>s \<Longrightarrow> \<Gamma>\<turnstile>cs',css'\<Down>t"
using step
proof (induct)
case Skip thus ?case
by (auto elim: terminates_Normal_elim_cases terminatess_elim_cases
intro: exec.intros)
next
case Guard thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case GuardFault thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case FaultProp show ?case by (rule terminatess_Fault)
next
case FaultPropBlock show ?case by (rule terminatess_Fault)
next
case AbruptProp thus ?case
by (blast elim: terminatess_elim_cases
intro: terminatess.intros)
next
case ExitBlockNormal thus ?case
by (blast elim: terminatess_elim_cases
intro: terminatess.intros )
next
case ExitBlockAbrupt thus ?case
by (blast elim: terminatess_elim_cases
intro: terminatess.intros )
next
case Basic thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case Spec thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case SpecStuck thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case Seq thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case CondTrue thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case CondFalse thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case WhileTrue thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case WhileFalse thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case (Call p bdy cs css s)
have bdy: "\<Gamma> p = Some bdy" by fact
from Call obtain
term_body: "\<Gamma>\<turnstile>bdy \<down> Normal s" and
term_rest: "\<forall>t. \<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow> t \<longrightarrow> \<Gamma>\<turnstile>cs,css\<Down>t"
by (fastforce elim!: terminatess_elim_cases terminates_Normal_elim_cases)
show "\<Gamma>\<turnstile>[bdy],(cs,Throw # cs)#css\<Down>Normal s"
proof (rule terminatess.Cons [OF term_body],clarsimp)
fix t
assume exec_body: "\<Gamma>\<turnstile>\<langle>bdy,Normal s\<rangle> \<Rightarrow> t"
show "\<Gamma>\<turnstile>[],(cs,Throw # cs) # css\<Down>t"
proof (cases t)
case (Normal t')
with exec_body bdy
have "\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow> Normal t'"
by (auto intro: exec.intros)
with term_rest have "\<Gamma>\<turnstile>cs,css\<Down>Normal t'"
by iprover
with Normal show ?thesis
by (auto intro: terminatess.intros terminates.intros
elim: exec_Normal_elim_cases)
next
case (Abrupt t')
with exec_body bdy
have "\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow> Abrupt t'"
by (auto intro: exec.intros)
with term_rest have "\<Gamma>\<turnstile>cs,css\<Down>Abrupt t'"
by iprover
with Abrupt show ?thesis
by (fastforce intro: terminatess.intros terminates.intros
elim: exec_Normal_elim_cases)
next
case Fault
thus ?thesis
by (iprover intro: terminatess_Fault)
next
case Stuck
thus ?thesis
by (iprover intro: terminatess_Stuck)
qed
qed
next
case CallUndefined thus ?case
by (iprover intro: terminatess_Stuck)
next
case StuckProp show ?case by (rule terminatess_Stuck)
next
case StuckPropBlock show ?case by (rule terminatess_Stuck)
next
case DynCom thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case Throw thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case (Catch c1 c2 cs css s)
then obtain
term_c1: "\<Gamma>\<turnstile>c1 \<down> Normal s" and
term_c2: "\<forall>s'. \<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow> Abrupt s' \<longrightarrow> \<Gamma>\<turnstile>c2 \<down> Normal s'"and
term_rest: "\<forall>t. \<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s\<rangle> \<Rightarrow> t \<longrightarrow> \<Gamma>\<turnstile>cs,css\<Down>t"
by (clarsimp elim!: terminatess_elim_cases terminates_Normal_elim_cases)
show "\<Gamma>\<turnstile>[c1],(cs, c2 # cs) # css\<Down>Normal s"
proof (rule terminatess.Cons [OF term_c1],clarsimp)
fix t
assume exec_c1: "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow> t"
show "\<Gamma>\<turnstile>[],(cs, c2 # cs) # css\<Down>t"
proof (cases t)
case (Normal t')
with exec_c1 have "\<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s\<rangle> \<Rightarrow> t"
by (auto intro: exec.intros)
with term_rest have "\<Gamma>\<turnstile>cs,css\<Down>t"
by iprover
with Normal show ?thesis
by (iprover intro: terminatess.intros)
next
case (Abrupt t')
with exec_c1 term_c2 have "\<Gamma>\<turnstile>c2 \<down> Normal t'"
by auto
moreover
{
fix w
assume exec_c2: "\<Gamma>\<turnstile>\<langle>c2,Normal t'\<rangle> \<Rightarrow> w"
have "\<Gamma>\<turnstile>cs,css\<Down>w"
proof -
from exec_c1 Abrupt exec_c2
have "\<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s\<rangle> \<Rightarrow> w"
by (auto intro: exec.intros)
with term_rest show ?thesis by simp
qed
}
ultimately
show ?thesis using Abrupt
by (auto intro: terminatess.intros)
next
case Fault thus ?thesis
by (iprover intro: terminatess_Fault)
next
case Stuck thus ?thesis
by (iprover intro: terminatess_Stuck)
qed
qed
qed
ML \<open>
ML_Thms.bind_thm ("rtrancl_induct3", Split_Rule.split_rule @{context}
(Rule_Insts.read_instantiate @{context}
[((("a", 0), Position.none), "(ax, ay, az)"),
((("b", 0), Position.none), "(bx, by, bz)")] []
@{thm rtranclp_induct}));
\<close>
lemma steps_preserves_terminations:
assumes steps: "\<Gamma>\<turnstile>(cs,css,s) \<rightarrow>\<^sup>* (cs',css',t)"
shows "\<Gamma>\<turnstile>cs,css\<Down>s \<Longrightarrow> \<Gamma>\<turnstile>cs',css'\<Down>t"
using steps
proof (induct rule: rtrancl_induct3 [consumes 1])
assume "\<Gamma>\<turnstile>cs,css\<Down>s" then show "\<Gamma>\<turnstile>cs,css\<Down>s".
next
fix cs'' css'' w cs' css' t
assume "\<Gamma>\<turnstile>(cs'',css'', w) \<rightarrow> (cs',css', t)" "\<Gamma>\<turnstile>cs,css\<Down>s \<Longrightarrow> \<Gamma>\<turnstile>cs'',css''\<Down>w"
"\<Gamma>\<turnstile>cs,css\<Down>s"
then show "\<Gamma>\<turnstile>cs',css'\<Down>t"
by (blast dest: step_preserves_terminations)
qed
theorem steps_preserves_termination:
assumes steps: "\<Gamma>\<turnstile>([c],[],s) \<rightarrow>\<^sup>* (c'#cs',css',t)"
assumes term_c: "\<Gamma>\<turnstile>c\<down>s"
shows "\<Gamma>\<turnstile>c'\<down>t"
proof -
from term_c have "\<Gamma>\<turnstile>[c],[]\<Down>s"
by (auto intro: terminatess.intros)
from steps this
have "\<Gamma>\<turnstile>c'#cs',css'\<Down>t"
by (rule steps_preserves_terminations)
thus "\<Gamma>\<turnstile>c'\<down>t"
by (auto elim: terminatess_elim_cases)
qed
lemma renumber':
assumes f: "\<forall>i. (a,f i) \<in> r\<^sup>* \<and> (f i,f(Suc i)) \<in> r"
assumes a_b: "(a,b) \<in> r\<^sup>*"
shows "b = f 0 \<Longrightarrow> (\<exists>f. f 0 = a \<and> (\<forall>i. (f i, f(Suc i)) \<in> r))"
using a_b
proof (induct rule: converse_rtrancl_induct [consumes 1])
assume "b = f 0"
with f show "\<exists>f. f 0 = b \<and> (\<forall>i. (f i, f (Suc i)) \<in> r)"
by blast
next
fix a z
assume a_z: "(a, z) \<in> r" and "(z, b) \<in> r\<^sup>*"
assume "b = f 0 \<Longrightarrow> \<exists>f. f 0 = z \<and> (\<forall>i. (f i, f (Suc i)) \<in> r)"
"b = f 0"
then obtain f where f0: "f 0 = z" and seq: "\<forall>i. (f i, f (Suc i)) \<in> r"
by iprover
{
fix i have "((\<lambda>i. case i of 0 \<Rightarrow> a | Suc i \<Rightarrow> f i) i, f i) \<in> r"
using seq a_z f0
by (cases i) auto
}
then
show "\<exists>f. f 0 = a \<and> (\<forall>i. (f i, f (Suc i)) \<in> r)"
by - (rule exI [where x="\<lambda>i. case i of 0 \<Rightarrow> a | Suc i \<Rightarrow> f i"],simp)
qed
lemma renumber:
"\<forall>i. (a,f i) \<in> r\<^sup>* \<and> (f i,f(Suc i)) \<in> r
\<Longrightarrow> \<exists>f. f 0 = a \<and> (\<forall>i. (f i, f(Suc i)) \<in> r)"
by(blast dest:renumber')
lemma not_inf_Fault':
assumes enum_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
shows "\<And>k cs. f k = (cs,css,Fault m) \<Longrightarrow> False"
proof (induct css)
case Nil
have f_k: "f k = (cs,[],Fault m)" by fact
have "\<And>k. f k = (cs,[],Fault m) \<Longrightarrow> False"
proof (induct cs)
case Nil
have "f k = ([], [], Fault m)" by fact
moreover
from enum_step have "\<Gamma>\<turnstile>f k \<rightarrow> f (Suc k)"..
ultimately show "False"
by (fastforce elim: step_elim_cases)
next
case (Cons c cs)
have fk: "f k = (c # cs, [], Fault m)" by fact
from enum_step have "\<Gamma>\<turnstile>f k \<rightarrow> f (Suc k)"..
with fk have "f (Suc k) = (cs,[],Fault m)"
by (fastforce elim: step_elim_cases)
with enum_step Cons.hyps
show False
by blast
qed
from this f_k show False by blast
next
case (Cons ds css)
then obtain nrms abrs where ds: "ds=(nrms,abrs)" by (cases ds) auto
have hyp: "\<And>k cs. f k = (cs,css,Fault m) \<Longrightarrow> False" by fact
have "\<And>k. f k = (cs,(nrms,abrs)#css,Fault m) \<Longrightarrow> False"
proof (induct cs)
case Nil
have fk: "f k = ([], (nrms, abrs) # css, Fault m)" by fact
from enum_step have "\<Gamma>\<turnstile>f k \<rightarrow> f (Suc k)"..
with fk have "f (Suc k) = (nrms,css,Fault m)"
by (fastforce elim: step_elim_cases)
thus ?case
by (rule hyp)
next
case (Cons c cs)
have fk: "f k = (c#cs, (nrms, abrs) # css, Fault m)" by fact
have hyp1: "\<And>k. f k = (cs, (nrms, abrs) # css, Fault m) \<Longrightarrow> False" by fact
from enum_step have "\<Gamma>\<turnstile>f k \<rightarrow> f (Suc k)"..
with fk have "f (Suc k) = (cs,(nrms,abrs)#css,Fault m)"
by (fastforce elim: step_elim_cases)
thus ?case
by (rule hyp1)
qed
with ds Cons.prems show False by auto
qed
lemma not_inf_Fault:
"\<not> inf \<Gamma> cs css (Fault m)"
apply (rule not_infI)
apply (rule_tac f=f in not_inf_Fault' )
by auto
lemma not_inf_Stuck':
assumes enum_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
shows "\<And>k cs. f k = (cs,css,Stuck) \<Longrightarrow> False"
proof (induct css)
case Nil
have f_k: "f k = (cs,[],Stuck)" by fact
have "\<And>k. f k = (cs,[],Stuck) \<Longrightarrow> False"
proof (induct cs)
case Nil
have "f k = ([], [], Stuck)" by fact
moreover
from enum_step have "\<Gamma>\<turnstile>f k \<rightarrow> f (Suc k)"..
ultimately show "False"
by (fastforce elim: step_elim_cases)
next
case (Cons c cs)
have fk: "f k = (c # cs, [], Stuck)" by fact
from enum_step have "\<Gamma>\<turnstile>f k \<rightarrow> f (Suc k)"..
with fk have "f (Suc k) = (cs,[],Stuck)"
by (fastforce elim: step_elim_cases)
with enum_step Cons.hyps
show False
by blast
qed
from this f_k show False .
next
case (Cons ds css)
then obtain nrms abrs where ds: "ds=(nrms,abrs)" by (cases ds) auto
have hyp: "\<And>k cs. f k = (cs,css,Stuck) \<Longrightarrow> False" by fact
have "\<And>k. f k = (cs,(nrms,abrs)#css,Stuck) \<Longrightarrow> False"
proof (induct cs)
case Nil
have fk: "f k = ([], (nrms, abrs) # css, Stuck)" by fact
from enum_step have "\<Gamma>\<turnstile>f k \<rightarrow> f (Suc k)"..
with fk have "f (Suc k) = (nrms,css,Stuck)"
by (fastforce elim: step_elim_cases)
thus ?case
by (rule hyp)
next
case (Cons c cs)
have fk: "f k = (c#cs, (nrms, abrs) # css, Stuck)" by fact
have hyp1: "\<And>k. f k = (cs, (nrms, abrs) # css, Stuck) \<Longrightarrow> False" by fact
from enum_step have "\<Gamma>\<turnstile>f k \<rightarrow> f (Suc k)"..
with fk have "f (Suc k) = (cs,(nrms,abrs)#css,Stuck)"
by (fastforce elim: step_elim_cases)
thus ?case
by (rule hyp1)
qed
with ds Cons.prems show False by auto
qed
lemma not_inf_Stuck:
"\<not> inf \<Gamma> cs css Stuck"
apply (rule not_infI)
apply (rule_tac f=f in not_inf_Stuck')
by auto
lemma last_butlast_app:
assumes butlast: "butlast as = xs @ butlast bs"
assumes not_Nil: "bs \<noteq> []" "as \<noteq> []"
assumes last: "fst (last as) = fst (last bs)" "snd (last as) = snd (last bs)"
shows "as = xs @ bs"
proof -
from last have "last as = last bs"
by (cases "last as",cases "last bs") simp
moreover
from not_Nil have "as = butlast as @ [last as]" "bs = butlast bs @ [last bs]"
by auto
ultimately show ?thesis
using butlast
by simp
qed
lemma last_butlast_tl:
assumes butlast: "butlast bs = x # butlast as"
assumes not_Nil: "bs \<noteq> []" "as \<noteq> []"
assumes last: "fst (last as) = fst (last bs)" "snd (last as) = snd (last bs)"
shows "as = tl bs"
proof -
from last have "last as = last bs"
by (cases "last as",cases "last bs") simp
moreover
from not_Nil have "as = butlast as @ [last as]" "bs = butlast bs @ [last bs]"
by auto
ultimately show ?thesis
using butlast
by simp
qed
locale inf =
fixes CS:: "('s,'p,'f) config \<Rightarrow> ('s, 'p,'f) com list"
and CSS:: "('s,'p,'f) config \<Rightarrow> ('s, 'p,'f) continuation list"
and S:: "('s,'p,'f) config \<Rightarrow> ('s,'f) xstate"
defines CS_def : "CS \<equiv> fst"
defines CSS_def : "CSS \<equiv> \<lambda>c. fst (snd c)"
defines S_def: "S \<equiv> \<lambda>c. snd (snd c)"
lemma (in inf) steps_hd_drop_suffix:
assumes f_0: "f 0 = (c#cs,css,s)"
assumes f_step: "\<forall>i. \<Gamma>\<turnstile> f(i) \<rightarrow> f(Suc i)"
assumes not_finished: "\<forall>i < k. \<not> (CS (f i) = cs \<and> CSS (f i) = css)"
assumes simul: "\<forall>i\<le>k.
(if pcss i = [] then CSS (f i)=css \<and> CS (f i)=pcs i@cs
else CS (f i)=pcs i \<and>
CSS (f i)= butlast (pcss i)@
[(fst (last (pcss i))@cs,(snd (last (pcss i)))@cs)]@
css)"
defines "p\<equiv>\<lambda>i. (pcs i, pcss i, S (f i))"
shows "\<forall>i<k. \<Gamma>\<turnstile> p i \<rightarrow> p (Suc i)"
using not_finished simul
proof (induct k)
case 0
thus ?case by simp
next
case (Suc k)
have simul: "\<forall>i\<le>Suc k.
(if pcss i = [] then CSS (f i)=css \<and> CS (f i)=pcs i@cs
else CS (f i)=pcs i \<and>
CSS (f i)= butlast (pcss i)@
[(fst (last (pcss i))@cs,(snd (last (pcss i)))@cs)]@
css)" by fact
have not_finished': "\<forall>i < Suc k. \<not> (CS (f i) = cs \<and> CSS (f i) = css)" by fact
with simul
have not_finished: "\<forall>i<Suc k. \<not> (pcs i = [] \<and> pcss i = [])"
by (auto simp add: CS_def CSS_def S_def split: if_split_asm)
show ?case
proof (clarify)
fix i
assume i_le_Suc_k: "i < Suc k"
show "\<Gamma>\<turnstile> p i \<rightarrow> p (Suc i)"
proof (cases "i < k")
case True
with not_finished' simul Suc.hyps
show ?thesis
by auto
next
case False
with i_le_Suc_k
have eq_i_k: "i=k"
by simp
show "\<Gamma>\<turnstile>p i \<rightarrow> p (Suc i)"
proof -
obtain cs' css' t' where
f_Suc_i: "f (Suc i) = (cs', css', t')"
by (cases "f (Suc i)")
obtain cs'' css'' t'' where
f_i: "f i = (cs'',css'',t'')"
by (cases "f i")
from not_finished eq_i_k
have pcs_pcss_not_Nil: "\<not> (pcs i = [] \<and> pcss i = [])"
by auto
from simul [rule_format, of i] i_le_Suc_k f_i
have pcs_pcss_i:
"if pcss i = [] then css''=css \<and> cs''=pcs i@cs
else cs''=pcs i \<and>
css''= butlast (pcss i)@
[(fst (last (pcss i))@cs,(snd (last (pcss i)))@cs)]@
css"
by (simp add: CS_def CSS_def S_def cong: if_cong)
from simul [rule_format, of "Suc i"] i_le_Suc_k f_Suc_i
have pcs_pcss_Suc_i:
"if pcss (Suc i) = [] then css' = css \<and> cs' = pcs (Suc i) @ cs
else cs' = pcs (Suc i) \<and>
css' = butlast (pcss (Suc i)) @
[(fst (last (pcss (Suc i))) @ cs, snd (last (pcss (Suc i))) @ cs)] @
css"
by (simp add: CS_def CSS_def S_def cong: if_cong)
show ?thesis
proof (cases "pcss i = []")
case True
note pcss_Nil = this
with pcs_pcss_i pcs_pcss_not_Nil obtain p ps where
pcs_i: "pcs i = p#ps" and
css'': "css''=css" and
cs'': "cs''=(p#ps)@cs"
by (auto simp add: neq_Nil_conv)
with f_i have "f i = (p#(ps@cs),css,t'')"
by simp
with f_Suc_i f_step [rule_format, of i]
have step_css: "\<Gamma>\<turnstile> (p#(ps@cs),css,t'') \<rightarrow> (cs',css',t')"
by simp
from step_Cons' [OF this, of p "ps@cs"]
obtain css''' where
css''': "css' = css''' @ css"
"if css''' = [] then \<exists>p. cs' = p @ ps @ cs
else (\<exists>pnorm pabr. css'''=[(pnorm @ ps @ cs,pabr @ ps @ cs)])"
by auto
show ?thesis
proof (cases "css''' = []")
case True
with css'''
obtain p' where
css': "css' = css" and
cs': "cs' = p' @ ps @ cs"
by auto
(*from cs' css' f_Suc_i f_i [rule_format, of "Suc k"]
have p_ps_not_Nil: "p'@ps \<noteq> Nil"
by auto*)
from css' cs' step_css
have step: "\<Gamma>\<turnstile> (p#(ps@cs),css,t'') \<rightarrow> (p'@ps@cs,css,t')"
by simp
hence "\<Gamma>\<turnstile> ((p#ps)@cs,css,t'') \<rightarrow> ((p'@ps)@cs,css,t')"
by simp
from drop_suffix_css_step' [OF drop_suffix_same_css_step [OF this],
where xs="css" and css="[]" and css'="[]"]
have "\<Gamma>\<turnstile> (p#ps,[],t'') \<rightarrow> (p'@ps,[],t')"
by simp
moreover
from css' cs' pcs_pcss_Suc_i
obtain "pcs (Suc i) = p'@ps" and "pcss (Suc i) = []"
by (simp split: if_split_asm)
ultimately show ?thesis
using pcs_i pcss_Nil f_i f_Suc_i
by (simp add: CS_def CSS_def S_def p_def)
next
case False
with css'''
obtain pnorm pabr where
css': "css'=css'''@css"
"css'''=[(pnorm @ ps @ cs,pabr @ ps @ cs)]"
by auto
with css''' step_css
have "\<Gamma>\<turnstile> (p#ps@cs,css,t'') \<rightarrow> (cs',[(pnorm@ps@cs,pabr@ps@cs)]@css,t')"
by simp
then
have "\<Gamma>\<turnstile>(p#ps, css, t'') \<rightarrow> (cs', [(pnorm@ps, pabr@ps)] @ css, t')"
by (rule drop_suffix_hd_css_step)
from drop_suffix_css_step' [OF this,
where css="[]" and xs="css" and css'="[(pnorm@ps, pabr@ps)]"]
have "\<Gamma>\<turnstile> (p#ps,[],t'') \<rightarrow> (cs',[(pnorm@ps, pabr@ps)],t')"
by simp
moreover
from css' pcs_pcss_Suc_i
obtain "pcs (Suc i) = cs'" "pcss (Suc i) = [(pnorm@ps, pabr@ps)]"
apply (cases "pcss (Suc i)")
apply (auto split: if_split_asm)
done
ultimately show ?thesis
using pcs_i pcss_Nil f_i f_Suc_i
by (simp add: p_def CS_def CSS_def S_def)
qed
next
case False
note pcss_i_not_Nil = this
with pcs_pcss_i obtain
cs'': "cs''=pcs i" and
css'': "css''= butlast (pcss i)@
[(fst (last (pcss i))@cs,(snd (last (pcss i)))@cs)]@
css"
by auto
from f_Suc_i f_i f_step [rule_format, of i]
have step_i_full: "\<Gamma>\<turnstile> (cs'',css'',t'') \<rightarrow> (cs',css',t')"
by simp
show ?thesis
proof (cases cs'')
case (Cons c' cs)
with step_Cons' [OF step_i_full]
obtain css''' where css': "css' = css'''@css''"
by auto
with step_i_full
have "\<Gamma>\<turnstile> (cs'',css'',t'') \<rightarrow> (cs',css'''@css'',t')"
by simp
from Cons_change_css_step [OF this, where xss="pcss i"] Cons cs''
have "\<Gamma>\<turnstile> (pcs i, pcss i,t'') \<rightarrow> (cs',css'''@pcss i,t')"
by simp
moreover
from cs'' css'' css' False pcs_pcss_Suc_i
obtain "pcs (Suc i) = cs'" "pcss (Suc i) = css'''@pcss i"
apply (auto split: if_split_asm)
apply (drule (4) last_butlast_app)
by simp
ultimately show ?thesis
using f_i f_Suc_i
by (simp add: p_def CS_def CSS_def S_def)
next
case Nil
note cs''_Nil = this
show ?thesis
proof (cases "butlast (pcss i)")
case (Cons bpcs bpcss)
with cs''_Nil step_i_full css''
have *: "\<Gamma>\<turnstile> ([],[hd css'']@tl css'',t'') \<rightarrow> (cs',css',t')"
by simp
moreover
from step_Nil [OF *]
have css': "css'=tl css''"
by simp
ultimately have
step_i_full: "\<Gamma>\<turnstile> ([],[hd css'']@tl css'',t'') \<rightarrow> (cs',tl css'',t')"
by simp
from css'' Cons pcss_i_not_Nil
have "hd css'' = hd (pcss i)"
by (auto simp add: neq_Nil_conv split: if_split_asm)
with cs'' cs''_Nil
Nil_change_css_step [where ass="[hd css'']" and
css="tl css''" and ass'="[]" and
xss="tl (pcss i)", simplified, OF step_i_full [simplified]]
have "\<Gamma>\<turnstile> (pcs i,[hd (pcss i)]@tl (pcss i),t'') \<rightarrow> (cs',tl (pcss i),t')"
by simp
with pcss_i_not_Nil
have "\<Gamma>\<turnstile> (pcs i,pcss i,t'') \<rightarrow> (cs',tl (pcss i),t')"
by simp
moreover
from css' css'' cs''_Nil Cons pcss_i_not_Nil pcs_pcss_Suc_i
obtain "pcs (Suc i) = cs'" "pcss (Suc i) = tl (pcss i)"
apply (clarsimp split: if_split_asm)
apply (drule (4) last_butlast_tl)
by simp
ultimately show ?thesis
using f_i f_Suc_i
by (simp add: p_def CS_def CSS_def S_def)
next
case Nil
with css'' pcss_i_not_Nil
obtain pnorm pabr
where css'': "css''= [(pnorm@cs,pabr@cs)]@css" and
pcss_i: "pcss i = [(pnorm,pabr)]"
by (force simp add: neq_Nil_conv split: if_split_asm)
with cs''_Nil step_i_full
have "\<Gamma>\<turnstile>([],[(pnorm@cs,pabr@cs)]@css,t'') \<rightarrow> (cs',css',t')"
by simp
from step_Nil [OF this]
obtain
css': "css'=css" and
cs': "(case t'' of
Abrupt s' \<Rightarrow> cs' = pabr @ cs \<and> t' = Normal s'
| _ \<Rightarrow> cs' = pnorm @ cs \<and> t' = t'')"
by (simp cong: xstate.case_cong)
let "?pcs_Suc_i " = "(case t'' of Abrupt s' \<Rightarrow> pabr | _ \<Rightarrow> pnorm)"
from cs'
have "\<Gamma>\<turnstile>([],[(pnorm,pabr)],t'') \<rightarrow> (?pcs_Suc_i,[],t')"
by (auto intro: step.intros split: xstate.splits)
moreover
from css'' css' cs' pcss_i pcs_pcss_Suc_i
obtain "pcs (Suc i) = ?pcs_Suc_i" "pcss (Suc i) = []"
by (simp split: if_split_asm xstate.splits)
ultimately
show ?thesis
using pcss_i cs'' cs''_Nil f_i f_Suc_i
by (simp add: p_def CS_def CSS_def S_def)
qed
qed
qed
qed
qed
qed
qed
lemma k_steps_to_rtrancl:
assumes steps: "\<forall>i<k. \<Gamma>\<turnstile> p i \<rightarrow> p (Suc i)"
shows "\<Gamma>\<turnstile>p 0\<rightarrow>\<^sup>* p k"
using steps
proof (induct k)
case 0 thus ?case by auto
next
case (Suc k)
have "\<forall>i<Suc k. \<Gamma>\<turnstile> p i \<rightarrow> p (Suc i)" by fact
then obtain
step_le_k: "\<forall>i<k. \<Gamma>\<turnstile> p i \<rightarrow> p (Suc i)" and step_k: "\<Gamma>\<turnstile> p k \<rightarrow> p (Suc k)"
by auto
from Suc.hyps [OF step_le_k]
have "\<Gamma>\<turnstile> p 0 \<rightarrow>\<^sup>* p k".
also note step_k
finally show ?case .
qed
lemma (in inf) steps_hd_drop_suffix_finite:
assumes f_0: "f 0 = (c#cs,css,s)"
assumes f_step: "\<forall>i. \<Gamma>\<turnstile> f(i) \<rightarrow> f(Suc i)"
assumes not_finished: "\<forall>i < k. \<not> (CS (f i) = cs \<and> CSS (f i) = css)"
assumes simul: "\<forall>i\<le>k.
(if pcss i = [] then CSS (f i)=css \<and> CS (f i)=pcs i@cs
else CS (f i)=pcs i \<and>
CSS (f i)= butlast (pcss i)@
[(fst (last (pcss i))@cs,(snd (last (pcss i)))@cs)]@
css)"
shows "\<Gamma>\<turnstile>([c],[],s) \<rightarrow>\<^sup>* (pcs k, pcss k, S (f k))"
proof -
from steps_hd_drop_suffix [OF f_0 f_step not_finished simul]
have "\<forall>i<k. \<Gamma>\<turnstile> (pcs i, pcss i, S (f i)) \<rightarrow>
(pcs (Suc i), pcss (Suc i), S (f (Suc i)))".
from k_steps_to_rtrancl [OF this]
have "\<Gamma>\<turnstile> (pcs 0, pcss 0, S (f 0)) \<rightarrow>\<^sup>* (pcs k, pcss k, S (f k))".
moreover from f_0 simul [rule_format, of 0]
have "(pcs 0, pcss 0, S (f 0)) = ([c],[],s)"
by (auto split: if_split_asm simp add: CS_def CSS_def S_def)
ultimately show ?thesis by simp
qed
lemma (in inf) steps_hd_drop_suffix_infinite:
assumes f_0: "f 0 = (c#cs,css,s)"
assumes f_step: "\<forall>i. \<Gamma>\<turnstile> f(i) \<rightarrow> f(Suc i)"
assumes not_finished: "\<forall>i. \<not> (CS (f i) = cs \<and> CSS (f i) = css)"
(*assumes not_finished: "\<forall>i. \<not> (pcs i = [] \<and> pcss i = [])"*)
assumes simul: "\<forall>i.
(if pcss i = [] then CSS (f i)=css \<and> CS (f i)=pcs i@cs
else CS (f i)=pcs i \<and>
CSS (f i)= butlast (pcss i)@
[(fst (last (pcss i))@cs,(snd (last (pcss i)))@cs)]@
css)"
defines "p\<equiv>\<lambda>i. (pcs i, pcss i, S (f i))"
shows "\<Gamma>\<turnstile> p i \<rightarrow> p (Suc i)"
proof -
from steps_hd_drop_suffix [OF f_0 f_step, of "Suc i" pcss pcs] not_finished simul
show ?thesis
by (auto simp add: p_def)
qed
lemma (in inf) steps_hd_progress:
assumes f_0: "f 0 = (c#cs,css,s)"
assumes f_step: "\<forall>i. \<Gamma>\<turnstile> f(i) \<rightarrow> f(Suc i)"
assumes c_unfinished: "\<forall>i < k. \<not> (CS (f i) = cs \<and> CSS (f i) = css)"
shows "\<forall>i \<le> k. (\<exists>pcs pcss.
(if pcss = [] then CSS (f i)=css \<and> CS (f i)=pcs@cs
else CS (f i)=pcs \<and>
CSS (f i)= butlast pcss@
[(fst (last pcss)@cs,(snd (last pcss))@cs)]@
css))"
using c_unfinished
proof (induct k)
case 0
with f_0 show ?case
by (simp add: CSS_def CS_def)
next
case (Suc k)
have c_unfinished: "\<forall>i<Suc k. \<not> (CS (f i) = cs \<and> CSS (f i) = css)" by fact
hence c_unfinished': "\<forall>i< k. \<not> (CS (f i) = cs \<and> CSS (f i) = css)" by simp
show ?case
proof (clarify)
fix i
assume i_le_Suc_k: "i \<le> Suc k"
show "\<exists>pcs pcss.
(if pcss = [] then CSS (f i)=css \<and> CS (f i)=pcs@cs
else CS (f i)=pcs \<and>
CSS (f i)= butlast pcss@
[(fst (last pcss)@cs,(snd (last pcss))@cs)]@
css)"
proof (cases "i < Suc k")
case True
with Suc.hyps [OF c_unfinished', rule_format, of i] c_unfinished
show ?thesis
by auto
next
case False
with i_le_Suc_k have eq_i_Suc_k: "i=Suc k"
by auto
obtain cs' css' t' where
f_Suc_k: "f (Suc k) = (cs', css', t')"
by (cases "f (Suc k)")
obtain cs'' css'' t'' where
f_k: "f k = (cs'',css'',t'')"
by (cases "f k")
with Suc.hyps [OF c_unfinished',rule_format, of k]
obtain pcs pcss where
pcs_pcss_k:
"if pcss = [] then css'' = css \<and> cs'' = pcs @ cs
else cs'' = pcs \<and>
css'' = butlast pcss @
[(fst (last pcss) @ cs, snd (last pcss) @ cs)] @
css"
by (auto simp add: CSS_def CS_def cong: if_cong)
from c_unfinished [rule_format, of k] f_k pcs_pcss_k
have pcs_pcss_empty: "\<not> (pcs = [] \<and> pcss = [])"
by (auto simp add: CS_def CSS_def S_def split: if_split_asm)
show ?thesis
proof (cases "pcss = []")
case True
note pcss_Nil = this
with pcs_pcss_k pcs_pcss_empty obtain p ps where
pcs_i: "pcs = p#ps" and
css'': "css''=css" and
cs'': "cs''=(p#ps)@cs"
by (cases "pcs") auto
with f_k have "f k = (p#(ps@cs),css,t'')"
by simp
with f_Suc_k f_step [rule_format, of k]
have step_css: "\<Gamma>\<turnstile> (p#(ps@cs),css,t'') \<rightarrow> (cs',css',t')"
by simp
from step_Cons' [OF this, of p "ps@cs"]
obtain css''' where
css''': "css' = css''' @ css"
"if css''' = [] then \<exists>p. cs' = p @ ps @ cs
else (\<exists>pnorm pabr. css'''=[(pnorm @ ps @ cs,pabr @ ps @ cs)])"
by auto
show ?thesis
proof (cases "css''' = []")
case True
with css'''
obtain p' where
css': "css' = css" and
cs': "cs' = p' @ ps @ cs"
by auto
from css' cs' f_Suc_k
show ?thesis
apply (rule_tac x="p'@ps" in exI)
apply (rule_tac x="[]" in exI)
apply (simp add: CSS_def CS_def eq_i_Suc_k)
done
next
case False
with css'''
obtain pnorm pabr where
css': "css'=css'''@css"
"css'''=[(pnorm @ ps @ cs,pabr @ ps @ cs)]"
by auto
with f_Suc_k eq_i_Suc_k
show ?thesis
apply (rule_tac x="cs'" in exI)
apply (rule_tac x="[(pnorm@ps, pabr@ps)]" in exI)
by (simp add: CSS_def CS_def)
qed
next
case False
note pcss_k_not_Nil = this
with pcs_pcss_k obtain
cs'': "cs''=pcs" and
css'': "css''= butlast pcss@
[(fst (last pcss)@cs,(snd (last pcss))@cs)]@
css"
by auto
from f_Suc_k f_k f_step [rule_format, of k]
have step_i_full: "\<Gamma>\<turnstile> (cs'',css'',t'') \<rightarrow> (cs',css',t')"
by simp
show ?thesis
proof (cases cs'')
case (Cons c' cs)
with step_Cons' [OF step_i_full]
obtain css''' where css': "css' = css'''@css''"
by auto
with cs'' css'' f_Suc_k eq_i_Suc_k pcss_k_not_Nil
show ?thesis
apply (rule_tac x="cs'" in exI)
apply (rule_tac x="css'''@pcss" in exI)
by (clarsimp simp add: CSS_def CS_def butlast_append)
next
case Nil
note cs''_Nil = this
show ?thesis
proof (cases "butlast pcss")
case (Cons bpcs bpcss)
with cs''_Nil step_i_full css''
have *: "\<Gamma>\<turnstile> ([],[hd css'']@tl css'',t'') \<rightarrow> (cs',css',t')"
by simp
moreover
from step_Nil [OF *]
obtain css': "css'=tl css''" and
cs': "cs' = (case t'' of Abrupt s' \<Rightarrow> snd (hd css'')
| _ \<Rightarrow> fst (hd css''))"
by (auto split: xstate.splits)
from css'' Cons pcss_k_not_Nil
have "hd css'' = hd pcss"
by (auto simp add: neq_Nil_conv split: if_split_asm)
with css' cs' css'' cs''_Nil Cons pcss_k_not_Nil f_Suc_k eq_i_Suc_k
show ?thesis
apply (rule_tac x="cs'" in exI)
apply (rule_tac x="tl pcss" in exI)
apply (clarsimp split: xstate.splits
simp add: CS_def CSS_def neq_Nil_conv split: if_split_asm)
done
next
case Nil
with css'' pcss_k_not_Nil
obtain pnorm pabr
where css'': "css''= [(pnorm@cs,pabr@cs)]@css" and
pcss_k: "pcss = [(pnorm,pabr)]"
by (force simp add: neq_Nil_conv split: if_split_asm)
with cs''_Nil step_i_full
have "\<Gamma>\<turnstile>([],[(pnorm@cs,pabr@cs)]@css,t'') \<rightarrow> (cs',css',t')"
by simp
from step_Nil [OF this]
obtain
css': "css'=css" and
cs': "(case t'' of
Abrupt s' \<Rightarrow> cs' = pabr @ cs \<and> t' = Normal s'
| _ \<Rightarrow> cs' = pnorm @ cs \<and> t' = t'')"
by (simp cong: xstate.case_cong)
let "?pcs_Suc_k " = "(case t'' of Abrupt s' \<Rightarrow> pabr | _ \<Rightarrow> pnorm)"
from css'' css' cs' pcss_k f_Suc_k eq_i_Suc_k
show ?thesis
apply (rule_tac x="?pcs_Suc_k" in exI)
apply (rule_tac x="[]" in exI)
apply (simp split: xstate.splits add: CS_def CSS_def)
done
qed
qed
qed
qed
qed
qed
lemma (in inf) inf_progress:
assumes f_0: "f 0 = (c#cs,css,s)"
assumes f_step: "\<forall>i. \<Gamma>\<turnstile> f(i) \<rightarrow> f(Suc i)"
assumes unfinished: "\<forall>i. \<not> ((CS (f i) = cs) \<and> (CSS (f i) = css))"
shows "\<exists>pcs pcss.
(if pcss = [] then CSS (f i)=css \<and> CS (f i)=pcs@cs
else CS (f i)=pcs \<and>
CSS (f i)= butlast pcss@
[(fst (last pcss)@cs,(snd (last pcss))@cs)]@
css)"
proof -
from steps_hd_progress [OF f_0 f_step, of "i"] unfinished
show ?thesis
by auto
qed
lemma skolemize1: "\<forall>x. P x \<longrightarrow> (\<exists>y. Q x y) \<Longrightarrow> \<exists>f.\<forall>x. P x \<longrightarrow> Q x (f x)"
by (rule choice) blast
lemma skolemize2: "\<forall>x. P x \<longrightarrow> (\<exists>y z. Q x y z) \<Longrightarrow> \<exists>f g.\<forall>x. P x \<longrightarrow> Q x (f x) (g x)"
apply (drule skolemize1)
apply (erule exE)
apply (drule skolemize1)
apply fast
done
lemma skolemize2': "\<forall>x.\<exists>y z. P x y z \<Longrightarrow> \<exists>f g.\<forall>x. P x (f x) (g x)"
apply (drule choice)
apply (erule exE)
apply (drule choice)
apply fast
done
theorem (in inf) inf_cases:
fixes c::"('s,'p,'f) com"
assumes inf: "inf \<Gamma> (c#cs) css s"
shows "inf \<Gamma> [c] [] s \<or> (\<exists>t. \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t \<and> inf \<Gamma> cs css t)"
proof -
from inf obtain f where
f_0: "f 0 = (c#cs,css,s)" and
f_step: "(\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i))"
by (auto simp add: inf_def)
show ?thesis
proof (cases "\<exists>i. CS (f i) = cs \<and> CSS (f i) = css")
case True
define k where "k = (LEAST i. CS (f i) = cs \<and> CSS (f i) = css)"
from True
obtain CS_f_k: "CS (f k) = cs" and CSS_f_k: "CSS (f k) = css"
apply -
apply (erule exE)
apply (drule LeastI)
apply (simp add: k_def)
done
have less_k_prop: "\<forall>i<k. \<not> (CS (f i) = cs \<and> CSS (f i) = css)"
apply (intro allI impI)
apply (unfold k_def)
apply (drule not_less_Least)
apply simp
done
have "\<Gamma>\<turnstile>([c], [], s) \<rightarrow>\<^sup>* ([],[],S (f k))"
proof -
have "\<forall>i\<le>k. \<exists>pcs pcss.
(if pcss = [] then CSS (f i)=css \<and> CS (f i)=pcs@cs
else CS (f i)=pcs \<and>
CSS (f i)= butlast pcss@
[(fst (last pcss)@cs,(snd (last pcss))@cs)]@
css)"
by (rule steps_hd_progress
[OF f_0 f_step, where k=k, OF less_k_prop])
from skolemize2 [OF this] obtain pcs pcss where
pcs_pcss:
"\<forall>i\<le>k.
(if pcss i = [] then CSS (f i)=css \<and> CS (f i)=pcs i@cs
else CS (f i)=pcs i \<and>
CSS (f i)= butlast (pcss i)@
[(fst (last (pcss i))@cs,(snd (last (pcss i)))@cs)]@
css)"
by iprover
from pcs_pcss [rule_format, of k] CS_f_k CSS_f_k
have finished: "pcs k = []" "pcss k = []"
by (auto simp add: CS_def CSS_def S_def split: if_split_asm)
from pcs_pcss
have simul: "\<forall>i\<le>k. (if pcss i = [] then CSS (f i)=css \<and> CS (f i)=pcs i@cs
else CS (f i)=pcs i \<and>
CSS (f i)= butlast (pcss i)@
[(fst (last (pcss i))@cs,(snd (last (pcss i)))@cs)]@
css)"
by auto
from steps_hd_drop_suffix_finite [OF f_0 f_step less_k_prop simul] finished
show ?thesis
by simp
qed
hence "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> S (f k)"
by (rule steps_impl_exec)
moreover
from CS_f_k CSS_f_k f_step
have "inf \<Gamma> cs css (S (f k))"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (i + k)" in exI)
apply simp
apply (auto simp add: CS_def CSS_def S_def)
done
ultimately
have "(\<exists>t. \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t \<and> inf \<Gamma> cs css t)"
by blast
thus ?thesis
by simp
next
case False
hence unfinished: "\<forall>i. \<not> ((CS (f i) = cs) \<and> (CSS (f i) = css))"
by simp
from inf_progress [OF f_0 f_step this]
have "\<forall>i. \<exists>pcs pcss.
(if pcss = [] then CSS (f i)=css \<and> CS (f i)=pcs@cs
else CS (f i)=pcs \<and>
CSS (f i)= butlast pcss@
[(fst (last pcss)@cs,(snd (last pcss))@cs)]@
css)"
by auto
from skolemize2' [OF this] obtain pcs pcss where
pcs_pcss: "\<forall>i.
(if pcss i = [] then CSS (f i)=css \<and> CS (f i)=pcs i@cs
else CS (f i)=pcs i \<and>
CSS (f i)= butlast (pcss i)@
[(fst (last (pcss i))@cs,(snd (last (pcss i)))@cs)]@
css)"
by iprover
define g where "g i = (pcs i, pcss i, S (f i))" for i
from pcs_pcss [rule_format, of 0] f_0
have "g 0 = ([c],[],s)"
by (auto split: if_split_asm simp add: CS_def CSS_def S_def g_def)
moreover
from steps_hd_drop_suffix_infinite [OF f_0 f_step unfinished pcs_pcss]
have "\<forall>i. \<Gamma>\<turnstile>g i \<rightarrow> g (Suc i)"
by (simp add: g_def)
ultimately
have "inf \<Gamma> [c] [] s"
by (auto simp add: inf_def)
thus ?thesis
by simp
qed
qed
lemma infE [consumes 1]:
assumes inf: "inf \<Gamma> (c#cs) css s"
assumes cases: "inf \<Gamma> [c] [] s \<Longrightarrow> P"
"\<And>t. \<lbrakk>\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t; inf \<Gamma> cs css t\<rbrakk> \<Longrightarrow> P"
shows P
using inf cases
apply -
apply (drule inf.inf_cases)
apply auto
done
lemma inf_Seq:
"inf \<Gamma> (Seq c1 c2#cs) css (Normal s) = inf \<Gamma> (c1#c2#cs) css (Normal s)"
proof
assume "inf \<Gamma> (Seq c1 c2 # cs) css (Normal s)"
then obtain f where
f_0: "f 0 = (Seq c1 c2#cs,css,Normal s)" and
f_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
by (auto simp add: inf_def)
from f_step [rule_format, of 0] f_0
have "f 1 = (c1#c2#cs,css,Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step show "inf \<Gamma> (c1#c2#cs) css (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
apply simp
done
next
assume "inf \<Gamma> (c1 # c2 # cs) css (Normal s)"
then obtain f where
f_0: "f 0 = (c1# c2#cs,css,Normal s)" and
f_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
by (auto simp add: inf_def)
define g where "g i = (case i of 0 \<Rightarrow> (Seq c1 c2#cs,css,Normal s) | Suc j \<Rightarrow> f j)" for i
with f_0 have
"\<Gamma>\<turnstile>g 0 \<rightarrow> g (Suc 0)"
by (auto intro: step.intros)
moreover
from f_step have "\<forall>i. i\<noteq>0 \<longrightarrow> \<Gamma>\<turnstile>g i \<rightarrow> g (Suc i)"
by (auto simp add: g_def split: nat.splits)
ultimately
show "inf \<Gamma> (Seq c1 c2 # cs) css (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x=g in exI)
apply (simp add: g_def split: nat.splits)
done
qed
lemma inf_WhileTrue:
assumes b: "s \<in> b"
shows "inf \<Gamma> (While b c#cs) css (Normal s) =
inf \<Gamma> (c#While b c#cs) css (Normal s)"
proof
assume "inf \<Gamma> (While b c # cs) css (Normal s)"
then obtain f where
f_0: "f 0 = (While b c#cs,css,Normal s)" and
f_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
by (auto simp add: inf_def)
from b f_step [rule_format, of 0] f_0
have "f 1 = (c#While b c#cs,css,Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step show "inf \<Gamma> (c # While b c # cs) css (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
apply simp
done
next
assume "inf \<Gamma> (c # While b c # cs) css (Normal s)"
then obtain f where
f_0: "f 0 = (c # While b c #cs,css,Normal s)" and
f_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
by (auto simp add: inf_def)
define h where "h i = (case i of 0 \<Rightarrow> (While b c#cs,css,Normal s) | Suc j \<Rightarrow> f j)" for i
with b f_0 have
"\<Gamma>\<turnstile>h 0 \<rightarrow> h (Suc 0)"
by (auto intro: step.intros)
moreover
from f_step have "\<forall>i. i\<noteq>0 \<longrightarrow> \<Gamma>\<turnstile>h i \<rightarrow> h (Suc i)"
by (auto simp add: h_def split: nat.splits)
ultimately
show "inf \<Gamma> (While b c # cs) css (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x=h in exI)
apply (simp add: h_def split: nat.splits)
done
qed
lemma inf_Catch:
"inf \<Gamma> (Catch c1 c2#cs) css (Normal s) = inf \<Gamma> [c1] ((cs,c2#cs)#css) (Normal s)"
proof
assume "inf \<Gamma> (Catch c1 c2#cs) css (Normal s)"
then obtain f where
f_0: "f 0 = (Catch c1 c2#cs,css,Normal s)" and
f_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
by (auto simp add: inf_def)
from f_step [rule_format, of 0] f_0
have "f 1 = ([c1],(cs,c2#cs)#css,Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step show "inf \<Gamma> [c1] ((cs,c2#cs)#css) (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
apply simp
done
next
assume "inf \<Gamma> [c1] ((cs,c2#cs)#css) (Normal s)"
then obtain f where
f_0: "f 0 = ([c1],(cs,c2#cs)#css,Normal s)" and
f_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
by (auto simp add: inf_def)
define h where "h i = (case i of 0 \<Rightarrow> (Catch c1 c2#cs,css,Normal s) | Suc j \<Rightarrow> f j)" for i
with f_0 have
"\<Gamma>\<turnstile>h 0 \<rightarrow> h (Suc 0)"
by (auto intro: step.intros)
moreover
from f_step have "\<forall>i. i\<noteq>0 \<longrightarrow> \<Gamma>\<turnstile>h i \<rightarrow> h (Suc i)"
by (auto simp add: h_def split: nat.splits)
ultimately
show "inf \<Gamma> (Catch c1 c2 # cs) css (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x=h in exI)
apply (simp add: h_def split: nat.splits)
done
qed
theorem terminates_impl_not_inf:
assumes termi: "\<Gamma>\<turnstile>c \<down> s"
shows "\<not>inf \<Gamma> [c] [] s"
using termi
proof induct
case (Skip s) thus ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Skip], [], Normal s)"
from f_step [of 0] f_0
have "f (Suc 0) = ([],[],Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step [of 1]
show False
by (auto elim: step_elim_cases)
qed
next
case (Basic g s)
thus ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Basic g], [], Normal s)"
from f_step [of 0] f_0
have "f (Suc 0) = ([],[],Normal (g s))"
by (auto elim: step_Normal_elim_cases)
with f_step [of 1]
show False
by (auto elim: step_elim_cases)
qed
next
case (Spec r s)
thus ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Spec r], [], Normal s)"
with f_step [of 0]
have "\<Gamma>\<turnstile>([Spec r], [], Normal s) \<rightarrow> f (Suc 0)"
by simp
then show False
proof (cases)
fix t
assume "(s, t) \<in> r" "f (Suc 0) = ([], [], Normal t)"
with f_step [of 1]
show False
by (auto elim: step_elim_cases)
next
assume "\<forall>t. (s, t) \<notin> r" "f (Suc 0) = ([], [], Stuck)"
with f_step [of 1]
show False
by (auto elim: step_elim_cases)
qed
qed
next
case (Guard s g c m)
have g: "s \<in> g" by fact
have hyp: "\<not> inf \<Gamma> [c] [] (Normal s)" by fact
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Guard m g c], [], Normal s)"
from g f_step [of 0] f_0
have "f (Suc 0) = ([c],[],Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step
have "inf \<Gamma> [c] [] (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
by simp
with hyp show False ..
qed
next
case (GuardFault s g m c)
have g: "s \<notin> g" by fact
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Guard m g c], [], Normal s)"
from g f_step [of 0] f_0
have "f (Suc 0) = ([],[],Fault m)"
by (auto elim: step_Normal_elim_cases)
with f_step [of 1]
show False
by (auto elim: step_elim_cases)
qed
next
case (Fault c m)
thus ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([c], [], Fault m)"
from f_step [of 0] f_0
have "f (Suc 0) = ([],[],Fault m)"
by (auto elim: step_Normal_elim_cases)
with f_step [of 1]
show False
by (auto elim: step_elim_cases)
qed
next
case (Seq c1 s c2)
have hyp_c1: "\<not> inf \<Gamma> [c1] [] (Normal s)" by fact
have hyp_c2: "\<forall>s'. \<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow> s' \<longrightarrow> \<Gamma>\<turnstile>c2 \<down> s' \<and> \<not> inf \<Gamma> [c2] [] s'" by fact
have "\<not> inf \<Gamma> ([c1,c2]) [] (Normal s)"
proof
assume "inf \<Gamma> [c1, c2] [] (Normal s)"
then show False
proof (cases rule: infE)
assume "inf \<Gamma> [c1] [] (Normal s)"
with hyp_c1 show ?thesis by simp
next
fix t
assume "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow> t" "inf \<Gamma> [c2] [] t"
with hyp_c2 show ?thesis by simp
qed
qed
thus ?case
by (simp add: inf_Seq)
next
case (CondTrue s b c1 c2)
have b: "s \<in> b" by fact
have hyp_c1: "\<not> inf \<Gamma> [c1] [] (Normal s)" by fact
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Cond b c1 c2], [], Normal s)"
from b f_step [of 0] f_0
have "f 1 = ([c1],[],Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step
have "inf \<Gamma> [c1] [] (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
by simp
with hyp_c1 show False by simp
qed
next
case (CondFalse s b c2 c1)
have b: "s \<notin> b" by fact
have hyp_c2: "\<not> inf \<Gamma> [c2] [] (Normal s)" by fact
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Cond b c1 c2], [], Normal s)"
from b f_step [of 0] f_0
have "f 1 = ([c2],[],Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step
have "inf \<Gamma> [c2] [] (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
by simp
with hyp_c2 show False by simp
qed
next
case (WhileTrue s b c)
have b: "s \<in> b" by fact
have hyp_c: "\<not> inf \<Gamma> [c] [] (Normal s)" by fact
have hyp_w: "\<forall>s'. \<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> \<Rightarrow> s' \<longrightarrow>
\<Gamma>\<turnstile>While b c \<down> s' \<and> \<not> inf \<Gamma> [While b c] [] s'" by fact
have "\<not> inf \<Gamma> [c,While b c] [] (Normal s)"
proof
assume "inf \<Gamma> [c,While b c] [] (Normal s)"
from this hyp_c hyp_w show False
by (cases rule: infE) auto
qed
with b show ?case
by (simp add: inf_WhileTrue)
next
case (WhileFalse s b c)
have b: "s \<notin> b" by fact
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([While b c], [], Normal s)"
from b f_step [of 0] f_0
have "f (Suc 0) = ([],[],Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step [of 1]
show False
by (auto elim: step_elim_cases)
qed
next
case (Call p bdy s)
have bdy: "\<Gamma> p = Some bdy" by fact
have hyp: "\<not> inf \<Gamma> [bdy] [] (Normal s)" by fact
have not_inf_bdy:
"\<not> inf \<Gamma> [bdy] [([],[Throw])] (Normal s)"
proof
assume "inf \<Gamma> [bdy] [([],[Throw])] (Normal s)"
then show False
proof (rule infE)
assume "inf \<Gamma> [bdy] [] (Normal s)"
with hyp show False by simp
next
fix t
assume "\<Gamma>\<turnstile>\<langle>bdy,Normal s\<rangle> \<Rightarrow> t"
assume inf: "inf \<Gamma> [] [([], [Throw])] t"
then obtain f where
f_0: "f 0 = ([],[([], [Throw])],t)" and
f_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
by (auto simp add: inf_def)
show False
proof (cases t)
case (Normal t')
with f_0 f_step [rule_format, of 0]
have "f (Suc 0) = ([],[],(Normal t'))"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of "Suc 0"]
show False
by (auto elim: step.cases)
next
case (Abrupt t')
with f_0 f_step [rule_format, of 0]
have "f (Suc 0) = ([Throw],[],(Normal t'))"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of "Suc 0"]
have "f (Suc (Suc 0)) = ([],[],(Abrupt t'))"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of "Suc(Suc 0)"]
show False
by (auto elim: step.cases)
next
case (Fault m)
with f_0 f_step [rule_format, of 0]
have "f (Suc 0) = ([],[],Fault m)"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of 1]
have "f (Suc (Suc 0)) = ([],[],Fault m)"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of "Suc (Suc 0)"]
show False
by (auto elim: step.cases)
next
case Stuck
with f_0 f_step [rule_format, of 0]
have "f (Suc 0) = ([],[],Stuck)"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of 1]
have "f (Suc (Suc 0)) = ([],[],Stuck)"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of "Suc (Suc 0)"]
show False
by (auto elim: step.cases)
qed
qed
qed
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Call p], [], Normal s)"
from bdy f_step [of 0] f_0
have "f (Suc 0) =
([bdy],[([],[Throw])],Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step
have "inf \<Gamma> [bdy] [([],[Throw])] (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
by simp
with not_inf_bdy
show False by simp
qed
next
case (CallUndefined p s)
have undef: "\<Gamma> p = None" by fact
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Call p], [], Normal s)"
from undef f_step [of 0] f_0
have "f (Suc 0) = ([],[],Stuck)"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of "Suc 0"]
show False
by (auto elim: step_elim_cases)
qed
next
case (Stuck c)
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([c], [], Stuck)"
from f_step [of 0] f_0
have "f (Suc 0) = ([],[],Stuck)"
by (auto elim: step_elim_cases)
with f_step [rule_format, of "Suc 0"]
show False
by (auto elim: step_elim_cases)
qed
next
case (DynCom c s)
have hyp: "\<not> inf \<Gamma> [(c s)] [] (Normal s)" by fact
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([DynCom c], [], Normal s)"
from f_step [of 0] f_0
have "f (Suc 0) = ([(c s)], [], Normal s)"
by (auto elim: step_elim_cases)
with f_step have "inf \<Gamma> [(c s)] [] (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
by simp
with hyp
show False by simp
qed
next
case (Throw s)
thus ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Throw], [], Normal s)"
from f_step [of 0] f_0
have "f (Suc 0) = ([],[],Abrupt s)"
by (auto elim: step_Normal_elim_cases)
with f_step [of 1]
show False
by (auto elim: step_elim_cases)
qed
next
case (Abrupt c s)
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([c], [], Abrupt s)"
from f_step [of 0] f_0
have "f (Suc 0) = ([],[],Abrupt s)"
by (auto elim: step_elim_cases)
with f_step [rule_format, of "Suc 0"]
show False
by (auto elim: step_elim_cases)
qed
next
case (Catch c1 s c2)
have hyp_c1: "\<not> inf \<Gamma> [c1] [] (Normal s)" by fact
have hyp_c2: "\<forall>s'. \<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow> Abrupt s' \<longrightarrow>
\<Gamma>\<turnstile>c2 \<down> Normal s' \<and> \<not> inf \<Gamma> [c2] [] (Normal s')" by fact
have "\<not> inf \<Gamma> [c1] [([],[c2])] (Normal s)"
proof
assume "inf \<Gamma> [c1] [([],[c2])] (Normal s)"
then show False
proof (rule infE)
assume "inf \<Gamma> [c1] [] (Normal s)"
with hyp_c1 show False by simp
next
fix t
assume eval: "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow> t"
assume inf: "inf \<Gamma> [] [([], [c2])] t"
then obtain f where
f_0: "f 0 = ([],[([], [c2] )],t)" and
f_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
by (auto simp add: inf_def)
show False
proof (cases t)
case (Normal t')
with f_0 f_step [rule_format, of 0]
have "f (Suc 0) = ([],[],Normal t')"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of 1]
show False
by (auto elim: step_elim_cases)
next
case (Abrupt t')
with f_0 f_step [rule_format, of 0]
have "f (Suc 0) = ([c2],[],Normal t')"
by (auto elim: step_Normal_elim_cases)
with f_step eval Abrupt
have "inf \<Gamma> [c2] [] (Normal t')"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
by simp
with eval hyp_c2 Abrupt show False by simp
next
case (Fault m)
with f_0 f_step [rule_format, of 0]
have "f (Suc 0) = ([],[],Fault m)"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of 1]
show False
by (auto elim: step_elim_cases)
next
case Stuck
with f_0 f_step [rule_format, of 0]
have "f (Suc 0) = ([],[],Stuck)"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of 1]
show False
by (auto elim: step_elim_cases)
qed
qed
qed
thus ?case
by (simp add: inf_Catch)
qed
lemma terminatess_impl_not_inf:
assumes termi: "\<Gamma>\<turnstile>cs,css\<Down>s"
shows "\<not>inf \<Gamma> cs css s"
using termi
proof (induct)
case (Nil s)
show ?case
proof (rule not_infI)
fix f
assume "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
hence "\<Gamma>\<turnstile>f 0 \<rightarrow> f (Suc 0)"
by simp
moreover
assume "f 0 = ([], [], s)"
ultimately show False
by (fastforce elim: step.cases)
qed
next
case (ExitBlockNormal nrms css s abrs)
have hyp: "\<not> inf \<Gamma> nrms css (Normal s)" by fact
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f0: "f 0 = ([], (nrms, abrs) # css, Normal s)"
with f_step [of 0] have "f (Suc 0) = (nrms,css,Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step have "inf \<Gamma> nrms css (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
by simp
with hyp show False ..
qed
next
case (ExitBlockAbrupt abrs css s nrms)
have hyp: "\<not> inf \<Gamma> abrs css (Normal s)" by fact
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f0: "f 0 = ([], (nrms, abrs) # css, Abrupt s)"
with f_step [of 0] have "f (Suc 0) = (abrs,css,Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step have "inf \<Gamma> abrs css (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
by simp
with hyp show False ..
qed
next
case (ExitBlockFault nrms css f abrs)
show ?case
by (rule not_inf_Fault)
next
case (ExitBlockStuck nrms css abrs)
show ?case
by (rule not_inf_Stuck)
next
case (Cons c s cs css)
have termi_c: "\<Gamma>\<turnstile>c \<down> s" by fact
have hyp: "\<forall>t. \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t \<longrightarrow> \<Gamma>\<turnstile>cs,css\<Down>t \<and> \<not> inf \<Gamma> cs css t" by fact
show "\<not> inf \<Gamma> (c # cs) css s"
proof
assume "inf \<Gamma> (c # cs) css s"
thus False
proof (rule infE)
assume "inf \<Gamma> [c] [] s"
with terminates_impl_not_inf [OF termi_c]
show False ..
next
fix t
assume "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" "inf \<Gamma> cs css t"
with hyp show False by simp
qed
qed
qed
lemma lem:
"\<forall>y. r\<^sup>+\<^sup>+ a y \<longrightarrow> P a \<longrightarrow> P y
\<Longrightarrow> ((b,a) \<in> {(y,x). P x \<and> r x y}\<^sup>+) = ((b,a) \<in> {(y,x). P x \<and> r\<^sup>+\<^sup>+ x y})"
apply(rule iffI)
apply clarify
apply(erule trancl_induct)
apply blast
apply(blast intro:tranclp_trans)
apply clarify
apply(erule tranclp_induct)
apply blast
apply(blast intro:trancl_trans)
done
corollary terminatess_impl_no_inf_chain:
assumes terminatess: "\<Gamma>\<turnstile>cs,css\<Down>s"
shows "\<not>(\<exists>f. f 0 = (cs,css,s) \<and> (\<forall>i::nat. \<Gamma>\<turnstile>f i \<rightarrow>\<^sup>+ f(Suc i)))"
proof -
have "wf({(y,x). \<Gamma>\<turnstile>(cs,css,s) \<rightarrow>\<^sup>* x \<and> \<Gamma>\<turnstile>x \<rightarrow> y}\<^sup>+)"
proof (rule wf_trancl)
show "wf {(y, x). \<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* x \<and> \<Gamma>\<turnstile>x \<rightarrow> y}"
proof (simp only: wf_iff_no_infinite_down_chain,clarify,simp)
fix f
assume "\<forall>i. \<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* f i \<and> \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
hence "\<exists>f. f 0 = (cs, css, s) \<and> (\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i))"
by (rule renumber [to_pred])
moreover from terminatess
have "\<not> (\<exists>f. f 0 = (cs, css, s) \<and> (\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)))"
by (rule terminatess_impl_not_inf [unfolded inf_def])
ultimately show False
by simp
qed
qed
hence "\<not> (\<exists>f. \<forall>i. (f (Suc i), f i)
\<in> {(y, x). \<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* x \<and> \<Gamma>\<turnstile>x \<rightarrow> y}\<^sup>+)"
by (simp add: wf_iff_no_infinite_down_chain)
thus ?thesis
proof (rule contrapos_nn)
assume "\<exists>f. f 0 = (cs, css, s) \<and> (\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow>\<^sup>+ f (Suc i))"
then obtain f where
f0: "f 0 = (cs, css, s)" and
seq: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow>\<^sup>+ f (Suc i)"
by iprover
show
"\<exists>f. \<forall>i. (f (Suc i), f i) \<in> {(y, x). \<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* x \<and> \<Gamma>\<turnstile>x \<rightarrow> y}\<^sup>+"
proof (rule exI [where x=f],rule allI)
fix i
show "(f (Suc i), f i) \<in> {(y, x). \<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* x \<and> \<Gamma>\<turnstile>x \<rightarrow> y}\<^sup>+"
proof -
{
fix i have "\<Gamma>\<turnstile>(cs,css,s) \<rightarrow>\<^sup>* f i"
proof (induct i)
case 0 show "\<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* f 0"
by (simp add: f0)
next
case (Suc n)
have "\<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* f n" by fact
with seq show "\<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* f (Suc n)"
by (blast intro: tranclp_into_rtranclp rtranclp_trans)
qed
}
hence "\<Gamma>\<turnstile>(cs,css,s) \<rightarrow>\<^sup>* f i"
by iprover
with seq have
"(f (Suc i), f i) \<in> {(y, x). \<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* x \<and> \<Gamma>\<turnstile>x \<rightarrow>\<^sup>+ y}"
by clarsimp
moreover
have "\<forall>y. \<Gamma>\<turnstile>f i \<rightarrow>\<^sup>+ y\<longrightarrow>\<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* f i\<longrightarrow>\<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* y"
by (blast intro: tranclp_into_rtranclp rtranclp_trans)
ultimately
show ?thesis
by (subst lem)
qed
qed
qed
qed
corollary terminates_impl_no_inf_chain:
"\<Gamma>\<turnstile>c\<down>s \<Longrightarrow> \<not>(\<exists>f. f 0 = ([c],[],s) \<and> (\<forall>i::nat. \<Gamma>\<turnstile>f i \<rightarrow>\<^sup>+ f(Suc i)))"
by (rule terminatess_impl_no_inf_chain) (iprover intro: terminatess.intros)
definition
termi_call_steps :: "('s,'p,'f) body \<Rightarrow> (('s \<times> 'p) \<times> ('s \<times> 'p))set"
where
"termi_call_steps \<Gamma> =
{((t,q),(s,p)). \<Gamma>\<turnstile>the (\<Gamma> p)\<down>Normal s \<and>
(\<exists>css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal s) \<rightarrow>\<^sup>+ ([the (\<Gamma> q)],css,Normal t))}"
text \<open>Sequencing computations, or more exactly continuation stacks\<close>
primrec seq:: "(nat \<Rightarrow> 'a list) \<Rightarrow> nat \<Rightarrow> 'a list"
where
"seq css 0 = []" |
"seq css (Suc i) = css i@seq css i"
theorem wf_termi_call_steps: "wf (termi_call_steps \<Gamma>)"
proof (simp only: termi_call_steps_def wf_iff_no_infinite_down_chain,
clarify,simp)
fix S
assume inf:
"\<forall>i. (\<lambda>(t,q) (s,p). \<Gamma>\<turnstile>(the (\<Gamma> p)) \<down> Normal s \<and>
(\<exists>css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal s) \<rightarrow>\<^sup>+ ([the (\<Gamma> q)],css,Normal t)))
(S (Suc i)) (S i)"
obtain s p where "s = (\<lambda>i. fst (S i))" and "p = (\<lambda>i. snd (S i))"
by auto
with inf
have inf':
"\<forall>i. \<Gamma>\<turnstile>(the (\<Gamma> (p i))) \<down> Normal (s i) \<and>
(\<exists>css. \<Gamma>\<turnstile>([the (\<Gamma> (p i))],[],Normal (s i)) \<rightarrow>\<^sup>+
([the (\<Gamma> (p (Suc i)))],css,Normal (s (Suc i))))"
apply -
apply (rule allI)
apply (erule_tac x=i in allE)
apply auto
done
show False
proof -
from inf' \<comment> \<open>Skolemization of css with axiom of choice\<close>
have "\<exists>css. \<forall>i. \<Gamma>\<turnstile>(the (\<Gamma> (p i))) \<down> Normal (s i) \<and>
\<Gamma>\<turnstile>([the (\<Gamma> (p i))],[],Normal (s i)) \<rightarrow>\<^sup>+
([the (\<Gamma> (p (Suc i)))],css i,Normal (s (Suc i)))"
apply -
apply (rule choice)
by blast
then obtain css where
termi_css: "\<forall>i. \<Gamma>\<turnstile>(the (\<Gamma> (p i))) \<down> Normal (s i)" and
step_css: "\<forall>i. \<Gamma>\<turnstile>([the (\<Gamma> (p i))],[],Normal (s i)) \<rightarrow>\<^sup>+
([the (\<Gamma> (p (Suc i)))],css i,Normal (s (Suc i)))"
by blast
define f where "f i = ([the (\<Gamma> (p i))], seq css i,Normal (s i)::('a,'c) xstate)" for i
have "f 0 = ([the (\<Gamma> (p 0))],[],Normal (s 0))"
by (simp add: f_def)
moreover
have "\<forall>i. \<Gamma>\<turnstile> (f i) \<rightarrow>\<^sup>+ (f (i+1))"
proof
fix i
from step_css [rule_format, of i]
have "\<Gamma>\<turnstile>([the (\<Gamma> (p i))], [], Normal (s i)) \<rightarrow>\<^sup>+
([the (\<Gamma> (p (Suc i)))], css i, Normal (s (Suc i)))".
from app_css_steps [OF this,simplified]
have "\<Gamma>\<turnstile>([the (\<Gamma> (p i))], seq css i, Normal (s i)) \<rightarrow>\<^sup>+
([the (\<Gamma> (p (Suc i)))], css i@seq css i, Normal (s (Suc i)))".
thus "\<Gamma>\<turnstile> (f i) \<rightarrow>\<^sup>+ (f (i+1))"
by (simp add: f_def)
qed
moreover from termi_css [rule_format, of 0]
have "\<not> (\<exists>f. (f 0 = ([the (\<Gamma> (p 0))],[],Normal (s 0)) \<and>
(\<forall>i. \<Gamma>\<turnstile>(f i) \<rightarrow>\<^sup>+ f(Suc i))))"
by (rule terminates_impl_no_inf_chain)
ultimately show False
by auto
qed
qed
text \<open>An alternative proof using Hilbert-choice instead of axiom of choice.\<close>
theorem "wf (termi_call_steps \<Gamma>)"
proof (simp only: termi_call_steps_def wf_iff_no_infinite_down_chain,
clarify,simp)
fix S
assume inf:
"\<forall>i. (\<lambda>(t,q) (s,p). \<Gamma>\<turnstile>(the (\<Gamma> p)) \<down> Normal s \<and>
(\<exists>css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal s) \<rightarrow>\<^sup>+ ([the (\<Gamma> q)],css,Normal t)))
(S (Suc i)) (S i)"
obtain s p where "s = (\<lambda>i. fst (S i))" and "p = (\<lambda>i. snd (S i))"
by auto
with inf
have inf':
"\<forall>i. \<Gamma>\<turnstile>(the (\<Gamma> (p i))) \<down> Normal (s i) \<and>
(\<exists>css. \<Gamma>\<turnstile>([the (\<Gamma> (p i))],[],Normal (s i)) \<rightarrow>\<^sup>+
([the (\<Gamma> (p (Suc i)))],css,Normal (s (Suc i))))"
apply -
apply (rule allI)
apply (erule_tac x=i in allE)
apply auto
done
show "False"
proof -
define CSS where "CSS i = (SOME css.
\<Gamma>\<turnstile>([the (\<Gamma> (p i))],[], Normal (s i)) \<rightarrow>\<^sup>+
([the (\<Gamma> (p (i+1)))],css,Normal (s (i+1))))" for i
define f where "f i = ([the (\<Gamma> (p i))], seq CSS i,Normal (s i)::('a,'c) xstate)" for i
have "f 0 = ([the (\<Gamma> (p 0))],[],Normal (s 0))"
by (simp add: f_def)
moreover
have "\<forall>i. \<Gamma>\<turnstile> (f i) \<rightarrow>\<^sup>+ (f (i+1))"
proof
fix i
from inf' [rule_format, of i] obtain css where
css: "\<Gamma>\<turnstile>([the (\<Gamma> (p i))],[],Normal (s i)) \<rightarrow>\<^sup>+
([the (\<Gamma> (p (i+1)))],css,Normal (s (i+1)))"
by fastforce
hence "\<Gamma>\<turnstile>([the (\<Gamma> (p i))], seq CSS i, Normal (s i)) \<rightarrow>\<^sup>+
([the (\<Gamma> (p (i+1)))], CSS i @ seq CSS i, Normal (s (i+1)))"
apply -
apply (unfold CSS_def)
apply (rule someI2
[where P="\<lambda>css.
\<Gamma>\<turnstile>([the (\<Gamma> (p i))],[],Normal (s i))\<rightarrow>\<^sup>+
([the (\<Gamma> (p (i+1)))],css, Normal (s (i+1)))"])
apply (rule css)
apply (fastforce dest: app_css_steps)
done
thus "\<Gamma>\<turnstile> (f i) \<rightarrow>\<^sup>+ (f (i+1))"
by (simp add: f_def)
qed
moreover from inf' [rule_format, of 0]
have "\<Gamma>\<turnstile>the (\<Gamma> (p 0)) \<down> Normal (s 0)"
by iprover
then have "\<not> (\<exists>f. (f 0 = ([the (\<Gamma> (p 0))],[],Normal (s 0)) \<and>
(\<forall>i. \<Gamma>\<turnstile>(f i) \<rightarrow>\<^sup>+ f(Suc i))))"
by (rule terminates_impl_no_inf_chain)
ultimately show False
by auto
qed
qed
lemma not_inf_implies_wf: assumes not_inf: "\<not> inf \<Gamma> cs css s"
shows "wf {(c2,c1). \<Gamma> \<turnstile> (cs,css,s) \<rightarrow>\<^sup>* c1 \<and> \<Gamma> \<turnstile> c1 \<rightarrow> c2}"
proof (simp only: wf_iff_no_infinite_down_chain,clarify, simp)
fix f
assume "\<forall>i. \<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* f i \<and> \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
hence "\<exists>f. f 0 = (cs, css, s) \<and> (\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i))"
by (rule renumber [to_pred])
moreover from not_inf
have "\<not> (\<exists>f. f 0 = (cs, css, s) \<and> (\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)))"
by (unfold inf_def)
ultimately show False
by simp
qed
lemma wf_implies_termi_reach:
assumes wf: "wf {(c2,c1). \<Gamma> \<turnstile> (cs,css,s) \<rightarrow>\<^sup>* c1 \<and> \<Gamma> \<turnstile> c1 \<rightarrow> c2}"
shows "\<And>cs1 css1 s1. \<lbrakk>\<Gamma> \<turnstile> (cs,css,s) \<rightarrow>\<^sup>* c1; c1=(cs1,css1,s1)\<rbrakk>\<Longrightarrow> \<Gamma>\<turnstile>cs1,css1\<Down>s1"
using wf
proof (induct c1, simp)
fix cs1 css1 s1
assume reach: "\<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* (cs1, css1, s1)"
assume hyp_raw: "\<And>y cs2 css2 s2. \<lbrakk>\<Gamma> \<turnstile> (cs1,css1,s1) \<rightarrow> (cs2,css2,s2);
\<Gamma> \<turnstile> (cs,css,s) \<rightarrow>\<^sup>* (cs2,css2,s2); y=(cs2,css2,s2)\<rbrakk> \<Longrightarrow>
\<Gamma>\<turnstile>cs2,css2\<Down>s2"
have hyp: "\<And>cs2 css2 s2. \<lbrakk>\<Gamma> \<turnstile> (cs1,css1,s1) \<rightarrow> (cs2,css2,s2)\<rbrakk> \<Longrightarrow>
\<Gamma>\<turnstile>cs2,css2\<Down>s2"
apply -
apply (rule hyp_raw)
apply assumption
using reach
apply simp
apply (rule refl)
done
show "\<Gamma>\<turnstile>cs1,css1\<Down>s1"
proof (cases s1)
case (Normal s1')
show ?thesis
proof (cases cs1)
case Nil
note cs1_Nil = this
show ?thesis
proof (cases css1)
case Nil
with cs1_Nil show ?thesis
by (auto intro: terminatess.intros)
next
case (Cons nrms_abrs css1')
then obtain nrms abrs where nrms_abrs: "nrms_abrs=(nrms,abrs)"
by (cases "nrms_abrs")
have "\<Gamma> \<turnstile> ([],(nrms,abrs)#css1',Normal s1') \<rightarrow> (nrms,css1',Normal s1')"
by (rule step.intros)
from hyp [simplified cs1_Nil Cons nrms_abrs Normal, OF this]
have "\<Gamma>\<turnstile>nrms,css1'\<Down>Normal s1'".
from ExitBlockNormal [OF this] cs1_Nil Cons nrms_abrs Normal
show ?thesis
by auto
qed
next
case (Cons c1 cs1')
have "\<Gamma>\<turnstile>c1#cs1',css1\<Down>Normal s1'"
proof (cases c1)
case Skip
have "\<Gamma> \<turnstile> (Skip#cs1',css1,Normal s1') \<rightarrow> (cs1',css1,Normal s1')"
by (rule step.intros)
from hyp [simplified Cons Skip Normal, OF this]
have "\<Gamma>\<turnstile>cs1',css1\<Down>Normal s1'".
with Normal Skip show ?thesis
by (auto intro: terminatess.intros terminates.intros
elim: exec_Normal_elim_cases)
next
case (Basic f)
have "\<Gamma> \<turnstile> (Basic f#cs1',css1,Normal s1') \<rightarrow> (cs1',css1,Normal (f s1'))"
by (rule step.intros)
from hyp [simplified Cons Basic Normal, OF this]
have "\<Gamma>\<turnstile>cs1',css1\<Down>Normal (f s1')".
with Normal Basic show ?thesis
by (auto intro: terminatess.intros terminates.intros
elim: exec_Normal_elim_cases)
next
case (Spec r)
with Normal show ?thesis
apply simp
apply (rule terminatess.Cons)
apply (fastforce intro: terminates.intros)
apply (clarify)
apply (erule exec_Normal_elim_cases)
apply clarsimp
apply (rule hyp)
apply (fastforce intro: step.intros simp add: Cons Spec Normal )
apply (fastforce intro: terminatess_Stuck)
done
next
case (Seq c\<^sub>1 c\<^sub>2)
have "\<Gamma> \<turnstile> (Seq c\<^sub>1 c\<^sub>2#cs1',css1,Normal s1') \<rightarrow> (c\<^sub>1#c\<^sub>2#cs1',css1,Normal s1')"
by (rule step.intros)
from hyp [simplified Cons Seq Normal, OF this]
have "\<Gamma>\<turnstile>c\<^sub>1 # c\<^sub>2 # cs1',css1\<Down>Normal s1'".
with Normal Seq show ?thesis
by (fastforce intro: terminatess.intros terminates.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
next
case (Cond b c\<^sub>1 c\<^sub>2)
show ?thesis
proof (cases "s1' \<in> b")
case True
hence "\<Gamma>\<turnstile>(Cond b c\<^sub>1 c\<^sub>2#cs1',css1,Normal s1') \<rightarrow> (c\<^sub>1#cs1',css1,Normal s1')"
by (rule step.intros)
from hyp [simplified Cons Cond Normal, OF this]
have "\<Gamma>\<turnstile>c\<^sub>1 # cs1',css1\<Down>Normal s1'".
with Normal Cond True show ?thesis
by (fastforce intro: terminatess.intros terminates.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
next
case False
hence "\<Gamma>\<turnstile>(Cond b c\<^sub>1 c\<^sub>2#cs1',css1,Normal s1') \<rightarrow> (c\<^sub>2#cs1',css1,Normal s1')"
by (rule step.intros)
from hyp [simplified Cons Cond Normal, OF this]
have "\<Gamma>\<turnstile>c\<^sub>2 # cs1',css1\<Down>Normal s1'".
with Normal Cond False show ?thesis
by (fastforce intro: terminatess.intros terminates.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
qed
next
case (While b c')
show ?thesis
proof (cases "s1' \<in> b")
case True
then have "\<Gamma>\<turnstile>(While b c' # cs1', css1, Normal s1') \<rightarrow>
(c' # While b c' # cs1', css1, Normal s1')"
by (rule step.intros)
from hyp [simplified Cons While Normal, OF this]
have "\<Gamma>\<turnstile>c' # While b c' # cs1',css1\<Down>Normal s1'".
with Cons While True Normal
show ?thesis
by (fastforce intro: terminatess.intros terminates.intros exec.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
next
case False
then
have "\<Gamma>\<turnstile>(While b c' # cs1', css1, Normal s1') \<rightarrow> (cs1', css1, Normal s1')"
by (rule step.intros)
from hyp [simplified Cons While Normal, OF this]
have "\<Gamma>\<turnstile>cs1',css1\<Down>Normal s1'".
with Cons While False Normal
show ?thesis
by (fastforce intro: terminatess.intros terminates.intros exec.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
qed
next
case (Call p)
show ?thesis
proof (cases "\<Gamma> p")
case None
with Call Normal show ?thesis
by (fastforce intro: terminatess.intros terminates.intros terminatess_Stuck
elim: exec_Normal_elim_cases)
next
case (Some bdy)
then
have "\<Gamma> \<turnstile> (Call p#cs1',css1,Normal s1') \<rightarrow>
([bdy],(cs1',Throw#cs1')#css1,Normal s1')"
by (rule step.intros)
from hyp [simplified Cons Call Normal Some, OF this]
have "\<Gamma>\<turnstile>[bdy],(cs1', Throw # cs1') # css1\<Down>Normal s1'".
with Some Call Normal show ?thesis
apply simp
apply (rule terminatess.intros)
apply (blast elim: terminatess_elim_cases intro: terminates.intros)
apply clarify
apply (erule terminatess_elim_cases)
apply (erule exec_Normal_elim_cases)
prefer 2
apply simp
apply (erule_tac x=t in allE)
apply (case_tac t)
apply (auto intro: terminatess_Stuck terminatess_Fault exec.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
done
qed
next
case (DynCom c')
have "\<Gamma> \<turnstile> (DynCom c'#cs1',css1,Normal s1') \<rightarrow> (c' s1'#cs1',css1,Normal s1')"
by (rule step.intros)
from hyp [simplified Cons DynCom Normal, OF this]
have "\<Gamma>\<turnstile>c' s1'#cs1',css1\<Down>Normal s1'".
with Normal DynCom show ?thesis
by (fastforce intro: terminatess.intros terminates.intros exec.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
next
case (Guard f g c')
show ?thesis
proof (cases "s1' \<in> g")
case True
then have "\<Gamma> \<turnstile> (Guard f g c'#cs1',css1,Normal s1') \<rightarrow> (c'#cs1',css1,Normal s1')"
by (rule step.intros)
from hyp [simplified Cons Guard Normal, OF this]
have "\<Gamma>\<turnstile>c'#cs1',css1\<Down>Normal s1'".
with Normal Guard True show ?thesis
by (fastforce intro: terminatess.intros terminates.intros exec.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
next
case False
with Guard Normal show ?thesis
by (fastforce intro: terminatess.intros terminatess_Fault
terminates.intros
elim: exec_Normal_elim_cases)
qed
next
case Throw
have "\<Gamma> \<turnstile> (Throw#cs1',css1,Normal s1') \<rightarrow> (cs1',css1,Abrupt s1')"
by (rule step.intros)
from hyp [simplified Cons Throw Normal, OF this]
have "\<Gamma>\<turnstile>cs1',css1\<Down>Abrupt s1'".
with Normal Throw show ?thesis
by (auto intro: terminatess.intros terminates.intros
elim: exec_Normal_elim_cases)
next
case (Catch c\<^sub>1 c\<^sub>2)
have "\<Gamma> \<turnstile> (Catch c\<^sub>1 c\<^sub>2#cs1',css1,Normal s1') \<rightarrow>
([c\<^sub>1], (cs1',c\<^sub>2#cs1')# css1,Normal s1')"
by (rule step.intros)
from hyp [simplified Cons Catch Normal, OF this]
have "\<Gamma>\<turnstile>[c\<^sub>1],(cs1', c\<^sub>2 # cs1') # css1\<Down>Normal s1'".
with Normal Catch show ?thesis
by (fastforce intro: terminatess.intros terminates.intros exec.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
qed
with Cons Normal show ?thesis
by simp
qed
next
case (Abrupt s1')
show ?thesis
proof (cases cs1)
case Nil
note cs1_Nil = this
show ?thesis
proof (cases css1)
case Nil
with cs1_Nil show ?thesis by (auto intro: terminatess.intros)
next
case (Cons nrms_abrs css1')
then obtain nrms abrs where nrms_abrs: "nrms_abrs=(nrms,abrs)"
by (cases "nrms_abrs")
have "\<Gamma> \<turnstile> ([],(nrms,abrs)#css1',Abrupt s1') \<rightarrow> (abrs,css1',Normal s1')"
by (rule step.intros)
from hyp [simplified cs1_Nil Cons nrms_abrs Abrupt, OF this]
have "\<Gamma>\<turnstile>abrs,css1'\<Down>Normal s1'".
from ExitBlockAbrupt [OF this] cs1_Nil Cons nrms_abrs Abrupt
show ?thesis
by auto
qed
next
case (Cons c1 cs1')
have "\<Gamma>\<turnstile>c1#cs1',css1\<Down>Abrupt s1'"
proof -
have "\<Gamma> \<turnstile> (c1#cs1',css1,Abrupt s1') \<rightarrow> (cs1',css1,Abrupt s1')"
by (rule step.intros)
from hyp [simplified Cons Abrupt, OF this]
have "\<Gamma>\<turnstile>cs1',css1\<Down>Abrupt s1'".
with Cons Abrupt
show ?thesis
by (fastforce intro: terminatess.intros terminates.intros exec.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
qed
with Cons Abrupt show ?thesis by simp
qed
next
case (Fault f)
thus ?thesis by (auto intro: terminatess_Fault)
next
case Stuck
thus ?thesis by (auto intro: terminatess_Stuck)
qed
qed
lemma not_inf_impl_terminatess:
assumes not_inf: "\<not> inf \<Gamma> cs css s"
shows "\<Gamma>\<turnstile>cs,css\<Down>s"
proof -
from not_inf_implies_wf [OF not_inf]
have wf: "wf {(c2, c1). \<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* c1 \<and> \<Gamma>\<turnstile>c1 \<rightarrow> c2}".
show ?thesis
by (rule wf_implies_termi_reach [OF wf]) auto
qed
lemma not_inf_impl_terminates:
assumes not_inf: "\<not> inf \<Gamma> [c] [] s"
shows "\<Gamma>\<turnstile>c\<down>s"
proof -
from not_inf_impl_terminatess [OF not_inf]
have "\<Gamma>\<turnstile>[c],[]\<Down>s".
thus ?thesis
by (auto elim: terminatess_elim_cases)
qed
theorem terminatess_iff_not_inf:
"\<Gamma>\<turnstile>cs,css\<Down>s = (\<not> inf \<Gamma> cs css s)"
apply rule
apply (erule terminatess_impl_not_inf)
apply (erule not_inf_impl_terminatess)
done
corollary terminates_iff_not_inf:
"\<Gamma>\<turnstile>c\<down>s = (\<not> inf \<Gamma> [c] [] s)"
apply (rule)
apply (erule terminates_impl_not_inf)
apply (erule not_inf_impl_terminates)
done
subsection \<open>Completeness of Total Correctness Hoare Logic\<close>
lemma ConseqMGT:
assumes modif: "\<forall>Z::'a. \<Gamma>,\<Theta> \<turnstile>\<^sub>t\<^bsub>/F\<^esub> (P' Z::'a assn) c (Q' Z),(A' Z)"
assumes impl: "\<And>s. s \<in> P \<Longrightarrow> s \<in> P' s \<and> (\<forall>t. t \<in> Q' s \<longrightarrow> t \<in> Q) \<and>
(\<forall>t. t \<in> A' s \<longrightarrow> t \<in> A)"
shows "\<Gamma>,\<Theta> \<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A"
using impl
by - (rule conseq [OF modif],blast)
lemma conseq_extract_state_indep_prop:
assumes state_indep_prop:"\<forall>s \<in> P. R"
assumes to_show: "R \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A"
shows "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A"
apply (rule Conseq)
apply (clarify)
apply (rule_tac x="P" in exI)
apply (rule_tac x="Q" in exI)
apply (rule_tac x="A" in exI)
using state_indep_prop to_show
by blast
{
fix u assume "\<Gamma>\<turnstile>\<langle>c,Normal e\<rangle> \<Rightarrow> Abrupt u"
with Abrupt_r have "\<Gamma>\<turnstile>\<langle>While b c,Normal r\<rangle> \<Rightarrow> Abrupt u" by simp
moreover from Z_r obtain
"Z \<in> b" "\<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow> Normal r"
by simp
ultimately have "\<Gamma>\<turnstile>\<langle>While b c,Normal Z\<rangle> \<Rightarrow> Abrupt u"
by (blast intro: exec.intros)
}
with cNoFault show "?Prop Z e"
by iprover
qed
}
with P show "s \<in> ?P' s"
by blast
next
{
fix t
assume "termination": "t \<notin> b"
assume "(Z, t) \<in> ?unroll"
hence "\<Gamma>\<turnstile>\<langle>While b c,Normal Z\<rangle> \<Rightarrow> Normal t"
proof (induct rule: converse_rtrancl_induct [consumes 1])
from "termination"
show "\<Gamma>\<turnstile>\<langle>While b c,Normal t\<rangle> \<Rightarrow> Normal t"
by (blast intro: exec.WhileFalse)
next
fix Z r
assume first_body:
"(Z, r) \<in> {(s, t). s \<in> b \<and> \<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> \<Rightarrow> Normal t}"
assume "(r, t) \<in> ?unroll"
assume rest_loop: "\<Gamma>\<turnstile>\<langle>While b c, Normal r\<rangle> \<Rightarrow> Normal t"
show "\<Gamma>\<turnstile>\<langle>While b c,Normal Z\<rangle> \<Rightarrow> Normal t"
proof -
from first_body obtain
"Z \<in> b" "\<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow> Normal r"
by fast
moreover
from rest_loop have
"\<Gamma>\<turnstile>\<langle>While b c,Normal r\<rangle> \<Rightarrow> Normal t"
by fast
ultimately show "\<Gamma>\<turnstile>\<langle>While b c,Normal Z\<rangle> \<Rightarrow> Normal t"
by (rule exec.WhileTrue)
qed
qed
}
with P
show "\<forall>t. t\<in>(?P' s \<inter> - b)
\<longrightarrow>t\<in>{t. \<Gamma>\<turnstile>\<langle>While b c,Normal Z\<rangle> \<Rightarrow> Normal t}"
by blast
next
from P show "\<forall>t. t\<in>?A s \<longrightarrow> t\<in>?A Z"
by simp
qed
qed
next
case (Call q)
let ?P = "{s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Call q ,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p)\<down>Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>*
(Call q # cs,css,Normal s))}"
from noStuck_Call
have "\<forall>s \<in> ?P. q \<in> dom \<Gamma>"
by (fastforce simp add: final_notin_def)
then show ?case
proof (rule conseq_extract_state_indep_prop)
assume q_defined: "q \<in> dom \<Gamma>"
from Call_hyp have
"\<forall>q\<in>dom \<Gamma>. \<forall>Z.
\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub>{s. s=Z \<and> \<Gamma>\<turnstile>\<langle>the (\<Gamma> q),Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>(the (\<Gamma> q))\<down>Normal s \<and> ((s,q),(\<sigma>,p)) \<in> termi_call_steps \<Gamma>}
(Call q)
{t. \<Gamma>\<turnstile>\<langle>the (\<Gamma> q),Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>the (\<Gamma> q),Normal Z\<rangle> \<Rightarrow> Abrupt t}"
by (simp add: exec_Call_body' noFaultStuck_Call_body' [simplified]
terminates_Normal_Call_body)
from Call_hyp q_defined have Call_hyp':
"\<forall>Z. \<Gamma>,\<Theta> \<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Call q,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>Call q\<down>Normal s \<and> ((s,q),(\<sigma>,p)) \<in> termi_call_steps \<Gamma>}
(Call q)
{t. \<Gamma>\<turnstile>\<langle>Call q,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call q,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
by auto
show
"\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> ?P
(Call q)
{t. \<Gamma>\<turnstile>\<langle>Call q ,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call q ,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
proof (rule ConseqMGT [OF Call_hyp'],safe)
fix cs css
assume
"\<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>)\<rightarrow>\<^sup>* (Call q # cs,css,Normal Z)"
"\<Gamma>\<turnstile>the (\<Gamma> p) \<down> Normal \<sigma>"
hence "\<Gamma>\<turnstile>Call q \<down> Normal Z"
by (rule steps_preserves_termination)
with q_defined show "\<Gamma>\<turnstile>Call q \<down> Normal Z"
by (auto elim: terminates_Normal_elim_cases)
next
fix cs css
assume reach:
"\<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (Call q#cs,css,Normal Z)"
moreover have "\<Gamma>\<turnstile>(Call q # cs,css, Normal Z) \<rightarrow>
([the (\<Gamma> q)],(cs,Throw#cs)#css, Normal Z)"
by (rule step.Call) (insert q_defined,auto)
ultimately
have "\<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>+ ([the (\<Gamma> q)],(cs,Throw#cs)#css,Normal Z)"
by (rule rtranclp_into_tranclp1)
moreover
assume termi: "\<Gamma>\<turnstile>the (\<Gamma> p) \<down> Normal \<sigma>"
ultimately
show "((Z,q), \<sigma>,p) \<in> termi_call_steps \<Gamma>"
by (auto simp add: termi_call_steps_def)
qed
qed
next
case (DynCom c)
have hyp:
"\<And>s'. \<forall>Z. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub>
{s. s = Z \<and> \<Gamma>\<turnstile>\<langle>c s',Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p) \<down> Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (c s'#cs,css,Normal s))}
(c s')
{t. \<Gamma>\<turnstile>\<langle>c s',Normal Z\<rangle> \<Rightarrow> Normal t},{t. \<Gamma>\<turnstile>\<langle>c s',Normal Z\<rangle> \<Rightarrow> Abrupt t}"
using DynCom by simp
have hyp':
"\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. s=Z \<and> \<Gamma>\<turnstile>\<langle>DynCom c,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p) \<down> Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (DynCom c#cs,css,Normal s))}
(c Z)
{t. \<Gamma>\<turnstile>\<langle>DynCom c,Normal Z\<rangle> \<Rightarrow> Normal t},{t. \<Gamma>\<turnstile>\<langle>DynCom c,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
proof (rule ConseqMGT [OF hyp],safe)
assume "\<Gamma>\<turnstile>\<langle>DynCom c,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
then show "\<Gamma>\<turnstile>\<langle>c Z,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
by (fastforce simp add: final_notin_def intro: exec.intros)
next
fix cs css
assume "\<Gamma>\<turnstile>([the (\<Gamma> p)], [], Normal \<sigma>) \<rightarrow>\<^sup>* (DynCom c # cs, css, Normal Z)"
also have "\<Gamma>\<turnstile>(DynCom c # cs, css, Normal Z) \<rightarrow> (c Z#cs,css,Normal Z)"
by (rule step.DynCom)
finally
show "\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)], [], Normal \<sigma>) \<rightarrow>\<^sup>* (c Z # cs, css, Normal Z)"
by blast
next
fix t
assume "\<Gamma>\<turnstile>\<langle>c Z,Normal Z\<rangle> \<Rightarrow> Normal t"
thus "\<Gamma>\<turnstile>\<langle>DynCom c,Normal Z\<rangle> \<Rightarrow> Normal t"
by (auto intro: exec.intros)
next
fix t
assume "\<Gamma>\<turnstile>\<langle>c Z,Normal Z\<rangle> \<Rightarrow> Abrupt t"
thus "\<Gamma>\<turnstile>\<langle>DynCom c,Normal Z\<rangle> \<Rightarrow> Abrupt t"
by (auto intro: exec.intros)
qed
show ?case
apply (rule hoaret.DynCom)
apply safe
apply (rule hyp')
done
next
case (Guard f g c)
have hyp_c: "\<forall>Z. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub>
{s. s=Z \<and> \<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p)\<down>Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (c#cs,css,Normal s))}
c
{t. \<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
using Guard.hyps by iprover
show "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Guard f g c ,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p)\<down>Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (Guard f g c#cs,css,Normal s))}
Guard f g c
{t. \<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
proof (cases "f \<in> F")
case True
have "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (g \<inter> {s. s=Z \<and>
\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p)\<down>Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (Guard f g c#cs,css,Normal s))})
c
{t. \<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
proof (rule ConseqMGT [OF hyp_c], safe)
assume "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))" "Z\<in>g"
thus "\<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
by (auto simp add: final_notin_def intro: exec.intros)
next
fix cs css
assume "\<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (Guard f g c#cs,css,Normal Z)"
also
assume "Z \<in> g"
hence "\<Gamma>\<turnstile>(Guard f g c#cs,css,Normal Z) \<rightarrow> (c#cs,css,Normal Z)"
by (rule step.Guard)
finally show "\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (c#cs,css,Normal Z)"
by iprover
next
fix t
assume "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
"\<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow> Normal t" "Z \<in> g"
thus "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Normal t"
by (auto simp add: final_notin_def intro: exec.intros )
next
fix t
assume "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
"\<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow> Abrupt t" "Z \<in> g"
thus "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Abrupt t"
by (auto simp add: final_notin_def intro: exec.intros )
qed
from True this show ?thesis
by (rule conseqPre [OF Guarantee]) auto
next
case False
have "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (g \<inter> {s. s=Z \<and>
\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p)\<down>Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (Guard f g c#cs,css,Normal s))})
c
{t. \<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
proof (rule ConseqMGT [OF hyp_c], safe)
assume "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
thus "\<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
using False
by (cases "Z\<in> g") (auto simp add: final_notin_def intro: exec.intros)
next
fix cs css
assume "\<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (Guard f g c#cs,css,Normal Z)"
also assume "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
hence "Z \<in> g"
using False by (auto simp add: final_notin_def intro: exec.GuardFault)
hence "\<Gamma>\<turnstile>(Guard f g c#cs,css,Normal Z) \<rightarrow> (c#cs,css,Normal Z)"
by (rule step.Guard)
finally show "\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (c#cs,css,Normal Z)"
by iprover
next
fix t
assume "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
"\<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow> Normal t"
thus "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Normal t"
using False
by (cases "Z\<in> g") (auto simp add: final_notin_def intro: exec.intros )
next
fix t
assume "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
"\<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow> Abrupt t"
thus "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Abrupt t"
using False
by (cases "Z\<in> g") (auto simp add: final_notin_def intro: exec.intros )
qed
then show ?thesis
apply (rule conseqPre [OF hoaret.Guard])
apply clarify
apply (frule Guard_noFaultStuckD [OF _ False])
apply auto
done
qed
next
case Throw
show "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Throw,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p)\<down>Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[], Normal \<sigma>) \<rightarrow>\<^sup>* (Throw#cs,css,Normal s))}
Throw
{t. \<Gamma>\<turnstile>\<langle>Throw,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Throw,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
by (rule conseqPre [OF hoaret.Throw])
(blast intro: exec.intros terminates.intros)
next
case (Catch c\<^sub>1 c\<^sub>2)
have hyp_c1:
"\<forall>Z. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. s= Z \<and> \<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p) \<down> Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (c\<^sub>1# cs, css,Normal s))}
c\<^sub>1
{t. \<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal Z\<rangle> \<Rightarrow> Normal t},{t. \<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
using Catch.hyps by iprover
have hyp_c2:
"\<forall>Z. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. s= Z \<and> \<Gamma>\<turnstile>\<langle>c\<^sub>2,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p) \<down> Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (c\<^sub>2# cs, css,Normal s))}
c\<^sub>2
{t. \<Gamma>\<turnstile>\<langle>c\<^sub>2,Normal Z\<rangle> \<Rightarrow> Normal t},{t. \<Gamma>\<turnstile>\<langle>c\<^sub>2,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
using Catch.hyps by iprover
have
"\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. s = Z \<and> \<Gamma>\<turnstile>\<langle>Catch c\<^sub>1 c\<^sub>2,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p) \<down> Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>)\<rightarrow>\<^sup>*(Catch c\<^sub>1 c\<^sub>2 #cs,css,Normal s))}
c\<^sub>1
{t. \<Gamma>\<turnstile>\<langle>Catch c\<^sub>1 c\<^sub>2,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal Z\<rangle> \<Rightarrow> Abrupt t \<and>
\<Gamma>\<turnstile>\<langle>c\<^sub>2,Normal t\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault`(-F)) \<and> \<Gamma>\<turnstile>the (\<Gamma> p) \<down> Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (c\<^sub>2# cs, css,Normal t))}"
proof (rule ConseqMGT [OF hyp_c1],clarify,safe)
assume "\<Gamma>\<turnstile>\<langle>Catch c\<^sub>1 c\<^sub>2,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
thus "\<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
by (fastforce simp add: final_notin_def intro: exec.intros)
next
fix cs css
assume "\<Gamma>\<turnstile>([the (\<Gamma> p)], [], Normal \<sigma>) \<rightarrow>\<^sup>* (Catch c\<^sub>1 c\<^sub>2 # cs, css, Normal Z)"
also have
"\<Gamma>\<turnstile>(Catch c\<^sub>1 c\<^sub>2 # cs, css, Normal Z) \<rightarrow> ([c\<^sub>1],(cs,c\<^sub>2#cs)#css,Normal Z)"
by (rule step.Catch)
finally
show "\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)], [], Normal \<sigma>) \<rightarrow>\<^sup>* (c\<^sub>1 # cs, css, Normal Z)"
by iprover
next
fix t
assume "\<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal Z\<rangle> \<Rightarrow> Normal t"
thus "\<Gamma>\<turnstile>\<langle>Catch c\<^sub>1 c\<^sub>2,Normal Z\<rangle> \<Rightarrow> Normal t"
by (auto intro: exec.intros)
next
fix t
assume "\<Gamma>\<turnstile>\<langle>Catch c\<^sub>1 c\<^sub>2,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
"\<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal Z\<rangle> \<Rightarrow> Abrupt t"
thus "\<Gamma>\<turnstile>\<langle>c\<^sub>2,Normal t\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
by (auto simp add: final_notin_def intro: exec.intros)
next
fix cs css t
assume "\<Gamma>\<turnstile>([the (\<Gamma> p)], [], Normal \<sigma>) \<rightarrow>\<^sup>* (Catch c\<^sub>1 c\<^sub>2 # cs, css, Normal Z)"
also have
"\<Gamma>\<turnstile>(Catch c\<^sub>1 c\<^sub>2 # cs, css, Normal Z) \<rightarrow> ([c\<^sub>1],(cs,c\<^sub>2#cs)#css,Normal Z)"
by (rule step.Catch)
also
assume "\<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal Z\<rangle> \<Rightarrow> Abrupt t"
hence "\<Gamma>\<turnstile>([c\<^sub>1],(cs,c\<^sub>2#cs)#css,Normal Z) \<rightarrow>\<^sup>* ([],(cs,c\<^sub>2#cs)#css,Abrupt t)"
by (rule exec_impl_steps)
also
have "\<Gamma>\<turnstile>([],(cs,c\<^sub>2#cs)#css,Abrupt t) \<rightarrow> (c\<^sub>2#cs,css,Normal t)"
by (rule step.intros)
finally
show "\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)], [], Normal \<sigma>) \<rightarrow>\<^sup>* (c\<^sub>2 # cs, css, Normal t)"
by iprover
qed
moreover
have "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {t. \<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal Z\<rangle> \<Rightarrow> Abrupt t \<and>
\<Gamma>\<turnstile>\<langle>c\<^sub>2,Normal t\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p) \<down> Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (c\<^sub>2# cs, css,Normal t))}
c\<^sub>2
{t. \<Gamma>\<turnstile>\<langle>Catch c\<^sub>1 c\<^sub>2,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Catch c\<^sub>1 c\<^sub>2,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
by (rule ConseqMGT [OF hyp_c2]) (fastforce intro: exec.intros)
ultimately show ?case
by (rule hoaret.Catch)
qed
text \<open>To prove a procedure implementation correct it suffices to assume
only the procedure specifications of procedures that actually
occur during evaluation of the body.
\<close>
lemma Call_lemma:
assumes
Call: "\<forall>q \<in> dom \<Gamma>. \<forall>Z. \<Gamma>,\<Theta> \<turnstile>\<^sub>t\<^bsub>/F\<^esub>
{s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Call q,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>Call q\<down>Normal s \<and> ((s,q),(\<sigma>,p)) \<in> termi_call_steps \<Gamma>}
(Call q)
{t. \<Gamma>\<turnstile>\<langle>Call q,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call q,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
shows "\<And>Z. \<Gamma>,\<Theta> \<turnstile>\<^sub>t\<^bsub>/F\<^esub>
({\<sigma>} \<inter> {s. s=Z \<and> \<Gamma>\<turnstile>\<langle>the (\<Gamma> p),Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p)\<down>Normal s})
the (\<Gamma> p)
{t. \<Gamma>\<turnstile>\<langle>the (\<Gamma> p),Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>the (\<Gamma> p),Normal Z\<rangle> \<Rightarrow> Abrupt t}"
apply (rule conseqPre)
apply (rule Call_lemma')
apply (rule Call)
apply blast
done
lemma Call_lemma_switch_Call_body:
assumes
call: "\<forall>q \<in> dom \<Gamma>. \<forall>Z. \<Gamma>,\<Theta> \<turnstile>\<^sub>t\<^bsub>/F\<^esub>
{s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Call q,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>Call q\<down>Normal s \<and> ((s,q),(\<sigma>,p)) \<in> termi_call_steps \<Gamma>}
(Call q)
{t. \<Gamma>\<turnstile>\<langle>Call q,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call q,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
assumes p_defined: "p \<in> dom \<Gamma>"
shows "\<And>Z. \<Gamma>,\<Theta> \<turnstile>\<^sub>t\<^bsub>/F\<^esub>
({\<sigma>} \<inter> {s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>Call p\<down>Normal s})
the (\<Gamma> p)
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
apply (simp only: exec_Call_body' [OF p_defined] noFaultStuck_Call_body' [OF p_defined] terminates_Normal_Call_body [OF p_defined])
apply (rule conseqPre)
apply (rule Call_lemma')
apply (rule call)
apply blast
done
lemma MGT_Call:
"\<forall>p \<in> dom \<Gamma>. \<forall>Z.
\<Gamma>,\<Theta> \<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>(Call p)\<down>Normal s}
(Call p)
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
apply (intro ballI allI)
apply (rule CallRec' [where Procs="dom \<Gamma>" and
P="\<lambda>p Z. {s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>Call p\<down>Normal s}" and
Q="\<lambda>p Z. {t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Normal t}" and
A="\<lambda>p Z. {t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Abrupt t}" and
r="termi_call_steps \<Gamma>"
])
apply simp
apply simp
apply (rule wf_termi_call_steps)
apply (intro ballI allI)
apply simp
apply (rule Call_lemma_switch_Call_body [rule_format, simplified])
apply (rule hoaret.Asm)
apply fastforce
apply assumption
done
lemma CollInt_iff: "{s. P s} \<inter> {s. Q s} = {s. P s \<and> Q s}"
by auto
lemma image_Un_conv: "f ` (\<Union>p\<in>dom \<Gamma>. \<Union>Z. {x p Z}) = (\<Union>p\<in>dom \<Gamma>. \<Union>Z. {f (x p Z)})"
by (auto iff: not_None_eq)
text \<open>Another proof of \<open>MGT_Call\<close>, maybe a little more readable\<close>
lemma
"\<forall>p \<in> dom \<Gamma>. \<forall>Z.
\<Gamma>,{} \<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>(Call p)\<down>Normal s}
(Call p)
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
proof -
{
fix p Z \<sigma>
assume defined: "p \<in> dom \<Gamma>"
define Specs where "Specs = (\<Union>p\<in>dom \<Gamma>. \<Union>Z.
{({s. s=Z \<and>
\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>Call p\<down>Normal s},
p,
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Abrupt t})})"
define Specs_wf where "Specs_wf p \<sigma> = (\<lambda>(P,q,Q,A).
(P \<inter> {s. ((s,q),\<sigma>,p) \<in> termi_call_steps \<Gamma>}, q, Q, A)) ` Specs" for p \<sigma>
have "\<Gamma>,Specs_wf p \<sigma>
\<turnstile>\<^sub>t\<^bsub>/F\<^esub>({\<sigma>} \<inter>
{s. s = Z \<and> \<Gamma>\<turnstile>\<langle>the (\<Gamma> p),Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p)\<down>Normal s})
(the (\<Gamma> p))
{t. \<Gamma>\<turnstile>\<langle>the (\<Gamma> p),Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>the (\<Gamma> p),Normal Z\<rangle> \<Rightarrow> Abrupt t}"
apply (rule Call_lemma [rule_format])
apply (rule hoaret.Asm)
apply (clarsimp simp add: Specs_wf_def Specs_def image_Un_conv)
apply (rule_tac x=q in bexI)
apply (rule_tac x=Z in exI)
apply (clarsimp simp add: CollInt_iff)
apply auto
done
hence "\<Gamma>,Specs_wf p \<sigma>
\<turnstile>\<^sub>t\<^bsub>/F\<^esub>({\<sigma>} \<inter>
{s. s = Z \<and> \<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>Call p\<down>Normal s})
(the (\<Gamma> p))
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
by (simp only: exec_Call_body' [OF defined]
noFaultStuck_Call_body' [OF defined]
terminates_Normal_Call_body [OF defined])
} note bdy=this
show ?thesis
apply (intro ballI allI)
apply (rule hoaret.CallRec [where Specs="(\<Union>p\<in>dom \<Gamma>. \<Union>Z.
{({s. s=Z \<and>
\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>Call p\<down>Normal s},
p,
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Abrupt t})})",
OF _ wf_termi_call_steps [of \<Gamma>] refl])
apply fastforce
apply clarify
apply (rule conjI)
apply fastforce
apply (rule allI)
apply (simp (no_asm_use) only : Un_empty_left)
apply (rule bdy)
apply auto
done
qed
end
|
#ifndef __NED_CLASS__
#define __NED_CLASS__
#include "math.h"
#include <Eigen/Dense>
namespace geodesy_ned {
static const double a = 6378137;
static const double b = 6356752.3142;
static const double esq = 6.69437999014 * 0.001;
static const double e1sq = 6.73949674228 * 0.001;
static const double f = 1 / 298.257223563;
class Ned {
public:
Ned( const double lat,
const double lon,
const double height )
{
// Save NED origin
_init_lat = deg2Rad( lat );
_init_lon = deg2Rad( lon );
_init_h = height;
// Compute ECEF of NED origin
geodetic2Ecef( lat, lon, height,
_init_ecef_x,
_init_ecef_y,
_init_ecef_z );
// Compute ECEF to NED and NED to ECEF matrices
double phiP = atan2( _init_ecef_z, sqrt( pow( _init_ecef_x, 2 ) +
pow( _init_ecef_y, 2 ) ) );
_ecef_to_ned_matrix = __nRe__( phiP, _init_lon );
_ned_to_ecef_matrix = __nRe__( _init_lat, _init_lon ).transpose();
}
void
geodetic2Ecef( const double lat,
const double lon,
const double height,
double& x,
double& y,
double& z )
{
// Convert geodetic coordinates to ECEF.
// http://code.google.com/p/pysatel/source/browse/trunk/coord.py?r=22
double lat_rad = deg2Rad( lat );
double lon_rad = deg2Rad( lon );
double xi = sqrt(1 - esq * sin( lat_rad ) * sin( lat_rad ) );
x = ( a / xi + height ) * cos( lat_rad ) * cos( lon_rad );
y = ( a / xi + height ) * cos( lat_rad ) * sin( lon_rad );
z = ( a / xi * ( 1 - esq ) + height ) * sin( lat_rad );
}
void
ecef2Geodetic( const double x,
const double y,
const double z,
double& lat,
double& lon,
double& height )
{
// Convert ECEF coordinates to geodetic.
// J. Zhu, "Conversion of Earth-centered Earth-fixed coordinates
// to geodetic coordinates," IEEE Transactions on Aerospace and
// Electronic Systems, vol. 30, pp. 957-961, 1994.
double r = sqrt( x * x + y * y );
double Esq = a * a - b * b;
double F = 54 * b * b * z * z;
double G = r * r + (1 - esq) * z * z - esq * Esq;
double C = (esq * esq * F * r * r) / pow( G, 3 );
double S = __cbrt__( 1 + C + sqrt( C * C + 2 * C ) );
double P = F / (3 * pow( (S + 1 / S + 1), 2 ) * G * G);
double Q = sqrt( 1 + 2 * esq * esq * P );
double r_0 = -(P * esq * r) / (1 + Q) + sqrt( 0.5 * a * a * (1 + 1.0 / Q) - P * (1 - esq) * z * z / (Q * (1 + Q)) - 0.5 * P * r * r);
double U = sqrt( pow( (r - esq * r_0), 2 ) + z * z );
double V = sqrt( pow( (r - esq * r_0), 2 ) + (1 - esq) * z * z );
double Z_0 = b * b * z / (a * V);
height = U * (1 - b * b / (a * V));
lat = rad2Deg( atan( (z + e1sq * Z_0) / r ) );
lon = rad2Deg( atan2( y, x ) );
}
void
ecef2Ned( const double x,
const double y,
const double z,
double& north,
double& east,
double& depth )
{
// Converts ECEF coordinate pos into local-tangent-plane ENU
// coordinates relative to another ECEF coordinate ref. Returns a tuple
// (East, North, Up).
Eigen::Vector3d vect, ret;
vect(0) = x - _init_ecef_x;
vect(1) = y - _init_ecef_y;
vect(2) = z - _init_ecef_z;
ret = _ecef_to_ned_matrix * vect;
north = ret(0);
east = ret(1);
depth = -ret(2);
}
void
ned2Ecef( const double north,
const double east,
const double depth,
double& x,
double& y,
double& z )
{
// NED (north/east/down) to ECEF coordinate system conversion.
Eigen::Vector3d ned, ret;
ned(0) = north;
ned(1) = east;
ned(2) = -depth;
ret = _ned_to_ecef_matrix * ned;
x = ret(0) + _init_ecef_x;
y = ret(1) + _init_ecef_y;
z = ret(2) + _init_ecef_z;
}
void
geodetic2Ned( const double lat,
const double lon,
const double height,
double& north,
double& east,
double& depth )
{
// Geodetic position to a local NED system """
double x, y, z;
geodetic2Ecef( lat, lon, height,
x, y, z );
ecef2Ned( x, y, z,
north, east, depth );
}
void
ned2Geodetic( const double north,
const double east,
const double depth,
double& lat,
double& lon,
double& height )
{
// Local NED position to geodetic
double x, y, z;
ned2Ecef( north, east, depth,
x, y, z );
ecef2Geodetic( x, y, z,
lat, lon, height );
}
private:
double _init_lat;
double _init_lon;
double _init_h;
double _init_ecef_x;
double _init_ecef_y;
double _init_ecef_z;
Eigen::Matrix3d _ecef_to_ned_matrix;
Eigen::Matrix3d _ned_to_ecef_matrix;
double
__cbrt__( const double x )
{
if( x >= 0.0 ) {
return pow( x, 1.0/3.0 );
}
else {
return -pow( fabs(x), 1.0/3.0 );
}
}
Eigen::Matrix3d
__nRe__( const double lat_rad,
const double lon_rad )
{
double sLat = sin( lat_rad );
double sLon = sin( lon_rad );
double cLat = cos( lat_rad );
double cLon = cos( lon_rad );
Eigen::Matrix3d ret;
ret(0, 0) = -sLat*cLon; ret(0, 1) = -sLat*sLon; ret(0, 2) = cLat;
ret(1, 0) = -sLon; ret(1, 1) = cLon; ret(1, 2) = 0.0;
ret(2, 0) = cLat*cLon; ret(2, 1) = cLat*sLon; ret(2, 2) = sLat;
return ret;
}
double
rad2Deg( const double radians )
{
return ( radians / M_PI ) * 180.0;
}
double
deg2Rad( const double degrees )
{
return ( degrees / 180.0 ) * M_PI;
}
};
}; // namespace geodesy_ned
#endif // __NED_CLASS__
|
SUBROUTINE CALEXP (ISTL_)
C
C ** SUBROUTINE CALEXP CALCULATES EXPLICIT MOMENTUM EQUATION TERMS
C ** THIS SUBROUTINE IS CURRENT PRODUCTION VERSION
C
C ** THIS SUBROUTINE IS PART OF EFDC-FULL VERSION 1.0a
C
C ** LAST MODIFIED BY JOHN HAMRICK ON 1 NOVEMBER 2001
C
C----------------------------------------------------------------------C
C
C CHANGE RECORD
C DATE MODIFIED BY DATE APPROVED BY
C
C----------------------------------------------------------------------C
C
C**********************************************************************C
C
C ** THIS SUBROUTINE IS CURRENT PRODUCTION VERSION
C CHANGE RECORD
C
USE GLOBAL
IMPLICIT NONE
INTEGER::LU,NS,ID,JD,KD,LD,K,L,LL,LW,LNW,LSE,LE
INTEGER::ND,LF,NWR,IU,JU,KU,ISTL_,LN,LS
REAL::QMF,QUMF,WU,VTMPATU,UTMPATV,UMAGTMP,VMAGTMP
REAL::DZICK,DZICKC,WVFACT,RCDZF,WV,CACSUM,CFEFF,TMPVAL,DZPU,DZPV
REAL::VHC,VHB,DELTD2,UHC,UHB
C
REAL,SAVE,ALLOCATABLE,DIMENSION(:,:)::FUHJ
REAL,SAVE,ALLOCATABLE,DIMENSION(:,:)::FVHJ
REAL,SAVE,ALLOCATABLE,DIMENSION(:,:)::DZPC
IF(.NOT.ALLOCATED(DZPC))THEN
ALLOCATE(FUHJ(LCM,KCM))
ALLOCATE(FVHJ(LCM,KCM))
ALLOCATE(DZPC(LCM,KCM))
FUHJ=0.
FVHJ=0.
DZPC=0.
ENDIF
C
C**********************************************************************C
C
DELT=DT2
DELTD2=DT
IF(ISTL_.EQ.2)THEN
DELT=DT
DELTD2=0.5*DT
ENDIF
C
DELTI=1./DELT
C
IF(N.EQ.1.AND.DEBUG)THEN
OPEN(1,FILE='MFLUX.DIA')
CLOSE(1,STATUS='DELETE')
ENDIF
C
IF(N.LE.4.AND.DEBUG)THEN
OPEN(1,FILE='MFLUX.DIA',POSITION='APPEND')
ENDIF
C
C**********************************************************************C
C
C ** INITIALIZE EXTERNAL CORIOLIS-CURVATURE AND ADVECTIVE FLUX TERMS
C
C----------------------------------------------------------------------C
C
! *** DSLLC BEGIN BLOCK
DO L=1,LC
FCAXE(L)=0.
FCAYE(L)=0.
C PMC FCAX1E(L)=0.
C PMC FCAY1E(L)=0.
FXE(L)=0.
FYE(L)=0.
ENDDO
C
IF(NQWR.GT.0)THEN
DO K=1,KC
DO L=1,LC
FUHJ(L,K)=0.
FVHJ(L,K)=0.
ENDDO
ENDDO
ENDIF
! *** DSLLC END BLOCK
C
C**********************************************************************C
C
C ** SELECT ADVECTIVE FLUX FORM
C
C----------------------------------------------------------------------C
C
IF(ISTL_.EQ.2) GOTO 200
IF(ISCDMA.EQ.0) GOTO 300
IF(ISCDMA.EQ.1) GOTO 400
IF(ISCDMA.EQ.2) GOTO 350
C
C**********************************************************************C
C
C ** TWO TIME LEVEL STEP
C ** CALCULATE ADVECTIVE FLUXES BY UPWIND DIFFERENCE WITH ADVECTION
C ** AVERAGED BETWEEN (N) AND (N+1) AND ADVECTED FIELD AT N
C
200 CONTINUE
C
C----------------------------------------------------------------------C
C
DO K=1,KC
DO L=2,LA
UHDY2(L,K)=0.5*(UHDY1(L,K)+UHDY(L,K))
VHDX2(L,K)=0.5*(VHDX1(L,K)+VHDX(L,K))
W2(L,K)=W1(L,K)+W(L,K)
ENDDO
ENDDO
C
C----------------------------------------------------------------------C
C
DO K=1,KC
DO L=2,LA
LN=LNC(L)
LS=LSC(L)
LE=LEAST(L)
LW=LWEST(L)
UHC=0.5*(UHDY2(L,K)+UHDY2(LS,K))
UHB=0.5*(UHDY2(L,K)+UHDY2(LE,K))
VHC=0.5*(VHDX2(L,K)+VHDX2(LW,K))
VHB=0.5*(VHDX2(L,K)+VHDX2(LN,K))
C
FUHU(L,K)=MAX(UHB,0.)*U1(L,K)
& +MIN(UHB,0.)*U1(LE,K)
FVHU(L,K)=MAX(VHC,0.)*U1(LS,K)
& +MIN(VHC,0.)*U1(L,K)
FUHV(L,K)=MAX(UHC,0.)*V1(LW,K)
& +MIN(UHC,0.)*V1(L,K)
FVHV(L,K)=MAX(VHB,0.)*V1(L,K)
& +MIN(VHB,0.)*V1(LN,K)
ENDDO
ENDDO
C
C ADD RETURN FLOW MOMENTUM FLUX
C
DO NWR=1,NQWR
IF(NQWRMFU(NWR).GT.0)THEN
IU=IQWRU(NWR)
JU=JQWRU(NWR)
KU=KQWRU(NWR)
LU=LIJ(IU,JU)
NS=NQWRSERQ(NWR)
QMF=QWR(NWR)+QWRSERT(NS)
QUMF=QMF*QMF/(H1P(LU)*DZC(KU)*DZC(KU)*BQWRMFU(NWR))
IF(NQWRMFU(NWR).EQ.1) FUHJ(LU ,KU)=-QUMF
IF(NQWRMFU(NWR).EQ.2) FVHJ(LU ,KU)=-QUMF
IF(NQWRMFU(NWR).EQ.3) FUHJ(LU+1 ,KU)=-QUMF
IF(NQWRMFU(NWR).EQ.4) FVHJ(LNC(LU),KU)=-QUMF
IF(NQWRMFU(NWR).EQ.-1) FUHJ(LU ,KU)=QUMF
IF(NQWRMFU(NWR).EQ.-2) FVHJ(LU ,KU)=QUMF
IF(NQWRMFU(NWR).EQ.-3) FUHJ(LU+1 ,KU)=QUMF
IF(NQWRMFU(NWR).EQ.-4) FVHJ(LNC(LU),KU)=QUMF
ENDIF
IF(NQWRMFD(NWR).GT.0)THEN
ID=IQWRD(NWR)
JD=JQWRD(NWR)
KD=KQWRD(NWR)
LD=LIJ(ID,JD)
NS=NQWRSERQ(NWR)
QMF=QWR(NWR)+QWRSERT(NS)
QUMF=QMF*QMF/(H1P(LD)*DZC(KD)*DZC(KD)*BQWRMFD(NWR))
IF(NQWRMFD(NWR).EQ.1) FUHJ(LD ,KD)=QUMF
IF(NQWRMFD(NWR).EQ.2) FVHJ(LD ,KD)=QUMF
IF(NQWRMFD(NWR).EQ.3) FUHJ(LD+1 ,KD)=QUMF
IF(NQWRMFD(NWR).EQ.4) FVHJ(LNC(LD),KD)=QUMF
IF(NQWRMFD(NWR).EQ.-1) FUHJ(LD ,KD)=-QUMF
IF(NQWRMFD(NWR).EQ.-2) FVHJ(LD ,KD)=-QUMF
IF(NQWRMFD(NWR).EQ.-3) FUHJ(LD+1 ,KD)=-QUMF
IF(NQWRMFD(NWR).EQ.-4) FVHJ(LNC(LD),KD)=-QUMF
C IF(N.LE.4.AND.DEBUG)THEN
C WRITE(1,1112)N,NWR,NS,ID,JD,KD,NQWRMFD(NWR),H1P(LD),QMF,
C & QUMF,FUHJ(LD,KD),FVHJ(LD,KD)
C ENDIF
ENDIF
ENDDO
C
C----------------------------------------------------------------------C
C
DO K=1,KS
DO L=2,LA
LS=LSC(L)
C WU=0.5/(1.+SUB(L))*DXYU(L)*(W2(L,K)+SUB(L)*W2(LWEST(L),K)) ! PMC
C WV=0.5/(1.+SVB(L))*DXYV(L)*(W2(L,K)+SVB(L)*W2(LS,K)) ! PMC
WU=0.25*DXYU(L)*(W2(L,K)+W2(LWEST(L),K))
WV=0.25*DXYV(L)*(W2(L,K)+W2(LS,K))
FWU(L,K)=MAX(WU,0.)*U1(L,K)
& +MIN(WU,0.)*U1(L,K+1)
FWV(L,K)=MAX(WV,0.)*V1(L,K)
& +MIN(WV,0.)*V1(L,K+1)
ENDDO
ENDDO
C
C----------------------------------------------------------------------C
C
GOTO 500
C
C**********************************************************************C
C
C ** THREE TIME LEVEL (LEAP-FROG) STEP
C ** WITH TRANSPORT AT (N) AND TRANSPORTED FIELD AT (N-1)
C
300 CONTINUE
C
C----------------------------------------------------------------------C
C
DO K=1,KC
DO L=2,LA
LN=LNC(L)
LS=LSC(L)
UHC=0.5*(UHDY(L,K)+UHDY(LS,K))
UHB=0.5*(UHDY(L,K)+UHDY(LEAST(L),K))
VHC=0.5*(VHDX(L,K)+VHDX(LWEST(L),K))
VHB=0.5*(VHDX(L,K)+VHDX(LN,K))
FUHU(L,K)=MAX(UHB,0.)*U1(L,K)
& +MIN(UHB,0.)*U1(LEAST(L),K)
FVHU(L,K)=MAX(VHC,0.)*U1(LS,K)
& +MIN(VHC,0.)*U1(L,K)
FUHV(L,K)=MAX(UHC,0.)*V1(LWEST(L),K)
& +MIN(UHC,0.)*V1(L,K)
FVHV(L,K)=MAX(VHB,0.)*V1(L,K)
& +MIN(VHB,0.)*V1(LN,K)
ENDDO
ENDDO
C
C ADD RETURN FLOW MOMENTUM FLUX
C
DO NWR=1,NQWR
IF(NQWRMFU(NWR).GT.0)THEN
IU=IQWRU(NWR)
JU=JQWRU(NWR)
KU=KQWRU(NWR)
LU=LIJ(IU,JU)
NS=NQWRSERQ(NWR)
QMF=QWR(NWR)+QWRSERT(NS)
QUMF=QMF*QMF/(H1P(LU)*DZC(KU)*DZC(KU)*BQWRMFU(NWR))
IF(NQWRMFU(NWR).EQ.1) FUHJ(LU ,KU)=-QUMF
IF(NQWRMFU(NWR).EQ.2) FVHJ(LU ,KU)=-QUMF
IF(NQWRMFU(NWR).EQ.3) FUHJ(LU+1 ,KU)=-QUMF
IF(NQWRMFU(NWR).EQ.4) FVHJ(LNC(LU),KU)=-QUMF
IF(NQWRMFU(NWR).EQ.-1) FUHJ(LU ,KU)=QUMF
IF(NQWRMFU(NWR).EQ.-2) FVHJ(LU ,KU)=QUMF
IF(NQWRMFU(NWR).EQ.-3) FUHJ(LU+1 ,KU)=QUMF
IF(NQWRMFU(NWR).EQ.-4) FVHJ(LNC(LU),KU)=QUMF
ENDIF
IF(NQWRMFD(NWR).GT.0)THEN
ID=IQWRD(NWR)
JD=JQWRD(NWR)
KD=KQWRD(NWR)
LD=LIJ(ID,JD)
NS=NQWRSERQ(NWR)
QMF=QWR(NWR)+QWRSERT(NS)
QUMF=QMF*QMF/(H1P(LD)*DZC(KD)*DZC(KD)*BQWRMFD(NWR))
IF(NQWRMFD(NWR).EQ.1) FUHJ(LD ,KD)=QUMF
IF(NQWRMFD(NWR).EQ.2) FVHJ(LD ,KD)=QUMF
IF(NQWRMFD(NWR).EQ.3) FUHJ(LD+1 ,KD)=QUMF
IF(NQWRMFD(NWR).EQ.4) FVHJ(LNC(LD),KD)=QUMF
IF(NQWRMFD(NWR).EQ.-1) FUHJ(LD ,KD)=-QUMF
IF(NQWRMFD(NWR).EQ.-2) FVHJ(LD ,KD)=-QUMF
IF(NQWRMFD(NWR).EQ.-3) FUHJ(LD+1 ,KD)=-QUMF
IF(NQWRMFD(NWR).EQ.-4) FVHJ(LNC(LD),KD)=-QUMF
ENDIF
ENDDO
C
C----------------------------------------------------------------------C
C
DO K=1,KS
DO L=2,LA
LS=LSC(L)
WU=0.5*DXYU(L)*(W(L,K)+W(LWEST(L),K))
WV=0.5*DXYV(L)*(W(L,K)+W(LS,K))
FWU(L,K)=MAX(WU,0.)*U1(L,K)
& +MIN(WU,0.)*U1(L,K+1)
FWV(L,K)=MAX(WV,0.)*V1(L,K)
& +MIN(WV,0.)*V1(L,K+1)
ENDDO
ENDDO
C
C----------------------------------------------------------------------C
C
GOTO 500
C
C**********************************************************************C
C
C ** THREE TIME LEVEL (LEAP-FROG) STEP
C ** FIRST HALF STEP CALCULATE ADVECTIVE FLUXES BY UPWIND DIFFERENCE
C ** WITH TRANSPORT AT (N-1/2) AND TRANSPORTED FIELD AT (N-1)
C ** SECOND HALF STEP CALCULATE ADVECTIVE FLUXES BY UPWIND DIFFERENCE
C ** WITH TRANSPORT AT (N+1/2) AND TRANSPORTED FIELD AT (N)
C
350 CONTINUE
C
C----------------------------------------------------------------------C
C
DO K=1,KC
DO L=2,LA
U2(L,K)=U1(L,K)+U(L,K)
V2(L,K)=V1(L,K)+V(L,K)
ENDDO
ENDDO
C
C----------------------------------------------------------------------C
C
DO K=1,KC
DO L=2,LA
LN=LNC(L)
LS=LSC(L)
UHC=0.25*(UHDY(L,K)+UHDY(LS,K))
UHB=0.25*(UHDY(L,K)+UHDY(LEAST(L),K))
VHC=0.25*(VHDX(L,K)+VHDX(LWEST(L),K))
VHB=0.25*(VHDX(L,K)+VHDX(LN,K))
FUHU(L,K)=MAX(UHB,0.)*U2(L,K)
& +MIN(UHB,0.)*U2(LEAST(L),K)
FVHU(L,K)=MAX(VHC,0.)*U2(LS,K)
& +MIN(VHC,0.)*U2(L,K)
FUHV(L,K)=MAX(UHC,0.)*V2(LWEST(L),K)
& +MIN(UHC,0.)*V2(L,K)
FVHV(L,K)=MAX(VHB,0.)*V2(L,K)
& +MIN(VHB,0.)*V2(LN,K)
ENDDO
ENDDO
C
C----------------------------------------------------------------------C
C
DO K=1,KS
DO L=2,LA
LS=LSC(L)
WU=0.25*DXYU(L)*(W(L,K)+W(LWEST(L),K))
WV=0.25*DXYV(L)*(W(L,K)+W(LS,K))
FWU(L,K)=MAX(WU,0.)*U2(L,K)
& +MIN(WU,0.)*U2(L,K+1)
FWV(L,K)=MAX(WV,0.)*V2(L,K)
& +MIN(WV,0.)*V2(L,K+1)
ENDDO
ENDDO
C
C----------------------------------------------------------------------C
C
GOTO 500
C
C**********************************************************************C
C
C ** THREE TIME LEVEL (LEAP-FROG) STEP
C ** CALCULATE ADVECTIVE FLUXES BY CENTRAL DIFFERENCE WITH TRANSPORT
C ** AT (N) AND TRANSPORTED FIELD AT (N)
C
400 CONTINUE
C
C----------------------------------------------------------------------C
C
DO K=1,KC
DO L=2,LA
LN=LNC(L)
LS=LSC(L)
FUHU(L,K)=0.25*(UHDY(LEAST(L),K)+UHDY(L,K))*(U(LEAST(L),K)+U(L,K))
FVHU(L,K)=0.25*(VHDX(L,K)+VHDX(LWEST(L),K))*(U(L,K)+U(LS,K))
FUHV(L,K)=0.25*(UHDY(L,K)+UHDY(LS,K))*(V(L,K)+V(LWEST(L),K))
FVHV(L,K)=0.25*(VHDX(L,K)+VHDX(LN,K))*(V(LN,K)+V(L,K))
ENDDO
ENDDO
C
C----------------------------------------------------------------------C
C
DO K=1,KS
DO L=2,LA
LS=LSC(L)
FWU(L,K)=0.25*DXYU(L)*(W(L,K)+W(LWEST(L),K))*(U(L,K+1)+U(L,K))
FWV(L,K)=0.25*DXYV(L)*(W(L,K)+W(LS,K))*(V(L,K+1)+V(L,K))
ENDDO
ENDDO
C
C**********************************************************************C
C
500 CONTINUE
C
IF(ITRICELL.GT.0)THEN
DO K=1,KC
DO L=1,LA
FUHU(L,K)=STCUV(L)*FUHU(L,K)
FVHV(L,K)=STCUV(L)*FVHV(L,K)
ENDDO
ENDDO
ENDIF
C
C**********************************************************************C
C
C ** CALCULATE CORIOLIS AND CURVATURE ACCELERATION COEFFICIENTS
C
C----------------------------------------------------------------------C
C
CACSUM=0
CFMAX=CF
IF(ISCURVATURE)THEN
IF(ISDCCA.EQ.0)THEN
C
DO K=1,KC
DO L=2,LA
LN=LNC(L)
CAC(L,K)=( FCORC(L)*DXYP(L)
& +0.5*SNLT*(V(LN,K)+V(L,K))*DYDI(L)
& -0.5*SNLT*(U(LEAST(L),K)+U(L,K))*DXDJ(L) )*HP(L)
CACSUM=CACSUM+CAC(L,K)
ENDDO
ENDDO
C
ELSE
C
DO K=1,KC
DO L=2,LA
LN=LNC(L)
CAC(L,K)=( FCORC(L)*DXYP(L)
& +0.5*SNLT*(V(LN,K)+V(L,K))*DYDI(L)
& -0.5*SNLT*(U(LEAST(L),K)+U(L,K))*DXDJ(L) )*HP(L)
CFEFF=ABS(CAC(L,K))*DXYIP(L)*HPI(L)
CFMAX=MAX(CFMAX,CFEFF)
CACSUM=CACSUM+CAC(L,K)
ENDDO
ENDDO
C
ENDIF
ENDIF
C
C IF(N.EQ.2)THEN
C OPEN(1,FILE='CORC.DIA')
C CLOSE(2,STATUS='DELETE')
C OPEN(1,FILE='CORC.DIA')
C K=1
C DO L=2,LA
C LN=LNC(L)
C WRITE(1,1111)IL(L),JL(L),LN,V(LN,K),V(L,K),DYU(LEAST(L)),DYU(L),
C & U(LEAST(L),K),U(L,K),DXV(LN),DXV(L),HP(L),CAC(L,K)
C ENDDO
C CLOSE(1)
C ENDIF
1111 FORMAT(3I5,10E13.4)
C
C**********************************************************************C
C
C ** CALCULATE CORIOLIS-CURVATURE AND ADVECTIVE ACCELERATIONS
C
C----------------------------------------------------------------------C
C
IF(CACSUM.GT.1.E-7)THEN
DO K=1,KC
DO L=1,LC
FCAX1(L,K)=0.
FCAY1(L,K)=0.
ENDDO
ENDDO
C
C----------------------------------------------------------------------C
C
DO K=1,KC
DO L=2,LA
LN=LNC(L)
LS=LSC(L)
LE=LEAST(L)
LW=LWEST(L)
LNW=LNWC(L)
LSE=LSEC(L)
FCAX(L,K)=ROLD*FCAX(L,K)
& +0.25*RNEW*SCAX(L)*(CAC(L,K)*(V(LN,K)+V(L,K))
& +CAC(LWEST(L),K)*(V(LNW,K)+V(LW,K)))
FCAY(L,K)=ROLD*FCAY(L,K)
& +0.25*RNEW*SCAY(L)*(CAC(L,K)*(U(LE,K)+U(L,K))
& +CAC(LS,K)*(U(LSE,K)+U(LS,K)))
ENDDO
ENDDO
C
C----------------------------------------------------------------------C
C
C ** MODIFICATION FOR TYPE 2 OPEN BOUNDARIES
C
DO LL=1,NPBW
IF(ISPBW(LL).EQ.2)THEN
L=LPBW(LL)+1
LN=LNC(L)
DO K=1,KC
FCAX(L,K)=0.5*SCAX(L)*CAC(L,K)*(V(LN,K)+V(L,K))
ENDDO
ENDIF
ENDDO
C
DO LL=1,NPBE
IF(ISPBE(LL).EQ.2)THEN
L=LPBE(LL)
LNW=LNWC(L)
DO K=1,KC
FCAX(L,K)=0.5*SCAX(L)*CAC(LWEST(L),K)*(V(LNW,K)+V(LWEST(L),K))
ENDDO
ENDIF
ENDDO
C
DO LL=1,NPBS
IF(ISPBS(LL).EQ.2)THEN
L=LNC(LPBS(LL))
DO K=1,KC
FCAY(L,K)=0.5*SCAY(L)*CAC(L,K)*(U(LEAST(L),K)+U(L,K))
ENDDO
ENDIF
ENDDO
C
DO LL=1,NPBN
IF(ISPBN(LL).EQ.2)THEN
L=LPBN(LL)
LS=LSC(L)
LSE=LSEC(L)
DO K=1,KC
FCAY(L,K)=0.5*SCAY(L)*CAC(LS,K)*(U(LSE,K)+U(LS,K))
ENDDO
ENDIF
ENDDO
ENDIF
C
C----------------------------------------------------------------------C
C *** COMPUTE MAIN MOMENTUM TERMS
C
DO K=1,KC
DO L=2,LA
LN=LNC(L)
LS=LSC(L)
LE=LEAST(L)
LW=LWEST(L)
!HRUO(L)=SUBO(L)*DYU(L)*DXIU(L)
!HRXYU(L)=DXU(L)/DYU(L)
FX(L,K)=(FUHU(L ,K)-FUHU(LW,K)+FVHU(LN,K)-FVHU(L ,K)+FUHJ(L,K))
FY(L,K)=(FUHV(LE,K)-FUHV(L ,K)+FVHV(L ,K)-FVHV(LS,K)+FVHJ(L,K))
ENDDO
ENDDO
! *** TREAT BC'S NEAR EDGES PMC
DO LL=1,NBCS
! *** BC CELL
L=LBCS(LL)
DO K=1,KC
FX(L,K)=SAAX(L)*FX(L,K)
FY(L,K)=SAAY(L)*FY(L,K)
ENDDO
! *** EAST/WEST ADJACENT CELL
L=LBERC(LL)
DO K=1,KC
FX(L,K)=SAAX(L)*FX(L,K)
ENDDO
! *** NORTH/SOUTH ADJACENT CELL
L=LBNRC(LL)
DO K=1,KC
FY(L,K)=SAAY(L)*FY(L,K)
ENDDO
ENDDO
C
C**********************************************************************C
C
C ** ADD VEGETATION DRAG TO HORIZONTAL ADVECTIVE ACCELERATIONS
C
C----------------------------------------------------------------------C
C
IF(ISVEG.GE.1)THEN
C
DO L=2,LA
FXVEGE(L)=0.
FYVEGE(L)=0.
ENDDO
C
DO K=1,KC
DO L=2,LA
LW=LWEST(L)
LE=LEAST(L)
LS=LSC(L)
LN=LNC(L)
LNW=LNWC(L)
LSE=LSEC(L)
VTMPATU=0.25*(V1(L,K)+V1(LW,K)+V1(LN,K)+V1(LNW,K))
UTMPATV=0.25*(U1(L,K)+U1(LE,K)+U1(LS,K)+U1(LSE,K))
UMAGTMP=SQRT( U1(L,K)*U1(L,K)+VTMPATU*VTMPATU )
VMAGTMP=SQRT( UTMPATV*UTMPATV+V1(L,K)*V1(L,K) )
FXVEG(L,K)=UMAGTMP*SUB(L)*DXYU(L)*FXVEG(L,K)
FYVEG(L,K)=VMAGTMP*SVB(L)*DXYV(L)*FYVEG(L,K)
FXVEGE(L)=FXVEGE(L)+FXVEG(L,K)*DZC(K)
FYVEGE(L)=FYVEGE(L)+FYVEG(L,K)*DZC(K)
ENDDO
ENDDO
C
DO K=1,KC
DO L=2,LA
FXVEG(L,K)=FXVEG(L,K)*U1(L,K)
FYVEG(L,K)=FYVEG(L,K)*V1(L,K)
FX(L,K)=FX(L,K)+FXVEG(L,K)-FXVEGE(L)*U1(L,K)
FY(L,K)=FY(L,K)+FYVEG(L,K)-FYVEGE(L)*V1(L,K)
ENDDO
ENDDO
C
IF(LMHK)CALL MHKPWRDIS !MHK devices exist
DO L=2,LA
FXVEGE(L)=DXYIU(L)*FXVEGE(L)/H1U(L)
FYVEGE(L)=DXYIV(L)*FYVEGE(L)/H1V(L)
ENDDO
FXVEGE(:)=FXVEGE(:)+FXMHKE(:)+FXSUPE(:) !Add MHK to vegetative dissipation in FUHDYE for momentum conservation in CALPUV
FYVEGE(:)=FYVEGE(:)+FYMHKE(:)+FYSUPE(:) !Add MHK to vegetative dissipation in FVHDXE for momentum conservation in CALPUV
C
ENDIF
C
C
C**********************************************************************C
C
C ** ADD HORIZONTAL MOMENTUM DIFFUSION TO ADVECTIVE ACCELERATIONS
C
C----------------------------------------------------------------------C
C
IF(ISHDMF.GE.1)THEN
DO K=1,KC
DO L=2,LA
LS=LSC(L)
LN=LNC(L)
FX(L,K)=FX(L,K)-(FMDUX(L,K)+FMDUY(L,K))
FY(L,K)=FY(L,K)-(FMDVX(L,K)+FMDVY(L,K))
ENDDO
ENDDO
ENDIF
C
C**********************************************************************C
C
C ** ADD BODY FORCE TO ADVECTIVE ACCELERATIONS
C ** DISTRIBUTE UNIFORMLY OVER ALL LAYERS IF ISBODYF=1
C ** DISTRIBUTE OVER SURFACE LAYER IF ISBODYF=2
C
C----------------------------------------------------------------------C
C
IF(ISBODYF.EQ.1.OR.ISUVDA.GE.1)THEN
C
DO K=1,KC
DZICK=1./DZC(K)
DO L=2,LA
FX(L,K)=FX(L,K)-DYU(L)*HU(L)*FBODYFX(L,K)
FY(L,K)=FY(L,K)-DXV(L)*HV(L)*FBODYFY(L,K)
ENDDO
ENDDO
C
ENDIF
C
IF(ISBODYF.EQ.2)THEN
C
DZICKC=1./DZC(KC)
DO L=2,LA
FX(L,KC)=FX(L,KC)-DZICKC*DYU(L)*HU(L)*FBODYFX(L,K)
FY(L,KC)=FY(L,KC)-DZICKC*DXV(L)*HV(L)*FBODYFY(L,K)
ENDDO
C
ENDIF
C
C**********************************************************************C
C
C ** ADD EXPLICIT NONHYDROSTATIC PRESSURE
C
IF(KC.GT.1.AND.ISPNHYDS.GE.1) THEN
C
TMPVAL=2./(DZC(1)+DZC(2))
DO L=2,LA
DZPC(L,1)=TMPVAL*(PNHYDS(L,2)-PNHYDS(L,1))
ENDDO
C
TMPVAL=2./(DZC(KC)+DZC(KC-1))
DO L=2,LA
DZPC(L,KC)=TMPVAL*(PNHYDS(L,KC)-PNHYDS(L,KC-1))
ENDDO
IF(KC.GE.3)THEN
DO K=2,KS
TMPVAL=2./(DZC(K+1)+2.*DZC(K)+DZC(K-1))
DO L=2,LA
DZPC(L,K)=TMPVAL*(PNHYDS(L,K+1)-PNHYDS(L,K-1))
ENDDO
ENDDO
ENDIF
C
DO K=1,KC
DO L=2,LA
LS=LSC(L)
DZPU=0.5*(DZPC(L,K)+DZPC(LWEST(L),K))
DZPV=0.5*(DZPC(L,K)+DZPC(LS ,K))
FX(L,K)=FX(L,K)+SUB(L)*DYU(L)*
& ( HU(L)*(PNHYDS(L,K)-PNHYDS(LWEST(L),K))
& -( BELV(L)-BELV(LWEST(L))+ZZ(K)*(HP(L)-HP(LWEST(L))) )*DZPU )
FY(L,K)=FY(L,K)+SVB(L)*DXV(L)*
& ( HV(L)*(PNHYDS(L,K)-PNHYDS(LS ,K))
& -( BELV(L)-BELV(LS )+ZZ(K)*(HP(L)-HP(LS )) )*DZPV )
ENDDO
ENDDO
C
ENDIF
C
C----------------------------------------------------------------------C
C
C ** ADD NET WAVE REYNOLDS STRESSES TO EXTERNAL ADVECTIVE ACCEL.
C
C *** DSLLC BEGIN BLOCK
IF(ISWAVE.EQ.2)THEN
C
IF(N.LT.NTSWV)THEN
TMPVAL=FLOAT(N)/FLOAT(NTSWV)
WVFACT=0.5-0.5*COS(PI*TMPVAL)
ELSE
WVFACT=1.0
ENDIF
C
DO K=1,KC
DO L=2,LA
FX(L,K)=FX(L,K)+WVFACT*SAAX(L)*FXWAVE(L,K)
FY(L,K)=FY(L,K)+WVFACT*SAAY(L)*FYWAVE(L,K)
ENDDO
ENDDO
C
ENDIF
C *** DSLLC END BLOCK
C
C**********************************************************************C
C
C ** CALCULATE EXTERNAL ACCELERATIONS
C
C----------------------------------------------------------------------C
C
DO K=1,KC
DO L=2,LA
FCAXE(L)=FCAXE(L)+FCAX(L,K)*DZC(K)
FCAYE(L)=FCAYE(L)+FCAY(L,K)*DZC(K)
FXE(L)=FXE(L)+FX(L,K)*DZC(K)
FYE(L)=FYE(L)+FY(L,K)*DZC(K)
ENDDO
ENDDO
C
C**********************************************************************C
C
C ** COMPLETE CALCULATION OF INTERNAL ADVECTIVE ACCELERATIONS
C
C----------------------------------------------------------------------C
C
IF(KC.GT.1)THEN
DO K=1,KC
DO L=2,LA
FX(L,K)=FX(L,K)+SAAX(L)*(FWU(L,K)-FWU(L,K-1))*DZIC(K)
FY(L,K)=FY(L,K)+SAAY(L)*(FWV(L,K)-FWV(L,K-1))*DZIC(K)
ENDDO
ENDDO
ENDIF
C
C**********************************************************************C
C
C ** CALCULATE EXPLICIT INTERNAL BUOYANCY FORCINGS CENTERED AT N FOR
C ** THREE TIME LEVEL STEP AND AT (N+1/2) FOR TWO TIME LEVEL STEP
C ** SBX=SBX*0.5*DYU & SBY=SBY*0.5*DXV
C
C----------------------------------------------------------------------C
C
IF(BSC.GT.1.E-6)THEN
C
IF(IINTPG.EQ.0)THEN
C *** ORIGINAL
DO K=1,KS
DO L=2,LA
LS=LSC(L)
FBBX(L,K)=ROLD*FBBX(L,K)+RNEW*SBX(L)*GP*HU(L)*
& ( HU(L)*( (B(L,K+1)-B(LWEST(L),K+1))*DZC(K+1)
& +(B(L,K)-B(LWEST(L),K))*DZC(K) )
& -(B(L,K+1)-B(L,K)+B(LWEST(L),K+1)-B(LWEST(L),K))*
& (BELV(L)-BELV(LWEST(L))+Z(K)*(HP(L)-HP(LWEST(L)))) )
FBBY(L,K)=ROLD*FBBY(L,K)+RNEW*SBY(L)*GP*HV(L)*
& ( HV(L)*( (B(L,K+1)-B(LS,K+1))*DZC(K+1)
& +(B(L,K)-B(LS,K))*DZC(K) )
& -(B(L,K+1)-B(L,K)+B(LS,K+1)-B(LS,K))*
& (BELV(L)-BELV(LS)+Z(K)*(HP(L)-HP(LS))) )
ENDDO
ENDDO
C
ENDIF
C
C JACOBIAN
C
IF(IINTPG.EQ.1)THEN
C
K=1
DO L=2,LA
LS=LSC(L)
FBBX(L,K)=ROLD*FBBX(L,K)+RNEW*SBX(L)*GP*HU(L)*
& ( 0.5*HU(L)*( (B(L,K+2)-B(LWEST(L),K+2))*DZC(K+2)
& +(B(L,K+1)-B(LWEST(L),K+1))*DZC(K+1)
& +(B(L,K )-B(LWEST(L),K ))*DZC(K )
& +(B(L,K )-B(LWEST(L),K ))*DZC(K ) )
& -0.5*(B(L,K+2)-B(L,K+1)+B(LWEST(L),K+2)-B(LWEST(L),K+1))*
& (BELV(L)-BELV(LWEST(L))+Z(K+1)*(HP(L)-HP(LWEST(L))))
& -0.5*(B(L,K )-B(L,K )+B(LWEST(L),K )-B(LWEST(L),K ))*
& (BELV(L)-BELV(LWEST(L))+Z(K-1)*(HP(L)-HP(LWEST(L)))) )
C
FBBY(L,K)=ROLD*FBBY(L,K)+RNEW*SBY(L)*GP*HV(L)*
& ( 0.5*HV(L)*( (B(L,K+2)-B(LS ,K+2))*DZC(K+2)
& +(B(L,K+1)-B(LS ,K+1))*DZC(K+1)
& +(B(L,K )-B(LS ,K ))*DZC(K )
& +(B(L,K )-B(LS ,K ))*DZC(K ) )
& -0.5*(B(L,K+2)-B(L,K+1)+B(LS ,K+2)-B(LS ,K+1))*
& (BELV(L)-BELV(LS)+Z(K+1)*(HP(L)-HP(LS)))
& -0.5*(B(L,K )-B(L,K )+B(LS ,K )-B(LS ,K ))*
& (BELV(L)-BELV(LS )+Z(K-1)*(HP(L)-HP(LS ))) )
ENDDO
C
IF(KC.GT.2)THEN
K=KS
DO L=2,LA
LS=LSC(L)
FBBX(L,K)=ROLD*FBBX(L,K)+RNEW*SBX(L)*GP*HU(L)*
& ( 0.5*HU(L)*( (B(L,K+1)-B(LWEST(L),K+1))*DZC(K+1)
& +(B(L,K+1)-B(LWEST(L),K+1))*DZC(K+1)
& +(B(L,K )-B(LWEST(L),K ))*DZC(K )
& +(B(L,K-1)-B(LWEST(L),K-1))*DZC(K-1) )
& -0.5*(B(L,K+1)-B(L,K+1)+B(LWEST(L),K+1)-B(LWEST(L),K+1))*
& (BELV(L)-BELV(LWEST(L))+Z(K+1)*(HP(L)-HP(LWEST(L))))
& -0.5*(B(L,K )-B(L,K-1)+B(LWEST(L),K )-B(LWEST(L),K-1))*
& (BELV(L)-BELV(LWEST(L))+Z(K-1)*(HP(L)-HP(LWEST(L)))) )
FBBY(L,K)=ROLD*FBBY(L,K)+RNEW*SBY(L)*GP*HV(L)*
& ( 0.5*HV(L)*( (B(L,K+1)-B(LS ,K+1))*DZC(K+1)
& +(B(L,K+1)-B(LS ,K+1))*DZC(K+1)
& +(B(L,K )-B(LS ,K ))*DZC(K )
& +(B(L,K-1)-B(LS ,K-1))*DZC(K-1) )
& -0.5*(B(L,K+1)-B(L,K+1)+B(LS ,K+1)-B(LS ,K+1))*
& (BELV(L)-BELV(LS)+Z(K+1)*(HP(L)-HP(LS)))
& -0.5*(B(L,K )-B(L,K-1)+B(LS ,K )-B(LS ,K-1))*
& (BELV(L)-BELV(LS )+Z(K-1)*(HP(L)-HP(LS ))) )
ENDDO
ENDIF
C
IF(KC.GT.3)THEN
DO K=1,KS
DO L=2,LA
LS=LSC(L)
FBBX(L,K)=ROLD*FBBX(L,K)+RNEW*SBX(L)*GP*HU(L)*
& ( 0.5*HU(L)*( (B(L,K+2)-B(LWEST(L),K+2))*DZC(K+2)
& +(B(L,K+1)-B(LWEST(L),K+1))*DZC(K+1)
& +(B(L,K )-B(LWEST(L),K ))*DZC(K )
& +(B(L,K-1)-B(LWEST(L),K-1))*DZC(K-1) )
& -0.5*(B(L,K+2)-B(L,K+1)+B(LWEST(L),K+2)-B(LWEST(L),K+1))*
& (BELV(L)-BELV(LWEST(L))+Z(K+1)*(HP(L)-HP(LWEST(L))))
& -0.5*(B(L,K )-B(L,K-1)+B(LWEST(L),K )-B(LWEST(L),K-1))*
& (BELV(L)-BELV(LWEST(L))+Z(K-1)*(HP(L)-HP(LWEST(L)))) )
FBBY(L,K)=ROLD*FBBY(L,K)+RNEW*SBY(L)*GP*HV(L)*
& ( 0.5*HV(L)*( (B(L,K+2)-B(LS ,K+2))*DZC(K+2)
& +(B(L,K+1)-B(LS ,K+1))*DZC(K+1)
& +(B(L,K )-B(LS ,K ))*DZC(K )
& +(B(L,K-1)-B(LS ,K-1))*DZC(K-1) )
& -0.5*(B(L,K+2)-B(L,K+1)+B(LS ,K+2)-B(LS ,K+1))*
& (BELV(L)-BELV(LS)+Z(K+1)*(HP(L)-HP(LS)))
& -0.5*(B(L,K )-B(L,K-1)+B(LS ,K )-B(LS ,K-1))*
& (BELV(L)-BELV(LS )+Z(K-1)*(HP(L)-HP(LS ))) )
ENDDO
ENDDO
ENDIF
C
ENDIF
C
C FINITE VOLUME
C
IF(IINTPG.EQ.2)THEN
C
DO K=1,KS
DO L=2,LA
LS=LSC(L)
FBBX(L,K)=ROLD*FBBX(L,K)
& +RNEW*SBX(L)*GP*HU(L)*
& ( ( HP(L)*B(L,K+1)-HP(LWEST(L))*B(LWEST(L),K+1) )*DZC(K+1)
& +( HP(L)*B(L,K )-HP(LWEST(L))*B(LWEST(L),K ) )*DZC(K ) )
& -RNEW*SBX(L)*GP*(BELV(L)-BELV(LWEST(L)))*
& ( HP(L)*B(L,K+1)-HP(L)*B(L,K)
& +HP(LWEST(L))*B(LWEST(L),K+1)-HP(LWEST(L))*B(LWEST(L),K) )
& -RNEW*SBX(L)*GP*(HP(L)-HP(LWEST(L)))*
& ( HP(L)*ZZ(K+1)*B(L,K+1)-HP(L)*ZZ(K)*B(L,K)
& +HP(LWEST(L))*ZZ(K+1)*B(LWEST(L),K+1)-HP(LWEST(L))*ZZ(K)*B(LWEST(L),K) )
FBBY(L,K)=ROLD*FBBY(L,K)
& +RNEW*SBY(L)*GP*HV(L)*
& ( ( HP(L)*B(L,K+1)-HP(LS )*B(LS ,K+1) )*DZC(K+1)
& +( HP(L)*B(L,K )-HP(LS )*B(LS ,K ) )*DZC(K ) )
& -RNEW*SBY(L)*GP*(BELV(L)-BELV(LS ))*
& ( HP(L)*B(L,K+1)-HP(L)*B(L,K)
& +HP(LS)*B(LS ,K+1)-HP(LS)*B(LS ,K) )
& -RNEW*SBY(L)*GP*(HP(L)-HP(LS ))*
& ( HP(L)*ZZ(K+1)*B(L,K+1)-HP(L)*ZZ(K)*B(L,K)
& +HP(LS)*ZZ(K+1)*B(LS ,K+1)-HP(LS)*ZZ(K)*B(LS ,K) )
ENDDO
ENDDO
C
ENDIF
ENDIF ! *** END OF BOUYANCY
C
C IF(N.EQ.1)THEN
C OPEN(1,FILE='BUOY.DIA',STATUS='UNKNOWN')
C DO L=2,LA
C DO K=1,KS
C TMP3D(K)=SUBO(L)*FBBX(L,K)
C ENDDO
C WRITE(1,1111)IL(L),JL(L),(TMP3D(K),K=1,KS)
C DO K=1,KS
C TMP3D(K)=SVBO(L)*FBBY(L,K)
C ENDDO
C WRITE(1,1111)IL(L),JL(L),(TMP3D(K),K=1,KS)
C ENDDO
C CLOSE(1)
C ENDIF
C
C 1111 FORMAT(2I5,2X,8E12.4)
C
C**********************************************************************C
C
C ** CALCULATE EXPLICIT INTERNAL U AND V SHEAR EQUATION TERMS
C
C----------------------------------------------------------------------C
C
IF(KC.GT.1)THEN
DO L=1,LC
DU(L,KC)=0.0
DV(L,KC)=0.0
ENDDO
DO K=1,KS
RCDZF=CDZF(K)
DO L=2,LA
!DXYIU(L)=1./(DXU(L)*DYU(L))
DU(L,K)=RCDZF*( H1U(L)*(U1(L,K+1)-U1(L,K))*DELTI
& +DXYIU(L)*(FCAX(L,K+1)-FCAX(L,K)+FBBX(L,K)
& +SNLT*(FX(L,K)-FX(L,K+1))) )
DV(L,K)=RCDZF*( H1V(L)*(V1(L,K+1)-V1(L,K))*DELTI
& +DXYIV(L)*(FCAY(L,K)-FCAY(L,K+1)+FBBY(L,K)
& +SNLT*(FY(L,K)-FY(L,K+1))) )
ENDDO
ENDDO
ENDIF
C
IF(ISTL_.EQ.2.AND.NWSER.GT.0)THEN
C
DO ND=1,NDM
LF=2+(ND-1)*LDM
LL=LF+LDM-1
DO L=LF,LL
DU(L,KS)=DU(L,KS)-CDZU(KS)*TSX(L)
DV(L,KS)=DV(L,KS)-CDZU(KS)*TSY(L)
ENDDO
ENDDO
C
ENDIF
C
C**********************************************************************C
C
IF(N.LE.4)THEN
CLOSE(1)
ENDIF
C
1112 FORMAT('N,NW,NS,I,J,K,NF,H,Q,QU,FUU,FVV=',/,2X,7I5,5E12.4)
C
C**********************************************************************C
C
RETURN
END
|
#create map of Other Agriculture Captial
#currently this is based solely on slope (script converts to values needed)
rm(list=ls())
library(raster)
#note decliv_class.asc in zip file is 1.8GB!
#read munis.r as latlong
#unzip(zipfile="Data/sim10_BRmunis_latlon_5kmzip",exdir="Data") #unzip
munis.r <- raster("Data/sim10_BRmunis_latlon_5km.asc")
latlong <- "+proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs "
crs(munis.r) <- latlong
#note decliv_class.asc in zip file is 1.8GB!
unzip(zipfile="Data/decliv_class.zip",exdir="Data") #unzip
vslope<-raster("Data/decliv_class.asc")
vslope.m<- resample(vslope, munis.r, method='ngb') #JM edited munis.r
vslope.m<- mask(x=vslope.m, mask=munis.r) #JM edited munis.r
# 0 (1) becomes 0.2 – (0 – 3% No limitation)
# 1 (2) becomes 0.4 – (3 – 8% Slight limitation )
# 2 (3) becomes 0.6 – (8 – 13% Moderate limitation)
# 3 (4) becomes 0.8 – (13 – 20% Strong limitation)
# 4* (5) becomes 1.0 – (20 – 45 % Very strong limitation)
# 4* (6) becomes 0 –(>45% Unsuitable)
a <- c(1,0.2)
a <- rbind(a,(c(2,0.4)))
a <- rbind(a,(c(3,0.6)))
a <- rbind(a,(c(4,0.8)))
a <- rbind(a,(c(5,1.0)))
a <- rbind(a,(c(6,0)))
OAslope.m <- reclassify(vslope.m, a)
summary(OAslope.m)
writeRaster(OAslope.m, "Data/OAgri-slope_2018-08-16", "ascii", "overwrite"=T)
unlink("Data/decliv_class.asc") #large file so delete!
#unlink("Data/sim10_BRmunis_latlon_5km.asc")
|
open import Level
import Categories.Category
open import Relation.Binary.PropositionalEquality using (_≡_; refl; sym; trans; subst; cong)
open import Syntax
open import Renaming
open import Substitution
open import Instantiation
module SyntaxMap where
open Signature
open Expression
open Equality
infix 5 _→ᵐ_
-- syntax map
_→ᵐ_ : Signature → Signature → Set
𝕊 →ᵐ 𝕋 = ∀ {cl} (S : symb 𝕊 cl) → Expr 𝕋 (obj cl) (symb-arg 𝕊 S) 𝟘
-- equality of syntax maps
infix 4 _≈ᵐ_
_≈ᵐ_ : ∀ {𝕊 𝕋} (f g : 𝕊 →ᵐ 𝕋) → Set
_≈ᵐ_ {𝕊 = 𝕊} {𝕋 = 𝕋} f g =
∀ {cl} (S : symb 𝕊 cl) → f S ≈ g S
-- equality is an equivalence relation
≈ᵐ-refl : ∀ {𝕊 𝕋} {f : 𝕊 →ᵐ 𝕋} → f ≈ᵐ f
≈ᵐ-refl {𝕋 = 𝕋} S = ≈-refl
≈ᵐ-sym : ∀ {𝕊 𝕋} {f g : 𝕊 →ᵐ 𝕋} → f ≈ᵐ g → g ≈ᵐ f
≈ᵐ-sym {𝕋 = 𝕋} ξ S = ≈-sym (ξ S)
≈ᵐ-trans : ∀ {𝕊 𝕋} {f g h : 𝕊 →ᵐ 𝕋} → f ≈ᵐ g → g ≈ᵐ h → f ≈ᵐ h
≈ᵐ-trans {𝕋 = 𝕋} ζ ξ S = ≈-trans (ζ S) (ξ S)
-- The identity raw syntax map
𝟙ᵐ : ∀ {𝕊} → (𝕊 →ᵐ 𝕊)
𝟙ᵐ {𝕊} S = expr-symb S (expr-meta-generic 𝕊)
-- Action of a raw syntax map
infixr 10 [_]ᵐ_
[_]ᵐ_ : ∀ {𝕊 𝕋} → (𝕊 →ᵐ 𝕋) → ∀ {cl 𝕄 γ} → Expr 𝕊 𝕄 cl γ → Expr 𝕋 𝕄 cl γ
[ f ]ᵐ (expr-var x) = expr-var x
[_]ᵐ_ {𝕋 = 𝕋} f {𝕄 = 𝕄} (expr-symb S es) =
[ (λ M → [ f ]ᵐ es M) ]ⁱ ([ 𝟘-initial ]ʳ f S)
[ f ]ᵐ (expr-meta M ts) = expr-meta M (λ i → [ f ]ᵐ (ts i))
[ f ]ᵐ expr-eqty = expr-eqty
[ f ]ᵐ expr-eqtm = expr-eqtm
-- Action preserves equality
[]ᵐ-resp-≈ : ∀ {𝕊 𝕋} {cl 𝕄 γ} (f : 𝕊 →ᵐ 𝕋) {t u : Expr 𝕊 𝕄 cl γ} →
t ≈ u → [ f ]ᵐ t ≈ [ f ]ᵐ u
[]ᵐ-resp-≈ f (≈-≡ ξ) = ≈-≡ (cong ([ f ]ᵐ_) ξ)
[]ᵐ-resp-≈ {𝕋 = 𝕋} f (≈-symb {S = S} ξ) =
[]ⁱ-resp-≈ⁱ ([ 𝟘-initial ]ʳ f S) λ M → []ᵐ-resp-≈ f (ξ M)
[]ᵐ-resp-≈ f (≈-meta ξ) = ≈-meta (λ i → []ᵐ-resp-≈ f (ξ i))
[]ᵐ-resp-≈ᵐ : ∀ {𝕊 𝕋} {cl 𝕄 γ} {f g : 𝕊 →ᵐ 𝕋} (t : Expr 𝕊 𝕄 cl γ) →
f ≈ᵐ g → [ f ]ᵐ t ≈ [ g ]ᵐ t
[]ᵐ-resp-≈ᵐ (expr-var x) ξ = ≈-refl
[]ᵐ-resp-≈ᵐ {f = f} {g = g} (expr-symb S es) ξ =
[]ⁱ-resp-≈ⁱ-≈ {I = λ M → [ f ]ᵐ es M} {J = λ M → [ g ]ᵐ es M}
(λ M → []ᵐ-resp-≈ᵐ (es M) ξ)
([]ʳ-resp-≈ 𝟘-initial (ξ S))
[]ᵐ-resp-≈ᵐ (expr-meta M ts) ξ = ≈-meta (λ i → []ᵐ-resp-≈ᵐ (ts i) ξ)
[]ᵐ-resp-≈ᵐ expr-eqty ξ = ≈-eqty
[]ᵐ-resp-≈ᵐ expr-eqtm ξ = ≈-eqtm
[]ᵐ-resp-≈ᵐ-≈ : ∀ {𝕊 𝕋} {cl 𝕄 γ} {f g : 𝕊 →ᵐ 𝕋} {t u : Expr 𝕊 𝕄 cl γ} →
f ≈ᵐ g → t ≈ u → [ f ]ᵐ t ≈ [ g ]ᵐ u
[]ᵐ-resp-≈ᵐ-≈ {g = g} {t = t} ζ ξ = ≈-trans ([]ᵐ-resp-≈ᵐ t ζ) ([]ᵐ-resp-≈ g ξ)
-- Composition of raw syntax maps
infixl 7 _∘ᵐ_
_∘ᵐ_ : ∀ {𝕊 𝕋 𝕌} → (𝕋 →ᵐ 𝕌) → (𝕊 →ᵐ 𝕋) → (𝕊 →ᵐ 𝕌)
(g ∘ᵐ f) S = [ g ]ᵐ (f S)
-- Action preserves identity
module _ {𝕊} where
open Equality
open Renaming
open Substitution
[𝟙ᵐ] : ∀ {cl 𝕄 γ} (t : Expr 𝕊 cl 𝕄 γ) → [ 𝟙ᵐ ]ᵐ t ≈ t
[𝟙ᵐ] (expr-var x) = ≈-refl
[𝟙ᵐ] (expr-symb S es) =
≈-symb (λ {cⁱ γⁱ} i → [𝟙ᵐ]-arg cⁱ γⁱ i)
where [𝟙ᵐ]-arg : ∀ cⁱ γⁱ (i : [ cⁱ , γⁱ ]∈ symb-arg 𝕊 S) → _
[𝟙ᵐ]-arg (obj x) γⁱ i =
≈-trans
([]ˢ-resp-≈ _ ([]ʳ-resp-≈ _ ([𝟙ᵐ] (es i))))
(≈-trans (≈-sym ([ˢ∘ʳ] (es i))) ([]ˢ-id (λ { (var-left _) → ≈-refl ; (var-right _) → ≈-refl })))
[𝟙ᵐ]-arg EqTy γⁱ i = ≈-eqty
[𝟙ᵐ]-arg EqTm γⁱ i = ≈-eqtm
[𝟙ᵐ] (expr-meta M ts) = ≈-meta λ i → [𝟙ᵐ] (ts i)
[𝟙ᵐ] expr-eqty = ≈-eqty
[𝟙ᵐ] expr-eqtm = ≈-eqtm
-- interaction of maps with instantiation and substitution
module _ {𝕊 𝕋} where
open Substitution
infixl 7 _ᵐ∘ˢ_
_ᵐ∘ˢ_ : ∀ {𝕊 𝕋} {𝕄 γ δ} (f : 𝕊 →ᵐ 𝕋) (σ : 𝕊 % 𝕄 ∥ γ →ˢ δ) → (𝕋 % 𝕄 ∥ γ →ˢ δ)
(f ᵐ∘ˢ σ) x = [ f ]ᵐ σ x
[]ᵐ-[]ʳ : ∀ {f : 𝕊 →ᵐ 𝕋} {cl 𝕄 γ δ} {ρ : γ →ʳ δ} (t : Expr 𝕊 cl 𝕄 γ) →
([ f ]ᵐ ([ ρ ]ʳ t)) ≈ ([ ρ ]ʳ [ f ]ᵐ t)
[]ᵐ-[]ʳ (expr-var x) = ≈-refl
[]ᵐ-[]ʳ {f = f} {ρ = ρ} (expr-symb S es) =
≈-trans
([]ⁱ-resp-≈ⁱ ([ 𝟘-initial ]ʳ f S) λ M → []ᵐ-[]ʳ (es M))
(≈-trans
([]ⁱ-resp-≈ⁱ-≈
{t = [ 𝟘-initial ]ʳ f S}
{u = [ ρ ]ʳ ([ 𝟘-initial ]ʳ f S)}
(λ M → ≈-refl)
(≈-trans ([]ʳ-resp-≡ʳ (f S) (λ {()})) ([∘ʳ] (f S))))
(≈-sym ([ʳ∘ⁱ] ([ 𝟘-initial ]ʳ f S))))
[]ᵐ-[]ʳ (expr-meta M ts) = ≈-meta (λ i → []ᵐ-[]ʳ (ts i))
[]ᵐ-[]ʳ expr-eqty = ≈-eqty
[]ᵐ-[]ʳ expr-eqtm = ≈-eqtm
[]ᵐ-[]ˢ : ∀ {cl 𝕄 γ δ} {f : 𝕊 →ᵐ 𝕋} {σ : 𝕊 % 𝕄 ∥ γ →ˢ δ} (t : Expr 𝕊 cl 𝕄 γ) →
[ f ]ᵐ ([ σ ]ˢ t) ≈ [ f ᵐ∘ˢ σ ]ˢ [ f ]ᵐ t
[]ᵐ-[]ˢ (expr-var x) = ≈-refl
[]ᵐ-[]ˢ {f = f} {σ = σ} (expr-symb S es) =
≈-trans
([]ⁱ-resp-≈ⁱ ([ 𝟘-initial ]ʳ f S) (λ M → []ᵐ-[]ˢ (es M)))
(≈-trans
([]ⁱ-resp-≈ⁱ
([ 𝟘-initial ]ʳ f S)
(λ M → []ˢ-resp-≈ˢ
(λ { (var-left x) → []ᵐ-[]ʳ (σ x)
; (var-right _) → ≈-refl})
([ f ]ᵐ es M)))
(≈-sym ([]ˢ-[]ⁱ {ρ = 𝟘-initial} (f S) λ {()})))
[]ᵐ-[]ˢ (expr-meta M ts) = ≈-meta (λ i → []ᵐ-[]ˢ (ts i))
[]ᵐ-[]ˢ expr-eqty = ≈-eqty
[]ᵐ-[]ˢ expr-eqtm = ≈-eqtm
infixl 7 _ᵐ∘ⁱ_
_ᵐ∘ⁱ_ : ∀ {𝕂 𝕄 γ} (f : 𝕊 →ᵐ 𝕋) (I : 𝕊 % 𝕂 →ⁱ 𝕄 ∥ γ) → 𝕋 % 𝕂 →ⁱ 𝕄 ∥ γ
(f ᵐ∘ⁱ I) M = [ f ]ᵐ I M
⇑ⁱ-resp-ᵐ∘ⁱ : ∀ {𝕂 𝕄 γ δ} {f : 𝕊 →ᵐ 𝕋} {I : 𝕊 % 𝕂 →ⁱ 𝕄 ∥ γ} →
⇑ⁱ {δ = δ} (f ᵐ∘ⁱ I) ≈ⁱ f ᵐ∘ⁱ ⇑ⁱ I
⇑ⁱ-resp-ᵐ∘ⁱ {I = I} M = ≈-sym ([]ᵐ-[]ʳ (I M))
[]ᵐ-[]ⁱ : ∀ {cl 𝕂 𝕄 γ} {f : 𝕊 →ᵐ 𝕋} {I : 𝕊 % 𝕂 →ⁱ 𝕄 ∥ γ} (t : Expr 𝕊 cl 𝕂 γ) →
[ f ]ᵐ ([ I ]ⁱ t) ≈ [ f ᵐ∘ⁱ I ]ⁱ [ f ]ᵐ t
[]ᵐ-[]ⁱ (expr-var x) = ≈-refl
[]ᵐ-[]ⁱ {f = f} {I = I} (expr-symb S es) =
≈-trans
([]ⁱ-resp-≈ⁱ
([ 𝟘-initial ]ʳ f S)
λ M → ≈-trans
([]ᵐ-[]ⁱ (es M))
([]ⁱ-resp-≈ⁱ ([ f ]ᵐ es M) (≈ⁱ-sym (⇑ⁱ-resp-ᵐ∘ⁱ {I = I}))))
([∘ⁱ] ([ 𝟘-initial ]ʳ f S))
[]ᵐ-[]ⁱ {f = f} {I = I} (expr-meta M ts) =
≈-trans
([]ᵐ-[]ˢ (I M))
([]ˢ-resp-≈ˢ (λ { (var-left _) → ≈-refl ; (var-right x) → []ᵐ-[]ⁱ (ts x)}) ([ f ]ᵐ I M))
[]ᵐ-[]ⁱ expr-eqty = ≈-eqty
[]ᵐ-[]ⁱ expr-eqtm = ≈-eqtm
-- idenity is right-neutral
[]ᵐ-meta-generic : ∀ {𝕊 𝕋} {𝕄 γ} {f : 𝕊 →ᵐ 𝕋} {clᴹ γᴹ} {M : [ clᴹ , γᴹ ]∈ 𝕄} →
[ f ]ᵐ (expr-meta-generic 𝕊 {γ = γ} M) ≈ expr-meta-generic 𝕋 M
[]ᵐ-meta-generic {clᴹ = obj _} = ≈-refl
[]ᵐ-meta-generic {clᴹ = EqTy} = ≈-eqty
[]ᵐ-meta-generic {clᴹ = EqTm} = ≈-eqtm
𝟙ᵐ-right : ∀ {𝕊 𝕋} {f : 𝕊 →ᵐ 𝕋} → f ∘ᵐ 𝟙ᵐ ≈ᵐ f
𝟙ᵐ-right {f = f} S =
≈-trans
([]ⁱ-resp-≈ⁱ ([ 𝟘-initial ]ʳ (f S)) λ M → []ᵐ-meta-generic {M = M})
(≈-trans ([𝟙ⁱ] ([ 𝟘-initial ]ʳ f S)) ([]ʳ-id (λ { ()})))
-- Action preserves composition
module _ {𝕊 𝕋 𝕌} where
[∘ᵐ] : ∀ {f : 𝕊 →ᵐ 𝕋} {g : 𝕋 →ᵐ 𝕌} {cl 𝕄 γ} (t : Expr 𝕊 cl 𝕄 γ) → [ g ∘ᵐ f ]ᵐ t ≈ [ g ]ᵐ [ f ]ᵐ t
[∘ᵐ] (expr-var x) = ≈-refl
[∘ᵐ] {f = f} {g = g} (expr-symb S es) =
≈-trans
([]ⁱ-resp-≈ⁱ-≈ (λ M → [∘ᵐ] (es M)) (≈-sym ([]ᵐ-[]ʳ (f S))))
(≈-sym ([]ᵐ-[]ⁱ ([ 𝟘-initial ]ʳ f S)))
[∘ᵐ] (expr-meta M ts) = ≈-meta (λ i → [∘ᵐ] (ts i))
[∘ᵐ] expr-eqty = ≈-eqty
[∘ᵐ] expr-eqtm = ≈-eqtm
-- Associativity of composition
assocᵐ : ∀ {𝕊 𝕋 𝕌 𝕍} {f : 𝕊 →ᵐ 𝕋} {g : 𝕋 →ᵐ 𝕌} {h : 𝕌 →ᵐ 𝕍} →
(h ∘ᵐ g) ∘ᵐ f ≈ᵐ h ∘ᵐ (g ∘ᵐ f)
assocᵐ {f = f} S = [∘ᵐ] (f S)
-- The category of signatures and syntax maps
module _ where
open Categories.Category
SyntaxMaps : Category (suc zero) zero zero
SyntaxMaps =
record
{ Obj = Signature
; _⇒_ = _→ᵐ_
; _≈_ = _≈ᵐ_
; id = 𝟙ᵐ
; _∘_ = _∘ᵐ_
; assoc = λ {_} {_} {_} {_} {f} {_} {_} {_} S → [∘ᵐ] (f S)
; sym-assoc = λ {_} {_} {_} {𝕍} {f} {_} {_} {_} S → ≈-sym ([∘ᵐ] (f S))
; identityˡ = λ S → [𝟙ᵐ] _
; identityʳ = λ {_} {_} {f} {_} → 𝟙ᵐ-right {f = f}
; identity² = λ _ → [𝟙ᵐ] _
; equiv = record { refl = λ _ → ≈-refl ; sym = ≈ᵐ-sym ; trans = ≈ᵐ-trans }
; ∘-resp-≈ = λ ζ ξ S → []ᵐ-resp-≈ᵐ-≈ ζ (ξ S)
}
|
# this script will convert a DarwinCore taxonomy file to an Arctos hierarchical taxonomy upload file
# add libraries
library(readxl)
library(data.table)
# Replace "~/GitHub/arctos_r/input/filename.xlsx" with the file name and directory where the file to be converted is found
df <- read_excel("~/GitHub/arctos-r/input/filename.xlsx",
col_types = c("text", "numeric", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric", "numeric",
"text", "text", "text", "text", "numeric",
"numeric", "numeric", "numeric",
"text", "text", "text", "text", "text",
"text", "text", "text", "text", "text",
"text", "numeric", "text", "numeric",
"text", "text", "text", "text", "text")) #read in DwC file to transform
names(df)[names(df) == 'canonicalName'] <- 'scientific_name' #change canonicalName to scientific_name
names(df)[names(df) == 'taxonRank'] <- 'name_rank' #change taxonRank to taxon_rank
# get parent name if not supplied
for(i in 1:nrow(df)){
df$parentNameUsage[i] <- ifelse(!is.na(df$parentNameUsage[i]), df$parentNameUsage[i], # use parentNameUsage is available
ifelse(is.na(df$name_rank[i]), NA, # if both parentNameUsage and taxon_rank are blank, insert NA
ifelse(df$name_rank[i] == "subspecies", df$specificEpithet[i],
ifelse(df$name_rank[i] == "species", ifelse(is.na(df$subgenus[i]), df$genus[i], df$subgenus[i]) ,# if name rank is species and there is no subgenus, insert genus, otherwise insert genus
ifelse(df$name_rank[i] == "subgenus", df$genus[i], # if name rank is species, insert genus
ifelse(df$name_rank[i] == "genus", df$family[i], #if name rank is genus, insert family
ifelse(df$name_rank[i] == "family", df$order[i], #if name rank is family, insert order
NA)) # otherwise NA
)
)
)
)
)
}
names(df)[names(df) == 'parentNameUsage'] <- 'parent_name'
# replace "user" with the Arctos username of the person who will upload the file
df$username <- "user" # fill in username
# replace "filename"hierarchy" with the name of the hierarchy to be uploaded
df$hierarchy_name <- "hierarchy" # fill in hierarchy name
names(df)[names(df) == 'scientificNameAuthorship'] <- 'noclass_term_1' # change column with scientifcNameAuthorship to no_class_term_1
df$noclass_term_type_1 <- ifelse(!is.na(df$noclass_term_1), 'author_text', NA) #set fourth non classification term to "author_text" if no_class_term_1 is not NA
names(df)[names(df) == 'nomenclaturalCode'] <- 'noclass_term_2' # change column with nomenclaturalCode to no_class_term_2
df$noclass_term_2 <- ifelse(is.na(df$noclass_term_2), 'ICZN', df$noclass_term_2) # set all nomenclatural code terms
df$noclass_term_type_2 <- ifelse(!is.na(df$noclass_term_2), 'nomenclatural_code', NA) # set second non classification term type to nomenclatural_code
df$noclass_term_type_3 <- 'source_authority' # set third non classification term to source_authority
df$noclass_term_3 <- 'Terrestrial Parasite Tracker Thematic Collection Network' # set third non classification term to Terrestrial Parasite Tracker Thematic Collection Network
names(df)[names(df) == 'taxonRemarks'] <- 'noclass_term_4' # change column with taxonRemark to no_class_term_4
df$noclass_term_type_4 <- ifelse(!is.na(df$noclass_term_4), 'taxon_remark', NA) #set fourth non classification term to taxon_remark if no_class_term_4 is not NA
names(df)[names(df) == 'taxonomicStatus'] <- 'noclass_term_5' # change column with to no_class_term_5
df$noclass_term_type_5 <- ifelse(!is.na(df$noclass_term_5), 'taxon_status', NA) #set fourth non classification term to taxon_status if no_class_term_5 is not NA
df$noclass_term_5 <- ifelse(df$noclass_term_5 == 'accepted', 'valid', df$noclass_term_5) # adjust to Arctos code table terms
names(df)[names(df) == 'acceptedNameUsage'] <- 'noclass_term_6' # change accepteNameUsage to preferred_name
df$noclass_term_type_6 <- ifelse(!is.na(df$noclass_term_6), 'preferred_name', NA) #set fourth non classification term to preferred_name if no_class_term_6 is not NA
# dealing with duplicates
df$reason <- c(ifelse(duplicated(df$scientific_name, fromLast = TRUE) | duplicated(df$scientific_name),
"dupe", NA)) # Flag internal dupes
dupes <- df[which(grepl('dupe',df$reason) == TRUE), ] # get all duplicates
dupes <- df[which(duplicated(df$scientificName, fromLast = TRUE) | duplicated(df$scientificName)),] # only keep those with duplicated scientific names
# order column names
# df[,c(1,2,3,4)]. Note the first comma means keep all the rows, and the 1,2,3,4 refers to the columns.
columns <- df[, colnames(df)[c(grepl("^noclass_term", colnames(df)))]]
df1 <- subset(df, select = grep("^noclass_term", names(df)))
Arctos_upload <- df[,c("username",
"hierarchy_name",
"scientific_name",
"name_rank",
"parent_name",
"noclass_term_type_1",
"noclass_term_1",
"noclass_term_type_2",
"noclass_term_2",
"noclass_term_type_3",
"noclass_term_3",
"noclass_term_type_4",
"noclass_term_4",
"noclass_term_type_5",
"noclass_term_5",
"noclass_term_type_6",
"noclass_term_6"
)
]
# replace "~/GitHub/arctos_r/output/Arctos_upload.csv" with the directrory and filename to save the csv to
write.csv(Arctos_upload,"~/GitHub/arctos_r/output/Arctos_upload.csv", row.names = FALSE) # write out csv for upload
|
[GOAL]
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
⊢ IsSquare 2 ↔ Fintype.card F % 8 ≠ 3 ∧ Fintype.card F % 8 ≠ 5
[PROOFSTEP]
classical
by_cases hF : ringChar F = 2
focus
have h := FiniteField.even_card_of_char_two hF
simp only [FiniteField.isSquare_of_char_two hF, true_iff_iff]
rotate_left
focus
have h := FiniteField.odd_card_of_char_ne_two hF
rw [← quadraticChar_one_iff_isSquare (Ring.two_ne_zero hF), quadraticChar_two hF, χ₈_nat_eq_if_mod_eight]
simp only [h, Nat.one_ne_zero, if_false, ite_eq_left_iff, Ne.def, (by decide : (-1 : ℤ) ≠ 1), imp_false,
Classical.not_not]
all_goals
rw [← Nat.mod_mod_of_dvd _ (by norm_num : 2 ∣ 8)] at h
have h₁ := Nat.mod_lt (Fintype.card F) (by decide : 0 < 8)
revert h₁ h
generalize Fintype.card F % 8 = n
intros;
interval_cases n <;>
simp_all
-- Porting note: was `decide!`
[GOAL]
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
⊢ IsSquare 2 ↔ Fintype.card F % 8 ≠ 3 ∧ Fintype.card F % 8 ≠ 5
[PROOFSTEP]
by_cases hF : ringChar F = 2
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
⊢ IsSquare 2 ↔ Fintype.card F % 8 ≠ 3 ∧ Fintype.card F % 8 ≠ 5
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
⊢ IsSquare 2 ↔ Fintype.card F % 8 ≠ 3 ∧ Fintype.card F % 8 ≠ 5
[PROOFSTEP]
focus
have h := FiniteField.even_card_of_char_two hF
simp only [FiniteField.isSquare_of_char_two hF, true_iff_iff]
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
⊢ IsSquare 2 ↔ Fintype.card F % 8 ≠ 3 ∧ Fintype.card F % 8 ≠ 5
[PROOFSTEP]
have h := FiniteField.even_card_of_char_two hF
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
h : Fintype.card F % 2 = 0
⊢ IsSquare 2 ↔ Fintype.card F % 8 ≠ 3 ∧ Fintype.card F % 8 ≠ 5
[PROOFSTEP]
simp only [FiniteField.isSquare_of_char_two hF, true_iff_iff]
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
h : Fintype.card F % 2 = 0
⊢ Fintype.card F % 8 ≠ 3 ∧ Fintype.card F % 8 ≠ 5
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
⊢ IsSquare 2 ↔ Fintype.card F % 8 ≠ 3 ∧ Fintype.card F % 8 ≠ 5
[PROOFSTEP]
rotate_left
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
⊢ IsSquare 2 ↔ Fintype.card F % 8 ≠ 3 ∧ Fintype.card F % 8 ≠ 5
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
h : Fintype.card F % 2 = 0
⊢ Fintype.card F % 8 ≠ 3 ∧ Fintype.card F % 8 ≠ 5
[PROOFSTEP]
focus
have h := FiniteField.odd_card_of_char_ne_two hF
rw [← quadraticChar_one_iff_isSquare (Ring.two_ne_zero hF), quadraticChar_two hF, χ₈_nat_eq_if_mod_eight]
simp only [h, Nat.one_ne_zero, if_false, ite_eq_left_iff, Ne.def, (by decide : (-1 : ℤ) ≠ 1), imp_false,
Classical.not_not]
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
⊢ IsSquare 2 ↔ Fintype.card F % 8 ≠ 3 ∧ Fintype.card F % 8 ≠ 5
[PROOFSTEP]
have h := FiniteField.odd_card_of_char_ne_two hF
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
h : Fintype.card F % 2 = 1
⊢ IsSquare 2 ↔ Fintype.card F % 8 ≠ 3 ∧ Fintype.card F % 8 ≠ 5
[PROOFSTEP]
rw [← quadraticChar_one_iff_isSquare (Ring.two_ne_zero hF), quadraticChar_two hF, χ₈_nat_eq_if_mod_eight]
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
h : Fintype.card F % 2 = 1
⊢ (if Fintype.card F % 2 = 0 then 0 else if Fintype.card F % 8 = 1 ∨ Fintype.card F % 8 = 7 then 1 else -1) = 1 ↔
Fintype.card F % 8 ≠ 3 ∧ Fintype.card F % 8 ≠ 5
[PROOFSTEP]
simp only [h, Nat.one_ne_zero, if_false, ite_eq_left_iff, Ne.def, (by decide : (-1 : ℤ) ≠ 1), imp_false,
Classical.not_not]
[GOAL]
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
h : Fintype.card F % 2 = 1
⊢ -1 ≠ 1
[PROOFSTEP]
decide
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
h : Fintype.card F % 2 = 1
⊢ Fintype.card F % 8 = 1 ∨ Fintype.card F % 8 = 7 ↔ ¬Fintype.card F % 8 = 3 ∧ ¬Fintype.card F % 8 = 5
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
h : Fintype.card F % 2 = 0
⊢ Fintype.card F % 8 ≠ 3 ∧ Fintype.card F % 8 ≠ 5
[PROOFSTEP]
all_goals
rw [← Nat.mod_mod_of_dvd _ (by norm_num : 2 ∣ 8)] at h
have h₁ := Nat.mod_lt (Fintype.card F) (by decide : 0 < 8)
revert h₁ h
generalize Fintype.card F % 8 = n
intros;
interval_cases n <;>
simp_all
-- Porting note: was `decide!`
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
h : Fintype.card F % 2 = 1
⊢ Fintype.card F % 8 = 1 ∨ Fintype.card F % 8 = 7 ↔ ¬Fintype.card F % 8 = 3 ∧ ¬Fintype.card F % 8 = 5
[PROOFSTEP]
rw [← Nat.mod_mod_of_dvd _ (by norm_num : 2 ∣ 8)] at h
[GOAL]
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
h : Fintype.card F % 2 = 1
⊢ 2 ∣ 8
[PROOFSTEP]
norm_num
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
h : Fintype.card F % 8 % 2 = 1
⊢ Fintype.card F % 8 = 1 ∨ Fintype.card F % 8 = 7 ↔ ¬Fintype.card F % 8 = 3 ∧ ¬Fintype.card F % 8 = 5
[PROOFSTEP]
have h₁ := Nat.mod_lt (Fintype.card F) (by decide : 0 < 8)
[GOAL]
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
h : Fintype.card F % 8 % 2 = 1
⊢ 0 < 8
[PROOFSTEP]
decide
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
h : Fintype.card F % 8 % 2 = 1
h₁ : Fintype.card F % 8 < 8
⊢ Fintype.card F % 8 = 1 ∨ Fintype.card F % 8 = 7 ↔ ¬Fintype.card F % 8 = 3 ∧ ¬Fintype.card F % 8 = 5
[PROOFSTEP]
revert h₁ h
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
⊢ Fintype.card F % 8 % 2 = 1 →
Fintype.card F % 8 < 8 →
(Fintype.card F % 8 = 1 ∨ Fintype.card F % 8 = 7 ↔ ¬Fintype.card F % 8 = 3 ∧ ¬Fintype.card F % 8 = 5)
[PROOFSTEP]
generalize Fintype.card F % 8 = n
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
⊢ n % 2 = 1 → n < 8 → (n = 1 ∨ n = 7 ↔ ¬n = 3 ∧ ¬n = 5)
[PROOFSTEP]
intros
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
h✝ : n % 2 = 1
h₁✝ : n < 8
⊢ n = 1 ∨ n = 7 ↔ ¬n = 3 ∧ ¬n = 5
[PROOFSTEP]
interval_cases n
[GOAL]
case neg.«0»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
h✝ : 0 % 2 = 1
h₁✝ : 0 < 8
⊢ 0 = 1 ∨ 0 = 7 ↔ ¬0 = 3 ∧ ¬0 = 5
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case neg.«1»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
h✝ : 1 % 2 = 1
h₁✝ : 1 < 8
⊢ 1 = 1 ∨ 1 = 7 ↔ ¬1 = 3 ∧ ¬1 = 5
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case neg.«2»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
h✝ : 2 % 2 = 1
h₁✝ : 2 < 8
⊢ 2 = 1 ∨ 2 = 7 ↔ ¬2 = 3 ∧ ¬2 = 5
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case neg.«3»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
h✝ : 3 % 2 = 1
h₁✝ : 3 < 8
⊢ 3 = 1 ∨ 3 = 7 ↔ ¬3 = 3 ∧ ¬3 = 5
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case neg.«4»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
h✝ : 4 % 2 = 1
h₁✝ : 4 < 8
⊢ 4 = 1 ∨ 4 = 7 ↔ ¬4 = 3 ∧ ¬4 = 5
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case neg.«5»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
h✝ : 5 % 2 = 1
h₁✝ : 5 < 8
⊢ 5 = 1 ∨ 5 = 7 ↔ ¬5 = 3 ∧ ¬5 = 5
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case neg.«6»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
h✝ : 6 % 2 = 1
h₁✝ : 6 < 8
⊢ 6 = 1 ∨ 6 = 7 ↔ ¬6 = 3 ∧ ¬6 = 5
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case neg.«7»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
h✝ : 7 % 2 = 1
h₁✝ : 7 < 8
⊢ 7 = 1 ∨ 7 = 7 ↔ ¬7 = 3 ∧ ¬7 = 5
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
h : Fintype.card F % 2 = 0
⊢ Fintype.card F % 8 ≠ 3 ∧ Fintype.card F % 8 ≠ 5
[PROOFSTEP]
rw [← Nat.mod_mod_of_dvd _ (by norm_num : 2 ∣ 8)] at h
[GOAL]
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
h : Fintype.card F % 2 = 0
⊢ 2 ∣ 8
[PROOFSTEP]
norm_num
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
h : Fintype.card F % 8 % 2 = 0
⊢ Fintype.card F % 8 ≠ 3 ∧ Fintype.card F % 8 ≠ 5
[PROOFSTEP]
have h₁ := Nat.mod_lt (Fintype.card F) (by decide : 0 < 8)
[GOAL]
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
h : Fintype.card F % 8 % 2 = 0
⊢ 0 < 8
[PROOFSTEP]
decide
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
h : Fintype.card F % 8 % 2 = 0
h₁ : Fintype.card F % 8 < 8
⊢ Fintype.card F % 8 ≠ 3 ∧ Fintype.card F % 8 ≠ 5
[PROOFSTEP]
revert h₁ h
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
⊢ Fintype.card F % 8 % 2 = 0 → Fintype.card F % 8 < 8 → Fintype.card F % 8 ≠ 3 ∧ Fintype.card F % 8 ≠ 5
[PROOFSTEP]
generalize Fintype.card F % 8 = n
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
⊢ n % 2 = 0 → n < 8 → n ≠ 3 ∧ n ≠ 5
[PROOFSTEP]
intros
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
h✝ : n % 2 = 0
h₁✝ : n < 8
⊢ n ≠ 3 ∧ n ≠ 5
[PROOFSTEP]
interval_cases n
[GOAL]
case pos.«0»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
h✝ : 0 % 2 = 0
h₁✝ : 0 < 8
⊢ 0 ≠ 3 ∧ 0 ≠ 5
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case pos.«1»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
h✝ : 1 % 2 = 0
h₁✝ : 1 < 8
⊢ 1 ≠ 3 ∧ 1 ≠ 5
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case pos.«2»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
h✝ : 2 % 2 = 0
h₁✝ : 2 < 8
⊢ 2 ≠ 3 ∧ 2 ≠ 5
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case pos.«3»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
h✝ : 3 % 2 = 0
h₁✝ : 3 < 8
⊢ 3 ≠ 3 ∧ 3 ≠ 5
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case pos.«4»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
h✝ : 4 % 2 = 0
h₁✝ : 4 < 8
⊢ 4 ≠ 3 ∧ 4 ≠ 5
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case pos.«5»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
h✝ : 5 % 2 = 0
h₁✝ : 5 < 8
⊢ 5 ≠ 3 ∧ 5 ≠ 5
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case pos.«6»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
h✝ : 6 % 2 = 0
h₁✝ : 6 < 8
⊢ 6 ≠ 3 ∧ 6 ≠ 5
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case pos.«7»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
h✝ : 7 % 2 = 0
h₁✝ : 7 < 8
⊢ 7 ≠ 3 ∧ 7 ≠ 5
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
inst✝ : DecidableEq F
hF : ringChar F ≠ 2
⊢ ↑(quadraticChar F) (-2) = ↑χ₈' ↑(Fintype.card F)
[PROOFSTEP]
rw [(by norm_num : (-2 : F) = -1 * 2), map_mul, χ₈'_eq_χ₄_mul_χ₈, quadraticChar_neg_one hF, quadraticChar_two hF,
@cast_nat_cast _ (ZMod 4) _ _ _ (by norm_num : 4 ∣ 8)]
[GOAL]
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
inst✝ : DecidableEq F
hF : ringChar F ≠ 2
⊢ -2 = -1 * 2
[PROOFSTEP]
norm_num
[GOAL]
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
inst✝ : DecidableEq F
hF : ringChar F ≠ 2
⊢ 4 ∣ 8
[PROOFSTEP]
norm_num
[GOAL]
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
⊢ IsSquare (-2) ↔ Fintype.card F % 8 ≠ 5 ∧ Fintype.card F % 8 ≠ 7
[PROOFSTEP]
classical
by_cases hF : ringChar F = 2
focus
have h := FiniteField.even_card_of_char_two hF
simp only [FiniteField.isSquare_of_char_two hF, true_iff_iff]
rotate_left
focus
have h := FiniteField.odd_card_of_char_ne_two hF
rw [← quadraticChar_one_iff_isSquare (neg_ne_zero.mpr (Ring.two_ne_zero hF)), quadraticChar_neg_two hF,
χ₈'_nat_eq_if_mod_eight]
simp only [h, Nat.one_ne_zero, if_false, ite_eq_left_iff, Ne.def, (by decide : (-1 : ℤ) ≠ 1), imp_false,
Classical.not_not]
all_goals
rw [← Nat.mod_mod_of_dvd _ (by norm_num : 2 ∣ 8)] at h
have h₁ := Nat.mod_lt (Fintype.card F) (by decide : 0 < 8)
revert h₁ h
generalize Fintype.card F % 8 = n
intros;
interval_cases n <;>
simp_all
-- Porting note: was `decide!`
[GOAL]
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
⊢ IsSquare (-2) ↔ Fintype.card F % 8 ≠ 5 ∧ Fintype.card F % 8 ≠ 7
[PROOFSTEP]
by_cases hF : ringChar F = 2
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
⊢ IsSquare (-2) ↔ Fintype.card F % 8 ≠ 5 ∧ Fintype.card F % 8 ≠ 7
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
⊢ IsSquare (-2) ↔ Fintype.card F % 8 ≠ 5 ∧ Fintype.card F % 8 ≠ 7
[PROOFSTEP]
focus
have h := FiniteField.even_card_of_char_two hF
simp only [FiniteField.isSquare_of_char_two hF, true_iff_iff]
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
⊢ IsSquare (-2) ↔ Fintype.card F % 8 ≠ 5 ∧ Fintype.card F % 8 ≠ 7
[PROOFSTEP]
have h := FiniteField.even_card_of_char_two hF
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
h : Fintype.card F % 2 = 0
⊢ IsSquare (-2) ↔ Fintype.card F % 8 ≠ 5 ∧ Fintype.card F % 8 ≠ 7
[PROOFSTEP]
simp only [FiniteField.isSquare_of_char_two hF, true_iff_iff]
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
h : Fintype.card F % 2 = 0
⊢ Fintype.card F % 8 ≠ 5 ∧ Fintype.card F % 8 ≠ 7
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
⊢ IsSquare (-2) ↔ Fintype.card F % 8 ≠ 5 ∧ Fintype.card F % 8 ≠ 7
[PROOFSTEP]
rotate_left
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
⊢ IsSquare (-2) ↔ Fintype.card F % 8 ≠ 5 ∧ Fintype.card F % 8 ≠ 7
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
h : Fintype.card F % 2 = 0
⊢ Fintype.card F % 8 ≠ 5 ∧ Fintype.card F % 8 ≠ 7
[PROOFSTEP]
focus
have h := FiniteField.odd_card_of_char_ne_two hF
rw [← quadraticChar_one_iff_isSquare (neg_ne_zero.mpr (Ring.two_ne_zero hF)), quadraticChar_neg_two hF,
χ₈'_nat_eq_if_mod_eight]
simp only [h, Nat.one_ne_zero, if_false, ite_eq_left_iff, Ne.def, (by decide : (-1 : ℤ) ≠ 1), imp_false,
Classical.not_not]
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
⊢ IsSquare (-2) ↔ Fintype.card F % 8 ≠ 5 ∧ Fintype.card F % 8 ≠ 7
[PROOFSTEP]
have h := FiniteField.odd_card_of_char_ne_two hF
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
h : Fintype.card F % 2 = 1
⊢ IsSquare (-2) ↔ Fintype.card F % 8 ≠ 5 ∧ Fintype.card F % 8 ≠ 7
[PROOFSTEP]
rw [← quadraticChar_one_iff_isSquare (neg_ne_zero.mpr (Ring.two_ne_zero hF)), quadraticChar_neg_two hF,
χ₈'_nat_eq_if_mod_eight]
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
h : Fintype.card F % 2 = 1
⊢ (if Fintype.card F % 2 = 0 then 0 else if Fintype.card F % 8 = 1 ∨ Fintype.card F % 8 = 3 then 1 else -1) = 1 ↔
Fintype.card F % 8 ≠ 5 ∧ Fintype.card F % 8 ≠ 7
[PROOFSTEP]
simp only [h, Nat.one_ne_zero, if_false, ite_eq_left_iff, Ne.def, (by decide : (-1 : ℤ) ≠ 1), imp_false,
Classical.not_not]
[GOAL]
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
h : Fintype.card F % 2 = 1
⊢ -1 ≠ 1
[PROOFSTEP]
decide
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
h : Fintype.card F % 2 = 1
⊢ Fintype.card F % 8 = 1 ∨ Fintype.card F % 8 = 3 ↔ ¬Fintype.card F % 8 = 5 ∧ ¬Fintype.card F % 8 = 7
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
h : Fintype.card F % 2 = 0
⊢ Fintype.card F % 8 ≠ 5 ∧ Fintype.card F % 8 ≠ 7
[PROOFSTEP]
all_goals
rw [← Nat.mod_mod_of_dvd _ (by norm_num : 2 ∣ 8)] at h
have h₁ := Nat.mod_lt (Fintype.card F) (by decide : 0 < 8)
revert h₁ h
generalize Fintype.card F % 8 = n
intros;
interval_cases n <;>
simp_all
-- Porting note: was `decide!`
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
h : Fintype.card F % 2 = 1
⊢ Fintype.card F % 8 = 1 ∨ Fintype.card F % 8 = 3 ↔ ¬Fintype.card F % 8 = 5 ∧ ¬Fintype.card F % 8 = 7
[PROOFSTEP]
rw [← Nat.mod_mod_of_dvd _ (by norm_num : 2 ∣ 8)] at h
[GOAL]
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
h : Fintype.card F % 2 = 1
⊢ 2 ∣ 8
[PROOFSTEP]
norm_num
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
h : Fintype.card F % 8 % 2 = 1
⊢ Fintype.card F % 8 = 1 ∨ Fintype.card F % 8 = 3 ↔ ¬Fintype.card F % 8 = 5 ∧ ¬Fintype.card F % 8 = 7
[PROOFSTEP]
have h₁ := Nat.mod_lt (Fintype.card F) (by decide : 0 < 8)
[GOAL]
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
h : Fintype.card F % 8 % 2 = 1
⊢ 0 < 8
[PROOFSTEP]
decide
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
h : Fintype.card F % 8 % 2 = 1
h₁ : Fintype.card F % 8 < 8
⊢ Fintype.card F % 8 = 1 ∨ Fintype.card F % 8 = 3 ↔ ¬Fintype.card F % 8 = 5 ∧ ¬Fintype.card F % 8 = 7
[PROOFSTEP]
revert h₁ h
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
⊢ Fintype.card F % 8 % 2 = 1 →
Fintype.card F % 8 < 8 →
(Fintype.card F % 8 = 1 ∨ Fintype.card F % 8 = 3 ↔ ¬Fintype.card F % 8 = 5 ∧ ¬Fintype.card F % 8 = 7)
[PROOFSTEP]
generalize Fintype.card F % 8 = n
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
⊢ n % 2 = 1 → n < 8 → (n = 1 ∨ n = 3 ↔ ¬n = 5 ∧ ¬n = 7)
[PROOFSTEP]
intros
[GOAL]
case neg
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
h✝ : n % 2 = 1
h₁✝ : n < 8
⊢ n = 1 ∨ n = 3 ↔ ¬n = 5 ∧ ¬n = 7
[PROOFSTEP]
interval_cases n
[GOAL]
case neg.«0»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
h✝ : 0 % 2 = 1
h₁✝ : 0 < 8
⊢ 0 = 1 ∨ 0 = 3 ↔ ¬0 = 5 ∧ ¬0 = 7
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case neg.«1»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
h✝ : 1 % 2 = 1
h₁✝ : 1 < 8
⊢ 1 = 1 ∨ 1 = 3 ↔ ¬1 = 5 ∧ ¬1 = 7
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case neg.«2»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
h✝ : 2 % 2 = 1
h₁✝ : 2 < 8
⊢ 2 = 1 ∨ 2 = 3 ↔ ¬2 = 5 ∧ ¬2 = 7
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case neg.«3»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
h✝ : 3 % 2 = 1
h₁✝ : 3 < 8
⊢ 3 = 1 ∨ 3 = 3 ↔ ¬3 = 5 ∧ ¬3 = 7
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case neg.«4»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
h✝ : 4 % 2 = 1
h₁✝ : 4 < 8
⊢ 4 = 1 ∨ 4 = 3 ↔ ¬4 = 5 ∧ ¬4 = 7
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case neg.«5»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
h✝ : 5 % 2 = 1
h₁✝ : 5 < 8
⊢ 5 = 1 ∨ 5 = 3 ↔ ¬5 = 5 ∧ ¬5 = 7
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case neg.«6»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
h✝ : 6 % 2 = 1
h₁✝ : 6 < 8
⊢ 6 = 1 ∨ 6 = 3 ↔ ¬6 = 5 ∧ ¬6 = 7
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case neg.«7»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ¬ringChar F = 2
n : ℕ
h✝ : 7 % 2 = 1
h₁✝ : 7 < 8
⊢ 7 = 1 ∨ 7 = 3 ↔ ¬7 = 5 ∧ ¬7 = 7
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
h : Fintype.card F % 2 = 0
⊢ Fintype.card F % 8 ≠ 5 ∧ Fintype.card F % 8 ≠ 7
[PROOFSTEP]
rw [← Nat.mod_mod_of_dvd _ (by norm_num : 2 ∣ 8)] at h
[GOAL]
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
h : Fintype.card F % 2 = 0
⊢ 2 ∣ 8
[PROOFSTEP]
norm_num
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
h : Fintype.card F % 8 % 2 = 0
⊢ Fintype.card F % 8 ≠ 5 ∧ Fintype.card F % 8 ≠ 7
[PROOFSTEP]
have h₁ := Nat.mod_lt (Fintype.card F) (by decide : 0 < 8)
[GOAL]
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
h : Fintype.card F % 8 % 2 = 0
⊢ 0 < 8
[PROOFSTEP]
decide
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
h : Fintype.card F % 8 % 2 = 0
h₁ : Fintype.card F % 8 < 8
⊢ Fintype.card F % 8 ≠ 5 ∧ Fintype.card F % 8 ≠ 7
[PROOFSTEP]
revert h₁ h
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
⊢ Fintype.card F % 8 % 2 = 0 → Fintype.card F % 8 < 8 → Fintype.card F % 8 ≠ 5 ∧ Fintype.card F % 8 ≠ 7
[PROOFSTEP]
generalize Fintype.card F % 8 = n
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
⊢ n % 2 = 0 → n < 8 → n ≠ 5 ∧ n ≠ 7
[PROOFSTEP]
intros
[GOAL]
case pos
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
h✝ : n % 2 = 0
h₁✝ : n < 8
⊢ n ≠ 5 ∧ n ≠ 7
[PROOFSTEP]
interval_cases n
[GOAL]
case pos.«0»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
h✝ : 0 % 2 = 0
h₁✝ : 0 < 8
⊢ 0 ≠ 5 ∧ 0 ≠ 7
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case pos.«1»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
h✝ : 1 % 2 = 0
h₁✝ : 1 < 8
⊢ 1 ≠ 5 ∧ 1 ≠ 7
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case pos.«2»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
h✝ : 2 % 2 = 0
h₁✝ : 2 < 8
⊢ 2 ≠ 5 ∧ 2 ≠ 7
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case pos.«3»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
h✝ : 3 % 2 = 0
h₁✝ : 3 < 8
⊢ 3 ≠ 5 ∧ 3 ≠ 7
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case pos.«4»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
h✝ : 4 % 2 = 0
h₁✝ : 4 < 8
⊢ 4 ≠ 5 ∧ 4 ≠ 7
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case pos.«5»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
h✝ : 5 % 2 = 0
h₁✝ : 5 < 8
⊢ 5 ≠ 5 ∧ 5 ≠ 7
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case pos.«6»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
h✝ : 6 % 2 = 0
h₁✝ : 6 < 8
⊢ 6 ≠ 5 ∧ 6 ≠ 7
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
case pos.«7»
F : Type u_1
inst✝¹ : Field F
inst✝ : Fintype F
hF : ringChar F = 2
n : ℕ
h✝ : 7 % 2 = 0
h₁✝ : 7 < 8
⊢ 7 ≠ 5 ∧ 7 ≠ 7
[PROOFSTEP]
simp_all
-- Porting note: was `decide!`
[GOAL]
F : Type u_1
inst✝⁵ : Field F
inst✝⁴ : Fintype F
inst✝³ : DecidableEq F
hF : ringChar F ≠ 2
F' : Type u_2
inst✝² : Field F'
inst✝¹ : Fintype F'
inst✝ : DecidableEq F'
hF' : ringChar F' ≠ 2
h : ringChar F' ≠ ringChar F
⊢ ↑(quadraticChar F) ↑(Fintype.card F') = ↑(quadraticChar F') (↑(↑(quadraticChar F) (-1)) * ↑(Fintype.card F))
[PROOFSTEP]
let χ := (quadraticChar F).ringHomComp (algebraMap ℤ F')
[GOAL]
F : Type u_1
inst✝⁵ : Field F
inst✝⁴ : Fintype F
inst✝³ : DecidableEq F
hF : ringChar F ≠ 2
F' : Type u_2
inst✝² : Field F'
inst✝¹ : Fintype F'
inst✝ : DecidableEq F'
hF' : ringChar F' ≠ 2
h : ringChar F' ≠ ringChar F
χ : MulChar F F' := ringHomComp (quadraticChar F) (algebraMap ℤ F')
⊢ ↑(quadraticChar F) ↑(Fintype.card F') = ↑(quadraticChar F') (↑(↑(quadraticChar F) (-1)) * ↑(Fintype.card F))
[PROOFSTEP]
have hχ₁ : χ.IsNontrivial := by
obtain ⟨a, ha⟩ := quadraticChar_exists_neg_one hF
have hu : IsUnit a := by
contrapose ha
exact ne_of_eq_of_ne (map_nonunit (quadraticChar F) ha) (mt zero_eq_neg.mp one_ne_zero)
use hu.unit
simp only [IsUnit.unit_spec, ringHomComp_apply, eq_intCast, Ne.def, ha]
rw [Int.cast_neg, Int.cast_one]
exact Ring.neg_one_ne_one_of_char_ne_two hF'
[GOAL]
F : Type u_1
inst✝⁵ : Field F
inst✝⁴ : Fintype F
inst✝³ : DecidableEq F
hF : ringChar F ≠ 2
F' : Type u_2
inst✝² : Field F'
inst✝¹ : Fintype F'
inst✝ : DecidableEq F'
hF' : ringChar F' ≠ 2
h : ringChar F' ≠ ringChar F
χ : MulChar F F' := ringHomComp (quadraticChar F) (algebraMap ℤ F')
⊢ IsNontrivial χ
[PROOFSTEP]
obtain ⟨a, ha⟩ := quadraticChar_exists_neg_one hF
[GOAL]
case intro
F : Type u_1
inst✝⁵ : Field F
inst✝⁴ : Fintype F
inst✝³ : DecidableEq F
hF : ringChar F ≠ 2
F' : Type u_2
inst✝² : Field F'
inst✝¹ : Fintype F'
inst✝ : DecidableEq F'
hF' : ringChar F' ≠ 2
h : ringChar F' ≠ ringChar F
χ : MulChar F F' := ringHomComp (quadraticChar F) (algebraMap ℤ F')
a : F
ha : ↑(quadraticChar F) a = -1
⊢ IsNontrivial χ
[PROOFSTEP]
have hu : IsUnit a := by
contrapose ha
exact ne_of_eq_of_ne (map_nonunit (quadraticChar F) ha) (mt zero_eq_neg.mp one_ne_zero)
[GOAL]
F : Type u_1
inst✝⁵ : Field F
inst✝⁴ : Fintype F
inst✝³ : DecidableEq F
hF : ringChar F ≠ 2
F' : Type u_2
inst✝² : Field F'
inst✝¹ : Fintype F'
inst✝ : DecidableEq F'
hF' : ringChar F' ≠ 2
h : ringChar F' ≠ ringChar F
χ : MulChar F F' := ringHomComp (quadraticChar F) (algebraMap ℤ F')
a : F
ha : ↑(quadraticChar F) a = -1
⊢ IsUnit a
[PROOFSTEP]
contrapose ha
[GOAL]
F : Type u_1
inst✝⁵ : Field F
inst✝⁴ : Fintype F
inst✝³ : DecidableEq F
hF : ringChar F ≠ 2
F' : Type u_2
inst✝² : Field F'
inst✝¹ : Fintype F'
inst✝ : DecidableEq F'
hF' : ringChar F' ≠ 2
h : ringChar F' ≠ ringChar F
χ : MulChar F F' := ringHomComp (quadraticChar F) (algebraMap ℤ F')
a : F
ha : ¬IsUnit a
⊢ ¬↑(quadraticChar F) a = -1
[PROOFSTEP]
exact ne_of_eq_of_ne (map_nonunit (quadraticChar F) ha) (mt zero_eq_neg.mp one_ne_zero)
[GOAL]
case intro
F : Type u_1
inst✝⁵ : Field F
inst✝⁴ : Fintype F
inst✝³ : DecidableEq F
hF : ringChar F ≠ 2
F' : Type u_2
inst✝² : Field F'
inst✝¹ : Fintype F'
inst✝ : DecidableEq F'
hF' : ringChar F' ≠ 2
h : ringChar F' ≠ ringChar F
χ : MulChar F F' := ringHomComp (quadraticChar F) (algebraMap ℤ F')
a : F
ha : ↑(quadraticChar F) a = -1
hu : IsUnit a
⊢ IsNontrivial χ
[PROOFSTEP]
use hu.unit
[GOAL]
case h
F : Type u_1
inst✝⁵ : Field F
inst✝⁴ : Fintype F
inst✝³ : DecidableEq F
hF : ringChar F ≠ 2
F' : Type u_2
inst✝² : Field F'
inst✝¹ : Fintype F'
inst✝ : DecidableEq F'
hF' : ringChar F' ≠ 2
h : ringChar F' ≠ ringChar F
χ : MulChar F F' := ringHomComp (quadraticChar F) (algebraMap ℤ F')
a : F
ha : ↑(quadraticChar F) a = -1
hu : IsUnit a
⊢ ↑χ ↑(IsUnit.unit hu) ≠ 1
[PROOFSTEP]
simp only [IsUnit.unit_spec, ringHomComp_apply, eq_intCast, Ne.def, ha]
[GOAL]
case h
F : Type u_1
inst✝⁵ : Field F
inst✝⁴ : Fintype F
inst✝³ : DecidableEq F
hF : ringChar F ≠ 2
F' : Type u_2
inst✝² : Field F'
inst✝¹ : Fintype F'
inst✝ : DecidableEq F'
hF' : ringChar F' ≠ 2
h : ringChar F' ≠ ringChar F
χ : MulChar F F' := ringHomComp (quadraticChar F) (algebraMap ℤ F')
a : F
ha : ↑(quadraticChar F) a = -1
hu : IsUnit a
⊢ ¬↑(-1) = 1
[PROOFSTEP]
rw [Int.cast_neg, Int.cast_one]
[GOAL]
case h
F : Type u_1
inst✝⁵ : Field F
inst✝⁴ : Fintype F
inst✝³ : DecidableEq F
hF : ringChar F ≠ 2
F' : Type u_2
inst✝² : Field F'
inst✝¹ : Fintype F'
inst✝ : DecidableEq F'
hF' : ringChar F' ≠ 2
h : ringChar F' ≠ ringChar F
χ : MulChar F F' := ringHomComp (quadraticChar F) (algebraMap ℤ F')
a : F
ha : ↑(quadraticChar F) a = -1
hu : IsUnit a
⊢ ¬-1 = 1
[PROOFSTEP]
exact Ring.neg_one_ne_one_of_char_ne_two hF'
[GOAL]
F : Type u_1
inst✝⁵ : Field F
inst✝⁴ : Fintype F
inst✝³ : DecidableEq F
hF : ringChar F ≠ 2
F' : Type u_2
inst✝² : Field F'
inst✝¹ : Fintype F'
inst✝ : DecidableEq F'
hF' : ringChar F' ≠ 2
h : ringChar F' ≠ ringChar F
χ : MulChar F F' := ringHomComp (quadraticChar F) (algebraMap ℤ F')
hχ₁ : IsNontrivial χ
⊢ ↑(quadraticChar F) ↑(Fintype.card F') = ↑(quadraticChar F') (↑(↑(quadraticChar F) (-1)) * ↑(Fintype.card F))
[PROOFSTEP]
have hχ₂ : χ.IsQuadratic := IsQuadratic.comp (quadraticChar_isQuadratic F) _
[GOAL]
F : Type u_1
inst✝⁵ : Field F
inst✝⁴ : Fintype F
inst✝³ : DecidableEq F
hF : ringChar F ≠ 2
F' : Type u_2
inst✝² : Field F'
inst✝¹ : Fintype F'
inst✝ : DecidableEq F'
hF' : ringChar F' ≠ 2
h : ringChar F' ≠ ringChar F
χ : MulChar F F' := ringHomComp (quadraticChar F) (algebraMap ℤ F')
hχ₁ : IsNontrivial χ
hχ₂ : IsQuadratic χ
⊢ ↑(quadraticChar F) ↑(Fintype.card F') = ↑(quadraticChar F') (↑(↑(quadraticChar F) (-1)) * ↑(Fintype.card F))
[PROOFSTEP]
have h := Char.card_pow_card hχ₁ hχ₂ h hF'
[GOAL]
F : Type u_1
inst✝⁵ : Field F
inst✝⁴ : Fintype F
inst✝³ : DecidableEq F
hF : ringChar F ≠ 2
F' : Type u_2
inst✝² : Field F'
inst✝¹ : Fintype F'
inst✝ : DecidableEq F'
hF' : ringChar F' ≠ 2
h✝ : ringChar F' ≠ ringChar F
χ : MulChar F F' := ringHomComp (quadraticChar F) (algebraMap ℤ F')
hχ₁ : IsNontrivial χ
hχ₂ : IsQuadratic χ
h : (↑χ (-1) * ↑(Fintype.card F)) ^ (Fintype.card F' / 2) = ↑χ ↑(Fintype.card F')
⊢ ↑(quadraticChar F) ↑(Fintype.card F') = ↑(quadraticChar F') (↑(↑(quadraticChar F) (-1)) * ↑(Fintype.card F))
[PROOFSTEP]
rw [← quadraticChar_eq_pow_of_char_ne_two' hF'] at h
[GOAL]
F : Type u_1
inst✝⁵ : Field F
inst✝⁴ : Fintype F
inst✝³ : DecidableEq F
hF : ringChar F ≠ 2
F' : Type u_2
inst✝² : Field F'
inst✝¹ : Fintype F'
inst✝ : DecidableEq F'
hF' : ringChar F' ≠ 2
h✝ : ringChar F' ≠ ringChar F
χ : MulChar F F' := ringHomComp (quadraticChar F) (algebraMap ℤ F')
hχ₁ : IsNontrivial χ
hχ₂ : IsQuadratic χ
h : ↑(↑(quadraticChar F') (↑χ (-1) * ↑(Fintype.card F))) = ↑χ ↑(Fintype.card F')
⊢ ↑(quadraticChar F) ↑(Fintype.card F') = ↑(quadraticChar F') (↑(↑(quadraticChar F) (-1)) * ↑(Fintype.card F))
[PROOFSTEP]
exact (IsQuadratic.eq_of_eq_coe (quadraticChar_isQuadratic F') (quadraticChar_isQuadratic F) hF' h).symm
[GOAL]
F : Type u_1
inst✝³ : Field F
inst✝² : Fintype F
inst✝¹ : DecidableEq F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp₁ : p ≠ 2
hp₂ : ringChar F ≠ p
⊢ ↑(quadraticChar F) ↑p = ↑(quadraticChar (ZMod p)) (↑(↑χ₄ ↑(Fintype.card F)) * ↑(Fintype.card F))
[PROOFSTEP]
rw [← quadraticChar_neg_one hF]
[GOAL]
F : Type u_1
inst✝³ : Field F
inst✝² : Fintype F
inst✝¹ : DecidableEq F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp₁ : p ≠ 2
hp₂ : ringChar F ≠ p
⊢ ↑(quadraticChar F) ↑p = ↑(quadraticChar (ZMod p)) (↑(↑(quadraticChar F) (-1)) * ↑(Fintype.card F))
[PROOFSTEP]
have h :=
quadraticChar_card_card hF (ne_of_eq_of_ne (ringChar_zmod_n p) hp₁) (ne_of_eq_of_ne (ringChar_zmod_n p) hp₂.symm)
[GOAL]
F : Type u_1
inst✝³ : Field F
inst✝² : Fintype F
inst✝¹ : DecidableEq F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp₁ : p ≠ 2
hp₂ : ringChar F ≠ p
h :
↑(quadraticChar F) ↑(Fintype.card (ZMod p)) =
↑(quadraticChar (ZMod p)) (↑(↑(quadraticChar F) (-1)) * ↑(Fintype.card F))
⊢ ↑(quadraticChar F) ↑p = ↑(quadraticChar (ZMod p)) (↑(↑(quadraticChar F) (-1)) * ↑(Fintype.card F))
[PROOFSTEP]
rwa [card p] at h
[GOAL]
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp : p ≠ 2
⊢ IsSquare ↑p ↔ ↑(quadraticChar (ZMod p)) (↑(↑χ₄ ↑(Fintype.card F)) * ↑(Fintype.card F)) ≠ -1
[PROOFSTEP]
classical
by_cases hFp : ringChar F = p
· rw [show (p : F) = 0 by rw [← hFp]; exact ringChar.Nat.cast_ringChar]
simp only [isSquare_zero, Ne.def, true_iff_iff, map_mul]
obtain ⟨n, _, hc⟩ := FiniteField.card F (ringChar F)
have hchar : ringChar F = ringChar (ZMod p) := by rw [hFp]; exact (ringChar_zmod_n p).symm
conv => enter [1, 1, 2]; rw [hc, Nat.cast_pow, map_pow, hchar, map_ringChar]
simp only [zero_pow n.pos, mul_zero, zero_eq_neg, one_ne_zero, not_false_iff]
· rw [← Iff.not_left (@quadraticChar_neg_one_iff_not_isSquare F _ _ _ _), quadraticChar_odd_prime hF hp]
exact hFp
[GOAL]
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp : p ≠ 2
⊢ IsSquare ↑p ↔ ↑(quadraticChar (ZMod p)) (↑(↑χ₄ ↑(Fintype.card F)) * ↑(Fintype.card F)) ≠ -1
[PROOFSTEP]
by_cases hFp : ringChar F = p
[GOAL]
case pos
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp : p ≠ 2
hFp : ringChar F = p
⊢ IsSquare ↑p ↔ ↑(quadraticChar (ZMod p)) (↑(↑χ₄ ↑(Fintype.card F)) * ↑(Fintype.card F)) ≠ -1
[PROOFSTEP]
rw [show (p : F) = 0 by rw [← hFp]; exact ringChar.Nat.cast_ringChar]
[GOAL]
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp : p ≠ 2
hFp : ringChar F = p
⊢ ↑p = 0
[PROOFSTEP]
rw [← hFp]
[GOAL]
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp : p ≠ 2
hFp : ringChar F = p
⊢ ↑(ringChar F) = 0
[PROOFSTEP]
exact ringChar.Nat.cast_ringChar
[GOAL]
case pos
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp : p ≠ 2
hFp : ringChar F = p
⊢ IsSquare 0 ↔ ↑(quadraticChar (ZMod p)) (↑(↑χ₄ ↑(Fintype.card F)) * ↑(Fintype.card F)) ≠ -1
[PROOFSTEP]
simp only [isSquare_zero, Ne.def, true_iff_iff, map_mul]
[GOAL]
case pos
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp : p ≠ 2
hFp : ringChar F = p
⊢ ¬↑(quadraticChar (ZMod p)) ↑(↑χ₄ ↑(Fintype.card F)) * ↑(quadraticChar (ZMod p)) ↑(Fintype.card F) = -1
[PROOFSTEP]
obtain ⟨n, _, hc⟩ := FiniteField.card F (ringChar F)
[GOAL]
case pos.intro.intro
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp : p ≠ 2
hFp : ringChar F = p
n : ℕ+
left✝ : Nat.Prime (ringChar F)
hc : Fintype.card F = ringChar F ^ ↑n
⊢ ¬↑(quadraticChar (ZMod p)) ↑(↑χ₄ ↑(Fintype.card F)) * ↑(quadraticChar (ZMod p)) ↑(Fintype.card F) = -1
[PROOFSTEP]
have hchar : ringChar F = ringChar (ZMod p) := by rw [hFp]; exact (ringChar_zmod_n p).symm
[GOAL]
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp : p ≠ 2
hFp : ringChar F = p
n : ℕ+
left✝ : Nat.Prime (ringChar F)
hc : Fintype.card F = ringChar F ^ ↑n
⊢ ringChar F = ringChar (ZMod p)
[PROOFSTEP]
rw [hFp]
[GOAL]
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp : p ≠ 2
hFp : ringChar F = p
n : ℕ+
left✝ : Nat.Prime (ringChar F)
hc : Fintype.card F = ringChar F ^ ↑n
⊢ p = ringChar (ZMod p)
[PROOFSTEP]
exact (ringChar_zmod_n p).symm
[GOAL]
case pos.intro.intro
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp : p ≠ 2
hFp : ringChar F = p
n : ℕ+
left✝ : Nat.Prime (ringChar F)
hc : Fintype.card F = ringChar F ^ ↑n
hchar : ringChar F = ringChar (ZMod p)
⊢ ¬↑(quadraticChar (ZMod p)) ↑(↑χ₄ ↑(Fintype.card F)) * ↑(quadraticChar (ZMod p)) ↑(Fintype.card F) = -1
[PROOFSTEP]
conv => enter [1, 1, 2]; rw [hc, Nat.cast_pow, map_pow, hchar, map_ringChar]
[GOAL]
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp : p ≠ 2
hFp : ringChar F = p
n : ℕ+
left✝ : Nat.Prime (ringChar F)
hc : Fintype.card F = ringChar F ^ ↑n
hchar : ringChar F = ringChar (ZMod p)
| ¬↑(quadraticChar (ZMod p)) ↑(↑χ₄ ↑(Fintype.card F)) * ↑(quadraticChar (ZMod p)) ↑(Fintype.card F) = -1
[PROOFSTEP]
enter [1, 1, 2]; rw [hc, Nat.cast_pow, map_pow, hchar, map_ringChar]
[GOAL]
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp : p ≠ 2
hFp : ringChar F = p
n : ℕ+
left✝ : Nat.Prime (ringChar F)
hc : Fintype.card F = ringChar F ^ ↑n
hchar : ringChar F = ringChar (ZMod p)
| ¬↑(quadraticChar (ZMod p)) ↑(↑χ₄ ↑(Fintype.card F)) * ↑(quadraticChar (ZMod p)) ↑(Fintype.card F) = -1
[PROOFSTEP]
enter [1, 1, 2]; rw [hc, Nat.cast_pow, map_pow, hchar, map_ringChar]
[GOAL]
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp : p ≠ 2
hFp : ringChar F = p
n : ℕ+
left✝ : Nat.Prime (ringChar F)
hc : Fintype.card F = ringChar F ^ ↑n
hchar : ringChar F = ringChar (ZMod p)
| ¬↑(quadraticChar (ZMod p)) ↑(↑χ₄ ↑(Fintype.card F)) * ↑(quadraticChar (ZMod p)) ↑(Fintype.card F) = -1
[PROOFSTEP]
enter [1, 1, 2]
[GOAL]
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp : p ≠ 2
hFp : ringChar F = p
n : ℕ+
left✝ : Nat.Prime (ringChar F)
hc : Fintype.card F = ringChar F ^ ↑n
hchar : ringChar F = ringChar (ZMod p)
| ↑(quadraticChar (ZMod p)) ↑(Fintype.card F)
[PROOFSTEP]
rw [hc, Nat.cast_pow, map_pow, hchar, map_ringChar]
[GOAL]
case pos.intro.intro
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp : p ≠ 2
hFp : ringChar F = p
n : ℕ+
left✝ : Nat.Prime (ringChar F)
hc : Fintype.card F = ringChar F ^ ↑n
hchar : ringChar F = ringChar (ZMod p)
⊢ ¬↑(quadraticChar (ZMod p)) ↑(↑χ₄ ↑(Fintype.card F)) * 0 ^ ↑n = -1
[PROOFSTEP]
simp only [zero_pow n.pos, mul_zero, zero_eq_neg, one_ne_zero, not_false_iff]
[GOAL]
case neg
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp : p ≠ 2
hFp : ¬ringChar F = p
⊢ IsSquare ↑p ↔ ↑(quadraticChar (ZMod p)) (↑(↑χ₄ ↑(Fintype.card F)) * ↑(Fintype.card F)) ≠ -1
[PROOFSTEP]
rw [← Iff.not_left (@quadraticChar_neg_one_iff_not_isSquare F _ _ _ _), quadraticChar_odd_prime hF hp]
[GOAL]
case neg
F : Type u_1
inst✝² : Field F
inst✝¹ : Fintype F
hF : ringChar F ≠ 2
p : ℕ
inst✝ : Fact (Nat.Prime p)
hp : p ≠ 2
hFp : ¬ringChar F = p
⊢ ringChar F ≠ p
[PROOFSTEP]
exact hFp
|
[STATEMENT]
lemma prv_inj_suc:
"t \<in> atrm \<Longrightarrow> t' \<in> atrm \<Longrightarrow>
prv (imp (eql (suc t) (suc t'))
(eql t t'))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>t \<in> atrm; t' \<in> atrm\<rbrakk> \<Longrightarrow> prv (imp (eql (suc t) (suc t')) (eql t t'))
[PROOF STEP]
using prv_psubst[OF _ _ _ prv_inj_suc_var, of "[(t,xx),(t',yy)]"]
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>imp (eql (suc (Var xx)) (suc (Var yy))) (eql (Var xx) (Var yy)) \<in> fmla; snd ` set [(t, xx), (t', yy)] \<subseteq> var; fst ` set [(t, xx), (t', yy)] \<subseteq> trm\<rbrakk> \<Longrightarrow> prv (psubst (imp (eql (suc (Var xx)) (suc (Var yy))) (eql (Var xx) (Var yy))) [(t, xx), (t', yy)])
goal (1 subgoal):
1. \<lbrakk>t \<in> atrm; t' \<in> atrm\<rbrakk> \<Longrightarrow> prv (imp (eql (suc t) (suc t')) (eql t t'))
[PROOF STEP]
by simp |
This club does not (yet) exist, although perhaps it will in the future, if its past doesnt catch up with it before then. This, of course, has nothing to do, nope nope nope, with the Campus Crusade for Chaos and Confusion.
I have heard lore of these occultish folk, they prove that pies can be squared and things may be taken to imaginary powers. ~DavePoole
|
If $s$ is a finite set of functions from $\mathbb{N}$ to $\mathbb{N}$ such that for every $x, y \in s$, either $x \leq y$ or $y \leq x$, then there exists a function $a \in s$ such that for every $x \in s$, $a \leq x$, and there exists a function $a \in s$ such that for every $x \in s$, $x \leq a$. |
Formal statement is: lemma analytic_on_Union: "f analytic_on (\<Union>\<T>) \<longleftrightarrow> (\<forall>T \<in> \<T>. f analytic_on T)" Informal statement is: A function is analytic on a union of sets if and only if it is analytic on each of the sets. |
(* -------------------------------------------------------------------- *)
Require Import ssreflect ssrbool List.
Require Import Coq.Lists.List.
Require Import Coq.Arith.PeanoNat.
Set Implicit Arguments.
Axiom todo : forall {A}, A.
Ltac todo := by apply: todo.
(* ==================================================================== *)
(* This template contains incomplete definitions that you have to *)
(* fill. We always used the keyword `Definition` for all of them but *)
(* you are free to change for a `Fixpoint` or an `Inductive`. *)
(* *)
(* If needed, it is perfectly fine to add intermediate definitions and *)
(* local lemmas. *)
(* ==================================================================== *)
(* In this project, we are going to develop and prove correct an *)
(* algorithm for deciding the membership of a word w.r.t. a given *)
(* regular language - all these terms are going to be defined below *)
(* This project lies in the domain of *formal languages*. The study *)
(* of formal languages is a branch of theoretical computer science and *)
(* is about that is interested in the purely syntactical aspects of *)
(* of languages and as applications in different domains, ranging from *)
(* the definition of the grammar of programming languages to the field *)
(* of automated translation. *)
(* As with natural languages, we first need to fix an alphabet. In our *)
(* case, we are simply going to declare a type `A : Type` - i.e. we *)
(* will use the same alphabet for all the formal languages we are going *)
(* to study. Inhabitants of `A` are called `letters`. *)
Parameter (A : Type).
(* -------------------------------------------------------------------- *)
(* A `word` is then simply a finite sequence of letters of `A`. We *)
(* denote by A* the set of words over `A`. In Coq, we are going to *)
(* represent words as lists whose elements are inhabitants of `A`. This *)
(* naturally leads to the following definition: *)
Notation word := (list A).
(* -------------------------------------------------------------------- *)
(* You can get an overview of the List library at the following URL: *)
(* https://coq.inria.fr/distrib/current/stdlib/Coq.Lists.List.html *)
(* -------------------------------------------------------------------- *)
(* In this setting, a `language` is simply a subset of A*. Assuming *)
(* that `x` & `y` are letters of A, we can define the following *)
(* languages: *)
(* *)
(* - the empty language: `L = ∅`; *)
(* *)
(* - the language that contains only the empty word ε (i.e. the only *)
(* (word of length 0): L = {ε}`; *)
(* *)
(* - the language that contains all the words solely composed of the *)
(* letter `x`: L = { ε, x, xx, xxx, ... } = { xⁿ | n ∈ ℕ } (here, *)
(* xⁿ stands for the word x…x, where x is repeated n times); *)
(* *)
(* - the language that contains all the words of the form xⁿyⁿ: *)
(* L = { xⁿyⁿ | n ∈ ℕ }; *)
(* *)
(* - if we assume that A contains the letter '[' & ']', we can *)
(* define the language of well-balanced words for '[' & ']': *)
(* L = { w ∈ { [, ] }* | s.t. P(w) && Q(w) }, where *)
(* - P(w) = any prefix of w contain no more ]'s then ['s *)
(* - Q(w) = the number of ['s and ]'s of w are equal. *)
(* -------------------------------------------------------------------- *)
(* We can also combine languages to form other languages. For example, *)
(* if L and G are languages, we can define: *)
(* *)
(* - the union of L & G L ∪ G *)
(* - the concatenation of L & G { w1 · w2 | w1 ∈ L, w2 ∈ G } *)
(* - the intersection of L & G L ∩ G *)
(* - the complement of L A* \ L *)
(* - the Kleene closure of L L* = { w_1 ... w_n | n \in ℕ, w_i ∈ L } *)
(* - the mirror of L rev(L) = { rev(w) | w ∈ L } *)
(* -------------------------------------------------------------------- *)
(* To define languages in Coq, we need a way to represent subsets *)
(* of A*, i.e. subsets of the set of `word`'s. To that end, we are *)
(* going to represent a set using its indicator function. (We remind *)
(* that, given a subset F of an ambient set E, the indicator function *)
(* of F is the function f_E from E to { ⊤, ⊥ } s.t. *)
(* *)
(* f_E(x) = ⊤ iff x ∈ E *)
(* In Coq, the codomain of its indicator function is going to be a *)
(* proposition: given a function `F : E -> Prop`, we say that x belongs *)
(* to `x` iff `f x` holds. *)
Notation language := (word -> Prop).
(* -------------------------------------------------------------------- *)
(* From now use, we assume that L, G, H denote languages, x, y denote *)
(* letters and that and w denotes a word. *)
Implicit Types (L G H : language) (x y : A) (w : word).
(* -------------------------------------------------------------------- *)
(* From there, we can define the following languages *)
(* The empty language: no words belong to it. *)
(* (its indicator function always return `False`) *)
Definition lang0 : language :=
fun w => False.
(* The language that only contains the empty word. *)
Definition lang1 : language :=
fun w => w = nil.
(* Q1. We now ask you to define the following languages *)
(* Given a word `w0`, the language that only contains the word `w0`. *)
Definition langW w0 : language :=
fun w => w = w0.
(* Given a sequence `ws` of words, the language that contains all the *)
(* the words `ws` and only these words. *)
Definition langF (ws : list word) : language :=
fun w => In w ws.
(* Given a letter `x`, the language that only contains the letter `x` *)
(* seen as a word of length 1. *)
Definition langA x : language :=
fun w =>
match w with
| cons a nil => a = x
| _ => False
end.
(* The union of the two languages `L` and `G`. *)
Definition langU L G : language :=
fun w => L w \/ G w.
(* The intersection of the two languages `L` and `G`. *)
Definition langI L G : language :=
fun w => L w /\ G w.
(* The concatenation of the two languages `L` and `G`. *)
Definition langS L G : language :=
fun w => exists w1 w2, w = w1 ++ w2 /\ L w1 /\ G w2.
Fixpoint Ln L n : language :=
match n with
|0 => lang1
|S n => langS L (Ln L n)
end.
(* (* The Kleene closure of the language `L` *)
Definition langK L : language :=
fun w => exists n, Ln L n w. *)
Inductive langK L : language :=
|Knil : langK L nil
|Kself w : L w -> langK L w
|Kconcat w1 w2 : langK L w1 -> langK L w2 -> langK L (w1 ++ w2).
Definition langK_2 L : language :=
fun w => exists n, Ln L n w.
(*
Fixpoint langKn L : language:=
fun w => w = nil \/ exists w1 w2, w1 <> nil /\ L w1 /\ langKn L w2 /\ w = w1 ++ w2.
*)
(* The mirror of the language `L` (You can use the `rev`, that reversed *)
(* a list, from the standard library. *)
Definition langM L : language :=
fun w => L (rev w).
(* -------------------------------------------------------------------- *)
(* Given two languages, we will consider `L` & `G` equal iff they *)
(* contain the same words: *)
Definition eqL L G := forall w, L w <-> G w.
Infix "=L" := eqL (at level 90).
(* Q2. Prove the following equivalences: *)
(* Helpful lemmas: *)
Lemma eqL_A (L G H:language): (L =L G) /\ (G =L H) -> (L =L H).
Proof.
intros. move: H0 => [LG GH].
split;intro.
apply GH. apply LG. done.
apply LG. apply GH. done.
Qed.
Lemma eqL_R L G : (L =L G) -> (G =L L).
Proof.
intros.
split.
apply H.
apply H.
Qed.
(* Q2. Prove the following equivalances: *)
Lemma concat0L L : langS lang0 L =L lang0.
Proof.
split.
+ move => [w1 [w2 [eq [false l]]]].
contradiction.
+ contradiction.
Qed.
Lemma concatL0 L : langS L lang0 =L lang0.
Proof.
unfold langS.
unfold lang0.
split.
+ move => [w1 [w2 [eq [l false]]]]. contradiction.
+ contradiction.
Qed.
Lemma concat1L L : langS lang1 L =L L.
Proof.
split.
+ move => [w1 [w2 [eq [wnil lw2]]]].
rewrite wnil in eq.
simpl in eq.
rewrite eq.
apply lw2.
+ exists nil. exists w. done.
Qed.
Lemma concatL1 L : langS L lang1 =L L.
Proof.
unfold langS; unfold lang1.
split.
+ move => [w1 [w2 [eq [lw1 wnil]]]].
rewrite wnil in eq.
rewrite app_nil_r in eq.
rewrite eq.
done.
+ move => Lw.
exists w. exists nil.
split.
- rewrite app_nil_r. done.
- done.
Qed.
Lemma concatA L G H : langS (langS L G) H =L langS L (langS G H).
Proof.
unfold langS.
split.
+ move => [w1 [w2 [eq1 [[w3 [w4 [eq2 [lw3 gw4] hw2]]]]]]].
exists w3. exists (w4 ++ w2).
split.
- rewrite eq1. rewrite eq2. symmetry. apply app_assoc.
- split.
* apply lw3.
* exists w4. exists w2. done.
+ move => [w1 [w2 [eq1 [lw1 [w3 [w4 [eq2 [gw3 hw4]]]]]]]].
exists (w1 ++ w3). exists w4.
split.
- rewrite eq1. rewrite eq2. apply app_assoc.
- split.
* exists w1. exists w3. done.
* apply hw4.
Qed.
Lemma unionC L G : langU L G =L langU G L.
Proof.
unfold langU.
split; move => [lw | gw].
+ right. done.
+ left. done.
+ right. done.
+ left. done.
Qed.
Lemma interC L G : langI L G =L langI G L.
Proof.
unfold langI.
split; move => [lw gw]; done.
Qed.
Lemma langKK L : langK (langK L) =L langK L.
Proof.
split; move => L1.
+ induction L1.
- apply Knil.
- apply H.
- apply Kconcat.
* apply IHL1_1.
* apply IHL1_2.
+ induction L1.
- apply Knil.
- apply Kself. apply Kself. apply H.
- apply Kconcat.
* apply IHL1_1.
* apply IHL1_2.
Qed.
(* Note that, since languages are represented as indicator functions *)
(* over `Prop`, we cannot assess that `L =L G` implies `L = G`. *)
(* ==================================================================== *)
(* REGULAR LANGUAGES *)
(* We are now interested in a subclass of languages called "regular *)
(* languages": a language `L` is said to be regular iff one of the *)
(* following holds: *)
(* *)
(* - L = ∅ or L = {ε} or L = {x} for some x ∈ A ; *)
(* - L = L1 ∪ L2 for L1, L2 regular languages ; *)
(* - L = L1 · L2 for L1, L2 regular languages ; *)
(* - L = G* for G a regular language. *)
(* This kind of inductive definitions can be encoded in Coq using *)
(* an inductive predicate `regular : language -> Prop` s.t. *)
(* *)
(* L is regular iff `regular L` holds *)
(* Q3. complete the following definition of the predicate `regular`: *)
Inductive regular : language -> Prop :=
(* Any language equivalent to a regular language is regular *)
| REq L G of regular L & G =L L : regular G
(* The empty language is regular *)
| REmpty : regular lang0
(* The empty word is regular*)
| REword : regular lang1
(* The language with a single word *)
| ROne : forall w0, regular (langW w0)
(* The Union of two languages *)
| RUnion L G of regular L & regular G : regular (langU L G)
(* The Concatenation of two languages *)
| RConc L G of regular L & regular G : regular (langS L G)
(* The Kleene closure of a regular language *)
| RKleene L of regular L : regular (langK L)
.
(* -------------------------------------------------------------------- *)
(* Q4. prove that `langW w` is regular. *)
Lemma regularW w : regular (langW w).
Proof. todo. Qed.
(* -------------------------------------------------------------------- *)
(* Q5. prove that `langM L` is regular, given that L is regular. *)
Lemma regularM L : regular L -> regular (langM L).
Proof. todo. Qed.
(* ==================================================================== *)
(* REGULAR EXPRESSIONS *)
(* Related to regular languages is the notion of regular expressions. *)
(* A regular expression is a formal, syntactic expression that can *)
(* latter be interpreted as a regular language. Regular expressions are *)
(* pervasive in computer science, e.g. for searching for some text in *)
(* a file, as it is possible with the `grep` command line tool. *)
(* *)
(* For instance, the command: *)
(* *)
(* grep -E 'ab*a' foo.txt *)
(* *)
(* is going to print all the lines of `foo.txt` that contains a word *)
(* of the form ab⋯ba (where the letter b can be repeated 0, 1 or more *)
(* time. I.e., grep is going to find all the lines of `foo.txt` that *)
(* contains a word that belongs in the formal language: *)
(* *)
(* L = { abⁿa | n ∈ ℕ } *)
(* *)
(* If you need to convince yourself that L is regular, note that: *)
(* *)
(* L = { a } ∪ { b }* ∪ { a } *)
(* *)
(* In some sense, a regular expression is just a compact way to *)
(* represent a regular language, and its definition is going to be *)
(* close to the one of regular languages. *)
(* *)
(* A regular expression is either: *)
(* *)
(* - the constant ∅ or the constant ε or one letter from A *)
(* - the disjunction r1 | r2 of two regular expressions *)
(* - the concatenation r1 · r2 of two regular expressions *)
(* - the Kleene r* of some regular expression *)
(* We can represent regular expressions as a inductive type in Coq. *)
(* Q6. complete the following definition: *)
Inductive regexp : Type :=
| RE_Empty : regexp
| RE_Void : regexp
| RE_Atom : A -> regexp
(* TO BE COMPLETED *)
.
Implicit Types (r : regexp).
(* We now have to formally related regular expressions to regular *)
(* languages. For that purpose, we are going to interpret a regular *)
(* expression as a languages. If r is a regular expression, then we *)
(* denote by language [r] as follows: *)
(* *)
(* - [∅] = ∅ *)
(* - [ε] = ε *)
(* - [a] = { a } for a ∈ A *)
(* - [r₁ ∪ r₂] = [r₁] ∪ [r₂] *)
(* - [r₁ · r₂] = [r₁] · [r₂] *)
(* - [r*] = [r]* *)
(* Q7. implement the Coq counterpart of the above definition: *)
Fixpoint interp (r : regexp) {struct r} : language :=
match r with
| _ => todo
end.
(* Q8. show that the interpretation of a regular expression is a *)
(* regular language: *)
Lemma regular_regexp r : regular (interp r).
Proof. todo. Qed.
(* Q9. show that any regular language can be interpreted as a *)
(* regular expression: *)
Lemma regexp_regular L : regular L -> exists r, L =L interp r.
Proof. todo. Qed.
(* Of course, it may happen that two regular expressions represent *)
(* the same language: r1 ~ r2 iff [r1] = [r2]. *)
(* Q10. write a binary predicate eqR : regexp -> regexp -> Prop s.t. *)
(* eqR r1 r2 iff r1 and r2 are equivalent regexp. *)
Definition eqR (r1 r2 : regexp) : Prop := todo.
Infix "~" := eqR (at level 90).
(* Q11. state and prove the following regexp equivalence: *)
(* (a|b)* ~ ( a*b* )* *)
(* ==================================================================== *)
(* REGEXP MATCHING *)
(* We now want to write a algorithm for deciding if a given word `w` *)
(* matches a regular expression `r`, i.e. for deciding wether `w ∈ [r]` *)
(* *)
(* For that purpose, we are going to use Brzozowski's derivatives. *)
(* *)
(* The idea of the algorithm is the following: *)
(* *)
(* Given a letter `x` and an regular expression `r`, the Brzozowski's *)
(* derivatives of `x` w.r.t. `r` is a regular expression x⁻¹·r s.t. *)
(* *)
(* x · w ∈ [r] ⇔ w ∈ [x⁻¹·r] *)
(* *)
(* Assuming that we can compute a Brzozowski's derivative for any *)
(* letter `x` and regular expression `r`, one can check that a word `w` *)
(* matches a regexp `r` as follows: *)
(* *)
(* - if w = x · w' for some letter x and word w', we recursively *)
(* check that `w` matches `x⁻¹·r`; otherwise *)
(* - if w = ε, then we directly check that [r] contains the empty *)
(* word - a property that is deciable. *)
(* Q12. write a nullity test `contains0` : regexp -> bool s.t. *)
(* *)
(* ∀ r, contains0 r ⇔ ε ∈ [e] *)
Definition contains0 (r : regexp) : bool := todo.
(* Q13. prove that your definition of `contains0` is correct: *)
Lemma contains0_ok r : contains0 r <-> interp r nil.
Proof. todo. Qed.
(* We give below the definition of the Brzozowski's derivative: *)
(* *)
(* - x⁻¹ · x = ε *)
(* - x⁻¹ · y = ∅ if x ≠ y *)
(* - x⁻¹ · ε = ∅ *)
(* - x⁻¹ · ∅ = ∅ *)
(* - x⁻¹ · (r₁ | r₂) = (x⁻¹ · r₁) | (x⁻¹ · r₂) *)
(* - x⁻¹ · (r₁ · r₂) = (x⁻¹ · r₁) · r₂ | E(r₁) · (x⁻¹ · r₂) *)
(* - x⁻¹ · r* = (x⁻¹ · r) · r* *)
(* *)
(* where E(r) = ε if ε ∈ [r] & E(r) = ∅ otherwise. *)
(* Q14. write a function `Brzozowski` that computes a Brzozowski's *)
(* derivative as defined above. *)
(* *)
(* For that purpose, you may need to have a decidable equality over *)
(* `A`. The parameter `Aeq` along with the axioms `Aeq_dec` give *)
(* you such a decidable equality. *)
Parameter Aeq : A -> A -> bool.
(* Here, `Aeq x y` has to be read as `Aeq x y = true` *)
Axiom Aeq_dec : forall (x y : A), Aeq x y <-> x = y.
Definition Brzozowski (x : A) (r : regexp) : regexp := todo.
(* Q15. write a function `rmatch` s.t. `rmatch r w` checks wether a *)
(* word `w` matches a given regular expression `r`. *)
Definition rmatch (r : regexp) (w : word) : bool := todo.
(* Q16. show that the `Brzozowski` function is correct. *)
Lemma Brzozowski_correct (x : A) (w : word) (r : regexp) :
interp (Brzozowski x r) w -> interp r (x :: w).
Proof. todo. Qed.
(* Q17. show that `rmatch` is correct. *)
Lemma rmatch_correct (r : regexp) (w : word):
rmatch r w -> interp r w.
Proof. todo. Qed.
(* Q18. (HARD - OPTIONAL) show that `rmatch` is complete. *)
Lemma rmatch_complete (r : regexp) (w : word):
interp r w -> rmatch r w.
Proof. todo. Qed.
|
\section{FE cantonmathguy Seclected Problems}
\begin{enumerate}
\item Determine all functions $f: \mathbb{Q} \to \mathbb{Q}$ satisfying $f(x + y) = f(x) + f(y)$ for all $x, y \in \mathbb{Q}$.
\item Let $a_1, a_2, \ldots$ be a sequence of integers with infinitely many positive and negative terms. Suppose that for every positive integer $n$ the numbers $a_1, a_2, \ldots, a_n$ leave $n$ different remainders upon division by $n$. Prove that every integer occurs exactly once in the sequence $a_1, a_2, \ldots$.
\item Determine all functions $f: \mathbb{R} \to \mathbb{R}$ satisfying \[f(x)f(y) = f(x + y) + xy\]for all real $x$ and $y$.
\item Find all functions $f: \mathbb{Z} \rightarrow \mathbb{Z}$ such that, for all integers $a$, $b$, $c$ that satisfy $a + b + c = 0$, the following equality holds:
\[f(a)^2 + f(b)^2 + f(c)^2 = 2f(a)f(b) + 2f(b)f(c) + 2f(c)f(a).\]
\item Determine all functions $f: \mathbb{R} \to \mathbb{R}$ satisfying
\[f(x) + f(y) = f(x + y) \quad \text{and} \quad f(xy) = f(x)f(y)\]for all $x, y \in \mathbb{R}$.
\item Find all functions $f: \mathbb{R} \rightarrow \mathbb{R}$ such that for all $x,y \in \mathbb{R}$, the following equality holds
\[f(\left\lfloor x\right\rfloor y)=f(x)\left\lfloor f(y)\right\rfloor\]where $\left\lfloor a\right\rfloor$ is the greatest integer not greater than $a$.
\item $ \bigstar $ Let $k$ be a real number. Find all functions $f: \mathbb{R} \to \mathbb{R}$ satisfying
\[|f(x) - f(y)| \le k(x - y)^2\]for all real $x$ and $y$.
\item Let $f: \mathbb{N} \to \mathbb{N}$ be a function, and suppose that positive integers $k$ and $c$ satisfy
\[f^k(n) = n + c\]for all $n \in \mathbb{N}$, where $f^k$ denotes $f$ applied $k$ times. Show that $k \mid c$.
\item Find all functions $f: \mathbb{N} \to \mathbb{N}$ satisfying
\[f(f(f(n))) + f(f(n)) + f(n) = 3n\]for every positive integer $n$.
\item Let $S$ be the set of integers greater than $1$. Find all functions $f: S \to S$ such that
(i) $f(n) \mid n$ for all $n \in S$,
(ii) $f(a) \ge f(b)$ for all $a, b \in S$ with $a \mid b$.
\item Let $\mathbb{R}$ be the set of real numbers. Determine all functions $f: \mathbb{R} \to \mathbb{R}$ such that \[f(x^2 - y^2) = x f(x) - y f(y)\]for all pairs of real numbers $x$ and $y$.
\item $ \bigstar $ Let $T$ denote the set of all ordered triples $(p,q,r)$ of nonnegative integers. Find all functions $f: T \to \mathbb{R}$ satisfying
\[f(p,q,r) = \begin{cases} 0 & \text{if} \; pqr = 0, \\ 1 + \frac{1}{6}(f(p + 1,q - 1,r) + f(p - 1,q + 1,r) & \\ + f(p - 1,q,r + 1) + f(p + 1,q,r - 1) & \\ + f(p,q + 1,r - 1) + f(p,q - 1,r + 1)) & \text{otherwise} \end{cases} \]for all nonnegative integers $p$, $q$, $r$.
\item Determine all strictly increasing functions $f: \mathbb{N} \to \mathbb{N}$ satisfying $nf(f(n)) = f(n)^2$ for all positive integers $n$.
\item Determine all functions $f: \mathbb{Z} \rightarrow \mathbb{Z}$ with the property that
\[f(x - f(y)) = f(f(x)) - f(y) - 1\]holds for all $x,y \in \mathbb{Z}$.
\item Find all real-valued functions $f$ defined on pairs of real numbers, having the following property: for all real numbers $a, b, c$, the median of $f(a,b), f(b,c), f(c,a)$ equals the median of $a, b, c$.
\item Find all functions $f: \mathbb{N} \rightarrow \mathbb{N}$ such that, for all positive integer $n$, we have $f(f(n)) < f(n + 1)$.
\item Let $f: \mathbb{N} \to \mathbb{N}$ be a function such that, for any $w, x, y, z \in N$,
\[f(f(f(z))) f(wxf(yf(z))) = z^2 f(xf(y)) f(w).\]Show that $f(n!) \ge n!$ for every positive integer $n$.
\item Find all functions $f: \mathbb{N} \rightarrow \mathbb{N}$ such that $f(n!) = f(n)!$ for all positive integers $n$ and such that $m-n$ divides $f(m) - f(n)$ for all distinct positive integers $m$, $n$.
\item Find all functions $f$ from the reals to the reals such that
\[(f(a) + f(b))(f(c) + f(d)) = f(ac + bd) + f(ad - bc)\]for all real $a, b, c, d$.
\item Determine all functions $f$ defined on the natural numbers that take values among the natural numbers for which
\[(f(n))^p \equiv n \pmod{f(p)}\]for all $n \in \mathbb{N}$ and all prime numbers $p$.
\item Let $n \ge 4$ be an integer, and define $[n] = \{1, 2, \ldots, n\}$. Find all functions $W: [n]^2 \to \mathbb{R}$ such that for every partition $[n] = A \cup B \cup C$ into disjoint sets,
\[\sum_{a \in A} \sum_{b \in B} \sum_{c \in C} W(a,b) W(b,c) = |A| |B| |C|.\]
\item $ \bigstar $ Find all infinite sequences $a_1, a_2, \ldots$ of positive integers satisfying the following properties:
(a) $a_1 < a_2 < a_3 < \cdots$,
(b) there are no positive integers $i$, $j$, $k$, not necessarily distinct, such that $a_i + a_j = a_k$,
(c) there are infinitely many $k$ such that $a_k = 2k - 1$.
\item Show that there exists a bijective function $f:\mathbb N_0\to\mathbb N_0$ such that for all $m,n\in\mathbb{N}_{0}$, $$f(3mn + m + n) = 4f(m)f(n) + f(m) + f(n)$$
\item Determine all functions $f: \mathbb Z \to \mathbb Z$ satisfying $$f(f(m) + n) + f(m) = f(n) + f(3m) + 2014$$ for all integers $m$ and $n$.
\item Let $n \ge 3$ be a given positive integer. We wish to label each side and each diagonal of a regular $n$-gon $P_1 \ldots P_n$ with a positive integer less than or equal to $r$ so that:
\begin{enumerate}
\item every integer between $1$ and $r$ occurs as a label;
\item in each triangle $P_iP_jP_k$ two of the labels are equal and greater than the third.
\end{enumerate}
Given these conditions:
\begin{enumerate}
\item Determine the largest positive integer $r$ for which this can be done.
\item For that value of $r$, how many such labellings are there?
\end{enumerate}
\item $ \bigstar $ Suppose that $f$ and $g$ are two functions defined on the set of positive integers and taking positive integer values. Suppose also that the equations $f(g(n)) = f(n) + 1$ and $g(f(n)) = g(n) + 1$ hold for all positive integer $n$. Prove that $f(n) = g(n)$ for all positive integer $n$.
\item Find all the functions $f: \mathbb N_0 \to \mathbb N_0$ satisfying the relation
\item Let $\mathbb{R}$ be the set of real numbers. Determine all functions $f: \mathbb{R} \to \mathbb{R}$ that satisfy the equation
\[f(x + f(x + y)) + f(xy) = x + f(x + y) + yf(x)\]for all real numbers $x$ and $y$.
\item Suppose that $s_1, s_2, s_3, \ldots$ is a strictly increasing sequence of positive integers such that the sub-sequences
\[s_{s_1}, s_{s_2}, s_{s_3}, \ldots \qquad\text{and}\qquad s_{s_1+1}, s_{s_2+1}, s_{s_3+1}, \ldots\]are both arithmetic progressions. Prove that the sequence $s_1, s_2, s_3, \ldots$ is itself an arithmetic progression.
\item Find all functions $f$ from $\mathbb{N}_0$ to itself such that
\[f(m + f(n)) = f(f(m)) + f(n)\]for all $m, n \in \mathbb{N}_0$.
\item $ \bigstar $ Consider a function $f: \mathbb{N} \to \mathbb{N}$. For any $m, n \in \mathbb{N}$ we write $f^n(m) = \underbrace{f(f(\ldots f}_{n}(m)\ldots))$. Suppose that $f$ has the following two properties:
\begin{enumerate}
\item if $m, n \in \mathbb{N}$, then $\frac{f^n(m) - m}{n} \in \mathbb{N}$;
\item The set $\mathbb{N} \setminus \{f(n) \mid n\in \mathbb{N}\}$ is finite.
\end{enumerate}
Prove that the sequence $f(1) - 1, f(2) - 2, f(3) - 3, \ldots$ is periodic.
\item Let $\mathbb{N}$ be the set of positive integers. Find all functions $f: \mathbb{N} \to \mathbb{N}$ that satisfy the equation
\[f^{abc-a}(abc) + f^{abc-b}(abc) + f^{abc-c}(abc) = a + b + c\]for all $a,b,c \ge 2$.
\item Let $2\mathbb{Z} + 1$ denote the set of odd integers. Find all functions $f:\mathbb{Z} \to 2\mathbb{Z} + 1$ satisfying
\[f(x + f(x) + y) + f(x - f(x) - y) = f(x + y) + f(x - y)\]for every $x, y \in \mathbb{Z}$.
\end{enumerate} |
function compute_RMSE(U, V, Y, r, d1, d2, rows_t, vals_t, cols_t)
res = 0.0
n = 0.0
for i = 1:d1
tmp = nzrange(Y, i)
d2_bar = rows_t[tmp];
vals_d2_bar = vals_t[tmp];
ui = U[:, i]
len = size(d2_bar)[1]
for j = 1:len
J = d2_bar[j];
vj = V[:, J]
res += (vals_d2_bar[j] - dot(ui,vj))^2
n += 1.0
end
end
return (res / n)^0.5
end
function compute_RMSE_train(U, V, X, r, d1, d2, rows, vals, cols)
res = 0.0
n = 0.0
for i = 1:d1
tmp = nzrange(X, i)
d2_bar = rows[tmp];
vals_d2_bar = vals[tmp];
ui = U[:, i]
len = size(d2_bar)[1]
for j = 1:len
J = d2_bar[j];
vj = V[:, J]
res += (vals_d2_bar[j] - dot(ui,vj))^2
n += 1.0
end
end
return (res / n)^0.5
end
function compute_RMSE(U, V, Y, r, d1, d2, rows_t, vals_t, cols_t, threshold)
res = 0.0
n = 0.0
u_bar = zeros(r)
for i = 1:d1
u_bar += U[:, i]
end
u_bar /= d1
for i = 1:d1
tmp = nzrange(Y, i)
d2_bar = rows_t[tmp];
vals_d2_bar = vals_t[tmp];
#ui = U[:, i]
#ui = U[:, i] * threshold + (1 - threshold) * u_bar
if rand(1)[1] > threshold
i = rand(1:d1)
end
ui = U[:, i]
len = size(d2_bar)[1]
for j = 1:len
J = d2_bar[j];
vj = V[:, J]
res += (vals_d2_bar[j] - dot(ui,vj))^2
n += 1.0
end
end
return (res / n)^0.5
end
function compute_RMSE_train(U, V, X, r, d1, d2, rows, vals, cols, threshold)
res = 0.0
n = 0.0
u_bar = zeros(r)
for i = 1:d1
u_bar += U[:, i]
end
u_bar /= d1
for i = 1:d1
tmp = nzrange(X, i)
d2_bar = rows[tmp];
vals_d2_bar = vals[tmp];
#ui = U[:, i]
#ui = U[:, i] * threshold + (1 - threshold) * u_bar
if rand(1)[1] > threshold
i = rand(1:d1)
end
ui = U[:, i]
len = size(d2_bar)[1]
for j = 1:len
J = d2_bar[j];
vj = V[:, J]
res += (vals_d2_bar[j] - dot(ui,vj))^2
n += 1.0
end
end
return (res / n)^0.5
end
function objective(U, V, X, d1, lambda, rows, vals)
res = 0.0
res = lambda * (vecnorm(U) ^ 2 + vecnorm(V) ^ 2)
for i in 1:d1
tmp = nzrange(X, i)
d2_bar = rows[tmp];
vals_d2_bar = vals[tmp];
len = size(d2_bar)[1];
for k in 1:len
j = d2_bar[k]
res += (vals_d2_bar[k] - dot(U[:,i], V[:,j]))^2
end
end
return res
end
function compute_pairwise_error_ndcg(U, V, Y, r, d1, d2, rows_t, vals_t, cols_t, ndcg_k)
sum_error = 0.; ndcg_sum = 0.;
for i = 1:d1
tmp = nzrange(Y, i)
d2_bar = rows_t[tmp];
vals_d2_bar = vals_t[tmp];
ui = U[:, i]
len = size(d2_bar)[1]
score = zeros(len)
for j = 1:len
J = d2_bar[j];
vj = V[:, J]
score[j] = dot(ui,vj)
end
error_this = 0
n_comps_this = 0
for j in 1:(len - 1)
jval = vals_d2_bar[j]
for k in (j + 1):len
kval = vals_d2_bar[k]
if score[j] >= score[k] && jval < kval
error_this += 1
end
if score[j] <= score[k] && jval > kval
error_this += 1
end
n_comps_this += 1
end
end
sum_error += error_this / n_comps_this
p1 = sortperm(score, rev = true)
p1 = p1[1:ndcg_k]
M1 = vals_d2_bar[p1]
p2 = sortperm(vals_d2_bar, rev = true)
p2 = p2[1:ndcg_k]
M2 = vals_d2_bar[p2]
dcg = 0.; dcg_max = 0.
for k = 1:ndcg_k
dcg += (2 ^ M1[k] - 1) / log2(k + 1)
dcg_max += (2 ^ M2[k] - 1) / log2(k + 1)
end
ndcg_sum += dcg / dcg_max
end
return sum_error / d1, ndcg_sum / d1
end
function update(U, V, X, r, d1, d2, lambda, rows, vals, stepsize, cols, threshold, p)
l = rand(1:length(rows))
j = rows[l]
i = cols[l]
#i = rand(1:d1)
#j = rand(1:d2)
#eij = X[j, i] - dot(U[:,i], V[:,j])
if rand(1)[1] > threshold
i = rand(1:d1)
end
if rand(1)[1] > threshold
j = rand(1:d2)
end
eij = vals[l] - dot(U[:,i], V[:,j])
for k in 1:r
if rand(1)[1] <= p
U[k, i] += stepsize * (eij * V[k,j] - lambda * U[k,i]) / p
end
end
for k in 1:r
if rand(1)[1] <= p
V[k,j] += stepsize * (eij * U[k,i] - lambda * V[k,j]) / p
end
end
#U[:,i] = ui
#V[:,j] = vj
return U, V
end
# command to run julia program after include this file
# main("data/ml1m_train_ratings.csv", "data/ml1m_test_ratings.csv", 100, 0.1, 0.99)
# p is probability of keeping embeddings
function main(train, test, r, lambda, threshold, p)
X = readdlm(train, ',' , Int64);
x = vec(X[:,1]);
y = vec(X[:,2]);
v = vec(X[:,3]);
Y = readdlm(test, ',' , Int64);
xx = vec(Y[:,1]);
yy = vec(Y[:,2]);
vv = vec(Y[:,3]);
# userid; movieid
# n = 6040; msize = 3952;
# depending on the size of X, read n_users and n_items from python output
n = max(maximum(x), maximum(xx)); msize = max(maximum(y), maximum(yy));
println("Training dataset ", train, " and test dataset ", test, " are loaded. \n There are ", n, " users and ", msize, " items in the dataset.")
#n = 1496; msize = 3952;
#n = 12851; msize = 65134
#n = 221004; msize = 17771
X = sparse(x, y, v, n, msize); # userid by movieid
Y = sparse(xx, yy, vv, n, msize);
# julia column major
# now moveid by userid
X = X';
Y = Y';
# too large to debug the algorithm, subset a small set: 500 by 750
#X = X[1:500, 1:750];
#X = X[1:1000, 1:2000];
rows = rowvals(X);
vals = nonzeros(X);
cols = zeros(Int, size(vals)[1]);
d2, d1 = size(X);
cc = 0;
for i = 1:d1
tmp = nzrange(X, i);
nowlen = size(tmp)[1];
for j = 1:nowlen
cc += 1
cols[cc] = i
end
end
rows_t = rowvals(Y);
vals_t = nonzeros(Y);
cols_t = zeros(Int, size(vals_t)[1]);
cc = 0;
for i = 1:d1
tmp = nzrange(Y, i);
nowlen = size(tmp)[1];
for j = 1:nowlen
cc += 1
cols_t[cc] = i
end
end
#r = 100;
#lambda = 0.1
#lambda = 7000 # works better for movielens10m data
#lambda = 10000; # works better for netflix data
ndcg_k = 10;
# initialize U, V
U = randn(r, d1); V = randn(r, d2);
# U = 0.01*randn(r, d1); V = 0.01*randn(r, d2); # works better for netflix data
#stepsize = 0.0001
stepsize = 0.005
totaltime = 0.00000;
#println("iter time objective_function pairwise_error NDCG RMSE")
println("iter time objective_function train_RMSE test_RMSE")
#pairwise_error, ndcg = compute_pairwise_error_ndcg(U, V, Y, r, d1, d2, rows_t, vals_t, cols_t, ndcg_k)
nowobj = objective(U, V, X, d1, lambda, rows, vals)
rmse = compute_RMSE(U, V, Y, r, d1, d2, rows_t, vals_t, cols_t)
rmse_tr = compute_RMSE_train(U, V, X, r, d1, d2, rows, vals, cols)
#println("[", 0, ", ", totaltime, ", ", nowobj, ", ", pairwise_error, ", ", ndcg, ", ", rmse, ", ", rmse_tr, "],")
println("[", 0, ", ", totaltime, ", ", nowobj, ", ", rmse, ", ", rmse_tr, "],")
#for iter in 1:150000000
for iter in 1:3000000000
tic();
#V, m, nowobj = update_V(U, V, X, r, d1, d2, lambda, rows, vals, stepsize, cols)
#U, nowobj = update_U(U, V, X, r, d1, d2, lambda, rows, vals, stepsize, m)
U, V = update(U, V, X, r, d1, d2, lambda, rows, vals, stepsize, cols, threshold, p)
totaltime += toq();
# need to add codes for computing pairwise error and NDCG
#pairwise_error = compute_pairwise_error(U, V, Y, r, d1, d2, rows_t, vals_t, cols_t)
#ndcg = compute_NDCG(U, V, Y, r, d1, d2, rows_t, vals_t, cols_t, ndcg_k)
#if iter % 3000000 == 0
if iter % 10000000 == 0
#if iter % 100000000 == 0
#threshold += (1 - threshold) / 3
nowobj = objective(U, V, X, d1, lambda, rows, vals)
#pairwise_error, ndcg = compute_pairwise_error_ndcg(U, V, Y, r, d1, d2, rows_t, vals_t, cols_t, ndcg_k)
rmse = compute_RMSE(U, V, Y, r, d1, d2, rows_t, vals_t, cols_t)
rmse_tr = compute_RMSE_train(U, V, X, r, d1, d2, rows, vals, cols)
#rmse = compute_RMSE(U, V, Y, r, d1, d2, rows_t, vals_t, cols_t, threshold)
#rmse_tr = compute_RMSE_train(U, V, X, r, d1, d2, rows, vals, cols, threshold)
#println("[", iter, ", ", totaltime, ", ", nowobj, ", ", pairwise_error, ", ", ndcg, ", ", rmse_tr, ", ", rmse, "],")
println("[", iter, ", ", totaltime, ", ", nowobj, ", ", rmse_tr, ", ", rmse, "],")
end
end
return V, U
end
|
!! eta derivs is (1-eta^2) d/deta - eta (E1) or O1
!! eta_rhoderivs is d/deta
!! adapted from eta_init
subroutine GetJacobiKE(points,weights,ketot, lbig, eta_derivs,eta_rhoderivs,evenodd)
implicit none
integer,intent(in) :: lbig, evenodd
real*8,intent(out) :: points((lbig+1)), weights((lbig+1)),ketot((lbig+1),(lbig+1)),&
eta_derivs((lbig+1),(lbig+1)),eta_rhoderivs(lbig+1,lbig+1)
integer, parameter :: numextra=6
integer :: numpoints, one=1, two=2, izero=0, i,j,k,jj , extraorder
real*8 :: extrapoints((lbig+1)+numextra), extraweights(numextra+(lbig+1)), &
firstdertot((lbig+1)+numextra,(lbig+1)), scratch(numextra+(lbig+1)), &
etavals((lbig+1)+numextra,(lbig+1)), endpoints(2)=[-1.0d0,1.0d0] , zero = 0.0, sum
extrapoints=0; extraweights=0; firstdertot=0; scratch=0; etavals=0
numpoints=lbig+1
one=1;two=2
extraorder=numextra+numpoints
call gaussq(one,numpoints,zero,zero,izero,endpoints,scratch,points,weights)
call gaussq(one,extraorder,zero,zero,izero,endpoints,scratch,extrapoints,extraweights)
! firstderiv(i,j) First derivative matrix. Deriv of ith dvr at x_j
do k=1,extraorder ! point k
do j=1,numpoints ! which basis function
sum=1.d0
do i=1,numpoints
if (j/=i) then
sum=sum * (extrapoints(k)-points(i))/(points(j)-points(i))
endif
enddo
etavals(k,j)=sum
enddo
enddo
if (numextra.ne.0) then
do k=1,extraorder ! point k
do j=1,numpoints
sum=0.d0
do i=1,numpoints
if (j/=i) then
sum=sum+ etavals(k,j)/(extrapoints(k)-points(i))
endif
enddo
firstdertot(k,j)=sum
enddo
enddo
else
print *, "Numextra not supported.", numextra; stop
endif
do jj=1,numpoints
firstdertot(:,jj) = firstdertot(:,jj) / sqrt(weights(jj))
etavals(:,jj) = etavals(:,jj) / sqrt(weights(jj))
enddo
do i=1,numpoints
do j=1,numpoints
sum=0
do k=1,extraorder
sum=sum + extraweights(k) * etavals(k,i) * ( extrapoints(k)*(1-extrapoints(k)**2) * &
firstdertot(k,j) + (0.5d0 - 3d0/2d0 * extrapoints(k)**2) * etavals(k,j) )
enddo
eta_rhoderivs(i,j)=sum
sum=0.0d0
if (evenodd.eq.0) then
do k=1,extraorder
sum= sum + etavals(k,i) &
* (firstdertot(k,j)* (1-extrapoints(k)**2) - etavals(k,j) * extrapoints(k) ) &
* extraweights(k)
enddo
else
do k=1,extraorder
sum= sum + etavals(k,i) &
* (firstdertot(k,j)* (1-extrapoints(k)**2)**2 - 2*etavals(k,j) * &
(1-extrapoints(k)**2)*extrapoints(k) ) &
* extraweights(k)
enddo
sum=sum/sqrt((1-points(i)**2)*(1-points(j)**2))
endif
eta_derivs(i,j)=sum
enddo
enddo
!! negative definite operators for eta.
do j=1,numpoints
do i=1,numpoints
if (evenodd.eq.0) then !! even, d/dx (1-x^2)**2 d/dx
sum=0.0d0
do k=1,extraorder
sum = sum - firstdertot(k,j) * firstdertot(k,i) * extraweights(k) * (1-extrapoints(k)**2)
enddo
else
sum=0.0d0
do k=1,extraorder
sum= sum - (firstdertot(k,j)* (1-extrapoints(k)**2) - etavals(k,j) * extrapoints(k) ) &
* (firstdertot(k,i)* (1-extrapoints(k)**2) - etavals(k,i) * extrapoints(k) ) &
* extraweights(k)
enddo
sum=sum/sqrt((1-points(i)**2)*(1-points(j)**2))
endif
ketot(i,j)= sum !! symmetric kinetic energy
enddo
enddo
end subroutine GetJacobiKE
|
SUBROUTINE INTERP(N,NP,NQ,MODE,E,FP,CP,VEC,FOCK,P,H,VECL)
IMPLICIT DOUBLE PRECISION (A-H,O-Z)
INCLUDE 'SIZES'
DIMENSION FP(MPACK), CP(N,N)
DIMENSION VEC(N,N), FOCK(N,N),
1 P(N,N), H(N*N), VECL(N*N)
**********************************************************************
*
* INTERP: AN INTERPOLATION PROCEDURE FOR FORCING SCF CONVERGANCE
* ORIGINAL THEORY AND FORTRAN WRITTEN BY R.N. CAMP AND
* H.F. KING, J. CHEM. PHYS. 75, 268 (1981)
**********************************************************************
*
* ON INPUT N = NUMBER OF ORBITALS
* NP = NUMBER OF FILLED LEVELS
* NQ = NUMBER OF EMPTY LEVELS
* MODE = 1, DO NOT RESET.
* E = ENERGY
* FP = FOCK MATRIX, AS LOWER HALF TRIANGLE, PACKED
* CP = EIGENVECTORS OF FOCK MATRIX OF ITERATION -1
* AS PACKED ARRAY OF N*N COEFFICIENTS
*
* ON OUTPUT CP = BEST GUESSED SET OF EIGENVECTORS
* MODE = 2 OR 3 - USED BY CALLING PROGRAM
**********************************************************************
DIMENSION THETA(MAXORB), IA(MAXORB)
COMMON /KEYWRD/ KEYWRD
COMMON/FIT/NPNTS,IDUM2,XLOW,XHIGH,XMIN,EMIN,DEMIN,X(12),F(12),
1 DF(12)
LOGICAL FIRST, DEBUG, DEBUG1
CHARACTER*80 KEYWRD
DATA ZERO,FF,RADMAX/0.0,0.9,1.5708/,FIRST/.TRUE./
IF(FIRST)THEN
DEBUG=(INDEX(KEYWRD,'INTERP').NE.0)
DEBUG1=(INDEX(KEYWRD,'DEBUG').NE.0.AND.DEBUG)
FIRST=.FALSE.
DO 10 I=1,MAXORB
10 IA(I)=(I*I-I)/2
ENDIF
C
C RADMAX=MAXIMUM ROTATION ANGLE (RADIANS). 1.5708 = 90 DEGREES.
C FF=FACTOR FOR CONVERGENCE TEST FOR 1D SEARCH.
C
MINPQ=MIN0(NP,NQ)
MAXPQ=MAX0(NP,NQ)
NP1=NP+1
NP2=MAX0(1,NP/2)
IF(MODE.EQ.2) GO TO 110
C
C (MODE=1 OR 3 ENTRY)
C TRANSFORM FOCK MATRIX TO CURRENT MO BASIS.
C ONLY THE OFF DIAGONAL OCC-VIRT BLOCK IS COMPUTED.
C STORE IN FOCK ARRAY
C
II=0
DO 50 I=1,N
I1=I+1
DO 40 J=1,NQ
DUM=ZERO
DO 20 K=1,I
20 DUM=DUM+FP(II+K)*CP(K,J+NP)
IF(I.EQ.N) GO TO 40
IK=II+I+I
DO 30 K=I1,N
DUM=DUM+FP(IK)*CP(K,J+NP)
30 IK=IK+K
40 P(I,J)=DUM
50 II=II+I
DO 80 I=1,NP
DO 70 J=1,NQ
DUM=ZERO
DO 60 K=1,N
60 DUM=DUM+CP(K,I)*P(K,J)
FOCK(I,J)=DUM
70 CONTINUE
80 CONTINUE
IF(MODE.EQ.3) GO TO 100
C
C CURRENT POINT BECOMES OLD POINT (MODE=1 ENTRY)
C
DO 90 I=1,N
DO 90 J=1,N
90 VEC(I,J)=CP(I,J)
EOLD=E
XOLD=1.0
MODE=2
RETURN
C
C (MODE=3 ENTRY)
C FOCK CORRESPONDS TO CURRENT POINT IN CORRESPONDING REPRESENTATION.
C VEC DOES NOT HOLD CURRENT VECTORS. VEC SET IN LAST MODE=2 ENTRY.
C
100 NPNTS=NPNTS+1
IF(DEBUG)WRITE(6,'('' INTERPOLATED ENERGY:'',F13.6)')E*23.061D0
IPOINT=NPNTS
GO TO 500
C
C (MODE=2 ENTRY) CALCULATE THETA, AND U, V, W MATRICES.
C U ROTATES CURRENT INTO OLD MO.
C V ROTATES CURRENT INTO CORRESPONDING CURRENT MO.
C W ROTATES OLD INTO CORRESPONDING OLD MO.
C
110 J1=1
DO 140 I=1,N
IF(I.EQ.NP1) J1=NP1
DO 130 J=J1,N
P(I,J)=ZERO
DO 120 K=1,N
120 P(I,J)=P(I,J)+CP(K,I)*VEC(K,J)
130 CONTINUE
140 CONTINUE
C
C U = CP(DAGGER)*VEC IS NOW IN P ARRAY.
C VEC IS NOW AVAILABLE FOR TEMPORARY STORAGE.
C
IJ=0
DO 170 I=1,NP
DO 160 J=1,I
IJ=IJ+1
H(IJ)=0.D0
DO 150 K=NP1,N
150 H(IJ)=H(IJ)+P(I,K)*P(J,K)
160 CONTINUE
170 CONTINUE
CALL HQRII(H,NP,NP,THETA,VECL)
DO 180 I=NP,1,-1
IL=I*NP-NP
DO 180 J=NP,1,-1
180 VEC(J,I)=VECL(J+IL)
DO 200 I=1,NP2
DUM=THETA(NP1-I)
THETA(NP1-I)=THETA(I)
THETA(I)=DUM
DO 190 J=1,NP
DUM=VEC(J,NP1-I)
VEC(J,NP1-I)=VEC(J,I)
190 VEC(J,I)=DUM
200 CONTINUE
DO 210 I=1,MINPQ
THETA(I)=MAX(THETA(I),ZERO)
THETA(I)=MIN(THETA(I),1.D0)
210 THETA(I)=ASIN(SQRT(THETA(I)))
C
C THETA MATRIX HAS NOW BEEN CALCULATED, ALSO UNITARY VP MATRIX
C HAS BEEN CALCULATED AND STORED IN FIRST NP COLUMNS OF VEC MATRIX.
C NOW COMPUTE WQ
C
DO 240 I=1,NQ
DO 230 J=1,MINPQ
VEC(I,NP+J)=ZERO
DO 220 K=1,NP
220 VEC(I,NP+J)=VEC(I,NP+J)+P(K,NP+I)*VEC(K,J)
230 CONTINUE
240 CONTINUE
CALL SCHMIT(VEC(1,NP1),NQ,N)
C
C UNITARY WQ MATRIX NOW IN LAST NQ COLUMNS OF VEC MATRIX.
C TRANSPOSE NP BY NP BLOCK OF U STORED IN P
C
DO 260 I=1,NP
DO 250 J=1,I
DUM=P(I,J)
P(I,J)=P(J,I)
250 P(J,I)=DUM
260 CONTINUE
C
C CALCULATE WP MATRIX AND HOLD IN FIRST NP COLUMNS OF P
C
DO 300 I=1,NP
DO 270 K=1,NP
270 H(K)=P(I,K)
DO 290 J=1,NP
P(I,J)=ZERO
DO 280 K=1,NP
280 P(I,J)=P(I,J)+H(K)*VEC(K,J)
290 CONTINUE
300 CONTINUE
CALL SCHMIB(P,NP,N)
C
C CALCULATE VQ MATRIX AND HOLD IN LAST NQ COLUMNS OF P MATRIX.
C
DO 340 I=1,NQ
DO 310 K=1,NQ
310 H(K)=P(NP+I,NP+K)
DO 330 J=NP1,N
P(I,J)=ZERO
DO 320 K=1,NQ
320 P(I,J)=P(I,J)+H(K)*VEC(K,J)
330 CONTINUE
340 CONTINUE
CALL SCHMIB(P(1,NP1),NQ,N)
C
C CALCULATE (DE/DX) AT OLD POINT
C
DEDX=ZERO
DO 370 I=1,NP
DO 360 J=1,NQ
DUM=ZERO
DO 350 K=1,MINPQ
350 DUM=DUM+THETA(K)*P(I,K)*VEC(J,NP+K)
360 DEDX=DEDX+DUM*FOCK(I,J)
370 CONTINUE
C
C STORE OLD POINT INFORMATION FOR SPLINE FIT
C
DEOLD=-4.0*DEDX
X(2)=XOLD
F(2)=EOLD
DF(2)=DEOLD
C
C MOVE VP OUT OF VEC ARRAY INTO FIRST NP COLUMNS OF P MATRIX.
C
DO 380 I=1,NP
DO 380 J=1,NP
380 P(I,J)=VEC(I,J)
K1=0
K2=NP
DO 410 J=1,N
IF(J.EQ.NP1) K1=NP
IF(J.EQ.NP1) K2=NQ
DO 400 I=1,N
DUM=ZERO
DO 390 K=1,K2
390 DUM=DUM+CP(I,K1+K)*P(K,J)
400 VEC(I,J)=DUM
410 CONTINUE
C
C CORRESPONDING CURRENT MO VECTORS NOW HELD IN VEC.
C COMPUTE VEC(DAGGER)*FP*VEC
C STORE OFF-DIAGONAL BLOCK IN FOCK ARRAY.
C
420 II=0
DO 460 I=1,N
I1=I+1
DO 450 J=1,NQ
DUM=ZERO
DO 430 K=1,I
430 DUM=DUM+FP(II+K)*VEC(K,J+NP)
IF(I.EQ.N) GO TO 450
IK=II+I+I
DO 440 K=I1,N
DUM=DUM+FP(IK)*VEC(K,J+NP)
440 IK=IK+K
450 P(I,J)=DUM
460 II=II+I
DO 490 I=1,NP
DO 480 J=1,NQ
DUM=ZERO
DO 470 K=1,N
470 DUM=DUM+VEC(K,I)*P(K,J)
FOCK(I,J)=DUM
480 CONTINUE
490 CONTINUE
C
C SET LIMITS ON RANGE OF 1-D SEARCH
C
NPNTS=2
IPOINT=1
XNOW=ZERO
XHIGH=RADMAX/THETA(1)
XLOW=-0.5*XHIGH
C
C CALCULATE (DE/DX) AT CURRENT POINT AND
C STORE INFORMATION FOR SPLINE FIT
C ***** JUMP POINT FOR MODE=3 ENTRY *****
C
500 DEDX=ZERO
DO 510 K=1,MINPQ
510 DEDX=DEDX+THETA(K)*FOCK(K,K)
DENOW=-4.0*DEDX
ENOW=E
IF(IPOINT.LE.12) GO TO 530
520 FORMAT(//34H EXCESSIVE DATA PNTS FOR SPLINE./
1,9H IPOINT =,I3,15H MAXIMUM IS 12.)
C
C PERFORM 1-D SEARCH AND DETERMINE EXIT MODE.
C
530 X(IPOINT)=XNOW
F(IPOINT)=ENOW
DF(IPOINT)=DENOW
CALL SPLINE
IF((EOLD-ENOW).GT.FF*(EOLD-EMIN).OR.IPOINT.GT.10) GO TO 560
C
C (MODE=3 EXIT) RECOMPUTE CP VECTORS AT PREDICTED MINIMUM.
C
XNOW=XMIN
DO 550 K=1,MINPQ
CK=COS(XNOW*THETA(K))
SK=SIN(XNOW*THETA(K))
IF(DEBUG)WRITE(6,'('' ROTATION ANGLE:'',F12.4)')SK*57.29578
DO 540 I=1,N
CP(I,K) =CK*VEC(I,K)-SK*VEC(I,NP+K)
540 CP(I,NP+K)=SK*VEC(I,K)+CK*VEC(I,NP+K)
550 CONTINUE
MODE=3
RETURN
C
C (MODE=2 EXIT) CURRENT VECTORS GIVE SATISFACTORY ENERGY IMPROVEMENT
C CURRENT POINT BECOMES OLD POINT FOR THE NEXT 1-D SEARCH.
C
560 IF(MODE.EQ.2) GO TO 580
DO 570 I=1,N
DO 570 J=1,N
570 VEC(I,J)=CP(I,J)
MODE=2
580 ROLD=XOLD*THETA(1)*57.29578
RNOW=XNOW*THETA(1)*57.29578
RMIN=XMIN*THETA(1)*57.29578
IF(DEBUG)WRITE(6,600) XOLD,EOLD*23.061,DEOLD,ROLD
1, XNOW,ENOW*23.061,DENOW,RNOW
2, XMIN,EMIN*23.061,DEMIN,RMIN
EOLD=ENOW
IF(NPNTS.LE.200) RETURN
WRITE(6,610)
DO 590 K=1,NPNTS
590 WRITE(6,620) K,X(K),F(K),DF(K)
WRITE(6,630)
RETURN
600 FORMAT(
1/14X,3H X ,10X,6H F(X) ,9X,7H DF/DX ,21H ROTATION (DEGREES),
2/10H OLD ,F10.5,3F15.10,
3/10H CURRENT ,F10.5,3F15.10,
4/10H PREDICTED,F10.5,3F15.10/)
610 FORMAT(3H K,10H X(K) ,15H F(K) ,10H DF(K))
620 FORMAT(I3,F10.5,2F15.10)
630 FORMAT(10X)
END
|
-- Andreas, 2011-05-30
-- {-# OPTIONS -v tc.lhs.unify:50 #-}
module Issue292c where
data ⊥ : Set where
infix 3 ¬_
¬_ : Set → Set
¬ P = P → ⊥
infix 4 _≅_
data _≅_ {A : Set} (x : A) : ∀ {B : Set} → B → Set where
refl : x ≅ x
record Σ (A : Set) (B : A → Set) : Set where
constructor _,_
field
proj₁ : A
proj₂ : B proj₁
open Σ public
data Bool : Set where true false : Bool
data Unit1 : Set where unit1 : Unit1
data Unit2 : Set where unit2 : Unit2
D : Bool -> Set
D true = Unit1
D false = Unit2
P : Set -> Set
P S = Σ S (\s → s ≅ unit1)
pbool : P (D true)
pbool = unit1 , refl
¬pbool2 : ¬ P (D false)
¬pbool2 ( unit2 , () )
{- expected error
unit2 ≅ unit1 should be empty, but that's not obvious to me
when checking that the clause ¬pbool2 (unit2 , ()) has type
¬ P (D false)
-}
|
numerous aunts, uncles and cousins. She attended Shanksville Stonycreek High School and was a member of St. Paul's Lutheran Church, Buckstown. Family will receive friends from 2 to 4 p.m. and 6 p.m. until time of service at 8 p.m. Sunday at the Deaner Funeral Home, Stoystown. Rev. Robert Way officiating. Interment Lambertsville Cemetery. Contributions may be given to assist the family c/o Kay Grasser 158 Juniata St., Berlin, PA 15530, or to St. Paul's Lutheran Church, 6872 Lincoln Hwy., Stoystown, PA 15563. DeanerFuneralsAndCremations.com. |
#include <boost/test/unit_test.hpp>
#include "algorithms/data_structures/array/find_pivot_index.hpp"
BOOST_AUTO_TEST_SUITE(TestFindPivotIndex)
BOOST_AUTO_TEST_CASE(invalid_arrays)
{
std::vector<int> nums = { };
BOOST_CHECK(-1 == Algo::DS::Array::FindPivot::PivotIndex(nums));
nums = { 1 };
BOOST_CHECK(-1 == Algo::DS::Array::FindPivot::PivotIndex(nums));
nums = { 1, 2 };
BOOST_CHECK(-1 == Algo::DS::Array::FindPivot::PivotIndex(nums));
}
BOOST_AUTO_TEST_CASE(valid_arrays)
{
std::vector<int> nums = {0, 0, 0};
BOOST_CHECK(0 == Algo::DS::Array::FindPivot::PivotIndex(nums));
nums = {1, 2, 3};
BOOST_CHECK(-1 == Algo::DS::Array::FindPivot::PivotIndex(nums));
nums = {1, 7, 3, 6, 5, 6};
BOOST_CHECK(3 == Algo::DS::Array::FindPivot::PivotIndex(nums));
}
BOOST_AUTO_TEST_SUITE_END()
|
##############################################################################################
# 1. Importing original data set of Stack Overflow 2018 Developer Survey
original_data <- read.csv("Stack_Overflow_2018_Developer_Public_Survey.csv")
# 1.1. Randomly choosing 1000 rows from the original data (*default seed)
random_sample <- original_data[sample(1:nrow(original_data), 1000),]
##############################################################################################
# 2. Performing basic descriptive statistics on the random sample
sink('random_sample_summary.txt')
summary(random_sample)
sink()
##############################################################################################
# 3. Data visualization of all the yearly salaries in the random sample
hist(random_sample$Yearly.Salary.in.USD, main = "Salary Distribution Amongst Stock Overflow Developer Survey Respondents", ylab = "Number of Respondents", xlab = "Yearly Salary ($)")
##############################################################################################
# 4. Analysis of the shared variability between "Open Source" and "Yearly Salary in USD"
developer_opinion <- plot(random_sample$Open.Source, random_sample$Yearly.Salary.in.USD, main = "Stock Overflow Developer Survey: Respondent Yearly Salary ($) vs Stance on Open Source Software", ylab = "Yearly Salary ($)", xlab = "Stance on open source software", col=7:6)
developer_opinion_no <- developer_opinion$stats[,1]
developer_opinion_yes <- developer_opinion$stats[,2]
sink('final_analysis.txt')
print(' Min. Lower Qu. Median Upper Qu. Max')
print(developer_opinion_no)
print(developer_opinion_yes)
sink() |
lemma convex_imp_contractible: fixes S :: "'a::real_normed_vector set" shows "convex S \<Longrightarrow> contractible S" |
State Before: 𝕜 : Type u_1
E : Type u_2
inst✝² : NontriviallyNormedField 𝕜
inst✝¹ : NormedAddCommGroup E
inst✝ : NormedSpace 𝕜 E
f : 𝕜 → E
a b : 𝕜
s : Set 𝕜
h : b ≠ a
⊢ DifferentiableAt 𝕜 (dslope f a) b ↔ DifferentiableAt 𝕜 f b State After: no goals Tactic: simp only [← differentiableWithinAt_univ, differentiableWithinAt_dslope_of_ne h] |
-- --------------------------------------------------------------- [ Error.idr ]
-- Module : Error.idr
-- Copyright : (c) Jan de Muijnck-Hughes
-- License : see LICENSE
-- --------------------------------------------------------------------- [ EOH ]
module Freyja.Error
import XML.XPath
%access public export
data FreyjaError : Type where
ExtractionError : XPathError -> FreyjaError
GeneralError : String -> FreyjaError
TextConvError : String -> FreyjaError
MalformedDocError : String -> String -> FreyjaError
Show FreyjaError where
show (ExtractionError msg) = unwords ["Extraction Error", show msg]
show (TextConvError msg) = unwords ["Text Conversion Error", show msg]
show (GeneralError msg) = msg
show (MalformedDocError qstr msg) =
unlines [ "Malformed Document Error."
, " The query:"
, unwords ["\t", show qstr]
, "was expected to work,"
, msg]
Extract : Type -> Type
Extract a = Either FreyjaError a
-- --------------------------------------------------------------------- [ EOF ]
|
classdef DTLZ9 < PROBLEM
% <multi/many> <real> <large/none> <constrained> <expensive/none>
% Benchmark MOP proposed by Deb, Thiele, Laumanns, and Zitzler
%------------------------------- Reference --------------------------------
% K. Deb, L. Thiele, M. Laumanns, and E. Zitzler, Scalable test problems
% for evolutionary multiobjective optimization, Evolutionary multiobjective
% Optimization. Theoretical Advances and Applications, 2005, 105-145.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------
methods
%% Default settings of the problem
function Setting(obj)
if isempty(obj.M); obj.M = 2; end
if isempty(obj.D); obj.D = 10*obj.M; end
obj.D = ceil(obj.D/obj.M)*obj.M;
obj.lower = zeros(1,obj.D);
obj.upper = ones(1,obj.D);
obj.encoding = ones(1,obj.D);
end
%% Calculate objective values and constraint violations
function Population = Evaluation(obj,varargin)
PopDec = varargin{1};
PopDec = max(min(PopDec,repmat(obj.upper,size(PopDec,1),1)),repmat(obj.lower,size(PopDec,1),1));
X = PopDec;
PopDec = PopDec.^0.1;
PopObj = zeros(size(PopDec,1),obj.M);
for m = 1 : obj.M
PopObj(:,m) = sum(PopDec(:,(m-1)*obj.D/obj.M+1:m*obj.D/obj.M),2);
end
PopCon = 1 - repmat(PopObj(:,obj.M).^2,1,obj.M-1) - PopObj(:,1:obj.M-1).^2;
Population = SOLUTION(X,PopObj,PopCon,varargin{2:end});
obj.FE = obj.FE + length(Population);
end
%% Generate points on the Pareto front
function R = GetOptimum(obj,N)
Temp = (0:1/(N-1):1)';
R = [repmat(cos(0.5.*pi.*Temp),1,obj.M-1),sin(0.5.*pi.*Temp)];
end
%% Generate the image of Pareto front
function R = GetPF(obj)
if obj.M < 4
R = obj.GetOptimum(100);
else
R = [];
end
end
end
end |
{-
(1, 1)
System.Collections.Generic.HashSet`1[System.Tuple`2[System.Int32,System.Int32]]
True
False
True
False
-}
import CIL.FFI
TupleTy : CILTy
TupleTy = corlibTy "System.Tuple"
IntTupleTy : CILTy
IntTupleTy = CILTyGen TupleTy [CILTyInt32, CILTyInt32]
IntTuple : Type
IntTuple = CIL IntTupleTy
IsA Object IntTuple where {}
CreateIntTuple : Int -> Int -> CIL_IO IntTuple
CreateIntTuple =
invoke (CILCall (CILGenMethod CCCStatic TupleTy "Create" [CILTyInt32, CILTyInt32]
[CILTyGenMethodParam "0", CILTyGenMethodParam "1"]
(CILTyGen TupleTy [CILTyGenMethodParam "0", CILTyGenMethodParam "1"])))
(Int -> Int -> CIL_IO IntTuple)
systemCollectionsTy : String -> CILTy
systemCollectionsTy = CILTyRef "System.Collections"
HashSetTy : CILTy
HashSetTy = systemCollectionsTy "System.Collections.Generic.HashSet"
IntTupleHashSet : Type
IntTupleHashSet = CIL (CILTyGen HashSetTy [IntTupleTy])
IsA Object IntTupleHashSet where {}
Add : IntTupleHashSet -> IntTuple -> CIL_IO Bool
Add =
invoke (CILInstanceCustom "Add" [CILTyGenParam "0"] CILTyBool)
(IntTupleHashSet -> IntTuple -> CIL_IO Bool)
Contains : IntTupleHashSet -> IntTuple -> CIL_IO Bool
Contains =
invoke (CILInstanceCustom "Contains" [CILTyGenParam "0"] CILTyBool)
(IntTupleHashSet -> IntTuple -> CIL_IO Bool)
AssemblyReferences : CIL_IO ()
AssemblyReferences =
assemblyRef "System.Collections" "4.0.10.0" "B0 3F 5F 7F 11 D5 0A 3A"
main : CIL_IO ()
main = do
AssemblyReferences
CreateIntTuple 1 1 >>= ToString >>= putStrLn
set <- new (CIL_IO IntTupleHashSet)
ToString set >>= putStrLn
CreateIntTuple 1 1 >>= Add set >>= printLn
CreateIntTuple 1 1 >>= Add set >>= printLn
CreateIntTuple 1 1 >>= Contains set >>= printLn
CreateIntTuple 1 2 >>= Contains set >>= printLn
-- Local Variables:
-- idris-load-packages: ("cil")
-- End:
|
theory SNOC
imports
Main
begin
fun snoc :: "'a list \<Rightarrow> 'a \<Rightarrow> 'a list" where
"snoc Nil e = (Cons e Nil)" |
"snoc (Cons x xs) e = (Cons x (snoc xs e))"
lemma rev_app_back:
shows "xs @ [x] = snoc xs x"
proof(induct xs arbitrary: x)
case Nil
then show ?case by simp
next
case (Cons a xs)
then show ?case by simp
qed
theorem rev_cons:
shows "rev (x # xs) = snoc (rev xs) x"
proof(induct xs arbitrary: x)
case Nil
then show ?case by simp
next
case (Cons a xs)
then show ?case using rev_app_back by auto
qed
end |
module SystemF.Syntax.Term where
open import Prelude
open import SystemF.Syntax.Type
infixl 9 _[_] _·_
data Term (ν n : ℕ) : Set where
var : (x : Fin n) → Term ν n
Λ : Term (suc ν) n → Term ν n
λ' : Type ν → Term ν (suc n) → Term ν n
_[_] : Term ν n → Type ν → Term ν n
_·_ : Term ν n → Term ν n → Term ν n
|
function [qp]=da2(input)
% [qp] = da2(input)
% Dahlin's controller for processes of 2nd order.
% This function computes parameters of the controller (q0, q1, q2, p1, p2).
% Transfer function of the controller is as follows:
%
% q0 + q1*z^-1 + q2*z^-2 q0 + q1*z^-1 + q2*z^-2
% G(z^-1) = ------------------------ = ------------------------
% 1 - z^-1 1 + p1*z^-1 + p2*z^-2
%
% where p1=-1 and p2=0.
%
% Transfer function of the controlled system is:
%
% b1*z^-1
% Gs(z^-1) = -----------------------
% 1 + a1*z^-1 + a2*z^-2
%
% Input: input ... input parameters
% input(1) ... a1
% input(2) ... b1
% input(3) ... a2
% input(4) ... sample time T0
% input(5) ... adjustment factor B
% Output: qp ... controller parameters
% qp(1) ... q0
% qp(2) ... q1
% qp(3) ... q2
% qp(4) ... -1 (p1 of the controller)
% qp(5) ... 0 (p2 of the controller)
a1 = input(1);
b1 = input(2);
a2 = input(3);
T0 = input(4);
B = input(5);
% check inputs
if (T0 <= 0)
disp('da2.m: Input parameter T0 (sample time) must be greater than 0');
disp(' parameter value has been changed to 1');
T0 = 1;
end;
if (B <= 0)
disp('da2.m: Input parameter B (adjustment factor) must be greater than 0');
disp(' parameter value has been changed to 1e-6');
B = 1e-6;
end;
Q = 1-exp(-T0/B);
Kp = -(a1+2*a2)*Q/b1;
Td = T0*a2*Q/(Kp*b1);
Ti = -T0/((1/(a1+2*a2))+1+Td/T0);
q0 = Kp*(1+T0/Ti+Td/T0);
q1 = -Kp*(1+2*Td/T0);
q2 = Kp*Td/T0;
p1 = -1;
p2 = 0;
qp=[q0; q1; q2; p1; p2]; |
import data.list init.algebra.classes
import tactic.norm_num tactic.tauto tactic.rewrite tactic.rewrite_all tactic.omega tactic.tidy
import tactic.hint
variables {α: Type*}
variables [semiring α]
@[simp]
theorem map_id {l: list α}: list.map (λ x, x) l = l := begin
induction l, reflexivity, simp, assumption,
end
theorem map_forall {β: Type*} {l: list α} {f: α -> β} {p: β -> Prop} (h: ∀ b:β, p b):
(∀ a ∈ l, p (f a)) -> ∀ b ∈ (list.map f l), p b := by tidy
@[simp]
def scalar_l (x: α) (l: list α) := list.map (λ y, x*y) l
infixr `[*]`:1000 := scalar_l
@[simp]
def scalar_add_l (x: α) (l: list α) := list.map (λ y, x+y) l
infixr `[+]`:500 := scalar_add_l
@[simp]
def scalar_r (l: list α) (x: α) := list.map (λ y, y*x) l
@[simp]
def scalar_add_r (l: list α) (x: α) := list.map (λ y, y+x) l
@[simp]
def tensor : list α -> list α -> list α
| [] ys := []
| (x::xs) ys := (x [*] ys) ++ (tensor xs ys)
infixr `<*>` := tensor
infixr ` ⊗`:1000 := tensor
@[simp]
def vec_add: list α -> list α -> list α
| [] ys := ys
| xs [] := xs
| (x::xs) (y::ys) := (x+y)::(vec_add xs ys)
infixr `<+>`:500 := vec_add
@[simp]
theorem scalar_l_sum {x: α} {l: list α}: (x [*] l).sum = x * l.sum := begin
induction l, simp,
case list.cons: hd tl ih {
rw list.sum_cons,
simp,
simp at ih,
rw ih,
rw left_distrib,
}
end
@[simp]
theorem scalar_l_cons {x y: α} {l: list α}: (x [*] (y::l)) = (x*y)::(x [*] l) := by simp
@[simp]
theorem add_scalar_l_distrib {x y: α} {l: list α}: (x + y) [*] l = (x[*]l) <+> (y[*]l) := begin
induction l, reflexivity,
case list.cons: hd tl ih {
repeat {rw scalar_l_cons },
rw ih,
simp,
rw semiring.right_distrib,
reflexivity,
}
end
@[simp]
theorem tensor_l_id {l: list α}: [1] <*> l = l := begin
induction l, reflexivity,
case list.cons: hd tl ih {
simp,
}
end
@[simp]
theorem tensor_r_id {l: list α}: l <*> [1] = l := begin
induction l,
reflexivity,
simp, assumption,
end
@[simp]
theorem tensor_sum {l1 l2: list α}: (l1 <*> l2).sum = l1.sum * l2.sum := begin
induction l1, {
rw tensor, simp,
},
case list.cons: hd tl ih {
rw list.sum_cons,
rw right_distrib,
rw tensor,
rw list.sum_append,
rw scalar_l_sum,
rw ih,
}
end
-- geom (n, e) = [n^0, n^1, ..., n^e]
@[simp, reducible]
def geom (p: α × ℕ) := list.map (λ c, (p.1 ^ c)) (list.range (p.2+1))
notation `<|` p `|>` := geom p
@[simp]
theorem geom_zero (e: α): <| (e, 0) |> = [1] := rfl
@[simp]
theorem geom_succ (p: α × ℕ): <| (p.1, p.2+1) |> = 1::(p.1 [*] <| p |>) := begin
simp,
repeat { rw add_comm, rw list.range_succ_eq_map, rw list.map_cons},
simp,
have: (pow p.fst) ∘ nat.succ ∘ nat.succ = (pow p.fst ∘ nat.succ) ∘ nat.succ, by simp,
rw this, clear this,
have: (pow p.fst ∘ nat.succ) = (has_mul.mul p.fst ∘ pow p.fst), {
apply funext,
intro,
simp,
rw pow_succ,
},
rw this,
end |
/-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Chris Hughes, Michael Howes
-/
import data.fintype.basic
import algebra.group.hom
import algebra.group.semiconj
import data.equiv.mul_add_aut
import algebra.group_with_zero.basic
/-!
# Conjugacy of group elements
See also `mul_aut.conj` and `quandle.conj`.
-/
universes u v
variables {α : Type u} {β : Type v}
section monoid
variables [monoid α] [monoid β]
/-- We say that `a` is conjugate to `b` if for some unit `c` we have `c * a * c⁻¹ = b`. -/
def is_conj (a b : α) := ∃ c : units α, semiconj_by ↑c a b
@[refl] lemma is_conj.refl (a : α) : is_conj a a :=
⟨1, semiconj_by.one_left a⟩
@[symm] lemma is_conj.symm {a b : α} : is_conj a b → is_conj b a
| ⟨c, hc⟩ := ⟨c⁻¹, hc.units_inv_symm_left⟩
@[trans] lemma is_conj.trans {a b c : α} : is_conj a b → is_conj b c → is_conj a c
| ⟨c₁, hc₁⟩ ⟨c₂, hc₂⟩ := ⟨c₂ * c₁, hc₂.mul_left hc₁⟩
@[simp] lemma is_conj_iff_eq {α : Type*} [comm_monoid α] {a b : α} : is_conj a b ↔ a = b :=
⟨λ ⟨c, hc⟩, begin
rw [semiconj_by, mul_comm, ← units.mul_inv_eq_iff_eq_mul, mul_assoc, c.mul_inv, mul_one] at hc,
exact hc,
end, λ h, by rw h⟩
protected lemma monoid_hom.map_is_conj (f : α →* β) {a b : α} : is_conj a b → is_conj (f a) (f b)
| ⟨c, hc⟩ := ⟨units.map f c, by rw [units.coe_map, semiconj_by, ← f.map_mul, hc.eq, f.map_mul]⟩
end monoid
section group
variables [group α]
@[simp] lemma is_conj_iff {a b : α} :
is_conj a b ↔ ∃ c : α, c * a * c⁻¹ = b :=
⟨λ ⟨c, hc⟩, ⟨c, mul_inv_eq_iff_eq_mul.2 hc⟩, λ ⟨c, hc⟩,
⟨⟨c, c⁻¹, mul_inv_self c, inv_mul_self c⟩, mul_inv_eq_iff_eq_mul.1 hc⟩⟩
@[simp] lemma is_conj_one_right {a : α} : is_conj 1 a ↔ a = 1 :=
⟨λ ⟨c, hc⟩, mul_right_cancel (hc.symm.trans ((mul_one _).trans (one_mul _).symm)), λ h, by rw [h]⟩
@[simp] lemma is_conj_one_left {a : α} : is_conj a 1 ↔ a = 1 :=
calc is_conj a 1 ↔ is_conj 1 a : ⟨is_conj.symm, is_conj.symm⟩
... ↔ a = 1 : is_conj_one_right
@[simp] lemma conj_inv {a b : α} : (b * a * b⁻¹)⁻¹ = b * a⁻¹ * b⁻¹ :=
((mul_aut.conj b).map_inv a).symm
@[simp] lemma conj_mul {a b c : α} : (b * a * b⁻¹) * (b * c * b⁻¹) = b * (a * c) * b⁻¹ :=
((mul_aut.conj b).map_mul a c).symm
@[simp] lemma conj_pow {i : ℕ} {a b : α} : (a * b * a⁻¹) ^ i = a * (b ^ i) * a⁻¹ :=
begin
induction i with i hi,
{ simp },
{ simp [pow_succ, hi] }
end
@[simp] lemma conj_zpow {i : ℤ} {a b : α} : (a * b * a⁻¹) ^ i = a * (b ^ i) * a⁻¹ :=
begin
induction i,
{ simp },
{ simp [zpow_neg_succ_of_nat, conj_pow] }
end
lemma conj_injective {x : α} : function.injective (λ (g : α), x * g * x⁻¹) :=
(mul_aut.conj x).injective
end group
@[simp] lemma is_conj_iff₀ [group_with_zero α] {a b : α} :
is_conj a b ↔ ∃ c : α, c ≠ 0 ∧ c * a * c⁻¹ = b :=
⟨λ ⟨c, hc⟩, ⟨c, begin
rw [← units.coe_inv', units.mul_inv_eq_iff_eq_mul],
exact ⟨c.ne_zero, hc⟩,
end⟩, λ ⟨c, c0, hc⟩,
⟨units.mk0 c c0, begin
rw [semiconj_by, ← units.mul_inv_eq_iff_eq_mul, units.coe_inv', units.coe_mk0],
exact hc
end⟩⟩
namespace is_conj
/- This small quotient API is largely copied from the API of `associates`;
where possible, try to keep them in sync -/
/-- The setoid of the relation `is_conj` iff there is a unit `u` such that `u * x = y * u` -/
protected def setoid (α : Type*) [monoid α] : setoid α :=
{ r := is_conj, iseqv := ⟨is_conj.refl, λa b, is_conj.symm, λa b c, is_conj.trans⟩ }
end is_conj
local attribute [instance, priority 100] is_conj.setoid
/-- The quotient type of conjugacy classes of a group. -/
def conj_classes (α : Type*) [monoid α] : Type* :=
quotient (is_conj.setoid α)
namespace conj_classes
section monoid
variables [monoid α] [monoid β]
/-- The canonical quotient map from a monoid `α` into the `conj_classes` of `α` -/
protected def mk {α : Type*} [monoid α] (a : α) : conj_classes α :=
⟦a⟧
instance : inhabited (conj_classes α) := ⟨⟦1⟧⟩
theorem mk_eq_mk_iff_is_conj {a b : α} :
conj_classes.mk a = conj_classes.mk b ↔ is_conj a b :=
iff.intro quotient.exact quot.sound
theorem quotient_mk_eq_mk (a : α) : ⟦ a ⟧ = conj_classes.mk a := rfl
theorem quot_mk_eq_mk (a : α) : quot.mk setoid.r a = conj_classes.mk a := rfl
theorem forall_is_conj {p : conj_classes α → Prop} :
(∀a, p a) ↔ (∀a, p (conj_classes.mk a)) :=
iff.intro
(assume h a, h _)
(assume h a, quotient.induction_on a h)
theorem mk_surjective : function.surjective (@conj_classes.mk α _) :=
forall_is_conj.2 (λ a, ⟨a, rfl⟩)
instance : has_one (conj_classes α) := ⟨⟦ 1 ⟧⟩
theorem one_eq_mk_one : (1 : conj_classes α) = conj_classes.mk 1 := rfl
lemma exists_rep (a : conj_classes α) : ∃ a0 : α, conj_classes.mk a0 = a :=
quot.exists_rep a
/-- A `monoid_hom` maps conjugacy classes of one group to conjugacy classes of another. -/
def map (f : α →* β) : conj_classes α → conj_classes β :=
quotient.lift (conj_classes.mk ∘ f) (λ a b ab, mk_eq_mk_iff_is_conj.2 (f.map_is_conj ab))
instance [fintype α] [decidable_rel (is_conj : α → α → Prop)] :
fintype (conj_classes α) :=
quotient.fintype (is_conj.setoid α)
end monoid
section comm_monoid
variable [comm_monoid α]
lemma mk_injective : function.injective (@conj_classes.mk α _) :=
λ _ _, (mk_eq_mk_iff_is_conj.trans is_conj_iff_eq).1
lemma mk_bijective : function.bijective (@conj_classes.mk α _) :=
⟨mk_injective, mk_surjective⟩
/-- The bijection between a `comm_group` and its `conj_classes`. -/
def mk_equiv : α ≃ conj_classes α :=
⟨conj_classes.mk, quotient.lift id (λ (a : α) b, is_conj_iff_eq.1), quotient.lift_mk _ _,
begin
rw [function.right_inverse, function.left_inverse, forall_is_conj],
intro x,
rw [← quotient_mk_eq_mk, ← quotient_mk_eq_mk, quotient.lift_mk, id.def],
end⟩
end comm_monoid
end conj_classes
section monoid
variables [monoid α]
/-- Given an element `a`, `conjugates a` is the set of conjugates. -/
def conjugates_of (a : α) : set α := {b | is_conj a b}
lemma mem_conjugates_of_self {a : α} : a ∈ conjugates_of a := is_conj.refl _
lemma is_conj.conjugates_of_eq {a b : α} (ab : is_conj a b) :
conjugates_of a = conjugates_of b :=
set.ext (λ g, ⟨λ ag, (ab.symm).trans ag, λ bg, ab.trans bg⟩)
lemma is_conj_iff_conjugates_of_eq {a b : α} :
is_conj a b ↔ conjugates_of a = conjugates_of b :=
⟨is_conj.conjugates_of_eq, λ h, begin
have ha := mem_conjugates_of_self,
rwa ← h at ha,
end⟩
end monoid
namespace conj_classes
variables [monoid α]
local attribute [instance] is_conj.setoid
/-- Given a conjugacy class `a`, `carrier a` is the set it represents. -/
def carrier : conj_classes α → set α :=
quotient.lift conjugates_of (λ (a : α) b ab, is_conj.conjugates_of_eq ab)
lemma mem_carrier_mk {a : α} : a ∈ carrier (conj_classes.mk a) := is_conj.refl _
lemma mem_carrier_iff_mk_eq {a : α} {b : conj_classes α} :
a ∈ carrier b ↔ conj_classes.mk a = b :=
begin
revert b,
rw forall_is_conj,
intro b,
rw [carrier, eq_comm, mk_eq_mk_iff_is_conj, ← quotient_mk_eq_mk, quotient.lift_mk],
refl,
end
lemma carrier_eq_preimage_mk {a : conj_classes α} :
a.carrier = conj_classes.mk ⁻¹' {a} :=
set.ext (λ x, mem_carrier_iff_mk_eq)
end conj_classes
|
The NS @-@ 10 displaced the <unk> 5C Sound Cube as the nearfield monitor of choice in the 1980s and was recognised for its ability to reveal shortcomings in recordings . It probably first reached American shores through a recording engineer 's visit to Japan . The engineer , likely to have been Greg Ladanyi , monitored a recording session through the speaker in a Japanese studio and brought a pair back on his return to the US . Ladanyi then began using the speakers in a Los Angeles studio . Other engineers heard the NS @-@ 10 for the first time and were impressed by its sound . Its use spread to New York where the NS @-@ 10 was adopted at The Power Station and other studios .
|
using Slack
mutable struct channel
is_private::Bool
pending_connected_team_ids
topic
is_archived::Bool
is_general::Bool
is_mpim::Bool
name
previous_names
num_members::Int64
is_im::Bool
id
created::Int64
name_normalized
is_group::Bool
purpose
creator
is_channel::Bool
pending_shared
is_shared::Bool
is_ext_shared::Bool
shared_team_ids
is_member::Bool
parent_conversation
is_pending_ext_shared::Bool
is_org_shared::Bool
end
"""
getchannels(token::String)
Takes in the Slack App Auth token and returns a array of channel objects.
The main value in a channel object is the Channel ID and name which you
need in order to send threaded messages to Slack.
Tokens can be accessed at "https://api.slack.com/apps/random-letters-and-numbers/oauth?"
"""
function getchannels(token::String)
HTTP.setuseragent!("HTTP.jl")
url = "https://slack.com/api/conversations.list?token=$(token)"
r = HTTP.get(url, ["Content-Type" => "application/json"])
json_obj = JSON.parse(String(r.body))
channel_holder = []
for (k,v) in json_obj
if occursin("channels", k)
for item in v
is_private = false
pending_connected_team_ids = []
topic = []
is_archived = false
is_general = false
is_mpim = false
name = ""
previous_names = []
num_members = 0
is_im = false
id = ""
created = 0
name_normalized = ""
is_group = false
purpose = []
creator = ""
is_channel = false
pending_shared = []
is_shared = false
is_ext_shared = false
shared_team_ids = []
is_member = false
parent_conversation = []
is_pending_ext_shared = false
is_org_shared = false
for (key,value) in item
if occursin("is_private", key)
is_private = value
elseif occursin("pending_connected_team_ids", key)
pending_connected_team_ids = value
elseif occursin("topic", key)
topic = value
elseif occursin("is_archived", key)
is_archived = value
elseif occursin("is_general", key)
is_general = value
elseif occursin("is_mpim", key)
is_mpim = value
elseif occursin("name", key)
name = value
elseif occursin("previous_names", key)
previous_names = value
elseif occursin("num_members", key)
num_members = value
elseif occursin("is_im", key)
is_im = value
elseif "id" == key
id = value
elseif occursin("created", key)
created = value
elseif occursin("name_normalized", key)
name_normalized = value
elseif occursin("is_group", key)
is_group = value
elseif occursin("purpose", key)
purpose = value
elseif occursin("creator", key)
creator = value
elseif occursin("is_channel", key)
is_channel = value
elseif occursin("pending_shared", key)
pending_shared = value
elseif occursin("is_shared", key)
is_shared = value
elseif occursin("is_ext_shared", key)
is_ext_shared = value
elseif occursin("shared_team_ids", key)
shared_team_ids = value
elseif occursin("is_member", key)
is_member = value
elseif occursin("parent_conversation", key)
parent_conversation = value
elseif occursin("is_pending_ext_shared", key)
is_pending_ext_shared = value
elseif occursin("is_org_shared", key)
is_org_shared = value
end
# println("$(key) $(value)") #DEBUG
end
new_channel = channel(is_private, pending_connected_team_ids, topic, is_archived, is_general,
is_mpim, name, previous_names, num_members, is_im, id, created, name_normalized,
is_group, purpose, creator, is_channel, pending_shared, is_shared, is_ext_shared,
shared_team_ids, is_member, parent_conversation, is_pending_ext_shared, is_org_shared)
push!(channel_holder, new_channel)
end
end
end
return (channel_holder)
end
|
(* Author: Tobias Nipkow *)
theory Radix_Sort
imports
"HOL-Library.List_Lexorder"
"HOL-Library.Sublist"
"HOL-Library.Multiset"
begin
text \<open>The \<open>Radix_Sort\<close> locale provides a sorting function \<open>radix_sort\<close> that sorts
lists of lists. It is parameterized by a sorting function \<open>sort1 f\<close> that also sorts
lists of lists, but only w.r.t. the column selected by \<open>f\<close>.
Working with lists, \<open>f\<close> is instantiated with \<^term>\<open>\<lambda>xs. xs ! n\<close> to select the \<open>n\<close>-th element.
A more efficient implementation would sort lists of arrays because arrays support
constant time access to every element.\<close>
locale Radix_Sort =
fixes sort1 :: "('a list \<Rightarrow> 'a::linorder) \<Rightarrow> 'a list list \<Rightarrow> 'a list list"
assumes sorted: "sorted (map f (sort1 f xss))"
assumes mset: "mset (sort1 f xss) = mset xss"
assumes stable: "stable_sort_key sort1"
begin
lemma set_sort1[simp]: "set(sort1 f xss) = set xss"
by (metis mset set_mset_mset)
abbreviation "sort_col i xss \<equiv> sort1 (\<lambda>xs. xs ! i) xss"
abbreviation "sorted_col i xss \<equiv> sorted (map (\<lambda>xs. xs ! i) xss)"
fun radix_sort :: "nat \<Rightarrow> 'a list list \<Rightarrow> 'a list list" where
"radix_sort 0 xss = xss" |
"radix_sort (Suc i) xss = radix_sort i (sort_col i xss)"
lemma mset_radix_sort: "mset (radix_sort i xss) = mset xss"
by(induction i arbitrary: xss) (auto simp: mset)
abbreviation "sorted_from i xss \<equiv> sorted (map (drop i) xss)"
definition "cols xss n = (\<forall>xs \<in> set xss. length xs = n)"
lemma cols_sort1: "cols xss n \<Longrightarrow> cols (sort1 f xss) n"
by(simp add: cols_def)
lemma sorted_from_Suc2:
"\<lbrakk> cols xss n; i < n;
sorted_col i xss;
\<And>x. sorted_from (i+1) [ys \<leftarrow> xss. ys!i = x] \<rbrakk>
\<Longrightarrow> sorted_from i xss"
proof(induction xss rule: induct_list012)
case 1 show ?case by simp
next
case 2 show ?case by simp
next
case (3 xs1 xs2 xss)
have lxs1: "length xs1 = n" and lxs2: "length xs2 = n"
using "3.prems"(1) by(auto simp: cols_def)
have *: "drop i xs1 \<le> drop i xs2"
proof -
have "drop i xs1 = xs1!i # drop (i+1) xs1"
using \<open>i < n\<close> by (simp add: Cons_nth_drop_Suc lxs1)
also have "\<dots> \<le> xs2!i # drop (i+1) xs2"
using "3.prems"(3) "3.prems"(4)[of "xs2!i"] by(auto)
also have "\<dots> = drop i xs2"
using \<open>i < n\<close> by (simp add: Cons_nth_drop_Suc lxs2)
finally show ?thesis .
qed
have "sorted_from i (xs2 # xss)"
proof(rule "3.IH"[OF _ "3.prems"(2)])
show "cols (xs2 # xss) n" using "3.prems"(1) by(simp add: cols_def)
show "sorted_col i (xs2 # xss)" using "3.prems"(3) by simp
show "\<And>x. sorted_from (i+1) [ys\<leftarrow>xs2 # xss . ys ! i = x]"
using "3.prems"(4)
sorted_antimono_suffix[OF map_mono_suffix[OF filter_mono_suffix[OF suffix_ConsI[OF suffix_order.refl]]]]
by fastforce
qed
with * show ?case by (auto)
qed
lemma sorted_from_radix_sort_step:
assumes "cols xss n" and "i < n" and "sorted_from (i+1) xss"
shows "sorted_from i (sort_col i xss)"
proof (rule sorted_from_Suc2[OF cols_sort1[OF assms(1)] assms(2)])
show "sorted_col i (sort_col i xss)" by(simp add: sorted)
fix x show "sorted_from (i+1) [ys \<leftarrow> sort_col i xss . ys ! i = x]"
proof -
from assms(3)
have "sorted_from (i+1) (filter (\<lambda>ys. ys!i = x) xss)"
by(rule sorted_filter)
thus "sorted (map (drop (i+1)) (filter (\<lambda>ys. ys!i = x) (sort_col i xss)))"
by (metis stable stable_sort_key_def)
qed
qed
lemma sorted_from_radix_sort:
"\<lbrakk> cols xss n; i \<le> n; sorted_from i xss \<rbrakk> \<Longrightarrow> sorted_from 0 (radix_sort i xss)"
proof(induction i arbitrary: xss)
case 0 thus ?case by simp
next
case (Suc i)
thus ?case by(simp add: sorted_from_radix_sort_step cols_sort1)
qed
corollary sorted_radix_sort: "cols xss n \<Longrightarrow> sorted (radix_sort n xss)"
apply(frule sorted_from_radix_sort[OF _ le_refl])
apply(auto simp add: cols_def sorted_iff_nth_mono)
done
end
end
|
After the season ended York released Tom Allan , Andrew , Dickinson , McDonald , Puri and Reed , while McGurk retired from professional football . Bowman and Oyebanjo left to sign for Torquay and Crawley Town respectively while Coulson signed a new contract with the club . York 's summer signings included goalkeeper Jason Mooney from Tranmere Rovers , defenders Femi Ilesanmi from Dagenham , Marvin McCoy from Wycombe and Dave Winfield from Shrewsbury Town , midfielders Lindon Meikle from Mansfield , Anthony Straker from Southend and Luke Summerfield from Shrewsbury and striker Jake Hyde from Barnet .
|
import category_theory.preadditive
import algebraic_topology.cech_nerve
import for_mathlib.simplicial.complex
import for_mathlib.arrow.split
namespace category_theory
universes v u v' u'
namespace arrow
noncomputable theory
open_locale simplicial
open category_theory.limits
variables {C : Type u} [category.{v} C] (f : arrow C)
variables [∀ n : ℕ, has_wide_pullback f.right (λ i : fin (n+1), f.left) (λ i, f.hom)]
/-- The splittings of the Cech nerve associated to a split arrow. -/
def cech_splitting [split f] (n : ℕ) : f.cech_nerve _[n] ⟶ f.cech_nerve _[n+1] :=
wide_pullback.lift (wide_pullback.base _)
(λ i, if h : i = 0 then wide_pullback.base _ ≫ split.σ else wide_pullback.π _ (i.pred h))
begin
rintro ⟨j⟩,
split_ifs,
tidy,
end
lemma cech_splitting_face_zero [split f] (n : ℕ) :
f.cech_splitting n ≫ f.cech_nerve.δ 0 = 𝟙 _ :=
begin
ext j,
dsimp [cech_splitting, simplicial_object.δ],
simp only [category.id_comp, category.assoc, wide_pullback.lift_π],
split_ifs,
{ exfalso,
exact fin.succ_ne_zero _ h },
{ congr,
dsimp [simplicial_object.δ, simplex_category.δ],
simp },
{ dsimp [simplicial_object.δ, cech_splitting],
simp },
end
lemma face_π (n : ℕ) (i : fin (n+1)) (j : fin (n+2)) :
(f.cech_nerve.δ j : f.cech_nerve _[n+1] ⟶ _) ≫ wide_pullback.π _ i =
wide_pullback.π _ (j.succ_above i) :=
begin
change wide_pullback.lift _ _ _ ≫ _ = _,
simpa,
end
lemma cech_splitting_face [split f] (n : ℕ) (j : fin (n+3)) (hj : j ≠ 0) :
f.cech_splitting (n+1) ≫ f.cech_nerve.δ j =
f.cech_nerve.δ (j.pred hj) ≫ f.cech_splitting n :=
begin
ext k,
swap,
{ dsimp [cech_splitting, simplicial_object.δ],
simp },
{ dsimp [cech_splitting, simplicial_object.δ],
simp only [category.assoc, limits.wide_pullback.lift_π],
split_ifs with h1 h2,
{ simp },
{ refine false.elim (h2 _),
change j.succ_above k = 0 at h1,
change k = 0,
rwa ← fin.succ_above_eq_zero_iff hj },
{ refine false.elim (h1 _),
erw h,
change j.succ_above 0 = 0,
rw fin.succ_above_eq_zero_iff hj },
{ simp only [category_theory.limits.wide_pullback.lift_π],
congr,
change (j.succ_above k).pred h1 = (j.pred hj).succ_above (k.pred h),
rw fin.pred_succ_above_pred,
refl } }
end
end arrow
namespace arrow
section contracting_homotopy
open category_theory.limits opposite
-- Note: Universe restrictions! I hope this doesn't pose any issues later...
-- jmc: seems like it might! I removed them.
variables {P : Type u} {N : Type u'} [category.{v} P] [category.{v'} N] (M : Pᵒᵖ ⥤ N)
variables (f : arrow P)
variables [∀ n : ℕ, has_wide_pullback f.right (λ i : fin (n+1), f.left) (λ i, f.hom)]
/-- The augmented Cech conerve induced by applying M to `f.augmented_cech_nerve`. -/
abbreviation conerve : cosimplicial_object.augmented N :=
((cosimplicial_object.augmented.whiskering _ _).obj M).obj f.augmented_cech_nerve.right_op
variables [arrow.split f] [preadditive N]
/-- The morphisms yielding the contracting homotopy. -/
def contracting_homotopy : Π (n : ℕ),
(f.conerve M).to_cocomplex.X (n+1) ⟶ (f.conerve M).to_cocomplex.X n
| 0 := M.map (wide_pullback.lift (𝟙 _)
(λ i, (split.σ : f.right ⟶ _))
(by simp)).op
| (n+1) := M.map (f.cech_splitting n).op
open cosimplicial_object.augmented
open_locale big_operators
lemma is_contracting_homotopy_zero :
(f.conerve M).to_cocomplex.d 0 1 ≫ f.contracting_homotopy M 0 = 𝟙 _ :=
begin
dsimp,
rw if_pos,
swap, { simp },
delta conerve,
dsimp [to_cocomplex_d, to_cocomplex_obj, contracting_homotopy ],
simp only [category.id_comp, category.comp_id],
simp_rw [← M.map_comp, ← op_comp, ← M.map_id, ← op_id],
congr' 2,
simp,
end
lemma is_contracting_homotopy_one :
(f.conerve M).to_cocomplex.d 1 2 ≫ f.contracting_homotopy M 1 +
f.contracting_homotopy M 0 ≫ (f.conerve M).to_cocomplex.d 0 1 = 𝟙 _ :=
begin
rw ← add_zero (𝟙 ((conerve M f).to_cocomplex.X 1)),
dsimp only [to_cocomplex, cochain_complex.of],
rw dif_pos,
swap, { dec_trivial },
rw dif_pos,
swap, { dec_trivial },
dsimp,
delta conerve,
dsimp only [to_cocomplex_d, cosimplicial_object.coboundary, whiskering, whiskering_obj,
drop, to_cocomplex_obj, comma.snd, cosimplicial_object.whiskering, whiskering_right,
contracting_homotopy],
simp_rw fin.sum_univ_succ,
simp only [fin.coe_zero, fin.sum_univ_zero, fin.coe_one,
one_zsmul, preadditive.add_comp, pow_one, fin.succ_zero_eq_one,
category.id_comp, neg_smul, category.comp_id, preadditive.neg_comp, pow_zero ],
rw [add_assoc],
congr' 1,
{ dsimp [cosimplicial_object.δ],
simp_rw [← M.map_comp, ← M.map_id, ← op_id, ← op_comp],
congr' 2,
dsimp [cech_splitting],
ext j,
{ simp only [wide_pullback.lift_π, category.id_comp, category.assoc],
split_ifs,
{ cases j,
injection h with hh,
simp only [nat.succ_ne_zero] at hh,
cases hh },
{ congr, have hj : j = 0 := subsingleton.elim j 0, subst j,
dsimp only [simplex_category.δ],
simp only [simplex_category.mk_hom, simplex_category.hom.to_order_hom_mk,
order_embedding.to_order_hom_coe, fin.zero_succ_above, fin.succ_zero_eq_one,
fin.one_eq_zero_iff, nat.one_ne_zero],
refl, } },
{ simp only [wide_pullback.lift_base, category.assoc, category.id_comp] } },
{ dsimp [cosimplicial_object.δ],
rw [add_assoc, neg_add_eq_zero, ← M.map_comp],
simp only [zero_comp, category.id_comp, zero_add, functor.map_comp, ← M.map_comp, ← op_comp],
congr' 2,
dsimp [cech_splitting],
ext j,
{ simp only [wide_pullback.lift_π, category.assoc],
split_ifs,
{ refl },
{ refine false.elim (h _),
change (1 : fin 2).succ_above j = 0,
rw fin.succ_above_eq_zero_iff,
{ simp },
{ exact top_ne_bot } } },
{ simp only [wide_pullback.lift_base, category.assoc, category.comp_id] } }
end
lemma is_contracting_homotopy (n : ℕ) :
(f.conerve M).to_cocomplex.d (n+2) (n+3) ≫ f.contracting_homotopy M (n+2) +
f.contracting_homotopy M (n+1) ≫ (f.conerve M).to_cocomplex.d (n+1) (n+2) = 𝟙 _ :=
begin
dsimp,
erw if_pos,
swap, refl,
dsimp only [to_cocomplex_d],
rw if_pos,
swap, refl,
dsimp only [cosimplicial_object.coboundary],
simp only [preadditive.sum_comp, preadditive.comp_sum],
erw [fin.sum_univ_succ, add_assoc, ← finset.sum_add_distrib],
rw ← add_zero (𝟙 ((conerve M f).to_cocomplex_obj (n + 2))),
dsimp only [cosimplicial_object.δ],
congr' 1,
{ delta conerve,
dsimp [to_cocomplex_obj, contracting_homotopy],
simp only [category_theory.category.comp_id, one_zsmul, pow_zero],
simp_rw [← M.map_id, ← M.map_comp, ← op_comp, ← op_id],
congr' 2,
apply cech_splitting_face_zero },
{ apply fintype.sum_eq_zero,
intros i,
simp only [
category.comp_id,
add_zero,
functor.comp_map,
fin.coe_succ,
preadditive.comp_zsmul,
preadditive.zsmul_comp],
suffices :
(drop.obj (conerve M f)).map (simplex_category.δ i.succ) ≫ contracting_homotopy M f (n+2) =
contracting_homotopy M f (n+1) ≫ (drop.obj (conerve M f)).map (simplex_category.δ i),
{ rw [this, pow_succ],
simp },
delta conerve,
dsimp [contracting_homotopy],
simp_rw [← M.map_comp, ← op_comp],
congr' 2,
convert cech_splitting_face _ _ _ (fin.succ_ne_zero _),
funext,
congr,
simp }
end
end contracting_homotopy
section covariant_contracting_homotopy
open category_theory.limits opposite
variables {P : Type u} {N : Type u'} [category.{v} P] [category.{v'} N] (M : P ⥤ N)
variables (f : arrow P)
variables [∀ n : ℕ, has_wide_pullback f.right (λ i : fin (n+1), f.left) (λ i, f.hom)]
/-- The augmented Cech nerve induced by applying M to `f.augmented_cech_nerve`. -/
abbreviation nerve : simplicial_object.augmented N :=
((simplicial_object.augmented.whiskering _ _).obj M).obj f.augmented_cech_nerve
variables [arrow.split f] [preadditive N]
open simplicial_object.augmented
open_locale big_operators
def covariant_contracting_homotopy : Π (n : ℕ),
(f.nerve M).to_complex.X n ⟶ (f.nerve M).to_complex.X (n+1)
| 0 := M.map $ wide_pullback.lift (𝟙 _) (λ i, (split.σ : f.right ⟶ _)) (by simpa)
| (n+1) := M.map $ f.cech_splitting n
lemma covariant_is_contracting_homotopy_zero :
f.covariant_contracting_homotopy M 0 ≫ (f.nerve M).to_complex.d 1 0 = 𝟙 _ :=
begin
dsimp,
rw if_pos,
swap, { simp },
delta nerve,
dsimp [to_complex_obj, to_complex_d, covariant_contracting_homotopy],
simp only [category.id_comp, category.comp_id],
simp_rw [← M.map_comp, ← M.map_id],
congr' 2,
simp,
end
lemma covariant_is_contracting_homotopy_one :
f.covariant_contracting_homotopy M 1 ≫ (f.nerve M).to_complex.d 2 1 +
(f.nerve M).to_complex.d 1 0 ≫ f.covariant_contracting_homotopy M 0 = 𝟙 _ :=
begin
dsimp [covariant_contracting_homotopy],
rw if_pos, rw if_pos, any_goals { dec_trivial },
dsimp [to_complex_d, simplicial_object.boundary, simplicial_object.δ],
delta nerve,
dsimp [to_complex_obj],
simp only [fin.sum_univ_succ, fin.coe_zero, pow_zero, one_zsmul, fintype.univ_of_subsingleton,
nat.add_def, fin.mk_zero, fin.coe_succ, pow_one, neg_smul, finset.sum_singleton,
preadditive.comp_add, category.id_comp, preadditive.comp_neg, category.comp_id],
simp only [← M.map_comp],
rw add_assoc,
convert add_zero _,
swap,
{ symmetry,
convert M.map_id _,
dsimp [arrow.cech_splitting],
ext ⟨j,hj⟩, simp,
rw dif_neg, refl,
dsimp [simplex_category.δ],
have : j = 0, by simpa using hj, subst this, dec_trivial,
simp },
{ rw neg_add_eq_zero,
congr' 1,
dsimp [cech_splitting],
ext ⟨j,hj⟩,
{ simp only [category.assoc, wide_pullback.lift_π], dsimp [simplex_category.δ],
rw dif_pos, have : j = 0, by simpa using hj, subst this,
dsimp [simplex_category.δ], dec_trivial },
{ simp } }
end
lemma covariant_is_contracting_homotopy (n : ℕ) :
f.covariant_contracting_homotopy M (n+2) ≫ (f.nerve M).to_complex.d (n+3) (n+2) +
(f.nerve M).to_complex.d (n+2) (n+1) ≫ f.covariant_contracting_homotopy M (n+1) = 𝟙 _ :=
begin
dsimp, rw if_pos, rw if_pos, swap, { refl }, swap, { refl },
simp only [category.comp_id, category.id_comp],
dsimp only [to_complex_d, simplicial_object.boundary],
simp only [preadditive.sum_comp, preadditive.comp_sum],
rw [fin.sum_univ_succ, add_assoc, ← finset.sum_add_distrib],
convert add_zero _,
{ apply fintype.sum_eq_zero, intros j,
have : ((j.succ : fin _) : ℕ) = (j : ℕ) + 1 := by simp, rw this, clear this,
rw [pow_succ],
simp only [neg_mul, one_mul, neg_smul, preadditive.comp_neg],
rw neg_add_eq_zero,
simp only [preadditive.comp_zsmul, preadditive.zsmul_comp],
congr' 1,
dsimp [covariant_contracting_homotopy, simplicial_object.δ],
delta nerve,
dsimp [whiskering],
simp only [← M.map_comp],
congr' 1,
convert cech_splitting_face _ _ _ (fin.succ_ne_zero _), funext i,
congr, simp },
{ dsimp [covariant_contracting_homotopy],
simp only [pow_zero, one_zsmul],
delta nerve,
dsimp [arrow.cech_splitting, simplicial_object.whiskering, simplicial_object.δ],
rw ← M.map_comp, symmetry,
convert M.map_id _,
ext ⟨j,hj⟩,
simp only [category.assoc, wide_pullback.lift_π],
rw dif_neg, dsimp, simpa, dsimp [simplex_category.δ],
intro c, apply_fun (λ e, e.1) at c, simpa using c,
simp, dsimp, simp }
end
end covariant_contracting_homotopy
end arrow
end category_theory
|
(* Author: Amine Chaieb, TU Muenchen *)
section \<open>Fundamental Theorem of Algebra\<close>
theory Fundamental_Theorem_Algebra
imports Polynomial Complex_Main
begin
subsection \<open>More lemmas about module of complex numbers\<close>
text \<open>The triangle inequality for cmod\<close>
lemma complex_mod_triangle_sub: "cmod w \<le> cmod (w + z) + norm z"
using complex_mod_triangle_ineq2[of "w + z" "-z"] by auto
subsection \<open>Basic lemmas about polynomials\<close>
lemma poly_bound_exists:
fixes p :: "'a::{comm_semiring_0,real_normed_div_algebra} poly"
shows "\<exists>m. m > 0 \<and> (\<forall>z. norm z \<le> r \<longrightarrow> norm (poly p z) \<le> m)"
proof (induct p)
case 0
then show ?case by (rule exI[where x=1]) simp
next
case (pCons c cs)
from pCons.hyps obtain m where m: "\<forall>z. norm z \<le> r \<longrightarrow> norm (poly cs z) \<le> m"
by blast
let ?k = " 1 + norm c + \<bar>r * m\<bar>"
have kp: "?k > 0"
using abs_ge_zero[of "r*m"] norm_ge_zero[of c] by arith
have "norm (poly (pCons c cs) z) \<le> ?k" if H: "norm z \<le> r" for z
proof -
from m H have th: "norm (poly cs z) \<le> m"
by blast
from H have rp: "r \<ge> 0"
using norm_ge_zero[of z] by arith
have "norm (poly (pCons c cs) z) \<le> norm c + norm (z * poly cs z)"
using norm_triangle_ineq[of c "z* poly cs z"] by simp
also have "\<dots> \<le> norm c + r * m"
using mult_mono[OF H th rp norm_ge_zero[of "poly cs z"]]
by (simp add: norm_mult)
also have "\<dots> \<le> ?k"
by simp
finally show ?thesis .
qed
with kp show ?case by blast
qed
text \<open>Offsetting the variable in a polynomial gives another of same degree\<close>
definition offset_poly :: "'a::comm_semiring_0 poly \<Rightarrow> 'a \<Rightarrow> 'a poly"
where "offset_poly p h = fold_coeffs (\<lambda>a q. smult h q + pCons a q) p 0"
lemma offset_poly_0: "offset_poly 0 h = 0"
by (simp add: offset_poly_def)
lemma offset_poly_pCons:
"offset_poly (pCons a p) h =
smult h (offset_poly p h) + pCons a (offset_poly p h)"
by (cases "p = 0 \<and> a = 0") (auto simp add: offset_poly_def)
lemma offset_poly_single: "offset_poly [:a:] h = [:a:]"
by (simp add: offset_poly_pCons offset_poly_0)
lemma poly_offset_poly: "poly (offset_poly p h) x = poly p (h + x)"
apply (induct p)
apply (simp add: offset_poly_0)
apply (simp add: offset_poly_pCons algebra_simps)
done
lemma offset_poly_eq_0_lemma: "smult c p + pCons a p = 0 \<Longrightarrow> p = 0"
by (induct p arbitrary: a) (simp, force)
lemma offset_poly_eq_0_iff: "offset_poly p h = 0 \<longleftrightarrow> p = 0"
apply (safe intro!: offset_poly_0)
apply (induct p)
apply simp
apply (simp add: offset_poly_pCons)
apply (frule offset_poly_eq_0_lemma, simp)
done
lemma degree_offset_poly: "degree (offset_poly p h) = degree p"
apply (induct p)
apply (simp add: offset_poly_0)
apply (case_tac "p = 0")
apply (simp add: offset_poly_0 offset_poly_pCons)
apply (simp add: offset_poly_pCons)
apply (subst degree_add_eq_right)
apply (rule le_less_trans [OF degree_smult_le])
apply (simp add: offset_poly_eq_0_iff)
apply (simp add: offset_poly_eq_0_iff)
done
definition "psize p = (if p = 0 then 0 else Suc (degree p))"
lemma psize_eq_0_iff [simp]: "psize p = 0 \<longleftrightarrow> p = 0"
unfolding psize_def by simp
lemma poly_offset:
fixes p :: "'a::comm_ring_1 poly"
shows "\<exists>q. psize q = psize p \<and> (\<forall>x. poly q x = poly p (a + x))"
proof (intro exI conjI)
show "psize (offset_poly p a) = psize p"
unfolding psize_def
by (simp add: offset_poly_eq_0_iff degree_offset_poly)
show "\<forall>x. poly (offset_poly p a) x = poly p (a + x)"
by (simp add: poly_offset_poly)
qed
text \<open>An alternative useful formulation of completeness of the reals\<close>
lemma real_sup_exists:
assumes ex: "\<exists>x. P x"
and bz: "\<exists>z. \<forall>x. P x \<longrightarrow> x < z"
shows "\<exists>s::real. \<forall>y. (\<exists>x. P x \<and> y < x) \<longleftrightarrow> y < s"
proof
from bz have "bdd_above (Collect P)"
by (force intro: less_imp_le)
then show "\<forall>y. (\<exists>x. P x \<and> y < x) \<longleftrightarrow> y < Sup (Collect P)"
using ex bz by (subst less_cSup_iff) auto
qed
subsection \<open>Fundamental theorem of algebra\<close>
lemma unimodular_reduce_norm:
assumes md: "cmod z = 1"
shows "cmod (z + 1) < 1 \<or> cmod (z - 1) < 1 \<or> cmod (z + \<i>) < 1 \<or> cmod (z - \<i>) < 1"
proof -
obtain x y where z: "z = Complex x y "
by (cases z) auto
from md z have xy: "x\<^sup>2 + y\<^sup>2 = 1"
by (simp add: cmod_def)
have False if "cmod (z + 1) \<ge> 1" "cmod (z - 1) \<ge> 1" "cmod (z + \<i>) \<ge> 1" "cmod (z - \<i>) \<ge> 1"
proof -
from that z xy have "2 * x \<le> 1" "2 * x \<ge> -1" "2 * y \<le> 1" "2 * y \<ge> -1"
by (simp_all add: cmod_def power2_eq_square algebra_simps)
then have "\<bar>2 * x\<bar> \<le> 1" "\<bar>2 * y\<bar> \<le> 1"
by simp_all
then have "\<bar>2 * x\<bar>\<^sup>2 \<le> 1\<^sup>2" "\<bar>2 * y\<bar>\<^sup>2 \<le> 1\<^sup>2"
by - (rule power_mono, simp, simp)+
then have th0: "4 * x\<^sup>2 \<le> 1" "4 * y\<^sup>2 \<le> 1"
by (simp_all add: power_mult_distrib)
from add_mono[OF th0] xy show ?thesis
by simp
qed
then show ?thesis
unfolding linorder_not_le[symmetric] by blast
qed
text \<open>Hence we can always reduce modulus of \<open>1 + b z^n\<close> if nonzero\<close>
lemma reduce_poly_simple:
assumes b: "b \<noteq> 0"
and n: "n \<noteq> 0"
shows "\<exists>z. cmod (1 + b * z^n) < 1"
using n
proof (induct n rule: nat_less_induct)
fix n
assume IH: "\<forall>m<n. m \<noteq> 0 \<longrightarrow> (\<exists>z. cmod (1 + b * z ^ m) < 1)"
assume n: "n \<noteq> 0"
let ?P = "\<lambda>z n. cmod (1 + b * z ^ n) < 1"
show "\<exists>z. ?P z n"
proof cases
assume "even n"
then have "\<exists>m. n = 2 * m"
by presburger
then obtain m where m: "n = 2 * m"
by blast
from n m have "m \<noteq> 0" "m < n"
by presburger+
with IH[rule_format, of m] obtain z where z: "?P z m"
by blast
from z have "?P (csqrt z) n"
by (simp add: m power_mult)
then show ?thesis ..
next
assume "odd n"
then have "\<exists>m. n = Suc (2 * m)"
by presburger+
then obtain m where m: "n = Suc (2 * m)"
by blast
have th0: "cmod (complex_of_real (cmod b) / b) = 1"
using b by (simp add: norm_divide)
from unimodular_reduce_norm[OF th0] \<open>odd n\<close>
have "\<exists>v. cmod (complex_of_real (cmod b) / b + v^n) < 1"
apply (cases "cmod (complex_of_real (cmod b) / b + 1) < 1")
apply (rule_tac x="1" in exI)
apply simp
apply (cases "cmod (complex_of_real (cmod b) / b - 1) < 1")
apply (rule_tac x="-1" in exI)
apply simp
apply (cases "cmod (complex_of_real (cmod b) / b + \<i>) < 1")
apply (cases "even m")
apply (rule_tac x="\<i>" in exI)
apply (simp add: m power_mult)
apply (rule_tac x="- \<i>" in exI)
apply (simp add: m power_mult)
apply (cases "even m")
apply (rule_tac x="- \<i>" in exI)
apply (simp add: m power_mult)
apply (auto simp add: m power_mult)
apply (rule_tac x="\<i>" in exI)
apply (auto simp add: m power_mult)
done
then obtain v where v: "cmod (complex_of_real (cmod b) / b + v^n) < 1"
by blast
let ?w = "v / complex_of_real (root n (cmod b))"
from odd_real_root_pow[OF \<open>odd n\<close>, of "cmod b"]
have th1: "?w ^ n = v^n / complex_of_real (cmod b)"
by (simp add: power_divide of_real_power[symmetric])
have th2:"cmod (complex_of_real (cmod b) / b) = 1"
using b by (simp add: norm_divide)
then have th3: "cmod (complex_of_real (cmod b) / b) \<ge> 0"
by simp
have th4: "cmod (complex_of_real (cmod b) / b) *
cmod (1 + b * (v ^ n / complex_of_real (cmod b))) <
cmod (complex_of_real (cmod b) / b) * 1"
apply (simp only: norm_mult[symmetric] distrib_left)
using b v
apply (simp add: th2)
done
from mult_left_less_imp_less[OF th4 th3]
have "?P ?w n" unfolding th1 .
then show ?thesis ..
qed
qed
text \<open>Bolzano-Weierstrass type property for closed disc in complex plane.\<close>
lemma metric_bound_lemma: "cmod (x - y) \<le> \<bar>Re x - Re y\<bar> + \<bar>Im x - Im y\<bar>"
using real_sqrt_sum_squares_triangle_ineq[of "Re x - Re y" 0 0 "Im x - Im y"]
unfolding cmod_def by simp
lemma bolzano_weierstrass_complex_disc:
assumes r: "\<forall>n. cmod (s n) \<le> r"
shows "\<exists>f z. subseq f \<and> (\<forall>e >0. \<exists>N. \<forall>n \<ge> N. cmod (s (f n) - z) < e)"
proof -
from seq_monosub[of "Re \<circ> s"]
obtain f where f: "subseq f" "monoseq (\<lambda>n. Re (s (f n)))"
unfolding o_def by blast
from seq_monosub[of "Im \<circ> s \<circ> f"]
obtain g where g: "subseq g" "monoseq (\<lambda>n. Im (s (f (g n))))"
unfolding o_def by blast
let ?h = "f \<circ> g"
from r[rule_format, of 0] have rp: "r \<ge> 0"
using norm_ge_zero[of "s 0"] by arith
have th: "\<forall>n. r + 1 \<ge> \<bar>Re (s n)\<bar>"
proof
fix n
from abs_Re_le_cmod[of "s n"] r[rule_format, of n]
show "\<bar>Re (s n)\<bar> \<le> r + 1" by arith
qed
have conv1: "convergent (\<lambda>n. Re (s (f n)))"
apply (rule Bseq_monoseq_convergent)
apply (simp add: Bseq_def)
apply (metis gt_ex le_less_linear less_trans order.trans th)
apply (rule f(2))
done
have th: "\<forall>n. r + 1 \<ge> \<bar>Im (s n)\<bar>"
proof
fix n
from abs_Im_le_cmod[of "s n"] r[rule_format, of n]
show "\<bar>Im (s n)\<bar> \<le> r + 1"
by arith
qed
have conv2: "convergent (\<lambda>n. Im (s (f (g n))))"
apply (rule Bseq_monoseq_convergent)
apply (simp add: Bseq_def)
apply (metis gt_ex le_less_linear less_trans order.trans th)
apply (rule g(2))
done
from conv1[unfolded convergent_def] obtain x where "LIMSEQ (\<lambda>n. Re (s (f n))) x"
by blast
then have x: "\<forall>r>0. \<exists>n0. \<forall>n\<ge>n0. \<bar>Re (s (f n)) - x\<bar> < r"
unfolding LIMSEQ_iff real_norm_def .
from conv2[unfolded convergent_def] obtain y where "LIMSEQ (\<lambda>n. Im (s (f (g n)))) y"
by blast
then have y: "\<forall>r>0. \<exists>n0. \<forall>n\<ge>n0. \<bar>Im (s (f (g n))) - y\<bar> < r"
unfolding LIMSEQ_iff real_norm_def .
let ?w = "Complex x y"
from f(1) g(1) have hs: "subseq ?h"
unfolding subseq_def by auto
have "\<exists>N. \<forall>n\<ge>N. cmod (s (?h n) - ?w) < e" if "e > 0" for e
proof -
from that have e2: "e/2 > 0"
by simp
from x[rule_format, OF e2] y[rule_format, OF e2]
obtain N1 N2 where N1: "\<forall>n\<ge>N1. \<bar>Re (s (f n)) - x\<bar> < e / 2"
and N2: "\<forall>n\<ge>N2. \<bar>Im (s (f (g n))) - y\<bar> < e / 2"
by blast
have "cmod (s (?h n) - ?w) < e" if "n \<ge> N1 + N2" for n
proof -
from that have nN1: "g n \<ge> N1" and nN2: "n \<ge> N2"
using seq_suble[OF g(1), of n] by arith+
from add_strict_mono[OF N1[rule_format, OF nN1] N2[rule_format, OF nN2]]
show ?thesis
using metric_bound_lemma[of "s (f (g n))" ?w] by simp
qed
then show ?thesis by blast
qed
with hs show ?thesis by blast
qed
text \<open>Polynomial is continuous.\<close>
lemma poly_cont:
fixes p :: "'a::{comm_semiring_0,real_normed_div_algebra} poly"
assumes ep: "e > 0"
shows "\<exists>d >0. \<forall>w. 0 < norm (w - z) \<and> norm (w - z) < d \<longrightarrow> norm (poly p w - poly p z) < e"
proof -
obtain q where q: "degree q = degree p" "poly q x = poly p (z + x)" for x
proof
show "degree (offset_poly p z) = degree p"
by (rule degree_offset_poly)
show "\<And>x. poly (offset_poly p z) x = poly p (z + x)"
by (rule poly_offset_poly)
qed
have th: "\<And>w. poly q (w - z) = poly p w"
using q(2)[of "w - z" for w] by simp
show ?thesis unfolding th[symmetric]
proof (induct q)
case 0
then show ?case
using ep by auto
next
case (pCons c cs)
from poly_bound_exists[of 1 "cs"]
obtain m where m: "m > 0" "norm z \<le> 1 \<Longrightarrow> norm (poly cs z) \<le> m" for z
by blast
from ep m(1) have em0: "e/m > 0"
by (simp add: field_simps)
have one0: "1 > (0::real)"
by arith
from real_lbound_gt_zero[OF one0 em0]
obtain d where d: "d > 0" "d < 1" "d < e / m"
by blast
from d(1,3) m(1) have dm: "d * m > 0" "d * m < e"
by (simp_all add: field_simps)
show ?case
proof (rule ex_forward[OF real_lbound_gt_zero[OF one0 em0]], clarsimp simp add: norm_mult)
fix d w
assume H: "d > 0" "d < 1" "d < e/m" "w \<noteq> z" "norm (w - z) < d"
then have d1: "norm (w-z) \<le> 1" "d \<ge> 0"
by simp_all
from H(3) m(1) have dme: "d*m < e"
by (simp add: field_simps)
from H have th: "norm (w - z) \<le> d"
by simp
from mult_mono[OF th m(2)[OF d1(1)] d1(2) norm_ge_zero] dme
show "norm (w - z) * norm (poly cs (w - z)) < e"
by simp
qed
qed
qed
text \<open>Hence a polynomial attains minimum on a closed disc
in the complex plane.\<close>
lemma poly_minimum_modulus_disc: "\<exists>z. \<forall>w. cmod w \<le> r \<longrightarrow> cmod (poly p z) \<le> cmod (poly p w)"
proof -
show ?thesis
proof (cases "r \<ge> 0")
case False
then show ?thesis
by (metis norm_ge_zero order.trans)
next
case True
then have "cmod 0 \<le> r \<and> cmod (poly p 0) = - (- cmod (poly p 0))"
by simp
then have mth1: "\<exists>x z. cmod z \<le> r \<and> cmod (poly p z) = - x"
by blast
have False if "cmod z \<le> r" "cmod (poly p z) = - x" "\<not> x < 1" for x z
proof -
from that have "- x < 0 "
by arith
with that(2) norm_ge_zero[of "poly p z"] show ?thesis
by simp
qed
then have mth2: "\<exists>z. \<forall>x. (\<exists>z. cmod z \<le> r \<and> cmod (poly p z) = - x) \<longrightarrow> x < z"
by blast
from real_sup_exists[OF mth1 mth2] obtain s where
s: "\<forall>y. (\<exists>x. (\<exists>z. cmod z \<le> r \<and> cmod (poly p z) = - x) \<and> y < x) \<longleftrightarrow> y < s"
by blast
let ?m = "- s"
have s1[unfolded minus_minus]:
"(\<exists>z x. cmod z \<le> r \<and> - (- cmod (poly p z)) < y) \<longleftrightarrow> ?m < y" for y
using s[rule_format, of "-y"]
unfolding minus_less_iff[of y] equation_minus_iff by blast
from s1[of ?m] have s1m: "\<And>z x. cmod z \<le> r \<Longrightarrow> cmod (poly p z) \<ge> ?m"
by auto
have "\<exists>z. cmod z \<le> r \<and> cmod (poly p z) < - s + 1 / real (Suc n)" for n
using s1[rule_format, of "?m + 1/real (Suc n)"] by simp
then have th: "\<forall>n. \<exists>z. cmod z \<le> r \<and> cmod (poly p z) < - s + 1 / real (Suc n)" ..
from choice[OF th] obtain g where
g: "\<forall>n. cmod (g n) \<le> r" "\<forall>n. cmod (poly p (g n)) <?m + 1 /real(Suc n)"
by blast
from bolzano_weierstrass_complex_disc[OF g(1)]
obtain f z where fz: "subseq f" "\<forall>e>0. \<exists>N. \<forall>n\<ge>N. cmod (g (f n) - z) < e"
by blast
{
fix w
assume wr: "cmod w \<le> r"
let ?e = "\<bar>cmod (poly p z) - ?m\<bar>"
{
assume e: "?e > 0"
then have e2: "?e/2 > 0"
by simp
from poly_cont[OF e2, of z p] obtain d where
d: "d > 0" "\<forall>w. 0<cmod (w - z)\<and> cmod(w - z) < d \<longrightarrow> cmod(poly p w - poly p z) < ?e/2"
by blast
have th1: "cmod(poly p w - poly p z) < ?e / 2" if w: "cmod (w - z) < d" for w
using d(2)[rule_format, of w] w e by (cases "w = z") simp_all
from fz(2) d(1) obtain N1 where N1: "\<forall>n\<ge>N1. cmod (g (f n) - z) < d"
by blast
from reals_Archimedean2[of "2/?e"] obtain N2 :: nat where N2: "2/?e < real N2"
by blast
have th2: "cmod (poly p (g (f (N1 + N2))) - poly p z) < ?e/2"
using N1[rule_format, of "N1 + N2"] th1 by simp
have th0: "a < e2 \<Longrightarrow> \<bar>b - m\<bar> < e2 \<Longrightarrow> 2 * e2 \<le> \<bar>b - m\<bar> + a \<Longrightarrow> False"
for a b e2 m :: real
by arith
have ath: "m \<le> x \<Longrightarrow> x < m + e \<Longrightarrow> \<bar>x - m\<bar> < e" for m x e :: real
by arith
from s1m[OF g(1)[rule_format]] have th31: "?m \<le> cmod(poly p (g (f (N1 + N2))))" .
from seq_suble[OF fz(1), of "N1 + N2"]
have th00: "real (Suc (N1 + N2)) \<le> real (Suc (f (N1 + N2)))"
by simp
have th000: "0 \<le> (1::real)" "(1::real) \<le> 1" "real (Suc (N1 + N2)) > 0"
using N2 by auto
from frac_le[OF th000 th00]
have th00: "?m + 1 / real (Suc (f (N1 + N2))) \<le> ?m + 1 / real (Suc (N1 + N2))"
by simp
from g(2)[rule_format, of "f (N1 + N2)"]
have th01:"cmod (poly p (g (f (N1 + N2)))) < - s + 1 / real (Suc (f (N1 + N2)))" .
from order_less_le_trans[OF th01 th00]
have th32: "cmod (poly p (g (f (N1 + N2)))) < ?m + (1/ real(Suc (N1 + N2)))" .
from N2 have "2/?e < real (Suc (N1 + N2))"
by arith
with e2 less_imp_inverse_less[of "2/?e" "real (Suc (N1 + N2))"]
have "?e/2 > 1/ real (Suc (N1 + N2))"
by (simp add: inverse_eq_divide)
with ath[OF th31 th32] have thc1: "\<bar>cmod (poly p (g (f (N1 + N2)))) - ?m\<bar> < ?e/2"
by arith
have ath2: "\<bar>a - b\<bar> \<le> c \<Longrightarrow> \<bar>b - m\<bar> \<le> \<bar>a - m\<bar> + c" for a b c m :: real
by arith
have th22: "\<bar>cmod (poly p (g (f (N1 + N2)))) - cmod (poly p z)\<bar> \<le>
cmod (poly p (g (f (N1 + N2))) - poly p z)"
by (simp add: norm_triangle_ineq3)
from ath2[OF th22, of ?m]
have thc2: "2 * (?e/2) \<le>
\<bar>cmod(poly p (g (f (N1 + N2)))) - ?m\<bar> + cmod (poly p (g (f (N1 + N2))) - poly p z)"
by simp
from th0[OF th2 thc1 thc2] have False .
}
then have "?e = 0"
by auto
then have "cmod (poly p z) = ?m"
by simp
with s1m[OF wr] have "cmod (poly p z) \<le> cmod (poly p w)"
by simp
}
then show ?thesis by blast
qed
qed
text \<open>Nonzero polynomial in z goes to infinity as z does.\<close>
lemma poly_infinity:
fixes p:: "'a::{comm_semiring_0,real_normed_div_algebra} poly"
assumes ex: "p \<noteq> 0"
shows "\<exists>r. \<forall>z. r \<le> norm z \<longrightarrow> d \<le> norm (poly (pCons a p) z)"
using ex
proof (induct p arbitrary: a d)
case 0
then show ?case by simp
next
case (pCons c cs a d)
show ?case
proof (cases "cs = 0")
case False
with pCons.hyps obtain r where r: "\<forall>z. r \<le> norm z \<longrightarrow> d + norm a \<le> norm (poly (pCons c cs) z)"
by blast
let ?r = "1 + \<bar>r\<bar>"
have "d \<le> norm (poly (pCons a (pCons c cs)) z)" if "1 + \<bar>r\<bar> \<le> norm z" for z
proof -
have r0: "r \<le> norm z"
using that by arith
from r[rule_format, OF r0] have th0: "d + norm a \<le> 1 * norm(poly (pCons c cs) z)"
by arith
from that have z1: "norm z \<ge> 1"
by arith
from order_trans[OF th0 mult_right_mono[OF z1 norm_ge_zero[of "poly (pCons c cs) z"]]]
have th1: "d \<le> norm(z * poly (pCons c cs) z) - norm a"
unfolding norm_mult by (simp add: algebra_simps)
from norm_diff_ineq[of "z * poly (pCons c cs) z" a]
have th2: "norm (z * poly (pCons c cs) z) - norm a \<le> norm (poly (pCons a (pCons c cs)) z)"
by (simp add: algebra_simps)
from th1 th2 show ?thesis
by arith
qed
then show ?thesis by blast
next
case True
with pCons.prems have c0: "c \<noteq> 0"
by simp
have "d \<le> norm (poly (pCons a (pCons c cs)) z)"
if h: "(\<bar>d\<bar> + norm a) / norm c \<le> norm z" for z :: 'a
proof -
from c0 have "norm c > 0"
by simp
from h c0 have th0: "\<bar>d\<bar> + norm a \<le> norm (z * c)"
by (simp add: field_simps norm_mult)
have ath: "\<And>mzh mazh ma. mzh \<le> mazh + ma \<Longrightarrow> \<bar>d\<bar> + ma \<le> mzh \<Longrightarrow> d \<le> mazh"
by arith
from norm_diff_ineq[of "z * c" a] have th1: "norm (z * c) \<le> norm (a + z * c) + norm a"
by (simp add: algebra_simps)
from ath[OF th1 th0] show ?thesis
using True by simp
qed
then show ?thesis by blast
qed
qed
text \<open>Hence polynomial's modulus attains its minimum somewhere.\<close>
lemma poly_minimum_modulus: "\<exists>z.\<forall>w. cmod (poly p z) \<le> cmod (poly p w)"
proof (induct p)
case 0
then show ?case by simp
next
case (pCons c cs)
show ?case
proof (cases "cs = 0")
case False
from poly_infinity[OF False, of "cmod (poly (pCons c cs) 0)" c]
obtain r where r: "cmod (poly (pCons c cs) 0) \<le> cmod (poly (pCons c cs) z)"
if "r \<le> cmod z" for z
by blast
have ath: "\<And>z r. r \<le> cmod z \<or> cmod z \<le> \<bar>r\<bar>"
by arith
from poly_minimum_modulus_disc[of "\<bar>r\<bar>" "pCons c cs"]
obtain v where v: "cmod (poly (pCons c cs) v) \<le> cmod (poly (pCons c cs) w)"
if "cmod w \<le> \<bar>r\<bar>" for w
by blast
have "cmod (poly (pCons c cs) v) \<le> cmod (poly (pCons c cs) z)" if z: "r \<le> cmod z" for z
using v[of 0] r[OF z] by simp
with v ath[of r] show ?thesis
by blast
next
case True
with pCons.hyps show ?thesis
by simp
qed
qed
text \<open>Constant function (non-syntactic characterization).\<close>
definition "constant f \<longleftrightarrow> (\<forall>x y. f x = f y)"
lemma nonconstant_length: "\<not> constant (poly p) \<Longrightarrow> psize p \<ge> 2"
by (induct p) (auto simp: constant_def psize_def)
lemma poly_replicate_append: "poly (monom 1 n * p) (x::'a::comm_ring_1) = x^n * poly p x"
by (simp add: poly_monom)
text \<open>Decomposition of polynomial, skipping zero coefficients after the first.\<close>
lemma poly_decompose_lemma:
assumes nz: "\<not> (\<forall>z. z \<noteq> 0 \<longrightarrow> poly p z = (0::'a::idom))"
shows "\<exists>k a q. a \<noteq> 0 \<and> Suc (psize q + k) = psize p \<and> (\<forall>z. poly p z = z^k * poly (pCons a q) z)"
unfolding psize_def
using nz
proof (induct p)
case 0
then show ?case by simp
next
case (pCons c cs)
show ?case
proof (cases "c = 0")
case True
from pCons.hyps pCons.prems True show ?thesis
apply auto
apply (rule_tac x="k+1" in exI)
apply (rule_tac x="a" in exI)
apply clarsimp
apply (rule_tac x="q" in exI)
apply auto
done
next
case False
show ?thesis
apply (rule exI[where x=0])
apply (rule exI[where x=c])
apply (auto simp: False)
done
qed
qed
lemma poly_decompose:
assumes nc: "\<not> constant (poly p)"
shows "\<exists>k a q. a \<noteq> (0::'a::idom) \<and> k \<noteq> 0 \<and>
psize q + k + 1 = psize p \<and>
(\<forall>z. poly p z = poly p 0 + z^k * poly (pCons a q) z)"
using nc
proof (induct p)
case 0
then show ?case
by (simp add: constant_def)
next
case (pCons c cs)
have "\<not> (\<forall>z. z \<noteq> 0 \<longrightarrow> poly cs z = 0)"
proof
assume "\<forall>z. z \<noteq> 0 \<longrightarrow> poly cs z = 0"
then have "poly (pCons c cs) x = poly (pCons c cs) y" for x y
by (cases "x = 0") auto
with pCons.prems show False
by (auto simp add: constant_def)
qed
from poly_decompose_lemma[OF this]
show ?case
apply clarsimp
apply (rule_tac x="k+1" in exI)
apply (rule_tac x="a" in exI)
apply simp
apply (rule_tac x="q" in exI)
apply (auto simp add: psize_def split: if_splits)
done
qed
text \<open>Fundamental theorem of algebra\<close>
lemma fundamental_theorem_of_algebra:
assumes nc: "\<not> constant (poly p)"
shows "\<exists>z::complex. poly p z = 0"
using nc
proof (induct "psize p" arbitrary: p rule: less_induct)
case less
let ?p = "poly p"
let ?ths = "\<exists>z. ?p z = 0"
from nonconstant_length[OF less(2)] have n2: "psize p \<ge> 2" .
from poly_minimum_modulus obtain c where c: "\<forall>w. cmod (?p c) \<le> cmod (?p w)"
by blast
show ?ths
proof (cases "?p c = 0")
case True
then show ?thesis by blast
next
case False
from poly_offset[of p c] obtain q where q: "psize q = psize p" "\<forall>x. poly q x = ?p (c + x)"
by blast
have False if h: "constant (poly q)"
proof -
from q(2) have th: "\<forall>x. poly q (x - c) = ?p x"
by auto
have "?p x = ?p y" for x y
proof -
from th have "?p x = poly q (x - c)"
by auto
also have "\<dots> = poly q (y - c)"
using h unfolding constant_def by blast
also have "\<dots> = ?p y"
using th by auto
finally show ?thesis .
qed
with less(2) show ?thesis
unfolding constant_def by blast
qed
then have qnc: "\<not> constant (poly q)"
by blast
from q(2) have pqc0: "?p c = poly q 0"
by simp
from c pqc0 have cq0: "\<forall>w. cmod (poly q 0) \<le> cmod (?p w)"
by simp
let ?a0 = "poly q 0"
from False pqc0 have a00: "?a0 \<noteq> 0"
by simp
from a00 have qr: "\<forall>z. poly q z = poly (smult (inverse ?a0) q) z * ?a0"
by simp
let ?r = "smult (inverse ?a0) q"
have lgqr: "psize q = psize ?r"
using a00
unfolding psize_def degree_def
by (simp add: poly_eq_iff)
have False if h: "\<And>x y. poly ?r x = poly ?r y"
proof -
have "poly q x = poly q y" for x y
proof -
from qr[rule_format, of x] have "poly q x = poly ?r x * ?a0"
by auto
also have "\<dots> = poly ?r y * ?a0"
using h by simp
also have "\<dots> = poly q y"
using qr[rule_format, of y] by simp
finally show ?thesis .
qed
with qnc show ?thesis
unfolding constant_def by blast
qed
then have rnc: "\<not> constant (poly ?r)"
unfolding constant_def by blast
from qr[rule_format, of 0] a00 have r01: "poly ?r 0 = 1"
by auto
have mrmq_eq: "cmod (poly ?r w) < 1 \<longleftrightarrow> cmod (poly q w) < cmod ?a0" for w
proof -
have "cmod (poly ?r w) < 1 \<longleftrightarrow> cmod (poly q w / ?a0) < 1"
using qr[rule_format, of w] a00 by (simp add: divide_inverse ac_simps)
also have "\<dots> \<longleftrightarrow> cmod (poly q w) < cmod ?a0"
using a00 unfolding norm_divide by (simp add: field_simps)
finally show ?thesis .
qed
from poly_decompose[OF rnc] obtain k a s where
kas: "a \<noteq> 0" "k \<noteq> 0" "psize s + k + 1 = psize ?r"
"\<forall>z. poly ?r z = poly ?r 0 + z^k* poly (pCons a s) z" by blast
have "\<exists>w. cmod (poly ?r w) < 1"
proof (cases "psize p = k + 1")
case True
with kas(3) lgqr[symmetric] q(1) have s0: "s = 0"
by auto
have hth[symmetric]: "cmod (poly ?r w) = cmod (1 + a * w ^ k)" for w
using kas(4)[rule_format, of w] s0 r01 by (simp add: algebra_simps)
from reduce_poly_simple[OF kas(1,2)] show ?thesis
unfolding hth by blast
next
case False note kn = this
from kn kas(3) q(1) lgqr have k1n: "k + 1 < psize p"
by simp
have th01: "\<not> constant (poly (pCons 1 (monom a (k - 1))))"
unfolding constant_def poly_pCons poly_monom
using kas(1)
apply simp
apply (rule exI[where x=0])
apply (rule exI[where x=1])
apply simp
done
from kas(1) kas(2) have th02: "k + 1 = psize (pCons 1 (monom a (k - 1)))"
by (simp add: psize_def degree_monom_eq)
from less(1) [OF k1n [simplified th02] th01]
obtain w where w: "1 + w^k * a = 0"
unfolding poly_pCons poly_monom
using kas(2) by (cases k) (auto simp add: algebra_simps)
from poly_bound_exists[of "cmod w" s] obtain m where
m: "m > 0" "\<forall>z. cmod z \<le> cmod w \<longrightarrow> cmod (poly s z) \<le> m" by blast
have w0: "w \<noteq> 0"
using kas(2) w by (auto simp add: power_0_left)
from w have "(1 + w ^ k * a) - 1 = 0 - 1"
by simp
then have wm1: "w^k * a = - 1"
by simp
have inv0: "0 < inverse (cmod w ^ (k + 1) * m)"
using norm_ge_zero[of w] w0 m(1)
by (simp add: inverse_eq_divide zero_less_mult_iff)
with real_lbound_gt_zero[OF zero_less_one] obtain t where
t: "t > 0" "t < 1" "t < inverse (cmod w ^ (k + 1) * m)" by blast
let ?ct = "complex_of_real t"
let ?w = "?ct * w"
have "1 + ?w^k * (a + ?w * poly s ?w) = 1 + ?ct^k * (w^k * a) + ?w^k * ?w * poly s ?w"
using kas(1) by (simp add: algebra_simps power_mult_distrib)
also have "\<dots> = complex_of_real (1 - t^k) + ?w^k * ?w * poly s ?w"
unfolding wm1 by simp
finally have "cmod (1 + ?w^k * (a + ?w * poly s ?w)) =
cmod (complex_of_real (1 - t^k) + ?w^k * ?w * poly s ?w)"
by metis
with norm_triangle_ineq[of "complex_of_real (1 - t^k)" "?w^k * ?w * poly s ?w"]
have th11: "cmod (1 + ?w^k * (a + ?w * poly s ?w)) \<le> \<bar>1 - t^k\<bar> + cmod (?w^k * ?w * poly s ?w)"
unfolding norm_of_real by simp
have ath: "\<And>x t::real. 0 \<le> x \<Longrightarrow> x < t \<Longrightarrow> t \<le> 1 \<Longrightarrow> \<bar>1 - t\<bar> + x < 1"
by arith
have "t * cmod w \<le> 1 * cmod w"
apply (rule mult_mono)
using t(1,2)
apply auto
done
then have tw: "cmod ?w \<le> cmod w"
using t(1) by (simp add: norm_mult)
from t inv0 have "t * (cmod w ^ (k + 1) * m) < 1"
by (simp add: field_simps)
with zero_less_power[OF t(1), of k] have th30: "t^k * (t* (cmod w ^ (k + 1) * m)) < t^k * 1"
by simp
have "cmod (?w^k * ?w * poly s ?w) = t^k * (t* (cmod w ^ (k + 1) * cmod (poly s ?w)))"
using w0 t(1)
by (simp add: algebra_simps power_mult_distrib norm_power norm_mult)
then have "cmod (?w^k * ?w * poly s ?w) \<le> t^k * (t* (cmod w ^ (k + 1) * m))"
using t(1,2) m(2)[rule_format, OF tw] w0
by auto
with th30 have th120: "cmod (?w^k * ?w * poly s ?w) < t^k"
by simp
from power_strict_mono[OF t(2), of k] t(1) kas(2) have th121: "t^k \<le> 1"
by auto
from ath[OF norm_ge_zero[of "?w^k * ?w * poly s ?w"] th120 th121]
have th12: "\<bar>1 - t^k\<bar> + cmod (?w^k * ?w * poly s ?w) < 1" .
from th11 th12 have "cmod (1 + ?w^k * (a + ?w * poly s ?w)) < 1"
by arith
then have "cmod (poly ?r ?w) < 1"
unfolding kas(4)[rule_format, of ?w] r01 by simp
then show ?thesis
by blast
qed
with cq0 q(2) show ?thesis
unfolding mrmq_eq not_less[symmetric] by auto
qed
qed
text \<open>Alternative version with a syntactic notion of constant polynomial.\<close>
lemma fundamental_theorem_of_algebra_alt:
assumes nc: "\<not> (\<exists>a l. a \<noteq> 0 \<and> l = 0 \<and> p = pCons a l)"
shows "\<exists>z. poly p z = (0::complex)"
using nc
proof (induct p)
case 0
then show ?case by simp
next
case (pCons c cs)
show ?case
proof (cases "c = 0")
case True
then show ?thesis by auto
next
case False
have "\<not> constant (poly (pCons c cs))"
proof
assume nc: "constant (poly (pCons c cs))"
from nc[unfolded constant_def, rule_format, of 0]
have "\<forall>w. w \<noteq> 0 \<longrightarrow> poly cs w = 0" by auto
then have "cs = 0"
proof (induct cs)
case 0
then show ?case by simp
next
case (pCons d ds)
show ?case
proof (cases "d = 0")
case True
then show ?thesis
using pCons.prems pCons.hyps by simp
next
case False
from poly_bound_exists[of 1 ds] obtain m where
m: "m > 0" "\<forall>z. \<forall>z. cmod z \<le> 1 \<longrightarrow> cmod (poly ds z) \<le> m" by blast
have dm: "cmod d / m > 0"
using False m(1) by (simp add: field_simps)
from real_lbound_gt_zero[OF dm zero_less_one]
obtain x where x: "x > 0" "x < cmod d / m" "x < 1"
by blast
let ?x = "complex_of_real x"
from x have cx: "?x \<noteq> 0" "cmod ?x \<le> 1"
by simp_all
from pCons.prems[rule_format, OF cx(1)]
have cth: "cmod (?x*poly ds ?x) = cmod d"
by (simp add: eq_diff_eq[symmetric])
from m(2)[rule_format, OF cx(2)] x(1)
have th0: "cmod (?x*poly ds ?x) \<le> x*m"
by (simp add: norm_mult)
from x(2) m(1) have "x * m < cmod d"
by (simp add: field_simps)
with th0 have "cmod (?x*poly ds ?x) \<noteq> cmod d"
by auto
with cth show ?thesis
by blast
qed
qed
then show False
using pCons.prems False by blast
qed
then show ?thesis
by (rule fundamental_theorem_of_algebra)
qed
qed
subsection \<open>Nullstellensatz, degrees and divisibility of polynomials\<close>
lemma nullstellensatz_lemma:
fixes p :: "complex poly"
assumes "\<forall>x. poly p x = 0 \<longrightarrow> poly q x = 0"
and "degree p = n"
and "n \<noteq> 0"
shows "p dvd (q ^ n)"
using assms
proof (induct n arbitrary: p q rule: nat_less_induct)
fix n :: nat
fix p q :: "complex poly"
assume IH: "\<forall>m<n. \<forall>p q.
(\<forall>x. poly p x = (0::complex) \<longrightarrow> poly q x = 0) \<longrightarrow>
degree p = m \<longrightarrow> m \<noteq> 0 \<longrightarrow> p dvd (q ^ m)"
and pq0: "\<forall>x. poly p x = 0 \<longrightarrow> poly q x = 0"
and dpn: "degree p = n"
and n0: "n \<noteq> 0"
from dpn n0 have pne: "p \<noteq> 0" by auto
show "p dvd (q ^ n)"
proof (cases "\<exists>a. poly p a = 0")
case True
then obtain a where a: "poly p a = 0" ..
have ?thesis if oa: "order a p \<noteq> 0"
proof -
let ?op = "order a p"
from pne have ap: "([:- a, 1:] ^ ?op) dvd p" "\<not> [:- a, 1:] ^ (Suc ?op) dvd p"
using order by blast+
note oop = order_degree[OF pne, unfolded dpn]
show ?thesis
proof (cases "q = 0")
case True
with n0 show ?thesis by (simp add: power_0_left)
next
case False
from pq0[rule_format, OF a, unfolded poly_eq_0_iff_dvd]
obtain r where r: "q = [:- a, 1:] * r" by (rule dvdE)
from ap(1) obtain s where s: "p = [:- a, 1:] ^ ?op * s"
by (rule dvdE)
have sne: "s \<noteq> 0"
using s pne by auto
show ?thesis
proof (cases "degree s = 0")
case True
then obtain k where kpn: "s = [:k:]"
by (cases s) (auto split: if_splits)
from sne kpn have k: "k \<noteq> 0" by simp
let ?w = "([:1/k:] * ([:-a,1:] ^ (n - ?op))) * (r ^ n)"
have "q ^ n = p * ?w"
apply (subst r)
apply (subst s)
apply (subst kpn)
using k oop [of a]
apply (subst power_mult_distrib)
apply simp
apply (subst power_add [symmetric])
apply simp
done
then show ?thesis
unfolding dvd_def by blast
next
case False
with sne dpn s oa have dsn: "degree s < n"
apply auto
apply (erule ssubst)
apply (simp add: degree_mult_eq degree_linear_power)
done
have "poly r x = 0" if h: "poly s x = 0" for x
proof -
have xa: "x \<noteq> a"
proof
assume "x = a"
from h[unfolded this poly_eq_0_iff_dvd] obtain u where u: "s = [:- a, 1:] * u"
by (rule dvdE)
have "p = [:- a, 1:] ^ (Suc ?op) * u"
apply (subst s)
apply (subst u)
apply (simp only: power_Suc ac_simps)
done
with ap(2)[unfolded dvd_def] show False
by blast
qed
from h have "poly p x = 0"
by (subst s) simp
with pq0 have "poly q x = 0"
by blast
with r xa show ?thesis
by auto
qed
with IH[rule_format, OF dsn, of s r] False have "s dvd (r ^ (degree s))"
by blast
then obtain u where u: "r ^ (degree s) = s * u" ..
then have u': "\<And>x. poly s x * poly u x = poly r x ^ degree s"
by (simp only: poly_mult[symmetric] poly_power[symmetric])
let ?w = "(u * ([:-a,1:] ^ (n - ?op))) * (r ^ (n - degree s))"
from oop[of a] dsn have "q ^ n = p * ?w"
apply -
apply (subst s)
apply (subst r)
apply (simp only: power_mult_distrib)
apply (subst mult.assoc [where b=s])
apply (subst mult.assoc [where a=u])
apply (subst mult.assoc [where b=u, symmetric])
apply (subst u [symmetric])
apply (simp add: ac_simps power_add [symmetric])
done
then show ?thesis
unfolding dvd_def by blast
qed
qed
qed
then show ?thesis
using a order_root pne by blast
next
case False
with fundamental_theorem_of_algebra_alt[of p]
obtain c where ccs: "c \<noteq> 0" "p = pCons c 0"
by blast
then have pp: "poly p x = c" for x
by simp
let ?w = "[:1/c:] * (q ^ n)"
from ccs have "(q ^ n) = (p * ?w)"
by simp
then show ?thesis
unfolding dvd_def by blast
qed
qed
lemma nullstellensatz_univariate:
"(\<forall>x. poly p x = (0::complex) \<longrightarrow> poly q x = 0) \<longleftrightarrow>
p dvd (q ^ (degree p)) \<or> (p = 0 \<and> q = 0)"
proof -
consider "p = 0" | "p \<noteq> 0" "degree p = 0" | n where "p \<noteq> 0" "degree p = Suc n"
by (cases "degree p") auto
then show ?thesis
proof cases
case p: 1
then have eq: "(\<forall>x. poly p x = (0::complex) \<longrightarrow> poly q x = 0) \<longleftrightarrow> q = 0"
by (auto simp add: poly_all_0_iff_0)
{
assume "p dvd (q ^ (degree p))"
then obtain r where r: "q ^ (degree p) = p * r" ..
from r p have False by simp
}
with eq p show ?thesis by blast
next
case dp: 2
then obtain k where k: "p = [:k:]" "k \<noteq> 0"
by (cases p) (simp split: if_splits)
then have th1: "\<forall>x. poly p x \<noteq> 0"
by simp
from k dp(2) have "q ^ (degree p) = p * [:1/k:]"
by (simp add: one_poly_def)
then have th2: "p dvd (q ^ (degree p))" ..
from dp(1) th1 th2 show ?thesis
by blast
next
case dp: 3
have False if dvd: "p dvd (q ^ (Suc n))" and h: "poly p x = 0" "poly q x \<noteq> 0" for x
proof -
from dvd obtain u where u: "q ^ (Suc n) = p * u" ..
from h have "poly (q ^ (Suc n)) x \<noteq> 0"
by simp
with u h(1) show ?thesis
by (simp only: poly_mult) simp
qed
with dp nullstellensatz_lemma[of p q "degree p"] show ?thesis
by auto
qed
qed
text \<open>Useful lemma\<close>
lemma constant_degree:
fixes p :: "'a::{idom,ring_char_0} poly"
shows "constant (poly p) \<longleftrightarrow> degree p = 0" (is "?lhs = ?rhs")
proof
show ?rhs if ?lhs
proof -
from that[unfolded constant_def, rule_format, of _ "0"]
have th: "poly p = poly [:poly p 0:]"
by auto
then have "p = [:poly p 0:]"
by (simp add: poly_eq_poly_eq_iff)
then have "degree p = degree [:poly p 0:]"
by simp
then show ?thesis
by simp
qed
show ?lhs if ?rhs
proof -
from that obtain k where "p = [:k:]"
by (cases p) (simp split: if_splits)
then show ?thesis
unfolding constant_def by auto
qed
qed
text \<open>Arithmetic operations on multivariate polynomials.\<close>
lemma mpoly_base_conv:
fixes x :: "'a::comm_ring_1"
shows "0 = poly 0 x" "c = poly [:c:] x" "x = poly [:0,1:] x"
by simp_all
lemma mpoly_norm_conv:
fixes x :: "'a::comm_ring_1"
shows "poly [:0:] x = poly 0 x" "poly [:poly 0 y:] x = poly 0 x"
by simp_all
lemma mpoly_sub_conv:
fixes x :: "'a::comm_ring_1"
shows "poly p x - poly q x = poly p x + -1 * poly q x"
by simp
lemma poly_pad_rule: "poly p x = 0 \<Longrightarrow> poly (pCons 0 p) x = 0"
by simp
lemma poly_cancel_eq_conv:
fixes x :: "'a::field"
shows "x = 0 \<Longrightarrow> a \<noteq> 0 \<Longrightarrow> y = 0 \<longleftrightarrow> a * y - b * x = 0"
by auto
lemma poly_divides_pad_rule:
fixes p:: "('a::comm_ring_1) poly"
assumes pq: "p dvd q"
shows "p dvd (pCons 0 q)"
proof -
have "pCons 0 q = q * [:0,1:]" by simp
then have "q dvd (pCons 0 q)" ..
with pq show ?thesis by (rule dvd_trans)
qed
lemma poly_divides_conv0:
fixes p:: "'a::field poly"
assumes lgpq: "degree q < degree p"
and lq: "p \<noteq> 0"
shows "p dvd q \<longleftrightarrow> q = 0" (is "?lhs \<longleftrightarrow> ?rhs")
proof
assume ?rhs
then have "q = p * 0" by simp
then show ?lhs ..
next
assume l: ?lhs
show ?rhs
proof (cases "q = 0")
case True
then show ?thesis by simp
next
assume q0: "q \<noteq> 0"
from l q0 have "degree p \<le> degree q"
by (rule dvd_imp_degree_le)
with lgpq show ?thesis by simp
qed
qed
lemma poly_divides_conv1:
fixes p :: "'a::field poly"
assumes a0: "a \<noteq> 0"
and pp': "p dvd p'"
and qrp': "smult a q - p' = r"
shows "p dvd q \<longleftrightarrow> p dvd r" (is "?lhs \<longleftrightarrow> ?rhs")
proof
from pp' obtain t where t: "p' = p * t" ..
show ?rhs if ?lhs
proof -
from that obtain u where u: "q = p * u" ..
have "r = p * (smult a u - t)"
using u qrp' [symmetric] t by (simp add: algebra_simps)
then show ?thesis ..
qed
show ?lhs if ?rhs
proof -
from that obtain u where u: "r = p * u" ..
from u [symmetric] t qrp' [symmetric] a0
have "q = p * smult (1/a) (u + t)"
by (simp add: algebra_simps)
then show ?thesis ..
qed
qed
lemma basic_cqe_conv1:
"(\<exists>x. poly p x = 0 \<and> poly 0 x \<noteq> 0) \<longleftrightarrow> False"
"(\<exists>x. poly 0 x \<noteq> 0) \<longleftrightarrow> False"
"(\<exists>x. poly [:c:] x \<noteq> 0) \<longleftrightarrow> c \<noteq> 0"
"(\<exists>x. poly 0 x = 0) \<longleftrightarrow> True"
"(\<exists>x. poly [:c:] x = 0) \<longleftrightarrow> c = 0"
by simp_all
lemma basic_cqe_conv2:
assumes l: "p \<noteq> 0"
shows "\<exists>x. poly (pCons a (pCons b p)) x = (0::complex)"
proof -
have False if "h \<noteq> 0" "t = 0" and "pCons a (pCons b p) = pCons h t" for h t
using l that by simp
then have th: "\<not> (\<exists> h t. h \<noteq> 0 \<and> t = 0 \<and> pCons a (pCons b p) = pCons h t)"
by blast
from fundamental_theorem_of_algebra_alt[OF th] show ?thesis
by auto
qed
lemma basic_cqe_conv_2b: "(\<exists>x. poly p x \<noteq> (0::complex)) \<longleftrightarrow> p \<noteq> 0"
by (metis poly_all_0_iff_0)
lemma basic_cqe_conv3:
fixes p q :: "complex poly"
assumes l: "p \<noteq> 0"
shows "(\<exists>x. poly (pCons a p) x = 0 \<and> poly q x \<noteq> 0) \<longleftrightarrow> \<not> (pCons a p) dvd (q ^ psize p)"
proof -
from l have dp: "degree (pCons a p) = psize p"
by (simp add: psize_def)
from nullstellensatz_univariate[of "pCons a p" q] l
show ?thesis
by (metis dp pCons_eq_0_iff)
qed
lemma basic_cqe_conv4:
fixes p q :: "complex poly"
assumes h: "\<And>x. poly (q ^ n) x = poly r x"
shows "p dvd (q ^ n) \<longleftrightarrow> p dvd r"
proof -
from h have "poly (q ^ n) = poly r"
by auto
then have "(q ^ n) = r"
by (simp add: poly_eq_poly_eq_iff)
then show "p dvd (q ^ n) \<longleftrightarrow> p dvd r"
by simp
qed
lemma poly_const_conv:
fixes x :: "'a::comm_ring_1"
shows "poly [:c:] x = y \<longleftrightarrow> c = y"
by simp
end
|
Require Import Grph.Graph.
Require Import Grph.GraphCat.
Definition LinGraphV (n : nat) :=
{x : nat | x <= n}.
Definition LinGraphA (n : nat) :=
{x : nat | x < n}.
Definition src {n : nat} (v : LinGraphA n) : LinGraphV n.
refine (match v with exist x _ => exist _ n _ end).
auto.
Defined.
Definition tgt {n : nat} (v : LinGraphA n) : LinGraphV n.
refine (match v with exist x _ => exist _ (S x) _ end).
assumption.
Defined.
Definition LinGraph (n : nat) : Graph (LinGraphV n) (LinGraphA n)
:= graph src tgt.
Definition LinGrph (n : nat) : Grph :=
grph (LinGraph n). |
module Utils.Handle
import Data.Vect
import Data.Nat
import Control.Monad.Error.Either
import Control.Linear.LIO
public export
ReadHack : (t_ok : Type) -> (t_read_failed : Type) -> Bool -> Type
ReadHack t_ok t_read_failed False = t_read_failed
ReadHack t_ok t_read_failed True = Res (List Bits8) (const t_ok)
public export
WriteHack : (t_ok : Type) -> (t_write_failed : Type) -> Bool -> Type
WriteHack t_ok t_write_failed False = t_write_failed
WriteHack t_ok t_write_failed True = t_ok
public export
record Handle (t_ok : Type) (t_closed : Type) (t_read_failed : Type) (t_write_failed : Type) where
constructor MkHandle
1 underlying : t_ok
do_read : forall m. LinearIO m => (1 _ : t_ok) -> (len : Nat) -> L1 m $ Res Bool $ ReadHack t_ok t_read_failed
do_write : forall m. LinearIO m => (1 _ : t_ok) -> List Bits8 -> L1 m $ Res Bool $ WriteHack t_ok t_write_failed
do_close : forall m. LinearIO m => (1 _ : t_ok) -> L1 m t_closed
public export
close : LinearIO m => (1 _ : Handle t_ok t_closed t_read_failed t_write_failed) -> L1 m t_closed
close (MkHandle x do_read do_write do_close) = do_close x
public export
read : LinearIO m => (1 _ : Handle t_ok t_closed t_read_failed t_write_failed) -> (len : Nat) -> L1 m $ Res Bool $ \case
False => t_read_failed
True => Res (List Bits8) (\_ => Handle t_ok t_closed t_read_failed t_write_failed)
read (MkHandle x do_read do_write do_close) len = do
(True # (output # x)) <- do_read x len
| (False # x) => pure1 $ False # x
pure1 $ True # (output # MkHandle x do_read do_write do_close)
public export
write : LinearIO m => (1 _ : Handle t_ok t_closed t_read_failed t_write_failed) -> (input : List Bits8) -> L1 m $ Res Bool $ \case
False => t_write_failed
True => Handle t_ok t_closed t_read_failed t_write_failed
write (MkHandle x do_read do_write do_close) input = do
(True # x) <- do_write x input
| (False # x) => pure1 $ False # x
pure1 $ True # MkHandle x do_read do_write do_close
public export
Handle' : Type -> Type -> Type
Handle' t_ok t_closed = Handle t_ok t_closed (Res String $ const t_closed) (Res String $ const t_closed)
|
(* *********************************************************************)
(* *)
(* The Compcert verified compiler *)
(* *)
(* Xavier Leroy, INRIA Paris-Rocquencourt *)
(* *)
(* Copyright Institut National de Recherche en Informatique et en *)
(* Automatique. All rights reserved. This file is distributed *)
(* under the terms of the GNU General Public License as published by *)
(* the Free Software Foundation, either version 2 of the License, or *)
(* (at your option) any later version. This file is also distributed *)
(* under the terms of the INRIA Non-Commercial License Agreement. *)
(* *)
(* *********************************************************************)
(** This file collects some axioms used throughout the CompCert development. *)
Require ClassicalFacts.
(** * Extensionality axioms *)
(** The following [Require Export] gives us functional extensionality for dependent function types:
<<
Axiom functional_extensionality_dep : forall {A} {B : A -> Type},
forall (f g : forall x : A, B x),
(forall x, f x = g x) -> f = g.
>>
and, as a corollary, functional extensionality for non-dependent functions:
<<
Lemma functional_extensionality {A B} (f g : A -> B) :
(forall x, f x = g x) -> f = g.
>>
*)
Require Export FunctionalExtensionality.
(** For compatibility with earlier developments, [extensionality]
is an alias for [functional_extensionality]. *)
Lemma extensionality:
forall (A B: Type) (f g : A -> B), (forall x, f x = g x) -> f = g.
Proof. intros; apply functional_extensionality. auto. Qed.
Implicit Arguments extensionality.
(** We also assert propositional extensionality. *)
Axiom prop_ext: ClassicalFacts.prop_extensionality.
Implicit Arguments prop_ext.
(** * Proof irrelevance *)
(** We also use proof irrelevance, which is a consequence of propositional
extensionality. *)
Lemma proof_irr: ClassicalFacts.proof_irrelevance.
Proof.
exact (ClassicalFacts.ext_prop_dep_proof_irrel_cic prop_ext).
Qed.
Implicit Arguments proof_irr.
|
module EMLlead_lag
using DanaTypes
using DotPlusInheritance
using Reexport
@reexport using ...types.EMLtypes
import EMLtypes.length
include("lead_lag/Lead_lag.jl")
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.