text
stringlengths 0
3.34M
|
---|
State Before: α : Type u_1
inst✝ : OrderedSemiring α
x : ↑(Icc 0 1)
⊢ ↑x = 0 ↔ x = 0 State After: α : Type u_1
inst✝ : OrderedSemiring α
x : ↑(Icc 0 1)
⊢ x = 0 ↔ ↑x = 0 Tactic: symm State Before: α : Type u_1
inst✝ : OrderedSemiring α
x : ↑(Icc 0 1)
⊢ x = 0 ↔ ↑x = 0 State After: no goals Tactic: exact Subtype.ext_iff |
import ring_theory.algebra
universes u v w u₁ v₁
namespace algebra
variables {R : Type u} {S : Type v} {A : Type w}
variables [comm_ring R] [comm_ring S] [ring A] [algebra R A]
lemma mul_sub_algebra_map_commutes (x : A) (r : R) :
x * (x - algebra_map R A r) = (x - algebra_map R A r) * x :=
by rw [mul_sub, ←commutes, sub_mul]
lemma mul_sub_algebra_map_pow_commutes (x : A) (r : R) (n : ℕ) :
x * (x - algebra_map R A r) ^ n = (x - algebra_map R A r) ^ n * x :=
begin
induction n with n ih,
{ simp },
{ rw [pow_succ, ←mul_assoc, mul_sub_algebra_map_commutes,
mul_assoc, ih, ←mul_assoc], }
end
end algebra |
Jockey Jim Almost in the Home Stretch!
Seems like all I’ve been doing is learning my lines for “Jockey Jim”or going to rehearsal at the Henry Clay. This play is written by my friend and great playwright Larry Muhammad, (https://insiderlouisville.com/lifestyle_culture/larry-muhammad-play-highlights-the-fascinating-story-of-black-jockey-jimmy-winkfield/ and https://www.power2give.org/campaigns/376) I have the female lead, Lydia de Minkiwitz, James Winkfield’s wife who was a Russian baroness, so I have my share of lines, and I have learned them, YES! And I’m saying them all with a Russian accent, ha! I have five costume changes, below is a picture of my favorite costume, haha, you guessed it, it’s glam!
I hope all my Louisville friends come to see us, it’s going to be one fine play! |
[GOAL]
α : Type u_1
M₀ : Type u_2
G₀ : Type u_3
M₀' : Type u_4
G₀' : Type u_5
F : Type u_6
F' : Type u_7
inst✝¹ : MonoidWithZero M₀
inst✝ : GroupWithZero G₀
a✝ b c a : G₀
hc : c ≠ 0
⊢ a / c / (b / c) = a / b
[PROOFSTEP]
rw [div_div_eq_mul_div, div_mul_cancel _ hc]
[GOAL]
α : Type u_1
M₀ : Type u_2
G₀ : Type u_3
M₀' : Type u_4
G₀' : Type u_5
F : Type u_6
F' : Type u_7
inst✝¹ : MonoidWithZero M₀
inst✝ : GroupWithZero G₀
a✝ b c a : G₀
hc : c ≠ 0
⊢ a / c * (c / b) = a / b
[PROOFSTEP]
rw [← mul_div_assoc, div_mul_cancel _ hc]
[GOAL]
α : Type u_1
M₀ : Type u_2
G₀ : Type u_3
M₀' : Type u_4
G₀' : Type u_5
F : Type u_6
F' : Type u_7
inst✝¹ : MonoidWithZero M₀
inst✝ : GroupWithZero G₀
a✝ b✝ c a b : G₀
h : b = 0 → a = 0
hb : b = 0
⊢ a / b * b = a
[PROOFSTEP]
simp [*]
[GOAL]
α : Type u_1
M₀ : Type u_2
G₀ : Type u_3
M₀' : Type u_4
G₀' : Type u_5
F : Type u_6
F' : Type u_7
inst✝¹ : MonoidWithZero M₀
inst✝ : GroupWithZero G₀
a✝ b✝ c a b : G₀
h : b = 0 → a = 0
hb : b = 0
⊢ a * b / b = a
[PROOFSTEP]
simp [*]
[GOAL]
α : Type u_1
M₀ : Type u_2
G₀ : Type u_3
M₀' : Type u_4
G₀' : Type u_5
F : Type u_6
F' : Type u_7
inst✝¹ : MonoidWithZero M₀
inst✝ : CommGroupWithZero G₀
a✝ b✝ c d a b : G₀
h : a = 0 → b = 0
⊢ a * b / a = b
[PROOFSTEP]
rw [mul_comm, mul_div_cancel_of_imp h]
[GOAL]
α : Type u_1
M₀ : Type u_2
G₀ : Type u_3
M₀' : Type u_4
G₀' : Type u_5
F : Type u_6
F' : Type u_7
inst✝¹ : MonoidWithZero M₀
inst✝ : CommGroupWithZero G₀
a✝ b✝ c d a b : G₀
h : b = 0 → a = 0
⊢ b * (a / b) = a
[PROOFSTEP]
rw [mul_comm, div_mul_cancel_of_imp h]
[GOAL]
α : Type u_1
M₀ : Type u_2
G₀ : Type u_3
M₀' : Type u_4
G₀' : Type u_5
F : Type u_6
F' : Type u_7
inst✝¹ : MonoidWithZero M₀
inst✝ : CommGroupWithZero G₀
a✝ b✝ c✝ d✝ a b c d : G₀
hb : b ≠ 0
hd : d ≠ 0
h : a / b = c / d
⊢ a * d = c * b
[PROOFSTEP]
rw [← mul_one a, ← div_self hb, ← mul_comm_div, h, div_mul_eq_mul_div, div_mul_cancel _ hd]
[GOAL]
α : Type u_1
M₀ : Type u_2
G₀ : Type u_3
M₀' : Type u_4
G₀' : Type u_5
F : Type u_6
F' : Type u_7
inst✝¹ : MonoidWithZero M₀
inst✝ : CommGroupWithZero G₀
a b✝ c d b : G₀
h : a ≠ 0
⊢ 1 / (a * b) * a = 1 / b
[PROOFSTEP]
rw [div_mul_eq_mul_div, one_mul, div_mul_right _ h]
[GOAL]
α : Type u_1
M₀ : Type u_2
G₀ : Type u_3
M₀' : Type u_4
G₀' : Type u_5
F : Type u_6
F' : Type u_7
inst✝¹ : MonoidWithZero M₀
inst✝ : CommGroupWithZero G₀
a✝ b✝ c d a b : G₀
hc : c ≠ 0
⊢ c / a / (c / b) = b / a
[PROOFSTEP]
rw [div_div_div_eq, mul_comm, mul_div_mul_right _ _ hc]
[GOAL]
α : Type u_1
M₀ : Type u_2
G₀ : Type u_3
M₀' : Type u_4
G₀' : Type u_5
F : Type u_6
F' : Type u_7
inst✝⁵ : MonoidWithZero M₀
inst✝⁴ : GroupWithZero G₀
inst✝³ : Nontrivial M₀
inst✝² : MonoidWithZero M₀'
inst✝¹ : MonoidWithZeroHomClass F G₀ M₀
inst✝ : MonoidWithZeroHomClass F' G₀ M₀'
f✝ : F
a : G₀
f g : F'
h : ↑f a = ↑g a
⊢ ↑f a⁻¹ = ↑g a⁻¹
[PROOFSTEP]
rcases eq_or_ne a 0 with (rfl | ha)
[GOAL]
case inl
α : Type u_1
M₀ : Type u_2
G₀ : Type u_3
M₀' : Type u_4
G₀' : Type u_5
F : Type u_6
F' : Type u_7
inst✝⁵ : MonoidWithZero M₀
inst✝⁴ : GroupWithZero G₀
inst✝³ : Nontrivial M₀
inst✝² : MonoidWithZero M₀'
inst✝¹ : MonoidWithZeroHomClass F G₀ M₀
inst✝ : MonoidWithZeroHomClass F' G₀ M₀'
f✝ : F
f g : F'
h : ↑f 0 = ↑g 0
⊢ ↑f 0⁻¹ = ↑g 0⁻¹
[PROOFSTEP]
rw [inv_zero, map_zero, map_zero]
[GOAL]
case inr
α : Type u_1
M₀ : Type u_2
G₀ : Type u_3
M₀' : Type u_4
G₀' : Type u_5
F : Type u_6
F' : Type u_7
inst✝⁵ : MonoidWithZero M₀
inst✝⁴ : GroupWithZero G₀
inst✝³ : Nontrivial M₀
inst✝² : MonoidWithZero M₀'
inst✝¹ : MonoidWithZeroHomClass F G₀ M₀
inst✝ : MonoidWithZeroHomClass F' G₀ M₀'
f✝ : F
a : G₀
f g : F'
h : ↑f a = ↑g a
ha : a ≠ 0
⊢ ↑f a⁻¹ = ↑g a⁻¹
[PROOFSTEP]
exact (IsUnit.mk0 a ha).eq_on_inv f g h
[GOAL]
α : Type u_1
M₀ : Type u_2
G₀ : Type u_3
M₀' : Type u_4
G₀' : Type u_5
F : Type u_6
F' : Type u_7
inst✝³ : MonoidWithZero M₀
inst✝² : GroupWithZero G₀
inst✝¹ : GroupWithZero G₀'
inst✝ : MonoidWithZeroHomClass F G₀ G₀'
f : F
a b : G₀
⊢ ↑f a⁻¹ = (↑f a)⁻¹
[PROOFSTEP]
by_cases h : a = 0
[GOAL]
case pos
α : Type u_1
M₀ : Type u_2
G₀ : Type u_3
M₀' : Type u_4
G₀' : Type u_5
F : Type u_6
F' : Type u_7
inst✝³ : MonoidWithZero M₀
inst✝² : GroupWithZero G₀
inst✝¹ : GroupWithZero G₀'
inst✝ : MonoidWithZeroHomClass F G₀ G₀'
f : F
a b : G₀
h : a = 0
⊢ ↑f a⁻¹ = (↑f a)⁻¹
[PROOFSTEP]
simp [h, map_zero f]
[GOAL]
case neg
α : Type u_1
M₀ : Type u_2
G₀ : Type u_3
M₀' : Type u_4
G₀' : Type u_5
F : Type u_6
F' : Type u_7
inst✝³ : MonoidWithZero M₀
inst✝² : GroupWithZero G₀
inst✝¹ : GroupWithZero G₀'
inst✝ : MonoidWithZeroHomClass F G₀ G₀'
f : F
a b : G₀
h : ¬a = 0
⊢ ↑f a⁻¹ = (↑f a)⁻¹
[PROOFSTEP]
apply eq_inv_of_mul_eq_one_left
[GOAL]
case neg.h
α : Type u_1
M₀ : Type u_2
G₀ : Type u_3
M₀' : Type u_4
G₀' : Type u_5
F : Type u_6
F' : Type u_7
inst✝³ : MonoidWithZero M₀
inst✝² : GroupWithZero G₀
inst✝¹ : GroupWithZero G₀'
inst✝ : MonoidWithZeroHomClass F G₀ G₀'
f : F
a b : G₀
h : ¬a = 0
⊢ ↑f a⁻¹ * ↑f a = 1
[PROOFSTEP]
rw [← map_mul, inv_mul_cancel h, map_one]
|
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE UnicodeSyntax #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE CPP #-}
module NQS.SR
( -- * Stochastic Reconfiguration
--
-- Globally, the SR algorithm looks more or less like this
--
-- @
-- for n in {0,...,maxIter - 1} do
-- (F, ∂ψ) <- sample ψ
-- S <- covariance⁽ⁿ⁾ ∂ψ
-- δ <- (S + λ⁽ⁿ⁾)⁻¹ F
-- ψ <- ψ - learningRate * δ
-- done
-- @
-- * AXPY
-- * Sampling
-- * Constructing S
-- * Solving S
sr
, IterInfo(..)
, HasIter(..)
, HasSampler(..)
, HasSolver(..)
, HasMoments(..)
, HasForceNorm(..)
) where
import Prelude hiding ( zipWith
, zipWithM
, map
, mapM
)
import GHC.Generics ( Generic )
import Debug.Trace
import Control.Exception ( assert )
import Control.Monad.Identity ( Identity(..) )
import Control.Monad.ST
import System.IO.Unsafe ( unsafePerformIO )
import Foreign.Storable
import Foreign.ForeignPtr
import Data.Vector.Storable ( Vector )
import qualified Data.Vector.Storable as V
import Data.Vector.Storable.Mutable ( MVector )
import qualified Data.Vector.Storable.Mutable as MV
import qualified Data.Vector.Unboxed
import Data.Singletons
import Data.Complex
import Data.Semigroup ( (<>) )
import Control.Monad ( (>=>) )
import Control.Monad.Primitive
import Control.DeepSeq
import System.CPUTime
import Data.Aeson
import qualified NQS.CG as CG
import NQS.CG ( Operator )
import NQS.Rbm (Rbm(..))
import NQS.Rbm.Mutable
import NQS.Internal.BLAS
import NQS.Internal.LAPACK
import NQS.Internal.Types
import NQS.Internal.Hamiltonian
import NQS.Internal.Sampling
import NQS.Internal.Rbm (unsafeFreezeRbm)
import Lens.Micro
import Lens.Micro.TH
import Lens.Micro.Extras
import GHC.Float ( int2Float )
import Data.Aeson
import qualified Data.ByteString.Lazy.Char8 as BS
-- | In Stochastic Reconfiguration we only ever deal with 'Direct' vectors.
type V = MDenseVector 'Direct
-- | A shorter name for dense matrices.
type M orient s a = MDenseMatrix orient s a
data SolverStats = SolverStats
{ _solverStatsIters :: {-# UNPACK #-}!Int
, _solverStatsErr :: {-# UNPACK #-}!ℝ
, _solverStatsTime :: {-# UNPACK #-}!Double
}
makeFields ''SolverStats
instance ToJSON SolverStats where
toJSON stats =
object [ "iters" .= (stats ^. iters)
, "error" .= (stats ^. err)
, "time" .= (stats ^. time)
]
toEncoding stats =
pairs $ "iters" .= (stats ^. iters)
<> "error" .= (stats ^. err)
<> "time" .= (stats ^. time)
instance FromJSON SolverStats where
parseJSON = withObject "SolverStats" $ \v ->
SolverStats <$> v .: "iters"
<*> v .: "error"
<*> v .: "time"
data SamplerStats = SamplerStats
{ _samplerStatsMoments :: {-# UNPACK #-}!(Vector ℂ)
, _samplerStatsStdDev :: !(Maybe ℝ)
, _samplerStatsDim :: {-# UNPACK #-}!Int
, _samplerStatsTime :: {-# UNPACK #-}!Double
}
makeFields ''SamplerStats
instance ToJSON SamplerStats where
toJSON stats =
object [ "moments" .= (stats ^. moments)
, "stddev" .= (stats ^. stdDev)
, "dim" .= (stats ^. dim)
, "time" .= (stats ^. time)
]
toEncoding stats =
pairs $ "moments" .= (stats ^. moments)
<> "stddev" .= (stats ^. stdDev)
<> "dim" .= (stats ^. dim)
<> "time" .= (stats ^. time)
instance FromJSON SamplerStats where
parseJSON = withObject "SamplerStats" $ \v ->
SamplerStats <$> v .: "moments"
<*> v .: "stddev"
<*> v .: "dim"
<*> v .: "time"
data IterInfo = IterInfo
{ _iterInfoIter :: {-# UNPACK #-}!Int
, _iterInfoState :: Rbm
, _iterInfoSampler :: !SamplerStats
, _iterInfoSolver :: !SolverStats
, _iterInfoForceNorm :: {-# UNPACK #-}!ℝ
, _iterInfoDeltaNorm :: {-# UNPACK #-}!ℝ
}
makeFields ''IterInfo
instance ToJSON IterInfo where
toJSON stats =
object [ "iter" .= (stats ^. iter)
, "state" .= (stats ^. state)
, "sampler" .= (stats ^. sampler)
, "solver" .= (stats ^. solver)
, "forceNorm" .= (stats ^. forceNorm)
, "deltaNorm" .= (stats ^. deltaNorm)
]
toEncoding stats =
pairs $ "iter" .= (stats ^. iter)
<> "state" .= (stats ^. state)
<> "sampler" .= (stats ^. sampler)
<> "solver" .= (stats ^. solver)
<> "forceNorm" .= (stats ^. forceNorm)
<> "deltaNorm" .= (stats ^. deltaNorm)
instance FromJSON IterInfo where
parseJSON = withObject "IterInfo" $ \v ->
IterInfo <$> v .: "iter"
<*> v .: "state"
<*> v .: "sampler"
<*> v .: "solver"
<*> v .: "forceNorm"
<*> v .: "deltaNorm"
-- AXPY
-- -----------------------------------------------------------------------------
type AxpyFun v m = ℂ -> V (PrimState m) ℂ -> v (PrimState m) -> m ()
-- | \(Y \leftarrow \alpha X + Y\) for 'Column' matrices.
axpyMatrix
:: (PrimMonad m, Storable a, AXPY (MDenseVector 'Direct) a)
=> a
-> MDenseVector 'Direct (PrimState m) a
-> MDenseMatrix 'Column (PrimState m) a
-> m ()
axpyMatrix !α !x !y@(MDenseMatrix !rows !cols !stride !buff) =
assert (rows * cols == x ^. dim) $ loop 0
where
getX !i = slice (i * rows) rows x
getY !i = unsafeColumn i y
loop !i | i < cols = axpy α (getX i) (getY i) >> loop (i + 1)
| otherwise = return ()
-- | Performs @y <- αx + y@ where @x@ is a vector and @y@ -- an RBM.
axpyRbm :: AxpyFun MRbm IO
axpyRbm α x y =
let n = sizeVisible y
m = sizeHidden y
in assert (x ^. dim == size y) $ do
withVisible y $ \a -> do
axpy α (slice 0 n x) a
-- unsafeFreeze a >>= \a' -> print (a' ^. buffer)
withHidden y $ \b -> do
axpy α (slice n m x) b
-- unsafeFreeze b >>= \b' -> print (b' ^. buffer)
withWeights y $ \w -> do
axpyMatrix α (slice (n + m) (n * m) x) w
-- unsafeFreeze w >>= \w' -> print (w' ^. buffer)
-- Monte-Carlo sampling
-- -----------------------------------------------------------------------------
-- | Sampling
type SampleFun v m
= v (PrimState m)
-> V (PrimState m) ℂ
-> M 'Row (PrimState m) ℂ
-> m SamplerStats
-- | Monte-Carlo sampling an RBM
sampleRbm :: MCConfig -> Hamiltonian -> SampleFun MRbm IO
sampleRbm config hamiltonian = doSample
where
doSample rbm force derivatives = do
t1 <- getCPUTime
moments <- MV.new 2
(dimension, variance) <- sampleGradients config
hamiltonian
rbm
moments
force
derivatives
t2 <- getCPUTime
V.unsafeFreeze moments >>= \moments' -> return
(SamplerStats moments'
(sqrt <$> variance)
dimension
(fromIntegral (t2 - t1) * 1.0E-12)
)
type SolveFun wrapper m
= wrapper -- ^ S
-> V (PrimState m) ℂ -- ^ b
-> V (PrimState m) ℂ -- ^ x
-> m SolverStats
type MakeSFun wrapper m = Int -> M 'Row (PrimState m) ℂ -> m wrapper
-- | Sparse representation of the @S@ matrix.
data SMatrix s =
SMatrix !(M 'Row s ℂ) -- ^ Derivatives (O - 〈O〉)
!(V s ℂ) -- ^ Workspace of size #steps.
!(Maybe ℂ) -- ^ Regulariser λ
makeS :: PrimMonad m => Maybe (Int -> ℂ) -> MakeSFun (SMatrix (PrimState m)) m
makeS regulariser i gradients = do
workspace <- newDenseVector (gradients ^. dim ^. _1)
return $! SMatrix gradients workspace ((\f -> f i) <$> regulariser)
makeS' :: PrimMonad m => Maybe (Int -> ℂ) -> MakeSFun (M 'Row (PrimState m) ℂ) m
makeS' regulariser i gradients = do
let (steps, params) = gradients ^. dim
s <- newDenseMatrix params params
herk MatUpper ConjTranspose (1 / int2Float steps) gradients 0 s
herk MatLower ConjTranspose (1 / int2Float steps) gradients 0 s
case regulariser of
Just f -> do
one <- MDenseVector @'Direct params 0 <$> V.unsafeThaw (V.singleton 1)
axpy (f i) one (MDenseVector @'Direct params (s ^. stride + 1) (s ^. buffer))
Nothing -> return ()
return $! s
opS :: PrimMonad m => SMatrix (PrimState m) -> Operator m ℂ
opS (SMatrix o temp λ) x out = do
let scale = (1 / int2Float (o ^. dim ^. _1)) :+ 0
gemv NoTranspose 1 o x 0 temp
case λ of
(Just λ') -> copy x out >> gemv ConjTranspose scale o temp λ' out
Nothing -> gemv ConjTranspose scale o temp 0 out
{-
solveS :: PrimMonad m => CGConfig ℝ -> SolveFun (MDenseMatrix 'Row (PrimState m) ℂ) m
solveS (CGConfig maxIter tol) = doSolve
where doSolve s b x = do
let operator = \input output -> gemv NoTranspose 1 s input 0 output
zero <- MDenseVector @'Direct (b ^. dim) 0 <$> V.unsafeThaw (V.singleton 0)
copy zero x
!answer <- CG.cg maxIter tol operator b x
trace (show answer) (return ())
-}
solveS :: CGConfig ℝ -> SolveFun (SMatrix RealWorld) IO
solveS (CGConfig maxIter tol) = doSolve
where
doSolve s b x = do
t1 <- getCPUTime
one <- MDenseVector @ 'Direct (b ^. dim) 0 <$> V.unsafeThaw (V.singleton 0)
copy one x
(iters, err) <- CG.cg maxIter tol (opS s) b x
t2 <- getCPUTime
return $! SolverStats iters err (fromIntegral (t2 - t1) * 1.0E-12)
solveS' :: SolveFun (MDenseMatrix 'Row RealWorld ℂ) IO
solveS' s b x = assert (x ^. stride == 1) $ do
t1 <- getCPUTime
copy b x
cgelsd s (MDenseMatrix (b ^. dim) 1 1 (x ^. buffer)) (-1.0)
t2 <- getCPUTime
return $! SolverStats (-1) (-1.0) (fromIntegral (t2 - t1) * 1.0E-12)
type Stepper v m a = v (PrimState m) a -> m ()
numberSteps :: (Int, Int, Int) -> Int
numberSteps (low, high, step) = (high - low - 1) `div` step + 1
newWorkspace :: PrimMonad m => Int -> Int -> m (DenseWorkspace (PrimState m) ℂ)
newWorkspace nParams nSteps =
DenseWorkspace
<$> newDenseVector nParams
<*> newDenseMatrix nSteps nParams
<*> newDenseVector nParams
sr
:: SRConfig ℂ
-> Hamiltonian
-> MRbm (PrimState IO)
-> (IterInfo -> IO ())
-> IO ()
sr config hamiltonian ψ process = newWorkspace nParams nSteps
>>= \w -> loop w 0
where
nParams = size ψ
nSteps = config ^. mc ^. runs * numberSteps (config ^. mc ^. steps)
doAxpy = axpyRbm
doMakeS = makeS (config ^. regulariser)
doSolveS = solveS (config ^. cg)
doSample = sampleRbm (config ^. mc) hamiltonian
loop !w@(DenseWorkspace f grad δ) !i
| i >= config ^. maxIter = return ()
| otherwise = do
mcStats <- doSample ψ f grad
fNorm <- nrm2 f
cgStats <- doMakeS i grad >>= \s -> doSolveS s f δ
δNorm <- nrm2 δ
unsafeFreezeRbm ψ
>>= \ψ' ->
let stats = IterInfo i ψ' mcStats cgStats fNorm δNorm
in process stats
doAxpy (-(config ^. rate) i) δ ψ
loop w (i + 1)
|
# Overloadable method, e.g to insert OffsetPrecalc's precalculated stride multiples
@inline tdot(ptr::AbstractStridedPointer, ::Tuple{}, ::Tuple{}) = (pointer(ptr), Zero())
@inline tdot(ptr::AbstractStridedPointer{T}, a, b) where {T} = tdot(pointer(ptr), a, b)
@inline function tdot(p::Ptr{T}, a::Tuple{A}, b::Tuple{B,Vararg}) where {T,A,B}
p, lazymul(first(a), first(b))
end
@inline function tdot(
p::Ptr{T},
a::Tuple{A},
b::Tuple{B,Vararg},
c::Tuple{C,Vararg},
) where {T,A,B,C}
p, lazymul(first(a), first(b), first(c))
end
@inline function tdot(
p::Ptr{T},
a::Tuple{A1,A2,Vararg},
b::Tuple{B1,B2,Vararg},
) where {T,A1,A2,B1,B2}
i = lazymul(first(a), first(b))
p, j = tdot(p, tail(a), tail(b))
add_indices(p, i, j)
end
@inline function tdot(
p::Ptr{T},
a::Tuple{A1,A2,Vararg},
b::Tuple{B1,B2,Vararg},
c::Tuple{C1,C2,Vararg},
) where {T,A1,A2,B1,B2,C1,C2}
i = lazymul(first(a), first(b), first(c))
p, j = tdot(p, tail(a), tail(b), tail(c))
add_indices(p, i, j)
end
@inline function tdot(
p::Ptr{T},
a::Tuple{A1,A2,Vararg},
b::Tuple{B1,B2,Vararg},
c::Tuple{C1},
) where {T,A1,A2,B1,B2,C1}
i = lazymul(first(a), first(b), first(c))
p, j = tdot(p, tail(a), tail(b))
add_indices(p, i, j)
end
|
'Tis not through envy of thy happy lot , 5
|
context("extra_field_calculator")
#testthat::test_that("only one file type inputted",
# expect_equal(extra_field_calculator(file_name = "data/Indicators_Targets_NEW.xlsx"),
# extra_field_calculator(file_name = "data/Indiacotrs_Targets.xlsx", dataframe = NULL)))
################################################# TESTING
# # ## Inputs
# fileName = "Indicators_Targets_NEW.com" # NOT excel file
# fileName = here::here("inst/data/Indicators_Targets_NEW.xlsx") # excel file
# for_year = 2018 ## Specify Year the analysis represents
# FY = TRUE ## Is this a fiscal year? (as opposed to calendar year)
# project_start_date <- "2016/03/01" # as string! %Y/%D/%M
#
# ##
# dataframe <- extra_field_calculator("data/Indicators_Targets_NEW.xlsx", for_year = 2018)
# df <- extra_field_calculator(fileName, for_year = 2018)
|
# <copyright file="download_selection.r" company="Oxford Economics">
# Copyright (c) 2017 Oxford Economics Ltd. All rights reserved.
# Licensed under the MIT License. See LICENSE file in the
# project root for full license information.
# </copyright>
# this R script shows one way a user might download a saved selection
# from the Oxford Economics Global Data Workstation and convert this
# raw output into a usable dataframe. it contains the following functions...
#
# download_selection_as_dataframe: the functions listed below are called
# to produce a usable dataframe
# download_raw_data: the http calls to our API
# get_quarterly_rows: an internal function for splitting quarterly
# data into multiple rows
# flatten_dataframe: converts the raw output of the API calls into
# a usable dataframe
# import modules
require('httr')
require('jsonlite')
# program constants
# note: API_KEY and selection id must be set below
#
API_KEY <- ''
SELECTION_ID <- ''
BASE <- 'https://services.oxfordeconomics.com/api'
PAGE_SIZE <- 2000
# essentially the main function: takes a saved selection id, downloads
# and processes the raw data from the Oxford Economics API and returns
#
download_selection_as_dataframe <- function(selection_id)
{
raw_data <- download_raw_data(selection_id)
df <- flatten_dataframe(raw_data)
return(df)
}
# this function makes the necessary HTTP calls for downloading
# and combining raw data
# returns: dataframe, where each row is a dataseries. note that
# annual and quarterly data are each contained in single
# columns at this point (e.g. instead of 2016, 2017,
# and 2018, the data column is AnnualData)
#
download_raw_data <- function(selection_id)
{
# select resource endpoint, in this case /download
endpoint <- '/download'
options1 <- '?includemetadata=true&page='
options2 <- '&pagesize='
# set up and run the request
raw_data <- data.frame()
page <- 0
repeat
{
print(paste('Downloading page', page+1))
http_request <- paste(BASE, endpoint, selection_id, options1, page, options2, PAGE_SIZE, sep='')
http_response <- GET(http_request, add_headers('api-key' = API_KEY))
if (status_code(http_response) > 400) {
print('Error - couldn\'t download selection')
print(paste('Status code: ', status_code(http_response)))
print(paste('Url: ', http_request))
break
}
new_data <- fromJSON(content(http_response, 'text', flatten=TRUE))
raw_data <- c(raw_data, new_data)
# check to see whether there are more pages
if ( length(new_data) < PAGE_SIZE ) {
break
}
page <- page + 1
}
print(paste('Downloaded', length(raw_data), 'rows of data'))
return(raw_data)
}
# this takes a dataframe row with quarterly data and returns a list
# whose elements are [1] the years and [2-] quarterly data values
#
get_quarterly_rows <- function(id, indicator, location, quarterly_data)
{
df_list <- list()
q1 <- list(id, indicator, location, 'Q1')
q2 <- list(id, indicator, location, 'Q2')
q3 <- list(id, indicator, location, 'Q3')
q4 <- list(id, indicator, location, 'Q4')
years <- list()
previous_year <- -1
for (yq_index in c(1:length(quarterly_data)))
{
col_label <- names(quarterly_data)[yq_index]
year <- substr(col_label, 1, 4)
period <- substr(col_label, 6, 6)
val <- quarterly_data[[col_label]]
# add each new year to the list of years
if (year != previous_year)
{
years[[length(years)+1]] <- year
}
# append the new data value to the appropriate list
if (period == '1')
{
q1[[length(q1)+1]] <- val
}
else if (period == '2')
{
q2[[length(q2)+1]] <- val
}
else if (period == '3')
{
q3[[length(q3)+1]] <- val
}
else if (period == '4')
{
q4[[length(q4)+1]] <- val
}
previous_year <- year
}
return(list(years, q1, q2, q3, q4))
}
# takes a dataframe with, among others, AnnualData and QuarterlyData columns
# and flattens them such that each year has a column and excess metadata is
# removed from the frame
#
flatten_dataframe <- function(raw_data)
{
# convert raw data into usable dataframes
row_list <- list()
years <- list()
for (i in c(1:length(raw_data$DatabankCode)))
{
# pull the necessary values from raw data
# create a unique id based on the variable mnemonic and sector
id <- paste(raw_data$VariableCode[i], raw_data$LocationCode[i], raw_data$MeasureCode[i], sep='_')
indicator <- raw_data$Metadata$IndicatorName[i]
location <- raw_data$Metadata$Location[i]
annual_data <- raw_data$AnnualData[i,]
quarterly_data <- raw_data$QuarterlyData[i,]
print(paste('Adding ', id, '...', sep=''))
# add quarterly rows
if (length(quarterly_data) > 0)
{
quarterly_rows <- get_quarterly_rows(id, indicator, location, quarterly_data)
for (i in c(2:length(quarterly_rows)))
{
row_list[[length(row_list)+1]] <- quarterly_rows[i]
}
if (length(years) == 0)
{
years <- quarterly_rows[[1]]
}
}
# add annual row
if (length(annual_data) > 0)
{
if (length(years) == 0)
{
years <- names(annual_data)
}
row_list[[length(row_list)+1]] <- append(list(id, indicator, location, 'A'), annual_data)
}
}
# cast list to dataframe
dim_names <- append(list('id', 'variable', 'location', 'period'), years)
df <- as.data.frame(t(matrix(unlist(row_list), nrow=length(unlist(row_list[1])))))
names(df) <- dim_names
return(df)
}
# generate a dataframe from the saved selection id listed in the constants
#
df <- download_selection_as_dataframe(SELECTION_ID)
print(df)
|
# Open Science Prize: Supplementary Material
This notebook is meant to provide a little more information about the Open Science Prize, but mostly, this notebook is a launching point from which the motivated learner can find open access sources with even more detailed information.
## 1 The Heisenberg Spin Model
In the open prize notebook, the Hamiltonian you are simulating is defined as the [Heisenberg XXX model](https://en.wikipedia.org/wiki/Quantum_Heisenberg_model#XXX_model) for 3 spins in a line:
$$
H_{\text{Heis3}} = \sigma_x^{(0)}\sigma_x^{(1)} + \sigma_x^{(1)}\sigma_x^{(2)} + \sigma_y^{(0)}\sigma_y^{(1)} + \sigma_y^{(1)}\sigma_y^{(2)} + \sigma_z^{(0)}\sigma_z^{(1)} + \sigma_z^{(1)}\sigma_z^{(2)}.
$$
### 1-1 Why call it XXX?
The XXX model is one of a family of spin models known as [Heisenberg spin models](https://en.wikipedia.org/wiki/Quantum_Heisenberg_model). In some sense, the most general form of Heisenberg model is often refered to as the XYZ model. The name 'XYZ' is used because the three pair-wise operators $\sigma_x\sigma_x$, $\sigma_y\sigma_y$, and $\sigma_z \sigma_z$ in the Hamitlonian have different coefficients $J_x$, $J_y$, and $J_z$ respectively. In the case where $J_x = J_y = J_z$, the model is labeled the 'XXX' model.
### 1-2 Numerically computing the matrix representation
To compute the matrix representation of $H_{\text{Heis3}}$, we are actually missing some pieces namely the identity operator $I$ and the [tensor product](https://en.wikipedia.org/wiki/Tensor_product#Tensor_product_of_linear_maps) $\otimes$ symbol. They are both often left out in when writing a Hamiltonian, but they are implied to be there. Writing out the full $H_{\text{Heis3}}$ including the identity operators and tensor product symbols
$$
H_{\text{Heis3}} = \sigma_x^{(0)}\otimes\sigma_x^{(1)}\otimes I^{(2)} + I^{(0)} \otimes\sigma_x^{(1)}\otimes\sigma_x^{(2)} + \sigma_y^{(0)}\otimes\sigma_y^{(1)}\otimes I^{(2)} + I^{(0)} \otimes \sigma_y^{(1)}\otimes\sigma_y^{(2)} + I^{(0)} \otimes\sigma_z^{(0)}\otimes\sigma_z^{(1)} + I^{(0)}\otimes\sigma_z^{(1)}\otimes\sigma_z^{(2)}.
$$
You can see why physicists don't write that all out all the time.
#### 1-2.1 Tensor product vs Kronecker product
A point of clarity about jargon. To numerically compute the [tensor product](https://en.wikipedia.org/wiki/Tensor_product#Tensor_product_of_linear_maps) of $\sigma_x\otimes\sigma_x$, as an example, we often have already chosen to be working with the matrix representation of the operators at hand ($\sigma_x = \begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}$ in this example). Because a computer works in the matrix representation, what a computer does is actually called a [Kronecker product](https://en.wikipedia.org/wiki/Kronecker_product#Examples). When doing numerically computations, Kronecker product is the name you would look up for the given software package you're using such as [Mathematica](https://reference.wolfram.com/language/ref/KroneckerProduct.html), [numpy](https://numpy.org/doc/stable/reference/generated/numpy.kron.html), or [Qiskit](https://qiskit.org/documentation/tutorials/operators/01_operator_flow.html#Pauli-operators,-sums,-compositions,-and-tensor-products).
Below is an example in Qiskit and numpy.
```python
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
# Import Qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
```
```python
# Compute a kronecker product in qiskit
# Qiskit already knows what I and X are (the identity and Pauli-X operators), so to compute the kronecker product it's very simple: ^
IX_qiskit = (I^X)
print('Qiskit Kronecker product:\n', IX_qiskit.to_matrix())
print("----------------")
# Compute a kronecker product in numpy
X_numpy = np.array([[0,1],[1,0]], dtype=complex)
I_numpy = np.eye(2, dtype=complex)
IX_numpy = np.kron(I_numpy, X_numpy)
print('Numpy Kronecker product:\n', IX_numpy)
```
Qiskit Kronecker product:
[[0.+0.j 1.+0.j 0.+0.j 0.+0.j]
[1.+0.j 0.+0.j 0.+0.j 0.+0.j]
[0.+0.j 0.+0.j 0.+0.j 1.+0.j]
[0.+0.j 0.+0.j 1.+0.j 0.+0.j]]
----------------
Numpy Kronecker product:
[[0.+0.j 1.+0.j 0.+0.j 0.+0.j]
[1.+0.j 0.+0.j 0.+0.j 0.+0.j]
[0.+0.j 0.+0.j 0.+0.j 1.+0.j]
[0.+0.j 0.+0.j 1.+0.j 0.+0.j]]
## 2 Using OpFlow
Qiskit offers [functionality for mathematically working with quantum states and operators](https://qiskit.org/documentation/apidoc/opflow.html) called ```opflow``` with tutorials found [here](https://qiskit.org/documentation/tutorials/operators/index.html). Opflow is especially convenient when dealing with large numbers of qubits as tensor products can become unweildy when using numpy both in size and syntax. For example, to define $H_{\text{Heis3}}$, we could use ```numpy```'s ```numpy.kron(...)``` function to compute the tensor product as shown below.
```python
# Returns matrix representation of the XXX Heisenberg model for 3 spin-1/2 particles in a line (uses np.kron())
def H_heis3_np_kron():
#iden is the identity matrix; sig_x, sig_y, and sig_z are Pauli matrices
iden = np.eye(2,2)
sig_x = np.array([[0,1],[1,0]])
sig_y = np.array([[0,-1j],[1j,0]])
sig_z = np.array([[0,1],[0,-1]])
# Interactions (np.kron(A,B) is the tensor product of A and B)
XXs = np.kron(iden, np.kron(sig_x, sig_x)) + np.kron(sig_x, np.kron(sig_x, iden))
YYs = np.kron(iden, np.kron(sig_y, sig_y)) + np.kron(sig_y, np.kron(sig_y, iden))
ZZs = np.kron(iden, np.kron(sig_z, sig_z)) + np.kron(sig_z, np.kron(sig_z, iden))
# Sum interactions
H = XXs + YYs + ZZs
# Return Hamiltonian
return H
# Returns matrix representation of the XXX Heisenberg model for 3 spin-1/2 particles in a line (uses opflow)
def H_heis3_opflow():
# Interactions (I is the identity matrix; X, Y, and Z are Pauli matricies; ^ is a tensor product)
XXs = (I^X^X) + (X^X^I)
YYs = (I^Y^Y) + (Y^Y^I)
ZZs = (I^Z^Z) + (Z^Z^I)
# Sum interactions
H = XXs + YYs + ZZs
# Return Hamiltonian
return H
```
Using opflow, however, the math is much easier to read and does not require recursive function calls, which can be confusing when generalizing a Hamiltonian to many qubits. Also, the operators do not need to be explicity computed in opflow saving memory. In opflow, the carrot symbol ```^``` denotes a tensor product. Important note, paranetheses are often needed to clarify the order of operations especially if doing other math operations such as ```+```. See below.
```python
# Example of incorrectly adding two PauliOp objects.
op = X^X + Z^Z
print('matrix dimensions of op:', op.to_matrix().shape)
```
matrix dimensions of op: (8, 8)
The shape of ```op``` should be (4,4) since $X$ and $Z$ are 2x2, but without parentheses, the order of operations is not correct. Shown below is the correct way of adding the two tensored Pauli operators in opflow.
```python
# Example of correctly adding two PauliOp objects.
op = (X^X) + (Z^Z)
print('matrix dimensions of op:', op.to_matrix().shape)
```
matrix dimensions of op: (4, 4)
## 3 Solution to the Time-Independent Schrödinger Equation
The [Schrödinger equation](https://en.wikipedia.org/wiki/Schrödinger_equation) is a foundational pillar of quantum mechanics. It relates how a quantum state $|\psi(t)\rangle$ changes in time given what the state was initially $|\psi(0)\rangle$. It's solution is relatively simple (more on how it's not simple in the next section) when the Hamiltonian $H$ that governs the state evolvution does not depend on time. Treating Schrödinger equation as the differential equation it is, we can use separation of variables to solve it
$$
\begin{align}
i \hbar \frac{d |\psi(t)\rangle}{dt} &= H|\psi(t)\rangle \\
|\psi(t)\rangle &= e^{-iHt / \hbar} |\psi(0)\rangle.
\end{align}
$$
## 4 Exponential of a Matrix
The solution to the [Schrödinger equation](https://en.wikipedia.org/wiki/Schrödinger_equation) for a Hamiltonian $H$ that does not depend on time (and $\hbar = 1$) is
$$
|\psi(t)\rangle = e^{-iHt}|\psi(0)\rangle.
$$
But, what does it mean to take $e$ to the power of an operator $H$? Let's briefly address this topic and give references where you can learn more.
Working with the the matrix representation of $H$, the time evolution $U_H(t) = e^{-iHt}$ can be numerically and algebraically evaluated using a [taylor series expansion](https://en.wikipedia.org/wiki/Taylor_series#Exponential_function) ($e^x = 1 + x + x^2/2! + x^3/3! + ... $) . This is often where computers step in. Although, single Pauli operators (e.g. $H=\sigma_x$) have a nice algebraic result. On a computer, many different software packages have methods for computing $e^A$ where $A$ is a matrix (see scipy's [expm](https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.expm.html) or opflow's [.exp_i()](https://qiskit.org/documentation/tutorials/operators/01_operator_flow.html#Evolutions,-exp_i(),-and-the-EvolvedOp)).
We do need to be careful when the matrix that is being exponentiated is a sum of operators that do not commute ($[A,B] = AB - BA \neq 0$). For example, if $H = \sigma_x + \sigma_z$, we need to take care in working with $e^{it(\sigma_x + \sigma_z)}$ since the Pauli operatos $\sigma_x$ and $\sigma_z$ do not commute $[\sigma_x, \sigma_z] = \sigma_x \sigma_z - \sigma_z \sigma_x = -2i\sigma_y \neq0$. If we want to apply $e^{it(\sigma_x + \sigma_z)}$ on a quantum computer, however, we will want to decompose the sum in the exponential into a product of exponentials. Each product can then be implemented on the quantum computer as a single or two-qubit gate. Continuing the example, $\sigma_x$ and $\sigma_z$ do not commute ($[\sigma_x, \sigma_z] \neq 0$), so we cannot simply decompose the exponential into a product of exponentials $e^{-it(\sigma_x + \sigma_z)} \neq e^{-it\sigma_x}e^{-it\sigma_z}$. This is where approximation methods come in such as Trotterization (more on that in the next section).
## 5 Trotterization
The Open Science Prize notebook ends the decomposition of the unitary time evolution $U_{\text{Heis3}}(t)$ calculation with
$$
U_{\text{Heis3}}(t) \approx \left[XX^{(0,1)}(t/n) YY^{(0,1)}(t/n) ZZ^{(0,1)}(t/n) XX^{(1,2)}(t/n) YY^{(1,2)}(t/n) ZZ^{(1,2)}(t/n) \right]^{n}
$$
where $t$ is time and $n$ is the number of Trotter steps. (Remember, this is not the only possible Trotterization.)
The physical implementation of the two-qubit gates $XX(t)$, $YY(t)$, and $ZZ(t)$ are outlined in the Open Science Prize notebook, though without explanation. Here we provide a brief explanation with references where you can learn more.
Qiskit has a library of circuits that include such gates called the [circuit library](https://qiskit.org/documentation/apidoc/circuit_library.html), but not every gate in the library is native to a physical device. Nonnative gates (such as $XX$, $YY$, $ZZ$, or $ZX$) need to be decomposed into gates that are [native to the physical device](https://qiskit.org/documentation/tutorials/circuits_advanced/08_gathering_system_information.html#Configuration). You may even come across three-qubit gates like XXY or XYZ in some models. These interactions can be decomposition into native gates, or you may find it effective go further and [engineer a typically nonnative interaction](https://qiskit.org/textbook/ch-quantum-hardware/hamiltonian-tomography.html) using Pulse.
Assuming you want to only use native gates and not pulses, this review article is a useful starting point: F. Tacchino, et. al., *Quantum Computers as Universal Quantum Simulators: State-of-the-Art and Perspectives*, [Adv. Quantum Technol. *3* 3 (2020)](https://doi.org/10.1002/qute.201900052) \[[free arxiv version](https://arxiv.org/abs/1907.03505)\]
In this notebook, let's start with the [ZZ gate](https://qiskit.org/documentation/stubs/qiskit.circuit.library.RZZGate.html)
$$
\begin{align}
ZZ(2t) &= e^{-it\sigma_z \otimes \sigma_z} \\
ZZ(2t) &= \begin{bmatrix} e^{-it} & 0 & 0 & 0 \\ 0 & e^{it} & 0 & 0 \\ 0 & 0 & e^{it} & 0 \\ 0 & 0 & 0 & e^{-it} \\ \end{bmatrix}
\end{align}.
$$
This can be implemented in terms of two-qubit [CNOT gates](https://qiskit.org/documentation/stubs/qiskit.circuit.library.CXGate.html#qiskit.circuit.library.CXGate) sandwiching a single qubit rotation [$R_z(2t)$ rotation](https://qiskit.org/documentation/stubs/qiskit.circuit.library.RZGate.html) as shown below. (Note that $R_z$ is evaluated at the angle $2t$ instead of the typical $t$ to simplify writing the exponential terms.)
```python
from qiskit.circuit import Parameter
from qiskit import QuantumCircuit, QuantumRegister, execute
t = Parameter('t')
```
```python
# ZZ in two and single qubit gates
qc = QuantumCircuit(2)
qc.cnot(0,1)
qc.rz(2 * t, 1)
qc.cnot(0,1)
qc.draw(output='mpl')
```
For fun, let's check this mathematically by evaluating the circuit library ZZ gate and decomposed circuit at various time values.
```python
from qiskit.circuit.library import RXXGate, RYYGate, RZZGate, CXGate
from qiskit.quantum_info.operators import Operator
import qiskit.quantum_info as qi
```
```python
# time
time = np.pi/2 # try different time values as a check that the decomposition of ZZ into native gates is accurate
# Qiskit circuit library ZZ gate
qc = QuantumCircuit(2)
qc.append(RZZGate(time), [0,1])
qc_ZZ_matrix = qi.Operator(qc)
# Decomposed ZZ gate
CNOT = Operator(np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]))
Rz = Operator(np.array([[np.exp(-1j*time/2),0], [0,np.exp(1j*time/2)]]))
I_Rz = (Operator(I)^Rz)
#np_ZZ_matrix = CNOT@I_Rz@CNOT
np_ZZ_matrix = np.matmul(np.matmul(CNOT, I_Rz), CNOT)
# Confirm matrices are the same at time t
np.array_equal(qc_ZZ_matrix, np_ZZ_matrix)
```
True
The $ZZ(t)$ gate can be rotated to the $XX(t)$ gate by adding single qubit rotations. Single qubit rotations such as $R_y(\pi/2) \sigma_z R_y(-\pi/2) = \sigma_x$ can transform $\sigma_z$ to $\sigma_x$. Consider computing the calculation yourself. Remember that Pauli matrices can be decomposed from an exponential form like so $R_z(2\theta)= \exp\left(-i\theta\sigma_z\right) = \cos(\theta)I - i \sin(\theta)\sigma_z$. Below is an abbreviated calculation to guide your own. Note that most tensor products with the identity have been omitted (e.g. $\sigma_z^{(0)} = \sigma_z^{(0)} \otimes I^{(1)}$), and for extra clarity, each operator has the qubit it acts on indexed in the superscript, so $\sigma_z^{(0)}$ would be the $\sigma_z$ operator acting on qubit $0$.
$$
\begin{align}
\left(R_y^{(0)}(\pi/2) \otimes R_Y^{(1)}(\pi/2)\right) ZZ(t)^{(0,1)}\left( R_y^{(0)}(-\pi/2) \otimes R_Y^{(1)}(-\pi/2)\right) &= \\
\exp\left[\frac{-i\pi}{4}(\sigma_y^{(0)} + \sigma_y^{(1)})\right] \exp\left[\frac{-it}{2} \sigma_z^{(0)} \otimes \sigma_z^{(1)}\right] \exp\left[\frac{i\pi}{4}(\sigma_y^{(0)} + \sigma_y^{(1)})\right] &= \\
\exp\left[\frac{-i\pi}{4}(\sigma_y^{(0)} + \sigma_y^{(1)})\right] \left[\cos(t/2)(I^{(0)} \otimes I^{(1)}) -i\sin(t/2)(\sigma_z^{(0)} \otimes \sigma_z^{(1)}) \right] \exp\left[\frac{i\pi}{4}(\sigma_y^{(0)} + \sigma_y^{(1)})\right] &= \\
\cos(t/2) \exp\left[\frac{-i\pi}{4}(\sigma_y^{(0)} + \sigma_y^{(1)})\right] (I^{(0)} \otimes I^{(1)}) \exp\left[\frac{i\pi}{4}(\sigma_y^{(0)} + \sigma_y^{(1)})\right] - i \exp\left[\frac{-i\pi}{4}(\sigma_y^{(0)} + \sigma_y^{(1)})\right] \sin(t/2)(\sigma_z \otimes \sigma_z) \exp\left[\frac{i\pi}{4}(\sigma_y^{(0)} + \sigma_y^{(1)})\right] &= \\
\cos(t/2) (I^{(0)} \otimes I^{(1)}) - \frac{i \sin(t/2)}{4} \left[\left(I^{(0)} - i \sigma_y^{(0)}\right) \sigma_z^{(0)} \left(I^{(0)} + i \sigma_y^{(0)}\right)\right] \otimes \left[\left(I^{(1)} - i \sigma_y^{(1)}\right) \sigma_z^{(1)} \left(I^{(1)} + i \sigma_y^{(1)}\right)\right] &= \\
\cos(t/2) (I^{(0)} \otimes I^{(1)}) - i \sin(t/2) (\sigma_x^{(0)} \otimes \sigma_x^{(1)}) &= \\
\exp\left[\frac{-it}{2} \sigma_x^{(0)} \otimes \sigma_x^{(1)}\right] &= \\
&= XX(t) \\
\end{align}
$$
```python
# XX(t)
qc = QuantumCircuit(2)
qc.ry(np.pi/2,[0,1])
qc.cnot(0,1)
qc.rz(2 * t, 1)
qc.cnot(0,1)
qc.ry(-np.pi/2,[0,1])
qc.draw(output='mpl')
```
Let's check for fun again.
```python
# time
time = np.pi/6 # try different time values as a check that the decomposition of XX into native gates is accurate
# Qiskit circuit library XX gate
qc = QuantumCircuit(2)
qc.append(RXXGate(time), [0,1])
qc_XX_matrix = qi.Operator(qc).data
# Decomposed XX gate
Rz = Operator(np.array([[np.exp(-1j*time/2),0], [0,np.exp(1j*time/2)]]))
Ry = Operator(np.array([[np.cos(np.pi/4), -np.sin(np.pi/4)],[np.sin(np.pi/4), np.cos(np.pi/4)]]))
Ry_minus = Operator(np.array([[np.cos(-np.pi/4), -np.sin(-np.pi/4)],[np.sin(-np.pi/4), np.cos(-np.pi/4)]]))
I_Rz = (Operator(I)^Rz)
np_XX_matrix = (Ry^Ry)@CNOT@I_Rz@CNOT@(Ry_minus^Ry_minus)
# Confirm matrices are the same at time t
np.array_equal(np.round(qc_XX_matrix, 6), np.round(np_XX_matrix, 6))
```
True
The $ZZ(t)$ gate can be rotated to the $YY(t)$ gate by adding single qubit rotations $R_x(\pi/2) \sigma_z R_x(-\pi/2) = -\sigma_y$ around the $ZZ$ gate just as was done with the $XX$ gate.
```python
# YY(t)
qc = QuantumCircuit(2)
qc.rx(np.pi/2,[0,1])
qc.cnot(0,1)
qc.rz(2 * t, 1)
qc.cnot(0,1)
qc.rx(-np.pi/2,[0,1])
qc.draw(output='mpl')
```
```python
# time
time = np.pi/6 # try different time values as a check that the decomposition of YY into native gates is accurate
# Qiskit circuit library YY gate
qc = QuantumCircuit(2)
qc.append(RYYGate(time), [0,1])
qc_YY_matrix = qi.Operator(qc).data
# Decomposed YY gate
Rz = Operator(np.array([[np.exp(-1j*time/2),0], [0,np.exp(1j*time/2)]]))
Rx = Operator(np.array([[np.cos(np.pi/4), -1j*np.sin(np.pi/4)],[-1j*np.sin(np.pi/4), np.cos(np.pi/4)]]))
Rx_minus = Operator(np.array([[np.cos(-np.pi/4), -1j*np.sin(-np.pi/4)],[-1j*np.sin(-np.pi/4), np.cos(-np.pi/4)]]))
I_Rz = (Operator(I)^Rz)
np_YY_matrix = (Rx^Rx)@CNOT@I_Rz@CNOT@(Rx_minus^Rx_minus)
# Confirm matrices are the same at time t
np.array_equal(np.round(qc_YY_matrix, 6), np.round(np_YY_matrix, 6))
```
True
## 6 State Tomography
[State tomography](https://qiskit.org/documentation/tutorials/noise/8_tomography.html) is a method for determining the quantum state of a qubit, or qubits, even if the state is in a superposition or entangled. Repeatedly measuring a prepared quantum state may not be enough to determine the full state. For example, what if you want to know if the result of a quantum calculation is the state $|0\rangle -i|1\rangle$?
Repeated measurements in the $Z$-basis would return $|0\rangle$ 50% of the time and $|1\rangle$ 50% of the time. However, there are other states that give the same measurement result, such as $|0\rangle + |1\rangle$, $|0\rangle - |1\rangle$, and $|0\rangle + i|1\rangle$. How could you determine the state you have has the $-i$ phase you're looking for? This requires measurements in [different bases](https://qiskit.org/textbook/ch-states/single-qubit-gates.html#measuring). In state tomography, a quantum circuit is repeated with measurements done in different bases to exhaustively determine the full quantum state (including any phase information). The Open Science Prize this year is using this technique to determine the full quantum state after the quantum simulation. That state is then compared to the exact expected result to compute a fidelity. Although this fidelity only gives information on how well the quantum simulation produces one particular state, it's a more lightweight approach than a full [process tomography](https://qiskit.org/documentation/tutorials/noise/8_tomography.html) caluclation. In short, a high fidelity measured by state tomography doesn't gaurentee a high fidelity quantum simulation, but a low fidelity state tomography does imply a low fidelity quantum simulation.
# 7 Two-Qubit Gate with Pulse
[Qiskit Pulse](https://qiskit.org/documentation/apidoc/pulse.html) offers low-level control of a device's qubits. Pulse allows users to program the physical interactions happening on the superconducting chip. This can be a powerful tool for streamlining circuits \[1-4\], crafting new types of gates \[1-4\], getting [higher fidelity readout](https://www.youtube.com/watch?v=_1XTChcvbOs), and more. Of course, the increased level of control requires more understanding of [the physics of the qubit and how gates are physically generated on chip](https://qiskit.org/textbook/ch-quantum-hardware/transmon-physics.html). For someone new to Pulse, this may seem intimidating. However, there are great tutorials, and the [qiskit textbook](https://qiskit.org/textbook/ch-quantum-hardware/index-pulses.html) can slowly introduce you to these ideas with real and practically useful examples. For those more experienced with Pulse, it may be time to review papers such as this [general overview](https://arxiv.org/pdf/2004.06755.pdf). There will be other papers you find useful for this competition. Below, there is a small--and far from exhaustive--list to get you started \[1-4\].
To aid your efforts, we've provided a simple example of implementing a pulse-efficient [$R_{ZX}$ gate](https://qiskit.org/documentation/stubs/qiskit.circuit.library.RZXGate.html#qiskit.circuit.library.RZXGate) as outlined in paper [3](https://arxiv.org/pdf/2105.01063.pdf). Note that although the example below is interesting, it is not the only way to make a "pulse-efficient" two-qubit rotation gate.
\[1\] T. Alexander, et al., *Qiskit Pulse: Programming Quantum Computers Through the Cloud with Pulses*, [Quantum Sci. and Technol. **5** 044006 (2020)](https://arxiv.org/pdf/2004.06755.pdf)
\[2\] J. Stenger, et al., *Simulating the dynamics of braiding of Majorana zero modes using an IBM quantum computer*, [Phys. Rev. Research **3**, 033171 (2021)](https://arxiv.org/pdf/2012.11660.pdf)
\[3\] N. Earnest, et al., *Pulse-efficient circuit transpilation for quantum applications on cross-resonance-based hardware*, [arXiv:2105.01063 \[quant-ph\] (2021)](https://arxiv.org/pdf/2105.01063.pdf)
\[4\] S. Oomura, et al., *Design and application of high-speed and high-precision CV gate on IBM Q OpenPulse system*, [arXiv:2102.06117 \[quant-ph\] (2021)](https://arxiv.org/pdf/2102.06117.pdf)
[qiskit experiments repo](https://github.com/Qiskit/qiskit-experiments)
```python
# Import qiskit packages
from qiskit import IBMQ
from qiskit import schedule, transpile
from qiskit.tools.monitor import job_monitor
# load IBMQ Account data
# IBMQ.save_account(TOKEN)
provider = IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
backend = provider.get_backend('ibmq_jakarta')
```
## 7.1 The [$R_{ZX}$ Gate](https://qiskit.org/documentation/stubs/qiskit.circuit.library.RZXGate.html#qiskit.circuit.library.RZXGate)
It's now time for an example of implementing a rotational two-qubit gate and how you might go about using Pulse to implement it as efficiently as possible. Remembering the dicussion in sections 4 and 5, we can write out the form of the $R_{ZX}(\theta)$ gate:
$$
R_{ZX}(2\theta) = \exp\left(-i \theta \sigma_z^{(0)} \otimes \sigma_x^{(1)}\right) = \cos(\theta)(I^{(0)}\otimes I^{(1)}) -i \sin(\theta)(\sigma_z^{(0)} \otimes \sigma_x^{(1)})
$$
Let's follow paper [\[3\]](https://arxiv.org/pdf/2105.01063.pdf)'s same line of reasoning. First, implement an $R_{ZX}$ using native circuit gates. Second, compare that circuit's performance to an $R_{ZX}$ gate contrusted from native pulses. Since the competition focuses on Jakarta's qubits 1, 3, and 5, let's just consider an $R_{ZX}$ gate between 1 and 3.
```python
# RZX gate circuit (see section 5 for details on why this is the circuit for RZX)
theta = 3*np.pi/11 # pick arbitrary rotation angle theta
qrs = QuantumRegister(4)
qc = QuantumCircuit(qrs)
qc.ry(-np.pi/2, 3)
qc.cx(1, 3)
qc.rz(theta, 3)
qc.cx(1, 3)
qc.ry(np.pi/2, 3)
print(qc.draw())
qct = transpile(qc, backend) # display the typical circuit diagram
schedule(qct, backend).draw() # display what the pulse schedule looks like for the circuit
```
Now that we have an $R_{ZX}$ circuit implementation (shown above in circuit and pulse schedule forms), let's make the "pulse-efficient" version of $R_{ZX}$. (Spoiler: it's only two pulses!)
```python
# The PassManager helps decide how a circuit should be optimized
# (https://qiskit.org/documentation/tutorials/circuits_advanced/04_transpiler_passes_and_passmanager.html)
from qiskit.transpiler import PassManager
# This function will pull pulse-level calibration values to build RZX gates and tell the PassManager to leave RZX gates alone
from qiskit.transpiler.passes import RZXCalibrationBuilderNoEcho
```
```python
# Equivalent circuit in terms of cross-resonance gates (https://qiskit.org/textbook/ch-quantum-hardware/cQED-JC-SW.html#6.-The-Cross-Resonance-Entangling-Gate)
qrs_pe = QuantumRegister(4)
qc_pe = QuantumCircuit(qrs_pe)
qc_pe.rzx(theta/2, 1, 3)
qc_pe.x(1)
qc_pe.rzx(-theta/2, 1, 3)
qc_pe.x(1)
# Add the pulse-level calibrations
pm = PassManager([RZXCalibrationBuilderNoEcho(backend)])
qc_pulse_efficient = pm.run(qc_pe)
schedule(qc_pulse_efficient, backend).draw() # show pulse schedule
```
```python
# Compare the schedule durations
print('Duration of standard CNOT-based circuit:')
print(schedule(qct, backend).duration)
print('Duration of pulse-efficient circuit:')
print(schedule(qc_pulse_efficient, backend).duration)
```
Duration of standard CNOT-based circuit:
3776
Duration of pulse-efficient circuit:
1184
You've just optimized an $R_{ZX}$ gate using pulse-level control! The shorter circuit time for the pulse-efficient circuit is great news! The shorter the circuit, the less likely the qubit will decohere. This time savings, and fewer pulses to the qubits, will reduce errors. Let's quantify this reduction by measuring the [process fidelity](https://qiskit.org/documentation/tutorials/noise/8_tomography.html) of the two circuits. If we wanted to be thorough, we should do a [randomized benchmarking](https://qiskit.org/textbook/ch-quantum-hardware/randomized-benchmarking.html) as shown in Fig. 1 of paper [\[3\]](https://arxiv.org/pdf/2105.01063.pdf).
```python
# Process tomography functions
from qiskit.ignis.verification.tomography import process_tomography_circuits, ProcessTomographyFitter
# Get exact gate for comparison in process tomography
from qiskit.circuit.library import RZXGate
# Get the ideal unitary operator to compare to circuit output
target_unitary = qi.Operator(RZXGate(theta).to_matrix())
# Generate process tomography circuits and run
qpt_qcs = process_tomography_circuits(qc, [qrs[1], qrs[3]])
job = execute(qpt_qcs, backend, shots=8192)
```
```python
job_monitor(job)
```
Job Status: job has successfully run
```python
# Extract tomography data
qpt_tomo = ProcessTomographyFitter(job.result(), qpt_qcs)
# Tomographic reconstruction
choi_fit_lstsq = qpt_tomo.fit(method='lstsq')
print('Average gate fidelity: F = {:.5f}'.format(qi.average_gate_fidelity(choi_fit_lstsq, target=target_unitary)))
```
Average gate fidelity: F = 0.91322
Now for the pulse-efficient gate
```python
# Generate process tomography circuits and run
qpt_qcs = process_tomography_circuits(qc_pulse_efficient, [qrs_pe[1], qrs_pe[3]])
job = execute(qpt_qcs, backend, shots=8192)
```
```python
job_monitor(job)
```
Job Status: job has successfully run
```python
# Extract tomography data so that counts are indexed by measurement configuration
qpt_tomo = ProcessTomographyFitter(job.result(), qpt_qcs)
# Tomographic reconstruction
choi_fit_lstsq = qpt_tomo.fit(method='lstsq')
print('Average gate fidelity: F = {:.5f}'.format(qi.average_gate_fidelity(choi_fit_lstsq, target=target_unitary)))
```
Average gate fidelity: F = 0.92471
This is just one example of how Pulse could be used. Read [tutorials](https://qiskit.org/documentation/tutorials/circuits_advanced/05_pulse_gates.html), papers, and the [Qiskit youtube channel](https://www.youtube.com/c/qiskit) for more ideas.
```python
import qiskit.tools.jupyter
%qiskit_version_table
```
<h3>Version Information</h3><table><tr><th>Qiskit Software</th><th>Version</th></tr><tr><td><code>qiskit-terra</code></td><td>0.18.3</td></tr><tr><td><code>qiskit-aer</code></td><td>0.9.1</td></tr><tr><td><code>qiskit-ignis</code></td><td>0.6.0</td></tr><tr><td><code>qiskit-ibmq-provider</code></td><td>0.18.0</td></tr><tr><td><code>qiskit-aqua</code></td><td>0.9.5</td></tr><tr><td><code>qiskit</code></td><td>0.32.0</td></tr><tr><td><code>qiskit-nature</code></td><td>0.1.3</td></tr><tr><th>System information</th></tr><tr><td>Python</td><td>3.8.8 (default, Apr 13 2021, 12:59:45)
[Clang 10.0.0 ]</td></tr><tr><td>OS</td><td>Darwin</td></tr><tr><td>CPUs</td><td>8</td></tr><tr><td>Memory (Gb)</td><td>64.0</td></tr><tr><td colspan='2'>Mon Nov 29 09:01:00 2021 EST</td></tr></table>
|
Beautiful grained myrtlewood would be nice on any dresser. It has a divided tray on top that just lifts up to store more of your jewelry underneath. 8 1/4" long x 5 1/4" deep x 5 1/4" tall. |
(* This file is part of the Linear Logic formalization in Coq: https://github.com/meta-logic/coq-ll *)
(** ** Cut Elimination
Here we prove cut-elimination for linear logic and, as a corollary, we show the consistency of the logic
*)
(*Add LoadPath "../". *)
Require Import Coq.Relations.Relations.
Require Import Coq.Arith.EqNat.
Require Import Coq.Classes.Morphisms.
Require Import Coq.Setoids.Setoid.
Require Export Coq.Sorting.PermutSetoid.
Require Export Coq.Sorting.PermutEq.
Require Import Coq.Program.Equality.
(* Require Export StructuralRules. *)
Require Export LL.SequentCalculi.
Require Export LL.Eqset.
Require Import LL.CutCases.
Module CElimination (DT : Eqset_dec_pol).
Module Export Sys := CCases DT.
Ltac simpl_duals H :=
try rewrite one_bot in H;
try rewrite bot_one in H;
try rewrite top_zero in H;
try rewrite zero_top in H;
try rewrite atom_perp in H;
try rewrite perp_atom in H;
try rewrite tensor_par in H;
try rewrite par_tensor in H;
try rewrite with_plus in H;
try rewrite plus_with in H;
try rewrite bang_quest in H;
try rewrite quest_bang in H.
Theorem cut_aux B L M1 M2 F :
L =mul= M1 ++ M2 ->
0 |~> 0 ; B ; F :: M1 ->
0 |~> 0 ; B ; F° :: M2 ->
exists m, m |~> 0 ; B ; L.
Proof.
intros P Hn1 Hn2.
inversion Hn1; subst.
*
apply axPair in H.
destruct H;
firstorder; subst.
+
simpl_duals Hn2.
inversion Hn2; subst.
- (* init rule *)
apply axPair in H.
destruct H;
firstorder; [lexp_contr H |].
apply PerpEq in H; subst.
eexists; eapply sig3_init.
eauto.
- (* contradiction *)
eapply resolvers2 in H; firstorder; lexp_contr H.
- (* top rule *)
simpl_cases2.
top_commutes.
+ (* symmetric case *)
simpl_duals Hn2.
inversion Hn2; subst.
- (* init rule *)
apply axPair in H.
destruct H;
firstorder; [|lexp_contr H].
apply AtomEq in H; subst.
eexists; eapply sig3_init.
eauto.
- (* contradiction *)
eapply resolvers2 in H; firstorder; lexp_contr H.
- (* top rule *)
simpl_cases2.
top_commutes.
*
eapply resolvers2 in H; firstorder.
subst.
simpl_duals Hn2.
inversion Hn2; subst.
+ (* contradiction *)
apply resolvers in H; firstorder; lexp_contr H.
+ (* contradiction *)
eapply resolvers2 in H; firstorder; lexp_contr H.
+ (* top rule *)
simpl_cases2.
top_commutes.
*
destruct (FEqDec F Top).
+
subst. simpl_cases4.
simpl_duals Hn2.
inversion Hn2; subst.
- (* contradiction *)
apply resolvers in H0; firstorder; lexp_contr H0.
- (* contradiction *)
eapply resolvers2 in H0; firstorder; lexp_contr H0.
- (* top rule *)
simpl_cases2.
top_commutes.
+ (* top rule *)
simpl_cases2.
top_commutes.
Qed.
Arguments cut_aux[B L M1 M2 F].
Theorem ccut_aux B L M1 M2 F w :
S w = Lexp_weight (! F) -> L =mul= M1 ++ M2 ->
0 |~> 0 ; B ; ! F :: M1 -> 0 |~> 0 ; F° :: B ; M2 ->
exists m, m |~> 0 ; B ; L.
Proof.
intros Hw P Hn1 Hn2.
inversion Hn1; subst;
[ apply resolvers in H; firstorder; lexp_contr H |
apply resolvers2 in H; firstorder; lexp_contr H |
simpl_cases2; top_commutes].
Qed.
Arguments ccut_aux [B L M1 M2 F w].
Lemma cut_elimination_base: forall n B L,
n |~> 1 ; B ; L -> exists m, m |~> 0 ; B ; L.
Proof.
intros.
revert dependent B.
revert dependent L.
induction n using strongind; intros.
- inversion H.
- inversion H0; subst.
+ assert (exists m, m |~> 0; B; M) as Hyp by solve [eapply H; auto].
destruct Hyp as [t Ht]; eexists;
refine (sig3_bot _ Ht); eauto.
+ assert (exists m, m |~> 0; B; F :: G :: M) as Hyp by solve [eapply H; auto].
destruct Hyp as [t Ht]; eexists;
refine (sig3_par _ Ht); resolve_rewrite.
+ apply Nat.eq_add_1 in H2.
destruct H2; destruct H1; subst.
assert (exists m, m |~> 0; B; F :: M) as Hyp.
refine (H _ _ _ _ H4); resolve_max.
destruct Hyp as [t Ht]; eexists;
refine (sig3_tensor _ Ht H5); resolve_rewrite; auto.
assert (exists m, m |~> 0; B; G :: N) as Hyp.
refine (H _ _ _ _ H5); resolve_max.
destruct Hyp as [t Ht]; eexists;
refine (sig3_tensor _ H4 Ht); resolve_rewrite.
+ assert (exists m, m |~> 0; B; F :: M) as Hyp by solve [eapply H; auto].
destruct Hyp as [t Ht]; eexists;
refine (sig3_plus1 _ Ht); resolve_rewrite.
+ assert (exists m, m |~> 0; B; G :: M) as Hyp by solve [eapply H; auto].
destruct Hyp as [t Ht]; eexists;
refine (sig3_plus2 _ Ht); resolve_rewrite.
+ apply Nat.eq_add_1 in H2.
destruct H2; destruct H1; subst.
assert (exists m, m |~> 0; B; F :: M) as Hyp.
refine (H _ _ _ _ H4); resolve_max.
destruct Hyp as [t Ht]; eexists;
refine (sig3_with _ Ht H5); resolve_rewrite. auto.
assert (exists m, m |~> 0; B; G :: M) as Hyp.
refine (H _ _ _ _ H5); resolve_max.
destruct Hyp as [t Ht]; eexists;
refine (sig3_with _ H4 Ht); resolve_rewrite.
+ rewrite H3 in H4.
assert (exists m, m |~> 0; B; F:: L) as Hyp by solve [eapply H; auto].
destruct Hyp as [t Ht]; eexists;
refine (sig3_copy _ _ Ht); auto.
+ assert (exists m, m |~> 0; F:: B; M) as Hyp by solve [eapply H; auto].
destruct Hyp as [t Ht]; eexists;
refine (sig3_quest _ Ht); auto.
+ assert (exists m, m |~> 0; B; [F]) as Hyp by solve [eapply H; auto].
destruct Hyp as [t Ht]; eexists;
refine (sig3_bang _ Ht); auto.
+ assert (exists m, m |~> 0; B; Subst FX t :: M) as Hyp by solve [eapply H; auto].
destruct Hyp as [p Hp]; eexists; eapply sig3_ex; eauto.
+
assert (forall y : Term, exists m, m |~> 0; B; Subst FX y :: M) as Hyp.
intro.
assert (n |~> 1; B; Subst FX y :: M) by auto.
eapply H; auto.
apply fx_swap_sig3h in Hyp.
destruct Hyp as [p Hp];
eexists; eapply sig3_fx; eauto.
+ (* caso CUT *)
clear H0. clear H.
revert dependent B.
revert dependent L.
revert dependent n.
dependent induction w using strongind;
dependent induction h using strongind; intros.
* (* w=h=0 *)
inversion H3; subst.
**
cut_free.
simpl in H0, H1.
cut_free.
eapply cut_aux; eauto.
**
cut_free.
simpl in H1, H0.
inversion H0.
*
inversion H3; subst.
**
cut_free.
simpl in H1.
rename H1 into Hw, H2 into Hh.
rename H4 into P, H5 into Hn1, H9 into Hn2.
rename m into n1, n0 into n2.
rename M into M1, N into M2.
caseLexp F; subst; simpl; try inversion Hw;
simpl_duals Hn1; simpl_duals Hn2.
refine (aux_CUT_ap _ Hh _ P Hn1 Hn2); eauto.
rewrite union_comm in P.
rewrite Nat.add_comm in Hh.
refine (aux_CUT_ap _ Hh _ _ Hn2 Hn1); eauto.
rewrite union_comm in P.
rewrite Nat.add_comm in Hh.
refine (aux_CUT_bo _ Hh _ _ Hn2 Hn1); eauto.
refine (aux_CUT_bo _ Hh _ _ Hn1 Hn2); eauto.
rewrite union_comm in P.
rewrite Nat.add_comm in Hh.
refine (aux_CUT_tz _ Hh _ _ Hn2 Hn1); eauto.
refine (aux_CUT_tz _ Hh _ _ Hn1 Hn2); eauto.
**
cut_free.
simpl in H1.
inversion H1.
* (* h=0 e S w *)
inversion H3; subst.
**
cut_free.
simpl in H2.
cut_free.
eapply cut_aux; eauto.
**
cut_free.
simpl in H2.
cut_free.
eapply ccut_aux; eauto.
* inversion H3; subst; try cut_free.
-- (** cut *)
rename H2 into Hw, H4 into Hh.
rename H5 into P, H6 into Hn1, H10 into Hn2.
rename m into n1, n0 into n2.
rename M into M1, N into M2.
clear H3.
caseLexp F; subst; simpl; try inversion Hw;
simpl_duals Hn1; simpl_duals Hn2.
refine (aux_CUT_tp _ _ _ _ P Hn1 Hn2); eauto.
rewrite union_comm in P.
rewrite Nat.add_comm in Hh.
refine (aux_CUT_tp _ _ _ _ P Hn2 _); eauto.
rewrite <- !lweight_dual; auto.
rewrite <- !Ng_involutive; auto.
rewrite union_comm in P.
rewrite Nat.add_comm in Hh.
refine (aux_CUT_pw _ _ _ _ P Hn2 _); eauto.
rewrite <- !lweight_dual; auto.
rewrite <- !Ng_involutive; auto.
refine (aux_CUT_pw _ _ _ _ P Hn1 Hn2); eauto.
refine (aux_CUT_bq _ _ _ _ P Hn1 Hn2); eauto.
rewrite union_comm in P.
rewrite Nat.add_comm in Hh.
refine (aux_CUT_bq _ _ _ _ P Hn2 _); eauto.
rewrite <- !lweight_dual; auto.
rewrite <- !Ng_involutive; auto.
refine (aux_CUT_ef _ _ Hw _ P Hn1 Hn2 ); eauto.
refine (aux_CUT_fe _ _ Hw _ P Hn1 Hn2 ); eauto.
-- (** ccut *)
rename H2 into Hw, H4 into Hh.
rename H5 into P, H6 into Hn1, H10 into Hn2.
rename m into n1, n0 into n2.
rename M into M1, N into M2.
inversion Hn1;subst.
eapply resolvers in H1; intuition;
lexp_contr H2.
eapply resolvers2 in H1; intuition;
lexp_contr H2.
(* Top Commutes *)
simpl_cases2.
eexists.
rewrite P.
rewrite H2.
eapply sig3_top. eauto.
(* Bot Commutes *)
simpl_cases2.
assert (exists m, m |~> 0 ; B; x ++ M2) as Hyp.
rewrite H1 in H2.
refine (H0 _ _ _ _ _ _);
[ | change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ H2 Hn2);
auto; try resolve_rewrite]; resolve_max.
destruct Hyp as [t Ht];
eexists;
refine (sig3_bot _ Ht); auto; resolve_rewrite.
(* Par Commutes *)
simpl_cases2.
assert (exists m, m |~> 0 ; B; F0 :: G :: (x ++ M2)) as Hyp.
rewrite H1 in H2;
rewrite union_rotate_cons in H2.
refine (H0 _ _ _ _ _ _);
[ | change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ H2 Hn2);
auto; try resolve_rewrite]; resolve_max.
destruct Hyp as [t Ht];
eexists;
refine (sig3_par _ Ht); auto; resolve_rewrite.
(* Tensor Commutes *)
simpl_cases2.
cut_free.
simpl_cases_tns.
assert (exists m, m |~> 0 ; B; F0 :: (L1 ++ M2)) as Hyp.
rewrite HL1 in H4;
rewrite meq_swap_cons in H4.
refine (H0 _ _ _ _ _ _);
[ | change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ H4 Hn2);
auto; try resolve_rewrite].
inversion Hh. resolve_max.
destruct Hyp as [t Ht];
eexists;
refine (sig3_tensor _ Ht H6); auto; resolve_rewrite.
assert (exists m, m |~> 0 ; B; G :: (L2 ++ M2)) as Hyp.
rewrite HL2 in H6;
rewrite meq_swap_cons in H6.
refine (H0 _ _ _ _ _ _);
[ | change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ H6 Hn2);
auto; try resolve_rewrite].
inversion Hh. resolve_max.
destruct Hyp as [t Ht];
eexists;
refine (sig3_tensor _ H4 Ht); auto; resolve_rewrite.
(* Plus1 Commutes *)
simpl_cases2.
assert (exists m : nat, m |~> 0 ; B; F0 :: x ++ M2) as Hyp.
rewrite H1 in H2;
rewrite meq_swap_cons in H2.
refine (H0 _ _ _ _ _ _);
[ | change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ H2 Hn2);
auto; try resolve_rewrite]; resolve_max.
destruct Hyp as [t Ht];
try rewrite union_assoc in Ht;
eexists;
refine (sig3_plus1 _ Ht); auto; resolve_rewrite.
(* Plus2 Commutes *)
simpl_cases2.
assert (exists m : nat, m |~> 0 ; B; G :: x ++ M2) as Hyp.
rewrite H1 in H2;
rewrite meq_swap_cons in H2.
refine (H0 _ _ _ _ _ _);
[ | change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ H2 Hn2);
auto; try resolve_rewrite]; resolve_max.
destruct Hyp as [t Ht];
try rewrite union_assoc in Ht;
eexists;
refine (sig3_plus2 _ Ht); auto; resolve_rewrite.
(* With Commutes *)
simpl_cases2.
cut_free.
assert (exists m, m |~> 0 ; B; F0 :: (x ++ M2)) as Hyp1.
rewrite H2 in H4;
rewrite meq_swap_cons in H4;
refine (H0 _ _ _ _ _ _);
[ | change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ H4 Hn2);
auto; try resolve_rewrite];resolve_max.
inversion Hh; resolve_max.
assert (exists m, m |~> 0 ; B; G :: (x ++ M2)) as Hyp2.
rewrite H2 in H6; rewrite meq_swap_cons in H6;
refine (H0 _ _ _ _ _ _);
[ | change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ H6 Hn2);
auto; try resolve_rewrite];resolve_max.
inversion Hh; resolve_max.
destruct Hyp1 as [t1 Ht1];
destruct Hyp2 as [t2 Ht2];
eexists;
refine (sig3_with _ Ht1 Ht2); resolve_rewrite.
(* Copy Commutes *)
assert (exists m, m |~> 0 ; B ; F0 :: L) as Hyp.
rewrite meq_swap_cons in H2.
rewrite H2 in H4.
refine (H0 _ _ _ _ _ _);
[ | change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ H4 Hn2);
auto; try resolve_rewrite];resolve_max.
destruct Hyp as [t Ht];
eexists;
refine (sig3_copy _ _ Ht); auto; resolve_rewrite.
(* Quest Commutes *)
simpl_cases2.
assert (exists m, m |~> 0 ; F0 :: B; x ++ M2) as Hyp.
rewrite H1 in H2.
eapply height_preserving_weakning_sig3 with (D:=[F0]) in Hn2.
rewrite <- app_comm_cons in Hn2.
rewrite union_comm in Hn2.
refine (H0 _ _ _ _ _ _);
[ | change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ H2 Hn2);
auto; try resolve_rewrite]; resolve_max.
destruct Hyp as [t Ht];
eexists;
refine (sig3_quest _ Ht); auto; resolve_rewrite.
(* Bang Principal *)
eapply resolvers2 in H1; intuition.
rewrite H5 in P, Hn1; clear H5.
rewrite <- P in *. clear P.
LexpSubst.
inversion Hn2; subst; inversion Hh; try cut_free.
eexists; eapply sig3_init; eassumption.
eexists; eapply sig3_one; eassumption.
eexists; eapply sig3_top; eassumption.
assert (exists m : nat, m |~> 0; B; M) as Hyp.
refine (H0 _ _ _ _ _ _);
[ |
change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ Hn1 H4);
auto]; resolve_max.
destruct Hyp as [t Ht];
eexists;
refine (sig3_bot _ Ht); auto; resolve_rewrite.
assert (exists m, m |~> 0; B; F0 :: G :: M) as Hyp.
refine (H0 _ _ _ _ _ _);
[ |
change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ Hn1 H4);
auto]; resolve_max.
destruct Hyp as [t Ht];
eexists;
refine (sig3_par _ Ht); auto; resolve_rewrite.
assert (exists m, m |~> 0; B; F0 :: M) as Hyp1.
refine (H0 _ _ _ _ _ _);
[ |
change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ Hn1 H5);
auto]; resolve_max.
assert (exists m, m |~> 0; B; G :: N) as Hyp2.
refine (H0 _ _ _ _ _ _);
[ |
change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ Hn1 H7);
auto]; resolve_max.
destruct Hyp1 as [t1 Ht1];
destruct Hyp2 as [t2 Ht2];
eexists;
refine (sig3_tensor _ Ht1 Ht2); auto; resolve_rewrite.
assert (exists m, m |~> 0; B; F0 :: M) as Hyp.
refine (H0 _ _ _ _ _ _);
[ |
change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ Hn1 H4);
auto]; resolve_max.
destruct Hyp as [t Ht];
eexists;
refine (sig3_plus1 _ Ht); auto; resolve_rewrite.
assert (exists m, m |~> 0; B; G :: M) as Hyp.
refine (H0 _ _ _ _ _ _);
[ |
change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ Hn1 H4);
auto]; resolve_max.
destruct Hyp as [t Ht];
eexists;
refine (sig3_plus2 _ Ht); auto; resolve_rewrite.
assert (exists m, m |~> 0; B; F0 :: M) as Hyp1.
refine (H0 _ _ _ _ _ _);
[ |
change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ Hn1 H5);
auto]; resolve_max.
assert (exists m, m |~> 0; B; G :: M) as Hyp2.
refine (H0 _ _ _ _ _ _);
[ |
change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ Hn1 H7);
auto]; resolve_max.
destruct Hyp1 as [t1 Ht1];
destruct Hyp2 as [t2 Ht2];
eexists;
refine (sig3_with _ Ht1 Ht2); auto; resolve_rewrite.
2:{
assert (exists m, m |~> 0; F0 :: B; M) as Hyp.
rewrite meq_swap_cons in H4.
eapply height_preserving_weakning_sig3 with (D:=[F0]) in Hn1.
rewrite union_comm in Hn1.
refine (H0 _ _ _ _ _ _);
[ |
change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ Hn1 H4);
auto]; resolve_max.
destruct Hyp as [t Ht];
eexists;
refine (sig3_quest _ Ht); auto; resolve_rewrite.
}
2:{
assert (exists m, m |~> 0; B; [F0]) as Hyp.
refine (H0 _ _ _ _ _ _);
[ |
change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ Hn1 H4);
auto]; resolve_max.
destruct Hyp as [t Ht];
eexists;
refine (sig3_bang _ Ht); auto; resolve_rewrite.
}
destruct (FEqDec F0 F°); subst.
assert (exists m, m |~> 0; B; F° :: L) as Hyp.
rewrite H4 in H5.
refine (H0 _ _ _ _ _ _);
[ | change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ Hn1 H5);
auto; resolve_rewrite]; resolve_max.
destruct Hyp as [t Ht].
refine (H _ _ _ _ _ _ _);
[ | change (0%nat) with (plus 0 0)].
2:{ refine (sig3_cut _ _ _ H2 Ht); auto. }
inversion Hw. unfold Lexp_weight; auto.
apply not_eqLExp_sym in n1.
simpl_cases2.
assert (exists m, m |~> 0; B; F0 :: L) as Hyp.
rewrite H4 in H5.
refine (H0 _ _ _ _ _ _);
[ |
change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ Hn1 H5);
auto]; resolve_max.
destruct Hyp as [t Ht];
eexists;
refine (sig3_copy _ _ Ht); auto.
assert (exists m, m |~> 0; B; Subst FX t :: M) as Hyp.
refine (H0 _ _ _ _ _ _);
[ |
change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ Hn1 H4);
auto]; resolve_max.
destruct Hyp as [p Hp];
eexists;
refine (sig3_ex _ Hp); auto; resolve_rewrite.
assert (forall y : Term, exists m, m |~> 0; B; Subst FX y :: M) as Hyp.
intro.
assert (n0 |~> 0; F° :: B; Subst FX y :: M) by auto.
refine (H0 _ _ _ _ _ _);
[ |
change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ Hn1 H5);
auto]; resolve_max.
apply fx_swap_sig3h in Hyp.
destruct Hyp as [p Hp];
eexists;
refine (sig3_fx _ Hp); auto; resolve_rewrite.
simpl_cases2.
assert (exists m, m |~> 0; B; Subst FX t :: (x++M2)) as Hyp.
rewrite H1 in H2.
rewrite meq_swap_cons in H2.
refine (H0 _ _ _ _ _ _);
[ |
change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ H2 Hn2) ;
auto]; resolve_max.
destruct Hyp as [p Hp];
eexists;
refine (sig3_ex _ Hp); auto; resolve_rewrite.
simpl_cases2.
assert (forall y : Term, exists m, m |~> 0; B; Subst FX y :: (x++M2)) as Hyp.
intro.
assert (n |~> 0; B; Subst FX y :: M) by auto.
rewrite H1 in H5.
rewrite meq_swap_cons in H5.
refine (H0 _ _ _ _ _ _);
[ |
change (0%nat) with (plus 0 0);
refine (sig3_ccut _ _ _ H5 Hn2) ;
auto]; resolve_max.
apply fx_swap_sig3h in Hyp.
destruct Hyp as [p Hp];
eexists;
refine (sig3_fx _ Hp); auto; resolve_rewrite.
Qed.
Theorem cut_elimination : forall B L n c, n |~> c ; B ; L ->
exists m, m |~> 0 ; B ; L.
Proof.
intros.
dependent induction n generalizing B L using strongind; induction c using strongind.
+ (* Case <0,0> *)
eexists; eauto.
+ (* Case <0, S c> *)
inversion H.
+ (* case <Sn, 0> *)
inversion H0;subst;try (rewrite H2).
++ (* BOTTOM*) eexists. eapply sig3_bot;eauto.
++ (* PAR *) eexists. eapply sig3_par;eauto.
++ (* TENSOR *)
cut_free.
eexists.
change (0%nat) with (plus 0 0).
eapply sig3_tensor;eauto.
++ (* OPLUS F *) eexists. eapply sig3_plus1; eauto.
++ (* OPLUS G *) eexists. eapply sig3_plus2; eauto.
++ (* WITH *)
cut_free.
eexists.
change (0%nat) with (plus 0 0).
eapply sig3_with;eauto.
++ (* COPY *) eexists. eapply sig3_copy; eauto.
++ (* QUEST *) eexists. eapply sig3_quest; eauto.
++ (* BANG *) eexists. eapply sig3_bang; eauto.
++ (* EX *) eexists. eapply sig3_ex; eauto.
++ (* FX *) eexists. eapply sig3_fx; eauto.
+ (* Case <Sn, Sc> *)
rename H1 into IHn.
inversion H0;subst.
++ (* bottom *)
apply H in H3; auto. destruct H3.
eexists.
eapply sig3_bot; eauto.
++ (* PAR *)
apply H in H3;auto. destruct H3.
eexists.
eapply sig3_par; eauto.
++
(* TENSOR *)
apply H in H4;auto. destruct H4.
apply H in H5;auto. destruct H5.
change (0%nat) with (plus 0 0).
eexists.
eapply sig3_tensor;eauto.
++ (* PLUS1 *)
apply H in H3;auto. destruct H3.
eexists.
eapply sig3_plus1; eauto.
++ (* PLUS2 *)
apply H in H3;auto. destruct H3.
eexists.
eapply sig3_plus2; eauto.
++ (* WITH *)
apply H in H4;auto. destruct H4.
apply H in H5;auto. destruct H5.
change (0%nat) with (plus 0 0).
eexists.
eapply sig3_with;eauto.
++ (* copy *)
apply H in H4;auto. destruct H4.
eexists.
eapply sig3_copy; eauto.
++ (* quest *)
apply H in H3;auto. destruct H3.
eexists.
eapply sig3_quest;eauto.
++ (* bang *)
apply H in H3;auto. destruct H3.
eexists.
eapply sig3_bang; eauto.
++ (* ex *)
apply H in H3;auto. destruct H3.
eexists.
eapply sig3_ex; eauto.
++ (* fx *)
assert (forall y : Term, exists m, m |~> 0; B; Subst FX y :: M) as Hyp.
intro.
assert (n |~> S c; B; Subst FX y :: M) by auto.
eapply H; auto.
apply fx_swap_sig3h in Hyp.
destruct Hyp as [p Hp].
eexists.
eapply sig3_fx;eauto.
++ (* CUT *)
destruct H3.
--
apply H in H4;auto. destruct H4.
apply H in H5;auto. destruct H5.
assert(Hc: S(Init.Nat.max x0 x) |~> S(0 + 0) ; B ; L).
eapply sig3_CUT.
eapply sig3_cut;eauto.
apply cut_elimination_base in Hc.
destruct Hc.
eexists. eauto.
--
(* CCUT *)
apply H in H4;auto. destruct H4.
apply H in H5;auto. destruct H5.
assert(Hc: S(Init.Nat.max x0 x) |~> S(0 + 0) ; B ; L).
eapply sig3_CUT.
eapply sig3_ccut;eauto.
apply cut_elimination_base in Hc.
destruct Hc.
eexists; eauto.
Qed.
Theorem weak_consistency : forall n c, ~ sig3 n c [] [0].
Proof.
intros.
intro.
apply cut_elimination in H.
destruct H.
inversion H; subst;
try simpl_cases0.
eapply DestructMulFalse; eauto.
Qed.
Lemma strong_cons : forall n c, ~ sig3 n c [] [].
Proof.
intros.
intro.
apply cut_elimination in H.
destruct H.
inversion H; subst;
try solve [eapply DestructMulFalse; eauto].
Qed.
Theorem strong_consistency : forall n c, ~ sig3 n c [] [Bot].
Proof.
intros.
intro.
apply cut_elimination in H.
destruct H.
inversion H; subst;
try simpl_cases0.
rewrite Hm in H1.
eapply strong_cons; eauto.
eapply DestructMulFalse; eauto.
Qed.
End CElimination.
|
/*
* OperatorChooseConstraint.cpp
* @brief OperatorChooseConstraint constraint
* @date Mar 20, 2022
* @author Yoonwoo Kim
*/
#include <gtsam/base/Testable.h>
#include <gtsam/discrete/DecisionTreeFactor.h>
#include <cpp/planning/OperatorChooseConstraint.h>
#include <boost/make_shared.hpp>
using namespace gtsam;
using namespace std;
namespace gtsam_planner {
/* ************************************************************************* */
OperatorChooseConstraint::OperatorChooseConstraint(const vector<MultiValueConstraint>& factors,
size_t which_op) : DiscreteFactor(factors[which_op].discreteKeys().indices()) {
for (const MultiValueConstraint& factor: factors) factors_.push_back(factor);
dkeys_ = factors_[which_op].discreteKeys();
which_op_ = which_op;
}
/* ************************************************************************* */
void OperatorChooseConstraint::print(const string& s, const KeyFormatter& formatter) const {
cout << s << "OperatorChooseConstraint on ";
for (DiscreteKey dkey : dkeys_) cout << formatter(dkey.first) << " ";
cout << endl;
}
/* ************************************************************************* */
double OperatorChooseConstraint::operator()(const DiscreteValues& values) const {
return factors_[which_op_](values);
}
/* ************************************************************************* */
DecisionTreeFactor OperatorChooseConstraint::toDecisionTreeFactor() const {
DecisionTreeFactor converted = factors_[which_op_].toDecisionTreeFactor();
return converted;
}
/* ************************************************************************* */
DecisionTreeFactor OperatorChooseConstraint::operator*(const DecisionTreeFactor& f) const {
// TODO: can we do this more efficiently?
return toDecisionTreeFactor() * f;
}
} // namespace gtsam_planner
|
# a function returning (i + j) * -998
func $foo (
# var %i xxx,
var %i i32,
var %j i32) i32 {
return (
mul i32 (
add i32 ( dread i32 %i, dread i32 %j),
constval i32 -998))}
# EXEC: %irbuild Main.mpl
# EXEC: %irbuild Main.irb.mpl
# EXEC: %cmp Main.irb.mpl Main.irb.irb.mpl
|
(* Author: Sébastien Gouëzel [email protected]
License: BSD
*)
section \<open>The exponential on extended real numbers.\<close>
theory Eexp_Eln
imports Library_Complements
begin
text \<open>To define the distance on the Gromov completion of hyperbolic spaces, we need to use
the exponential on extended real numbers. We can not use the symbol \verb+exp+, as this symbol
is already used in Banach algebras, so we use \verb+ennexp+ instead. We prove its basic
properties (together with properties of the logarithm) here. We also use it to define the square
root on ennreal. Finally, we also define versions from ereal to ereal.\<close>
function ennexp::"ereal \<Rightarrow> ennreal" where
"ennexp (ereal r) = ennreal (exp r)"
| "ennexp (\<infinity>) = \<infinity>"
| "ennexp (-\<infinity>) = 0"
by (auto intro: ereal_cases)
termination by standard (rule wf_empty)
lemma ennexp_0 [simp]:
"ennexp 0 = 1"
by (auto simp add: zero_ereal_def one_ennreal_def)
function eln::"ennreal \<Rightarrow> ereal" where
"eln (ennreal r) = (if r \<le> 0 then -\<infinity> else ereal (ln r))"
| "eln (\<infinity>) = \<infinity>"
by (auto intro: ennreal_cases, metis ennreal_eq_0_iff, simp add: ennreal_neg)
termination by standard (rule wf_empty)
lemma eln_simps [simp]:
"eln 0 = -\<infinity>"
"eln 1 = 0"
"eln top = \<infinity>"
apply (simp only: eln.simps ennreal_0[symmetric], simp)
apply (simp only: eln.simps ennreal_1[symmetric], simp)
using eln.simps(2) by auto
lemma eln_real_pos:
assumes "r > 0"
shows "eln (ennreal r) = ereal (ln r)"
using eln.simps assms by auto
lemma eln_ennexp [simp]:
"eln (ennexp x) = x"
apply (cases x) using eln.simps by auto
lemma ennexp_eln [simp]:
"ennexp (eln x) = x"
apply (cases x) using eln.simps by auto
lemma ennexp_strict_mono:
"strict_mono ennexp"
proof -
have "ennexp x < ennexp y" if "x < y" for x y
apply (cases x, cases y)
using that apply (auto simp add: ennreal_less_iff)
by (cases y, auto)
then show ?thesis unfolding strict_mono_def by auto
qed
lemma ennexp_mono:
"mono ennexp"
using ennexp_strict_mono by (simp add: strict_mono_mono)
lemma ennexp_strict_mono2 [mono_intros]:
assumes "x < y"
shows "ennexp x < ennexp y"
using ennexp_strict_mono assms unfolding strict_mono_def by auto
lemma ennexp_mono2 [mono_intros]:
assumes "x \<le> y"
shows "ennexp x \<le> ennexp y"
using ennexp_mono assms unfolding mono_def by auto
lemma ennexp_le1 [simp]:
"ennexp x \<le> 1 \<longleftrightarrow> x \<le> 0"
by (metis ennexp_0 ennexp_mono2 ennexp_strict_mono eq_iff le_cases strict_mono_eq)
lemma ennexp_ge1 [simp]:
"ennexp x \<ge> 1 \<longleftrightarrow> x \<ge> 0"
by (metis ennexp_0 ennexp_mono2 ennexp_strict_mono eq_iff le_cases strict_mono_eq)
lemma eln_strict_mono:
"strict_mono eln"
by (metis ennexp_eln strict_monoI ennexp_strict_mono strict_mono_less)
lemma eln_strict_mono2 [mono_intros]:
assumes "x < y"
shows "eln x < eln y"
using eln_strict_mono assms unfolding strict_mono_def by auto
lemma eln_mono2 [mono_intros]:
assumes "x \<le> y"
shows "eln x \<le> eln y"
using eln_mono assms unfolding mono_def by auto
lemma eln_le0 [simp]:
"eln x \<le> 0 \<longleftrightarrow> x \<le> 1"
by (metis ennexp_eln ennexp_le1)
lemma eln_ge0 [simp]:
"eln x \<ge> 0 \<longleftrightarrow> x \<ge> 1"
by (metis ennexp_eln ennexp_ge1)
lemma bij_ennexp:
"bij ennexp"
by (auto intro!: bij_betw_byWitness[of _ eln])
lemma bij_eln:
"bij eln"
by (auto intro!: bij_betw_byWitness[of _ ennexp])
lemma ennexp_continuous:
"continuous_on UNIV ennexp"
apply (rule continuous_onI_mono)
using ennexp_mono unfolding mono_def by (auto simp add: bij_ennexp bij_is_surj)
lemma ennexp_tendsto [tendsto_intros]:
assumes "((\<lambda>n. u n) \<longlongrightarrow> l) F"
shows "((\<lambda>n. ennexp(u n)) \<longlongrightarrow> ennexp l) F"
using ennexp_continuous assms by (metis UNIV_I continuous_on tendsto_compose)
lemma eln_continuous:
"continuous_on UNIV eln"
apply (rule continuous_onI_mono)
using eln_mono unfolding mono_def by (auto simp add: bij_eln bij_is_surj)
lemma eln_tendsto [tendsto_intros]:
assumes "((\<lambda>n. u n) \<longlongrightarrow> l) F"
shows "((\<lambda>n. eln(u n)) \<longlongrightarrow> eln l) F"
using eln_continuous assms by (metis UNIV_I continuous_on tendsto_compose)
lemma ennexp_special_values [simp]:
"ennexp x = 0 \<longleftrightarrow> x = -\<infinity>"
"ennexp x = 1 \<longleftrightarrow> x = 0"
"ennexp x = \<infinity> \<longleftrightarrow> x = \<infinity>"
"ennexp x = top \<longleftrightarrow> x = \<infinity>"
by auto (metis eln_ennexp eln_simps)+
lemma eln_special_values [simp]:
"eln x = -\<infinity> \<longleftrightarrow> x = 0"
"eln x = 0 \<longleftrightarrow> x = 1"
"eln x = \<infinity> \<longleftrightarrow> x = \<infinity>"
apply auto
apply (metis ennexp.simps ennexp_eln ennexp_0)+
by (metis ennexp.simps(2) ennexp_eln infinity_ennreal_def)
lemma ennexp_add_mult:
assumes "\<not>((a = \<infinity> \<and> b = -\<infinity>) \<or> (a = -\<infinity> \<and> b = \<infinity>))"
shows "ennexp(a+b) = ennexp a * ennexp b"
apply (cases a, cases b)
using assms by (auto simp add: ennreal_mult'' exp_add ennreal_top_eq_mult_iff)
lemma eln_mult_add:
assumes "\<not>((a = \<infinity> \<and> b = 0) \<or> (a = 0 \<and> b = \<infinity>))"
shows "eln(a * b) = eln a + eln b"
by (smt assms ennexp.simps(2) ennexp.simps(3) ennexp_add_mult ennexp_eln eln_ennexp)
text \<open>We can also define the square root on ennreal using the above exponential.\<close>
definition ennsqrt::"ennreal \<Rightarrow> ennreal"
where "ennsqrt x = ennexp(eln x/2)"
lemma ennsqrt_square [simp]:
"(ennsqrt x) * (ennsqrt x) = x"
proof -
have "y/2 + y/2 = y" for y::ereal
by (cases y, auto)
then show ?thesis
unfolding ennsqrt_def by (subst ennexp_add_mult[symmetric], auto)
qed
lemma ennsqrt_simps [simp]:
"ennsqrt 0 = 0"
"ennsqrt 1 = 1"
"ennsqrt \<infinity> = \<infinity>"
"ennsqrt top = top"
unfolding ennsqrt_def by auto
lemma ennsqrt_mult:
"ennsqrt(a * b) = ennsqrt a * ennsqrt b"
proof -
have [simp]: "z/ereal 2 = -\<infinity> \<longleftrightarrow> z = -\<infinity>" for z
by (auto simp add: ereal_divide_eq)
consider "a = 0" | "b = 0" | "a > 0 \<and> b > 0"
using zero_less_iff_neq_zero by auto
then show ?thesis
apply (cases, auto)
apply (cases a, cases b, auto simp add: ennreal_mult_top ennreal_top_mult)
unfolding ennsqrt_def apply (subst ennexp_add_mult[symmetric], auto)
apply (subst eln_mult_add, auto)
done
qed
lemma ennsqrt_square2 [simp]:
"ennsqrt (x * x) = x"
unfolding ennsqrt_mult by auto
lemma ennsqrt_eq_iff_square:
"ennsqrt x = y \<longleftrightarrow> x = y * y"
by auto
lemma ennsqrt_bij:
"bij ennsqrt"
by (rule bij_betw_byWitness[of _ "\<lambda>x. x * x"], auto)
lemma ennsqrt_strict_mono:
"strict_mono ennsqrt"
unfolding ennsqrt_def
apply (rule strict_mono_compose[OF ennexp_strict_mono])
apply (rule strict_mono_compose[OF _ eln_strict_mono])
by (auto simp add: ereal_less_divide_pos ereal_mult_divide strict_mono_def)
lemma ennsqrt_mono:
"mono ennsqrt"
using ennsqrt_strict_mono by (simp add: strict_mono_mono)
lemma ennsqrt_mono2 [mono_intros]:
assumes "x \<le> y"
shows "ennsqrt x \<le> ennsqrt y"
using ennsqrt_mono assms unfolding mono_def by auto
lemma ennsqrt_continuous:
"continuous_on UNIV ennsqrt"
apply (rule continuous_onI_mono)
using ennsqrt_mono unfolding mono_def by (auto simp add: ennsqrt_bij bij_is_surj)
lemma ennsqrt_tendsto [tendsto_intros]:
assumes "((\<lambda>n. u n) \<longlongrightarrow> l) F"
shows "((\<lambda>n. ennsqrt(u n)) \<longlongrightarrow> ennsqrt l) F"
using ennsqrt_continuous assms by (metis UNIV_I continuous_on tendsto_compose)
lemma ennsqrt_ennreal_ennreal_sqrt [simp]:
assumes "t \<ge> (0::real)"
shows "ennsqrt (ennreal t) = ennreal (sqrt t)"
proof -
have "ennreal t = ennreal (sqrt t) * ennreal(sqrt t)"
apply (subst ennreal_mult[symmetric]) using assms by auto
then show ?thesis
by auto
qed
lemma ennreal_sqrt2:
"ennreal (sqrt 2) = ennsqrt 2"
using ennsqrt_ennreal_ennreal_sqrt[of 2] by auto
lemma ennsqrt_4 [simp]:
"ennsqrt 4 = 2"
by (metis ennreal_numeral ennsqrt_ennreal_ennreal_sqrt real_sqrt_four zero_le_numeral)
lemma ennsqrt_le [simp]:
"ennsqrt x \<le> ennsqrt y \<longleftrightarrow> x \<le> y"
proof
assume "ennsqrt x \<le> ennsqrt y"
then have "ennsqrt x * ennsqrt x \<le> ennsqrt y * ennsqrt y"
by (intro mult_mono, auto)
then show "x \<le> y" by auto
qed (auto intro: mono_intros)
text \<open>We can also define the square root on ereal using the square root on ennreal, and $0$
for negative numbers.\<close>
definition esqrt::"ereal \<Rightarrow> ereal"
where "esqrt x = enn2ereal(ennsqrt (e2ennreal x))"
lemma esqrt_square [simp]:
assumes "x \<ge> 0"
shows "(esqrt x) * (esqrt x) = x"
unfolding esqrt_def times_ennreal.rep_eq[symmetric] ennsqrt_square[of "e2ennreal x"]
using assms enn2ereal_e2ennreal by auto
lemma esqrt_nonneg [simp]:
"esqrt x \<ge> 0"
unfolding esqrt_def by auto
lemma esqrt_eq_iff_square [simp]:
assumes "x \<ge> 0" "y \<ge> 0"
shows "esqrt x = y \<longleftrightarrow> x = y * y"
using esqrt_def esqrt_square assms apply auto
by (metis e2ennreal_enn2ereal ennsqrt_square2 eq_onp_same_args ereal_ennreal_cases leD times_ennreal.abs_eq)
lemma esqrt_simps [simp]:
"esqrt 0 = 0"
"esqrt 1 = 1"
"esqrt \<infinity> = \<infinity>"
"esqrt top = top"
"esqrt (-\<infinity>) = 0"
by (auto simp: top_ereal_def)
lemma esqrt_mult:
assumes "a \<ge> 0"
shows "esqrt(a * b) = esqrt a * esqrt b"
proof (cases "b \<ge> 0")
case True
show ?thesis
unfolding esqrt_def apply (subst times_ennreal.rep_eq[symmetric])
apply (subst ennsqrt_mult[of "e2ennreal a" "e2ennreal b", symmetric])
apply (subst times_ennreal.abs_eq)
using assms True by (auto simp add: eq_onp_same_args)
next
case False
then have "a * b \<le> 0" using assms ereal_mult_le_0_iff by auto
then have "esqrt(a * b) = 0" by auto
moreover have "esqrt b = 0" using False by auto
ultimately show ?thesis by auto
qed
lemma esqrt_square2 [simp]:
"esqrt(x * x) = abs(x)"
proof -
have "esqrt(x * x) = esqrt(abs x * abs x)"
by (metis (no_types, hide_lams) abs_ereal_ge0 ereal_abs_mult ereal_zero_le_0_iff linear)
also have "... = abs x"
by (auto simp add: esqrt_mult)
finally show ?thesis by auto
qed
lemma esqrt_mono:
"mono esqrt"
unfolding esqrt_def mono_def by (auto intro: mono_intros)
lemma esqrt_mono2 [mono_intros]:
assumes "x \<le> y"
shows "esqrt x \<le> esqrt y"
using esqrt_mono assms unfolding mono_def by auto
lemma esqrt_continuous:
"continuous_on UNIV esqrt"
unfolding esqrt_def apply (rule continuous_on_compose2[of UNIV enn2ereal], intro continuous_on_enn2ereal)
by (rule continuous_on_compose2[of UNIV ennsqrt], auto intro!: ennsqrt_continuous continuous_on_e2ennreal)
lemma esqrt_tendsto [tendsto_intros]:
assumes "((\<lambda>n. u n) \<longlongrightarrow> l) F"
shows "((\<lambda>n. esqrt(u n)) \<longlongrightarrow> esqrt l) F"
using esqrt_continuous assms by (metis UNIV_I continuous_on tendsto_compose)
lemma esqrt_ereal_ereal_sqrt [simp]:
assumes "t \<ge> (0::real)"
shows "esqrt (ereal t) = ereal (sqrt t)"
proof -
have "ereal t = ereal (sqrt t) * ereal(sqrt t)"
using assms by auto
then show ?thesis
using assms ereal_less_eq(5) esqrt_mult esqrt_square real_sqrt_ge_zero by presburger
qed
lemma ereal_sqrt2:
"ereal (sqrt 2) = esqrt 2"
using esqrt_ereal_ereal_sqrt[of 2] by auto
lemma esqrt_4 [simp]:
"esqrt 4 = 2"
by auto
lemma esqrt_le [simp]:
"esqrt x \<le> esqrt y \<longleftrightarrow> (x \<le> 0 \<or> x \<le> y)"
apply (auto simp add: esqrt_mono2)
by (metis eq_iff ereal_zero_times esqrt_mono2 esqrt_square le_cases)
text \<open>Finally, we define eexp, as the composition of ennexp and the injection of ennreal in ereal.\<close>
definition eexp::"ereal \<Rightarrow> ereal" where
"eexp x = enn2ereal (ennexp x)"
lemma eexp_special_values [simp]:
"eexp 0 = 1"
"eexp (\<infinity>) = \<infinity>"
"eexp(-\<infinity>) = 0"
unfolding eexp_def by (auto simp add: zero_ennreal.rep_eq one_ennreal.rep_eq)
lemma eexp_strict_mono:
"strict_mono eexp"
unfolding eexp_def using ennexp_strict_mono unfolding strict_mono_def by (auto intro: mono_intros)
lemma eexp_mono:
"mono eexp"
using eexp_strict_mono by (simp add: strict_mono_mono)
lemma eexp_strict_mono2 [mono_intros]:
assumes "x < y"
shows "eexp x < eexp y"
using eexp_strict_mono assms unfolding strict_mono_def by auto
lemma eexp_mono2 [mono_intros]:
assumes "x \<le> y"
shows "eexp x \<le> eexp y"
using eexp_mono assms unfolding mono_def by auto
lemma eexp_le_eexp_iff_le:
"eexp x \<le> eexp y \<longleftrightarrow> x \<le> y"
using eexp_strict_mono2 not_le by (auto intro: mono_intros)
lemma eexp_lt_eexp_iff_lt:
"eexp x < eexp y \<longleftrightarrow> x < y"
using eexp_mono2 not_le by (auto intro: mono_intros)
lemma eexp_special_values_iff [simp]:
"eexp x = 0 \<longleftrightarrow> x = -\<infinity>"
"eexp x = 1 \<longleftrightarrow> x = 0"
"eexp x = \<infinity> \<longleftrightarrow> x = \<infinity>"
"eexp x = top \<longleftrightarrow> x = \<infinity>"
unfolding eexp_def apply (auto simp add: zero_ennreal.rep_eq one_ennreal.rep_eq top_ereal_def)
apply (metis e2ennreal_enn2ereal ennexp.simps(3) ennexp_strict_mono strict_mono_eq zero_ennreal_def)
by (metis e2ennreal_enn2ereal eln_ennexp eln_simps(2) one_ennreal_def)
lemma eexp_ineq_iff [simp]:
"eexp x \<le> 1 \<longleftrightarrow> x \<le> 0"
"eexp x \<ge> 1 \<longleftrightarrow> x \<ge> 0"
"eexp x > 1 \<longleftrightarrow> x > 0"
"eexp x < 1 \<longleftrightarrow> x < 0"
"eexp x \<ge> 0"
"eexp x > 0 \<longleftrightarrow> x \<noteq> - \<infinity>"
"eexp x < \<infinity> \<longleftrightarrow> x \<noteq> \<infinity>"
apply (metis eexp_le_eexp_iff_le eexp_lt_eexp_iff_lt eexp_special_values)+
apply (simp add: eexp_def)
using eexp_strict_mono2 apply (force)
by simp
lemma eexp_ineq [mono_intros]:
"x \<le> 0 \<Longrightarrow> eexp x \<le> 1"
"x < 0 \<Longrightarrow> eexp x < 1"
"x \<ge> 0 \<Longrightarrow> eexp x \<ge> 1"
"x > 0 \<Longrightarrow> eexp x > 1"
"eexp x \<ge> 0"
"x > -\<infinity> \<Longrightarrow> eexp x > 0"
"x < \<infinity> \<Longrightarrow> eexp x < \<infinity>"
by auto
lemma eexp_continuous:
"continuous_on UNIV eexp"
unfolding eexp_def by (rule continuous_on_compose2[of UNIV enn2ereal], auto simp: continuous_on_enn2ereal ennexp_continuous)
lemma eexp_tendsto' [simp]:
"((\<lambda>n. eexp(u n)) \<longlongrightarrow> eexp l) F \<longleftrightarrow> ((\<lambda>n. u n) \<longlongrightarrow> l) F"
proof
assume H: "((\<lambda>n. eexp (u n)) \<longlongrightarrow> eexp l) F"
have "((\<lambda>n. eln (e2ennreal (eexp (u n)))) \<longlongrightarrow> eln (e2ennreal (eexp l))) F"
by (intro tendsto_intros H)
then show "(u \<longlongrightarrow> l) F"
unfolding eexp_def by auto
next
assume "(u \<longlongrightarrow> l) F"
then show "((\<lambda>n. eexp(u n)) \<longlongrightarrow> eexp l) F"
using eexp_continuous by (metis UNIV_I continuous_on tendsto_compose)
qed
lemma eexp_tendsto [tendsto_intros]:
assumes "((\<lambda>n. u n) \<longlongrightarrow> l) F"
shows "((\<lambda>n. eexp(u n)) \<longlongrightarrow> eexp l) F"
using assms by auto
lemma eexp_add_mult:
assumes "\<not>((a = \<infinity> \<and> b = -\<infinity>) \<or> (a = -\<infinity> \<and> b = \<infinity>))"
shows "eexp(a+b) = eexp a * eexp b"
using ennexp_add_mult[OF assms] unfolding eexp_def by (simp add: times_ennreal.rep_eq)
lemma eexp_ereal [simp]:
"eexp(ereal x) = ereal(exp x)"
by (simp add: eexp_def)
end (*of theory Eexp_Eln*)
|
#include <iostream>
#include "document.hpp"
#include <boost/unordered_map.hpp>
#include <vector>
#include <cmath>
#if DEBUG
#include <iostream>
#endif
using namespace doc;
int Word::maxId;
void Word::idInit() {
maxId = 0;
}
Word::Word( std::string word) {
this->id = maxId;
maxId++;
this->word = word;
}
Word::~Word() {
delete this;
}
bool Word::operator==( Word* other) {
return this->id == other->id;
}
Document::Document( std::vector<Word*>* words) {
this->words = *words;
this->score = .0f;
this->documentNorm = .0f;
for (auto const& word: this->words) {
this->countMap[word->id] = this->countMap.count( word->id) == 0 ?
1 : this->countMap[word->id] + 1;
}
for (auto const& pair: this->countMap) {
this->documentNorm += pair.second ^ 2;
}
this->documentNorm = sqrt( this->documentNorm);
}
Document::~Document() {
this->words.clear();
delete this;
}
void Document::getScore( Document* other) {
float partialScore = .0f;
float score;
if (this->documentNorm == .0f || other->documentNorm == .0f)
return;
for (auto const& pair: this->countMap) {
int count = other->countMap.count( pair.first);
partialScore += pair.second * count;
}
this->score = partialScore / this->documentNorm / other->documentNorm;
}
|
lemma emeasure_union_summable: assumes [measurable]: "\<And>n. A n \<in> sets M" and "\<And>n. emeasure M (A n) < \<infinity>" "summable (\<lambda>n. measure M (A n))" shows "emeasure M (\<Union>n. A n) < \<infinity>" "emeasure M (\<Union>n. A n) \<le> (\<Sum>n. measure M (A n))" |
/-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import algebra.group_power.lemmas
import data.int.bitwise
/-!
# Powers of elements of groups with an adjoined zero element
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define integer power functions for groups with an adjoined zero element.
This generalises the integer power function on a division ring.
-/
section group_with_zero
variables {G₀ : Type*} [group_with_zero G₀] {a : G₀} {m n : ℕ}
section nat_pow
theorem pow_sub₀ (a : G₀) {m n : ℕ} (ha : a ≠ 0) (h : n ≤ m) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ :=
have h1 : m - n + n = m, from tsub_add_cancel_of_le h,
have h2 : a ^ (m - n) * a ^ n = a ^ m, by rw [←pow_add, h1],
by simpa only [div_eq_mul_inv] using eq_div_of_mul_eq (pow_ne_zero _ ha) h2
lemma pow_sub_of_lt (a : G₀) {m n : ℕ} (h : n < m) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ :=
begin
obtain rfl | ha := eq_or_ne a 0,
{ rw [zero_pow (tsub_pos_of_lt h), zero_pow (n.zero_le.trans_lt h), zero_mul] },
{ exact pow_sub₀ _ ha h.le }
end
theorem pow_inv_comm₀ (a : G₀) (m n : ℕ) : (a⁻¹) ^ m * a ^ n = a ^ n * (a⁻¹) ^ m :=
(commute.refl a).inv_left₀.pow_pow m n
lemma inv_pow_sub₀ (ha : a ≠ 0) (h : n ≤ m) : a⁻¹ ^ (m - n) = (a ^ m)⁻¹ * a ^ n :=
by rw [pow_sub₀ _ (inv_ne_zero ha) h, inv_pow, inv_pow, inv_inv]
lemma inv_pow_sub_of_lt (a : G₀) (h : n < m) : a⁻¹ ^ (m - n) = (a ^ m)⁻¹ * a ^ n :=
by rw [pow_sub_of_lt a⁻¹ h, inv_pow, inv_pow, inv_inv]
end nat_pow
end group_with_zero
section zpow
open int
variables {G₀ : Type*} [group_with_zero G₀]
local attribute [ematch] le_of_lt
lemma zero_zpow : ∀ z : ℤ, z ≠ 0 → (0 : G₀) ^ z = 0
| (n : ℕ) h := by { rw [zpow_coe_nat, zero_pow'], simpa using h }
| -[1+n] h := by simp
lemma zero_zpow_eq (n : ℤ) : (0 : G₀) ^ n = if n = 0 then 1 else 0 :=
begin
split_ifs with h,
{ rw [h, zpow_zero] },
{ rw [zero_zpow _ h] }
end
lemma zpow_add_one₀ {a : G₀} (ha : a ≠ 0) : ∀ n : ℤ, a ^ (n + 1) = a ^ n * a
| (n : ℕ) := by simp only [← int.coe_nat_succ, zpow_coe_nat, pow_succ']
| -[1+0] := by erw [zpow_zero, zpow_neg_succ_of_nat, pow_one, inv_mul_cancel ha]
| -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, zpow_neg, neg_add, neg_add_cancel_right, zpow_neg,
← int.coe_nat_succ, zpow_coe_nat, zpow_coe_nat, pow_succ _ (n + 1), mul_inv_rev, mul_assoc,
inv_mul_cancel ha, mul_one]
lemma zpow_sub_one₀ {a : G₀} (ha : a ≠ 0) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ :=
calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : by rw [mul_assoc, mul_inv_cancel ha, mul_one]
... = a^n * a⁻¹ : by rw [← zpow_add_one₀ ha, sub_add_cancel]
lemma zpow_add₀ {a : G₀} (ha : a ≠ 0) (m n : ℤ) : a ^ (m + n) = a ^ m * a ^ n :=
begin
induction n using int.induction_on with n ihn n ihn,
case hz : { simp },
{ simp only [← add_assoc, zpow_add_one₀ ha, ihn, mul_assoc] },
{ rw [zpow_sub_one₀ ha, ← mul_assoc, ← ihn, ← zpow_sub_one₀ ha, add_sub_assoc] }
end
lemma zpow_add' {a : G₀} {m n : ℤ} (h : a ≠ 0 ∨ m + n ≠ 0 ∨ m = 0 ∧ n = 0) :
a ^ (m + n) = a ^ m * a ^ n :=
begin
by_cases hm : m = 0, { simp [hm] },
by_cases hn : n = 0, { simp [hn] },
by_cases ha : a = 0,
{ subst a,
simp only [false_or, eq_self_iff_true, not_true, ne.def, hm, hn, false_and, or_false] at h,
rw [zero_zpow _ h, zero_zpow _ hm, zero_mul] },
{ exact zpow_add₀ ha m n }
end
theorem zpow_one_add₀ {a : G₀} (h : a ≠ 0) (i : ℤ) : a ^ (1 + i) = a * a ^ i :=
by rw [zpow_add₀ h, zpow_one]
theorem semiconj_by.zpow_right₀ {a x y : G₀} (h : semiconj_by a x y) :
∀ m : ℤ, semiconj_by a (x^m) (y^m)
| (n : ℕ) := by simp [h.pow_right n]
| -[1+n] := by simp [(h.pow_right (n + 1)).inv_right₀]
theorem commute.zpow_right₀ {a b : G₀} (h : commute a b) : ∀ m : ℤ, commute a (b^m) :=
h.zpow_right₀
theorem commute.zpow_left₀ {a b : G₀} (h : commute a b) (m : ℤ) : commute (a^m) b :=
(h.symm.zpow_right₀ m).symm
theorem commute.zpow_zpow₀ {a b : G₀} (h : commute a b) (m n : ℤ) : commute (a^m) (b^n) :=
(h.zpow_left₀ m).zpow_right₀ n
theorem commute.zpow_self₀ (a : G₀) (n : ℤ) : commute (a^n) a := (commute.refl a).zpow_left₀ n
theorem commute.self_zpow₀ (a : G₀) (n : ℤ) : commute a (a^n) := (commute.refl a).zpow_right₀ n
theorem commute.zpow_zpow_self₀ (a : G₀) (m n : ℤ) : commute (a^m) (a^n) :=
(commute.refl a).zpow_zpow₀ m n
theorem zpow_bit1₀ (a : G₀) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a :=
begin
rw [← zpow_bit0, bit1, zpow_add', zpow_one],
right, left,
apply bit1_ne_zero
end
lemma zpow_ne_zero_of_ne_zero {a : G₀} (ha : a ≠ 0) : ∀ (z : ℤ), a ^ z ≠ 0
| (n : ℕ) := by { rw zpow_coe_nat, exact pow_ne_zero _ ha }
| -[1+n] := by { rw zpow_neg_succ_of_nat, exact inv_ne_zero (pow_ne_zero _ ha) }
lemma zpow_sub₀ {a : G₀} (ha : a ≠ 0) (z1 z2 : ℤ) : a ^ (z1 - z2) = a ^ z1 / a ^ z2 :=
by rw [sub_eq_add_neg, zpow_add₀ ha, zpow_neg, div_eq_mul_inv]
theorem zpow_bit1' (a : G₀) (n : ℤ) : a ^ bit1 n = (a * a) ^ n * a :=
by rw [zpow_bit1₀, (commute.refl a).mul_zpow]
lemma zpow_eq_zero {x : G₀} {n : ℤ} (h : x ^ n = 0) : x = 0 :=
classical.by_contradiction $ λ hx, zpow_ne_zero_of_ne_zero hx n h
lemma zpow_eq_zero_iff {a : G₀} {n : ℤ} (hn : n ≠ 0) :
a ^ n = 0 ↔ a = 0 :=
⟨zpow_eq_zero, λ ha, ha.symm ▸ zero_zpow _ hn⟩
lemma zpow_ne_zero {x : G₀} (n : ℤ) : x ≠ 0 → x ^ n ≠ 0 :=
mt zpow_eq_zero
theorem zpow_neg_mul_zpow_self (n : ℤ) {x : G₀} (h : x ≠ 0) :
x ^ (-n) * x ^ n = 1 :=
begin
rw [zpow_neg],
exact inv_mul_cancel (zpow_ne_zero n h)
end
end zpow
section
variables {G₀ : Type*} [comm_group_with_zero G₀]
lemma div_sq_cancel (a b : G₀) : a ^ 2 * b / a = a * b :=
begin
by_cases ha : a = 0,
{ simp [ha] },
rw [sq, mul_assoc, mul_div_cancel_left _ ha]
end
end
/-- If a monoid homomorphism `f` between two `group_with_zero`s maps `0` to `0`, then it maps `x^n`,
`n : ℤ`, to `(f x)^n`. -/
@[simp] lemma map_zpow₀ {F G₀ G₀' : Type*} [group_with_zero G₀] [group_with_zero G₀']
[monoid_with_zero_hom_class F G₀ G₀'] (f : F) (x : G₀) (n : ℤ) :
f (x ^ n) = f x ^ n :=
map_zpow' f (map_inv₀ f) x n
|
The set $s$ is equal to the image of the set $\{0, 1, \ldots, n\}$ under the function $enum$. |
using CAGD
include("./model.jl")
include("./input.jl")
include("./splitting.jl")
include("./congruence.jl")
include("./tgw2.jl")
include("./tgw3.jl")
include("./loops.jl")
include("./utils.jl")
include("./output.jl")
|
function update_status(data::GitHubAutoMergeData; kwargs...)
if data.read_only
@info "`read_only` mode; skipping updating the status"
return nothing
end
return my_retry(
() -> GitHub.create_status(
data.api,
data.registry,
data.current_pr_head_commit_sha;
auth=data.auth,
params=Dict(kwargs...),
),
)
end
|
[STATEMENT]
lemma gauss_cnj_add [simp]:
\<open>cnj (x + y) = cnj x + cnj y\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. cnj (x + y) = cnj x + cnj y
[PROOF STEP]
by (simp add: gauss_eq_iff) |
[STATEMENT]
lemma sepnMT[rule_format]: "p \<noteq> [] \<longrightarrow> (separate p) \<noteq> []"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. p \<noteq> [] \<longrightarrow> separate p \<noteq> []
[PROOF STEP]
by (induct p rule: separate.induct) simp_all |
------------------------------------------------------------------------
-- The Agda standard library
--
-- Bisimilarity for Colists
------------------------------------------------------------------------
{-# OPTIONS --without-K --safe --sized-types #-}
module Codata.Colist.Bisimilarity where
open import Level using (_⊔_)
open import Size
open import Codata.Thunk
open import Codata.Colist
open import Relation.Binary
open import Relation.Binary.PropositionalEquality as Eq using (_≡_)
data Bisim {a b r} {A : Set a} {B : Set b} (R : A → B → Set r) (i : Size) :
(xs : Colist A ∞) (ys : Colist B ∞) → Set (r ⊔ a ⊔ b) where
[] : Bisim R i [] []
_∷_ : ∀ {x y xs ys} → R x y → Thunk^R (Bisim R) i xs ys → Bisim R i (x ∷ xs) (y ∷ ys)
module _ {a r} {A : Set a} {R : A → A → Set r} where
reflexive : Reflexive R → ∀ {i} → Reflexive (Bisim R i)
reflexive refl^R {i} {[]} = []
reflexive refl^R {i} {r ∷ rs} = refl^R ∷ λ where .force → reflexive refl^R
module _ {a b} {A : Set a} {B : Set b}
{r} {P : A → B → Set r} {Q : B → A → Set r} where
symmetric : Sym P Q → ∀ {i} → Sym (Bisim P i) (Bisim Q i)
symmetric sym^PQ [] = []
symmetric sym^PQ (p ∷ ps) = sym^PQ p ∷ λ where .force → symmetric sym^PQ (ps .force)
module _ {a b c} {A : Set a} {B : Set b} {C : Set c}
{r} {P : A → B → Set r} {Q : B → C → Set r} {R : A → C → Set r} where
transitive : Trans P Q R → ∀ {i} → Trans (Bisim P i) (Bisim Q i) (Bisim R i)
transitive trans^PQR [] [] = []
transitive trans^PQR (p ∷ ps) (q ∷ qs) =
trans^PQR p q ∷ λ where .force → transitive trans^PQR (ps .force) (qs .force)
-- Pointwise Equality as a Bisimilarity
------------------------------------------------------------------------
module _ {ℓ} {A : Set ℓ} where
infix 1 _⊢_≈_
_⊢_≈_ : ∀ i → Colist A ∞ → Colist A ∞ → Set ℓ
_⊢_≈_ = Bisim _≡_
refl : ∀ {i} → Reflexive (i ⊢_≈_)
refl = reflexive Eq.refl
sym : ∀ {i} → Symmetric (i ⊢_≈_)
sym = symmetric Eq.sym
trans : ∀ {i} → Transitive (i ⊢_≈_)
trans = transitive Eq.trans
|
Francisco de Saldanha da Gama ( April 5 , 1756 ) – Cardinal @-@ Priest [ no title assigned ] ; patriarch of Lisbon
|
#ifndef OPENMC_VOLUME_CALC_H
#define OPENMC_VOLUME_CALC_H
#include "openmc/position.h"
#include "openmc/tallies/trigger.h"
#include "pugixml.hpp"
#include "xtensor/xtensor.hpp"
#include <array>
#include <string>
#include <vector>
#include <gsl/gsl>
namespace openmc {
//==============================================================================
// Volume calculation class
//==============================================================================
class VolumeCalculation {
public:
// Aliases, types
struct Result {
std::array<double, 2> volume; //!< Mean/standard deviation of volume
std::vector<int> nuclides; //!< Index of nuclides
std::vector<double> atoms; //!< Number of atoms for each nuclide
std::vector<double> uncertainty; //!< Uncertainty on number of atoms
int iterations; //!< Number of iterations needed to obtain the results
}; // Results for a single domain
// Constructors
VolumeCalculation(pugi::xml_node node);
// Methods
//! \brief Stochastically determine the volume of a set of domains along with the
//! average number densities of nuclides within the domain
//
//! \return Vector of results for each user-specified domain
std::vector<Result> execute() const;
//! \brief Write volume calculation results to HDF5 file
//
//! \param[in] filename Path to HDF5 file to write
//! \param[in] results Vector of results for each domain
void to_hdf5(const std::string& filename, const std::vector<Result>& results) const;
// Tally filter and map types
enum class TallyDomain {
UNIVERSE,
MATERIAL,
CELL
};
// Data members
TallyDomain domain_type_; //!< Type of domain (cell, material, etc.)
size_t n_samples_; //!< Number of samples to use
double threshold_ {-1.0}; //!< Error threshold for domain volumes
TriggerMetric trigger_type_ {TriggerMetric::not_active}; //!< Trigger metric for the volume calculation
Position lower_left_; //!< Lower-left position of bounding box
Position upper_right_; //!< Upper-right position of bounding box
std::vector<int> domain_ids_; //!< IDs of domains to find volumes of
private:
//! \brief Check whether a material has already been hit for a given domain.
//! If not, add new entries to the vectors
//
//! \param[in] i_material Index in global materials vector
//! \param[in,out] indices Vector of material indices
//! \param[in,out] hits Number of hits corresponding to each material
void check_hit(int i_material, std::vector<int>& indices,
std::vector<int>& hits) const;
};
//==============================================================================
// Global variables
//==============================================================================
namespace model {
extern std::vector<VolumeCalculation> volume_calcs;
}
//==============================================================================
// Non-member functions
//==============================================================================
void free_memory_volume();
} // namespace openmc
#endif // OPENMC_VOLUME_CALC_H
|
{-# OPTIONS --without-K --safe #-}
module Categories.Category.Instance.Properties.Setoids where
open import Level
open import Relation.Binary using (Setoid; module Setoid; Preorder)
open import Relation.Binary.PropositionalEquality as ≡ using (_≡_)
import Relation.Binary.Reasoning.Setoid as RS
open import Function.Equality using (Π)
open import Relation.Binary.Indexed.Heterogeneous using (_=[_]⇒_)
open import Data.Product using (Σ; proj₁; proj₂; _,_; Σ-syntax; _×_)
import Relation.Binary.Construct.Symmetrize as Symmetrize
open Symmetrize hiding (setoid; trans; sym)
open import Data.Unit using (⊤; tt)
open import Categories.Category using (Category; _[_,_])
open import Categories.Functor
open import Categories.Category.Instance.Setoids
open import Categories.Diagram.Cocone
open import Categories.Category.Construction.Cocones hiding (Cocone)
open import Categories.Diagram.Cone
open import Categories.Category.Complete
open import Categories.Category.Cocomplete
Setoids-Cocomplete : (o ℓ e c ℓ′ : Level) → Cocomplete o ℓ e (Setoids (o ⊔ c) (o ⊔ ℓ ⊔ c ⊔ ℓ′))
Setoids-Cocomplete o ℓ e c ℓ′ {J} F = record { initial = record
{ ⊥ = record
{ N = ⇛-Setoid
; coapex = record
{ ψ = λ j → record
{ _⟨$⟩_ = j ,_
; cong = λ i≈k → disorient (slish (J.id , identity i≈k))
}
; commute = λ {X} X⇒Y x≈y → disorient (slash (X⇒Y , cong (F₁ X⇒Y) (Setoid.sym (F₀ X) x≈y)))
}
}
; ! = λ {A} → record
{ arr = record
{ _⟨$⟩_ = to-coapex A
; cong = λ eq → minimal ⇛-preorder (Cocone.N A) (to-coapex A) (coapex-cong A) eq
}
; commute = λ {X} x≈y → cong (Coapex.ψ (Cocone.coapex A) X) x≈y
}
; !-unique = λ {A} cocone⇒ x⇛y → Setoid.trans (Cocone.N A)
(Setoid.sym (Cocone.N A) (Cocone⇒.commute cocone⇒ (refl (F₀ _))))
(cong (Cocone⇒.arr cocone⇒) x⇛y)
} }
where
open Setoid
open Π
open Functor F
D = Cocones F
module J = Category J
C = Setoids _ _
setoid : J.Obj → Category.Obj C
setoid j = F₀ j
module S (j : J.Obj) = Setoid (setoid j)
open S using () renaming (_≈_ to _[_≈_])
vertex-carrier = Σ[ j ∈ J.Obj ] Carrier (setoid j)
_⇛_ : (x y : vertex-carrier) → Set _
(X , x) ⇛ (Y , y) = Σ[ f ∈ J [ X , Y ] ] ( Y [ (F₁ f ⟨$⟩ x) ≈ y ])
⇛-preorder : Preorder _ _ _
⇛-preorder = record
{ Carrier = vertex-carrier
; _≈_ = _≡_
; _∼_ = _⇛_
; isPreorder = record
{ isEquivalence = ≡.isEquivalence
; reflexive = λ { {i , Fi} {.i , .Fi} ≡.refl → J.id , Functor.identity F (refl (F₀ i))}
; trans = λ { {i , Fi} {j , Fj} {k , Fk} i≈j j≈k → proj₁ j≈k J.∘ proj₁ i≈j ,
let S = F₀ k in
let open RS S in begin
F₁ (proj₁ j≈k J.∘ proj₁ i≈j) ⟨$⟩ Fi ≈⟨ homomorphism (refl (F₀ i)) ⟩
F₁ (proj₁ j≈k) ⟨$⟩ (F₁ (proj₁ i≈j) ⟨$⟩ Fi) ≈⟨ cong (F₁ (proj₁ j≈k)) (proj₂ i≈j) ⟩
F₁ (proj₁ j≈k) ⟨$⟩ Fj ≈⟨ proj₂ j≈k ⟩
Fk ∎}
}
}
⇛-Setoid : Setoid (o ⊔ c) (o ⊔ ℓ ⊔ c ⊔ ℓ′)
⇛-Setoid = Symmetrize.setoid ⇛-preorder
to-coapex : (A : Cocone F) → vertex-carrier → Carrier (Cocone.N A)
to-coapex A (j , Fj) = Cocone.ψ A j ⟨$⟩ Fj
coapex-cong : (A : Cocone F) → _⇛_ =[ to-coapex A ]⇒ (_≈_ (Cocone.N A))
coapex-cong A {X , x} {Y , y} (f , fx≈y) = Setoid.trans A.N
(Setoid.sym A.N (A.commute f (refl (F₀ X))))
(cong (A.ψ Y) fx≈y)
where module A = Cocone A
Setoids-Complete : (o ℓ e c ℓ′ : Level) → Complete o ℓ e (Setoids (ℓ′ ⊔ ℓ ⊔ o) (o ⊔ ℓ′))
Setoids-Complete o ℓ e c ℓ′ {J} F = record { terminal = record
{ ⊤ = record
{ N = record
{ Carrier = Σ
((j : Category.Obj J) → Setoid.Carrier (F₀ j))
(λ P → ∀ {X Y} (f : J [ X , Y ]) → Setoid._≈_ (F₀ Y) (F₁ f Π.⟨$⟩ P X) (P Y))
; _≈_ = λ f g → ∀ (j : Category.Obj J) → Setoid._≈_ (F₀ j) (proj₁ f j) (proj₁ g j)
; isEquivalence = record
{ refl = λ j → Setoid.refl (F₀ j)
; sym = λ a≈b j → Setoid.sym (F₀ j) (a≈b j)
; trans = λ a≈b b≈c j → Setoid.trans (F₀ j) (a≈b j) (b≈c j)
}
}
; apex = record
{ ψ = λ j → record
{ _⟨$⟩_ = λ x → proj₁ x j
; cong = λ x → x j
}
; commute = λ {X} {Y} X⇒Y {x} {y} f≈g → Setoid.trans (F₀ Y) (proj₂ x X⇒Y) (f≈g Y)
}
}
; ! = λ {A} → record
{ arr = record
{ _⟨$⟩_ = λ x → (λ j → ψ A j Π.⟨$⟩ x) , λ {X} {Y} f → commute A f (Setoid.refl (N A))
; cong = λ a≈b j → Π.cong (ψ A j) a≈b
}
; commute = λ {j} x≈y → Π.cong (ψ A j) x≈y
}
; !-unique = λ {A} f x≈y j → Setoid.sym (F₀ j) (Cone⇒.commute f (Setoid.sym (N A) x≈y))
} }
where
open Functor F
S : Category (suc (c ⊔ ℓ)) (c ⊔ ℓ) (c ⊔ ℓ)
S = Setoids c ℓ
open Category S
open Cone
|
function [y, eo_fun] = embed_out(y, Mdim)
%|function [y, eo_fun] = embed_out(y, Mdim)
%|
%| Dual or adjoint of embed_in(). See embed_in() for details.
%| To be used around _back() routines that expect [(M) *L]
%| input and produce [(N) *L] output that then must be reshaped
%| to be either [(N) (L)] or [np *L]
%|
%| in
%| y [*M (L)] or [(M) (L)] input data array(s), possibly as columns
%| Mdim (M)
%| out
%| y [(M) *L] output data arrays
%| eo_fun strum object with methods:
%| x = eo_fun.shape(x, mask, np) reshape x from [(N) *L] to be either
%| [np (L)] or [(N) (L)], depending on y
%|
%| Copyright 2006-12-9, Jeff Fessler, University of Michigan
if nargin < 1, ir_usage, end
if nargin == 1 && streq(y, 'test'), embed_out_test, clear y, return, end
if nargin < 2, Mdim = size(y,1); end % trick: try to guess...
if size(y,1) == prod(Mdim) % convert [*M (L)] to [(M) *L]
state.column = true;
dimy = size(y);
state.diml = dimy(2:end); % [(L)]
y = reshape(y, [Mdim prod(state.diml)]); % [(M) *L]
else % convert [(M) (L)] to [(M) *L]
state.column = false;
dimi = [size(y) 1];
jf_equal(dimi(1:length(Mdim)), Mdim)
state.diml = dimi(length(Mdim)+1:end); % (L) (possibly empty)
y = reshape(y, [Mdim prod(state.diml) 1]); % [(N) *L]
end
eo_fun = strum(state, {'shape', @embed_out_shape});
%
% embed_out_shape()
%
function x = embed_out_shape(state, x, mask, np)
if nargin < 4, np = sum(mask(:)); end
diml = state.diml;
if state.column % column in yields column out, i.e., [(N) *L] to [np (L)]
if any(diml > 1)
x = reshape(x, numel(mask), []); % [*N *L]
x = x(mask,:); % [np *L]
x = reshape(x, [np diml]); % [np (L)]
else
x = x(mask); % [np,1]
end
else % [(N) *L] to [(N) (L)]
if any(diml > 1)
x = reshape(x, [size(mask) diml]); % [(N) (L)]
end
end
%
% embed_out_test
%
function embed_out_test
ig = image_geom('nx', 10, 'ny', 8, 'dx', 1);
ig.mask = ig.circ > 0;
Mdim = [6 7];
y0 = ones(Mdim); % [(M)]
dl = [2 3];
[y2 eo] = embed_out(y0(:), Mdim); % single column
x2 = eo.shape(ig.ones, ig.mask);
jf_equal(size(x2), [ig.np 1])
[y2 eo] = embed_out(y0, Mdim); % usual 2d
x2 = eo.shape(ig.ones, ig.mask);
jf_equal(size(x2), [ig.nx ig.ny])
yr = repmat(y0, [1 1 dl]); % [(M) (L)]
[y2 eo] = embed_out(yr, Mdim);
x2 = eo.shape(ones([ig.nx ig.ny prod(dl)]), ig.mask);
jf_equal(size(x2), [ig.nx ig.ny dl])
yr = repmat(y0(:), [1 dl]); % [*M (L)]
[y2 eo] = embed_out(yr, Mdim);
x2 = eo.shape(ones([ig.nx ig.ny prod(dl)]), ig.mask);
jf_equal(size(x2), [ig.np dl])
|
[STATEMENT]
lemma lset_llist_of_tllist [simp]:
"lset (llist_of_tllist xs) = tset xs" (is "?lhs = ?rhs")
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. lset (llist_of_tllist xs) = tset xs
[PROOF STEP]
proof(intro set_eqI iffI)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>x. x \<in> lset (llist_of_tllist xs) \<Longrightarrow> x \<in> tset xs
2. \<And>x. x \<in> tset xs \<Longrightarrow> x \<in> lset (llist_of_tllist xs)
[PROOF STEP]
fix x
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>x. x \<in> lset (llist_of_tllist xs) \<Longrightarrow> x \<in> tset xs
2. \<And>x. x \<in> tset xs \<Longrightarrow> x \<in> lset (llist_of_tllist xs)
[PROOF STEP]
assume "x \<in> ?lhs"
[PROOF STATE]
proof (state)
this:
x \<in> lset (llist_of_tllist xs)
goal (2 subgoals):
1. \<And>x. x \<in> lset (llist_of_tllist xs) \<Longrightarrow> x \<in> tset xs
2. \<And>x. x \<in> tset xs \<Longrightarrow> x \<in> lset (llist_of_tllist xs)
[PROOF STEP]
thus "x \<in> ?rhs"
[PROOF STATE]
proof (prove)
using this:
x \<in> lset (llist_of_tllist xs)
goal (1 subgoal):
1. x \<in> tset xs
[PROOF STEP]
by(induct "llist_of_tllist xs" arbitrary: xs rule: llist_set_induct)(auto simp: tllist.set_sel(2))
[PROOF STATE]
proof (state)
this:
x \<in> tset xs
goal (1 subgoal):
1. \<And>x. x \<in> tset xs \<Longrightarrow> x \<in> lset (llist_of_tllist xs)
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. x \<in> tset xs \<Longrightarrow> x \<in> lset (llist_of_tllist xs)
[PROOF STEP]
fix x
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. x \<in> tset xs \<Longrightarrow> x \<in> lset (llist_of_tllist xs)
[PROOF STEP]
assume "x \<in> ?rhs"
[PROOF STATE]
proof (state)
this:
x \<in> tset xs
goal (1 subgoal):
1. \<And>x. x \<in> tset xs \<Longrightarrow> x \<in> lset (llist_of_tllist xs)
[PROOF STEP]
thus "x \<in> ?lhs"
[PROOF STATE]
proof (prove)
using this:
x \<in> tset xs
goal (1 subgoal):
1. x \<in> lset (llist_of_tllist xs)
[PROOF STEP]
proof(induct rule: tllist_set_induct)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>xs. \<not> is_TNil xs \<Longrightarrow> thd xs \<in> lset (llist_of_tllist xs)
2. \<And>xs y. \<lbrakk>\<not> is_TNil xs; y \<in> tset (ttl xs); y \<in> lset (llist_of_tllist (ttl xs))\<rbrakk> \<Longrightarrow> y \<in> lset (llist_of_tllist xs)
[PROOF STEP]
case (find xs)
[PROOF STATE]
proof (state)
this:
\<not> is_TNil xs
goal (2 subgoals):
1. \<And>xs. \<not> is_TNil xs \<Longrightarrow> thd xs \<in> lset (llist_of_tllist xs)
2. \<And>xs y. \<lbrakk>\<not> is_TNil xs; y \<in> tset (ttl xs); y \<in> lset (llist_of_tllist (ttl xs))\<rbrakk> \<Longrightarrow> y \<in> lset (llist_of_tllist xs)
[PROOF STEP]
thus ?case
[PROOF STATE]
proof (prove)
using this:
\<not> is_TNil xs
goal (1 subgoal):
1. thd xs \<in> lset (llist_of_tllist xs)
[PROOF STEP]
by(cases xs) auto
[PROOF STATE]
proof (state)
this:
thd xs \<in> lset (llist_of_tllist xs)
goal (1 subgoal):
1. \<And>xs y. \<lbrakk>\<not> is_TNil xs; y \<in> tset (ttl xs); y \<in> lset (llist_of_tllist (ttl xs))\<rbrakk> \<Longrightarrow> y \<in> lset (llist_of_tllist xs)
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>xs y. \<lbrakk>\<not> is_TNil xs; y \<in> tset (ttl xs); y \<in> lset (llist_of_tllist (ttl xs))\<rbrakk> \<Longrightarrow> y \<in> lset (llist_of_tllist xs)
[PROOF STEP]
case step
[PROOF STATE]
proof (state)
this:
\<not> is_TNil xs_
y_ \<in> tset (ttl xs_)
y_ \<in> lset (llist_of_tllist (ttl xs_))
goal (1 subgoal):
1. \<And>xs y. \<lbrakk>\<not> is_TNil xs; y \<in> tset (ttl xs); y \<in> lset (llist_of_tllist (ttl xs))\<rbrakk> \<Longrightarrow> y \<in> lset (llist_of_tllist xs)
[PROOF STEP]
thus ?case
[PROOF STATE]
proof (prove)
using this:
\<not> is_TNil xs_
y_ \<in> tset (ttl xs_)
y_ \<in> lset (llist_of_tllist (ttl xs_))
goal (1 subgoal):
1. y_ \<in> lset (llist_of_tllist xs_)
[PROOF STEP]
by(auto simp add: ltl_llist_of_tllist[symmetric] simp del: ltl_llist_of_tllist dest: in_lset_ltlD)
[PROOF STATE]
proof (state)
this:
y_ \<in> lset (llist_of_tllist xs_)
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
x \<in> lset (llist_of_tllist xs)
goal:
No subgoals!
[PROOF STEP]
qed |
[STATEMENT]
lemma coeff_Poly: "coeff (Poly xs) i = (nth_default 0 xs i)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. coeff (Poly xs) i = nth_default (0::'a) xs i
[PROOF STEP]
unfolding nth_default_coeffs_eq[of "Poly xs", symmetric] coeffs_Poly
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. nth_default (0::'a) (strip_while ((=) (0::'a)) xs) i = nth_default (0::'a) xs i
[PROOF STEP]
by simp |
[GOAL]
α : Type u_1
β : Type u_2
inst✝ : Preorder α
s t : Set α
Ixx : α → α → Set α
⊢ Tendsto (fun p => Ixx p.fst p.snd) (𝓟 s ×ˢ 𝓟 s) (smallSets (𝓟 t)) ↔ ∀ (x : α), x ∈ s → ∀ (y : α), y ∈ s → Ixx x y ⊆ t
[PROOFSTEP]
simp only [smallSets_principal, prod_principal_principal, tendsto_principal_principal, forall_prod_set,
mem_powerset_iff, mem_principal]
[GOAL]
α : Type u_1
β : Type u_2
inst✝ : Preorder α
l₁ l₁' l₂ l₂' : Filter α
Ixx : α → α → Set α
h : TendstoIxxClass Ixx l₁ l₂
h' : TendstoIxxClass Ixx l₁' l₂'
⊢ Tendsto (fun p => Ixx p.fst p.snd) ((l₁ ⊓ l₁') ×ˢ (l₁ ⊓ l₁')) (smallSets (l₂ ⊓ l₂'))
[PROOFSTEP]
simpa only [prod_inf_prod, smallSets_inf] using h.1.inf h'.1
[GOAL]
α : Type u_1
β : Type u_2
inst✝ : PartialOrder α
a : α
⊢ TendstoIxxClass Icc (pure a) (pure a)
[PROOFSTEP]
rw [← principal_singleton]
[GOAL]
α : Type u_1
β : Type u_2
inst✝ : PartialOrder α
a : α
⊢ TendstoIxxClass Icc (𝓟 {a}) (𝓟 {a})
[PROOFSTEP]
exact tendstoIxxClass_principal.2 ordConnected_singleton.out
[GOAL]
α : Type u_1
β : Type u_2
inst✝ : PartialOrder α
a : α
⊢ Tendsto (fun p => Ico p.fst p.snd) (pure a ×ˢ pure a) (smallSets ⊥)
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
β : Type u_2
inst✝ : PartialOrder α
a : α
⊢ Tendsto (fun p => Ioc p.fst p.snd) (pure a ×ˢ pure a) (smallSets ⊥)
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
β : Type u_2
inst✝ : PartialOrder α
a : α
⊢ Tendsto (fun p => Ioo p.fst p.snd) (pure a ×ˢ pure a) (smallSets ⊥)
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
l : Filter α
inst✝ : TendstoIxxClass Icc l l
⊢ TendstoIxxClass uIcc l l
[PROOFSTEP]
refine' ⟨fun s hs => mem_map.2 <| mem_prod_self_iff.2 _⟩
[GOAL]
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
l : Filter α
inst✝ : TendstoIxxClass Icc l l
s : Set (Set α)
hs : s ∈ smallSets l
⊢ ∃ t, t ∈ l ∧ t ×ˢ t ⊆ (fun p => [[p.fst, p.snd]]) ⁻¹' s
[PROOFSTEP]
obtain ⟨t, htl, hts⟩ : ∃ t ∈ l, ∀ p ∈ (t : Set α) ×ˢ t, Icc (p : α × α).1 p.2 ∈ s
[GOAL]
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
l : Filter α
inst✝ : TendstoIxxClass Icc l l
s : Set (Set α)
hs : s ∈ smallSets l
⊢ ∃ t, t ∈ l ∧ ∀ (p : α × α), p ∈ t ×ˢ t → Icc p.fst p.snd ∈ s
case intro.intro
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
l : Filter α
inst✝ : TendstoIxxClass Icc l l
s : Set (Set α)
hs : s ∈ smallSets l
t : Set α
htl : t ∈ l
hts : ∀ (p : α × α), p ∈ t ×ˢ t → Icc p.fst p.snd ∈ s
⊢ ∃ t, t ∈ l ∧ t ×ˢ t ⊆ (fun p => [[p.fst, p.snd]]) ⁻¹' s
[PROOFSTEP]
exact mem_prod_self_iff.1 (mem_map.1 (tendsto_fst.Icc tendsto_snd hs))
[GOAL]
case intro.intro
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
l : Filter α
inst✝ : TendstoIxxClass Icc l l
s : Set (Set α)
hs : s ∈ smallSets l
t : Set α
htl : t ∈ l
hts : ∀ (p : α × α), p ∈ t ×ˢ t → Icc p.fst p.snd ∈ s
⊢ ∃ t, t ∈ l ∧ t ×ˢ t ⊆ (fun p => [[p.fst, p.snd]]) ⁻¹' s
[PROOFSTEP]
refine' ⟨t, htl, fun p hp => _⟩
[GOAL]
case intro.intro
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
l : Filter α
inst✝ : TendstoIxxClass Icc l l
s : Set (Set α)
hs : s ∈ smallSets l
t : Set α
htl : t ∈ l
hts : ∀ (p : α × α), p ∈ t ×ˢ t → Icc p.fst p.snd ∈ s
p : α × α
hp : p ∈ t ×ˢ t
⊢ p ∈ (fun p => [[p.fst, p.snd]]) ⁻¹' s
[PROOFSTEP]
cases' le_total p.1 p.2 with h h
[GOAL]
case intro.intro.inl
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
l : Filter α
inst✝ : TendstoIxxClass Icc l l
s : Set (Set α)
hs : s ∈ smallSets l
t : Set α
htl : t ∈ l
hts : ∀ (p : α × α), p ∈ t ×ˢ t → Icc p.fst p.snd ∈ s
p : α × α
hp : p ∈ t ×ˢ t
h : p.fst ≤ p.snd
⊢ p ∈ (fun p => [[p.fst, p.snd]]) ⁻¹' s
[PROOFSTEP]
rw [mem_preimage, uIcc_of_le h]
[GOAL]
case intro.intro.inl
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
l : Filter α
inst✝ : TendstoIxxClass Icc l l
s : Set (Set α)
hs : s ∈ smallSets l
t : Set α
htl : t ∈ l
hts : ∀ (p : α × α), p ∈ t ×ˢ t → Icc p.fst p.snd ∈ s
p : α × α
hp : p ∈ t ×ˢ t
h : p.fst ≤ p.snd
⊢ Icc p.fst p.snd ∈ s
[PROOFSTEP]
exact hts p hp
[GOAL]
case intro.intro.inr
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
l : Filter α
inst✝ : TendstoIxxClass Icc l l
s : Set (Set α)
hs : s ∈ smallSets l
t : Set α
htl : t ∈ l
hts : ∀ (p : α × α), p ∈ t ×ˢ t → Icc p.fst p.snd ∈ s
p : α × α
hp : p ∈ t ×ˢ t
h : p.snd ≤ p.fst
⊢ p ∈ (fun p => [[p.fst, p.snd]]) ⁻¹' s
[PROOFSTEP]
rw [mem_preimage, uIcc_of_ge h]
[GOAL]
case intro.intro.inr
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
l : Filter α
inst✝ : TendstoIxxClass Icc l l
s : Set (Set α)
hs : s ∈ smallSets l
t : Set α
htl : t ∈ l
hts : ∀ (p : α × α), p ∈ t ×ˢ t → Icc p.fst p.snd ∈ s
p : α × α
hp : p ∈ t ×ˢ t
h : p.snd ≤ p.fst
⊢ Icc p.snd p.fst ∈ s
[PROOFSTEP]
exact hts ⟨p.2, p.1⟩ ⟨hp.2, hp.1⟩
|
{-# LANGUAGE TypeFamilies #-}
-- | The "pair of vectors" implementation of vectors of dual numbers.
-- This is much faster than "vector of pairs" implementation, but terribly
-- hard to use in case of scalar dual numbers, in particular to efficiently
-- construct in @ST@ such pairs of vectors from monadic operations that create
-- vector elements (a bit easier in @IO@, but so far we managed to avoid @IO@).
-- For this reason, this representation is currently used only to represent
-- the inputs of functions, that is, dual numbers with initial values
-- of parameters and, in case of dual components that are delta-expressions,
-- with @Delta@ variables assigned to each.
module HordeAd.Core.PairOfVectors
( DualNumberVariables
, makeDualNumberVariables, var0, vars, var1, var2, varX, varS
, ifoldMDual', foldMDual', ifoldlDual', foldlDual'
) where
import Prelude
import qualified Data.Array.DynamicS as OT
import qualified Data.Array.ShapedS as OS
import qualified Data.Strict.Vector as Data.Vector
import qualified Data.Vector.Generic as V
import GHC.Exts (inline)
import Numeric.LinearAlgebra (Matrix, Vector)
import HordeAd.Core.DualClass (Dual)
import HordeAd.Core.DualNumber
-- These are optimized as "pair of vectors" representing vectors of @DualNumber@
-- in an efficient way (especially, or only, with gradient descent,
-- where the vectors are reused in some ways).
type DualNumberVariables d r =
( Domain0 r
, Data.Vector.Vector (Dual d r)
, Domain1 r
, Data.Vector.Vector (Dual d (Vector r))
, Domain2 r
, Data.Vector.Vector (Dual d (Matrix r))
, DomainX r
, Data.Vector.Vector (Dual d (OT.Array r))
)
makeDualNumberVariables
:: Domains r
-> ( Data.Vector.Vector (Dual d r)
, Data.Vector.Vector (Dual d (Vector r))
, Data.Vector.Vector (Dual d (Matrix r))
, Data.Vector.Vector (Dual d (OT.Array r)) )
-> DualNumberVariables d r
{-# INLINE makeDualNumberVariables #-}
makeDualNumberVariables (params0, params1, params2, paramsX)
(vs0, vs1, vs2, vsX)
= (params0, vs0, params1, vs1, params2, vs2, paramsX, vsX)
var0 :: IsScalar d r => DualNumberVariables d r -> Int -> DualNumber d r
var0 (vValue, vVar, _, _, _, _, _, _) i = D (vValue V.! i) (vVar V.! i)
-- Unsafe, but handy for toy examples.
vars :: IsScalar d r => DualNumberVariables d r -> [DualNumber d r]
vars vec = map ( var0 vec) [0 ..]
var1 :: DualNumberVariables d r -> Int -> DualNumber d (Vector r)
var1 (_, _, vValue, vVar, _, _, _, _) i = D (vValue V.! i) (vVar V.! i)
var2 :: DualNumberVariables d r -> Int -> DualNumber d (Matrix r)
var2 (_, _, _, _, vValue, vVar, _, _) i = D (vValue V.! i) (vVar V.! i)
varX :: DualNumberVariables d r -> Int -> DualNumber d (OT.Array r)
varX (_, _, _, _, _, _, vValue, vVar) i = D (vValue V.! i) (vVar V.! i)
varS :: (IsScalar d r, OS.Shape sh)
=> DualNumberVariables d r -> Int -> DualNumber d (OS.Array sh r)
varS (_, _, _, _, _, _, vValue, vVar) i =
inline fromXS $ D (vValue V.! i) (vVar V.! i)
ifoldMDual' :: forall a d r m. (Monad m, IsScalar d r)
=> (a -> Int -> DualNumber d r -> m a)
-> a
-> DualNumberVariables d r
-> m a
{-# INLINE ifoldMDual' #-}
ifoldMDual' f a (vecR, vecD, _, _, _, _, _, _) = do
let g :: a -> Int -> r -> m a
g !acc i valX = do
let !b = D valX (vecD V.! i)
f acc i b
V.ifoldM' g a vecR
foldMDual' :: forall a d r m. (Monad m, IsScalar d r)
=> (a -> DualNumber d r -> m a)
-> a
-> DualNumberVariables d r
-> m a
{-# INLINE foldMDual' #-}
foldMDual' f a (vecR, vecD, _, _, _, _, _, _) = do
let g :: a -> Int -> r -> m a
g !acc i valX = do
let !b = D valX (vecD V.! i)
f acc b
V.ifoldM' g a vecR
ifoldlDual' :: forall a d r. IsScalar d r
=> (a -> Int -> DualNumber d r -> a)
-> a
-> DualNumberVariables d r
-> a
{-# INLINE ifoldlDual' #-}
ifoldlDual' f a (vecR, vecD, _, _, _, _, _, _) = do
let g :: a -> Int -> r -> a
g !acc i valX =
let !b = D valX (vecD V.! i)
in f acc i b
V.ifoldl' g a vecR
foldlDual' :: forall a d r. IsScalar d r
=> (a -> DualNumber d r -> a)
-> a
-> DualNumberVariables d r
-> a
{-# INLINE foldlDual' #-}
foldlDual' f a (vecR, vecD, _, _, _, _, _, _) = do
let g :: a -> Int -> r -> a
g !acc i valX =
let !b = D valX (vecD V.! i)
in f acc b
V.ifoldl' g a vecR
|
{-# OPTIONS --safe --warning=error --without-K #-}
open import LogicalFormulae
open import Setoids.Setoids
open import Functions.Definition
open import Sets.EquivalenceRelations
open import Rings.Definition
module Rings.Divisible.Lemmas {a b : _} {A : Set a} {S : Setoid {a} {b} A} {_+_ _*_ : A → A → A} (R : Ring S _+_ _*_) where
open Setoid S
open Equivalence eq
open Ring R
open import Rings.Divisible.Definition R
open import Rings.Units.Definition R
divisionTransitive : (x y z : A) → x ∣ y → y ∣ z → x ∣ z
divisionTransitive x y z (a , pr) (b , pr2) = (a * b) , transitive (transitive *Associative (*WellDefined pr reflexive)) pr2
divisionReflexive : (x : A) → x ∣ x
divisionReflexive x = 1R , transitive *Commutative identIsIdent
everythingDividesZero : (r : A) → r ∣ 0R
everythingDividesZero r = 0R , timesZero
nonzeroInherits : {x y : A} (nz : (x ∼ 0R) → False) → y ∣ x → (y ∼ 0R) → False
nonzeroInherits {x} {y} nz (c , pr) y=0 = nz (transitive (symmetric pr) (transitive (*WellDefined y=0 reflexive) (transitive *Commutative timesZero)))
nonunitInherits : {x y : A} (nonunit : Unit x → False) → x ∣ y → Unit y → False
nonunitInherits nu (s , pr) (a , b) = nu ((s * a) , transitive (transitive *Associative (*WellDefined pr reflexive)) b)
|
#! /usr/bin/env python3
"A script to perform the linear regression and create the plot."
#REF https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.drop_duplicates.html
#REF https://towardsdatascience.com/how-to-export-pandas-dataframe-to-csv-2038e43d9c03
#### Create Dataframe:
import pandas as pd
import numpy as np
# Import data from .csv file
df = pd.read_csv('C.search-immune-defense-dmel-FlyBase_IDs.txt', delimiter = "\t")
#print(df)
df1 = df.drop_duplicates()
df1.to_csv('D.search-immune-defense-unique-dmel.csv', index=False)
|
[GOAL]
J : Type w
X✝ Y✝ : WalkingParallelFamily J
f : X✝ ⟶ Y✝
⊢ f ≫ 𝟙 Y✝ = f
[PROOFSTEP]
cases f
[GOAL]
case id
J : Type w
X✝ : WalkingParallelFamily J
⊢ Hom.id X✝ ≫ 𝟙 X✝ = Hom.id X✝
[PROOFSTEP]
aesop_cat
[GOAL]
case line
J : Type w
x✝ : J
⊢ line x✝ ≫ 𝟙 one = line x✝
[PROOFSTEP]
aesop_cat
[GOAL]
J : Type w
W✝ X✝ Y✝ Z✝ : WalkingParallelFamily J
f : W✝ ⟶ X✝
g : X✝ ⟶ Y✝
h : Y✝ ⟶ Z✝
⊢ (f ≫ g) ≫ h = f ≫ g ≫ h
[PROOFSTEP]
cases f
[GOAL]
case id
J : Type w
W✝ Y✝ Z✝ : WalkingParallelFamily J
h : Y✝ ⟶ Z✝
g : W✝ ⟶ Y✝
⊢ (Hom.id W✝ ≫ g) ≫ h = Hom.id W✝ ≫ g ≫ h
[PROOFSTEP]
cases g
[GOAL]
case line
J : Type w
Y✝ Z✝ : WalkingParallelFamily J
h : Y✝ ⟶ Z✝
x✝ : J
g : one ⟶ Y✝
⊢ (line x✝ ≫ g) ≫ h = line x✝ ≫ g ≫ h
[PROOFSTEP]
cases g
[GOAL]
case id.id
J : Type w
W✝ Z✝ : WalkingParallelFamily J
h : W✝ ⟶ Z✝
⊢ (Hom.id W✝ ≫ Hom.id W✝) ≫ h = Hom.id W✝ ≫ Hom.id W✝ ≫ h
[PROOFSTEP]
cases h
[GOAL]
case id.line
J : Type w
Z✝ : WalkingParallelFamily J
x✝ : J
h : one ⟶ Z✝
⊢ (Hom.id zero ≫ line x✝) ≫ h = Hom.id zero ≫ line x✝ ≫ h
[PROOFSTEP]
cases h
[GOAL]
case line.id
J : Type w
Z✝ : WalkingParallelFamily J
x✝ : J
h : one ⟶ Z✝
⊢ (line x✝ ≫ Hom.id one) ≫ h = line x✝ ≫ Hom.id one ≫ h
[PROOFSTEP]
cases h
[GOAL]
case id.id.id
J : Type w
W✝ : WalkingParallelFamily J
⊢ (Hom.id W✝ ≫ Hom.id W✝) ≫ Hom.id W✝ = Hom.id W✝ ≫ Hom.id W✝ ≫ Hom.id W✝
[PROOFSTEP]
aesop_cat
[GOAL]
case id.id.line
J : Type w
x✝ : J
⊢ (Hom.id zero ≫ Hom.id zero) ≫ line x✝ = Hom.id zero ≫ Hom.id zero ≫ line x✝
[PROOFSTEP]
aesop_cat
[GOAL]
case id.line.id
J : Type w
x✝ : J
⊢ (Hom.id zero ≫ line x✝) ≫ Hom.id one = Hom.id zero ≫ line x✝ ≫ Hom.id one
[PROOFSTEP]
aesop_cat
[GOAL]
case line.id.id
J : Type w
x✝ : J
⊢ (line x✝ ≫ Hom.id one) ≫ Hom.id one = line x✝ ≫ Hom.id one ≫ Hom.id one
[PROOFSTEP]
aesop_cat
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
⊢ ∀ {X_1 Y_1 Z : WalkingParallelFamily J} (f_1 : X_1 ⟶ Y_1) (g : Y_1 ⟶ Z),
{ obj := fun x => WalkingParallelFamily.casesOn x X Y,
map := fun {x y} h =>
match x, y, h with
| x, .(x), Hom.id .(x) => 𝟙 ((fun x => WalkingParallelFamily.casesOn x X Y) x)
| .(zero), .(one), line j => f j }.map
(f_1 ≫ g) =
{ obj := fun x => WalkingParallelFamily.casesOn x X Y,
map := fun {x y} h =>
match x, y, h with
| x, .(x), Hom.id .(x) => 𝟙 ((fun x => WalkingParallelFamily.casesOn x X Y) x)
| .(zero), .(one), line j => f j }.map
f_1 ≫
{ obj := fun x => WalkingParallelFamily.casesOn x X Y,
map := fun {x y} h =>
match x, y, h with
| x, .(x), Hom.id .(x) => 𝟙 ((fun x => WalkingParallelFamily.casesOn x X Y) x)
| .(zero), .(one), line j => f j }.map
g
[PROOFSTEP]
rintro _ _ _ ⟨⟩ ⟨⟩
[GOAL]
case id.id
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
X✝ : WalkingParallelFamily J
⊢ { obj := fun x => WalkingParallelFamily.casesOn x X Y,
map := fun {x y} h =>
match x, y, h with
| x, .(x), Hom.id .(x) => 𝟙 ((fun x => WalkingParallelFamily.casesOn x X Y) x)
| .(zero), .(one), line j => f j }.map
(Hom.id X✝ ≫ Hom.id X✝) =
{ obj := fun x => WalkingParallelFamily.casesOn x X Y,
map := fun {x y} h =>
match x, y, h with
| x, .(x), Hom.id .(x) => 𝟙 ((fun x => WalkingParallelFamily.casesOn x X Y) x)
| .(zero), .(one), line j => f j }.map
(Hom.id X✝) ≫
{ obj := fun x => WalkingParallelFamily.casesOn x X Y,
map := fun {x y} h =>
match x, y, h with
| x, .(x), Hom.id .(x) => 𝟙 ((fun x => WalkingParallelFamily.casesOn x X Y) x)
| .(zero), .(one), line j => f j }.map
(Hom.id X✝)
[PROOFSTEP]
aesop_cat
[GOAL]
case id.line
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
x✝ : J
⊢ { obj := fun x => WalkingParallelFamily.casesOn x X Y,
map := fun {x y} h =>
match x, y, h with
| x, .(x), Hom.id .(x) => 𝟙 ((fun x => WalkingParallelFamily.casesOn x X Y) x)
| .(zero), .(one), line j => f j }.map
(Hom.id zero ≫ line x✝) =
{ obj := fun x => WalkingParallelFamily.casesOn x X Y,
map := fun {x y} h =>
match x, y, h with
| x, .(x), Hom.id .(x) => 𝟙 ((fun x => WalkingParallelFamily.casesOn x X Y) x)
| .(zero), .(one), line j => f j }.map
(Hom.id zero) ≫
{ obj := fun x => WalkingParallelFamily.casesOn x X Y,
map := fun {x y} h =>
match x, y, h with
| x, .(x), Hom.id .(x) => 𝟙 ((fun x => WalkingParallelFamily.casesOn x X Y) x)
| .(zero), .(one), line j => f j }.map
(line x✝)
[PROOFSTEP]
aesop_cat
[GOAL]
case line.id
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
x✝ : J
⊢ { obj := fun x => WalkingParallelFamily.casesOn x X Y,
map := fun {x y} h =>
match x, y, h with
| x, .(x), Hom.id .(x) => 𝟙 ((fun x => WalkingParallelFamily.casesOn x X Y) x)
| .(zero), .(one), line j => f j }.map
(line x✝ ≫ Hom.id one) =
{ obj := fun x => WalkingParallelFamily.casesOn x X Y,
map := fun {x y} h =>
match x, y, h with
| x, .(x), Hom.id .(x) => 𝟙 ((fun x => WalkingParallelFamily.casesOn x X Y) x)
| .(zero), .(one), line j => f j }.map
(line x✝) ≫
{ obj := fun x => WalkingParallelFamily.casesOn x X Y,
map := fun {x y} h =>
match x, y, h with
| x, .(x), Hom.id .(x) => 𝟙 ((fun x => WalkingParallelFamily.casesOn x X Y) x)
| .(zero), .(one), line j => f j }.map
(Hom.id one)
[PROOFSTEP]
aesop_cat
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
j : WalkingParallelFamily J
⊢ F.obj j = (parallelFamily fun j => F.map (line j)).obj j
[PROOFSTEP]
cases j
[GOAL]
case zero
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
⊢ F.obj zero = (parallelFamily fun j => F.map (line j)).obj zero
[PROOFSTEP]
aesop_cat
[GOAL]
case one
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
⊢ F.obj one = (parallelFamily fun j => F.map (line j)).obj one
[PROOFSTEP]
aesop_cat
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
⊢ ∀ {X Y : WalkingParallelFamily J} (f : X ⟶ Y),
F.map f ≫ ((fun j => eqToIso (_ : F.obj j = (parallelFamily fun j => F.map (line j)).obj j)) Y).hom =
((fun j => eqToIso (_ : F.obj j = (parallelFamily fun j => F.map (line j)).obj j)) X).hom ≫
(parallelFamily fun j => F.map (line j)).map f
[PROOFSTEP]
rintro _ _ (_ | _)
[GOAL]
case id
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
X✝ : WalkingParallelFamily J
⊢ F.map (Hom.id X✝) ≫ ((fun j => eqToIso (_ : F.obj j = (parallelFamily fun j => F.map (line j)).obj j)) X✝).hom =
((fun j => eqToIso (_ : F.obj j = (parallelFamily fun j => F.map (line j)).obj j)) X✝).hom ≫
(parallelFamily fun j => F.map (line j)).map (Hom.id X✝)
[PROOFSTEP]
aesop_cat
[GOAL]
case line
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
x✝ : J
⊢ F.map (line x✝) ≫ ((fun j => eqToIso (_ : F.obj j = (parallelFamily fun j => F.map (line j)).obj j)) one).hom =
((fun j => eqToIso (_ : F.obj j = (parallelFamily fun j => F.map (line j)).obj j)) zero).hom ≫
(parallelFamily fun j => F.map (line j)).map (line x✝)
[PROOFSTEP]
aesop_cat
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X✝ Y : C
f : J → (X✝ ⟶ Y)
X : WalkingParallelFamily (ULift Bool)
⊢ (𝟭 (WalkingParallelFamily (ULift Bool))).obj X =
((parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right) ⋙
parallelPair (line { down := true }) (line { down := false })).obj
X
[PROOFSTEP]
cases X
[GOAL]
case zero
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
⊢ (𝟭 (WalkingParallelFamily (ULift Bool))).obj zero =
((parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right) ⋙
parallelPair (line { down := true }) (line { down := false })).obj
zero
[PROOFSTEP]
rfl
[GOAL]
case one
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
⊢ (𝟭 (WalkingParallelFamily (ULift Bool))).obj one =
((parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right) ⋙
parallelPair (line { down := true }) (line { down := false })).obj
one
[PROOFSTEP]
rfl
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
⊢ ∀ {X Y : WalkingParallelFamily (ULift Bool)} (f : X ⟶ Y),
(𝟭 (WalkingParallelFamily (ULift Bool))).map f ≫
((fun X =>
eqToIso
(_ :
(𝟭 (WalkingParallelFamily (ULift Bool))).obj X =
((parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right) ⋙
parallelPair (line { down := true }) (line { down := false })).obj
X))
Y).hom =
((fun X =>
eqToIso
(_ :
(𝟭 (WalkingParallelFamily (ULift Bool))).obj X =
((parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right) ⋙
parallelPair (line { down := true }) (line { down := false })).obj
X))
X).hom ≫
((parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right) ⋙
parallelPair (line { down := true }) (line { down := false })).map
f
[PROOFSTEP]
rintro _ _ (_ | ⟨_ | _⟩)
[GOAL]
case id
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
X✝ : WalkingParallelFamily (ULift Bool)
⊢ (𝟭 (WalkingParallelFamily (ULift Bool))).map (Hom.id X✝) ≫
((fun X =>
eqToIso
(_ :
(𝟭 (WalkingParallelFamily (ULift Bool))).obj X =
((parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right) ⋙
parallelPair (line { down := true }) (line { down := false })).obj
X))
X✝).hom =
((fun X =>
eqToIso
(_ :
(𝟭 (WalkingParallelFamily (ULift Bool))).obj X =
((parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right) ⋙
parallelPair (line { down := true }) (line { down := false })).obj
X))
X✝).hom ≫
((parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right) ⋙
parallelPair (line { down := true }) (line { down := false })).map
(Hom.id X✝)
[PROOFSTEP]
aesop_cat
[GOAL]
case line.up.false
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
⊢ (𝟭 (WalkingParallelFamily (ULift Bool))).map (line { down := false }) ≫
((fun X =>
eqToIso
(_ :
(𝟭 (WalkingParallelFamily (ULift Bool))).obj X =
((parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right) ⋙
parallelPair (line { down := true }) (line { down := false })).obj
X))
one).hom =
((fun X =>
eqToIso
(_ :
(𝟭 (WalkingParallelFamily (ULift Bool))).obj X =
((parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right) ⋙
parallelPair (line { down := true }) (line { down := false })).obj
X))
zero).hom ≫
((parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right) ⋙
parallelPair (line { down := true }) (line { down := false })).map
(line { down := false })
[PROOFSTEP]
aesop_cat
[GOAL]
case line.up.true
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
⊢ (𝟭 (WalkingParallelFamily (ULift Bool))).map (line { down := true }) ≫
((fun X =>
eqToIso
(_ :
(𝟭 (WalkingParallelFamily (ULift Bool))).obj X =
((parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right) ⋙
parallelPair (line { down := true }) (line { down := false })).obj
X))
one).hom =
((fun X =>
eqToIso
(_ :
(𝟭 (WalkingParallelFamily (ULift Bool))).obj X =
((parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right) ⋙
parallelPair (line { down := true }) (line { down := false })).obj
X))
zero).hom ≫
((parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right) ⋙
parallelPair (line { down := true }) (line { down := false })).map
(line { down := true })
[PROOFSTEP]
aesop_cat
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X✝ Y : C
f : J → (X✝ ⟶ Y)
X : WalkingParallelPair
⊢ (parallelPair (line { down := true }) (line { down := false }) ⋙
parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj
X =
(𝟭 WalkingParallelPair).obj X
[PROOFSTEP]
cases X
[GOAL]
case zero
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
⊢ (parallelPair (line { down := true }) (line { down := false }) ⋙
parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj
WalkingParallelPair.zero =
(𝟭 WalkingParallelPair).obj WalkingParallelPair.zero
[PROOFSTEP]
rfl
[GOAL]
case one
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
⊢ (parallelPair (line { down := true }) (line { down := false }) ⋙
parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj
WalkingParallelPair.one =
(𝟭 WalkingParallelPair).obj WalkingParallelPair.one
[PROOFSTEP]
rfl
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
⊢ ∀ {X Y : WalkingParallelPair} (f : X ⟶ Y),
(parallelPair (line { down := true }) (line { down := false }) ⋙
parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).map
f ≫
((fun X =>
eqToIso
(_ :
(parallelPair (line { down := true }) (line { down := false }) ⋙
parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj
X =
(𝟭 WalkingParallelPair).obj X))
Y).hom =
((fun X =>
eqToIso
(_ :
(parallelPair (line { down := true }) (line { down := false }) ⋙
parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj
X =
(𝟭 WalkingParallelPair).obj X))
X).hom ≫
(𝟭 WalkingParallelPair).map f
[PROOFSTEP]
rintro _ _ (_ | _ | _)
[GOAL]
case left
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
⊢ (parallelPair (line { down := true }) (line { down := false }) ⋙
parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).map
WalkingParallelPairHom.left ≫
((fun X =>
eqToIso
(_ :
(parallelPair (line { down := true }) (line { down := false }) ⋙
parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj
X =
(𝟭 WalkingParallelPair).obj X))
WalkingParallelPair.one).hom =
((fun X =>
eqToIso
(_ :
(parallelPair (line { down := true }) (line { down := false }) ⋙
parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj
X =
(𝟭 WalkingParallelPair).obj X))
WalkingParallelPair.zero).hom ≫
(𝟭 WalkingParallelPair).map WalkingParallelPairHom.left
[PROOFSTEP]
aesop_cat
[GOAL]
case right
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
⊢ (parallelPair (line { down := true }) (line { down := false }) ⋙
parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).map
WalkingParallelPairHom.right ≫
((fun X =>
eqToIso
(_ :
(parallelPair (line { down := true }) (line { down := false }) ⋙
parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj
X =
(𝟭 WalkingParallelPair).obj X))
WalkingParallelPair.one).hom =
((fun X =>
eqToIso
(_ :
(parallelPair (line { down := true }) (line { down := false }) ⋙
parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj
X =
(𝟭 WalkingParallelPair).obj X))
WalkingParallelPair.zero).hom ≫
(𝟭 WalkingParallelPair).map WalkingParallelPairHom.right
[PROOFSTEP]
aesop_cat
[GOAL]
case id
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
X✝ : WalkingParallelPair
⊢ (parallelPair (line { down := true }) (line { down := false }) ⋙
parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).map
(WalkingParallelPairHom.id X✝) ≫
((fun X =>
eqToIso
(_ :
(parallelPair (line { down := true }) (line { down := false }) ⋙
parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj
X =
(𝟭 WalkingParallelPair).obj X))
X✝).hom =
((fun X =>
eqToIso
(_ :
(parallelPair (line { down := true }) (line { down := false }) ⋙
parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj
X =
(𝟭 WalkingParallelPair).obj X))
X✝).hom ≫
(𝟭 WalkingParallelPair).map (WalkingParallelPairHom.id X✝)
[PROOFSTEP]
aesop_cat
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
⊢ ∀ (X : WalkingParallelFamily (ULift Bool)),
(parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).map
(NatTrans.app
(NatIso.ofComponents fun X =>
eqToIso
(_ :
(𝟭 (WalkingParallelFamily (ULift Bool))).obj X =
((parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right) ⋙
parallelPair (line { down := true }) (line { down := false })).obj
X)).hom
X) ≫
NatTrans.app
(NatIso.ofComponents fun X =>
eqToIso
(_ :
(parallelPair (line { down := true }) (line { down := false }) ⋙
parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj
X =
(𝟭 WalkingParallelPair).obj X)).hom
((parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj
X) =
𝟙 ((parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj X)
[PROOFSTEP]
rintro (_ | _)
[GOAL]
case zero
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
⊢ (parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).map
(NatTrans.app
(NatIso.ofComponents fun X =>
eqToIso
(_ :
(𝟭 (WalkingParallelFamily (ULift Bool))).obj X =
((parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right) ⋙
parallelPair (line { down := true }) (line { down := false })).obj
X)).hom
zero) ≫
NatTrans.app
(NatIso.ofComponents fun X =>
eqToIso
(_ :
(parallelPair (line { down := true }) (line { down := false }) ⋙
parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj
X =
(𝟭 WalkingParallelPair).obj X)).hom
((parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj
zero) =
𝟙 ((parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj zero)
[PROOFSTEP]
aesop_cat
[GOAL]
case one
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
⊢ (parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).map
(NatTrans.app
(NatIso.ofComponents fun X =>
eqToIso
(_ :
(𝟭 (WalkingParallelFamily (ULift Bool))).obj X =
((parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right) ⋙
parallelPair (line { down := true }) (line { down := false })).obj
X)).hom
one) ≫
NatTrans.app
(NatIso.ofComponents fun X =>
eqToIso
(_ :
(parallelPair (line { down := true }) (line { down := false }) ⋙
parallelFamily fun p =>
bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj
X =
(𝟭 WalkingParallelPair).obj X)).hom
((parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj
one) =
𝟙 ((parallelFamily fun p => bif p.down then WalkingParallelPairHom.left else WalkingParallelPairHom.right).obj one)
[PROOFSTEP]
aesop_cat
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
s : Trident f
j : J
⊢ NatTrans.app s.π zero ≫ f j = NatTrans.app s.π one
[PROOFSTEP]
rw [← s.w (line j), parallelFamily_map_left]
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
s : Cotrident f
j : J
⊢ f j ≫ NatTrans.app s.ι one = NatTrans.app s.ι zero
[PROOFSTEP]
rw [← s.w (line j), parallelFamily_map_left]
[GOAL]
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f✝ : J → (X ⟶ Y)
inst✝ : Nonempty J
P : C
ι : P ⟶ X
w : ∀ (j₁ j₂ : J), ι ≫ f✝ j₁ = ι ≫ f✝ j₂
i j : WalkingParallelFamily J
f : i ⟶ j
⊢ ((Functor.const (WalkingParallelFamily J)).obj P).map f ≫
(fun X_1 => WalkingParallelFamily.casesOn X_1 ι (ι ≫ f✝ (Classical.arbitrary J))) j =
(fun X_1 => WalkingParallelFamily.casesOn X_1 ι (ι ≫ f✝ (Classical.arbitrary J))) i ≫ (parallelFamily f✝).map f
[PROOFSTEP]
dsimp
[GOAL]
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f✝ : J → (X ⟶ Y)
inst✝ : Nonempty J
P : C
ι : P ⟶ X
w : ∀ (j₁ j₂ : J), ι ≫ f✝ j₁ = ι ≫ f✝ j₂
i j : WalkingParallelFamily J
f : i ⟶ j
⊢ 𝟙 P ≫ WalkingParallelFamily.rec ι (ι ≫ f✝ (Classical.arbitrary J)) j =
WalkingParallelFamily.rec ι (ι ≫ f✝ (Classical.arbitrary J)) i ≫ (parallelFamily f✝).map f
[PROOFSTEP]
cases' f with _ k
[GOAL]
case id
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
inst✝ : Nonempty J
P : C
ι : P ⟶ X
w : ∀ (j₁ j₂ : J), ι ≫ f j₁ = ι ≫ f j₂
i : WalkingParallelFamily J
⊢ 𝟙 P ≫ WalkingParallelFamily.rec ι (ι ≫ f (Classical.arbitrary J)) i =
WalkingParallelFamily.rec ι (ι ≫ f (Classical.arbitrary J)) i ≫ (parallelFamily f).map (Hom.id i)
[PROOFSTEP]
simp
[GOAL]
case line
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
inst✝ : Nonempty J
P : C
ι : P ⟶ X
w : ∀ (j₁ j₂ : J), ι ≫ f j₁ = ι ≫ f j₂
k : J
⊢ 𝟙 P ≫ WalkingParallelFamily.rec ι (ι ≫ f (Classical.arbitrary J)) one =
WalkingParallelFamily.rec ι (ι ≫ f (Classical.arbitrary J)) zero ≫ (parallelFamily f).map (line k)
[PROOFSTEP]
simp [w (Classical.arbitrary J) k]
[GOAL]
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f✝ : J → (X ⟶ Y)
inst✝ : Nonempty J
P : C
π : Y ⟶ P
w : ∀ (j₁ j₂ : J), f✝ j₁ ≫ π = f✝ j₂ ≫ π
i j : WalkingParallelFamily J
f : i ⟶ j
⊢ (parallelFamily f✝).map f ≫ (fun X_1 => WalkingParallelFamily.casesOn X_1 (f✝ (Classical.arbitrary J) ≫ π) π) j =
(fun X_1 => WalkingParallelFamily.casesOn X_1 (f✝ (Classical.arbitrary J) ≫ π) π) i ≫
((Functor.const (WalkingParallelFamily J)).obj P).map f
[PROOFSTEP]
dsimp
[GOAL]
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f✝ : J → (X ⟶ Y)
inst✝ : Nonempty J
P : C
π : Y ⟶ P
w : ∀ (j₁ j₂ : J), f✝ j₁ ≫ π = f✝ j₂ ≫ π
i j : WalkingParallelFamily J
f : i ⟶ j
⊢ (parallelFamily f✝).map f ≫ WalkingParallelFamily.rec (f✝ (Classical.arbitrary J) ≫ π) π j =
WalkingParallelFamily.rec (f✝ (Classical.arbitrary J) ≫ π) π i ≫ 𝟙 P
[PROOFSTEP]
cases' f with _ k
[GOAL]
case id
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
inst✝ : Nonempty J
P : C
π : Y ⟶ P
w : ∀ (j₁ j₂ : J), f j₁ ≫ π = f j₂ ≫ π
i : WalkingParallelFamily J
⊢ (parallelFamily f).map (Hom.id i) ≫ WalkingParallelFamily.rec (f (Classical.arbitrary J) ≫ π) π i =
WalkingParallelFamily.rec (f (Classical.arbitrary J) ≫ π) π i ≫ 𝟙 P
[PROOFSTEP]
simp
[GOAL]
case line
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
inst✝ : Nonempty J
P : C
π : Y ⟶ P
w : ∀ (j₁ j₂ : J), f j₁ ≫ π = f j₂ ≫ π
k : J
⊢ (parallelFamily f).map (line k) ≫ WalkingParallelFamily.rec (f (Classical.arbitrary J) ≫ π) π one =
WalkingParallelFamily.rec (f (Classical.arbitrary J) ≫ π) π zero ≫ 𝟙 P
[PROOFSTEP]
simp [w (Classical.arbitrary J) k]
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
j₁ j₂ : J
t : Trident f
⊢ ι t ≫ f j₁ = ι t ≫ f j₂
[PROOFSTEP]
rw [t.app_zero, t.app_zero]
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
j₁ j₂ : J
t : Cotrident f
⊢ f j₁ ≫ π t = f j₂ ≫ π t
[PROOFSTEP]
rw [t.app_one, t.app_one]
[GOAL]
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
inst✝ : Nonempty J
s : Trident f
W : C
k l : W ⟶ s.pt
h : k ≫ ι s = l ≫ ι s
⊢ k ≫ NatTrans.app s.π one = l ≫ NatTrans.app s.π one
[PROOFSTEP]
rw [← s.app_zero (Classical.arbitrary J), reassoc_of% h]
[GOAL]
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
inst✝ : Nonempty J
s : Cotrident f
W : C
k l : s.pt ⟶ W
h : π s ≫ k = π s ≫ l
⊢ NatTrans.app s.ι zero ≫ k = NatTrans.app s.ι zero ≫ l
[PROOFSTEP]
rw [← s.app_one (Classical.arbitrary J), Category.assoc, Category.assoc, h]
[GOAL]
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
inst✝ : Nonempty J
t : Trident f
lift : (s : Trident f) → s.pt ⟶ t.pt
fac : ∀ (s : Trident f), lift s ≫ ι t = ι s
uniq :
∀ (s : Trident f) (m : s.pt ⟶ t.pt),
(∀ (j : WalkingParallelFamily J), m ≫ NatTrans.app t.π j = NatTrans.app s.π j) → m = lift s
s : Cone (parallelFamily f)
j : WalkingParallelFamily J
⊢ lift s ≫ NatTrans.app t.π one = NatTrans.app s.π one
[PROOFSTEP]
rw [← t.w (line (Classical.arbitrary J)), reassoc_of% fac, s.w]
[GOAL]
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
inst✝ : Nonempty J
t : Cotrident f
desc : (s : Cotrident f) → t.pt ⟶ s.pt
fac : ∀ (s : Cotrident f), π t ≫ desc s = π s
uniq :
∀ (s : Cotrident f) (m : t.pt ⟶ s.pt),
(∀ (j : WalkingParallelFamily J), NatTrans.app t.ι j ≫ m = NatTrans.app s.ι j) → m = desc s
s : Cocone (parallelFamily f)
j : WalkingParallelFamily J
⊢ NatTrans.app t.ι zero ≫ desc s = NatTrans.app s.ι zero
[PROOFSTEP]
rw [← t.w_assoc (line (Classical.arbitrary J)), fac, s.w]
[GOAL]
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
inst✝ : Nonempty J
t : Trident f
ht : IsLimit t
Z : C
k : Z ⟶ t.pt
⊢ ∀ (j₁ j₂ : J), (k ≫ ι t) ≫ f j₁ = (k ≫ ι t) ≫ f j₂
[PROOFSTEP]
simp
[GOAL]
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
inst✝ : Nonempty J
t : Cotrident f
ht : IsColimit t
Z : C
k : t.pt ⟶ Z
⊢ ∀ (j₁ j₂ : J), f j₁ ≫ π t ≫ k = f j₂ ≫ π t ≫ k
[PROOFSTEP]
simp
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X✝ Y : C
f : J → (X✝ ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Trident fun j => F.map (line j)
X : WalkingParallelFamily J
⊢ (parallelFamily fun j => F.map (line j)).obj X = F.obj X
[PROOFSTEP]
cases X
[GOAL]
case zero
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Trident fun j => F.map (line j)
⊢ (parallelFamily fun j => F.map (line j)).obj zero = F.obj zero
[PROOFSTEP]
aesop_cat
[GOAL]
case one
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Trident fun j => F.map (line j)
⊢ (parallelFamily fun j => F.map (line j)).obj one = F.obj one
[PROOFSTEP]
aesop_cat
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Trident fun j => F.map (line j)
j j' : WalkingParallelFamily J
g : j ⟶ j'
⊢ ((Functor.const (WalkingParallelFamily J)).obj t.pt).map g ≫
(fun X => NatTrans.app t.π X ≫ eqToHom (_ : (parallelFamily fun j => F.map (line j)).obj X = F.obj X)) j' =
(fun X => NatTrans.app t.π X ≫ eqToHom (_ : (parallelFamily fun j => F.map (line j)).obj X = F.obj X)) j ≫ F.map g
[PROOFSTEP]
cases g
[GOAL]
case id
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Trident fun j => F.map (line j)
j : WalkingParallelFamily J
⊢ ((Functor.const (WalkingParallelFamily J)).obj t.pt).map (Hom.id j) ≫
(fun X => NatTrans.app t.π X ≫ eqToHom (_ : (parallelFamily fun j => F.map (line j)).obj X = F.obj X)) j =
(fun X => NatTrans.app t.π X ≫ eqToHom (_ : (parallelFamily fun j => F.map (line j)).obj X = F.obj X)) j ≫
F.map (Hom.id j)
[PROOFSTEP]
aesop_cat
[GOAL]
case line
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Trident fun j => F.map (line j)
x✝ : J
⊢ ((Functor.const (WalkingParallelFamily J)).obj t.pt).map (line x✝) ≫
(fun X => NatTrans.app t.π X ≫ eqToHom (_ : (parallelFamily fun j => F.map (line j)).obj X = F.obj X)) one =
(fun X => NatTrans.app t.π X ≫ eqToHom (_ : (parallelFamily fun j => F.map (line j)).obj X = F.obj X)) zero ≫
F.map (line x✝)
[PROOFSTEP]
aesop_cat
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X✝ Y : C
f : J → (X✝ ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cotrident fun j => F.map (line j)
X : WalkingParallelFamily J
⊢ F.obj X = (parallelFamily fun j => F.map (line j)).obj X
[PROOFSTEP]
cases X
[GOAL]
case zero
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cotrident fun j => F.map (line j)
⊢ F.obj zero = (parallelFamily fun j => F.map (line j)).obj zero
[PROOFSTEP]
aesop_cat
[GOAL]
case one
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cotrident fun j => F.map (line j)
⊢ F.obj one = (parallelFamily fun j => F.map (line j)).obj one
[PROOFSTEP]
aesop_cat
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cotrident fun j => F.map (line j)
j j' : WalkingParallelFamily J
g : j ⟶ j'
⊢ F.map g ≫ (fun X => eqToHom (_ : F.obj X = (parallelFamily fun j => F.map (line j)).obj X) ≫ NatTrans.app t.ι X) j' =
(fun X => eqToHom (_ : F.obj X = (parallelFamily fun j => F.map (line j)).obj X) ≫ NatTrans.app t.ι X) j ≫
((Functor.const (WalkingParallelFamily J)).obj t.pt).map g
[PROOFSTEP]
cases g
[GOAL]
case id
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cotrident fun j => F.map (line j)
j : WalkingParallelFamily J
⊢ F.map (Hom.id j) ≫
(fun X => eqToHom (_ : F.obj X = (parallelFamily fun j => F.map (line j)).obj X) ≫ NatTrans.app t.ι X) j =
(fun X => eqToHom (_ : F.obj X = (parallelFamily fun j => F.map (line j)).obj X) ≫ NatTrans.app t.ι X) j ≫
((Functor.const (WalkingParallelFamily J)).obj t.pt).map (Hom.id j)
[PROOFSTEP]
dsimp
[GOAL]
case line
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cotrident fun j => F.map (line j)
x✝ : J
⊢ F.map (line x✝) ≫
(fun X => eqToHom (_ : F.obj X = (parallelFamily fun j => F.map (line j)).obj X) ≫ NatTrans.app t.ι X) one =
(fun X => eqToHom (_ : F.obj X = (parallelFamily fun j => F.map (line j)).obj X) ≫ NatTrans.app t.ι X) zero ≫
((Functor.const (WalkingParallelFamily J)).obj t.pt).map (line x✝)
[PROOFSTEP]
dsimp
[GOAL]
case id
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cotrident fun j => F.map (line j)
j : WalkingParallelFamily J
⊢ F.map (𝟙 j) ≫ eqToHom (_ : F.obj j = (parallelFamily fun j => F.map (line j)).obj j) ≫ NatTrans.app t.ι j =
(eqToHom (_ : F.obj j = (parallelFamily fun j => F.map (line j)).obj j) ≫ NatTrans.app t.ι j) ≫ 𝟙 t.pt
[PROOFSTEP]
simp [Cotrident.app_one t]
[GOAL]
case line
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cotrident fun j => F.map (line j)
x✝ : J
⊢ F.map (line x✝) ≫ 𝟙 (F.obj one) ≫ NatTrans.app t.ι one = (𝟙 (F.obj zero) ≫ NatTrans.app t.ι zero) ≫ 𝟙 t.pt
[PROOFSTEP]
simp [Cotrident.app_one t]
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Trident fun j => F.map (line j)
j : WalkingParallelFamily J
⊢ (parallelFamily fun j => F.map (line j)).obj j = F.obj j
[PROOFSTEP]
cases j
[GOAL]
case zero
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Trident fun j => F.map (line j)
⊢ (parallelFamily fun j => F.map (line j)).obj zero = F.obj zero
[PROOFSTEP]
aesop_cat
[GOAL]
case one
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Trident fun j => F.map (line j)
⊢ (parallelFamily fun j => F.map (line j)).obj one = F.obj one
[PROOFSTEP]
aesop_cat
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cotrident fun j => F.map (line j)
j : WalkingParallelFamily J
⊢ F.obj j = (parallelFamily fun j => F.map (line j)).obj j
[PROOFSTEP]
cases j
[GOAL]
case zero
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cotrident fun j => F.map (line j)
⊢ F.obj zero = (parallelFamily fun j => F.map (line j)).obj zero
[PROOFSTEP]
aesop_cat
[GOAL]
case one
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cotrident fun j => F.map (line j)
⊢ F.obj one = (parallelFamily fun j => F.map (line j)).obj one
[PROOFSTEP]
aesop_cat
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X✝ Y : C
f : J → (X✝ ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cone F
X : WalkingParallelFamily J
⊢ F.obj X = (parallelFamily fun j => F.map (line j)).obj X
[PROOFSTEP]
cases X
[GOAL]
case zero
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cone F
⊢ F.obj zero = (parallelFamily fun j => F.map (line j)).obj zero
[PROOFSTEP]
aesop_cat
[GOAL]
case one
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cone F
⊢ F.obj one = (parallelFamily fun j => F.map (line j)).obj one
[PROOFSTEP]
aesop_cat
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cone F
⊢ ∀ ⦃X Y : WalkingParallelFamily J⦄ (f : X ⟶ Y),
((Functor.const (WalkingParallelFamily J)).obj t.pt).map f ≫
(fun X => NatTrans.app t.π X ≫ eqToHom (_ : F.obj X = (parallelFamily fun j => F.map (line j)).obj X)) Y =
(fun X => NatTrans.app t.π X ≫ eqToHom (_ : F.obj X = (parallelFamily fun j => F.map (line j)).obj X)) X ≫
(parallelFamily fun j => F.map (line j)).map f
[PROOFSTEP]
rintro _ _ (_ | _)
[GOAL]
case id
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cone F
X✝ : WalkingParallelFamily J
⊢ ((Functor.const (WalkingParallelFamily J)).obj t.pt).map (Hom.id X✝) ≫
(fun X => NatTrans.app t.π X ≫ eqToHom (_ : F.obj X = (parallelFamily fun j => F.map (line j)).obj X)) X✝ =
(fun X => NatTrans.app t.π X ≫ eqToHom (_ : F.obj X = (parallelFamily fun j => F.map (line j)).obj X)) X✝ ≫
(parallelFamily fun j => F.map (line j)).map (Hom.id X✝)
[PROOFSTEP]
aesop_cat
[GOAL]
case line
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cone F
x✝ : J
⊢ ((Functor.const (WalkingParallelFamily J)).obj t.pt).map (line x✝) ≫
(fun X => NatTrans.app t.π X ≫ eqToHom (_ : F.obj X = (parallelFamily fun j => F.map (line j)).obj X)) one =
(fun X => NatTrans.app t.π X ≫ eqToHom (_ : F.obj X = (parallelFamily fun j => F.map (line j)).obj X)) zero ≫
(parallelFamily fun j => F.map (line j)).map (line x✝)
[PROOFSTEP]
aesop_cat
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X✝ Y : C
f : J → (X✝ ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cocone F
X : WalkingParallelFamily J
⊢ (parallelFamily fun j => F.map (line j)).obj X = F.obj X
[PROOFSTEP]
cases X
[GOAL]
case zero
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cocone F
⊢ (parallelFamily fun j => F.map (line j)).obj zero = F.obj zero
[PROOFSTEP]
aesop_cat
[GOAL]
case one
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cocone F
⊢ (parallelFamily fun j => F.map (line j)).obj one = F.obj one
[PROOFSTEP]
aesop_cat
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cocone F
⊢ ∀ ⦃X Y : WalkingParallelFamily J⦄ (f : X ⟶ Y),
(parallelFamily fun j => F.map (line j)).map f ≫
(fun X => eqToHom (_ : (parallelFamily fun j => F.map (line j)).obj X = F.obj X) ≫ NatTrans.app t.ι X) Y =
(fun X => eqToHom (_ : (parallelFamily fun j => F.map (line j)).obj X = F.obj X) ≫ NatTrans.app t.ι X) X ≫
((Functor.const (WalkingParallelFamily J)).obj t.pt).map f
[PROOFSTEP]
rintro _ _ (_ | _)
[GOAL]
case id
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cocone F
X✝ : WalkingParallelFamily J
⊢ (parallelFamily fun j => F.map (line j)).map (Hom.id X✝) ≫
(fun X => eqToHom (_ : (parallelFamily fun j => F.map (line j)).obj X = F.obj X) ≫ NatTrans.app t.ι X) X✝ =
(fun X => eqToHom (_ : (parallelFamily fun j => F.map (line j)).obj X = F.obj X) ≫ NatTrans.app t.ι X) X✝ ≫
((Functor.const (WalkingParallelFamily J)).obj t.pt).map (Hom.id X✝)
[PROOFSTEP]
aesop_cat
[GOAL]
case line
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cocone F
x✝ : J
⊢ (parallelFamily fun j => F.map (line j)).map (line x✝) ≫
(fun X => eqToHom (_ : (parallelFamily fun j => F.map (line j)).obj X = F.obj X) ≫ NatTrans.app t.ι X) one =
(fun X => eqToHom (_ : (parallelFamily fun j => F.map (line j)).obj X = F.obj X) ≫ NatTrans.app t.ι X) zero ≫
((Functor.const (WalkingParallelFamily J)).obj t.pt).map (line x✝)
[PROOFSTEP]
aesop_cat
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cone F
j : WalkingParallelFamily J
⊢ F.obj j = (parallelFamily fun j => F.map (line j)).obj j
[PROOFSTEP]
cases j
[GOAL]
case zero
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cone F
⊢ F.obj zero = (parallelFamily fun j => F.map (line j)).obj zero
[PROOFSTEP]
aesop_cat
[GOAL]
case one
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cone F
⊢ F.obj one = (parallelFamily fun j => F.map (line j)).obj one
[PROOFSTEP]
aesop_cat
[GOAL]
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cocone F
j : WalkingParallelFamily J
⊢ (parallelFamily fun j => F.map (line j)).obj j = F.obj j
[PROOFSTEP]
cases j
[GOAL]
case zero
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cocone F
⊢ (parallelFamily fun j => F.map (line j)).obj zero = F.obj zero
[PROOFSTEP]
aesop_cat
[GOAL]
case one
J : Type w
C : Type u
inst✝ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
F : WalkingParallelFamily J ⥤ C
t : Cocone F
⊢ (parallelFamily fun j => F.map (line j)).obj one = F.obj one
[PROOFSTEP]
aesop_cat
[GOAL]
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
inst✝ : Nonempty J
s t : Trident f
k : s.pt ⟶ t.pt
w : autoParam (k ≫ ι t = ι s) _auto✝
⊢ ∀ (j : WalkingParallelFamily J), k ≫ NatTrans.app t.π j = NatTrans.app s.π j
[PROOFSTEP]
rintro ⟨_ | _⟩
[GOAL]
case zero
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
inst✝ : Nonempty J
s t : Trident f
k : s.pt ⟶ t.pt
w : autoParam (k ≫ ι t = ι s) _auto✝
⊢ k ≫ NatTrans.app t.π zero = NatTrans.app s.π zero
[PROOFSTEP]
exact w
[GOAL]
case one
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
inst✝ : Nonempty J
s t : Trident f
k : s.pt ⟶ t.pt
w : autoParam (k ≫ ι t = ι s) _auto✝
⊢ k ≫ NatTrans.app t.π one = NatTrans.app s.π one
[PROOFSTEP]
simpa using w =≫ f (Classical.arbitrary J)
[GOAL]
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
inst✝ : Nonempty J
s t : Trident f
i : s.pt ≅ t.pt
w : autoParam (i.hom ≫ ι t = ι s) _auto✝
⊢ i.inv ≫ ι s = ι t
[PROOFSTEP]
rw [← w, Iso.inv_hom_id_assoc]
[GOAL]
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
inst✝ : Nonempty J
s t : Cotrident f
k : s.pt ⟶ t.pt
w : autoParam (π s ≫ k = π t) _auto✝
⊢ ∀ (j : WalkingParallelFamily J), NatTrans.app s.ι j ≫ k = NatTrans.app t.ι j
[PROOFSTEP]
rintro ⟨_ | _⟩
[GOAL]
case zero
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
inst✝ : Nonempty J
s t : Cotrident f
k : s.pt ⟶ t.pt
w : autoParam (π s ≫ k = π t) _auto✝
⊢ NatTrans.app s.ι zero ≫ k = NatTrans.app t.ι zero
[PROOFSTEP]
simpa using f (Classical.arbitrary J) ≫= w
[GOAL]
case one
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
inst✝ : Nonempty J
s t : Cotrident f
k : s.pt ⟶ t.pt
w : autoParam (π s ≫ k = π t) _auto✝
⊢ NatTrans.app s.ι one ≫ k = NatTrans.app t.ι one
[PROOFSTEP]
exact w
[GOAL]
J : Type w
C : Type u
inst✝¹ : Category.{v, u} C
X Y : C
f : J → (X ⟶ Y)
inst✝ : Nonempty J
s t : Cotrident f
i : s.pt ≅ t.pt
w : autoParam (π s ≫ i.hom = π t) _auto✝
⊢ π t ≫ i.inv = π s
[PROOFSTEP]
rw [Iso.comp_inv_eq, w]
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
module Section_4_5.TwoLayer where
import Data.List
import Numeric.LinearAlgebra
import System.Random.MWC
import System.Random.MWC.Distributions (normal)
crossEntropyError :: Vector Double -> Vector Double -> Double
crossEntropyError y t =
let delta = 1.0e-7
in -1 * (sumElements $ t * cmap (\x -> log (x + delta)) y)
class Indexes c t where
indexes :: c t -> [IndexOf c]
instance Container Vector t => Indexes Vector t where
indexes v = [0 .. size v - 1]
instance (Num t, Container Vector t) => Indexes Matrix t where
indexes m = let (x, y) = size m in (,) <$> [0..x-1] <*> [0..y-1]
numericalGradient :: (Container c Double, Additive (c Double), Indexes c Double) => (c Double -> Double) -> c Double -> c Double
numericalGradient f x =
foldr add (assoc (size x) 0.0 []) $
flip map (indexes x) $ \i ->
let df1 = f (x `add` assoc (size x) 0.0 [(i, h)])
df2 = f (x `add` assoc (size x) 0.0 [(i, -h)])
dfdx = (df1 - df2) / (2*h)
in assoc (size x) 0.0 [(i, dfdx)]
where h = 1.0e-4 -- 0.0001
type ActivationFunction = Vector Double -> Vector Double
-- | シグモイド関数
sigmoid :: ActivationFunction
sigmoid = cmap (\x -> 1 / (1 + exp (-x)))
-- | ソフトマックス関数
softmax :: ActivationFunction
softmax a =
let c = maxElement a
exp_a = cmap (\x -> exp (x - c)) a
sum_exp_a = sumElements exp_a
in cmap (/sum_exp_a) exp_a
type Layer = ( Matrix Double -- 重み行列
, Vector Double -- バイアス
, ActivationFunction -- 活性化関数
)
type Network = [Layer]
-- | 学習前のニューラルネットワークを生成する
initNetwork :: [Int] -- 各層のユニット数
-> [ActivationFunction] -- 各層の活性化関数
-> IO Network
initNetwork inputs as =
withSystemRandom $ \gen ->
sequence (zipWith (build gen) inouts as)
where
inouts :: [(Int, Int)]
inouts = zip inputs (tail inputs)
build :: GenIO -> (Int, Int) -> ActivationFunction -> IO Layer
build gen (x, y) a = do
w <- (x >< y) <$> (sequence $ replicate (x * y) (normal 0 0.01 gen))
b <- vector <$> (sequence $ replicate y (normal 0 0.01 gen))
pure (w, b, a)
-- | 認識(推論)を行う
predict :: Network -> Vector Double -> Vector Double
predict nw x = foldl (\x (w, b, h) -> h (x <# w + b)) x nw
-- | 損失関数の値を求める
loss :: [Vector Double] -> [Vector Double] -> Network -> Double
loss xs ts nw =
let batchSize = genericLength xs
ys = map (predict nw) xs
in sum (zipWith crossEntropyError ys ts) / batchSize
-- | 認識精度を求める
accuracy :: [Vector Double] -> [Vector Double] -> Network -> Double
accuracy xs ts nw =
let batchSize = genericLength xs
ys = map (predict nw) xs
yis = map maxIndex ys
tis = map maxIndex ts
correctCount = genericLength (filter id (zipWith (==) yis tis))
in correctCount / batchSize
dismantle :: [a] -> [(a, a -> [a])]
dismantle xs = map (\i -> (xs!!i, (\x -> (take i xs) ++ [x] ++ (drop (i+1) xs)))) [0..length xs - 1] -- TODO more efficient implementation
updateNetwork :: ([Vector Double] -> [Vector Double] -> Network -> Double) -> [Vector Double] -> [Vector Double] -> Network -> Network
updateNetwork loss xs ts network = map (uncurry $ updateLayer xs ts) $ dismantle network
where
rate :: Double
rate = 0.1
updateLayer :: [Vector Double] -> [Vector Double] -> Layer -> (Layer -> Network) -> Layer
updateLayer xs ts (w, b, a) mkNw =
let dw = numericalGradient (\w -> loss xs ts (mkNw (w, b, a))) w
db = numericalGradient (\b -> loss xs ts (mkNw (w, b, a))) b
in (w - rate `scale` dw, b - rate `scale` db, a)
|
lemma has_field_derivative_Re[derivative_intros]: "(f has_vector_derivative D) F \<Longrightarrow> ((\<lambda>x. Re (f x)) has_field_derivative (Re D)) F" |
module FunctorComposition where
open import Functor as F
compose : {F₁ F₂ : Setoid → Setoid} →
Functor F₁ → Functor F₂ → Functor (λ A → F₁ (F₂ A))
compose {F₁} {F₂} FF₁ FF₂ = record
{ map = map FF₁ ∘ map FF₂
; identity = λ {A} →
trans (F₁ (F₂ A) ⇨ F₁ (F₂ A))
{i = map FF₁ ⟨$⟩ (map FF₂ ⟨$⟩ id)}
{j = map FF₁ ⟨$⟩ id}
{k = id}
(cong (map FF₁) (identity FF₂))
(identity FF₁)
; composition = λ {A B C} f g →
trans (F₁ (F₂ A) ⇨ F₁ (F₂ C))
{i = map FF₁ ⟨$⟩ (map FF₂ ⟨$⟩ (f ∘ g))}
{j = map FF₁ ⟨$⟩ ((map FF₂ ⟨$⟩ f) ∘ (map FF₂ ⟨$⟩ g))}
{k = (map FF₁ ⟨$⟩ (map FF₂ ⟨$⟩ f)) ∘
(map FF₁ ⟨$⟩ (map FF₂ ⟨$⟩ g))}
(cong (map FF₁) (composition FF₂ f g))
(composition FF₁ (map FF₂ ⟨$⟩ f) (map FF₂ ⟨$⟩ g))
}
where
open Setoid
open F.Functor
|
[STATEMENT]
lemma iWeakSince_False_left[simp]: "(False. t' \<B> t I. Q t) = (I = {} \<or> (finite I \<and> Q (Max I)))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (False. t' \<B> t I. Q t) = (I = {} \<or> finite I \<and> Q (Max I))
[PROOF STEP]
apply (simp add: iTL_defs)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (I = {} \<or> (\<exists>t\<in>I. Q t \<and> I \<down>> t = {})) = (I = {} \<or> finite I \<and> Q (Max I))
[PROOF STEP]
apply (case_tac "I = {}", simp)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. I \<noteq> {} \<Longrightarrow> (I = {} \<or> (\<exists>t\<in>I. Q t \<and> I \<down>> t = {})) = (I = {} \<or> finite I \<and> Q (Max I))
[PROOF STEP]
apply (case_tac "infinite I")
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<lbrakk>I \<noteq> {}; infinite I\<rbrakk> \<Longrightarrow> (I = {} \<or> (\<exists>t\<in>I. Q t \<and> I \<down>> t = {})) = (I = {} \<or> finite I \<and> Q (Max I))
2. \<lbrakk>I \<noteq> {}; \<not> infinite I\<rbrakk> \<Longrightarrow> (I = {} \<or> (\<exists>t\<in>I. Q t \<and> I \<down>> t = {})) = (I = {} \<or> finite I \<and> Q (Max I))
[PROOF STEP]
apply (simp add: nat_cut_greater_infinite_not_empty)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>I \<noteq> {}; \<not> infinite I\<rbrakk> \<Longrightarrow> (I = {} \<or> (\<exists>t\<in>I. Q t \<and> I \<down>> t = {})) = (I = {} \<or> finite I \<and> Q (Max I))
[PROOF STEP]
apply (rule iffI)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<lbrakk>I \<noteq> {}; \<not> infinite I; I = {} \<or> (\<exists>t\<in>I. Q t \<and> I \<down>> t = {})\<rbrakk> \<Longrightarrow> I = {} \<or> finite I \<and> Q (Max I)
2. \<lbrakk>I \<noteq> {}; \<not> infinite I; I = {} \<or> finite I \<and> Q (Max I)\<rbrakk> \<Longrightarrow> I = {} \<or> (\<exists>t\<in>I. Q t \<and> I \<down>> t = {})
[PROOF STEP]
apply clarsimp
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>t. \<lbrakk>I \<noteq> {}; finite I; t \<in> I; Q t; I \<down>> t = {}\<rbrakk> \<Longrightarrow> Q (Max I)
2. \<lbrakk>I \<noteq> {}; \<not> infinite I; I = {} \<or> finite I \<and> Q (Max I)\<rbrakk> \<Longrightarrow> I = {} \<or> (\<exists>t\<in>I. Q t \<and> I \<down>> t = {})
[PROOF STEP]
apply (drule Max_equality)
[PROOF STATE]
proof (prove)
goal (4 subgoals):
1. \<And>t. \<lbrakk>I \<noteq> {}; finite I; Q t; I \<down>> t = {}\<rbrakk> \<Longrightarrow> finite I
2. \<And>t x. \<lbrakk>I \<noteq> {}; finite I; Q t; I \<down>> t = {}; x \<in> I\<rbrakk> \<Longrightarrow> x \<le> t
3. \<And>t. \<lbrakk>I \<noteq> {}; finite I; Q t; I \<down>> t = {}; Max I = t\<rbrakk> \<Longrightarrow> Q (Max I)
4. \<lbrakk>I \<noteq> {}; \<not> infinite I; I = {} \<or> finite I \<and> Q (Max I)\<rbrakk> \<Longrightarrow> I = {} \<or> (\<exists>t\<in>I. Q t \<and> I \<down>> t = {})
[PROOF STEP]
apply simp
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<And>t x. \<lbrakk>I \<noteq> {}; finite I; Q t; I \<down>> t = {}; x \<in> I\<rbrakk> \<Longrightarrow> x \<le> t
2. \<And>t. \<lbrakk>I \<noteq> {}; finite I; Q t; I \<down>> t = {}; Max I = t\<rbrakk> \<Longrightarrow> Q (Max I)
3. \<lbrakk>I \<noteq> {}; \<not> infinite I; I = {} \<or> finite I \<and> Q (Max I)\<rbrakk> \<Longrightarrow> I = {} \<or> (\<exists>t\<in>I. Q t \<and> I \<down>> t = {})
[PROOF STEP]
apply (simp add: cut_greater_empty_iff)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>t. \<lbrakk>I \<noteq> {}; finite I; Q t; I \<down>> t = {}; Max I = t\<rbrakk> \<Longrightarrow> Q (Max I)
2. \<lbrakk>I \<noteq> {}; \<not> infinite I; I = {} \<or> finite I \<and> Q (Max I)\<rbrakk> \<Longrightarrow> I = {} \<or> (\<exists>t\<in>I. Q t \<and> I \<down>> t = {})
[PROOF STEP]
apply simp
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>I \<noteq> {}; \<not> infinite I; I = {} \<or> finite I \<and> Q (Max I)\<rbrakk> \<Longrightarrow> I = {} \<or> (\<exists>t\<in>I. Q t \<and> I \<down>> t = {})
[PROOF STEP]
apply simp
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>I \<noteq> {}; finite I; Q (Max I)\<rbrakk> \<Longrightarrow> \<exists>t\<in>I. Q t \<and> I \<down>> t = {}
[PROOF STEP]
apply (rule_tac x="Max I" in bexI)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<lbrakk>I \<noteq> {}; finite I; Q (Max I)\<rbrakk> \<Longrightarrow> Q (Max I) \<and> I \<down>> Max I = {}
2. \<lbrakk>I \<noteq> {}; finite I; Q (Max I)\<rbrakk> \<Longrightarrow> Max I \<in> I
[PROOF STEP]
apply (simp add: cut_greater_Max_empty)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>I \<noteq> {}; finite I; Q (Max I)\<rbrakk> \<Longrightarrow> Max I \<in> I
[PROOF STEP]
apply simp
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
/-
Copyright (c) 2021 Arthur Paulino. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Arthur Paulino
-/
import LeanMusic.Utils
abbrev Intervals := List Int
namespace Intervals
@[simp] def allPositive : Intervals → Prop
| h :: t => 0 < h ∧ allPositive t
| _ => True
@[simp] def delta : Intervals → Int
| h :: t => h + delta t
| _ => 0
def invertedAt : Intervals → Int → Intervals
| h :: (t : Intervals), a => t ++ [a - delta (h :: t)]
| _, _ => []
theorem appendPosOfPos (l l' : Intervals)
(hpl : l.allPositive) (hpl' : l'.allPositive) :
(l ++ l').allPositive := by
induction l with
| nil => rw [List.nil_append]; exact hpl'
| cons _ _ hi => exact ⟨hpl.1, hi hpl.2⟩
theorem deltaAppendEqSumDeltas (l l' : Intervals) :
delta (l ++ l') = delta l + delta l' := by
induction l with
| nil => simp [Int.ZeroAdd]
| cons _ _ hi =>
simp only [HAppend.hAppend, Append.append] at hi
simp [hi, Int.AddAssoc]
theorem posInvOfPosAndBound (l : Intervals) (i : Int)
(hp : l.allPositive) (hb : l.delta < i) :
(l.invertedAt i).allPositive := by
cases l with
| nil => simp
| cons h t =>
let iSubDelta := [(i - (h + delta t))]
have hpid : allPositive iSubDelta := by
exact ⟨Int.zeroLtSubOfLt (h + delta t) i hb, ⟨⟩⟩
exact appendPosOfPos t iSubDelta hp.2 hpid
theorem boundInvOfPosAndBound (l : Intervals) (i : Int)
(hp : l.allPositive) (hb : l.delta < i) :
(l.invertedAt i).delta < i := by
cases l with
| nil => exact hb
| cons h t =>
simp only [invertedAt, deltaAppendEqSumDeltas]
exact Int.what (delta t) i h hp.1
end Intervals
|
[STATEMENT]
theorem mac_otp:
defines "\<I>_real \<equiv> \<lambda>\<eta>. \<I>_uniform {x. valid_mac_query \<eta> x} UNIV"
and "\<I>_ideal \<equiv> \<lambda>_. \<I>_full"
and "\<I>_common \<equiv> \<lambda>\<eta>. \<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_full"
shows
"constructive_security
(\<lambda>\<eta>. 1\<^sub>C |\<^sub>= (CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring \<rhd>
parallel_resource1_wiring \<rhd>
CIPHER.KEY.res \<eta> \<parallel>
(1\<^sub>C |\<^sub>= MAC.enm \<eta> |\<^sub>= MAC.dem \<eta> \<rhd>
1\<^sub>C |\<^sub>= parallel_wiring \<rhd>
parallel_resource1_wiring \<rhd> MAC.RO.res \<eta> \<parallel> INSEC.res))
(\<lambda>_. SEC.res)
(\<lambda>\<eta>. CNV Message_Authentication_Code.sim (Inl None) \<odot> CNV One_Time_Pad.sim None)
(\<lambda>\<eta>. \<I>_uniform (Set.Collect (valid_mac_query \<eta>)) (insert None (Some ` (nlists UNIV \<eta> \<times> nlists UNIV \<eta>))))
(\<lambda>\<eta>. \<I>_uniform UNIV {None, Some \<eta>})
(\<lambda>\<eta>. \<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>)))
(\<lambda>_. enat q) True (\<lambda>\<eta>. (id, map_option length) \<circ>\<^sub>w (insec_query_of, map_option snd))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. constructive_security (\<lambda>\<eta>. 1\<^sub>C |\<^sub>= (CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring \<rhd> parallel_resource1_wiring \<rhd> CIPHER.KEY.res \<eta> \<parallel> (1\<^sub>C |\<^sub>= MAC.enm \<eta> |\<^sub>= MAC.dem \<eta> \<rhd> 1\<^sub>C |\<^sub>= parallel_wiring \<rhd> parallel_resource1_wiring \<rhd> MAC.RO.res \<eta> \<parallel> INSEC.res)) (\<lambda>_. SEC.res) (\<lambda>\<eta>. CNV Message_Authentication_Code.sim (Inl None) \<odot> CNV One_Time_Pad.sim None) (\<lambda>\<eta>. \<I>_uniform (Set.Collect (valid_mac_query \<eta>)) (insert None (Some ` (nlists UNIV \<eta> \<times> nlists UNIV \<eta>)))) (\<lambda>\<eta>. \<I>_uniform UNIV {None, Some \<eta>}) (\<lambda>\<eta>. \<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>))) (\<lambda>_. enat q) True (\<lambda>\<eta>. (id, map_option length) \<circ>\<^sub>w (insec_query_of, map_option snd))
[PROOF STEP]
proof(rule composability[OF one_time_pad[THEN constructive_security2.constructive_security, unfolded CIPHER.res_alt_def comp_converter_parallel2 comp_converter_id_left]
secure_mac[unfolded MAC.res_def,
THEN constructive_security.parallel_resource1,
THEN constructive_security.lifting],
where ?\<I>_res2="\<lambda>\<eta>. \<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)" and ?bound_conv1="\<lambda>_. 2" and ?q3 = "2 * q" and bound_sim = "\<lambda>_. \<infinity>",
simplified]
, goal_cases)
[PROOF STATE]
proof (state)
goal (6 subgoals):
1. \<And>\<eta>. \<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>) \<turnstile>res CIPHER.KEY.res \<eta> \<surd>
2. \<And>\<eta>. lossless_resource (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) (CIPHER.KEY.res \<eta>)
3. \<And>\<eta>. \<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>)), (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>))) \<turnstile>\<^sub>C (CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring \<surd>
4. \<And>\<eta>. interaction_any_bounded_converter ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring) 2
5. \<And>\<eta>. enat q * 2 \<le> enat (2 * q)
6. \<And>\<eta>. plossless_converter (\<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>))) ((\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>)))) ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring)
[PROOF STEP]
case (1 \<eta>)
[PROOF STATE]
proof (state)
this:
goal (6 subgoals):
1. \<And>\<eta>. \<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>) \<turnstile>res CIPHER.KEY.res \<eta> \<surd>
2. \<And>\<eta>. lossless_resource (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) (CIPHER.KEY.res \<eta>)
3. \<And>\<eta>. \<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>)), (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>))) \<turnstile>\<^sub>C (CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring \<surd>
4. \<And>\<eta>. interaction_any_bounded_converter ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring) 2
5. \<And>\<eta>. enat q * 2 \<le> enat (2 * q)
6. \<And>\<eta>. plossless_converter (\<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>))) ((\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>)))) ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring)
[PROOF STEP]
have [simp]: "\<I>_uniform UNIV (nlists UNIV \<eta>) \<turnstile>c CIPHER.KEY.key_oracle \<eta> s \<surd>"
if "pred_option (\<lambda>x. length x = \<eta>) s" for s \<eta>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<I>_uniform UNIV (nlists UNIV \<eta>) \<turnstile>c CIPHER.KEY.key_oracle \<eta> s \<surd>
[PROOF STEP]
apply(rule WT_calleeI)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>call ret sa. \<lbrakk>call \<in> outs_\<I> (\<I>_uniform UNIV (nlists UNIV \<eta>)); (ret, sa) \<in> set_spmf (CIPHER.KEY.key_oracle \<eta> s call)\<rbrakk> \<Longrightarrow> ret \<in> responses_\<I> (\<I>_uniform UNIV (nlists UNIV \<eta>)) call
[PROOF STEP]
subgoal for call
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>call \<in> outs_\<I> (\<I>_uniform UNIV (nlists UNIV \<eta>)); (ret_, sa_) \<in> set_spmf (CIPHER.KEY.key_oracle \<eta> s call)\<rbrakk> \<Longrightarrow> ret_ \<in> responses_\<I> (\<I>_uniform UNIV (nlists UNIV \<eta>)) call
[PROOF STEP]
using that
[PROOF STATE]
proof (prove)
using this:
pred_option (\<lambda>x. length x = \<eta>) s
goal (1 subgoal):
1. \<lbrakk>call \<in> outs_\<I> (\<I>_uniform UNIV (nlists UNIV \<eta>)); (ret_, sa_) \<in> set_spmf (CIPHER.KEY.key_oracle \<eta> s call)\<rbrakk> \<Longrightarrow> ret_ \<in> responses_\<I> (\<I>_uniform UNIV (nlists UNIV \<eta>)) call
[PROOF STEP]
by(cases s; cases call; clarsimp; auto simp add: key_def in_nlists_UNIV)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
[PROOF STATE]
proof (state)
this:
pred_option (\<lambda>x. length x = ?\<eta>1) ?s1 \<Longrightarrow> \<I>_uniform UNIV (nlists UNIV ?\<eta>1) \<turnstile>c CIPHER.KEY.key_oracle ?\<eta>1 ?s1 \<surd>
goal (6 subgoals):
1. \<And>\<eta>. \<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>) \<turnstile>res CIPHER.KEY.res \<eta> \<surd>
2. \<And>\<eta>. lossless_resource (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) (CIPHER.KEY.res \<eta>)
3. \<And>\<eta>. \<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>)), (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>))) \<turnstile>\<^sub>C (CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring \<surd>
4. \<And>\<eta>. interaction_any_bounded_converter ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring) 2
5. \<And>\<eta>. enat q * 2 \<le> enat (2 * q)
6. \<And>\<eta>. plossless_converter (\<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>))) ((\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>)))) ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring)
[PROOF STEP]
have *: "callee_invariant_on (CIPHER.KEY.key_oracle \<eta> \<oplus>\<^sub>O CIPHER.KEY.key_oracle \<eta>) (pred_option (\<lambda>x. length x = \<eta>))
(\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>))" for \<eta>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. callee_invariant_on (CIPHER.KEY.key_oracle \<eta> \<oplus>\<^sub>O CIPHER.KEY.key_oracle \<eta>) (pred_option (\<lambda>x. length x = \<eta>)) (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>))
[PROOF STEP]
apply(unfold_locales)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>s x y s'. \<lbrakk>(y, s') \<in> set_spmf ((CIPHER.KEY.key_oracle \<eta> \<oplus>\<^sub>O CIPHER.KEY.key_oracle \<eta>) s x); pred_option (\<lambda>x. length x = \<eta>) s; x \<in> outs_\<I> (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>))\<rbrakk> \<Longrightarrow> pred_option (\<lambda>x. length x = \<eta>) s'
2. \<And>s. pred_option (\<lambda>x. length x = \<eta>) s \<Longrightarrow> \<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>) \<turnstile>c (CIPHER.KEY.key_oracle \<eta> \<oplus>\<^sub>O CIPHER.KEY.key_oracle \<eta>) s \<surd>
[PROOF STEP]
subgoal for s x y s'
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>(y, s') \<in> set_spmf ((CIPHER.KEY.key_oracle \<eta> \<oplus>\<^sub>O CIPHER.KEY.key_oracle \<eta>) s x); pred_option (\<lambda>x. length x = \<eta>) s; x \<in> outs_\<I> (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>))\<rbrakk> \<Longrightarrow> pred_option (\<lambda>x. length x = \<eta>) s'
[PROOF STEP]
by(cases s; cases x; clarsimp; auto simp add: key_def in_nlists_UNIV)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>s. pred_option (\<lambda>x. length x = \<eta>) s \<Longrightarrow> \<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>) \<turnstile>c (CIPHER.KEY.key_oracle \<eta> \<oplus>\<^sub>O CIPHER.KEY.key_oracle \<eta>) s \<surd>
[PROOF STEP]
subgoal for s
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. pred_option (\<lambda>x. length x = \<eta>) s \<Longrightarrow> \<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>) \<turnstile>c (CIPHER.KEY.key_oracle \<eta> \<oplus>\<^sub>O CIPHER.KEY.key_oracle \<eta>) s \<surd>
[PROOF STEP]
by auto
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
[PROOF STATE]
proof (state)
this:
callee_invariant_on (CIPHER.KEY.key_oracle ?\<eta>1 \<oplus>\<^sub>O CIPHER.KEY.key_oracle ?\<eta>1) (pred_option (\<lambda>x. length x = ?\<eta>1)) (\<I>_uniform UNIV (nlists UNIV ?\<eta>1) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV ?\<eta>1))
goal (6 subgoals):
1. \<And>\<eta>. \<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>) \<turnstile>res CIPHER.KEY.res \<eta> \<surd>
2. \<And>\<eta>. lossless_resource (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) (CIPHER.KEY.res \<eta>)
3. \<And>\<eta>. \<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>)), (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>))) \<turnstile>\<^sub>C (CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring \<surd>
4. \<And>\<eta>. interaction_any_bounded_converter ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring) 2
5. \<And>\<eta>. enat q * 2 \<le> enat (2 * q)
6. \<And>\<eta>. plossless_converter (\<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>))) ((\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>)))) ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring)
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
callee_invariant_on (CIPHER.KEY.key_oracle ?\<eta>1 \<oplus>\<^sub>O CIPHER.KEY.key_oracle ?\<eta>1) (pred_option (\<lambda>x. length x = ?\<eta>1)) (\<I>_uniform UNIV (nlists UNIV ?\<eta>1) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV ?\<eta>1))
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
callee_invariant_on (CIPHER.KEY.key_oracle ?\<eta>1 \<oplus>\<^sub>O CIPHER.KEY.key_oracle ?\<eta>1) (pred_option (\<lambda>x. length x = ?\<eta>1)) (\<I>_uniform UNIV (nlists UNIV ?\<eta>1) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV ?\<eta>1))
goal (1 subgoal):
1. \<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>) \<turnstile>res CIPHER.KEY.res \<eta> \<surd>
[PROOF STEP]
unfolding CIPHER.KEY.res_def
[PROOF STATE]
proof (prove)
using this:
callee_invariant_on (CIPHER.KEY.key_oracle ?\<eta>1 \<oplus>\<^sub>O CIPHER.KEY.key_oracle ?\<eta>1) (pred_option (\<lambda>x. length x = ?\<eta>1)) (\<I>_uniform UNIV (nlists UNIV ?\<eta>1) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV ?\<eta>1))
goal (1 subgoal):
1. \<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>) \<turnstile>res RES (CIPHER.KEY.key_oracle \<eta> \<oplus>\<^sub>O CIPHER.KEY.key_oracle \<eta>) None \<surd>
[PROOF STEP]
by(rule callee_invariant_on.WT_resource_of_oracle) simp
[PROOF STATE]
proof (state)
this:
\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>) \<turnstile>res CIPHER.KEY.res \<eta> \<surd>
goal (5 subgoals):
1. \<And>\<eta>. lossless_resource (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) (CIPHER.KEY.res \<eta>)
2. \<And>\<eta>. \<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>)), (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>))) \<turnstile>\<^sub>C (CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring \<surd>
3. \<And>\<eta>. interaction_any_bounded_converter ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring) 2
4. \<And>\<eta>. enat q * 2 \<le> enat (2 * q)
5. \<And>\<eta>. plossless_converter (\<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>))) ((\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>)))) ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring)
[PROOF STEP]
case (2 \<eta>)
[PROOF STATE]
proof (state)
this:
goal (5 subgoals):
1. \<And>\<eta>. lossless_resource (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) (CIPHER.KEY.res \<eta>)
2. \<And>\<eta>. \<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>)), (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>))) \<turnstile>\<^sub>C (CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring \<surd>
3. \<And>\<eta>. interaction_any_bounded_converter ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring) 2
4. \<And>\<eta>. enat q * 2 \<le> enat (2 * q)
5. \<And>\<eta>. plossless_converter (\<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>))) ((\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>)))) ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring)
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. lossless_resource (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) (CIPHER.KEY.res \<eta>)
[PROOF STEP]
unfolding CIPHER.KEY.res_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. lossless_resource (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) (RES (CIPHER.KEY.key_oracle \<eta> \<oplus>\<^sub>O CIPHER.KEY.key_oracle \<eta>) None)
[PROOF STEP]
apply(rule callee_invariant_on.lossless_resource_of_oracle[OF *])
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>s x. \<lbrakk>x \<in> outs_\<I> (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)); pred_option (\<lambda>x. length x = \<eta>) s\<rbrakk> \<Longrightarrow> lossless_spmf ((CIPHER.KEY.key_oracle \<eta> \<oplus>\<^sub>O CIPHER.KEY.key_oracle \<eta>) s x)
2. pred_option (\<lambda>x. length x = \<eta>) None
[PROOF STEP]
subgoal for s x
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>x \<in> outs_\<I> (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)); pred_option (\<lambda>x. length x = \<eta>) s\<rbrakk> \<Longrightarrow> lossless_spmf ((CIPHER.KEY.key_oracle \<eta> \<oplus>\<^sub>O CIPHER.KEY.key_oracle \<eta>) s x)
[PROOF STEP]
by(cases s; cases x)(auto split: plus_oracle_split; simp add: key_def)+
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. pred_option (\<lambda>x. length x = \<eta>) None
[PROOF STEP]
subgoal
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. pred_option (\<lambda>x. length x = \<eta>) None
[PROOF STEP]
by simp
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
[PROOF STATE]
proof (state)
this:
lossless_resource (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) (CIPHER.KEY.res \<eta>)
goal (4 subgoals):
1. \<And>\<eta>. \<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>)), (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>))) \<turnstile>\<^sub>C (CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring \<surd>
2. \<And>\<eta>. interaction_any_bounded_converter ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring) 2
3. \<And>\<eta>. enat q * 2 \<le> enat (2 * q)
4. \<And>\<eta>. plossless_converter (\<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>))) ((\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>)))) ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring)
[PROOF STEP]
case (3 \<eta>)
[PROOF STATE]
proof (state)
this:
goal (4 subgoals):
1. \<And>\<eta>. \<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>)), (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>))) \<turnstile>\<^sub>C (CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring \<surd>
2. \<And>\<eta>. interaction_any_bounded_converter ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring) 2
3. \<And>\<eta>. enat q * 2 \<le> enat (2 * q)
4. \<And>\<eta>. plossless_converter (\<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>))) ((\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>)))) ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring)
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>)), (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>))) \<turnstile>\<^sub>C (CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring \<surd>
[PROOF STEP]
by(rule WT_intro)+
[PROOF STATE]
proof (state)
this:
\<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>)), (\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>))) \<turnstile>\<^sub>C (CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring \<surd>
goal (3 subgoals):
1. \<And>\<eta>. interaction_any_bounded_converter ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring) 2
2. \<And>\<eta>. enat q * 2 \<le> enat (2 * q)
3. \<And>\<eta>. plossless_converter (\<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>))) ((\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>)))) ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring)
[PROOF STEP]
case (4 \<eta>)
[PROOF STATE]
proof (state)
this:
goal (3 subgoals):
1. \<And>\<eta>. interaction_any_bounded_converter ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring) 2
2. \<And>\<eta>. enat q * 2 \<le> enat (2 * q)
3. \<And>\<eta>. plossless_converter (\<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>))) ((\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>)))) ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring)
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. interaction_any_bounded_converter ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring) 2
[PROOF STEP]
by interaction_bound_converter code_simp
[PROOF STATE]
proof (state)
this:
interaction_any_bounded_converter ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring) 2
goal (2 subgoals):
1. \<And>\<eta>. enat q * 2 \<le> enat (2 * q)
2. \<And>\<eta>. plossless_converter (\<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>))) ((\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>)))) ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring)
[PROOF STEP]
case (5 \<eta>)
[PROOF STATE]
proof (state)
this:
goal (2 subgoals):
1. \<And>\<eta>. enat q * 2 \<le> enat (2 * q)
2. \<And>\<eta>. plossless_converter (\<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>))) ((\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>)))) ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring)
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. enat q * 2 \<le> enat (2 * q)
[PROOF STEP]
by (simp add: mult_2_right)
[PROOF STATE]
proof (state)
this:
enat q * 2 \<le> enat (2 * q)
goal (1 subgoal):
1. \<And>\<eta>. plossless_converter (\<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>))) ((\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>)))) ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring)
[PROOF STEP]
case (6 \<eta>)
[PROOF STATE]
proof (state)
this:
goal (1 subgoal):
1. \<And>\<eta>. plossless_converter (\<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>))) ((\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>)))) ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring)
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. plossless_converter (\<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>))) ((\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>)))) ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring)
[PROOF STEP]
unfolding vld_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. plossless_converter (\<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>))) ((\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>)))) ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring)
[PROOF STEP]
by(rule plossless_intro WT_intro[unfolded vld_def])+
[PROOF STATE]
proof (state)
this:
plossless_converter (\<I>_uniform (nlists UNIV \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` nlists UNIV \<eta>))) ((\<I>_uniform UNIV (nlists UNIV \<eta>) \<oplus>\<^sub>\<I> \<I>_uniform UNIV (nlists UNIV \<eta>)) \<oplus>\<^sub>\<I> (\<I>_uniform (vld \<eta>) UNIV \<oplus>\<^sub>\<I> \<I>_uniform UNIV (insert None (Some ` vld \<eta>)))) ((CIPHER.enc \<eta> |\<^sub>= CIPHER.dec \<eta>) \<odot> parallel_wiring)
goal:
No subgoals!
[PROOF STEP]
qed |
# train_model.r
library('RPostgreSQL')
pg <- dbDriver("PostgreSQL")
con <- dbConnect(pg, user=Sys.getenv('USERNAME'), password=Sys.getenv('PASSWORD'),
host="localhost", port=5432, dbname="allergyalert")
dtab <- dbGetQuery(con, "
select distinct on(t.dateof) t.dateof, *
from daily_weather d
join pollutants p
on to_char(to_timestamp(p.dateof), 'YYYY-MM-DD') = to_char(to_timestamp(d.time), 'YYYY-MM-DD')
join treatments t
on to_char(to_timestamp(t.dateof), 'YYYY-MM-DD') = to_char(to_timestamp(d.time), 'YYYY-MM-DD')
join allergens a
on to_char(to_timestamp(a.dateof), 'YYYY-MM-DD') = to_char(to_timestamp(d.time), 'YYYY-MM-DD')
")
# for now, ignoring distinction between breathing treatment (2) and inhaler useage (1)
dtab$treatment_ <- ifelse(dtab$treatment>0, 1, 0)
model <- glm(
treatment_ ~ ozone
+ dewPoint
+ humidity
+ pressure
+ windSpeed
+ pollutant
+ Index
+ value,
data=dtab,
family=binomial(link="logit")
)
saveRDS(model, 'achoo_model_logistic_glm.r') |
State Before: α : Type uu
β : Type vv
l₁ l₂ : List α
⊢ ∀ {ts is l : List α}, l ~ is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts is State After: α : Type uu
β : Type vv
l₁ l₂ : List α
⊢ ∀ (ts is l : List α), l ~ is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts is Tactic: show ∀ (ts is l : List α),
l ~ is ++ ts → (∃ (is' : _)(_ : is' ~ is), l = is' ++ ts) ∨ l ∈ permutationsAux ts is State Before: α : Type uu
β : Type vv
l₁ l₂ : List α
⊢ ∀ (ts is l : List α), l ~ is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts is State After: α : Type uu
β : Type vv
l₁ l₂ : List α
⊢ ∀ (t : α) (ts is : List α),
(∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)) →
(∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []) →
∀ (l : List α), l ~ is ++ t :: ts → (∃ is' x, l = is' ++ t :: ts) ∨ l ∈ permutationsAux (t :: ts) is Tactic: refine' permutationsAux.rec (by simp) _ State Before: α : Type uu
β : Type vv
l₁ l₂ : List α
⊢ ∀ (t : α) (ts is : List α),
(∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)) →
(∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []) →
∀ (l : List α), l ~ is ++ t :: ts → (∃ is' x, l = is' ++ t :: ts) ∨ l ∈ permutationsAux (t :: ts) is State After: α : Type uu
β : Type vv
l₁ l₂ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l : List α
p : l ~ is ++ t :: ts
⊢ (∃ is' x, l = is' ++ t :: ts) ∨ l ∈ permutationsAux (t :: ts) is Tactic: intro t ts is IH1 IH2 l p State Before: α : Type uu
β : Type vv
l₁ l₂ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l : List α
p : l ~ is ++ t :: ts
⊢ (∃ is' x, l = is' ++ t :: ts) ∨ l ∈ permutationsAux (t :: ts) is State After: α : Type uu
β : Type vv
l₁ l₂ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l : List α
p : l ~ is ++ t :: ts
⊢ (∃ is' x, l = is' ++ t :: ts) ∨
l ∈ permutationsAux ts (t :: is) ∨ ∃ l₁ l₂, l₁ ++ l₂ ∈ permutations is ∧ l₂ ≠ [] ∧ l = l₁ ++ t :: l₂ ++ ts Tactic: rw [permutationsAux_cons, mem_foldr_permutationsAux2] State Before: α : Type uu
β : Type vv
l₁ l₂ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l : List α
p : l ~ is ++ t :: ts
⊢ (∃ is' x, l = is' ++ t :: ts) ∨
l ∈ permutationsAux ts (t :: is) ∨ ∃ l₁ l₂, l₁ ++ l₂ ∈ permutations is ∧ l₂ ≠ [] ∧ l = l₁ ++ t :: l₂ ++ ts State After: case inl.intro.intro
α : Type uu
β : Type vv
l₁ l₂ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l : List α
p : l ~ is ++ t :: ts
is' : List α
p' : is' ~ t :: is
e : l = is' ++ ts
⊢ (∃ is' x, l = is' ++ t :: ts) ∨
l ∈ permutationsAux ts (t :: is) ∨ ∃ l₁ l₂, l₁ ++ l₂ ∈ permutations is ∧ l₂ ≠ [] ∧ l = l₁ ++ t :: l₂ ++ ts
case inr
α : Type uu
β : Type vv
l₁ l₂ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l : List α
p : l ~ is ++ t :: ts
m : l ∈ permutationsAux ts (t :: is)
⊢ (∃ is' x, l = is' ++ t :: ts) ∨
l ∈ permutationsAux ts (t :: is) ∨ ∃ l₁ l₂, l₁ ++ l₂ ∈ permutations is ∧ l₂ ≠ [] ∧ l = l₁ ++ t :: l₂ ++ ts Tactic: rcases IH1 _ (p.trans perm_middle) with (⟨is', p', e⟩ | m) State Before: α : Type uu
β : Type vv
l₁ l₂ : List α
⊢ ∀ (is l : List α), l ~ is ++ [] → (∃ is' x, l = is' ++ []) ∨ l ∈ permutationsAux [] is State After: no goals Tactic: simp State Before: case inl.intro.intro
α : Type uu
β : Type vv
l₁ l₂ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l : List α
p : l ~ is ++ t :: ts
is' : List α
p' : is' ~ t :: is
e : l = is' ++ ts
⊢ (∃ is' x, l = is' ++ t :: ts) ∨
l ∈ permutationsAux ts (t :: is) ∨ ∃ l₁ l₂, l₁ ++ l₂ ∈ permutations is ∧ l₂ ≠ [] ∧ l = l₁ ++ t :: l₂ ++ ts State After: case inl.intro.intro
α : Type uu
β : Type vv
l₁ l₂ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l is' : List α
p' : is' ~ t :: is
e : l = is' ++ ts
⊢ (∃ is' x, l = is' ++ t :: ts) ∨
l ∈ permutationsAux ts (t :: is) ∨ ∃ l₁ l₂, l₁ ++ l₂ ∈ permutations is ∧ l₂ ≠ [] ∧ l = l₁ ++ t :: l₂ ++ ts Tactic: clear p State Before: case inl.intro.intro
α : Type uu
β : Type vv
l₁ l₂ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l is' : List α
p' : is' ~ t :: is
e : l = is' ++ ts
⊢ (∃ is' x, l = is' ++ t :: ts) ∨
l ∈ permutationsAux ts (t :: is) ∨ ∃ l₁ l₂, l₁ ++ l₂ ∈ permutations is ∧ l₂ ≠ [] ∧ l = l₁ ++ t :: l₂ ++ ts State After: case inl.intro.intro
α : Type uu
β : Type vv
l₁ l₂ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
is' : List α
p' : is' ~ t :: is
⊢ (∃ is'_1 x, is' ++ ts = is'_1 ++ t :: ts) ∨
is' ++ ts ∈ permutationsAux ts (t :: is) ∨
∃ l₁ l₂, l₁ ++ l₂ ∈ permutations is ∧ l₂ ≠ [] ∧ is' ++ ts = l₁ ++ t :: l₂ ++ ts Tactic: subst e State Before: case inl.intro.intro
α : Type uu
β : Type vv
l₁ l₂ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
is' : List α
p' : is' ~ t :: is
⊢ (∃ is'_1 x, is' ++ ts = is'_1 ++ t :: ts) ∨
is' ++ ts ∈ permutationsAux ts (t :: is) ∨
∃ l₁ l₂, l₁ ++ l₂ ∈ permutations is ∧ l₂ ≠ [] ∧ is' ++ ts = l₁ ++ t :: l₂ ++ ts State After: case inl.intro.intro.intro.intro
α : Type uu
β : Type vv
l₁✝ l₂✝ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
is' : List α
p' : is' ~ t :: is
l₁ l₂ : List α
e : is' = l₁ ++ t :: l₂
⊢ (∃ is'_1 x, is' ++ ts = is'_1 ++ t :: ts) ∨
is' ++ ts ∈ permutationsAux ts (t :: is) ∨
∃ l₁ l₂, l₁ ++ l₂ ∈ permutations is ∧ l₂ ≠ [] ∧ is' ++ ts = l₁ ++ t :: l₂ ++ ts Tactic: rcases mem_split (p'.symm.subset (mem_cons_self _ _)) with ⟨l₁, l₂, e⟩ State Before: case inl.intro.intro.intro.intro
α : Type uu
β : Type vv
l₁✝ l₂✝ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
is' : List α
p' : is' ~ t :: is
l₁ l₂ : List α
e : is' = l₁ ++ t :: l₂
⊢ (∃ is'_1 x, is' ++ ts = is'_1 ++ t :: ts) ∨
is' ++ ts ∈ permutationsAux ts (t :: is) ∨
∃ l₁ l₂, l₁ ++ l₂ ∈ permutations is ∧ l₂ ≠ [] ∧ is' ++ ts = l₁ ++ t :: l₂ ++ ts State After: case inl.intro.intro.intro.intro
α : Type uu
β : Type vv
l₁✝ l₂✝ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l₁ l₂ : List α
p' : l₁ ++ t :: l₂ ~ t :: is
⊢ (∃ is' x, l₁ ++ t :: l₂ ++ ts = is' ++ t :: ts) ∨
l₁ ++ t :: l₂ ++ ts ∈ permutationsAux ts (t :: is) ∨
∃ l₁_1 l₂_1, l₁_1 ++ l₂_1 ∈ permutations is ∧ l₂_1 ≠ [] ∧ l₁ ++ t :: l₂ ++ ts = l₁_1 ++ t :: l₂_1 ++ ts Tactic: subst is' State Before: case inl.intro.intro.intro.intro
α : Type uu
β : Type vv
l₁✝ l₂✝ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l₁ l₂ : List α
p' : l₁ ++ t :: l₂ ~ t :: is
⊢ (∃ is' x, l₁ ++ t :: l₂ ++ ts = is' ++ t :: ts) ∨
l₁ ++ t :: l₂ ++ ts ∈ permutationsAux ts (t :: is) ∨
∃ l₁_1 l₂_1, l₁_1 ++ l₂_1 ∈ permutations is ∧ l₂_1 ≠ [] ∧ l₁ ++ t :: l₂ ++ ts = l₁_1 ++ t :: l₂_1 ++ ts State After: case inl.intro.intro.intro.intro
α : Type uu
β : Type vv
l₁✝ l₂✝ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l₁ l₂ : List α
p' : l₁ ++ t :: l₂ ~ t :: is
p : l₁ ++ l₂ ~ is
⊢ (∃ is' x, l₁ ++ t :: l₂ ++ ts = is' ++ t :: ts) ∨
l₁ ++ t :: l₂ ++ ts ∈ permutationsAux ts (t :: is) ∨
∃ l₁_1 l₂_1, l₁_1 ++ l₂_1 ∈ permutations is ∧ l₂_1 ≠ [] ∧ l₁ ++ t :: l₂ ++ ts = l₁_1 ++ t :: l₂_1 ++ ts Tactic: have p := (perm_middle.symm.trans p').cons_inv State Before: case inl.intro.intro.intro.intro
α : Type uu
β : Type vv
l₁✝ l₂✝ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l₁ l₂ : List α
p' : l₁ ++ t :: l₂ ~ t :: is
p : l₁ ++ l₂ ~ is
⊢ (∃ is' x, l₁ ++ t :: l₂ ++ ts = is' ++ t :: ts) ∨
l₁ ++ t :: l₂ ++ ts ∈ permutationsAux ts (t :: is) ∨
∃ l₁_1 l₂_1, l₁_1 ++ l₂_1 ∈ permutations is ∧ l₂_1 ≠ [] ∧ l₁ ++ t :: l₂ ++ ts = l₁_1 ++ t :: l₂_1 ++ ts State After: case inl.intro.intro.intro.intro.nil
α : Type uu
β : Type vv
l₁✝ l₂ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l₁ : List α
p' : l₁ ++ [t] ~ t :: is
p : l₁ ++ [] ~ is
⊢ (∃ is' x, l₁ ++ [t] ++ ts = is' ++ t :: ts) ∨
l₁ ++ [t] ++ ts ∈ permutationsAux ts (t :: is) ∨
∃ l₁_1 l₂, l₁_1 ++ l₂ ∈ permutations is ∧ l₂ ≠ [] ∧ l₁ ++ [t] ++ ts = l₁_1 ++ t :: l₂ ++ ts
case inl.intro.intro.intro.intro.cons
α : Type uu
β : Type vv
l₁✝ l₂ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l₁ : List α
a : α
l₂' : List α
p' : l₁ ++ t :: a :: l₂' ~ t :: is
p : l₁ ++ a :: l₂' ~ is
⊢ (∃ is' x, l₁ ++ t :: a :: l₂' ++ ts = is' ++ t :: ts) ∨
l₁ ++ t :: a :: l₂' ++ ts ∈ permutationsAux ts (t :: is) ∨
∃ l₁_1 l₂, l₁_1 ++ l₂ ∈ permutations is ∧ l₂ ≠ [] ∧ l₁ ++ t :: a :: l₂' ++ ts = l₁_1 ++ t :: l₂ ++ ts Tactic: cases' l₂ with a l₂' State Before: case inl.intro.intro.intro.intro.nil
α : Type uu
β : Type vv
l₁✝ l₂ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l₁ : List α
p' : l₁ ++ [t] ~ t :: is
p : l₁ ++ [] ~ is
⊢ (∃ is' x, l₁ ++ [t] ++ ts = is' ++ t :: ts) ∨
l₁ ++ [t] ++ ts ∈ permutationsAux ts (t :: is) ∨
∃ l₁_1 l₂, l₁_1 ++ l₂ ∈ permutations is ∧ l₂ ≠ [] ∧ l₁ ++ [t] ++ ts = l₁_1 ++ t :: l₂ ++ ts State After: no goals Tactic: exact Or.inl ⟨l₁, by simpa using p⟩ State Before: α : Type uu
β : Type vv
l₁✝ l₂ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l₁ : List α
p' : l₁ ++ [t] ~ t :: is
p : l₁ ++ [] ~ is
⊢ ∃ x, l₁ ++ [t] ++ ts = l₁ ++ t :: ts State After: no goals Tactic: simpa using p State Before: case inl.intro.intro.intro.intro.cons
α : Type uu
β : Type vv
l₁✝ l₂ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l₁ : List α
a : α
l₂' : List α
p' : l₁ ++ t :: a :: l₂' ~ t :: is
p : l₁ ++ a :: l₂' ~ is
⊢ (∃ is' x, l₁ ++ t :: a :: l₂' ++ ts = is' ++ t :: ts) ∨
l₁ ++ t :: a :: l₂' ++ ts ∈ permutationsAux ts (t :: is) ∨
∃ l₁_1 l₂, l₁_1 ++ l₂ ∈ permutations is ∧ l₂ ≠ [] ∧ l₁ ++ t :: a :: l₂' ++ ts = l₁_1 ++ t :: l₂ ++ ts State After: no goals Tactic: exact Or.inr (Or.inr ⟨l₁, a :: l₂', mem_permutations_of_perm_lemma (IH2 _) p, by simp⟩) State Before: α : Type uu
β : Type vv
l₁✝ l₂ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l₁ : List α
a : α
l₂' : List α
p' : l₁ ++ t :: a :: l₂' ~ t :: is
p : l₁ ++ a :: l₂' ~ is
⊢ a :: l₂' ≠ [] ∧ l₁ ++ t :: a :: l₂' ++ ts = l₁ ++ t :: a :: l₂' ++ ts State After: no goals Tactic: simp State Before: case inr
α : Type uu
β : Type vv
l₁ l₂ : List α
t : α
ts is : List α
IH1 : ∀ (l : List α), l ~ t :: is ++ ts → (∃ is' x, l = is' ++ ts) ∨ l ∈ permutationsAux ts (t :: is)
IH2 : ∀ (l : List α), l ~ [] ++ is → (∃ is' x, l = is' ++ is) ∨ l ∈ permutationsAux is []
l : List α
p : l ~ is ++ t :: ts
m : l ∈ permutationsAux ts (t :: is)
⊢ (∃ is' x, l = is' ++ t :: ts) ∨
l ∈ permutationsAux ts (t :: is) ∨ ∃ l₁ l₂, l₁ ++ l₂ ∈ permutations is ∧ l₂ ≠ [] ∧ l = l₁ ++ t :: l₂ ++ ts State After: no goals Tactic: exact Or.inr (Or.inl m) |
#Note -- depends on test_syllablize.jl running first.
info("Testing syllable dominant frequency tracing...")
@test dftrace(a, syllables_boxed) == [[3, 3], [4, 2], [3]]
@test dftrace(a, syllables) == dftrace(a, syllables_boxed)
|
-- code from Edward Kmett's blog post
-- Mirrored Lenses
-- http://comonad.com/reader/2012/mirrored-lenses/
-- Slightly adapted since Data.PolyLens doesn't use Rank 2 types.
-- Mostly this means adding "Functor f =>" everywhere
import Data.Complex
import Data.PolyLens
realLens :: (RealFloat a, Functor f) => Lens (Complex a) a f
realLens f (r :+ i) = fmap (:+ i) (f r)
imagLens :: (RealFloat a, Functor f) => Lens (Complex a) a f
imagLens f (r :+ i) = fmap (r :+) (f i)
fstLens :: Functor f => PolyLens (a,c) (b,c) a b f
fstLens f (a, b) = fmap (\x -> (x, b)) (f a)
sndLens :: Functor f => PolyLens (a,b) (a,c) b c f
sndLens f (a, b) = fmap ((,) a) (f b)
swap :: (a, b) -> (b, a)
swap (a, b) = (b, a)
swapped :: Functor f => PolyLens (a, b) (c, d) (b, a) (d, c) f
swapped = iso swap swap
negated :: (Num a, Functor f) => Lens a a f
negated = iso negate negate
traverseLens :: ((c -> c) -> a -> b) -> a -> b
traverseLens f = f id
getFst :: Getter (a, b) a r
getFst = getting fst
getSnd :: Getter (a, b) b r
getSnd = getting snd
getPhase :: RealFloat a => Getter (Complex a) a r
getPhase = getting phase
getAbs, getSignum :: Num a => Getter a a r
getAbs = getting abs
getSignum = getting signum
plus, times :: Num a => Setter a a a
plus = setting (+)
times = setting (*)
reals :: (RealFloat a, RealFloat b) => Modifier (Complex a) (Complex b) a b
reals = modifying (\f (r :+ i) -> f r :+ f i)
|
#
# Exemplo 2
#
# Atribuição de valores para variáveis x1 e x2
x1 <- 0.003815
x2 <- 1234567890
# Realiza o mesmo cálculo do Exemplo 1 atribuindo o
# valor do resultado para a variável resultado1
resultado1 <- (x1 + x2) - x2
resultado1
# Realize o segundo cálculo do Exemplo 1 atribuindo
# o valor do resultado para a variável resultado2
resultado2 <- x1 + (x2 - x2)
resultado2 |
(* Suppress some annoying warnings from Coq: *)
Set Warnings "-notation-overridden,-parsing".
Add LoadPath "lf/"
Require Import lists.
(* Polymorphic lists *)
Inductive list (X : Type) : Type :=
| nil : list X
| cons : X -> list X -> list X.
Fixpoint repeat (X : Type) (x : X) (count : nat) : list X :=
match count with
| 0 => nil X
| S count' => cons X x (repeat X x count')
end.
Example test_repeat_1:
repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).
Proof.
reflexivity. Qed.
Example test_repeat_2:
repeat bool false 1 = cons bool false (nil bool).
Proof.
reflexivity. Qed.
(* Exercise *)
Module MumbleGrumble.
Inductive mumble : Type :=
| a : mumble
| b : mumble -> nat -> mumble
| c : mumble.
Inductive grumble (X : Type) : Type :=
| d : mumble -> grumble X
| e : X -> grumble X.
(* Check d (b a 5). *)
Check d mumble (b a 5).
Check d bool (b a 5).
Check e bool true.
Check e mumble (b c 0).
(* Check e bool (b c 0). *)
Check c.
(* Demonstrating type inference *)
Fixpoint repeat' X x count : list X :=
match count with
| 0 => nil X
| S count' => cons X x (repeat' X x count')
end.
(* and holes *)
Fixpoint repeat'' X x count : list X :=
match count with
| 0 => nil _
| S count' => cons _ x (repeat'' _ x count')
end.
(* and `Arguments` directive *)
Arguments nil {X}.
Arguments cons {X}.
Fixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=
match count with
| 0 => nil
| S count' => cons x (repeat''' x count')
end.
Check repeat.
Check repeat'.
Check repeat''.
Check repeat'''.
(* Reimplementing some standard list functions on the new polymorphic lists *)
Fixpoint app {X : Type} (m n : list X) : list X :=
match m with
| nil => n
| cons h t => cons h (app t n)
end.
Fixpoint rev {X : Type} (l : list X) : list X :=
match l with
| nil => nil
| cons h t => app (rev t) (cons h nil)
end.
Fixpoint length {X : Type} (l : list X) : nat :=
match l with
| nil => 0
| cons _ l' => S (length l')
end.
Example test_rev_1:
rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).
Proof.
reflexivity. Qed.
Example test_rev_2:
rev (cons true nil) = cons true nil.
Proof.
reflexivity. Qed.
Example test_length_1:
length (cons 1 (cons 2 (cons 3 nil))) = 3.
Proof.
reflexivity. Qed.
Notation "x :: y" := (cons x y)
(at level 60, right associativity).
Notation "[ ]" := nil.
Notation "[ x ; .. ; y ]" := (cons x .. (cons y []) ..).
Notation "x ++ y" := (app x y)
(at level 60, right associativity).
(* Exercise *)
Theorem app_nil_r: forall (X : Type), forall l : list X,
l ++ [] = l.
Proof.
intros.
induction l as [| k l' IHl' ].
- simpl. reflexivity.
- simpl. rewrite -> IHl'. reflexivity.
Qed.
Theorem app_assoc: forall A (l m n : list A),
l ++ m ++ n = (l ++ m) ++ n.
Proof.
intros.
induction l as [| k l' IHl' ].
- simpl. reflexivity.
- simpl. rewrite <- IHl'. reflexivity.
Qed.
Lemma app_length: forall (X : Type) (m n : list X),
length (m ++ n) = length m + length n.
Proof.
intros.
induction m as [| l m' IHm' ].
- simpl. reflexivity.
- simpl. rewrite -> IHm'. reflexivity.
Qed.
(* Exercise *)
Theorem rev_app_distr: forall X (m n : list X),
rev (m ++ n) = rev n ++ rev m.
Proof.
intros.
induction m as [| k m' IHm' ].
- simpl. rewrite -> app_nil_r. reflexivity.
- simpl. rewrite -> IHm', app_assoc. reflexivity.
Qed.
(* Exercise *)
Theorem rev_involutive: forall X : Type, forall l : list X,
rev (rev l) = l.
Proof.
intros.
induction l as [| k l' IHl' ].
- simpl. reflexivity.
- simpl.
rewrite -> rev_app_distr.
simpl. rewrite IHl'.
reflexivity.
Qed.
(* Demonstrating polymorphic pairs *)
Inductive prod (X Y : Type) : Type :=
| pair : X -> Y -> prod X Y.
Arguments pair {X} {Y} _ _.
Notation "( x , y )" := (pair x y).
Notation "X * Y" := (prod X Y) : type_scope.
Definition fst {X Y : Type} (p : X * Y) : X :=
match p with
| (x, y) => x
end.
Definition snd {X Y : Type} (p : X * Y) : Y :=
match p with
| (x, y) => y
end.
Fixpoint combine {X Y : Type} (lx : list X) (ly : list Y)
: list (X * Y) :=
match lx, ly with
| [], _ => []
| _, [] => []
| x :: tx, y :: ty => (x, y) :: (combine tx ty)
end.
(* Exercise *)
Compute (combine [1;2] [false;false;true;true]).
(* Exercise *)
Fixpoint iter_fst {X Y : Type} (l : list (X * Y))
: list X :=
match l with
| [] => nil
| p :: t => cons (fst p) (iter_fst t)
end.
Fixpoint iter_snd {X Y : Type} (l : list (X * Y))
: list Y :=
match l with
| [] => nil
| p :: t => cons (snd p) (iter_snd t)
end.
Definition split {X Y : Type} (l : list (X * Y))
: (list X) * (list Y) := (iter_fst l, iter_snd l).
Example test_split:
split [(1,false);(2,false)] = ([1;2],[false;false]).
Proof.
reflexivity. Qed.
(* Introducing functions *)
Definition doit3times {X : Type} (f: X -> X) (n : X) : X :=
f (f (f n)).
Check @doit3times.
(* ===> doit3times : forall X : Type, (X -> X) -> X -> X *)
Example test_doit3times: doit3times negb true = false.
Proof. reflexivity. Qed.
Fixpoint filter {X : Type} (test : X -> bool) (l : list X)
: (list X) :=
match l with
| [] => []
| h :: t =>
if test h
then h :: (filter test t)
else filter test t
end.
Example test_filter1: filter even [1;2;3;4] = [2;4].
Proof. reflexivity. Qed.
Definition length_is_1 {X : Type} (l : list X) : bool :=
beq_nat (length l) 1.
Example test_filter2:
filter length_is_1
[ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]
= [ [3]; [4]; [8] ].
Proof. reflexivity. Qed.
Definition countoddmembers' (l:list nat) : nat :=
length (filter odd l).
Example test_countoddmembers'1: countoddmembers' [1;0;3;1;4;5] = 4.
Proof. reflexivity. Qed.
Example test_countoddmembers'2: countoddmembers' [0;2;4] = 0.
Proof. reflexivity. Qed.
Example test_countoddmembers'3: countoddmembers' nil = 0.
Proof. reflexivity. Qed.
(* Demonstrating anonymous functions *)
Example test_anon_fun':
doit3times (fun n => n * n) 2 = 256.
Proof.
reflexivity. Qed.
Example test_filter2':
filter (fun l => beq_nat (length l) 1)
[ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]
= [ [3]; [4]; [8] ].
Proof. reflexivity. Qed.
(* Exercise *)
Definition filter_even_gt7 (l : list nat) : list nat :=
filter (fun x => bgt_nat x 7) (filter even l).
Compute filter_even_gt7 [1;2;6;9;10;3;12;8].
Example test_filter_even_gt7_1 :
filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].
Proof.
reflexivity. Qed.
Example test_filter_even_gt7_2 :
filter_even_gt7 [5;2;6;19;129] = [].
Proof.
reflexivity. Qed.
Definition partition {X : Type}
(test : X -> bool)
(l : list X)
: list X * list X :=
(filter test l, filter (fun x => negb (test x)) l).
Example test_partition1: partition odd [1;2;3;4;5] = ([1;3;5], [2;4]).
Proof.
reflexivity. Qed.
Example test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).
Proof.
reflexivity. Qed.
(* Map *)
Fixpoint map {X Y : Type} (f: X -> Y) (l: list X) : (list Y) :=
match l with
| [] => []
| h :: t => (f h) :: (map f t)
end.
Example test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].
Proof. reflexivity. Qed.
Example test_map2:
map odd [2;1;2;5] = [false;true;false;true].
Proof. reflexivity. Qed.
Example test_map3:
map (fun n => [even n;odd n]) [2;1;2;5]
= [[true;false];[false;true];[true;false];[false;true]].
Proof. reflexivity. Qed.
(* Exercise *)
Lemma map_app_distr:
forall (X Y : Type) (f: X -> Y) (l: list X) (m: list X),
map f (l ++ m) = (map f l) ++ (map f m).
Proof.
intros.
induction l as [| k l' IHl' ].
- simpl. reflexivity.
- simpl. rewrite <- IHl'. reflexivity.
Qed.
Theorem map_rev :
forall (X Y : Type) (f: X -> Y) (l: list X),
map f (rev l) = rev (map f l).
Proof.
intros.
induction l as [| k l' IHl' ].
- simpl. reflexivity.
- simpl.
rewrite -> map_app_distr.
simpl.
rewrite -> IHl'.
reflexivity.
Qed.
(* Exercise *)
Fixpoint flat_map
{X Y: Type} (f: X -> list Y) (l: list X)
: (list Y) :=
match l with
| nil => nil
| h :: t => (f h) ++ (flat_map f t)
end.
Example test_flat_map1:
flat_map (fun n => [n;n;n]) [1;5;4]
= [1; 1; 1; 5; 5; 5; 4; 4; 4].
Proof.
reflexivity. Qed.
(* Demonstrating fold *)
Fixpoint fold {X Y : Type} (f: X -> Y -> Y)
(l: list X) (b: Y) : Y :=
match l with
| nil => b
| h :: t => f h (fold f t b)
end.
Example fold_example1 :
fold mult [1;2;3;4] 1 = 24.
Proof.
reflexivity. Qed.
Example fold_example2 :
fold andb [true;true;false;true] true = false.
Proof.
reflexivity. Qed.
Example fold_example3 :
fold app [[1];[];[2;3];[4]] [] = [1;2;3;4].
Proof.
reflexivity. Qed.
End MumbleGrumble.
|
[STATEMENT]
lemma "\<upsilon>(null::('\<AA>)String) = true"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<upsilon> null = true
[PROOF STEP]
by simp |
%!TEX TS-program = pdflatex
% dissertation.tex -- main dissertation file
%
% Wisconsin dissertation template
% Copyright (c) 2008-2009 William C. Benton. All rights reserved.
%
% This program can redistributed and/or modified under the terms
% of the LaTeX Project Public License Distributed from CTAN
% archives in directory macros/latex/base/lppl.txt; either
% version 1 of the License, or (at your option) any later version.
%
% This program includes other software that is licensed under the
% terms of the LPPL and the Perl Artistic License; see README for details.
%
% You, the user, still hold the copyright to any document you produce
% with this software (like your dissertation).
%
% Copyright (c) 2013 Evan Driscoll
%
% In my evaluation the items remaining from Will's original version do not
% withstand the test of copyright, and so as a result I don't think I need to
% meet the sole criteria of the Latex PPL which I otherwise wouldn't -- I am
% not renaming this file.
%%% You'll want ``oneside'' for the deposit version, but probably not for any
%%% versions that don't need to meet the UW requirements
%\documentclass[12pt,letterpaper,numbers,oneside]{memoir}
%\documentclass[12pt,letterpaper,numbersm,oldfontcommands]{memoir}
%\documentclass[12pt, letterpaper, oldfontcommands]{memoir}
\documentclass[12pt, letterpaper, oldfontcommands, numbers,oneside]{memoir}
%\def\ShortenThesis{y}
%\newcommand{\TODO}[1]{\textbf{#1}\protect\marginnote{\large{[**]}}}
\newcommand{\CHECK}[1]{#1} %\protect\marginnote{\large{[**]}}}
\input{includes/preamble}
\input{includes/defs}
\usepackage[algo2e,noline,noend,linesnumbered,algochapter]{algorithm2e}
\usepackage{algorithmic} % must come after hyperref
\usepackage{algorithm}
\usepackage{aliascnt}
\usepackage{bookmark}
\usepackage{mathtools}
\usepackage{colortbl}
\usepackage{lipsum}
%\usepackage[hyphens]{url}
\PassOptionsToPackage{hyphens}{url}
% Include last: only autonum should be after this (or hypdvips, but if you
% need that you're doing something wrong)
\usepackage[capitalize]{cleveref}
\usepackage{alltt,url}
\usepackage{rotating}
%\usepackage{textcomp}
%\usepackage{graphics}
%\usepackage{floatflt}
\usepackage{multirow}
%\usepackage{cite}
%\usepackage{needspace}
%\usepackage[hyphens, breaklinks]{hyperref}
%\usepackage{breakurl}
\usepackage{hyperref}
%\usepackage{epstopdf}
%\epstopdfDeclareGraphicsRule{.eps}{pdf}{.pdf}{%
%ps2pdf -dEPSCrop #1 \OutputFile
%}
\usepackage{fancyvrb}
\usepackage{relsize}
\usepackage{soul}
\usepackage{array}
\usepackage{caption}
\usepackage{graphicx} % for subfigure
%\newsubfloat{figure} % for subfigure
%\usepackage{subfigure}
%\usepackage{subcaption}
%\captionsetup{compatibility=false}
%\captionsetup[subfigure]{labelformat=simple, labelsep=colon}
%\captionsetup[subfloat]{labelfont={bf,small},textfont={it,small},
%subrefformat=parens}
\usepackage{booktabs}
\usepackage{enumitem}
\usepackage{verbatim}
%\usepackage[toc,page]{appendix}
%%%%%%%%%%%%%%%%%%
\usepackage{caption}
\usepackage{subcaption}
\usepackage{multirow}
\usepackage{amssymb}% http://ctan.org/pkg/amssymb
\usepackage{pifont}% http://ctan.org/pkg/pifont
\usepackage{cleveref}
%%%%%%%%%%%%%%%%%%%%
\newlength{\tmpa}
\newlength{\tempa}
\input{macros}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% No \usepackage after this point %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\input{includes/thesisdefs}
% Some style options
\hangcaption
\captionnamefont{\small}
\captiontitlefont{\small}
\setsecnumdepth{subsection}
\maxtocdepth{subsection}
\crefname{algorithm}{Listing}{Listings}
\Crefname{algorithm}{Listing}{Listings}
\crefname{equation}{Equation}{Equations}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Number tables, theorems, and listings %%
%% inline with figures, instead of with %%
%% their own, parallel counter which is %%
%% dumb. %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\makeatletter
\let\c@table\@undefined
\let\c@thm\@undefined
\let\c@algocf\@undefined
\makeatother
\newaliascnt{table}{figure}
\newaliascnt{thm}{figure}
\newaliascnt{algocf}{figure}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\renewcommand{\AlCapSty}[1]{#1}
\renewcommand{\AlCapFnt}{\small}
\renewcommand*{\cftfigurename}{Figure\space}
\renewcommand*{\cftfigurename}{Figure\space}
\renewcommand*{\cfttablename}{Table\space}
%\newcommand*{\cftalgocfname}{Listing\space}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand{\algrule}[1][.2pt]{\par\vskip.2\baselineskip\hrule height #1\par\vskip.2\baselineskip}
\newcommand{\cf}{{cf.}\xspace}
\newcommand{\cut}[1]{}
\renewcommand{\ttdefault}{cmtt}
\newcommand{\tightparagraph}[1]{\vspace{5pt}\noindent\textbf{#1}\ }
\newcommand{\acdc}{{AC/DC}\xspace}
%\newcommand{\acdc}{{AC/DC}\xspace}
\newcommand{\cwnd}{{{\tt CWND}}\xspace}
\newcommand{\rwnd}{{{\tt RWND}}\xspace}
\newcommand{\crs}[1]{#1}% Do nothing
%\usepackage{cleveref}
\crefname{section}{§}{§§}
\Crefname{section}{§}{§§}
\crefformat{section}{§#2#1#3}
%%%%%rate limiter
\newcommand{\dem}{DEM\xspace}
\newcommand{\spring}{SPRING\xspace}
\newcommand{\nameone}{DEM\xspace}
\newcommand{\nametwo}{SPRING\xspace}
\newcommand{\cmark}{\ding{51}}%
\newcommand{\xmark}{\ding{55}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\overfullrule=2mm
% Thesis options
\title{Improving Datacenter Network Performance via Intelligent Network Edge}
\author{Keqiang He}
\department{Computer Sciences}
\date{2017 \vspace{-1in}}
\defensedate{June 8, 2017}
\committeeMemberOne{Aditya Akella, Professor, Computer Sciences}
\committeeMemberTwo{Suman Banerjee, Professor, Computer Sciences}
\committeeMemberThree{Eric Rozner, Research Staff Member, IBM Research}
\committeeMemberFour{Michael Swift, Associate Professor, Computer Sciences}
\committeeMemberFive{Xinyu Zhang, Assistant Professor, Electrical \& Computer Engineering}
\includeonly{frontmatter/fm,xfa-pcca}
\begin{document}
% Add \part declarations if you want, but it's not necessary
%\part{Preliminaries}
\ifdef{\ShortenThesis}{
}{
\include{frontmatter/fm}
}
\chapter{Introduction}
\label{thesis:chapter:intro}
\input{intro/intro}
\chapter{Edge-based Load Balancing for Fast Datacenter Networks}
\label{thesis:chapter:presto}
\input{presto/presto}
\chapter{Virtual Congestion Control Enforcement for Datacenter Networks}
\label{thesis:chapter:acdctcp}
\input{acdctcp/acdctcp}
\chapter{Low Latency Software Rate Limiters for Cloud Networks}
\label{thesis:chapter:rate_limiter}
\input{rate_limiter/rate_limiter}
\chapter{Related Work}
\label{thesis:chapter:related}
\input{related/related}
\chapter{Conclusion and Future Work}
\label{thesis:chapter:conclusion}
\input{conc/conc}
\bibliography{refs} % Make the bibliography
\bibliographystyle{plain}
%\lipsum
%\chapter{Something Else Cool}
%\lipsum
%\part{Second Part}
%\chapter{Something Even Cooler}
%\lipsum
% Ends the \part for purposes of the PDF TOC tree
%\bookmarksetup{startatroot}
%\chapter{Conclusions}
%\lipsum
\if 0
\begin{appendices}
\include{backmatter/appendix1}
%\include{appendix/main}
\end{appendices}
\appendix
\chapter{Appendix A}
\input{backmatter/appendix1}
\fi
\end{document}
|
```python
import sys, os
sys.path.insert(0, os.path.join(os.pardir, 'src'))
import sympy as sym
from approx1D import least_squares_orth, comparison_plot
import matplotlib.pyplot as plt
x = sym.Symbol('x')
def efficient(f, B, s, Omega, N=10, basis='a'):
u = B
for i in range(N+1):
if basis == 'a':
psi = [sym.sin((i+1)*x)]
elif basis == 'b':
psi = [sym.sin((2*i+1)*x)]
elif basis == 'c':
psi = [sym.sin(2*(i+1)*x)]
next_term, c = least_squares_orth(f-B, psi, Omega, False)
u = u + next_term
# Make only plot for i even
if i % 2 == 0:
comparison_plot(f, u, Omega, 'tmp_sin%02dx' % i,
legend_loc='upper left', show=False,
plot_title='s=%g, i=%d' % (s, i))
if __name__ == '__main__':
s = 20 # steepness
f = sym.tanh(s*(x-sym.pi))
from math import pi
Omega = [0, 2*pi] # sym.pi did not work here
# sin((i+1)*x) basis
xL = Omega[0]
xR = Omega[1]
B = ((xR-x)*f.subs(x, xL) + (x-xL)*f.subs(x, xR))/(xR-xL)
for exercise in 'a', 'b', 'c':
efficient(f, B, s, Omega, N=16, basis=exercise)
# Make movie
cmd = 'convert -delay 200 tmp_sin*.png '
cmd += 'tanh_sines_boundary_term_%s.gif' % exercise
os.system(cmd)
# Make static plots, 3 figures on 2 lines
for ext in 'pdf', 'png':
cmd = 'doconce combine_images %s -3 ' % ext
cmd += 'tmp_sin00x tmp_sin02x tmp_sin04x tmp_sin08x '
cmd += 'tmp_sin12x tmp_sin16x '
cmd += 'tanh_sines_boundary_term_%s' % exercise
os.system(cmd)
```
```python
```
|
<?xml version="1.0" encoding="utf-8"?>
<serviceModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="WebApplicationAzureDeployment" generation="1" functional="0" release="0" Id="9216712b-6430-4653-bf7b-c412c241b644" dslVersion="1.2.0.0" xmlns="http://schemas.microsoft.com/dsltools/RDSM">
<groups>
<group name="WebApplicationAzureDeploymentGroup" generation="1" functional="0" release="0">
<componentports>
<inPort name="WebApplication:dataup2httpsin" protocol="https">
<inToChannel>
<lBChannelMoniker name="/WebApplicationAzureDeployment/WebApplicationAzureDeploymentGroup/LB:WebApplication:dataup2httpsin" />
</inToChannel>
</inPort>
</componentports>
<settings>
<aCS name="Certificate|WebApplication:dataup2cert" defaultValue="">
<maps>
<mapMoniker name="/WebApplicationAzureDeployment/WebApplicationAzureDeploymentGroup/MapCertificate|WebApplication:dataup2cert" />
</maps>
</aCS>
<aCS name="WebApplication:FileDeletionAlertCheckpoints" defaultValue="">
<maps>
<mapMoniker name="/WebApplicationAzureDeployment/WebApplicationAzureDeploymentGroup/MapWebApplication:FileDeletionAlertCheckpoints" />
</maps>
</aCS>
<aCS name="WebApplication:FileDeletionAlertDisplayThreshold" defaultValue="">
<maps>
<mapMoniker name="/WebApplicationAzureDeployment/WebApplicationAzureDeploymentGroup/MapWebApplication:FileDeletionAlertDisplayThreshold" />
</maps>
</aCS>
<aCS name="WebApplication:Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" defaultValue="">
<maps>
<mapMoniker name="/WebApplicationAzureDeployment/WebApplicationAzureDeploymentGroup/MapWebApplication:Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" />
</maps>
</aCS>
<aCS name="WebApplicationInstances" defaultValue="[1,1,1]">
<maps>
<mapMoniker name="/WebApplicationAzureDeployment/WebApplicationAzureDeploymentGroup/MapWebApplicationInstances" />
</maps>
</aCS>
</settings>
<channels>
<lBChannel name="LB:WebApplication:dataup2httpsin">
<toPorts>
<inPortMoniker name="/WebApplicationAzureDeployment/WebApplicationAzureDeploymentGroup/WebApplication/dataup2httpsin" />
</toPorts>
</lBChannel>
</channels>
<maps>
<map name="MapCertificate|WebApplication:dataup2cert" kind="Identity">
<certificate>
<certificateMoniker name="/WebApplicationAzureDeployment/WebApplicationAzureDeploymentGroup/WebApplication/dataup2cert" />
</certificate>
</map>
<map name="MapWebApplication:FileDeletionAlertCheckpoints" kind="Identity">
<setting>
<aCSMoniker name="/WebApplicationAzureDeployment/WebApplicationAzureDeploymentGroup/WebApplication/FileDeletionAlertCheckpoints" />
</setting>
</map>
<map name="MapWebApplication:FileDeletionAlertDisplayThreshold" kind="Identity">
<setting>
<aCSMoniker name="/WebApplicationAzureDeployment/WebApplicationAzureDeploymentGroup/WebApplication/FileDeletionAlertDisplayThreshold" />
</setting>
</map>
<map name="MapWebApplication:Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" kind="Identity">
<setting>
<aCSMoniker name="/WebApplicationAzureDeployment/WebApplicationAzureDeploymentGroup/WebApplication/Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" />
</setting>
</map>
<map name="MapWebApplicationInstances" kind="Identity">
<setting>
<sCSPolicyIDMoniker name="/WebApplicationAzureDeployment/WebApplicationAzureDeploymentGroup/WebApplicationInstances" />
</setting>
</map>
</maps>
<components>
<groupHascomponents>
<role name="WebApplication" generation="1" functional="0" release="0" software="C:\DataOnboarding\Deployment\WebApplicationAzureDeployment\csx\Release\roles\WebApplication" entryPoint="base\x64\WaHostBootstrapper.exe" parameters="base\x64\WaIISHost.exe " memIndex="14336" hostingEnvironment="frontendadmin" hostingEnvironmentVersion="2">
<componentports>
<inPort name="dataup2httpsin" protocol="https" portRanges="443">
<certificate>
<certificateMoniker name="/WebApplicationAzureDeployment/WebApplicationAzureDeploymentGroup/WebApplication/dataup2cert" />
</certificate>
</inPort>
</componentports>
<settings>
<aCS name="FileDeletionAlertCheckpoints" defaultValue="" />
<aCS name="FileDeletionAlertDisplayThreshold" defaultValue="" />
<aCS name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" defaultValue="" />
<aCS name="__ModelData" defaultValue="<m role="WebApplication" xmlns="urn:azure:m:v1"><r name="WebApplication"><e name="dataup2httpsin" /></r></m>" />
</settings>
<resourcereferences>
<resourceReference name="DiagnosticStore" defaultAmount="[4096,4096,4096]" defaultSticky="true" kind="Directory" />
<resourceReference name="EventStore" defaultAmount="[1000,1000,1000]" defaultSticky="false" kind="LogStore" />
</resourcereferences>
<storedcertificates>
<storedCertificate name="Stored0dataup2cert" certificateStore="CA" certificateLocation="System">
<certificate>
<certificateMoniker name="/WebApplicationAzureDeployment/WebApplicationAzureDeploymentGroup/WebApplication/dataup2cert" />
</certificate>
</storedCertificate>
</storedcertificates>
<certificates>
<certificate name="dataup2cert" />
</certificates>
</role>
<sCSPolicy>
<sCSPolicyIDMoniker name="/WebApplicationAzureDeployment/WebApplicationAzureDeploymentGroup/WebApplicationInstances" />
<sCSPolicyUpdateDomainMoniker name="/WebApplicationAzureDeployment/WebApplicationAzureDeploymentGroup/WebApplicationUpgradeDomains" />
<sCSPolicyFaultDomainMoniker name="/WebApplicationAzureDeployment/WebApplicationAzureDeploymentGroup/WebApplicationFaultDomains" />
</sCSPolicy>
</groupHascomponents>
</components>
<sCSPolicy>
<sCSPolicyUpdateDomain name="WebApplicationUpgradeDomains" defaultPolicy="[5,5,5]" />
<sCSPolicyFaultDomain name="WebApplicationFaultDomains" defaultPolicy="[2,2,2]" />
<sCSPolicyID name="WebApplicationInstances" defaultPolicy="[1,1,1]" />
</sCSPolicy>
</group>
</groups>
<implements>
<implementation Id="0fb05564-53df-4fa5-a7a0-0c213f7cd435" ref="Microsoft.RedDog.Contract\ServiceContract\WebApplicationAzureDeploymentContract@ServiceDefinition">
<interfacereferences>
<interfaceReference Id="fed48e25-bef5-4332-9eda-65d750c62461" ref="Microsoft.RedDog.Contract\Interface\WebApplication:dataup2httpsin@ServiceDefinition">
<inPort>
<inPortMoniker name="/WebApplicationAzureDeployment/WebApplicationAzureDeploymentGroup/WebApplication:dataup2httpsin" />
</inPort>
</interfaceReference>
</interfacereferences>
</implementation>
</implements>
</serviceModel> |
function newName = rename(oldName , format, varargin)
% rename(fileTest, '%s/<name>--DRIM.png', dirDrimResult)
[path, name, ext] = fileparts(oldName);
if numel(varargin) ~= 0
format = sprintf(format, varargin{:});
end
newName = strrep(format, '<path>', path);
newName = strrep(newName, '<name>', name);
newName = strrep(newName, '<ext>', ext(2:end)); % no . mark
end |
While in the bathroom , Bart notices that the water in the sink always drains counterclockwise . Lisa explains ( not entirely correctly ) that the water never drains the other way except in the southern hemisphere , due to the Coriolis effect , but Bart does not believe her . To confirm this , Bart makes phone calls to various countries in the southern hemisphere . Lisa points out how expensive international calls are , so Bart decides to make a collect call instead . He calls Australia , where a little boy answers the phone . Pretending to represent the " International Drainage Commission " , Bart is informed that the toilet and sink are both draining clockwise . Frustrated , Bart asks him to go and check the toilets of the neighbors . The call takes six hours to complete , since the boy lives in the outback , and Bart forgets to hang up the phone . Later , the boy 's father is billed A $ 900 ( referred to as " <unk> " ) . The father calls Bart and demands that he pay , but Bart only taunts him . Unfortunately for Bart , the father 's neighbour is a federal Member of Parliament , who reports Bart 's offense to the Prime Minister — who is relaxing naked in a nearby pond .
|
#ifndef _MU_NSQ_
#define _MU_NSQ_
#include <vector>
#include <iostream>
#include <nuSQuIDS/nuSQuIDS.h>
#include <gsl/gsl_deriv.h>
#include "exCross.h"
namespace musquids {
using nusquids::nuSQUIDS;
using nusquids::marray;
/// \brief This class implements muon energy loss into nuSQuIDS.
class muSQUIDS: public nuSQUIDS {
private:
std::vector<double> inv_lambda;
marray<double,2> dScalardE;
/// The following variables are to evaluate the derivative of the scalar flux
std::shared_ptr<gsl_spline> scalar_spline;
std::shared_ptr<gsl_interp_accel> scalar_spline_acc;
std::vector<double> tmp_scalar_state;
protected:
/// \brief Here we will calculate the muon flux derivative
void AddToPreDerive(double x){
for(size_t si=0; si<dScalardE.extent(0); si++){
for(size_t ei; ei<dScalardE.extent(1); ei++){
tmp_scalar_state[ei] = state[ei].scalar[si];
}
gsl_spline_init(scalar_spline.get(),E_range.get_data(),tmp_scalar_state.data(),ne);
gsl_interp_accel_reset(scalar_spline_acc.get());
for(size_t ei; ei<dScalardE.extent(1); ei++){
dScalardE[si][ei] = gsl_spline_eval_deriv(scalar_spline.get(),E_range[ei],scalar_spline_acc.get());
}
}
}
protected:
double EnergyLoss(double Emuon) const {
// From T. Gaisser Cosmic Ray book
// From http://pdg.lbl.gov/2015/AtomicNuclearProperties/
// Good from Emuon>10Gev
double RadDensH=4.405e5; // gr/cm^2
// current_density in gr/cm^3
// coeffcients in MeV/cm^2
return (((-1.9-0.08*log(Emuon/params.muon_mass))-(Emuon/params.MeV)/RadDensH)*current_density)*(params.MeV/params.cm);
}
double Fmue(double Emuon, double Enu) const {
// Fits to muon decay spectrum including spin
double z = Enu/Emuon;
return (1.79779466e-02*pow(z,4)+1.20239959e+01*pow(z,3.)-2.38837016e+01*z*z+1.17861335e+01*z+5.85725324e-02)/Emuon;
}
double Fmumu(double Emuon, double Enu) const {
// Fits to muon decay spectrum including spin
double z = Enu/Emuon;
return (-0.24794224*pow(z,4.)+4.51300659*pow(z,3.)-6.2556965*z*z-0.03647084*z+2.02480429)/Emuon;
}
double lambda(double Emuon) const {
return Emuon*params.muon_lifetime/params.muon_mass;
}
protected:
// These scalar functions will manage the muon decay and energy loss
double GammaScalar(unsigned int ei,unsigned int index_scalar) const {
double muon_decay_term=inv_lambda[ei];
return nuSQUIDS::GammaScalar(ei,index_scalar) + muon_decay_term;
}
double InteractionsScalar(unsigned int ei,unsigned int index_scalar) const {
double muon_energy_loss_terms=EnergyLoss(E_range[ei])*dScalardE[index_scalar][ei];
return nuSQUIDS::InteractionsScalar(ei,index_scalar) + muon_energy_loss_terms;
}
// This rho function will add the neutrinos from muon decay
squids::SU_vector InteractionsRho(unsigned int ei,unsigned int index_rho) const {
squids::SU_vector from_muon_decay_terms(nsun);
double muon_decay_to_muon_integral = 0.;
double muon_decay_to_e_integral = 0.;
unsigned int other_index_rho = (index_rho == 0) ? 1 : 0;
for(unsigned int em = ei+1; em < ne; em++){ // loop in the tau neutrino energies
muon_decay_to_muon_integral += state[em].scalar[index_rho]*Fmumu(E_range[em],E_range[ei])*inv_lambda[em]*delE[em-1];
muon_decay_to_e_integral += state[em].scalar[other_index_rho]*Fmue(E_range[em],E_range[ei])*inv_lambda[em]*delE[em-1];
}
from_muon_decay_terms += evol_b1_proj[index_rho][1][ei]*muon_decay_to_muon_integral;
from_muon_decay_terms += evol_b1_proj[index_rho][0][ei]*muon_decay_to_e_integral;
return nuSQUIDS::InteractionsRho(ei,index_rho) + from_muon_decay_terms;
}
public:
muSQUIDS(){}
muSQUIDS(marray<double,1> E_range,
int numneu=3, nusquids::NeutrinoType NT=nusquids::both,bool iinteraction=true):
nuSQUIDS(E_range,numneu,NT,iinteraction,std::make_shared<nusquids::NeutrinoDISCrossSectionsFromTablesExtended>()),
scalar_spline(gsl_spline_alloc(gsl_interp_cspline,E_range.size()),[](gsl_spline* t){ gsl_spline_free(t);}),
scalar_spline_acc(gsl_interp_accel_alloc(),[](gsl_interp_accel* t){ gsl_interp_accel_free(t);})
{
// resetting squids nodes to the right scalar size
ini(ne,numneu,nrhos,2,Get_t());
// initializing the muon decay lenght
inv_lambda.resize(ne);
for(unsigned int ei=0; ei<ne; ei++)
inv_lambda[ei] = 1./lambda(E_range[ei]);
// initializing the scalar derivative matrix
dScalardE.resize(std::vector<size_t>{nscalars,ne});
std::fill(dScalardE.begin(),dScalardE.end(),0);
// initializing the scalar temporary state
tmp_scalar_state.resize(ne);
std::fill(tmp_scalar_state.begin(),tmp_scalar_state.end(),0);
}
void Set_initial_state(const marray<double,2>& muon_flux,const marray<double,3>& neutrino_state,nusquids::Basis basis)
{
nuSQUIDS::Set_initial_state(neutrino_state,basis);
for(unsigned int ie = 0; ie < ne; ie++){
for(unsigned int ir = 0; ir < nscalars; ir++){
state[ie].scalar[ir] = muon_flux[ie][ir];
}
}
}
double GetMuonFlux(unsigned int ie, unsigned int irho){
return state[ie].scalar[irho];
}
};
} // close musquids namespace
#endif
|
/-
Copyright (c) 2022 Alexander Bentkamp. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp
! This file was ported from Lean 3 source module linear_algebra.matrix.pos_def
! leanprover-community/mathlib commit 46b633fd842bef9469441c0209906f6dddd2b4f5
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.LinearAlgebra.Matrix.Spectrum
import Mathbin.LinearAlgebra.QuadraticForm.Basic
/-! # Positive Definite Matrices
This file defines positive (semi)definite matrices and connects the notion to positive definiteness
of quadratic forms.
## Main definition
* `matrix.pos_def` : a matrix `M : matrix n n 𝕜` is positive definite if it is hermitian and `xᴴMx`
is greater than zero for all nonzero `x`.
* `matrix.pos_semidef` : a matrix `M : matrix n n 𝕜` is positive semidefinite if it is hermitian
and `xᴴMx` is nonnegative for all `x`.
-/
namespace Matrix
variable {𝕜 : Type _} [IsROrC 𝕜] {m n : Type _} [Fintype m] [Fintype n]
open Matrix
/-- A matrix `M : matrix n n 𝕜` is positive definite if it is hermitian
and `xᴴMx` is greater than zero for all nonzero `x`. -/
def PosDef (M : Matrix n n 𝕜) :=
M.IsHermitian ∧ ∀ x : n → 𝕜, x ≠ 0 → 0 < IsROrC.re (dotProduct (star x) (M.mulVec x))
#align matrix.pos_def Matrix.PosDef
theorem PosDef.isHermitian {M : Matrix n n 𝕜} (hM : M.PosDef) : M.IsHermitian :=
hM.1
#align matrix.pos_def.is_hermitian Matrix.PosDef.isHermitian
/-- A matrix `M : matrix n n 𝕜` is positive semidefinite if it is hermitian
and `xᴴMx` is nonnegative for all `x`. -/
def PosSemidef (M : Matrix n n 𝕜) :=
M.IsHermitian ∧ ∀ x : n → 𝕜, 0 ≤ IsROrC.re (dotProduct (star x) (M.mulVec x))
#align matrix.pos_semidef Matrix.PosSemidef
theorem PosDef.posSemidef {M : Matrix n n 𝕜} (hM : M.PosDef) : M.PosSemidef :=
by
refine' ⟨hM.1, _⟩
intro x
by_cases hx : x = 0
· simp only [hx, zero_dot_product, star_zero, IsROrC.zero_re']
· exact le_of_lt (hM.2 x hx)
#align matrix.pos_def.pos_semidef Matrix.PosDef.posSemidef
theorem PosSemidef.submatrix {M : Matrix n n 𝕜} (hM : M.PosSemidef) (e : m ≃ n) :
(M.submatrix e e).PosSemidef :=
by
refine' ⟨hM.1.submatrix e, fun x => _⟩
have : (M.submatrix (⇑e) ⇑e).mulVec x = (M.mul_vec fun i : n => x (e.symm i)) ∘ e :=
by
ext i
dsimp only [(· ∘ ·), mul_vec, dot_product]
rw [Finset.sum_bij' (fun i _ => e i) _ _ fun i _ => e.symm i] <;>
simp only [eq_self_iff_true, imp_true_iff, Equiv.symm_apply_apply, Finset.mem_univ,
submatrix_apply, Equiv.apply_symm_apply]
rw [this]
convert hM.2 fun i => x (e.symm i) using 3
unfold dot_product
rw [Finset.sum_bij' (fun i _ => e i) _ _ fun i _ => e.symm i] <;>
simp only [eq_self_iff_true, imp_true_iff, Equiv.symm_apply_apply, Finset.mem_univ,
submatrix_apply, Equiv.apply_symm_apply, Pi.star_apply]
#align matrix.pos_semidef.submatrix Matrix.PosSemidef.submatrix
@[simp]
theorem posSemidef_submatrix_equiv {M : Matrix n n 𝕜} (e : m ≃ n) :
(M.submatrix e e).PosSemidef ↔ M.PosSemidef :=
⟨fun h => by simpa using h.submatrix e.symm, fun h => h.submatrix _⟩
#align matrix.pos_semidef_submatrix_equiv Matrix.posSemidef_submatrix_equiv
theorem PosDef.transpose {M : Matrix n n 𝕜} (hM : M.PosDef) : Mᵀ.PosDef :=
by
refine' ⟨is_hermitian.transpose hM.1, fun x hx => _⟩
convert hM.2 (star x) (star_ne_zero.2 hx) using 2
rw [mul_vec_transpose, Matrix.dotProduct_mulVec, star_star, dot_product_comm]
#align matrix.pos_def.transpose Matrix.PosDef.transpose
theorem posDef_of_toQuadraticForm' [DecidableEq n] {M : Matrix n n ℝ} (hM : M.IsSymm)
(hMq : M.toQuadraticForm'.PosDef) : M.PosDef :=
by
refine' ⟨hM, fun x hx => _⟩
simp only [to_quadratic_form', QuadraticForm.PosDef, BilinForm.toQuadraticForm_apply,
Matrix.toBilin'_apply'] at hMq
apply hMq x hx
#align matrix.pos_def_of_to_quadratic_form' Matrix.posDef_of_toQuadraticForm'
theorem posDefToQuadraticForm' [DecidableEq n] {M : Matrix n n ℝ} (hM : M.PosDef) :
M.toQuadraticForm'.PosDef := by
intro x hx
simp only [to_quadratic_form', BilinForm.toQuadraticForm_apply, Matrix.toBilin'_apply']
apply hM.2 x hx
#align matrix.pos_def_to_quadratic_form' Matrix.posDefToQuadraticForm'
namespace PosDef
variable {M : Matrix n n ℝ} (hM : M.PosDef)
include hM
theorem det_pos [DecidableEq n] : 0 < det M :=
by
rw [hM.is_hermitian.det_eq_prod_eigenvalues]
apply Finset.prod_pos
intro i _
rw [hM.is_hermitian.eigenvalues_eq]
apply hM.2 _ fun h => _
have h_det : hM.is_hermitian.eigenvector_matrixᵀ.det = 0 :=
Matrix.det_eq_zero_of_row_eq_zero i fun j => congr_fun h j
simpa only [h_det, not_isUnit_zero] using
is_unit_det_of_invertible hM.is_hermitian.eigenvector_matrixᵀ
#align matrix.pos_def.det_pos Matrix.PosDef.det_pos
end PosDef
end Matrix
namespace QuadraticForm
variable {n : Type _} [Fintype n]
theorem posDefOfToMatrix' [DecidableEq n] {Q : QuadraticForm ℝ (n → ℝ)} (hQ : Q.toMatrix'.PosDef) :
Q.PosDef :=
by
rw [← to_quadratic_form_associated ℝ Q, ← bilin_form.to_matrix'.left_inv ((associated_hom _) Q)]
apply Matrix.posDefToQuadraticForm' hQ
#align quadratic_form.pos_def_of_to_matrix' QuadraticForm.posDefOfToMatrix'
theorem posDef_toMatrix' [DecidableEq n] {Q : QuadraticForm ℝ (n → ℝ)} (hQ : Q.PosDef) :
Q.toMatrix'.PosDef :=
by
rw [← to_quadratic_form_associated ℝ Q, ←
bilin_form.to_matrix'.left_inv ((associated_hom _) Q)] at hQ
apply Matrix.posDef_of_toQuadraticForm' (is_symm_to_matrix' Q) hQ
#align quadratic_form.pos_def_to_matrix' QuadraticForm.posDef_toMatrix'
end QuadraticForm
namespace Matrix
variable {𝕜 : Type _} [IsROrC 𝕜] {n : Type _} [Fintype n]
/-- A positive definite matrix `M` induces a norm `‖x‖ = sqrt (re xᴴMx)`. -/
@[reducible]
noncomputable def NormedAddCommGroup.ofMatrix {M : Matrix n n 𝕜} (hM : M.PosDef) :
NormedAddCommGroup (n → 𝕜) :=
@InnerProductSpace.OfCore.toNormedAddCommGroup _ _ _ _ _
{ inner := fun x y => dotProduct (star x) (M.mulVec y)
conj_symm := fun x y => by
rw [star_dot_product, starRingEnd_apply, star_star, star_mul_vec, dot_product_mul_vec,
hM.is_hermitian.eq]
nonneg_re := fun x => by
by_cases h : x = 0
· simp [h]
· exact le_of_lt (hM.2 x h)
definite := fun x hx => by
by_contra' h
simpa [hx, lt_self_iff_false] using hM.2 x h
add_left := by simp only [star_add, add_dot_product, eq_self_iff_true, forall_const]
smul_left := fun x y r => by
rw [← smul_eq_mul, ← smul_dot_product, starRingEnd_apply, ← star_smul] }
#align matrix.normed_add_comm_group.of_matrix Matrix.NormedAddCommGroup.ofMatrix
/-- A positive definite matrix `M` induces an inner product `⟪x, y⟫ = xᴴMy`. -/
def InnerProductSpace.ofMatrix {M : Matrix n n 𝕜} (hM : M.PosDef) :
@InnerProductSpace 𝕜 (n → 𝕜) _ (NormedAddCommGroup.ofMatrix hM) :=
InnerProductSpace.ofCore _
#align matrix.inner_product_space.of_matrix Matrix.InnerProductSpace.ofMatrix
end Matrix
|
Jan 30 (Lagos) - The Nigerian Naira was steady against a broadly weaker Dollar despite US-China trade tensions and global growth fears weighing on risk sentiment.
With no key economic reports expected from Nigeria today, the Naira is likely to remain driven by geopolitical risk factors, the Dollar’s performance and global sentiment. However, the Naira’s medium- to long-term outlook hangs on the upcoming presidential elections and oil prices.
If increased government and election-related spending ends up stimulating inflationary pressures, this is seen impacting the Naira exchange. The local currency is likely to be pressured further by falling oil prices, especially when considering how WTI Crude is struggling to keep above $52.
It remains unclear how the second parliamentary vote will play out, especially when considering how ‘Plan B’ shares many similarities with ‘Plan A’ which was previously rejected by British MP’s. Although the pending vote is not legally binding, it should provide fresh insight into what the House of Commons desires regarding Brexit. While there are more than a dozen amendments suggested, Sterling is seen appreciating if the speaker chooses the Cooper and Brady amendments.
Although expectations continue to mount over the government extending Article 50, it is worth noting that the unanimous agreement of all the remaining 27 EU countries will be needed for this to materialize. The truth of the matter remains that one must always expect the unexpected when dealing with Brexit, and the parliamentary Brexit vote this evening should be no exception.
Source - Lukman Otunuga FXTM. |
#define BOOST_TEST_MODULE Controlling output
#include <boost/test/included/unit_test.hpp>
BOOST_AUTO_TEST_CASE(test_case) {
BOOST_TEST(true);
}
BOOST_AUTO_TEST_SUITE(test_suite)
BOOST_AUTO_TEST_CASE(test_case) {
int a = 42;
BOOST_TEST(a == 0);
}
BOOST_AUTO_TEST_SUITE_END() |
From Perennial.program_proof.mvcc Require Import
wrbuf_prelude wrbuf_repr
index_proof
tuple_repr tuple_own tuple_free tuple_write_lock.
Section heap.
Context `{!heapGS Σ, !mvcc_ghostG Σ}.
(*****************************************************************)
(* func swap(ents []WrEnt, i, j uint64) *)
(*****************************************************************)
Local Lemma wp_swap (entsS : Slice.t) (ents : list wrent) (i j : u64) :
{{{ slice.is_slice_small entsS (structTy WrEnt) 1 (wrent_to_val <$> ents) ∗
⌜(int.nat i < length ents ∧ int.nat j < length ents)%nat⌝
}}}
swap (to_val entsS) #i #j
{{{ (ents' : list wrent), RET #();
slice.is_slice_small entsS (structTy WrEnt) 1 (wrent_to_val <$> ents') ∗
⌜ents' ≡ₚ ents⌝
}}}.
Proof.
iIntros (Φ) "[HentsS %Hbounds] HΦ".
destruct Hbounds as [Hi Hj].
apply list_lookup_lt in Hi as Hx.
destruct Hx as [x Hx].
apply list_lookup_lt in Hj as Hy.
destruct Hy as [y Hy].
iDestruct (is_slice_small_sz with "HentsS") as "%HentsLen".
rewrite fmap_length in HentsLen.
wp_call.
(***********************************************************)
(* tmp := ents[i] *)
(* ents[i] = ents[j] *)
(* ents[j] = tmp *)
(***********************************************************)
wp_apply (wp_SliceGet with "[$HentsS]").
{ iPureIntro. by rewrite list_lookup_fmap Hx. }
iIntros "[HentsS %Htyx]".
wp_apply (wp_SliceGet with "[$HentsS]").
{ iPureIntro. by rewrite list_lookup_fmap Hy. }
iIntros "[HentsS %Htyy]".
wp_apply (wp_SliceSet with "[$HentsS]").
{ iPureIntro. split; last done. by rewrite list_lookup_fmap fmap_is_Some. }
iIntros "HentsS".
wp_apply (wp_SliceSet with "[$HentsS]").
{ iPureIntro. split; last done.
rewrite -list_fmap_insert list_lookup_fmap fmap_is_Some.
apply lookup_lt_is_Some_2.
rewrite insert_length.
word.
}
iIntros "HentsS".
wp_pures.
iApply "HΦ".
iFrame.
do 2 rewrite -list_fmap_insert.
iFrame.
iPureIntro.
apply list_insert_insert_swap; done.
Qed.
(*********************************************************************)
(* func (wrbuf *WrBuf) sortEntsByKey() *)
(*********************************************************************)
Theorem wp_wrbuf__sortEntsByKey wrbuf mods :
{{{ own_wrbuf_xtpls wrbuf mods }}}
WrBuf__sortEntsByKey #wrbuf
{{{ RET #(); own_wrbuf_xtpls wrbuf mods }}}.
Proof.
iIntros (Φ) "Hwrbuf HΦ".
wp_call.
(***********************************************************)
(* ents := wrbuf.ents *)
(* var i uint64 = 1 *)
(***********************************************************)
iNamed "Hwrbuf".
wp_loadField.
wp_pures.
wp_apply (wp_ref_to); first by auto.
iIntros (iRef) "HiRef".
wp_pures.
iDestruct (is_slice_small_acc with "HentsS") as "[HentsS HentsC]".
iDestruct (is_slice_small_sz with "HentsS") as "%HentsLen".
rewrite fmap_length in HentsLen.
(***********************************************************)
(* for i < uint64(len(ents)) { *)
(* var j uint64 = i *)
(* for j > 0 { *)
(* if ents[j - 1].key <= ents[j].key { *)
(* break *)
(* } *)
(* swap(ents, j - 1, j) *)
(* j-- *)
(* } *)
(* i++ *)
(* } *)
(***********************************************************)
set P := (λ (b : bool), ∃ (ents' : list wrent) (i : u64),
"HentsS" ∷ is_slice_small entsS (struct.t WrEnt) 1 (wrent_to_val <$> ents') ∗
"HiRef" ∷ iRef ↦[uint64T] #i ∗
"%Hperm" ∷ ⌜ents' ≡ₚ ents⌝
)%I.
wp_apply (wp_forBreak_cond P with "[] [HentsS HiRef]").
{ (* Outer loop body. *)
clear Φ.
iIntros (Φ) "!> HP HΦ".
iNamed "HP".
wp_load.
wp_apply (wp_slice_len).
wp_if_destruct; last first.
{ (* Outer loop condition. *)
iApply "HΦ".
subst P. simpl.
eauto 10 with iFrame.
}
wp_load.
wp_apply (wp_ref_to); first by auto.
iIntros (jRef) "HjRef".
wp_pures.
(* Inner loop. *)
set Q := (λ (b : bool), ∃ (ents'' : list wrent) (j : u64),
"HentsS" ∷ is_slice_small entsS (struct.t WrEnt) 1 (wrent_to_val <$> ents'') ∗
"HjRef" ∷ jRef ↦[uint64T] #j ∗
"%Hperm" ∷ ⌜ents'' ≡ₚ ents'⌝ ∗
"%Hle" ∷ ⌜int.Z j ≤ int.Z i⌝
)%I.
wp_apply (wp_forBreak_cond Q with "[] [HentsS HjRef]").
{ (* Inner loop body. *)
clear Φ.
iIntros (Φ) "!> HQ HΦ".
iNamed "HQ".
wp_load.
wp_if_destruct; last first.
{ (* Inner loop condition. *)
iApply "HΦ".
subst Q. simpl.
eauto 10 with iFrame.
}
wp_pures.
assert (Hboundj : (int.nat j < length ents'')%nat).
{ apply Permutation_length in Hperm, Hperm0. word. }
(* Read key of entry at [j - 1]. *)
wp_load.
destruct (list_lookup_lt _ (wrent_to_val <$> ents'') (int.nat (word.sub j (U64 1)))) as [entx Hlookupx].
{ rewrite fmap_length. word. }
wp_apply (wp_SliceGet with "[$HentsS]"); first done.
iIntros "[HentsS %Hty]".
wp_pures.
apply val_to_wrent_with_val_ty in Hty as (kx & vx & wx & tx & Hentx).
subst entx.
wp_pures.
(* Read key of entry at [j]. *)
wp_load.
destruct (list_lookup_lt _ (wrent_to_val <$> ents'') (int.nat j)) as [enty Hlookupy].
{ rewrite fmap_length. word. }
wp_apply (wp_SliceGet with "[$HentsS]"); first done.
iIntros "[HentsS %Hty]".
wp_pures.
apply val_to_wrent_with_val_ty in Hty as (ky & vy & wy & ty & Henty).
subst enty.
wp_pures.
wp_if_destruct.
{ (* Early return of inner loop. *)
iApply "HΦ". subst Q. simpl.
eauto with iFrame.
}
(* Swap entries at [j - 1] and at [j]. *)
do 2 wp_load.
wp_apply (wp_swap with "[$HentsS]").
{ iPureIntro. word. }
iIntros (ents1) "[HentsS %Hperm1]".
wp_load.
wp_store.
iApply "HΦ".
subst Q. simpl.
do 2 iExists _.
iFrame.
iPureIntro.
split; last by word.
by rewrite -Hperm0.
}
{ (* Inner loop entry. *)
subst Q. simpl.
eauto with iFrame.
}
(* Increment [i]. *)
iIntros "HQ".
subst Q. simpl.
iNamed "HQ".
wp_load.
wp_store.
iApply "HΦ".
subst P. simpl.
do 2 iExists _. iFrame.
iPureIntro.
by rewrite <- Hperm.
}
{ (* Outer loop entry. *)
subst P. simpl.
eauto with iFrame.
}
(* RETURN. *)
iIntros "HP".
subst P. simpl.
iNamed "HP".
iDestruct ("HentsC" with "HentsS") as "HentsS".
wp_pures.
iApply "HΦ".
do 2 iExists _.
iFrame.
iPureIntro.
split.
{ (* Prove [NoDup]. *)
by rewrite Hperm.
}
{ (* Prove [list_to_map]. *)
rewrite Hmods.
apply list_to_map_proper; last by rewrite Hperm.
by apply NoDup_wrent_to_key_dbval.
}
Qed.
End heap.
|
[STATEMENT]
lemma funion_transfer [transfer_rule]:
"(rel_fset A ===> rel_fset A ===> rel_fset A) funion funion"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (rel_fset A ===> rel_fset A ===> rel_fset A) (|\<union>|) (|\<union>|)
[PROOF STEP]
unfolding rel_fun_def rel_fset_alt_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>x y. (\<forall>xa. \<exists>ya. xa |\<in>| x \<longrightarrow> ya |\<in>| y \<and> A xa ya) \<and> (\<forall>ya. \<exists>xa. ya |\<in>| y \<longrightarrow> xa |\<in>| x \<and> A xa ya) \<longrightarrow> (\<forall>xa ya. (\<forall>x. \<exists>y. x |\<in>| xa \<longrightarrow> y |\<in>| ya \<and> A x y) \<and> (\<forall>y. \<exists>x. y |\<in>| ya \<longrightarrow> x |\<in>| xa \<and> A x y) \<longrightarrow> (\<forall>xb. \<exists>yb. xb |\<in>| x |\<union>| xa \<longrightarrow> yb |\<in>| y |\<union>| ya \<and> A xb yb) \<and> (\<forall>yb. \<exists>xb. yb |\<in>| y |\<union>| ya \<longrightarrow> xb |\<in>| x |\<union>| xa \<and> A xb yb))
[PROOF STEP]
by blast |
/-
Copyright (c) 2021 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Gabriel Ebner
-/
import Mathlib.Tactic.Cache
import Mathlib.Tactic.Core
import Mathlib.Tactic.SolveByElim
import Mathlib.Tactic.TryThis
/-!
# Library search
This file defines a tactic `librarySearch`
and a term elaborator `librarySearch%`
that tries to find a lemma
solving the current goal
(subgoals are solved using `solveByElim`).
```
example : x < x + 1 := librarySearch%
example : Nat := by librarySearch
```
-/
namespace Tactic
namespace LibrarySearch
open Lean Meta TryThis
initialize registerTraceClass `Tactic.librarySearch
-- from Lean.Server.Completion
private def isBlackListed (declName : Name) : MetaM Bool := do
if declName == ``sorryAx then return false
if declName matches Name.str _ "inj" _ then return false
if declName matches Name.str _ "noConfusionType" _ then return false
let env ← getEnv
pure $ declName.isInternal
|| isAuxRecursor env declName
|| isNoConfusion env declName
<||> isRec declName <||> isMatcher declName
initialize librarySearchLemmas : DeclCache (DiscrTree Name) ←
DeclCache.mk "librarySearch: init cache" {} fun name constInfo lemmas => do
if constInfo.isUnsafe then return lemmas
if ← isBlackListed name then return lemmas
withNewMCtxDepth do
let (xs, bis, type) ← withReducible <| forallMetaTelescopeReducing constInfo.type
let keys ← withReducible <| DiscrTree.mkPath type
pure $ lemmas.insertCore keys name
def librarySearch (mvarId : MVarId) (lemmas : DiscrTree Name) (solveByElimDepth := 6) :
MetaM <| Option (Array <| MetavarContext × List MVarId) := do
profileitM Exception "librarySearch" (← getOptions) do
let mvar := mkMVar mvarId
let ty ← inferType mvar
let mut suggestions := #[]
let state0 ← get
try
solveByElim solveByElimDepth mvarId
return none
catch _ =>
set state0
for lem in ← lemmas.getMatch ty do
trace[Tactic.librarySearch] "{lem}"
match ← traceCtx `Tactic.librarySearch try
let newMVars ← apply mvarId (← mkConstWithFreshMVarLevels lem)
(try
for newMVar in newMVars do
withMVarContext newMVar do
trace[Tactic.librarySearch] "proving {← addMessageContextFull (mkMVar newMVar)}"
solveByElim solveByElimDepth newMVar
pure $ some $ Sum.inr ()
catch _ =>
let res := some $ Sum.inl <| (← getMCtx, newMVars)
set state0
pure res)
catch _ =>
set state0
pure none
with
| none => pure ()
| some (Sum.inr ()) => return none
| some (Sum.inl suggestion) => suggestions := suggestions.push suggestion
pure $ some suggestions
def lines (ls : List MessageData) :=
MessageData.joinSep ls (MessageData.ofFormat Format.line)
open Lean.Parser.Tactic
-- TODO: implement the additional options for `library_search` from Lean 3,
-- in particular including additional lemmas
-- with `library_search [X, Y, Z]` or `library_search with attr`,
-- or requiring that a particular hypothesis is used in the solution, with `library_search using h`.
syntax (name := librarySearch') "library_search" (config)? (" [" simpArg,* "]")?
(" with " (colGt ident)+)? (" using " (colGt binderIdent)+)? : tactic
syntax (name := librarySearch!) "library_search!" (config)? (" [" simpArg,* "]")?
(" with " (colGt ident)+)? (" using " (colGt binderIdent)+)? : tactic
-- For now we only implement the basic functionality.
-- The full syntax is recognized, but will produce a "Tactic has not been implemented" error.
open Elab.Tactic Elab Tactic in
elab_rules : tactic | `(tactic| library_search%$tk) => do
withNestedTraces do
trace[Tactic.librarySearch] "proving {← getMainTarget}"
let mvar ← getMainGoal
let (hs, introdMVar) ← intros (← getMainGoal)
withMVarContext introdMVar do
if let some suggestions ← librarySearch introdMVar (← librarySearchLemmas.get) then
for suggestion in suggestions do
addExactSuggestion tk (← instantiateMVars (mkMVar mvar))
admitGoal introdMVar
else
addExactSuggestion tk (← instantiateMVars (mkMVar mvar))
open Elab Term in
elab tk:"library_search%" : term <= expectedType => do
withNestedTraces do
trace[Tactic.librarySearch] "proving {expectedType}"
let mvar ← mkFreshExprMVar expectedType
let (hs, introdMVar) ← intros mvar.mvarId!
withMVarContext introdMVar do
if let some suggestions ← librarySearch introdMVar (← librarySearchLemmas.get) then
for suggestion in suggestions do
addTermSuggestion tk (← instantiateMVars mvar)
mkSorry expectedType (synthetic := true)
else
addTermSuggestion tk (← instantiateMVars mvar)
instantiateMVars mvar
|
-- WARNING: This file was generated automatically by Vehicle
-- and should not be modified manually!
-- Metadata
-- - Agda version: 2.6.2
-- - AISEC version: 0.1.0.1
-- - Time generated: ???
{-# OPTIONS --allow-exec #-}
open import Vehicle
open import Vehicle.Data.Tensor
open import Data.Product
open import Data.Integer as ℤ using (ℤ)
open import Data.Rational as ℚ using (ℚ)
open import Data.Fin as Fin using (Fin; #_)
open import Data.List
module windController-temp-output where
InputVector : Set
InputVector = Tensor ℚ (2 ∷ [])
currentSensor : ∀ {_x0 : Set} {{_x1 : HasNatLits _x0}} → _x0
currentSensor = 0
previousSensor : ∀ {_x4 : Set} {{_x5 : HasNatLits _x4}} → _x4
previousSensor = 1
postulate controller : InputVector → Tensor ℚ (1 ∷ [])
SafeInput : InputVector → Set
SafeInput x = ∀ (i : Fin 2) → ℚ.- (ℤ.+ 13 ℚ./ 4) ℚ.≤ x i × x i ℚ.≤ ℤ.+ 13 ℚ./ 4
SafeOutput : InputVector → Set
SafeOutput x = ℚ.- (ℤ.+ 5 ℚ./ 4) ℚ.< (controller x (# 0) ℚ.+ (ℤ.+ 2 ℚ./ 1) ℚ.* x currentSensor) ℚ.- x previousSensor × (controller x (# 0) ℚ.+ (ℤ.+ 2 ℚ./ 1) ℚ.* x currentSensor) ℚ.- x previousSensor ℚ.< ℤ.+ 5 ℚ./ 4
abstract
safe : ∀ (x : Tensor ℚ (2 ∷ [])) → SafeInput x → SafeOutput x
safe = checkSpecification record
{ proofCache = "/home/matthew/Code/AISEC/vehicle/proofcache.vclp"
} |
A circle path is simple if and only if the radius is nonzero. |
------------------------------------------------------------------------
-- agda-combinatorics
-- All modules
------------------------------------------------------------------------
{-# OPTIONS --without-K --safe #-}
module AgdaCombinatoricsEverything where
import Math.BinomialTheorem.Generic
-- Proof of the binomial theorem
import Math.BinomialTheorem.Nat
-- Definitions of combinatorial functions
import Math.Combinatorics.Function
-- Properties of combinatorial functions
import Math.Combinatorics.Function.Properties
-- Definitions of combinatorial functions on integer
import Math.Combinatorics.IntegerFunction
-- Properties of combinatorial functions on integer
import Math.Combinatorics.IntegerFunction.Properties
import Math.Combinatorics.ListFunction
import Math.Combinatorics.ListFunction.Properties
import Math.Combinatorics.VecFunction
|
[STATEMENT]
lemma non_exec_assign_global :
assumes "\<triangleright> \<sigma>"
shows "(\<sigma> \<Turnstile> ( _ \<leftarrow> assign_global upd rhs; M)) = ((upd (\<lambda>_. rhs \<sigma>) \<sigma>) \<Turnstile> M)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<sigma> \<Turnstile> _bind_SE _ (upd :==\<^sub>G rhs) M) = (upd (\<lambda>_. rhs \<sigma>) \<sigma> \<Turnstile> M)
[PROOF STEP]
by(simp add: assign_global_def non_exec_assign assms) |
% Copyright 2019 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Free Documentation License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.
\section{Externalizing Graphics}
\label{section-external}
\subsection{Overview}
There are two fundamentally different ways of inserting graphics into a
\TeX-document. First, you can create a graphic using some external program like
|xfig| or |InDesign| and then include this graphic in your text. This is done
using commands like |\includegraphics| or |\pgfimage|. In this case, the
graphic file contains all the low-level graphic commands that describe the
picture. When such a file is included, all \TeX\ has to worry about is the size
of the picture; the internals of the picture are unknown to \TeX\ and it does
not care about them.
The second method of creating graphics is to use a special package that
transforms \TeX-commands like |\draw| or |\psline| into appropriate low-level
graphic commands. In this case, \TeX\ has to do all the hard work of
``typesetting'' the picture and if a picture has a complicated internal
structure this may take a lot of time.
While \pgfname\ was created to facilitate the second method of creating
pictures, there are two main reasons why you may need to employ the first
method of image-inclusion, nevertheless:
%
\begin{enumerate}
\item Typesetting a picture using \TeX\ can be a very time-consuming
process. If \TeX\ needs a minute to typeset a picture, you do not want
to wait this minute when you re\TeX\ your document after having changed
a single comma.
\item Some users, especially journal editors, may not be able to process
files that contain \pgfname\ commands -- for the simple reason that the
systems of many publishing houses do not have \pgfname\ installed.
\end{enumerate}
In both cases, the solution is to ``extract'' or ``externalize'' pictures that
would normally be typeset every time a document is \TeX ed. Once the pictures
have been extracted into separate graphics files, these graphic files can be
reinserted into the text using the first method.
Extracting a graphic from a file is not as easy as it may sound at first since
\TeX\ cannot write parts of its output into different files and a bit of
trickery is needed. The following macros simplify the workflow:
%
\begin{enumerate}
\item You have to tell \pgfname\ which files will be used for which
pictures. To do so, you enclose each picture that you wish to be
``externalized'' in a pair of |\beginpgfgraphicnamed| and
|\endpgfgraphicnamed| macros.
\item The next step is to generate the extracted graphics. For this you run
\TeX\ with the |\jobname| set to the graphic file's name. This will
cause |\pgfname| to behave in a very special way: All of your document
will simply be thrown away, \emph{except} for the single graphic having
the same name as the current jobname.
\item After you have run \TeX\ once for each graphic that your wish to
externalize, you can rerun \TeX\ on your document normally. This will
have the following effect: Each time a |\beginpgfgraphicnamed| is
encountered, \pgfname\ checks whether a graphic file of the given name
exists (if you did step 2, it will). If this graphic file exists, it
will be input and the text till the corresponding |\endpgfgraphicnamed|
will be ignored.
\end{enumerate}
In the rest of this section, the above workflow is explained in more detail.
\subsection{Workflow Step 1: Naming Graphics}
In order to put each graphic in an external file, you first need to tell
\pgfname\ the names of these files.
\begin{command}{\beginpgfgraphicnamed\marg{file name prefix}}
This command indicates that everything up to the next call of
|\endpgfgraphicnamed| is part of a graphic that should be placed in a file
named \meta{file name prefix}|.|\meta{suffix}, where the \meta{suffix}
depends on your backend driver. Typically, \meta{suffix} will be |dvi| or
|pdf|.
Here is a typical example of how this command is used:
%
\begin{codeexample}[code only]
% In file main.tex:
...
As we see in Figure~\ref{fig1}, the world is flat.
\begin{figure}
\beginpgfgraphicnamed{graphic-of-flat-world}
\begin{tikzpicture}
\fill (0,0) circle (1cm);
\end{tikzpicture}
\endpgfgraphicnamed
\caption{The flat world.}
\label{fig1}
\end{figure}
\end{codeexample}
Each graphic to be externalized should have a unique name. Note that this
name will be used as the name of a file in the file system, so it should
not contain any funny characters.
This command can have three different effects:
%
\begin{enumerate}
\item The easiest situation arises if there does not yet exist a
graphic file called \meta{file name prefix}|.|\meta{suffix}, where
the \meta{suffix} is one of the suffixes understood by your current
backend driver (so |pdf| or |jpg| if you use |pdftex|, |eps| if you
use |dvips|, and so on). In this case, both this command and the
|\endpgfgraphicnamed| command simply have no effect.
\item A more complex situation arises when a graphic file named
\meta{file name prefix}|.|\meta{suffix} \emph{does} exist. In this
case, this graphic file is included using the |\includegraphics|
command%
%
\footnote{Actually, the command key \texttt{/pgf/images/include
external} is invoked which calls an appropriate
\texttt{\textbackslash includegraphics} command.}.
%
Furthermore, the text between |\beginpgfgraphicnamed| and
|\endpgfgraphicnamed| is ignored.
When the text is ``ignored'', what actually happens is that all
text up to the next occurrence of |\endpgfgraphicnamed| is thrown
away without any macro expansion. This means, in particular, that
(a) you cannot put |\endpgfgraphicnamed| inside a macro and (b) the
macros used in the graphics need not be defined at all when the
graphic file is included. \item The most complex behavior arises
when current the |\jobname| equals the \meta{file name prefix} and,
furthermore, the \emph{real job name} has been declared. The
behavior for this case is explained later.
\end{enumerate}
Note that the |\beginpgfgraphicnamed| does not really have any effect until
you have generated the graphic files named. Till then, this command is
simply ignored. Also, if you delete the graphics file later on, the
graphics are typeset normally once more.
\end{command}
\begin{command}{\endpgfgraphicnamed}
This command just marks the end of the graphic that should be externalized.
\end{command}
\subsection{Workflow Step 2: Generating the External Graphics}
We have now indicated all the graphics for which we would like graphic files to
be generated. In order to generate the files, you now need to modify the
|\jobname| appropriately. This is done in two steps:
%
\begin{enumerate}
\item You use the following command to tell \pgfname\ the real name of your
|.tex| file:
%
\begin{command}{\pgfrealjobname\marg{name}}
Tells \pgfname\ the real name of your job. For instance, if you
have a file called |survey.tex| that contains two graphics that you
wish to be called |survey-graphic1| and |survey-graphic2|, then you
should write the following.
%
\begin{codeexample}[code only]
% This is file survey.tex
\documentclass{article}
...
\usepackage{tikz}
\pgfrealjobname{survey}
\end{codeexample}
\end{command}
\item You run \TeX\ with the |\jobname| set to the name of the graphic for
which you need an external graphic to be generated. To set the
|\jobname|, you use the |--jobname=| option of \TeX:
%
\begin{codeexample}[code only, tikz syntax=false]
bash> latex --jobname=survey-graphic1 survey.tex
\end{codeexample}
%
\end{enumerate}
The following things will now happen:
%
\begin{enumerate}
\item |\pgfrealjobname| notices that the |\jobname| is not the ``real''
jobname and, thus, must be the name of a graphic that is to be put in
an external file.
\item At the beginning of the document, \pgfname\ changes the definition of
\TeX's internal |\shipout| macro. The new shipout macro simply throws
away the output. This means that the document is typeset normally, but
no output is produced.
\item When the |\beginpgfgraphicnamed{|\meta{name}|}| command is
encountered where the \meta{name} is the same as the current
|\jobname|, then a \TeX-box is started and \meta{everything} up to the
following |\endpgfgraphicnamed| command is stored inside this box.
Note that, typically, \meta{everything} will contain just a single
|{tikzpicture}| or |{pgfpicture}| environment. However, this need not
be the case, you can use, say, a |{pspicture}| environment as
\meta{everything} or even just some normal \TeX-text.
\item At the |\endpgfgraphicnamed|, the box \emph{is} shipped out using the
original |\shipout| command. Thus, unlike everything else, the contents
of the graphic is made part of the output.
\item When the box containing the graphic is shipped out, the paper size is
modified such that it is exactly equal to the height and width of the
box.
\end{enumerate}
The net effect of everything described above is that the two commands
%
\begin{codeexample}[code only, tikz syntax=false]
bash> latex --jobname=survey-graphic1 survey.tex
bash> dvips survey-graphic1
\end{codeexample}
%
\noindent produce a file called |survey-graphic1.ps| that consists of a single
page that contains exactly the graphic produced by the code between
|\beginpgfgraphicnamed{survey-graphic1}| and |\endpgfgraphicnamed|.
Furthermore, the size of this single page is exactly the size of the graphic.
If you use pdf\TeX, producing the graphic is even simpler:
%
\begin{codeexample}[code only, tikz syntax=false]
bash> pdflatex --jobname=survey-graphic1 survey.tex
\end{codeexample}
%
\noindent produces the single-page |pdf|-file |survey-graphic1.pdf|.
\subsection{Workflow Step 3: Including the External Graphics}
Once you have produced all the pictures in the text, including them into the
main document is easy: Simply run \TeX\ again without any modification of the
|\jobname|. In this case the |\pgfrealjobname| command will notice that the
main file is, indeed, the main file. The main file will then be typeset
normally and the |\beginpgfgraphicnamed| commands also behave normally, which
means that they will try to include the generated graphic files -- which is
exactly what you want.
Suppose that you wish to send your survey to a journal that does not have
\pgfname\ installed. In this case, you now have all the necessary external
graphics, but you still need \pgfname\ to automatically include them instead of
the executing the picture code! One way to solve this problem is to simply
delete all of the \pgfname\ or \tikzname\ code from your |survey.tex| and
instead insert appropriate |\includegraphics| commands ``by hand''. However,
there is a better way: You input the file |pgfexternal.tex|.
\begin{filedescription}{pgfexternal.tex}
This file defines the command |\beginpgfgraphicnamed| and causes it to have
the following effect: It includes the graphic file given as a parameter to
it and then gobbles everything up to |\endpgfgraphicnamed|.
Since |\beginpgfgraphicnamed| does not do macro expansion as it searches
for |\endpgfgraphicnamed|, it is not necessary to actually include the
packages necessary for \emph{creating} the graphics. So the idea is that
you comment out things like |\usepackage{tikz}| and instead say
|\input pgfexternal.tex|.
Indeed, the contents of this file is simply the following line:
%
\begin{codeexample}[code only]
\long\def\beginpgfgraphicnamed#1#2\endpgfgraphicnamed{\includegraphics{#1}}
\end{codeexample}
Instead of |\input pgfexternal.tex| you could also include this line in
your main file.
\end{filedescription}
As a final remark, note that the |baseline| option does not work directly with
pictures written to an external graphic file. The simple reason is that there
is no way to store this baseline information in an external graphic file. To
allow the |baseline| option (or any \TeX\ construction with non-zero depth),
the baseline information is stored into a separate file. This file is named
\marg{image file}|.dpth| and contains something like |5pt|.
So, if you need baseline information, you will have to keep the external
graphic file together with its~|.dpth| file. Furthermore, the short command in
|\input pgfexternal.tex| is no longer enough because it ignores any baseline
information. You will need to use |\input pgfexternalwithdepth.tex| instead (it
is shown below). It is slightly longer, but it can be used in the same way as
|pgfexternal.tex|.
\begin{key}{/pgf/images/include external (initially \textbackslash pgfimage\{\#1\})}
\label{pgf:includeexternalkey}
\index{External Graphics!Bounding Box Issues}
This key constitutes the public interface to exchange the
|\includegraphics| command used for the image inclusion.
Redefining this key allows to provide bounding box or viewport options:
%
\begin{codeexample}[code only]
\pgfkeys{/pgf/images/include external/.code={\includegraphics[viewport=0 0 211.28 175.686]{#1}}}
\end{codeexample}
%
Do not forget the |.code| here which redefines the command.
One application could be image externalization and bounding box
restrictions: As far as I know, a |.pdf| graphics with restricted bounding
box is always cropped (which is not always desired). One solution could be
to use |latex| and |dvips| which doesn't have this restriction. Another is
to manually provide the |viewport| option as shown above.
A possible value for |viewport| can be found in the |.pdf| image, search
for |/MediaBox = [ ... ]|.
\end{key}
\subsection{A Complete Example}
Let us now have a look at a simple, but complete example. We start out with a
normal file called |survey.tex| that has the following contents:
%
\begin{codeexample}[code only]
% This is the file survey.tex
\documentclass{article}
\usepackage{graphics}
\usepackage{tikz}
\begin{document}
In the following figure, we see a circle:
\begin{tikzpicture}
\fill (0,0) circle (10pt);
\end{tikzpicture}
By comparison, in this figure we see a rectangle:
\begin{tikzpicture}
\fill (0,0) rectangle (10pt,10pt);
\end{tikzpicture}
\end{document}
\end{codeexample}
Now our editor tells us that the publisher will need all figures to be provided
in separate PostScript or |.pdf|-files. For this, we enclose all figures in
|...graphicnamed|-pairs and we add a call to the |\pgfrealjobname| macro:
%
\begin{codeexample}[code only]
% This is the file survey.tex
\documentclass{article}
\usepackage{graphics}
\usepackage{tikz}
\pgfrealjobname{survey}
\begin{document}
In the following figure, we see a circle:
\beginpgfgraphicnamed{survey-f1}
\begin{tikzpicture}
\fill (0,0) circle (10pt);
\end{tikzpicture}
\endpgfgraphicnamed
By comparison, in this figure we see a rectangle:
\beginpgfgraphicnamed{survey-f2}
\begin{tikzpicture}
\fill (0,0) rectangle (10pt,10pt);
\end{tikzpicture}
\endpgfgraphicnamed
\end{document}
\end{codeexample}
After these changes, typesetting the file will still yield the same output as
it did before -- after all, we have not yet created any external graphics.
To create the external graphics, we run |pdflatex| twice, once for each
graphic:
%
\begin{codeexample}[code only, tikz syntax=false]
bash> pdflatex --jobname=survey-f1 survey.tex
This is pdfTeX, Version 3.141592-1.40.3 (Web2C 7.5.6)
entering extended mode
(./survey.tex
LaTeX2e <2005/12/01>
...
) [1] (./survey-f1.aux) )
Output written on survey-f1.pdf (1 page, 1016 bytes).
Transcript written on survey-f1.log.
\end{codeexample}
\begin{codeexample}[code only, tikz syntax=false]
bash> pdflatex --jobname=survey-f2 survey.tex
This is pdfTeX, Version 3.141592-1.40.3 (Web2C 7.5.6)
entering extended mode
(./survey.tex
LaTeX2e <2005/12/01>
...
(./survey-f2.aux) )
Output written on survey-f2.pdf (1 page, 1002 bytes).
Transcript written on survey-f2.log.
\end{codeexample}
We can now send the two generated graphics (|survey-f1.pdf| and
|survey-f2.pdf|) to the editor. However, the publisher cannot use our
|survey.tex| file, yet. The reason is that it contains the command
|\usepackage{tikz}| and they do not have \pgfname\ installed.
Thus, we modify the main file |survey.tex| as follows:
%
\begin{codeexample}[code only]
% This is the file survey.tex
\documentclass{article}
\usepackage{graphics}
\input pgfexternal.tex
% \usepackage{tikz}
% \pgfrealjobname{survey}
\begin{document}
In the following figure, we see a circle:
\beginpgfgraphicnamed{survey-f1}
\begin{tikzpicture}
\fill (0,0) circle (10pt);
\end{tikzpicture}
\endpgfgraphicnamed
By comparison, in this figure we see a rectangle:
\beginpgfgraphicnamed{survey-f2}
\begin{tikzpicture}
\fill (0,0) rectangle (10pt,10pt);
\end{tikzpicture}
\endpgfgraphicnamed
\end{document}
\end{codeexample}
%
If we now run pdf\LaTeX, then, indeed, \pgfname\ is no longer needed:
% In the following, we switch off typesetting of listings because the
% parentheses confuse the pretty printer
%
\begin{codeexample}[code only,typeset listing/.code=#1]
bash> pdflatex survey.tex
This is pdfTeX, Version 3.141592-1.40.3 (Web2C 7.5.6)
entering extended mode
(./survey.tex
LaTeX2e <2005/12/01>
Babel <v3.8h> and hyphenation patterns for english, ..., loaded.
(/usr/local/gwTeX/texmf.texlive/tex/latex/base/article.cls
Document Class: article 2005/09/16 v1.4f Standard LaTeX document class
(/usr/local/gwTeX/texmf.texlive/tex/latex/base/size10.clo))
(/usr/local/gwTeX/texmf.texlive/tex/latex/graphics/graphics.sty
(/usr/local/gwTeX/texmf.texlive/tex/latex/graphics/trig.sty)
(/usr/local/gwTeX/texmf.texlive/tex/latex/config/graphics.cfg)
(/usr/local/gwTeX/texmf.texlive/tex/latex/pdftex-def/pdftex.def))
(/Users/tantau/Library/texmf/tex/generic/pgf/generic/pgf/utilities/pgfexternal.
tex) (./survey.aux)
(/usr/local/gwTeX/texmf.texlive/tex/context/base/supp-pdf.tex
[Loading MPS to PDF converter (version 2006.09.02).]
) <survey-f1.pdf, id=1, 23.33318pt x 19.99973pt> <use survey-f1.pdf>
<survey-f2.pdf, id=2, 13.33382pt x 10.00037pt> <use survey-f2.pdf> [1{/Users/ta
ntau/Library/texmf/fonts/map/pdftex/updmap/pdftex.map} <./survey-f1.pdf> <./sur
vey-f2.pdf>] (./survey.aux) )</usr/local/gwTeX/texmf.texlive/fonts/type1/bluesk
y/cm/cmr10.pfb>
Output written on survey.pdf (1 page, 10006 bytes).
Transcript written on survey.log.
\end{codeexample}
To our editor, we send the following files:
%
\begin{itemize}
\item The last |survey.tex| shown above.
\item The graphic file |survey-f1.pdf|.
\item The graphic file |survey-f2.pdf|.
\item The file |pgfexternal.tex|, whose contents is simply
%
\begin{codeexample}[code only]
\long\def\beginpgfgraphicnamed#1#2\endpgfgraphicnamed{\includegraphics{#1}}
\end{codeexample}
%
(Alternatively, we can also directly add this line to our |survey.tex|
file).
\end{itemize}
%
In case we have used the |baseline| option, we also need to include any |.dpth|
files and we need to use the file |pgfexternalwithdepth.tex| instead of
|pgfexternal.tex|. This file also checks for the existence of |.dpth| files
containing baseline information, its contents is
%
\begin{codeexample}[code only]
\long\def\beginpgfgraphicnamed#1#2\endpgfgraphicnamed{%
\begingroup
\setbox1=\hbox{\includegraphics{#1}}%
\openin1=#1.dpth
\ifeof1 \box1
\else
\read1 to\pgfincludeexternalgraphicsdp\closein1
\dimen0=\pgfincludeexternalgraphicsdp\relax
\hbox{\lower\dimen0 \box1 }%
\fi
\endgroup
}
\end{codeexample}
%
Again, we could simply copy these lines to our |survey.tex| file.
%%% Local Variables:
%%% mode: latex
%%% TeX-master: "pgfmanual"
%%% End:
|
From stdpp Require Export list fin_maps.
From iris.program_logic Require Import hoare.
From iris.heap_lang Require Export lifting notation.
From iris_hashtable Require Import util.
Class Hashable Σ `{heapG Σ} (Key : Type) `{EqDecision Key} (Hash : Key -> nat) :=
{ equalf : val;
hashf : val;
as_key : val -> option Key;
equal_spec (k1 k2: Key) (v1 v2: val) :
as_key v1 = Some k1 ->
as_key v2 = Some k2 ->
WP equalf v1 v2 {{u, ⌜u = #(bool_decide (k1 = k2))⌝}}%I;
hash_spec k v : as_key v = Some k -> WP hashf v {{u, ⌜u = #(Hash k)⌝}}%I }.
Section model.
Context {Σ Key Hash map} `{FinMap Key map, heapG Σ, !Hashable Σ Key Hash}.
Implicit Type m : map (list val).
Definition insert_val m k x := (<[k := x :: from_option id [] (m !! k)]>m).
Definition remove_val m k := match m !! k with
| Some (x :: y :: l) => <[k := y :: l]> m
| Some _ => delete k m
| None => m
end.
(*(<[ k := tail (lookup_all M k)]>M).*)
Definition all_elements m := map_fold (fun k l acc => ((fun v => (k, v)) <$> l) ++ acc) [] m.
Definition table_wf m := map_Forall (fun _ l => exists x xs, l = x :: xs) m.
Lemma table_wf_empty : table_wf ∅.
Proof. apply map_Forall_empty. Qed.
Lemma table_wf_insert_val m k x : table_wf m -> table_wf (insert_val m k x).
Proof. apply map_Forall_insert_2. eauto. Qed.
Lemma table_wf_remove_val m k : table_wf m -> table_wf (remove_val m k).
Proof.
unfold remove_val.
case_eq (m !! k) ; last done.
intros [|?[|]] Hlookup ; last (apply map_Forall_insert_2 ; eauto).
all: rewrite -{1}(insert_id _ _ _ Hlookup) -insert_delete ;
apply map_Forall_insert_12, lookup_delete.
Qed.
Definition lookup_insert_val_ne m k k' x :
k ≠ k' -> (insert_val m k x) !! k' = m !! k'.
Proof.
intros Hne. rewrite /insert_val lookup_insert_ne //.
Qed.
Definition lookup_remove_val_ne m k k' :
k ≠ k' -> (remove_val m k) !! k' = m !! k'.
Proof.
intros Hne. unfold remove_val.
case_eq (m !! k) ; last done.
intros [|?[|]] Hlookup ; [apply lookup_delete_ne ..| apply lookup_insert_ne] ; done.
Qed.
Inductive removal : map (list val) -> list (val * val) -> map (list val) -> Prop :=
| RemovalNil {m} : removal m [] m
| RemovalCons {k k' x xs l m m' } :
as_key k = Some k' ->
m !! k' = Some (x :: xs) ->
removal (remove_val m k') l m' ->
removal m ((k, x) :: l) m'.
Lemma removal_app_1 m seq m' seq' m'':
removal m seq m' ->
removal m' seq' m'' ->
removal m (seq ++ seq') m''.
Proof.
intro HRem. induction HRem as [|] ; [done | econstructor ; eauto].
Qed.
Lemma removal_app_2 m m' seq seq' :
removal m (seq ++ seq') m' ->
exists m'', removal m seq m'' /\ removal m'' seq' m'.
Proof.
revert m.
induction seq as [|[k x] seq IH].
- simpl. intros m ?. exists m. split. by constructor 1. assumption.
- simpl. intros m Hrem. inversion Hrem as [| ? k' ??????? Hrem']. simplify_eq.
specialize (IH (remove_val m k') Hrem'). destruct IH as [m'' [Hseq Hseq']].
exists m''. split.
by econstructor. assumption.
Qed.
Definition permitted m seq := exists m', removal m seq m'.
Definition complete m seq := removal m seq ∅ .
Lemma complete_all_elements m seq:
complete m seq ->
exists seq', Forall2 (fun '(k, x) '(k', x') => x = x' /\ as_key k' = Some k) seq' seq /\
seq' ≡ₚ all_elements m.
Proof.
assert (forall (k : Key) (l : list val),
Proper (Permutation ==> Permutation) (fun acc => ((fun x => (k, x)) <$> l) ++ acc)).
{ solve_proper. }
assert ( forall A (l1 l2 l3 : list A),
l1 ++ l2 ++ l3 ≡ₚ l2 ++ l1 ++ l3).
{ intros. do 2 rewrite app_assoc. f_equiv. apply Permutation_app_comm. }
revert m. induction seq as [|[k x] seq IH].
- intros m HCom. exists [].
split ; first done. inversion HCom.
by rewrite /all_elements map_fold_empty.
- intros m HCom. inversion HCom as [| ??k'?????? Hlookup HRem].
specialize (IH _ HRem). destruct IH as [seq' [Hforall HPerm]].
exists ((k', x) :: seq'). split.
+ by apply Forall2_cons.
+ rewrite HPerm /all_elements /remove_val Hlookup. destruct xs.
* rewrite -{2}(insert_id m k' [x]) // -insert_delete.
rewrite (map_fold_insert Permutation) //. apply lookup_delete.
* rewrite -insert_delete (map_fold_insert Permutation) // ; last apply lookup_delete.
rewrite app_comm_cons -fmap_cons.
rewrite -{2}(insert_id m k' (x :: v :: xs)) // -insert_delete.
rewrite (map_fold_insert Permutation) //. apply lookup_delete.
Qed.
End model.
Structure table Σ key hash map `{FinMap key map, heapG Σ, !Hashable Σ key hash} : Type :=
{ table_create : val ;
table_insert : val ;
table_remove : val ;
table_lookup : val ;
table_fold : val ;
table_cascade : val ;
table_state : Type ;
table_in_state : map (list val) -> table_state -> val -> iProp Σ ;
is_cascade : map (list val) -> val -> list (val * val) -> table_state -> val -> iProp Σ ;
table_in_state_wf m state t : (table_in_state m state t → ⌜table_wf m⌝)%I ;
is_cascade_persistent m f seq state t : PersistentP (is_cascade m f seq state t) ;
table_create_spec (n : nat) : (n > 0)%nat -> WP table_create #n {{t, ∃ state, table_in_state ∅ state t}}%I ;
table_insert_spec (t k x : val) m state k' :
as_key k = Some k' ->
{{{table_in_state m state t}}}
table_insert t k x
{{{state', RET #(); table_in_state (insert_val m k' x) state' t}}} ;
table_remove_spec m state t k k' :
as_key k = Some k' ->
{{{table_in_state m state t}}}
table_remove t k
{{{ state', RET match m !! k' with
| Some (v :: _) => SOMEV v
| _ => NONEV end ;
table_in_state (remove_val m k') state' t }}} ;
table_lookup_spec m state t k k' :
as_key k = Some k' ->
{{{table_in_state m state t}}}
table_lookup t k
{{{ RET match m !! k' with
| Some (v :: _) => SOMEV v
| _ => NONEV end ;
table_in_state m state t }}} ;
table_fold_spec m state I (f t a : val) :
{{{(∀ k x seq (a' : val),
{{⌜permitted m (seq ++ [(k,x)])⌝ ∗I seq a'}}
f k x a'
{{v, I (seq ++ [(k,x)]) v }}) ∗
table_in_state m state t ∗ I [] a}}}
table_fold f t a
{{{v seq, RET v; ⌜complete m seq⌝ ∗ table_in_state m state t ∗ I seq v}}} ;
is_cascade_spec m f seq state t:
{{{ is_cascade m f seq state t ∗ table_in_state m state t }}}
f #()
{{{v k x f' , RET v; table_in_state m state t ∗
((⌜v = NONEV⌝ ∗ ⌜complete m seq⌝) ∨
(⌜v = SOMEV ((k, x), f')⌝ ∗
⌜permitted m (seq ++ [(k, x)])⌝ ∗
is_cascade m f' (seq ++ [(k, x)]) state t)) }}};
table_cascade_spec m state t:
{{{table_in_state m state t}}}
table_cascade t
{{{f, RET f; is_cascade m f [] state t ∗ table_in_state m state t }}}
}.
Arguments table_create {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _} _.
Arguments table_insert {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _} _.
Arguments table_remove {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _} _.
Arguments table_lookup {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _} _.
Arguments table_fold {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _} _.
Arguments table_cascade {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _} _.
Arguments table_state {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _} _.
Arguments table_in_state {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _} _ _ _ _.
Arguments is_cascade {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _} _ _ _ _ _ _.
Arguments table_in_state_wf {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _} _ _ _ _.
Arguments is_cascade_persistent {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _} _ _ _ _ _ _.
Arguments table_create_spec {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _} _ _ _.
Arguments table_insert_spec {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _} _ _ _ _ _ _ _ _ _.
Arguments table_remove_spec {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _} _ _ _ _ _ _ _ _.
Arguments table_lookup_spec {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _} _ _ _ _ _ _ _ _.
Arguments table_fold_spec {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _} _ _ _ _ _ _ _.
Arguments is_cascade_spec {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _} _ _ _ _ _ _ _.
Arguments table_cascade_spec {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _} _ _ _ _ _.
Existing Instance is_cascade_persistent.
|
% This file contains the content for a main section
\numberedformat
%% Modify below this line %%
\chapter{Terminology}
These terms should be introduced:
Viewing Transform (or View Transform) -- Generally, a color transformation that converts values from a working space into colorimetry for a display device. Specifically in this context, the Viewing Transform is what contains the Academy-supplied algorithms for converting scene-referred ACES values into colorimetry for a given viewing environment and class of display.
Display Transform -- A color transformation that converts colorimetry intended to be reproduced on a display into the code values that must be sent to the device. |
function tinv = t_inv (x, v, mu, sigma)
% T_INV Inverse of Student's T cumulative distribution function (cdf).
% X=TINV(P,V,MU,SIGMA) returns the inverse of Student's T cdf with V degrees
% of freedom, at the values in P, with mean MU and standard deviation
% SIGMA.
%
% The size of X is the common size of P and V. A scalar input
% functions as a constant matrix of the same size as the other input.
% Copyright (c) 1995-1997, 2005-2007 Kurt Hornik
% This software is distributed under the GNU General Public
% License (version 3 or later); please refer to the file
% License.txt, included with the software, for details.
if nargin < 4
sigma = 1;
end
if nargin < 3
mu = 0;
end
if (~isscalar(mu) || ~isscalar(sigma))
if ~((size(x,1) == size(mu,1)) && (size(mu,1) == size(sigma,1)))
error ('norm_inv: x, mu and sigma must be of common size or scalars');
end
end
x = (x-mu)./sigma;
if (nargin < 2)
error('must give atleast 2 input arguments')
end
if (~isscalar(v))
if (size(x,1) ~= size(v,1))
error ('tinv: x and v must be of common size or scalar');
end
end
tinv = zeros(size(x));
k = find( (x<0) || (x > 1) || isnan(x) || (v<0));
if (any(k))
tinv(k) = NaN;
end
k = find ((x == 0) & (v > 0));
if (any (k))
tinv(k) = -Inf;
end
k = find ((x == 1) & (v > 0));
if (any (k))
tinv(k) = Inf;
end
k = find ((x > 0) & (x < 1) & (v > 0) & (v < 10000));
if (any (k))
if (isscalar (v))
tinv(k) = (sign (x(k) - 1/2) ...
.* sqrt (v .* (1 ./ beta_inv (2*min(x(k),1-x(k)), ...
v/2,1/2)-1)));
else
tinv(k) = (sign(x(k)-1/2) ...
.* sqrt (v(k).*(1./beta_inv(2*min(x(k), 1-x(k)), ...
v(k)/2,1/2)-1)));
end
end
% For large v, use the quantiles of the standard normal
k = find ((x > 0) & (x < 1) & (v >= 10000));
if (any (k))
tinv(k) = sqrt (2)*erfinv(2*x(k)-1);
end
end
% inv = sqrt (2) * erfinv (2 * x - 1); |
[STATEMENT]
lemma seq_bot_right [simp]: "c;\<bottom> \<sqsubseteq> c"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. c ; \<bottom> \<sqsubseteq> c
variables:
c :: 'a
(;) :: 'a \<Rightarrow> 'a \<Rightarrow> 'a
type variables:
'a :: refinement_lattice
[PROOF STEP]
by (metis bot.extremum seq.right_neutral seq_mono_right) |
from __future__ import division
from styx_msgs.msg import TrafficLight
import rospy
import tensorflow as tf
import numpy as np
#from PIL import Image
import cv2
FASTER_RCNN_GRAPH_FILE = 'light_classification/tld/frozen_inference_graph.pb'
BOX_CONFIDENCE = 0.8
RED_THRESHOLD = 200
GREEN_THRESHOLD = 200
CONF_TOP = 1.2
CONF_BOT = 0.8
TOP_5 = 5
HISTOGRAM_WEIGHT = 2.0
class TLClassifier(object):
def __init__(self):
#TODO load classifier
self.detection_graph = self.load_graph(FASTER_RCNN_GRAPH_FILE)
# The input placeholder for the image.
# `get_tensor_by_name` returns the Tensor with the associated name in the Graph.
self.image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')
# Each box represents a part of the image where a particular object was detected.
self.detection_boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')
# Each score represent how level of confidence for each of the objects.
# Score is shown on the result image, together with the class label.
self.detection_scores = self.detection_graph.get_tensor_by_name('detection_scores:0')
# The classification of the object (integer id).
self.detection_classes = self.detection_graph.get_tensor_by_name('detection_classes:0')
self.count = 0
def get_classification(self, image):
"""Determines the color of the traffic light in the image
Args:
image (cv::Mat): image containing the traffic light
Returns:
int: ID of traffic light color (specified in styx_msgs/TrafficLight)
"""
#TODO implement light color prediction
#norm_img = self.image_normalize(image)
#image = (norm_img + 1.0)*255/2
#cv2.imwrite("/media/sf_Shared/sim_{}_cv2.jpg".format(self.count), image)
#self.count += 1
image_np = np.expand_dims(np.asarray(image, dtype=np.uint8), 0)
with tf.Session(graph=self.detection_graph) as sess:
# Actual detection.
(boxes, scores, classes) = sess.run([self.detection_boxes, self.detection_scores, self.detection_classes],
feed_dict={self.image_tensor: image_np})
# Remove unnecessary dimensions
boxes = np.squeeze(boxes)
scores = np.squeeze(scores)
classes = np.squeeze(classes)
#confidence_cutoff = BOX_CONFIDENCE
top_x = TOP_5
# Filter boxes with a confidence score less than `confidence_cutoff`
boxes, scores, classes = self.filter_boxes(top_x, boxes, scores, classes)
#accumulate the scores according to the class
r_conf, g_conf, y_conf, u_conf = self.accumulate_conf(scores, classes)
"""
# The current box coordinates are normalized to a range between 0 and 1.
# This converts the coordinates actual location on the image.
#width, height = image.size
height, width, channel = image.shape
box_coords = self.to_image_coords(boxes, height, width)
# One pixel has one vote
r_vote = 0
g_vote = 0
total_vote = 0
if len(boxes) > 0:
TL_Detected = True
else:
TL_Detected = False
for i in range(len(boxes)):
# Get the position of each box
bot, left, top, right = box_coords[i, ...]
# The class id of traffic light should be 1, but depend on the graph
#class_id = int(classes[i])
#tl_image = image.crop((int(left), int(bot), int(right), int(top)))
tl_image = image[int(bot):int(top), int(left):int(right)]
# For debug
#self.draw_boxes(image, box_coords, classes)
#cv2.imwrite("./tl_{}.jpg".format(i), tl_image)
im = np.array(tl_image)
total_vote += im.shape[0]*im.shape[1]
# Create the histogram for each RGB channel
bh, gh, rh = self.color_hist(im, nbins=32, bins_range=(0, 256))
if rh is not None:
for i in range(len(rh[0])):
if rh[1][i] > RED_THRESHOLD:
r_vote += rh[0][i]
if gh is not None:
for i in range(len(gh[0])):
if gh[1][i] > GREEN_THRESHOLD:
g_vote += gh[0][i]
if TL_Detected:
# For debug
#cv2.imwrite("./result.jpg", image)
r_confidence = r_vote/total_vote
g_confidence = g_vote/total_vote
print("r_confidence={}".format(r_confidence))
print("g_confidence={}".format(g_confidence))
if g_confidence > 0.0:
conf_ratio = r_confidence/g_confidence
if conf_ratio > CONF_TOP:
#return TrafficLight.RED
r_conf += HISTOGRAM_WEIGHT
#print("hist judge is Red")
elif conf_ratio < CONF_BOT:
#return TrafficLight.GREEN
g_conf += HISTOGRAM_WEIGHT
#print("hist judge is Green")
else:
#return TrafficLight.YELLOW
y_conf += HISTOGRAM_WEIGHT
#print("hist judge is Yellow")
else:
if r_confidence > 0.0:
#return TrafficLight.RED
r_conf += HISTOGRAM_WEIGHT
#print("hist judge is Red")
else:
#return TrafficLight.UNKNOWN
u_conf += HISTOGRAM_WEIGHT
#print("hist judge is Unknown")
else:
#return TrafficLight.UNKNOWN
u_conf += HISTOGRAM_WEIGHT
"""
#return TrafficLight.UNKNOWN
return self.sort_conf(r_conf, g_conf, y_conf, u_conf)
def filter_boxes(self, top_x, boxes, scores, classes):
"""Return the top several scores boxes """
idxs = []
for i in range(top_x):
#print("scores[{}] = {}, class = {}".format(i, scores[i], classes[i]))
#rospy.loginfo("scores[{}] = {}, class = {}".format(i, scores[i], classes[i]))
idxs.append(i)
filtered_boxes = boxes[idxs, ...]
filtered_scores = scores[idxs, ...]
filtered_classes = classes[idxs, ...]
return filtered_boxes, filtered_scores, filtered_classes
def to_image_coords(self, boxes, height, width):
"""
The original box coordinate output is normalized, i.e [0, 1].
This converts it back to the original coordinate based on the image
size.
"""
box_coords = np.zeros_like(boxes)
box_coords[:, 0] = boxes[:, 0] * height
box_coords[:, 1] = boxes[:, 1] * width
box_coords[:, 2] = boxes[:, 2] * height
box_coords[:, 3] = boxes[:, 3] * width
return box_coords
def load_graph(self, graph_file):
"""Loads a frozen inference graph"""
graph = tf.Graph()
with graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(graph_file, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
return graph
def image_normalize(self, x):
original_image = np.array(x, dtype=np.float32)
for n in range(len(original_image)):
#for the R, G, B channel respectively
for i in range(3):
maxPixel = np.amax(original_image[n][...,i])
minPixel = np.amin(original_image[n][...,i])
original_image[n][...,i] = -1.0 + (original_image[n][...,i] - minPixel)*2.0/(maxPixel-minPixel)
return original_image
def color_hist(self, img, nbins=32, bins_range=(0, 256)):
# Compute the histogram of the RGB channels separately
rhist = np.histogram(img[:,:,0], nbins, bins_range)
ghist = np.histogram(img[:,:,1], nbins, bins_range)
bhist = np.histogram(img[:,:,2], nbins, bins_range)
return rhist, ghist, bhist
@staticmethod
def accumulate_conf(scores, classes):
r_conf = 0
g_conf = 0
y_conf = 0
u_conf = 0
for i in range(len(classes)):
if classes[i] == 1:
g_conf += scores[i]
elif classes[i] == 2:
r_conf += scores[i]
elif classes[i] == 7:
y_conf += scores[i]
else:
u_conf += scores[i]
return r_conf, g_conf, y_conf, u_conf
@staticmethod
def sort_conf(r_conf, g_conf, y_conf, u_conf):
conf = [(TrafficLight.RED, r_conf),
(TrafficLight.GREEN, g_conf),
(TrafficLight.YELLOW, y_conf),
(TrafficLight.UNKNOWN, u_conf)]
conf = sorted(conf, key = lambda x: x[1])
for i in range(len(conf)):
# print("{} is {}".format(conf[i][0], conf[i][1]))
rospy.loginfo("{} is {}".format(conf[i][0], conf[i][1]))
return conf[-1][0]
def draw_boxes(self, image, boxes, classes, thickness=4):
"""Draw bounding boxes on the image"""
#draw = ImageDraw.Draw(image)
for i in range(len(boxes)):
bot, left, top, right = boxes[i, ...]
#class_id = int(classes[i])
#color = COLOR_LIST[class_id]
#draw.line([(left, top), (left, bot), (right, bot), (right, top), (left, top)], width=thickness, fill=color)
cv2.rectangle(image, (left, top), (right, bot), (0, 255, 0), 3)
|
State Before: α : Type ?u.158839
r : α → α → Prop
o : Ordinal
f : (a : Ordinal) → a < o → Ordinal
c : Cardinal
hc : IsRegular c
ho : lift (card o) < c
⊢ lift (card o) < Ordinal.cof (ord c) State After: no goals Tactic: rwa [hc.cof_eq] |
Theorem a_implies_a : (forall A : Prop, A -> A).
Proof.
intros A.
intros proof_of_A.
exact proof_of_A.
Print a_implies_a.
(*1 subgoal
______________________________________(1/1)
forall A : Prop, A -> A
1 subgoal
A : Prop
______________________________________(1/1)
A -> A
1 subgoal
A : Prop
proof_of_A : A
______________________________________(1/1)
A
No more subgoals.
a_implies_a is defined
a_implies_a =
fun (A : Prop) (proof_of_A : A) => proof_of_A
: forall A : Prop, A -> A
Argument scopes are [type_scope _]*)
Theorem forward_small : (forall A B : Prop, A -> (A -> B) -> B).
Proof.
intros A.
intros B.
intros proof_of_A.
intros A_implies_B.
pose (proof_of_B := A_implies_B proof_of_A).
exact proof_of_B.
Qed.
Print forward_small.
(*1 subgoal
______________________________________(1/1)
forall A B : Prop,
A -> (A -> B) -> B
1 subgoal
______________________________________(1/1)
forall A B : Prop, A -> (A -> B) -> B
1 subgoal
A : Prop
______________________________________(1/1)
forall B : Prop, A -> (A -> B) -> B
1 subgoal
A, B : Prop
______________________________________(1/1)
A -> (A -> B) -> B
1 subgoal
A, B : Prop
proof_of_A : A
______________________________________(1/1)
(A -> B) -> B
1 subgoal
A, B : Prop
proof_of_A : A
A_implies_B : A -> B
______________________________________(1/1)
B
No more subgoals.
forward_small is defined
*forward_small =
fun (A B : Prop) (proof_of_A : A)
(A_implies_B : A -> B) =>
let proof_of_B := A_implies_B proof_of_A in
proof_of_B
: forall A B : Prop, A -> (A -> B) -> B
Argument scopes are [type_scope type_scope _ _]*)
Theorem backward_large : (forall A B C : Prop, A -> (A -> B) -> (B -> C) -> C).
Proof.
intros A B C.
intros proof_of_A A_implies_B B_implies_C.
refine (B_implies_C _).
refine (A_implies_B _).
exact proof_of_A.
Qed.
Print backward_large.
(*1 subgoal
______________________________________(1/1)
forall A B C : Prop,
A -> (A -> B) -> (B -> C) -> C
1 subgoal
A, B, C : Prop
______________________________________(1/1)
A -> (A -> B) -> (B -> C) -> C
1 subgoal
A, B, C : Prop
proof_of_A : A
A_implies_B : A -> B
B_implies_C : B -> C
______________________________________(1/1)
C
1 subgoal
A, B, C : Prop
proof_of_A : A
A_implies_B : A -> B
B_implies_C : B -> C
______________________________________(1/1)
A
backward_large is defined
backward_large =
fun (A B C : Prop) (proof_of_A : A)
(A_implies_B : A -> B) (B_implies_C : B -> C) =>
B_implies_C (A_implies_B proof_of_A)
: forall A B C : Prop,
A -> (A -> B) -> (B -> C) -> C
Argument scopes are [type_scope type_scope
type_scope _ _ _]*)
Theorem bigger_than_last : (forall A B C : Prop, A -> (A -> B) -> (A -> B -> C) -> C).
Proof.
intros A B C.
intros proof_of_A A_implies_B A_imp_B_imp_C.
pose (proof_of_B := A_implies_B proof_of_A).
pose (proof_of_C := A_imp_B_imp_C proof_of_A proof_of_B).
exact proof_of_C.
Show Proof.
Qed.
(*
1 subgoal
______________________________________(1/1)
forall A B C : Prop,
A -> (A -> B) -> (A -> B -> C) -> C
1 subgoal
A, B, C : Prop
______________________________________(1/1)
A -> (A -> B) -> (A -> B -> C) -> C
1 subgoal
A, B, C : Prop
proof_of_A : A
A_implies_B : A -> B
A_imp_B_imp_C : A -> B -> C
______________________________________(1/1)
C
1 subgoal
A, B, C : Prop
proof_of_A : A
A_implies_B : A -> B
A_imp_B_imp_C : A -> B -> C
proof_of_B := A_implies_B proof_of_A : B
______________________________________(1/1)
C
1 subgoal
A, B, C : Prop
proof_of_A : A
A_implies_B : A -> B
A_imp_B_imp_C : A -> B -> C
proof_of_B := A_implies_B proof_of_A : B
proof_of_C := A_imp_B_imp_C proof_of_A
proof_of_B : C
______________________________________(1/1)
C
No more subgoals.
(fun (A B C : Prop) (proof_of_A : A)
(A_implies_B : A -> B)
(A_imp_B_imp_C : A -> B -> C) =>
let proof_of_B := A_implies_B proof_of_A in
let proof_of_C :=
A_imp_B_imp_C proof_of_A proof_of_B in
proof_of_C)
bigger_than_last is defined
*)
Theorem inl : (forall A B : Prop, A -> A \/ B).
Proof.
intros A B.
intros proof_of_A.
pose (proof_of_A_or_B := or_introl proof_of_A : A \/ B).
exact proof_of_A_or_B.
Show Proof.
Qed.
(*
1 subgoal
______________________________________(1/1)
forall A B : Prop, A -> A \/ B
1 subgoal
A, B : Prop
______________________________________(1/1)
A -> A \/ B
1 subgoal
A, B : Prop
proof_of_A : A
______________________________________(1/1)
A \/ B
1 subgoal
A, B : Prop
proof_of_A : A
proof_of_A_or_B := (or_introl proof_of_A
:
A \/ B) : A \/ B
______________________________________(1/1)
A \/ B
No more subgoals.
(fun (A B : Prop) (proof_of_A : A) =>
let proof_of_A_or_B :=
or_introl proof_of_A : A \/ B in
proof_of_A_or_B)
inl is defined
*)
Theorem inr : (forall A B : Prop, B -> A \/ B).
Proof.
intros A B.
intros proof_of_B.
refine (or_intror _).
exact proof_of_B.
Show Proof.
Qed.
(*
1 subgoal
______________________________________(1/1)
forall A B : Prop, B -> A \/ B
1 subgoal
A, B : Prop
______________________________________(1/1)
B -> A \/ B
1 subgoal
A, B : Prop
proof_of_B : B
______________________________________(1/1)
A \/ B
1 subgoal
A, B : Prop
proof_of_B : B
______________________________________(1/1)
B
No more subgoals.
(fun (A B : Prop) (proof_of_B : B) =>
or_intror proof_of_B)
inr is defined
*)
Theorem or_commutes : (forall A B, A \/ B -> B \/ A).
Proof.
intros A B.
intros A_or_B.
case A_or_B.
intros proof_of_A.
refine (or_intror _).
exact proof_of_A.
intros proof_of_B.
refine (or_introl _).
exact proof_of_B.
Show Proof.
Qed.
(*
1 subgoal
______________________________________(1/1)
forall A B : Prop, A \/ B -> B \/ A
1 subgoal
A, B : Prop
______________________________________(1/1)
A \/ B -> B \/ A
1 subgoal
A, B : Prop
A_or_B : A \/ B
______________________________________(1/1)
B \/ A
2 subgoals
A, B : Prop
A_or_B : A \/ B
______________________________________(1/2)
A -> B \/ A
______________________________________(2/2)
B -> B \/ A
2 subgoals
A, B : Prop
A_or_B : A \/ B
proof_of_A : A
______________________________________(1/2)
B \/ A
______________________________________(2/2)
B -> B \/ A
2 subgoals
A, B : Prop
A_or_B : A \/ B
proof_of_A : A
______________________________________(1/2)
A
______________________________________(2/2)
B -> B \/ A
1 subgoal
A, B : Prop
A_or_B : A \/ B
______________________________________(1/1)
B -> B \/ A
1 subgoal
A, B : Prop
A_or_B : A \/ B
proof_of_B : B
______________________________________(1/1)
B \/ A
1 subgoal
A, B : Prop
A_or_B : A \/ B
proof_of_B : B
______________________________________(1/1)
B
No more subgoals.
(fun (A B : Prop) (A_or_B : A \/ B) =>
match A_or_B with
| or_introl proof_of_A => or_intror proof_of_A
| or_intror proof_of_B => or_introl proof_of_B
end)
*)
Theorem conj_intr : (forall A B : Prop, A -> B -> A /\ B).
Proof.
intros A B.
intros proof_of_A proof_of_B.
refine (conj _ _).
exact proof_of_A.
exact proof_of_B.
Show Proof.
Qed.
(*
1 subgoal
______________________________________(1/1)
forall A B : Prop, A -> B -> A /\ B
1 subgoal
A, B : Prop
______________________________________(1/1)
A -> B -> A /\ B
1 subgoal
A, B : Prop
proof_of_A : A
proof_of_B : B
______________________________________(1/1)
A /\ B
2 subgoals
A, B : Prop
proof_of_A : A
proof_of_B : B
______________________________________(1/2)
A
______________________________________(2/2)
B
1 subgoal
A, B : Prop
proof_of_A : A
proof_of_B : B
______________________________________(1/1)
B
No more subgoals.
(fun (A B : Prop) (proof_of_A : A) (proof_of_B : B) =>
conj proof_of_A proof_of_B)
*)
Theorem conj_commutes : (forall A B, A /\ B -> B /\ A).
Proof.
intros A B.
intros A_and_B.
case A_and_B.
intros proof_of_A proof_of_B.
refine (conj _ _).
exact proof_of_B.
exact proof_of_A.
Show Proof.
Qed.
(*
1 subgoal
______________________________________(1/1)
forall A B : Prop,
A /\ B -> B /\ A
1 subgoal
A, B : Prop
______________________________________(1/1)
A /\ B -> B /\ A
1 subgoal
A, B : Prop
A_and_B : A /\ B
______________________________________(1/1)
B /\ A
1 subgoal
A, B : Prop
A_and_B : A /\ B
______________________________________(1/1)
A -> B -> B /\ A
1 subgoal
A, B : Prop
A_and_B : A /\ B
proof_of_A : A
proof_of_B : B
______________________________________(1/1)
B /\ A
2 subgoals
A, B : Prop
A_and_B : A /\ B
proof_of_A : A
proof_of_B : B
______________________________________(1/2)
B
______________________________________(2/2)
A
1 subgoal
A, B : Prop
A_and_B : A /\ B
proof_of_A : A
proof_of_B : B
______________________________________(1/1)
A
No more subgoals.
(fun (A B : Prop) (A_and_B : A /\ B) =>
match A_and_B with
| conj proof_of_A proof_of_B =>
conj proof_of_B proof_of_A
end)
*)
Theorem exists_forall : (forall P : Set -> Prop, ~(exists x, P x) -> (forall x, ~(P x))).
Proof.
intros P.
intros not_exists_x_Px.
intros x.
unfold not.
intros P_x.
unfold not in not_exists_x_Px.
refine (not_exists_x_Px _).
exact (ex_intro P x P_x).
Show Proof.
Qed.
(*
1 subgoal
______________________________________(1/1)
forall P : Set -> Prop,
~ (exists x : Set, P x) ->
forall x : Set, ~ P x
1 subgoal
P : Set -> Prop
______________________________________(1/1)
~ (exists x : Set, P x) -> forall x : Set, ~ P x
1 subgoal
P : Set -> Prop
not_exists_x_Px : ~ (exists x : Set, P x)
______________________________________(1/1)
forall x : Set, ~ P x
1 subgoal
P : Set -> Prop
not_exists_x_Px : ~ (exists x : Set, P x)
x : Set
______________________________________(1/1)
~ P x
1 subgoal
P : Set -> Prop
not_exists_x_Px : ~ (exists x : Set, P x)
x : Set
______________________________________(1/1)
P x -> False
1 subgoal
P : Set -> Prop
not_exists_x_Px : ~ (exists x : Set, P x)
x : Set
P_x : P x
______________________________________(1/1)
False
1 subgoal
P : Set -> Prop
not_exists_x_Px : (exists x : Set, P x) -> False
x : Set
P_x : P x
______________________________________(1/1)
False
1 subgoal
P : Set -> Prop
not_exists_x_Px : (exists x : Set, P x) -> False
x : Set
P_x : P x
______________________________________(1/1)
exists x0 : Set, P x0
No more subgoals.
(fun (P : Set -> Prop)
(not_exists_x_Px : ~ (exists x : Set, P x))
(x : Set) (P_x : P x) =>
not_exists_x_Px (ex_intro P x P_x))
*)
Theorem eq_sym : (forall x y : Set, x = y -> y = x).
Proof.
intros x y.
intros x_y.
destruct x_y as [].
exact (eq_refl x).
Show Proof.
Qed.
(*
1 subgoal
______________________________________(1/1)
forall x y : Set, x = y -> y = x
1 subgoal
x, y : Set
______________________________________(1/1)
x = y -> y = x
1 subgoal
x, y : Set
x_y : x = y
______________________________________(1/1)
y = x
1 subgoal
x : Set
______________________________________(1/1)
x = x
No more subgoals.
(fun (x y : Set) (x_y : x = y) =>
match x_y in (_ = y0) return (y0 = x) with
| eq_refl => eq_refl
end)
*)
Theorem eq_trans : (forall x y z : Set, x = y -> y = z -> x = z).
Proof.
intros x y z.
intros x_y y_z.
destruct x_y as [].
destruct y_z as [].
exact (eq_refl x).
Show Proof.
Qed.
(*
1 subgoal
______________________________________(1/1)
forall x y z : Set, x = y -> y = z -> x = z
1 subgoal
x, y, z : Set
______________________________________(1/1)
x = y -> y = z -> x = z
1 subgoal
x, y, z : Set
x_y : x = y
y_z : y = z
______________________________________(1/1)
x = z
1 subgoal
x, z : Set
y_z : x = z
______________________________________(1/1)
x = z
1 subgoal
x : Set
______________________________________(1/1)
x = x
(fun (x y z : Set) (x_y : x = y) (y_z : y = z) =>
match x_y in (_ = y0) return (y0 = z -> x = z) with
| eq_refl =>
fun y_z0 : x = z =>
match y_z0 in (_ = y0) return (x = y0) with
| eq_refl => eq_refl
end
end y_z)
*)
Theorem plus_sym : (forall n m, n + m = m + n).
Proof.
intros n m.
elim n.
elim m.
exact (eq_refl (0 + 0)).
intros m'.
intros inductive_hyp_m.
simpl.
rewrite <- inductive_hyp_m.
simpl.
exact (eq_refl (S m')).
intros n'.
intros inductive_hyp_n.
simpl.
rewrite inductive_hyp_n.
elim m.
simpl.
exact (eq_refl (S n')).
intros m'.
intros inductive_hyp_m.
simpl.
rewrite inductive_hyp_m.
simpl.
exact (eq_refl (S (m' + S n'))).
Show Proof.
Qed.
(*
1 subgoal
______________________________________(1/1)
forall n m : nat, n + m = m + n
1 subgoal
n, m : nat
______________________________________(1/1)
n + m = m + n
2 subgoals
n, m : nat
______________________________________(1/2)
0 + m = m + 0
______________________________________(2/2)
forall n0 : nat,
n0 + m = m + n0 -> S n0 + m = m + S n0
3 subgoals
n, m : nat
______________________________________(1/3)
0 + 0 = 0 + 0
______________________________________(2/3)
forall n0 : nat,
0 + n0 = n0 + 0 -> 0 + S n0 = S n0 + 0
______________________________________(3/3)
forall n0 : nat,
n0 + m = m + n0 -> S n0 + m = m + S n0
2 subgoals
n, m : nat
______________________________________(1/2)
forall n0 : nat,
0 + n0 = n0 + 0 -> 0 + S n0 = S n0 + 0
______________________________________(2/2)
forall n0 : nat,
n0 + m = m + n0 -> S n0 + m = m + S n0
2 subgoals
n, m, m' : nat
______________________________________(1/2)
0 + m' = m' + 0 -> 0 + S m' = S m' + 0
______________________________________(2/2)
forall n0 : nat,
n0 + m = m + n0 -> S n0 + m = m + S n0
2 subgoals
n, m, m' : nat
inductive_hyp_m : 0 + m' = m' + 0
______________________________________(1/2)
0 + S m' = S m' + 0
______________________________________(2/2)
forall n0 : nat,
n0 + m = m + n0 -> S n0 + m = m + S n0
2 subgoals
n, m, m' : nat
inductive_hyp_m : 0 + m' = m' + 0
______________________________________(1/2)
S m' = S (m' + 0)
______________________________________(2/2)
forall n0 : nat,
n0 + m = m + n0 -> S n0 + m = m + S n0
2 subgoals
n, m, m' : nat
inductive_hyp_m : 0 + m' = m' + 0
______________________________________(1/2)
S m' = S (0 + m')
______________________________________(2/2)
forall n0 : nat,
n0 + m = m + n0 -> S n0 + m = m + S n0
2 subgoals
n, m, m' : nat
inductive_hyp_m : 0 + m' = m' + 0
______________________________________(1/2)
S m' = S m'
______________________________________(2/2)
forall n0 : nat,
n0 + m = m + n0 -> S n0 + m = m + S n0
1 subgoal
n, m : nat
______________________________________(1/1)
forall n0 : nat,
n0 + m = m + n0 -> S n0 + m = m + S n0
1 subgoal
n, m, n' : nat
______________________________________(1/1)
n' + m = m + n' -> S n' + m = m + S n'
1 subgoal
n, m, n' : nat
inductive_hyp_n : n' + m = m + n'
______________________________________(1/1)
S n' + m = m + S n'
1 subgoal
n, m, n' : nat
inductive_hyp_n : n' + m = m + n'
______________________________________(1/1)
S (n' + m) = m + S n'
1 subgoal
n, m, n' : nat
inductive_hyp_n : n' + m = m + n'
______________________________________(1/1)
S (m + n') = m + S n'
2 subgoals
n, m, n' : nat
inductive_hyp_n : n' + m = m + n'
______________________________________(1/2)
S (0 + n') = 0 + S n'
______________________________________(2/2)
forall n0 : nat,
S (n0 + n') = n0 + S n' -> S (S n0 + n') = S n0 + S n'
2 subgoals
n, m, n' : nat
inductive_hyp_n : n' + m = m + n'
______________________________________(1/2)
S n' = S n'
______________________________________(2/2)
forall n0 : nat,
S (n0 + n') = n0 + S n' -> S (S n0 + n') = S n0 + S n'
1 subgoal
n, m, n' : nat
inductive_hyp_n : n' + m = m + n'
______________________________________(1/1)
forall n0 : nat,
S (n0 + n') = n0 + S n' -> S (S n0 + n') = S n0 + S n'
1 subgoal
n, m, n' : nat
inductive_hyp_n : n' + m = m + n'
m' : nat
______________________________________(1/1)
S (m' + n') = m' + S n' -> S (S m' + n') = S m' + S n'
1 subgoal
n, m, n' : nat
inductive_hyp_n : n' + m = m + n'
m' : nat
inductive_hyp_m : S (m' + n') = m' + S n'
______________________________________(1/1)
S (S m' + n') = S m' + S n'
1 subgoal
n, m, n' : nat
inductive_hyp_n : n' + m = m + n'
m' : nat
inductive_hyp_m : S (m' + n') = m' + S n'
______________________________________(1/1)
S (S (m' + n')) = S (m' + S n')
1 subgoal
n, m, n' : nat
inductive_hyp_n : n' + m = m + n'
m' : nat
inductive_hyp_m : S (m' + n') = m' + S n'
______________________________________(1/1)
S (m' + S n') = S (m' + S n')
1 subgoal
n, m, n' : nat
inductive_hyp_n : n' + m = m + n'
m' : nat
inductive_hyp_m : S (m' + n') = m' + S n'
______________________________________(1/1)
S (m' + S n') = S (m' + S n')
No more subgoals.
(fun n m : nat =>
nat_ind (fun n0 : nat => n0 + m = m + n0)
(nat_ind (fun m0 : nat => 0 + m0 = m0 + 0) eq_refl
(fun (m' : nat)
(inductive_hyp_m : 0 + m' = m' + 0) =>
eq_ind (0 + m') (fun n0 : nat => S m' = S n0)
eq_refl (m' + 0) inductive_hyp_m) m)
(fun (n' : nat) (inductive_hyp_n : n' + m = m + n')
=>
eq_ind_r (fun n0 : nat => S n0 = m + S n')
(nat_ind
(fun m0 : nat => S (m0 + n') = m0 + S n')
eq_refl
(fun (m' : nat)
(inductive_hyp_m : S (m' + n') = m' + S n')
=>
eq_ind_r
(fun n0 : nat => S n0 = S (m' + S n'))
eq_refl inductive_hyp_m) m)
inductive_hyp_n) n)
*)
|
[STATEMENT]
lemma Mapping_upd_set_keys: "Mapping.keys (upd_set m f X) = Mapping.keys m \<union> X"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Mapping.keys (upd_set m f X) = Mapping.keys m \<union> X
[PROOF STEP]
by (auto simp add: Mapping_lookup_upd_set dest!: Mapping_keys_dest intro: Mapping_keys_intro) |
module TypedContainers.In
import Data.List
import Data.List.Elem
import Data.DPair
%default total
lemma0 : ([x] = [y]) -> (x = y)
lemma0 Refl = Refl
lemma1 : {0 xs : List a} -> {0 ys : List a} -> ((x :: xs) = (y :: ys)) -> (xs = ys)
lemma1 Refl = Refl
lemma2 : {0 xs : List a} -> {0 ys : List a} -> ((x :: xs) = (y :: ys)) -> (x = y)
lemma2 Refl = Refl
public export
data In : (a -> Bool) -> List a -> Type where
MkIn : (x : a) -> (f x = True) -> (xs : List a) -> In f (x :: xs)
MkInCons : (x : a) -> (0 xs : List a) -> In f xs -> In f (x :: xs)
public export
inFilter : (f : a -> Bool) -> (g : a -> Bool) -> ((x : a) -> (g x = True) -> f x = True) -> (l : List a) -> In g l -> In g (filter f l)
inFilter f g p1 [] p2 impossible
inFilter f g p1 (x :: xs) (MkIn x p2 xs) =
let p3 = p1 x p2 in
rewrite p3 in MkIn x p2 (filter f xs) {f = g}
inFilter f g p1 (x :: xs) (MkInCons x xs p2) =
let r = inFilter f g p1 xs p2 in
let MkDPair p2 p3 : DPair Bool (f x ===) = MkDPair (f x) Refl in
case p2 of
True => rewrite p3 in MkInCons x (filter f xs) r
False => rewrite p3 in r
fromFilter : {f : a -> Bool} -> {l : List a} -> {lEq : l' === filter f l} -> Elem x l' -> (f x = True)
fromFilter (Here {x, xs}) = case l of
[] impossible
y :: ys =>
let (MkDPair p0 p1) : DPair Bool ((f y) ===) = MkDPair (f y) Refl in
case p0 of
True =>
let p2 : (y :: filter f ys = filter f (y :: ys)) = rewrite p1 in Refl in
let p3 : (x :: xs = y :: filter f ys) = rewrite p2 in lEq in
let p4 = lemma2 p3 in
rewrite p4 in p1
False =>
let p2 : (filter f ys = filter f (y :: ys)) = rewrite p1 in Refl in
let p3 : (x :: xs = filter f ys) = rewrite p2 in lEq in
fromFilter {f, l = ys, lEq = p3} (Here {x, xs})
fromFilter (There p {x, y, xs}) =
case l of
[] impossible
z :: zs =>
let (MkDPair p0 p1) : DPair Bool ((f z) ===) = MkDPair (f z) Refl in
case p0 of
True =>
let p2 : (z :: filter f zs = filter f (z :: zs)) = rewrite p1 in Refl in
let p3 : (y :: xs = z :: filter f zs) = rewrite p2 in lEq in
let p4 = lemma1 p3 in
fromFilter {f, lEq = p4} p
False =>
let p2 : (filter f zs = filter f (z :: zs)) = rewrite p1 in Refl in
let p3 : (y :: xs = filter f zs) = rewrite p2 in lEq in
fromFilter {f, lEq = p3} (There p {x, y, xs})
extractIn' : {f : a -> Bool} -> {g : a -> Bool} -> {l : List a} -> {l' : List a} -> {lEq : l' = filter g l} -> In f l' -> DPair a (\x => (f x = True, g x = True))
extractIn' (MkIn x p0 xs) =
let p1 = Here {x, xs} in
let p2 = fromFilter {f = g, l, l' = x :: xs, lEq} p1 in
MkDPair x (p0, p2)
extractIn' (MkInCons x xs rec) =
case l of
[] impossible
y :: ys =>
let (MkDPair p2 p3) : DPair Bool ((g y) ===) = MkDPair (g y) Refl in
case p2 of
True =>
let p4 : (y :: filter g ys = filter g (y :: ys)) = rewrite p3 in Refl in
let p5 : (x :: xs = y :: filter g ys) = rewrite p4 in lEq in
extractIn' {f, g, l = ys, l' = xs, lEq = lemma1 p5} rec
False =>
let p4 : (filter g ys = filter g (y :: ys)) = rewrite p3 in Refl in
let p5 : (x :: xs = filter g ys) = rewrite p4 in lEq in
extractIn' {f, g, l = ys, l' = x :: xs, lEq = p5} (MkInCons x xs rec)
public export
extractIn : {f : a -> Bool} -> {g : a -> Bool} -> {l : List a} -> In f (filter g l) -> DPair a (\x => (f x = True, g x = True))
extractIn = extractIn' {lEq = Refl}
outFilter' : {0 f : a -> Bool} -> {g : a -> Bool} -> (xxs : List a) -> (pl : yys = filter g xxs) -> In f yys -> In f xxs
outFilter' [] pl (MkIn _ _ _) impossible
outFilter' [] pl (MkInCons _ _ _) impossible
outFilter' (x :: xs) pl (MkIn y py ys) with (g x)
outFilter' (x :: xs) pl (MkIn y py ys) | True =
let pl' = lemma2 pl in
let px : (f x = True) = rewrite sym pl' in py in
MkIn x px xs
outFilter' (x :: xs) pl (MkIn y py ys) | False = MkInCons x xs $ outFilter' {f, g} xs pl (MkIn {f} y py ys)
outFilter' (x :: xs) pl (MkInCons y ys py) with (g x)
outFilter' (x :: xs) pl (MkInCons y ys py) | True = MkInCons x xs $ outFilter' {f, g} xs (lemma1 pl) py
outFilter' (x :: xs) pl (MkInCons y ys py) | False = MkInCons x xs $ outFilter' {f, g} xs pl (MkInCons y ys py)
public export
outFilter : {g : a -> Bool} -> {l : List a} -> In f (filter g l) -> In f l
outFilter p = outFilter' {f, g} l Refl p
|
(* Title: HOL/Metis_Examples/Type_Encodings.thy
Author: Jasmin Blanchette, TU Muenchen
Example that exercises Metis's (and hence Sledgehammer's) type encodings.
*)
section \<open>
Example that Exercises Metis's (and Hence Sledgehammer's) Type Encodings
\<close>
theory Type_Encodings
imports Main
begin
declare [[metis_new_skolem]]
text \<open>Setup for testing Metis exhaustively\<close>
lemma fork: "P \<Longrightarrow> P \<Longrightarrow> P" by assumption
ML \<open>
val type_encs =
["erased",
"poly_guards",
"poly_guards?",
"poly_guards??",
"poly_guards@",
"poly_tags",
"poly_tags?",
"poly_tags??",
"poly_tags@",
"poly_args",
"poly_args?",
"raw_mono_guards",
"raw_mono_guards?",
"raw_mono_guards??",
"raw_mono_guards@",
"raw_mono_tags",
"raw_mono_tags?",
"raw_mono_tags??",
"raw_mono_tags@",
"raw_mono_args",
"raw_mono_args?",
"mono_guards",
"mono_guards?",
"mono_guards??",
"mono_tags",
"mono_tags?",
"mono_tags??",
"mono_args"]
fun metis_exhaust_tac ctxt ths =
let
fun tac [] st = all_tac st
| tac (type_enc :: type_encs) st =
st (* |> tap (fn _ => tracing (@{make_string} type_enc)) *)
|> ((if null type_encs then all_tac else resolve_tac ctxt @{thms fork} 1)
THEN Metis_Tactic.metis_tac [type_enc]
ATP_Problem_Generate.combsN ctxt ths 1
THEN COND (has_fewer_prems 2) all_tac no_tac
THEN tac type_encs)
in tac type_encs end
\<close>
method_setup metis_exhaust = \<open>
Attrib.thms >>
(fn ths => fn ctxt => SIMPLE_METHOD (metis_exhaust_tac ctxt ths))
\<close> "exhaustively run Metis with all type encodings"
text \<open>Miscellaneous tests\<close>
lemma "x = y \<Longrightarrow> y = x"
by metis_exhaust
lemma "[a] = [Suc 0] \<Longrightarrow> a = 1"
by (metis_exhaust last.simps One_nat_def)
lemma "map Suc [0] = [Suc 0]"
by (metis_exhaust list.map)
lemma "map Suc [1 + 1] = [Suc 2]"
by (metis_exhaust list.map nat_1_add_1)
lemma "map Suc [2] = [Suc (1 + 1)]"
by (metis_exhaust list.map nat_1_add_1)
definition "null xs = (xs = [])"
lemma "P (null xs) \<Longrightarrow> null xs \<Longrightarrow> xs = []"
by (metis_exhaust null_def)
lemma "(0::nat) + 0 = 0"
by (metis_exhaust add_0_left)
end
|
function quadrule_test13 ( )
%*****************************************************************************80
%
%% TEST13 tests LAGUERRE_EK_COMPUTE and LAGUERRE_SUM.
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 23 April 2011
%
% Author:
%
% John Burkardt
%
order_max = 20;
nfunc = func_set ( 'COUNT', 'DUMMY' );
fprintf ( 1, '\n' );
fprintf ( 1, 'TEST13\n' );
fprintf ( 1, ' LAGUERRE_EK_COMPUTE computes a Gauss-Laguerre rule;\n' );
fprintf ( 1, ' LAGUERRE_SUM carries it out.\n' );
fprintf ( 1, '\n' );
fprintf ( 1, ' Quadrature order will vary.\n' );
fprintf ( 1, ' Integrand will vary.\n' );
fprintf ( 1, ' The weight function is EXP ( - X ).\n' );
fprintf ( 1, '\n' );
a = 1.0;
fprintf ( 1, ' The integration interval is [ %f, +oo ).\n', a );
fprintf ( 1, '\n' );
for ilo = 1 : 5 : nfunc
ihi = min ( ilo + 4, nfunc );
fprintf ( 1, '\n' );
fprintf ( 1, ' ' );
for i = ilo : ihi
fprintf ( '%14s', fname(i) );
end
fprintf ( 1, '\n' );
fprintf ( 1, '\n' );
for norder = 1 : order_max
fprintf ( 1, ' %2d', norder );
for i = ilo : ihi
func_set ( 'SET', i );
[ xtab, weight ] = laguerre_ek_compute ( norder );
result(i) = laguerre_sum ( @func, a, norder, xtab, weight );
fprintf ( 1, ' %12f', result(i) );
end
fprintf ( 1, '\n' );
end
end
return
end
|
"Simulation controls"
global NUMBER_OF_WALKS = 100
global MAX_STEPS_PER_WALK = Int(floor(20 * 60 / 0.0000027))
# twenty minutes in experiment
"Solvent Diffusion Step Sizes (microns per 2.7 microseconds)"
STEP_SIZE_DICT = Dict("water" => 0.1, "enz" => 0.005, "ppd" => 0.001)
const WATER_STEP_SIZE = 0.1
const ENZ_STEP_SIZE = 0.005
const PPD_STEP_SIZE = 0.001
"Sensor/Walls Coordinates"
const WALL_Y = 0.0
const SENSOR_WIDTH = 25.0
const SENSOR_SPACING = 25.0
const SENSOR_SPAWN_LEFT_X = 0.0
const SENSOR_SPAWN_RIGHT_X = SENSOR_SPAWN_LEFT_X + SENSOR_WIDTH
const SENSOR_SECOND_LEFT_X = SENSOR_SPAWN_RIGHT_X + SENSOR_SPACING
const SENSOR_SECOND_RIGHT_X = SENSOR_SECOND_LEFT_X + SENSOR_WIDTH
const SENSOR_THIRD_LEFT_X = SENSOR_SECOND_RIGHT_X + SENSOR_SPACING
const SENSOR_THIRD_RIGHT_X = SENSOR_THIRD_LEFT_X + SENSOR_WIDTH
const SENSOR_FOURTH_LEFT_X = SENSOR_THIRD_RIGHT_X + SENSOR_SPACING
const SENSOR_FOURTH_RIGHT_X = SENSOR_FOURTH_LEFT_X + SENSOR_WIDTH
"PPD Layer Dimensions (for spawn)"
const PPD_MAX_Y = 0.15
const PPD_MIN_Y = 0.0
const PPD_LEFT_X = 0.0
const PPD_RIGHT_X = 25.0
"Enzyme Layer Dimensions (for spawn, other sensors are standardized)"
const ENZYME_MAX_Y = 3.0
const ENZYME_SPACING = 21.0
const ENZYME_WIDTH = 29.0
const ENZYME_LEFT_X = -2.0
const ENZYME_RIGHT_X = ENZYME_LEFT_X + ENZYME_WIDTH
const ZONE_ONE_RIGHT_X = ENZYME_RIGHT_X + 0.5 * ENZYME_SPACING
const ZONE_TWO_RIGHT_X = ZONE_ONE_RIGHT_X + ENZYME_SPACING + ENZYME_WIDTH
const ZONE_THREE_RIGHT_X = ZONE_TWO_RIGHT_X + ENZYME_SPACING + ENZYME_WIDTH
"Spawn inside main enzyme layer"
const BORDER_CORRECTION = 0.001
const SPAWN_LEFT_X = ENZYME_LEFT_X + BORDER_CORRECTION
const SPAWN_RIGHT_X = ENZYME_RIGHT_X - BORDER_CORRECTION
const SPAWN_ENZYME_MAX_Y = ENZYME_MAX_Y - BORDER_CORRECTION
const SPAWN_LENGTH = SPAWN_RIGHT_X - SPAWN_LEFT_X + 2 * SPAWN_ENZYME_MAX_Y
"Enzyme-Water Corners"
const CORNER_CUT_IN_ENZ = ENZ_STEP_SIZE * sqrt(2) / 2
const CORNER_CUT_IN_WATER = WATER_STEP_SIZE * sqrt(2) / 2
# test set: locationbools here
const WATER_TO_ENZ_NORTHEAST = [ENZYME_RIGHT_X - CORNER_CUT_IN_ENZ, ENZYME_MAX_Y - CORNER_CUT_IN_ENZ]
const WATER_TO_ENZ_NORTHWEST = [ENZYME_LEFT_X + CORNER_CUT_IN_ENZ, ENZYME_MAX_Y - CORNER_CUT_IN_ENZ]
const ENZ_TO_WATER_NORTHEAST = [ENZYME_RIGHT_X + CORNER_CUT_IN_WATER, ENZYME_MAX_Y + CORNER_CUT_IN_WATER]
const ENZ_TO_WATER_NORTHWEST = [ENZYME_LEFT_X - CORNER_CUT_IN_WATER, ENZYME_MAX_Y + CORNER_CUT_IN_WATER]
"PPD-Enzyme Corners"
const CORNER_CUT_IN_PPD = PPD_STEP_SIZE * sqrt(2) / 2
const ENZ_TO_PPD_NORTHEAST = [PPD_RIGHT_X - CORNER_CUT_IN_PPD, PPD_MAX_Y - CORNER_CUT_IN_PPD]
const ENZ_TO_PPD_NORTHWEST = [PPD_LEFT_X + CORNER_CUT_IN_PPD, PPD_MAX_Y - CORNER_CUT_IN_PPD]
const PPD_TO_ENZ_NORTHEAST = [PPD_RIGHT_X + CORNER_CUT_IN_ENZ, PPD_MAX_Y + CORNER_CUT_IN_ENZ]
const PPD_TO_ENZ_NORTHWEST = [PPD_LEFT_X - CORNER_CUT_IN_ENZ, PPD_MAX_Y + CORNER_CUT_IN_ENZ]
"Escape Bound Limits"
const ESCAPE_X = 4 * SENSOR_WIDTH + 4 * SENSOR_SPACING
const ESCAPE_Y = ESCAPE_X
"Safe Bound Limits"
const MARGIN_OF_COLLISION = 2 * WATER_STEP_SIZE
const SAFE_MIN_Y = ENZYME_MAX_Y + MARGIN_OF_COLLISION
const SAFE_MAX_Y = ESCAPE_Y - MARGIN_OF_COLLISION
const SAFE_MAX_X = ESCAPE_X - MARGIN_OF_COLLISION
|
[STATEMENT]
lemma PO_m3_step5_refines_m2_step5:
"{R23}
(m2_step5 Rb A B Nb Kab), (m3_step5 Rb A B Nb Kab)
{> R23}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. {R23} m2_step5 Rb A B Nb Kab, m3_step5 Rb A B Nb Kab {> R23}
[PROOF STEP]
by (auto simp add: PO_rhoare_defs R23_def m2_defs m3_defs intro!: R23_intros)
(auto) |
! Name = ARPIT KUMAR JAIN ROLL No = 180122009
! Code for HA8 Time Dependent Schrodinger Equation (TDSE) --> Using Discrete Fourire Transformation
MODULE precision
IMPLICIT NONE
! dp = double precisiona
INTEGER, PARAMETER:: dp = SELECTED_REAL_KIND(12)
END MODULE precision
MODULE constants
USE precision
IMPLICIT NONE
REAL(KIND = dp), PARAMETER:: pi = acos(-1.0)
! k0 = p0/hbar, hbar = 1 for a.u.
! So k0 = p0
REAL(KIND = dp), PARAMETER:: alpha = 20.0, x0 = -0.5, p0 = 50.0, m = 14500.0
REAL(KIND = dp), PARAMETER:: Xmin = -2.0, dx = 0.02, dt = 0.1
INTEGER, PARAMETER:: numX = 256
COMPLEX, PARAMETER:: iota = (0.0, 1.0)
CHARACTER*64:: filename
END MODULE constants
PROGRAM TDSE_Discrete_Fourier_Transformation
USE precision
USE constants
IMPLICIT NONE
INTEGER:: i, j
REAL(KIND = dp), DIMENSION(numX):: x, pot_V, Km, KSquare
COMPLEX(KIND = dp), DIMENSION(numX):: psit0, psit1, psit2, Tpsi
OPEN(UNIT = 6789, FILE = 'potential.txt')
! First Set Up X-Grid
DO i = 1, numX
x(i) = Xmin + (i-1) * dx
ENDDO
! Now Set Up Potential Grid
DO i = 1, numX
IF(x(i) .GE. 0.0_dp) THEN
pot_V(i) = 0.1
ELSE
pot_V(i) = 0.0
ENDIF
WRITE(6789, 859) x(i), pot_V(i)
859 FORMAT(f0.3, 3x, f0.6)
ENDDO
CLOSE(6789)
! Calculate Initial wavepacket ψ(x, t0) using given equation
CALL InitialWavePacket(x, psit0)
! Calculation of K-Grid
CALL CalculateKgrid(Km, KSquare)
! Calculate Wavepacket at time t = 1 ψ(x, t1) using Euler Method
CALL EulerWavePacket(x, pot_V, psit0, psit1, Km, KSquare)
! Propagation of ψ from t = 2 to 5000 time step
DO j = 2, 5000
Tpsi = psit1
CALL DiscreteFourierTransformation(x, Tpsi, Km, KSquare)
CALL PropagateWavePacket(x, pot_V, psit0, psit1, psit2, Tpsi, j)
! Update Values for next propagation
psit0 = psit1
psit1 = psit2
ENDDO
END PROGRAM TDSE_Discrete_Fourier_Transformation
! Subroutine for initial wavepacket at t = 0
SUBROUTINE InitialWavePacket(x, psit0)
USE precision
USE constants
IMPLICIT NONE
REAL(KIND = dp):: x(numX), psisq
COMPLEX(KIND = dp):: psit0(numX)
INTEGER:: i
OPEN(UNIT = 0, FILE = 'psi0.txt')
DO i = 1, numX
psit0(i) = ( (2.0_dp * alpha/pi)**0.25_dp ) * EXP(iota * p0 * (x(i)-x0)) * EXP(-alpha * (x(i)-x0)**2)
psisq = REAL(psit0(i) * CONJG(psit0(i)))
WRITE(0, *) x(i), psisq
ENDDO
CLOSE(0)
END SUBROUTINE InitialWavePacket
! Subroutine for calculation of K and K^2
SUBROUTINE CalculateKgrid(Km, KSquare)
USE precision
USE constants
IMPLICIT NONE
REAL(KIND = dp):: Km(numX), KSquare(numX)
INTEGER:: i
DO i = 1, numX/2
Km(i) = 2.0_dp * pi * dfloat(i-1) / (dfloat(numX) * dx)
ENDDO
DO i = numX/2+1, numX
Km(i) = 2.0_dp * pi * dfloat(i-1-numX) / (dfloat(numX) * dx)
ENDDO
KSquare = Km * Km
END SUBROUTINE CalculateKgrid
! Subroutine for WavePacket at t = 1 step using Euler Method
SUBROUTINE EulerWavePacket(x, pot_V, psit0, psit1, Km, KSquare)
USE precision
USE constants
IMPLICIT NONE
REAL(KIND = dp):: x(numX), pot_V(numX), Km(numX), KSquare(numX)
COMPLEX(KIND = dp):: psit0(numX), psit1(numX), Tpsi(numX)
INTEGER:: i
Tpsi = psit0
CALL DiscreteFourierTransformation(x, Tpsi, Km, KSquare)
DO i = 1, numX
psit1(i) = psit0(i) + iota * dt * ( Tpsi(i)/(2.0_dp * m) - pot_V(i) * psit0(i) )
ENDDO
END SUBROUTINE EulerWavePacket
SUBROUTINE PropagateWavePacket(x, pot_V, psit0, psit1, psit2, Tpsi, iterationNumber)
USE precision
USE constants
IMPLICIT NONE
REAL(KIND = dp):: x(numX), pot_V(numX), psisq
COMPLEX(KIND = dp):: psit0(numX), psit1(numX), psit2(numX), Tpsi(numX)
INTEGER:: i, iterationNumber
DO i = 1, numX
psit2(i) = psit0(i) - 2.0_dp * iota * dt * ( -Tpsi(i)/(2.0_dp*m) + pot_V(i) * psit1(i) )
psisq = REAL(psit2(i) * CONJG(psit2(i)))
! We have to plot for every 100th time stap so take mode with 100
IF(MOD(iterationNumber, 100) .EQ. 0) THEN
WRITE(filename, 8976) iterationNumber
8976 FORMAT('psi',i0,'.txt')
IF(i .EQ. 1) WRITE(*, 15) filename
15 FORMAT("Generating ", A11, "...")
OPEN(unit = 16, FILE = filename)
WRITE(16, *) x(i), psisq
ENDIF
ENDDO
END SUBROUTINE PropagateWavePacket
SUBROUTINE DiscreteFourierTransformation(x, psi, Km, KSquare)
USE precision
USE constants
IMPLICIT NONE
REAL(KIND = dp):: x(numX), Km(numX), KSquare(numX)
COMPLEX(KIND = dp):: psi(numX), phi(numX)
INTEGER:: i, j
phi = 0.0
DO j = 1, numX
phi = phi + psi(j) * EXP(-iota * Km * x(j))
ENDDO
phi = phi / sqrt(dfloat(numX))
phi = -KSquare * phi
psi = 0.0
DO i = 1, numX
psi = psi + phi(i) * EXP(iota * Km(i) * x)
ENDDO
psi = psi / sqrt(dfloat(numX))
END SUBROUTINE DiscreteFourierTransformation
|
The degree of a polynomial raised to a power is less than or equal to the degree of the polynomial times the power. |
Old English Wielisc, Wylisc (West Saxon), Welisc, Wælisc (Anglian and Kentish) "foreign; British (not Anglo-Saxon), Welsh; not free, servile," from Wealh, Walh "Celt, Briton, Welshman, non-Germanic foreigner;" in Tolkien's definition, "common Gmc. name for a man of what we should call Celtic speech," but also applied in Germanic languages to speakers of Latin, hence Old High German Walh, Walah "Celt, Roman, Gaulish," and Old Norse Val-land "France," Valir "Gauls, non-Germanic inhabitants of France" (Danish vælsk "Italian, French, southern"); from Proto-Germanic *Walkhiskaz, from a Celtic tribal name represented by Latin Volcæ (Caesar) "ancient Celtic tribe in southern Gaul."
As a noun, "the Britons," also "the Welsh language," both from Old English. The word survives in Wales, Cornwall, Walloon, walnut, and in surnames Walsh and Wallace. Borrowed in Old Church Slavonic as vlachu, and applied to the Rumanians, hence Wallachia. Among the English, Welsh was used disparagingly of inferior or substitute things (such as Welsh cricket "louse" (1590s); Welsh comb "thumb and four fingers" (1796), and compare welch (v.)). Welsh rabbit is from 1725, also perverted by folk-etymology as Welsh rarebit (1785). |
[GOAL]
R : Type u
inst✝ : EuclideanDomain R
m k : R
⊢ m % k + m / k * k = m
[PROOFSTEP]
rw [mul_comm]
[GOAL]
R : Type u
inst✝ : EuclideanDomain R
m k : R
⊢ m % k + k * (m / k) = m
[PROOFSTEP]
exact mod_add_div _ _
[GOAL]
R : Type u
inst✝ : EuclideanDomain R
m k : R
⊢ m / k * k + m % k = m
[PROOFSTEP]
rw [mul_comm]
[GOAL]
R : Type u
inst✝ : EuclideanDomain R
m k : R
⊢ k * (m / k) + m % k = m
[PROOFSTEP]
exact div_add_mod _ _
[GOAL]
R✝ : Type u
inst✝¹ : EuclideanDomain R✝
R : Type u_1
inst✝ : EuclideanDomain R
a b : R
⊢ b * (a / b) + a % b - b * (a / b) = a - b * (a / b)
[PROOFSTEP]
rw [div_add_mod]
[GOAL]
R : Type u
inst✝ : EuclideanDomain R
a b : R
h : a ≠ 0
⊢ ¬a * b ≺ b
[PROOFSTEP]
rw [mul_comm]
[GOAL]
R : Type u
inst✝ : EuclideanDomain R
a b : R
h : a ≠ 0
⊢ ¬b * a ≺ b
[PROOFSTEP]
exact mul_left_not_lt b h
[GOAL]
R : Type u
inst✝ : EuclideanDomain R
a : R
⊢ a % 0 = a
[PROOFSTEP]
simpa only [zero_mul, zero_add] using div_add_mod a 0
[GOAL]
R : Type u
inst✝ : EuclideanDomain R
a : R
this : (p : Prop) → Decidable p
h : ¬a = 0
⊢ ¬a ≺ 1
[PROOFSTEP]
simpa only [one_mul] using mul_left_not_lt 1 h
[GOAL]
R : Type u
inst✝ : EuclideanDomain R
b d : R
ha : b * d ≠ 0
⊢ d = 0 → b * d = 0
[PROOFSTEP]
rintro rfl
[GOAL]
R : Type u
inst✝ : EuclideanDomain R
b : R
ha : b * 0 ≠ 0
⊢ b * 0 = 0
[PROOFSTEP]
exact mul_zero _
[GOAL]
R : Type u
inst✝ : EuclideanDomain R
P : R → R → Prop
a b : R
H0 : ∀ (x : R), P 0 x
H1 : ∀ (a b : R), a ≠ 0 → P (b % a) a → P a b
a0 : a = 0
⊢ P a b
[PROOFSTEP]
change P a b
[GOAL]
R : Type u
inst✝ : EuclideanDomain R
P : R → R → Prop
a b : R
H0 : ∀ (x : R), P 0 x
H1 : ∀ (a b : R), a ≠ 0 → P (b % a) a → P a b
a0 : a = 0
⊢ P a b
[PROOFSTEP]
exact a0.symm ▸ H0 b
[GOAL]
R : Type u
inst✝¹ : EuclideanDomain R
inst✝ : DecidableEq R
a : R
⊢ gcd 0 a = a
[PROOFSTEP]
rw [gcd]
[GOAL]
R : Type u
inst✝¹ : EuclideanDomain R
inst✝ : DecidableEq R
a : R
⊢ (if a0 : 0 = 0 then a
else
let_fun x := (_ : a % 0 ≺ 0);
gcd (a % 0) 0) =
a
[PROOFSTEP]
exact if_pos rfl
[GOAL]
R : Type u
inst✝¹ : EuclideanDomain R
inst✝ : DecidableEq R
s t r' s' t' : R
⊢ xgcdAux 0 s t r' s' t' = (r', s', t')
[PROOFSTEP]
unfold xgcdAux
[GOAL]
R : Type u
inst✝¹ : EuclideanDomain R
inst✝ : DecidableEq R
s t r' s' t' : R
⊢ (if _hr : 0 = 0 then (r', s', t')
else
let q := r' / 0;
let_fun x := (_ : r' % 0 ≺ 0);
xgcdAux (r' % 0) (s' - q * s) (t' - q * t) 0 s t) =
(r', s', t')
[PROOFSTEP]
exact if_pos rfl
[GOAL]
R : Type u
inst✝¹ : EuclideanDomain R
inst✝ : DecidableEq R
r s t r' s' t' : R
h : r ≠ 0
⊢ xgcdAux r s t r' s' t' = xgcdAux (r' % r) (s' - r' / r * s) (t' - r' / r * t) r s t
[PROOFSTEP]
conv =>
lhs
rw [xgcdAux]
[GOAL]
R : Type u
inst✝¹ : EuclideanDomain R
inst✝ : DecidableEq R
r s t r' s' t' : R
h : r ≠ 0
| xgcdAux r s t r' s' t' = xgcdAux (r' % r) (s' - r' / r * s) (t' - r' / r * t) r s t
[PROOFSTEP]
lhs
rw [xgcdAux]
[GOAL]
R : Type u
inst✝¹ : EuclideanDomain R
inst✝ : DecidableEq R
r s t r' s' t' : R
h : r ≠ 0
| xgcdAux r s t r' s' t' = xgcdAux (r' % r) (s' - r' / r * s) (t' - r' / r * t) r s t
[PROOFSTEP]
lhs
rw [xgcdAux]
[GOAL]
R : Type u
inst✝¹ : EuclideanDomain R
inst✝ : DecidableEq R
r s t r' s' t' : R
h : r ≠ 0
| xgcdAux r s t r' s' t' = xgcdAux (r' % r) (s' - r' / r * s) (t' - r' / r * t) r s t
[PROOFSTEP]
lhs
[GOAL]
R : Type u
inst✝¹ : EuclideanDomain R
inst✝ : DecidableEq R
r s t r' s' t' : R
h : r ≠ 0
| xgcdAux r s t r' s' t'
[PROOFSTEP]
rw [xgcdAux]
[GOAL]
R : Type u
inst✝¹ : EuclideanDomain R
inst✝ : DecidableEq R
r s t r' s' t' : R
h : r ≠ 0
⊢ (if _hr : r = 0 then (r', s', t')
else
let q := r' / r;
let_fun x := (_ : r' % r ≺ r);
xgcdAux (r' % r) (s' - q * s) (t' - q * t) r s t) =
xgcdAux (r' % r) (s' - r' / r * s) (t' - r' / r * t) r s t
[PROOFSTEP]
exact if_neg h
[GOAL]
R : Type u
inst✝¹ : EuclideanDomain R
inst✝ : DecidableEq R
s : R
⊢ gcdA 0 s = 0
[PROOFSTEP]
unfold gcdA
[GOAL]
R : Type u
inst✝¹ : EuclideanDomain R
inst✝ : DecidableEq R
s : R
⊢ (xgcd 0 s).fst = 0
[PROOFSTEP]
rw [xgcd, xgcd_zero_left]
[GOAL]
R : Type u
inst✝¹ : EuclideanDomain R
inst✝ : DecidableEq R
s : R
⊢ gcdB 0 s = 1
[PROOFSTEP]
unfold gcdB
[GOAL]
R : Type u
inst✝¹ : EuclideanDomain R
inst✝ : DecidableEq R
s : R
⊢ (xgcd 0 s).snd = 1
[PROOFSTEP]
rw [xgcd, xgcd_zero_left]
|
-- Andreas, 2018-06-09, issue #2513, parsing attributes
postulate
@0 @ω A : Set
-- Should fail with error:
-- Conflicting attributes: 0 ω
|
------------------------------------------------------------------------
-- The Agda standard library
--
-- Basic types related to coinduction
------------------------------------------------------------------------
module Coinduction where
import Level
------------------------------------------------------------------------
-- A type used to make recursive arguments coinductive
infix 1000 ♯_
postulate
∞ : ∀ {a} (A : Set a) → Set a
♯_ : ∀ {a} {A : Set a} → A → ∞ A
♭ : ∀ {a} {A : Set a} → ∞ A → A
{-# BUILTIN INFINITY ∞ #-}
{-# BUILTIN SHARP ♯_ #-}
{-# BUILTIN FLAT ♭ #-}
------------------------------------------------------------------------
-- Rec, a type which is analogous to the Rec type constructor used in
-- ΠΣ (see Altenkirch, Danielsson, Löh and Oury. ΠΣ: Dependent Types
-- without the Sugar. FLOPS 2010, LNCS 6009.)
data Rec {a} (A : ∞ (Set a)) : Set a where
fold : (x : ♭ A) → Rec A
unfold : ∀ {a} {A : ∞ (Set a)} → Rec A → ♭ A
unfold (fold x) = x
{-
-- If --guardedness-preserving-type-constructors is enabled one can
-- define types like ℕ by recursion:
open import Data.Sum
open import Data.Unit
ℕ : Set
ℕ = ⊤ ⊎ Rec (♯ ℕ)
zero : ℕ
zero = inj₁ _
suc : ℕ → ℕ
suc n = inj₂ (fold n)
ℕ-rec : (P : ℕ → Set) →
P zero →
(∀ n → P n → P (suc n)) →
∀ n → P n
ℕ-rec P z s (inj₁ _) = z
ℕ-rec P z s (inj₂ (fold n)) = s n (ℕ-rec P z s n)
-- This feature is very experimental, though: it may lead to
-- inconsistencies.
-}
|
Below is a comparison of the Regional GDP on the island of Ireland .
|
If $C$ is a closed set and almost every point of the real line is in $C$, then $x \in C$. |
# Matrix
## Create a matrix $$\begin{bmatrix} 1 & 2 \\ -2 & 3 \\ 3 & 4 \end{bmatrix}$$
```python
# Create a matrix
from sympy import *
init_printing(use_unicode=True)
Matrix([[1, 2], [-2, 3], [3, 4]])
```
$\displaystyle \left[\begin{matrix}1 & 2\\-2 & 3\\3 & 4\end{matrix}\right]$
## Create some matrix
$$M = \begin{bmatrix} 1 & 2 \\ -2 & 1 \end{bmatrix}$$
$$N = \begin{bmatrix} -1 \\ 1 \end{bmatrix}$$
```python
# Manipulate the matrix
M = Matrix([[1, 2], [-2, 1]])
N = Matrix([-1, 1])
N
```
$\displaystyle \left[\begin{matrix}-1\\1\end{matrix}\right]$
## Manipulate the matrix
$$M \times N$$
```python
M*N
```
$\displaystyle \left[\begin{matrix}1\\3\end{matrix}\right]$
```python
# Basic Operations
# Get the shape of the matrix M
shape(M)
```
```python
# Accessing rows
M.row(0)
```
$\displaystyle \left[\begin{matrix}1 & 2\end{matrix}\right]$
```python
# Accessing columns
M.col(-1)
```
$\displaystyle \left[\begin{matrix}2\\1\end{matrix}\right]$
## Addition of M and N $$\begin{bmatrix} 1 & 2 \\ -2 & 1 \end{bmatrix} + \begin{bmatrix} -1 & 1 \\ 1 & 2 \end{bmatrix} = \begin{bmatrix} 0 & 3 \\ -1 & 3 \end{bmatrix}$$
```python
# Addition of matrices
M = Matrix([[1, 2], [-2, 1]])
N = Matrix([[-1, 1], [1, 2]])
M + N
```
$\displaystyle \left[\begin{matrix}0 & 3\\-1 & 3\end{matrix}\right]$
## Multiplication of M and N $$\begin{bmatrix} 1 & 2 \\ -2 & 1 \end{bmatrix} \times \begin{bmatrix} -1 & 1 \\ 1 & 2 \end{bmatrix} = \begin{bmatrix} 1 & 5 \\ 3 & 0 \end{bmatrix}$$
```python
# Multiplication of matrices
M*N
```
$\displaystyle \left[\begin{matrix}1 & 5\\3 & 0\end{matrix}\right]$
## Power of matrix M $$\begin{bmatrix} 1 & 2 \\ -2 & 1 \end{bmatrix}^2 = \begin{bmatrix} -3 & 4 \\ -4 & -3 \end{bmatrix}$$
```python
# Power of a matrix
M**2
```
$\displaystyle \left[\begin{matrix}-3 & 4\\-4 & -3\end{matrix}\right]$
## Inverse of matrix M $$\begin{bmatrix} 1 & 2 \\ -2 & 1 \end{bmatrix}^{-1} = \begin{bmatrix} \frac{1}{5} & -\frac{2}{5} \\ \frac{2}{5} & \frac{1}{5} \end{bmatrix}$$
```python
# Inverse of a matrix
M**-1
```
$\displaystyle \left[\begin{matrix}\frac{1}{5} & - \frac{2}{5}\\\frac{2}{5} & \frac{1}{5}\end{matrix}\right]$
## Transpose of matrix M $$MT = \begin{bmatrix} 1 & -2 \\ 2 & 1 \end{bmatrix}$$
```python
# Transpose of a matrix
M.T
```
$\displaystyle \left[\begin{matrix}1 & -2\\2 & 1\end{matrix}\right]$
## Create a matrix identity $$\begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 1 \\ 0 & 0 & 1 \end{bmatrix}$$
```python
# Matrix Constructor
# Identity Matrix
eye(3)
```
$\displaystyle \left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & 0 & 1\end{matrix}\right]$
## Create all zeros matrix $$\begin{bmatrix} 0 & 0 \\ 0 & 0 \end{bmatrix}$$
```python
# All zeros matrix
zeros(2, 2)
```
$\displaystyle \left[\begin{matrix}0 & 0\\0 & 0\end{matrix}\right]$
## Create all ones matrix $$\begin{bmatrix} 1 & 1 \\ 1 & 1 \end{bmatrix}$$
```python
# All ones matrix
ones(2, 2)
```
$\displaystyle \left[\begin{matrix}1 & 1\\1 & 1\end{matrix}\right]$
## Create a diagonal matrix $$\begin{bmatrix} 1 & 0 & 0 \\ 0 & 2 & 0 \\ 0 & 0 & 3 \end{bmatrix}$$
```python
# Diagonal Matrix
diag(1, 2, 3)
```
$\displaystyle \left[\begin{matrix}1 & 0 & 0\\0 & 2 & 0\\0 & 0 & 3\end{matrix}\right]$
## Determinant of matrix M $$a \times d - b \times c$$ $$=1 \times 1 - 2 \times (-2) = 5$$
```python
# Determinant of a matrix
M.det()
```
|
InstallMethod( JupyterRender, "default fallback"
, [ IsObject ],
function(obj)
local str;
str := ViewString(obj);
RemoveCharacters(str, "\<\>\n");
return Objectify( JupyterRenderableType
, rec( data := rec( text\/plain := str )
, metadata := rec( text\/plain := "") ) );
end);
InstallMethod( JupyterRender, "default fallback"
, [ IsJupyterRenderableRep ],
IdFunc);
InstallMethod( JupyterRenderableData, "for a JupyterRenderable"
, [ IsJupyterRenderableRep ]
, x -> x!.data );
InstallMethod( JupyterRenderableMetadata, "for a JupyterRenderable"
, [ IsJupyterRenderableRep ]
, x -> x!.metadata );
InstallMethod( ViewString, "for a JupyterRenderable"
, [ IsJupyterRenderableRep ]
, x -> "<jupyter renderable>" );
InstallMethod( JupyterRenderable, "for a record and a record"
, [ IsObject, IsObject ],
function(data, metadata)
return Objectify( JupyterRenderableType
, rec( data := data, metadata := metadata ) );
end);
|
[STATEMENT]
lemma ipv4addr_upto: "set (ipv4addr_upto i j) = {i .. j}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. set (ipv4addr_upto i j) = {i..j}
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. set (ipv4addr_upto i j) = {i..j}
[PROOF STEP]
have int_interval_eq_image: "{int m..int n} = int ` {m..n}" for m n
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. {int m..int n} = int ` {m..n}
[PROOF STEP]
by (auto intro!: image_eqI [of _ int "nat k" for k])
[PROOF STATE]
proof (state)
this:
{int ?m..int ?n} = int ` {?m..?n}
goal (1 subgoal):
1. set (ipv4addr_upto i j) = {i..j}
[PROOF STEP]
have helpX:"\<And>f (i::nat) (j::nat). (f \<circ> nat) ` {int i..int j} = f ` {i .. j}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>f i j. (f \<circ> nat) ` {int i..int j} = f ` {i..j}
[PROOF STEP]
by (auto simp add: image_comp int_interval_eq_image)
[PROOF STATE]
proof (state)
this:
(?f \<circ> nat) ` {int ?i..int ?j} = ?f ` {?i..?j}
goal (1 subgoal):
1. set (ipv4addr_upto i j) = {i..j}
[PROOF STEP]
have hlp: \<open>i \<le> word_of_nat (nat xa)\<close> \<open>word_of_nat (nat xa) \<le> j\<close>
if \<open>uint i \<le> xa\<close> \<open>xa \<le> uint j\<close> for xa :: int
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. i \<le> word_of_nat (nat xa) &&& word_of_nat (nat xa) \<le> j
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. i \<le> word_of_nat (nat xa)
2. word_of_nat (nat xa) \<le> j
[PROOF STEP]
from uint_nonnegative [of i] \<open>uint i \<le> xa\<close>
[PROOF STATE]
proof (chain)
picking this:
0 \<le> uint i
uint i \<le> xa
[PROOF STEP]
have \<open>0 \<le> xa\<close>
[PROOF STATE]
proof (prove)
using this:
0 \<le> uint i
uint i \<le> xa
goal (1 subgoal):
1. 0 \<le> xa
[PROOF STEP]
by (rule order_trans)
[PROOF STATE]
proof (state)
this:
0 \<le> xa
goal (2 subgoals):
1. i \<le> word_of_nat (nat xa)
2. word_of_nat (nat xa) \<le> j
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
0 \<le> xa
goal (2 subgoals):
1. i \<le> word_of_nat (nat xa)
2. word_of_nat (nat xa) \<le> j
[PROOF STEP]
from \<open>xa \<le> uint j\<close> uint_bounded [of j]
[PROOF STATE]
proof (chain)
picking this:
xa \<le> uint j
uint j < 2 ^ LENGTH(32)
[PROOF STEP]
have \<open>xa < 2 ^ 32\<close>
[PROOF STATE]
proof (prove)
using this:
xa \<le> uint j
uint j < 2 ^ LENGTH(32)
goal (1 subgoal):
1. xa < 2 ^ 32
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
xa < 2 ^ 32
goal (2 subgoals):
1. i \<le> word_of_nat (nat xa)
2. word_of_nat (nat xa) \<le> j
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
0 \<le> xa
xa < 2 ^ 32
[PROOF STEP]
have xa: \<open>take_bit 32 xa = xa\<close>
[PROOF STATE]
proof (prove)
using this:
0 \<le> xa
xa < 2 ^ 32
goal (1 subgoal):
1. take_bit 32 xa = xa
[PROOF STEP]
by (simp add: take_bit_int_eq_self)
[PROOF STATE]
proof (state)
this:
take_bit 32 xa = xa
goal (2 subgoals):
1. i \<le> word_of_nat (nat xa)
2. word_of_nat (nat xa) \<le> j
[PROOF STEP]
from xa \<open>uint i \<le> xa\<close>
[PROOF STATE]
proof (chain)
picking this:
take_bit 32 xa = xa
uint i \<le> xa
[PROOF STEP]
show \<open>i \<le> word_of_nat (nat xa)\<close>
[PROOF STATE]
proof (prove)
using this:
take_bit 32 xa = xa
uint i \<le> xa
goal (1 subgoal):
1. i \<le> word_of_nat (nat xa)
[PROOF STEP]
by transfer simp
[PROOF STATE]
proof (state)
this:
i \<le> word_of_nat (nat xa)
goal (1 subgoal):
1. word_of_nat (nat xa) \<le> j
[PROOF STEP]
from xa \<open>xa \<le> uint j\<close>
[PROOF STATE]
proof (chain)
picking this:
take_bit 32 xa = xa
xa \<le> uint j
[PROOF STEP]
show \<open>word_of_nat (nat xa) \<le> j\<close>
[PROOF STATE]
proof (prove)
using this:
take_bit 32 xa = xa
xa \<le> uint j
goal (1 subgoal):
1. word_of_nat (nat xa) \<le> j
[PROOF STEP]
by transfer simp
[PROOF STATE]
proof (state)
this:
word_of_nat (nat xa) \<le> j
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<lbrakk>uint i \<le> ?xa1; ?xa1 \<le> uint j\<rbrakk> \<Longrightarrow> i \<le> word_of_nat (nat ?xa1)
\<lbrakk>uint i \<le> ?xa1; ?xa1 \<le> uint j\<rbrakk> \<Longrightarrow> word_of_nat (nat ?xa1) \<le> j
goal (1 subgoal):
1. set (ipv4addr_upto i j) = {i..j}
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. set (ipv4addr_upto i j) = {i..j}
[PROOF STEP]
unfolding ipv4addr_upto_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. set (map (word_of_nat \<circ> nat) [int (unat i)..int (unat j)]) = {i..j}
[PROOF STEP]
apply (rule set_eqI)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>x. (x \<in> set (map (word_of_nat \<circ> nat) [int (unat i)..int (unat j)])) = (x \<in> {i..j})
[PROOF STEP]
apply (auto simp add: hlp)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>x. \<lbrakk>i \<le> x; x \<le> j\<rbrakk> \<Longrightarrow> x \<in> (\<lambda>x. word_of_nat (nat x)) ` {uint i..uint j}
[PROOF STEP]
apply (metis (mono_tags) atLeastAtMost_iff image_iff unat_eq_nat_uint word_less_eq_iff_unsigned word_unat.Rep_inverse)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
[PROOF STATE]
proof (state)
this:
set (ipv4addr_upto i j) = {i..j}
goal:
No subgoals!
[PROOF STEP]
qed |
Formal statement is: lemma has_complex_derivative_locally_injective: assumes holf: "f holomorphic_on S" and S: "\<xi> \<in> S" "open S" and dnz: "deriv f \<xi> \<noteq> 0" obtains r where "r > 0" "ball \<xi> r \<subseteq> S" "inj_on f (ball \<xi> r)" Informal statement is: If $f$ is a holomorphic function on an open set $S$ and $\xi \in S$, then there exists a neighborhood $U$ of $\xi$ such that $f$ is injective on $U$. |
lemma measurable_SUP[measurable]: fixes F :: "'i \<Rightarrow> 'a \<Rightarrow> 'b::{complete_lattice, countable}" assumes [simp]: "countable I" assumes [measurable]: "\<And>i. i \<in> I \<Longrightarrow> F i \<in> measurable M (count_space UNIV)" shows "(\<lambda>x. SUP i\<in>I. F i x) \<in> measurable M (count_space UNIV)" |
State Before: α : Type u_1
R : α → α → Prop
l₁ l₂ : List α
⊢ Pairwise R (l₁ ++ l₂) ↔ Pairwise R l₁ ∧ Pairwise R l₂ ∧ ∀ (a : α), a ∈ l₁ → ∀ (b : α), b ∈ l₂ → R a b State After: no goals Tactic: induction l₁ <;> simp [*, or_imp, forall_and, and_assoc, and_left_comm] |
(* Title: thys/Turing.thy
Author: Jian Xu, Xingyuan Zhang, and Christian Urban
Modifications: Sebastiaan Joosten
*)
chapter \<open>Turing Machines\<close>
theory Turing
imports Main
begin
section \<open>Basic definitions of Turing machine\<close>
datatype action = W0 | W1 | L | R | Nop
datatype cell = Bk | Oc
type_synonym tape = "cell list \<times> cell list"
type_synonym state = nat
type_synonym instr = "action \<times> state"
type_synonym tprog = "instr list \<times> nat"
type_synonym tprog0 = "instr list"
type_synonym config = "state \<times> tape"
fun nth_of where
"nth_of xs i = (if i \<ge> length xs then None else Some (xs ! i))"
lemma nth_of_map [simp]:
shows "nth_of (map f p) n = (case (nth_of p n) of None \<Rightarrow> None | Some x \<Rightarrow> Some (f x))"
by simp
fun
fetch :: "instr list \<Rightarrow> state \<Rightarrow> cell \<Rightarrow> instr"
where
"fetch p 0 b = (Nop, 0)"
| "fetch p (Suc s) Bk =
(case nth_of p (2 * s) of
Some i \<Rightarrow> i
| None \<Rightarrow> (Nop, 0))"
|"fetch p (Suc s) Oc =
(case nth_of p ((2 * s) + 1) of
Some i \<Rightarrow> i
| None \<Rightarrow> (Nop, 0))"
lemma fetch_Nil [simp]:
shows "fetch [] s b = (Nop, 0)"
by (cases s,force) (cases b;force)
fun
update :: "action \<Rightarrow> tape \<Rightarrow> tape"
where
"update W0 (l, r) = (l, Bk # (tl r))"
| "update W1 (l, r) = (l, Oc # (tl r))"
| "update L (l, r) = (if l = [] then ([], Bk # r) else (tl l, (hd l) # r))"
| "update R (l, r) = (if r = [] then (Bk # l, []) else ((hd r) # l, tl r))"
| "update Nop (l, r) = (l, r)"
abbreviation
"read r == if (r = []) then Bk else hd r"
fun step :: "config \<Rightarrow> tprog \<Rightarrow> config"
where
"step (s, l, r) (p, off) =
(let (a, s') = fetch p (s - off) (read r) in (s', update a (l, r)))"
abbreviation
"step0 c p \<equiv> step c (p, 0)"
fun steps :: "config \<Rightarrow> tprog \<Rightarrow> nat \<Rightarrow> config"
where
"steps c p 0 = c" |
"steps c p (Suc n) = steps (step c p) p n"
abbreviation
"steps0 c p n \<equiv> steps c (p, 0) n"
lemma steps_add [simp]:
shows "steps c p (m + n) = steps (steps c p m) p n"
by (induct m arbitrary: c) (auto)
lemma step_0 [simp]:
shows "step (0, (l, r)) p = (0, (l, r))"
by (cases p, simp)
lemma steps_0 [simp]:
shows "steps (0, (l, r)) p n = (0, (l, r))"
by (induct n) (simp_all)
fun
is_final :: "config \<Rightarrow> bool"
where
"is_final (s, l, r) = (s = 0)"
lemma is_final_eq:
shows "is_final (s, tp) = (s = 0)"
by (cases tp) (auto)
lemma is_finalI [intro]:
shows "is_final (0, tp)"
by (simp add: is_final_eq)
lemma after_is_final:
assumes "is_final c"
shows "is_final (steps c p n)"
using assms
by(induct n;cases c;auto)
lemma is_final:
assumes a: "is_final (steps c p n1)"
and b: "n1 \<le> n2"
shows "is_final (steps c p n2)"
proof -
obtain n3 where eq: "n2 = n1 + n3" using b by (metis le_iff_add)
from a show "is_final (steps c p n2)" unfolding eq
by (simp add: after_is_final)
qed
lemma not_is_final:
assumes a: "\<not> is_final (steps c p n1)"
and b: "n2 \<le> n1"
shows "\<not> is_final (steps c p n2)"
proof (rule notI)
obtain n3 where eq: "n1 = n2 + n3" using b by (metis le_iff_add)
assume "is_final (steps c p n2)"
then have "is_final (steps c p n1)" unfolding eq
by (simp add: after_is_final)
with a show "False" by simp
qed
(* if the machine is in the halting state, there must have
been a state just before the halting state *)
lemma before_final:
assumes "steps0 (1, tp) A n = (0, tp')"
shows "\<exists> n'. \<not> is_final (steps0 (1, tp) A n') \<and> steps0 (1, tp) A (Suc n') = (0, tp')"
using assms
proof(induct n arbitrary: tp')
case (0 tp')
have asm: "steps0 (1, tp) A 0 = (0, tp')" by fact
then show "\<exists>n'. \<not> is_final (steps0 (1, tp) A n') \<and> steps0 (1, tp) A (Suc n') = (0, tp')"
by simp
next
case (Suc n tp')
have ih: "\<And>tp'. steps0 (1, tp) A n = (0, tp') \<Longrightarrow>
\<exists>n'. \<not> is_final (steps0 (1, tp) A n') \<and> steps0 (1, tp) A (Suc n') = (0, tp')" by fact
have asm: "steps0 (1, tp) A (Suc n) = (0, tp')" by fact
obtain s l r where cases: "steps0 (1, tp) A n = (s, l, r)"
by (auto intro: is_final.cases)
then show "\<exists>n'. \<not> is_final (steps0 (1, tp) A n') \<and> steps0 (1, tp) A (Suc n') = (0, tp')"
proof (cases "s = 0")
case True (* in halting state *)
then have "steps0 (1, tp) A n = (0, tp')"
using asm cases by (simp del: steps.simps)
then show ?thesis using ih by simp
next
case False (* not in halting state *)
then have "\<not> is_final (steps0 (1, tp) A n) \<and> steps0 (1, tp) A (Suc n) = (0, tp')"
using asm cases by simp
then show ?thesis by auto
qed
qed
lemma least_steps:
assumes "steps0 (1, tp) A n = (0, tp')"
shows "\<exists> n'. (\<forall>n'' < n'. \<not> is_final (steps0 (1, tp) A n'')) \<and>
(\<forall>n'' \<ge> n'. is_final (steps0 (1, tp) A n''))"
proof -
from before_final[OF assms]
obtain n' where
before: "\<not> is_final (steps0 (1, tp) A n')" and
final: "steps0 (1, tp) A (Suc n') = (0, tp')" by auto
from before
have "\<forall>n'' < Suc n'. \<not> is_final (steps0 (1, tp) A n'')"
using not_is_final by auto
moreover
from final
have "\<forall>n'' \<ge> Suc n'. is_final (steps0 (1, tp) A n'')"
using is_final[of _ _ "Suc n'"] by (auto simp add: is_final_eq)
ultimately
show "\<exists> n'. (\<forall>n'' < n'. \<not> is_final (steps0 (1, tp) A n'')) \<and> (\<forall>n'' \<ge> n'. is_final (steps0 (1, tp) A n''))"
by blast
qed
(* well-formedness of Turing machine programs *)
abbreviation "is_even n \<equiv> (n::nat) mod 2 = 0"
fun
tm_wf :: "tprog \<Rightarrow> bool"
where
"tm_wf (p, off) = (length p \<ge> 2 \<and> is_even (length p) \<and>
(\<forall>(a, s) \<in> set p. s \<le> length p div 2 + off \<and> s \<ge> off))"
abbreviation
"tm_wf0 p \<equiv> tm_wf (p, 0)"
abbreviation exponent :: "'a \<Rightarrow> nat \<Rightarrow> 'a list" ("_ \<up> _" [100, 99] 100)
where "x \<up> n == replicate n x"
lemma hd_repeat_cases:
"P (hd (a \<up> m @ r)) \<longleftrightarrow> (m = 0 \<longrightarrow> P (hd r)) \<and> (\<forall>nat. m = Suc nat \<longrightarrow> P a)"
by (cases m,auto)
class tape =
fixes tape_of :: "'a \<Rightarrow> cell list" ("<_>" 100)
instantiation nat::tape begin
definition tape_of_nat where "tape_of_nat (n::nat) \<equiv> Oc \<up> (Suc n)"
instance by standard
end
type_synonym nat_list = "nat list"
instantiation list::(tape) tape begin
fun tape_of_nat_list :: "('a::tape) list \<Rightarrow> cell list"
where
"tape_of_nat_list [] = []" |
"tape_of_nat_list [n] = <n>" |
"tape_of_nat_list (n#ns) = <n> @ Bk # (tape_of_nat_list ns)"
definition tape_of_list where "tape_of_list \<equiv> tape_of_nat_list"
instance by standard
end
instantiation prod:: (tape, tape) tape begin
fun tape_of_nat_prod :: "('a::tape) \<times> ('b::tape) \<Rightarrow> cell list"
where "tape_of_nat_prod (n, m) = <n> @ [Bk] @ <m>"
definition tape_of_prod where "tape_of_prod \<equiv> tape_of_nat_prod"
instance by standard
end
fun
shift :: "instr list \<Rightarrow> nat \<Rightarrow> instr list"
where
"shift p n = (map (\<lambda> (a, s). (a, (if s = 0 then 0 else s + n))) p)"
fun
adjust :: "instr list \<Rightarrow> nat \<Rightarrow> instr list"
where
"adjust p e = map (\<lambda> (a, s). (a, if s = 0 then e else s)) p"
abbreviation
"adjust0 p \<equiv> adjust p (Suc (length p div 2))"
lemma length_shift [simp]:
shows "length (shift p n) = length p"
by simp
lemma length_adjust [simp]:
shows "length (adjust p n) = length p"
by (induct p) (auto)
(* composition of two Turing machines *)
fun
tm_comp :: "instr list \<Rightarrow> instr list \<Rightarrow> instr list" ("_ |+| _" [0, 0] 100)
where
"tm_comp p1 p2 = ((adjust0 p1) @ (shift p2 (length p1 div 2)))"
lemma tm_comp_length:
shows "length (A |+| B) = length A + length B"
by auto
lemma tm_comp_wf[intro]:
"\<lbrakk>tm_wf (A, 0); tm_wf (B, 0)\<rbrakk> \<Longrightarrow> tm_wf (A |+| B, 0)"
by (fastforce)
lemma tm_comp_step:
assumes unfinal: "\<not> is_final (step0 c A)"
shows "step0 c (A |+| B) = step0 c A"
proof -
obtain s l r where eq: "c = (s, l, r)" by (metis is_final.cases)
have "\<not> is_final (step0 (s, l, r) A)" using unfinal eq by simp
then have "case (fetch A s (read r)) of (a, s) \<Rightarrow> s \<noteq> 0"
by (auto simp add: is_final_eq)
then have "fetch (A |+| B) s (read r) = fetch A s (read r)"
apply (cases "read r";cases s)
by (auto simp: tm_comp_length nth_append)
then show "step0 c (A |+| B) = step0 c A" by (simp add: eq)
qed
lemma tm_comp_steps:
assumes "\<not> is_final (steps0 c A n)"
shows "steps0 c (A |+| B) n = steps0 c A n"
using assms
proof(induct n)
case 0
then show "steps0 c (A |+| B) 0 = steps0 c A 0" by auto
next
case (Suc n)
have ih: "\<not> is_final (steps0 c A n) \<Longrightarrow> steps0 c (A |+| B) n = steps0 c A n" by fact
have fin: "\<not> is_final (steps0 c A (Suc n))" by fact
then have fin1: "\<not> is_final (step0 (steps0 c A n) A)"
by (auto simp only: step_red)
then have fin2: "\<not> is_final (steps0 c A n)"
by (metis is_final_eq step_0 surj_pair)
have "steps0 c (A |+| B) (Suc n) = step0 (steps0 c (A |+| B) n) (A |+| B)"
by (simp only: step_red)
also have "... = step0 (steps0 c A n) (A |+| B)" by (simp only: ih[OF fin2])
also have "... = step0 (steps0 c A n) A" by (simp only: tm_comp_step[OF fin1])
finally show "steps0 c (A |+| B) (Suc n) = steps0 c A (Suc n)"
by (simp only: step_red)
qed
lemma tm_comp_fetch_in_A:
assumes h1: "fetch A s x = (a, 0)"
and h2: "s \<le> length A div 2"
and h3: "s \<noteq> 0"
shows "fetch (A |+| B) s x = (a, Suc (length A div 2))"
using h1 h2 h3
apply(cases s;cases x)
by(auto simp: tm_comp_length nth_append)
lemma tm_comp_exec_after_first:
assumes h1: "\<not> is_final c"
and h2: "step0 c A = (0, tp)"
and h3: "fst c \<le> length A div 2"
shows "step0 c (A |+| B) = (Suc (length A div 2), tp)"
using h1 h2 h3
apply(case_tac c)
apply(auto simp del: tm_comp.simps)
apply(case_tac "fetch A a Bk")
apply(simp del: tm_comp.simps)
apply(subst tm_comp_fetch_in_A;force)
apply(case_tac "fetch A a (hd ca)")
apply(simp del: tm_comp.simps)
apply(subst tm_comp_fetch_in_A)
apply(auto)[4]
done
lemma step_in_range:
assumes h1: "\<not> is_final (step0 c A)"
and h2: "tm_wf (A, 0)"
shows "fst (step0 c A) \<le> length A div 2"
using h1 h2
apply(cases c;cases "fst c";cases "hd (snd (snd c))")
by(auto simp add: Let_def case_prod_beta')
lemma steps_in_range:
assumes h1: "\<not> is_final (steps0 (1, tp) A stp)"
and h2: "tm_wf (A, 0)"
shows "fst (steps0 (1, tp) A stp) \<le> length A div 2"
using h1
proof(induct stp)
case 0
then show "fst (steps0 (1, tp) A 0) \<le> length A div 2" using h2
by (auto)
next
case (Suc stp)
have ih: "\<not> is_final (steps0 (1, tp) A stp) \<Longrightarrow> fst (steps0 (1, tp) A stp) \<le> length A div 2" by fact
have h: "\<not> is_final (steps0 (1, tp) A (Suc stp))" by fact
from ih h h2 show "fst (steps0 (1, tp) A (Suc stp)) \<le> length A div 2"
by (metis step_in_range step_red)
qed
(* if A goes into the final state, then A |+| B will go into the first state of B *)
lemma tm_comp_next:
assumes a_ht: "steps0 (1, tp) A n = (0, tp')"
and a_wf: "tm_wf (A, 0)"
obtains n' where "steps0 (1, tp) (A |+| B) n' = (Suc (length A div 2), tp')"
proof -
assume a: "\<And>n. steps (1, tp) (A |+| B, 0) n = (Suc (length A div 2), tp') \<Longrightarrow> thesis"
obtain stp' where fin: "\<not> is_final (steps0 (1, tp) A stp')" and h: "steps0 (1, tp) A (Suc stp') = (0, tp')"
using before_final[OF a_ht] by blast
from fin have h1:"steps0 (1, tp) (A |+| B) stp' = steps0 (1, tp) A stp'"
by (rule tm_comp_steps)
from h have h2: "step0 (steps0 (1, tp) A stp') A = (0, tp')"
by (simp only: step_red)
have "steps0 (1, tp) (A |+| B) (Suc stp') = step0 (steps0 (1, tp) (A |+| B) stp') (A |+| B)"
by (simp only: step_red)
also have "... = step0 (steps0 (1, tp) A stp') (A |+| B)" using h1 by simp
also have "... = (Suc (length A div 2), tp')"
by (rule tm_comp_exec_after_first[OF fin h2 steps_in_range[OF fin a_wf]])
finally show thesis using a by blast
qed
lemma tm_comp_fetch_second_zero:
assumes h1: "fetch B s x = (a, 0)"
and hs: "tm_wf (A, 0)" "s \<noteq> 0"
shows "fetch (A |+| B) (s + (length A div 2)) x = (a, 0)"
using h1 hs
by(cases x; cases s; fastforce simp: tm_comp_length nth_append)
lemma tm_comp_fetch_second_inst:
assumes h1: "fetch B sa x = (a, s)"
and hs: "tm_wf (A, 0)" "sa \<noteq> 0" "s \<noteq> 0"
shows "fetch (A |+| B) (sa + length A div 2) x = (a, s + length A div 2)"
using h1 hs
by(cases x; cases sa; fastforce simp: tm_comp_length nth_append)
lemma tm_comp_second:
assumes a_wf: "tm_wf (A, 0)"
and steps: "steps0 (1, l, r) B stp = (s', l', r')"
shows "steps0 (Suc (length A div 2), l, r) (A |+| B) stp
= (if s' = 0 then 0 else s' + length A div 2, l', r')"
using steps
proof(induct stp arbitrary: s' l' r')
case 0
then show ?case by simp
next
case (Suc stp s' l' r')
obtain s'' l'' r'' where a: "steps0 (1, l, r) B stp = (s'', l'', r'')"
by (metis is_final.cases)
then have ih1: "s'' = 0 \<Longrightarrow> steps0 (Suc (length A div 2), l, r) (A |+| B) stp = (0, l'', r'')"
and ih2: "s'' \<noteq> 0 \<Longrightarrow> steps0 (Suc (length A div 2), l, r) (A |+| B) stp = (s'' + length A div 2, l'', r'')"
using Suc by (auto)
have h: "steps0 (1, l, r) B (Suc stp) = (s', l', r')" by fact
{ assume "s'' = 0"
then have ?case using a h ih1 by (simp del: steps.simps)
} moreover
{ assume as: "s'' \<noteq> 0" "s' = 0"
from as a h
have "step0 (s'', l'', r'') B = (0, l', r')" by (simp del: steps.simps)
with as have ?case
apply(cases "fetch B s'' (read r'')")
by (auto simp add: tm_comp_fetch_second_zero[OF _ a_wf] ih2[OF as(1)]
simp del: tm_comp.simps steps.simps)
} moreover
{ assume as: "s'' \<noteq> 0" "s' \<noteq> 0"
from as a h
have "step0 (s'', l'', r'') B = (s', l', r')" by (simp del: steps.simps)
with as have ?case
apply(simp add: ih2[OF as(1)] del: tm_comp.simps steps.simps)
apply(case_tac "fetch B s'' (read r'')")
apply(auto simp add: tm_comp_fetch_second_inst[OF _ a_wf as] simp del: tm_comp.simps)
done
}
ultimately show ?case by blast
qed
lemma tm_comp_final:
assumes "tm_wf (A, 0)"
and "steps0 (1, l, r) B stp = (0, l', r')"
shows "steps0 (Suc (length A div 2), l, r) (A |+| B) stp = (0, l', r')"
using tm_comp_second[OF assms] by (simp)
end
|
[STATEMENT]
lemma \<PP>_covers_\<P>: "\<P> k u \<subseteq> \<PP>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<P> k u \<subseteq> \<PP>
[PROOF STEP]
by (rule subset_trans[OF subset_\<P>\<Q>k \<PP>_covers_\<Q>]) |
{- Byzantine Fault Tolerant Consensus Verification in Agda, version 0.9.
Copyright (c) 2020, 2021, Oracle and/or its affiliates.
Licensed under the Universal Permissive License v 1.0 as shown at https://opensource.oracle.com/licenses/upl
-}
open import LibraBFT.Prelude
open import LibraBFT.Impl.Consensus.Types
-- This module defines the LBFT monad used by our (fake/simple,
-- for now) "implementation", along with some utility functions
-- to facilitate reasoning about it.
module LibraBFT.Impl.Util.Util where
open import LibraBFT.Impl.Util.RWST public
----------------
-- LBFT Monad --
----------------
-- Global 'LBFT'; works over the whole state.
LBFT : Set → Set
LBFT = RWST Unit Output EventProcessor
LBFT-run : ∀ {A} → LBFT A → EventProcessor → (A × EventProcessor × List Output)
LBFT-run m = RWST-run m unit
LBFT-post : ∀ {A} → LBFT A → EventProcessor → EventProcessor
LBFT-post m ep = proj₁ (proj₂ (LBFT-run m ep))
LBFT-outs : ∀ {A} → LBFT A → EventProcessor → List Output
LBFT-outs m ep = proj₂ (proj₂ (LBFT-run m ep))
-- Local 'LBFT' monad; which operates only over the part of
-- the state that /depends/ on the ec; not the part
-- of the state that /defines/ the ec.
--
-- This is very convenient to define functions that
-- do not alter the ec.
LBFT-ec : EpochConfig → Set → Set
LBFT-ec ec = RWST Unit Output (EventProcessorWithEC ec)
-- Lifting a function that does not alter the pieces that
-- define the epoch config is easy
liftEC : {A : Set}(f : ∀ ec → LBFT-ec ec A) → LBFT A
liftEC f = rwst λ _ st
→ let ec = α-EC (₋epEC st , ₋epEC-correct st)
res , stec' , acts = RWST-run (f ec) unit (₋epWithEC st)
in res , record st { ₋epWithEC = stec' } , acts
-- Type that captures a proof that a computation in the LBFT monad
-- satisfies a given contract.
LBFT-Contract : ∀{A} → LBFT A
→ (EventProcessor → Set)
→ (EventProcessor → Set)
→ Set
LBFT-Contract f Pre Post =
∀ ep → Pre ep × Post (proj₁ (proj₂ (RWST-run f unit ep)))
|
c
subroutine open_sdf_sl(IYEAR,IDAY,IUNIT,FILE_EXTENT_PREFIX,IFLAG)
C
C Routine to open a STEP Data File (SDF) that resides on any
C SDF volume in the VMS search list "sdfdir".
C
C This subroutine reads through this listing, finds the requested
C SDF (if it exists) and volume name, and opens the SDF using the
C unit number IUNIT.
C
C J. Mazur 6/1/93
C Modified for STEP
C E. Salter 2/1/95
C Modified to use VMS search list
C J. Dwyer 9/29/95
c J. Dwyer replaced write with print 11/21/95
C
C Input:
C IYEAR year of the SDF to open (e.g., 1992)
C IDAY day number of SDF to open
C IUNIT unit number for SDF
C IFLAG t/f flag that tells if this SDF exists
C FILE_EXTENT_PREFIX for input file (u for hex_to_unf generated files)
C
C Revisions
C
C 6/8/93 Close ldf_locations.dat before each return.
C 6/24/93 Add 'readonly' to open statement.
C 9/29/95 No longer use sdf_locations.dat to find file
C Use VMS search list.
c 5/5/08 install on Mac for Absoft compiler /gm
C
C________________________________________________________________________
c Local variables
CHARACTER*120 VOLUME_NAME ! full sdf volume name
CHARACTER*4 YEAR ! character form of iyear
CHARACTER*3 DAY ! character form of iday
CHARACTER*3 FILE_EXTENT_PREFIX
LOGICAL IFLAG ! flag for sucessful file open
LOGICAL ifile ! test for SDF inquire
include 'include_paths.inc'
C SEARCH SETUP
C ************
C Write the requested day and year into character strings; check the day
C number to insure it has three characters (e.g., '003' instead of ' 3')
do 200 i_version=9,1,-1
write(volume_name, 100) adjustl(trim(data_path)), iyear, iday, file_extent_prefix,i_version
100 format(a,'sdf',i4.4,'_',i3.3,'.'a3,';',i1)
c type *, ' attempting to open: ', adjustl(trim(VOLUME_NAME))
OPEN(UNIT=IUNIT, file=adjustl(trim(VOLUME_NAME)),
* status='old',action='read',err=200)
type *, 'OPEN_SDF: file ', adjustl(trim(VOLUME_NAME))
IFLAG=.TRUE.
RETURN
200 continue
C We get to here if weve read through the entire SDF listing
C and never found a file that matched the year and day of the
C one we requested.
1000 type *,'SDF_OPEN: SDF for ',
1 IYEAR,' day ',IDAY,' is not in the '
type *,' folder ', data_path, '. No file opened.'
IFLAG=.FALSE.
c write out the last day processed:
rewind(88)
write(88,350) iyear, iday-1
350 format(2i5, ' sdf_rom_spikes last day processed')
write(88,*) ! extra line at end
close(88)
RETURN
END ! end open_sdf_sl
c
|
MODULE charg_I
INTERFACE
!...Generated by Pacific-Sierra Research 77to90 4.4G 12:41:19 03/10/06
REAL(KIND(0.0D0)) FUNCTION charg (R, L1, L2, M, DA, DB, ADD)
USE vast_kind_param,ONLY: DOUBLE
real(DOUBLE), INTENT(IN) :: R
integer, INTENT(IN) :: L1
integer, INTENT(IN) :: L2
integer, INTENT(IN) :: M
real(DOUBLE), INTENT(IN) :: DA
real(DOUBLE), INTENT(IN) :: DB
real(DOUBLE), INTENT(IN) :: ADD
END FUNCTION
END INTERFACE
END MODULE
|
import analysis.inner_product_space.basic
import analysis.inner_product_space.pi_L2
import analysis.normed_space.pi_Lp
variables {F M m : Type*}
[is_R_or_C F]
[fintype m]
[decidable_eq m]
def std_basis (F m : Type*) [is_R_or_C F] [fintype m] [decidable_eq m]: m → (euclidean_space F m) := λ (i : m), (λ (j : m), ite (i = j) 1 0)
lemma std_basis_on : orthonormal F (std_basis F m) :=
begin
rw std_basis,
rw orthonormal,
split,
{
intro i,
rw euclidean_space.norm_eq,
simp,
have : (λ (i_1 : m), ∥ ite (i = i_1) (1:F) (0 : F) ∥^2) = λ (i_1 : m), ite (i = i_1) 1 0 :=
begin
ext,
split_ifs,
simp,
simp,
end,
rw this,
rw finset.sum_ite,
simp,
have : (finset.filter (eq i) finset.univ).card = 1 :=
begin
rw finset.card_eq_one,
use i,
ext,
split,
intro h,
have : a = i :=
begin
simp at h,
rw h,
end,
rw this,
simp,
intro h,
simp at h,
simp,
rw h,
end,
rw this,
simp,
},
{
intros i_1 i_2 hij,
unfold inner,
simp,
exact hij,
}
end
|
One of the first tasks for the new army was to suppress the smuggling of slaves from Pangani on the mainland to the island of Pemba , north of Zanzibar . The troops completed this mission , capturing several slavers and hindering the trade . Mathews retired from the Royal Navy in June 1881 and was appointed Brigadier @-@ General of Zanzibar . In 1880 , the Sultan dispatched a military force under Mathews to bring his unruly African mainland territories under control . Mathews ' expedition was initially intended to reach <unk> but his men refused to march inland and , when made to do so , deserted in large numbers . The expedition ended instead at <unk> where a 60 @-@ man garrison was established . This had been reduced to a mere handful of men by the mid @-@ 1880s but the expedition proved that the Sultan was serious about maintaining control of all of his possessions . Mathews ' men were also involved in several expeditions to halt the land @-@ based slave trade which had developed once the seas became too heavily policed for the traders .
|
(* Title: HOL/Metis_Examples/Sets.thy
Author: Lawrence C. Paulson, Cambridge University Computer Laboratory
Author: Jasmin Blanchette, TU Muenchen
Metis example featuring typed set theory.
*)
section \<open>Metis Example Featuring Typed Set Theory\<close>
theory Sets
imports MainRLT
begin
declare [[metis_new_skolem]]
lemma "\<exists>x X. \<forall>y. \<exists>z Z. (~P(y,y) | P(x,x) | ~S(z,x)) &
(S(x,y) | ~S(y,z) | Q(Z,Z)) &
(Q(X,y) | ~Q(y,Z) | S(X,X))"
by metis
lemma "P(n::nat) ==> \<not>P(0) ==> n \<noteq> 0"
by metis
sledgehammer_params [isar_proofs, compress = 1]
(*multiple versions of this example*)
lemma (*equal_union: *)
"(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))"
proof -
have F1: "\<forall>(x\<^sub>2::'b set) x\<^sub>1::'b set. x\<^sub>1 \<subseteq> x\<^sub>1 \<union> x\<^sub>2" by (metis Un_commute Un_upper2)
have F2a: "\<forall>(x\<^sub>2::'b set) x\<^sub>1::'b set. x\<^sub>1 \<subseteq> x\<^sub>2 \<longrightarrow> x\<^sub>2 = x\<^sub>2 \<union> x\<^sub>1" by (metis Un_commute subset_Un_eq)
have F2: "\<forall>(x\<^sub>2::'b set) x\<^sub>1::'b set. x\<^sub>1 \<subseteq> x\<^sub>2 \<and> x\<^sub>2 \<subseteq> x\<^sub>1 \<longrightarrow> x\<^sub>1 = x\<^sub>2" by (metis F2a subset_Un_eq)
{ assume "\<not> Z \<subseteq> X"
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis Un_upper2) }
moreover
{ assume AA1: "Y \<union> Z \<noteq> X"
{ assume "\<not> Y \<subseteq> X"
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis F1) }
moreover
{ assume AAA1: "Y \<subseteq> X \<and> Y \<union> Z \<noteq> X"
{ assume "\<not> Z \<subseteq> X"
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis Un_upper2) }
moreover
{ assume "(Z \<subseteq> X \<and> Y \<subseteq> X) \<and> Y \<union> Z \<noteq> X"
hence "Y \<union> Z \<subseteq> X \<and> X \<noteq> Y \<union> Z" by (metis Un_subset_iff)
hence "Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> Y \<union> Z" by (metis F2)
hence "\<exists>x\<^sub>1::'a set. Y \<subseteq> x\<^sub>1 \<union> Z \<and> Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> x\<^sub>1 \<union> Z" by (metis F1)
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis Un_upper2) }
ultimately have "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis AAA1) }
ultimately have "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis AA1) }
moreover
{ assume "\<exists>x\<^sub>1::'a set. (Z \<subseteq> x\<^sub>1 \<and> Y \<subseteq> x\<^sub>1) \<and> \<not> X \<subseteq> x\<^sub>1"
{ assume "\<not> Y \<subseteq> X"
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis F1) }
moreover
{ assume AAA1: "Y \<subseteq> X \<and> Y \<union> Z \<noteq> X"
{ assume "\<not> Z \<subseteq> X"
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis Un_upper2) }
moreover
{ assume "(Z \<subseteq> X \<and> Y \<subseteq> X) \<and> Y \<union> Z \<noteq> X"
hence "Y \<union> Z \<subseteq> X \<and> X \<noteq> Y \<union> Z" by (metis Un_subset_iff)
hence "Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> Y \<union> Z" by (metis F2)
hence "\<exists>x\<^sub>1::'a set. Y \<subseteq> x\<^sub>1 \<union> Z \<and> Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> x\<^sub>1 \<union> Z" by (metis F1)
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis Un_upper2) }
ultimately have "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis AAA1) }
ultimately have "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by blast }
moreover
{ assume "\<not> Y \<subseteq> X"
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis F1) }
ultimately show "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by metis
qed
sledgehammer_params [isar_proofs, compress = 2]
lemma (*equal_union: *)
"(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))"
proof -
have F1: "\<forall>(x\<^sub>2::'b set) x\<^sub>1::'b set. x\<^sub>1 \<subseteq> x\<^sub>2 \<and> x\<^sub>2 \<subseteq> x\<^sub>1 \<longrightarrow> x\<^sub>1 = x\<^sub>2" by (metis Un_commute subset_Un_eq)
{ assume AA1: "\<exists>x\<^sub>1::'a set. (Z \<subseteq> x\<^sub>1 \<and> Y \<subseteq> x\<^sub>1) \<and> \<not> X \<subseteq> x\<^sub>1"
{ assume AAA1: "Y \<subseteq> X \<and> Y \<union> Z \<noteq> X"
{ assume "\<not> Z \<subseteq> X"
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis Un_upper2) }
moreover
{ assume "Y \<union> Z \<subseteq> X \<and> X \<noteq> Y \<union> Z"
hence "\<exists>x\<^sub>1::'a set. Y \<subseteq> x\<^sub>1 \<union> Z \<and> Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> x\<^sub>1 \<union> Z" by (metis F1 Un_commute Un_upper2)
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis Un_upper2) }
ultimately have "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis AAA1 Un_subset_iff) }
moreover
{ assume "\<not> Y \<subseteq> X"
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis Un_commute Un_upper2) }
ultimately have "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis AA1 Un_subset_iff) }
moreover
{ assume "\<not> Z \<subseteq> X"
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis Un_upper2) }
moreover
{ assume "\<not> Y \<subseteq> X"
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis Un_commute Un_upper2) }
moreover
{ assume AA1: "Y \<subseteq> X \<and> Y \<union> Z \<noteq> X"
{ assume "\<not> Z \<subseteq> X"
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis Un_upper2) }
moreover
{ assume "Y \<union> Z \<subseteq> X \<and> X \<noteq> Y \<union> Z"
hence "\<exists>x\<^sub>1::'a set. Y \<subseteq> x\<^sub>1 \<union> Z \<and> Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> x\<^sub>1 \<union> Z" by (metis F1 Un_commute Un_upper2)
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis Un_upper2) }
ultimately have "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis AA1 Un_subset_iff) }
ultimately show "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by metis
qed
sledgehammer_params [isar_proofs, compress = 3]
lemma (*equal_union: *)
"(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))"
proof -
have F1a: "\<forall>(x\<^sub>2::'b set) x\<^sub>1::'b set. x\<^sub>1 \<subseteq> x\<^sub>2 \<longrightarrow> x\<^sub>2 = x\<^sub>2 \<union> x\<^sub>1" by (metis Un_commute subset_Un_eq)
have F1: "\<forall>(x\<^sub>2::'b set) x\<^sub>1::'b set. x\<^sub>1 \<subseteq> x\<^sub>2 \<and> x\<^sub>2 \<subseteq> x\<^sub>1 \<longrightarrow> x\<^sub>1 = x\<^sub>2" by (metis F1a subset_Un_eq)
{ assume "(Z \<subseteq> X \<and> Y \<subseteq> X) \<and> Y \<union> Z \<noteq> X"
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis F1 Un_commute Un_subset_iff Un_upper2) }
moreover
{ assume AA1: "\<exists>x\<^sub>1::'a set. (Z \<subseteq> x\<^sub>1 \<and> Y \<subseteq> x\<^sub>1) \<and> \<not> X \<subseteq> x\<^sub>1"
{ assume "(Z \<subseteq> X \<and> Y \<subseteq> X) \<and> Y \<union> Z \<noteq> X"
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis F1 Un_commute Un_subset_iff Un_upper2) }
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis AA1 Un_commute Un_subset_iff Un_upper2) }
ultimately show "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis Un_commute Un_upper2)
qed
sledgehammer_params [isar_proofs, compress = 4]
lemma (*equal_union: *)
"(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))"
proof -
have F1: "\<forall>(x\<^sub>2::'b set) x\<^sub>1::'b set. x\<^sub>1 \<subseteq> x\<^sub>2 \<and> x\<^sub>2 \<subseteq> x\<^sub>1 \<longrightarrow> x\<^sub>1 = x\<^sub>2" by (metis Un_commute subset_Un_eq)
{ assume "\<not> Y \<subseteq> X"
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis Un_commute Un_upper2) }
moreover
{ assume AA1: "Y \<subseteq> X \<and> Y \<union> Z \<noteq> X"
{ assume "\<exists>x\<^sub>1::'a set. Y \<subseteq> x\<^sub>1 \<union> Z \<and> Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> x\<^sub>1 \<union> Z"
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis Un_upper2) }
hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis AA1 F1 Un_commute Un_subset_iff Un_upper2) }
ultimately show "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" by (metis Un_subset_iff Un_upper2)
qed
sledgehammer_params [isar_proofs, compress = 1]
lemma (*equal_union: *)
"(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))"
by (metis Un_least Un_upper1 Un_upper2 set_eq_subset)
lemma "(X = Y \<inter> Z) = (X \<subseteq> Y \<and> X \<subseteq> Z \<and> (\<forall>V. V \<subseteq> Y \<and> V \<subseteq> Z \<longrightarrow> V \<subseteq> X))"
by (metis Int_greatest Int_lower1 Int_lower2 subset_antisym)
lemma fixedpoint: "\<exists>!x. f (g x) = x \<Longrightarrow> \<exists>!y. g (f y) = y"
by metis
lemma (* fixedpoint: *) "\<exists>!x. f (g x) = x \<Longrightarrow> \<exists>!y. g (f y) = y"
proof -
assume "\<exists>!x::'a. f (g x) = x"
thus "\<exists>!y::'b. g (f y) = y" by metis
qed
lemma (* singleton_example_2: *)
"\<forall>x \<in> S. \<Union>S \<subseteq> x \<Longrightarrow> \<exists>z. S \<subseteq> {z}"
by (metis Set.subsetI Union_upper insertCI set_eq_subset)
lemma (* singleton_example_2: *)
"\<forall>x \<in> S. \<Union>S \<subseteq> x \<Longrightarrow> \<exists>z. S \<subseteq> {z}"
by (metis Set.subsetI Union_upper insert_iff set_eq_subset)
lemma singleton_example_2:
"\<forall>x \<in> S. \<Union>S \<subseteq> x \<Longrightarrow> \<exists>z. S \<subseteq> {z}"
proof -
assume "\<forall>x \<in> S. \<Union>S \<subseteq> x"
hence "\<forall>x\<^sub>1. x\<^sub>1 \<subseteq> \<Union>S \<and> x\<^sub>1 \<in> S \<longrightarrow> x\<^sub>1 = \<Union>S" by (metis set_eq_subset)
hence "\<forall>x\<^sub>1. x\<^sub>1 \<in> S \<longrightarrow> x\<^sub>1 = \<Union>S" by (metis Union_upper)
hence "\<forall>x\<^sub>1::('a set) set. \<Union>S \<in> x\<^sub>1 \<longrightarrow> S \<subseteq> x\<^sub>1" by (metis subsetI)
hence "\<forall>x\<^sub>1::('a set) set. S \<subseteq> insert (\<Union>S) x\<^sub>1" by (metis insert_iff)
thus "\<exists>z. S \<subseteq> {z}" by metis
qed
text \<open>
From W. W. Bledsoe and Guohui Feng, SET-VAR. JAR 11 (3), 1993, pages
293-314.
\<close>
(* Notes: (1) The numbering doesn't completely agree with the paper.
(2) We must rename set variables to avoid type clashes. *)
lemma "\<exists>B. (\<forall>x \<in> B. x \<le> (0::int))"
"D \<in> F \<Longrightarrow> \<exists>G. \<forall>A \<in> G. \<exists>B \<in> F. A \<subseteq> B"
"P a \<Longrightarrow> \<exists>A. (\<forall>x \<in> A. P x) \<and> (\<exists>y. y \<in> A)"
"a < b \<and> b < (c::int) \<Longrightarrow> \<exists>B. a \<notin> B \<and> b \<in> B \<and> c \<notin> B"
"P (f b) \<Longrightarrow> \<exists>s A. (\<forall>x \<in> A. P x) \<and> f s \<in> A"
"P (f b) \<Longrightarrow> \<exists>s A. (\<forall>x \<in> A. P x) \<and> f s \<in> A"
"\<exists>A. a \<notin> A"
"(\<forall>C. (0, 0) \<in> C \<and> (\<forall>x y. (x, y) \<in> C \<longrightarrow> (Suc x, Suc y) \<in> C) \<longrightarrow> (n, m) \<in> C) \<and> Q n \<longrightarrow> Q m"
apply (metis all_not_in_conv)
apply (metis all_not_in_conv)
apply (metis mem_Collect_eq)
apply (metis less_le singleton_iff)
apply (metis mem_Collect_eq)
apply (metis mem_Collect_eq)
apply (metis all_not_in_conv)
by (metis pair_in_Id_conv)
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.