Datasets:
AI4M
/

text
stringlengths
0
3.34M
{-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# LANGUAGE ViewPatterns #-} import Numeric.Sundials.ARKode.ODE import Numeric.LinearAlgebra import Graphics.Plot vanderpol mu = do let xdot nu _t [x,v] = [v, -x + nu * v * (1-x*x)] xdot _ _ _ = error "vanderpol RHS not defined" ts = linspace 1000 (0,50) sol = toColumns $ odeSolve (xdot mu) [1,0] ts mplot (ts : sol) mplot sol harmonic w d = do let xdot u dd _t [x,v] = [v, a*x + b*v] where a = -u*u; b = -2*dd*u xdot _ _ _ _ = error "harmonic RHS not defined" ts = linspace 100 (0,20) sol = odeSolve (xdot w d) [1,0] ts mplot (ts : toColumns sol) kepler v a = mplot (take 2 $ toColumns sol) where xdot _t [x,y,vx,vy] = [vx,vy,x*k,y*k] where g=1 k=(-g)*(x*x+y*y)**(-1.5) xdot _ _ = error "kepler RHS not defined" ts = linspace 100 (0,30) sol = odeSolve xdot [4, 0, v * cos (a*degree), v * sin (a*degree)] ts degree = pi/180 main = do vanderpol 2 harmonic 1 0 harmonic 1 0.1 kepler 0.3 60 kepler 0.4 70 vanderpol' 2 -- example of odeSolveV with jacobian vanderpol' mu = do let xdot nu _t (toList->[x,v]) = fromList [v, -x + nu * v * (1-x*x)] xdot _ _ _ = error "vanderpol' RHS not defined" jac _ (toList->[x,v]) = (2><2) [ 0 , 1 , -1-2*x*v*mu, mu*(1-x**2) ] jac _ _ = error "vanderpol' Jacobian not defined" ts = linspace 1000 (0,50) hi = pure $ (ts!1 - ts!0) / 100.0 sol = toColumns $ odeSolveV (SDIRK_5_3_4 jac) hi 1E-8 1E-8 (xdot mu) (fromList [1,0]) ts mplot sol
------------------------------------------------------------------------------- {- LANGUAGE CPP #-} #define DO_TRACE 0 #define HANDLE_ATTRS_DATA_CONSTRAINT 0 -- XXX Note: Show constraints are for debugging purposes. #define INCLUDE_SHOW_INSTANCES 0 -- Formerly DEBUG_WITH_DEEPSEQ_GENERICS. -- Now also needed to force issuance of all compilePat warnings -- (so not strictly a debugging flag anymore). -- [Except it didn't work...] --- #define NFDATA_INSTANCE_PATTERN 1 -- now it's a .cabal flag -- Now specified via --flag=[-]USE_WWW_DEEPSEQ --- #define USE_WW_DEEPSEQ 1 ------------------------------------------------------------------------------- -- Used to create a custom Exception instance -- needed? -- I know we are no longer allowed to write our own instance? -- I thought Exceptions were in Haskell 98?... {-# LANGUAGE DeriveDataTypeable #-} -- For tracing only: {- LANGUAGE BangPatterns #-} {-# LANGUAGE BangPatterns #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-overlapping-patterns #-} #if ! HASKELL98_FRAGMENT {-# LANGUAGE ScopedTypeVariables #-} {- LANGUAGE RankNTypes #-} {-# LANGUAGE ConstraintKinds #-} #endif ------------------------------------------------------------------------------- -- | -- Module : Control.DeepSeq.Bounded.NFDataP -- Copyright : Andrew G. Seniuk 2014-2015 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Andrew Seniuk <[email protected]> -- Stability : provisional -- Portability : portable -- -- This module provides an overloaded function, 'deepseqp', for partially -- (or fully) evaluating data structures to bounded depth via pattern -- matching on term shape, and on class, type, and constructor names. -- -- There are two ways to use this API. -- -- (1) You can use the 'PatNode' constructors directly. -- -- (2) You can compile your patterns from strings in a concise -- embedded language. -- -- There's no difference in expressive power, but use of the DSL -- is recommended, because the embedded 'Pattern' compiler can catch -- some errors that GHC cannot (using 'PatNode' constructors explicitly). -- Also, the pattern strings are easier to read and write. -- -- With some qualifications (concerning 'WI' nodes, and 'PatNodeAttrs' -- configuration), composition fuses, and what's more, it's commutative... -- -- __Motivation__ -- -- A typical use is to ensure any exceptions hidden within lazy -- fields of a data structure do not leak outside the scope of the -- exception handler; another is to force evaluation of a data structure in -- one thread, before passing it to another thread (preventing work moving -- to the wrong threads). Unlike <http://hackage.haskell.org/package/deepseq/docs/Control-DeepSeq.html DeepSeq>, potentially infinite values of coinductive -- data types are supported by principled bounding of deep evaluation. -- -- It is also useful for diagnostic purposes when trying to understand -- and manipulate space\/time trade-offs in lazy code, -- and as an optimal substitute for 'deepseq' -- (where \"optimal\" doesn't include changing the code to remove -- the need for artificial forcing!). -- -- 'deepseqp' with optimal patterns is usually a better solution -- even than stict fields in your data structures, because the -- latter will behave strictly everywhere the constructors -- are used, instead of just where its laziness is problematic. -- -- There may be possible applications to the prevention of resource leaks -- in lazy streaming, but I'm not certain. -- -- __Semantics__ -- -- (For additional details, see "Control.DeepSeq.Bounded.Pattern".) -- -- 'deepseqp' and friends artifically force evaluation of a term -- so long as the pattern matches. -- -- A mismatch occurs at a pattern node when the corresponding constructor node either: -- -- * has arity different than the number of subpatterns (only when subpatterns given) -- -- * has class\/type\/name not named in the constraint (only when constraint given) -- -- A mismatch will cause evaluation down that branch to stop, but any -- upstream matching/forcing will continue uninterrupted. -- / (This behaviour can now be changed with 'PatNodeAttrs', available since 0.6.) / -- -- Note that patterns may extend beyond the values they match against, -- without incurring any mismatch. This semantics is not the only -- possible, but bear in mind that order of evaluation is nondeterministic, -- barring further measures. -- / (This behaviour can also now be changed with 'PatNodeAttrs'.) / -- -- See also <http://hackage.haskell.org/package/deepseq-bounded-0.8.0.0/docs/Control-DeepSeq-Bounded-NFDataPDyn.html NFDataPDyn> for another approach, which dynamically -- generates forcing patterns, and can depend on value info -- (in addition to type info). -- / (These dynamic aspects never received the attention I intended to give them, I got so caught up in seqaid, which offers similar features. Hopefully actual use of these tools in the near future will give me some perspective on whether/ -- <http://hackage.haskell.org/package/deepseq-bounded-0.8.0.0/docs/Control-DeepSeq-Bounded-NFDataPDyn.html NFDataPDyn> /should get attention.) / -- ------------------------------------------------------------------------------- module Control.DeepSeq.Bounded.NFDataP ( #if OVERLOADED_STRINGS deepseqp, forcep -- take Pattern arg or String **literal** , deepseqp_, forcep_ -- aliases to the aforegoing (for compatability) #else -- * Pattern-bounded analogues of 'deepseq' and 'force' deepseqp, forcep -- take String arg (pattern DSL) -- * Avoid DSL compilation overhead -- -- However, we don't anticipate that this overhead would be -- significant in most applications, because using <deepseq-bounded> -- in a tight loop would only be done for diagnostic purposes. , deepseqp_, forcep_ -- take Pattern structure arg #endif -- * A custom exception, raised by choice 'PatNode's, that can be caught in the caller #if USE_PING_PATNODE , DeepSeqBounded_PingException(..) #endif -- * Related modules re-exported , module Control.DeepSeq.Bounded.Pattern , module Control.DeepSeq.Bounded.PatUtil -- actually exports former -- * Class of things that can be evaluated over an arbitrary finite pattern , NFDataP(..) -- * Shared with GNFDataP (internal use) , handleAttrs -- used by GNFDataP at least ) where ------------------------------------------------------------------------------- import Control.DeepSeq.Bounded.Pattern import Control.DeepSeq.Bounded.Compile import Control.DeepSeq.Bounded.PatUtil ( unionPats, liftPats ) -- debugging... #if 1 import Control.DeepSeq.Bounded.PatUtil ( probDensRose , weightedRose , unzipRose , showRose #if ! HASKELL98_FRAGMENT , Shape , shapeOf , ghom #endif ) #endif import Control.DeepSeq.Bounded.NFDataN -- finally used ("*3" etc.) #if USE_WW_DEEPSEQ import Control.DeepSeq ( NFData ) import Control.DeepSeq ( rnf ) #endif #if HANDLE_ATTRS_DATA_CONSTRAINT -- Brought back only to add Data d constraint to handleAttrs, which -- is a hack so can print something distinct for multiple +-nodes... import Data.Data #endif --import Data.Data -- "redundant" last checked import Data.Typeable ( Typeable ) #if 1 import Data.Typeable ( typeOf ) #else -- XXX These are NOT interchangeable! #if __GLASGOW_HASKELL__ >= 781 import Data.Typeable ( typeRep ) #else import Data.Typeable ( typeOf ) #endif #endif import Data.Typeable ( mkTyCon3, mkTyConApp ) import Data.Typeable ( typeRepTyCon ) #if USE_PAR_PATNODE import Control.Parallel ( par ) #endif #if USE_PSEQ_PATNODE import Control.Parallel ( pseq ) #endif #if USE_PING_PATNODE import Control.Concurrent ( myThreadId, killThread ) import Control.Concurrent ( forkIO ) #endif import Control.Concurrent ( threadDelay ) import Data.Int import Data.Word import Data.Ratio import Data.Complex import Data.Array import Data.Fixed import Data.Version import Data.Maybe ( Maybe(..), isJust, fromJust, isNothing ) import Control.Exception ( Exception ) import Control.Exception ( asyncExceptionFromException ) import Control.Exception ( throwTo ) import Control.Exception ( throw ) import Control.Exception( AsyncException( UserInterrupt ) ) import Control.Monad ( liftM ) -- XXX unsafePerformIO *is* used [besides indirectly with trace and throwTo]. -- Grep the source on a case by case basis... import System.IO.Unsafe ( unsafeInterleaveIO ) import System.IO.Unsafe ( unsafeDupablePerformIO ) import System.IO.Unsafe ( unsafePerformIO ) import Control.Exception ( evaluate ) import System.Random ( randomIO ) import Debug.Trace ( trace ) ------------------------------------------------------------------------------- #if USE_PING_PATNODE data DeepSeqBounded_PingException = DeepSeqBounded_PingException String deriving (Show, Typeable) instance Exception DeepSeqBounded_PingException #endif ------------------------------------------------------------------------------- #if DO_TRACE mytrace = trace #else mytrace _ = id #endif ------------------------------------------------------------------------------- --infixr 0 $!! ------------------------------------------------------------------------------- #if OVERLOADED_STRINGS {-# DEPRECATED deepseqp_, forcep_ "OverloadedStrings is in effect for pattern strings (since 0.8), so you can use deepseqp and forcep with either a Pattern or a String literal as first argument. To work with String variables, write your own wrapper function calling compilePat (or build with OVERLOEADED_STRINGS flag False). These underscore versions will be removed in 0.9 (mere days from now...)." #-} -- For compatibility with prior, non-OVERLOADED_STRINGS API. -- I can actually upload this without a major version bump, -- even though it very much has the feel of one. That's -- extension magic for ya! ------ -- It seems the signatures are needed, unfortunately. #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) deepseqp_ :: NFDataP_ictx a => Pattern -> a -> b -> b --deepseqp_ :: NFDataP_cctx a => Pattern -> a -> b -> b #else #if INCLUDE_SHOW_INSTANCES deepseqp_ :: (Show a, NFDataP a) => Pattern -> a -> b -> b #else deepseqp_ :: NFDataP a => Pattern -> a -> b -> b #endif #endif deepseqp_ = deepseqp -- | 'deepseqp_' and 'forcep_' are merely aliases to the -- non-underscored functions. They are vestigial and -- retained for compatibility until the next major -- version bump. Then it seems safe to remove them, -- since can always build with @OVERLOADED_STRINGS@ flag -- set @False@ if their absence is a problem (or define -- the aliases yourself). So, DEPRECATED, and slated -- for removal in 0.8. #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) forcep_ :: NFDataP_ictx a => Pattern -> a -> a --forcep_ :: NFDataP_cctx a => Pattern -> a -> a #else #if INCLUDE_SHOW_INSTANCES forcep_ :: (Show a, NFDataP a) => Pattern -> a -> a #else forcep_ :: NFDataP a => Pattern -> a -> a #endif #endif forcep_ = forcep -- XXX NOTE TO SELF: These comments are verbatim from Control.DeepSeq: -- | 'deepseqp' evaluates the first argument to the extent specified -- by a 'Pattern', before returning the second. -- -- Quoting from the <http://hackage.haskell.org/package/deepseq/docs/Control-DeepSeq.html DeepSeq> documentation (<http://hackage.haskell.org/package/deepseq deepseq> package): -- -- \"<http://hackage.haskell.org/package/deepseq/docs/Control-DeepSeq.html#t:deepseq deepseq> /can be useful for forcing pending exceptions, eradicating space leaks, or forcing lazy I\/O to happen. It is also useful in conjunction with parallel Strategies (see the/ <http://hackage.haskell.org/package/parallel parallel> /package). / -- -- Self-composition fuses via -- -- @ -- "deepseqp/composition" -- forall p1 p2 x1 x2. -- (.) ('deepseqp' p2 x2) ('deepseqp' p1 x1) -- = 'deepseqp' ( 'liftPats' [p1, p2] ) (x1,x2) -- @ -- -- (Other fusion rules, not yet documented, may also be in effect.) {--} -- [No longer true, but discussing doPseq here is too much, so tacit.] -- / There is no guarantee about the ordering of evaluation. The implementation may evaluate the components of the structure in any order or in parallel. To impose an actual order on evaluation, use 'pseq' from "Control.Parallel" in the @parallel@ package.\" / {--} -- XXX LATER: This is flawed for # at root of pattern. -- Maybe not quite flawed, just "untestable" if there's bottom at -- the root of the value (that is to say, the value is (undefined::b). #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) deepseqp :: NFDataP_ictx a => Pattern -> a -> b -> b --deepseqp :: NFDataP_cctx a => Pattern -> a -> b -> b #else #if INCLUDE_SHOW_INSTANCES deepseqp :: (Show a, NFDataP a) => Pattern -> a -> b -> b #else deepseqp :: NFDataP a => Pattern -> a -> b -> b #endif #endif deepseqp pat a b = rnfp pat a `seq` b -- XXX Need to double-check that this makes sense; didn't think -- it through -- when b != a, things are not so simple. -- XXX Partially-applied; is that okay in GHC RULES? {-# RULES "deepseqp/composition" forall p1 p2 x1 x2. (.) (deepseqp p2 x2) (deepseqp p1 x1) = deepseqp ( liftPats [p1, p2] ) (x1,x2) #-} -- "deepseqp/composition" forall p1 p2 x. (.) (deepseqp p2) (deepseqp p1) x = deepseqp ( unionPats [p1, p2] ) x ------------------------------------------------------------------------------- #if 0 -- | the deep analogue of '$!'. In the expression @f $!! x@, @x@ is -- fully evaluated before the function @f@ is applied to it. ($!!) :: (NFData a) => (a -> b) -> a -> b f $!! x = x `deepseq` f x #endif -- XXX NOTE TO SELF: These comments are verbatim from Control.DeepSeq: -- | A variant of 'deepseqp' that is sometimes convenient: -- -- > forcep pat x = deepseqp pat x x -- (cannot write x `deepseqp pat` x by analogy with x `deepseq` x) -- -- @forcep pat x@ evaluates @x@ to the depth determined by @pat@, and -- then returns @x@. Again from -- <http://hackage.haskell.org/package/deepseq deepseq>: -- / \"Note that @forcep pat x@ only takes effect when the value of @forcep pat x@ itself is demanded, so essentially it turns shallow evaluation into evaluation to arbitrary bounded depth.\" / -- -- Self-composition fuses via -- -- @ -- "forcep/composition" -- forall p1 p2 x. -- (.) ('forcep' p2) ('forcep' p1) x -- = 'forcep' ( 'unionPats' [p1, p2] ) x -- @ -- -- (Other fusion rules, not yet documented, may also be in effect.) {--} -- XXX What about fusion of mixed applications?... -- XXX LATER: This is "flawed" for # at root of pattern. (See deepseqp.) #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) forcep :: NFDataP_ictx a => Pattern -> a -> a --forcep :: NFDataP_cctx a => Pattern -> a -> a #else #if INCLUDE_SHOW_INSTANCES forcep :: (Show a, NFDataP a) => Pattern -> a -> a #else forcep :: NFDataP a => Pattern -> a -> a #endif #endif forcep pat x = deepseqp pat x x {-# RULES "forcep/composition" forall p1 p2 x. (.) (forcep p2) (forcep p1) x = forcep ( unionPats [p1, p2] ) x #-} #else -- else not OVERLOADED_STRINGS -- XXX NOTE TO SELF: These comments are verbatim from Control.DeepSeq: -- | 'deepseqp' evaluates the first argument to the extent specified -- by a 'Pattern', before returning the second. -- -- Quoting from the <http://hackage.haskell.org/package/deepseq/docs/Control-DeepSeq.html DeepSeq> documentation (<http://hackage.haskell.org/package/deepseq deepseq> package): -- -- \"<http://hackage.haskell.org/package/deepseq/docs/Control-DeepSeq.html#t:deepseq deepseq> /can be useful for forcing pending exceptions, eradicating space leaks, or forcing lazy I\/O to happen. It is also useful in conjunction with parallel Strategies (see the/ <http://hackage.haskell.org/package/parallel parallel> /package). / -- -- Composition fuses (see 'deepseqp_'). {--} -- [No longer true, but discussing doPseq here is too much, so tacit.] -- / There is no guarantee about the ordering of evaluation. The implementation may evaluate the components of the structure in any order or in parallel. To impose an actual order on evaluation, use 'pseq' from "Control.Parallel" in the @parallel@ package.\" / {--} -- XXX LATER: This is "flawed" for # at root of pattern. (See deepseqp_.) #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) deepseqp :: NFDataP_ictx a => String -> a -> b -> b --deepseqp :: NFDataP_cctx a => String -> a -> b -> b #else #if INCLUDE_SHOW_INSTANCES deepseqp :: (Show a, NFDataP a) => String -> a -> b -> b #else deepseqp :: NFDataP a => String -> a -> b -> b #endif #endif #if 0 #elif 0 deepseqp patstr a b = fromJust $ deepseqp_ (compilePat patstr) a b --deepseqp patstr = fromJust $ deepseqp_ (compilePat patstr) #elif 1 deepseqp patstr = deepseqp_ (compilePat patstr) #elif 0 deepseqp patstr a b = rnfp (compilePat patstr) a `seq` b -- XXX Partially-applied; is that okay in GHC RULES? {-# RULES "deepseqp/composition" forall p1 p2 x. (.) (deepseqp p2) (deepseqp p1) x = deepseqp_ ( unionPats [compilePat p1, compilePat p2] ) x #-} #endif -- | Self-composition fuses via -- -- @ -- "deepseqp_/composition" -- forall p1 p2 x1 x2. -- (.) ('deepseqp_' p2 x2) ('deepseqp_' p1 x1) -- = 'deepseqp_' ( 'liftPats' [p1, p2] ) (x1,x2) -- @ -- -- (Other fusion rules, not yet documented, may also be in effect.) {--} -- XXX LATER: This is "flawed" for # at root of pattern. -- Maybe not quite "flawed", just "untestable" if there's bottom at -- the root of the value (that is to say, the value is (undefined::b). #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) deepseqp_ :: NFDataP_ictx a => Pattern -> a -> b -> b --deepseqp_ :: NFDataP_cctx a => Pattern -> a -> b -> b #else #if INCLUDE_SHOW_INSTANCES deepseqp_ :: (Show a, NFDataP a) => Pattern -> a -> b -> b #else deepseqp_ :: NFDataP a => Pattern -> a -> b -> b #endif #endif #if 0 #elif 0 deepseqp_ pat@(Node WI _) _ b = b deepseqp_ pat@(Node (TR as) chs) a b = if elem ta treps then doit `seq` b else b where ta = show $ typeRepTyCon $ typeOf a doit = rnfp pat a `seq` b treps = typeConstraints as deepseqp_ pat@(Node (TI as) chs) a b = if elem ta treps then b else doit `seq` b where ta = show $ typeRepTyCon $ typeOf a doit = rnfp pat a `seq` b treps = typeConstraints as deepseqp_ pat a b = rnfp pat a `seq` b #elif 1 deepseqp_ pat a b = rnfp pat a `seq` b -- XXX Need to double-check that this makes sense; didn't think -- it through -- when b != a, things are not so simple. -- XXX Partially-applied; is that okay in GHC RULES? {-# RULES "deepseqp_/composition" forall p1 p2 x1 x2. (.) (deepseqp_ p2 x2) (deepseqp_ p1 x1) = deepseqp_ ( liftPats [p1, p2] ) (x1,x2) #-} -- "deepseqp_/composition" forall p1 p2 x. (.) (deepseqp_ p2) (deepseqp_ p1) x = deepseqp_ ( unionPats [p1, p2] ) x #endif ------------------------------------------------------------------------------- #if 0 -- | the deep analogue of '$!'. In the expression @f $!! x@, @x@ is -- fully evaluated before the function @f@ is applied to it. ($!!) :: (NFData a) => (a -> b) -> a -> b f $!! x = x `deepseq` f x #endif -- XXX NOTE TO SELF: These comments are verbatim from Control.DeepSeq: -- | A variant of 'deepseqp' that is sometimes convenient: -- -- > forcep pat x = deepseqp pat x x -- (cannot write x `deepseqp pat` x by analogy with x `deepseq` x) -- -- @forcep pat x@ evaluates @x@ to the depth determined by @pat@, and -- then returns @x@. Again from -- <http://hackage.haskell.org/package/deepseq deepseq>: -- / \"Note that @forcep pat x@ only takes effect when the value of @forcep pat x@ itself is demanded, so essentially it turns shallow evaluation into evaluation to arbitrary bounded depth.\" / -- -- Composition fuses (see 'forcep_'). {--} -- XXX What about fusion of mixed applications?... -- XXX LATER: This is "flawed" for # at root of pattern. (See deepseqp_.) #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) forcep :: NFDataP_ictx a => String -> a -> a --forcep :: NFDataP_cctx a => String -> a -> a #else #if INCLUDE_SHOW_INSTANCES forcep :: (Show a, NFDataP a) => String -> a -> a #else forcep :: NFDataP a => String -> a -> a #endif #endif #if 0 #elif 0 forcep patstr x | p = fromJust ma -- | otherwise = error "here" | otherwise = undefined::a where ma = deepseqp_ (compilePat patstr) x x p = isJust ma #elif 0 forcep patstr x = fromJust $ deepseqp_ (compilePat patstr) x x #elif 0 forcep patstr x | b = x | otherwise = fromJust y where y = deepseqp_ (compilePat patstr) x (Just x) pat@(Node pas chs) = compilePat patstr b | WI <- pas = True | TR <- pas = True | TN <- pas = True | TW <- pas = True | TI <- pas = True | otherwise = False #elif 1 forcep patstr x = deepseqp_ (compilePat patstr) x x --forcep patstr x = deepseqp patstr x x {-# RULES "forcep/composition" forall p1 p2 x. (.) (forcep p2) (forcep p1) x = forcep_ ( unionPats [compilePat p1, compilePat p2] ) x #-} #endif -- | Self-composition fuses via -- -- @ -- "forcep_/composition" -- forall p1 p2 x. -- (.) ('forcep_' p2) ('forcep_' p1) x -- = 'forcep_' ( 'unionPats' [p1, p2] ) x -- @ -- -- (Other fusion rules, not yet documented, may also be in effect.) {--} -- XXX LATER: This is "flawed" for # at root of pattern. (See deepseqp_.) #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) forcep_ :: NFDataP_ictx a => Pattern -> a -> a --forcep_ :: NFDataP_cctx a => Pattern -> a -> a #else #if INCLUDE_SHOW_INSTANCES forcep_ :: (Show a, NFDataP a) => Pattern -> a -> a #else forcep_ :: NFDataP a => Pattern -> a -> a #endif #endif #if 0 forcep_ pat x = fromJust $ deepseqp_ pat x x #else forcep_ pat x = deepseqp_ pat x x {-# RULES "forcep_/composition" forall p1 p2 x. (.) (forcep_ p2) (forcep_ p1) x = forcep_ ( unionPats [p1, p2] ) x #-} #endif #endif -- of if OVERLOADED_STRINGS else ------------------------------------------------------------------------------- #if ! HASKELL98_FRAGMENT -- We don't need 7.10 for tuple predicates /here/, but when try to -- use in seqaid, the TH splice complains -- Can't represent tuple predicates in Template Haskell: -- Control.DeepSeq.Bounded.NFDataP_new_grammar.NFDataP_cctx -- That is with GHC 7.8.4. -- So we need template-haskell-2.10, which means need base >= base-4.8.0.0, -- which means need GHC >= 7.10. #if __GLASGOW_HASKELL__ >= 710 -- XXX Not H98! -XConstraintKinds type NFDataP_cctx a = ( Typeable a #if HANDLE_ATTRS_DATA_CONSTRAINT , Data a #endif , NFDataN a #if USE_WW_DEEPSEQ , NFData a #endif ) #if 0 -- XXX Because TH < 2.10 cannot hand tuple predicates, -- even if the corresponding GHC can! -- And this didn't help anyway, still get the error -- when TH runs in seqaid... type NFDataP_ictx a = ( Typeable a #if HANDLE_ATTRS_DATA_CONSTRAINT , Data a #endif , NFDataN a #if USE_WW_DEEPSEQ , NFData a #endif , NFDataP a #if INCLUDE_SHOW_INSTANCES , Show a #endif ) #else type NFDataP_ictx a = ( NFDataP_cctx a , NFDataP a #if INCLUDE_SHOW_INSTANCES , Show a #endif ) #endif #endif #endif ------------------------------------------------------------------------------- -- | A class of types that can be evaluated over an arbitrary finite pattern. #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) class NFDataP_cctx a => NFDataP a where #else class ( Typeable a #if HANDLE_ATTRS_DATA_CONSTRAINT , Data a #endif , NFDataN a #if USE_WW_DEEPSEQ , NFData a #endif ) => NFDataP a where #endif -- | Self-composition fuses via -- -- @ -- "rnfp/composition" -- forall p1 p2 x. -- (.) ('rnfp' p2) ('rnfp' p1) x -- = 'rnfp' ( 'unionPats' [p1, p2] ) x -- @ -- -- (Other fusion rules, not yet documented, may also be in effect.) {- NOINLINE rnfp #-} #if INCLUDE_SHOW_INSTANCES rnfp :: Show a => Pattern -> a -> () #else rnfp :: Pattern -> a -> () #endif #if 0 -- rnfp p x | p `seq` trace "Boo!" () `seq` p == Node XX [] = undefined -- does NOT work -- rnfp p x | trace "Boo!" p `seq` p == Node XX [] = undefined -- WORKS!!! -- rnfp p x | trace "Boo!" () `seq` p == (trace "FOO!!" (Node XX [])) = undefined -- FOO!! /is/ printed, though only once (like Boo) -- rnfp p x | trace "Boo!" () `seq` p == Node XX [] = undefined -- NOT works (printed once only) -- rnfp p x | (trace "Boo!" p) == Node XX [] = undefined -- WORKS!!! (printed every time) -- rnfp p x | trace "Boo!" () `seq` p == Node TN{} [] = undefined -- rnfp p x | trace "Boo!" () `seq` False = undefined -- rnfp p x | trace "Boo!" True, p `seq` False = undefined -- rnfp p x | trace "Boo!" False = undefined #endif #if 1 rnfp p x | handleAttrs p x == Node XX [] = undefined -- rnfp p@(Node pn _) x | as <- getPatNodeAttrs pn, 9 == uniqueID as = error $ showPatNodeRaw pn -- rnfp p@(Node pn@(WI _) _) x = error $ showPatNodeRaw pn -- rnfp p@(Node pn@WI{} _) x = error $ showPatNodeRaw pn -- rnfp p@(Node WI{} _) x = handleAttrs p x `seq` () rnfp (Node WI{} _) _ = () #else rnfp (Node WI{} _) _ = () #endif rnfp (Node (TR as) chs) d = if elem td treps then d `seq` () else () where td = show $ typeRepTyCon $ typeOf d treps = typeConstraints as rnfp (Node (TI as) chs) d = if elem td treps then () else d `seq` () where td = show $ typeRepTyCon $ typeOf d treps = typeConstraints as #if USE_WW_DEEPSEQ -- complement of TI, equivalent to TR in this special case rnfp (Node (TW as) chs) d = if elem td treps then d `seq` () else () where td = show $ typeRepTyCon $ typeOf d treps = typeConstraints as #endif #if 1 rnfp _ d = d `seq` () -- rnfp _ _ = () #else -- XXX temporarily (at least) commenting out; not making any -- use of patternShapeOK -- but there is room for more -- error-trapping code in here, definitely... rnfp pat a | not $ patternShapeOK pat a = () | otherwise = rnf a #endif {-# RULES "rnfp/composition" forall p1 p2 x. (.) (rnfp p2) (rnfp p1) x = rnfp ( unionPats [p1, p2] ) x #-} -- "rnfp/composition" forall p1 p2 x. compose (rnfp p2) (rnfp p1) x = rnfp ( unionPats [p1, p2] ) x -- "rnfp/composition" forall p1 p2 x. ( rnfp p2 . rnfp p1 ) x = rnfp ( unionPats [p1, p2] ) x ------------------------------------------------------------------------------- #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) rnfp' :: NFDataP_ictx a => PatNode -> () -> a -> () #else #if USE_WW_DEEPSEQ rnfp' :: (Typeable a, NFDataN a, NFData a) => PatNode -> () -> a -> () #else rnfp' :: (Typeable a, NFDataN a) => PatNode -> () -> a -> () #endif #endif rnfp' pas recurs d -- I can only conclude that we've already evaluated the argument -- by the time this code runs (or that we evaluate it after...). -- But this code doesn't do the dirty deed! = {-trace ( "rnfp' " ++ show pat) $-} let td = show $ typeRepTyCon $ typeOf d -- no problem on bottom as = getPatNodeAttrs pas treps = typeConstraints as n = depth as in #if USE_PAR_PATNODE if doSpark as then case pas of WS{} -> () `par` () WR{} -> recurs `par` () WN{} -> rnfn n d `par` () #if USE_WW_DEEPSEQ WW{} -> rnf d `par` () -- should reimplement deepseq for uniformity... #endif WI{} -> error "rnfp: unexpected =WI (please report this bug!)" _ -> error $ "rnfp: Unexpected PatNode (with doSpark): " ++ show pas ++ "(please report this bug!)" else #endif case pas of WR{} -> recurs WS{} -> () -- WS{} -> d `seq` () WN{} -> rnfn n d #if USE_WW_DEEPSEQ WW{} -> rnf d -- should reimplement deepseq for uniformity... #endif #if 0 -- This code stays the same whether we (are able to) compare -- actual TypeRep's for equality, or we just hack it -- and match: show . typeRepTyCon . typeOf TR{} -> if elem td treps then recurs else () #endif #if 0 -- This is not right. To pull this off (b/c it depends on -- types in the value you're matching with), need to construct -- the pattern dynamically. In particular, to produce Nil -- where a TR (or TS) constraint causes (or would cause) -- match failure. TS{} -> if elem td treps then () else () #endif TN{} -> if elem td treps then rnfn n d else () #if USE_WW_DEEPSEQ TW{} -> if elem td treps then rnf d else () #endif #if 0 NTR{} -> if not $ elem td treps then recurs else () NTN{} -> if not $ elem td treps then rnfn n d else () #if USE_WW_DEEPSEQ NTW{} -> if not $ elem td treps then rnf d else () #endif #endif -- these handled upstream WI{} -> error "rnfp: unexpected WI (please report this bug!)" TR{} -> error "rnfp: unexpected TR (please report this bug!)" TI{} -> error "rnfp: unexpected TI (please report this bug!)" _ -> error $ "rnfp: Unexpected PatNode: " ++ show pas ++ " (please report this bug!)" ------------------------------------------------------------------------------- #if 0 compose = (.) {-# NOINLINE compose #-} -- Can't do this, unfortunately. GHC warns it may get inlined before -- rules have a chance to fire. I would rather avoid forcing the API -- user to use some custom "compose" function, since base (.) works -- perfectly, except it's hard to control its inlining... {- NOINLINE (.) #-} #endif ------------------------------------------------------------------------------- -- Base nullary types. instance NFDataP Int instance NFDataP Word instance NFDataP Integer instance NFDataP Float instance NFDataP Double instance NFDataP Char instance NFDataP Bool instance NFDataP () instance NFDataP Int8 instance NFDataP Int16 instance NFDataP Int32 instance NFDataP Int64 instance NFDataP Word8 instance NFDataP Word16 instance NFDataP Word32 instance NFDataP Word64 ------------------------------------------------------------------------------- --- Fixed a instance Typeable a => NFDataP (Fixed a) --instance NFDataP (Fixed a) ------------------------------------------------------------------------------- --- a -> b -- [Quoted from deepseq:] -- This instance is for convenience and consistency with 'seq'. -- This assumes that WHNF is equivalent to NF for functions. #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) instance (NFDataP_ictx a, NFDataP_ictx b) => NFDataP (a -> b) #else instance ( Typeable a, Typeable b #if HANDLE_ATTRS_DATA_CONSTRAINT , Data a, Data b -- XXX why only needed in THIS instance? #endif ) => NFDataP (a -> b) --instance NFDataP (a -> b) #endif ------------------------------------------------------------------------------- --- Ratio a -- not taken to be a level of depth #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) instance (NFDataP_ictx a, Integral a) => NFDataP (Ratio a) where #else #if INCLUDE_SHOW_INSTANCES instance (Show a, Integral a, NFDataP a) => NFDataP (Ratio a) where #else instance (Integral a, NFDataP a) => NFDataP (Ratio a) where #endif #endif -- XXX This is very dubious!... {- NOINLINE rnfp #-} rnfp p x | handleAttrs p x == Node XX [] = undefined rnfp (Node WI{} _) _ = () rnfp pat x = rnfp pat (numerator x, denominator x) ------------------------------------------------------------------------------- --- Complex a -- Note that (Complex a) constructor (:+) has strict fields, -- so unwrapping the ctor also forces both components. #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) instance (NFDataP_ictx a, RealFloat a) => NFDataP (Complex a) where #else #if INCLUDE_SHOW_INSTANCES instance (Show a, RealFloat a, NFDataP a) => NFDataP (Complex a) where #else instance (RealFloat a, NFDataP a) => NFDataP (Complex a) where #endif #endif {- NOINLINE rnfp #-} rnfp p x | handleAttrs p x == Node XX [] = undefined rnfp (Node WI{} _) _ = () rnfp pat@(Node pas chs) d | TR{} <- pas = if elem td treps then recurs else () #if USE_WW_DEEPSEQ | TI{} <- pas = if elem td treps then () else rnf d | TW{} <- pas = if elem td treps then rnf d else () #else | TI{} <- pas = if elem td treps then () else rnfn 999999 d -- XXX thack! #endif | otherwise = rnfp' pas recurs d where as = getPatNodeAttrs pas treps = typeConstraints as td = show $ typeRepTyCon $ typeOf d recurs = case length chs of 0 -> case pas of WS{} -> () _ -> pat_match_fail 2 -> let [px,py] = chs (x:+y) = d #if USE_PSEQ_PATNODE in pseq_condition pat [ rnfp px x , rnfp py y ] #else in rnfp px x `seq` rnfp py y #endif `seq` () -- needed? _ -> pat_match_fail pat_match_fail = patMatchFail' "(Complex a)" pas chs d ------------------------------------------------------------------------------- --- Maybe a -- XXX Never until now (so much later) did I properly consider how to -- handle a no-arg (nullary) constructor! It's not hard, but it's -- significantly different than the other cases, as there's no -- subvalue we can grab hold of -- there's no "d"; so this invalidates -- all the code, in the posary (complement of nullary, coinage :) case -- case, which references d. #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) instance NFDataP_ictx a => NFDataP (Maybe a) where #else #if INCLUDE_SHOW_INSTANCES instance (Show a, NFDataP a) => NFDataP (Maybe a) where #else instance NFDataP a => NFDataP (Maybe a) where #endif #endif {- NOINLINE rnfp #-} rnfp p x | handleAttrs p x == Node XX [] = undefined rnfp (Node WI{} _) _ = () rnfp pat@(Node pas chs) Nothing | not $ null chs = pat_match_fail | otherwise = () where pat_match_fail = patMatchFail' "Nothing" pas chs () rnfp (Node pas chs) (Just d) | TR{} <- pas = if elem td treps then recurs else () #if USE_WW_DEEPSEQ | TI{} <- pas = if elem td treps then () else rnf d | TW{} <- pas = if elem td treps then rnf d else () #else | TI{} <- pas = if elem td treps then () else rnfn 999999 d -- XXX thack! #endif | otherwise = rnfp' pas recurs d where as = getPatNodeAttrs pas treps = typeConstraints as td = show $ typeRepTyCon $ typeOf d recurs = case length chs of 0 -> case pas of WS{} -> () _ -> pat_match_fail 1 -> let [p_J] = chs in rnfp p_J d `seq` () -- needed? _ -> pat_match_fail pat_match_fail = patMatchFail' "Just" pas chs d rnfp (Node pas chs) d = patMatchFail pas chs d -- unreachable ------------------------------------------------------------------------------- --- Either a b #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) instance (NFDataP_ictx a, NFDataP_ictx b) => NFDataP (Either a b) where #else #if INCLUDE_SHOW_INSTANCES instance (Show a, Show b, NFDataP a, NFDataP b) => NFDataP (Either a b) where #else instance (NFDataP a, NFDataP b) => NFDataP (Either a b) where #endif #endif {- NOINLINE rnfp #-} rnfp p x | handleAttrs p x == Node XX [] = undefined rnfp (Node WI{} _) _ = () rnfp (Node pas chs) (Left d) | TR{} <- pas = if elem td treps then recurs else () #if USE_WW_DEEPSEQ | TI{} <- pas = if elem td treps then () else rnf d | TW{} <- pas = if elem td treps then rnf d else () #else | TI{} <- pas = if elem td treps then () else rnfn 999999 d -- XXX thack! #endif | otherwise = rnfp' pas recurs d where as = getPatNodeAttrs pas treps = typeConstraints as td = show $ typeRepTyCon $ typeOf d recurs = case length chs of 0 -> case pas of WS{} -> () _ -> pat_match_fail 1 -> let [p_L] = chs in rnfp p_L d `seq` () -- needed? _ -> pat_match_fail pat_match_fail = patMatchFail' "Left" pas chs d -- pat_match_fail = patMatchFail' "(Either a b)" pas chs d rnfp (Node pas chs) (Right d) | TR{} <- pas = if elem td treps then recurs else () #if USE_WW_DEEPSEQ | TI{} <- pas = if elem td treps then () else rnf d | TW{} <- pas = if elem td treps then rnf d else () #else | TI{} <- pas = if elem td treps then () else rnfn 999999 d -- XXX thack! #endif | otherwise = rnfp' pas recurs d where as = getPatNodeAttrs pas treps = typeConstraints as td = show $ typeRepTyCon $ typeOf d recurs = case length chs of 0 -> case pas of WS{} -> () _ -> pat_match_fail 1 -> let [p_R] = chs in rnfp p_R d `seq` () -- needed? _ -> pat_match_fail pat_match_fail = patMatchFail' "Right" pas chs d -- pat_match_fail = patMatchFail' "(Either a b)" pas chs d rnfp (Node pas chs) d = patMatchFail pas chs d -- unreachable ------------------------------------------------------------------------------- --- Data.Version.Version --- #if __GLASGOW_HASKELL__ < 781 --- -- requires -XStandaloneDeriving --- -- orphan instance, but better than dropping support --- -- (It seems it already has its Show instance!) --- deriving instance Data Data.Version.Version --- #endif --deriving instance Data TypeRep -- can't b/c not all data ctors are in scope! -- Data.Version ctor does /not/ have strict fields. instance NFDataP Data.Version.Version where {- NOINLINE rnfp #-} rnfp p x | handleAttrs p x == Node XX [] = undefined rnfp (Node WI{} _) _ = () rnfp pat@(Node pas chs) d | TR{} <- pas = if elem td treps then recurs else () #if USE_WW_DEEPSEQ | TI{} <- pas = if elem td treps then () else rnf d | TW{} <- pas = if elem td treps then rnf d else () #else | TI{} <- pas = if elem td treps then () else rnfn 999999 d -- XXX thack! #endif | otherwise = rnfp' pas recurs d where as = getPatNodeAttrs pas treps = typeConstraints as td = show $ typeRepTyCon $ typeOf d recurs = case length chs of 0 -> case pas of WS{} -> () _ -> pat_match_fail 2 -> let [pbr,ptags] = chs Data.Version.Version branch tags = d #if USE_PSEQ_PATNODE in pseq_condition pat [rnfp pbr branch, rnfp ptags tags] #else in rnfp pbr branch `seq` rnfp ptags tags #endif `seq` () -- needed? _ -> pat_match_fail pat_match_fail = patMatchFail' "Data.Version.Version" pas chs d ------------------------------------------------------------------------------- --- [a] -- Data.List ctors do /not/ have strict fields (i.e. (:) is not strict). #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) instance NFDataP_ictx a => NFDataP [a] where #else #if INCLUDE_SHOW_INSTANCES instance (Show a, NFDataP a) => NFDataP [a] where #else instance NFDataP a => NFDataP [a] where #endif #endif {- NOINLINE rnfp #-} rnfp p x | handleAttrs p x == Node XX [] = undefined rnfp (Node WI{} _) _ = () rnfp _ [] = () -- perhaps dubious?... rnfp pat@(Node pas chs) d | TR{} <- pas = if elem td treps then recurs else () #if USE_WW_DEEPSEQ | TI{} <- pas = if elem td treps then () else rnf d | TW{} <- pas = if elem td treps then rnf d else () #else | TI{} <- pas = if elem td treps then () else rnfn 999999 d -- XXX thack! #endif | otherwise = rnfp' pas recurs d where as = getPatNodeAttrs pas treps = typeConstraints as td = show $ typeRepTyCon $ typeOf d recurs = case length chs of 0 -> case pas of WS{} -> () _ -> pat_match_fail 2 -> let [px,pxs] = chs (x:xs) = d #if USE_PSEQ_PATNODE in pseq_condition pat [rnfp px x, rnfp pxs xs] #else in rnfp px x `seq` rnfp pxs xs #endif `seq` () -- needed? _ -> pat_match_fail pat_match_fail = patMatchFail' "[a]" pas chs d ------------------------------------------------------------------------------- --- Array a b -- Data.Array ctor does /not/ have strict fields. -- not taken to be a level of depth #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) instance (Ix a, NFDataP_ictx a, NFDataP_ictx b) => NFDataP (Array a b) where #else #if INCLUDE_SHOW_INSTANCES instance (Show a, Show b, Ix a, NFDataP a, NFDataP b) => NFDataP (Array a b) where #else instance (Ix a, NFDataP a, NFDataP b) => NFDataP (Array a b) where #endif #endif -- XXX This is very dubious!... {- NOINLINE rnfp #-} rnfp p x | handleAttrs p x == Node XX [] = undefined rnfp (Node WI{} _) _ = () rnfp pas x = rnfp pas (bounds x, Data.Array.elems x) `seq` () -- needed? ------------------------------------------------------------------------------- --- (a,b) #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) instance (NFDataP_ictx a, NFDataP_ictx b) => NFDataP (a,b) where #else #if INCLUDE_SHOW_INSTANCES instance (Show a,Typeable a,NFDataP a, Show b,Typeable b,NFDataP b) => NFDataP (a,b) where #else instance (Typeable a,NFDataP a, Typeable b,NFDataP b) => NFDataP (a,b) where #endif #endif {- NOINLINE rnfp #-} -- rnfp _ _ = error "booy" -- rnfp p x | trace "hoop!" (handleAttrs p x) `seq` p == Node XX [] = undefined rnfp p x | handleAttrs p x `seq` p == Node XX [] = undefined rnfp (Node WI{} _) _ = () rnfp pat@(Node pas chs) d | TR{} <- pas = if elem td treps then recurs else () #if USE_WW_DEEPSEQ | TI{} <- pas = if elem td treps then () else rnf d | TW{} <- pas = if elem td treps then rnf d else () #else | TI{} <- pas = if elem td treps then () else rnfn 999999 d -- XXX thack! #endif | otherwise = rnfp' pas recurs d where as = getPatNodeAttrs pas treps = typeConstraints as td = show $ typeRepTyCon $ typeOf d recurs = case length chs of 0 -> case pas of WS{} -> () _ -> pat_match_fail 2 -> let [px,py] = chs (x,y) = d #if USE_PSEQ_PATNODE in pseq_condition pat [rnfp px x, rnfp py y] #else in rnfp px x `seq` rnfp py y #endif `seq` () -- needed? _ -> pat_match_fail pat_match_fail = patMatchFail' "(,)" pas chs d ------------------------------------------------------------------------------- --- (a,b,c) #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) instance (NFDataP_ictx a, NFDataP_ictx b, NFDataP_ictx c) => NFDataP (a,b,c) where #else #if INCLUDE_SHOW_INSTANCES instance (Show a, Typeable a, NFDataP a, Show b, Typeable b, NFDataP b, Show c, Typeable c, NFDataP c) => NFDataP (a,b,c) where #else instance (Typeable a, NFDataP a, Typeable b, NFDataP b, Typeable c, NFDataP c) => NFDataP (a,b,c) where #endif #endif {- NOINLINE rnfp #-} rnfp p x | handleAttrs p x == Node XX [] = undefined rnfp (Node WI{} _) _ = () rnfp pat@(Node pas chs) d | TR{} <- pas = if elem td treps then recurs else () #if USE_WW_DEEPSEQ | TI{} <- pas = if elem td treps then () else rnf d | TW{} <- pas = if elem td treps then rnf d else () #else | TI{} <- pas = if elem td treps then () else rnfn 999999 d -- XXX thack! #endif | otherwise = rnfp' pas recurs d where as = getPatNodeAttrs pas treps = typeConstraints as td = show $ typeRepTyCon $ typeOf d recurs = case length chs of 0 -> case pas of WS{} -> () _ -> pat_match_fail 3 -> {-trace "WWW" $-} let [px,py,pz] = chs (x,y,z) = d #if USE_PSEQ_PATNODE in pseq_condition pat [ rnfp px x , rnfp py y , rnfp pz z ] #else in ({-trace "XXX" $-} rnfp px x) `seq` ({-trace "YYY" $-} rnfp py y) -- This WILL change the semantics unfortunately... -- `seq` (trace ("YYY "++show py++" "++show y) $ rnfp py y) `seq` ({-trace "ZZZ" $-} rnfp pz z) #endif `seq` () -- needed? _ -> pat_match_fail pat_match_fail = patMatchFail' "(,,)" pas chs d ------------------------------------------------------------------------------- --- (a,b,c,d) #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) instance (NFDataP_ictx a, NFDataP_ictx b, NFDataP_ictx c, NFDataP_ictx d) => NFDataP (a,b,c,d) where #else #if INCLUDE_SHOW_INSTANCES instance (Show a, Typeable a, NFDataP a, Show b, Typeable b, NFDataP b, Show c, Typeable c, NFDataP c, Show d, Typeable d, NFDataP d) => NFDataP (a,b,c,d) where #else instance (Typeable a, NFDataP a, Typeable b, NFDataP b, Typeable c, NFDataP c, Typeable d, NFDataP d) => NFDataP (a,b,c,d) where #endif #endif {- NOINLINE rnfp #-} rnfp p x | handleAttrs p x == Node XX [] = undefined rnfp (Node WI{} _) _ = () rnfp pat@(Node pas chs) d | TR{} <- pas = if elem td treps then recurs else () #if USE_WW_DEEPSEQ | TI{} <- pas = if elem td treps then () else rnf d | TW{} <- pas = if elem td treps then rnf d else () #else | TI{} <- pas = if elem td treps then () else rnfn 999999 d -- XXX thack! #endif | otherwise = rnfp' pas recurs d where as = getPatNodeAttrs pas treps = typeConstraints as td = show $ typeRepTyCon $ typeOf d recurs = case length chs of 0 -> case pas of WS{} -> () _ -> pat_match_fail 4 -> let [px1,px2,px3,px4] = chs (x1,x2,x3,x4) = d #if USE_PSEQ_PATNODE in pseq_condition pat [ rnfp px1 x1 , rnfp px2 x2 , rnfp px3 x3 , rnfp px4 x4 ] #else in rnfp px1 x1 `seq` rnfp px2 x2 `seq` rnfp px3 x3 `seq` rnfp px4 x4 #endif `seq` () -- needed? _ -> pat_match_fail pat_match_fail = patMatchFail' "(,,,)" pas chs d ------------------------------------------------------------------------------- --- (a,b,c,d,e) #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) instance (NFDataP_ictx a, NFDataP_ictx b, NFDataP_ictx c, NFDataP_ictx d, NFDataP_ictx e) => #else #if INCLUDE_SHOW_INSTANCES instance (Show a, Typeable a, NFDataP a, Show b, Typeable b, NFDataP b, Show c, Typeable c, NFDataP c, Show d, Typeable d, NFDataP d, Show e, Typeable e, NFDataP e) => #else instance (Typeable a, NFDataP a, Typeable b, NFDataP b, Typeable c, NFDataP c, Typeable d, NFDataP d, Typeable e, NFDataP e) => #endif #endif NFDataP (a, b, c, d, e) where {- NOINLINE rnfp #-} rnfp p x | handleAttrs p x == Node XX [] = undefined rnfp (Node WI{} _) _ = () rnfp pat@(Node pas chs) d | TR{} <- pas = if elem td treps then recurs else () #if USE_WW_DEEPSEQ | TI{} <- pas = if elem td treps then () else rnf d | TW{} <- pas = if elem td treps then rnf d else () #else | TI{} <- pas = if elem td treps then () else rnfn 999999 d -- XXX thack! #endif | otherwise = rnfp' pas recurs d where as = getPatNodeAttrs pas treps = typeConstraints as td = show $ typeRepTyCon $ typeOf d recurs = case length chs of 0 -> case pas of WS{} -> () _ -> pat_match_fail 5 -> let [px1,px2,px3,px4,px5] = chs (x1,x2,x3,x4,x5) = d #if USE_PSEQ_PATNODE in pseq_condition pat [ rnfp px1 x1 , rnfp px2 x2 , rnfp px3 x3 , rnfp px4 x4 , rnfp px5 x5 ] #else in rnfp px1 x1 `seq` rnfp px2 x2 `seq` rnfp px3 x3 `seq` rnfp px4 x4 `seq` rnfp px5 x5 #endif `seq` () -- needed? _ -> pat_match_fail pat_match_fail = patMatchFail' "(,,,,)" pas chs d ------------------------------------------------------------------------------- --- (a,b,c,d,e,f) #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) instance (NFDataP_ictx a, NFDataP_ictx b, NFDataP_ictx c, NFDataP_ictx d, NFDataP_ictx e, NFDataP_ictx f) => #else #if INCLUDE_SHOW_INSTANCES instance (Show a, Typeable a, NFDataP a, Show b, Typeable b, NFDataP b, Show c, Typeable c, NFDataP c, Show d, Typeable d, NFDataP d, Show e, Typeable e, NFDataP e, Show f, Typeable f, NFDataP f) => #else instance (Typeable a, NFDataP a, Typeable b, NFDataP b, Typeable c, NFDataP c, Typeable d, NFDataP d, Typeable e, NFDataP e, Typeable f, NFDataP f) => #endif #endif NFDataP (a, b, c, d, e, f) where {- NOINLINE rnfp #-} rnfp p x | handleAttrs p x == Node XX [] = undefined rnfp (Node WI{} _) _ = () rnfp pat@(Node pas chs) d | TR{} <- pas = if elem td treps then recurs else () #if USE_WW_DEEPSEQ | TI{} <- pas = if elem td treps then () else rnf d | TW{} <- pas = if elem td treps then rnf d else () #else | TI{} <- pas = if elem td treps then () else rnfn 999999 d -- XXX thack! #endif | otherwise = rnfp' pas recurs d where as = getPatNodeAttrs pas treps = typeConstraints as td = show $ typeRepTyCon $ typeOf d recurs = case length chs of 0 -> case pas of WS{} -> () _ -> pat_match_fail 6 -> let [px1,px2,px3,px4,px5,px6] = chs (x1,x2,x3,x4,x5,x6) = d #if USE_PSEQ_PATNODE in pseq_condition pat [ rnfp px1 x1 , rnfp px2 x2 , rnfp px3 x3 , rnfp px4 x4 , rnfp px5 x5 , rnfp px6 x6 ] #else in rnfp px1 x1 `seq` rnfp px2 x2 `seq` rnfp px3 x3 `seq` rnfp px4 x4 `seq` rnfp px5 x5 `seq` rnfp px6 x6 #endif `seq` () -- needed? _ -> pat_match_fail pat_match_fail = patMatchFail' "(,,,,,)" pas chs d ------------------------------------------------------------------------------- --- (a,b,c,d,e,f,g) #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) instance (NFDataP_ictx a, NFDataP_ictx b, NFDataP_ictx c, NFDataP_ictx d, NFDataP_ictx e, NFDataP_ictx f, NFDataP_ictx g) => #else #if INCLUDE_SHOW_INSTANCES instance (Show a, Typeable a, NFDataP a, Show b, Typeable b, NFDataP b, Show c, Typeable c, NFDataP c, Show d, Typeable d, NFDataP d, Show e, Typeable e, NFDataP e, Show f, Typeable f, NFDataP f, Show g, Typeable g, NFDataP g) => #else instance (Typeable a, NFDataP a, Typeable b, NFDataP b, Typeable c, NFDataP c, Typeable d, NFDataP d, Typeable e, NFDataP e, Typeable f, NFDataP f, Typeable g, NFDataP g) => #endif #endif NFDataP (a, b, c, d, e, f, g) where {- NOINLINE rnfp #-} rnfp p x | handleAttrs p x == Node XX [] = undefined rnfp (Node WI{} _) _ = () rnfp pat@(Node pas chs) d | TR{} <- pas = if elem td treps then recurs else () #if USE_WW_DEEPSEQ | TI{} <- pas = if elem td treps then () else rnf d | TW{} <- pas = if elem td treps then rnf d else () #else | TI{} <- pas = if elem td treps then () else rnfn 999999 d -- XXX thack! #endif | otherwise = rnfp' pas recurs d where as = getPatNodeAttrs pas treps = typeConstraints as td = show $ typeRepTyCon $ typeOf d recurs = case length chs of 0 -> case pas of WS{} -> () _ -> pat_match_fail 7 -> let [px1,px2,px3,px4,px5,px6,px7] = chs (x1,x2,x3,x4,x5,x6,x7) = d #if USE_PSEQ_PATNODE in pseq_condition pat [ rnfp px1 x1 , rnfp px2 x2 , rnfp px3 x3 , rnfp px4 x4 , rnfp px5 x5 , rnfp px6 x6 , rnfp px7 x7 ] #else in rnfp px1 x1 `seq` rnfp px2 x2 `seq` rnfp px3 x3 `seq` rnfp px4 x4 `seq` rnfp px5 x5 `seq` rnfp px6 x6 `seq` rnfp px7 x7 #endif `seq` () -- needed? _ -> pat_match_fail pat_match_fail = patMatchFail' "(,,,,,,)" pas chs d #if 0 -- XXX No Typeable instances for tuples larger than 7 in 7.8.1, seemingly? ------------------------------------------------------------------------------- --- (a,b,c,d,e,f,g,h) #if ( ! HASKELL98_FRAGMENT ) && ( __GLASGOW_HASKELL__ >= 710 ) instance (NFDataP_ictx a, NFDataP_ictx b, NFDataP_ictx c, NFDataP_ictx d, NFDataP_ictx e, NFDataP_ictx f, NFDataP_ictx g, NFDataP_ictx h) => #else #if INCLUDE_SHOW_INSTANCES instance (Show a, Typeable a, NFDataP a, Show b, Typeable b, NFDataP b, Show c, Typeable c, NFDataP c, Show d, Typeable d, NFDataP d, Show e, Typeable e, NFDataP e, Show f, Typeable f, NFDataP f, Show g, Typeable g, NFDataP g, Show h, Typeable h, NFDataP h) => #else instance (Typeable a, NFDataP a, Typeable b, NFDataP b, Typeable c, NFDataP c, Typeable d, NFDataP d, Typeable e, NFDataP e, Typeable f, NFDataP f, Typeable g, NFDataP g, Typeable h, NFDataP h) => #endif #endif NFDataP (a, b, c, d, e, f, g, h) where {- NOINLINE rnfp #-} rnfp p x | handleAttrs p x == Node XX [] = undefined rnfp (Node WI{} _) _ = () rnfp pat@(Node pas chs) d | TR{} <- pas = if elem td treps then recurs else () #if USE_WW_DEEPSEQ | TI{} <- pas = if elem td treps then () else rnf d | TW{} <- pas = if elem td treps then rnf d else () #else | TI{} <- pas = if elem td treps then () else rnfn 999999 d -- XXX thack! #endif | otherwise = rnfp' pas recurs d where as = getPatNodeAttrs pas treps = typeConstraints as td = show $ typeRepTyCon $ typeOf d recurs = case length chs of 0 -> case pas of WS{} -> () _ -> pat_match_fail 8 -> let [px1,px2,px3,px4,px5,px6,px7,px8] = chs (x1,x2,x3,x4,x5,x6,x7,x8) = d #if USE_PSEQ_PATNODE in pseq_condition pat [ rnfp px1 x1 , rnfp px2 x2 , rnfp px3 x3 , rnfp px4 x4 , rnfp px5 x5 , rnfp px6 x6 , rnfp px7 x7 , rnfp px8 x8 ] #else in rnfp px1 x1 `seq` rnfp px2 x2 `seq` rnfp px3 x3 `seq` rnfp px4 x4 `seq` rnfp px5 x5 `seq` rnfp px6 x6 `seq` rnfp px7 x7 `seq` rnfp px8 x8 #endif `seq` () -- needed? _ -> pat_match_fail pat_match_fail = patMatchFail' "(,,,,,,,)" pas chs d #endif ------------------------------------------------------------------------------- patMatchFail :: (Show a, Show b) => a -> b -> c -> () patMatchFail pas chs d #if WARN_PATTERN_MATCH_FAILURE = ( unsafePerformIO $! putStrLn $! "NFDataP: warning: couldn't match " ++ show pas ++ " (having children " ++ show chs ++ ")" ) `seq` () #else = () #endif -- = error $ "NFDataP: Couldn't match " ++ show pas ++ " (having children " ++ show chs ++ ")\nwith data " ++ show d patMatchFail' :: (Show a, Show b) => String -> a -> b -> c -> () patMatchFail' inst pas chs d #if WARN_PATTERN_MATCH_FAILURE = ( unsafePerformIO $! putStrLn $! "NFDataP: warning: instance " ++ inst ++ ": bad PatNode child list" ) `seq` patMatchFail pas chs d #else = () #endif ------------------------------------------------------------------------------- -- XXX Seeing as we're having troubles anyway, and considering -- that most of this function requires popping into unsafePerformIO -- anyway -- should the whole thing be returning IO, and then just -- use unsafePerformIO in caller? -- This function collects all the "harmless impure things" we -- need to pop into IO to do. To what extent we get away with -- this remains to be investigated... ------ -- So, which of the PatNodeAttrs product type can be dealt with here? -- NOT doSpark - dealt with downstream in rnfp' -- NOT doPseq - about to be dealt with downstream (hopefully rnfp')... -- doDelay -- doTrace -- doPing -- doDie -- doTiming ----- -- XXX Returning Pattern instead of Bool, in a continued attempt -- to outsmart GHC and get certain things to be evaluated... {- NOINLINE handleAttrs #-} #if 0 -- XXX XXX XXX testing only!!!! XXX XXX XXX handleAttrs pat@(Node p _) x = pat #else #if ! HASKELL98_FRAGMENT #if HANDLE_ATTRS_DATA_CONSTRAINT handleAttrs :: forall d. Data d => Pattern -> d -> Pattern --handleAttrs :: forall d. Data d => Pattern -> d -> Bool handleAttrs (Node p _) x #else handleAttrs :: forall d. Typeable d => Pattern -> d -> Pattern --handleAttrs :: forall d. Typeable d => Pattern -> d -> Bool handleAttrs (Node p _) x #endif #else handleAttrs :: Pattern -> a -> Pattern --handleAttrs :: Pattern -> a -> Bool handleAttrs (Node p _) _ #endif --- | doTrace as && trace ("HERE! "++show p++"\n"++show as) False = undefined --- | trace ("HERE! "++show p++"\n"++show as) False = undefined #if 0 | uniqueID as == 4 && trace ("HERE! "++show p++"\n"++show as) False = undefined | uniqueID as == 9 && trace ("HERE! "++show p++"\n"++show as) False = undefined | uniqueID as == 11 && trace ("HERE! "++show p++"\n"++show as) False = undefined #endif --- | otherwise = unsafePerformIO $! do | otherwise = unsafePerformIO $ do --- | otherwise = trace ("BUHGO!") $ unsafePerformIO $ do --- | otherwise = trace ("BUHGO!") $ unsafeDupablePerformIO $ do let p0 = p p1 <- if doDelay as then dly p0 b else return p0 #if USE_TRACE_PATNODE p2 <- if doTrace as then trc p1 b msg_trc else return p1 #else let p2 = p1 #endif #if USE_PING_PATNODE p3 <- if doPing as then png p2 b msg_png else return p2 #else let p3 = p2 #endif #if USE_DIE_PATNODE p4 <- if doDie as then die p3 b msg_die else return p3 #else let p4 = p3 #endif #if USE_TIMING_PATNODE p5 <- if doTiming as then timing p4 b msg_timing else return p4 #else let p5 = p4 #endif return $! Node p5 [] | otherwise = Node p [] -- don't forget! --- | otherwise = p -- don't forget! --- | otherwise = True -- don't forget! where #if 1 b = False -- WORKED for Ping/png; not working for Trace/trc... #else b = unsafePerformIO $ ( randomIO :: IO Bool ) -- WORKS!!! (even though value is constant!) #endif {-# NOINLINE dly #-} -- XXX crucial dly p b --- | trace "dly msg!" False = undefined | otherwise = do if b then do !_ <- threadDelay $ delayus as return p -- return $ not b else do !_ <- threadDelay $ delayus as return p -- return ' #if USE_TRACE_PATNODE msg_trc = "NFDataP: TRACE: " ++ show (uniqueID as) #if ! HASKELL98_FRAGMENT ++ " " ++ show (typeOf x) #if HANDLE_ATTRS_DATA_CONSTRAINT ++ "\n" ++ showRose (shapeOf x) #endif #endif {-# NOINLINE trc #-} -- XXX crucial trc p b msg --- | trace "trc msg!" False = undefined | otherwise = do if b then do --- !_ <- forkIO $ return (trace msg ()) --- !_ <- forkIO (return (trace msg ())) !_ <- trace msg $ return () return p -- return $ not b else do --- !_ <- forkIO $ return (trace msg ()) --- !_ <- forkIO (return (trace msg ())) !_ <- trace msg $ return () return p -- return ' #endif #if USE_PING_PATNODE msg_png = "NFDataP: PING: " ++ show (uniqueID as) #if ! HASKELL98_FRAGMENT ++ " " ++ show (typeOf x) #if HANDLE_ATTRS_DATA_CONSTRAINT ++ "\n" ++ showRose (shapeOf x) #endif #endif {-# NOINLINE png #-} -- XXX crucial -- Consider mkWeakThreadId :: ThreadId -> IO (Weak ThreadId) png p b msg --- | trace "png msg!" False = undefined #if 1 | isNothing mpngtid = do -- b <- randomIO :: IO Bool --- let b = False in if b then do return p -- return $ not b else do return p -- return b #else | isNothing mpngtid = False #endif | otherwise = do -- b <- randomIO :: IO Bool --- let b = False in if b then do !_ <- forkIO $ throw $ DeepSeqBounded_PingException msg --- putStrLn "Carrying on FALSE ..." return p -- return $ not b else do -- This worked! (exception thrown, yet continues) -- Getting repeatable actions still eludes... -- evaluate (unsafeInterleaveIO (do -- evaluate (unsafeDupablePerformIO (do !_ <- forkIO $ throw $ DeepSeqBounded_PingException msg --- putStrLn "Carrying on TRUE ..." return p -- return b where mpngtid = pingParentTID as #endif #if USE_DIE_PATNODE msg_die = "NFDataP: DIE: " ++ show (uniqueID as) #if ! HASKELL98_FRAGMENT ++ " " ++ show (typeOf x) #if HANDLE_ATTRS_DATA_CONSTRAINT ++ "\n" ++ showRose (shapeOf x) #endif #endif {-# NOINLINE die #-} -- XXX crucial (except perhaps in this die case...) die p b msg = do if b then do putStrLn msg >> myThreadId >>= killThread return p -- return $ not b else do putStrLn msg >> myThreadId >>= killThread return p -- return b #endif #if USE_TIMING_PATNODE msg_timing = "NFDataP: TIMING: " ++ show (uniqueID as) #if ! HASKELL98_FRAGMENT ++ " " ++ show (typeOf x) #if HANDLE_ATTRS_DATA_CONSTRAINT ++ "\n" ++ showRose (shapeOf x) #endif #endif {-# NOINLINE timing #-} timing p b msg = do if b then do -- ... XXX return p -- return $ not b else do -- ... XXX return p -- return b #endif as = getPatNodeAttrs p -- XXX THIS IS BAD (bottleneck) -- [See 000-readme, cotemp 20150104.] -- Is there not a simpler way to get at the PatNodeAttr? -- One thing could do, is put the node type (WR, etc.) -- in PatNodeAttrs, and then PatNode = PatNodeAttrs. -- There's no real disadvantage, right? -- we can still -- pattern match almost as do now: -- (Node WR{} cs) -- now -- (Node PN{nodeKind=WR} cs) -- hopefully! #endif ------------------------------------------------------------------------------- #if USE_PSEQ_PATNODE -- Note that, if USE_PSEQ_PATNODE flag is True, then Control.Parallel.pseq -- is used instead of Prelude.seq, whether or not a >cdba permutation was -- specified. I'd kinda rather continue to use seq for the cases where -- no permutation was specified... pseq_condition :: Pattern -> [()] -> () --pseq_condition :: [Pattern] -> [()] -> () --pseq_condition :: [Pattern] -> [ Pattern -> x -> () ] -> () --pseq_condition :: [Pattern] -> [Pattern -> x -> ()] -> [Pattern -> x -> ()] #if 0 #elif 1 pseq_condition pat@(Node pn cs) fs | isNothing mperm = foldr seq () fs | otherwise = foldr pseq () $ map (\i->(fs!!i)) perm where mperm = pseqPerm $ getPatNodeAttrs pn perm = fromJust mperm #elif 0 pseq_condition pat@(Node pn cs) fs = foldr pseq () fs' -- is foldr the right fold? where mperm = pseqPerm $ getPatNodeAttrs pn perm = fromJust mperm fs' | isNothing mperm = fs | otherwise = map (\i->(fs!!i)) perm #elif 0 pseq_condition pats fs = foldr seq () fs -- is foldr the right fold? #endif #endif -------------------------------------------------------------------------------
infix 3 # data T : Type where (#) : T -> T -> T leaf : T
{-# OPTIONS --rewriting --confluence-check #-} module Issue4333.N1 where open import Issue4333.M {-# REWRITE p₁ #-} b₁' : B a₁' b₁' = b
# See https://en.wikipedia.org/wiki/Complex_number expressions = [ :(sqrt(-1+0im)) :(exp(π * im) + 1) :(sin(im)) :(acos(2+0im)) :(asin(2+0im)) :(atan(1+2im)) :(log(-1+0im)) :(log(-im)) ] for expr in expressions println("[] :julia-answer \"\"\"", escape_string(string(expr)), " = ", eval(expr), "\"\"\".") end
{-# OPTIONS --without-K #-} open import HoTT open import cohomology.Exactness open import cohomology.FunctionOver module cohomology.ProductRepr where {- Given the following commutative diagram of homomorphisms, H₁ i₁ i₂ H₂ ↘ ↙ id ↓ G ↓ id ↙ ↘ H₁ j₁ j₂ H₂ - there exists an isomorphism G == H₁ × H₂ such that i₁,i₂ correspond - to the natural injections and j₁,j₂ correspond to the natural - projections. -} module ProductRepr {i j} {G : Group (lmax i j)} {H₁ : Group i} {H₂ : Group j} (i₁ : H₁ →ᴳ G) (i₂ : H₂ →ᴳ G) (j₁ : G →ᴳ H₁) (j₂ : G →ᴳ H₂) (p₁ : ∀ h₁ → GroupHom.f j₁ (GroupHom.f i₁ h₁) == h₁) (p₂ : ∀ h₂ → GroupHom.f j₂ (GroupHom.f i₂ h₂) == h₂) (ex₁ : is-exact (GroupHom.⊙f i₁) (GroupHom.⊙f j₂)) (ex₂ : is-exact (GroupHom.⊙f i₂) (GroupHom.⊙f j₁)) where zero-ker : (g : Group.El G) → GroupHom.f (×ᴳ-hom-in j₁ j₂) g == Group.ident (H₁ ×ᴳ H₂) → g == Group.ident G zero-ker g q = Trunc-rec (Group.El-level G _ _) (lemma g (fst×= q)) (ktoi ex₁ g (snd×= q)) where lemma : (g : Group.El G) (r : GroupHom.f j₁ g == Group.ident H₁) → Σ (Group.El H₁) (λ h → GroupHom.f i₁ h == g) → g == Group.ident G lemma ._ r (h , idp) = ap (GroupHom.f i₁) (! (p₁ h) ∙ r) ∙ GroupHom.pres-ident i₁ β₁ : (h₁ : Group.El H₁) (h₂ : Group.El H₂) → GroupHom.f j₁ (Group.comp G (GroupHom.f i₁ h₁) (GroupHom.f i₂ h₂)) == h₁ β₁ h₁ h₂ = GroupHom.pres-comp j₁ (GroupHom.f i₁ h₁) (GroupHom.f i₂ h₂) ∙ ap2 (Group.comp H₁) (p₁ h₁) (itok ex₂ _ [ h₂ , idp ]) ∙ Group.unitr H₁ h₁ β₂ : (h₁ : Group.El H₁) (h₂ : Group.El H₂) → GroupHom.f j₂ (Group.comp G (GroupHom.f i₁ h₁) (GroupHom.f i₂ h₂)) == h₂ β₂ h₁ h₂ = GroupHom.pres-comp j₂ (GroupHom.f i₁ h₁) (GroupHom.f i₂ h₂) ∙ ap2 (Group.comp H₂) (itok ex₁ _ [ h₁ , idp ]) (p₂ h₂) ∙ Group.unitl H₂ h₂ iso : G == H₁ ×ᴳ H₂ iso = surj-inj-= (×ᴳ-hom-in j₁ j₂) (zero-kernel-injective (×ᴳ-hom-in j₁ j₂) zero-ker) (λ {(h₁ , h₂) → [ Group.comp G (GroupHom.f i₁ h₁) (GroupHom.f i₂ h₂) , pair×= (β₁ h₁ h₂) (β₂ h₁ h₂) ]}) fst-over : j₁ == ×ᴳ-fst [ (λ U → U →ᴳ H₁) ↓ iso ] fst-over = domain-over-iso _ _ _ _ $ domain-over-equiv fst _ snd-over : j₂ == ×ᴳ-snd {G = H₁} [ (λ U → U →ᴳ H₂) ↓ iso ] snd-over = domain-over-iso _ _ _ _ $ domain-over-equiv snd _ inl-over : i₁ == ×ᴳ-inl [ (λ V → H₁ →ᴳ V) ↓ iso ] inl-over = codomain-over-iso _ _ _ _ $ codomain-over-equiv (GroupHom.f i₁) _ ▹ λ= (λ h₁ → pair×= (p₁ h₁) (itok ex₁ _ [ h₁ , idp ])) inr-over : i₂ == ×ᴳ-inr {G = H₁} [ (λ V → H₂ →ᴳ V) ↓ iso ] inr-over = codomain-over-iso _ _ _ _ $ codomain-over-equiv (GroupHom.f i₂) _ ▹ λ= (λ h₂ → pair×= (itok ex₂ _ [ h₂ , idp ]) (p₂ h₂)) {- Given additionally maps i₀ j₀ K –––→ G ––→ L - such that j₀∘i₀ = 0, we have j₀(i₁(j₁(i₀ k)))⁻¹ = j₀(i₂(j₂(i₀ k))). - (This is called the hexagon lemma in Eilenberg & Steenrod's book. - The hexagon is not visible in this presentation.) -} module HexagonLemma {k l} {K : Group k} {L : Group l} (i₀ : K →ᴳ G) (j₀ : G →ᴳ L) (ex₀ : ∀ g → GroupHom.f j₀ (GroupHom.f i₀ g) == Group.ident L) where decomp : ∀ g → Group.comp G (GroupHom.f i₁ (GroupHom.f j₁ g)) (GroupHom.f i₂ (GroupHom.f j₂ g)) == g decomp = transport (λ {(G' , i₁' , i₂' , j₁' , j₂') → ∀ g → Group.comp G' (GroupHom.f i₁' (GroupHom.f j₁' g)) (GroupHom.f i₂' (GroupHom.f j₂' g)) == g}) (! (pair= iso (↓-×-in inl-over (↓-×-in inr-over (↓-×-in fst-over snd-over))))) (λ {(h₁ , h₂) → pair×= (Group.unitr H₁ h₁) (Group.unitl H₂ h₂)}) cancel : ∀ k → Group.comp L (GroupHom.f (j₀ ∘ᴳ i₁ ∘ᴳ j₁ ∘ᴳ i₀) k) (GroupHom.f (j₀ ∘ᴳ i₂ ∘ᴳ j₂ ∘ᴳ i₀) k) == Group.ident L cancel k = ! (GroupHom.pres-comp j₀ _ _) ∙ ap (GroupHom.f j₀) (decomp (GroupHom.f i₀ k)) ∙ ex₀ k inv₁ : ∀ k → Group.inv L (GroupHom.f (j₀ ∘ᴳ i₁ ∘ᴳ j₁ ∘ᴳ i₀) k) == GroupHom.f (j₀ ∘ᴳ i₂ ∘ᴳ j₂ ∘ᴳ i₀) k inv₁ k = group-inv-unique-r L _ _ (cancel k) inv₂ : ∀ k → Group.inv L (GroupHom.f (j₀ ∘ᴳ i₂ ∘ᴳ j₂ ∘ᴳ i₀) k) == GroupHom.f (j₀ ∘ᴳ i₁ ∘ᴳ j₁ ∘ᴳ i₀) k inv₂ k = group-inv-unique-l L _ _ (cancel k)
The real number $1$ is equal to the complex number $1$.
lemma coeff_pcompose_semiring_closed: assumes "\<And>i. coeff p i \<in> R" "\<And>i. coeff q i \<in> R" shows "coeff (pcompose p q) i \<in> R"
# Copyright (c) 2018-2020, Carnegie Mellon University # See LICENSE for details UnparseQASM := function (spl) PrintTo("./qspiralout", spl); Exec( "./namespaces/packages/quantum/unparser/bin/unparser ./qspiralout"); end;
module Data.List.Primitive where -- In Agda 2.2.10 and below, there's no FFI binding for the stdlib -- List type, so we have to roll our own. This will change. data #List (X : Set) : Set where [] : #List X _∷_ : X → #List X → #List X {-# COMPILED_DATA #List [] [] (:) #-}
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "compearth.h" #include "cmopad.h" #ifdef COMPEARTH_USE_MKL #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreserved-id-macro" #pragma clang diagnostic ignored "-Wstrict-prototypes" #endif #include <mkl_cblas.h> #ifdef __clang__ #pragma clang diagnostic pop #endif #else #include <cblas.h> #endif struct mt_struct { double mt[6]; double tax[3]; double bax[3]; double pax[3]; double sdr1[3]; //strike dip rake; fault plane 2 double sdr2[3]; //strike dip rake; fault plane 1 double mag; double exp; }; /* int compearth_standardDecomposition(const int nmt, const double *__restrict__ M, enum compearthCoordSystem_enum basis, double *__restrict__ M0, double *__restrict__ Mw, double *__restrict__ fp1, double *__restrict__ fp2, double *__restrict__ pAxis, double *__restrict__ bAxis, double *__restrict__ tAxis, double *__restrict__ isoPct, double *__restrict__ devPct, double *__restrict__ dcPct, double *__restrict__ clvdPct); */ int decompose(const int nmt, const double mtUSE[6]); int decompose(const int nmt, const double mtUSE[6]) { //double K[3], N[3], S[3], lam[3], U[9], Uuse[9], b[3], p[3], t[3], //double gamma, delta, M0, kappa, theta, sigma, thetadc, // k2, d2, s2; struct cmopad_struct src; const char *fcnm = "decompose\0"; enum cmopad_basis_enum cin, cloc; double M[3][3], pax[3], bax[3], tax[3]; int i, ierr; const int iverb = 0; /* //------------------------------------------------------------------------// // Do the cMoPaD decomposition // //------------------------------------------------------------------------// // Copy moment tensor M[0][0] = mtUSE[0]; //Mrr M[1][1] = mtUSE[1]; //Mtt M[2][2] = mtUSE[2]; //Mpp M[0][1] = M[1][0] = mtUSE[3]; //Mrt M[0][2] = M[2][0] = mtUSE[4]; //Mrp M[1][2] = M[2][1] = mtUSE[5]; //Mtp // Mopad works in North, East, Down frame but inversion is Up, South, East cin = USE; cloc = NED; cmopad_basis_transformMatrixM33(M, cin, cloc); //USE -> NED // Compute the isotropic, CLVD, DC decomposition ierr = cmopad_standardDecomposition(M, &src); if (ierr != 0) { printf("%s: Error in decomposition!\n", fcnm); return EXIT_FAILURE; } // Compute the princple axes with corresponding strikes, dips, and rakes ierr = cmopad_MT2PrincipalAxisSystem(iverb, &src); if (ierr != 0) { printf("%s: Error computing principal axis\n",fcnm); return EXIT_FAILURE; } // Compute the pressure, null, and, tension principal axes as len,az,plunge cin = NED; //MoPaD is in north, east, down ierr = cmopad_Eigenvector2PrincipalAxis(cin, src.eig_pnt[0], src.p_axis, pax); if (ierr != 0) { printf("%s: Error converting pax\n",fcnm); return EXIT_FAILURE; } ierr = cmopad_Eigenvector2PrincipalAxis(cin, src.eig_pnt[1], src.null_axis, bax); if (ierr != 0){ printf("%s: Error converting bax\n",fcnm); return EXIT_FAILURE; } ierr = cmopad_Eigenvector2PrincipalAxis(cin, src.eig_pnt[2], src.t_axis, tax); if (ierr != 0) { printf("%s: Error converting tax\n",fcnm); return EXIT_FAILURE; } */ //printf("%f %f %f %f %f %f\n", // mtUSE[0], mtUSE[1], mtUSE[2], mtUSE[3], mtUSE[4], mtUSE[5]); //ierr = compearth_CMT2TT(1, mtUSE, false, // &gamma, &delta, &M0, // &kappa, &theta, &sigma, // K, N, S, &thetadc, // lam, U); //if (ierr != 0) //{ // fprintf(stderr, "%s: CMT2TT failed\n", __func__); // return EXIT_FAILURE; //} /* // Need to switch from SEU to USE. This requires computing // R U inv(R) where: // R = [0 0 1 // 1 0 0 // 0 1 0] // Carrying through the multiplication yields the permutation // U_{use} = [U_{33} U_{31} U_{32} // U_{13} U_{11} U_{12} // U_{23} U_{21} U_{22}] // // Permute the column major matrix Uuse[0] = U[8]; Uuse[1] = U[6]; Uuse[2] = U[7]; Uuse[3] = U[2]; Uuse[4] = U[0]; Uuse[5] = U[1]; Uuse[6] = U[5]; Uuse[7] = U[3]; Uuse[8] = U[4]; printf("%f %f %f\n%f %f %f\n%f %f %f\n", U[0], U[3], U[6], U[1], U[4], U[7], U[2], U[5], U[8]); */ //ierr = compearth_U2pa(1, U, // &p[2], &p[1], &b[2], &b[1], &t[2], &t[1]); //if (ierr != 0) //{ // fprintf(stderr, "%s: Error converting u to plunge/azimuth\n", // __func__); // return EXIT_FAILURE; //} //// Fill in the eigenvalues //p[0] = lam[0]; //b[0] = lam[1]; //t[0] = lam[2]; //printf("p: %e %f %f\n", p[0], p[1], p[2]); //printf("b: %e %f %f\n", b[0], b[1], b[2]); //printf("t: %e %f %f\n", t[0] ,t[1], t[2]); // Compute the auxiliary fault plane //ierr = compearth_auxiliaryPlane(1, &kappa, &theta, &sigma, // &k2, &d2, &s2); // Just define some convention where smaller strike goes first //printf("%e %f %f %f\n", M0, kappa, theta, sigma); //printf("%f %f %f\n", k2, d2, s2); //------------------------------------------------------------------------// // do the standard decomposition // //------------------------------------------------------------------------// //double pAxis[3], bAxis[3], tAxis[3], fp1[3], fp2[3], isoPct, dcPct, devPct, clvdPct, Mw; double *pAxis, *bAxis, *tAxis, *fp1, *fp2, *isoPct, *dcPct, *devPct, *clvdPct, *Mw, *M0; M0 = (double *) calloc((size_t) nmt, sizeof(double)); Mw = (double *) calloc((size_t) nmt, sizeof(double)); fp1 = (double *) calloc((size_t) (3*nmt), sizeof(double)); fp2 = (double *) calloc((size_t) (3*nmt), sizeof(double)); pAxis = (double *) calloc((size_t) (3*nmt), sizeof(double)); bAxis = (double *) calloc((size_t) (3*nmt), sizeof(double)); tAxis = (double *) calloc((size_t) (3*nmt), sizeof(double)); isoPct = (double *) calloc((size_t) nmt, sizeof(double)); devPct = (double *) calloc((size_t) nmt, sizeof(double)); dcPct = (double *) calloc((size_t) nmt, sizeof(double)); clvdPct = (double *) calloc((size_t) nmt, sizeof(double)); ierr = compearth_standardDecomposition(nmt, mtUSE, CE_USE, M0, Mw, fp1, fp2, pAxis, bAxis, tAxis, isoPct, devPct, dcPct, clvdPct); if (ierr != 0) { fprintf(stderr, "Failed to compute standard decomposition\n"); return EXIT_FAILURE; } for (i=0; i<nmt; i++) { //--------------------------------------------------------------------// // Do the cMoPaD decomposition // //--------------------------------------------------------------------// // Copy moment tensor M[0][0] = mtUSE[6*i+0]; //Mrr M[1][1] = mtUSE[6*i+1]; //Mtt M[2][2] = mtUSE[6*i+2]; //Mpp M[0][1] = M[1][0] = mtUSE[6*i+3]; //Mrt M[0][2] = M[2][0] = mtUSE[6*i+4]; //Mrp M[1][2] = M[2][1] = mtUSE[6*i+5]; //Mtp // Mopad works in North, East, Down cin = USE; cloc = NED; cmopad_basis_transformMatrixM33(M, cin, cloc); //USE -> NED // Compute the isotropic, CLVD, DC decomposition ierr = cmopad_standardDecomposition(M, &src); if (ierr != 0) { printf("%s: Error in decomposition!\n", fcnm); return EXIT_FAILURE; } // Compute the princple axes and strikes, dips, and rakes ierr = cmopad_MT2PrincipalAxisSystem(iverb, &src); if (ierr != 0) { printf("%s: Error computing principal axis\n",fcnm); return EXIT_FAILURE; } // Compute the pressure, null, and, tension principal axes as // len,az,plunge cin = NED; //MoPaD is in north, east, down ierr = cmopad_Eigenvector2PrincipalAxis(cin, src.eig_pnt[0], src.p_axis, pax); if (ierr != 0) { printf("%s: Error converting pax\n",fcnm); return EXIT_FAILURE; } ierr = cmopad_Eigenvector2PrincipalAxis(cin, src.eig_pnt[1], src.null_axis, bax); if (ierr != 0) { printf("%s: Error converting bax\n",fcnm); return EXIT_FAILURE; } ierr = cmopad_Eigenvector2PrincipalAxis(cin, src.eig_pnt[2], src.t_axis, tax); if (ierr != 0) { printf("%s: Error converting tax\n",fcnm); return EXIT_FAILURE; } // Check it //printf("%d %d %e\n", i, i%9, Mw[i]); if (fabs(M0[i] - src.seismic_moment)/src.seismic_moment > 1.e-10) { fprintf(stderr, "failed M0 %f %f %e %d\n", M0[i], src.seismic_moment, fabs(M0[i] - src.seismic_moment)/src.seismic_moment, i); return EXIT_FAILURE; } if (fabs(Mw[i] - src.moment_magnitude) > 1.e-10) { fprintf(stderr, "failed Mw %f %f %d\n", Mw[i], src.moment_magnitude, i); return EXIT_FAILURE; } if (fabs(isoPct[i] - src.ISO_percentage) > 1.e-10) { fprintf(stderr, "Failed iso pct %f %f\n", isoPct[i], src.ISO_percentage); return EXIT_FAILURE; } if (fabs(dcPct[i] - src.DC_percentage) > 1.e-10) { fprintf(stderr, "Failed DC pct %f %f %d\n", dcPct[i], src.DC_percentage, i); return EXIT_FAILURE; } if (fabs(devPct[i] - src.DEV_percentage) > 1.e-10) { fprintf(stderr, "Failed dev pct %f %f\n", devPct[i], src.DEV_percentage); return EXIT_FAILURE; } if (fabs(clvdPct[i] - src.CLVD_percentage) > 1.e-10) { fprintf(stderr, "Failed clvd pct %f %f\n", devPct[i], src.CLVD_percentage); return EXIT_FAILURE; } // Swap fault planes if (fabs(fp1[3*i+0] - src.fp1[0]) > 1.e-10) { if (fabs(fp1[3*i+0] - src.fp2[0]) > 1.e-10) { fprintf(stderr, "Failed strike 1 %f %f\n", fp1[3*i+0], src.fp2[0]); return EXIT_FAILURE; } if (fabs(fp1[3*i+1] - src.fp2[1]) > 1.e-10) { fprintf(stderr, "Failed dip 1 %f %f\n", fp1[3*i+1], src.fp2[1]); return EXIT_FAILURE; } if (fabs(fp1[3*i+2] - src.fp2[2]) > 1.e-10) { fprintf(stderr, "Failed rake 1 %f %f\n", fp1[3*i+2], src.fp2[2]); return EXIT_FAILURE; } if (fabs(fp2[3*i+0] - src.fp1[0]) > 1.e-10) { fprintf(stderr, "Failed strike 2 %f %f\n", fp2[3*i+0], src.fp1[0]); return EXIT_FAILURE; } if (fabs(fp2[3*i+1] - src.fp1[1]) > 1.e-10) { fprintf(stderr, "Failed dip 2 %f %f\n", fp2[3*i+1], src.fp1[1]); return EXIT_FAILURE; } if (fabs(fp2[3*i+2] - src.fp1[2]) > 1.e-10) { fprintf(stderr, "Failed rake 2 %f %f\n", fp2[3*i+2], src.fp1[2]); return EXIT_FAILURE; } } else { if (fabs(fp1[3*i+0] - src.fp1[0]) > 1.e-10) { fprintf(stderr, "Failed strike 1 %f %f\n", fp1[3*i+0], src.fp1[0]); return EXIT_FAILURE; } if (fabs(fp1[3*i+1] - src.fp1[1]) > 1.e-10) { fprintf(stderr, "Failed dip 1 %f %f\n", fp1[3*i+1], src.fp1[1]); return EXIT_FAILURE; } if (fabs(fp1[3*i+2] - src.fp1[2]) > 1.e-10) { fprintf(stderr, "Failed rake 1 %f %f\n", fp1[3*i+2], src.fp1[2]); return EXIT_FAILURE; } if (fabs(fp2[3*i+0] - src.fp2[0]) > 1.e-10) { fprintf(stderr, "Failed strike 2 %f %f\n", fp2[3*i+0], src.fp2[0]); return EXIT_FAILURE; } if (fabs(fp2[3*i+1] - src.fp2[1]) > 1.e-10) { fprintf(stderr, "Failed dip 2 %f %f\n", fp2[3*i+1], src.fp2[1]); return EXIT_FAILURE; } if (fabs(fp2[3*i+2] - src.fp2[2]) > 1.e-10) { fprintf(stderr, "Failed rake 2 %f %f\n", fp2[3*i+2], src.fp2[2]); return EXIT_FAILURE; } } if (fabs(pAxis[3*i+0] - pax[0]) > 1.e-10 || fabs(pAxis[3*i+1] - pax[1]) > 1.e-10 || fabs((pAxis[3*i+2] - pax[2])/pax[2]) > 1.e-10) { fprintf(stderr, "failed pressure axix: %f %f %f %f %f %f\n", pAxis[0], pAxis[1], pAxis[2], pax[0], pax[1], pax[2]); return EXIT_FAILURE; } if (fabs(bAxis[3*i+0] - bax[0]) > 1.e-10 || fabs(bAxis[3*i+1] - bax[1]) > 1.e-10 || fabs((bAxis[3*i+2] - bax[2])/bax[2]) > 1.e-10) { fprintf(stderr, "Failed null axis: %f %f %f %f %f %f\n", bAxis[0], bAxis[1], bAxis[2], bax[0], bax[1], bax[2]); return EXIT_FAILURE; } if (fabs(tAxis[3*i+0] - tax[0]) > 1.e-10 || fabs(tAxis[3*i+1] - tax[1]) > 1.e-10 || fabs((tAxis[3*i+2] - tax[2])/tax[2]) > 1.e-10) { fprintf(stderr, "Failed tension axis %f %f %f %f %f %f\n", tAxis[0], tAxis[1], tAxis[2], tax[0], tax[1], tax[2]); return EXIT_FAILURE; } if (nmt == 1) { printf("Summary:\n"); printf("Mw: %f\n", Mw[i]); printf("(strike,dip,rake): (%f,%f,%f)\n", fp1[3*i+0], fp1[3*i+1], fp1[3*i+2]); printf("(strike,dip,rake): (%f,%f,%f)\n", fp2[3*i+0], fp2[3*i+1], fp2[3*i+2]); printf("iso pct: %f\n", isoPct[i]); printf("dc pct: %f\n", dcPct[i]); printf("dev pct: %f\n", devPct[i]); printf("clvd pct: %f\n", clvdPct[i]); printf("\n"); } } free(M0); free(Mw); free(fp1); free(fp2); free(pAxis); free(bAxis); free(tAxis); free(isoPct); free(devPct); free(dcPct); free(clvdPct); return EXIT_SUCCESS; } int main() { struct mt_struct mt; const int nmt = 21*CE_CHUNKSIZE - 1; double *mtTest = (double *) calloc((size_t) (6*nmt), sizeof(double)); //mtTest[2*6*CE_CHUNKSIZE]; double xscal; int ierr, jmt; const int n6 = 6; const int incx = 1; //-----------------------------------1------------------------------------// mt.exp = 23.0 - 7.0; mt.mag = 5.1; mt.mt[0] =-4.360; mt.mt[1] = 3.200; mt.mt[2] = 1.170; mt.mt[3] =-0.794; mt.mt[4] = 1.650; mt.mt[5] = 2.060; mt.sdr1[0] = 77.0; mt.sdr1[1] = 47.0; mt.sdr1[2] =-62.0; mt.sdr2[0] = 219.0; mt.sdr2[1] = 50.0; mt.sdr2[2] =-117.0; mt.tax[0] = 4.49; mt.tax[1] = 1.0; mt.tax[2] = 328.0; mt.bax[0] = 0.56; mt.bax[1] = 20.0; mt.bax[2] = 237.0; mt.pax[0] =-5.04; mt.pax[1] = 70.0; mt.pax[2] = 61.0; xscal = pow(10.0, mt.exp); cblas_dscal(n6, xscal, mt.mt, incx); cblas_dcopy(n6, mt.mt, 1, &mtTest[0], 1); // Perform decomposition ierr = decompose(1, mt.mt); if (ierr != EXIT_SUCCESS) { fprintf(stderr, "Error decomposiing 1\n"); return EXIT_FAILURE; } //--------------------------------------2----------------------------------// mt.exp = 23.0 - 7.0; mt.mag = 5.0; mt.mt[0] =-4.480; mt.mt[1] = 1.440; mt.mt[2] = 3.040; mt.mt[3] = 0.603; mt.mt[4] = 0.722; mt.mt[5] =-1.870; mt.sdr1[0] =316.0; mt.sdr1[1] = 44.0; mt.sdr1[2] =-105.0; mt.sdr2[0] = 157.0; mt.sdr2[1] = 48.0; mt.sdr2[2] =-76.0; mt.tax[0] = 4.28; mt.tax[1] = 2.0; mt.tax[2] = 237.0; mt.bax[0] = 0.37; mt.bax[1] = 10.0; mt.bax[2] = 327.0; mt.pax[0] =-4.66; mt.pax[1] = 79.0; mt.pax[2] =137.0; xscal = pow(10.0,mt.exp); cblas_dscal(n6, xscal, mt.mt, incx); cblas_dcopy(n6, mt.mt, 1, &mtTest[6], 1); // Perform decomposition ierr = decompose(1, mt.mt); if (ierr != EXIT_SUCCESS) { fprintf(stderr, "Error decomposiing 1\n"); return EXIT_FAILURE; } //------------------------------------3-----------------------------------// mt.exp = 23.0 - 7.0; mt.mag = 4.9; mt.mt[0] =-2.460; mt.mt[1] = 0.207; mt.mt[2] = 2.250; mt.mt[3] = 0.793; mt.mt[4] = 0.267; mt.mt[5] =-0.363; mt.sdr1[0] =335.0; mt.sdr1[1] = 46.0; mt.sdr1[2] =-113.0; mt.sdr2[0] = 186.0; mt.sdr2[1] = 49.0; mt.sdr2[2] =-68.0; mt.tax[0] = 2.32; mt.tax[1] = 2.0; mt.tax[2] = 261.0; mt.bax[0] = 0.38; mt.bax[1] = 16.0; mt.bax[2] = 351.0; mt.pax[0] =-2.70; mt.pax[1] = 74.0; mt.pax[2] =165.0; xscal = pow(10.0,mt.exp); cblas_dscal(n6, xscal, mt.mt, incx); cblas_dcopy(n6, mt.mt, 1, &mtTest[12], 1); ierr = decompose(1, mt.mt); if (ierr != EXIT_SUCCESS) { fprintf(stderr, "Error decomposing 3\n"); return EXIT_FAILURE; } //-----------------------------------4------------------------------------// mt.exp = 23.0 - 7.0; mt.mag = 4.9; mt.mt[0] =-2.270; mt.mt[1] = 0.058; mt.mt[2] = 2.210; mt.mt[3] = 0.079; mt.mt[4] =-0.737; mt.mt[5] = 0.246; mt.sdr1[0] =190.0; mt.sdr1[1] = 36.0; mt.sdr1[2] =-84.0; mt.sdr2[0] = 3.0; mt.sdr2[1] = 54.0; mt.sdr2[2] =-94.0; mt.tax[0] = 2.35; mt.tax[1] = 9.0; mt.tax[2] = 96.0; mt.bax[0] = 0.04; mt.bax[1] = 4.0; mt.bax[2] = 5.0; mt.pax[0] =-2.39; mt.pax[1] = 80.0; mt.pax[2] =253.0; xscal = pow(10.0,mt.exp); cblas_dscal(n6, xscal, mt.mt, incx); cblas_dcopy(n6, mt.mt, 1, &mtTest[18], 1); ierr = decompose(1, mt.mt); if (ierr != EXIT_SUCCESS) { fprintf(stderr, "Error dcomposing 4\n"); return EXIT_FAILURE; } //-----------------------------------5------------------------------------// mt.exp = 26.0 - 7.0; mt.mag = 6.5; mt.mt[0] = 0.745; mt.mt[1] =-0.036; mt.mt[2] =-0.709; mt.mt[3] =-0.242; mt.mt[4] =-0.048; mt.mt[5] = 0.208; mt.sdr1[0] =181.0; mt.sdr1[1] = 47.0; mt.sdr1[2] =114.0; mt.sdr2[0] = 328.0; mt.sdr2[1] = 48.0; mt.sdr2[2] = 67.0; mt.tax[0] = 0.82; mt.tax[1] = 73.0; mt.tax[2] = 166.0; mt.bax[0] =-0.05; mt.bax[1] = 17.0; mt.bax[2] = 344.0; mt.pax[0] =-0.77; mt.pax[1] = 1.0; mt.pax[2] = 74.0; xscal = pow(10.0,mt.exp); cblas_dscal(n6, xscal, mt.mt, incx); cblas_dcopy(n6, mt.mt, 1, &mtTest[24], 1); ierr = decompose(1, mt.mt); if (ierr != EXIT_SUCCESS) { fprintf(stderr, "Error decomposing 5\n"); return EXIT_FAILURE; } //-----------------------------------6------------------------------------// mt.exp = 24.0 - 7.0; mt.mag = 5.3; mt.mt[0] = 0.700; mt.mt[1] =-0.883; mt.mt[2] = 0.183; mt.mt[3] = 0.260; mt.mt[4] = 0.289; mt.mt[5] = 0.712; mt.sdr1[0] =329.0; mt.sdr1[1] = 54.0; mt.sdr1[2] =141.0; mt.sdr2[0] = 85.0; mt.sdr2[1] = 59.0; mt.sdr2[2] = 43.0; mt.tax[0] = 1.01; mt.tax[1] = 51.0; mt.tax[2] = 300.0; mt.bax[0] = 0.24; mt.bax[1] = 39.0; mt.bax[2] = 113.0; mt.pax[0] =-1.25; mt.pax[1] = 3.0; mt.pax[2] = 206.; xscal = pow(10.0,mt.exp); cblas_dscal(n6, xscal, mt.mt, incx); cblas_dcopy(n6, mt.mt, 1, &mtTest[30], 1); ierr = decompose(1, mt.mt); if (ierr != EXIT_SUCCESS) { fprintf(stderr, "Error decomposing 6\n"); return EXIT_FAILURE; } //-----------------------------------7------------------------------------// mt.exp = 23.0 - 7.0; mt.mag = 5.0; mt.mt[0] = 3.150; mt.mt[1] =-2.470; mt.mt[2] =-0.676; mt.mt[3] = 1.650; mt.mt[4] = 1.880; mt.mt[5] =-1.470; mt.sdr1[0] =252.0; mt.sdr1[1] = 28.0; mt.sdr1[2] =111.0; mt.sdr2[0] = 49.0; mt.sdr2[1] = 64.0; mt.sdr2[2] = 79.0; mt.tax[0] = 4.08; mt.tax[1] = 69.0; mt.tax[2] = 297.0; mt.bax[0] = 0.01; mt.bax[1] = 10.0; mt.bax[2] = 54.0; mt.pax[0] =-4.08; mt.pax[1] = 18.0; mt.pax[2] = 147.0; xscal = pow(10.0,mt.exp); cblas_dscal(n6, xscal, mt.mt, incx); cblas_dcopy(n6, mt.mt, 1, &mtTest[36], 1); ierr = decompose(1, mt.mt); if (ierr != EXIT_SUCCESS) { fprintf(stderr, "Error decomposing 7\n"); return EXIT_FAILURE; } //-----------------------------------8------------------------------------// mt.exp = 23.0 - 7.0; mt.mag = 4.8; mt.mt[0] =-1.870; mt.mt[1] = 0.488; mt.mt[2] = 1.380; mt.mt[3] =-0.057; mt.mt[4] = 0.600; mt.mt[5] = 0.664; mt.sdr1[0] = 36.0; mt.sdr1[1] = 38.0; mt.sdr1[2] =-76.0; mt.sdr2[0] = 199.0; mt.sdr2[1] = 53.0; mt.sdr2[2] =-101.0; mt.tax[0] = 1.80; mt.tax[1] = 8.0; mt.tax[2] = 296.0; mt.bax[0] = 0.18; mt.bax[1] = 9.0; mt.bax[2] = 205.0; mt.pax[0] =-1.99; mt.pax[1] = 78.0; mt.pax[2] = 69.0; xscal = pow(10.0,mt.exp); cblas_dscal(n6, xscal, mt.mt, incx); cblas_dcopy(n6, mt.mt, 1, &mtTest[42], 1); ierr = decompose(1, mt.mt); if (ierr != EXIT_SUCCESS) { fprintf(stderr, "Error decomposing 8\n"); return EXIT_FAILURE; } //-----------------------------------9------------------------------------// mt.exp = 23.0 - 7.0; mt.mag = 5.0; mt.mt[0] =-3.540; mt.mt[1] = 1.040; mt.mt[2] = 2.510; mt.mt[3] =-0.474; mt.mt[4] = 1.640; mt.mt[5] = 1.530; mt.sdr1[0] = 47.0; mt.sdr1[1] = 38.0; mt.sdr1[2] =-63.0; mt.sdr2[0] = 195.0; mt.sdr2[1] = 56.0; mt.sdr2[2] =-109.0; mt.tax[0] = 3.66; mt.tax[1] = 10.0; mt.tax[2] = 299.0; mt.bax[0] = 0.45; mt.bax[1] = 16.0; mt.bax[2] =206.0; mt.pax[0] =-4.10; mt.pax[1] = 71.0; mt.pax[2] = 58.0; xscal = pow(10.0,mt.exp); cblas_dscal(n6, xscal, mt.mt, incx); cblas_dcopy(n6, mt.mt, 1, &mtTest[48], 1); // now copy this for (jmt=9; jmt<nmt; jmt++) { cblas_dcopy(n6, &mtTest[6*((jmt-9)%9)], 1, &mtTest[6*jmt], 1); } ierr = decompose(1, mt.mt); if (ierr != EXIT_SUCCESS) { fprintf(stderr, "Error decompsoing 9\n"); return EXIT_FAILURE; } //-----------------------------Test 'em all-------------------------------// ierr = decompose(nmt, mtTest); if (ierr != EXIT_SUCCESS) { fprintf(stderr, "Error in bulk decomposition\n"); return EXIT_FAILURE; } fprintf(stdout, "Success!\n"); free(mtTest); return EXIT_SUCCESS; }
// // request_handler.hpp // ~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2012 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER_REQUEST_HANDLER_HPP #define HTTP_SERVER_REQUEST_HANDLER_HPP #ifdef _MSC_VER #include "targetver.h" #endif #include <string> #include <boost/noncopyable.hpp> #include <json_spirit.h> #include "connection_fwd.hpp" #include "shared_data.hpp" namespace http { namespace server { struct reply; struct request; /// The common handler for all incoming requests. class request_handler : private boost::noncopyable { public: /// Construct with a directory containing files to be served. explicit request_handler(const std::string& doc_root, game_server::shared_data& data); /// Handle a request and produce a reply. bool handle_request(const request& req, reply& rep, http::server::connection_ptr conn); // Handle post's. bool handle_post_tbs(const request& req, reply& rep, http::server::connection_ptr conn); bool handle_post_user(const request& req, reply& rep, http::server::connection_ptr conn); // Handle get bool handle_get(const request& req, reply& rep, http::server::connection_ptr conn); // Check message queue and reply based on that. bool check_messages(const std::string& user, reply& rep, http::server::connection_ptr conn); private: /// The directory containing the files to be served. std::string doc_root_; /// Perform URL-decoding on a string. Returns false if the encoding was /// invalid. static bool url_decode(const std::string& in, std::string& out); // Data (game/client lists) shared with the worker thread. game_server::shared_data& data_; }; } // namespace server } // namespace http #endif // HTTP_SERVER_REQUEST_HANDLER_HPP
\section{Beacon of Light}\label{prayer:beaconOfLight} \textbf{Cost:} 100 CP\\ \textbf{Requirements:} Disciple of Avior, 3 Piety Points \\ \textbf{Active, Prayer, Weapon, Repeatable, Source(50 Gold)}\\ Pray for 8 AP. You become engulfed in a radiant glow, shedding bright light in a radius of \passus{6}. You can then point at a creature of your choice, shooting a bolt of radiant light at them. This costs another 2 AP, and ends the effect of the prayer, including the lighting. The bolt is a ranged weapon attack with a range of \passus{12} that deals 1d12 radiant damage.\\ \\ Level Progression:\\ II: 500 CP, 7 Piety Points, you can shoot two bolts before the prayer ends\\ III: 1,000 CP, 12 Piety Points, you can shoot three bolts before the prayer ends\\ IV: 2,500 CP, 18 Piety Points, you can shoot four bolts before the prayer ends\\ V: 5,000 CP, 25 Piety Points, you can shoot five bolts before the prayer ends\\
From iris.proofmode Require Import tactics. From machine_program_logic.program_logic Require Import weakestpre. From HypVeri.algebra Require Import base pagetable mem trans. From HypVeri.rules Require Import rules_base ldr. From HypVeri.logrel Require Import logrel logrel_extra. From HypVeri Require Import proofmode. Import uPred. Section ftlr_ldr. Context `{hypconst:HypervisorConstants}. Context `{hypparams:!HypervisorParameters}. Context `{vmG: !gen_VMG Σ}. Lemma ftlr_ldr {i mem_acc_tx ai regs rxs ps_acc p_tx p_rx instr trans src dst} P: base_extra.is_total_gmap regs -> base_extra.is_total_gmap rxs -> {[p_tx; p_rx]} ⊆ ps_acc -> currently_accessible_in_trans_memory_pages i trans ⊆ ps_acc ∖ {[p_tx; p_rx]} -> p_rx ∉ ps_acc ∖ {[p_rx; p_tx]} ∪ accessible_in_trans_memory_pages i trans -> p_tx ∉ ps_acc ∖ {[p_rx; p_tx]} ∪ accessible_in_trans_memory_pages i trans -> regs !! PC = Some ai -> tpa ai ∈ ps_acc -> tpa ai ≠ p_tx -> dom mem_acc_tx = set_of_addr (ps_acc ∖ {[p_tx]}) -> tpa ai ∈ ps_acc ∖ {[p_tx]} -> mem_acc_tx !! ai = Some instr -> decode_instruction instr = Some (Ldr dst src) -> ⊢ ▷ (∀ (a : gmap reg_name Addr) (a0 : gset PID) (a1 : gmap Addr transaction) (a2 : gmap VMID (option (Addr * VMID))), ⌜base_extra.is_total_gmap a2⌝ -∗ ⌜base_extra.is_total_gmap a⌝ -∗ ⌜{[p_tx; p_rx]} ⊆ a0⌝ -∗ ⌜currently_accessible_in_trans_memory_pages i a1 ⊆ a0 ∖ {[p_tx; p_rx]}⌝ -∗ ⌜p_rx ∉ a0 ∖ {[p_rx; p_tx]} ∪ accessible_in_trans_memory_pages i a1⌝ -∗ ⌜p_tx ∉ a0 ∖ {[p_rx; p_tx]} ∪ accessible_in_trans_memory_pages i a1⌝ -∗ ([∗ map] r↦w ∈ a, r @@ i ->r w) -∗ TX@i:=p_tx -∗ p_tx -@O> - ∗ p_tx -@E> true -∗ mailbox.rx_page i p_rx -∗ i -@A> a0 -∗ pagetable_entries_excl_owned i (a0 ∖ {[p_rx; p_tx]} ∖ currently_accessible_in_trans_memory_pages i a1) -∗ transaction_hpool_global_transferred a1 -∗ transaction_pagetable_entries_transferred i a1 -∗ retrievable_transaction_transferred i a1 -∗ rx_state_get i a2 -∗ rx_states_global (delete i a2) -∗ transaction_pagetable_entries_owned i a1 -∗ retrieved_transaction_owned i a1 -∗ (∃ mem : lang.mem, memory_pages (a0 ∪ (accessible_in_trans_memory_pages i a1)) mem) -∗ (P a1 a2) -∗ WP ExecI @ i {{ _, True }}) -∗ ([∗ map] r↦w ∈ regs, r @@ i ->r w) -∗ TX@i:=p_tx -∗ p_tx -@O> - ∗ p_tx -@E> true -∗ i -@A> ps_acc -∗ pagetable_entries_excl_owned i (ps_acc ∖ {[p_rx; p_tx]} ∖ (currently_accessible_in_trans_memory_pages i trans)) -∗ transaction_hpool_global_transferred trans -∗ transaction_pagetable_entries_transferred i trans -∗ retrievable_transaction_transferred i trans -∗ rx_state_get i rxs -∗ mailbox.rx_page i p_rx -∗ rx_states_global (delete i rxs) -∗ transaction_pagetable_entries_owned i trans -∗ retrieved_transaction_owned i trans -∗ (∃ mem1 : mem, memory_pages ((ps_acc ∪ (accessible_in_trans_memory_pages i trans)) ∖ ps_acc) mem1) -∗ ([∗ map] k↦v ∈ mem_acc_tx, k ->a v) -∗ (∃ mem2 : mem, memory_page p_tx mem2) -∗ (P trans rxs) -∗ SSWP ExecI @ i {{ bm, (if bm.1 then VMProp_holds i (1 / 2) else True) -∗ WP bm.2 @ i {{ _, True }} }}. Proof. iIntros (Htotal_regs Htotal_rxs Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx Hlookup_PC Hin_ps_acc Hneq_ptx Hdom_mem_acc_tx Hin_ps_acc_tx Hlookup_mem_ai Heqn). iIntros "IH regs tx pgt_tx pgt_acc pgt_owned trans_hpool_global tran_pgt_transferred retri rx_state rx other_rx tran_pgt_owned retri_owned mem_rest mem_acc_tx mem_tx P". pose proof Heqn as Hdecode. apply decode_instruction_valid in Heqn. inversion Heqn as [| | ? ? Hvalid_dst Hvalid_src Hvalid_neq | | | | | | | | | ]. subst dst0 src0. unfold reg_valid_cond in Hvalid_dst, Hvalid_src. pose proof (Htotal_regs src) as [a_src Hlookup_src]. pose proof (Htotal_regs dst) as [w_dst Hlookup_dst]. (* getting registers *) iDestruct ((reg_big_sepM_split_upd3 i Hlookup_PC Hlookup_src Hlookup_dst) with "[$regs]") as "(PC & r_src & r_dst & Hacc_regs)"; [by destruct_and ! | by destruct_and ! | done | done |]. (* case analysis on src *) destruct (decide ((tpa a_src) ∈ ps_acc)) as [Hin' | Hin'']. { (* has access to the page, more cases.. *) destruct (decide((tpa a_src) = p_tx)). { (* trying to read from tx page, fail *) (* getting mem *) iDestruct (mem_big_sepM_split mem_acc_tx Hlookup_mem_ai with "[mem_acc_tx]") as "[mem_instr Hacc_mem_acc_tx]"; first done. iApply (ldr_access_tx (w3 := w_dst) ai a_src dst src with "[PC pgt_acc tx mem_instr r_src r_dst]"); iFrameAutoSolve. iNext. iIntros "(tx & PC & a_instr & r_src & acc & r_dst) _". by iApply wp_terminated. } { (* normal case *) destruct (decide (a_src = ai)) as [|Hneq'']. { (* exact same addr *) iDestruct (mem_big_sepM_split mem_acc_tx Hlookup_mem_ai with "[mem_acc_tx]") as "[mem_instr Hacc_mem_acc_tx]"; first done. iApply (ldr_same_addr (s := ps_acc) ai a_src dst src with "[PC mem_instr r_src r_dst tx pgt_acc]"); iFrameAutoSolve. { symmetry;done. } iNext. iIntros "(PC & mem_instr & r_src & r_dst & pgt_acc & tx) _". iDestruct ("Hacc_regs" with "[$PC $r_src $r_dst]") as (regs') "[%Htotal_regs' regs]";iFrame. iDestruct ("Hacc_mem_acc_tx" with "mem_instr") as "mem_acc_tx". iApply ("IH" $! _ ps_acc trans _ Htotal_rxs Htotal_regs' Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx with "regs tx pgt_tx rx pgt_acc pgt_owned trans_hpool_global tran_pgt_transferred retri rx_state other_rx tran_pgt_owned retri_owned [mem_rest mem_acc_tx mem_tx] P"). { iDestruct (memory_pages_split_singleton' p_tx ps_acc with "[mem_acc_tx $mem_tx]") as "mem_acc". set_solver + Hsubset_mb. iExists mem_acc_tx;by iFrame "mem_acc_tx". iApply (memory_pages_split_diff' _ ps_acc with "[$mem_rest $mem_acc]"). set_solver +. } } { (* different addresses *) destruct (decide ((tpa a_src) = (tpa ai))) as [Heqn'|]. { (* in same page *) pose proof Hin_ps_acc as Hin_ps_acc. rewrite <-Heqn' in Hin_ps_acc. assert (tpa a_src ∈ ps_acc ∖ {[p_tx]}) as Hin_ps_acc'. set_solver + Hin_ps_acc n. pose proof (elem_of_memory_pages_lookup _ _ _ Hin_ps_acc' Hdom_mem_acc_tx) as [w_src Hlookup_a_src]. iDestruct (mem_big_sepM_split2 mem_acc_tx Hneq'' Hlookup_a_src Hlookup_mem_ai with "[$mem_acc_tx]") as "[a_src [a_instr Hacc_mem_acc_tx]]". iApply (ldr_same_page (s := ps_acc) ai a_src dst src with "[PC a_instr a_src r_src r_dst tx pgt_acc]"); iFrameAutoSolve. set_solver. intro; apply Hneq''. symmetry;done. symmetry;done. iNext. iIntros "(PC & mem_instr & r_src & a_src & r_dst & pgt_acc & tx) _". iDestruct ("Hacc_regs" with "[$PC $r_src $r_dst]") as (regs') "[%Htotal_regs' regs]";iFrame. iDestruct ("Hacc_mem_acc_tx" with "[a_src mem_instr]") as "mem_acc_tx"; iFrame. iApply ("IH" $! _ ps_acc trans _ Htotal_rxs Htotal_regs' Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx with "regs tx pgt_tx rx pgt_acc pgt_owned trans_hpool_global tran_pgt_transferred retri rx_state other_rx tran_pgt_owned retri_owned [mem_rest mem_acc_tx mem_tx] P"). { iDestruct (memory_pages_split_singleton' p_tx ps_acc with "[mem_acc_tx $mem_tx]") as "mem_acc". set_solver + Hsubset_mb. iExists mem_acc_tx;by iFrame "mem_acc_tx". iApply (memory_pages_split_diff' _ ps_acc with "[$mem_rest $mem_acc]"). set_solver +. } } { (* in difference pages *) (* getting mem *) assert (tpa a_src ∈ ps_acc ∖ {[p_tx]}) as Hin_ps_acc'. set_solver + Hin' n. pose proof (elem_of_memory_pages_lookup _ _ _ Hin_ps_acc' Hdom_mem_acc_tx) as [w_src Hlookup_a_src]. iDestruct (mem_big_sepM_split2 mem_acc_tx Hneq'' Hlookup_a_src Hlookup_mem_ai with "[$mem_acc_tx]") as "[a_src [mem_instr Hacc_mem_acc_tx]]". iApply (ldr (s := ps_acc) ai a_src dst src with "[PC mem_instr a_src r_src r_dst tx pgt_acc]"); iFrameAutoSolve. { set_solver. } iNext. iIntros "(PC & mem_instr & r_src & a_src & r_dst & pgt_acc & tx) _". iDestruct ("Hacc_regs" with "[$PC $r_src $r_dst]") as (regs') "[%Htotal_regs' regs]";iFrame. iDestruct ("Hacc_mem_acc_tx" with "[a_src mem_instr]") as "mem_acc_tx"; iFrame. iApply ("IH" $! _ ps_acc trans _ Htotal_rxs Htotal_regs' Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx with "regs tx pgt_tx rx pgt_acc pgt_owned trans_hpool_global tran_pgt_transferred retri rx_state other_rx tran_pgt_owned retri_owned [mem_rest mem_acc_tx mem_tx] P"). { iDestruct (memory_pages_split_singleton' p_tx ps_acc with "[mem_acc_tx $mem_tx]") as "mem_acc". set_solver + Hsubset_mb. iExists mem_acc_tx;by iFrame "mem_acc_tx". iApply (memory_pages_split_diff' _ ps_acc with "[$mem_rest $mem_acc]"). set_solver +. } } } } } { (* no access to the page, apply ldr_error *) (* getting mem *) (* we don't update memory *) iDestruct (mem_big_sepM_split mem_acc_tx Hlookup_mem_ai with "[mem_acc_tx]") as "[mem_instr Hacc_mem_acc_tx]"; first done. iApply (ldr_no_access (s := ps_acc) ai a_src dst src with "[PC mem_instr r_src r_dst tx pgt_acc]"); iFrameAutoSolve. iNext. iIntros "(PC & mem_instr & r_src & pgt_acc & r_dst & tx) _". by iApply wp_terminated. } Qed. End ftlr_ldr.
Our network team scheduled a maintenance today (06-20-18) on links between DC3 and AMS1. Migration is scheduled on one link after another, which might cause saturation issues on other links still in production. We will update this status as the maintenance goes on.
------------------------------------------------------------------------------ -- Distributive laws on a binary operation: Task B ------------------------------------------------------------------------------ {-# OPTIONS --exact-split #-} {-# OPTIONS --no-sized-types #-} {-# OPTIONS --no-universe-polymorphism #-} {-# OPTIONS --without-K #-} module DistributiveLaws.TaskB-AllStepsATP where open import DistributiveLaws.Base open import Common.FOL.Relation.Binary.EqReasoning ------------------------------------------------------------------------------ -- We prove all the proof steps of DistributiveLaws.TaskB-I using the -- ATPs. prop₂ : ∀ u x y z → (x · y · (z · u)) · ((x · y · (z · u)) · (x · z · (y · u))) ≡ x · z · (y · u) prop₂ u x y z = xy·zu · (xy·zu · xz·yu) ≡⟨ j₁ ⟩ xy·zu · (x·zu · y·zu · xz·yu) ≡⟨ j₂ ⟩ xy·zu · (x·zu · xz·yu · (y·zu · xz·yu)) ≡⟨ j₃ ⟩ xy·zu · (xz·xu · xz·yu · (y·zu · xz·yu)) ≡⟨ j₄ ⟩ xy·zu · (xz · xu·yu · (y·zu · xz·yu)) ≡⟨ j₅ ⟩ xy·zu · (xz · xyu · (y·zu · xz·yu)) ≡⟨ j₆ ⟩ xy·zu · (xz · xyu · (yz·yu · xz·yu)) ≡⟨ j₇ ⟩ xy·zu · (xz · xyu · (yz·xz · yu)) ≡⟨ j₈ ⟩ xy·zu · (xz · xyu · (yxz · yu)) ≡⟨ j₉ ⟩ xy·zu · (xz · xyu · (yx·yu · z·yu)) ≡⟨ j₁₀ ⟩ xy·zu · (xz · xyu · (y·xu · z·yu)) ≡⟨ j₁₁ ⟩ xyz · xyu · (xz · xyu · (y·xu · z·yu)) ≡⟨ j₁₂ ⟩ xz·yz · xyu · (xz · xyu · (y·xu · z·yu)) ≡⟨ j₁₃ ⟩ xz · xyu · (yz · xyu) · (xz · xyu · (y·xu · z·yu)) ≡⟨ j₁₄ ⟩ xz · xyu · (yz · xyu · (y·xu · z·yu)) ≡⟨ j₁₅ ⟩ xz · xyu · (yz · xu·yu · (y·xu · z·yu)) ≡⟨ j₁₆ ⟩ xz · xyu · (y · xu·yu · (z · xu·yu) · (y·xu · z·yu)) ≡⟨ j₁₇ ⟩ xz · xyu · (y · xu·yu · (y·xu · z·yu) · (z · xu·yu · (y·xu · z·yu))) ≡⟨ j₁₈ ⟩ xz · xyu · (y·xu · y·yu · (y·xu · z·yu) · (z · xu·yu · (y·xu · z·yu))) ≡⟨ j₁₉ ⟩ xz · xyu · (y·xu · (y·yu · z·yu) · (z · xu·yu · (y·xu · z·yu))) ≡⟨ j₂₀ ⟩ xz · xyu · (y·xu · yz·yu · (z · xu·yu · (y·xu · z·yu))) ≡⟨ j₂₁ ⟩ xz · xyu · (y·xu · y·zu · (z · xu·yu · (y·xu · z·yu))) ≡⟨ j₂₂ ⟩ xz · xyu · (y · xu·zu · (z · xu·yu · (y·xu · z·yu))) ≡⟨ j₂₃ ⟩ xz · xyu · (y · xu·zu · (z·xu · z·yu · (y·xu · z·yu))) ≡⟨ j₂₄ ⟩ (xz · xyu) · (y · xu·zu · (z·xu · y·xu · z·yu)) ≡⟨ j₂₅ ⟩ xz · xyu · (y · xu·zu · (zy·xu · z·yu)) ≡⟨ j₂₆ ⟩ xz · xyu · (y · xu·zu · (zy·xu · zy·zu)) ≡⟨ j₂₇ ⟩ xz · xyu · (y · xu·zu · (zy · xu·zu)) ≡⟨ j₂₈ ⟩ xz · xyu · (y·zy · xu·zu) ≡⟨ j₂₉ ⟩ xz · xyu · (y·zy · xzu) ≡⟨ j₃₀ ⟩ xz·xy · xzu · (y·zy · xzu) ≡⟨ j₃₁ ⟩ x·zy · xzu · (y·zy · xzu) ≡⟨ j₃₂ ⟩ x·zy · y·zy · xzu ≡⟨ j₃₃ ⟩ xy·zy · xzu ≡⟨ j₃₄ ⟩ xzy · xzu ≡⟨ j₃₅ ⟩ xz·yu ∎ where -- Two variables abbreviations xz = x · z yu = y · u yz = y · z zy = z · y {-# ATP definitions xz yu yz zy #-} -- Three variables abbreviations xyu = x · y · u xyz = x · y · z xzu = x · z · u xzy = x · z · y yxz = y · x · z {-# ATP definitions xyu xyz xzu xzy yxz #-} x·yu = x · (y · u) x·zu = x · (z · u) x·zy = x · (z · y) {-# ATP definitions x·yu x·zu x·zy #-} y·xu = y · (x · u) y·yu = y · (y · u) y·zu = y · (z · u) y·zy = y · (z · y) {-# ATP definitions y·xu y·yu y·zu y·zy #-} z·xu = z · (x · u) z·yu = z · (y · u) {-# ATP definitions z·xu z·yu #-} -- Four variables abbreviations xu·yu = x · u · (y · u) xu·zu = x · u · (z · u) {-# ATP definitions xu·yu xu·zu #-} xy·yz = x · y · (y · z) xy·zu = x · y · (z · u) xy·zy = x · y · (z · y) {-# ATP definitions xy·yz xy·zu xy·zy #-} xz·xu = x · z · (x · u) xz·xy = x · z · (x · y) xz·yu = x · z · (y · u) xz·yz = x · z · (y · z) {-# ATP definitions xz·xu xz·xy xz·yu xz·yz #-} yx·yu = y · x · (y · u) {-# ATP definition yx·yu #-} yz·xz = y · z · (x · z) yz·yu = y · z · (y · u) {-# ATP definitions yz·xz yz·yu #-} zy·xu = z · y · (x · u) zy·zu = z · y · (z · u) {-# ATP definitions zy·xu zy·zu #-} -- Steps justifications postulate j₁ : xy·zu · (xy·zu · xz·yu) ≡ xy·zu · (x·zu · y·zu · xz·yu) {-# ATP prove j₁ #-} postulate j₂ : xy·zu · (x·zu · y·zu · xz·yu) ≡ xy·zu · (x·zu · xz·yu · (y·zu · xz·yu)) {-# ATP prove j₂ #-} postulate j₃ : xy·zu · (x·zu · xz·yu · (y·zu · xz·yu)) ≡ xy·zu · (xz·xu · xz·yu · (y·zu · xz·yu)) {-# ATP prove j₃ #-} postulate j₄ : xy·zu · (xz·xu · xz·yu · (y·zu · xz·yu)) ≡ xy·zu · (xz · xu·yu · (y·zu · xz·yu)) {-# ATP prove j₄ #-} postulate j₅ : xy·zu · (xz · xu·yu · (y·zu · xz·yu)) ≡ xy·zu · (xz · xyu · (y·zu · xz·yu)) {-# ATP prove j₅ #-} postulate j₆ : xy·zu · (xz · xyu · (y·zu · xz·yu)) ≡ xy·zu · (xz · xyu · (yz·yu · xz·yu)) {-# ATP prove j₆ #-} postulate j₇ : xy·zu · (xz · xyu · (yz·yu · xz·yu)) ≡ xy·zu · (xz · xyu · (yz·xz · yu)) {-# ATP prove j₇ #-} postulate j₈ : xy·zu · (xz · xyu · (yz·xz · yu)) ≡ xy·zu · (xz · xyu · (yxz · yu)) {-# ATP prove j₈ #-} postulate j₉ : xy·zu · (xz · xyu · (yxz · yu)) ≡ xy·zu · (xz · xyu · (yx·yu · z·yu)) {-# ATP prove j₉ #-} postulate j₁₀ : xy·zu · (xz · xyu · (yx·yu · z·yu)) ≡ xy·zu · (xz · xyu · (y·xu · z·yu)) {-# ATP prove j₁₀ #-} postulate j₁₁ : xy·zu · (xz · xyu · (y·xu · z·yu)) ≡ xyz · xyu · (xz · xyu · (y·xu · z·yu)) {-# ATP prove j₁₁ #-} postulate j₁₂ : xyz · xyu · (xz · xyu · (y·xu · z·yu)) ≡ xz·yz · xyu · (xz · xyu · (y·xu · z·yu)) {-# ATP prove j₁₂ #-} postulate j₁₃ : xz·yz · xyu · (xz · xyu · (y·xu · z·yu)) ≡ xz · xyu · (yz · xyu) · (xz · xyu · (y·xu · z·yu)) {-# ATP prove j₁₃ #-} postulate j₁₄ : xz · xyu · (yz · xyu) · (xz · xyu · (y·xu · z·yu)) ≡ xz · xyu · (yz · xyu · (y·xu · z·yu)) {-# ATP prove j₁₄ #-} postulate j₁₅ : xz · xyu · (yz · xyu · (y·xu · z·yu)) ≡ xz · xyu · (yz · xu·yu · (y·xu · z·yu)) {-# ATP prove j₁₅ #-} postulate j₁₆ : xz · xyu · (yz · xu·yu · (y·xu · z·yu)) ≡ xz · xyu · (y · xu·yu · (z · xu·yu) · (y·xu · z·yu)) {-# ATP prove j₁₆ #-} postulate j₁₇ : xz · xyu · (y · xu·yu · (z · xu·yu) · (y·xu · z·yu)) ≡ xz · xyu · (y · xu·yu · (y·xu · z·yu) · (z · xu·yu · (y·xu · z·yu))) {-# ATP prove j₁₇ #-} postulate j₁₈ : xz · xyu · (y · xu·yu · (y·xu · z·yu) · (z · xu·yu · (y·xu · z·yu))) ≡ xz · xyu · (y·xu · y·yu · (y·xu · z·yu) · (z · xu·yu · (y·xu · z·yu))) {-# ATP prove j₁₈ #-} postulate j₁₉ : xz · xyu · (y·xu · y·yu · (y·xu · z·yu) · (z · xu·yu · (y·xu · z·yu))) ≡ xz · xyu · (y·xu · (y·yu · z·yu) · (z · xu·yu · (y·xu · z·yu))) {-# ATP prove j₁₉ #-} postulate j₂₀ : xz · xyu · (y·xu · (y·yu · z·yu) · (z · xu·yu · (y·xu · z·yu))) ≡ xz · xyu · (y·xu · yz·yu · (z · xu·yu · (y·xu · z·yu))) {-# ATP prove j₂₀ #-} postulate j₂₁ : xz · xyu · (y·xu · yz·yu · (z · xu·yu · (y·xu · z·yu))) ≡ xz · xyu · (y·xu · y·zu · (z · xu·yu · (y·xu · z·yu))) {-# ATP prove j₂₁ #-} postulate j₂₂ : xz · xyu · (y·xu · y·zu · (z · xu·yu · (y·xu · z·yu))) ≡ xz · xyu · (y · xu·zu · (z · xu·yu · (y·xu · z·yu))) {-# ATP prove j₂₂ #-} postulate j₂₃ : xz · xyu · (y · xu·zu · (z · xu·yu · (y·xu · z·yu))) ≡ xz · xyu · (y · xu·zu · (z·xu · z·yu · (y·xu · z·yu))) {-# ATP prove j₂₃ #-} postulate j₂₄ : xz · xyu · (y · xu·zu · (z·xu · z·yu · (y·xu · z·yu))) ≡ (xz · xyu) · (y · xu·zu · (z·xu · y·xu · z·yu)) {-# ATP prove j₂₄ #-} postulate j₂₅ : (xz · xyu) · (y · xu·zu · (z·xu · y·xu · z·yu)) ≡ xz · xyu · (y · xu·zu · (zy·xu · z·yu)) {-# ATP prove j₂₅ #-} postulate j₂₆ : xz · xyu · (y · xu·zu · (zy·xu · z·yu)) ≡ xz · xyu · (y · xu·zu · (zy·xu · zy·zu)) {-# ATP prove j₂₆ #-} postulate j₂₇ : xz · xyu · (y · xu·zu · (zy·xu · zy·zu)) ≡ xz · xyu · (y · xu·zu · (zy · xu·zu)) {-# ATP prove j₂₇ #-} postulate j₂₈ : xz · xyu · (y · xu·zu · (zy · xu·zu)) ≡ xz · xyu · (y·zy · xu·zu) {-# ATP prove j₂₈ #-} postulate j₂₉ : xz · xyu · (y·zy · xu·zu) ≡ xz · xyu · (y·zy · xzu) {-# ATP prove j₂₉ #-} postulate j₃₀ : xz · xyu · (y·zy · xzu) ≡ xz·xy · xzu · (y·zy · xzu) {-# ATP prove j₃₀ #-} postulate j₃₁ : xz·xy · xzu · (y·zy · xzu) ≡ x·zy · xzu · (y·zy · xzu) {-# ATP prove j₃₁ #-} postulate j₃₂ : x·zy · xzu · (y·zy · xzu) ≡ x·zy · y·zy · xzu {-# ATP prove j₃₂ #-} postulate j₃₃ : x·zy · y·zy · xzu ≡ xy·zy · xzu {-# ATP prove j₃₃ #-} postulate j₃₄ : xy·zy · xzu ≡ xzy · xzu {-# ATP prove j₃₄ #-} postulate j₃₅ : xzy · xzu ≡ xz·yu {-# ATP prove j₃₅ #-}
[STATEMENT] lemma Lr_rec_in: assumes n: "n \<in> ns" shows "Lr ns n \<subseteq> {Inl -` tns \<union> (\<Union>{K n' | n'. Inr n' \<in> tns}) | tns K. (n,tns) \<in> P \<and> (\<forall> n'. Inr n' \<in> tns \<longrightarrow> K n' \<in> Lr (ns - {n}) n')}" (is "Lr ns n \<subseteq> {?F tns K | tns K. (n,tns) \<in> P \<and> ?\<phi> tns K}") [PROOF STATE] proof (prove) goal (1 subgoal): 1. Lr ns n \<subseteq> {Inl -` tns \<union> \<Union> {K n' |n'. Inr n' \<in> tns} |tns K. (n, tns) \<in> P \<and> (\<forall>n'. Inr n' \<in> tns \<longrightarrow> K n' \<in> Lr (ns - {n}) n')} [PROOF STEP] proof safe [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x. x \<in> Lr ns n \<Longrightarrow> \<exists>tns K. x = Inl -` tns \<union> \<Union> {K n' |n'. Inr n' \<in> tns} \<and> (n, tns) \<in> P \<and> (\<forall>n'. Inr n' \<in> tns \<longrightarrow> K n' \<in> Lr (ns - {n}) n') [PROOF STEP] fix ts [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x. x \<in> Lr ns n \<Longrightarrow> \<exists>tns K. x = Inl -` tns \<union> \<Union> {K n' |n'. Inr n' \<in> tns} \<and> (n, tns) \<in> P \<and> (\<forall>n'. Inr n' \<in> tns \<longrightarrow> K n' \<in> Lr (ns - {n}) n') [PROOF STEP] assume "ts \<in> Lr ns n" [PROOF STATE] proof (state) this: ts \<in> Lr ns n goal (1 subgoal): 1. \<And>x. x \<in> Lr ns n \<Longrightarrow> \<exists>tns K. x = Inl -` tns \<union> \<Union> {K n' |n'. Inr n' \<in> tns} \<and> (n, tns) \<in> P \<and> (\<forall>n'. Inr n' \<in> tns \<longrightarrow> K n' \<in> Lr (ns - {n}) n') [PROOF STEP] then [PROOF STATE] proof (chain) picking this: ts \<in> Lr ns n [PROOF STEP] obtain tr where dtr: "wf tr" and r: "root tr = n" and tr: "regular tr" and ts: "ts = Fr ns tr" [PROOF STATE] proof (prove) using this: ts \<in> Lr ns n goal (1 subgoal): 1. (\<And>tr. \<lbrakk>wf tr; root tr = n; regular tr; ts = Fr ns tr\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] unfolding Lr_def [PROOF STATE] proof (prove) using this: ts \<in> {Fr ns tr |tr. wf tr \<and> root tr = n \<and> regular tr} goal (1 subgoal): 1. (\<And>tr. \<lbrakk>wf tr; root tr = n; regular tr; ts = Fr ns tr\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: wf tr root tr = n regular tr ts = Fr ns tr goal (1 subgoal): 1. \<And>x. x \<in> Lr ns n \<Longrightarrow> \<exists>tns K. x = Inl -` tns \<union> \<Union> {K n' |n'. Inr n' \<in> tns} \<and> (n, tns) \<in> P \<and> (\<forall>n'. Inr n' \<in> tns \<longrightarrow> K n' \<in> Lr (ns - {n}) n') [PROOF STEP] define tns where "tns = (id \<oplus> root) ` (cont tr)" [PROOF STATE] proof (state) this: tns = prodOf tr goal (1 subgoal): 1. \<And>x. x \<in> Lr ns n \<Longrightarrow> \<exists>tns K. x = Inl -` tns \<union> \<Union> {K n' |n'. Inr n' \<in> tns} \<and> (n, tns) \<in> P \<and> (\<forall>n'. Inr n' \<in> tns \<longrightarrow> K n' \<in> Lr (ns - {n}) n') [PROOF STEP] define K where "K n' = Fr (ns - {n}) (subtrOf tr n')" for n' [PROOF STATE] proof (state) this: K ?n' = Fr (ns - {n}) (subtrOf tr ?n') goal (1 subgoal): 1. \<And>x. x \<in> Lr ns n \<Longrightarrow> \<exists>tns K. x = Inl -` tns \<union> \<Union> {K n' |n'. Inr n' \<in> tns} \<and> (n, tns) \<in> P \<and> (\<forall>n'. Inr n' \<in> tns \<longrightarrow> K n' \<in> Lr (ns - {n}) n') [PROOF STEP] show "\<exists>tns K. ts = ?F tns K \<and> (n, tns) \<in> P \<and> ?\<phi> tns K" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>tns K. ts = Inl -` tns \<union> \<Union> {K n' |n'. Inr n' \<in> tns} \<and> (n, tns) \<in> P \<and> (\<forall>n'. Inr n' \<in> tns \<longrightarrow> K n' \<in> Lr (ns - {n}) n') [PROOF STEP] apply(rule exI[of _ tns], rule exI[of _ K]) [PROOF STATE] proof (prove) goal (1 subgoal): 1. ts = Inl -` tns \<union> \<Union> {K n' |n'. Inr n' \<in> tns} \<and> (n, tns) \<in> P \<and> (\<forall>n'. Inr n' \<in> tns \<longrightarrow> K n' \<in> Lr (ns - {n}) n') [PROOF STEP] proof(intro conjI allI impI) [PROOF STATE] proof (state) goal (3 subgoals): 1. ts = Inl -` tns \<union> \<Union> {K n' |n'. Inr n' \<in> tns} 2. (n, tns) \<in> P 3. \<And>n'. Inr n' \<in> tns \<Longrightarrow> K n' \<in> Lr (ns - {n}) n' [PROOF STEP] show "ts = Inl -` tns \<union> \<Union>{K n' |n'. Inr n' \<in> tns}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ts = Inl -` tns \<union> \<Union> {K n' |n'. Inr n' \<in> tns} [PROOF STEP] unfolding ts regular_Fr[OF tr n[unfolded r[symmetric]]] [PROOF STATE] proof (prove) goal (1 subgoal): 1. Inl -` cont tr \<union> \<Union> {Fr (ns - {root tr}) tr' |tr'. Inr tr' \<in> cont tr} = Inl -` tns \<union> \<Union> {K n' |n'. Inr n' \<in> tns} [PROOF STEP] unfolding tns_def K_def r[symmetric] [PROOF STATE] proof (prove) goal (1 subgoal): 1. Inl -` cont tr \<union> \<Union> {Fr (ns - {root tr}) tr' |tr'. Inr tr' \<in> cont tr} = Inl -` prodOf tr \<union> \<Union> {Fr (ns - {root tr}) (subtrOf tr n') |n'. Inr n' \<in> prodOf tr} [PROOF STEP] unfolding Inl_prodOf wf_subtrOf_Union[OF dtr] [PROOF STATE] proof (prove) goal (1 subgoal): 1. Inl -` cont tr \<union> \<Union> {Fr (ns - {root tr}) (subtrOf tr n) |n. Inr n \<in> prodOf tr} = Inl -` cont tr \<union> \<Union> {Fr (ns - {root tr}) (subtrOf tr n') |n'. Inr n' \<in> prodOf tr} [PROOF STEP] .. [PROOF STATE] proof (state) this: ts = Inl -` tns \<union> \<Union> {K n' |n'. Inr n' \<in> tns} goal (2 subgoals): 1. (n, tns) \<in> P 2. \<And>n'. Inr n' \<in> tns \<Longrightarrow> K n' \<in> Lr (ns - {n}) n' [PROOF STEP] show "(n, tns) \<in> P" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (n, tns) \<in> P [PROOF STEP] unfolding tns_def r[symmetric] [PROOF STATE] proof (prove) goal (1 subgoal): 1. (root tr, prodOf tr) \<in> P [PROOF STEP] using wf_P[OF dtr] [PROOF STATE] proof (prove) using this: (root tr, prodOf tr) \<in> P goal (1 subgoal): 1. (root tr, prodOf tr) \<in> P [PROOF STEP] . [PROOF STATE] proof (state) this: (n, tns) \<in> P goal (1 subgoal): 1. \<And>n'. Inr n' \<in> tns \<Longrightarrow> K n' \<in> Lr (ns - {n}) n' [PROOF STEP] fix n' [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>n'. Inr n' \<in> tns \<Longrightarrow> K n' \<in> Lr (ns - {n}) n' [PROOF STEP] assume "Inr n' \<in> tns" [PROOF STATE] proof (state) this: Inr n' \<in> tns goal (1 subgoal): 1. \<And>n'. Inr n' \<in> tns \<Longrightarrow> K n' \<in> Lr (ns - {n}) n' [PROOF STEP] thus "K n' \<in> Lr (ns - {n}) n'" [PROOF STATE] proof (prove) using this: Inr n' \<in> tns goal (1 subgoal): 1. K n' \<in> Lr (ns - {n}) n' [PROOF STEP] unfolding K_def Lr_def mem_Collect_eq [PROOF STATE] proof (prove) using this: Inr n' \<in> tns goal (1 subgoal): 1. \<exists>tra. Fr (ns - {n}) (subtrOf tr n') = Fr (ns - {n}) tra \<and> wf tra \<and> root tra = n' \<and> regular tra [PROOF STEP] apply(intro exI[of _ "subtrOf tr n'"]) [PROOF STATE] proof (prove) goal (1 subgoal): 1. Inr n' \<in> tns \<Longrightarrow> Fr (ns - {n}) (subtrOf tr n') = Fr (ns - {n}) (subtrOf tr n') \<and> wf (subtrOf tr n') \<and> root (subtrOf tr n') = n' \<and> regular (subtrOf tr n') [PROOF STEP] using dtr tr [PROOF STATE] proof (prove) using this: wf tr regular tr goal (1 subgoal): 1. Inr n' \<in> tns \<Longrightarrow> Fr (ns - {n}) (subtrOf tr n') = Fr (ns - {n}) (subtrOf tr n') \<and> wf (subtrOf tr n') \<and> root (subtrOf tr n') = n' \<and> regular (subtrOf tr n') [PROOF STEP] apply(intro conjI refl) [PROOF STATE] proof (prove) goal (3 subgoals): 1. \<lbrakk>Inr n' \<in> tns; wf tr; regular tr\<rbrakk> \<Longrightarrow> wf (subtrOf tr n') 2. \<lbrakk>Inr n' \<in> tns; wf tr; regular tr\<rbrakk> \<Longrightarrow> root (subtrOf tr n') = n' 3. \<lbrakk>Inr n' \<in> tns; wf tr; regular tr\<rbrakk> \<Longrightarrow> regular (subtrOf tr n') [PROOF STEP] unfolding tns_def [PROOF STATE] proof (prove) goal (3 subgoals): 1. \<lbrakk>Inr n' \<in> prodOf tr; wf tr; regular tr\<rbrakk> \<Longrightarrow> wf (subtrOf tr n') 2. \<lbrakk>Inr n' \<in> prodOf tr; wf tr; regular tr\<rbrakk> \<Longrightarrow> root (subtrOf tr n') = n' 3. \<lbrakk>Inr n' \<in> prodOf tr; wf tr; regular tr\<rbrakk> \<Longrightarrow> regular (subtrOf tr n') [PROOF STEP] apply(erule wf_subtrOf[OF dtr]) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<lbrakk>Inr n' \<in> prodOf tr; wf tr; regular tr\<rbrakk> \<Longrightarrow> root (subtrOf tr n') = n' 2. \<lbrakk>Inr n' \<in> prodOf tr; wf tr; regular tr\<rbrakk> \<Longrightarrow> regular (subtrOf tr n') [PROOF STEP] apply (metis subtrOf) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>Inr n' \<in> prodOf tr; wf tr; regular tr\<rbrakk> \<Longrightarrow> regular (subtrOf tr n') [PROOF STEP] by (metis Inr_subtrOf UNIV_I regular_subtr subtr.simps) [PROOF STATE] proof (state) this: K n' \<in> Lr (ns - {n}) n' goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: \<exists>tns K. ts = Inl -` tns \<union> \<Union> {K n' |n'. Inr n' \<in> tns} \<and> (n, tns) \<in> P \<and> (\<forall>n'. Inr n' \<in> tns \<longrightarrow> K n' \<in> Lr (ns - {n}) n') goal: No subgoals! [PROOF STEP] qed
<!-- dom:TITLE: A minimal test that DocOnce works --> # A minimal test that DocOnce works <!-- dom:AUTHOR: Hans Petter Langtangen --> <!-- Author: --> **Hans Petter Langtangen** Date: **Jan 1, 2031** **Summary.** This is a small document for testing the installation of DocOnce. # Test of plain text ## Test standard text with lists and inline tagging Here are some DocOnce features: * DocOnce addresses small and large documents containing *text with much computer source code and LaTeX mathematics*, where the output is desired in different formats such as LaTeX, pdfLaTeX, Sphinx, HTML, MediaWiki, blogger.com, and wordpress.com. A piece of DocOnce text can enter (e.g.) a classical science book, an ebook, a web document, and a blog post. * DocOnce offers a range of HTML designs, including many Bootstrap and Sphinx styles and [solarized color schemes](http://ethanschoonover.com/solarized). A special feature is the many styles for **admonitions** (boxes for warning, notice, question, etc.) in HTML and LaTeX. * DocOnce targets in particular large book projects where many different pieces of text and software can be assembled in different ways and published in different formats for different devices (see [example](http://hplgit.github.io/setup4book-doconce/doc/web/index.html)). * DocOnce enables authors who write for many times of media (blog posts, wikis, LaTeX manuscripts, Sphinx, HTML) to use a common source language such that lots of different pieces can easily be brought together later to form a coherent (big) document. * DocOnce has good support for copying computer code directly from the source code files via regular expressions for the start and end lines. * DocOnce first runs two preprocessors (Preprocess and Mako), which allow programming constructs (includes, if-tests, function calls) as part of the text. This feature makes it easy to write *one text* with different flavors: long vs short text, Python vs Matlab code examples, experimental vs mature content. * DocOnce can be converted to plain *untagged* text, often desirable for email and computer code documentation. * DocOnce markup does include tags, so the format is more tagged than Markdown, but less than reST, and very much less than LaTeX and HTML. * Compared to the related tools Sphinx and Markdown, DocOnce allows more types of equations (especially systems of equations with references), has more flexible inclusion of source code, integrates preprocessors, has special support for exercises, and produces cleaner LaTeX and HTML output. ## Test of figures and movies Inline figure: <!-- dom:FIGURE: [../doc/src/manual/fig/wave1D.png, width=300 frac=0.7] --> <!-- begin figure --> <p></p> <!-- end figure --> [Figure](#fig1) has a caption. <!-- dom:FIGURE: [../doc/src/manual/fig/wave1D.png, width=300 frac=0.7] Figure with caption. <div id="fig1"></div> --> <!-- begin figure --> <div id="fig1"></div> <p>Figure with caption.</p> <!-- end figure --> Here is a YouTube movie: <!-- dom:MOVIE: [https://www.youtube.com/embed/P8VcZzgdfSc, width=420 height=315] --> <!-- begin movie --> ``` from IPython.display import HTML _s = """ """ HTML(_s) ``` <!-- end movie --> <!-- dom:MOVIE: [../doc/src/manual/mov/wave.webm, width=700 height=400] Movie on the hard disk: 1D wave motion. --> <!-- begin movie --> ``` _s = """ <div> </div> <p><em>Movie on the hard disk: 1D wave motion.</em></p> <!-- Issue warning if in a Safari browser --> """ HTML(_s) ``` <!-- end movie --> # Test of math, code, admons, quiz ## Math We have <!-- Equation labels as ordinary links --> <div id="_auto1"></div> $$ \begin{equation} F = \int_a^b f(x)dx. \label{_auto1} \tag{1} \end{equation} $$ ## Code We can do the integral by ``` from sympy import * x = 'symbols('x') f = x*sin(x)*exp(-x) integrate(f, x(0, 4)) ``` Or we can do it numerically via the Trapezoidal rule: ``` import numpy def trapezoidal(f, a, b, n=100): """Integrate f from a to b with 100 intervals.""" x = numpy.linspace(a, b, n+1) F = (b-a)/float(n)*(numpy.sum(f(x)) - 0.5*(f(a) + f(b))) return F def f(x): return x*numpy.sin(x)*numpy.exp(-x) print trapezoidal(f, 0, 4) ``` ## Admonitions **Question.** How do adminitions look like? That depends on the output format and what type of admon design in the format one has chosen. **White space is important!** Many DocOnce errors arise from wrong use of white space. The white space is not as critical as in reStructuredText, but is not ignored either, as in LaTeX and HTML.
#download csv and have it in working directory library(tidyverse) library(dplyr) library(ggplot2) library(scales) library(reshape2) df <- read.csv('publish-performance.csv') #convert start date into days df$start_date <- substr(df$PublishStartDate,1,10) df$start_date <- as.Date(df$start_date, '%Y-%m-%d') #remove NAs df <- df[!is.na(df$start_date),] #make sure data is numeric df$FileCount <- as.numeric(df$FileCount) df$FileSize <- as.numeric(df$FileSize) df$Duration <- as.numeric(df$Duration) df_scheduled <- df[!(df$Type == "scheduled"),] df_manual <- df[!(df$Type == "manual"),] #pivot to get values pivot <- df %>% group_by(start_date) %>% summarise(sumFileCount = sum(FileCount), sumFileSize = sum(FileSize)/100000, maxDuration = max(Duration), aveDuration = mean(Duration), count = n()*1000) pivot_scheduled <- df_scheduled %>% group_by(start_date) %>% summarise(sumFileCount = sum(FileCount), sumFileSize = sum(FileSize)/100000, maxDuration = max(Duration), aveDuration = mean(Duration), count = n()*1000) pivot_manual <- df_manual %>% group_by(start_date) %>% summarise(sumFileCount = sum(FileCount), sumFileSize = sum(FileSize)/100000, maxDuration = max(Duration), aveDuration = mean(Duration), count = n()*1000) #get count of entries #entries <- df %>% # group_by(start_date) %>% # summarise(count = n()) #melted <- melt(pivot, id=c("start_date")) # graph the pivot table by month #ggplot(data = melted, aes(x=`strftime(start_date, "%Y/%m")`, y=value, colour=variable)) + geom_line(aes(group=variable)) + geom_smooth(method = "lm", aes(group=variable)) + xlab("Month") + ylab("Words") + ggtitle("Number of words by page type by month") + scale_y_continuous(label=comma) pivot_x <- pivot[!(pivot$maxDuration > 100000),] pivot_x_scheduled <- pivot_scheduled[!(pivot_scheduled$maxDuration > 100000),] pivot_x_manual <- pivot_manual[!(pivot_manual$maxDuration > 100000),] pivot_gathered <- pivot_x %>% gather(key = 'key', value = 'value', -start_date) pivot_gathered_scheduled <- pivot_x_scheduled %>% gather(key = 'key', value = 'value', -start_date) pivot_gathered_manual <- pivot_x_manual %>% gather(key = 'key', value = 'value', -start_date) ggplot(pivot_gathered, aes(x = start_date, y = value, color = key)) + geom_line() + geom_smooth(method="lm", aes(group=key)) + scale_y_continuous(sec.axis = sec_axis(~./1000)) ggplot(pivot_gathered_scheduled, aes(x = start_date, y = value, color = key)) + geom_line() + geom_smooth(method="lm", aes(group=key)) + scale_y_continuous(sec.axis = sec_axis(~./1000)) ggplot(pivot_gathered_manual, aes(x = start_date, y = value, color = key)) + geom_line() + geom_smooth(method="lm", aes(group=key)) + scale_y_continuous(sec.axis = sec_axis(~./1000))
module vegetables_assert_equals_integer_matrix_m use iso_varying_string, only: varying_string, operator(//), var_str use strff, only: join use vegetables_messages_m, only: & make_equals_failure_message, & make_equals_success_message, & with_user_message use vegetables_result_m, only: result_t, fail, succeed use vegetables_utilities_m, only: to_string implicit none private public :: assert_equals interface assert_equals module procedure assert_equals_integer_matrix_basic module procedure assert_equals_integer_matrix_with_message_c module procedure assert_equals_integer_matrix_with_message_s module procedure assert_equals_integer_matrix_with_messages_cc module procedure assert_equals_integer_matrix_with_messages_cs module procedure assert_equals_integer_matrix_with_messages_sc module procedure assert_equals_integer_matrix_with_messages_ss end interface contains pure function assert_equals_integer_matrix_basic(expected, actual) result(result__) integer, intent(in) :: expected(:,:) integer, intent(in) :: actual(:,:) type(result_t) :: result__ result__ = assert_equals( & expected, & actual, & var_str(""), & var_str("")) end function pure function assert_equals_integer_matrix_with_message_c( & expected, actual, message) result(result__) integer, intent(in) :: expected(:,:) integer, intent(in) :: actual(:,:) character(len=*), intent(in) :: message type(result_t) :: result__ result__ = assert_equals( & expected, & actual, & var_str(message), & var_str(message)) end function pure function assert_equals_integer_matrix_with_message_s( & expected, actual, message) result(result__) integer, intent(in) :: expected(:,:) integer, intent(in) :: actual(:,:) type(varying_string), intent(in) :: message type(result_t) :: result__ result__ = assert_equals( & expected, & actual, & message, & message) end function pure function assert_equals_integer_matrix_with_messages_cc( & expected, actual, success_message, failure_message) result(result__) integer, intent(in) :: expected(:,:) integer, intent(in) :: actual(:,:) character(len=*), intent(in) :: success_message character(len=*), intent(in) :: failure_message type(result_t) :: result__ result__ = assert_equals( & expected, & actual, & var_str(success_message), & var_str(failure_message)) end function pure function assert_equals_integer_matrix_with_messages_cs( & expected, actual, success_message, failure_message) result(result__) integer, intent(in) :: expected(:,:) integer, intent(in) :: actual(:,:) character(len=*), intent(in) :: success_message type(varying_string), intent(in) :: failure_message type(result_t) :: result__ result__ = assert_equals( & expected, actual, var_str(success_message), failure_message) end function pure function assert_equals_integer_matrix_with_messages_sc( & expected, actual, success_message, failure_message) result(result__) integer, intent(in) :: expected(:,:) integer, intent(in) :: actual(:,:) type(varying_string), intent(in) :: success_message character(len=*), intent(in) :: failure_message type(result_t) :: result__ result__ = assert_equals( & expected, actual, success_message, var_str(failure_message)) end function pure function assert_equals_integer_matrix_with_messages_ss( & expected, actual, success_message, failure_message) result(result__) integer, intent(in) :: expected(:,:) integer, intent(in) :: actual(:,:) type(varying_string), intent(in) :: success_message type(varying_string), intent(in) :: failure_message type(result_t) :: result__ if ( & size(expected, dim=1) == size(actual, dim=1) & .and. size(expected, dim=2) == size(actual, dim=2)) then if (all(expected == actual)) then result__ = succeed(with_user_message( & make_equals_success_message(to_string(expected)), & success_message)) return end if end if result__ = fail(with_user_message( & make_equals_failure_message( & to_string(expected), & to_string(actual)), & failure_message)) end function end module
[STATEMENT] lemma prefix_tm_to_nat_list_cons: "\<exists>u v. tm_to_nat_list (x#xs) = u # v # tm_to_nat_list xs" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>u v. tm_to_nat_list (x # xs) = u # v # tm_to_nat_list xs [PROOF STEP] proof (cases x) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>a b. x = (a, b) \<Longrightarrow> \<exists>u v. tm_to_nat_list (x # xs) = u # v # tm_to_nat_list xs [PROOF STEP] case (Pair a b) [PROOF STATE] proof (state) this: x = (a, b) goal (1 subgoal): 1. \<And>a b. x = (a, b) \<Longrightarrow> \<exists>u v. tm_to_nat_list (x # xs) = u # v # tm_to_nat_list xs [PROOF STEP] then [PROOF STATE] proof (chain) picking this: x = (a, b) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: x = (a, b) goal (1 subgoal): 1. \<exists>u v. tm_to_nat_list (x # xs) = u # v # tm_to_nat_list xs [PROOF STEP] by (cases a)(auto) [PROOF STATE] proof (state) this: \<exists>u v. tm_to_nat_list (x # xs) = u # v # tm_to_nat_list xs goal: No subgoals! [PROOF STEP] qed
(** This file is part of the Coquelicot formalization of real analysis in Coq: http://coquelicot.saclay.inria.fr/ Copyright (C) 2011-2015 Sylvie Boldo #<br /># Copyright (C) 2011-2015 Catherine Lelay #<br /># Copyright (C) 2011-2015 Guillaume Melquiond This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the COPYING file for more details. *) From Coq Require Import RIneq Lia. Require Import Rcomplements. (** This file proves the Limited Principle of Omniscience: given a decidable property P on [nat], either P never holds or we can construct a witness for which P holds. Several variants are given. *) Open Scope R_scope. (** * Limited Principle of Omniscience *) Theorem LPO_min : forall P : nat -> Prop, (forall n, P n \/ ~ P n) -> {n : nat | P n /\ forall i, (i < n)%nat -> ~ P i} + {forall n, ~ P n}. Proof. assert (Hi: forall n, 0 < INR n + 1). intros N. rewrite <- S_INR. apply lt_0_INR. apply Nat.lt_0_succ. intros P HP. set (E y := exists n, (P n /\ y = / (INR n + 1)) \/ (~ P n /\ y = 0)). assert (HE: forall n, P n -> E (/ (INR n + 1))). intros n Pn. exists n. left. now split. assert (BE: is_upper_bound E 1). intros x [y [[_ ->]|[_ ->]]]. rewrite <- Rinv_1 at 2. apply Rinv_le_contravar. exact Rlt_0_1. rewrite <- S_INR. apply (le_INR 1), le_n_S, Nat.le_0_l. exact Rle_0_1. destruct (completeness E) as [l [ub lub]]. now exists 1. destruct (HP O) as [H0|H0]. exists 1. exists O. left. apply (conj H0). rewrite Rplus_0_l. apply sym_eq, Rinv_1. exists 0. exists O. right. now split. destruct (Rle_lt_dec l 0) as [Hl|Hl]. right. intros n Pn. apply Rle_not_lt with (1 := Hl). apply Rlt_le_trans with (/ (INR n + 1)). now apply Rinv_0_lt_compat. apply ub. now apply HE. left. set (N := Z.abs_nat (up (/l) - 2)). exists N. assert (HN: INR N + 1 = IZR (up (/ l)) - 1). unfold N. rewrite INR_IZR_INZ. rewrite inj_Zabs_nat. replace (IZR (up (/ l)) - 1) with (IZR (up (/ l) - 2) + 1). apply (f_equal (fun v => IZR v + 1)). apply Z.abs_eq. apply Zle_minus_le_0. apply (Zlt_le_succ 1). apply lt_IZR. apply Rle_lt_trans with (/l). apply Rmult_le_reg_r with (1 := Hl). rewrite Rmult_1_l, Rinv_l by now apply Rgt_not_eq. apply lub. exact BE. apply archimed. rewrite minus_IZR. simpl. ring. assert (H: forall i, (i < N)%nat -> ~ P i). intros i HiN Pi. unfold is_upper_bound in ub. refine (Rle_not_lt _ _ (ub (/ (INR i + 1)) _) _). now apply HE. rewrite <- (Rinv_involutive l) by now apply Rgt_not_eq. apply Rinv_1_lt_contravar. rewrite <- S_INR. apply (le_INR 1). apply le_n_S. apply Nat.le_0_l. apply Rlt_le_trans with (INR N + 1). apply Rplus_lt_compat_r. now apply lt_INR. rewrite HN. apply Rplus_le_reg_r with (-/l + 1). ring_simplify. apply archimed. destruct (HP N) as [PN|PN]. now split. exfalso. refine (Rle_not_lt _ _ (lub (/ (INR (S N) + 1)) _) _). intros x [y [[Py ->]|[_ ->]]]. destruct (eq_nat_dec y N) as [HyN|HyN]. elim PN. now rewrite <- HyN. apply Rinv_le_contravar. apply Hi. apply Rplus_le_compat_r. apply Rnot_lt_le. intros Hy. refine (H _ _ Py). apply INR_lt in Hy. clear -Hy HyN. lia. now apply Rlt_le, Rinv_0_lt_compat. rewrite S_INR, HN. ring_simplify (IZR (up (/ l)) - 1 + 1). rewrite <- (Rinv_involutive l) at 2 by now apply Rgt_not_eq. apply Rinv_1_lt_contravar. rewrite <- Rinv_1. apply Rinv_le_contravar. exact Hl. now apply lub. apply archimed. Qed. Theorem LPO : forall P : nat -> Prop, (forall n, P n \/ ~ P n) -> {n : nat | P n} + {forall n, ~ P n}. Proof. intros P HP. destruct (LPO_min P HP) as [[n [Pn _]]|Pn]. left. now exists n. now right. Qed. Lemma LPO_bool : forall f : nat -> bool, {n | f n = true} + {forall n, f n = false}. Proof. intros f. destruct (LPO (fun n => f n = true)) as [H|H]. simpl. intros n. case (f n). now left. now right. now left. right. intros n. now apply Bool.not_true_is_false. Qed. (** ** Corollaries *) Lemma LPO_notforall : forall P : nat -> Prop, (forall n, P n \/ ~P n) -> (~ forall n : nat, ~ P n) -> exists n : nat, P n. Proof. intros. destruct (LPO P H). destruct s as (n,H1) ; exists n ; apply H1. contradict H0 ; apply n. Qed. Lemma LPO_notnotexists : forall P : nat -> Prop, (forall n, P n \/ ~P n) -> ~~ (exists n : nat, P n) -> exists n : nat, P n. Proof. intros. apply LPO_notforall. apply H. contradict H0. intros (n,H1). contradict H1 ; apply H0. Qed. Lemma LPO_ub_dec : forall (u : nat -> R), {M : R | forall n, u n <= M} + {forall M : R, exists n, M < u n}. Proof. intros u. destruct (LPO (fun M => forall n, u n <= (INR M))) as [ [M MHM] | HM ]. intros M. destruct (LPO (fun n => INR M < u n)) as [[n Hn] | Hn]. intros n. destruct (Rlt_dec (INR M) (u n)) as [H|H]. now left. now right. right ; contradict Hn. now apply Rle_not_lt. left ; intro n. now apply Rnot_lt_le. left ; now exists (INR M). right ; intros M. destruct (nfloor_ex (Rbasic_fun.Rmax 0 M)) as [m Hm]. now apply Rbasic_fun.Rmax_l. specialize (HM (S m)). apply LPO_notforall. intros n. destruct (Rlt_dec M (u n)) as [H|H]. now left. now right. contradict HM ; intros n. rewrite S_INR. eapply Rle_trans, Rlt_le, Hm. eapply Rle_trans, Rbasic_fun.Rmax_r. now apply Rnot_lt_le. Qed. (** * Excluded-middle and decidability *) Lemma EM_dec : forall P : Prop, {not (not P)} + {not P}. Proof. intros P. set (E := fun x => x = 0 \/ (x = 1 /\ P)). destruct (completeness E) as [x H]. - exists 1. intros x [->|[-> _]]. apply Rle_0_1. apply Rle_refl. - exists 0. now left. destruct (Rle_lt_dec 1 x) as [H'|H']. - left. intros HP. elim Rle_not_lt with (1 := H'). apply Rle_lt_trans with (2 := Rlt_0_1). apply H. intros y [->|[_ Hy]]. apply Rle_refl. now elim HP. - right. intros HP. apply Rlt_not_le with (1 := H'). apply H. right. now split. Qed. Lemma EM_dec' : forall P : Prop, P \/ not P -> {P} + {not P}. Proof. intros P HP. destruct (EM_dec P) as [H|H]. - left. now destruct HP. - now right. Qed.
import Base: expand IMPLEMENT_ONE_ARG_FUNC(:expand, :expand)
{-# LANGUAGE BangPatterns, FlexibleContexts #-} -- | -- Module : Statistics.Transform -- Copyright : (c) 2011 Bryan O'Sullivan -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Fourier-related transformations of mathematical functions. -- -- These functions are written for simplicity and correctness, not -- speed. If you need a fast FFT implementation for your application, -- you should strongly consider using a library of FFTW bindings -- instead. module Statistics.Transform ( -- * Type synonyms CD -- * Discrete cosine transform , dct , dct_ , idct , idct_ -- * Fast Fourier transform , fft , ifft ) where import Control.Monad (when) import Control.Monad.ST (ST) import Data.Bits (shiftL, shiftR) import Data.Complex (Complex(..), conjugate, realPart) import Numeric.SpecFunctions (log2) import qualified Data.Vector.Generic as G import qualified Data.Vector.Generic.Mutable as M import qualified Data.Vector.Unboxed as U import qualified Data.Vector as V type CD = Complex Double -- | Discrete cosine transform (DCT-II). dct :: (G.Vector v CD, G.Vector v Double, G.Vector v Int) => v Double -> v Double dct = dctWorker . G.map (:+0) {-# INLINABLE dct #-} {-# SPECIAlIZE dct :: U.Vector Double -> U.Vector Double #-} {-# SPECIAlIZE dct :: V.Vector Double -> V.Vector Double #-} -- | Discrete cosine transform (DCT-II). Only real part of vector is -- transformed, imaginary part is ignored. dct_ :: (G.Vector v CD, G.Vector v Double, G.Vector v Int) => v CD -> v Double dct_ = dctWorker . G.map (\(i :+ _) -> i :+ 0) {-# INLINABLE dct_ #-} {-# SPECIAlIZE dct_ :: U.Vector CD -> U.Vector Double #-} {-# SPECIAlIZE dct_ :: V.Vector CD -> V.Vector Double#-} dctWorker :: (G.Vector v CD, G.Vector v Double, G.Vector v Int) => v CD -> v Double {-# INLINE dctWorker #-} dctWorker xs -- length 1 is special cased because shuffle algorithms fail for it. | G.length xs == 1 = G.map ((2*) . realPart) xs | vectorOK xs = G.map realPart $ G.zipWith (*) weights (fft interleaved) | otherwise = error "Statistics.Transform.dct: bad vector length" where interleaved = G.backpermute xs $ G.enumFromThenTo 0 2 (len-2) G.++ G.enumFromThenTo (len-1) (len-3) 1 weights = G.cons 2 . G.generate (len-1) $ \x -> 2 * exp ((0:+(-1))*fi (x+1)*pi/(2*n)) where n = fi len len = G.length xs -- | Inverse discrete cosine transform (DCT-III). It's inverse of -- 'dct' only up to scale parameter: -- -- > (idct . dct) x = (* length x) idct :: (G.Vector v CD, G.Vector v Double) => v Double -> v Double idct = idctWorker . G.map (:+0) {-# INLINABLE idct #-} {-# SPECIAlIZE idct :: U.Vector Double -> U.Vector Double #-} {-# SPECIAlIZE idct :: V.Vector Double -> V.Vector Double #-} -- | Inverse discrete cosine transform (DCT-III). Only real part of vector is -- transformed, imaginary part is ignored. idct_ :: (G.Vector v CD, G.Vector v Double) => v CD -> v Double idct_ = idctWorker . G.map (\(i :+ _) -> i :+ 0) {-# INLINABLE idct_ #-} {-# SPECIAlIZE idct_ :: U.Vector CD -> U.Vector Double #-} {-# SPECIAlIZE idct_ :: V.Vector CD -> V.Vector Double #-} idctWorker :: (G.Vector v CD, G.Vector v Double) => v CD -> v Double {-# INLINE idctWorker #-} idctWorker xs | vectorOK xs = G.generate len interleave | otherwise = error "Statistics.Transform.dct: bad vector length" where interleave z | even z = vals `G.unsafeIndex` halve z | otherwise = vals `G.unsafeIndex` (len - halve z - 1) vals = G.map realPart . ifft $ G.zipWith (*) weights xs weights = G.cons n $ G.generate (len - 1) $ \x -> 2 * n * exp ((0:+1) * fi (x+1) * pi/(2*n)) where n = fi len len = G.length xs -- | Inverse fast Fourier transform. ifft :: G.Vector v CD => v CD -> v CD ifft xs | vectorOK xs = G.map ((/fi (G.length xs)) . conjugate) . fft . G.map conjugate $ xs | otherwise = error "Statistics.Transform.ifft: bad vector length" {-# INLINABLE ifft #-} {-# SPECIAlIZE ifft :: U.Vector CD -> U.Vector CD #-} {-# SPECIAlIZE ifft :: V.Vector CD -> V.Vector CD #-} -- | Radix-2 decimation-in-time fast Fourier transform. fft :: G.Vector v CD => v CD -> v CD fft v | vectorOK v = G.create $ do mv <- G.thaw v mfft mv return mv | otherwise = error "Statistics.Transform.fft: bad vector length" {-# INLINABLE fft #-} {-# SPECIAlIZE fft :: U.Vector CD -> U.Vector CD #-} {-# SPECIAlIZE fft :: V.Vector CD -> V.Vector CD #-} -- Vector length must be power of two. It's not checked mfft :: (M.MVector v CD) => v s CD -> ST s () {-# INLINE mfft #-} mfft vec = bitReverse 0 0 where bitReverse i j | i == len-1 = stage 0 1 | otherwise = do when (i < j) $ M.swap vec i j let inner k l | k <= l = inner (k `shiftR` 1) (l-k) | otherwise = bitReverse (i+1) (l+k) inner (len `shiftR` 1) j stage l !l1 | l == m = return () | otherwise = do let !l2 = l1 `shiftL` 1 !e = -6.283185307179586/fromIntegral l2 flight j !a | j == l1 = stage (l+1) l2 | otherwise = do let butterfly i | i >= len = flight (j+1) (a+e) | otherwise = do let i1 = i + l1 xi1 :+ yi1 <- M.read vec i1 let !c = cos a !s = sin a d = (c*xi1 - s*yi1) :+ (s*xi1 + c*yi1) ci <- M.read vec i M.write vec i1 (ci - d) M.write vec i (ci + d) butterfly (i+l2) butterfly j flight 0 0 len = M.length vec m = log2 len ---------------------------------------------------------------- -- Helpers ---------------------------------------------------------------- fi :: Int -> CD fi = fromIntegral halve :: Int -> Int halve = (`shiftR` 1) vectorOK :: G.Vector v a => v a -> Bool {-# INLINE vectorOK #-} vectorOK v = (1 `shiftL` log2 n) == n where n = G.length v
lemma emeasure_bounded_finite: assumes "bounded A" shows "emeasure lborel A < \<infinity>"
# Vessel Manoeuvring Models Many simulation model for ship manoeuvring have been developed in the field of ship hydrodynamics such as: the Abkowitz model {cite:p}`abkowitz_ship_1964` or the Norrbin model {cite:p}`norrbin_study_1960`. This chapter will develop a general simulation model for ship manoeuvring, that can be further specified to become either the Abkowitz or Norbin model. Expressing the models on a general form is important in this research where many different models will be tested and compared. ```python # %load imports.py %load_ext autoreload %autoreload 2 %config Completer.use_jedi = False ## (To fix autocomplete) import pandas as pd from src.models.vmm import ModelSimulator import matplotlib.pyplot as plt import matplotlib plt.style.use('presentation') from src.visualization.plot import track_plots, plot, captive_plot import kedro import numpy as np import os.path import anyconfig from myst_nb import glue from src.symbols import * import src.symbols as symbols from src.system_equations import * from IPython.display import display, Math, Latex, Markdown from sympy.physics.vector.printing import vpprint, vlatex from src.models.regression import MotionRegression from src.parameters import df_parameters p = df_parameters["symbol"] # Read configs: conf_path = os.path.join("../../conf/base/") runs_globals_path = os.path.join( conf_path, "runs_globals.yml", ) runs_globals = anyconfig.load(runs_globals_path) model_test_ids = runs_globals["model_test_ids"] join_globals_path = os.path.join( conf_path, "join_globals.yml", ) joins = runs_globals["joins"] join_runs_dict = anyconfig.load(join_globals_path) globals_path = os.path.join( conf_path, "globals.yml", ) global_variables = anyconfig.load(globals_path) vmm_names = global_variables["vmms"] only_joined = global_variables[ "only_joined" ] # (regress/predict with only models from joined runs)S vmms = {} for vmm_name in vmm_names: vmms[vmm_name] = catalog.load(vmm_name) ``` 2022-03-29 08:08:33,835 - kedro.io.data_catalog - INFO - Loading data from `vmm_abkowitz` (PickleDataSet)... 2022-03-29 08:08:33,999 - kedro.io.data_catalog - INFO - Loading data from `vmm_abkowitz_simple` (PickleDataSet)... 2022-03-29 08:08:34,058 - kedro.io.data_catalog - INFO - Loading data from `vmm_martin` (PickleDataSet)... 2022-03-29 08:08:34,108 - kedro.io.data_catalog - INFO - Loading data from `vmm_linear` (PickleDataSet)... 2022-03-29 08:08:34,146 - kedro.io.data_catalog - INFO - Loading data from `vmm_martins_simple` (PickleDataSet)... 2022-03-29 08:08:34,185 - kedro.io.data_catalog - INFO - Loading data from `vmm_abkowitz_expanded` (PickleDataSet)... 3DOF system for manoeurving: ```python eq_system ``` $\displaystyle \left[\begin{matrix}- X_{\dot{u}} + m & 0 & 0\\0 & - Y_{\dot{v}} + m & - Y_{\dot{r}} + m x_{G}\\0 & - N_{\dot{v}} + m x_{G} & I_{z} - N_{\dot{r}}\end{matrix}\right] \left[\begin{matrix}\dot{u}\\\dot{v}\\\dot{r}\end{matrix}\right] = \left[\begin{matrix}m r^{2} x_{G} + m r v + \operatorname{X_{D}}{\left(u,v,r,\delta,thrust \right)}\\- m r u + \operatorname{Y_{D}}{\left(u,v,r,\delta,thrust \right)}\\- m r u x_{G} + \operatorname{N_{D}}{\left(u,v,r,\delta,thrust \right)}\end{matrix}\right]$ The manoeuvring simulation can now be conducted by numerical integration of the above equation. The main difference between various vessel manoeuvring models such as the Abkowitz model {cite:p}`abkowitz_ship_1964` or the Norrbin model {cite:p}`norrbin_study_1960` lies in how the hydrodynamic functions $X_D(u,v,r,\delta,thrust)$, $Y_D(u,v,r,\delta,thrust)$, $N_D(u,v,r,\delta,thrust)$ are defined. These functions cane be found in [Appendix](appendix_vmms.md). Note that a coefficient $X_{thrust}$ has been added to the Abkowitz X equation to allow for propeller thrust as an input to the model. ```python vmms['vmm_abkowitz'].Y_qs_eq ``` $\displaystyle \operatorname{Y_{D}}{\left(u,v,r,\delta,thrust \right)} = Y_{0uu} u^{2} + Y_{0u} u + Y_{0} + Y_{deltadeltadelta} \delta^{3} + Y_{delta} \delta + Y_{rdeltadelta} \delta^{2} r + Y_{rrdelta} \delta r^{2} + Y_{rrr} r^{3} + Y_{r} r + Y_{udelta} \delta u + Y_{ur} r u + Y_{uudelta} \delta u^{2} + Y_{uur} r u^{2} + Y_{uuv} u^{2} v + Y_{uv} u v + Y_{vdeltadelta} \delta^{2} v + Y_{vrdelta} \delta r v + Y_{vrr} r^{2} v + Y_{vvdelta} \delta v^{2} + Y_{vvr} r v^{2} + Y_{vvv} v^{3} + Y_{v} v$ ```python vmms['vmm_linear'].Y_qs_eq ``` $\displaystyle \operatorname{Y_{D}}{\left(u,v,r,\delta,thrust \right)} = Y_{delta} \delta + Y_{r} r + Y_{u} u + Y_{v} v$ This equation can be rewritten to get the acceleration on the left hand side: ```python eq_acceleration_matrix_clean ``` $\displaystyle \dot{\nu} = \left[\begin{matrix}\dot{u}\\\dot{v}\\\dot{r}\end{matrix}\right] = \left[\begin{matrix}\frac{1}{- X_{\dot{u}} + m} & 0 & 0\\0 & - \frac{- I_{z} + N_{\dot{r}}}{S} & - \frac{- Y_{\dot{r}} + m x_{G}}{S}\\0 & - \frac{- N_{\dot{v}} + m x_{G}}{S} & - \frac{Y_{\dot{v}} - m}{S}\end{matrix}\right] \left[\begin{matrix}m r^{2} x_{G} + m r v + \operatorname{X_{D}}{\left(u,v,r,\delta,thrust \right)}\\- m r u + \operatorname{Y_{D}}{\left(u,v,r,\delta,thrust \right)}\\- m r u x_{G} + \operatorname{N_{D}}{\left(u,v,r,\delta,thrust \right)}\end{matrix}\right]$ where $S$ is a helper variable: ```python eq_S ``` $\displaystyle S = - I_{z} Y_{\dot{v}} + I_{z} m + N_{\dot{r}} Y_{\dot{v}} - N_{\dot{r}} m - N_{\dot{v}} Y_{\dot{r}} + N_{\dot{v}} m x_{G} + Y_{\dot{r}} m x_{G} - m^{2} x_{G}^{2}$ A state space model for manoeuvring can now be defined with six states: ```python eq_x ``` $\displaystyle \vec{x} = \left[\begin{matrix}x_{0}\\y_{0}\\\Psi\\u\\v\\r\end{matrix}\right]$ An transition function $f$ defines how the states changes with time: ```python eq_state_space ``` $\displaystyle \dot{\vec{x}} = f{\left(\vec{x},u_{input},w_{noise} \right)}$ Using geometrical relations for how $x_0$, $y_0$ and $\Psi$ depend on $u$, $v$, and $r$ and the time derivatives that was derived above: $\dot{u}$, $\dot{v}$, $\dot{r}$, the transition function can be written: ```python eq_f ``` $\displaystyle f{\left(\vec{x},u_{input},w_{noise} \right)} = \left[\begin{matrix}u \cos{\left(\Psi \right)} - v \sin{\left(\Psi \right)}\\u \sin{\left(\Psi \right)} + v \cos{\left(\Psi \right)}\\r\\\dot{u}\\\dot{v}\\\dot{r}\end{matrix}\right]$ ```python %reload_kedro vmm_name = 'vmm_martins_simple' model = catalog.load(f"{ vmm_name}.motion_regression.joined.model") vmm = catalog.load(f"{ vmm_name }") initial_parameters = catalog.load("initial_parameters") model.parameters=initial_parameters id = 22773 ship_data = catalog.load("ship_data") data = catalog.load(f"{ id }.data_ek_smooth") ``` 2022-03-29 08:08:36,025 - kedro.framework.session.store - INFO - `read()` not implemented for `SQLiteStore`. Assuming empty store. 2022-03-29 08:08:38,077 - root - INFO - ** Kedro project wPCC_pipeline 2022-03-29 08:08:38,080 - root - INFO - Defined global variable `context`, `session`, `catalog` and `pipelines` 2022-03-29 08:08:38,089 - root - INFO - Registered line magic `run_viz` 2022-03-29 08:08:38,090 - kedro.io.data_catalog - INFO - Loading data from `vmm_martins_simple.motion_regression.joined.model` (PickleDataSet)... 2022-03-29 08:08:38,097 - kedro.io.data_catalog - INFO - Loading data from `vmm_martins_simple` (PickleDataSet)... 2022-03-29 08:08:38,102 - kedro.io.data_catalog - INFO - Loading data from `initial_parameters` (YAMLDataSet)... 2022-03-29 08:08:38,108 - kedro.io.data_catalog - INFO - Loading data from `ship_data` (YAMLDataSet)... 2022-03-29 08:08:38,110 - kedro.io.data_catalog - INFO - Loading data from `22773.data_ek_smooth` (CSVDataSet)... ```python #t = np.arange(0, 70, 0.01) #input_columns = ['delta','U','thrust'] #state_columns = ['x0', 'y0', 'psi', 'u', 'v', 'r'] #data = pd.DataFrame(index=t, columns=state_columns + input_columns) #data['u'] = 2 #data['delta'] = np.deg2rad(-35) #data['thrust'] = 30 #data.fillna(0, inplace=True) #data['U'] = np.sqrt(data['u']**2 + data['v']**2) # result = model.simulate(df_=data) dataframes = {'simulation': result.result, 'model test' : data} styles = {} styles['model test'] = {'style':'k-', 'alpha':1, 'lw':1.5} styles['simulation'] = {'style':'r-', 'alpha':1, 'lw':1.5} #dataframes['simulate'] = ek.simulate(data=data, input_columns=input_columns, solver='Radau') fig,ax=plt.subplots() fig.set_size_inches(matplotlib.rcParams["figure.figsize"][0]*0.4, matplotlib.rcParams["figure.figsize"][1]) track_plots(dataframes, lpp=model.ship_parameters['L'], beam=model.ship_parameters['B'], N=7, styles=styles, ax=ax); result.result.to_csv('example.csv') ```
(* Title: HOL/HOLCF/IOA/ABP/Lemmas.thy Author: Olaf Müller *) theory Lemmas imports Main begin subsection \<open>Logic\<close> lemma and_de_morgan_and_absorbe: "(~(A&B)) = ((~A)&B| ~B)" by blast lemma bool_if_impl_or: "(if C then A else B) --> (A|B)" by auto lemma exis_elim: "(? x. x=P & Q(x)) = Q(P)" by blast subsection \<open>Sets\<close> lemma set_lemmas: "f(x) : (UN x. {f(x)})" "f x y : (UN x y. {f x y})" "!!a. (!x. a ~= f(x)) ==> a ~: (UN x. {f(x)})" "!!a. (!x y. a ~= f x y) ==> a ~: (UN x y. {f x y})" by auto text \<open>2 Lemmas to add to \<open>set_lemmas\<close>, used also for action handling, namely for Intersections and the empty list (compatibility of IOA!).\<close> lemma singleton_set: "(UN b.{x. x=f(b)})= (UN b.{f(b)})" by blast lemma de_morgan: "((A|B)=False) = ((~A)&(~B))" by blast subsection \<open>Lists\<close> lemma cons_not_nil: "l ~= [] --> (? x xs. l = (x#xs))" by (induct l) simp_all end
c---------------------------------------------------------------------- c parabolic interpolation of signal amplitude and phase, c finding phase derivative c---------------------------------------------------------------------- subroutine fmax(am1,am2,am3,ph1,ph2,ph3,om,dt,t,dph,tm,ph,piover4) implicit none real*8 t, dph, tm, pi2,ph1,ph2,ph3,ph,om,dt real*8 am1,am2,am3,piover4 real*8 a1,a2,a3,dd integer*4 k c --- pi2 = datan(1.0d0)*8.0d0 dd=am1+am3-2*am2 t=0.0d0 if(dd .ne. 0.0d0) then t=(am1-am3)/dd/2.0d0 endif c phase derivative a1 = ph1 a2 = ph2 a3 = ph3 c check for 2*pi phase jump k = nint((a2-a1-om*dt)/pi2) a2 = a2-k*pi2 k = nint((a3-a2-om*dt)/pi2) a3 = a3-k*pi2 c interpolation dph=t*(a1+a3-2.0d0*a2)+(a3-a1)/2.0d0 tm=t*t*(am1+am3-2.0d0*am2)/2.0d0+t*(am3-am1)/2.0d0+am2 ph=t*t*(a1+a3-2.0d0*a2)/2.0d0+t*(a3-a1)/2.0d0+a2+pi2*piover4/8.0d0 return end
variables (α : Type) (p q : α → Prop) example : (∃ x, p x ∧ q x) -> ∃ x, q x ∧ p x := assume ⟨w, hpw, hqw⟩, ⟨w, hqw, hpw⟩
= = Plot summary = =
# USAGE # python demo_bulk.py --base-model $CAFFE_ROOT/models/bvlc_googlenet \ # --images initial_images/the_matrix --output examples/output/the_matrix # import the necessary packages from __future__ import print_function from batcountry import BatCountry from imutils import paths from PIL import Image import numpy as np import argparse # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-b", "--base-model", required=True, help="base model path") ap.add_argument("-i", "--images", required=True, help="base path to input directory of images") ap.add_argument("-o", "--output", required=True, help="base path to output directory") args = ap.parse_args() # buy the ticket, take the ride bc = BatCountry(args.base_model) layers = ("conv2/3x3", "inception_3b/5x5_reduce", "inception_4c/output") # loop over the input directory of images for imagePath in paths.list_images(args.images): # loop over the layers for layer in layers: # we can't stop here... print("[INFO] processing `{}`".format(imagePath)) image = bc.dream(np.float32(Image.open(imagePath)), end=layer) # write the output image to file filename = imagePath[imagePath.rfind("/") + 1:] outputPath = "{}/{}_{}".format(args.output, layer.replace("/", "_"), filename) result = Image.fromarray(np.uint8(image)) result.save(outputPath)
{-# OPTIONS --without-K --safe #-} module Categories.NaturalTransformation.Core where open import Level open import Categories.Category open import Categories.Functor renaming (id to idF) open import Categories.Functor.Properties import Categories.Morphism as Morphism import Categories.Morphism.Reasoning as MR private variable o ℓ e o′ ℓ′ e′ : Level C D E : Category o ℓ e record NaturalTransformation {C : Category o ℓ e} {D : Category o′ ℓ′ e′} (F G : Functor C D) : Set (o ⊔ ℓ ⊔ ℓ′ ⊔ e′) where eta-equality private module F = Functor F module G = Functor G open F using (F₀; F₁) open Category D hiding (op) field η : ∀ X → D [ F₀ X , G.F₀ X ] commute : ∀ {X Y} (f : C [ X , Y ]) → η Y ∘ F₁ f ≈ G.F₁ f ∘ η X -- We introduce an extra proof to ensure the opposite of the opposite of a natural -- transformation is definitionally equal to itself. sym-commute : ∀ {X Y} (f : C [ X , Y ]) → G.F₁ f ∘ η X ≈ η Y ∘ F₁ f op : NaturalTransformation G.op F.op op = record { η = η ; commute = sym-commute ; sym-commute = commute } -- Just like `Category`, we introduce a helper definition to ease the actual -- construction of a natural transformation. record NTHelper {C : Category o ℓ e} {D : Category o′ ℓ′ e′} (F G : Functor C D) : Set (o ⊔ ℓ ⊔ e ⊔ o′ ⊔ ℓ′ ⊔ e′) where private module G = Functor G open Functor F using (F₀; F₁) open Category D hiding (op) field η : ∀ X → D [ F₀ X , G.F₀ X ] commute : ∀ {X Y} (f : C [ X , Y ]) → η Y ∘ F₁ f ≈ G.F₁ f ∘ η X ntHelper : ∀ {F G : Functor C D} → NTHelper F G → NaturalTransformation F G ntHelper {D = D} α = record { η = η ; commute = commute ; sym-commute = λ f → Equiv.sym (commute f) } where open NTHelper α open Category D id : ∀ {F : Functor C D} → NaturalTransformation F F id {D = D} = ntHelper record { η = λ _ → D.id ; commute = λ _ → D.identityˡ ○ ⟺ D.identityʳ } where module D = Category D open D.HomReasoning infixr 9 _∘ᵥ_ _∘ₕ_ _∘ˡ_ _∘ʳ_ -- "Vertical composition" _∘ᵥ_ : ∀ {F G H : Functor C D} → NaturalTransformation G H → NaturalTransformation F G → NaturalTransformation F H _∘ᵥ_ {C = C} {D = D} {F} {G} {H} X Y = ntHelper record { η = λ q → D [ X.η q ∘ Y.η q ] ; commute = λ f → glue (X.commute f) (Y.commute f) } where module X = NaturalTransformation X module Y = NaturalTransformation Y open MR D -- "Horizontal composition" _∘ₕ_ : ∀ {F G : Functor C D} {H I : Functor D E} → NaturalTransformation H I → NaturalTransformation F G → NaturalTransformation (H ∘F F) (I ∘F G) _∘ₕ_ {E = E} {F} {I = I} Y X = ntHelper record { η = λ q → E [ I₁ (X.η q) ∘ Y.η (F.F₀ q) ] ; commute = λ f → glue ([ I ]-resp-square (X.commute f)) (Y.commute (F.F₁ f)) } where module F = Functor F module X = NaturalTransformation X module Y = NaturalTransformation Y open Functor I renaming (F₀ to I₀; F₁ to I₁) open MR E _∘ˡ_ : ∀ {G H : Functor C D} (F : Functor D E) → NaturalTransformation G H → NaturalTransformation (F ∘F G) (F ∘F H) _∘ˡ_ F α = ntHelper record { η = λ X → F₁ (η X) ; commute = λ f → [ F ]-resp-square (commute f) } where open Functor F open NaturalTransformation α _∘ʳ_ : ∀ {G H : Functor D E} → NaturalTransformation G H → (F : Functor C D) → NaturalTransformation (G ∘F F) (H ∘F F) _∘ʳ_ {D = D} {E = E} {G = G} {H = H} α F = ntHelper record { η = λ X → η (F₀ X) ; commute = λ f → commute (F₁ f) } where open Functor F open NaturalTransformation α id∘id⇒id : {C : Category o ℓ e} → NaturalTransformation {C = C} {D = C} (idF ∘F idF) idF id∘id⇒id {C = C} = ntHelper record { η = λ _ → Category.id C ; commute = λ f → MR.id-comm-sym C {f = f} } id⇒id∘id : {C : Category o ℓ e} → NaturalTransformation {C = C} {D = C} idF (idF ∘F idF) id⇒id∘id {C = C} = ntHelper record { η = λ _ → Category.id C ; commute = λ f → MR.id-comm-sym C {f = f} } module _ {F : Functor C D} where open Category.HomReasoning D open Functor F open Category D open MR D private module D = Category D F⇒F∘id : NaturalTransformation F (F ∘F idF) F⇒F∘id = ntHelper record { η = λ _ → D.id ; commute = λ _ → id-comm-sym } F⇒id∘F : NaturalTransformation F (idF ∘F F) F⇒id∘F = ntHelper record { η = λ _ → D.id ; commute = λ _ → id-comm-sym } F∘id⇒F : NaturalTransformation (F ∘F idF) F F∘id⇒F = ntHelper record { η = λ _ → D.id ; commute = λ _ → id-comm-sym } id∘F⇒F : NaturalTransformation (idF ∘F F) F id∘F⇒F = ntHelper record { η = λ _ → D.id ; commute = λ _ → id-comm-sym }
#Series temporais e analises preditivas - Fernando Amaral library(forecast) library(ggplot2) autoplot(AirPassengers) previ = stlf(AirPassengers, h=48) print(previ) autoplot(previ)
[GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I : Ideal R ⊢ ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I [PROOFSTEP] refine' IsNoetherian.induction (P := fun I => ∃ Z : Multiset (PrimeSpectrum R), Multiset.prod (Z.map asIdeal) ≤ I) (fun (M : Ideal R) hgt => _) I [GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J ⊢ (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) M [PROOFSTEP] by_cases h_prM : M.IsPrime [GOAL] case pos R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : Ideal.IsPrime M ⊢ (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) M [PROOFSTEP] use{⟨M, h_prM⟩} [GOAL] case h R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : Ideal.IsPrime M ⊢ Multiset.prod (Multiset.map asIdeal {{ asIdeal := M, IsPrime := h_prM }}) ≤ M [PROOFSTEP] rw [Multiset.map_singleton, Multiset.prod_singleton] [GOAL] case neg R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : ¬Ideal.IsPrime M ⊢ (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) M [PROOFSTEP] by_cases htop : M = ⊤ [GOAL] case pos R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : ¬Ideal.IsPrime M htop : M = ⊤ ⊢ (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) M [PROOFSTEP] rw [htop] [GOAL] case pos R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : ¬Ideal.IsPrime M htop : M = ⊤ ⊢ (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) ⊤ [PROOFSTEP] exact ⟨0, le_top⟩ [GOAL] case neg R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : ¬Ideal.IsPrime M htop : ¬M = ⊤ ⊢ (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) M [PROOFSTEP] have lt_add : ∀ (z) (_ : z ∉ M), M < M + span R { z } := by intro z hz refine' lt_of_le_of_ne le_sup_left fun m_eq => hz _ rw [m_eq] exact Ideal.mem_sup_right (mem_span_singleton_self z) [GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : ¬Ideal.IsPrime M htop : ¬M = ⊤ ⊢ ∀ (z : R), ¬z ∈ M → M < M + span R {z} [PROOFSTEP] intro z hz [GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : ¬Ideal.IsPrime M htop : ¬M = ⊤ z : R hz : ¬z ∈ M ⊢ M < M + span R {z} [PROOFSTEP] refine' lt_of_le_of_ne le_sup_left fun m_eq => hz _ [GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : ¬Ideal.IsPrime M htop : ¬M = ⊤ z : R hz : ¬z ∈ M m_eq : M = M + span R {z} ⊢ z ∈ M [PROOFSTEP] rw [m_eq] [GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : ¬Ideal.IsPrime M htop : ¬M = ⊤ z : R hz : ¬z ∈ M m_eq : M = M + span R {z} ⊢ z ∈ M + span R {z} [PROOFSTEP] exact Ideal.mem_sup_right (mem_span_singleton_self z) [GOAL] case neg R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : ¬Ideal.IsPrime M htop : ¬M = ⊤ lt_add : ∀ (z : R), ¬z ∈ M → M < M + span R {z} ⊢ (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) M [PROOFSTEP] obtain ⟨x, hx, y, hy, hxy⟩ := (Ideal.not_isPrime_iff.mp h_prM).resolve_left htop [GOAL] case neg.intro.intro.intro.intro R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : ¬Ideal.IsPrime M htop : ¬M = ⊤ lt_add : ∀ (z : R), ¬z ∈ M → M < M + span R {z} x : R hx : ¬x ∈ M y : R hy : ¬y ∈ M hxy : x * y ∈ M ⊢ (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) M [PROOFSTEP] obtain ⟨Wx, h_Wx⟩ := hgt (M + span R { x }) (lt_add _ hx) [GOAL] case neg.intro.intro.intro.intro.intro R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : ¬Ideal.IsPrime M htop : ¬M = ⊤ lt_add : ∀ (z : R), ¬z ∈ M → M < M + span R {z} x : R hx : ¬x ∈ M y : R hy : ¬y ∈ M hxy : x * y ∈ M Wx : Multiset (PrimeSpectrum R) h_Wx : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span R {x} ⊢ (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) M [PROOFSTEP] obtain ⟨Wy, h_Wy⟩ := hgt (M + span R { y }) (lt_add _ hy) [GOAL] case neg.intro.intro.intro.intro.intro.intro R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : ¬Ideal.IsPrime M htop : ¬M = ⊤ lt_add : ∀ (z : R), ¬z ∈ M → M < M + span R {z} x : R hx : ¬x ∈ M y : R hy : ¬y ∈ M hxy : x * y ∈ M Wx : Multiset (PrimeSpectrum R) h_Wx : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span R {x} Wy : Multiset (PrimeSpectrum R) h_Wy : Multiset.prod (Multiset.map asIdeal Wy) ≤ M + span R {y} ⊢ (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) M [PROOFSTEP] use Wx + Wy [GOAL] case h R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : ¬Ideal.IsPrime M htop : ¬M = ⊤ lt_add : ∀ (z : R), ¬z ∈ M → M < M + span R {z} x : R hx : ¬x ∈ M y : R hy : ¬y ∈ M hxy : x * y ∈ M Wx : Multiset (PrimeSpectrum R) h_Wx : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span R {x} Wy : Multiset (PrimeSpectrum R) h_Wy : Multiset.prod (Multiset.map asIdeal Wy) ≤ M + span R {y} ⊢ Multiset.prod (Multiset.map asIdeal (Wx + Wy)) ≤ M [PROOFSTEP] rw [Multiset.map_add, Multiset.prod_add] [GOAL] case h R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : ¬Ideal.IsPrime M htop : ¬M = ⊤ lt_add : ∀ (z : R), ¬z ∈ M → M < M + span R {z} x : R hx : ¬x ∈ M y : R hy : ¬y ∈ M hxy : x * y ∈ M Wx : Multiset (PrimeSpectrum R) h_Wx : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span R {x} Wy : Multiset (PrimeSpectrum R) h_Wy : Multiset.prod (Multiset.map asIdeal Wy) ≤ M + span R {y} ⊢ Multiset.prod (Multiset.map asIdeal Wx) * Multiset.prod (Multiset.map asIdeal Wy) ≤ M [PROOFSTEP] apply le_trans (Submodule.mul_le_mul h_Wx h_Wy) [GOAL] case h R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : ¬Ideal.IsPrime M htop : ¬M = ⊤ lt_add : ∀ (z : R), ¬z ∈ M → M < M + span R {z} x : R hx : ¬x ∈ M y : R hy : ¬y ∈ M hxy : x * y ∈ M Wx : Multiset (PrimeSpectrum R) h_Wx : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span R {x} Wy : Multiset (PrimeSpectrum R) h_Wy : Multiset.prod (Multiset.map asIdeal Wy) ≤ M + span R {y} ⊢ (M + span R {x}) * (M + span R {y}) ≤ M [PROOFSTEP] rw [add_mul] [GOAL] case h R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : ¬Ideal.IsPrime M htop : ¬M = ⊤ lt_add : ∀ (z : R), ¬z ∈ M → M < M + span R {z} x : R hx : ¬x ∈ M y : R hy : ¬y ∈ M hxy : x * y ∈ M Wx : Multiset (PrimeSpectrum R) h_Wx : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span R {x} Wy : Multiset (PrimeSpectrum R) h_Wy : Multiset.prod (Multiset.map asIdeal Wy) ≤ M + span R {y} ⊢ M * (M + span R {y}) + span R {x} * (M + span R {y}) ≤ M [PROOFSTEP] apply sup_le (show M * (M + span R { y }) ≤ M from Ideal.mul_le_right) [GOAL] case h R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : ¬Ideal.IsPrime M htop : ¬M = ⊤ lt_add : ∀ (z : R), ¬z ∈ M → M < M + span R {z} x : R hx : ¬x ∈ M y : R hy : ¬y ∈ M hxy : x * y ∈ M Wx : Multiset (PrimeSpectrum R) h_Wx : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span R {x} Wy : Multiset (PrimeSpectrum R) h_Wy : Multiset.prod (Multiset.map asIdeal Wy) ≤ M + span R {y} ⊢ span R {x} * (M + span R {y}) ≤ M [PROOFSTEP] rw [mul_add] [GOAL] case h R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : ¬Ideal.IsPrime M htop : ¬M = ⊤ lt_add : ∀ (z : R), ¬z ∈ M → M < M + span R {z} x : R hx : ¬x ∈ M y : R hy : ¬y ∈ M hxy : x * y ∈ M Wx : Multiset (PrimeSpectrum R) h_Wx : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span R {x} Wy : Multiset (PrimeSpectrum R) h_Wy : Multiset.prod (Multiset.map asIdeal Wy) ≤ M + span R {y} ⊢ span R {x} * M + span R {x} * span R {y} ≤ M [PROOFSTEP] apply sup_le (show span R { x } * M ≤ M from Ideal.mul_le_left) [GOAL] case h R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A I M : Ideal R hgt : ∀ (J : Submodule R R), J > M → (fun I => ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I) J h_prM : ¬Ideal.IsPrime M htop : ¬M = ⊤ lt_add : ∀ (z : R), ¬z ∈ M → M < M + span R {z} x : R hx : ¬x ∈ M y : R hy : ¬y ∈ M hxy : x * y ∈ M Wx : Multiset (PrimeSpectrum R) h_Wx : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span R {x} Wy : Multiset (PrimeSpectrum R) h_Wy : Multiset.prod (Multiset.map asIdeal Wy) ≤ M + span R {y} ⊢ span R {x} * span R {y} ≤ M [PROOFSTEP] rwa [span_mul_span, Set.singleton_mul_singleton, span_singleton_le_iff_mem] [GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I : Ideal A h_nzI : I ≠ ⊥ ⊢ ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥ [PROOFSTEP] revert h_nzI [GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I : Ideal A ⊢ I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥ [PROOFSTEP] refine' IsNoetherian.induction (P := fun I => I ≠ ⊥ → ∃ Z : Multiset (PrimeSpectrum A), Multiset.prod (Z.map asIdeal) ≤ I ∧ Multiset.prod (Z.map asIdeal) ≠ ⊥) (fun (M : Ideal A) hgt => _) I [GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J ⊢ (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) M [PROOFSTEP] intro h_nzM [GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ ⊢ ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ M ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥ [PROOFSTEP] have hA_nont : Nontrivial A [GOAL] case hA_nont R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ ⊢ Nontrivial A R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A ⊢ ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ M ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥ [PROOFSTEP] apply IsDomain.toNontrivial [GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A ⊢ ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ M ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥ [PROOFSTEP] by_cases h_topM : M = ⊤ [GOAL] case pos R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : M = ⊤ ⊢ ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ M ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥ [PROOFSTEP] rcases h_topM with rfl [GOAL] case pos R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I : Ideal A hA_nont : Nontrivial A hgt : ∀ (J : Submodule A A), J > ⊤ → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : ⊤ ≠ ⊥ ⊢ ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ ⊤ ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥ [PROOFSTEP] obtain ⟨p_id, h_nzp, h_pp⟩ : ∃ p : Ideal A, p ≠ ⊥ ∧ p.IsPrime := by apply Ring.not_isField_iff_exists_prime.mp h_fA [GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I : Ideal A hA_nont : Nontrivial A hgt : ∀ (J : Submodule A A), J > ⊤ → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : ⊤ ≠ ⊥ ⊢ ∃ p, p ≠ ⊥ ∧ Ideal.IsPrime p [PROOFSTEP] apply Ring.not_isField_iff_exists_prime.mp h_fA [GOAL] case pos.intro.intro R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I : Ideal A hA_nont : Nontrivial A hgt : ∀ (J : Submodule A A), J > ⊤ → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : ⊤ ≠ ⊥ p_id : Ideal A h_nzp : p_id ≠ ⊥ h_pp : Ideal.IsPrime p_id ⊢ ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ ⊤ ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥ [PROOFSTEP] use({⟨p_id, h_pp⟩} : Multiset (PrimeSpectrum A)), le_top [GOAL] case right R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I : Ideal A hA_nont : Nontrivial A hgt : ∀ (J : Submodule A A), J > ⊤ → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : ⊤ ≠ ⊥ p_id : Ideal A h_nzp : p_id ≠ ⊥ h_pp : Ideal.IsPrime p_id ⊢ Multiset.prod (Multiset.map asIdeal {{ asIdeal := p_id, IsPrime := h_pp }}) ≠ ⊥ [PROOFSTEP] rwa [Multiset.map_singleton, Multiset.prod_singleton] [GOAL] case neg R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ ⊢ ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ M ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥ [PROOFSTEP] by_cases h_prM : M.IsPrime [GOAL] case pos R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : Ideal.IsPrime M ⊢ ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ M ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥ [PROOFSTEP] use({⟨M, h_prM⟩} : Multiset (PrimeSpectrum A)) [GOAL] case h R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : Ideal.IsPrime M ⊢ Multiset.prod (Multiset.map asIdeal {{ asIdeal := M, IsPrime := h_prM }}) ≤ M ∧ Multiset.prod (Multiset.map asIdeal {{ asIdeal := M, IsPrime := h_prM }}) ≠ ⊥ [PROOFSTEP] rw [Multiset.map_singleton, Multiset.prod_singleton] [GOAL] case h R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : Ideal.IsPrime M ⊢ { asIdeal := M, IsPrime := h_prM }.asIdeal ≤ M ∧ { asIdeal := M, IsPrime := h_prM }.asIdeal ≠ ⊥ [PROOFSTEP] exact ⟨le_rfl, h_nzM⟩ [GOAL] case neg R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : ¬Ideal.IsPrime M ⊢ ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ M ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥ [PROOFSTEP] obtain ⟨x, hx, y, hy, h_xy⟩ := (Ideal.not_isPrime_iff.mp h_prM).resolve_left h_topM [GOAL] case neg.intro.intro.intro.intro R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : ¬Ideal.IsPrime M x : A hx : ¬x ∈ M y : A hy : ¬y ∈ M h_xy : x * y ∈ M ⊢ ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ M ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥ [PROOFSTEP] have lt_add : ∀ (z) (_ : z ∉ M), M < M + span A { z } := by intro z hz refine' lt_of_le_of_ne le_sup_left fun m_eq => hz _ rw [m_eq] exact mem_sup_right (mem_span_singleton_self z) [GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : ¬Ideal.IsPrime M x : A hx : ¬x ∈ M y : A hy : ¬y ∈ M h_xy : x * y ∈ M ⊢ ∀ (z : A), ¬z ∈ M → M < M + span A {z} [PROOFSTEP] intro z hz [GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : ¬Ideal.IsPrime M x : A hx : ¬x ∈ M y : A hy : ¬y ∈ M h_xy : x * y ∈ M z : A hz : ¬z ∈ M ⊢ M < M + span A {z} [PROOFSTEP] refine' lt_of_le_of_ne le_sup_left fun m_eq => hz _ [GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : ¬Ideal.IsPrime M x : A hx : ¬x ∈ M y : A hy : ¬y ∈ M h_xy : x * y ∈ M z : A hz : ¬z ∈ M m_eq : M = M + span A {z} ⊢ z ∈ M [PROOFSTEP] rw [m_eq] [GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : ¬Ideal.IsPrime M x : A hx : ¬x ∈ M y : A hy : ¬y ∈ M h_xy : x * y ∈ M z : A hz : ¬z ∈ M m_eq : M = M + span A {z} ⊢ z ∈ M + span A {z} [PROOFSTEP] exact mem_sup_right (mem_span_singleton_self z) [GOAL] case neg.intro.intro.intro.intro R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : ¬Ideal.IsPrime M x : A hx : ¬x ∈ M y : A hy : ¬y ∈ M h_xy : x * y ∈ M lt_add : ∀ (z : A), ¬z ∈ M → M < M + span A {z} ⊢ ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ M ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥ [PROOFSTEP] obtain ⟨Wx, h_Wx_le, h_Wx_ne⟩ := hgt (M + span A { x }) (lt_add _ hx) (ne_bot_of_gt (lt_add _ hx)) [GOAL] case neg.intro.intro.intro.intro.intro.intro R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : ¬Ideal.IsPrime M x : A hx : ¬x ∈ M y : A hy : ¬y ∈ M h_xy : x * y ∈ M lt_add : ∀ (z : A), ¬z ∈ M → M < M + span A {z} Wx : Multiset (PrimeSpectrum A) h_Wx_le : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span A {x} h_Wx_ne : Multiset.prod (Multiset.map asIdeal Wx) ≠ ⊥ ⊢ ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ M ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥ [PROOFSTEP] obtain ⟨Wy, h_Wy_le, h_Wx_ne⟩ := hgt (M + span A { y }) (lt_add _ hy) (ne_bot_of_gt (lt_add _ hy)) [GOAL] case neg.intro.intro.intro.intro.intro.intro.intro.intro R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : ¬Ideal.IsPrime M x : A hx : ¬x ∈ M y : A hy : ¬y ∈ M h_xy : x * y ∈ M lt_add : ∀ (z : A), ¬z ∈ M → M < M + span A {z} Wx : Multiset (PrimeSpectrum A) h_Wx_le : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span A {x} h_Wx_ne✝ : Multiset.prod (Multiset.map asIdeal Wx) ≠ ⊥ Wy : Multiset (PrimeSpectrum A) h_Wy_le : Multiset.prod (Multiset.map asIdeal Wy) ≤ M + span A {y} h_Wx_ne : Multiset.prod (Multiset.map asIdeal Wy) ≠ ⊥ ⊢ ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ M ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥ [PROOFSTEP] use Wx + Wy [GOAL] case h R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : ¬Ideal.IsPrime M x : A hx : ¬x ∈ M y : A hy : ¬y ∈ M h_xy : x * y ∈ M lt_add : ∀ (z : A), ¬z ∈ M → M < M + span A {z} Wx : Multiset (PrimeSpectrum A) h_Wx_le : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span A {x} h_Wx_ne✝ : Multiset.prod (Multiset.map asIdeal Wx) ≠ ⊥ Wy : Multiset (PrimeSpectrum A) h_Wy_le : Multiset.prod (Multiset.map asIdeal Wy) ≤ M + span A {y} h_Wx_ne : Multiset.prod (Multiset.map asIdeal Wy) ≠ ⊥ ⊢ Multiset.prod (Multiset.map asIdeal (Wx + Wy)) ≤ M ∧ Multiset.prod (Multiset.map asIdeal (Wx + Wy)) ≠ ⊥ [PROOFSTEP] rw [Multiset.map_add, Multiset.prod_add] [GOAL] case h R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : ¬Ideal.IsPrime M x : A hx : ¬x ∈ M y : A hy : ¬y ∈ M h_xy : x * y ∈ M lt_add : ∀ (z : A), ¬z ∈ M → M < M + span A {z} Wx : Multiset (PrimeSpectrum A) h_Wx_le : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span A {x} h_Wx_ne✝ : Multiset.prod (Multiset.map asIdeal Wx) ≠ ⊥ Wy : Multiset (PrimeSpectrum A) h_Wy_le : Multiset.prod (Multiset.map asIdeal Wy) ≤ M + span A {y} h_Wx_ne : Multiset.prod (Multiset.map asIdeal Wy) ≠ ⊥ ⊢ Multiset.prod (Multiset.map asIdeal Wx) * Multiset.prod (Multiset.map asIdeal Wy) ≤ M ∧ Multiset.prod (Multiset.map asIdeal Wx) * Multiset.prod (Multiset.map asIdeal Wy) ≠ ⊥ [PROOFSTEP] refine' ⟨le_trans (Submodule.mul_le_mul h_Wx_le h_Wy_le) _, mt Ideal.mul_eq_bot.mp _⟩ [GOAL] case h.refine'_1 R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : ¬Ideal.IsPrime M x : A hx : ¬x ∈ M y : A hy : ¬y ∈ M h_xy : x * y ∈ M lt_add : ∀ (z : A), ¬z ∈ M → M < M + span A {z} Wx : Multiset (PrimeSpectrum A) h_Wx_le : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span A {x} h_Wx_ne✝ : Multiset.prod (Multiset.map asIdeal Wx) ≠ ⊥ Wy : Multiset (PrimeSpectrum A) h_Wy_le : Multiset.prod (Multiset.map asIdeal Wy) ≤ M + span A {y} h_Wx_ne : Multiset.prod (Multiset.map asIdeal Wy) ≠ ⊥ ⊢ (M + span A {x}) * (M + span A {y}) ≤ M [PROOFSTEP] rw [add_mul] [GOAL] case h.refine'_1 R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : ¬Ideal.IsPrime M x : A hx : ¬x ∈ M y : A hy : ¬y ∈ M h_xy : x * y ∈ M lt_add : ∀ (z : A), ¬z ∈ M → M < M + span A {z} Wx : Multiset (PrimeSpectrum A) h_Wx_le : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span A {x} h_Wx_ne✝ : Multiset.prod (Multiset.map asIdeal Wx) ≠ ⊥ Wy : Multiset (PrimeSpectrum A) h_Wy_le : Multiset.prod (Multiset.map asIdeal Wy) ≤ M + span A {y} h_Wx_ne : Multiset.prod (Multiset.map asIdeal Wy) ≠ ⊥ ⊢ M * (M + span A {y}) + span A {x} * (M + span A {y}) ≤ M [PROOFSTEP] apply sup_le (show M * (M + span A { y }) ≤ M from Ideal.mul_le_right) [GOAL] case h.refine'_1 R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : ¬Ideal.IsPrime M x : A hx : ¬x ∈ M y : A hy : ¬y ∈ M h_xy : x * y ∈ M lt_add : ∀ (z : A), ¬z ∈ M → M < M + span A {z} Wx : Multiset (PrimeSpectrum A) h_Wx_le : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span A {x} h_Wx_ne✝ : Multiset.prod (Multiset.map asIdeal Wx) ≠ ⊥ Wy : Multiset (PrimeSpectrum A) h_Wy_le : Multiset.prod (Multiset.map asIdeal Wy) ≤ M + span A {y} h_Wx_ne : Multiset.prod (Multiset.map asIdeal Wy) ≠ ⊥ ⊢ span A {x} * (M + span A {y}) ≤ M [PROOFSTEP] rw [mul_add] [GOAL] case h.refine'_1 R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : ¬Ideal.IsPrime M x : A hx : ¬x ∈ M y : A hy : ¬y ∈ M h_xy : x * y ∈ M lt_add : ∀ (z : A), ¬z ∈ M → M < M + span A {z} Wx : Multiset (PrimeSpectrum A) h_Wx_le : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span A {x} h_Wx_ne✝ : Multiset.prod (Multiset.map asIdeal Wx) ≠ ⊥ Wy : Multiset (PrimeSpectrum A) h_Wy_le : Multiset.prod (Multiset.map asIdeal Wy) ≤ M + span A {y} h_Wx_ne : Multiset.prod (Multiset.map asIdeal Wy) ≠ ⊥ ⊢ span A {x} * M + span A {x} * span A {y} ≤ M [PROOFSTEP] apply sup_le (show span A { x } * M ≤ M from Ideal.mul_le_left) [GOAL] case h.refine'_1 R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : ¬Ideal.IsPrime M x : A hx : ¬x ∈ M y : A hy : ¬y ∈ M h_xy : x * y ∈ M lt_add : ∀ (z : A), ¬z ∈ M → M < M + span A {z} Wx : Multiset (PrimeSpectrum A) h_Wx_le : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span A {x} h_Wx_ne✝ : Multiset.prod (Multiset.map asIdeal Wx) ≠ ⊥ Wy : Multiset (PrimeSpectrum A) h_Wy_le : Multiset.prod (Multiset.map asIdeal Wy) ≤ M + span A {y} h_Wx_ne : Multiset.prod (Multiset.map asIdeal Wy) ≠ ⊥ ⊢ span A {x} * span A {y} ≤ M [PROOFSTEP] rwa [span_mul_span, Set.singleton_mul_singleton, span_singleton_le_iff_mem] [GOAL] case h.refine'_2 R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : ¬Ideal.IsPrime M x : A hx : ¬x ∈ M y : A hy : ¬y ∈ M h_xy : x * y ∈ M lt_add : ∀ (z : A), ¬z ∈ M → M < M + span A {z} Wx : Multiset (PrimeSpectrum A) h_Wx_le : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span A {x} h_Wx_ne✝ : Multiset.prod (Multiset.map asIdeal Wx) ≠ ⊥ Wy : Multiset (PrimeSpectrum A) h_Wy_le : Multiset.prod (Multiset.map asIdeal Wy) ≤ M + span A {y} h_Wx_ne : Multiset.prod (Multiset.map asIdeal Wy) ≠ ⊥ ⊢ ¬(Multiset.prod (Multiset.map asIdeal Wx) = ⊥ ∨ Multiset.prod (Multiset.map asIdeal Wy) = ⊥) [PROOFSTEP] rintro (hx | hy) [GOAL] case h.refine'_2.inl R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : ¬Ideal.IsPrime M x : A hx✝ : ¬x ∈ M y : A hy : ¬y ∈ M h_xy : x * y ∈ M lt_add : ∀ (z : A), ¬z ∈ M → M < M + span A {z} Wx : Multiset (PrimeSpectrum A) h_Wx_le : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span A {x} h_Wx_ne✝ : Multiset.prod (Multiset.map asIdeal Wx) ≠ ⊥ Wy : Multiset (PrimeSpectrum A) h_Wy_le : Multiset.prod (Multiset.map asIdeal Wy) ≤ M + span A {y} h_Wx_ne : Multiset.prod (Multiset.map asIdeal Wy) ≠ ⊥ hx : Multiset.prod (Multiset.map asIdeal Wx) = ⊥ ⊢ False [PROOFSTEP] contradiction [GOAL] case h.refine'_2.inr R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A h_fA : ¬IsField A I M : Ideal A hgt : ∀ (J : Submodule A A), J > M → (fun I => I ≠ ⊥ → ∃ Z, Multiset.prod (Multiset.map asIdeal Z) ≤ I ∧ Multiset.prod (Multiset.map asIdeal Z) ≠ ⊥) J h_nzM : M ≠ ⊥ hA_nont : Nontrivial A h_topM : ¬M = ⊤ h_prM : ¬Ideal.IsPrime M x : A hx : ¬x ∈ M y : A hy✝ : ¬y ∈ M h_xy : x * y ∈ M lt_add : ∀ (z : A), ¬z ∈ M → M < M + span A {z} Wx : Multiset (PrimeSpectrum A) h_Wx_le : Multiset.prod (Multiset.map asIdeal Wx) ≤ M + span A {x} h_Wx_ne✝ : Multiset.prod (Multiset.map asIdeal Wx) ≠ ⊥ Wy : Multiset (PrimeSpectrum A) h_Wy_le : Multiset.prod (Multiset.map asIdeal Wy) ≤ M + span A {y} h_Wx_ne : Multiset.prod (Multiset.map asIdeal Wy) ≠ ⊥ hy : Multiset.prod (Multiset.map asIdeal Wy) = ⊥ ⊢ False [PROOFSTEP] contradiction [GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A ⊢ NoetherianSpace (PrimeSpectrum R) [PROOFSTEP] apply ((noetherianSpace_TFAE <| PrimeSpectrum R).out 0 1).mpr [GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A ⊢ WellFounded fun s t => s < t [PROOFSTEP] have H := ‹IsNoetherianRing R› [GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A H : IsNoetherianRing R ⊢ WellFounded fun s t => s < t [PROOFSTEP] rw [isNoetherianRing_iff, isNoetherian_iff_wellFounded] at H [GOAL] R : Type u inst✝⁴ : CommRing R inst✝³ : IsNoetherianRing R A : Type u inst✝² : CommRing A inst✝¹ : IsDomain A inst✝ : IsNoetherianRing A H : WellFounded fun x x_1 => x > x_1 ⊢ WellFounded fun s t => s < t [PROOFSTEP] exact (closedsEmbedding R).dual.wellFounded H
/** * This reads a list of netflows from a file and finds all the triangles. * This is used as a check on what is found using the SAM parallel * infrastructure. */ //#define DEBUG #define DETAIL_TIMING #include <fstream> #include <boost/program_options.hpp> #include <sam/Util.hpp> #include <sam/VastNetflow.hpp> namespace po = boost::program_options; using namespace sam; int main(int argc, char** argv) { double queryTimeWindow; ///> Amount of time within a triangle can occur. std::string infile; ///> The location of the netflows po::options_description desc("Reads netflows from a file and counts " "how many triangles"); desc.add_options() ("help", "help message") ("queryTimeWindow", po::value<double>(&queryTimeWindow)->default_value(10), "Time window for the query to be satisfied (default: 10).") ("infile", po::value<std::string>(&infile), "The file with the netflows.") ; // Parse the command line variables po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); // Print out the help and exit if --help was specified. if (vm.count("help")) { std::cout << desc << std::endl; return 1; } std::vector<VastNetflow> netflows; std::ifstream netflowFile; netflowFile.open(infile); std::string line; size_t i = 0; while (std::getline(netflowFile, line)) { VastNetflow netflow = makeNetflow(i, line); netflows.push_back(netflow); i++; } size_t numTri = sam::numTriangles<VastNetflow, SourceIp, DestIp, TimeSeconds, DurationSeconds>(netflows, queryTimeWindow); std::cout << "Number of triangles " << numTri << std::endl; }
(* Copyright 2014 Cornell University This file is part of VPrl (the Verified Nuprl project). VPrl is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. VPrl is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VPrl. If not, see <http://www.gnu.org/licenses/>. Website: http://nuprl.org/html/verification/ Authors: Abhishek Anand & Vincent Rahli *) Require Export type_sys. Require Import dest_close. Lemma per_uatom_uniquely_valued {p} : forall lib (ts : cts(p)), uniquely_valued (per_uatom lib ts). Proof. unfold uniquely_valued, per_uatom, eq_term_equals; sp. allrw; sp. Qed. Lemma per_uatom_type_extensionality {p} : forall lib (ts : cts(p)), type_extensionality (per_uatom lib ts). Proof. unfold type_extensionality, per_uatom, eq_term_equals; sp. allrw <-; sp. Qed. Lemma per_uatom_type_symmetric {p} : forall lib (ts : cts(p)), type_symmetric (per_uatom lib ts). Proof. unfold type_symmetric, per_uatom; sp. Qed. Lemma per_uatom_type_transitive {p} : forall lib (ts : cts(p)), type_transitive (per_uatom lib ts). Proof. unfold type_transitive, per_uatom; sp. Qed. Lemma per_uatom_type_value_respecting {p} : forall lib (ts : cts(p)), type_value_respecting lib (per_uatom lib ts). Proof. sp; unfold type_value_respecting, per_uatom; sp; auto. spcast; apply @cequivc_uatom with (T := T); auto. Qed. Lemma per_uatom_term_symmetric {p} : forall lib (ts : cts(p)), term_symmetric (per_uatom lib ts). Proof. introv; unfold term_symmetric, term_equality_symmetric, per_uatom. introv k e; repnd. allrw. apply k in e. allunfold @equality_of_uatom; exrepnd. exists u; sp. Qed. Lemma per_uatom_term_transitive {p} : forall lib (ts : cts(p)), term_transitive (per_uatom lib ts). Proof. unfold term_transitive, term_equality_transitive, per_uatom. introv cts i e1 e2. destruct i as [ ct i ]. destruct i as [ ct' i ]. rw i in e1; rw i in e2; rw i; sp. allunfold @equality_of_uatom; exrepnd. exists u; sp. ccomputes_to_eqval; spcast; sp. Qed. Lemma per_uatom_term_value_respecting {p} : forall lib (ts : cts(p)), term_value_respecting lib (per_uatom lib ts). Proof. sp; unfold term_value_respecting, term_equality_respecting, per_uatom. introv i e c. destruct i as [ ct i ]. destruct i as [ ct' i ]. rw i in e; rw i; sp. allunfold @equality_of_uatom; exrepnd. exists u; sp. spcast; apply @cequivc_utoken with (T := t); auto. Qed. Lemma per_uatom_type_system {p} : forall lib (ts : cts(p)), type_system lib (per_uatom lib ts). Proof. intros; unfold type_system; sp. try apply per_uatom_uniquely_valued; auto. try apply per_uatom_type_extensionality; auto. try apply per_uatom_type_symmetric; auto. try apply per_uatom_type_transitive; auto. try apply per_uatom_type_value_respecting; auto. try apply per_uatom_term_symmetric; auto. try apply per_uatom_term_transitive; auto. try apply per_uatom_term_value_respecting; auto. Qed. Lemma close_type_system_uatom {p} : forall lib (ts : cts(p)), forall T T' eq, type_system lib ts -> defines_only_universes lib ts -> per_uatom lib (close lib ts) T T' eq -> type_sys_props lib (close lib ts) T T' eq. Proof. introv X X0 per. duplicate per as pi. unfold per_uatom in pi; repnd; spcast. rw @type_sys_props_iff_type_sys_props3. prove_type_sys_props3 SCase; intros. + SCase "uniquely_valued". dclose_lr. * SSCase "CL_uatom". assert (uniquely_valued (per_uatom lib (close lib ts))) as uv by (apply per_uatom_uniquely_valued). apply uv with (T := T) (T' := T'); auto. apply uniquely_valued_trans5 with (T2 := T3) (eq2 := eq); auto. apply per_uatom_type_extensionality. apply per_uatom_type_symmetric. apply per_uatom_type_transitive. + SCase "type_symmetric"; repdors; subst; dclose_lr; apply CL_uatom; auto; assert (type_symmetric (per_uatom lib (close lib ts))) as tys by (apply per_uatom_type_symmetric); assert (type_extensionality (per_uatom lib (close lib ts))) as tye by (apply per_uatom_type_extensionality); apply tye with (eq := eq); auto. + SCase "type_value_respecting"; sp; subst; apply CL_uatom; assert (type_value_respecting lib (per_uatom lib (close lib ts))) as tvr by (apply per_uatom_type_value_respecting). apply tvr; auto; apply @type_system_type_mem with (T' := T'); auto; try (apply per_uatom_type_symmetric); try (apply per_uatom_type_transitive). apply tvr; auto. apply @type_system_type_mem1 with (T := T); auto; try (apply per_uatom_type_transitive); try (apply per_uatom_type_symmetric). + SCase "term_symmetric". assert (term_symmetric (per_uatom lib (close lib ts))) as tes by (apply per_uatom_term_symmetric). apply tes with (T := T) (T' := T'); auto. + SCase "term_transitive". assert (term_transitive (per_uatom lib (close lib ts))) as tet by (apply per_uatom_term_transitive). apply tet with (T := T) (T' := T'); auto. + SCase "term_value_respecting". assert (term_value_respecting lib (per_uatom lib (close lib ts))) as tvr by (apply per_uatom_term_value_respecting). apply tvr with (T := T); auto. apply @type_system_type_mem with (T' := T'); auto. apply per_uatom_type_symmetric. apply per_uatom_type_transitive. + SCase "type_gsymmetric"; repdors; subst; split; sp; dclose_lr. apply CL_uatom; allunfold @per_uatom; sp. apply CL_uatom; allunfold @per_uatom; sp. + SCase "type_gtransitive"; sp. + SCase "type_mtransitive"; repdors; subst; dclose_lr; dands; apply CL_uatom; allunfold @per_uatom; sp. Qed.
Inductive Product (A B:Type) : Type := mk_Product { π₁ : A ; π₂ : B }. Inductive DProduct (A:Type) (B:A -> Type) : Type := mk_DProduct { dπ₁ : A ; dπ₂ : B dπ₁ }.
if (!require("TFX")) { install.packages("TFX") library(TFX) } getwd() setwd("./data/") data = data.frame(QueryTrueFX()) for(i in c(1:((60*24)*30))) { Sys.sleep(60) data = rbind(data, data.frame(QueryTrueFX())) data = subset(data, data$Symbol == "EUR/USD") write.csv(data, 'data.csv') }
The concert was held on 23 September 1997 , and approximately 45 @,@ 000 people attended . It was broadcast in Bosnia by local television networks , as well as globally by BBC . During the event , 10 @,@ 000 soldiers stood on the left side of the stadium to ensure no conflicts broke out . At <unk> , a decision was made to open the stadium gates to all , allowing approximately 10 @,@ 000 more fans who could not afford the concert or who had not purchased tickets in time to attend . In addition to the local and foreign fans , 6 @,@ 000 off @-@ duty SFOR soldiers attended the event in uniform . <unk> Nogić attended the concert and arrived in a limo with the band . The concert was broadcast live internationally on radio , and all proceeds from the radio sales were donated to the War Child project .
(* Title: Native_Cast.thy Author: Andreas Lochbihler, ETH Zurich *) chapter {* Conversions between unsigned words and between char *} theory Native_Cast imports "HOL-Library.Code_Char" Uint8 Uint16 Uint32 Uint64 begin text {* Auxiliary stuff *} context includes lifting_syntax begin lemma char_of_integer_transfer [transfer_rule]: "(pcr_integer ===> op =) (\<lambda>n. char_of_nat (nat n)) char_of_integer" by(simp add: integer.pcr_cr_eq cr_integer_def rel_fun_def char_of_integer_def nat_of_integer_def) lemma integer_of_char_transfer [transfer_rule]: "(op = ===> pcr_integer) (\<lambda>n. int (nat_of_char n)) integer_of_char" by(simp add: integer.pcr_cr_eq cr_integer_def rel_fun_def integer_of_char_def) end lemma integer_of_char_char_of_integer [simp]: "0 \<le> x \<Longrightarrow> integer_of_char (char_of_integer x) = x mod 256" unfolding integer_of_char_def char_of_integer_def o_apply nat_of_char_of_nat including integer.lifting by transfer(auto dest: nat_mod_distrib[of _ 256, symmetric]) lemma char_of_integer_integer_of_char [simp]: "char_of_integer (integer_of_char x) = x" by(simp add: integer_of_char_def char_of_integer_def) lemma int_lt_numeral [simp]: "int x < numeral n \<longleftrightarrow> x < numeral n" by (metis nat_numeral zless_nat_eq_int_zless) lemma int_of_integer_ge_0: "0 \<le> int_of_integer x \<longleftrightarrow> 0 \<le> x" including integer.lifting by transfer simp lemma integer_of_char_ge_0 [simp]: "0 \<le> integer_of_char x" including integer.lifting by transfer simp section {* Conversions between @{typ uint8} and @{typ char} *} definition uint8_of_char :: "char \<Rightarrow> uint8" where "uint8_of_char = Uint8 \<circ> integer_of_char" definition char_of_uint8 :: "uint8 \<Rightarrow> char" where "char_of_uint8 = char_of_integer \<circ> integer_of_int \<circ> uint \<circ> Rep_uint8'" lemma uint8_of_char_char_of_uint8 [simp]: "uint8_of_char (char_of_uint8 x) = x" apply(simp add: uint8_of_char_def char_of_uint8_def) including integer.lifting apply transfer apply(simp add: mod_pos_pos_trivial uint_bounded[where ?'a=8, simplified]) done lemma char_of_uint8_uint8_of_char [simp]: "char_of_uint8 (uint8_of_char x) = x" proof - have "char_of_uint8 (uint8_of_char x) = char_of_integer (of_int (int_of_integer (integer_of_char x) mod 256))" by(simp add: uint8_of_char_def char_of_uint8_def Uint8.rep_eq uint_word_of_int) also { have "int_of_integer (integer_of_char x) < 256" including integer.lifting by transfer(simp add: nat_of_char_less_256) } hence "\<dots> = x" by(simp add: semiring_numeral_div_class.mod_less int_of_integer_ge_0) finally show ?thesis . qed code_printing code_module Native_Casts \<rightharpoonup> (Haskell) {*import qualified Data.Char; ord :: Char -> Int; ord = Data.Char.ord; chr :: Int -> Char; chr = Data.Char.chr; *} code_reserved Haskell Native_Casts code_printing constant uint8_of_char \<rightharpoonup> (SML) "Word8.fromInt (Char.ord _)" and (Haskell) "(Prelude.fromIntegral (Native'_Casts.ord _) :: Uint8.Word8)" and (Scala) "_.toByte" | constant char_of_uint8 \<rightharpoonup> (SML) "Char.chr (Word8.toInt _)" and (Haskell) "Native'_Casts.chr (Prelude.fromIntegral _)" and (Scala) "((_).toInt & 0xFF).toChar" section {* Conversion between native words *} lift_definition uint8_of_uint16 :: "uint16 \<Rightarrow> uint8" is ucast . lift_definition uint8_of_uint32 :: "uint32 \<Rightarrow> uint8" is ucast . lift_definition uint8_of_uint64 :: "uint64 \<Rightarrow> uint8" is ucast . lift_definition uint16_of_uint8 :: "uint8 \<Rightarrow> uint16" is ucast . lift_definition uint16_of_uint32 :: "uint32 \<Rightarrow> uint16" is ucast . lift_definition uint16_of_uint64 :: "uint64 \<Rightarrow> uint16" is ucast . lift_definition uint32_of_uint8 :: "uint8 \<Rightarrow> uint32" is ucast . lift_definition uint32_of_uint16 :: "uint16 \<Rightarrow> uint32" is ucast . lift_definition uint32_of_uint64 :: "uint64 \<Rightarrow> uint32" is ucast . lift_definition uint64_of_uint8 :: "uint8 \<Rightarrow> uint64" is ucast . lift_definition uint64_of_uint16 :: "uint16 \<Rightarrow> uint64" is ucast . lift_definition uint64_of_uint32 :: "uint32 \<Rightarrow> uint64" is ucast . definition mask where "mask = (0xFFFFFFFF :: integer)" export_code mask in OCaml code_printing constant uint8_of_uint16 \<rightharpoonup> (SML_word) "Word8.fromLarge (Word16.toLarge _)" and (Haskell) "(Prelude.fromIntegral _ :: Uint8.Word8)" and (Scala) "_.toByte" | constant uint8_of_uint32 \<rightharpoonup> (SML) "Word8.fromLarge (Word32.toLarge _)" and (Haskell) "(Prelude.fromIntegral _ :: Uint8.Word8)" and (Scala) "_.toByte" | constant uint8_of_uint64 \<rightharpoonup> (SML) "Word8.fromLarge (Uint64.toLarge _)" and (Haskell) "(Prelude.fromIntegral _ :: Uint8.Word8)" and (Scala) "_.toByte" | constant uint16_of_uint8 \<rightharpoonup> (SML_word) "Word16.fromLarge (Word8.toLarge _)" and (Haskell) "(Prelude.fromIntegral _ :: Uint16.Word16)" and (Scala) "((_).toInt & 0xFF).toChar" | constant uint16_of_uint32 \<rightharpoonup> (SML_word) "Word16.fromLarge (Word32.toLarge _)" and (Haskell) "(Prelude.fromIntegral _ :: Uint16.Word16)" and (Scala) "_.toChar" | constant uint16_of_uint64 \<rightharpoonup> (SML_word) "Word16.fromLarge (Uint64.toLarge _)" and (Haskell) "(Prelude.fromIntegral _ :: Uint16.Word16)" and (Scala) "_.toChar" | constant uint32_of_uint8 \<rightharpoonup> (SML) "Word32.fromLarge (Word8.toLarge _)" and (Haskell) "(Prelude.fromIntegral _ :: Uint32.Word32)" and (Scala) "((_).toInt & 0xFF)" | constant uint32_of_uint16 \<rightharpoonup> (SML_word) "Word32.fromLarge (Word16.toLarge _)" and (Haskell) "(Prelude.fromIntegral _ :: Uint32.Word32)" and (Scala) "(_).toInt" | constant uint32_of_uint64 \<rightharpoonup> (SML_word) "Word32.fromLarge (Uint64.toLarge _)" and (Haskell) "(Prelude.fromIntegral _ :: Uint32.Word32)" and (Scala) "(_).toInt" and (OCaml) "Int64.to'_int32" | constant uint64_of_uint8 \<rightharpoonup> (SML_word) "Word64.fromLarge (Word8.toLarge _)" and (Haskell) "(Prelude.fromIntegral _ :: Uint64.Word64)" and (Scala) "((_).toLong & 0xFF)" | constant uint64_of_uint16 \<rightharpoonup> (SML_word) "Word64.fromLarge (Word16.toLarge _)" and (Haskell) "(Prelude.fromIntegral _ :: Uint64.Word64)" and (Scala) "_.toLong" | constant uint64_of_uint32 \<rightharpoonup> (SML_word) "Word64.fromLarge (Word32.toLarge _)" and (Haskell) "(Prelude.fromIntegral _ :: Uint64.Word64)" and (Scala) "((_).toLong & 0xFFFFFFFFL)" and (OCaml) "Int64.logand (Int64.of'_int32 _) (Int64.of'_string \"4294967295\")" text {* Use @{const Abs_uint8'} etc. instead of @{const Rep_uint8} in code equations for conversion functions to avoid exceptions during code generation when the target language provides only some of the uint types. *} lemma uint8_of_uint16_code [code]: "uint8_of_uint16 x = Abs_uint8' (ucast (Rep_uint16' x))" by transfer simp lemma uint8_of_uint32_code [code]: "uint8_of_uint32 x = Abs_uint8' (ucast (Rep_uint32' x))" by transfer simp lemma uint8_of_uint64_code [code]: "uint8_of_uint64 x = Abs_uint8' (ucast (Rep_uint64' x))" by transfer simp lemma uint16_of_uint8_code [code]: "uint16_of_uint8 x = Abs_uint16' (ucast (Rep_uint8' x))" by transfer simp lemma uint16_of_uint32_code [code]: "uint16_of_uint32 x = Abs_uint16' (ucast (Rep_uint32' x))" by transfer simp lemma uint16_of_uint64_code [code]: "uint16_of_uint64 x = Abs_uint16' (ucast (Rep_uint64' x))" by transfer simp lemma uint32_of_uint8_code [code]: "uint32_of_uint8 x = Abs_uint32' (ucast (Rep_uint8' x))" by transfer simp lemma uint32_of_uint16_code [code]: "uint32_of_uint16 x = Abs_uint32' (ucast (Rep_uint16' x))" by transfer simp lemma uint32_of_uint64_code [code]: "uint32_of_uint64 x = Abs_uint32' (ucast (Rep_uint64' x))" by transfer simp lemma uint64_of_uint8_code [code]: "uint64_of_uint8 x = Abs_uint64' (ucast (Rep_uint8' x))" by transfer simp lemma uint64_of_uint16_code [code]: "uint64_of_uint16 x = Abs_uint64' (ucast (Rep_uint16' x))" by transfer simp lemma uint64_of_uint32_code [code]: "uint64_of_uint32 x = Abs_uint64' (ucast (Rep_uint32' x))" by transfer simp end
(* 3 - Case Analysis and Pattern-matching *) (* 3.1 Non-dependent Case Analysis *) (* An elimination rule for the type A is some way to use an object a : A in order to define an object in some type B. A natural elimination for an inductive type is case analysis. For instance, any value of type nat is built using either O or S. Thus, a systematic way of building a value of type B from any value of type nat is to associate to O a constant t0 : B, and to every term of the form 'S p' a term ts : B. The following construction has type B: match n return B with | O => t0 | S p => ts end In most of the case, Coq is able to infer the type B of the object defined, so the 'return B' part may be omitted. The computing rules associated with construct are the expected ones: match O return B with O => t0 | S p => ts end ==> to match S q return B with O => t0 | S p => ts end ==> ts{q/p} *) (* 3.2 Dependent Case Analysis *) (* For a pattern matching construct of the form 'match n with ... end', a more general typing rule is obtained considering that the type of the whole expression may also depend on n. For instance, consider some function Q : nat -> Set, and n : nat. In order to build a term of type Q n, we can associate to the constructor O some term tO : Q O and to the pattern 'S p' some term tS : Q (S p). Note that the terms tO and tS do not have the same type. The syntax of the dependent case analysis and its associated typing rule are as follows: Q : nat -> Set tO : Q O p : nat |- tp : Q (S p) n : nat ------------------------------------------------------------------ match n as nO return Q nO with | O => tO | S p => tS end : Q n The former, non-dependent version of case analysis can be obtained from this latter rule by taking Q as a constant function on n. *) (* Strong specification of the predecessor function *) Definition pred_spec (n : nat) := { m : nat | n = O /\ m = O \/ n = S m }. Definition predecessor : forall n : nat, pred_spec n. intro n; case n. unfold pred_spec; exists O; auto. unfold pred_spec; intro n'; exists n'; auto. Defined. Print predecessor. Extraction predecessor. (* Exercise 3.1 *) Theorem nat_expand : forall n : nat, n = match n with | O => O | S p => S p end. Proof. intro n; induction n; reflexivity. Qed. (* The Empty type *) (* The rule of (non-dependent) case analysis for the type False is (for s in Prop, Set or Type): Q : s p : False -------------------- match p return Q with end : Q *) Theorem fromFalse : False -> 0 = 1. Proof. intros; contradiction. Qed. Print not. Fact Nosense : O <> O -> 2 = 3. Proof. intro H; case H; reflexivity. Qed.
import category_theory.category.default universes v u -- The order in this declaration matters: v often needs to be explicitly specified while u often can be omitted namespace category_theory variables (C : Type u) [category.{v} C] /- # Category world ## Level 2: Definition of category A category `C` consists of * a collection of objects `X, Y, Z, ...` * a collection of morphisms `f, g, h, ...` so that: * each morphism has specified domain and codomain objects; `f : X ⟶ Y` signifies that `f` is a morphism with domain `X` and codomain `Y` * each object has a designated identity morphism `𝟙 X : X ⟶ X` * for any pair of morphisms `f, g` with the codomain of `f` equal to the domain of `g`,the exists a specified composite morphism `f ≫ g` whose domain is that of `f` and codomain that of `g`, i.e. `f : X ⟶ Y, g : Y ⟶ Z` then `f ≫ g : X ⟶ Z` This data is subject to the following axioms: * For any `f : X ⟶ Y`, -/ /- Axiom : f ≫ 𝟙 Y = f-/ /- Axiom: 𝟙 X ≫ f = f-/ /-* For any composable triple of morphisms `f, g, h`, we have associativity `f ≫ (g ≫ h) = (f ≫ g) ≫ h`-/ /- Axiom: f ≫ (g ≫ h) = (f ≫ g) ≫ h-/ /-First we start out with some easy lemmas to get us warmed up.-/ /- Lemma If $$f : X ⟶ Y$$ and $$g : X ⟶ Y$$ are morphisms such that $$f = g$$, then $$f ≫ h = g ≫ h$$. -/ lemma eq_postcomp_eq {X Y Z : C} {f g : Y ⟶ Z} (w : f = g) (h : X ⟶ Y) : h ≫ f = h ≫ g := begin rw w, end end category_theory
[STATEMENT] lemma put_state_parametric [transfer_rule]: "(S ===> rel_stateT S M ===> rel_stateT S M) put_state put_state" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (S ===> rel_stateT S M ===> rel_stateT S M) put_state put_state [PROOF STEP] unfolding put_state_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. (S ===> rel_stateT S M ===> rel_stateT S M) (\<lambda>uu uua. rec_stateT (\<lambda>f s. StateT (\<lambda>_. f s)) uua uu) (\<lambda>uu uua. rec_stateT (\<lambda>f s. StateT (\<lambda>_. f s)) uua uu) [PROOF STEP] by transfer_prover
function circle_segment_test16 ( ) %*****************************************************************************80 % %% CIRCLE_SEGMENT_TEST16 demonstrates GQCIRCSECT. % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 17 July 2013 % % Author: % % Feifei Xu % fprintf ( 1, '\n' ); fprintf ( 1, 'CIRCLE_SEGMENT_TEST17\n' ); fprintf ( 1, ' Demonstrate GQCIRCSECT.\n' ); close all; tmp = sqrt(2)/2; % % Acute angle % theta = -pi/4 : pi/200 : pi/4; for n = 9 [x,y,w] = gqcircsect ( n, pi/4, 1 ); figure; line([tmp,0,tmp],[-tmp,0,tmp]); hold on; plot(cos(theta),sin(theta)); axis equal; plot(x,y,'k*'); filename = 'test16_acute.png'; print ( '-dpng', filename ); fprintf ( 1, ' Created graphics image "%s".\n', filename ); end % % Obtuse angle % theta = -pi/4*3 : pi/200 : pi/4*3; for n = 9 [x,y,w] = gqcircsect ( n, pi/4*3, 1 ); figure; line([-tmp,0,-tmp],[-tmp,0,tmp]); hold on; plot(cos(theta),sin(theta)); axis equal; plot(x,y,'ko'); filename = 'test16_obtuse.png'; print ( '-dpng', filename ); fprintf ( 1, ' Created graphics image "%s".\n', filename ); end return end
lemmas prime_dvd_power_int = prime_dvd_power[where ?'a = int]
summary.parsec_polarization <- function(object, ...) { if (!is.null(object$profiles)) { res <- object$profiles$profiles } else { res <- data.frame(tmp = 1:object$number_of_profiles) } res$weights <- object$prof_w if (object$number_of_profiles < 11) print(res) else { print(res[1:5,]) cat("\n...\n\n") print(res[object$number_of_profiles - 4:0,]) } try ( { cat("\nComputed polarization measure", object$measure, "in", object$time, "seconds") }) try( { cat("\n\nMean: ", object$mean) cat("\nSD: ", object$sd) cat("\nMin: ", object$min) cat("\nMax: ", object$max) } ) invisible(res) }
Formal statement is: lemma norm_sum_lemma: assumes "e \<le> norm (a + b + c + d)" shows "e / 4 \<le> norm a \<or> e / 4 \<le> norm b \<or> e / 4 \<le> norm c \<or> e / 4 \<le> norm d" Informal statement is: If $e \leq \|a + b + c + d\|$, then at least one of $\|a\|$, $\|b\|$, $\|c\|$, or $\|d\|$ is at least $e/4$.
# # Envelopes """ struct ConstantProfile This is the trivial profile ```math envelope(z, t) = 1 ``` which gives an infinite duration for the electromagnetic field configuration (we cannot call this a laser pusle since a pulse implicitely has a finite duration). """ struct ConstantProfile <: AbstractTemporalProfile end @doc """ GaussProfile{V,T,L} This envelope provides a finite duration for the laser pulse and thus can provide a more realistic description of an actual laser pulse. ```math envelope(z, t) = \\exp\\left[-\\left(\\frac{φ}{τ}\\right)^2\\right], ``` where ```math \\varphi = (t - t_0) - \\frac{z - z_0}{c}\\,, ``` and - `c` is the speed of light - `τ` is the duration of the pulse (FWHM) and has the default value 18.02fs - `t₀` is the origin of the time axis and it is 0 by default - `z₀` is the initial position of the intensity peak and has the default value `-4*τ*c` """ GaussProfile struct GaussProfile{T,IT,L} <: AbstractTemporalProfile inv_τ::IT t₀::T z₀::L end function GaussProfile(;τ, t₀=zero(τ), z₀) GaussProfile(inv(τ), t₀, z₀) end @doc """ Cos²Profile{V,T,L} This envelope provides a finite duration for the laser pulse and thus can provide a more realistic description of an actual laser pulse. ```math envelope(z, t) = \\begin{cases} \\cos\\left[\\left(\\frac{φ}{τ}\\right)\\right]^2, & \\text{for } |t - t₀| < τ / 2\\\\ 0 \\,, & \\text{otherwise} \\end{cases} ``` where ```math \\varphi = (t - t_0) - \\frac{z - z_0}{c}\\,, ``` and - `c` is the speed of light - `τ` is the duration of the pulse and has the default value 18.02fs - `t₀` is the origin of the time axis and it is 0 by default - `z₀` is the initial position of the intensity peak and is 0 by default """ Cos²Profile struct Cos²Profile{T,IT,L} <: AbstractTemporalProfile τ::T inv_τ::IT t₀::T z₀::L end function Cos²Profile(;τ, t₀=zero(τ), z₀) t₀, τ = promote(t₀, τ) Cos²Profile(τ, inv(τ), t₀, z₀) end @doc """ QuasiRectangularProfile{V,T,L} This envelope produces a pulse with a predominant constant part of width ``Δz`` which could offer better results than the Gaussian profile in the paraxial limit (which is considered for the spatial profiles). The shape of the envelope is given by ```math envelope(z, t) = \\begin{cases} \\exp\\left[-\\left(\\frac{φ + Δt/2}{τ}\\right)^2\\right], & \\text{for } φ ≤ \\frac{Δt}{2}\\\\ 1\\,, & \\text{for } \\text{otherwise}\\\\ \\exp\\left[-\\left(\\frac{φ - Δt/2}{τ}\\right)^2\\right], & \\ φ > \\frac{Δt}{2} \\end{cases} ``` where ```math \\varphi = (t - t_0) - \\frac{z - z_0}{c}\\,, ``` and - `c` is the speed of light - `τ` is the duration of the pulse (FWHM) and has the default value 18.02fs - `t₀` is the origin of the time axis and it is 0 by default - `z₀` is the initial position of the intensity peak and has the default value `-4*τ*c` - `Δt` is the duration of the flat part of the profile and the default value `10*τ` """ QuasiRectangularProfile struct QuasiRectangularProfile{T,IT,L} <: AbstractTemporalProfile inv_τ::IT t₀::T z₀::L Δt::T end function QuasiRectangularProfile(;τ, t₀=zero(τ), z₀, Δt=10τ) τ, t₀, Δt = promote(τ, t₀, Δt) QuasiRectangularProfile(inv(τ), t₀, z₀, Δt) end """ g(z, t, par) The time dependence of the fields defined by this package is given by ```math g(z, t) = \\exp(i ω t) envelope(z, t), ``` where - `z` and `t` are the position on the ``Oz`` axis and the time - `par` are the laser parameters which pass the corresponding profile to the envelope and - ``ω`` is the angular frequency of the laser pulse - ``envelope(z, t)`` is a function that can be used to control the duration of the pulse """ function g(z, t, laser; inv_c) profile = laser.profile ω = immutable_cache(laser, :ω) exp(im*ω*t) * envelope(profile, z, t; inv_c) end @inline envelope(::ConstantProfile, z, t; inv_c) = 1 @inline function envelope(profile::GaussProfile, z, t; inv_c) @unpack inv_τ, t₀, z₀ = profile φ = (t - t₀) - (z - z₀) * inv_c exp(-(φ * inv_τ)^2) end @inline function envelope(profile::Cos²Profile, z, t; inv_c) @unpack inv_τ, τ, t₀, z₀ = profile φ = π*((t - t₀) - (z - z₀) * inv_c) if abs(φ) / π < τ / 2 cos(-(φ * inv_τ))^2 else zero(t * inv_τ) end end @inline function envelope(profile::QuasiRectangularProfile, z, t; inv_c) @unpack inv_τ, t₀, z₀, Δt = profile φ = (t - t₀/2) - (z - z₀/2) * inv_c if φ < -Δt/2 exp(-((φ + Δt/2) * inv_τ)^2) elseif φ < Δt/2 one(φ) else exp(-((φ - Δt/2) * inv_τ)^2) end end
[STATEMENT] theorem sup_state_rev_fst: "(G \<turnstile> (rev a, x) <=s (rev b, y)) = (G \<turnstile> (a, x) <=s (b, y))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. G \<turnstile> (rev a, x) <=s (rev b, y) = G \<turnstile> (a, x) <=s (b, y) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. G \<turnstile> (rev a, x) <=s (rev b, y) = G \<turnstile> (a, x) <=s (b, y) [PROOF STEP] have m: "\<And>f x. map f (rev x) = rev (map f x)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>f x. map f (rev x) = rev (map f x) [PROOF STEP] by (simp add: rev_map) [PROOF STATE] proof (state) this: map ?f (rev ?x) = rev (map ?f ?x) goal (1 subgoal): 1. G \<turnstile> (rev a, x) <=s (rev b, y) = G \<turnstile> (a, x) <=s (b, y) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. G \<turnstile> (rev a, x) <=s (rev b, y) = G \<turnstile> (a, x) <=s (b, y) [PROOF STEP] by (simp add: m sup_state_def stk_convert lesub_def Product.le_def) [PROOF STATE] proof (state) this: G \<turnstile> (rev a, x) <=s (rev b, y) = G \<turnstile> (a, x) <=s (b, y) goal: No subgoals! [PROOF STEP] qed
At the beginning of the 20th century , Rudyard Kipling referred to lines 69 and 70 , alongside three lines from Samuel Taylor Coleridge 's Kubla Khan , when he claimed of poetry : " In all the millions permitted there are no more than five — five little lines — of which one can say , ' These are the magic . These are the vision . The rest is only Poetry . ' " In 1906 , Alexander Mackie argued : " The nightingale and the lark for long monopolised poetic <unk> privilege they enjoyed solely on account of their pre @-@ eminence as song birds . Keats 's Ode to a Nightingale and Shelley 's Ode to a Skylark are two of the glories of English literature ; but both were written by men who had no claim to special or exact knowledge of ornithology as such . " Sidney Colvin , in 1920 , argued , " Throughout this ode Keats ’ s genius is at its height . Imagination cannot be more rich and satisfying , felicity of phrase and cadence cannot be more absolute , than in the several contrasted stanzas calling for the draft of southern vintage [ … ] To praise the art of a passage like that in the fourth stanza [ … ] to praise or comment on a stroke of art like this is to throw doubt on the reader ’ s power to perceive it for himself . "
import UnitConjecture.FreeAbelianGroup def induced_map {A : Type _} [AddCommGroup A] (x y z : A) : ℤ × ℤ × ℤ → A := let f : Unit ⊕ Unit ⊕ Unit → A := (fun | Sum.inl _ => x | Sum.inr (Sum.inl _) => y | Sum.inr (Sum.inr _) => z) FreeAbelianGroup.inducedMap A f theorem induced_ext {A : Type _} [AddCommGroup A] (x y z : A) : ((induced_map x y z) (1, 0, 0) = x ∧ (induced_map x y z) (0, 1, 0) = y ∧ (induced_map x y z) (0, 0, 1) = z) := let f : Unit ⊕ Unit ⊕ Unit → A := (fun | Sum.inl _ => x | Sum.inr (Sum.inl _) => y | Sum.inr (Sum.inr _) => z) let f_extends := FreeAbelianGroup.induced_extends f ⟨congrFun f_extends (Sum.inl ()), congrFun f_extends (Sum.inr (Sum.inl ())), congrFun f_extends (Sum.inr (Sum.inr ()))⟩ instance ind_hom {A : Type _} [AddCommGroup A] {x y z : A} : AddCommGroup.Homomorphism (induced_map x y z) := FreeAbelianGroup.induced_hom A _ def ν (A : Type) [AddCommGroup A] (x y z : A) := x + y + z + (-x + -z) = y theorem eqn_iff_free_basis : (∀ (A : Type) [AddCommGroup A], ∀ x y z : A, (ν A x y z)) ↔ (ν (ℤ × ℤ × ℤ) (1, 0, 0) (0, 1, 0) (0, 0, 1)) := by apply Iff.intro · intro h apply h · intro h intro A _ x y z let ⟨hx, hy, hz⟩ := induced_ext x y z have eqn := congrArg (induced_map x y z) h simp only [AddCommGroup.Homomorphism.add_dist, AddCommGroup.Homomorphism.neg_push, hx, hy, hz] at eqn assumption theorem eqn_check : ∀ (A : Type) [AddCommGroup A], ∀ x y z : A, ν A x y z := Iff.mpr eqn_iff_free_basis rfl
class group (G : Type u) := (id : G) (inv : G → G) (binop : G → G → G) binop_assoc : ∀ (a b c : G), binop (binop a b) c = binop a (binop b c) id_binop : ∀ (a : G), binop id a = a binop_left_inv (a : G) : binop (inv a) a = id attribute [simp] group.id_binop group.binop_left_inv infixl : 75 "⊙" => group.binop variable {S : Type u} [group S] namespace group @[simp] theorem binop_left_cancel (a b c : S) (h1 : a ⊙ b = a ⊙ c) : b = c := calc b = id ⊙ b := by rw [id_binop b] _ = ((inv a) ⊙ a) ⊙ b := by rw [binop_left_inv] _ = (inv a) ⊙ (a ⊙ b) := by rw [binop_assoc] _ = (inv a) ⊙ (a ⊙ c) := by rw [h1] _ = ((inv a) ⊙ a) ⊙ c := by rw [binop_assoc] _ = id ⊙ c := by rw [binop_left_inv] _ = c := by rw [id_binop] theorem binop_eq_of_eq_inv_binop (a x y : S) (h1 : x = (inv a) ⊙ y) : a ⊙ x = y := by apply binop_left_cancel (inv a) rw [← binop_assoc,binop_left_inv,id_binop] exact h1 @[simp] theorem binop_id (a : S) : a ⊙ id = a := by apply binop_eq_of_eq_inv_binop rw [binop_left_inv] @[simp] theorem binop_right_inv (a : S) : a ⊙ (inv a) = id := by apply binop_eq_of_eq_inv_binop rw [binop_id] @[simp] theorem inv_binop_cancel_left (a b : S) : (inv a) ⊙ (a ⊙ b) = b := by rw [← binop_assoc] simp @[simp] theorem binop_inv_cancel_left (a b : S) : a ⊙ ((inv a) ⊙ b) = b := by rw [← binop_assoc] simp @[simp] theorem inv_binop (a b : S) : inv (a ⊙ b) = (inv b) ⊙ (inv a) := by rw [← id_binop (inv b), binop_assoc] rw [← binop_left_inv (a ⊙ b),binop_assoc] rw [binop_assoc] simp @[simp] theorem id_inv : inv id = (id : S) := by rw [← binop_id (inv id)] rw [binop_left_inv] @[simp] theorem inv_inv (a : S) : inv (inv a) = a := by apply binop_left_cancel (inv a) simp class abelian_group (A : Type u) extends group A := binop_comm : ∀ (a b : A), binop a b = binop b a namespace abelian_group variable (K : Type u) [abelian_group K] @[simp] theorem group_commutator_eq_id (a b : K) : (inv a) ⊙ (inv b) ⊙ a ⊙ b = id := by rw [← binop_comm a, ← binop_assoc a] simp
\section{Introduction} \par If the ultimate goal is to solve linear systems of the form $AX = B$, one must compute an $A = LDU$, $A = U^TDU$ or $A = U^HDU$ factorization, depending on whether the matrix $A$ is nonsymmetric, symmetric or Hermitian. $D$ is a diagonal or block diagonal matrix, $L$ is unit lower triangular, and $U$ is unit upper triangular. $A$ is sparse, but the sparsity structure of $L$ and $U$ will likely be much larger than that of $A$, i.e., they will suffer fill-in. It is crucial to find a permutation matrix such that the factors of $PAP^T$ have as moderate fill-in as can be reasonably expected. \par To illustrate, consider a 27-point finite difference operator defined on an $n \times n \times n$ grid. The number of rows and columns in $A$ is $n^3$, as is the number of nonzero entries in $A$. Using the natural ordering, the numbers of entries in $L$ and $U$ are $O(n^5)$, and it takes $O(n^7)$ operations to compute the factorization. The banded and profile orderings \cite{geo81-book} have the same complexity. \par Using the nested dissection ordering, \cite{geo73-nested}, the factor storage is reduced to $O(n^4)$ and factor operations to $O(n^6)$. In practice, the minimum degree ordering has this same low-fill nature, although topological counterexamples exist \cite{ber90-mindeg}. A unit cube is the worst case comparison between banded and profile orderings and the minimum degree and nested dissection orderings. But, there is still a lot to be gained by using a good permutation when solving most sparse linear systems, and the relative gain becomes larger as the problem size increases. \par This short paper is a gentle introduction to the ordering methods --- the background as well as the specific function calls. But finding a good ordering is not enough. The ``choreography'' of the factorization and solves, i.e., what data structures and computations exist, and in a parallel environment, which thread or processor does what and when, is as crucial. The structure of the factor matrices, as well as the structure of the computations is controlled by a ``front tree''. This object is constructed directly by the {\bf SPOOLES} ordering software, or can be created from the graph of the matrix and an outside permutation. Various transformations on the front tree can make a large difference in performance. Some knowledge of the linear system, (e.g., does it come from a 2-D or 3-D problem? is it small or large?), coupled with some knowledge of how to tailor a front tree, can be important to getting the best performance from the library. \par Section~\ref{section:ordering} introduces some background on sparse matrix orderings and describes the {\bf SPOOLES} ordering software. Section~\ref{section:front-trees} presents the front tree object that controls the factorization, and its various transformations to improve performance.
% CORRESPONDENCE INFORMATION % This code is written by Gaofeng MENG % % Gaofeng MENG: % National Laboratory of Pattern Recognition, % Institute of Automation, Academy of Sciences, Beijing 100190 % Comments and bug reports are welcome. Email to [email protected] % % WORK SETTING: % This code has been compiled and tested by using MATLAB R2009a % % For more detials, please see our paper: % Gaofeng MENG, Ying WANG, Jiangyong DUAN, Shiming XIANG, Chunhong PAN. % Efficient Image Dehazing with Boundary Constraint and Contextual Regularization, % ICCV, Sydney, Australia, pp.617-624, 3-6 Dec., 2013. % % Last Modified: Feb. 14, 2014, By Gaofeng MENG % function A = DH_bccr_Airlight(HazeImg, method, wsz) % estimating the global airlight % if strcmp(method, 'manual') h = figure, imshow(HazeImg, []); title('manual airlight estimation: left click to pick a most hazy pixel. ') [x, y] = ginput(1); A = HazeImg(round(y), round(x), :); A = double(A) -1; A = min(A, 255); close(h); elseif strcmp(method, 'he') A = airlight_he(HazeImg, wsz); elseif strcmp(method, 'our') A = airlight_our(HazeImg, wsz); else error('parameter error.'); end %% function A = airlight_our(HazeImg, wsz) % estimating A channel by channel separately for k = 1 : 3 minImg = ordfilt2(double(HazeImg(:, :, k)), 1, ones(wsz), 'symmetric'); A(k) = max(minImg(:)); end %% function A = airlight_he(HazeImg, wsz) % estimating A using He's method hsv = rgb2hsv(HazeImg); GrayImg = hsv(:, :, 3); [nRows, nCols, bt] = size(HazeImg); % computing dark channel DarkImg = min(double(HazeImg), [], 3); DarkImg = ordfilt2(DarkImg, 1, ones(wsz), 'symmetric'); % topDark = sort(DarkImg(:), 'descend'); idx = round(0.001 * length(topDark)); val = topDark(idx); id_set = find(DarkImg >= val); % the top 0.1% brightest pixels in the dark channel BrightPxls = GrayImg(id_set); iBright = find(BrightPxls >= max(BrightPxls)); id = id_set(iBright); id = id(1); row = mod(id, nRows); col = floor(id / nRows) + 1; % A is a vector A = HazeImg(row, col, :); A = double(A(:));
(* Author: Stefan Berghofer, Lukas Bulwahn, TU Muenchen *) section \<open>A table-based implementation of the reflexive transitive closure\<close> theory Transitive_Closure_Table imports MainRLT begin inductive rtrancl_path :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> 'a list \<Rightarrow> 'a \<Rightarrow> bool" for r :: "'a \<Rightarrow> 'a \<Rightarrow> bool" where base: "rtrancl_path r x [] x" | step: "r x y \<Longrightarrow> rtrancl_path r y ys z \<Longrightarrow> rtrancl_path r x (y # ys) z" lemma rtranclp_eq_rtrancl_path: "r\<^sup>*\<^sup>* x y \<longleftrightarrow> (\<exists>xs. rtrancl_path r x xs y)" proof show "\<exists>xs. rtrancl_path r x xs y" if "r\<^sup>*\<^sup>* x y" using that proof (induct rule: converse_rtranclp_induct) case base have "rtrancl_path r y [] y" by (rule rtrancl_path.base) then show ?case .. next case (step x z) from \<open>\<exists>xs. rtrancl_path r z xs y\<close> obtain xs where "rtrancl_path r z xs y" .. with \<open>r x z\<close> have "rtrancl_path r x (z # xs) y" by (rule rtrancl_path.step) then show ?case .. qed show "r\<^sup>*\<^sup>* x y" if "\<exists>xs. rtrancl_path r x xs y" proof - from that obtain xs where "rtrancl_path r x xs y" .. then show ?thesis proof induct case (base x) show ?case by (rule rtranclp.rtrancl_refl) next case (step x y ys z) from \<open>r x y\<close> \<open>r\<^sup>*\<^sup>* y z\<close> show ?case by (rule converse_rtranclp_into_rtranclp) qed qed qed lemma rtrancl_path_trans: assumes xy: "rtrancl_path r x xs y" and yz: "rtrancl_path r y ys z" shows "rtrancl_path r x (xs @ ys) z" using xy yz proof (induct arbitrary: z) case (base x) then show ?case by simp next case (step x y xs) then have "rtrancl_path r y (xs @ ys) z" by simp with \<open>r x y\<close> have "rtrancl_path r x (y # (xs @ ys)) z" by (rule rtrancl_path.step) then show ?case by simp qed lemma rtrancl_path_appendE: assumes xz: "rtrancl_path r x (xs @ y # ys) z" obtains "rtrancl_path r x (xs @ [y]) y" and "rtrancl_path r y ys z" using xz proof (induct xs arbitrary: x) case Nil then have "rtrancl_path r x (y # ys) z" by simp then obtain xy: "r x y" and yz: "rtrancl_path r y ys z" by cases auto from xy have "rtrancl_path r x [y] y" by (rule rtrancl_path.step [OF _ rtrancl_path.base]) then have "rtrancl_path r x ([] @ [y]) y" by simp then show thesis using yz by (rule Nil) next case (Cons a as) then have "rtrancl_path r x (a # (as @ y # ys)) z" by simp then obtain xa: "r x a" and az: "rtrancl_path r a (as @ y # ys) z" by cases auto show thesis proof (rule Cons(1) [OF _ az]) assume "rtrancl_path r y ys z" assume "rtrancl_path r a (as @ [y]) y" with xa have "rtrancl_path r x (a # (as @ [y])) y" by (rule rtrancl_path.step) then have "rtrancl_path r x ((a # as) @ [y]) y" by simp then show thesis using \<open>rtrancl_path r y ys z\<close> by (rule Cons(2)) qed qed lemma rtrancl_path_distinct: assumes xy: "rtrancl_path r x xs y" obtains xs' where "rtrancl_path r x xs' y" and "distinct (x # xs')" and "set xs' \<subseteq> set xs" using xy proof (induct xs rule: measure_induct_rule [of length]) case (less xs) show ?case proof (cases "distinct (x # xs)") case True with \<open>rtrancl_path r x xs y\<close> show ?thesis by (rule less) simp next case False then have "\<exists>as bs cs a. x # xs = as @ [a] @ bs @ [a] @ cs" by (rule not_distinct_decomp) then obtain as bs cs a where xxs: "x # xs = as @ [a] @ bs @ [a] @ cs" by iprover show ?thesis proof (cases as) case Nil with xxs have x: "x = a" and xs: "xs = bs @ a # cs" by auto from x xs \<open>rtrancl_path r x xs y\<close> have cs: "rtrancl_path r x cs y" "set cs \<subseteq> set xs" by (auto elim: rtrancl_path_appendE) from xs have "length cs < length xs" by simp then show ?thesis by (rule less(1))(blast intro: cs less(2) order_trans del: subsetI)+ next case (Cons d ds) with xxs have xs: "xs = ds @ a # (bs @ [a] @ cs)" by auto with \<open>rtrancl_path r x xs y\<close> obtain xa: "rtrancl_path r x (ds @ [a]) a" and ay: "rtrancl_path r a (bs @ a # cs) y" by (auto elim: rtrancl_path_appendE) from ay have "rtrancl_path r a cs y" by (auto elim: rtrancl_path_appendE) with xa have xy: "rtrancl_path r x ((ds @ [a]) @ cs) y" by (rule rtrancl_path_trans) from xs have set: "set ((ds @ [a]) @ cs) \<subseteq> set xs" by auto from xs have "length ((ds @ [a]) @ cs) < length xs" by simp then show ?thesis by (rule less(1))(blast intro: xy less(2) set[THEN subsetD])+ qed qed qed inductive rtrancl_tab :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a list \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> bool" for r :: "'a \<Rightarrow> 'a \<Rightarrow> bool" where base: "rtrancl_tab r xs x x" | step: "x \<notin> set xs \<Longrightarrow> r x y \<Longrightarrow> rtrancl_tab r (x # xs) y z \<Longrightarrow> rtrancl_tab r xs x z" lemma rtrancl_path_imp_rtrancl_tab: assumes path: "rtrancl_path r x xs y" and x: "distinct (x # xs)" and ys: "({x} \<union> set xs) \<inter> set ys = {}" shows "rtrancl_tab r ys x y" using path x ys proof (induct arbitrary: ys) case base show ?case by (rule rtrancl_tab.base) next case (step x y zs z) then have "x \<notin> set ys" by auto from step have "distinct (y # zs)" by simp moreover from step have "({y} \<union> set zs) \<inter> set (x # ys) = {}" by auto ultimately have "rtrancl_tab r (x # ys) y z" by (rule step) with \<open>x \<notin> set ys\<close> \<open>r x y\<close> show ?case by (rule rtrancl_tab.step) qed lemma rtrancl_tab_imp_rtrancl_path: assumes tab: "rtrancl_tab r ys x y" obtains xs where "rtrancl_path r x xs y" using tab proof induct case base from rtrancl_path.base show ?case by (rule base) next case step show ?case by (iprover intro: step rtrancl_path.step) qed lemma rtranclp_eq_rtrancl_tab_nil: "r\<^sup>*\<^sup>* x y \<longleftrightarrow> rtrancl_tab r [] x y" proof show "rtrancl_tab r [] x y" if "r\<^sup>*\<^sup>* x y" proof - from that obtain xs where "rtrancl_path r x xs y" by (auto simp add: rtranclp_eq_rtrancl_path) then obtain xs' where xs': "rtrancl_path r x xs' y" and distinct: "distinct (x # xs')" by (rule rtrancl_path_distinct) have "({x} \<union> set xs') \<inter> set [] = {}" by simp with xs' distinct show ?thesis by (rule rtrancl_path_imp_rtrancl_tab) qed show "r\<^sup>*\<^sup>* x y" if "rtrancl_tab r [] x y" proof - from that obtain xs where "rtrancl_path r x xs y" by (rule rtrancl_tab_imp_rtrancl_path) then show ?thesis by (auto simp add: rtranclp_eq_rtrancl_path) qed qed declare rtranclp_rtrancl_eq [code del] declare rtranclp_eq_rtrancl_tab_nil [THEN iffD2, code_pred_intro] code_pred rtranclp using rtranclp_eq_rtrancl_tab_nil [THEN iffD1] by fastforce lemma rtrancl_path_Range: "\<lbrakk> rtrancl_path R x xs y; z \<in> set xs \<rbrakk> \<Longrightarrow> Rangep R z" by(induction rule: rtrancl_path.induct) auto lemma rtrancl_path_Range_end: "\<lbrakk> rtrancl_path R x xs y; xs \<noteq> [] \<rbrakk> \<Longrightarrow> Rangep R y" by(induction rule: rtrancl_path.induct)(auto elim: rtrancl_path.cases) lemma rtrancl_path_nth: "\<lbrakk> rtrancl_path R x xs y; i < length xs \<rbrakk> \<Longrightarrow> R ((x # xs) ! i) (xs ! i)" proof(induction arbitrary: i rule: rtrancl_path.induct) case step thus ?case by(cases i) simp_all qed simp lemma rtrancl_path_last: "\<lbrakk> rtrancl_path R x xs y; xs \<noteq> [] \<rbrakk> \<Longrightarrow> last xs = y" by(induction rule: rtrancl_path.induct)(auto elim: rtrancl_path.cases) lemma rtrancl_path_mono: "\<lbrakk> rtrancl_path R x p y; \<And>x y. R x y \<Longrightarrow> S x y \<rbrakk> \<Longrightarrow> rtrancl_path S x p y" by(induction rule: rtrancl_path.induct)(auto intro: rtrancl_path.intros) end
{-# OPTIONS_GHC -fno-warn-dodgy-exports #-} {- | an incomplete extension of dimensional-tf to work with hmatrix and ad Haddocks are organized to follow hmatrix note: for subscripting, use the 'HNat' while the units still use 'N.NumType' TODO: * Friendly syntax for introduction (more matD) * Friendly syntax for elimination (matD as pattern) * A pretty-printer that multiplies out the dimensions at each place? The current show instance makes you mentally multiply out row and column units (which helps you to see the big picture, but may be more work in other cases) * check that all types that could could be inferred are * default columns/rows to dimensionless? * missing operations (check export list comments) -} module DimMat.Internal where import Foreign.Storable (Storable) import GHC.Exts (Constraint) -- import Data.Type.Equality (type (==)) import qualified Prelude as P import Prelude (Double) import Numeric.Units.Dimensional hiding (Mul, Div) import Numeric.Units.Dimensional.Prelude hiding (Mul, Div) import qualified Numeric.Units.Dimensional as D import qualified Numeric.LinearAlgebra as H import qualified Numeric.LinearAlgebra.LAPACK as H import Text.PrettyPrint.ANSI.Leijen import Data.List (transpose) import Data.HList.CommonMain hiding (MapFst) -- * Replacements for Dimensional classes -- | a version of Numeric.Units.Dimensional.'D.Mul' which -- requires the arguments to include the 'D.Dim' type constructor class (D.Mul a b c) => Mul a b c instance (D.Mul a b c, a ~ Dim l m t i th n j, b ~ Dim l' m' t' i' th' n' j', c ~ Dim l'' m'' t'' i'' th'' n'' j'') => Mul a b c -- | a version of Numeric.Units.Dimensional.'D.Div' which -- requires the arguments to include the 'D.Dim' type constructor class (D.Div a b c) => Div a b c instance (D.Div a b c, a ~ Dim l m t i th n j, b ~ Dim l' m' t' i' th' n' j', c ~ Dim l'' m'' t'' i'' th'' n'' j'') => Div a b c -- * AD {- $ad TODO: gradients, hessians, etc. Types for derivative towers can see hlist's @HList\/Data\/HList\/broken\/Lazy.hs@, but laziness doesn't really make much sense if the @take@ that is eventually used to get a finite list for printing etc. Complications include the fact that AD.grad needs a traversable, but hmatrix stuff is not traversable (due needing Storable). In ipopt-hs I got around this problem by copying data. Perhaps that is the solution? > BROKEN > grad :: (Num a, AreRecips i iinv, H.Element a, Storable a, > MapMultEq o iinv r) => > (forall s. (AD.Mode s, H.Container H.Vector (AD.AD s a), > Storable (AD.AD s a), H.Field (AD.AD s a)) > => DimMat '[i] (AD.AD s a) > -> Quantity o (AD.AD s a)) > -> DimMat '[i] a > -> DimMat '[r] a > grad f (DimVec x) = DimMat (H.fromLists [AD.grad (unQty . f . DimVec . H.fromList) (H.toList x)]) > where unQty (Dimensional a) = a -} #ifdef WITH_AD {- | >>> let ke velocity = velocity*velocity*(1*~kilo gram) >>> diff ke (3 *~ (metre/second)) 6.0 m^-1 kg^-1 s -} diff :: (Num a) => (forall s. AD.Mode s => Dimensional v x (AD.AD s a) -> Dimensional v y (AD.AD s a)) -> Dimensional v x a -> Dimensional v (Div x y) a diff f z = Dimensional $ AD.diff (unD . f . Dimensional) (unD z) where unD (Dimensional a) = a #endif -- * GADT for linear algebra with units {- | Generalization of 'Dimensional' to matrices and vectors. Units in each coordinate are known at compile-time. This wraps up HMatrix. [@ 'DMat' @] the units at coordinate ij are @(r1 ': r)_i (DOne ': c)_j@ [@ 'DVec' @] the units at coordinate i are @(r1 ': r)_i@ [@ DScal @] is the same as Dimensional -} data D (sh :: ( *, [[ * ]])) e where DMat :: (H.Container H.Matrix e, H.Field e) => H.Matrix e -> D '(r1,[r, c]) e DVec :: (H.Container H.Vector e, H.Field e) => H.Vector e -> D '(r1, '[r]) e DScal :: (H.Field e) => e -> D '(r1,'[]) e instance (Show a, PPUnits sh) => Pretty (D sh a) where pretty (DVec v) = case ppUnits (Proxy :: Proxy sh) of [rs] -> vcat [ dullgreen (string label) <+> string (show e) | (e,label) <- H.toList v `zip` pad rs ] pretty (DMat m) = case ppUnits (Proxy :: Proxy sh) of [rs,cs] -> vcat $ map (hsep . onHead dullgreen) $ transpose $ map (onHead dullgreen . map string . pad) $ zipWith (\a b -> a:b) ((show (H.rows m) ++ "><"++ show (H.cols m)) : cs) $ transpose $ zipWith (\r e -> r : map show e) rs (H.toLists m) where onHead f (x:xs) = f x : xs onHead _ [] = [] instance Pretty (D sh a) => Show (D sh a) where showsPrec p x = showsPrec p (pretty x) -- ** pretty instance pad :: [String] -> [String] pad [] = [] pad xs = let w = maximum (map length xs) in map (\x -> take w $ x ++ replicate w ' ') xs class PPUnits (sh :: k) where ppUnits :: Proxy sh -> [[String]] instance forall (r1 :: *) (r::[*]) (c :: [*]) l m t i th n j. (PPUnits [r1 ': r, c], Show (Quantity r1 Int), PPUnits' c, PPUnits' r, r1 ~ Dim l m t i th n j) => PPUnits '(r1, [r,c]) where ppUnits _ = ppUnits (Proxy :: Proxy [r1 ': r, DOne ': c]) instance (PPUnits' x, PPUnits xs) => PPUnits (x ': xs) where ppUnits _ = ppUnits' (Proxy :: Proxy x) : ppUnits (Proxy :: Proxy xs) instance PPUnits '[] where ppUnits _ = [] class PPUnits' (sh :: [ * ]) where ppUnits' :: Proxy sh -> [String] instance (PPUnits' xs) => PPUnits' (DOne ': xs) where ppUnits' _ = "1" : ppUnits' (Proxy :: Proxy xs) instance (ShowDimSpec x, PPUnits' xs) => PPUnits' (x ': xs) where ppUnits' _ = showDimSpec (Proxy :: Proxy x) : ppUnits' (Proxy :: Proxy xs) instance PPUnits' '[] where ppUnits' _ = [] class ShowDimSpec a where showDimSpec :: Proxy a -> String instance (Show (Quantity a Int), Dim l m t i th n j ~ a) => ShowDimSpec a where showDimSpec _ = case drop 2 $ show (1 *~ (Dimensional 1 :: Unit a Int)) of "" -> "1" x -> x -- * Constraints {- $justification A major theme in this library is that type inference goes in whichever direction it can: in ordinary haskell it is very common for argument types to be determined by the result types. For example see any code that uses 'Num' or 'Read'. When we use type families, things look more convenient: @ data Nat = S Nat | Z type family Add (a :: Nat) (b :: Nat) :: Nat type instance Add Z b = b type instance Add (S a) b = Add a (S b) @ But ghc is unable to deduce things like @a ~ Z@ given evidence such as @Add Z a ~ Z@. One way around this is to use @ConstraintKinds@: @ type AddT (a :: Nat) (b :: Nat) (c :: Nat) = (Add a b ~ c, Sub c a ~ b, Sub c b ~ a) @ Which leads to functions like @f :: AddT a b ab => ... @. This is bad for a couple reasons: * the right-hand-side of the type can only mention type variables on the left-hand-side. * the left hand side can only bind type variables. Working around this leads to many auxiliary type families such as Fst, Snd and Head, or leads to a @type family AddT@ So below many constraints expressed as classes, since they have less of those limitations. -} -- | @a*b = c@ when any are lists class MultEq (a :: k1) (b :: k2) (c :: k3) -- instance (Zip3 MultEq aas bbs ccs) => MultEq aas bbs ccs instance Zip3 Mul as bs cs => MultEq as bs cs instance Zip1 Mul as b c => MultEq as b c instance Zip1 Mul bs a c => MultEq a bs c instance (Zip1 Mul cs aInv b, Mul a aInv DOne) => MultEq a b cs instance (SameLength as bs, Zip2 Mul as bs c) => MultEq as bs c instance (SameLength as cs, Zip2 Div as cs bInv, Mul b bInv DOne) => MultEq as b cs instance (Zip2 Div bs cs aInv, SameLength bs cs, Mul a aInv DOne) => MultEq a bs cs instance Mul a b c => MultEq a b c -- ** Zip class (SameLength a b, SameLength b c) => Zip3 (op :: k -> k -> k -> Constraint) (a :: [k]) (b :: [k]) (c :: [k]) instance (SameLength aas bbs, SameLength ccs bbs, op a b c, (a ': as) ~ aas, (b ': bs) ~ bbs, (c ': cs) ~ ccs, Zip3 op as bs cs) => Zip3 op aas bbs ccs instance Zip3 op '[] '[] '[] class (SameLength a b) => Zip2 (op :: k -> k -> k -> Constraint) (a :: [k]) (b :: [k]) (c :: k) instance (SameLength aas bbs, op a b c, (a ': as) ~ aas, (b ': bs) ~ bbs, Zip2 op as bs c) => Zip2 op aas bbs c instance Zip2 op '[] '[] c class Zip1 (op :: k -> k -> k -> Constraint) (a :: [k]) (b :: k) (c :: k) instance ((a ': as) ~ aas, op a b c, Zip1 op as b c) => Zip1 op aas b c instance Zip1 op '[] b c {- | given @ijs :: [[Quantity a]]@ (except the : and [] constructors are actually (,) and (), ie. a HList that doesn't use the HList constructors), calculate a @DimMat rowUnits colUnits@, where the outer product of rowUnits and colUnits gives the units at each index in the ijs. The first element of colUnits is DOne. -} class (SameLength a ab) => Outer a b ab instance Outer '[] b '[] instance (SameLength aas ccs, (a ': as) ~ aas, (c ': cs) ~ ccs, MultEq a b c, Outer as b cs) => Outer aas b ccs -- * DimMatFromTuple class DimMatFromTuple ijs r1 r c e type family TupleToHListU (a :: *) :: [*] type instance TupleToHListU (a, b) = () ': TupleToHListU b type instance TupleToHListU () = '[] type family TuplesToHListU (a :: *) :: [[*]] type instance TuplesToHListU (a, b) = TupleToHListU a ': TuplesToHListU b type instance TuplesToHListU () = '[] instance (Outer (r1 ': r) (DOne ': c) ijs', DMFromTuple1 e ijs ijs', SameLength (TuplesToHListU ijs) ijs') => DimMatFromTuple ijs r1 r c e -- | helper for 'DimMatFromTuple' type family DMFromTuple1 e b (b' :: [[*]]) :: Constraint type family DMFromTuple2 e b (b' :: [*]) :: Constraint type family DMFromTuple3 e b b' :: Constraint type instance DMFromTuple3 e (Quantity b e') b' = (e ~ e', b ~ b') type instance DMFromTuple1 e (x, xs) (x' ': xs') = (TupleToHListU x `SameLength` x', DMFromTuple2 e x x', DMFromTuple1 e xs xs') type instance DMFromTuple1 e () xs = (xs ~ '[]) type instance DMFromTuple2 e (x, xs) (x' ': xs') = (DMFromTuple3 e x x', DMFromTuple2 e xs xs') type instance DMFromTuple2 e () xs = (xs ~ '[]) -- | just for types produced by the matD quasiquote toDM :: DimMatFromTuple ijs r1 r c e => ijs -> Proxy (D '(r1, [r, c]) e) toDM _ = Proxy -- | @InnerCxt t a b = t ~ 'H.dot' a b@ type family InnerCxt (t :: k) (a :: [k]) (b :: [k]) :: Constraint type instance InnerCxt t (a ': as) (b ': bs) = (MultEq a b t, InnerCxt t as bs) type instance InnerCxt t '[] '[] = () class (SameLength a b, InnerCxt c a b) => Inner (a :: [*]) (b :: [*]) (c :: *) instance (SameLength aas bbs, InnerCxt c aas bbs) => Inner aas bbs c -- | @ProdEq a b@ is @product a ~ b@ class ProdEq a b instance (ProdEq as b', Mul a b' b) => ProdEq (a ': as) b instance (dOne ~ DOne) => ProdEq '[] dOne -- | @RecipEq a aInv@ is @a*aInv ~ DOne@ (or a list of DOne) class RecipEq (a :: k) (aInv :: k) instance (MultEq as aInvs DOne) => RecipEq as aInvs -- | @AtEq a n b m c@ calculates @(At a n \`Mult\` At b m) ~ c@, -- but also can infer part of the `a` if the `b` and `c` are known type family AtEq2 (a :: [k]) (n :: HNat) (b :: [k]) (m :: HNat) (c :: k) :: Constraint type instance AtEq2 (a ': as) HZero (b ': bs) HZero c = (MultEq a b c) type instance AtEq2 (a ': as) (HSucc n) bs m c = AtEq2 as n bs m c type instance AtEq2 as HZero (b ': bs) (HSucc m) c = AtEq2 as HZero bs m c type family AtEq (a :: [k]) (n :: HNat) (b :: k) :: Constraint type instance AtEq (a ': as) HZero b = (a ~ b) type instance AtEq (a ': as) (HSucc n) b = AtEq as n b -- | Data.Packed.Vector.'H.@>' (@>) :: (HNat2Integral i, AtEq r i ri, MultEq r1 ri u) => D '(r1,'[r]) a -> Proxy i -> Quantity u a DVec v @> i = Dimensional (v H.@> hNat2Integral i) -- | Data.Packed.Matrix.'H.@@>' (@@>) :: (HNat2Integral i, HNat2Integral j, AtEq2 (r1 ': r) i (DOne ': c) j ty) => D '(r1, [r,c]) a -> (Proxy i, Proxy j) -> Quantity ty a DMat m @@> (i,j) = Dimensional (m H.@@> (hNat2Integral i,hNat2Integral j)) pnorm :: (AllEq r1 r, AllEq DOne c) => H.NormType -> D '(r1, [r, c]) a -> Quantity r1 (H.RealOf a) pnorm normType (DMat a) = Dimensional (H.pnorm normType a) {- | @AllEq a xs@ is like @all (all (a==)) xs@, @all (a ==) xs@, @a == xs@: whichever amount of [ ] is peeled off before making the comparison (with ~) -} class AllEq (a :: k1) (xs :: k2) instance (a ~ x, AllEq a xs) => AllEq a (x ': xs) instance AllEq a '[] instance AllEq '[] xs instance (AllEq a xs, AllEq as xs) => AllEq (a ': as) xs {- | @c = a `dot` b@ is one of: > c_ij = sum_j a_ij b_jk > c_k = sum_j a_j b_jk > c_i = sum_j a_ij b_j > c = sum_j a_j b_j -} class Dot a b c {- | a b -> c -} where dot :: H.Element e => D a e -> D b e -> D c e instance ( MultEq (a ': ra) b (c ': rc), MultEq ca rb b, shA ~ '(a,[ra, ca]), shB ~ '(b, rb ': cb), shC ~ '(c, rc ': cb)) => Dot shA shB shC where dot (DMat a) (DMat b) = DMat (H.multiply a b) dot (DMat a) (DVec b) = DVec (H.mXv a b) {- dot (DVec a) (DMat b) = DVec (H.vXm a b) dot (DVec a) (DVec b) = DScal (H.dot a b) -} class DotS s a b instance (rest' ~ rest, MultEq s (a ': as) (b ': bs)) => DotS s '(a, as ': rest) '(b, bs ': rest') class Trans a b where trans :: D a e -> D b e instance (a ~ '(r1, [x,y]), b ~ '(r1, [y,x])) => Trans a b where trans (DMat a) = DMat (H.trans a) {- | type for a pseudoinverse (and inverse): The single instance comes from looking at inverses from a 2x2 matrix (let's call A): > a b > c d and the inverse * determinant of the original > d -b > -c a In the product A * A^-1 the diagonal is dimensionless ('DOne'). That happens if the row and column type-level unit lists are reciprocals of eachother ('AreRecips'), so the constraint on the instance of PInv encodes this exactly (plus some constraints requiring that sh and sh' are at least 1x1) -} class PInv a b where pinv :: D a e -> D b e type family LengthSndTwo (a :: k) :: Constraint type instance LengthSndTwo '(a, as) = SameLength as '[(), ()] type AreRecips a b = MultEq a b DOne instance (MultEq ra cb a, MultEq ca rb b, AreRecips a b, bSh ~ '(b, [rb, cb]), aSh ~ '(a, [ra, ca])) => PInv aSh bSh where pinv (DMat a) = DMat (H.pinv a) inv :: (PInv a b, b ~ '(t1, [t2, t3])) => D a e -> D b e inv (DMat a) = DMat (H.inv a) pinvTol :: (PInv a b, b ~ '(t1, [t2, t3]) ) => Double -> D a e -> D b e pinvTol tol (DMat a) = DMat (H.pinvTol tol a) class Det a b where det :: D a e -> Quantity b e instance (SameLength r c, ProdEq (r1 ': r) (pr :: *), ProdEq c (pc :: *), MultEq pr pc b, a ~ '(r1, [r, c])) => Det a b where det (DMat a) = Dimensional (H.det a) {- | Numeric.LinearAlgebra.Algorithms.'H.expm' @y t = expm (scale t a) \`multiply\` y0@ solves the DE @y' = Ay@ where y0 is the value of y at time 0 -} expm :: (AreRecips r c) => D '(r1, [r, c]) a -> D '(r1, [r, c]) a expm (DMat a) = DMat (H.expm a) {- | Numeric.Container.'H.scale' -} class Scale a b c where scale :: Quantity a e -> D b e -> D c e fromQty :: H.Field e => Quantity a e -> D '(a, '[]) e fromQty (Dimensional a) = DScal a toQty :: D '(a, '[]) e -> Quantity a e toQty (DScal a) = Dimensional a instance (MultEq a (r1 ': r) (r1' ': r'), b ~ '(r1, r ': rs), c ~ '(r1', r' ': rs)) => Scale a b c where scale (Dimensional t) (DMat a) = DMat (H.scale t a) scale (Dimensional t) (DVec a) = DVec (H.scale t a) {- | Numeric.Container.'H.scaleRecip' -} class ScaleRecip a b c where scaleRecip :: D '(a, '[]) e -> D b e -> D c e class ScaleRecip1 (bool :: Bool) a b c where scaleRecip1 :: Proxy bool -> D '(a, '[]) e -> D b e -> D c e instance (ScaleRecipCxt r1 r1' r r' rs rs' a b c , rs' ~ '[ t1 ] ) => ScaleRecip1 True a b c where scaleRecip1 _ (DScal t) (DMat a) = DMat (H.scaleRecip t a) instance (ScaleRecipCxt r1 r1' r r' rs rs' a b c, rs' ~ '[]) => ScaleRecip1 False a b c where scaleRecip1 _ (DScal t) (DVec a) = DVec (H.scaleRecip t a) instance (HEq (HLength bs) (HSucc (HSucc HZero)) bool1, HEq (HLength cs) (HSucc (HSucc HZero)) bool1, ScaleRecip1 bool1 a '(b, bs) '(c, cs)) => ScaleRecip a '(b, bs) '(c, cs) where scaleRecip = scaleRecip1 (Proxy :: Proxy bool1) type ScaleRecipCxt (r1 :: *) (r1' :: *) r r' rs rs' (a :: *) b c = (MultEq a (r1' ': r') (r1 ': r) , MultEq rs rs' DOne, b ~ '(r1, r ': rs), c ~ '(r1', r' ': rs')) -- | a shortcut for @scaleRecip (DScal 1)@ recipMat :: forall b c e. (H.Field e, ScaleRecip DOne b c) => D b e -> D c e recipMat m = scaleRecip (DScal 1 :: D '(DOne, '[]) e) m liftH2 :: ( forall h f. (H.Container f e, h ~ f e) => h -> h -> h) -> D a e -> D a e -> D a e liftH2 f (DMat a) (DMat b) = DMat (f a b) liftH2 f (DVec a) (DVec b) = DVec (f a b) add a b = liftH2 H.add a b sub a b = liftH2 H.sub a b mulMat :: ( MultEq as bs cs, MultEq a b c, cs ~ '[t1 , t2] ) => D '(a,as) e -> D '(b,bs) e -> D '(c,cs) e mulMat (DMat a) (DMat b) = DMat (H.mul a b) mulVec :: ( MultEq as bs cs, MultEq a b c, cs ~ '[t1] ) => D '(a,as) e -> D '(b,bs) e -> D '(c,cs) e mulVec (DVec a) (DVec b) = DVec (H.mul a b) divideMat :: ( MultEq as cs bs, MultEq a c b, cs ~ '[t1 , t2] ) => D '(a,as) e -> D '(b,bs) e -> D '(c,cs) e divideMat (DMat a) (DMat b) = DMat (H.divide a b) divideVec :: ( MultEq as cs bs, MultEq a c b, cs ~ '[t1] ) => D '(a,as) e -> D '(b,bs) e -> D '(c,cs) e divideVec (DVec a) (DVec b) = DVec (H.divide a b) arctan2 :: (bs ~ MapMapConst DOne as) => D '(a,as) e -> D '(a,as) e -> D '(b,bs) e arctan2 (DMat a) (DMat b) = DMat (H.arctan2 a b) arctan2 (DVec a) (DVec b) = DVec (H.arctan2 a b) equal :: D a e -> D a e -> Bool equal (DMat a) (DMat b) = H.equal a b equal (DVec a) (DVec b) = H.equal a b {- | @cmap f m@ gives a matrix @m'@ @f@ is applied to -} class CMap f a b e e' where cmap :: f -> D a e -> D b e' -- | Maybe there's a way to implement in terms of the real cmap (possibly -- unsafeCoerce?) instance (ToHLists sh e xs, FromHLists xs' sh' e', SameLength xs xs', HMapCxt HList (HMap f) xs xs') => CMap f sh sh' e e' where cmap f m = fromHLists (HMap f `hMap` (toHLists m :: HList xs) :: HList xs') type family AppendEq' (a :: [k]) (b :: [k]) (ab :: [k]) :: Constraint type instance AppendEq' (a ': as) b (a' ': abs) = (a ~ a', AppendEq' as b abs) type instance AppendEq' '[] b abs = (b ~ abs) -- | a bit overkill? -- @a ++ b = ab@ type AppendEq a b ab = (ab ~ HAppendR a b, AppendEq' a b ab, SameLength (DropPrefix a ab) b, SameLength (DropPrefix b ab) a) type instance HAppendR (x ': xs) ys = x ': HAppendR xs ys type instance HAppendR '[] ys = ys type family DropPrefix (a :: [k]) (ab :: [k]) :: [k] type instance DropPrefix (a ': as) (a' ': abs) = DropPrefix as abs type instance DropPrefix '[] bs = bs {- | the slightly involved type here exists because ci1 and ci2 both start with DOne, but ci2's contribution to ci3 does not need a DOne at the start. Another way to read the constraints here is: > map (*rem) (a11 : ri) = b11 : bi > ci3 = ci1 ++ map (*rem) ci2 The same idea happens with vconcat. -} hconcat :: ( MultEq (rem :: *) a b, MultEq rem ra rb, MultEq rem (DOne ': cb) cb', AppendEq ca cb' cc ) => D '(a, [ra,ca]) e -> D '(b, [rb, cb]) e -> D '(a, [ra, cc]) e hconcat (DMat a) (DMat b) = DMat (H.fromBlocks [[a, b]]) vconcat :: (AppendEq ra (b ': rb) rc) => D '(a, '[ra,ca]) e -> D '(b, '[rb,ca]) e -> D '(a, '[rc,ca]) e vconcat (DMat a) (DMat b) = DMat (H.fromBlocks [[a],[b]]) rank, rows, cols :: D t a -> Int rank (DMat a) = H.rank a rows (DMat a) = H.rows a cols (DMat a) = H.cols a -- | H.'H.rows' except type-level rowsNT :: D '(a, r ': c) e -> Proxy (HLength (a ': ri)) rowsNT _ = Proxy -- | H.'H.cols' except type-level colsNT :: D '(a, r ': c ': cs) e -> Proxy (HLength (DOne ': c)) colsNT _ = Proxy -- | (m `hasRows` n) constrains the matrix/vector @m@ to have @n@ rows hasRows :: (SameLength (HReplicateR n ()) r, -- forwards HLength r ~ n -- backwards ) => D '(a, ra ': ca) e -> Proxy (n :: HNat) -> D '(a, ra ': ca) e hasRows x _ = x -- | (m `hasRows` n) constrains the matrix/vector @m@ to have @n@ rows hasCols :: (SameLength (HReplicateR n ()) ci, -- forwards HLength ci ~ n -- backwards ) => D '(a, ra ': ca ': rest) e -> Proxy (n :: HNat) -> D '(a, ra ': ca ': rest) e hasCols x _ = x -- | H.'H.scalar' class (MapConst '[] as ~ as) => Scalar as where scalar :: D '(a, '[]) e -> D '(a, as) e instance Scalar '[ '[] ] where scalar (DScal a) = DVec (H.scalar a) instance Scalar '[ '[], '[] ] where scalar (DScal a) = DMat (H.scalar a) {- | Numeric.Container.'H.konst', but the size is determined by the type. >>> let n = hSucc (hSucc hZero) -- 2 >>> konst ((1::Double) *~ second) `hasRows` n `hasCols` n 2><2 1 1 s 1.0 1.0 s 1.0 1.0 -} konst :: forall e a ra ca. (H.Field e, HNat2Integral (HLength (a ': ra)), HNat2Integral (HLength (DOne ': ca)), AllEq DOne ca, AllEq a ra) => D '(a, '[]) e -> D '(a, '[ra, ca]) e konst (DScal a) = DMat (H.konst a (hNat2Integral (Proxy :: Proxy (HLength (a ': ra))), hNat2Integral (Proxy :: Proxy (HLength (DOne ': ca))))) -- | identity matrix. The size is determined by the type. ident :: forall ones e. (H.Field e, HNat2Integral (HLength (DOne ': ones))) => D '(DOne, [ones, ones]) e ident = DMat (H.ident (hNat2Integral (Proxy :: Proxy (HLength (DOne ': ones))))) -- | zero matrix. The size and dimension is determined by the type. zeroes :: forall c a r e. (H.Field e, HNat2Integral (HLength (a ': r)), HNat2Integral (HLength (DOne ': c))) => D '(a, '[r, c]) e zeroes = DMat (H.konst 0 (hNat2Integral (Proxy :: Proxy (HLength (a ': r))), hNat2Integral (Proxy :: Proxy (HLength (DOne ': c))))) type family CanAddConst (a :: k) (m :: [[k]]) :: Constraint type instance CanAddConst a [as, ones] = (AllEq a as, AllEq '[] ones) type instance CanAddConst a '[as] = (AllEq a as) addConstant :: (H.Field e, CanAddConst a sh) => D '(a, '[]) e -> D '(a, sh) e -> D '(a, sh) e addConstant (DScal a) (DMat b) = DMat (H.addConstant a b) addConstant (DScal a) (DVec b) = DVec (H.addConstant a b) conj :: D sh a -> D sh a conj (DMat a) = DMat (H.conj a) conj (DVec a) = DVec (H.conj a) -- | conjugate transpose ctrans x = conj . trans $ x diag :: (MapConst DOne r ~ c, SameLength r c) => D '(a, '[r]) t -> D '(a, '[r,c]) t diag (DVec a) = DMat (H.diag a) -- | 'H.blockDiag'. The blocks should be provided as: -- -- @blockDiag $ 'hBuild' m1 m2 m3@ -- -- only available if hmatrix >= 0.15 diagBlock :: (HMapOut UnDimMat (b ': bs) (H.Matrix e), Num e, H.Field e, AppendShOf b bs (D '(a, sh) e), sh ~ '[r,c]) => HList (b ': bs) -> D '(a, sh) e diagBlock pairs = DMat (H.diagBlock (hMapOut UnDimMat pairs)) data UnDimMat = UnDimMat instance (D sh a ~ x, H.Matrix a ~ y) => ApplyAB UnDimMat x y where applyAB _ (DMat x) = x class DiagBlock (bs :: [*]) t -- | @AppendShOf a [b,c,d] aas@ makes aas have the type of a matrix that -- has a,b,c,d along the diagonal class AppendShOf a (as :: [*]) aas instance (e ~ f, f ~ g, AppendShOf (D ab e) ds z, AppendDims a b ab, -- constraints to force D in the type x ~ D a e, y ~ D b f, z ~ D c g) => AppendShOf x (y ': ds) z instance (x ~ z) => AppendShOf x '[] z class AppendDims (a :: (*, [[*]])) (b :: (*, [[*]])) (c :: (*, [[*]])) | a b -> c, c a -> b, c b -> a instance (c ~ a, AppendEq ra (b ': rb) rc, AppendEq ca cb cc) => AppendDims '(a, [ra,ca]) '(b, [rb,cb]) '(c, [rc,cc]) -- how to handle vectors? --type instance AppendDims '(a, '[ra]) '(b, '[rb]) = '(a, '[HAppendR ra (b ': rb)]) class ToHList sh e result where toHList :: D sh e -> HList result -- | given a vector like @x = DimMat '[units] e@ this does something like -- @[ (x \@> i) | i <- [1 .. n] ]@, if we had comprehensions for HLists instance (HListFromList e e1, SameLength result e1, HMapCxt HList AddDimensional e1 result, -- HMapAddDimensional result e1, ToHListRow (r ': rs) e result) => ToHList '(r, '[rs]) e result where toHList (DVec v) = case hListFromList (H.toList v) :: HList e1 of e1 -> hMap AddDimensional e1 class HMapAddDimensional (a :: [*]) (b :: [*]) | a -> b instance HMapAddDimensional '[] '[] instance (HMapAddDimensional as bs, dta ~ Quantity t b) => HMapAddDimensional (dta ': as) (b ': bs) class HListFromList e e' | e' -> e where hListFromList :: [e] -> HList e' instance HListFromList e '[e] where hListFromList (e : _) = HCons e HNil hListFromList _ = error "HListFromList: not enough input" instance (e ~ e', HListFromList e es) => HListFromList e (e' ': es) where hListFromList (e : es) = e `HCons` hListFromList es type family ToHListRow (a :: [*]) e (b :: [*]) :: Constraint type instance ToHListRow (a ': as) e (b ': bs) = (Quantity a e ~ b, ToHListRow as e bs) data AddDimensional = AddDimensional instance (Quantity t x ~ y) => ApplyAB AddDimensional x y where applyAB _ x = Dimensional x class FromHList list sh e where fromHList :: HList list -> D sh e instance (H.Field e, HMapOut RmDimensional list e, ToHListRow (r ': rs) e list) => FromHList list '(r, '[rs]) e where fromHList xs = DVec (H.fromList (hMapOut RmDimensional xs)) data RmDimensional = RmDimensional instance (x ~ Quantity d y) => ApplyAB RmDimensional x y where applyAB _ (Dimensional a) = a class FromHLists lists sh e where fromHLists :: HList lists -> D sh e -- | [[Dim e unit]] -> DimMat units e instance (ToHListRows' (r1 ': r) c e lists, HMapOut (HMapOutWith RmDimensional) lists [e], H.Field e) => FromHLists lists '(r1, [r,c]) e where fromHLists xs = DMat (H.fromLists (hMapOut (HMapOutWith RmDimensional) xs)) newtype HMapOutWith f = HMapOutWith f instance (HMapOut f l e, es ~ [e], HList l ~ hl) => ApplyAB (HMapOutWith f) hl es where applyAB (HMapOutWith f) = hMapOut f class ToHListRows' (r :: [*]) (c :: [*]) (e :: *) (rows :: [*]) instance ToHListRows' '[] c e '[] instance (ToHListRows' r c e rows, MultEq r c c', HMapCxt HList (AddQty e) c' row') => ToHListRows' (r1 ': r) c e (hListRow ': rows) data AddQty u instance (qty ~ Quantity u e) => ApplyAB (AddQty u) e qty where applyAB _ = Dimensional class ToHLists sh e xs where toHLists :: D sh e -> HList xs -- | DimMat units e -> [[Dim e unit]] instance (HListFromList e e1, HListFromList (HList e1) e2, HMapCxt HList (HMap AddDimensional) e2 xs, ToHListRows' ri ci e xs, SameLength e2 xs, (r1 ': r) ~ ri, (DOne ': c) ~ ci ) => ToHLists '(r1, [r,c]) e xs where toHLists (DMat m) = case hListFromList (map hListFromList (H.toLists m) :: [HList e1]) :: HList e2 of e2 -> hMap (HMap AddDimensional) e2 {- still bad class PairsToList a t where pairsToList :: a -> [H.Matrix t] instance PairsToList () t where pairsToList _ = [] instance (PairsToList b t, t' ~ t) => PairsToList (DimMat sh t',b) t where pairsToList (DimMat a,b) = a : pairsToList b class EigV (sh :: [[ [DimSpec *] ]]) (eigenValue :: [[DimSpec *]]) (eigenVector :: [[[DimSpec *]]]) instance ( SameLengths [r,c,r',c',rinv,cinv,eigval,erinv], -- ZipWithMul r c eigval, MapConst '[] r ~ eigval, PInv [r',c'] [rinv,cinv], -- AreRecips r' cinv, -- AreRecips c' rinv, cinv ~ c, c ~ ('[] ': _1), c' ~ ('[] ': _2), ZipWithMul eigval rinv erinv, MultiplyCxt [r',c'] erinv r, sh ~ [r,c], sh' ~ [r',c']) => EigV sh eigval sh' -- | when no eigenvectors are needed type family EigE (sh :: [[ [DimSpec *] ]]) (eigenValue :: [ [DimSpec *] ]) :: Constraint type instance EigE [r,c] eigval = ( SameLengths [r,c,eigval], ZipWithMul r c eigval) {- $eigs The Hmatrix eig factors A into P and D where A = P D inv(P) and D is diagonal. The units for eigenvalues can be figured out: > _____ > -1 | c > P D P = A = |r > | > _______ > | d > P = |c > | > _______ > | -1 > | c > -1 | > P = | -1 > |d So we can see that the dimension labeled `d-1` in P inverse is actually the same `c` in `A`. The actual units of `d` don't seem to matter because the `inv(d)` un-does any units that the `d` adds. So `d` can be all DOne. But another choice, such as 1/c would be more appropriate, since then you can expm your eigenvectors (not that that seems to be something people do)? To get the row-units of A to match up, sometimes `D` will have units. The equation ends up as D/c = r Please ignore the type signatures on 'eig' 'eigC' etc. instead look at the type of 'wrapEig' 'wrapEigOnly' together with the hmatrix documentation (linked). Perhaps the convenience definitions `eig m = wrapEig H.eig m` should be in another module. -} {- -- | 'wrapEig' H.'H.eig' eig m = wrapEig H.eig m -- | 'wrapEig' H.'H.eigC' eigC m = wrapEig H.eigC m -- | 'wrapEig' H.'H.eigH' eigH m = wrapEig H.eigH m -- | 'wrapEig' H.'H.eigH'' eigH' m = wrapEig H.eigH' m -- | 'wrapEig' H.'H.eigR' eigR m = wrapEig H.eigR m -- | 'wrapEig' H.'H.eigS' eigS m = wrapEig H.eigS m -- | 'wrapEig' H.'H.eigS'' eigS' m = wrapEig H.eigS' m -- | 'wrapEig' H.'H.eigSH' eigSH m = wrapEig H.eigSH m -- | 'wrapEig' H.'H.eigSH'' eigSH' m = wrapEig H.eigSH' m -- | 'wrapEigOnly' H.'H.eigOnlyC' eigOnlyC m = wrapEigOnly H.eigOnlyC m -- | 'wrapEigOnly' H.'H.eigOnlyH' eigOnlyH m = wrapEigOnly H.eigOnlyH m -- | 'wrapEigOnly' H.'H.eigOnlyR' eigOnlyR m = wrapEigOnly H.eigOnlyR m -- | 'wrapEigOnly' H.'H.eigOnlyS' eigOnlyS m = wrapEigOnly H.eigOnlyS m -- | 'wrapEigOnly' H.'H.eigenvalues' eigenvalues m = wrapEigOnly H.eigenvalues m -- | 'wrapEigOnly' H.'H.eigenvaluesSH' eigenvaluesSH m = wrapEigOnly H.eigenvaluesSH m -- | 'wrapEigOnly' H.'H.eigenvaluesSH'' eigenvaluesSH' m = wrapEigOnly H.eigenvaluesSH' m -} wrapEig :: (c' ~ ('[] ': _1), EigV [r,c] eigVal [r',c'], H.Field y, H.Field z) => (H.Matrix x -> (H.Vector y, H.Matrix z)) -> DimMat [r,c] x -> (DimMat '[eigVal] y, DimMat [r',c'] z) wrapEig hmatrixFun (DimMat a) = case hmatrixFun a of (e,v) -> (DimVec e, DimMat v) wrapEigOnly :: (EigE [r,c] eigVal, H.Field y) => (H.Matrix x -> H.Vector y) -> DimMat [r,c] x -> DimMat '[eigVal] y wrapEigOnly hmatrixFun (DimMat a) = case hmatrixFun a of (e) -> DimVec e -} -- | @\\a xs -> map (map (const a)) xs@ type family MapMapConst (a::k) (xs :: [[l]]) :: [[k]] type instance MapMapConst a (x ': xs) = MapConst a x ': MapMapConst a xs type instance MapMapConst a '[] = '[] -- | @\\a xs -> map (const a) xs@ type family MapConst (a :: k) (xs :: [l]) :: [k] type instance MapConst a (x ': xs) = a ': MapConst a xs type instance MapConst a '[] = '[] -- | convert from (a,(b,(c,(d,())))) to '[a,b,c,d] type family FromPairs (a :: *) :: [*] type instance FromPairs (a,b) = a ': FromPairs b type instance FromPairs () = '[] {- -- | @map fst@ type family MapFst (a :: *) :: [*] type instance MapFst ((a,_t) , as) = a ': MapFst as type instance MapFst () = '[] -- | @\\a xs -> map (/a) xs@ type family MapDiv (a :: k) (xs :: [k]) :: [k] type instance MapDiv a (x ': xs) = (x @- a) ': MapDiv a xs type instance MapDiv a '[] = '[] type family UnDQuantity (a :: [*]) :: [ [*] ] type instance UnDQuantity (x ': xs) = UnDQuantity1 x ': UnDQuantity xs type instance UnDQuantity '[] = '[] type family UnDQuantity1 (a :: *) :: [*] type instance UnDQuantity1 (Unit t x) = x type family DimMatFromTuple ijs :: * -> * type instance DimMatFromTuple ijs = DimMat [UnDQuantity (MapFst ijs), '[] ': MapDiv (UnDQuantity1 (Fst (Fst ijs))) (UnDQuantity (FromPairs (Snd (Fst ijs))))] type family Append (a :: [k]) (b :: [k]) :: [k] type instance Append (a ': as) b = a ': Append as b type instance Append '[] b = b -}
lemma mul_assoc (a b c : mynat) : (a * b) * c = a * (b * c) := begin induction c with d hd, repeat {rw mul_zero}, repeat {rw mul_succ}, rwa [hd, mul_add], end
""" Ai2 Ai2 performs over-approximated reachability analysis to compute the over-approximated output reachable set for a network. # Problem requirement 1. Network: any depth, ReLU activation (more activations to be supported in the future) 2. Input: HPolytope 3. Output: HPolytope # Return `ReachabilityResult` # Method Reachability analysis using split and join. # Property Sound but not complete. # Reference T. Gehr, M. Mirman, D. Drashsler-Cohen, P. Tsankov, S. Chaudhuri, and M. Vechev, "Ai2: Safety and Robustness Certification of Neural Networks with Abstract Interpretation," in *2018 IEEE Symposium on Security and Privacy (SP)*, 2018. """ struct Ai2 end function solve(solver::Ai2, problem::Problem) reach = forward_network(solver, problem.network, problem.input) return check_inclusion(reach, problem.output) end forward_layer(solver::Ai2, layer::Layer, inputs::Vector{<:AbstractPolytope}) = forward_layer.(solver, layer, inputs) function forward_layer(solver::Ai2, layer::Layer, input::AbstractPolytope) W, b, act = layer.weights, layer.bias, layer.activation outLinear = shiftcenter(linear_map(W, input), b) return transform(act, outLinear) end function transform(f::ReLU, P::AbstractPolytope) polys = VPolytope[] # check if 1:2^n relus is tighter range than relu(relu(...to the n)) for i in dim(P) pos = meet(P, i, true) neg = meet(P, i, false) relu_neg = VPolytope([f(v) for v in vertices_list(neg)]) #dimensional relu push!(polys, tovrep(pos)) push!(polys, relu_neg) end hull = polys[1] for P in polys[2:end] hull = convex_hull(hull, P) end return hull end # constraints are added in H-representation meet(V::VPolytope, pos::Bool) = meet(tohrep(V), pos) function meet(HP::HPolytope{T}, pos::Bool) where T H = copy(HP) # constraints are given by ax <= b so (-) is required for a positive constraint if (pos) d = Matrix(-1.0I, dim(H), dim(H)) else d = Matrix(1.0I, dim(H), dim(H)) end for i in size(d, 1) new_hs = LazySets.HalfSpace(d[i, :], zero(T)) addconstraint!(H, new_hs) end end shiftcenter(zono::Zonotope, shift::Vector) = Zonotope(zono.center + shift, zono.generators) shiftcenter(poly::AbstractPolytope, shift::Vector) = shiftcenter(tovrep(poly), shift) function shiftcenter(V::VPolytope, shift::Vector) shifted = [v + shift for v in vertices_list(V)] return VPolytope(shifted) end #= meet and join will still become necessary in the zonotope case The Case type is probably not necessary for correct dispatch =# # function meet(case::Case, H::HPolytope) # addconstraint!(H, constraint(case, H)) # return H # end # function constraint(case::Type{Case}, n_dims, constraint_dim) # space = zeros(n_dims) # if case == Pos # space[constraint_dim] = 1.0 # elseif case == Neg # space[constraint_dim] = -1.0 # end # return HalfSpace(space, 0.0) # end # constraint(case::Case, poly::AbstractPolytope) = constraint(typeof(case), dim((poly), case.i)
Largely due to immigration from Hungary , Bohemia and Moravia , the Jewish population of Zagreb quickly grew in size : from 1 @,@ 285 members in 1887 to 3 @,@ 237 members in 1900 , and then to 5 @,@ 970 members in 1921 . The synagogue became too small to accommodate the needs of the ever @-@ growing community . In 1921 a renovation was undertaken to increase the number of available seats . A 1931 plan to increase the capacity to 944 seats was ultimately abandoned . A central heating system was installed in 1933 .
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2013. // // This software is released under a three-clause BSD license: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // -------------------------------------------------------------------------- // $Maintainer: $ // $Authors: Hendrik Weisser $ // -------------------------------------------------------------------------- #ifndef OPENMS_ANALYSIS_MAPMATCHING_TRANSFORMATIONMODEL_H #define OPENMS_ANALYSIS_MAPMATCHING_TRANSFORMATIONMODEL_H #include <OpenMS/DATASTRUCTURES/Param.h> #include <gsl/gsl_bspline.h> #include <gsl/gsl_interp.h> namespace OpenMS { /** @brief Base class for transformation models Implements the identity (no transformation). Parameters and data are ignored. @ingroup MapAlignment */ class OPENMS_DLLAPI TransformationModel { public: /// Coordinate pair typedef std::pair<DoubleReal, DoubleReal> DataPoint; /// Vector of coordinate pairs typedef std::vector<DataPoint> DataPoints; /// Constructor TransformationModel() {} /// Alternative constructor (derived classes should implement this one!) TransformationModel(const TransformationModel::DataPoints &, const Param &) : params_() {} /// Destructor virtual ~TransformationModel() {} /// Evaluates the model at the given value virtual DoubleReal evaluate(const DoubleReal value) const { return value; } /// Gets the (actual) parameters void getParameters(Param & params) const { params = params_; } /// Gets the default parameters static void getDefaultParameters(Param & params) { params.clear(); } protected: /// Parameters Param params_; }; /** @brief Linear model for transformations The model can be inferred from data or specified using explicit parameters. If data is given, a least squares fit is used to find the model parameters (slope and intercept). Depending on parameter @p symmetric_regression, a normal regression (@e y on @e x) or symmetric regression (@f$ y - x @f$ on @f$ y + x @f$) is performed. Without data, the model can be specified by giving the parameters @p slope and @p intercept explicitly. @ingroup MapAlignment */ class OPENMS_DLLAPI TransformationModelLinear : public TransformationModel { public: /** @brief Constructor @exception IllegalArgument is thrown if neither data points nor explicit parameters (slope/intercept) are given. */ TransformationModelLinear(const DataPoints & data, const Param & params); /// Destructor ~TransformationModelLinear(); /// Evaluates the model at the given value virtual DoubleReal evaluate(const DoubleReal value) const; using TransformationModel::getParameters; /// Gets the "real" parameters void getParameters(DoubleReal & slope, DoubleReal & intercept) const; /// Gets the default parameters static void getDefaultParameters(Param & params); /** @brief Computes the inverse @exception DivisionByZero is thrown if the slope is zero. */ void invert(); protected: /// Parameters of the linear model DoubleReal slope_, intercept_; /// Was the model estimated from data? bool data_given_; /// Use symmetric regression? bool symmetric_; }; /** @brief Interpolation model for transformations Between the data points, the interpolation uses the neighboring points. Outside the range spanned by the points, we extrapolate using a line through the first and the last point. Different types of interpolation (controlled by the parameter @p interpolation_type) are supported: "linear", "polynomial", "cspline", and "akima". Note that the number of required data points may differ between types. @ingroup MapAlignment */ class OPENMS_DLLAPI TransformationModelInterpolated : public TransformationModel { public: /** @brief Constructor @exception IllegalArgument is thrown if there are not enough data points or if an unknown interpolation type is given. */ TransformationModelInterpolated(const DataPoints & data, const Param & params); /// Destructor ~TransformationModelInterpolated(); /// Evaluates the model at the given value DoubleReal evaluate(const DoubleReal value) const; /// Gets the default parameters static void getDefaultParameters(Param & params); protected: /// Data coordinates std::vector<double> x_, y_; /// Number of data points size_t size_; /// Look-up accelerator gsl_interp_accel * acc_; /// Interpolation function gsl_interp * interp_; /// Linear model for extrapolation TransformationModelLinear * lm_; }; /** @brief B-spline model for transformations In the range of the data points, the transformation is evaluated from a cubic smoothing spline fit to the points. The number of breakpoints is given as a parameter (@p num_breakpoints). Outside of this range, linear extrapolation through the last point with the slope of the spline at that point is used. Positioning of the breakpoints is controlled by the parameter @p break_positions. Valid choices are "uniform" (equidistant spacing on the data range) and "quantiles" (equal numbers of data points in every interval). @ingroup MapAlignment */ class OPENMS_DLLAPI TransformationModelBSpline : public TransformationModel { public: /** @brief Constructor @exception IllegalArgument is thrown if not enough data points are given or if the required parameter @p num_breakpoints is missing. */ TransformationModelBSpline(const DataPoints & data, const Param & params); /// Destructor ~TransformationModelBSpline(); /// Evaluates the model at the given value DoubleReal evaluate(const DoubleReal value) const; /// Gets the default parameters static void getDefaultParameters(Param & params); protected: /** @brief Finds quantile values @param x Data vector to find quantiles in @param quantiles Quantiles to find (values between 0 and 1) @param results Resulting quantiles (vector must be already allocated to the correct size!) */ void getQuantiles_(const gsl_vector * x, const std::vector<double> & quantiles, gsl_vector * results); /// Computes the B-spline fit void computeFit_(); /// Computes the linear extrapolation void computeLinear_(const double pos, double & slope, double & offset, double & sd_err); /// Vectors for B-spline computation gsl_vector * x_, * y_, * w_, * bsplines_, * coeffs_; /// Covariance matrix gsl_matrix * cov_; /// B-spline workspace gsl_bspline_workspace * workspace_; /// Number of data points and coefficients size_t size_, ncoeffs_; // First/last breakpoint double xmin_, xmax_; /// Parameters for linear extrapolation double slope_min_, slope_max_, offset_min_, offset_max_; /// Fitting errors of linear extrapolation double sd_err_left_, sd_err_right_; }; } // end of namespace OpenMS #endif // OPENMS_ANALYSIS_MAPMATCHING_TRANSFORMATIONMODEL_H
current rating is 4 based on 6 www mathematical soccer predictions reviews. M Info, review, some of it can be quite useful. Site has wide range of data and information, fraud. Predictions are based on mathematical algorithms, scam, ratings, no clear logic behind it.the odds proposed in the betting market www mathematical soccer predictions ncaa football score predictions week 4 often reflect the market rather than the true probability of the matches. Similarly to an investiment in a financial market, higher probabilities do not coincide with a great opportunities to win! In the Home page of our website you can find our probabilities associated to the results 1,X,2,Under 2.5 and Over 2.5. In the column PICK s you find our suggestions. These advices are based on the idea that for each match, if the probability of. Maximum likelihood estimates are shown to be computationally obtainable, and the model is shown to have a positive return when used as the basis of a betting strategy. Hoping that this explanation is exhaustive for you, we wish you a good browsing! The pickforwin staff. USA: Www mathematical soccer predictions! modelling Association Football Scores and Inefficiencies in the Football Betting Market. Improvements can be achieved by the use of a bivariate Poisson model with www mathematical soccer predictions a correlation between scores of 0.2. Applied Statistic, s.G. M.J. (1997)). 265-280. And Coles, 46, summary. Dixon,this field of the www mathematical soccer predictions literature define a model for the number of goals scored and conceded by the two teams based on the Poisson distribution and then aggregate these results to obtain probabilities for different outcomes such as home team win, draw,Using just a bivariate Poisson distribution can improve model fit and prediction of the number of draws in football e model is extended by considering an inflation factor for diagonal terms in the bivariate joint is inflation improves in precision the estimation of draws and. came into www mathematical soccer predictions mind, a first thought, combined Effects of Mahadasha and Sub Dasha planets Lord While analysing to a birth chart,vbet - www mathematical soccer predictions active account, one minimal deposit. Conditions for receiving prizes: Bet-at-home - active account, 3 USD deposit. Dabblebet customers in the UK can watch and bet on this fixture live. Your account must be funded or active (have a bet placed in the previous 24 hours) to enjoy the action. Team news Marco Asensio missed Real Madrid&apos;s win over Alaves on Saturday. Especially somewhere like Memphis where it will be in the mid-80s and humid. Even casting aside that inauspicious framework, Memphis has had extra time to prepare and averaged 8-plus yards/carry in Week 1. UCLA may have the worst run defense in FBS. They allowed 6.7. soccer 1x2 fixed www mathematical soccer predictions matches, best soccer predictions, free fixed matches, best fixed match, ht/ft fixed matches, fixed matches,Football Betting Blog Free Super Tips array(39) "SERVER _SOFTWARE " string(12) "nginx "REQUEST _URI" string(6) blog "USER " string(8) "www-data" "HOME " string(8) var/www" "HTTP _CONNECTION " string(5) "close" "HTTP _CF_CONNECTING _IP" string(27) "2a02:c "HTTP _REFERER " string(24) "m "HTTP _COOKIE " string(5) "Array" "HTTP. facebook The president of www mathematical soccer predictions Occidental College announced his decision at a meeting of the Occidental Board of Trustees, full Story Occidental football to play 2018 season.get instant advice on your decision to draft www mathematical soccer predictions Barry Church or Trey Flowers in 2018. bracelets, and 100 perfect soccer predictions necklaces to provide the finest storage choices. Select a www mathematical soccer predictions field that features storage for earrings, jewellery Containers: A great jewellery field is certainly among the best investments you can also make for holding your items secure. Rings, ideally,kC Injuries Has some depth issues on the defensive line with back-up DEs Rakeem Nunez-Roches doubtful and Jarvis Jenkins questionable with a www mathematical soccer predictions knee injury. No. 3 CB Philip Gaines has been placed on IR. our in play betting tips are exclusive to Twitter so if you love an in play bet then you must follow us now ncaa www mathematical soccer predictions football games predictions to get involved! Do you offer any inplay free betting tips? Our inplay betting tips are available on the FreeSuperTips App.
C Copyright(C) 1999-2020 National Technology & Engineering Solutions C of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with C NTESS, the U.S. Government retains certain rights in this software. C C See packages/seacas/LICENSE for details C======================================================================= LOGICAL FUNCTION HELP (PROG, TYPE, OPTION) C======================================================================= CHARACTER*(*) PROG CHARACTER*(*) TYPE CHARACTER*(*) OPTION HELP = .FALSE. WRITE (*, 10) & 'Help for ', PROG(:LENSTR(PROG)), ' is not available' RETURN 10 FORMAT (/, 1X, 5A) END
lemma convex_translation: "convex ((+) a ` S)" if "convex S"
import fol import data.set /-! # IZF set theory In this file we define the signature and axioms of intuitionistic Zermelo-Fraenkel set theory and give a natural deduction proof of the induction principle in its set theoretical form. ## Main results - `omega_smallest_inductive_provable`: we show that ZFC proves that ω is the smallest inductive set. a direct consequence of - `omega_smallest_inductive`: a natural deduction proof that ω is the smallest inductive set ## References * [P. Aczel, M. Rathjen, *Notes on Constructive Set Theory*] [AR01] -- for the axioms of IZF * [L. Crosilla, *Set Theory: Constructive and Intuitionistic ZF*] [LC20] -- for cross referencing -/ namespace izf open fol universe variable u section izf_signature -- pp notation for inserting elements into a data.set local infix ` >> ` := insert /- We will use single predicate for membership -/ inductive pred_symb : ℕ → Type u | elem : pred_symb 2 --| subset : pred_symb 2 /- We allow constants for the empty set and ω, unary function symbols for the union set and the powerset and a binary function symbol for the pair set -/ inductive func_symb : ℕ → Type u | empty : func_symb 0 | omega : func_symb 0 | union : func_symb 1 | power : func_symb 1 | pair : func_symb 2 --| succ : func_symb 1 def σ : signature := { func_symb:= izf.func_symb , pred_symb:= izf.pred_symb } -- Definitions and notations for our functions @[simp]def emptyset : term σ := (func func_symb.empty : term σ) @[simp]def omegaset : term σ := (func func_symb.omega : term σ) @[simp]def unionset (t : term σ) : term σ := fapp (func func_symb.union) t @[simp]def powerset (t : term σ) : term σ := fapp (func func_symb.power) t @[simp]def pairset (t₁ t₂ : term σ) : term σ := fapp (fapp (func func_symb.pair) t₁) t₂ --def successorset (t: term σ) : term σ := fapp (func func_symb.succ) t notation `⌀` := emptyset -- this is not ∅; type ⌀ using \diameter notation `ω` := omegaset prefix ⋃ := unionset prefix 𝒫 := powerset --prefix S:max := successorset notation ⦃ a ` , ` b ⦄ := pairset a b -- type ⦃ and ⦄ using \{{ and \}} notation ⦃ a ⦄ := pairset a a /-- Definition of the membership predicate.-/ @[simp] def memb (t₁ t₂: term σ): formula σ := papp (papp (pred pred_symb.elem) t₁) t₂ infix ` ∈' `:100 := memb -- Meta predicates and functions -- def subset (t₁ t₂: term σ): formula σ := papp (papp (pred_symb pred_symb.subset) t₁) t₂ /-- Definition of the subset predicate.-/ @[simp] def subset (t₁ t₂: term σ): formula σ := ∀'(#0 ∈' (t₁ ↑ 1 @ 0) →' #0 ∈' (t₂ ↑ 1 @ 0)) infix ` ⊆' `:100 := subset /-- Definition of the successor set.-/ @[simp] def successor_set (t: term σ) : term σ := ⋃⦃ t , ⦃ t ⦄ ⦄ prefix `S`:max := successor_set /-- Definition of inductive sets.-/ @[simp] def inductive_def (t : term σ) := ⌀ ∈' t ∧' ∀' (#0 ∈' (t ↑ 1 @ 0) →' S #0 ∈' (t ↑ 1 @ 0)) postfix ` is_inductive`:max := inductive_def /-- Definition of uniqueness in the first variable. -/ @[simp] def unique_in_var0 (φ: formula σ) : formula σ := ∀' ∀' ((φ ↑ 1 @ 1) ∧' (φ ↑ 1 @ 0) →' (#0 =' #1)) /-- Definition of the unique existential quantifier. -/ @[simp] def unique_ex (φ : formula σ) : formula σ := (∃'φ) ∧' (unique_in_var0 φ) prefix `∃!`:110 := unique_ex end izf_signature -- reducing terms helps with evaluating lifts and substitutions -- however, pred_symb and func_symb will make more difficult: -- #reduce (⌀ ∈' ω ∧' ⦃ ⌀, S⦃ #3 ⦄ ⦄ ∈' 𝒫#1) ↑ 1 @ 1 /- ((pred pred_symb.elem).papp (func func_symb.empty)).papp (func func_symb.omega) ∧' ((pred pred_symb.elem).papp (((func func_symb.pair).fapp (func func_symb.empty)).fapp ((func func_symb.union).fapp (((func func_symb.pair).fapp (((func func_symb.pair).fapp #4).fapp #4)).fapp (((func func_symb.pair).fapp (((func func_symb.pair).fapp #4).fapp #4)).fapp (((func func_symb.pair).fapp #4).fapp #4)))))).papp ((func func_symb.power).fapp #2) -/ -- this seems helps pretty printing reduced terms and formulas and makes them much easier to read -- notation `'⌀` := func func_symb.empty -- notation `'ω` := func func_symb.omega -- notation `'⋃` t := fapp (func func_symb.union) t -- notation `'𝒫` t := fapp (func func_symb.power) t -- --notation `'S` t := fapp (func func_symb.succ) t -- notation `'{ ` a ` , `b` }` := fapp (fapp (func func_symb.pair) a) b -- notation s ` '∈ `:100 t := papp (papp (pred pred_symb.elem) s) t -- notation s ` '⊆ `:100 t := papp (papp (pred pred_symb.subset) s) t -- after -- #reduce (⌀ ∈' ω ∧' ⦃ ⌀, S⦃ #3 ⦄ ⦄∈' 𝒫#1) ↑ 1 @ 1 /- ('⌀ '∈ 'ω) ∧' '{ '⌀ , '⋃'{ '{ #4 , #4 } , '{ '{ #4 , #4 } , '{ #4 , #4 } } } } '∈ '𝒫#2 -/ -- much better section izf_axioms /- Definitions and lemmas related to the axiom scheme of separation -/ namespace separation open fol /-- Defintion of the axiom scheme of separation with free variables. -/ @[simp] def free_formula (φ : formula σ): formula σ := ∀' ∃' ∀' ((#0 ∈' #1) ↔' (#0 ∈' #2 ∧' (φ ↑ 1 @ 1))) lemma closed{k} {φ} (H: closed (k+2) φ) : closed k (free_formula φ) := begin have h₁: ¬ k + 3 ≤ 2, by linarith, have h₂: 1 ≤ k+2, by linarith, have h₃: φ ↑ 1 @ 1 ↑ 1 @ (k + 3) = φ ↑ 1 @ 1, begin rw ←(lift_lift φ 1 1 h₂), congr, exact H, end, simp[h₁, h₃], end /-- Defintion of the axiom scheme of separation. -/ def formula (φ : fol.formula σ) {n : ℕ} (φ_h: formula.closed (n+2) φ) : fol.formula σ := formula.closure (free_formula φ) (closed φ_h) lemma formula_is_sentence {k : ℕ} (φ : fol.formula σ) (H: formula.closed (k+2) φ) : (formula φ H) is_sentence := begin exact closure_is_sentence (closed H) end lemma lift_sentence (φ) (n) (φ_h: fol.formula.closed (n+2) φ) (m i) : (formula φ φ_h) ↑ m @ i = formula φ φ_h := lift_sentence_id (formula_is_sentence _ _) /- To following definition and lemmas are used to make future proofs more explicit and readable. -/ lemma mem {Γ:set $ fol.formula σ} (φ) (k) (φ_h: formula.closed (k+2) φ) {ψ} (h : ψ = separation.formula φ φ_h) (H: (separation.formula φ φ_h) ∈ Γ) : ψ ∈ Γ := begin subst h, exact H, end /-- Defintion of the axiom scheme of separation as set. -/ def scheme : set $ fol.formula σ := { (separation.formula φ φ_h) | (φ : fol.formula σ) (k: ℕ) (φ_h : formula.closed (k+2) φ) } lemma mem_scheme (φ : fol.formula σ) {k : ℕ} (φ_h: fol.formula.closed (k+2) φ) : separation.formula φ φ_h ∈ scheme := begin existsi [φ, k, φ_h], refl end end separation namespace collection /-- Defintion of the axiom scheme of collection with free variables -/ @[simp] def free_formula (φ: formula σ) := (∀'(∀'(#0 ∈' #1 →' ∃'φ) →' (∃' ∀' (#0 ∈' #2 →' (∃' (#0 ∈' #2 ∧' (φ ↑ 1 @ 2))))))) lemma closed {φ} {k} (H: formula.closed (k+3) φ) : formula.closed k (free_formula φ) := begin have : ¬ k+4 ≤ 2, by linarith, have : ¬ k+3 ≤ 2, by linarith, have h₁ : 0 ≤ k+3, from (k+3).zero_le, have h₂ : 1 ≤ k+3, by linarith, have h₃ : 2 ≤ k+3, by linarith, have H₁ : (φ ↑ 1 @ 0) ↑ 1 @ (k + 4) = φ ↑ 1 @ 0, begin rw ←(lift_lift φ 1 1 h₁), congr, exact H, end, have H₂ : (φ ↑ 1 @ 1) ↑ 1 @ (k + 4) = φ ↑ 1 @ 1, begin rw ←(lift_lift φ 1 1 h₂), congr, exact H, end, have H₃ : (φ ↑ 1 @ 2) ↑ 1 @ (k + 4) = φ ↑ 1 @ 2, begin rw ←(lift_lift φ 1 1 h₃), congr, exact H, end, rw closed at H, clear h₂, simp[*, closed], end /-- Defintion of the axiom scheme of collection -/ def formula (φ : fol.formula σ) {k : ℕ} (H: formula.closed (k+3) φ) : fol.formula σ := formula.closure (free_formula φ) (closed H) lemma formula_is_sentence (φ : fol.formula σ) {k : ℕ} (H: fol.formula.closed (k+3) φ) : (formula φ H) is_sentence := begin exact closure_is_sentence (closed H) end /- To following definition and lemmas are used to make future proofs more explicit and readable. -/ lemma mem {Γ:set $ fol.formula σ} {ψ} {k} (φ) (φ_h: formula.closed (k+3) φ) (h : ψ = formula φ φ_h) (H: (formula φ φ_h) ∈ Γ) : ψ ∈ Γ := begin subst h, exact H end /-- Defintion of the axiom scheme of collection as set -/ def scheme : set $ fol.formula σ := { (formula φ φ_h) | (φ : fol.formula σ) (k: ℕ) (φ_h : fol.formula.closed (k+3) φ) } lemma mem_scheme (φ : fol.formula σ) {k : ℕ} (φ_h: fol.formula.closed (k+3) φ) : formula φ φ_h ∈ scheme := begin existsi [φ, k, φ_h], refl, end end collection namespace set_induction /-- Defintion of the axiom scheme of set induction with free variables. -/ @[simp] def free_formula (φ: formula σ) := (∀'(∀'(#0 ∈' #1 →' (φ ↑ 1 @ 1)) →' φ) →' (∀'φ)) lemma closed {φ} {n} (φ_h: closed (n+1) φ) : closed n (free_formula φ) := begin have : φ ↑ 1 @ 1 ↑ 1 @ (n + 1 + 1) = φ ↑ 1 @ 1 := begin rw ←(lift_lift φ 1 1 (nat.succ_pos n)), congr, exact φ_h, end, rw closed at φ_h, simp*, end /-- Defintion of the axiom scheme of set induction -/ def formula (φ : fol.formula σ) {n : ℕ} (φ_h: formula.closed (n+1) φ) : fol.formula σ := formula.closure (free_formula φ) (closed φ_h) lemma formula_is_sentence (φ : fol.formula σ) {n : ℕ} (φ_h: fol.formula.closed (n+1) φ) : (formula φ φ_h) is_sentence := begin exact closure_is_sentence (closed φ_h) end /- To following definition and lemmas are used to make future proofs more explicit and readable. -/ lemma mem {Γ:set $ fol.formula σ} {ψ} (φ) {n} (φ_h: formula.closed (n+1) φ) (h : ψ = formula φ φ_h) (H: (formula φ φ_h) ∈ Γ) : ψ ∈ Γ := begin subst h, exact H end /-- Defintion of the axiom scheme of set induction as set -/ def scheme : set $ fol.formula σ := { (formula φ φ_h) | (φ : fol.formula σ) (k: ℕ) (φ_h : fol.formula.closed (k+1) φ) } lemma mem_scheme (φ : fol.formula σ) {k : ℕ} (φ_h: fol.formula.closed (k+1) φ) : formula φ φ_h ∈ scheme := begin existsi [φ, k, φ_h], refl, end end set_induction /- ∀b ∀a (∀x (x ∈ a ↔ x ∈ b) → a = b) -/ @[simp] def extensionality : formula σ := ∀' ∀' ((∀' (#0 ∈' #1 ↔' #0 ∈' #2)) →' (#0 =' #1)) /- ∀x (x ∈ ⌀ ↔ x ≠ x) -/ @[simp] def emptyset_ax : formula σ := ∀' (#0 ∈' ⌀ ↔' ¬'(#0 =' #0)) /- ∀b ∀a ∀x (x ∈{a,b} ↔ x = a ∨ x = b) -/ @[simp] def pairset_ax : formula σ := ∀' ∀' ∀' (#0 ∈' ⦃ #1 , #2 ⦄ ↔' (#0 =' #1 ∨' #0 =' #2)) /- ∀F ∀x (x ∈ ⋃F ↔ ∃y (x ∈ y ∧ y ∈ x)) -/ @[simp] def unionset_ax : formula σ := ∀' ∀' (#0 ∈' ⋃#1 ↔' ∃'(#1 ∈' #0 ∧' #0 ∈' #2)) /- ∀y ∀x (x ∈ 𝒫(y) → x ⊆ y) -/ @[simp] def powerset_ax : formula σ := ∀' ∀' (#0 ∈' 𝒫#1 ↔' #0 ⊆' #1) /- ∀x (x ∈ ω ↔ ∀w (w is inductive → x ∈ w)) -/ @[simp] def omega_ax : formula σ := ∀' (#0 ∈' ω ↔' ∀'((#0 is_inductive) →' #1 ∈' #0)) /- ∀xₙ ... ∀x₁ ∀A (∀x (x ∈ A → φ(x)) → φ(A)) → ∀A φ(A) -/ @[simp] def set_induction_ax (φ : formula σ) {n : ℕ} (φ_h: closed (n+1) φ) : formula σ := set_induction.formula φ φ_h /-- ∀xₙ ... ∀x₁ ∀A ∃B ∀x (x ∈ B ↔ x ∈ A ∧ φ ↑ 1 @ 1) -/ @[simp] def separation_ax (φ : formula σ) {n: ℕ} (φ_h: closed (n+2) φ) : formula σ := separation.formula φ φ_h /-- ∀xₙ ... ∀x₁ ∀A (∀x(x ∈ A → ∃y φ) → ∃B ∀x (x ∈ A → ∃y (y ∈ B ∧ φ) -/ @[simp] def collection_ax (φ : formula σ) {n : ℕ} (φ_h: closed (n+3) φ) : formula σ := collection.formula φ φ_h -- optional: definition of the subset predicate -- @[simp] def subset_def : formula σ := ∀' ∀' (#0 ⊆' #1 ↔' ∀' (#0 ∈' #1 →' #0 ∈' #2)) /- The following lemmas provide a convenient way to make explicit which axioms are used inside our proofs. -/ lemma extensionality_mem {Γ: set $ formula σ}{φ}(h: φ = extensionality)(H: extensionality ∈ Γ) : φ ∈ Γ := begin subst h, exact H end lemma emptyset_ax_mem {Γ: set $ formula σ} {φ} (h: φ = emptyset_ax) (H: emptyset_ax ∈ Γ) : φ ∈ Γ := begin subst h, exact H end lemma pairset_ax_mem {Γ: set $ formula σ} {φ} (h: φ = pairset_ax) (H: pairset_ax ∈ Γ) : φ ∈ Γ := begin subst h, exact H end lemma unionset_ax_mem {Γ: set $ formula σ} {φ} (h: φ = unionset_ax) (H: unionset_ax ∈ Γ) : φ ∈ Γ := begin subst h, exact H end lemma powerset_ax_mem {Γ: set $ formula σ} {φ} (H: powerset_ax ∈ Γ) (h: φ = powerset_ax) : φ ∈ Γ := begin subst h, exact H end lemma omega_ax_mem {Γ: set $ formula σ} {φ} (h: φ = omega_ax) (H: omega_ax ∈ Γ) : φ ∈ Γ := begin subst h, exact H end /-- The set of axioms for IZF. -/ def izf_ax : set $ formula σ := { extensionality, emptyset_ax, pairset_ax, unionset_ax, powerset_ax, omega_ax } ∪ set_induction.scheme ∪ separation.scheme ∪ collection.scheme lemma izf_ax_set_of_sentences : ∀ φ ∈ izf_ax, φ is_sentence := begin intros φ h, repeat {cases h,}; try {unfold sentence closed, refl, }, all_goals { cases h_h with k H, cases H with ϕ_closed, subst H_h }, exact set_induction.formula_is_sentence _ ϕ_closed, exact separation.formula_is_sentence _ ϕ_closed, exact collection.formula_is_sentence _ ϕ_closed, end lemma lift_izf_ax {m i : ℕ}: (λ (ϕ: formula σ) , ϕ ↑ m @ i) '' izf_ax = izf_ax := lift_set_of_sentences_id izf_ax_set_of_sentences end izf_axioms section izf_proofs /-- Proof scheme. Provides a formal proof of uniqueness of y satisfying formulas of the form `∀x (x ∈ y ↔ φ)`, provided `y` is not free in `φ`. Informally : {extensionality} ⊢ ∀y₁ ∀y₀ (y₀ = { x | φ } ∧ y₁ = { x | φ } → y₀ = y₁) -/ def extensionality_implies_uniqueness (φ : formula σ) : {extensionality} ⊢ unique_in_var0 ∀'(#0 ∈' #1 ↔' (φ ↑ 1 @ 1)) := begin apply allI, -- y₁ apply allI, -- y₀ apply impI, -- assume `∀ x (x ∈ y₀ ↔ φ(x, y₀)) ∧ ∀ x (x ∈ y₁ ↔ φ(x,y₁))` apply impE (∀' (#0 ∈' #1 ↔' #0 ∈' #2)), { -- y₁ y₀ ⊢ (∀' (#0 ∈' #1 ↔' #0 ∈' #2)) apply allI, -- x apply iffI_trans (φ ↑ 2 @ 1), { -- y₁ y₀ x ⊢ x ∈ y₀ ↔ φ (x, y₀) apply allE_var0, apply andE₁ _ , apply hypI, -- meta argument simp [set.image_insert_eq], simp [subst_var0_for_0_lift_by_1, lift_lift_merge φ 1] }, { -- y₁ y₀ x ⊢ φ (x, y₁) ↔ x ∈ y₁ apply iffI_symm, apply allE_var0, apply andE₂ _ , apply hypI, -- meta argument simp [set.image_insert_eq] } }, { -- y₁ y₀ ⊢ ∀ x (x ∈ y₀ ↔ x ∈ y₁) → y₀ = y₁ apply allE_var0, apply allE' _ #1, apply weak1, apply hypI, -- meta argument simp, simp, }, end /-- QoL version of `extensionality_implies_uniqueness` Informally : `Γ ⊢ ∀y₁ ∀y₀ (ψ(y₀) ∧ ψ(y₁) → y₀ = y₁`, provided `ψ(y) = ∀x (x ∈ y ↔ φ)`, `y` not free in `φ` and `extensionality ∈ Γ`. -/ def extensionality_implies_uniqueness' {Γ} (φ) {ψ} (h: ψ = ∀'(#0 ∈' #1 ↔' (φ ↑ 1 @ 1))) (H: extensionality ∈ Γ) : Γ ⊢ unique_in_var0 ψ := begin subst h, apply weak_singleton extensionality (extensionality_implies_uniqueness φ), exact H, end /-- `n`-closure variant of `extensionality_implies_uniqueness` Informally : `{extensionality} ⊢ ∀xₙ ... ∀x₁ ∀y₁ ∀y₀ (y₀ = { x | φ } ∧ y₁ = { x | φ } → y₀ = y₁)` -/ def extensionality_implies_uniqueness_alls (n) (φ : formula σ) : {extensionality} ⊢ alls n (unique_in_var0 ∀'(#0 ∈' #1 ↔' (φ ↑ 1 @ 1))) := begin apply allsI, apply extensionality_implies_uniqueness' φ (rfl), rw set.mem_image, use extensionality, exact ⟨ set.mem_singleton _ , rfl ⟩, end /-- Proof scheme. Provides a formal proof of `∃B ∀x(x ∈ B ↔ φ)` from `∃B ∀x (φ → x ∈ B)` by using the axiom of separation for `φ`. -/ def separation_proof_scheme (φ k) (φ_h₁: closed (k+2) φ) -- given a formula φ(x_1,...,x_{k+1}) (φ_h₂ : not_free 1 φ) -- such that the x₂ is not among its free variables {Γ} (h : separation_ax φ φ_h₁ ∈ Γ) -- ... (H : Γ ⊢ alls k ∃' ∀'(φ →' (#0 ∈' #1))) : Γ ⊢ alls k (∃' ∀'((#0 ∈' #1) ↔' φ)) := begin apply allsI, apply exE ∀'(φ →' (#0 ∈' #1)), -- A with ∀ x (φ → x ∈ A) { -- xₖ ... x₁ ⊢ ∃ A ∀x (φ → x ∈ A) apply allsE', exact H }, { -- xₖ ... x₁ A ⊢ ∃ B ∀ x (x ∈ B ↔ φ) apply exE (∀'((#0 ∈' #1) ↔' ((#0 ∈' #2) ∧' (φ ↑ 1 @ 1)))), -- B with ∀ x (x ∈ B ↔ x ∈ A ∧ φ) { -- xₖ ... x₁ A ⊢ ∃ B ∀ x (x ∈ B ↔ x ∈ A ∧ φ) apply weak1, apply allsE' 1, apply allsE' k, rw [alls,alls], apply hypI, -- meta apply separation.mem φ k φ_h₁ (rfl), assumption, }, { -- A B ⊢ ∃ B ∀ x (x ∈ B ↔ φ) apply exI #0, apply allI, -- x apply andI, { -- A B x ⊢ x ∈ B → φ apply impI, -- assume `x ∈ B` apply andE₂ (#0 ∈' #2), apply impE_insert, apply iffE_r, apply allE_var0, apply hypI, -- meta rw[set.image_insert_eq], left, cases φ_h₂ with ψ ψ_h, subst ψ_h, rw [subst_var0_lift_by_1, subst_var0_lift_by_1], rw [←lift_lift ψ _ _ (le_refl 1)], refl }, { -- A B x ⊢ φ → x ∈ B apply impI, -- assume `φ` apply impE (#0 ∈' #2), { -- A B x ⊢ x ∈ A apply impE (φ ↑ 1 @ 1), { -- A B x ⊢ φ apply hypI, left, cases φ_h₂ with ψ ψ_h, subst ψ_h, rw [subst_var0_lift_by_1, ←lift_lift ψ _ _ (le_rfl)] }, { -- A B x ⊢ φ → x ∈ A apply allE_var0, apply hypI, -- meta simp only [set.image_insert_eq], right, right, left, refl } }, { -- A B x ⊢ x ∈ A → x ∈ B apply impI, -- assume `x ∈ A` apply impE (#0 ∈' #2 ∧' (φ ↑ 1 @ 1)), { -- A B x ⊢ x ∈ A ∧ φ apply andI, { -- A B x ⊢ x ∈ A apply hypI1 }, { -- A B x ⊢ φ apply hypI, -- meta right, left, cases φ_h₂ with ψ ψ_h, subst ψ_h, rw [subst_var0_lift_by_1, lift_lift ψ _ _ (le_rfl)] } }, { -- A B x ⊢ x ∈ A ∧ φ → x ∈ B apply iffE_l, apply allE_var0, apply hypI, --meta simp only [set.image_insert_eq], right, right, left, simp } } } } } end /-- QoL version of `separation_proof_scheme`. Proof scheme. Provides a formal proof `ψ` from `∃B ∀x (φ → x ∈ B)` and `ψ = ∃B ∀x(x ∈ B ↔ φ)`. -/ def separation_proof_scheme' (φ) (k) (φ_h: closed (k+2) (φ ↑ 1 @ 1)) {ψ : formula σ} (ψ_h : ψ = alls k ∃' ∀'((#0 ∈' #1) ↔' (φ ↑ 1 @ 1))) {Γ} (h : separation.formula (φ ↑ 1 @ 1) φ_h ∈ Γ) (H: Γ ⊢ alls k ∃' ∀'(φ ↑ 1 @ 1 →' (#0 ∈' #1))) : Γ ⊢ ψ := begin subst ψ_h, apply separation_proof_scheme (φ ↑ 1 @ 1) k φ_h (by use φ) h H, end /-- Formal proof showing that `{a} := {a,a}` satisfies the defining property of the singleton set, derived from the pairset axiom. Informally: `{pairset_ax} ⊢ ∀ a : {a} = { x | x = a }`. -/ def singleton_def: {pairset_ax} ⊢ ∀' ∀' (#0 ∈' ⦃ #1 ⦄ ↔' #0 =' #1) := begin apply allI, -- a apply allI, -- x apply andI, { -- a x ⊢ x ∈ {a} → x = a apply impI, -- assume `x ∈ {a}` apply orE (#0 =' #1) (#0 =' #1), { -- a x ⊢ x = a ∨ x = a apply impE_insert, apply iffE_r, apply allE_var0, apply allE' _ #1, apply allE' _ #1, apply hypI, -- meta apply pairset_ax_mem (rfl), all_goals {simp [set.image_singleton] } }, { -- assume x = a -- a x ⊢ x = a apply hypI1 }, { -- assume x = a -- a x ⊢ x = a apply hypI1 }, }, { -- a x ⊢ x = a → x ∈ {a} apply impI, -- assume `x = a` apply impE (#0 =' #1 ∨' #0 =' #1), { -- a x ⊢ x = a ∨ x = a apply orI₁, apply hypI1, }, { -- a x ⊢ (x = a ∨ x = a) → x ∈ {a} apply iffE_l, apply allE_var0, apply allE' _ #1, apply allE' _ #1, apply hypI, -- meta apply pairset_ax_mem (rfl), all_goals {simp [set.image_singleton] } } } end /-- Informally: `Γ ⊢ φ` provided `φ = ∀ a : { a } = { x | x = a }` and `pairset_ax ∈ Γ`. -/ def singleton_def' {Γ} {φ : formula σ} (h₁: φ = ∀' ∀' (#0 ∈' ⦃ #1 ⦄ ↔' #0 =' #1)) (h₂ : pairset_ax ∈ Γ) : Γ ⊢ φ := begin subst h₁, apply weak_singleton pairset_ax, apply singleton_def, assumption, end /-- A formal proof showing that `a ∪ b := ⋃{a,b}` satisfies the defining property of the binary union, derived from the pairset and unionset axioms. Informally: `{pairset_ax, unionset_ax} ⊢ ∀b ∀a : a ∪ b = { x | x ∈ a ∨ x ∈ b }`. -/ def binary_union_def : {pairset_ax, unionset_ax} ⊢ ∀' ∀' ∀' (#0 ∈' ⋃ ⦃ #1, #2 ⦄ ↔' #0 ∈' #1 ∨' #0 ∈' #2) := begin apply allI, -- b apply allI, -- a apply allI, -- x apply andI, { -- b a x ⊢ x ∈ a ∪ b → x ∈ a ∨ x ∈ b apply impI, -- assume `x ∈ a ∪ b` apply exE (#1 ∈' #0 ∧' #0 ∈' ⦃#2 , #3⦄), -- y with `x ∈ y ∧ y ∈ {a,b}` { -- b a x ⊢ ∃y (x ∈ y ∧ y ∈ {a,b}) apply impE_insert, apply iffE_r, apply allE' _ #0, apply allE' _ ⦃#1 , #2⦄, apply hypI, -- meta apply unionset_ax_mem (rfl), all_goals { try { simp[set.image_insert_eq], }, }, split; refl }, { -- b a x y ⊢ x ∈ a ∨ x ∈ b apply impE (#0 =' #2 ∨' #0 =' #3), { -- b a x y ⊢ y = a ∨ y = b apply impE (#0 ∈' ⦃#2 , #3⦄), { -- b a x y ⊢ y ∈ {a,b} apply andE₂, apply hypI1 }, { -- b a x y ⊢ y ∈ {a,b} → y = a ∨ y = b apply iffE_r , apply allE' _ #0, apply allE' _ #2, apply allE' _ #3, apply hypI, -- meta apply pairset_ax_mem (rfl), all_goals { try { simp[set.image_insert_eq] } }, split; refl } }, { -- b a x y ⊢ y = a ∨ y = b → x ∈ a ∨ x ∈ b apply impI, -- assume `y = a ∨ y = b` apply orE (#0 =' #2) (#0 =' #3), { -- b a x y ⊢ y = a ∨ y = b apply hypI1, }, { -- assume `y = a` -- b a x y ⊢ x ∈ a ∨ x ∈ b apply orI₁, apply eqE' #0 #2 (#2 ∈' #0), { -- b a x y ⊢ y = a apply hypI1, }, { -- b a x y ⊢ x ∈ y apply andE₁, apply hypI, simp[set.image_insert_eq] }, { refl } }, { -- assume `y = b` -- b a x y ⊢ x ∈ a ∨ x ∈ b apply orI₂, apply eqE' #0 #3 (#2 ∈' #0), { -- b a x y ⊢ y = b apply hypI1, }, { -- b a x y ⊢ x ∈ y apply andE₁, apply hypI, simp[set.image_insert_eq] }, { refl } } } } }, { -- b a x ⊢ (x ∈ a ∨ x ∈ b) → x ∈ a ∪ b apply impI, -- assume `(x ∈ a) ∨ (x ∈ b)` apply orE (#0 ∈' #1) (#0 ∈' #2), { -- b a x ⊢ (x ∈ a) ∨ (x ∈ b) apply hypI1 }, { -- assume `x ∈ a` -- b a x ⊢ x ∈ a ∪ b apply impE (∃'(#1 ∈' #0 ∧' #0 ∈' ⦃#2 , #3⦄)), { -- b a x ⊢ ∃y (x ∈ y ∧ y ∈ {a,b}) apply exI #1, apply andI, { -- b a x ⊢ x ∈ a apply hypI1, }, { -- b a x ⊢ a ∈ {a,b} apply impE (#1 =' #1 ∨' #1 =' #2), { -- b a x ⊢ (a = a ∨ a = b) apply orI₁, apply eqI, }, { -- b a x ⊢ (a = a ∨ a = b) → a ∈ {a,b} apply iffE_l, apply allE' _ #1, apply allE' _ #1, apply allE' _ #2, apply hypI, apply pairset_ax_mem (rfl), all_goals { try { simp[set.image_insert_eq], }, }, split; refl } } }, { -- b a x ⊢ ∃y (x ∈ y ∧ y ∈ {a,b}) → x ∈ a ∪ b apply iffE_l , apply allE_var0, apply allE' _ ⦃ #1 , #2 ⦄, apply hypI, apply unionset_ax_mem (rfl), all_goals{ simp[set.image_insert_eq] }, refl } }, { -- assume `x ∈ b` -- b a x ⊢ x ∈ a ∪ b apply impE (∃'(#1 ∈' #0 ∧' #0 ∈' ⦃#2 , #3⦄)), { -- b a x ⊢ ∃y (x ∈ y ∧ y ∈ {a,b}) apply exI #2, apply andI, { -- b a x ⊢ x ∈ b apply hypI1, }, { -- b a x ⊢ b ∈ {a,b} apply impE (#2 =' #1 ∨' #2 =' #2), { -- b a x ⊢ (b = a ∨ b = b) apply orI₂, apply eqI, }, { -- b a x ⊢ (b = a ∨ b = b) → a ∈ {a,b} apply andE₂ _, apply allE' _ #2, apply allE' _ #1, apply allE' _ #2, apply hypI, apply pairset_ax_mem (rfl), all_goals { try { simp[set.image_insert_eq], }, }, split; refl } } }, { -- b a x ⊢ ∃y (x ∈ y ∧ y ∈ {a,b}) → x ∈ a ∪ b apply iffE_l , apply allE_var0, apply allE' _ ⦃ #1 , #2 ⦄, apply hypI, apply unionset_ax_mem (rfl), all_goals { simp[set.image_insert_eq] }, refl } } } end /-- Informally: `Γ ⊢ φ` provided `φ = ∀ b ∀ a : a ∪ b = { x | x ∈ a ∨ x ∈ b }` and `pairset_ax, unionset_ax ∈ Γ`. -/ def binary_union_def' {Γ} {φ : formula σ} (h₁: φ = ∀' ∀' ∀'(#0 ∈' ⋃ ⦃ #1, #2 ⦄ ↔' #0 ∈' #1 ∨' #0 ∈' #2)) (h₂: pairset_ax ∈ Γ) (h₃ : unionset_ax ∈ Γ) : Γ ⊢ φ := begin subst h₁, apply weak {pairset_ax, unionset_ax}, apply binary_union_def, intros x h, cases h, { subst h, exact h₂ }, { rw set.mem_singleton_iff at h, subst h, exact h₃ } end /-- A formal proof showing that `S(a) := a ∪ {a}` satisfies the defining property of the successor set, derived from the pairset and unionset axioms. Informally: `{pairset_ax, unionset_ax} ⊢ ∀a : S(a) = { x | x ∈ a ∨ x = a }`. -/ def successor_def : {pairset_ax, unionset_ax} ⊢ ∀' ∀' (#0 ∈' S#1 ↔' #0 ∈' #1 ∨' #0 =' #1) := begin apply allI, -- a apply allI, -- x apply andI, { -- a x ⊢ x ∈ S(a) → x ∈ a ∨ x = a apply impI, -- assume `x ∈ S(a)` apply impE (#0 ∈' #1 ∨' #0 ∈' ⦃ #1 ⦄), { -- a x ⊢ x ∈ a ∨ x ∈ {a} apply impE (#0 ∈' S#1), { -- a x ⊢ x ∈ S(a) apply hypI1, }, { -- a x ⊢ x ∈ S(a) → x ∈ a ∨ x ∈ {a} apply iffE_r, apply allE_var0, apply allE' _ #1, apply allE' _ ⦃ #1 ⦄, apply binary_union_def' (rfl), all_goals{ simp[set.image_insert_eq] } } }, { -- a x ⊢ x ∈ a ∨ x ∈ {a} → x ∈ a ∨ x = a apply impI, -- assume `x ∈ a ∨ x ∈ {a}` apply orE (#0 ∈' #1) (#0 ∈' ⦃ #1 ⦄), { -- a x ⊢ x ∈ a ∨ x ∈ {a} apply hypI1, }, { -- assume `x ∈ a` -- a x ⊢ x ∈ a ∨ x = a apply orI₁, apply hypI1 }, { -- assume `x ∈ {a}` -- a x ⊢ x ∈ a ∨ x = a apply orI₂, apply impE_insert, apply iffE_r, apply allE_var0, apply allE' _ #1, apply singleton_def' (rfl), all_goals{ simp[set.image_insert_eq] } } } }, { -- a x ⊢ x ∈ a ∨ x = a → x ∈ S(a) apply impI, -- assume `x ∈ a ∨ x = a` apply orE (#0 ∈' #1) (#0 =' #1), { -- a x ⊢ x ∈ a ∨ x = a apply hypI1, }, { -- assume `x ∈ a` -- a x ⊢ x ∈ S(a) apply impE (#0 ∈' #1 ∨' #0 ∈' ⦃ #1 ⦄), { -- a x ⊢ x ∈ a ∨ x ∈ {a} apply orI₁, apply hypI1,}, { -- a x ⊢ x ∈ a ∨ x ∈ {a} → x ∈ S(a) apply iffE_l, apply allE' _ #0, apply allE' _ #1, apply allE' _ ⦃ #1 ⦄, apply binary_union_def' (rfl), all_goals{ simp[set.image_insert_eq] } } }, { -- assume `x = a` -- a x ⊢ x ∈ S(a) apply impE (#0 ∈' #1 ∨' #0 ∈' ⦃ #1 ⦄), { -- a x ⊢ x ∈ a ∨ x ∈ {a} apply orI₂, apply impE_insert, apply iffE_l, apply allE' _ #0, apply allE' _ #1, apply singleton_def' (rfl), all_goals{ simp[set.image_insert_eq] } }, { -- a x ⊢ x ∈ a ∨ x ∈ {a} → x ∈ S(a) apply iffE_l, apply allE' _ #0, apply allE' _ #1, apply allE' _ ⦃ #1 ⦄, apply binary_union_def' (rfl), all_goals{ simp[set.image_insert_eq] } } } } end /-- Formal proof that ω is unique. -/ def omega_unique : ∅ ⊢ ∃! (#0 =' ω) := begin apply andI, { -- ∃ case is trivial apply exI ω, apply eqI }, { -- uniqueness apply allsI 2, apply impI, apply eqE' ω #1 (#1 =' #0), { apply eqI_symm, apply andE₂, apply hypI1, }, { apply andE₁, apply hypI1,}, { refl, }, }, end /-- A formal proof that `ω` is a subset of all inductive sets, derived from the omega axiom. Informally: `{omega_ax} ⊢ ∀ w : (w is inductive) → ω ⊆ w`. -/ def omega_subset_all_inductive: {omega_ax} ⊢ ∀' (#0 is_inductive →' (ω ⊆' #0)) := begin apply allI, -- w apply impI, -- assume `w is inductive` apply allI, -- x apply impI, -- assume `x ∈ ω` apply impE (#1 is_inductive), { -- w x ⊢ w is inductive apply hypI, simp [set.image_insert_eq] }, { -- w x ⊢ (w is inductive) → x ∈ w apply allE' (#0 is_inductive →' #1 ∈' (#0)) #1, apply iffE₂ (#0 ∈' ω), { -- w x ⊢ x ∈ ω apply hypI1 }, { -- w x ⊢ x ∈ ω ↔ ∀ w ((w is inductive) → x ∈ w) apply allE_var0, apply hypI, apply omega_ax_mem, all_goals {simp[set.image_insert_eq] } }, { refl } } end /-- Informally: `Γ ⊢ ∀ w : (w is inductive) → ω ⊆ w`, provided `omega_ax ∈ Γ`. -/ def omega_subset_all_inductive' {Γ} (h: omega_ax ∈ Γ) : Γ ⊢ ∀' (#0 is_inductive →' (ω ⊆' #0)) := begin apply weak {omega_ax}, exact omega_subset_all_inductive, exact set.singleton_subset_iff.mpr h, end /-- A formal proof of `ω is inductive`, derived from the omega axiom. -/ def omega_inductive : {omega_ax} ⊢ ω is_inductive := begin apply andI, { -- ⊢ ⌀ ∈ ω apply impE ∀'(#0 is_inductive →' ⌀ ∈' #0), { -- ⊢ ∀ w (w is inductive → ⌀ ∈ w) apply allI, apply impI, apply andE₁, apply hypI, simp }, { -- ⊢ ∀ w (w is inductive → ⌀ ∈ w) → ⌀ ∈ ω apply iffE_l, apply allE' _ ⌀, apply hypI, apply omega_ax_mem (rfl), all_goals { simp } } }, { -- ⊢ ∀ x (x ∈ ω → S(x) ∈ ω) apply allI, -- x apply impI, -- assume `x ∈ ω` apply impE (∀'(#0 is_inductive →' S#1 ∈' #0)), { -- x ⊢ ∀ w ((w is inductive) → S(x) ∈ w) apply allI, -- w apply impI, -- assume `w is inductive` apply impE (#1 ∈' #0), { -- x w ⊢ x ∈ w apply impE (#1 ∈' ω), { -- x w ⊢ x ∈ ω apply hypI, simp[set.image_insert_eq] }, { -- x w ⊢ x ∈ ω → x ∈ w apply allE' (#0 ∈' ω →' #0 ∈' #1) #1, apply impE_insert, apply allE_var0, apply omega_subset_all_inductive', { simp [set.image_insert_eq] }, { refl } } }, { -- (x ∈ ω) (w is inductive) ⊢ x ∈ w → S(x) ∈ w apply allE' (#0 ∈' #1 →' S #0 ∈' #1) #1 _ (rfl), apply andE₂ _ , apply hypI1 } }, { -- x ⊢ ∀ w ((w is inductive) → S(x) ∈ w) → S(x) ∈ ω apply iffE_l, apply allE' _ S#0, apply hypI, { simp [set.image_insert_eq] }, { simp, } } } end /-- Informally: `Γ ⊢ ω is inductive`, provided `omega_ax ∈ Γ`. -/ def omega_inductive' {Γ} (h: omega_ax ∈ Γ) : Γ ⊢ ω is_inductive := begin apply weak_singleton omega_ax, exact omega_inductive, exact h, end /-- A formal proof that `ω` is the smallest inductive set derived from the axioms of IZF. Informally : `izf_ax ⊢ (ω is inductive) ∧ ∀ w ((w is inductive) → ω ⊆ w)` -/ def omega_smallest_inductive : izf_ax ⊢ (ω is_inductive) ∧' ∀'((#0 is_inductive) →' ω ⊆' #0) := begin apply andI, { apply omega_inductive', simp[izf_ax] }, { apply omega_subset_all_inductive', simp[izf_ax], } end end izf_proofs /-- Main Theorem: IZF proves that ω is the smallest inductive set. -/ theorem omega_smallest_inductive_provable: ((ω is_inductive) ∧' ∀'((#0 is_inductive) →' ω ⊆' #0)) is_provable_within izf_ax := begin use omega_smallest_inductive end end izf
Require Import Parametricity. Require Import List. Import ListNotations. Definition bind_option {A B} (f : A -> option B) (x : option A) : option B := match x with | Some x => f x | None => None end. Notation "'do' X <- A 'in' B" := (bind_option (fun X => B) A) (at level 200, X ident, A at level 100, B at level 200). Definition bind_option2 {A B C} (f : A -> B -> option C) (x : option (A * B)) : option C := do yz <- x in let (y, z) := yz : A * B in f y z. Notation "'do' X , Y <- A 'in' B" := (bind_option2 (fun X Y => B) A) (at level 200, X ident, Y ident, A at level 100, B at level 200). Require Import List. Record Queue := { t :> Type; empty : t; push : nat -> t -> t; pop : t -> option (nat * t) }. Definition program (Q : Queue) (n : nat) : option nat := (* q := 0::1::2::...::n *) let q : Q := nat_rect (fun _ => Q) Q.(empty) Q.(push) (S n) in let q : option Q := nat_rect (fun _ => option Q) (Some q) (fun _ (q : option Q) => do q <- q in do x, q <- Q.(pop) q in do y, q <- Q.(pop) q in Some (Q.(push) (x + y) q)) n in do q <- q in option_map fst (Q.(pop) q). Definition ListQueue := {| t := list nat; empty := nil; push := @cons nat; pop := fun l => match rev l with | nil => None | hd :: tl => Some (hd, rev tl) end |}. Definition DListQueue := {| t := list nat * list nat; empty := (nil, nil); push x l := let (back, front) := l in (cons x back,front); pop := fun l => let (back, front) := l in match front with | [] => match rev back with | [] => None | hd :: tl => Some (hd, (nil, tl)) end | hd :: tl => Some (hd, (back, tl)) end |}. Parametricity Recursive nat. Print nat_R. Lemma nat_R_equal : forall x y, nat_R x y -> x = y. intros x y H; induction H; subst; trivial. Defined. Lemma equal_nat_R : forall x y, x = y -> nat_R x y. intros x y H; subst. induction y; constructor; trivial. Defined. Parametricity Recursive option. Lemma option_nat_R_equal : forall x y, option_R nat nat nat_R x y -> x = y. intros x1 x2 H; destruct H as [x1 x2 x_R | ]. rewrite (nat_R_equal _ _ x_R); reflexivity. reflexivity. Defined. Lemma equal_option_nat_R : forall x y, x = y -> option_R nat nat nat_R x y. intros x y H; subst. destruct y; constructor; apply equal_nat_R; reflexivity. Defined. Parametricity Recursive prod. Parametricity Recursive Queue. Print Queue_R. Check Queue_R. Notation Bisimilar := Queue_R. Print Queue_R. Definition R (l1 : list nat) (l2 : list nat * list nat) := let (back, front) := l2 in l1 = back ++ rev front. Lemma rev_app : forall A (l1 l2 : list A), rev (l1 ++ l2) = rev l2 ++ rev l1. induction l1. intro; symmetry; apply app_nil_r. intro; simpl; rewrite IHl1; rewrite app_ass. reflexivity. Defined. Lemma rev_list_rect A : forall P:list A-> Type, P [] -> (forall (a:A) (l:list A), P (rev l) -> P (rev (a :: l))) -> forall l:list A, P (rev l). Proof. induction l; auto. Defined. Theorem rev_rect A : forall P:list A -> Type, P [] -> (forall (x:A) (l:list A), P l -> P (l ++ [x])) -> forall l:list A, P l. Proof. intros. generalize (rev_involutive l). intros E; rewrite <- E. apply (rev_list_rect _ P). auto. simpl. intros. apply (X0 a (rev l0)). auto. Defined. Lemma bisim_list_dlist : Bisimilar ListQueue DListQueue. apply (Queue_R_Build_Queue_R _ _ R). * reflexivity. * intros n1 n2 n_R. pose (nat_R_equal _ _ n_R) as H. destruct H. clear n_R. intros l [back front]. unfold R. simpl. intro; subst. simpl. reflexivity. * intros l [back front]. generalize l. clear l. unfold R; fold R. pattern back. apply rev_rect. intros l H; subst. rewrite rev_app. simpl. rewrite app_nil_r. rewrite rev_involutive. destruct front. constructor. repeat constructor. apply equal_nat_R; reflexivity. clear back; intros hd back IHR l H. subst. rewrite rev_app. rewrite rev_involutive. rewrite rev_app. simpl. destruct front. simpl. repeat constructor. apply equal_nat_R; reflexivity. simpl. repeat constructor. apply equal_nat_R; reflexivity. unfold R. rewrite rev_app. simpl. rewrite rev_involutive. reflexivity. Defined. Print program. Check program. Parametricity Recursive program. Check program_R. Lemma program_independent : forall n, program ListQueue n = program DListQueue n. intro n. apply option_nat_R_equal. apply program_R. apply bisim_list_dlist. apply equal_nat_R. reflexivity. Defined. Print program. Print program_R.
#!/usr/local/bin/python3.6 import re import math import asyncio import discord from discord.ext import commands from datetime import datetime from datetime import timedelta import psycopg2 as dbSQL import numpy as np from bin import zb from bin import zb_config _var = zb_config _query = """ SELECT g.guild_id,u.real_user_id,r.role_id,u.name,g.nick,u.int_user_id FROM users u LEFT JOIN guild_membership g ON u.int_user_id = g.int_user_id LEFT JOIN role_membership r ON u.int_user_id = r.int_user_id """ rmvRoles = [[517850437626363925],[513156267024449556],[517140313408536576], [509865275705917440],[509865272283496449],[509861871193423873], [509866307857154048],[509857601081704448],[513021830173556759], [509857604328095775],[520654520443732009]] _int_user_id = """ SELECT int_user_id FROM users WHERE real_user_id = {0} """ _update_punish = """ UPDATE guild_membership SET punished = {0} WHERE int_user_id = {1} AND guild_id = {2} """ def punish_user(member,number): sql = _int_user_id.format(member.id) data, rows, string = zb.sql_query(sql) intID = int(data[0]) sql = _update_punish.format(number,intID,member.guild.id) rows, string = zb.sql_update(sql) def is_outranked(member1, member2, role_perms): """ test for valid data in database at two columns """ idList1 = [] for role in member1.roles: idList1.append(role.id) idList2 = [] for role in member2.roles: idList2.append(role.id) sql = """ SELECT MIN(role_perms) FROM roles WHERE guild_id = {0} AND NOT role_perms = 0 AND role_perms <= {1} AND role_id in {2} """ sql = sql.format(member1.guild.id, role_perms, zb.sql_list(idList1)) data1, rows, string = zb.sql_query(sql) sql = """ SELECT MIN(role_perms) FROM roles WHERE guild_id = {0} AND NOT role_perms = 0 AND role_perms <= {1} AND role_id in {2} """ sql = sql.format(member2.guild.id, role_perms, zb.sql_list(idList2)) data2, rows, string = zb.sql_query(sql) try: var = int(data2[0]) except: return True if rows == 0: return True elif int(data1[0]) < int(data2[0]): return True else: return False
Nationally important deities gave rise to local manifestations , which sometimes absorbed the characteristics of older regional gods . Horus had many forms tied to particular places , including Horus of Nekhen , Horus of Buhen , and Horus of Edfu . Such local manifestations could be treated almost as separate beings . During the New Kingdom , one man was accused of stealing clothes by an oracle supposed to communicate messages from Amun of Pe @-@ Khenty . He consulted two other local oracles of Amun hoping for a different judgment . Gods ' manifestations also differed according to their roles . Horus could be a powerful sky god or vulnerable child , and these forms were sometimes counted as independent deities .
-- {-# OPTIONS --sized-types #-} -- no longer necessary -- {-# OPTIONS --termination-depth=2 #-} -- not necessary! -- {-# OPTIONS -v tc.size.solve:60 --show-implicit #-} -- {-# OPTIONS -v term:5 #-} module Issue709 where open import Common.Size data Bool : Set where true false : Bool postulate A : Set _<=_ : A → A → Bool data List {i : Size} : Set where [] : List cons : (j : Size< i) → A → List {j} → List {i} module If where if_then_else_ : {A : Set} → Bool → A → A → A if true then t else e = t if false then t else e = e merge : ∀ {i j} → List {i} → List {j} → List -- {∞} merge {i} {j} [] ys = ys merge {i} {j} (cons i' x xs) [] = cons _ x xs merge {i} {j} (cons i' x xs) (cons j' y ys) = if x <= y then cons _ x (merge xs (cons _ y ys)) else cons _ y (merge (cons _ x xs) ys) module Succeeds where merge : ∀ {i j} → List {i} → List {j} → List merge [] ys = ys merge (cons i' x xs) [] = cons _ x xs merge {i} {j} (cons i' x xs) (cons j' y ys) with x <= y ... | true = cons _ x (merge {i'} {j} -- removing this implicit application makes it not termination check xs (cons _ y ys)) ... | false = cons _ y (merge (cons _ x xs) ys) module NeedsTerminationDepthTwo where merge : ∀ {i j} → List {i} → List {j} → List merge [] ys = ys merge (cons j x xs) [] = cons _ x xs merge {i} {i'} (cons j x xs) (cons j' y ys) with x <= y ... | true = cons _ x (merge xs (cons _ y ys)) ... | false = cons _ y (merge (cons _ x xs) ys)
-------------------------------------------------------------------------------- {-# OPTIONS_GHC -fno-warn-orphans #-} -------------------------------------------------------------------------------- {-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilyDependencies #-} {-# LANGUAGE TypeInType #-} {-# LANGUAGE UnboxedTuples #-} {-# LANGUAGE UndecidableInstances #-} -------------------------------------------------------------------------------- -- | Internal module to Eigen. -- Here we define all foreign function calls, -- and some typeclasses integral to the public and private interfaces -- of the library. module Eigen.Internal where -- FIXME: Explicit export list -------------------------------------------------------------------------------- import Control.Monad (when) import Data.Binary (Binary(put,get)) import Data.Binary.Get (getByteString, getWord32be) import Data.Binary.Put (putByteString, putWord32be) import Data.Bits (xor) import Data.Complex (Complex((:+))) import Data.Kind (Type) import Data.Proxy (Proxy(Proxy)) import Foreign.C.String (CString, peekCString) import Foreign.C.Types (CInt(CInt), CFloat(CFloat), CDouble(CDouble), CChar) import Foreign.ForeignPtr (ForeignPtr, castForeignPtr, withForeignPtr) import Foreign.Ptr (Ptr, castPtr, nullPtr, plusPtr) import Foreign.Storable (Storable(sizeOf, alignment, poke, peek, peekByteOff, peekElemOff, pokeByteOff, pokeElemOff)) import GHC.TypeLits (natVal, KnownNat, Nat) import System.IO.Unsafe (unsafeDupablePerformIO) import qualified Data.Vector.Storable as VS import qualified Data.ByteString as BS import qualified Data.ByteString.Internal as BSI -------------------------------------------------------------------------------- -- | Like 'Proxy', but specialised to 'Nat'. data Row (r :: Nat) = Row -- | Like 'Proxy', but specialised to 'Nat'. data Col (c :: Nat) = Col -- | Used internally. Given a 'KnownNat' constraint, turn the type-level 'Nat' into an 'Int'. natToInt :: forall n. KnownNat n => Int {-# INLINE natToInt #-} natToInt = fromIntegral (natVal @n Proxy) -------------------------------------------------------------------------------- -- | Cast to and from a C-FFI type -- 'Cast' is a closed typeclass with an associated injective type family. -- It is closed in the sense that we provide only four types -- with instances for it; and intend for eigen to only be used -- with those four types. The injectivity of the type family is -- then useful for avoiding MPTCs. 'Cast' has two functions; 'toC' -- and 'fromC', where 'toC' goes from a Haskell type to its associated -- C type for internal use, with the C FFI, and 'fromC' goes from the -- associated C type to the Haskell type. class Cast (a :: Type) where type family C a = (result :: Type) | result -> a toC :: a -> C a fromC :: C a -> a instance Cast Int where type C Int = CInt toC = CInt . fromIntegral {-# INLINE toC #-} fromC (CInt x) = fromIntegral x {-# INLINE fromC #-} instance Cast Float where type C Float = CFloat toC = CFloat {-# INLINE toC #-} fromC (CFloat x) = x {-# INLINE fromC #-} instance Cast Double where type C Double = CDouble toC = CDouble {-# INLINE toC #-} fromC (CDouble x) = x {-# INLINE fromC #-} instance Cast a => Cast (Complex a) where type C (Complex a) = CComplex (C a) toC (a :+ b) = CComplex (toC a) (toC b) {-# INLINE toC #-} fromC (CComplex a b) = (fromC a) :+ (fromC b) {-# INLINE fromC #-} -- | WARNING! 'toC' is lossy for any Int greater than (maxBound :: Int32)! instance Cast a => Cast (Int, Int, a) where type C (Int, Int, a) = CTriplet a {-# INLINE toC #-} toC (x, y, z) = CTriplet (toC x) (toC y) (toC z) {-# INLINE fromC #-} fromC (CTriplet x y z) = (fromC x, fromC y, fromC z) -------------------------------------------------------------------------------- -- | Complex number for FFI with the same memory layout as std::complex\<T\> data CComplex a = CComplex !a !a deriving (Show) instance Storable a => Storable (CComplex a) where sizeOf _ = sizeOf (undefined :: a) * 2 alignment _ = alignment (undefined :: a) poke p (CComplex x y) = do pokeElemOff (castPtr p) 0 x pokeElemOff (castPtr p) 1 y peek p = CComplex <$> peekElemOff (castPtr p) 0 <*> peekElemOff (castPtr p) 1 -------------------------------------------------------------------------------- -- | FIXME: Doc data CTriplet a where CTriplet :: Cast a => !CInt -> !CInt -> !(C a) -> CTriplet a deriving instance (Show a, Show (C a)) => Show (CTriplet a) instance (Storable a, Elem a) => Storable (CTriplet a) where sizeOf _ = sizeOf (undefined :: a) + sizeOf (undefined :: CInt) * 2 alignment _ = alignment (undefined :: CInt) poke p (CTriplet row col val) = do pokeElemOff (castPtr p) 0 row pokeElemOff (castPtr p) 1 col pokeByteOff p (sizeOf (undefined :: CInt) * 2) val peek p = CTriplet <$> peekElemOff (castPtr p) 0 <*> peekElemOff (castPtr p) 1 <*> peekByteOff p (sizeOf (undefined :: CInt) * 2) -------------------------------------------------------------------------------- -- | `Elem` is a closed typeclass that encompasses the properties -- eigen expects its values to possess, and simplifies the external -- API quite a bit. class (Num a, Cast a, Storable a, Storable (C a), Code (C a)) => Elem a instance Elem Float instance Elem Double instance Elem (Complex Float) instance Elem (Complex Double) -------------------------------------------------------------------------------- -- | Encode a C Type as a CInt -- -- Hack used in FFI wrapper functions when constructing FFI calls class Code a where; code :: a -> CInt instance Code CFloat where; code _ = 0 instance Code CDouble where; code _ = 1 instance Code (CComplex CFloat) where; code _ = 2 instance Code (CComplex CDouble) where; code _ = 3 -- | Hack used in constructing FFI calls. newtype MagicCode = MagicCode CInt deriving Eq instance Binary MagicCode where put (MagicCode _code) = putWord32be $ fromIntegral _code get = MagicCode . fromIntegral <$> getWord32be -- | Hack used in constructing FFI calls. magicCode :: Code a => a -> MagicCode magicCode x = MagicCode (code x `xor` 0x45696730) -------------------------------------------------------------------------------- -- | Machine size of a 'CInt'. intSize :: Int intSize = sizeOf (undefined :: CInt) -- | FIXME: Doc encodeInt :: CInt -> BS.ByteString encodeInt x = BSI.unsafeCreate (sizeOf x) $ (`poke` x) . castPtr -- | FIXME: Doc decodeInt :: BS.ByteString -> CInt decodeInt (BSI.PS fp fo fs) | fs == sizeOf x = x | otherwise = error "decodeInt: wrong buffer size" where x = performIO $ withForeignPtr fp $ peek . (`plusPtr` fo) -------------------------------------------------------------------------------- -- | 'Binary' instance for 'Data.Vector.Storable.Mutable.Vector' instance Storable a => Binary (VS.Vector a) where put vs = put (BS.length bs) >> putByteString bs where (fp,fs) = VS.unsafeToForeignPtr0 vs es = sizeOf (VS.head vs) bs = BSI.fromForeignPtr (castForeignPtr fp) 0 (fs * es) get = get >>= getByteString >>= \bs -> let (fp,fo,fs) = BSI.toForeignPtr bs es = sizeOf (VS.head vs) -- `plusForeignPtr` is used qualified here to just remind a reader -- that it is defined internally within eigen vs = VS.unsafeFromForeignPtr0 (Eigen.Internal.plusForeignPtr fp fo) (fs `div` es) in return vs -------------------------------------------------------------------------------- -- | FIXME: Doc data CSparseMatrix a -- | FIXME: Doc type CSparseMatrixPtr a = Ptr (CSparseMatrix a) -- | FIXME: Doc data CSolver a -- | FIXME: Doc type CSolverPtr a = Ptr (CSolver a) -- {-# INLINE unholyPerformIO #-} -- unholyPerformIO :: IO a -> a -- unholyPerformIO (IO m) = case m realWorld# of (# _, r #) -> r -- | FIXME: replace with unholyPerformIO (?) performIO :: IO a -> a performIO = unsafeDupablePerformIO -- | FIXME: Doc plusForeignPtr :: ForeignPtr a -> Int -> ForeignPtr b plusForeignPtr fp fo = castForeignPtr fp1 where vs :: VS.Vector CChar vs = VS.unsafeFromForeignPtr (castForeignPtr fp) fo 0 (fp1, _) = VS.unsafeToForeignPtr0 vs foreign import ccall "eigen-proxy.h free" c_freeString :: CString -> IO () call :: IO CString -> IO () call func = func >>= \c_str -> when (c_str /= nullPtr) $ peekCString c_str >>= \str -> c_freeString c_str >> fail str foreign import ccall "eigen-proxy.h free" free :: Ptr a -> IO () foreign import ccall "eigen-proxy.h eigen_setNbThreads" c_setNbThreads :: CInt -> IO () foreign import ccall "eigen-proxy.h eigen_getNbThreads" c_getNbThreads :: IO CInt -------------------------------------------------------------------------------- #let api1 name, args = "foreign import ccall \"eigen_%s\" c_%s :: CInt -> %s\n%s :: forall a . Code (C a) => %s\n%s = c_%s (code (undefined :: (C a)))", #name, #name, args, #name, args, #name, #name #api1 random, "Ptr (C a) -> CInt -> CInt -> IO CString" #api1 identity, "Ptr (C a) -> CInt -> CInt -> IO CString" #api1 add, "Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 sub, "Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 mul, "Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 diagonal, "Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 transpose, "Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 inverse, "Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 adjoint, "Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 conjugate, "Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 normalize, "Ptr (C a) -> CInt -> CInt -> IO CString" #api1 sum, "Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 prod, "Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 mean, "Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 norm, "Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 trace, "Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 squaredNorm, "Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 blueNorm, "Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 hypotNorm, "Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 determinant, "Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 rank, "CInt -> Ptr CInt -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 image, "CInt -> Ptr (Ptr (C a)) -> Ptr CInt -> Ptr CInt -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 kernel, "CInt -> Ptr (Ptr (C a)) -> Ptr CInt -> Ptr CInt -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 solve, "CInt -> Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString" #api1 relativeError, "Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString" -------------------------------------------------------------------------------- #let api2 name, args = "foreign import ccall \"eigen_%s\" c_%s :: CInt -> %s\n%s :: forall a . Code (C a) => %s\n%s = c_%s (code (undefined :: (C a)))", #name, #name, args, #name, args, #name, #name #api2 sparse_new, "CInt -> CInt -> Ptr (CSparseMatrixPtr a) -> IO CString" #api2 sparse_clone, "CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString" #api2 sparse_fromList, "CInt -> CInt -> Ptr (CTriplet a) -> CInt -> Ptr (CSparseMatrixPtr a) -> IO CString" #api2 sparse_toList, "CSparseMatrixPtr a -> Ptr (CTriplet a) -> CInt -> IO CString" #api2 sparse_free, "CSparseMatrixPtr a -> IO CString" #api2 sparse_makeCompressed,"CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString" #api2 sparse_uncompress, "CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString" #api2 sparse_isCompressed, "CSparseMatrixPtr a -> Ptr CInt -> IO CString" #api2 sparse_transpose, "CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString" #api2 sparse_adjoint, "CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString" #api2 sparse_pruned, "CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString" #api2 sparse_prunedRef, "CSparseMatrixPtr a -> Ptr (C a) -> Ptr (CSparseMatrixPtr a) -> IO CString" #api2 sparse_scale, "CSparseMatrixPtr a -> Ptr (C a) -> Ptr (CSparseMatrixPtr a) -> IO CString" #api2 sparse_nonZeros, "CSparseMatrixPtr a -> Ptr CInt -> IO CString" #api2 sparse_innerSize, "CSparseMatrixPtr a -> Ptr CInt -> IO CString" #api2 sparse_outerSize, "CSparseMatrixPtr a -> Ptr CInt -> IO CString" #api2 sparse_coeff, "CSparseMatrixPtr a -> CInt -> CInt -> Ptr (C a) -> IO CString" #api2 sparse_coeffRef, "CSparseMatrixPtr a -> CInt -> CInt -> Ptr (Ptr (C a)) -> IO CString" #api2 sparse_cols, "CSparseMatrixPtr a -> Ptr CInt -> IO CString" #api2 sparse_rows, "CSparseMatrixPtr a -> Ptr CInt -> IO CString" #api2 sparse_norm, "CSparseMatrixPtr a -> Ptr (C a) -> IO CString" #api2 sparse_squaredNorm, "CSparseMatrixPtr a -> Ptr (C a) -> IO CString" #api2 sparse_blueNorm, "CSparseMatrixPtr a -> Ptr (C a) -> IO CString" #api2 sparse_add, "CSparseMatrixPtr a -> CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString" #api2 sparse_sub, "CSparseMatrixPtr a -> CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString" #api2 sparse_mul, "CSparseMatrixPtr a -> CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString" #api2 sparse_block, "CSparseMatrixPtr a -> CInt -> CInt -> CInt -> CInt -> Ptr (CSparseMatrixPtr a) -> IO CString" #api2 sparse_fromMatrix, "Ptr (C a) -> CInt -> CInt -> Ptr (CSparseMatrixPtr a) -> IO CString" #api2 sparse_toMatrix, "CSparseMatrixPtr a -> Ptr (C a) -> CInt -> CInt -> IO CString" #api2 sparse_values, "CSparseMatrixPtr a -> Ptr CInt -> Ptr (Ptr (C a)) -> IO CString" #api2 sparse_outerStarts, "CSparseMatrixPtr a -> Ptr CInt -> Ptr (Ptr CInt) -> IO CString" #api2 sparse_innerIndices, "CSparseMatrixPtr a -> Ptr CInt -> Ptr (Ptr CInt) -> IO CString" #api2 sparse_innerNNZs, "CSparseMatrixPtr a -> Ptr CInt -> Ptr (Ptr CInt) -> IO CString" #api2 sparse_setZero, "CSparseMatrixPtr a -> IO CString" #api2 sparse_setIdentity, "CSparseMatrixPtr a -> IO CString" #api2 sparse_reserve, "CSparseMatrixPtr a -> CInt -> IO CString" #api2 sparse_resize, "CSparseMatrixPtr a -> CInt -> CInt -> IO CString" #api2 sparse_conservativeResize, "CSparseMatrixPtr a -> CInt -> CInt -> IO CString" #api2 sparse_compressInplace, "CSparseMatrixPtr a -> IO CString" #api2 sparse_uncompressInplace, "CSparseMatrixPtr a -> IO CString" -------------------------------------------------------------------------------- #let api3 name, args = "foreign import ccall \"eigen_%s\" c_%s :: CInt -> CInt -> %s\n%s :: forall s a . (Code s, Code (C a)) => s -> %s\n%s s = c_%s (code (undefined :: (C a))) (code s)", #name, #name, args, #name, args, #name, #name #api3 sparse_la_newSolver, "Ptr (CSolverPtr a) -> IO CString" #api3 sparse_la_freeSolver, "CSolverPtr a -> IO CString" #api3 sparse_la_factorize, "CSolverPtr a -> CSparseMatrixPtr a -> IO CString" #api3 sparse_la_analyzePattern, "CSolverPtr a -> CSparseMatrixPtr a -> IO CString" #api3 sparse_la_compute, "CSolverPtr a -> CSparseMatrixPtr a -> IO CString" #api3 sparse_la_tolerance, "CSolverPtr a -> Ptr CDouble -> IO CString" #api3 sparse_la_setTolerance, "CSolverPtr a -> CDouble -> IO CString" #api3 sparse_la_maxIterations, "CSolverPtr a -> Ptr CInt -> IO CString" #api3 sparse_la_setMaxIterations, "CSolverPtr a -> CInt -> IO CString" #api3 sparse_la_info, "CSolverPtr a -> Ptr CInt -> IO CString" #api3 sparse_la_error, "CSolverPtr a -> Ptr CDouble -> IO CString" #api3 sparse_la_iterations, "CSolverPtr a -> Ptr CInt -> IO CString" #api3 sparse_la_solve, "CSolverPtr a -> CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString" -- #api3 sparse_la_solveWithGuess, "CSolverPtr a -> CSparseMatrixPtr a -> CSparseMatrixPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString" #api3 sparse_la_matrixQ, "CSolverPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString" #api3 sparse_la_matrixR, "CSolverPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString" #api3 sparse_la_setPivotThreshold, "CSolverPtr a -> CDouble -> IO CString" #api3 sparse_la_rank, "CSolverPtr a -> Ptr CInt -> IO CString" #api3 sparse_la_matrixL, "CSolverPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString" #api3 sparse_la_matrixU, "CSolverPtr a -> Ptr (CSparseMatrixPtr a) -> IO CString" #api3 sparse_la_setSymmetric, "CSolverPtr a -> CInt -> IO CString" #api3 sparse_la_determinant, "CSolverPtr a -> Ptr (C a) -> IO CString" #api3 sparse_la_logAbsDeterminant, "CSolverPtr a -> Ptr (C a) -> IO CString" #api3 sparse_la_absDeterminant, "CSolverPtr a -> Ptr (C a) -> IO CString" #api3 sparse_la_signDeterminant, "CSolverPtr a -> Ptr (C a) -> IO CString" --------------------------------------------------------------------------------
(* Title: Conservation of CSP Noninterference Security under Sequential Composition Author: Pasquale Noce Security Certification Specialist at Arjo Systems, Italy pasquale dot noce dot lavoro at gmail dot com pasquale dot noce at arjosystems dot com *) section "Propaedeutic definitions and lemmas" theory Propaedeutics imports Noninterference_Ipurge_Unwinding.DeterministicProcesses begin text \<open> \null \emph{To our Lord Jesus Christ, my dear parents, and my "little" sister,} \emph{for the immense love with which they surround me.} \null In his outstanding work on Communicating Sequential Processes \cite{R4}, Hoare has defined two fundamental binary operations allowing to compose the input processes into another, typically more complex, process: sequential composition and concurrent composition. Particularly, the output of the former operation is a process that initially behaves like the first operand, and then like the second operand once the execution of the first one has terminated successfully, as long as it does. In order to distinguish it from deadlock, successful termination is regarded as a special event in the process alphabet (required to be the same for both the input processes and the output one). This paper formalizes Hoare's definition of sequential composition and proves, in the general case of a possibly intransitive policy, that CSP noninterference security \cite{R2} is conserved under this operation, viz. the security of both of the input processes implies that of the output process. This property is conditional on two nontrivial assumptions. The first assumption is that the policy do not allow successful termination to be affected by confidential events, viz. by other events not allowed to affect some event in the process alphabet. The second assumption is that successful termination do not occur as an alternative to other events in the traces of the first operand, viz. that whenever the process can terminate successfully, it cannot engage in any other event. Both of these assumptions are shown, by means of counterexamples, to be necessary for the theorem to hold. From the above sketch of the sequential composition of two processes @{term P} and @{term Q}, notwithstanding its informal character, it clearly follows that any failure of the output process is either a failure of @{term P} (case A), or a pair @{term "(xs @ ys, Y)"}, where @{term xs} is a trace of @{term P} and @{term "(ys, Y)"} is a failure of @{term Q} (case B). On the other hand, according to the definition of security given in \cite{R2}, the output process is secure just in case, for each of its failures, any event @{term x} contained in the failure trace can be removed from the trace, or inserted into the trace of another failure after the same previous events as in the original trace, and the resulting pair is still a failure of the process, provided that the future of @{term x} is deprived of the events that may be affected by @{term x}. In case A, this transformation is performed on a failure of process @{term P}; being it secure, the result is still a failure of @{term P}, and then of the output process. In case B, the transformation may involve either @{term ys} alone, or both @{term xs} and @{term ys}, depending on the position at which @{term x} is removed or inserted. In the former subcase, being @{term Q} secure, the result has the form @{term "(xs @ ys', Y')"} where @{term "(ys', Y')"} is a failure of @{term Q}, thus it is still a failure of the output process. In the latter subcase, @{term ys} has to be deprived of the events that may be affected by @{term x}, as well as by any event affected by @{term x} in the involved portion of @{term xs}, and a similar transformation applies to @{term Y}. In order that the output process be secure, the resulting pair @{term "(ys'', Y'')"} must still be a failure of @{term Q}, so that the pair @{term "(xs' @ ys'', Y'')"}, where @{term xs'} results from the transformation of @{term xs}, be a failure of the output process. The transformations bringing from @{term ys} and @{term Y} to @{term ys''} and @{term Y''} are implemented by the functions @{term ipurge_tr_aux} and @{term ipurge_ref_aux} defined in \cite{R3}. Therefore, the proof of the target security conservation theorem requires that of the following lemma: given a process @{term P}, a noninterference policy @{term I}, and an event-domain map @{term D}, if @{term P} is secure with respect to @{term I} and @{term D} and @{term "(xs, X)"} is a failure of @{term P}, then @{term "(ipurge_tr_aux I D U xs, ipurge_ref_aux I D U xs X)"} is still a failure of @{term P}. In other words, the lemma states that the failures of a secure process are closed under intransitive purge. This section contains a proof of such closure lemma, as well as further definitions and lemmas required for the proof of the target theorem. Throughout this paper, the salient points of definitions and proofs are commented; for additional information, cf. Isabelle documentation, particularly \cite{R6}, \cite{R7}, \cite{R8}, and \cite{R9}. \<close> subsection "Preliminary propaedeutic lemmas" text \<open> In what follows, some lemmas required for the demonstration of the target closure lemma are proven. Here below is the proof of some properties of functions @{term ipurge_tr} and @{term ipurge_ref}. \null \<close> lemma ipurge_tr_length: "length (ipurge_tr I D u xs) \<le> length xs" by (induction xs rule: rev_induct, simp_all) lemma ipurge_ref_swap: "ipurge_ref I D u xs {x \<in> X. P x} = {x \<in> ipurge_ref I D u xs X. P x}" proof (simp add: ipurge_ref_def) qed blast lemma ipurge_ref_last: "ipurge_ref I D u (xs @ [x]) X = (if (u, D x) \<in> I \<or> (\<exists>v \<in> sinks I D u xs. (v, D x) \<in> I) then ipurge_ref I D u xs {x' \<in> X. (D x, D x') \<notin> I} else ipurge_ref I D u xs X)" proof (cases "(u, D x) \<in> I \<or> (\<exists>v \<in> sinks I D u xs. (v, D x) \<in> I)", simp_all add: ipurge_ref_def) qed blast text \<open> \null Here below is the proof of some properties of function @{term sinks_aux}. \null \<close> lemma sinks_aux_append: "sinks_aux I D U (xs @ ys) = sinks_aux I D (sinks_aux I D U xs) ys" proof (induction ys rule: rev_induct, simp, subst append_assoc [symmetric]) qed (simp del: append_assoc) lemma sinks_aux_union: "sinks_aux I D (U \<union> V) xs = sinks_aux I D U xs \<union> sinks_aux I D V (ipurge_tr_aux I D U xs)" proof (induction xs rule: rev_induct, simp) fix x xs assume A: "sinks_aux I D (U \<union> V) xs = sinks_aux I D U xs \<union> sinks_aux I D V (ipurge_tr_aux I D U xs)" show "sinks_aux I D (U \<union> V) (xs @ [x]) = sinks_aux I D U (xs @ [x]) \<union> sinks_aux I D V (ipurge_tr_aux I D U (xs @ [x]))" proof (cases "\<exists>w \<in> sinks_aux I D (U \<union> V) xs. (w, D x) \<in> I") case True hence "\<exists>w \<in> sinks_aux I D U xs \<union> sinks_aux I D V (ipurge_tr_aux I D U xs). (w, D x) \<in> I" using A by simp hence "(\<exists>w \<in> sinks_aux I D U xs. (w, D x) \<in> I) \<or> (\<exists>w \<in> sinks_aux I D V (ipurge_tr_aux I D U xs). (w, D x) \<in> I)" by blast thus ?thesis using A and True by (cases "\<exists>w \<in> sinks_aux I D U xs. (w, D x) \<in> I", simp_all) next case False hence "\<not> (\<exists>w \<in> sinks_aux I D U xs \<union> sinks_aux I D V (ipurge_tr_aux I D U xs). (w, D x) \<in> I)" using A by simp hence "\<not> (\<exists>w \<in> sinks_aux I D U xs. (w, D x) \<in> I) \<and> \<not> (\<exists>w \<in> sinks_aux I D V (ipurge_tr_aux I D U xs). (w, D x) \<in> I)" by blast thus ?thesis using A and False by simp qed qed lemma sinks_aux_subset_dom: assumes A: "U \<subseteq> V" shows "sinks_aux I D U xs \<subseteq> sinks_aux I D V xs" proof (induction xs rule: rev_induct, simp add: A, rule subsetI) fix x xs w assume B: "sinks_aux I D U xs \<subseteq> sinks_aux I D V xs" and C: "w \<in> sinks_aux I D U (xs @ [x])" show "w \<in> sinks_aux I D V (xs @ [x])" proof (cases "\<exists>u \<in> sinks_aux I D U xs. (u, D x) \<in> I") case True hence "w = D x \<or> w \<in> sinks_aux I D U xs" using C by simp moreover { assume D: "w = D x" obtain u where E: "u \<in> sinks_aux I D U xs" and F: "(u, D x) \<in> I" using True .. have "u \<in> sinks_aux I D V xs" using B and E .. with F have "\<exists>u \<in> sinks_aux I D V xs. (u, D x) \<in> I" .. hence ?thesis using D by simp } moreover { assume "w \<in> sinks_aux I D U xs" with B have "w \<in> sinks_aux I D V xs" .. hence ?thesis by simp } ultimately show ?thesis .. next case False hence "w \<in> sinks_aux I D U xs" using C by simp with B have "w \<in> sinks_aux I D V xs" .. thus ?thesis by simp qed qed lemma sinks_aux_subset_ipurge_tr_aux: "sinks_aux I D U (ipurge_tr_aux I' D' U' xs) \<subseteq> sinks_aux I D U xs" proof (induction xs rule: rev_induct, simp, rule subsetI) fix x xs w assume A: "sinks_aux I D U (ipurge_tr_aux I' D' U' xs) \<subseteq> sinks_aux I D U xs" and B: "w \<in> sinks_aux I D U (ipurge_tr_aux I' D' U' (xs @ [x]))" show "w \<in> sinks_aux I D U (xs @ [x])" proof (cases "\<exists>u \<in> sinks_aux I D U xs. (u, D x) \<in> I", simp_all (no_asm_simp)) from B have "w = D x \<or> w \<in> sinks_aux I D U (ipurge_tr_aux I' D' U' xs)" proof (cases "\<exists>u' \<in> sinks_aux I' D' U' xs. (u', D' x) \<in> I'", simp_all) qed (cases "\<exists>u \<in> sinks_aux I D U (ipurge_tr_aux I' D' U' xs). (u, D x) \<in> I", simp_all) moreover { assume "w = D x" hence "w = D x \<or> w \<in> sinks_aux I D U xs" .. } moreover { assume "w \<in> sinks_aux I D U (ipurge_tr_aux I' D' U' xs)" with A have "w \<in> sinks_aux I D U xs" .. hence "w = D x \<or> w \<in> sinks_aux I D U xs" .. } ultimately show "w = D x \<or> w \<in> sinks_aux I D U xs" .. next assume C: "\<not> (\<exists>u \<in> sinks_aux I D U xs. (u, D x) \<in> I)" have "w \<in> sinks_aux I D U (ipurge_tr_aux I' D' U' xs)" proof (cases "\<exists>u' \<in> sinks_aux I' D' U' xs. (u', D' x) \<in> I'") case True thus "w \<in> sinks_aux I D U (ipurge_tr_aux I' D' U' xs)" using B by simp next case False hence "w \<in> sinks_aux I D U (ipurge_tr_aux I' D' U' xs @ [x])" using B by simp moreover have "\<not> (\<exists>u \<in> sinks_aux I D U (ipurge_tr_aux I' D' U' xs). (u, D x) \<in> I)" (is "\<not> ?P") proof assume ?P then obtain u where D: "u \<in> sinks_aux I D U (ipurge_tr_aux I' D' U' xs)" and E: "(u, D x) \<in> I" .. have "u \<in> sinks_aux I D U xs" using A and D .. with E have "\<exists>u \<in> sinks_aux I D U xs. (u, D x) \<in> I" .. thus False using C by contradiction qed ultimately show "w \<in> sinks_aux I D U (ipurge_tr_aux I' D' U' xs)" by simp qed with A show "w \<in> sinks_aux I D U xs" .. qed qed lemma sinks_aux_subset_ipurge_tr: "sinks_aux I D U (ipurge_tr I' D' u' xs) \<subseteq> sinks_aux I D U xs" by (simp add: ipurge_tr_aux_single_dom [symmetric] sinks_aux_subset_ipurge_tr_aux) lemma sinks_aux_member_ipurge_tr_aux [rule_format]: "u \<in> sinks_aux I D (U \<union> V) xs \<longrightarrow> (u, w) \<in> I \<longrightarrow> \<not> (\<exists>v \<in> sinks_aux I D V xs. (v, w) \<in> I) \<longrightarrow> u \<in> sinks_aux I D U (ipurge_tr_aux I D V xs)" proof (induction xs arbitrary: u w rule: rev_induct, (rule_tac [!] impI)+, simp) fix u w assume A: "(u, w) \<in> I" and B: "\<forall>v \<in> V. (v, w) \<notin> I" assume "u \<in> U \<or> u \<in> V" moreover { assume "u \<in> U" } moreover { assume "u \<in> V" with B have "(u, w) \<notin> I" .. hence "u \<in> U" using A by contradiction } ultimately show "u \<in> U" .. next fix x xs u w assume A: "\<And>u w. u \<in> sinks_aux I D (U \<union> V) xs \<longrightarrow> (u, w) \<in> I \<longrightarrow> \<not> (\<exists>v \<in> sinks_aux I D V xs. (v, w) \<in> I) \<longrightarrow> u \<in> sinks_aux I D U (ipurge_tr_aux I D V xs)" and B: "u \<in> sinks_aux I D (U \<union> V) (xs @ [x])" and C: "(u, w) \<in> I" and D: "\<not> (\<exists>v \<in> sinks_aux I D V (xs @ [x]). (v, w) \<in> I)" show "u \<in> sinks_aux I D U (ipurge_tr_aux I D V (xs @ [x]))" proof (cases "\<exists>u' \<in> sinks_aux I D (U \<union> V) xs. (u', D x) \<in> I") case True hence "u = D x \<or> u \<in> sinks_aux I D (U \<union> V) xs" using B by simp moreover { assume E: "u = D x" obtain u' where "u' \<in> sinks_aux I D (U \<union> V) xs" and F: "(u', D x) \<in> I" using True .. moreover have "u' \<in> sinks_aux I D (U \<union> V) xs \<longrightarrow> (u', D x) \<in> I \<longrightarrow> \<not> (\<exists>v \<in> sinks_aux I D V xs. (v, D x) \<in> I) \<longrightarrow> u' \<in> sinks_aux I D U (ipurge_tr_aux I D V xs)" (is "_ \<longrightarrow> _ \<longrightarrow> \<not> ?P \<longrightarrow> ?Q") using A . ultimately have "\<not> ?P \<longrightarrow> ?Q" by simp moreover have "\<not> ?P" proof have "(D x, w) \<in> I" using C and E by simp moreover assume ?P hence "D x \<in> sinks_aux I D V (xs @ [x])" by simp ultimately have "\<exists>v \<in> sinks_aux I D V (xs @ [x]). (v, w) \<in> I" .. moreover have "\<not> (\<exists>v \<in> sinks_aux I D V (xs @ [x]). (v, w) \<in> I)" using D by simp ultimately show False by contradiction qed ultimately have ?Q .. with F have "\<exists>u' \<in> sinks_aux I D U (ipurge_tr_aux I D V xs). (u', D x) \<in> I" .. hence "D x \<in> sinks_aux I D U (ipurge_tr_aux I D V xs @ [x])" by simp moreover have "ipurge_tr_aux I D V xs @ [x] = ipurge_tr_aux I D V (xs @ [x])" using \<open>\<not> ?P\<close> by simp ultimately have ?thesis using E by simp } moreover { assume "u \<in> sinks_aux I D (U \<union> V) xs" moreover have "u \<in> sinks_aux I D (U \<union> V) xs \<longrightarrow> (u, w) \<in> I \<longrightarrow> \<not> (\<exists>v \<in> sinks_aux I D V xs. (v, w) \<in> I) \<longrightarrow> u \<in> sinks_aux I D U (ipurge_tr_aux I D V xs)" (is "_ \<longrightarrow> _ \<longrightarrow> \<not> ?P \<longrightarrow> ?Q") using A . ultimately have "\<not> ?P \<longrightarrow> ?Q" using C by simp moreover have "\<not> ?P" proof assume ?P hence "\<exists>v \<in> sinks_aux I D V (xs @ [x]). (v, w) \<in> I" by simp thus False using D by contradiction qed ultimately have "u \<in> sinks_aux I D U (ipurge_tr_aux I D V xs)" .. hence ?thesis by simp } ultimately show ?thesis .. next case False hence "u \<in> sinks_aux I D (U \<union> V) xs" using B by simp moreover have "u \<in> sinks_aux I D (U \<union> V) xs \<longrightarrow> (u, w) \<in> I \<longrightarrow> \<not> (\<exists>v \<in> sinks_aux I D V xs. (v, w) \<in> I) \<longrightarrow> u \<in> sinks_aux I D U (ipurge_tr_aux I D V xs)" (is "_ \<longrightarrow> _ \<longrightarrow> \<not> ?P \<longrightarrow> ?Q") using A . ultimately have "\<not> ?P \<longrightarrow> ?Q" using C by simp moreover have "\<not> ?P" proof assume ?P hence "\<exists>v \<in> sinks_aux I D V (xs @ [x]). (v, w) \<in> I" by simp thus False using D by contradiction qed ultimately have "u \<in> sinks_aux I D U (ipurge_tr_aux I D V xs)" .. thus ?thesis by simp qed qed lemma sinks_aux_member_ipurge_tr: assumes A: "u \<in> sinks_aux I D (insert v U) xs" and B: "(u, w) \<in> I" and C: "\<not> ((v, w) \<in> I \<or> (\<exists>v' \<in> sinks I D v xs. (v', w) \<in> I))" shows "u \<in> sinks_aux I D U (ipurge_tr I D v xs)" proof (subst ipurge_tr_aux_single_dom [symmetric], rule_tac w = w in sinks_aux_member_ipurge_tr_aux) show "u \<in> sinks_aux I D (U \<union> {v}) xs" using A by simp next show "(u, w) \<in> I" using B . next show "\<not> (\<exists>v' \<in> sinks_aux I D {v} xs. (v', w) \<in> I)" using C by (simp add: sinks_aux_single_dom) qed text \<open> \null Here below is the proof of some properties of functions @{term ipurge_tr_aux} and @{term ipurge_ref_aux}. \null \<close> lemma ipurge_tr_aux_single_event: "ipurge_tr_aux I D U [x] = (if \<exists>v \<in> U. (v, D x) \<in> I then [] else [x])" by (subst (2) append_Nil [symmetric], simp del: append_Nil) lemma ipurge_tr_aux_cons: "ipurge_tr_aux I D U (x # xs) = (if \<exists>u \<in> U. (u, D x) \<in> I then ipurge_tr_aux I D (insert (D x) U) xs else x # ipurge_tr_aux I D U xs)" proof - have "ipurge_tr_aux I D U (x # xs) = ipurge_tr_aux I D U ([x] @ xs)" by simp also have "\<dots> = ipurge_tr_aux I D U [x] @ ipurge_tr_aux I D (sinks_aux I D U [x]) xs" by (simp only: ipurge_tr_aux_append) finally show ?thesis by (simp add: sinks_aux_single_event ipurge_tr_aux_single_event) qed lemma ipurge_tr_aux_union: "ipurge_tr_aux I D (U \<union> V) xs = ipurge_tr_aux I D V (ipurge_tr_aux I D U xs)" proof (induction xs rule: rev_induct, simp) fix x xs assume A: "ipurge_tr_aux I D (U \<union> V) xs = ipurge_tr_aux I D V (ipurge_tr_aux I D U xs)" show "ipurge_tr_aux I D (U \<union> V) (xs @ [x]) = ipurge_tr_aux I D V (ipurge_tr_aux I D U (xs @ [x]))" proof (cases "\<exists>v \<in> sinks_aux I D (U \<union> V) xs. (v, D x) \<in> I") case True hence "\<exists>w \<in> sinks_aux I D U xs \<union> sinks_aux I D V (ipurge_tr_aux I D U xs). (w, D x) \<in> I" by (simp add: sinks_aux_union) hence "(\<exists>w \<in> sinks_aux I D U xs. (w, D x) \<in> I) \<or> (\<exists>w \<in> sinks_aux I D V (ipurge_tr_aux I D U xs). (w, D x) \<in> I)" by blast thus ?thesis using A and True by (cases "\<exists>w \<in> sinks_aux I D U xs. (w, D x) \<in> I", simp_all) next case False hence "\<not> (\<exists>w \<in> sinks_aux I D U xs \<union> sinks_aux I D V (ipurge_tr_aux I D U xs). (w, D x) \<in> I)" by (simp add: sinks_aux_union) hence "\<not> (\<exists>w \<in> sinks_aux I D U xs. (w, D x) \<in> I) \<and> \<not> (\<exists>w \<in> sinks_aux I D V (ipurge_tr_aux I D U xs). (w, D x) \<in> I)" by blast thus ?thesis using A and False by simp qed qed lemma ipurge_tr_aux_insert: "ipurge_tr_aux I D (insert v U) xs = ipurge_tr_aux I D U (ipurge_tr I D v xs)" by (subst insert_is_Un, simp only: ipurge_tr_aux_union ipurge_tr_aux_single_dom) lemma ipurge_ref_aux_subset: "ipurge_ref_aux I D U xs X \<subseteq> X" by (subst ipurge_ref_aux_def, rule subsetI, simp) subsection "Intransitive purge of event sets with trivial base case" text \<open> Here below are the definitions of variants of functions @{term sinks_aux} and @{term ipurge_ref_aux}, respectively named \<open>sinks_aux_less\<close> and \<open>ipurge_ref_aux_less\<close>, such that their base cases in correspondence with an empty input list are trivial, viz. such that @{term "sinks_aux_less I D U [] = {}"} and @{term "ipurge_ref_aux_less I D U [] X = X"}. These functions will prove to be useful in what follows. \null \<close> function sinks_aux_less :: "('d \<times> 'd) set \<Rightarrow> ('a \<Rightarrow> 'd) \<Rightarrow> 'd set \<Rightarrow> 'a list \<Rightarrow> 'd set" where "sinks_aux_less _ _ _ [] = {}" | "sinks_aux_less I D U (xs @ [x]) = (if \<exists>v \<in> U \<union> sinks_aux_less I D U xs. (v, D x) \<in> I then insert (D x) (sinks_aux_less I D U xs) else sinks_aux_less I D U xs)" proof (atomize_elim, simp_all add: split_paired_all) qed (rule rev_cases, rule disjI1, assumption, simp) termination by lexicographic_order definition ipurge_ref_aux_less :: "('d \<times> 'd) set \<Rightarrow> ('a \<Rightarrow> 'd) \<Rightarrow> 'd set \<Rightarrow> 'a list \<Rightarrow> 'a set \<Rightarrow> 'a set" where "ipurge_ref_aux_less I D U xs X \<equiv> {x \<in> X. \<forall>v \<in> sinks_aux_less I D U xs. (v, D x) \<notin> I}" text \<open> \null Here below is the proof of some properties of function @{term sinks_aux_less} used in what follows. \null \<close> lemma sinks_aux_sinks_aux_less: "sinks_aux I D U xs = U \<union> sinks_aux_less I D U xs" by (induction xs rule: rev_induct, simp_all) lemma sinks_aux_less_single_dom: "sinks_aux_less I D {u} xs = sinks I D u xs" by (induction xs rule: rev_induct, simp_all) lemma sinks_aux_less_single_event: "sinks_aux_less I D U [x] = (if \<exists>u \<in> U. (u, D x) \<in> I then {D x} else {})" by (subst append_Nil [symmetric], simp del: append_Nil) lemma sinks_aux_less_append: "sinks_aux_less I D U (xs @ ys) = sinks_aux_less I D U xs \<union> sinks_aux_less I D (U \<union> sinks_aux_less I D U xs) ys" proof (induction ys rule: rev_induct, simp, subst append_assoc [symmetric]) qed (simp del: append_assoc) lemma sinks_aux_less_cons: "sinks_aux_less I D U (x # xs) = (if \<exists>u \<in> U. (u, D x) \<in> I then insert (D x) (sinks_aux_less I D (insert (D x) U) xs) else sinks_aux_less I D U xs)" proof - have "sinks_aux_less I D U (x # xs) = sinks_aux_less I D U ([x] @ xs)" by simp also have "\<dots> = sinks_aux_less I D U [x] \<union> sinks_aux_less I D (U \<union> sinks_aux_less I D U [x]) xs" by (simp only: sinks_aux_less_append) finally show ?thesis by (cases "\<exists>u \<in> U. (u, D x) \<in> I", simp_all add: sinks_aux_less_single_event) qed text \<open> \null Here below is the proof of some properties of function @{term ipurge_ref_aux_less} used in what follows. \null \<close> lemma ipurge_ref_aux_less_last: "ipurge_ref_aux_less I D U (xs @ [x]) X = (if \<exists>v \<in> U \<union> sinks_aux_less I D U xs. (v, D x) \<in> I then ipurge_ref_aux_less I D U xs {x' \<in> X. (D x, D x') \<notin> I} else ipurge_ref_aux_less I D U xs X)" by (cases "\<exists>v \<in> U \<union> sinks_aux_less I D U xs. (v, D x) \<in> I", simp_all add: ipurge_ref_aux_less_def) lemma ipurge_ref_aux_less_nil: "ipurge_ref_aux_less I D U xs (ipurge_ref_aux I D U [] X) = ipurge_ref_aux I D U xs X" proof (simp add: ipurge_ref_aux_def ipurge_ref_aux_less_def sinks_aux_sinks_aux_less) qed blast lemma ipurge_ref_aux_less_cons_1: assumes A: "\<exists>u \<in> U. (u, D x) \<in> I" shows "ipurge_ref_aux_less I D U (x # xs) X = ipurge_ref_aux_less I D U (ipurge_tr I D (D x) xs) (ipurge_ref I D (D x) xs X)" proof (induction xs arbitrary: X rule: rev_induct, simp add: ipurge_ref_def ipurge_ref_aux_less_def sinks_aux_less_single_event A) fix x' xs X assume B: "\<And>X. ipurge_ref_aux_less I D U (x # xs) X = ipurge_ref_aux_less I D U (ipurge_tr I D (D x) xs) (ipurge_ref I D (D x) xs X)" show "ipurge_ref_aux_less I D U (x # xs @ [x']) X = ipurge_ref_aux_less I D U (ipurge_tr I D (D x) (xs @ [x'])) (ipurge_ref I D (D x) (xs @ [x']) X)" proof (cases "\<exists>v \<in> U \<union> sinks_aux_less I D U (x # xs). (v, D x') \<in> I") assume C: "\<exists>v \<in> U \<union> sinks_aux_less I D U (x # xs). (v, D x') \<in> I" hence "ipurge_ref_aux_less I D U (x # xs @ [x']) X = ipurge_ref_aux_less I D U (x # xs) {y \<in> X. (D x', D y) \<notin> I}" by (subst append_Cons [symmetric], simp add: ipurge_ref_aux_less_last del: append_Cons) also have "\<dots> = ipurge_ref_aux_less I D U (ipurge_tr I D (D x) xs) (ipurge_ref I D (D x) xs {y \<in> X. (D x', D y) \<notin> I})" using B . finally have D: "ipurge_ref_aux_less I D U (x # xs @ [x']) X = ipurge_ref_aux_less I D U (ipurge_tr I D (D x) xs) (ipurge_ref I D (D x) xs {y \<in> X. (D x', D y) \<notin> I})" . show ?thesis proof (cases "(D x, D x') \<in> I \<or> (\<exists>v \<in> sinks I D (D x) xs. (v, D x') \<in> I)") case True hence "ipurge_ref I D (D x) xs {y \<in> X. (D x', D y) \<notin> I} = ipurge_ref I D (D x) (xs @ [x']) X" by (simp add: ipurge_ref_last) moreover have "D x' \<in> sinks I D (D x) (xs @ [x'])" using True by (simp only: sinks_interference_eq) hence "ipurge_tr I D (D x) xs = ipurge_tr I D (D x) (xs @ [x'])" by simp ultimately show ?thesis using D by simp next case False hence "ipurge_ref I D (D x) xs {y \<in> X. (D x', D y) \<notin> I} = ipurge_ref I D (D x) (xs @ [x']) {y \<in> X. (D x', D y) \<notin> I}" by (simp add: ipurge_ref_last) also have "\<dots> = {y \<in> ipurge_ref I D (D x) (xs @ [x']) X. (D x', D y) \<notin> I}" by (simp add: ipurge_ref_swap) finally have "ipurge_ref_aux_less I D U (x # xs @ [x']) X = ipurge_ref_aux_less I D U (ipurge_tr I D (D x) xs) {y \<in> ipurge_ref I D (D x) (xs @ [x']) X. (D x', D y) \<notin> I}" using D by simp also have "\<dots> = ipurge_ref_aux_less I D U (ipurge_tr I D (D x) xs @ [x']) (ipurge_ref I D (D x) (xs @ [x']) X)" proof - have "\<exists>v \<in> U \<union> sinks_aux_less I D U (ipurge_tr I D (D x) xs). (v, D x') \<in> I" proof - obtain v where E: "v \<in> U \<union> sinks_aux_less I D U (x # xs)" and F: "(v, D x') \<in> I" using C .. have "v \<in> sinks_aux I D U (x # xs)" using E by (simp add: sinks_aux_sinks_aux_less) hence "v \<in> sinks_aux I D (insert (D x) U) xs" using A by (simp add: sinks_aux_cons) hence "v \<in> sinks_aux I D U (ipurge_tr I D (D x) xs)" using F and False by (rule sinks_aux_member_ipurge_tr) hence "v \<in> U \<union> sinks_aux_less I D U (ipurge_tr I D (D x) xs)" by (simp add: sinks_aux_sinks_aux_less) with F show ?thesis .. qed thus ?thesis by (simp add: ipurge_ref_aux_less_last) qed finally have "ipurge_ref_aux_less I D U (x # xs @ [x']) X = ipurge_ref_aux_less I D U (ipurge_tr I D (D x) xs @ [x']) (ipurge_ref I D (D x) (xs @ [x']) X)" . moreover have "D x' \<notin> sinks I D (D x) (xs @ [x'])" using False by (simp only: sinks_interference_eq, simp) hence "ipurge_tr I D (D x) xs @ [x'] = ipurge_tr I D (D x) (xs @ [x'])" by simp ultimately show ?thesis by simp qed next assume C: "\<not> (\<exists>v \<in> U \<union> sinks_aux_less I D U (x # xs). (v, D x') \<in> I)" hence "ipurge_ref_aux_less I D U (x # xs @ [x']) X = ipurge_ref_aux_less I D U (x # xs) X" by (subst append_Cons [symmetric], simp add: ipurge_ref_aux_less_last del: append_Cons) also have "\<dots> = ipurge_ref_aux_less I D U (ipurge_tr I D (D x) xs) (ipurge_ref I D (D x) xs X)" using B . also have "\<dots> = ipurge_ref_aux_less I D U (ipurge_tr I D (D x) xs @ [x']) (ipurge_ref I D (D x) xs X)" proof - have "\<not> (\<exists>v \<in> U \<union> sinks_aux_less I D U (ipurge_tr I D (D x) xs). (v, D x') \<in> I)" (is "\<not> ?P") proof assume ?P then obtain v where D: "v \<in> U \<union> sinks_aux_less I D U (ipurge_tr I D (D x) xs)" and E: "(v, D x') \<in> I" .. have "sinks_aux I D U (ipurge_tr I D (D x) xs) \<subseteq> sinks_aux I D U xs" by (rule sinks_aux_subset_ipurge_tr) moreover have "v \<in> sinks_aux I D U (ipurge_tr I D (D x) xs)" using D by (simp add: sinks_aux_sinks_aux_less) ultimately have "v \<in> sinks_aux I D U xs" .. moreover have "U \<subseteq> insert (D x) U" by (rule subset_insertI) hence "sinks_aux I D U xs \<subseteq> sinks_aux I D (insert (D x) U) xs" by (rule sinks_aux_subset_dom) ultimately have "v \<in> sinks_aux I D (insert (D x) U) xs" .. hence "v \<in> sinks_aux I D U (x # xs)" using A by (simp add: sinks_aux_cons) hence "v \<in> U \<union> sinks_aux_less I D U (x # xs)" by (simp add: sinks_aux_sinks_aux_less) with E have "\<exists>v \<in> U \<union> sinks_aux_less I D U (x # xs). (v, D x') \<in> I" .. thus False using C by contradiction qed thus ?thesis by (simp add: ipurge_ref_aux_less_last) qed also have "\<dots> = ipurge_ref_aux_less I D U (ipurge_tr I D (D x) (xs @ [x'])) (ipurge_ref I D (D x) (xs @ [x']) X)" proof - have "\<not> ((D x, D x') \<in> I \<or> (\<exists>v \<in> sinks I D (D x) xs. (v, D x') \<in> I))" (is "\<not> ?P") proof (rule notI, erule disjE) assume D: "(D x, D x') \<in> I" have "insert (D x) U \<subseteq> sinks_aux I D (insert (D x) U) xs" by (rule sinks_aux_subset) moreover have "D x \<in> insert (D x) U" by simp ultimately have "D x \<in> sinks_aux I D (insert (D x) U) xs" .. hence "D x \<in> sinks_aux I D U (x # xs)" using A by (simp add: sinks_aux_cons) hence "D x \<in> U \<union> sinks_aux_less I D U (x # xs)" by (simp add: sinks_aux_sinks_aux_less) with D have "\<exists>v \<in> U \<union> sinks_aux_less I D U (x # xs). (v, D x') \<in> I" .. thus False using C by contradiction next assume "\<exists>v \<in> sinks I D (D x) xs. (v, D x') \<in> I" then obtain v where D: "v \<in> sinks I D (D x) xs" and E: "(v, D x') \<in> I" .. have "{D x} \<subseteq> insert (D x) U" by simp hence "sinks_aux I D {D x} xs \<subseteq> sinks_aux I D (insert (D x) U) xs" by (rule sinks_aux_subset_dom) moreover have "v \<in> sinks_aux I D {D x} xs" using D by (simp add: sinks_aux_single_dom) ultimately have "v \<in> sinks_aux I D (insert (D x) U) xs" .. hence "v \<in> sinks_aux I D U (x # xs)" using A by (simp add: sinks_aux_cons) hence "v \<in> U \<union> sinks_aux_less I D U (x # xs)" by (simp add: sinks_aux_sinks_aux_less) with E have "\<exists>v \<in> U \<union> sinks_aux_less I D U (x # xs). (v, D x') \<in> I" .. thus False using C by contradiction qed hence "ipurge_tr I D (D x) xs @ [x'] = ipurge_tr I D (D x) (xs @ [x'])" by (simp only: sinks_interference_eq, simp) moreover have "ipurge_ref I D (D x) xs X = ipurge_ref I D (D x) (xs @ [x']) X" using \<open>\<not> ?P\<close> by (simp add: ipurge_ref_last) ultimately show ?thesis by simp qed finally show ?thesis . qed qed lemma ipurge_ref_aux_less_cons_2: "\<not> (\<exists>u \<in> U. (u, D x) \<in> I) \<Longrightarrow> ipurge_ref_aux_less I D U (x # xs) X = ipurge_ref_aux_less I D U xs X" by (simp add: ipurge_ref_aux_less_def sinks_aux_less_cons) subsection "Closure of the failures of a secure process under intransitive purge" text \<open> The intransitive purge of an event list @{term xs} with regard to a policy @{term I}, an event-domain map @{term D}, and a set of domains @{term U} can equivalently be computed as follows: for each item @{term x} of @{term xs}, if @{term x} may be affected by some domain in @{term U}, discard @{term x} and go on recursively using @{term "ipurge_tr I D (D x) xs'"} as input, where @{term xs'} is the sublist of @{term xs} following @{term x}; otherwise, retain @{term x} and go on recursively using @{term xs'} as input. In fact, in each recursive step, any item allowed to be indirectly affected by @{term U} through the effect of some item preceding @{term x} within @{term xs} has already been removed from the list. Hence, it is sufficient to check whether @{term x} may be directly affected by @{term U}, and remove @{term x}, as well as any residual item allowed to be affected by @{term x}, if this is the case. Similarly, the intransitive purge of an event set @{term X} with regard to a policy @{term I}, an event-domain map @{term D}, a set of domains @{term U}, and an event list @{term xs} can be computed as follows. First of all, compute @{term "ipurge_ref_aux I D U [] X"} and use this set, along with @{term xs}, as the input for the subsequent step. Then, for each item @{term x} of @{term xs}, if @{term x} may be affected by some domain in @{term U}, go on recursively using @{term "ipurge_tr I D (D x) xs'"} and @{term "ipurge_ref I D (D x) xs' X'"} as input, where @{term X'} is the set input to the current recursive step; otherwise, go on recursively using @{term xs'} and @{term X'} as input. In fact, in each recursive step, any item allowed to be affected by @{term U} either directly, or through the effect of some item preceding @{term x} within @{term xs}, has already been removed from the set (in the initial step and in subsequent steps, respectively). Thus, it is sufficient to check whether @{term x} may be directly affected by @{term U}, and remove any residual item allowed to be affected by @{term x} if this is the case. Assume that the two computations be performed simultaneously by a single function, which will then take as input an event list-event set pair and return as output another such pair. Then, if the input pair is a failure of a secure process, the output pair is still a failure. In fact, for each item @{term x} of @{term xs} allowed to be affected by @{term U}, if @{term ys} is the partial output list for the sublist of @{term xs} preceding @{term x}, then @{term "(ys @ ipurge_tr I D (D x) xs', ipurge_ref I D (D x) xs' X')"} is a failure provided that such is @{term "(ys @ x # xs', X')"}, by virtue of the definition of CSP noninterference security \cite{R2}. Hence, the property of being a failure is conserved upon each recursive call by the event list-event set pair such that the list matches the concatenation of the partial output list with the residual input list, and the set matches the residual input set. This holds until the residual input list is nil, which is the base case determining the end of the computation. As shown by this argument, a proof by induction that the output event list-event set pair, under the aforesaid assumptions, is still a failure, requires that the partial output list be passed to the function as a further argument, in addition to the residual input list, in the recursive calls contained within the definition of the function. Therefore, the output list has to be accumulated into a parameter of the function, viz. the function needs to be tail-recursive. This suggests to prove the properties of interest of the function by applying the ten-step proof method for theorems on tail-recursive functions described in \cite{R1}. The starting point is to formulate a naive definition of the function, which will then be refined as specified by the proof method. A slight complication is due to the preliminary replacement of the input event set @{term X} with @{term "ipurge_ref_aux I D U [] X"}, to be performed before the items of the input event list start to be consumed recursively. A simple solution to this problem is to nest the accumulator of the output list within data type \<open>option\<close>. In this way, the initial state can be distinguished from the subsequent one, in which the input event list starts to be consumed, by assigning the distinct values @{term None} and @{term "Some []"}, respectively, to the accumulator. Everything is now ready for giving a naive definition of the function under consideration: \null \<close> function (sequential) ipurge_fail_aux_t_naive :: "('d \<times> 'd) set \<Rightarrow> ('a \<Rightarrow> 'd) \<Rightarrow> 'd set \<Rightarrow> 'a list \<Rightarrow> 'a list option \<Rightarrow> 'a set \<Rightarrow> 'a failure" where "ipurge_fail_aux_t_naive I D U xs None X = ipurge_fail_aux_t_naive I D U xs (Some []) (ipurge_ref_aux I D U [] X)" | "ipurge_fail_aux_t_naive I D U (x # xs) (Some ys) X = (if \<exists>u \<in> U. (u, D x) \<in> I then ipurge_fail_aux_t_naive I D U (ipurge_tr I D (D x) xs) (Some ys) (ipurge_ref I D (D x) xs X) else ipurge_fail_aux_t_naive I D U xs (Some (ys @ [x])) X)" | "ipurge_fail_aux_t_naive _ _ _ _ (Some ys) X = (ys, X)" oops text \<open> \null The parameter into which the output list is accumulated is the last but one. As shown by the above informal argument, function \<open>ipurge_fail_aux_t_naive\<close> enjoys the following properties: \null @{term "fst (ipurge_fail_aux_t_naive I D U xs None X) = ipurge_tr_aux I D U xs"} \null @{term "snd (ipurge_fail_aux_t_naive I D U xs None X) = ipurge_ref_aux I D U xs X"} \null @{term "\<lbrakk>secure P I D; (xs, X) \<in> failures P\<rbrakk> \<Longrightarrow> ipurge_fail_aux_t_naive I D U xs None X \<in> failures P"} \null which altogether imply the target lemma, viz. the closure of the failures of a secure process under intransitive purge. In what follows, the steps provided for by the aforesaid proof method will be dealt with one after the other, with the purpose of proving the target closure lemma in the final step. For more information on this proof method, cf. \cite{R1}. \<close> subsubsection "Step 1" text \<open> In the definition of the auxiliary tail-recursive function \<open>ipurge_fail_aux_t_aux\<close>, the Cartesian product of the input parameter types of function \<open>ipurge_fail_aux_t_naive\<close> will be implemented as the following record type: \null \<close> record ('a, 'd) ipurge_rec = Pol :: "('d \<times> 'd) set" Map :: "'a \<Rightarrow> 'd" Doms :: "'d set" List :: "'a list" ListOp :: "'a list option" Set :: "'a set" text \<open> \null Here below is the resulting definition of function \<open>ipurge_fail_aux_t_aux\<close>: \null \<close> function ipurge_fail_aux_t_aux :: "('a, 'd) ipurge_rec \<Rightarrow> ('a, 'd) ipurge_rec" where "ipurge_fail_aux_t_aux \<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = None, Set = X\<rparr> = ipurge_fail_aux_t_aux \<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = Some [], Set = ipurge_ref_aux I D U [] X\<rparr>" | "ipurge_fail_aux_t_aux \<lparr>Pol = I, Map = D, Doms = U, List = x # xs, ListOp = Some ys, Set = X\<rparr> = (if \<exists>u \<in> U. (u, D x) \<in> I then ipurge_fail_aux_t_aux \<lparr>Pol = I, Map = D, Doms = U, List = ipurge_tr I D (D x) xs, ListOp = Some ys, Set = ipurge_ref I D (D x) xs X\<rparr> else ipurge_fail_aux_t_aux \<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = Some (ys @ [x]), Set = X\<rparr>)" | "ipurge_fail_aux_t_aux \<lparr>Pol = I, Map = D, Doms = U, List = [], ListOp = Some ys, Set = X\<rparr> = \<lparr>Pol = I, Map = D, Doms = U, List = [], ListOp = Some ys, Set = X\<rparr>" proof (simp_all, atomize_elim) fix Y :: "('a, 'd) ipurge_rec" show "(\<exists>I D U xs X. Y = \<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = None, Set = X\<rparr>) \<or> (\<exists>I D U x xs ys X. Y = \<lparr>Pol = I, Map = D, Doms = U, List = x # xs, ListOp = Some ys, Set = X\<rparr>) \<or> (\<exists>I D U ys X. Y = \<lparr>Pol = I, Map = D, Doms = U, List = [], ListOp = Some ys, Set = X\<rparr>)" proof (cases Y, simp) fix xs :: "'a list" and yso :: "'a list option" show "yso = None \<or> (\<exists>x' xs'. xs = x' # xs') \<and> (\<exists>ys. yso = Some ys) \<or> xs = [] \<and> (\<exists>ys. yso = Some ys)" proof (cases yso, simp_all) qed (subst disj_commute, rule spec [OF list.nchotomy]) qed qed text \<open> \null The length of the input event list of function @{term ipurge_fail_aux_t_aux} decreases in every recursive call except for the first one, where the input list is left unchanged while the nested output list passes from @{term None} to @{term "Some []"}. A measure function decreasing in the first recursive call as well can then be obtained by increasing the length of the input list by one in case the nested output list matches @{term None}. Using such a measure function, the termination of function @{term ipurge_fail_aux_t_aux} is guaranteed by the fact that the event lists output by function @{term ipurge_tr} are not longer than the corresponding input ones. \null \<close> termination ipurge_fail_aux_t_aux proof (relation "measure (\<lambda>Y. (if ListOp Y = None then Suc else id) (length (List Y)))", simp_all) fix D :: "'a \<Rightarrow> 'd" and I x xs have "length (ipurge_tr I D (D x) xs) \<le> length xs" by (rule ipurge_tr_length) thus "length (ipurge_tr I D (D x) xs) < Suc (length xs)" by simp qed subsubsection "Step 2" definition ipurge_fail_aux_t_in :: "('d \<times> 'd) set \<Rightarrow> ('a \<Rightarrow> 'd) \<Rightarrow> 'd set \<Rightarrow> 'a list \<Rightarrow> 'a set \<Rightarrow> ('a, 'd) ipurge_rec" where "ipurge_fail_aux_t_in I D U xs X \<equiv> \<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = None, Set = X\<rparr>" definition ipurge_fail_aux_t_out :: "('a, 'd) ipurge_rec \<Rightarrow> 'a failure" where "ipurge_fail_aux_t_out Y \<equiv> (case ListOp Y of Some ys \<Rightarrow> ys, Set Y)" definition ipurge_fail_aux_t :: "('d \<times> 'd) set \<Rightarrow> ('a \<Rightarrow> 'd) \<Rightarrow> 'd set \<Rightarrow> 'a list \<Rightarrow> 'a set \<Rightarrow> 'a failure" where "ipurge_fail_aux_t I D U xs X \<equiv> ipurge_fail_aux_t_out (ipurge_fail_aux_t_aux (ipurge_fail_aux_t_in I D U xs X))" text \<open> \null Since the significant inputs of function \<open>ipurge_fail_aux_t_naive\<close> match pattern \<open>_, _, _, _, None, _\<close>, those of function @{term ipurge_fail_aux_t_aux}, as returned by function @{term ipurge_fail_aux_t_in}, match pattern \<open>\<lparr>Pol = _, Map = _, Doms = _, List = _, ListOp = None, Set = _\<rparr>\<close>. Likewise, since the nested output lists returned by function @{term ipurge_fail_aux_t_aux} match pattern \<open>Some _\<close>, function @{term ipurge_fail_aux_t_out} does not need to worry about dealing with nested output lists equal to @{term None}. In terms of function @{term ipurge_fail_aux_t}, the statements to be proven in order to demonstrate the target closure lemma, previously expressed using function \<open>ipurge_fail_aux_t_naive\<close> and henceforth respectively named \<open>ipurge_fail_aux_t_eq_tr\<close>, \<open>ipurge_fail_aux_t_eq_ref\<close>, and \<open>ipurge_fail_aux_t_failures\<close>, take the following form: \null @{term "fst (ipurge_fail_aux_t I D U xs X) = ipurge_tr_aux I D U xs"} \null @{term "snd (ipurge_fail_aux_t I D U xs X) = ipurge_ref_aux I D U xs X"} \null @{term "\<lbrakk>secure P I D; (xs, X) \<in> failures P\<rbrakk> \<Longrightarrow> ipurge_fail_aux_t I D U xs X \<in> failures P"} \<close> subsubsection "Step 3" inductive_set ipurge_fail_aux_t_set :: "('a, 'd) ipurge_rec \<Rightarrow> ('a, 'd) ipurge_rec set" for Y :: "('a, 'd) ipurge_rec" where R0: "Y \<in> ipurge_fail_aux_t_set Y" | R1: "\<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = None, Set = X\<rparr> \<in> ipurge_fail_aux_t_set Y \<Longrightarrow> \<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = Some [], Set = ipurge_ref_aux I D U [] X\<rparr> \<in> ipurge_fail_aux_t_set Y" | R2: "\<lbrakk>\<lparr>Pol = I, Map = D, Doms = U, List = x # xs, ListOp = Some ys, Set = X\<rparr> \<in> ipurge_fail_aux_t_set Y; \<exists>u \<in> U. (u, D x) \<in> I\<rbrakk> \<Longrightarrow> \<lparr>Pol = I, Map = D, Doms = U, List = ipurge_tr I D (D x) xs, ListOp = Some ys, Set = ipurge_ref I D (D x) xs X\<rparr> \<in> ipurge_fail_aux_t_set Y" | R3: "\<lbrakk>\<lparr>Pol = I, Map = D, Doms = U, List = x # xs, ListOp = Some ys, Set = X\<rparr> \<in> ipurge_fail_aux_t_set Y; \<not> (\<exists>u \<in> U. (u, D x) \<in> I)\<rbrakk> \<Longrightarrow> \<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = Some (ys @ [x]), Set = X\<rparr> \<in> ipurge_fail_aux_t_set Y" subsubsection "Step 4" lemma ipurge_fail_aux_t_subset: assumes A: "Z \<in> ipurge_fail_aux_t_set Y" shows "ipurge_fail_aux_t_set Z \<subseteq> ipurge_fail_aux_t_set Y" proof (rule subsetI, erule ipurge_fail_aux_t_set.induct) show "Z \<in> ipurge_fail_aux_t_set Y" using A . next fix I D U xs X assume "\<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = None, Set = X\<rparr> \<in> ipurge_fail_aux_t_set Y" thus "\<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = Some [], Set = ipurge_ref_aux I D U [] X\<rparr> \<in> ipurge_fail_aux_t_set Y" by (rule R1) next fix I D U x xs ys X assume "\<lparr>Pol = I, Map = D, Doms = U, List = x # xs, ListOp = Some ys, Set = X\<rparr> \<in> ipurge_fail_aux_t_set Y" and "\<exists>u \<in> U. (u, D x) \<in> I" thus "\<lparr>Pol = I, Map = D, Doms = U, List = ipurge_tr I D (D x) xs, ListOp = Some ys, Set = ipurge_ref I D (D x) xs X\<rparr> \<in> ipurge_fail_aux_t_set Y" by (rule R2) next fix I D U x xs ys X assume "\<lparr>Pol = I, Map = D, Doms = U, List = x # xs, ListOp = Some ys, Set = X\<rparr> \<in> ipurge_fail_aux_t_set Y" and "\<not> (\<exists>u \<in> U. (u, D x) \<in> I)" thus "\<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = Some (ys @ [x]), Set = X\<rparr> \<in> ipurge_fail_aux_t_set Y" by (rule R3) qed lemma ipurge_fail_aux_t_aux_set: "ipurge_fail_aux_t_aux Y \<in> ipurge_fail_aux_t_set Y" proof (induction rule: ipurge_fail_aux_t_aux.induct, simp_all add: R0 del: ipurge_fail_aux_t_aux.simps(2)) fix I U xs X and D :: "'a \<Rightarrow> 'd" let ?Y = "\<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = None, Set = X\<rparr>" and ?Y' = "\<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = Some [], Set = ipurge_ref_aux I D U [] X\<rparr>" have "?Y \<in> ipurge_fail_aux_t_set ?Y" by (rule R0) moreover have "?Y \<in> ipurge_fail_aux_t_set ?Y \<Longrightarrow> ?Y' \<in> ipurge_fail_aux_t_set ?Y" by (rule R1) ultimately have "?Y' \<in> ipurge_fail_aux_t_set ?Y" by simp hence "ipurge_fail_aux_t_set ?Y' \<subseteq> ipurge_fail_aux_t_set ?Y" by (rule ipurge_fail_aux_t_subset) moreover assume "ipurge_fail_aux_t_aux ?Y' \<in> ipurge_fail_aux_t_set ?Y'" ultimately show "ipurge_fail_aux_t_aux ?Y' \<in> ipurge_fail_aux_t_set ?Y" .. next fix I U x xs ys X and D :: "'a \<Rightarrow> 'd" let ?Y = "\<lparr>Pol = I, Map = D, Doms = U, List = x # xs, ListOp = Some ys, Set = X\<rparr>" and ?Y' = "\<lparr>Pol = I, Map = D, Doms = U, List = ipurge_tr I D (D x) xs, ListOp = Some ys, Set = ipurge_ref I D (D x) xs X\<rparr>" and ?Y'' = "\<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = Some (ys @ [x]), Set = X\<rparr>" assume A: "\<exists>u \<in> U. (u, D x) \<in> I \<Longrightarrow> ipurge_fail_aux_t_aux ?Y' \<in> ipurge_fail_aux_t_set ?Y'" and B: "\<forall>u \<in> U. (u, D x) \<notin> I \<Longrightarrow> ipurge_fail_aux_t_aux ?Y'' \<in> ipurge_fail_aux_t_set ?Y''" show "ipurge_fail_aux_t_aux ?Y \<in> ipurge_fail_aux_t_set ?Y" proof (cases "\<exists>u \<in> U. (u, D x) \<in> I", simp_all (no_asm_simp)) case True have "?Y \<in> ipurge_fail_aux_t_set ?Y" by (rule R0) moreover have "?Y \<in> ipurge_fail_aux_t_set ?Y \<Longrightarrow> \<exists>u \<in> U. (u, D x) \<in> I \<Longrightarrow> ?Y' \<in> ipurge_fail_aux_t_set ?Y" by (rule R2) ultimately have "?Y' \<in> ipurge_fail_aux_t_set ?Y" using True by simp hence "ipurge_fail_aux_t_set ?Y' \<subseteq> ipurge_fail_aux_t_set ?Y" by (rule ipurge_fail_aux_t_subset) moreover have "ipurge_fail_aux_t_aux ?Y' \<in> ipurge_fail_aux_t_set ?Y'" using A and True by simp ultimately show "ipurge_fail_aux_t_aux ?Y' \<in> ipurge_fail_aux_t_set ?Y" .. next case False have "?Y \<in> ipurge_fail_aux_t_set ?Y" by (rule R0) moreover have "?Y \<in> ipurge_fail_aux_t_set ?Y \<Longrightarrow> \<not> (\<exists>u \<in> U. (u, D x) \<in> I) \<Longrightarrow> ?Y'' \<in> ipurge_fail_aux_t_set ?Y" by (rule R3) ultimately have "?Y'' \<in> ipurge_fail_aux_t_set ?Y" using False by simp hence "ipurge_fail_aux_t_set ?Y'' \<subseteq> ipurge_fail_aux_t_set ?Y" by (rule ipurge_fail_aux_t_subset) moreover have "ipurge_fail_aux_t_aux ?Y'' \<in> ipurge_fail_aux_t_set ?Y''" using B and False by simp ultimately show "ipurge_fail_aux_t_aux ?Y'' \<in> ipurge_fail_aux_t_set ?Y" .. qed qed subsubsection "Step 5" definition ipurge_fail_aux_t_inv_1 :: "('d \<times> 'd) set \<Rightarrow> ('a \<Rightarrow> 'd) \<Rightarrow> 'd set \<Rightarrow> 'a list \<Rightarrow> ('a, 'd) ipurge_rec \<Rightarrow> bool" where "ipurge_fail_aux_t_inv_1 I D U xs Y \<equiv> (case ListOp Y of None \<Rightarrow> [] | Some ys \<Rightarrow> ys) @ ipurge_tr_aux I D U (List Y) = ipurge_tr_aux I D U xs" definition ipurge_fail_aux_t_inv_2 :: "('d \<times> 'd) set \<Rightarrow> ('a \<Rightarrow> 'd) \<Rightarrow> 'd set \<Rightarrow> 'a list \<Rightarrow> 'a set \<Rightarrow> ('a, 'd) ipurge_rec \<Rightarrow> bool" where "ipurge_fail_aux_t_inv_2 I D U xs X Y \<equiv> if ListOp Y = None then List Y = xs \<and> Set Y = X else ipurge_ref_aux_less I D U (List Y) (Set Y) = ipurge_ref_aux I D U xs X" definition ipurge_fail_aux_t_inv_3 :: "'a process \<Rightarrow> ('d \<times> 'd) set \<Rightarrow> ('a \<Rightarrow> 'd) \<Rightarrow> 'a list \<Rightarrow> 'a set \<Rightarrow> ('a, 'd) ipurge_rec \<Rightarrow> bool" where "ipurge_fail_aux_t_inv_3 P I D xs X Y \<equiv> secure P I D \<longrightarrow> (xs, X) \<in> failures P \<longrightarrow> ((case ListOp Y of None \<Rightarrow> [] | Some ys \<Rightarrow> ys) @ List Y, Set Y) \<in> failures P" text \<open> \null Three invariants have been defined, one for each of lemmas \<open>ipurge_fail_aux_t_eq_tr\<close>, \<open>ipurge_fail_aux_t_eq_ref\<close>, and \<open>ipurge_fail_aux_t_failures\<close>. More precisely, the invariants are @{term "ipurge_fail_aux_t_inv_1 I D U xs"}, @{term "ipurge_fail_aux_t_inv_2 I D U xs X"}, and @{term "ipurge_fail_aux_t_inv_3 P I D xs X"}, where the free variables are intended to match those appearing in the aforesaid lemmas. Particularly: \begin{itemize} \item The first invariant expresses the fact that in each recursive step, any item of the residual input list @{term "List Y"} indirectly affected by @{term U} through the effect of previous, already consumed items has already been removed from the list, so that applying function @{term "ipurge_tr_aux I D U"} to the list is sufficient to obtain the intransitive purge of the whole original list. \item The second invariant expresses the fact that in each recursive step, any item of the residual input set @{term "Set Y"} affected by @{term U} either directly, or through the effect of previous, already consumed items, has already been removed from the set, so that applying function @{term "ipurge_ref_aux_less I D U (List Y)"} to the set is sufficient to obtain the intransitive purge of the whole original set. \\The use of function @{term ipurge_ref_aux_less} ensures that the invariant implies the equality @{term "Set Y = ipurge_ref_aux I D U xs X"} for @{term "List Y = []"}, viz. for the output values of function @{term ipurge_fail_aux_t_aux}, which is the reason requiring the introduction of function @{term ipurge_ref_aux_less}. \item The third invariant expresses the fact that in each recursive step, the event list-event set pair such that the list matches the concatenation of the partial output list with @{term "List Y"}, and the set matches @{term "Set Y"}, is a failure provided that the original input pair is such as well. \end{itemize} \<close> subsubsection "Step 6" lemma ipurge_fail_aux_t_input_1: "ipurge_fail_aux_t_inv_1 I D U xs \<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = None, Set = X\<rparr>" by (simp add: ipurge_fail_aux_t_inv_1_def) lemma ipurge_fail_aux_t_input_2: "ipurge_fail_aux_t_inv_2 I D U xs X \<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = None, Set = X\<rparr>" by (simp add: ipurge_fail_aux_t_inv_2_def) lemma ipurge_fail_aux_t_input_3: "ipurge_fail_aux_t_inv_3 P I D xs X \<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = None, Set = X\<rparr>" by (simp add: ipurge_fail_aux_t_inv_3_def) subsubsection "Step 7" definition ipurge_fail_aux_t_form :: "('a, 'd) ipurge_rec \<Rightarrow> bool" where "ipurge_fail_aux_t_form Y \<equiv> case ListOp Y of None \<Rightarrow> False | Some ys \<Rightarrow> List Y = []" lemma ipurge_fail_aux_t_intro_1: "\<lbrakk>ipurge_fail_aux_t_inv_1 I D U xs Y; ipurge_fail_aux_t_form Y\<rbrakk> \<Longrightarrow> fst (ipurge_fail_aux_t_out Y) = ipurge_tr_aux I D U xs" proof (simp add: ipurge_fail_aux_t_inv_1_def ipurge_fail_aux_t_form_def ipurge_fail_aux_t_out_def) qed (simp split: option.split_asm) lemma ipurge_fail_aux_t_intro_2: "\<lbrakk>ipurge_fail_aux_t_inv_2 I D U xs X Y; ipurge_fail_aux_t_form Y\<rbrakk> \<Longrightarrow> snd (ipurge_fail_aux_t_out Y) = ipurge_ref_aux I D U xs X" proof (simp add: ipurge_fail_aux_t_inv_2_def ipurge_fail_aux_t_form_def ipurge_fail_aux_t_out_def) qed (simp add: ipurge_ref_aux_less_def split: option.split_asm) subsubsection "Step 8" lemma ipurge_fail_aux_t_form_aux: "ipurge_fail_aux_t_form (ipurge_fail_aux_t_aux Y)" by (induction Y rule: ipurge_fail_aux_t_aux.induct, simp_all add: ipurge_fail_aux_t_form_def) subsubsection "Step 9" lemma ipurge_fail_aux_t_invariance_aux: "Z \<in> ipurge_fail_aux_t_set Y \<Longrightarrow> Pol Z = Pol Y \<and> Map Z = Map Y \<and> Doms Z = Doms Y" by (erule ipurge_fail_aux_t_set.induct, simp_all) text \<open> \null The lemma just proven, stating the invariance of the first three record fields over inductive set @{term "ipurge_fail_aux_t_set Y"}, is used in the following proofs of the invariance of predicates @{term "ipurge_fail_aux_t_inv_1 I D U xs"}, @{term "ipurge_fail_aux_t_inv_2 I D U xs X"}, and @{term "ipurge_fail_aux_t_inv_3 P I D xs X"}. The equality between the free variables appearing in the predicates and the corresponding fields of the record generating the set, which is required for such invariance properties to hold, is asserted in the enunciation of the properties by means of record updates. In the subsequent proofs of lemmas \<open>ipurge_fail_aux_t_eq_tr\<close>, \<open>ipurge_fail_aux_t_eq_ref\<close>, and \<open>ipurge_fail_aux_t_failures\<close>, the enforcement of this equality will be ensured by the identification of both predicate variables and record fields with the related free variables appearing in the lemmas. \null \<close> lemma ipurge_fail_aux_t_invariance_1: "\<lbrakk>Z \<in> ipurge_fail_aux_t_set (Y\<lparr>Pol := I, Map := D, Doms := U\<rparr>); ipurge_fail_aux_t_inv_1 I D U xs (Y\<lparr>Pol := I, Map := D, Doms := U\<rparr>)\<rbrakk> \<Longrightarrow> ipurge_fail_aux_t_inv_1 I D U xs Z" proof (erule ipurge_fail_aux_t_set.induct, assumption, drule_tac [!] ipurge_fail_aux_t_invariance_aux, simp_all add: ipurge_fail_aux_t_inv_1_def) fix x xs' ys assume "ys @ ipurge_tr_aux I D U (x # xs') = ipurge_tr_aux I D U xs" (is "?A = ?C") moreover assume "\<exists>u \<in> U. (u, D x) \<in> I" hence "?A = ys @ ipurge_tr_aux I D (insert (D x) U) xs'" by (simp add: ipurge_tr_aux_cons) hence "?A = ys @ ipurge_tr_aux I D U (ipurge_tr I D (D x) xs')" (is "_ = ?B") by (simp add: ipurge_tr_aux_insert) ultimately show "?B = ?C" by simp next fix x xs' ys assume "ys @ ipurge_tr_aux I D U (x # xs') = ipurge_tr_aux I D U xs" (is "?A = ?C") moreover assume "\<forall>u \<in> U. (u, D x) \<notin> I" hence "?A = ys @ x # ipurge_tr_aux I D U xs'" (is "_ = ?B") by (simp add: ipurge_tr_aux_cons) ultimately show "?B = ?C" by simp qed lemma ipurge_fail_aux_t_invariance_2: "\<lbrakk>Z \<in> ipurge_fail_aux_t_set (Y\<lparr>Pol := I, Map := D, Doms := U\<rparr>); ipurge_fail_aux_t_inv_2 I D U xs X (Y\<lparr>Pol := I, Map := D, Doms := U\<rparr>)\<rbrakk> \<Longrightarrow> ipurge_fail_aux_t_inv_2 I D U xs X Z" proof (erule ipurge_fail_aux_t_set.induct, assumption, drule_tac [!] ipurge_fail_aux_t_invariance_aux, simp_all add: ipurge_fail_aux_t_inv_2_def) show "ipurge_ref_aux_less I D U xs (ipurge_ref_aux I D U [] X) = ipurge_ref_aux I D U xs X" by (rule ipurge_ref_aux_less_nil) next fix x xs' X' assume "ipurge_ref_aux_less I D U (x # xs') X' = ipurge_ref_aux I D U xs X" (is "?A = ?C") moreover assume "\<exists>u \<in> U. (u, D x) \<in> I" hence "?A = ipurge_ref_aux_less I D U (ipurge_tr I D (D x) xs') (ipurge_ref I D (D x) xs' X')" (is "_ = ?B") by (rule ipurge_ref_aux_less_cons_1) ultimately show "?B = ?C" by simp next fix x xs' X' assume "ipurge_ref_aux_less I D U (x # xs') X' = ipurge_ref_aux I D U xs X" (is "?A = ?C") moreover assume "\<forall>u \<in> U. (u, D x) \<notin> I" hence "\<not> (\<exists>u \<in> U. (u, D x) \<in> I)" by simp hence "?A = ipurge_ref_aux_less I D U xs' X'" (is "_ = ?B") by (rule ipurge_ref_aux_less_cons_2) ultimately show "?B = ?C" by simp qed lemma ipurge_fail_aux_t_invariance_3: "\<lbrakk>Z \<in> ipurge_fail_aux_t_set (Y\<lparr>Pol := I, Map := D\<rparr>); ipurge_fail_aux_t_inv_3 P I D xs X (Y\<lparr>Pol := I, Map := D\<rparr>)\<rbrakk> \<Longrightarrow> ipurge_fail_aux_t_inv_3 P I D xs X Z" proof (erule ipurge_fail_aux_t_set.induct, assumption, drule_tac [!] ipurge_fail_aux_t_invariance_aux, simp_all add: ipurge_fail_aux_t_inv_3_def, (rule_tac [!] impI)+) fix xs' X' assume "secure P I D" and "(xs, X) \<in> failures P" and "secure P I D \<longrightarrow> (xs, X) \<in> failures P \<longrightarrow> (xs', X') \<in> failures P" hence "(xs', X') \<in> failures P" by simp moreover have "ipurge_ref_aux I D (Doms Y) [] X' \<subseteq> X'" by (rule ipurge_ref_aux_subset) ultimately show "(xs', ipurge_ref_aux I D (Doms Y) [] X') \<in> failures P" by (rule process_rule_3) next fix x xs' ys X' assume S: "secure P I D" and "(xs, X) \<in> failures P" and "secure P I D \<longrightarrow> (xs, X) \<in> failures P \<longrightarrow> (ys @ x # xs', X') \<in> failures P" hence "(ys @ x # xs', X') \<in> failures P" by simp hence "(x # xs', X') \<in> futures P ys" by (simp add: futures_def) hence "(ipurge_tr I D (D x) xs', ipurge_ref I D (D x) xs' X') \<in> futures P ys" using S by (simp add: secure_def) thus "(ys @ ipurge_tr I D (D x) xs', ipurge_ref I D (D x) xs' X') \<in> failures P" by (simp add: futures_def) qed subsubsection "Step 10" text \<open> Here below are the proofs of lemmas \<open>ipurge_fail_aux_t_eq_tr\<close>, \<open>ipurge_fail_aux_t_eq_ref\<close>, and \<open>ipurge_fail_aux_t_failures\<close>, which are then applied to demonstrate the target closure lemma. \null \<close> lemma ipurge_fail_aux_t_eq_tr: "fst (ipurge_fail_aux_t I D U xs X) = ipurge_tr_aux I D U xs" proof - let ?Y = "\<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = None, Set = X\<rparr>" have "ipurge_fail_aux_t_aux ?Y \<in> ipurge_fail_aux_t_set (?Y\<lparr>Pol := I, Map := D, Doms := U\<rparr>)" by (simp add: ipurge_fail_aux_t_aux_set del: ipurge_fail_aux_t_aux.simps) moreover have "ipurge_fail_aux_t_inv_1 I D U xs (?Y\<lparr>Pol := I, Map := D, Doms := U\<rparr>)" by (simp add: ipurge_fail_aux_t_input_1) ultimately have "ipurge_fail_aux_t_inv_1 I D U xs (ipurge_fail_aux_t_aux ?Y)" by (rule ipurge_fail_aux_t_invariance_1) moreover have "ipurge_fail_aux_t_form (ipurge_fail_aux_t_aux ?Y)" by (rule ipurge_fail_aux_t_form_aux) ultimately have "fst (ipurge_fail_aux_t_out (ipurge_fail_aux_t_aux ?Y)) = ipurge_tr_aux I D U xs" by (rule ipurge_fail_aux_t_intro_1) moreover have "?Y = ipurge_fail_aux_t_in I D U xs X" by (simp add: ipurge_fail_aux_t_in_def) ultimately show ?thesis by (simp add: ipurge_fail_aux_t_def) qed lemma ipurge_fail_aux_t_eq_ref: "snd (ipurge_fail_aux_t I D U xs X) = ipurge_ref_aux I D U xs X" proof - let ?Y = "\<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = None, Set = X\<rparr>" have "ipurge_fail_aux_t_aux ?Y \<in> ipurge_fail_aux_t_set (?Y\<lparr>Pol := I, Map := D, Doms := U\<rparr>)" by (simp add: ipurge_fail_aux_t_aux_set del: ipurge_fail_aux_t_aux.simps) moreover have "ipurge_fail_aux_t_inv_2 I D U xs X (?Y\<lparr>Pol := I, Map := D, Doms := U\<rparr>)" by (simp add: ipurge_fail_aux_t_input_2) ultimately have "ipurge_fail_aux_t_inv_2 I D U xs X (ipurge_fail_aux_t_aux ?Y)" by (rule ipurge_fail_aux_t_invariance_2) moreover have "ipurge_fail_aux_t_form (ipurge_fail_aux_t_aux ?Y)" by (rule ipurge_fail_aux_t_form_aux) ultimately have "snd (ipurge_fail_aux_t_out (ipurge_fail_aux_t_aux ?Y)) = ipurge_ref_aux I D U xs X" by (rule ipurge_fail_aux_t_intro_2) moreover have "?Y = ipurge_fail_aux_t_in I D U xs X" by (simp add: ipurge_fail_aux_t_in_def) ultimately show ?thesis by (simp add: ipurge_fail_aux_t_def) qed lemma ipurge_fail_aux_t_failures [rule_format]: "secure P I D \<longrightarrow> (xs, X) \<in> failures P \<longrightarrow> ipurge_fail_aux_t I D U xs X \<in> failures P" proof - let ?Y = "\<lparr>Pol = I, Map = D, Doms = U, List = xs, ListOp = None, Set = X\<rparr>" have "ipurge_fail_aux_t_aux ?Y \<in> ipurge_fail_aux_t_set (?Y\<lparr>Pol := I, Map := D\<rparr>)" by (simp add: ipurge_fail_aux_t_aux_set del: ipurge_fail_aux_t_aux.simps) moreover have "ipurge_fail_aux_t_inv_3 P I D xs X (?Y\<lparr>Pol := I, Map := D\<rparr>)" by (simp add: ipurge_fail_aux_t_input_3) ultimately have "ipurge_fail_aux_t_inv_3 P I D xs X (ipurge_fail_aux_t_aux ?Y)" by (rule ipurge_fail_aux_t_invariance_3) moreover have "ipurge_fail_aux_t_form (ipurge_fail_aux_t_aux ?Y)" by (rule ipurge_fail_aux_t_form_aux) ultimately have "secure P I D \<longrightarrow> (xs, X) \<in> failures P \<longrightarrow> ipurge_fail_aux_t_out (ipurge_fail_aux_t_aux ?Y) \<in> failures P" by (rule ipurge_fail_aux_t_intro_3) moreover have "?Y = ipurge_fail_aux_t_in I D U xs X" by (simp add: ipurge_fail_aux_t_in_def) ultimately show ?thesis by (simp add: ipurge_fail_aux_t_def) qed lemma ipurge_tr_ref_aux_failures: "\<lbrakk>secure P I D; (xs, X) \<in> failures P\<rbrakk> \<Longrightarrow> (ipurge_tr_aux I D U xs, ipurge_ref_aux I D U xs X) \<in> failures P" proof (drule ipurge_fail_aux_t_failures [where U = U], assumption, cases "ipurge_fail_aux_t I D U xs X") qed (simp add: ipurge_fail_aux_t_eq_tr [where X = X, symmetric] ipurge_fail_aux_t_eq_ref [symmetric]) subsection "Additional propaedeutic lemmas" text \<open> In what follows, additional lemmas required for the demonstration of the target security conservation theorem are proven. Here below is the proof of some properties of functions @{term ipurge_tr_aux} and @{term ipurge_ref_aux}. Particularly, it is shown that in case an event list and its intransitive purge for some set of domains are both traces of a secure process, and the purged list has a future not affected by any purged event, then that future is also a future for the full event list. \null \<close> lemma ipurge_tr_aux_idem: "ipurge_tr_aux I D U (ipurge_tr_aux I D U xs) = ipurge_tr_aux I D U xs" by (simp add: ipurge_tr_aux_union [symmetric]) lemma ipurge_tr_aux_set: "set (ipurge_tr_aux I D U xs) \<subseteq> set xs" proof (induction xs rule: rev_induct, simp_all) qed blast lemma ipurge_tr_aux_nil [rule_format]: assumes A: "u \<in> U" shows "(\<forall>x \<in> set xs. (u, D x) \<in> I) \<longrightarrow> ipurge_tr_aux I D U xs = []" proof (induction xs rule: rev_induct, simp, rule impI) fix x xs assume "(\<forall>x' \<in> set xs. (u, D x') \<in> I) \<longrightarrow> ipurge_tr_aux I D U xs = []" moreover assume B: "\<forall>x' \<in> set (xs @ [x]). (u, D x') \<in> I" ultimately have C: "ipurge_tr_aux I D U xs = []" by simp have "(u, D x) \<in> I" using B by simp moreover have "U \<subseteq> sinks_aux I D U xs" by (rule sinks_aux_subset) hence "u \<in> sinks_aux I D U xs" using A .. ultimately have "\<exists>u \<in> sinks_aux I D U xs. (u, D x) \<in> I" .. hence "ipurge_tr_aux I D U (xs @ [x]) = ipurge_tr_aux I D U xs" by simp thus "ipurge_tr_aux I D U (xs @ [x]) = []" using C by simp qed lemma ipurge_tr_aux_del_failures [rule_format]: assumes S: "secure P I D" shows "(\<forall>u \<in> sinks_aux_less I D U ys. \<forall>z \<in> Z \<union> set zs. (u, D z) \<notin> I) \<longrightarrow> (xs @ ipurge_tr_aux I D U ys @ zs, Z) \<in> failures P \<longrightarrow> xs @ ys \<in> traces P \<longrightarrow> (xs @ ys @ zs, Z) \<in> failures P" proof (induction ys arbitrary: zs rule: rev_induct, simp, (rule impI)+) fix y ys zs assume A: "\<And>zs. (\<forall>u \<in> sinks_aux_less I D U ys. \<forall>z \<in> Z \<union> set zs. (u, D z) \<notin> I) \<longrightarrow> (xs @ ipurge_tr_aux I D U ys @ zs, Z) \<in> failures P \<longrightarrow> xs @ ys \<in> traces P \<longrightarrow> (xs @ ys @ zs, Z) \<in> failures P" and B: "\<forall>u \<in> sinks_aux_less I D U (ys @ [y]). \<forall>z \<in> Z \<union> set zs. (u, D z) \<notin> I" and C: "(xs @ ipurge_tr_aux I D U (ys @ [y]) @ zs, Z) \<in> failures P" and D: "xs @ (ys @ [y]) \<in> traces P" show "(xs @ (ys @ [y]) @ zs, Z) \<in> failures P" proof (cases "\<exists>u \<in> sinks_aux I D U ys. (u, D y) \<in> I", simp_all (no_asm)) case True have "(\<forall>u \<in> sinks_aux_less I D U ys. \<forall>z \<in> Z \<union> set zs. (u, D z) \<notin> I) \<longrightarrow> (xs @ ipurge_tr_aux I D U ys @ zs, Z) \<in> failures P \<longrightarrow> xs @ ys \<in> traces P \<longrightarrow> (xs @ ys @ zs, Z) \<in> failures P" using A . moreover have "\<exists>u \<in> U \<union> sinks_aux_less I D U ys. (u, D y) \<in> I" using True by (simp add: sinks_aux_sinks_aux_less) hence E: "\<forall>u \<in> insert (D y) (sinks_aux_less I D U ys). \<forall>z \<in> Z \<union> set zs. (u, D z) \<notin> I" using B by (simp only: sinks_aux_less.simps if_True) hence "\<forall>u \<in> sinks_aux_less I D U ys. \<forall>z \<in> Z \<union> set zs. (u, D z) \<notin> I" by simp moreover have "(xs @ ipurge_tr_aux I D U ys @ zs, Z) \<in> failures P" using C and True by simp moreover have "(xs @ ys) @ [y] \<in> traces P" using D by simp hence "xs @ ys \<in> traces P" by (rule process_rule_2_traces) ultimately have "(xs @ ys @ zs, Z) \<in> failures P" by simp hence "(zs, Z) \<in> futures P (xs @ ys)" by (simp add: futures_def) moreover have "(xs @ ys @ [y], {}) \<in> failures P" using D by (rule traces_failures) hence "([y], {}) \<in> futures P (xs @ ys)" by (simp add: futures_def) ultimately have "(y # ipurge_tr I D (D y) zs, ipurge_ref I D (D y) zs Z) \<in> futures P (xs @ ys)" using S by (simp add: secure_def) moreover have "ipurge_tr I D (D y) zs = zs" by (subst ipurge_tr_all, simp add: E) moreover have "ipurge_ref I D (D y) zs Z = Z" by (rule ipurge_ref_all, simp add: E) ultimately have "(y # zs, Z) \<in> futures P (xs @ ys)" by simp thus "(xs @ ys @ y # zs, Z) \<in> failures P" by (simp add: futures_def) next case False have E: "(\<forall>u \<in> sinks_aux_less I D U ys. \<forall>z \<in> Z \<union> set (y # zs). (u, D z) \<notin> I) \<longrightarrow> (xs @ ipurge_tr_aux I D U ys @ (y # zs), Z) \<in> failures P \<longrightarrow> xs @ ys \<in> traces P \<longrightarrow> (xs @ ys @ (y # zs), Z) \<in> failures P" using A . have F: "\<not> (\<exists>u \<in> U \<union> sinks_aux_less I D U ys. (u, D y) \<in> I)" using False by (simp add: sinks_aux_sinks_aux_less) hence "\<forall>u \<in> sinks_aux_less I D U ys. \<forall>z \<in> Z \<union> set zs. (u, D z) \<notin> I" using B by (simp only: sinks_aux_less.simps if_False) moreover have "\<forall>u \<in> sinks_aux_less I D U ys. (u, D y) \<notin> I" using F by simp ultimately have "\<forall>u \<in> sinks_aux_less I D U ys. \<forall>z \<in> Z \<union> set (y # zs). (u, D z) \<notin> I" by simp with E have "(xs @ ipurge_tr_aux I D U ys @ (y # zs), Z) \<in> failures P \<longrightarrow> xs @ ys \<in> traces P \<longrightarrow> (xs @ ys @ (y # zs), Z) \<in> failures P" .. moreover have "(xs @ ipurge_tr_aux I D U ys @ (y # zs), Z) \<in> failures P" using C and False by simp moreover have "(xs @ ys) @ [y] \<in> traces P" using D by simp hence "xs @ ys \<in> traces P" by (rule process_rule_2_traces) ultimately show "(xs @ ys @ (y # zs), Z) \<in> failures P" by simp qed qed lemma ipurge_ref_aux_append: "ipurge_ref_aux I D U (xs @ ys) X = ipurge_ref_aux I D (sinks_aux I D U xs) ys X" by (simp add: ipurge_ref_aux_def sinks_aux_append) lemma ipurge_ref_aux_empty [rule_format]: assumes A: "u \<in> sinks_aux I D U xs" and B: "\<forall>x \<in> X. (u, D x) \<in> I" shows "ipurge_ref_aux I D U xs X = {}" proof (rule equals0I, simp add: ipurge_ref_aux_def, erule conjE) fix x assume "x \<in> X" with B have "(u, D x) \<in> I" .. moreover assume "\<forall>u \<in> sinks_aux I D U xs. (u, D x) \<notin> I" hence "(u, D x) \<notin> I" using A .. ultimately show False by contradiction qed text \<open> \null Here below is the proof of some properties of functions @{term sinks}, @{term ipurge_tr}, and @{term ipurge_ref}. Particularly, using the previous analogous result on function @{term ipurge_tr_aux}, it is shown that in case an event list and its intransitive purge for some domain are both traces of a secure process, and the purged list has a future not affected by any purged event, then that future is also a future for the full event list. \null \<close> lemma sinks_idem: "sinks I D u (ipurge_tr I D u xs) = {}" by (induction xs rule: rev_induct, simp_all) lemma sinks_elem [rule_format]: "v \<in> sinks I D u xs \<longrightarrow> (\<exists>x \<in> set xs. v = D x)" by (induction xs rule: rev_induct, simp_all) lemma ipurge_tr_append: "ipurge_tr I D u (xs @ ys) = ipurge_tr I D u xs @ ipurge_tr_aux I D (insert u (sinks I D u xs)) ys" proof (simp add: sinks_aux_single_dom [symmetric] ipurge_tr_aux_single_dom [symmetric]) qed (simp add: ipurge_tr_aux_append) lemma ipurge_tr_idem: "ipurge_tr I D u (ipurge_tr I D u xs) = ipurge_tr I D u xs" by (simp add: ipurge_tr_aux_single_dom [symmetric] ipurge_tr_aux_idem) lemma ipurge_tr_set: "set (ipurge_tr I D u xs) \<subseteq> set xs" by (simp add: ipurge_tr_aux_single_dom [symmetric] ipurge_tr_aux_set) lemma ipurge_tr_del_failures [rule_format]: assumes S: "secure P I D" and A: "\<forall>v \<in> sinks I D u ys. \<forall>z \<in> Z \<union> set zs. (v, D z) \<notin> I" and B: "(xs @ ipurge_tr I D u ys @ zs, Z) \<in> failures P" and C: "xs @ ys \<in> traces P" shows "(xs @ ys @ zs, Z) \<in> failures P" proof (rule ipurge_tr_aux_del_failures [OF S _ _ C, where U = "{u}"]) qed (simp add: A sinks_aux_less_single_dom, simp add: B ipurge_tr_aux_single_dom) lemma ipurge_ref_append: "ipurge_ref I D u (xs @ ys) X = ipurge_ref_aux I D (insert u (sinks I D u xs)) ys X" proof (simp add: sinks_aux_single_dom [symmetric] ipurge_ref_aux_single_dom [symmetric]) qed (simp add: ipurge_ref_aux_append) lemma ipurge_ref_distrib_inter: "ipurge_ref I D u xs (X \<inter> Y) = ipurge_ref I D u xs X \<inter> ipurge_ref I D u xs Y" proof (simp add: ipurge_ref_def) qed blast lemma ipurge_ref_distrib_union: "ipurge_ref I D u xs (X \<union> Y) = ipurge_ref I D u xs X \<union> ipurge_ref I D u xs Y" proof (simp add: ipurge_ref_def) qed blast lemma ipurge_ref_subset: "ipurge_ref I D u xs X \<subseteq> X" by (subst ipurge_ref_def, rule subsetI, simp) lemma ipurge_ref_subset_union: "ipurge_ref I D u xs (X \<union> Y) \<subseteq> X \<union> ipurge_ref I D u xs Y" proof (simp add: ipurge_ref_def) qed blast lemma ipurge_ref_subset_insert: "ipurge_ref I D u xs (insert x X) \<subseteq> insert x (ipurge_ref I D u xs X)" by (simp only: insert_def ipurge_ref_subset_union) lemma ipurge_ref_empty [rule_format]: assumes A: "v = u \<or> v \<in> sinks I D u xs" and B: "\<forall>x \<in> X. (v, D x) \<in> I" shows "ipurge_ref I D u xs X = {}" proof (subst ipurge_ref_aux_single_dom [symmetric], rule ipurge_ref_aux_empty [of v]) show "v \<in> sinks_aux I D {u} xs" using A by (simp add: sinks_aux_single_dom) next fix x assume "x \<in> X" with B show "(v, D x) \<in> I" .. qed text \<open> \null Finally, in what follows, properties @{term process_prop_1}, @{term process_prop_5}, and @{term process_prop_6} of processes (cf. \cite{R2}) are put into the form of introduction rules. \null \<close> lemma process_rule_1: "([], {}) \<in> failures P" proof (simp add: failures_def) have "Rep_process P \<in> process_set" (is "?P' \<in> _") by (rule Rep_process) thus "([], {}) \<in> fst ?P'" by (simp add: process_set_def process_prop_1_def) qed lemma process_rule_5 [rule_format]: "xs \<in> divergences P \<longrightarrow> xs @ [x] \<in> divergences P" proof (simp add: divergences_def) have "Rep_process P \<in> process_set" (is "?P' \<in> _") by (rule Rep_process) hence "\<forall>xs x. xs \<in> snd ?P' \<longrightarrow> xs @ [x] \<in> snd ?P'" by (simp add: process_set_def process_prop_5_def) thus "xs \<in> snd ?P' \<longrightarrow> xs @ [x] \<in> snd ?P'" by blast qed lemma process_rule_6 [rule_format]: "xs \<in> divergences P \<longrightarrow> (xs, X) \<in> failures P" proof (simp add: failures_def divergences_def) have "Rep_process P \<in> process_set" (is "?P' \<in> _") by (rule Rep_process) hence "\<forall>xs X. xs \<in> snd ?P' \<longrightarrow> (xs, X) \<in> fst ?P'" by (simp add: process_set_def process_prop_6_def) thus "xs \<in> snd ?P' \<longrightarrow> (xs, X) \<in> fst ?P'" by blast qed end
Andrea Negroni ( July 18 , 1763 ) – Cardinal @-@ Deacon of SS . Vito e Modesto ; secretary of the Apostolic Briefs
[STATEMENT] theorem fr_eq: assumes lp: "isrlfm p" shows "(\<exists>x. Ifm (x#bs) p) \<longleftrightarrow> Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t,n) \<in> set (uset p). \<exists>(s,m) \<in> set (uset p). Ifm ((((Inum (x # bs) t) / real_of_int n + (Inum (x # bs) s) / real_of_int m) / 2) # bs) p)" (is "(\<exists>x. ?I x p) \<longleftrightarrow> (?M \<or> ?P \<or> ?F)" is "?E = ?D") [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<exists>x. Ifm (x # bs) p) = (Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p)) [PROOF STEP] proof [PROOF STATE] proof (state) goal (2 subgoals): 1. \<exists>x. Ifm (x # bs) p \<Longrightarrow> Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) 2. Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) \<Longrightarrow> \<exists>x. Ifm (x # bs) p [PROOF STEP] assume px: "\<exists>x. ?I x p" [PROOF STATE] proof (state) this: \<exists>x. Ifm (x # bs) p goal (2 subgoals): 1. \<exists>x. Ifm (x # bs) p \<Longrightarrow> Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) 2. Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) \<Longrightarrow> \<exists>x. Ifm (x # bs) p [PROOF STEP] consider "?M \<or> ?P" | "\<not> ?M" "\<not> ?P" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<Longrightarrow> thesis; \<lbrakk>\<not> Ifm (x # bs) (minusinf p); \<not> Ifm (x # bs) (plusinf p)\<rbrakk> \<Longrightarrow> thesis\<rbrakk> \<Longrightarrow> thesis [PROOF STEP] by blast [PROOF STATE] proof (state) this: \<lbrakk>Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<Longrightarrow> ?thesis; \<lbrakk>\<not> Ifm (x # bs) (minusinf p); \<not> Ifm (x # bs) (plusinf p)\<rbrakk> \<Longrightarrow> ?thesis\<rbrakk> \<Longrightarrow> ?thesis goal (2 subgoals): 1. \<exists>x. Ifm (x # bs) p \<Longrightarrow> Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) 2. Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) \<Longrightarrow> \<exists>x. Ifm (x # bs) p [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<lbrakk>Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<Longrightarrow> ?thesis; \<lbrakk>\<not> Ifm (x # bs) (minusinf p); \<not> Ifm (x # bs) (plusinf p)\<rbrakk> \<Longrightarrow> ?thesis\<rbrakk> \<Longrightarrow> ?thesis [PROOF STEP] show ?D [PROOF STATE] proof (prove) using this: \<lbrakk>Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<Longrightarrow> ?thesis; \<lbrakk>\<not> Ifm (x # bs) (minusinf p); \<not> Ifm (x # bs) (plusinf p)\<rbrakk> \<Longrightarrow> ?thesis\<rbrakk> \<Longrightarrow> ?thesis goal (1 subgoal): 1. Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) [PROOF STEP] proof cases [PROOF STATE] proof (state) goal (2 subgoals): 1. Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<Longrightarrow> Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) 2. \<lbrakk>\<not> Ifm (x # bs) (minusinf p); \<not> Ifm (x # bs) (plusinf p)\<rbrakk> \<Longrightarrow> Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) [PROOF STEP] case 1 [PROOF STATE] proof (state) this: Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) goal (2 subgoals): 1. Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<Longrightarrow> Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) 2. \<lbrakk>\<not> Ifm (x # bs) (minusinf p); \<not> Ifm (x # bs) (plusinf p)\<rbrakk> \<Longrightarrow> Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) goal (1 subgoal): 1. Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) [PROOF STEP] by blast [PROOF STATE] proof (state) this: Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) goal (1 subgoal): 1. \<lbrakk>\<not> Ifm (x # bs) (minusinf p); \<not> Ifm (x # bs) (plusinf p)\<rbrakk> \<Longrightarrow> Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<lbrakk>\<not> Ifm (x # bs) (minusinf p); \<not> Ifm (x # bs) (plusinf p)\<rbrakk> \<Longrightarrow> Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) [PROOF STEP] case 2 [PROOF STATE] proof (state) this: \<not> Ifm (x # bs) (minusinf p) \<not> Ifm (x # bs) (plusinf p) goal (1 subgoal): 1. \<lbrakk>\<not> Ifm (x # bs) (minusinf p); \<not> Ifm (x # bs) (plusinf p)\<rbrakk> \<Longrightarrow> Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) [PROOF STEP] from rinf_uset[OF lp this] [PROOF STATE] proof (chain) picking this: \<exists>x. Ifm (x # bs) p \<Longrightarrow> \<exists>(l, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) l / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p [PROOF STEP] have ?F [PROOF STATE] proof (prove) using this: \<exists>x. Ifm (x # bs) p \<Longrightarrow> \<exists>(l, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) l / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p goal (1 subgoal): 1. \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p [PROOF STEP] using px [PROOF STATE] proof (prove) using this: \<exists>x. Ifm (x # bs) p \<Longrightarrow> \<exists>(l, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) l / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p \<exists>x. Ifm (x # bs) p goal (1 subgoal): 1. \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p [PROOF STEP] by blast [PROOF STATE] proof (state) this: \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p goal (1 subgoal): 1. \<lbrakk>\<not> Ifm (x # bs) (minusinf p); \<not> Ifm (x # bs) (plusinf p)\<rbrakk> \<Longrightarrow> Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p goal (1 subgoal): 1. Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) [PROOF STEP] by blast [PROOF STATE] proof (state) this: Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) goal (1 subgoal): 1. Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) \<Longrightarrow> \<exists>x. Ifm (x # bs) p [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) \<Longrightarrow> \<exists>x. Ifm (x # bs) p [PROOF STEP] assume ?D [PROOF STATE] proof (state) this: Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) goal (1 subgoal): 1. Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) \<Longrightarrow> \<exists>x. Ifm (x # bs) p [PROOF STEP] then [PROOF STATE] proof (chain) picking this: Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) [PROOF STEP] consider ?M | ?P | ?F [PROOF STATE] proof (prove) using this: Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) goal (1 subgoal): 1. \<lbrakk>Ifm (x # bs) (minusinf p) \<Longrightarrow> thesis; Ifm (x # bs) (plusinf p) \<Longrightarrow> thesis; \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p \<Longrightarrow> thesis\<rbrakk> \<Longrightarrow> thesis [PROOF STEP] by blast [PROOF STATE] proof (state) this: \<lbrakk>Ifm (x # bs) (minusinf p) \<Longrightarrow> ?thesis; Ifm (x # bs) (plusinf p) \<Longrightarrow> ?thesis; \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p \<Longrightarrow> ?thesis\<rbrakk> \<Longrightarrow> ?thesis goal (1 subgoal): 1. Ifm (x # bs) (minusinf p) \<or> Ifm (x # bs) (plusinf p) \<or> (\<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p) \<Longrightarrow> \<exists>x. Ifm (x # bs) p [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<lbrakk>Ifm (x # bs) (minusinf p) \<Longrightarrow> ?thesis; Ifm (x # bs) (plusinf p) \<Longrightarrow> ?thesis; \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p \<Longrightarrow> ?thesis\<rbrakk> \<Longrightarrow> ?thesis [PROOF STEP] show ?E [PROOF STATE] proof (prove) using this: \<lbrakk>Ifm (x # bs) (minusinf p) \<Longrightarrow> ?thesis; Ifm (x # bs) (plusinf p) \<Longrightarrow> ?thesis; \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p \<Longrightarrow> ?thesis\<rbrakk> \<Longrightarrow> ?thesis goal (1 subgoal): 1. \<exists>x. Ifm (x # bs) p [PROOF STEP] proof cases [PROOF STATE] proof (state) goal (3 subgoals): 1. Ifm (x # bs) (minusinf p) \<Longrightarrow> \<exists>x. Ifm (x # bs) p 2. Ifm (x # bs) (plusinf p) \<Longrightarrow> \<exists>x. Ifm (x # bs) p 3. \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p \<Longrightarrow> \<exists>x. Ifm (x # bs) p [PROOF STEP] case 1 [PROOF STATE] proof (state) this: Ifm (x # bs) (minusinf p) goal (3 subgoals): 1. Ifm (x # bs) (minusinf p) \<Longrightarrow> \<exists>x. Ifm (x # bs) p 2. Ifm (x # bs) (plusinf p) \<Longrightarrow> \<exists>x. Ifm (x # bs) p 3. \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p \<Longrightarrow> \<exists>x. Ifm (x # bs) p [PROOF STEP] from rminusinf_ex[OF lp this] [PROOF STATE] proof (chain) picking this: \<exists>x. Ifm (x # bs) p [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: \<exists>x. Ifm (x # bs) p goal (1 subgoal): 1. \<exists>x. Ifm (x # bs) p [PROOF STEP] . [PROOF STATE] proof (state) this: \<exists>x. Ifm (x # bs) p goal (2 subgoals): 1. Ifm (x # bs) (plusinf p) \<Longrightarrow> \<exists>x. Ifm (x # bs) p 2. \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p \<Longrightarrow> \<exists>x. Ifm (x # bs) p [PROOF STEP] next [PROOF STATE] proof (state) goal (2 subgoals): 1. Ifm (x # bs) (plusinf p) \<Longrightarrow> \<exists>x. Ifm (x # bs) p 2. \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p \<Longrightarrow> \<exists>x. Ifm (x # bs) p [PROOF STEP] case 2 [PROOF STATE] proof (state) this: Ifm (x # bs) (plusinf p) goal (2 subgoals): 1. Ifm (x # bs) (plusinf p) \<Longrightarrow> \<exists>x. Ifm (x # bs) p 2. \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p \<Longrightarrow> \<exists>x. Ifm (x # bs) p [PROOF STEP] from rplusinf_ex[OF lp this] [PROOF STATE] proof (chain) picking this: \<exists>x. Ifm (x # bs) p [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: \<exists>x. Ifm (x # bs) p goal (1 subgoal): 1. \<exists>x. Ifm (x # bs) p [PROOF STEP] . [PROOF STATE] proof (state) this: \<exists>x. Ifm (x # bs) p goal (1 subgoal): 1. \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p \<Longrightarrow> \<exists>x. Ifm (x # bs) p [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p \<Longrightarrow> \<exists>x. Ifm (x # bs) p [PROOF STEP] case 3 [PROOF STATE] proof (state) this: \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p goal (1 subgoal): 1. \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p \<Longrightarrow> \<exists>x. Ifm (x # bs) p [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: \<exists>(t, n)\<in>set (uset p). \<exists>(s, m)\<in>set (uset p). Ifm ((Inum (x # bs) t / real_of_int n + Inum (x # bs) s / real_of_int m) / 2 # bs) p goal (1 subgoal): 1. \<exists>x. Ifm (x # bs) p [PROOF STEP] by blast [PROOF STATE] proof (state) this: \<exists>x. Ifm (x # bs) p goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: \<exists>x. Ifm (x # bs) p goal: No subgoals! [PROOF STEP] qed
Pop is a Scrabble word. Scrabble point value for pop: 7 points. Pop is a Words with Friends word. Words with Friends point value for pop: 7 points. Above are the results of unscrambling pop. Using the word generator and word unscrambler for the letters P O P, we unscrambled the letters to create a list of all the words found in Scrabble, Words with Friends, and Text Twist. We found a total of 2 words by unscrambling the letters in pop. Click these words to find out how many points they are worth, their definitions, and all the other words that can be made by unscrambling the letters from these words. If one or more words can be unscrambled with all the letters entered plus one new letter, then they will also be displayed.
[STATEMENT] lemma csdi:"s O d^-1 \<subseteq> b \<union> m \<union> ov \<union> f^-1 \<union> d^-1" [PROOF STATE] proof (prove) goal (1 subgoal): 1. s O d\<inverse> \<subseteq> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] proof [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x. x \<in> s O d\<inverse> \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] fix x::"'a\<times>'a" [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x. x \<in> s O d\<inverse> \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] assume "x \<in> s O d^-1" [PROOF STATE] proof (state) this: x \<in> s O d\<inverse> goal (1 subgoal): 1. \<And>x. x \<in> s O d\<inverse> \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] then [PROOF STATE] proof (chain) picking this: x \<in> s O d\<inverse> [PROOF STEP] obtain p q z where "(p,z) : s" and "(z,q) : d^-1" and x:"x = (p,q)" [PROOF STATE] proof (prove) using this: x \<in> s O d\<inverse> goal (1 subgoal): 1. (\<And>p z q. \<lbrakk>(p, z) \<in> s; (z, q) \<in> d\<inverse>; x = (p, q)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: (p, z) \<in> s (z, q) \<in> d\<inverse> x = (p, q) goal (1 subgoal): 1. \<And>x. x \<in> s O d\<inverse> \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] from \<open>(p,z) : s\<close> [PROOF STATE] proof (chain) picking this: (p, z) \<in> s [PROOF STEP] obtain k u v where kp:"k\<parallel>p" and kz:"k\<parallel>z" and pu:"p\<parallel>u" and uv:"u\<parallel>v" and zv:"z\<parallel>v" [PROOF STATE] proof (prove) using this: (p, z) \<in> s goal (1 subgoal): 1. (\<And>k u v. \<lbrakk>k \<parallel> p; k \<parallel> z; p \<parallel> u; u \<parallel> v; z \<parallel> v\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] using s [PROOF STATE] proof (prove) using this: (p, z) \<in> s ((?p, ?q) \<in> s) = (\<exists>k u v. k \<parallel> ?p \<and> ?p \<parallel> u \<and> u \<parallel> v \<and> k \<parallel> ?q \<and> ?q \<parallel> v) goal (1 subgoal): 1. (\<And>k u v. \<lbrakk>k \<parallel> p; k \<parallel> z; p \<parallel> u; u \<parallel> v; z \<parallel> v\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by blast [PROOF STATE] proof (state) this: k \<parallel> p k \<parallel> z p \<parallel> u u \<parallel> v z \<parallel> v goal (1 subgoal): 1. \<And>x. x \<in> s O d\<inverse> \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] from \<open>(z,q) : d^-1\<close> [PROOF STATE] proof (chain) picking this: (z, q) \<in> d\<inverse> [PROOF STEP] obtain l' k' u' v' where lpq:"l'\<parallel>q" and kplp:"k'\<parallel>l'" and kpz:"k'\<parallel>z" and qup:"q\<parallel>u'" and upvp:"u'\<parallel>v'" and zvp:"z\<parallel>v'" [PROOF STATE] proof (prove) using this: (z, q) \<in> d\<inverse> goal (1 subgoal): 1. (\<And>l' k' u' v'. \<lbrakk>l' \<parallel> q; k' \<parallel> l'; k' \<parallel> z; q \<parallel> u'; u' \<parallel> v'; z \<parallel> v'\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] using d [PROOF STATE] proof (prove) using this: (z, q) \<in> d\<inverse> ((?p, ?q) \<in> d) = (\<exists>k l u v. k \<parallel> l \<and> l \<parallel> ?p \<and> ?p \<parallel> u \<and> u \<parallel> v \<and> k \<parallel> ?q \<and> ?q \<parallel> v) goal (1 subgoal): 1. (\<And>l' k' u' v'. \<lbrakk>l' \<parallel> q; k' \<parallel> l'; k' \<parallel> z; q \<parallel> u'; u' \<parallel> v'; z \<parallel> v'\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by blast [PROOF STATE] proof (state) this: l' \<parallel> q k' \<parallel> l' k' \<parallel> z q \<parallel> u' u' \<parallel> v' z \<parallel> v' goal (1 subgoal): 1. \<And>x. x \<in> s O d\<inverse> \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] from kp kz kpz [PROOF STATE] proof (chain) picking this: k \<parallel> p k \<parallel> z k' \<parallel> z [PROOF STEP] have kpp:"k'\<parallel>p" [PROOF STATE] proof (prove) using this: k \<parallel> p k \<parallel> z k' \<parallel> z goal (1 subgoal): 1. k' \<parallel> p [PROOF STEP] using M1 [PROOF STATE] proof (prove) using this: k \<parallel> p k \<parallel> z k' \<parallel> z \<lbrakk>?p \<parallel> ?q; ?p \<parallel> ?s; ?r \<parallel> ?q\<rbrakk> \<Longrightarrow> ?r \<parallel> ?s goal (1 subgoal): 1. k' \<parallel> p [PROOF STEP] by auto [PROOF STATE] proof (state) this: k' \<parallel> p goal (1 subgoal): 1. \<And>x. x \<in> s O d\<inverse> \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] from pu qup [PROOF STATE] proof (chain) picking this: p \<parallel> u q \<parallel> u' [PROOF STEP] have "p\<parallel>u' \<oplus> ((\<exists>t. p\<parallel>t \<and> t\<parallel>u') \<oplus> (\<exists>t. q\<parallel>t \<and> t\<parallel>u))" (is "?A \<oplus> (?B \<oplus> ?C)") [PROOF STATE] proof (prove) using this: p \<parallel> u q \<parallel> u' goal (1 subgoal): 1. p \<parallel> u' \<oplus> ((\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<oplus> (\<exists>t. q \<parallel> t \<and> t \<parallel> u)) [PROOF STEP] using M2 [PROOF STATE] proof (prove) using this: p \<parallel> u q \<parallel> u' \<lbrakk>?p \<parallel> ?q; ?r \<parallel> ?s\<rbrakk> \<Longrightarrow> ?p \<parallel> ?s \<oplus> ((\<exists>t. ?p \<parallel> t \<and> t \<parallel> ?s) \<oplus> (\<exists>t. ?r \<parallel> t \<and> t \<parallel> ?q)) goal (1 subgoal): 1. p \<parallel> u' \<oplus> ((\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<oplus> (\<exists>t. q \<parallel> t \<and> t \<parallel> u)) [PROOF STEP] by blast [PROOF STATE] proof (state) this: p \<parallel> u' \<oplus> ((\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<oplus> (\<exists>t. q \<parallel> t \<and> t \<parallel> u)) goal (1 subgoal): 1. \<And>x. x \<in> s O d\<inverse> \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] then [PROOF STATE] proof (chain) picking this: p \<parallel> u' \<oplus> ((\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<oplus> (\<exists>t. q \<parallel> t \<and> t \<parallel> u)) [PROOF STEP] have "(?A\<and>\<not>?B\<and>\<not>?C) \<or> ((\<not>?A\<and>?B\<and>\<not>?C) \<or> (\<not>?A\<and>\<not>?B\<and>?C))" [PROOF STATE] proof (prove) using this: p \<parallel> u' \<oplus> ((\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<oplus> (\<exists>t. q \<parallel> t \<and> t \<parallel> u)) goal (1 subgoal): 1. p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<or> \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<or> \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) [PROOF STEP] by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets) [PROOF STATE] proof (state) this: p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<or> \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<or> \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) goal (1 subgoal): 1. \<And>x. x \<in> s O d\<inverse> \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] thus "x \<in> b \<union> m \<union> ov \<union> f^-1 \<union> d^-1" [PROOF STATE] proof (prove) using this: p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<or> \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<or> \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) goal (1 subgoal): 1. x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] proof (elim disjE) [PROOF STATE] proof (state) goal (3 subgoals): 1. p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 3. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] { [PROOF STATE] proof (state) goal (3 subgoals): 1. p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 3. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] assume "?A\<and>\<not>?B\<and>\<not>?C" [PROOF STATE] proof (state) this: p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) goal (3 subgoals): 1. p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 3. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] then [PROOF STATE] proof (chain) picking this: p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) [PROOF STEP] have ?A [PROOF STATE] proof (prove) using this: p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) goal (1 subgoal): 1. p \<parallel> u' [PROOF STEP] by simp [PROOF STATE] proof (state) this: p \<parallel> u' goal (3 subgoals): 1. p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 3. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] with qup kpp kplp lpq [PROOF STATE] proof (chain) picking this: q \<parallel> u' k' \<parallel> p k' \<parallel> l' l' \<parallel> q p \<parallel> u' [PROOF STEP] have "(p,q) \<in> f^-1" [PROOF STATE] proof (prove) using this: q \<parallel> u' k' \<parallel> p k' \<parallel> l' l' \<parallel> q p \<parallel> u' goal (1 subgoal): 1. (p, q) \<in> f\<inverse> [PROOF STEP] using f [PROOF STATE] proof (prove) using this: q \<parallel> u' k' \<parallel> p k' \<parallel> l' l' \<parallel> q p \<parallel> u' ((?p, ?q) \<in> f) = (\<exists>k l u. k \<parallel> l \<and> l \<parallel> ?p \<and> ?p \<parallel> u \<and> k \<parallel> ?q \<and> ?q \<parallel> u) goal (1 subgoal): 1. (p, q) \<in> f\<inverse> [PROOF STEP] by blast [PROOF STATE] proof (state) this: (p, q) \<in> f\<inverse> goal (3 subgoals): 1. p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 3. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: (p, q) \<in> f\<inverse> goal (1 subgoal): 1. x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] using x [PROOF STATE] proof (prove) using this: (p, q) \<in> f\<inverse> x = (p, q) goal (1 subgoal): 1. x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] by auto [PROOF STATE] proof (state) this: x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> goal (2 subgoals): 1. \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] } [PROOF STATE] proof (state) this: p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> goal (2 subgoals): 1. \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] next [PROOF STATE] proof (state) goal (2 subgoals): 1. \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] { [PROOF STATE] proof (state) goal (2 subgoals): 1. \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] assume "\<not>?A\<and>?B\<and>\<not>?C" [PROOF STATE] proof (state) this: \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) goal (2 subgoals): 1. \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) [PROOF STEP] have ?B [PROOF STATE] proof (prove) using this: \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) goal (1 subgoal): 1. \<exists>t. p \<parallel> t \<and> t \<parallel> u' [PROOF STEP] by simp [PROOF STATE] proof (state) this: \<exists>t. p \<parallel> t \<and> t \<parallel> u' goal (2 subgoals): 1. \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<exists>t. p \<parallel> t \<and> t \<parallel> u' [PROOF STEP] obtain t where pt:"p\<parallel>t" and tup:"t\<parallel>u'" [PROOF STATE] proof (prove) using this: \<exists>t. p \<parallel> t \<and> t \<parallel> u' goal (1 subgoal): 1. (\<And>t. \<lbrakk>p \<parallel> t; t \<parallel> u'\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: p \<parallel> t t \<parallel> u' goal (2 subgoals): 1. \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] from pt lpq [PROOF STATE] proof (chain) picking this: p \<parallel> t l' \<parallel> q [PROOF STEP] have "p\<parallel>q \<oplus> ((\<exists>t'. p\<parallel>t' \<and> t'\<parallel>q) \<oplus> (\<exists>t'. l'\<parallel>t' \<and> t'\<parallel>t))" (is "?A \<oplus> (?B \<oplus> ?C)") [PROOF STATE] proof (prove) using this: p \<parallel> t l' \<parallel> q goal (1 subgoal): 1. p \<parallel> q \<oplus> ((\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<oplus> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t)) [PROOF STEP] using M2 [PROOF STATE] proof (prove) using this: p \<parallel> t l' \<parallel> q \<lbrakk>?p \<parallel> ?q; ?r \<parallel> ?s\<rbrakk> \<Longrightarrow> ?p \<parallel> ?s \<oplus> ((\<exists>t. ?p \<parallel> t \<and> t \<parallel> ?s) \<oplus> (\<exists>t. ?r \<parallel> t \<and> t \<parallel> ?q)) goal (1 subgoal): 1. p \<parallel> q \<oplus> ((\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<oplus> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t)) [PROOF STEP] by blast [PROOF STATE] proof (state) this: p \<parallel> q \<oplus> ((\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<oplus> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t)) goal (2 subgoals): 1. \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] then [PROOF STATE] proof (chain) picking this: p \<parallel> q \<oplus> ((\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<oplus> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t)) [PROOF STEP] have "(?A\<and>\<not>?B\<and>\<not>?C) \<or> ((\<not>?A\<and>?B\<and>\<not>?C) \<or> (\<not>?A\<and>\<not>?B\<and>?C))" [PROOF STATE] proof (prove) using this: p \<parallel> q \<oplus> ((\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<oplus> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t)) goal (1 subgoal): 1. p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<or> \<not> p \<parallel> q \<and> (\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<or> \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) [PROOF STEP] by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets) [PROOF STATE] proof (state) this: p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<or> \<not> p \<parallel> q \<and> (\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<or> \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) goal (2 subgoals): 1. \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] thus "x \<in> b \<union> m \<union> ov \<union> f^-1 \<union> d^-1" [PROOF STATE] proof (prove) using this: p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<or> \<not> p \<parallel> q \<and> (\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<or> \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) goal (1 subgoal): 1. x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] proof (elim disjE) [PROOF STATE] proof (state) goal (3 subgoals): 1. p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> q \<and> (\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 3. \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] { [PROOF STATE] proof (state) goal (3 subgoals): 1. p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> q \<and> (\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 3. \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] assume "?A\<and>\<not>?B\<and>\<not>?C" [PROOF STATE] proof (state) this: p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) goal (3 subgoals): 1. p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> q \<and> (\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 3. \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] then [PROOF STATE] proof (chain) picking this: p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) [PROOF STEP] have ?A [PROOF STATE] proof (prove) using this: p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) goal (1 subgoal): 1. p \<parallel> q [PROOF STEP] by simp [PROOF STATE] proof (state) this: p \<parallel> q goal (3 subgoals): 1. p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> q \<and> (\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 3. \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: p \<parallel> q goal (1 subgoal): 1. x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] using x m [PROOF STATE] proof (prove) using this: p \<parallel> q x = (p, q) ((?p, ?q) \<in> m) = ?p \<parallel> ?q goal (1 subgoal): 1. x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] by auto [PROOF STATE] proof (state) this: x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> goal (2 subgoals): 1. \<not> p \<parallel> q \<and> (\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] } [PROOF STATE] proof (state) this: p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> goal (2 subgoals): 1. \<not> p \<parallel> q \<and> (\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] next [PROOF STATE] proof (state) goal (2 subgoals): 1. \<not> p \<parallel> q \<and> (\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] { [PROOF STATE] proof (state) goal (2 subgoals): 1. \<not> p \<parallel> q \<and> (\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] assume "\<not>?A\<and>?B\<and>\<not>?C" [PROOF STATE] proof (state) this: \<not> p \<parallel> q \<and> (\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) goal (2 subgoals): 1. \<not> p \<parallel> q \<and> (\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<not> p \<parallel> q \<and> (\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) [PROOF STEP] have ?B [PROOF STATE] proof (prove) using this: \<not> p \<parallel> q \<and> (\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) goal (1 subgoal): 1. \<exists>t'. p \<parallel> t' \<and> t' \<parallel> q [PROOF STEP] by simp [PROOF STATE] proof (state) this: \<exists>t'. p \<parallel> t' \<and> t' \<parallel> q goal (2 subgoals): 1. \<not> p \<parallel> q \<and> (\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> 2. \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: \<exists>t'. p \<parallel> t' \<and> t' \<parallel> q goal (1 subgoal): 1. x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] using x b [PROOF STATE] proof (prove) using this: \<exists>t'. p \<parallel> t' \<and> t' \<parallel> q x = (p, q) ((?p, ?q) \<in> b) = (\<exists>t. ?p \<parallel> t \<and> t \<parallel> ?q) goal (1 subgoal): 1. x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] by auto [PROOF STATE] proof (state) this: x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> goal (1 subgoal): 1. \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] } [PROOF STATE] proof (state) this: \<not> p \<parallel> q \<and> (\<exists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<nexists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> goal (1 subgoal): 1. \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] { [PROOF STATE] proof (state) goal (1 subgoal): 1. \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] assume "\<not>?A \<and> \<not>?B \<and> ?C" [PROOF STATE] proof (state) this: \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) goal (1 subgoal): 1. \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) [PROOF STEP] have ?C [PROOF STATE] proof (prove) using this: \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) goal (1 subgoal): 1. \<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t [PROOF STEP] by simp [PROOF STATE] proof (state) this: \<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t goal (1 subgoal): 1. \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t [PROOF STEP] obtain t' where lptp:"l'\<parallel>t'" and tpt:"t'\<parallel>t" [PROOF STATE] proof (prove) using this: \<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t goal (1 subgoal): 1. (\<And>t'. \<lbrakk>l' \<parallel> t'; t' \<parallel> t\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: l' \<parallel> t' t' \<parallel> t goal (1 subgoal): 1. \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] with pt tup qup kpp kplp lpq [PROOF STATE] proof (chain) picking this: p \<parallel> t t \<parallel> u' q \<parallel> u' k' \<parallel> p k' \<parallel> l' l' \<parallel> q l' \<parallel> t' t' \<parallel> t [PROOF STEP] have "(p,q) \<in> ov" [PROOF STATE] proof (prove) using this: p \<parallel> t t \<parallel> u' q \<parallel> u' k' \<parallel> p k' \<parallel> l' l' \<parallel> q l' \<parallel> t' t' \<parallel> t goal (1 subgoal): 1. (p, q) \<in> ov [PROOF STEP] using ov [PROOF STATE] proof (prove) using this: p \<parallel> t t \<parallel> u' q \<parallel> u' k' \<parallel> p k' \<parallel> l' l' \<parallel> q l' \<parallel> t' t' \<parallel> t ((?p, ?q) \<in> ov) = (\<exists>k l u v t. (k \<parallel> ?p \<and> ?p \<parallel> u \<and> u \<parallel> v) \<and> (k \<parallel> l \<and> l \<parallel> ?q \<and> ?q \<parallel> v) \<and> l \<parallel> t \<and> t \<parallel> u) goal (1 subgoal): 1. (p, q) \<in> ov [PROOF STEP] by blast [PROOF STATE] proof (state) this: (p, q) \<in> ov goal (1 subgoal): 1. \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: (p, q) \<in> ov goal (1 subgoal): 1. x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] using x [PROOF STATE] proof (prove) using this: (p, q) \<in> ov x = (p, q) goal (1 subgoal): 1. x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] by auto [PROOF STATE] proof (state) this: x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> goal: No subgoals! [PROOF STEP] } [PROOF STATE] proof (state) this: \<not> p \<parallel> q \<and> (\<nexists>t'. p \<parallel> t' \<and> t' \<parallel> q) \<and> (\<exists>t'. l' \<parallel> t' \<and> t' \<parallel> t) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> goal (1 subgoal): 1. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] } [PROOF STATE] proof (state) this: \<not> p \<parallel> u' \<and> (\<exists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<nexists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> goal (1 subgoal): 1. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] { [PROOF STATE] proof (state) goal (1 subgoal): 1. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] assume "\<not>?A \<and> \<not>?B \<and> ?C" [PROOF STATE] proof (state) this: \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) goal (1 subgoal): 1. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) [PROOF STEP] have ?C [PROOF STATE] proof (prove) using this: \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) goal (1 subgoal): 1. \<exists>t. q \<parallel> t \<and> t \<parallel> u [PROOF STEP] by simp [PROOF STATE] proof (state) this: \<exists>t. q \<parallel> t \<and> t \<parallel> u goal (1 subgoal): 1. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<exists>t. q \<parallel> t \<and> t \<parallel> u [PROOF STEP] obtain t where "q\<parallel>t" and "t\<parallel>u" [PROOF STATE] proof (prove) using this: \<exists>t. q \<parallel> t \<and> t \<parallel> u goal (1 subgoal): 1. (\<And>t. \<lbrakk>q \<parallel> t; t \<parallel> u\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: q \<parallel> t t \<parallel> u goal (1 subgoal): 1. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] with pu kpp kplp lpq [PROOF STATE] proof (chain) picking this: p \<parallel> u k' \<parallel> p k' \<parallel> l' l' \<parallel> q q \<parallel> t t \<parallel> u [PROOF STEP] have "(p,q) \<in> d^-1" [PROOF STATE] proof (prove) using this: p \<parallel> u k' \<parallel> p k' \<parallel> l' l' \<parallel> q q \<parallel> t t \<parallel> u goal (1 subgoal): 1. (p, q) \<in> d\<inverse> [PROOF STEP] using d [PROOF STATE] proof (prove) using this: p \<parallel> u k' \<parallel> p k' \<parallel> l' l' \<parallel> q q \<parallel> t t \<parallel> u ((?p, ?q) \<in> d) = (\<exists>k l u v. k \<parallel> l \<and> l \<parallel> ?p \<and> ?p \<parallel> u \<and> u \<parallel> v \<and> k \<parallel> ?q \<and> ?q \<parallel> v) goal (1 subgoal): 1. (p, q) \<in> d\<inverse> [PROOF STEP] by blast [PROOF STATE] proof (state) this: (p, q) \<in> d\<inverse> goal (1 subgoal): 1. \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: (p, q) \<in> d\<inverse> goal (1 subgoal): 1. x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] using x [PROOF STATE] proof (prove) using this: (p, q) \<in> d\<inverse> x = (p, q) goal (1 subgoal): 1. x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> [PROOF STEP] by auto [PROOF STATE] proof (state) this: x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> goal: No subgoals! [PROOF STEP] } [PROOF STATE] proof (state) this: \<not> p \<parallel> u' \<and> (\<nexists>t. p \<parallel> t \<and> t \<parallel> u') \<and> (\<exists>t. q \<parallel> t \<and> t \<parallel> u) \<Longrightarrow> x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: x \<in> b \<union> m \<union> ov \<union> f\<inverse> \<union> d\<inverse> goal: No subgoals! [PROOF STEP] qed
function tests = test_imSurfaceArea(varargin) % Test case for the file imSurfaceArea. % % output = test_imSurfaceArea(input) % % Example % test_imSurfaceArea % % See also % % ------ % Author: David Legland % e-mail: [email protected] % Created: 2010-10-08, using Matlab 7.9.0.529 (R2009b) % Copyright 2010 INRAE - Cepia Software Platform. tests = functiontests(localfunctions); function testAddBorderD3(testCase) img = ones([5 5 5]) > 0; imgb = padarray(img, [1 1 1]) > 0; nDir = 3; b = imSurfaceArea(img, nDir); bb = imSurfaceArea(imgb, nDir); assertEqual(testCase, b, bb); function testAddBorderD13(testCase) img = ones([5 5 5]) > 0; imgb = padarray(img, [1 1 1]) > 0; nDir = 13; b = imSurfaceArea(img, nDir); bb = imSurfaceArea(imgb, nDir); assertEqual(testCase, b, bb); function test_Anisotropic(testCase) img = ones([5 5 5]) > 0; imgb = padarray(img, [1 1 1]) > 0; nDir = 3; b = imSurfaceArea(img, nDir, [1 2 3]); bb = imSurfaceArea(imgb, nDir, [1 2 3]); assertEqual(testCase, b, bb); function test_Labels_D3(testCase) img = zeros([5 5 5]); img(1:3, 1:3, 1:3) = 1; img(4:5, 1:3, 1:3) = 2; img(1:3, 4:5, 1:3) = 3; img(4:5, 4:5, 1:3) = 4; img(1:3, 1:3, 4:5) = 5; img(4:5, 1:3, 4:5) = 6; img(1:3, 4:5, 4:5) = 7; img(4:5, 4:5, 4:5) = 8; b3 = imSurfaceArea(img, 3); assertEqual(testCase, 8, length(b3)); imgb = padarray(img, [1 1 1]); bb3 = imSurfaceArea(imgb, 3); assertEqual(testCase, b3, bb3); function test_Labels_D13(testCase) img = zeros([5 5 5]); img(1:3, 1:3, 1:3) = 1; img(4:5, 1:3, 1:3) = 2; img(1:3, 4:5, 1:3) = 3; img(4:5, 4:5, 1:3) = 4; img(1:3, 1:3, 4:5) = 5; img(4:5, 1:3, 4:5) = 6; img(1:3, 4:5, 4:5) = 7; img(4:5, 4:5, 4:5) = 8; b13 = imSurfaceArea(img, 13); assertEqual(testCase, 8, length(b13)); imgb = padarray(img, [1 1 1]); bb13 = imSurfaceArea(imgb, 13); assertEqual(testCase, b13, bb13); function test_Labels2_D3(testCase) img = zeros([5 5 5]); img(1:3, 1:3, 1:3) = 2; img(4:5, 1:3, 1:3) = 3; img(1:3, 4:5, 1:3) = 5; img(4:5, 4:5, 1:3) = 7; img(1:3, 1:3, 4:5) = 11; img(4:5, 1:3, 4:5) = 13; img(1:3, 4:5, 4:5) = 17; img(4:5, 4:5, 4:5) = 19; [b3, labels3] = imSurfaceArea(img, 3); assertEqual(testCase, 8, length(b3)); assertEqual(testCase, 8, length(labels3)); assertEqual(testCase, labels3, [2 3 5 7 11 13 17 19]'); function test_Labels2_D13(testCase) img = zeros([5 5 5]); img(1:3, 1:3, 1:3) = 2; img(4:5, 1:3, 1:3) = 3; img(1:3, 4:5, 1:3) = 5; img(4:5, 4:5, 1:3) = 7; img(1:3, 1:3, 4:5) = 11; img(4:5, 1:3, 4:5) = 13; img(1:3, 4:5, 4:5) = 17; img(4:5, 4:5, 4:5) = 19; [b13, labels13] = imSurfaceArea(img, 13); assertEqual(testCase, 8, length(b13)); assertEqual(testCase, 8, length(labels13)); assertEqual(testCase, labels13, [2 3 5 7 11 13 17 19]');
theory nat_alt_mul_comm imports Main "$HIPSTER_HOME/IsaHipster" begin datatype Nat = Z | S "Nat" fun plus :: "Nat => Nat => Nat" where "plus (Z) y = y" | "plus (S n) y = S (plus n y)" fun altmul :: "Nat => Nat => Nat" where "altmul (Z) y = Z" | "altmul (S z) (Z) = Z" | "altmul (S z) (S x2) = S (plus (plus (altmul z x2) z) x2)" (*hipster plus altmul *) theorem x0 : "!! (x :: Nat) (y :: Nat) . (altmul x y) = (altmul y x)" by (tactic \<open>Subgoal.FOCUS_PARAMS (K (Tactic_Data.hard_tac @{context})) @{context} 1\<close>) end
[STATEMENT] theorem hyp2_not_tarski: "\<not> (tarski real_hyp2_C real_hyp2_B)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<not> tarski real_hyp2_C real_hyp2_B [PROOF STEP] using hyp2_axiom10_false [PROOF STATE] proof (prove) using this: \<not> (\<forall>a b c d t. B\<^sub>K a d t \<and> B\<^sub>K b d c \<and> a \<noteq> d \<longrightarrow> (\<exists>x y. B\<^sub>K a b x \<and> B\<^sub>K a c y \<and> B\<^sub>K x t y)) goal (1 subgoal): 1. \<not> tarski real_hyp2_C real_hyp2_B [PROOF STEP] by (unfold tarski_def tarski_space_def tarski_space_axioms_def) simp
#pragma once #include <cybozu/inttype.hpp> #ifdef CYBOZU_USE_BOOST #include <boost/unordered_set.hpp> #elif (CYBOZU_CPP_VERSION >= CYBOZU_CPP_VERSION_CPP11) || defined(__APPLE__) #include <unordered_set> #elif (CYBOZU_CPP_VERSION == CYBOZU_CPP_VERSION_TR1) #include <list> #include <tr1/unordered_set> #endif
theory Refine_Parallel imports "HOL-Library.Parallel" Ordinary_Differential_Equations.ODE_Auxiliarities "../Refinement/Autoref_Misc" "../Refinement/Weak_Set" begin context includes autoref_syntax begin lemma dres_of_dress_impl: "nres_of (rec_list (dRETURN []) (\<lambda>x xs r. do { fx \<leftarrow> x; r \<leftarrow> r; dRETURN (fx # r)}) (Parallel.map f x)) \<le> nres_of_nress_impl (Parallel.map f' x)" if [refine_transfer]: "\<And>x. nres_of (f x) \<le> f' x" unfolding Parallel.map_def nres_of_nress_impl_map apply (induction x) apply auto apply refine_transfer done concrete_definition dres_of_dress_impl uses dres_of_dress_impl lemmas [refine_transfer] = dres_of_dress_impl.refine definition PAR_IMAGE::"('a \<Rightarrow> 'c \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> 'c nres) \<Rightarrow> 'a set \<Rightarrow> ('a \<times> 'c) set nres" where "PAR_IMAGE P f X = do { xs \<leftarrow> list_spec X; fxs \<leftarrow>nres_of_nress (\<lambda>(x, y). P x y) (Parallel.map (\<lambda>x. do { y \<leftarrow> f x; RETURN (x, y)}) xs); RETURN (set fxs) }" lemma [autoref_op_pat_def]: "PAR_IMAGE P \<equiv> OP (PAR_IMAGE P)" by auto lemma [autoref_rules]: "(Parallel.map, Parallel.map) \<in> (A \<rightarrow> B) \<rightarrow> \<langle>A\<rangle>list_rel \<rightarrow> \<langle>B\<rangle>list_rel" unfolding Parallel.map_def by parametricity schematic_goal PAR_IMAGE_nres: "(?r, PAR_IMAGE P $ f $ X) \<in> \<langle>\<langle>A\<times>\<^sub>rB\<rangle>list_wset_rel\<rangle>nres_rel" if [autoref_rules]: "(fi, f) \<in> A \<rightarrow> \<langle>B\<rangle>nres_rel" "(Xi, X) \<in> \<langle>A\<rangle>list_wset_rel" and [THEN PREFER_sv_D, relator_props]: "PREFER single_valued A" "PREFER single_valued B" unfolding PAR_IMAGE_def including art by autoref concrete_definition PAR_IMAGE_nres uses PAR_IMAGE_nres lemma PAR_IMAGE_nres_impl_refine[autoref_rules]: "PREFER single_valued A \<Longrightarrow> PREFER single_valued B \<Longrightarrow> (\<lambda>fi Xi. PAR_IMAGE_nres fi Xi, PAR_IMAGE P) \<in> (A \<rightarrow> \<langle>B\<rangle>nres_rel) \<rightarrow> \<langle>A\<rangle>list_wset_rel \<rightarrow> \<langle>\<langle>A\<times>\<^sub>rB\<rangle>list_wset_rel\<rangle>nres_rel" using PAR_IMAGE_nres.refine by force schematic_goal PAR_IMAGE_dres: assumes [refine_transfer]: "\<And>x. nres_of (f x) \<le> f' x" shows "nres_of (?f) \<le> PAR_IMAGE_nres f' X'" unfolding PAR_IMAGE_nres_def by refine_transfer concrete_definition PAR_IMAGE_dres for f X' uses PAR_IMAGE_dres lemmas [refine_transfer] = PAR_IMAGE_dres.refine lemma nres_of_nress_Parallel_map_SPEC[le, refine_vcg]: assumes "\<And>x. x \<in> set xs \<Longrightarrow> f x \<le> SPEC (I x)" shows "nres_of_nress (\<lambda>(x, y). I x y) (Parallel.map (\<lambda>x. f x \<bind> (\<lambda>y. RETURN (x, y))) xs) \<le> SPEC (\<lambda>xrs. map fst xrs = xs \<and> (\<forall>(x, r) \<in> set xrs. I x r))" using assms apply (induction xs) subgoal by simp apply clarsimp apply (rule refine_vcg) subgoal for x xs apply (rule order_trans[of _ "SPEC (I x)"]) apply force apply (rule refine_vcg) apply (rule refine_vcg) apply (rule order_trans, assumption) apply refine_vcg done done lemma PAR_IMAGE_SPEC[le, refine_vcg]: "PAR_IMAGE I f X \<le> SPEC (\<lambda>R. X = fst ` R \<and> (\<forall>(x,r) \<in> R. I x r))" if [le, refine_vcg]: "\<And>x. x \<in> X \<Longrightarrow> f x \<le> SPEC (I x)" unfolding PAR_IMAGE_def by refine_vcg end end
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Command import Lean.Meta.Closure import Lean.Meta.SizeOf import Lean.Meta.Injective import Lean.Meta.Structure import Lean.Meta.AppBuilder import Lean.Elab.Command import Lean.Elab.DeclModifiers import Lean.Elab.DeclUtil import Lean.Elab.Inductive import Lean.Elab.DeclarationRange import Lean.Elab.Binders namespace Lean.Elab.Command open Meta /- Recall that the `structure command syntax is ``` leading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> optional (" := " >> optional structCtor >> structFields) ``` -/ structure StructCtorView where ref : Syntax modifiers : Modifiers inferMod : Bool -- true if `{}` is used in the constructor declaration name : Name declName : Name structure StructFieldView where ref : Syntax modifiers : Modifiers binderInfo : BinderInfo inferMod : Bool declName : Name name : Name -- The field name as it is going to be registered in the kernel. It does not include macroscopes. rawName : Name -- Same as `name` but including macroscopes. binders : Syntax type? : Option Syntax value? : Option Syntax structure StructView where ref : Syntax modifiers : Modifiers scopeLevelNames : List Name -- All `universe` declarations in the current scope allUserLevelNames : List Name -- `scopeLevelNames` ++ explicit universe parameters provided in the `structure` command isClass : Bool declName : Name scopeVars : Array Expr -- All `variable` declaration in the current scope params : Array Expr -- Explicit parameters provided in the `structure` command parents : Array Syntax type : Syntax ctor : StructCtorView fields : Array StructFieldView inductive StructFieldKind where | newField | copiedField | fromParent | subobject deriving Inhabited, DecidableEq, Repr structure StructFieldInfo where name : Name declName : Name -- Remark: for `fromParent` fields, `declName` is only relevant in the generation of auxiliary "default value" functions. fvar : Expr kind : StructFieldKind inferMod : Bool := false value? : Option Expr := none deriving Inhabited, Repr def StructFieldInfo.isFromParent (info : StructFieldInfo) : Bool := match info.kind with | StructFieldKind.fromParent => true | _ => false def StructFieldInfo.isSubobject (info : StructFieldInfo) : Bool := match info.kind with | StructFieldKind.subobject => true | _ => false /- Auxiliary declaration for `mkProjections` -/ structure ProjectionInfo where declName : Name inferMod : Bool structure ElabStructResult where decl : Declaration projInfos : List ProjectionInfo projInstances : List Name -- projections (to parent classes) that must be marked as instances. mctx : MetavarContext lctx : LocalContext localInsts : LocalInstances defaultAuxDecls : Array (Name × Expr × Expr) private def defaultCtorName := `mk /- The structure constructor syntax is ``` leading_parser try (declModifiers >> ident >> optional inferMod >> " :: ") ``` -/ private def expandCtor (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM StructCtorView := do let useDefault := do let declName := structDeclName ++ defaultCtorName addAuxDeclarationRanges declName structStx[2] structStx[2] pure { ref := structStx, modifiers := {}, inferMod := false, name := defaultCtorName, declName } if structStx[5].isNone then useDefault else let optCtor := structStx[5][1] if optCtor.isNone then useDefault else let ctor := optCtor[0] withRef ctor do let ctorModifiers ← elabModifiers ctor[0] checkValidCtorModifier ctorModifiers if ctorModifiers.isPrivate && structModifiers.isPrivate then throwError "invalid 'private' constructor in a 'private' structure" if ctorModifiers.isProtected && structModifiers.isPrivate then throwError "invalid 'protected' constructor in a 'private' structure" let inferMod := !ctor[2].isNone let name := ctor[1].getId let declName := structDeclName ++ name let declName ← applyVisibility ctorModifiers.visibility declName addDocString' declName ctorModifiers.docString? addAuxDeclarationRanges declName ctor[1] ctor[1] pure { ref := ctor, name, modifiers := ctorModifiers, inferMod, declName } def checkValidFieldModifier (modifiers : Modifiers) : TermElabM Unit := do if modifiers.isNoncomputable then throwError "invalid use of 'noncomputable' in field declaration" if modifiers.isPartial then throwError "invalid use of 'partial' in field declaration" if modifiers.isUnsafe then throwError "invalid use of 'unsafe' in field declaration" if modifiers.attrs.size != 0 then throwError "invalid use of attributes in field declaration" /- ``` def structExplicitBinder := leading_parser atomic (declModifiers true >> "(") >> many1 ident >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) >> ")" def structImplicitBinder := leading_parser atomic (declModifiers true >> "{") >> many1 ident >> optional inferMod >> declSig >> "}" def structInstBinder := leading_parser atomic (declModifiers true >> "[") >> many1 ident >> optional inferMod >> declSig >> "]" def structSimpleBinder := leading_parser atomic (declModifiers true >> ident) >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) def structFields := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder) ``` -/ private def expandFields (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM (Array StructFieldView) := let fieldBinders := if structStx[5].isNone then #[] else structStx[5][2][0].getArgs fieldBinders.foldlM (init := #[]) fun (views : Array StructFieldView) fieldBinder => withRef fieldBinder do let mut fieldBinder := fieldBinder if fieldBinder.getKind == ``Parser.Command.structSimpleBinder then fieldBinder := mkNode ``Parser.Command.structExplicitBinder #[ fieldBinder[0], mkAtomFrom fieldBinder "(", mkNullNode #[ fieldBinder[1] ], fieldBinder[2], fieldBinder[3], fieldBinder[4], mkAtomFrom fieldBinder ")" ] let k := fieldBinder.getKind let binfo ← if k == ``Parser.Command.structExplicitBinder then pure BinderInfo.default else if k == ``Parser.Command.structImplicitBinder then pure BinderInfo.implicit else if k == ``Parser.Command.structInstBinder then pure BinderInfo.instImplicit else throwError "unexpected kind of structure field" let fieldModifiers ← elabModifiers fieldBinder[0] checkValidFieldModifier fieldModifiers if fieldModifiers.isPrivate && structModifiers.isPrivate then throwError "invalid 'private' field in a 'private' structure" if fieldModifiers.isProtected && structModifiers.isPrivate then throwError "invalid 'protected' field in a 'private' structure" let inferMod := !fieldBinder[3].isNone let (binders, type?) ← if binfo == BinderInfo.default then let (binders, type?) := expandOptDeclSig fieldBinder[4] let optBinderTacticDefault := fieldBinder[5] if optBinderTacticDefault.isNone then pure (binders, type?) else if optBinderTacticDefault[0].getKind != ``Parser.Term.binderTactic then pure (binders, type?) else let binderTactic := optBinderTacticDefault[0] match type? with | none => throwErrorAt binderTactic "invalid field declaration, type must be provided when auto-param (tactic) is used" | some type => let tac := binderTactic[2] let name ← Term.declareTacticSyntax tac -- The tactic should be for binders+type. -- It is safe to reset the binders to a "null" node since there is no value to be elaborated let type ← `(forall $(binders.getArgs):bracketedBinder*, $type) let type ← `(autoParam $type $(mkIdentFrom tac name)) pure (mkNullNode, some type) else let (binders, type) := expandDeclSig fieldBinder[4] pure (binders, some type) let value? ← if binfo != BinderInfo.default then pure none else let optBinderTacticDefault := fieldBinder[5] -- trace[Elab.struct] ">>> {optBinderTacticDefault}" if optBinderTacticDefault.isNone then pure none else if optBinderTacticDefault[0].getKind == ``Parser.Term.binderTactic then pure none else -- binderDefault := leading_parser " := " >> termParser pure (some optBinderTacticDefault[0][1]) let idents := fieldBinder[2].getArgs idents.foldlM (init := views) fun (views : Array StructFieldView) ident => withRef ident do let rawName := ident.getId let name := rawName.eraseMacroScopes unless name.isAtomic do throwErrorAt ident "invalid field name '{name.eraseMacroScopes}', field names must be atomic" let declName := structDeclName ++ name let declName ← applyVisibility fieldModifiers.visibility declName addDocString' declName fieldModifiers.docString? return views.push { ref := ident modifiers := fieldModifiers binderInfo := binfo inferMod declName name rawName binders type? value? } private def validStructType (type : Expr) : Bool := match type with | Expr.sort .. => true | _ => false private def findFieldInfo? (infos : Array StructFieldInfo) (fieldName : Name) : Option StructFieldInfo := infos.find? fun info => info.name == fieldName private def containsFieldName (infos : Array StructFieldInfo) (fieldName : Name) : Bool := (findFieldInfo? infos fieldName).isSome private def updateFieldInfoVal (infos : Array StructFieldInfo) (fieldName : Name) (value : Expr) : Array StructFieldInfo := infos.map fun info => if info.name == fieldName then { info with value? := value } else info register_builtin_option structureDiamondWarning : Bool := { defValue := false descr := "enable/disable warning messages for structure diamonds" } /-- Return `some fieldName` if field `fieldName` of the parent structure `parentStructName` is already in `infos` -/ private def findExistingField? (infos : Array StructFieldInfo) (parentStructName : Name) : CoreM (Option Name) := do let fieldNames := getStructureFieldsFlattened (← getEnv) parentStructName for fieldName in fieldNames do if containsFieldName infos fieldName then return some fieldName return none private partial def processSubfields (structDeclName : Name) (parentFVar : Expr) (parentStructName : Name) (subfieldNames : Array Name) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := go 0 infos where go (i : Nat) (infos : Array StructFieldInfo) := do if h : i < subfieldNames.size then let subfieldName := subfieldNames.get ⟨i, h⟩ if containsFieldName infos subfieldName then throwError "field '{subfieldName}' from '{parentStructName}' has already been declared" let val ← mkProjection parentFVar subfieldName let type ← inferType val withLetDecl subfieldName type val fun subfieldFVar => /- The following `declName` is only used for creating the `_default` auxiliary declaration name when its default value is overwritten in the structure. If the default value is not overwritten, then its value is irrelevant. -/ let declName := structDeclName ++ subfieldName let infos := infos.push { name := subfieldName, declName, fvar := subfieldFVar, kind := StructFieldKind.fromParent } go (i+1) infos else k infos /-- Given `obj.foo.bar.baz`, return `obj`. -/ private partial def getNestedProjectionArg (e : Expr) : MetaM Expr := do if let Expr.const subProjName .. := e.getAppFn then if let some { numParams, .. } ← getProjectionFnInfo? subProjName then if e.getAppNumArgs == numParams + 1 then return ← getNestedProjectionArg e.appArg! return e /-- Get field type of `fieldName` in `parentStructName`, but replace references to other fields of that structure by existing field fvars. Auxiliary method for `copyNewFieldsFrom`. -/ private def getFieldType (infos : Array StructFieldInfo) (parentStructName : Name) (parentType : Expr) (fieldName : Name) : MetaM Expr := do withLocalDeclD (← mkFreshId) parentType fun parent => do let proj ← mkProjection parent fieldName let projType ← inferType proj /- Eliminate occurrences of `parent.field`. This happens when the structure contains dependent fields. If the copied parent extended another structure via a subobject, then the occurrence can also look like `parent.toGrandparent.field` (where `toGrandparent` is not a field of the current structure). -/ let visit (e : Expr) : MetaM TransformStep := do if let Expr.const subProjName .. := e.getAppFn then if let some { ctorName, numParams, .. } ← getProjectionFnInfo? subProjName then let Name.str subStructName subFieldName .. := subProjName | throwError "invalid projection name {subProjName}" let args := e.getAppArgs if let some major := args.get? numParams then if (← getNestedProjectionArg major) == parent then if let some existingFieldInfo := findFieldInfo? infos subFieldName then return TransformStep.done <| mkAppN existingFieldInfo.fvar args[numParams+1:args.size] return TransformStep.done e let projType ← Meta.transform projType (post := visit) if projType.containsFVar parent.fvarId! then throwError "unsupported dependent field in {fieldName} : {projType}" return projType private def toVisibility (fieldInfo : StructureFieldInfo) : CoreM Visibility := do if isProtected (← getEnv) fieldInfo.projFn then return Visibility.protected else if isPrivateName fieldInfo.projFn then return Visibility.private else return Visibility.regular abbrev FieldMap := NameMap Expr -- Map from field name to expression representing the field /-- Reduce projetions of the structures in `structNames` -/ private def reduceProjs (e : Expr) (structNames : NameSet) : MetaM Expr := let reduce (e : Expr) : MetaM TransformStep := do match (← reduceProjOf? e structNames.contains) with | some v => return TransformStep.done v | _ => return TransformStep.done e transform e (post := reduce) /-- Copy the default value for field `fieldName` set at structure `structName`. The arguments for the `_default` auxiliary function are provided by `fieldMap`. Recall some of the entries in `fieldMap` are constructor applications, and they needed to be reduced using `reduceProjs`. Otherwise, the produced default value may be "cyclic". That is, we reduce projections of the structures in `expandedStructNames`. Here is an example that shows why the reduction is needed. ``` structure A where a : Nat structure B where a : Nat b : Nat c : Nat structure C extends B where d : Nat c := b + d structure D extends A, C #print D.c._default ``` Without the reduction, it produces ``` def D.c._default : A → Nat → Nat → Nat → Nat := fun toA b c d => id ({ a := toA.a, b := b, c := c : B }.b + d) ``` -/ private partial def copyDefaultValue? (fieldMap : FieldMap) (expandedStructNames : NameSet) (structName : Name) (fieldName : Name) : TermElabM (Option Expr) := do match getDefaultFnForField? (← getEnv) structName fieldName with | none => return none | some defaultFn => let cinfo ← getConstInfo defaultFn let us ← mkFreshLevelMVarsFor cinfo go? (cinfo.instantiateValueLevelParams us) where failed : TermElabM (Option Expr) := do logWarning s!"ignoring default value for field '{fieldName}' defined at '{structName}'" return none go? (e : Expr) : TermElabM (Option Expr) := do match e with | Expr.lam n d b c => if c.binderInfo.isExplicit then let fieldName := n match fieldMap.find? n with | none => failed | some val => let valType ← inferType val if (← isDefEq valType d) then go? (b.instantiate1 val) else failed else let arg ← mkFreshExprMVar d go? (b.instantiate1 arg) | e => let r := if e.isAppOfArity ``id 2 then e.appArg! else e return some (← reduceProjs (← instantiateMVars e.appArg!) expandedStructNames) private partial def copyNewFieldsFrom (structDeclName : Name) (infos : Array StructFieldInfo) (parentType : Expr) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := do copyFields infos {} parentType fun infos _ _ => k infos where copyFields (infos : Array StructFieldInfo) (expandedStructNames : NameSet) (parentType : Expr) (k : Array StructFieldInfo → FieldMap → NameSet → TermElabM α) : TermElabM α := do let parentStructName ← getStructureName parentType let fieldNames := getStructureFields (← getEnv) parentStructName let rec copy (i : Nat) (infos : Array StructFieldInfo) (fieldMap : FieldMap) (expandedStructNames : NameSet) : TermElabM α := do if h : i < fieldNames.size then let fieldName := fieldNames.get ⟨i, h⟩ let fieldType ← getFieldType infos parentStructName parentType fieldName match findFieldInfo? infos fieldName with | some existingFieldInfo => let existingFieldType ← inferType existingFieldInfo.fvar unless (← isDefEq fieldType existingFieldType) do throwError "parent field type mismatch, field '{fieldName}' from parent '{parentStructName}' {← mkHasTypeButIsExpectedMsg fieldType existingFieldType}" /- Remark: if structure has a default value for this field, it will be set at the `processOveriddenDefaultValues` below. -/ copy (i+1) infos (fieldMap.insert fieldName existingFieldInfo.fvar) expandedStructNames | none => let some fieldInfo := getFieldInfo? (← getEnv) parentStructName fieldName | unreachable! let addNewField : TermElabM α := do let value? ← copyDefaultValue? fieldMap expandedStructNames parentStructName fieldName withLocalDecl fieldName fieldInfo.binderInfo fieldType fun fieldFVar => do let fieldDeclName := structDeclName ++ fieldName let fieldDeclName ← applyVisibility (← toVisibility fieldInfo) fieldDeclName let infos := infos.push { name := fieldName, declName := fieldDeclName, fvar := fieldFVar, value?, kind := StructFieldKind.copiedField, inferMod := fieldInfo.inferMod } copy (i+1) infos (fieldMap.insert fieldName fieldFVar) expandedStructNames if fieldInfo.subobject?.isSome then let fieldParentStructName ← getStructureName fieldType if (← findExistingField? infos fieldParentStructName).isSome then -- See comment at `copyDefaultValue?` let expandedStructNames := expandedStructNames.insert fieldParentStructName copyFields infos expandedStructNames fieldType fun infos nestedFieldMap expandedStructNames => do let fieldVal ← mkCompositeField fieldType nestedFieldMap trace[Meta.debug] "composite, {fieldName} := {fieldVal}" copy (i+1) infos (fieldMap.insert fieldName fieldVal) expandedStructNames else let subfieldNames := getStructureFieldsFlattened (← getEnv) fieldParentStructName let fieldName := fieldInfo.fieldName withLocalDecl fieldName fieldInfo.binderInfo fieldType fun parentFVar => let infos := infos.push { name := fieldName, declName := structDeclName ++ fieldName, fvar := parentFVar, kind := StructFieldKind.subobject } processSubfields structDeclName parentFVar fieldParentStructName subfieldNames infos fun infos => copy (i+1) infos (fieldMap.insert fieldName parentFVar) expandedStructNames else addNewField else let infos ← processOveriddenDefaultValues infos fieldMap expandedStructNames parentStructName k infos fieldMap expandedStructNames copy 0 infos {} expandedStructNames processOveriddenDefaultValues (infos : Array StructFieldInfo) (fieldMap : FieldMap) (expandedStructNames : NameSet) (parentStructName : Name) : TermElabM (Array StructFieldInfo) := infos.mapM fun info => do match (← copyDefaultValue? fieldMap expandedStructNames parentStructName info.name) with | some value => return { info with value? := value } | none => return info mkCompositeField (parentType : Expr) (fieldMap : FieldMap) : TermElabM Expr := do let env ← getEnv let Expr.const parentStructName us _ ← pure parentType.getAppFn | unreachable! let parentCtor := getStructureCtor env parentStructName let mut result := mkAppN (mkConst parentCtor.name us) parentType.getAppArgs for fieldName in getStructureFields env parentStructName do match fieldMap.find? fieldName with | some val => result := mkApp result val | none => throwError "failed to copy fields from parent structure{indentExpr parentType}" -- TODO improve error message return result private partial def mkToParentName (parentStructName : Name) (p : Name → Bool) : Name := Id.run <| do let base := Name.mkSimple $ "to" ++ parentStructName.eraseMacroScopes.getString! if p base then base else let rec go (i : Nat) : Name := let curr := base.appendIndexAfter i if p curr then curr else go (i+1) go 1 private partial def withParents (view : StructView) (k : Array StructFieldInfo → Array Expr → TermElabM α) : TermElabM α := do go 0 #[] #[] where go (i : Nat) (infos : Array StructFieldInfo) (copiedParents : Array Expr) : TermElabM α := do if h : i < view.parents.size then let parentStx := view.parents.get ⟨i, h⟩ withRef parentStx do let parentType ← Term.elabType parentStx let parentStructName ← getStructureName parentType if let some existingFieldName ← findExistingField? infos parentStructName then if structureDiamondWarning.get (← getOptions) then logWarning s!"field '{existingFieldName}' from '{parentStructName}' has already been declared" copyNewFieldsFrom view.declName infos parentType fun infos => go (i+1) infos (copiedParents.push parentType) -- TODO: if `class`, then we need to create a let-decl that stores the local instance for the `parentStructure` else let env ← getEnv let subfieldNames := getStructureFieldsFlattened env parentStructName let toParentName := mkToParentName parentStructName fun n => !containsFieldName infos n && !subfieldNames.contains n let binfo := if view.isClass && isClass env parentStructName then BinderInfo.instImplicit else BinderInfo.default withLocalDecl toParentName binfo parentType fun parentFVar => let infos := infos.push { name := toParentName, declName := view.declName ++ toParentName, fvar := parentFVar, kind := StructFieldKind.subobject } processSubfields view.declName parentFVar parentStructName subfieldNames infos fun infos => go (i+1) infos copiedParents else k infos copiedParents private def elabFieldTypeValue (view : StructFieldView) : TermElabM (Option Expr × Option Expr) := do Term.withAutoBoundImplicit <| Term.elabBinders view.binders.getArgs fun params => do match view.type? with | none => match view.value? with | none => return (none, none) | some valStx => Term.synthesizeSyntheticMVarsNoPostponing let params ← Term.addAutoBoundImplicits params let value ← Term.elabTerm valStx none let value ← mkLambdaFVars params value return (none, value) | some typeStx => let type ← Term.elabType typeStx Term.synthesizeSyntheticMVarsNoPostponing let params ← Term.addAutoBoundImplicits params match view.value? with | none => let type ← mkForallFVars params type return (type, none) | some valStx => let value ← Term.elabTermEnsuringType valStx type Term.synthesizeSyntheticMVarsNoPostponing let type ← mkForallFVars params type let value ← mkLambdaFVars params value return (type, value) private partial def withFields (views : Array StructFieldView) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := do go 0 {} infos where go (i : Nat) (defaultValsOverridden : NameSet) (infos : Array StructFieldInfo) : TermElabM α := do if h : i < views.size then let view := views.get ⟨i, h⟩ withRef view.ref do match findFieldInfo? infos view.name with | none => let (type?, value?) ← elabFieldTypeValue view match type?, value? with | none, none => throwError "invalid field, type expected" | some type, _ => withLocalDecl view.rawName view.binderInfo type fun fieldFVar => let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value?, kind := StructFieldKind.newField, inferMod := view.inferMod } go (i+1) defaultValsOverridden infos | none, some value => let type ← inferType value withLocalDecl view.rawName view.binderInfo type fun fieldFVar => let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value, kind := StructFieldKind.newField, inferMod := view.inferMod } go (i+1) defaultValsOverridden infos | some info => let updateDefaultValue (fromParent : Bool) : TermElabM α := do match view.value? with | none => throwError "field '{view.name}' has been declared in parent structure" | some valStx => if let some type := view.type? then throwErrorAt type "omit field '{view.name}' type to set default value" else if defaultValsOverridden.contains info.name then throwError "field '{view.name}' new default value has already been set" let defaultValsOverridden := defaultValsOverridden.insert info.name let mut valStx := valStx if view.binders.getArgs.size > 0 then valStx ← `(fun $(view.binders.getArgs)* => $valStx:term) let fvarType ← inferType info.fvar let value ← Term.elabTermEnsuringType valStx fvarType let infos := updateFieldInfoVal infos info.name value go (i+1) defaultValsOverridden infos match info.kind with | StructFieldKind.newField => throwError "field '{view.name}' has already been declared" | StructFieldKind.subobject => throwError "unexpected subobject field reference" -- improve error message | StructFieldKind.copiedField => updateDefaultValue false | StructFieldKind.fromParent => updateDefaultValue true else k infos private def getResultUniverse (type : Expr) : TermElabM Level := do let type ← whnf type match type with | Expr.sort u _ => pure u | _ => throwError "unexpected structure resulting type" private def collectUsed (params : Array Expr) (fieldInfos : Array StructFieldInfo) : StateRefT CollectFVars.State MetaM Unit := do params.forM fun p => do let type ← inferType p Meta.collectUsedFVars type fieldInfos.forM fun info => do let fvarType ← inferType info.fvar Meta.collectUsedFVars fvarType match info.value? with | none => pure () | some value => Meta.collectUsedFVars value private def removeUnused (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (LocalContext × LocalInstances × Array Expr) := do let (_, used) ← (collectUsed params fieldInfos).run {} Meta.removeUnused scopeVars used private def withUsed {α} (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) (k : Array Expr → TermElabM α) : TermElabM α := do let (lctx, localInsts, vars) ← removeUnused scopeVars params fieldInfos withLCtx lctx localInsts <| k vars private def levelMVarToParamFVar (fvar : Expr) : StateRefT Nat TermElabM Unit := do let type ← inferType fvar discard <| Term.levelMVarToParam' type private def levelMVarToParamFVars (fvars : Array Expr) : StateRefT Nat TermElabM Unit := fvars.forM levelMVarToParamFVar private def levelMVarToParamAux (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : StateRefT Nat TermElabM (Array StructFieldInfo) := do levelMVarToParamFVars scopeVars levelMVarToParamFVars params fieldInfos.mapM fun info => do levelMVarToParamFVar info.fvar match info.value? with | none => pure info | some value => let value ← Term.levelMVarToParam' value pure { info with value? := value } private def levelMVarToParam (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (Array StructFieldInfo) := (levelMVarToParamAux scopeVars params fieldInfos).run' 1 private partial def collectUniversesFromFields (r : Level) (rOffset : Nat) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Level) := do fieldInfos.foldlM (init := #[]) fun (us : Array Level) (info : StructFieldInfo) => do let type ← inferType info.fvar let u ← getLevel type let u ← instantiateLevelMVars u accLevelAtCtor u r rOffset us private def updateResultingUniverse (fieldInfos : Array StructFieldInfo) (type : Expr) : TermElabM Expr := do let r ← getResultUniverse type let rOffset : Nat := r.getOffset let r : Level := r.getLevelOffset match r with | Level.mvar mvarId _ => let us ← collectUniversesFromFields r rOffset fieldInfos let rNew := mkResultUniverse us rOffset assignLevelMVar mvarId rNew instantiateMVars type | _ => throwError "failed to compute resulting universe level of structure, provide universe explicitly" private def collectLevelParamsInFVar (s : CollectLevelParams.State) (fvar : Expr) : TermElabM CollectLevelParams.State := do let type ← inferType fvar let type ← instantiateMVars type return collectLevelParams s type private def collectLevelParamsInFVars (fvars : Array Expr) (s : CollectLevelParams.State) : TermElabM CollectLevelParams.State := fvars.foldlM collectLevelParamsInFVar s private def collectLevelParamsInStructure (structType : Expr) (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Name) := do let s := collectLevelParams {} structType let s ← collectLevelParamsInFVars scopeVars s let s ← collectLevelParamsInFVars params s let s ← fieldInfos.foldlM (init := s) fun s info => collectLevelParamsInFVar s info.fvar return s.params private def addCtorFields (fieldInfos : Array StructFieldInfo) : Nat → Expr → TermElabM Expr | 0, type => pure type | i+1, type => do let info := fieldInfos[i] let decl ← Term.getFVarLocalDecl! info.fvar let type ← instantiateMVars type let type := type.abstract #[info.fvar] match info.kind with | StructFieldKind.fromParent => let val := decl.value addCtorFields fieldInfos i (type.instantiate1 val) | _ => addCtorFields fieldInfos i (mkForall decl.userName decl.binderInfo decl.type type) private def mkCtor (view : StructView) (levelParams : List Name) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM Constructor := withRef view.ref do let type := mkAppN (mkConst view.declName (levelParams.map mkLevelParam)) params let type ← addCtorFields fieldInfos fieldInfos.size type let type ← mkForallFVars params type let type ← instantiateMVars type let type := type.inferImplicit params.size !view.ctor.inferMod -- trace[Meta.debug] "ctor type {type}" pure { name := view.ctor.declName, type } @[extern "lean_mk_projections"] private constant mkProjections (env : Environment) (structName : Name) (projs : List ProjectionInfo) (isClass : Bool) : Except KernelException Environment private def addProjections (structName : Name) (projs : List ProjectionInfo) (isClass : Bool) : TermElabM Unit := do let env ← getEnv match mkProjections env structName projs isClass with | Except.ok env => setEnv env | Except.error ex => throwKernelException ex private def registerStructure (structName : Name) (infos : Array StructFieldInfo) : TermElabM Unit := do let fields ← infos.filterMapM fun info => do if info.kind == StructFieldKind.fromParent then return none else return some { fieldName := info.name projFn := info.declName inferMod := info.inferMod binderInfo := (← getFVarLocalDecl info.fvar).binderInfo subobject? := if info.kind == StructFieldKind.subobject then match (← getEnv).find? info.declName with | some (ConstantInfo.defnInfo val) => match val.type.getForallBody.getAppFn with | Expr.const parentName .. => some parentName | _ => panic! "ill-formed structure" | _ => panic! "ill-formed environment" else none } modifyEnv fun env => Lean.registerStructure env { structName, fields } private def mkAuxConstructions (declName : Name) : TermElabM Unit := do let env ← getEnv let hasUnit := env.contains `PUnit let hasEq := env.contains `Eq let hasHEq := env.contains `HEq mkRecOn declName if hasUnit then mkCasesOn declName if hasUnit && hasEq && hasHEq then mkNoConfusion declName private def addDefaults (lctx : LocalContext) (defaultAuxDecls : Array (Name × Expr × Expr)) : TermElabM Unit := do let localInsts ← getLocalInstances withLCtx lctx localInsts do defaultAuxDecls.forM fun (declName, type, value) => do let value ← instantiateMVars value if value.hasExprMVar then throwError "invalid default value for field, it contains metavariables{indentExpr value}" /- The identity function is used as "marker". -/ let value ← mkId value discard <| mkAuxDefinition declName type value (zeta := true) setReducibleAttribute declName private partial def mkCoercionToCopiedParent (levelParams : List Name) (params : Array Expr) (view : StructView) (parentType : Expr) : MetaM Unit := do let env ← getEnv let structName := view.declName let sourceFieldNames := getStructureFieldsFlattened env structName let structType := mkAppN (Lean.mkConst structName (levelParams.map mkLevelParam)) params let Expr.const parentStructName us _ ← pure parentType.getAppFn | unreachable! let binfo := if view.isClass && isClass env parentStructName then BinderInfo.instImplicit else BinderInfo.default withLocalDecl `self binfo structType fun source => do let declType ← instantiateMVars (← mkForallFVars params (← mkForallFVars #[source] parentType)) let declType := declType.inferImplicit params.size true let rec copyFields (parentType : Expr) : MetaM Expr := do let Expr.const parentStructName us _ ← pure parentType.getAppFn | unreachable! let parentCtor := getStructureCtor env parentStructName let mut result := mkAppN (mkConst parentCtor.name us) parentType.getAppArgs for fieldName in getStructureFields env parentStructName do if sourceFieldNames.contains fieldName then let fieldVal ← mkProjection source fieldName result := mkApp result fieldVal else -- fieldInfo must be a field of `parentStructName` let some fieldInfo := getFieldInfo? env parentStructName fieldName | unreachable! if fieldInfo.subobject?.isNone then throwError "failed to build coercion to parent structure" let resultType ← whnfD (← inferType result) unless resultType.isForall do throwError "failed to build coercion to parent structure, unexpect type{indentExpr resultType}" let fieldVal ← copyFields resultType.bindingDomain! result := mkApp result fieldVal return result let declVal ← instantiateMVars (← mkLambdaFVars params (← mkLambdaFVars #[source] (← copyFields parentType))) let declName := structName ++ mkToParentName (← getStructureName parentType) fun n => !env.contains (structName ++ n) addAndCompile <| Declaration.defnDecl { name := declName levelParams := levelParams type := declType value := declVal hints := ReducibilityHints.abbrev safety := if view.modifiers.isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe } if binfo.isInstImplicit then addInstance declName AttributeKind.global (eval_prio default) else setReducibleAttribute declName private def elabStructureView (view : StructView) : TermElabM Unit := do view.fields.forM fun field => do if field.declName == view.ctor.declName then throwErrorAt field.ref "invalid field name '{field.name}', it is equal to structure constructor name" addAuxDeclarationRanges field.declName field.ref field.ref let numExplicitParams := view.params.size let type ← Term.elabType view.type unless validStructType type do throwErrorAt view.type "expected Type" withRef view.ref do withParents view fun fieldInfos copiedParents => do withFields view.fields fieldInfos fun fieldInfos => do Term.synthesizeSyntheticMVarsNoPostponing let u ← getResultUniverse type let inferLevel ← shouldInferResultUniverse u withUsed view.scopeVars view.params fieldInfos fun scopeVars => do let numParams := scopeVars.size + numExplicitParams let fieldInfos ← levelMVarToParam scopeVars view.params fieldInfos let type ← withRef view.ref do if inferLevel then updateResultingUniverse fieldInfos type else checkResultingUniverse (← getResultUniverse type) pure type trace[Elab.structure] "type: {type}" let usedLevelNames ← collectLevelParamsInStructure type scopeVars view.params fieldInfos match sortDeclLevelParams view.scopeLevelNames view.allUserLevelNames usedLevelNames with | Except.error msg => withRef view.ref <| throwError msg | Except.ok levelParams => let params := scopeVars ++ view.params let ctor ← mkCtor view levelParams params fieldInfos let type ← mkForallFVars params type let type ← instantiateMVars type let indType := { name := view.declName, type := type, ctors := [ctor] : InductiveType } let decl := Declaration.inductDecl levelParams params.size [indType] view.modifiers.isUnsafe Term.ensureNoUnassignedMVars decl addDecl decl let projInfos := (fieldInfos.filter fun (info : StructFieldInfo) => !info.isFromParent).toList.map fun (info : StructFieldInfo) => { declName := info.declName, inferMod := info.inferMod : ProjectionInfo } addProjections view.declName projInfos view.isClass registerStructure view.declName fieldInfos mkAuxConstructions view.declName let instParents ← fieldInfos.filterM fun info => do let decl ← Term.getFVarLocalDecl! info.fvar pure (info.isSubobject && decl.binderInfo.isInstImplicit) withSaveInfoContext do -- save new env Term.addTermInfo view.ref[1] (← mkConstWithLevelParams view.declName) (isBinder := true) if let some _ := view.ctor.ref[1].getPos? (originalOnly := true) then Term.addTermInfo view.ctor.ref[1] (← mkConstWithLevelParams view.ctor.declName) (isBinder := true) for field in view.fields do -- may not exist if overriding inherited field if (← getEnv).contains field.declName then Term.addTermInfo field.ref (← mkConstWithLevelParams field.declName) (isBinder := true) Term.applyAttributesAt view.declName view.modifiers.attrs AttributeApplicationTime.afterTypeChecking let projInstances := instParents.toList.map fun info => info.declName projInstances.forM fun declName => addInstance declName AttributeKind.global (eval_prio default) copiedParents.forM fun parent => mkCoercionToCopiedParent levelParams params view parent let lctx ← getLCtx let fieldsWithDefault := fieldInfos.filter fun info => info.value?.isSome let defaultAuxDecls ← fieldsWithDefault.mapM fun info => do let type ← inferType info.fvar pure (mkDefaultFnOfProjFn info.declName, type, info.value?.get!) /- The `lctx` and `defaultAuxDecls` are used to create the auxiliary "default value" declarations The parameters `params` for these definitions must be marked as implicit, and all others as explicit. -/ let lctx := params.foldl (init := lctx) fun (lctx : LocalContext) (p : Expr) => lctx.setBinderInfo p.fvarId! BinderInfo.implicit let lctx := fieldInfos.foldl (init := lctx) fun (lctx : LocalContext) (info : StructFieldInfo) => if info.isFromParent then lctx -- `fromParent` fields are elaborated as let-decls, and are zeta-expanded when creating "default value" auxiliary functions else lctx.setBinderInfo info.fvar.fvarId! BinderInfo.default addDefaults lctx defaultAuxDecls /- leading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> " := " >> optional structCtor >> structFields >> optDeriving where def «extends» := leading_parser " extends " >> sepBy1 termParser ", " def typeSpec := leading_parser " : " >> termParser def optType : Parser := optional typeSpec def structFields := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder) def structCtor := leading_parser try (declModifiers >> ident >> optional inferMod >> " :: ") -/ def elabStructure (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do checkValidInductiveModifier modifiers let isClass := stx[0].getKind == ``Parser.Command.classTk let modifiers := if isClass then modifiers.addAttribute { name := `class } else modifiers let declId := stx[1] let params := stx[2].getArgs let exts := stx[3] let parents := if exts.isNone then #[] else exts[0][1].getSepArgs let optType := stx[4] let derivingClassViews ← getOptDerivingClasses stx[6] let type ← if optType.isNone then `(Sort _) else pure optType[0][1] let declName ← runTermElabM none fun scopeVars => do let scopeLevelNames ← Term.getLevelNames let ⟨name, declName, allUserLevelNames⟩ ← Elab.expandDeclId (← getCurrNamespace) scopeLevelNames declId modifiers addDeclarationRanges declName stx Term.withDeclName declName do let ctor ← expandCtor stx modifiers declName let fields ← expandFields stx modifiers declName Term.withLevelNames allUserLevelNames <| Term.withAutoBoundImplicit <| Term.elabBinders params fun params => do Term.synthesizeSyntheticMVarsNoPostponing let params ← Term.addAutoBoundImplicits params let allUserLevelNames ← Term.getLevelNames elabStructureView { ref := stx modifiers scopeLevelNames allUserLevelNames declName isClass scopeVars params parents type ctor fields } unless isClass do mkSizeOfInstances declName mkInjectiveTheorems declName return declName derivingClassViews.forM fun view => view.applyHandlers #[declName] builtin_initialize registerTraceClass `Elab.structure end Lean.Elab.Command
with(StringTools): input := ">.>..v..v.>vvvvv..>>>.>vv>vv>.......vv.vvv..v..vv.>v...>>>>>>.v>.>..>v.>.>v..v.vv.>.>...v.v>....v..v.v>.....v....>.>..v>v>.........>.v..... .>>.v..>..>vv>vv..vv>....vv>.>.>.>v>>......>>v..vv>.>>>..>>.>v.v.>v>..........>>....v.v....>>>>>.vv.v.v>v.v>...>>.>vv.v..>v>.v>..v>..>>...> vv...>.>...>.>.v..>...>....>vv.vv.>..v.>>.>v...>.>>.v>v.v>..>....>.vv..>v..v>.>.>.>.>.v>.v>.....>vv..>...>>...>.vvv>.v......>v....v.>>.>.>. v>v>...>.>>.v>v.v....vv>..v.v..............v.>v..>..>..v.vvv...>...vv>.>v.>>>v.>>.v>>>>..v..v..>...>v..>vvv...>..>...v>v.v.vv..v.>.>vv.>>.. vv...>.v...v..v>.v..v....>...vv..>v>.>.>>>...>vv.vv...vv>>..>..>.>..........v..v.v.>.>...>.>v.v>.v..>vv....v.....>.v>..>>>>v.....>......v.. v>>..>>>v...>.>>...>>vv>...vvv>.v>..vv.>>..v.>vv.v..>>v>vvv.v.>v..>v>vvv..vv.>>v..v..v.....v.>.>>>vv.>...>>>>>..>vv>>>.v....vv...v.>.>vv... >v..>>v..>..>....>.>.v.>..>...v..>.>.>.>...v.>v>>>.vv>vvv.>>.v>.>v>.vv......v>.vv..>...v>>.v>...vv.v>.v>.>>..v>.v.v...>>>>>.v.v>.v.v....>.. .>>>.>..v>>>>>>>vv.v>>...>>>v..vvv>.....>.......>.v>.>>>..v.>>>.v.v>.>>....v.>.>>.v.v>v.v.v>>v>v.v.v.v>>>>v.v....v..v>...>.v.>.......vvv>.> ..v......v>v.>vvv.v.......>.....v>.....vvv..>...>v....>..>>..>.v.>..v.>>>...>vvv..vv>.>v>.vvv>.>......>>v.v>>v.v..v>vv.>v.>..>>v>>.v.vv.v.v >v...>.>..vv..vv.v.v>>..>>..v..v..>.>...>.vv..vv.>..>..v.v.vv.....v.....v>..>>>.v..v>vv>v..>...vv>>>.v.>>.v>....vv..vvvv..v>v.>>...v.>v.>.v .>..v.>v.>....>>.v>..>>.v..v....v..v..>v..v>>>v.v>...>..v>.>.>>>.>..v>...v.>.>..vvv..v>v>.vv.>v.v...>...vv..v>v.>>v>.>>.>>..vv>.v.v>v.>.v.. .v>>.>..>.>>..>..>.v.v.v>.>v...>.........v>>....>.vv>>v.>v>.............>.>v>v.v..>v...>.>v...v..v..v.v>>....v.>>.>v>..v>>.vv..v.v...v>..>. >v..vv..>..v.>>.vvv.v.>>>>vv.>v.>v.....>...v...>.v.......v>v.>vv...>v..vv.>.vv.>.v>>v>>v.v>.>....>.>>>>.........vv.>..v..>v.v.vv.v..>>v...> v.>.>>....>..>.>.v....vv.>>v>>...>..v..>>>>.v.>v>>..v>......v>v>>..v.v>..v.>>v..>.v>v.v.vvv>.>v.....v.>.>..v..>>.>..>.>v>..>.vv>v>>..>>v>>. v..>>.vv...>.v.>vvv>>>>.>vvv.v......>vv.>.>..v..v.v>>.>>>..vv..v>>..v>vvv>..>>.>v>v..>.v.>vv.v....>.......vv.v...v.v.v>>v.vv.>.>..>.>..v.v> vv>.v>...>.>>....>v.>..vv>..v.>.>>.v.v>...>>...v..v.vv>.vv....>...v>.vv.vv.v.>v.vv.v>>v.>>vv.v.>...vv.>v.......>>.>.vv>.>v>>.v>.v.>..vv.>.> .>....>...>v>.>>>..>vv...v>...v>...v>.>v>......>.>v>..v>.>..>v...>...v..>.vv..vvvv>...v.>v.v....vv..>.v..v.vv...>vv..>.v.vv.>>.v.v.>..v.... vvv>>v......v....>.>v....>.>vv....>.>.>>vv>......v>.v..>.v..vv...v>vvv.v>.....vv..>vvvv.v.>...>.>v>>vv>..vv.....>.>v..>v...>v>..v.>..v..... .v.>>..>>v>>>>>.v>.v>.>.v.>.vv....>.v..>v.v>>.v.v>vv..>....>....vv..v...v>vv>v>....>>.>.vv>.v>vv....v.v>..>>...vvv>v.......>.v>v.v..v...vv. .>.vvv>.....>.>v.v..vv...v.v.vv.>...v...>vv..v.>..>v..>v..vv.v........v>>..>.v...v.>..vvv>vv>.>v.>>..>.>....>.v>>>v>..>v.>>.v...v..v....v.v vv..vvv>.>v.v>>...>v.>.>>..vvv>>..>.v>>>>....v......vv>>>v.>...v..v>v..>>v..>>.v..v..v>>v.v..v.vv.vvvvv>.v.>....v..v.>.v.....>....>.....>.. .>.v.vv...v>...>.v.v.v.>.>..>.>v..>v...v.>>..v...>>v>v>vv..>..>.v.>.>.>>.....>>v.>v>>...>..>.>>..>.v>...>v.....>.v.>>..vv.v.v...v>.>.>..... .v>>vv>.v>.>vvvv....v>v>.v......v...>>>.>>.>..vvv..>....>>v>vv.>.>v>vv.>.v.v..v.v..>v>.v>v>.vv>v.>>v>...vv>.....>>v>v>v..v>..>.vv.>>.>...>. v.v.>.v....v>.v.v..>v>v.v.v>.vv>.......>vv..>>.vv>>vv.>..v>>.>vv>v>>..v..>v>>>>vvv>>..v..v>v>>v>...>.v..>>...>.>.v.v.vv.>v...v.>>.>.>.>.>>> >>>v.>.vv>.v.>.>v.>>.>..v>..>v>>..vv..>.>.v...v>.v.>...>>vvv>v>>>v>v>....>v..vv.>.v>...>.>>>.v>.v...v....>>v>v..>.>...>..>>>.v..>v..>v..>v> .v...v...>...v>.>..vv.>....vv....v...>...>>v..>.vv.>v.>.>.>.v.v>.v.>vv>.v>v.>....>..>..>.v...v..>>..vvv.v.>v>..>vv..>.>...v...vv.vv>...v.v. ..v.....v>>vv.v>v>vv.>>..vvv.>v..v>.......>>>.>...>..v>v.>>..v.vvv..>.>>.>v.>v..>>.vvv..vv....v>...v.>>...>>....>>......>.>>...>.v.>....v.> >.>......>..v>>vv>.v.v...v....v>..>.v>>>v....v..>>>>>....v......v>...>.>..>..>v.>>>>..>.v>>v>.....>.v.v.>..vv>>>.>v>..>.v>>>vvv..>...v..... v..>v>vv>.v>>.>>v>.v..>.>.v..v>>>>..>vv.v.v>vvvv>.>..v.vv>v...>v>>.v..>..>v.v.....>..vvv>.v...>.vv..>>>>>.v.v.vv.v>..v..>..>v.vv.>.v..>.v.> >..v...v>>>.>vvvv>..v.>....>vvvvv.>v.v>v>.>.>v>>>.v..>.vvv.>>..>v...>.v..>v>.v>vvv.>..>.v>v...>v>.v>...>.....>v>...v......v>.v.>>>...>.vv.. >...v.>v.v.>>.>..>.>vv.vv...>>v.>v.vv.>v.>..>.v>..v..v.v..v.........>>vvv.>...>vv.v.>vv>v>v.>>>vv>vv.>..>...>>.>.>>..>....>v.v..v..>...v.>> >v.>.....v....>.....>..v>v.>.v>>v>...>vv.>v.>v..v...v>v.v.>..>v>....vvvv..>.>.vv.>.>v.>v.v....v.v....>>.>..>.>>....v.>vv..vv..v......v>.>.> >.vv.v>v....vv>>.>v..>...>..>.>>...>>...v.>v>.....>..v..v.v..v>...v>vv..>.v>.v.v.....vvv..v>vv>.>>vv..>>v.>>.>.v.v..>.>>v.v.v>......>...>v. .v.>....>v..>>>..>...>v>>..>>..>.>v>.v.....v....v.v.>...>>>....v......vv.v.......v>.>>.v..>.>>.vv>v....>v.>....>...vvvv..>v>.v.v..>v.>v.>.. v>..v>>..>>>.>>>v..>.>.>>.>>....v.v..v.v.v...v>.>..v>..v>>v.>.>.>vv.....>>>..>>.......>.>.v.v..>.>...>v.vv.vvv....v>>vv>>v.>.vvv.>>vv...>vv >..>>>v>v..vvv>.v.>>..v.vv>..v.vv>>v......vv.v.>v>>v>.....>>.>>.>....v.vv>.>v......>>v.>>.v.>..v....>..v>.>v.>...v...........>..>v..v.>v.>> .v.>..v...v>...vv.>..>>.>>v...v...>..vv.....v......v..............>.v......>.>>v.>...>v..>v>...v.vv>..>v>>.>.v...>.v>vv..vv.>vv>..>.......> .vv...v..vvvv.>...>.......vv>.vv.>v.>.v..v>v..>>v..v.v..vv>>..>.vv..>>.>..>..v......>..v.v>vv>v..v.vv>vv.....>.....>v.v>>.........v>..vv>.> v.>..>vv>..>>v..v>.v.vv..>>...v....v..>>.v..v>v..>>.v...>.>>.>..v.>..>v>.>v.>v.v>..>v>>....v.>>v...v...>vvv....v>...>....v...>v>>.vvv.....> >>>>>>>.>>.v..v>..>.>.v.vv.>vvv......>v......>v>v.v.vv.v>.v.>........>v>.v...>....vvvv.>v..v...v......v>.v...>..>.>..>..>.v..>>..vv.v..>..> >..>.vv.v>.v..>.>v...>.>.v>vvv>.v...v...v>vvv.>....vvv>>.vv>......>.>..>.vv.v.v.v.v.v>v.........>v.>v>v..>>..vv.v>v.v.v.>>>v>...v>.>v.>v.>. .>>.>>..v>..v....>>..v>>v..>..>v..v.v..v..>v..>...>v.v.>>>v..vv.>>.v>v...v.....v.>v>..v>.v>>v.>.>..>>v....>>>.>vv..>vv..vv..>v>.>.v.>>vvv.. ..v.v>>..>v..>.>.>....v>>.v.v.v.....>..>....>v>>.>....>.>v>>.....v>..vv.>v.>..>v.....vv.>>>...>>.....>.>v...........>>....>..v>....v..vv>v. vv>...>>..vv..v.v..>>.v.>vvv.>.v>v>v.>>>>...>v.v>...>v>..v.>..v..v.>....v.>.>v>.>...v..>v..>v.v>..vv..>.>v.v>.v.v>.v.>>vv.>v>.v.v.>..>..v>. ...>>>...vv>v.v...>v.>>..v.>...v..vvv.v..v>vv>v.>v.>...v..>.>>.>v.>...v..v>.v>v>v>..>v.>.>>vvvv>>.v..vv......>.v.>>>v>.>.v>.v.>.vv..>>..... >>>..>vv.v.vv...>.>v..v.>.>>.v>v>>>v.v........v.v.v...>..v>>v......v>>>.v>v..v>...>>>.vv.>v..>>.vv>>v.v........>..>>>v.>.>..v>v>.vv...v..>v .v.>......>...>>.>.v..v>>v.>vv..vv.>..>>>....>.v.>....v.>..v......v.>>>.>v..v....vvvv.....v....>.v>>v...v..v>>..v>..>.>v>v..>.>....v>v.v>.. .>.>.vv.vv.....v.>..v>.>v.v.v....v..>>vv.v..vv.>..v...vvvvvv>.vv......>v.v..v.>v>.v..>>vv>..v>v.>>.v...v.....>v>..>>.v.>..>.>..>v.v>.vv>... ........v.>....vv.>..>vv>...vv.>.....>..v.>>v..>vv>>v>.......v.>>v...>vv>...vv.>...vv..v>.v.>...v.>>>>>..v..v>>v.>...>.>>>v>...v>.v..>..>.. >.v.>>.v......>...v.>>..>v...v.>.....>v....>>v>.>.>..v>>..v.v>.>..vvvv.v......>..v.v.>>.v..v....v.vvv.......vv>...v.v...v>v>>.>..v>.>>..... .v>.>>v.v>>.>>.......>>.>...v>>.>>v..>...>..vv.v...>vv....vvv.vv..>.v.>vv>.v>.>>..>.>....v>..v.v..v>.>...vvv.>v...v...>.v...>>vv>...v..>>.. ..>.....v.>v.v..v.>v.>v>>..>v.v.vv..v.v..v..v..v>..>.v...>..>v>.v.v>.v>>vv.v.vv>vv>v>...>...>>v.v>.>>v.v>....v..vv..>>>>>.>.>..>v..>>...>>> >>>.>.>.v.v>.>v>..v....v.v.v.v.>.vv>...v.>v.>..v..>.>...v.....v>v.>vvvvvvv...>>>..>.>..vv.v.>vv.>.v.>>>.v>>.>.v.>.vvv>v.>>.v.v.v.........vv .>.v.vv.vv.>v...v.>..v>>>v...v..>..v.>v.v.>>.v...v.v.vv.v...v...v>.>..v...>.>.vv..vv..vvvv>.v.>>..>v>>>>v..vv.>..v.v.v.>>......>.v....vv.vv >v....>vv>..vv..v..>.>..>v.vv.>....>>>...>>>.vvv>>v.v.v.>>.v>vvv>.>>.>..v.v>>>>....v>>.v>.v...>v....>>vvv.>v.....v.>v...v.>v..>>v..v..vv.v. vv>.v.v>.>v..>.>>vv.v>..vvvvv.......v>..>.vv.>v.v..v..>v>>>v>vvvvv>v.vv.>>.v..v......v>....v..>...v>v.>vv.v>.>v.v..>>.v..>>>v...>..v.v...>. v.>v..>....v.>>.>..vv..>v>v.>....>....>v.>.v.>>.v>..vv.>v.vvv.>.....>..>.>...>>>..vv>>v...>>..>vvv.>>..v>.vv...v...v..>>v..v>..>.v..vv....v >v>.>v.>>..vv......vv..v...>...vv....>>....>.v..>vvv>..>.vv.vv>>v.>v>.>.v..v>v...v>>..>>>.>...vv..v.>>>...>.v.v>..vv.>v>......v..>v>.>..v.. .v>.>...vv>vv.>v...>..>v.>v....>..>v>v.>.vv>..v.>v.>v.v>.vv.>>v.....>.vv..v....>vv.>.v.>>vv.v...>..>>v>.>v.>...v.v..>.>......vvvvv...v.v>.> v..v>v...v>>v.v.>.>.>v.v>.>v>.vv.v.v.v..>vv..>.>v>.>v...>v>v.vv>>....>...>..vv.vv.vvvv.>....>>>v>.....>>vvvv.>.v...>vv..vv.>.>>.....>v..... ...>v....>.v>..>.v>..v>v..>...>.>..v....>>>..>..vv.>.v>..>>v...v.v...v..v..v>v>....>>...vv.>>..>v.vvv>.....>.>v.v....>v..>.>v......>.v>>v>. v....vv.....>>v.vv.vv..>>...>v.>v>v...v>>..v>.v>>>v.v.....>>vv>..v..v>.vv>v>v>..vv..>>...v...>v>....v>..v>.>.>>...>>>....>v.>.>.>.vvvvv.>v> v......>v..v...>>vv>>>.vvv.>>.vvv>..>..v>.>.>>..vv...v>v...>..>>....v........v...>>.v>...v..>.>>......>..>>...>v.v..>..>v.>>..>.>..v.v.>v.. .>>>>vv>...>.v...v.vvvv.>>>>>...v>>.vv.>..v>.v>>vv.v..vv>...>.v...v..>.v..>..v..v..v.v>..>>>v.v.v.......>v..>.v>>>v...>....>>v>>v>>>v>>.v>. ..v..v.....v..v>>vv>>.>>v>>...>>....>>.>.v>........>.>.>>.>....v.>v>..v.>v.v.vv>..>..v.>.v...>.>v.>..vv..>vv.>>..v....>.>v..v>.>>>vv......> >.v........v>..vv>.v..v.>>.vv>v>..>v.>v>.>v....vv.>..vv>>v..v.....v>..>v...>...>>vv.>>vv>>>v>.>.v...vv...vv...v..>v...v.>v.v>..>.v......>.. >>>...vv.v.>.v>>>.v.v..>>>.vvv>....v>>....v...v.v>>..>>.>....v..v..v.>v..>..>...>.vv.>.v.v..>v>.v..>......>>>..>>.....>.v>>..v..v.>...v.v>. .vv.v.>.v...>vvv>.....vv.vv>v>..v....v.>>.v..v>..>.v>.v.>..>>....>v.....>vvv.>v.....>.v>>..>>.>...v>>>.vv.v>v..>>.v>.v........>......v..>>> v>..>>.v...v>.>.v>..vv.>....v..>...>v.>.>..v>.>.>>.v..vv..vvv...v..vv.v>.v>..>....>v.>vvv.>>.v.>vvv...v..v>>.v.v.....>.>.>...>v.>v.>.vvv>>> .>>.v>.v..>...>.v.v...v>>.vvv..v>.>v.>>>>.v..>v..vv...>..>>>.>..>...>v>>v>..v....>>vvv..>.>....>.>v>.>.vv.v..>.v>>>>v>>v...v.>>>.v.vvv.>vvv .....v..v..>.>.>..>>.>.v>vvv.v.....>.v.>v...>v>v....>>>>..>>...v.>.>.....>..v.v.v.>v>.>..>v..>v...vv.>.v...v>>vvv...vv.v......v>.>>..>v>... >v..vv>.v..>v>..v.vv.>>.>>v....vv>..v>>v.>.v>.>>v...>..>..v>>..>vv.....v>>v..>v>>>.>.>>.v>v...>v...v...>..v.v.v>....>.>v.>.v...vv.v>>.vvv.v ...>v>.>.>>.vv..>.>..v.>>v>v..v>>...vv>.v.v...>..v>>..vv....>v.v..>v>.>.>>.......v...>v>.>.v...v...>>.>>v.vv>v..>...vv>..v>.v..>.v>vvv>vvv> v.vv>..>>.....>>.>>v.vv>v.vv>...vvv...>..v>.v>.v>..>v.vv>.v.>..v.....>v..>v>.vv>.vv>>..>v..v...v>.v.v.v>>v.vv>..>.>v.>.vv>.>.>v>vv.>v.>>.>v >>..v>.>..v......>v.v>....>.v.....>>.v.>.v...vv>>...v>.v>..v..v>..>v.vv>>v>..>.v..>.....v>....vvv>v>...>..v.v..>vv..vv..v.v.v...>>.>>>....v v>...v>vvvv..vvvv.v....>v>...>v>>vv..>v.v.>>.>..>.v.>vv.>..v>>>.v>vv>>.>.v.........>.....>.....v.v>.>v.......>..v>..>..v.v.>v.>v.>vv.>v...> .v..vvv>.vvv>>...>..vvv...>>.....v>v..vv.>v...........v...v>.>.vvvv.....>vv..>v.v.>..v>v.>v.>>.>.v.>.>v>.>v.>>...>vv>v..>>v....v.>.>vv.>vv> .v>.v.....>vv.v..>.>v..>>..v.vv.>v.v>.vv>..vv.>....v...>..>..v>.>>...>>>....v..>..v..vv.>>>>>v.>..>.....vv>.....>v>.>..>>..vv.>..>..>v>.v.. >.>.>>>>..>.v.>.>.>..v.>.>>>..vv>.>vv..>.......>>v.v>.>.v>v.v.>.>.....v..>v..v.v.v.v>v........>v.>vv.v.v>>.v>..v>.v...vv...v.vv.vvv..v..... .v>.>....v.v..v..v...>>v>.......>.v>>v.vv.>.>..>.v>.>v..>>vvv.v.......>v...v..v>...v>>.v>v>>vvv....v...>.v>..v.v....v>.>>...>..v....vv.v>>v ...>>v.v.>v.>..>>...v>vvvv.>..>...>vv>.>..>v.v.v.>>....>>.v.>...>>>>.vv.>.vvv>v...vv.v>v>>v....v>.>..v..>>..v.........>v>.>>.v>>>.vv..v.... .v......v.v.v>>..v..>>.>v>>v>>..v>v.v>..v>...>>.>>..>v..vvvv..>......v....v.v..>>.v>v.>.>.v.vvvv>.....>v>.>..v>>..>...>vv..vvv>vv.........v ...>.vv..v.v..v..>>..vvv...>v..v..>>>..v..v.>..>..>v...>......>v.>>v...>v.>>>.>.v..v.v..>>.v.>>..v...vvv....>v>>..v..v>v.>...>.v.vv>v>..v.. >..>.>.vv.>.>.v..v..v.>v...>.>v....>>v.vvvvv>>v...>vv.v....>v...vv....v.v.......>..v.>.v.>..v..v..>>v.>>>v..v>.>vv...>...>v.>>.v.>vv..>>..> ..>.>.v>.v.v>v.>.>>.v...>....>>v>vv.vv>v..>v>>...>vvv.>.v..>>>>..v.>>.vv..>>..>v>..v>v..>>v>.vv.v.vv.....vv.v..>.>.v.v>>....v..>....v>v>>v. ..>.>.v.vvv..v.>>.>.>.>...>.>..>.>>..v>..>v.v.....>.vv...vv..>>>..v>>.v.>..>..v>..>...v>>vv...v..v..v>>.v.v.v>v.>.>>..>.>..>......v........ >....>...v..v..>...>vv>v.vv.>vv.v>.v.>.v....v.>......vv.>vv>.>v....>.v>.vv>>.>..>v...v.v....>>...>v.vv.v.....>v...v......>.>.>....>...>v>v> ..>vv...vv.>.>..v>.>.>>>..v.v>v>>.>vv.>.v.v.>..>>....vv.....>vv.vvv.>>>vv.vv..v>.>.>..v>.v.>>...>>v..>v.>>.v......vv>>.>>v.>.>.>>.>.v...>.> >..v>>.v>..v.v.>.vv.>...v....>...>..vvvvvv........v.vv>>.....v>.v...>.>>...vv..>...>>....v>.....>>.v....>v.v...v..v..>.vvv.>v...v.v>v.>...> .>.vv.>..>>..>.v>..vv.vv.v>v.>.v.>....>..vv.>.>..>v..>..v.>>v..>vvv.>.>vvvvv..>.>...>>.v..v>v....>...>..>v.>...v....v>>v.v.v.v>v>.v.>.>...> >.>>v..>..>....>v>.v.v>.v.>.>..v>v.>v>>>.>>..v...>.v.vv>.>.....>.v.>...v.v.v>>>.v..>>v>...v>.>v....v.>>.vv>....>v>.vv...>v.>..v>v>v.>..v... v.v..>>v..v>>.vv>.>.v.>v...v....v.vv>..vv...>..v>..vvvv..v.v>v.vv....>.>.>....v>>..>vv.>..>v.>.>..>...v.>.>v>.v.>v>>>>>>v.v>.>v>.v...>..>.. >>..vv.>...v>.>.v.>v.>..vv>>vv>.v>v>...vv...v>.>.>>v...v>>vv.v.vv.....v....v>v........>v>v..>v.>>v...v>>..v..v.>>....v>....>vv>.v.>vv.>.v.. >..>>...>.v.vv>v..v>>>>.>v.vv....v...>v..>>vv>v...>..v.>v>>..v>.>>>.>....vv..v..vvv>v.....v.>.>v..vvv....>..vv....>>v..v.v...v.....>>v..... ...>.>..v>vv>....vv>v.v>>>..vv...>......>.....>..>...vv>..v>.>v>>.v..>>..vv>v.v..>.>.v..v.>v>>.v...v.v>v..v>v>v.>.v>v..v.v...>.>v>..>.....> v.v>.v.>.....>..>v....vvvv>>v>v>.>v.>vv.>.v....>v..v.v....v>vv..>...v....v..v....v>v>.>..>.v>.vv.v.vv..v>.v>.>v.>.>..>..>v......v..>v.v..vv v>.v>....>...>v..>v>..vv>....>v>v..>v...v..v>>...v>>...>v>..v.>v.v......vvv>.v.v.....v......v>v.>...v>.>.>.>>.v.>>>.v>...v..vvv>>....>v...> vv..v>v>..v...v.>>>vv..v...>.v...>..v..v.v>..>.vvv..>v..v.vv>v..>...>vvv>v>...>v>..v>..v>.v>>..>>..v>v.v.>v.v>....>..>v..>.v..v>>>v..>>.>v. v...>v>.>>vv>.vv....>.>>v.v>>v.v..v>>.vvv....>.>>.v>>........v.>v....v....v>.>.>v..>v....v>>v...>.>.>v.v.v.v.>...>>..v..>v.v>...vv.v>v...>v .>...>vv..>v..>.vv>.>.>v.>vv>v..>v.>..v>>vvvv.v>...v..>.>v.v.vv....>v...v............>vv.>.v>..>v...>>..v>.>.>...>.v.vv.v.>...>.>.>>v..vv.. ..>.>...>vvv>.....>>vv.>>v.>.>...vv>v.>.v...>.>.....>>..v....>..>..vvv.>vvvvv...>...>..v>v>vvv...>v>.....vvv.>>>.>.......>.......>v..v.v>.. v...>>vv..>>..vv..v>.>.......>.vv.>>>>..>.>v..>...>.v.vv..v.v.....v>v...>>.>..>....>>..>.v..v.>vv..v>..vv>.>.v>v.>..v.>.v.vv.>...>..>v.v>vv .v..vv>...vv.v>.vv.v.v...>v>.vvv..>>.>>v>>.>.vvvv.>...v>>>vv.>v>..>.>...>.v>.vv.v.>...v.......v.>.>v.v.v.>vv>...v.>.>...v..v>vv.>>.......>. >.>.....v.>>v.>v.>.>v.v>v>..>.>>v..v..v.v..>.....>.v>v.v.v>vv..v........>.>v...v>v..vv>v.vv.>vv.>v..v..>vv...>...vv.>.>.v>.>.vv.v>..v.vv.v. ...>v>.>>.>..vv...v.v.v..v..vv...>.v......v>.>>vv..v.>.>>>....v.v..vv.vv....>v>.>>.vv.v>.v.>....v.>>.vvv>v....v>v>.>v>.v.>vv.vv.>v>>>.>>..v .v..v.v>.>vv.vv.>>.v>v>v.>....>>.vv..v.>.vv.>...>>......v.>v>.v...v.>>v.v>vvvv>vvv.vv>..v>...v>>.vv.vvv>.>.v.v.>>vv>>>>v...vv>.v>v>v...>vv> .v>vv>>...>>....vvv>.......vvvv..>>>v>v..v......>..vvv.v>vv.>...>..>.v......>....v>.>v...v>>.vv>..v....>vv.>...>>.>>>.>vvv>>>>.v.>.v..>.v.v >.v>..v..v>..>....>>>v.vv>...>.>>>v.>v>.vv...v.>v...vv..>>>>.>>..v....v.......>.>.v.>.>v>>>..>....vv..>..>>.>v>.>..>v.>>v....v..>>>v.>vv>.. vv.v..v>>....v.>v>>.>>.>..>.v>v..>v..>vv......v>.v.v..>>.v>.v>vv>.>..>...>>.vvv>...v.v.....v.>vvv>.>.v>.>>.v.v.>v...>...>.....v.>>>>vv..v.. v.>>.>...>..>>.>>vv>>>...>v>v>>vv..v....>...vv.....>vv>.>>.v....vv>.>.>...>v..>.vv.vv.vv....>v>.>..v>....v>.>.vv.>.>>...>.v..v.>>v>>...vv.. v....>..>>..>>>>v.>..>vv..v>>....v>vv.v..>v.>v.v.>...>v....>v.>>>v>.>..>v.>>...v>>..vv.>vv>v>..>>v.>.v.>v........>v.v>.........>>..>>.v>v.> vv..v.>>>v>....vv..vv.v>>v.v...vvv>...vv>.>...>>>vv>>...>v.v>..>v....v.>v.v..v.>v>>>>.>v.v.vv.>>..v.....v...v>...>vv>.>vvvv>>.v..>.v..>v... >...v..vv.....v..>.>>...v..>..v.vv>>>>..>.>.>v.v>v...>v>>v.>>..>.vv.v.>>vv..vv.>>>.>v.>v.>>...>>>.>.>>.>...v>v...v>.>>.>>.v.vv.>.>>>.>>vvvv .vvv>.>v.>.....v>>.>.vvv.v.v..vv.v>.....vvv.vv........vv...>...>.v.v.>.....v.>.....v.>.v>>.v.....>v.v>.>...v>..>>.v.v.v.>..v>>>>.>...v>vv.v >>>>...>v..>vv>.>v...v..v>>v...v.v..v...>.>>..v>v.v.vv>.>v....v...v.v>.v>>v..v.v>v>...>vv>..>vv>>..vv>..>.>.>..>.v.>>>..>...v>..>.>.v.v>vvv >v>.>.>.v..vv.>v.vv>..v..v.....v>.>>>>..>v...v.>vvv.>.>>>.>>>.....v>.v..v.>.vv.v>..v..>vvvv..>vv.v>>>v.v>..v.v..v..>....>>>.>...v..>..v..>. .>..v>v>.v.vvv....>..v>..v...>.vv.>v..>.v.v>>..>>.v.v.v.>...>.>..v>v>.......>>.>>.>v...>>v>.v..>.>>>....v>>..v.>.>v...v>v>>v.>.v>...>.v>... ..>>>v.>....vvv..>.v...v.v>v>.v.vv>..>.>v.v.>vv.v..>....v...>v.v>........>v>vv.v.v.v..>v>....>.>...>....v.v.>>v...>v.>v.v>>>v.v.v>v...>>>.. >.vvv.v.v>vv.v..v>.>.>.vvvvv.>.vv>vv....v>>>v.>v..v.v.>>>.>>>.>.>>..v......>vv>...>v....>>>>......v>..v>vv..v...v>.>.v..>v.>..>>.v>.>...... ...v......vv.>.>...>v>vvv>>v>...v...>v...v.>....v.v...>vv..vv>v..>vv..v>.>.....v...v....>>...>v>v.vvv>..>>v.vvvvv...>>.v..>v.>.>v>..v>>.>>v ..v>.>..vv>v.>v.>>.>>>...v>vvv>v.v>>v>v>vv..vv...v......v..>.>.v..>.>.v.v.>>.>>>>...vvv..>>v>...v.>...>vv..vv>v.vv.>.v...>vv.>>>>>.>..v>v.> >.........>.v>.>...>.v>.....>>..v.......>.v>...>>v>.vvv.......vv.>...v.>.v>...>v>.....>...v.>>vvv....>vv>..v>.vvv>...>.v.v...>v.>.v.>.....v .v.>>>.vv>...>vv.>..vv..>v.>>.>..v.....v..>>>v..>..v>>.....>..v..vv.....v>......>v>vvv.vvv>>.>...v.>.v>.>v....>>>.......>..>>vv...>...>..>. ..>v>>...vv>.>>v.>.>.>vv.>>v...>..>v>..v>v>vv.v...>v>v.>..v>.v>>>.>...v>......v>..>v>v.v.>vv>v.>v.v..v.>..v..>.>v>>....v.>v>>vv>vv..>.....> .v.>.v>v>...>vv>.vv...vvv.v.v>>..v>>>>..>>...>.vvv....v...>...>..>.>..v...v....>...>>.vv....v.v.>vv>v.>.>..vv>>vv>v>>>v>.>v.v>>..v>.>v..v.. .>..v..........>.>.vv.vvv.>v...>.vv.v..>v........v..>>vv>..>.v.>..>.>..v..>..vv.v>>v.....>>vv>>.>v.....>...v...>.v.v>.v>..v..>.>.>v>>..>.>. .vv.>>>v.>.>...vv.v....>vv.>.v>>.v...v.>.>..>>>..>vv.>>..vvv.>....>>>..>v....vvv.>>.>.v>...>>...v.>..v...v.>>>.>>>..>>....vv.vvv.v...v..>.v v>.v>.>...v>vvv.vv.v..v.v.v>.>.vv.>.>...v>>.v..v>...>>.v.........v>>vvv.v>.v>v...v..v>>>.v.>.>>>>v.......>vv..vv..v.vv>>...>vv.v..v.v...... >>.v>..>.>.>>...>...v..v>.v...v.>.>.v..vv....v..v.v>.>>.>>>v....>.>.v.>>>v....v>.>......v>..>>>v.>..v..vv>.v>>....>v>v....>v.>.v..>....vvvv .vvv>>.v.>..vv..vvv......>.v>v.vv.>v>v.>>>..>v>...v.>.>vvvv......>vvv.v..>v.v..>v...v>>..>vv....v..v>v>....vv>..>.>....>....>v.vv.v>>.>>.v> >.vvvvv..>v>v.>..v>.v....v..>..v.vv.>v>>>v>>v....>v....>v.>v>...>>vv.>...>v..>....>.>.v..v.>.v>>...vv.>.v.v>>v....vvv..v>....v>v.>v.>.v..>. .v>.>v..>.v..>v.v...v.vv>....v.v>vv>.vvv>.>>.v.>v>>..>>>vvvv...>.>vv....v..v>.>.>...v.v>v>>..>v.v>v.v>>.>.v.>v>..v..>v>..>...>..>vvv>.v>..v >.>.vv>.>>.>v>v>>>.>.>.>v..v..vv...>..........v>vv.>v..>..v.>v..>..v>.v>......>.v...v..v.v.v..v..>>..v..v>...v>vv>v.>>v.>>..vv...v.v>vv.>v. ...>v..vv>v..>>.vv>>.v..v>>...>.vvvv>..v.>v...>..>v.v...v.>>>.v...>>..v.>>.>....>.v.vv..v>....vv.v..>..vv..>....vv.v.v>.......v.>v.vv.>v>.. .v.v...>v......vvv>..>.v..>>..v..>v..>..v.>.>>.>.>.vv..>...>..vvv.>..v....v>v.>>.>>...>......vvv.vv....>>....>v.v>v>>>vv.>..>v...v.v.>....> v.>.v>.>>>.v...>>.....v>...>v>>v..>..v....>>v.vv..>.v...>.>.>v..v.>.>..>v>>..v.>.>v>v>.>>.v.vvvv.v.>..>vv.....>>v....>.v.>>....>...>.v..vv. v.vvvvv.v.......>..v>.v>v...v.>>>..>..>>>>..v..v..v...>....vv>v.v>......>.....>>>...v...v>vv>v>>.v.>.v...v.v>.v.>v..>..v.......vvvv.v.>v.>.": testinput := "v...>>.vv> .vv>>.vv.. >>.>v>...v >>v>>.>.v. v>v.vv.v.. >.>>..v... .vv..>.>v. v.v..>>v.v ....v..v.>"; toyinput := "...>... ....... ......> v.....> ......> ....... ..vvv.."; grid := Matrix( (Explode~(Split(input, "\n"))) ): (gridl,gridw) := upperbound(grid); grid := Matrix( (Explode~(Split(input, "\n"))) ): updates := FAIL: gens := 1: PRINTF(cat("%s\n"$gridl,"\n"), seq(cat(seq(grid[i,j],j=1..gridw)),i=1..gridl)) : while updates <> 0 do updates := 0; updated := table(sparse=false): for i from 1 to gridl do for j from 1 to gridw do if not updated[i,j] and grid[i,j] = ">" and not updated[i,j mod gridw+1] and grid[i,j mod gridw+1] = "." then grid[i, j mod gridw +1] := ">"; grid[i, j] := "."; updated[i, j mod gridw+1] := true; updated[i,j] := true; updates += 1; end if; end do; end do; PRINTF(cat("%s\n"$gridl,"\n"), seq(cat(seq(grid[i,j],j=1..gridw)),i=1..gridl)); updated := table(sparse=false): for j from 1 to gridw do for i from 1 to gridl do # print([i,j]=grid[i,j],[(i mod 10)+1, j]); if not updated[i,j] and grid[i,j] = "v" and not updated[i mod gridl +1, j] and grid[i mod gridl+1,j] = "." then grid[i mod gridl +1, j] := "v"; grid[i, j] := "."; updated[i mod gridl +1, j] := true; updated[i,j] := true; updates += 1; end if; end do; end do; if updates = 0 then print(DONE); else PRINTF("After %d steps:\n",gens); PRINTF(cat("%s\n"$gridl,"\n"), seq(cat(seq(grid[i,j],j=1..gridw)),i=1..gridl)); gens += 1; end if; end do: printf(cat("%s\n"$gridl,"\n"), seq(cat(seq(grid[i,j],j=1..gridw)),i=1..gridl)); answer1 := gens;
theory Submission imports Defs begin lemma record_updates [simp]: "pc (update_pc st i l) = (pc st) (i := l)" "pc (update_x st i v) = pc st" "pc (update_y st i v) = pc st" "x (update_pc st i l) = x st" "x (update_x st i v) = (x st) (i := v)" "y (update_y st i v) = (y st) (i := v)" "y (update_pc st i l) = y st" "x (update_y st i v) = x st" "y (update_x st i v) = y st" by (simp_all add: update_pc_def update_x_def update_y_def) lemma x_assigned: assumes "reachable st" shows "\<forall>i. Proc i \<longrightarrow> pc st j \<noteq> assign_x \<longrightarrow> x st j = 1" using assms by induction auto lemma N_gt_0: "N > 0" using Proc_def proc_0 by auto theorem reachable_safe: "reachable st \<Longrightarrow> safe st" proof (induction rule: reachable.induct) case (y_step st i) show ?case proof (cases "Proc i") case True show ?thesis proof (cases "\<exists>j. Proc j \<and> j \<noteq> i \<and> pc st j \<noteq> finished") case True thus ?thesis by (auto simp: safe_def) next case False have "x st ((i + 1) mod N) = 1" proof - from y_step have "Proc ((i + 1) mod N)" using N_gt_0 by (simp add: Proc_def) moreover from this have "pc st ((i + 1) mod N) \<noteq> assign_x" using False y_step by auto ultimately show "x st ((i + 1) mod N) = 1" using x_assigned y_step by auto qed thus ?thesis using \<open>Proc i\<close> by (auto simp: safe_def) qed qed (use y_step in \<open>auto simp: safe_def\<close>) qed (use proc_0 in \<open>auto simp: safe_def\<close>) end
This topic contains 1 reply, has 2 voices. Last updated by Raam Dev 4 years, 11 months ago. I need a solution for a site I’m developing with S2 Members Pro, the issue is the clients run a chain of shops across the UK and a magazine that is subscribed from all over the world. The client wants its clients to be able to not only sign up online but also in store, the problem is my client will not accept the 0.01p charge on the checkout with a 100% discount code, this is because they feel there customers will not like having to pay online. I know you suggest 2 options on the plugin: 1 being a free registration form but this is open to abuse if the link gets leaked and will also require a lot of moderation on the admin side of things to make sure each sign up actually did join in store. 2 being a free trial, we can set the trial up to last a year but then the checkout will still require a form of payment to start running once the trial period has ended. Is there any solution to this problem? we need it to be as secure as it can without being open to abuse and easy to administrate. What is the best solution for this? Let us know if that answers your question.
{-# OPTIONS --sized-types #-} module SBList.Properties {A : Set}(_≤_ : A → A → Set) where open import Data.List open import List.Permutation.Base A open import SBList _≤_ lemma-unbound-bound : (xs : List A) → xs ∼ unbound (bound xs) lemma-unbound-bound [] = ∼[] lemma-unbound-bound (x ∷ xs) = ∼x /head /head (lemma-unbound-bound xs)
lemma CauchyD: "Cauchy X \<Longrightarrow> 0 < e \<Longrightarrow> \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. norm (X m - X n) < e" for X :: "nat \<Rightarrow> 'a::real_normed_vector"
[STATEMENT] lemma T_AE_iterates: assumes "AE x in M. P x" shows "AE x in M. \<forall>n. P ((T^^n) x)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. AE x in M. \<forall>n. P ((T ^^ n) x) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. AE x in M. \<forall>n. P ((T ^^ n) x) [PROOF STEP] have "AE x in M. P ((T^^n) x)" for n [PROOF STATE] proof (prove) goal (1 subgoal): 1. AE x in M. P ((T ^^ n) x) [PROOF STEP] by (rule quasi_measure_preserving_AE[OF Tn_quasi_measure_preserving[of n] assms]) [PROOF STATE] proof (state) this: AE x in M. P ((T ^^ ?n) x) goal (1 subgoal): 1. AE x in M. \<forall>n. P ((T ^^ n) x) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: AE x in M. P ((T ^^ ?n) x) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: AE x in M. P ((T ^^ ?n) x) goal (1 subgoal): 1. AE x in M. \<forall>n. P ((T ^^ n) x) [PROOF STEP] unfolding AE_all_countable [PROOF STATE] proof (prove) using this: AE x in M. P ((T ^^ ?n) x) goal (1 subgoal): 1. \<forall>n. AE x in M. P ((T ^^ n) x) [PROOF STEP] by simp [PROOF STATE] proof (state) this: AE x in M. \<forall>n. P ((T ^^ n) x) goal: No subgoals! [PROOF STEP] qed
lemma add_mul (a b t : mynat) : (a + b) * t = a * t + b * t := begin induction t with h hd, repeat {rw mul_zero}, refl, repeat {rw mul_succ}, rw hd, rw add_right_comm, rw add_assoc, rw add_assoc, rw add_comm (b * h), rw add_assoc, refl, end
If you enjoy cooking and preparing large quantities of food, then this is the course for you. Students rotate through learning stations, such as the bakeshop, cook station, salad/sandwich station, industrial ware washing, dining room, cash, and food service. Students also participate in catering preparation and set up for school functions. A fundamental understanding of catering service and customer service is stressed. Students also learn how to prepare main courses, soups, salads, sandwiches, and baked products. This course is a fundamental part of gaining an understanding of the Food and Beverage sector of the Tourism industry.
module Main import Effects import SQLite import CgiTypes -- We could also have SQLITE, or CGI here perhaps sampleHandler : Maybe String -> Maybe Int -> Maybe Int -> FormHandler [CGI (InitialisedCGI TaskRunning)] Bool sampleHandler (Just name) (Just age) (Just num) = ((output ("Your name is " ++ name ++ " and you are " ++ (show age) ++ " years old. You selected: " ++ (show num))) >>= (\_ pure True)) sampleHandler _ _ _ = output "There was an error processing input data." >>= (\_ => pure False) -- Effects.>>= : (EffM m xs xs' a) -> (a -> EffM m xs' xs'' b) -> EffM xs xs'' b -- addTextBox str >>= addTextBox int : EffM m [] [FormString] () -> EffM m [FormString] [FormInt, FormString] () -> EffM m [] [FormInt, FormString] myForm : UserForm myForm = do addTextBox FormString "Simon" addTextBox FormInt 21 addSelectionBox FormInt [1,2,3,4] ["One", "Two", "Three", "Four"] addSubmit sampleHandler [CgiEffect] FormBool --(addTextBox FormString "Simon") >>= ((\_ => addTextBox FormInt 21) >>= (\_ => addSubmit sampleHandler)) main : IO () main = do let ser_form = mkForm "myform" myForm putStrLn ser_form
module CellMapApplyTests using Test using CellwiseValues using TensorValues using ..CellValuesMocks using ..MapsMocks l = 10 a = VectorValue(10,10) b = VectorValue(15,20) p1 = VectorValue(1,1) p2 = VectorValue(2,2) p3 = VectorValue(3,3) p = [p1,p2,p3] m = MockMap(a) r = evaluate(m,p) cm = TestIterCellValue(m,l) cp = TestIterCellValue(p,l) rm = [ CachedArray(r) for i in 1:l] test_iter_cell_map(cm,cp,rm) cm2 = apply(-,cm,broadcast=true) rm = [ CachedArray(-r) for i in 1:l] test_iter_cell_map(cm2,cp,rm) cm = TestIndexCellValue(m,l) cp = TestIndexCellValue(p,l) rm = [ CachedArray(r) for i in 1:l] test_index_cell_map_with_index_arg(cm,cp,rm) ca2 = evaluate(cm,cp) test_index_cell_array(ca2,rm) end # module
(* Title: HOL/Limits.thy Author: Brian Huffman Author: Jacques D. Fleuriot, University of Cambridge Author: Lawrence C Paulson Author: Jeremy Avigad *) section \<open>Limits on Real Vector Spaces\<close> theory Limits imports Real_Vector_Spaces begin subsection \<open>Filter going to infinity norm\<close> definition at_infinity :: "'a::real_normed_vector filter" where "at_infinity = (INF r. principal {x. r \<le> norm x})" lemma eventually_at_infinity: "eventually P at_infinity \<longleftrightarrow> (\<exists>b. \<forall>x. b \<le> norm x \<longrightarrow> P x)" unfolding at_infinity_def by (subst eventually_INF_base) (auto simp: subset_eq eventually_principal intro!: exI[of _ "max a b" for a b]) corollary eventually_at_infinity_pos: "eventually p at_infinity \<longleftrightarrow> (\<exists>b. 0 < b \<and> (\<forall>x. norm x \<ge> b \<longrightarrow> p x))" unfolding eventually_at_infinity by (meson le_less_trans norm_ge_zero not_le zero_less_one) lemma at_infinity_eq_at_top_bot: "(at_infinity :: real filter) = sup at_top at_bot" proof - have 1: "\<lbrakk>\<forall>n\<ge>u. A n; \<forall>n\<le>v. A n\<rbrakk> \<Longrightarrow> \<exists>b. \<forall>x. b \<le> \<bar>x\<bar> \<longrightarrow> A x" for A and u v::real by (rule_tac x="max (- v) u" in exI) (auto simp: abs_real_def) have 2: "\<forall>x. u \<le> \<bar>x\<bar> \<longrightarrow> A x \<Longrightarrow> \<exists>N. \<forall>n\<ge>N. A n" for A and u::real by (meson abs_less_iff le_cases less_le_not_le) have 3: "\<forall>x. u \<le> \<bar>x\<bar> \<longrightarrow> A x \<Longrightarrow> \<exists>N. \<forall>n\<le>N. A n" for A and u::real by (metis (full_types) abs_ge_self abs_minus_cancel le_minus_iff order_trans) show ?thesis by (auto simp: filter_eq_iff eventually_sup eventually_at_infinity eventually_at_top_linorder eventually_at_bot_linorder intro: 1 2 3) qed lemma at_top_le_at_infinity: "at_top \<le> (at_infinity :: real filter)" unfolding at_infinity_eq_at_top_bot by simp lemma at_bot_le_at_infinity: "at_bot \<le> (at_infinity :: real filter)" unfolding at_infinity_eq_at_top_bot by simp lemma filterlim_at_top_imp_at_infinity: "filterlim f at_top F \<Longrightarrow> filterlim f at_infinity F" for f :: "_ \<Rightarrow> real" by (rule filterlim_mono[OF _ at_top_le_at_infinity order_refl]) lemma filterlim_real_at_infinity_sequentially: "filterlim real at_infinity sequentially" by (simp add: filterlim_at_top_imp_at_infinity filterlim_real_sequentially) lemma lim_infinity_imp_sequentially: "(f \<longlongrightarrow> l) at_infinity \<Longrightarrow> ((\<lambda>n. f(n)) \<longlongrightarrow> l) sequentially" by (simp add: filterlim_at_top_imp_at_infinity filterlim_compose filterlim_real_sequentially) subsubsection \<open>Boundedness\<close> definition Bfun :: "('a \<Rightarrow> 'b::metric_space) \<Rightarrow> 'a filter \<Rightarrow> bool" where Bfun_metric_def: "Bfun f F = (\<exists>y. \<exists>K>0. eventually (\<lambda>x. dist (f x) y \<le> K) F)" abbreviation Bseq :: "(nat \<Rightarrow> 'a::metric_space) \<Rightarrow> bool" where "Bseq X \<equiv> Bfun X sequentially" lemma Bseq_conv_Bfun: "Bseq X \<longleftrightarrow> Bfun X sequentially" .. lemma Bseq_ignore_initial_segment: "Bseq X \<Longrightarrow> Bseq (\<lambda>n. X (n + k))" unfolding Bfun_metric_def by (subst eventually_sequentially_seg) lemma Bseq_offset: "Bseq (\<lambda>n. X (n + k)) \<Longrightarrow> Bseq X" unfolding Bfun_metric_def by (subst (asm) eventually_sequentially_seg) lemma Bfun_def: "Bfun f F \<longleftrightarrow> (\<exists>K>0. eventually (\<lambda>x. norm (f x) \<le> K) F)" unfolding Bfun_metric_def norm_conv_dist proof safe fix y K assume K: "0 < K" and *: "eventually (\<lambda>x. dist (f x) y \<le> K) F" moreover have "eventually (\<lambda>x. dist (f x) 0 \<le> dist (f x) y + dist 0 y) F" by (intro always_eventually) (metis dist_commute dist_triangle) with * have "eventually (\<lambda>x. dist (f x) 0 \<le> K + dist 0 y) F" by eventually_elim auto with \<open>0 < K\<close> show "\<exists>K>0. eventually (\<lambda>x. dist (f x) 0 \<le> K) F" by (intro exI[of _ "K + dist 0 y"] add_pos_nonneg conjI zero_le_dist) auto qed (force simp del: norm_conv_dist [symmetric]) lemma BfunI: assumes K: "eventually (\<lambda>x. norm (f x) \<le> K) F" shows "Bfun f F" unfolding Bfun_def proof (intro exI conjI allI) show "0 < max K 1" by simp show "eventually (\<lambda>x. norm (f x) \<le> max K 1) F" using K by (rule eventually_mono) simp qed lemma BfunE: assumes "Bfun f F" obtains B where "0 < B" and "eventually (\<lambda>x. norm (f x) \<le> B) F" using assms unfolding Bfun_def by blast lemma Cauchy_Bseq: assumes "Cauchy X" shows "Bseq X" proof - have "\<exists>y K. 0 < K \<and> (\<exists>N. \<forall>n\<ge>N. dist (X n) y \<le> K)" if "\<And>m n. \<lbrakk>m \<ge> M; n \<ge> M\<rbrakk> \<Longrightarrow> dist (X m) (X n) < 1" for M by (meson order.order_iff_strict that zero_less_one) with assms show ?thesis by (force simp: Cauchy_def Bfun_metric_def eventually_sequentially) qed subsubsection \<open>Bounded Sequences\<close> lemma BseqI': "(\<And>n. norm (X n) \<le> K) \<Longrightarrow> Bseq X" by (intro BfunI) (auto simp: eventually_sequentially) lemma BseqI2': "\<forall>n\<ge>N. norm (X n) \<le> K \<Longrightarrow> Bseq X" by (intro BfunI) (auto simp: eventually_sequentially) lemma Bseq_def: "Bseq X \<longleftrightarrow> (\<exists>K>0. \<forall>n. norm (X n) \<le> K)" unfolding Bfun_def eventually_sequentially proof safe fix N K assume "0 < K" "\<forall>n\<ge>N. norm (X n) \<le> K" then show "\<exists>K>0. \<forall>n. norm (X n) \<le> K" by (intro exI[of _ "max (Max (norm ` X ` {..N})) K"] max.strict_coboundedI2) (auto intro!: imageI not_less[where 'a=nat, THEN iffD1] Max_ge simp: le_max_iff_disj) qed auto lemma BseqE: "Bseq X \<Longrightarrow> (\<And>K. 0 < K \<Longrightarrow> \<forall>n. norm (X n) \<le> K \<Longrightarrow> Q) \<Longrightarrow> Q" unfolding Bseq_def by auto lemma BseqD: "Bseq X \<Longrightarrow> \<exists>K. 0 < K \<and> (\<forall>n. norm (X n) \<le> K)" by (simp add: Bseq_def) lemma BseqI: "0 < K \<Longrightarrow> \<forall>n. norm (X n) \<le> K \<Longrightarrow> Bseq X" by (auto simp: Bseq_def) lemma Bseq_bdd_above: "Bseq X \<Longrightarrow> bdd_above (range X)" for X :: "nat \<Rightarrow> real" proof (elim BseqE, intro bdd_aboveI2) fix K n assume "0 < K" "\<forall>n. norm (X n) \<le> K" then show "X n \<le> K" by (auto elim!: allE[of _ n]) qed lemma Bseq_bdd_above': "Bseq X \<Longrightarrow> bdd_above (range (\<lambda>n. norm (X n)))" for X :: "nat \<Rightarrow> 'a :: real_normed_vector" proof (elim BseqE, intro bdd_aboveI2) fix K n assume "0 < K" "\<forall>n. norm (X n) \<le> K" then show "norm (X n) \<le> K" by (auto elim!: allE[of _ n]) qed lemma Bseq_bdd_below: "Bseq X \<Longrightarrow> bdd_below (range X)" for X :: "nat \<Rightarrow> real" proof (elim BseqE, intro bdd_belowI2) fix K n assume "0 < K" "\<forall>n. norm (X n) \<le> K" then show "- K \<le> X n" by (auto elim!: allE[of _ n]) qed lemma Bseq_eventually_mono: assumes "eventually (\<lambda>n. norm (f n) \<le> norm (g n)) sequentially" "Bseq g" shows "Bseq f" proof - from assms(2) obtain K where "0 < K" and "eventually (\<lambda>n. norm (g n) \<le> K) sequentially" unfolding Bfun_def by fast with assms(1) have "eventually (\<lambda>n. norm (f n) \<le> K) sequentially" by (fast elim: eventually_elim2 order_trans) with \<open>0 < K\<close> show "Bseq f" unfolding Bfun_def by fast qed lemma lemma_NBseq_def: "(\<exists>K > 0. \<forall>n. norm (X n) \<le> K) \<longleftrightarrow> (\<exists>N. \<forall>n. norm (X n) \<le> real(Suc N))" proof safe fix K :: real from reals_Archimedean2 obtain n :: nat where "K < real n" .. then have "K \<le> real (Suc n)" by auto moreover assume "\<forall>m. norm (X m) \<le> K" ultimately have "\<forall>m. norm (X m) \<le> real (Suc n)" by (blast intro: order_trans) then show "\<exists>N. \<forall>n. norm (X n) \<le> real (Suc N)" .. next show "\<And>N. \<forall>n. norm (X n) \<le> real (Suc N) \<Longrightarrow> \<exists>K>0. \<forall>n. norm (X n) \<le> K" using of_nat_0_less_iff by blast qed text \<open>Alternative definition for \<open>Bseq\<close>.\<close> lemma Bseq_iff: "Bseq X \<longleftrightarrow> (\<exists>N. \<forall>n. norm (X n) \<le> real(Suc N))" by (simp add: Bseq_def) (simp add: lemma_NBseq_def) lemma lemma_NBseq_def2: "(\<exists>K > 0. \<forall>n. norm (X n) \<le> K) = (\<exists>N. \<forall>n. norm (X n) < real(Suc N))" proof - have *: "\<And>N. \<forall>n. norm (X n) \<le> 1 + real N \<Longrightarrow> \<exists>N. \<forall>n. norm (X n) < 1 + real N" by (metis add.commute le_less_trans less_add_one of_nat_Suc) then show ?thesis unfolding lemma_NBseq_def by (metis less_le_not_le not_less_iff_gr_or_eq of_nat_Suc) qed text \<open>Yet another definition for Bseq.\<close> lemma Bseq_iff1a: "Bseq X \<longleftrightarrow> (\<exists>N. \<forall>n. norm (X n) < real (Suc N))" by (simp add: Bseq_def lemma_NBseq_def2) subsubsection \<open>A Few More Equivalence Theorems for Boundedness\<close> text \<open>Alternative formulation for boundedness.\<close> lemma Bseq_iff2: "Bseq X \<longleftrightarrow> (\<exists>k > 0. \<exists>x. \<forall>n. norm (X n + - x) \<le> k)" by (metis BseqE BseqI' add.commute add_cancel_right_left add_uminus_conv_diff norm_add_leD norm_minus_cancel norm_minus_commute) text \<open>Alternative formulation for boundedness.\<close> lemma Bseq_iff3: "Bseq X \<longleftrightarrow> (\<exists>k>0. \<exists>N. \<forall>n. norm (X n + - X N) \<le> k)" (is "?P \<longleftrightarrow> ?Q") proof assume ?P then obtain K where *: "0 < K" and **: "\<And>n. norm (X n) \<le> K" by (auto simp: Bseq_def) from * have "0 < K + norm (X 0)" by (rule order_less_le_trans) simp from ** have "\<forall>n. norm (X n - X 0) \<le> K + norm (X 0)" by (auto intro: order_trans norm_triangle_ineq4) then have "\<forall>n. norm (X n + - X 0) \<le> K + norm (X 0)" by simp with \<open>0 < K + norm (X 0)\<close> show ?Q by blast next assume ?Q then show ?P by (auto simp: Bseq_iff2) qed subsubsection \<open>Upper Bounds and Lubs of Bounded Sequences\<close> lemma Bseq_minus_iff: "Bseq (\<lambda>n. - (X n) :: 'a::real_normed_vector) \<longleftrightarrow> Bseq X" by (simp add: Bseq_def) lemma Bseq_add: fixes f :: "nat \<Rightarrow> 'a::real_normed_vector" assumes "Bseq f" shows "Bseq (\<lambda>x. f x + c)" proof - from assms obtain K where K: "\<And>x. norm (f x) \<le> K" unfolding Bseq_def by blast { fix x :: nat have "norm (f x + c) \<le> norm (f x) + norm c" by (rule norm_triangle_ineq) also have "norm (f x) \<le> K" by (rule K) finally have "norm (f x + c) \<le> K + norm c" by simp } then show ?thesis by (rule BseqI') qed lemma Bseq_add_iff: "Bseq (\<lambda>x. f x + c) \<longleftrightarrow> Bseq f" for f :: "nat \<Rightarrow> 'a::real_normed_vector" using Bseq_add[of f c] Bseq_add[of "\<lambda>x. f x + c" "-c"] by auto lemma Bseq_mult: fixes f g :: "nat \<Rightarrow> 'a::real_normed_field" assumes "Bseq f" and "Bseq g" shows "Bseq (\<lambda>x. f x * g x)" proof - from assms obtain K1 K2 where K: "norm (f x) \<le> K1" "K1 > 0" "norm (g x) \<le> K2" "K2 > 0" for x unfolding Bseq_def by blast then have "norm (f x * g x) \<le> K1 * K2" for x by (auto simp: norm_mult intro!: mult_mono) then show ?thesis by (rule BseqI') qed lemma Bfun_const [simp]: "Bfun (\<lambda>_. c) F" unfolding Bfun_metric_def by (auto intro!: exI[of _ c] exI[of _ "1::real"]) lemma Bseq_cmult_iff: fixes c :: "'a::real_normed_field" assumes "c \<noteq> 0" shows "Bseq (\<lambda>x. c * f x) \<longleftrightarrow> Bseq f" proof assume "Bseq (\<lambda>x. c * f x)" with Bfun_const have "Bseq (\<lambda>x. inverse c * (c * f x))" by (rule Bseq_mult) with \<open>c \<noteq> 0\<close> show "Bseq f" by (simp add: field_split_simps) qed (intro Bseq_mult Bfun_const) lemma Bseq_subseq: "Bseq f \<Longrightarrow> Bseq (\<lambda>x. f (g x))" for f :: "nat \<Rightarrow> 'a::real_normed_vector" unfolding Bseq_def by auto lemma Bseq_Suc_iff: "Bseq (\<lambda>n. f (Suc n)) \<longleftrightarrow> Bseq f" for f :: "nat \<Rightarrow> 'a::real_normed_vector" using Bseq_offset[of f 1] by (auto intro: Bseq_subseq) lemma increasing_Bseq_subseq_iff: assumes "\<And>x y. x \<le> y \<Longrightarrow> norm (f x :: 'a::real_normed_vector) \<le> norm (f y)" "strict_mono g" shows "Bseq (\<lambda>x. f (g x)) \<longleftrightarrow> Bseq f" proof assume "Bseq (\<lambda>x. f (g x))" then obtain K where K: "\<And>x. norm (f (g x)) \<le> K" unfolding Bseq_def by auto { fix x :: nat from filterlim_subseq[OF assms(2)] obtain y where "g y \<ge> x" by (auto simp: filterlim_at_top eventually_at_top_linorder) then have "norm (f x) \<le> norm (f (g y))" using assms(1) by blast also have "norm (f (g y)) \<le> K" by (rule K) finally have "norm (f x) \<le> K" . } then show "Bseq f" by (rule BseqI') qed (use Bseq_subseq[of f g] in simp_all) lemma nonneg_incseq_Bseq_subseq_iff: fixes f :: "nat \<Rightarrow> real" and g :: "nat \<Rightarrow> nat" assumes "\<And>x. f x \<ge> 0" "incseq f" "strict_mono g" shows "Bseq (\<lambda>x. f (g x)) \<longleftrightarrow> Bseq f" using assms by (intro increasing_Bseq_subseq_iff) (auto simp: incseq_def) lemma Bseq_eq_bounded: "range f \<subseteq> {a..b} \<Longrightarrow> Bseq f" for a b :: real proof (rule BseqI'[where K="max (norm a) (norm b)"]) fix n assume "range f \<subseteq> {a..b}" then have "f n \<in> {a..b}" by blast then show "norm (f n) \<le> max (norm a) (norm b)" by auto qed lemma incseq_bounded: "incseq X \<Longrightarrow> \<forall>i. X i \<le> B \<Longrightarrow> Bseq X" for B :: real by (intro Bseq_eq_bounded[of X "X 0" B]) (auto simp: incseq_def) lemma decseq_bounded: "decseq X \<Longrightarrow> \<forall>i. B \<le> X i \<Longrightarrow> Bseq X" for B :: real by (intro Bseq_eq_bounded[of X B "X 0"]) (auto simp: decseq_def) subsubsection\<^marker>\<open>tag unimportant\<close> \<open>Polynomal function extremal theorem, from HOL Light\<close> lemma polyfun_extremal_lemma: (*COMPLEX_POLYFUN_EXTREMAL_LEMMA in HOL Light*) fixes c :: "nat \<Rightarrow> 'a::real_normed_div_algebra" assumes "0 < e" shows "\<exists>M. \<forall>z. M \<le> norm(z) \<longrightarrow> norm (\<Sum>i\<le>n. c(i) * z^i) \<le> e * norm(z) ^ (Suc n)" proof (induct n) case 0 with assms show ?case apply (rule_tac x="norm (c 0) / e" in exI) apply (auto simp: field_simps) done next case (Suc n) obtain M where M: "\<And>z. M \<le> norm z \<Longrightarrow> norm (\<Sum>i\<le>n. c i * z^i) \<le> e * norm z ^ Suc n" using Suc assms by blast show ?case proof (rule exI [where x= "max M (1 + norm(c(Suc n)) / e)"], clarsimp simp del: power_Suc) fix z::'a assume z1: "M \<le> norm z" and "1 + norm (c (Suc n)) / e \<le> norm z" then have z2: "e + norm (c (Suc n)) \<le> e * norm z" using assms by (simp add: field_simps) have "norm (\<Sum>i\<le>n. c i * z^i) \<le> e * norm z ^ Suc n" using M [OF z1] by simp then have "norm (\<Sum>i\<le>n. c i * z^i) + norm (c (Suc n) * z ^ Suc n) \<le> e * norm z ^ Suc n + norm (c (Suc n) * z ^ Suc n)" by simp then have "norm ((\<Sum>i\<le>n. c i * z^i) + c (Suc n) * z ^ Suc n) \<le> e * norm z ^ Suc n + norm (c (Suc n) * z ^ Suc n)" by (blast intro: norm_triangle_le elim: ) also have "... \<le> (e + norm (c (Suc n))) * norm z ^ Suc n" by (simp add: norm_power norm_mult algebra_simps) also have "... \<le> (e * norm z) * norm z ^ Suc n" by (metis z2 mult.commute mult_left_mono norm_ge_zero norm_power) finally show "norm ((\<Sum>i\<le>n. c i * z^i) + c (Suc n) * z ^ Suc n) \<le> e * norm z ^ Suc (Suc n)" by simp qed qed lemma polyfun_extremal: (*COMPLEX_POLYFUN_EXTREMAL in HOL Light*) fixes c :: "nat \<Rightarrow> 'a::real_normed_div_algebra" assumes k: "c k \<noteq> 0" "1\<le>k" and kn: "k\<le>n" shows "eventually (\<lambda>z. norm (\<Sum>i\<le>n. c(i) * z^i) \<ge> B) at_infinity" using kn proof (induction n) case 0 then show ?case using k by simp next case (Suc m) let ?even = ?case show ?even proof (cases "c (Suc m) = 0") case True then show ?even using Suc k by auto (metis antisym_conv less_eq_Suc_le not_le) next case False then obtain M where M: "\<And>z. M \<le> norm z \<Longrightarrow> norm (\<Sum>i\<le>m. c i * z^i) \<le> norm (c (Suc m)) / 2 * norm z ^ Suc m" using polyfun_extremal_lemma [of "norm(c (Suc m)) / 2" c m] Suc by auto have "\<exists>b. \<forall>z. b \<le> norm z \<longrightarrow> B \<le> norm (\<Sum>i\<le>Suc m. c i * z^i)" proof (rule exI [where x="max M (max 1 (\<bar>B\<bar> / (norm(c (Suc m)) / 2)))"], clarsimp simp del: power_Suc) fix z::'a assume z1: "M \<le> norm z" "1 \<le> norm z" and "\<bar>B\<bar> * 2 / norm (c (Suc m)) \<le> norm z" then have z2: "\<bar>B\<bar> \<le> norm (c (Suc m)) * norm z / 2" using False by (simp add: field_simps) have nz: "norm z \<le> norm z ^ Suc m" by (metis \<open>1 \<le> norm z\<close> One_nat_def less_eq_Suc_le power_increasing power_one_right zero_less_Suc) have *: "\<And>y x. norm (c (Suc m)) * norm z / 2 \<le> norm y - norm x \<Longrightarrow> B \<le> norm (x + y)" by (metis abs_le_iff add.commute norm_diff_ineq order_trans z2) have "norm z * norm (c (Suc m)) + 2 * norm (\<Sum>i\<le>m. c i * z^i) \<le> norm (c (Suc m)) * norm z + norm (c (Suc m)) * norm z ^ Suc m" using M [of z] Suc z1 by auto also have "... \<le> 2 * (norm (c (Suc m)) * norm z ^ Suc m)" using nz by (simp add: mult_mono del: power_Suc) finally show "B \<le> norm ((\<Sum>i\<le>m. c i * z^i) + c (Suc m) * z ^ Suc m)" using Suc.IH apply (auto simp: eventually_at_infinity) apply (rule *) apply (simp add: field_simps norm_mult norm_power) done qed then show ?even by (simp add: eventually_at_infinity) qed qed subsection \<open>Convergence to Zero\<close> definition Zfun :: "('a \<Rightarrow> 'b::real_normed_vector) \<Rightarrow> 'a filter \<Rightarrow> bool" where "Zfun f F = (\<forall>r>0. eventually (\<lambda>x. norm (f x) < r) F)" lemma ZfunI: "(\<And>r. 0 < r \<Longrightarrow> eventually (\<lambda>x. norm (f x) < r) F) \<Longrightarrow> Zfun f F" by (simp add: Zfun_def) lemma ZfunD: "Zfun f F \<Longrightarrow> 0 < r \<Longrightarrow> eventually (\<lambda>x. norm (f x) < r) F" by (simp add: Zfun_def) lemma Zfun_ssubst: "eventually (\<lambda>x. f x = g x) F \<Longrightarrow> Zfun g F \<Longrightarrow> Zfun f F" unfolding Zfun_def by (auto elim!: eventually_rev_mp) lemma Zfun_zero: "Zfun (\<lambda>x. 0) F" unfolding Zfun_def by simp lemma Zfun_norm_iff: "Zfun (\<lambda>x. norm (f x)) F = Zfun (\<lambda>x. f x) F" unfolding Zfun_def by simp lemma Zfun_imp_Zfun: assumes f: "Zfun f F" and g: "eventually (\<lambda>x. norm (g x) \<le> norm (f x) * K) F" shows "Zfun (\<lambda>x. g x) F" proof (cases "0 < K") case K: True show ?thesis proof (rule ZfunI) fix r :: real assume "0 < r" then have "0 < r / K" using K by simp then have "eventually (\<lambda>x. norm (f x) < r / K) F" using ZfunD [OF f] by blast with g show "eventually (\<lambda>x. norm (g x) < r) F" proof eventually_elim case (elim x) then have "norm (f x) * K < r" by (simp add: pos_less_divide_eq K) then show ?case by (simp add: order_le_less_trans [OF elim(1)]) qed qed next case False then have K: "K \<le> 0" by (simp only: not_less) show ?thesis proof (rule ZfunI) fix r :: real assume "0 < r" from g show "eventually (\<lambda>x. norm (g x) < r) F" proof eventually_elim case (elim x) also have "norm (f x) * K \<le> norm (f x) * 0" using K norm_ge_zero by (rule mult_left_mono) finally show ?case using \<open>0 < r\<close> by simp qed qed qed lemma Zfun_le: "Zfun g F \<Longrightarrow> \<forall>x. norm (f x) \<le> norm (g x) \<Longrightarrow> Zfun f F" by (erule Zfun_imp_Zfun [where K = 1]) simp lemma Zfun_add: assumes f: "Zfun f F" and g: "Zfun g F" shows "Zfun (\<lambda>x. f x + g x) F" proof (rule ZfunI) fix r :: real assume "0 < r" then have r: "0 < r / 2" by simp have "eventually (\<lambda>x. norm (f x) < r/2) F" using f r by (rule ZfunD) moreover have "eventually (\<lambda>x. norm (g x) < r/2) F" using g r by (rule ZfunD) ultimately show "eventually (\<lambda>x. norm (f x + g x) < r) F" proof eventually_elim case (elim x) have "norm (f x + g x) \<le> norm (f x) + norm (g x)" by (rule norm_triangle_ineq) also have "\<dots> < r/2 + r/2" using elim by (rule add_strict_mono) finally show ?case by simp qed qed lemma Zfun_minus: "Zfun f F \<Longrightarrow> Zfun (\<lambda>x. - f x) F" unfolding Zfun_def by simp lemma Zfun_diff: "Zfun f F \<Longrightarrow> Zfun g F \<Longrightarrow> Zfun (\<lambda>x. f x - g x) F" using Zfun_add [of f F "\<lambda>x. - g x"] by (simp add: Zfun_minus) lemma (in bounded_linear) Zfun: assumes g: "Zfun g F" shows "Zfun (\<lambda>x. f (g x)) F" proof - obtain K where "norm (f x) \<le> norm x * K" for x using bounded by blast then have "eventually (\<lambda>x. norm (f (g x)) \<le> norm (g x) * K) F" by simp with g show ?thesis by (rule Zfun_imp_Zfun) qed lemma (in bounded_bilinear) Zfun: assumes f: "Zfun f F" and g: "Zfun g F" shows "Zfun (\<lambda>x. f x ** g x) F" proof (rule ZfunI) fix r :: real assume r: "0 < r" obtain K where K: "0 < K" and norm_le: "norm (x ** y) \<le> norm x * norm y * K" for x y using pos_bounded by blast from K have K': "0 < inverse K" by (rule positive_imp_inverse_positive) have "eventually (\<lambda>x. norm (f x) < r) F" using f r by (rule ZfunD) moreover have "eventually (\<lambda>x. norm (g x) < inverse K) F" using g K' by (rule ZfunD) ultimately show "eventually (\<lambda>x. norm (f x ** g x) < r) F" proof eventually_elim case (elim x) have "norm (f x ** g x) \<le> norm (f x) * norm (g x) * K" by (rule norm_le) also have "norm (f x) * norm (g x) * K < r * inverse K * K" by (intro mult_strict_right_mono mult_strict_mono' norm_ge_zero elim K) also from K have "r * inverse K * K = r" by simp finally show ?case . qed qed lemma (in bounded_bilinear) Zfun_left: "Zfun f F \<Longrightarrow> Zfun (\<lambda>x. f x ** a) F" by (rule bounded_linear_left [THEN bounded_linear.Zfun]) lemma (in bounded_bilinear) Zfun_right: "Zfun f F \<Longrightarrow> Zfun (\<lambda>x. a ** f x) F" by (rule bounded_linear_right [THEN bounded_linear.Zfun]) lemmas Zfun_mult = bounded_bilinear.Zfun [OF bounded_bilinear_mult] lemmas Zfun_mult_right = bounded_bilinear.Zfun_right [OF bounded_bilinear_mult] lemmas Zfun_mult_left = bounded_bilinear.Zfun_left [OF bounded_bilinear_mult] lemma tendsto_Zfun_iff: "(f \<longlongrightarrow> a) F = Zfun (\<lambda>x. f x - a) F" by (simp only: tendsto_iff Zfun_def dist_norm) lemma tendsto_0_le: "(f \<longlongrightarrow> 0) F \<Longrightarrow> eventually (\<lambda>x. norm (g x) \<le> norm (f x) * K) F \<Longrightarrow> (g \<longlongrightarrow> 0) F" by (simp add: Zfun_imp_Zfun tendsto_Zfun_iff) subsubsection \<open>Distance and norms\<close> lemma tendsto_dist [tendsto_intros]: fixes l m :: "'a::metric_space" assumes f: "(f \<longlongrightarrow> l) F" and g: "(g \<longlongrightarrow> m) F" shows "((\<lambda>x. dist (f x) (g x)) \<longlongrightarrow> dist l m) F" proof (rule tendstoI) fix e :: real assume "0 < e" then have e2: "0 < e/2" by simp from tendstoD [OF f e2] tendstoD [OF g e2] show "eventually (\<lambda>x. dist (dist (f x) (g x)) (dist l m) < e) F" proof (eventually_elim) case (elim x) then show "dist (dist (f x) (g x)) (dist l m) < e" unfolding dist_real_def using dist_triangle2 [of "f x" "g x" "l"] and dist_triangle2 [of "g x" "l" "m"] and dist_triangle3 [of "l" "m" "f x"] and dist_triangle [of "f x" "m" "g x"] by arith qed qed lemma continuous_dist[continuous_intros]: fixes f g :: "_ \<Rightarrow> 'a :: metric_space" shows "continuous F f \<Longrightarrow> continuous F g \<Longrightarrow> continuous F (\<lambda>x. dist (f x) (g x))" unfolding continuous_def by (rule tendsto_dist) lemma continuous_on_dist[continuous_intros]: fixes f g :: "_ \<Rightarrow> 'a :: metric_space" shows "continuous_on s f \<Longrightarrow> continuous_on s g \<Longrightarrow> continuous_on s (\<lambda>x. dist (f x) (g x))" unfolding continuous_on_def by (auto intro: tendsto_dist) lemma continuous_at_dist: "isCont (dist a) b" using continuous_on_dist [OF continuous_on_const continuous_on_id] continuous_on_eq_continuous_within by blast lemma tendsto_norm [tendsto_intros]: "(f \<longlongrightarrow> a) F \<Longrightarrow> ((\<lambda>x. norm (f x)) \<longlongrightarrow> norm a) F" unfolding norm_conv_dist by (intro tendsto_intros) lemma continuous_norm [continuous_intros]: "continuous F f \<Longrightarrow> continuous F (\<lambda>x. norm (f x))" unfolding continuous_def by (rule tendsto_norm) lemma continuous_on_norm [continuous_intros]: "continuous_on s f \<Longrightarrow> continuous_on s (\<lambda>x. norm (f x))" unfolding continuous_on_def by (auto intro: tendsto_norm) lemma continuous_on_norm_id [continuous_intros]: "continuous_on S norm" by (intro continuous_on_id continuous_on_norm) lemma tendsto_norm_zero: "(f \<longlongrightarrow> 0) F \<Longrightarrow> ((\<lambda>x. norm (f x)) \<longlongrightarrow> 0) F" by (drule tendsto_norm) simp lemma tendsto_norm_zero_cancel: "((\<lambda>x. norm (f x)) \<longlongrightarrow> 0) F \<Longrightarrow> (f \<longlongrightarrow> 0) F" unfolding tendsto_iff dist_norm by simp lemma tendsto_norm_zero_iff: "((\<lambda>x. norm (f x)) \<longlongrightarrow> 0) F \<longleftrightarrow> (f \<longlongrightarrow> 0) F" unfolding tendsto_iff dist_norm by simp lemma tendsto_rabs [tendsto_intros]: "(f \<longlongrightarrow> l) F \<Longrightarrow> ((\<lambda>x. \<bar>f x\<bar>) \<longlongrightarrow> \<bar>l\<bar>) F" for l :: real by (fold real_norm_def) (rule tendsto_norm) lemma continuous_rabs [continuous_intros]: "continuous F f \<Longrightarrow> continuous F (\<lambda>x. \<bar>f x :: real\<bar>)" unfolding real_norm_def[symmetric] by (rule continuous_norm) lemma continuous_on_rabs [continuous_intros]: "continuous_on s f \<Longrightarrow> continuous_on s (\<lambda>x. \<bar>f x :: real\<bar>)" unfolding real_norm_def[symmetric] by (rule continuous_on_norm) lemma tendsto_rabs_zero: "(f \<longlongrightarrow> (0::real)) F \<Longrightarrow> ((\<lambda>x. \<bar>f x\<bar>) \<longlongrightarrow> 0) F" by (fold real_norm_def) (rule tendsto_norm_zero) lemma tendsto_rabs_zero_cancel: "((\<lambda>x. \<bar>f x\<bar>) \<longlongrightarrow> (0::real)) F \<Longrightarrow> (f \<longlongrightarrow> 0) F" by (fold real_norm_def) (rule tendsto_norm_zero_cancel) lemma tendsto_rabs_zero_iff: "((\<lambda>x. \<bar>f x\<bar>) \<longlongrightarrow> (0::real)) F \<longleftrightarrow> (f \<longlongrightarrow> 0) F" by (fold real_norm_def) (rule tendsto_norm_zero_iff) subsection \<open>Topological Monoid\<close> class topological_monoid_add = topological_space + monoid_add + assumes tendsto_add_Pair: "LIM x (nhds a \<times>\<^sub>F nhds b). fst x + snd x :> nhds (a + b)" class topological_comm_monoid_add = topological_monoid_add + comm_monoid_add lemma tendsto_add [tendsto_intros]: fixes a b :: "'a::topological_monoid_add" shows "(f \<longlongrightarrow> a) F \<Longrightarrow> (g \<longlongrightarrow> b) F \<Longrightarrow> ((\<lambda>x. f x + g x) \<longlongrightarrow> a + b) F" using filterlim_compose[OF tendsto_add_Pair, of "\<lambda>x. (f x, g x)" a b F] by (simp add: nhds_prod[symmetric] tendsto_Pair) lemma continuous_add [continuous_intros]: fixes f g :: "_ \<Rightarrow> 'b::topological_monoid_add" shows "continuous F f \<Longrightarrow> continuous F g \<Longrightarrow> continuous F (\<lambda>x. f x + g x)" unfolding continuous_def by (rule tendsto_add) lemma continuous_on_add [continuous_intros]: fixes f g :: "_ \<Rightarrow> 'b::topological_monoid_add" shows "continuous_on s f \<Longrightarrow> continuous_on s g \<Longrightarrow> continuous_on s (\<lambda>x. f x + g x)" unfolding continuous_on_def by (auto intro: tendsto_add) lemma tendsto_add_zero: fixes f g :: "_ \<Rightarrow> 'b::topological_monoid_add" shows "(f \<longlongrightarrow> 0) F \<Longrightarrow> (g \<longlongrightarrow> 0) F \<Longrightarrow> ((\<lambda>x. f x + g x) \<longlongrightarrow> 0) F" by (drule (1) tendsto_add) simp lemma tendsto_sum [tendsto_intros]: fixes f :: "'a \<Rightarrow> 'b \<Rightarrow> 'c::topological_comm_monoid_add" shows "(\<And>i. i \<in> I \<Longrightarrow> (f i \<longlongrightarrow> a i) F) \<Longrightarrow> ((\<lambda>x. \<Sum>i\<in>I. f i x) \<longlongrightarrow> (\<Sum>i\<in>I. a i)) F" by (induct I rule: infinite_finite_induct) (simp_all add: tendsto_add) lemma tendsto_null_sum: fixes f :: "'a \<Rightarrow> 'b \<Rightarrow> 'c::topological_comm_monoid_add" assumes "\<And>i. i \<in> I \<Longrightarrow> ((\<lambda>x. f x i) \<longlongrightarrow> 0) F" shows "((\<lambda>i. sum (f i) I) \<longlongrightarrow> 0) F" using tendsto_sum [of I "\<lambda>x y. f y x" "\<lambda>x. 0"] assms by simp lemma continuous_sum [continuous_intros]: fixes f :: "'a \<Rightarrow> 'b::t2_space \<Rightarrow> 'c::topological_comm_monoid_add" shows "(\<And>i. i \<in> I \<Longrightarrow> continuous F (f i)) \<Longrightarrow> continuous F (\<lambda>x. \<Sum>i\<in>I. f i x)" unfolding continuous_def by (rule tendsto_sum) lemma continuous_on_sum [continuous_intros]: fixes f :: "'a \<Rightarrow> 'b::topological_space \<Rightarrow> 'c::topological_comm_monoid_add" shows "(\<And>i. i \<in> I \<Longrightarrow> continuous_on S (f i)) \<Longrightarrow> continuous_on S (\<lambda>x. \<Sum>i\<in>I. f i x)" unfolding continuous_on_def by (auto intro: tendsto_sum) instance nat :: topological_comm_monoid_add by standard (simp add: nhds_discrete principal_prod_principal filterlim_principal eventually_principal) instance int :: topological_comm_monoid_add by standard (simp add: nhds_discrete principal_prod_principal filterlim_principal eventually_principal) subsubsection \<open>Topological group\<close> class topological_group_add = topological_monoid_add + group_add + assumes tendsto_uminus_nhds: "(uminus \<longlongrightarrow> - a) (nhds a)" begin lemma tendsto_minus [tendsto_intros]: "(f \<longlongrightarrow> a) F \<Longrightarrow> ((\<lambda>x. - f x) \<longlongrightarrow> - a) F" by (rule filterlim_compose[OF tendsto_uminus_nhds]) end class topological_ab_group_add = topological_group_add + ab_group_add instance topological_ab_group_add < topological_comm_monoid_add .. lemma continuous_minus [continuous_intros]: "continuous F f \<Longrightarrow> continuous F (\<lambda>x. - f x)" for f :: "'a::t2_space \<Rightarrow> 'b::topological_group_add" unfolding continuous_def by (rule tendsto_minus) lemma continuous_on_minus [continuous_intros]: "continuous_on s f \<Longrightarrow> continuous_on s (\<lambda>x. - f x)" for f :: "_ \<Rightarrow> 'b::topological_group_add" unfolding continuous_on_def by (auto intro: tendsto_minus) lemma tendsto_minus_cancel: "((\<lambda>x. - f x) \<longlongrightarrow> - a) F \<Longrightarrow> (f \<longlongrightarrow> a) F" for a :: "'a::topological_group_add" by (drule tendsto_minus) simp lemma tendsto_minus_cancel_left: "(f \<longlongrightarrow> - (y::_::topological_group_add)) F \<longleftrightarrow> ((\<lambda>x. - f x) \<longlongrightarrow> y) F" using tendsto_minus_cancel[of f "- y" F] tendsto_minus[of f "- y" F] by auto lemma tendsto_diff [tendsto_intros]: fixes a b :: "'a::topological_group_add" shows "(f \<longlongrightarrow> a) F \<Longrightarrow> (g \<longlongrightarrow> b) F \<Longrightarrow> ((\<lambda>x. f x - g x) \<longlongrightarrow> a - b) F" using tendsto_add [of f a F "\<lambda>x. - g x" "- b"] by (simp add: tendsto_minus) lemma continuous_diff [continuous_intros]: fixes f g :: "'a::t2_space \<Rightarrow> 'b::topological_group_add" shows "continuous F f \<Longrightarrow> continuous F g \<Longrightarrow> continuous F (\<lambda>x. f x - g x)" unfolding continuous_def by (rule tendsto_diff) lemma continuous_on_diff [continuous_intros]: fixes f g :: "_ \<Rightarrow> 'b::topological_group_add" shows "continuous_on s f \<Longrightarrow> continuous_on s g \<Longrightarrow> continuous_on s (\<lambda>x. f x - g x)" unfolding continuous_on_def by (auto intro: tendsto_diff) lemma continuous_on_op_minus: "continuous_on (s::'a::topological_group_add set) ((-) x)" by (rule continuous_intros | simp)+ instance real_normed_vector < topological_ab_group_add proof fix a b :: 'a show "((\<lambda>x. fst x + snd x) \<longlongrightarrow> a + b) (nhds a \<times>\<^sub>F nhds b)" unfolding tendsto_Zfun_iff add_diff_add using tendsto_fst[OF filterlim_ident, of "(a,b)"] tendsto_snd[OF filterlim_ident, of "(a,b)"] by (intro Zfun_add) (auto simp: tendsto_Zfun_iff[symmetric] nhds_prod[symmetric] intro!: tendsto_fst) show "(uminus \<longlongrightarrow> - a) (nhds a)" unfolding tendsto_Zfun_iff minus_diff_minus using filterlim_ident[of "nhds a"] by (intro Zfun_minus) (simp add: tendsto_Zfun_iff) qed lemmas real_tendsto_sandwich = tendsto_sandwich[where 'a=real] subsubsection \<open>Linear operators and multiplication\<close> lemma linear_times [simp]: "linear (\<lambda>x. c * x)" for c :: "'a::real_algebra" by (auto simp: linearI distrib_left) lemma (in bounded_linear) tendsto: "(g \<longlongrightarrow> a) F \<Longrightarrow> ((\<lambda>x. f (g x)) \<longlongrightarrow> f a) F" by (simp only: tendsto_Zfun_iff diff [symmetric] Zfun) lemma (in bounded_linear) continuous: "continuous F g \<Longrightarrow> continuous F (\<lambda>x. f (g x))" using tendsto[of g _ F] by (auto simp: continuous_def) lemma (in bounded_linear) continuous_on: "continuous_on s g \<Longrightarrow> continuous_on s (\<lambda>x. f (g x))" using tendsto[of g] by (auto simp: continuous_on_def) lemma (in bounded_linear) tendsto_zero: "(g \<longlongrightarrow> 0) F \<Longrightarrow> ((\<lambda>x. f (g x)) \<longlongrightarrow> 0) F" by (drule tendsto) (simp only: zero) lemma (in bounded_bilinear) tendsto: "(f \<longlongrightarrow> a) F \<Longrightarrow> (g \<longlongrightarrow> b) F \<Longrightarrow> ((\<lambda>x. f x ** g x) \<longlongrightarrow> a ** b) F" by (simp only: tendsto_Zfun_iff prod_diff_prod Zfun_add Zfun Zfun_left Zfun_right) lemma (in bounded_bilinear) continuous: "continuous F f \<Longrightarrow> continuous F g \<Longrightarrow> continuous F (\<lambda>x. f x ** g x)" using tendsto[of f _ F g] by (auto simp: continuous_def) lemma (in bounded_bilinear) continuous_on: "continuous_on s f \<Longrightarrow> continuous_on s g \<Longrightarrow> continuous_on s (\<lambda>x. f x ** g x)" using tendsto[of f _ _ g] by (auto simp: continuous_on_def) lemma (in bounded_bilinear) tendsto_zero: assumes f: "(f \<longlongrightarrow> 0) F" and g: "(g \<longlongrightarrow> 0) F" shows "((\<lambda>x. f x ** g x) \<longlongrightarrow> 0) F" using tendsto [OF f g] by (simp add: zero_left) lemma (in bounded_bilinear) tendsto_left_zero: "(f \<longlongrightarrow> 0) F \<Longrightarrow> ((\<lambda>x. f x ** c) \<longlongrightarrow> 0) F" by (rule bounded_linear.tendsto_zero [OF bounded_linear_left]) lemma (in bounded_bilinear) tendsto_right_zero: "(f \<longlongrightarrow> 0) F \<Longrightarrow> ((\<lambda>x. c ** f x) \<longlongrightarrow> 0) F" by (rule bounded_linear.tendsto_zero [OF bounded_linear_right]) lemmas tendsto_of_real [tendsto_intros] = bounded_linear.tendsto [OF bounded_linear_of_real] lemmas tendsto_scaleR [tendsto_intros] = bounded_bilinear.tendsto [OF bounded_bilinear_scaleR] text\<open>Analogous type class for multiplication\<close> class topological_semigroup_mult = topological_space + semigroup_mult + assumes tendsto_mult_Pair: "LIM x (nhds a \<times>\<^sub>F nhds b). fst x * snd x :> nhds (a * b)" instance real_normed_algebra < topological_semigroup_mult proof fix a b :: 'a show "((\<lambda>x. fst x * snd x) \<longlongrightarrow> a * b) (nhds a \<times>\<^sub>F nhds b)" unfolding nhds_prod[symmetric] using tendsto_fst[OF filterlim_ident, of "(a,b)"] tendsto_snd[OF filterlim_ident, of "(a,b)"] by (simp add: bounded_bilinear.tendsto [OF bounded_bilinear_mult]) qed lemma tendsto_mult [tendsto_intros]: fixes a b :: "'a::topological_semigroup_mult" shows "(f \<longlongrightarrow> a) F \<Longrightarrow> (g \<longlongrightarrow> b) F \<Longrightarrow> ((\<lambda>x. f x * g x) \<longlongrightarrow> a * b) F" using filterlim_compose[OF tendsto_mult_Pair, of "\<lambda>x. (f x, g x)" a b F] by (simp add: nhds_prod[symmetric] tendsto_Pair) lemma tendsto_mult_left: "(f \<longlongrightarrow> l) F \<Longrightarrow> ((\<lambda>x. c * (f x)) \<longlongrightarrow> c * l) F" for c :: "'a::topological_semigroup_mult" by (rule tendsto_mult [OF tendsto_const]) lemma tendsto_mult_right: "(f \<longlongrightarrow> l) F \<Longrightarrow> ((\<lambda>x. (f x) * c) \<longlongrightarrow> l * c) F" for c :: "'a::topological_semigroup_mult" by (rule tendsto_mult [OF _ tendsto_const]) lemma tendsto_mult_left_iff [simp]: "c \<noteq> 0 \<Longrightarrow> tendsto(\<lambda>x. c * f x) (c * l) F \<longleftrightarrow> tendsto f l F" for c :: "'a::{topological_semigroup_mult,field}" by (auto simp: tendsto_mult_left dest: tendsto_mult_left [where c = "1/c"]) lemma tendsto_mult_right_iff [simp]: "c \<noteq> 0 \<Longrightarrow> tendsto(\<lambda>x. f x * c) (l * c) F \<longleftrightarrow> tendsto f l F" for c :: "'a::{topological_semigroup_mult,field}" by (auto simp: tendsto_mult_right dest: tendsto_mult_left [where c = "1/c"]) lemma tendsto_zero_mult_left_iff [simp]: fixes c::"'a::{topological_semigroup_mult,field}" assumes "c \<noteq> 0" shows "(\<lambda>n. c * a n)\<longlonglongrightarrow> 0 \<longleftrightarrow> a \<longlonglongrightarrow> 0" using assms tendsto_mult_left tendsto_mult_left_iff by fastforce lemma tendsto_zero_mult_right_iff [simp]: fixes c::"'a::{topological_semigroup_mult,field}" assumes "c \<noteq> 0" shows "(\<lambda>n. a n * c)\<longlonglongrightarrow> 0 \<longleftrightarrow> a \<longlonglongrightarrow> 0" using assms tendsto_mult_right tendsto_mult_right_iff by fastforce lemma tendsto_zero_divide_iff [simp]: fixes c::"'a::{topological_semigroup_mult,field}" assumes "c \<noteq> 0" shows "(\<lambda>n. a n / c)\<longlonglongrightarrow> 0 \<longleftrightarrow> a \<longlonglongrightarrow> 0" using tendsto_zero_mult_right_iff [of "1/c" a] assms by (simp add: field_simps) lemma lim_const_over_n [tendsto_intros]: fixes a :: "'a::real_normed_field" shows "(\<lambda>n. a / of_nat n) \<longlonglongrightarrow> 0" using tendsto_mult [OF tendsto_const [of a] lim_1_over_n] by simp lemmas continuous_of_real [continuous_intros] = bounded_linear.continuous [OF bounded_linear_of_real] lemmas continuous_scaleR [continuous_intros] = bounded_bilinear.continuous [OF bounded_bilinear_scaleR] lemmas continuous_mult [continuous_intros] = bounded_bilinear.continuous [OF bounded_bilinear_mult] lemmas continuous_on_of_real [continuous_intros] = bounded_linear.continuous_on [OF bounded_linear_of_real] lemmas continuous_on_scaleR [continuous_intros] = bounded_bilinear.continuous_on [OF bounded_bilinear_scaleR] lemmas continuous_on_mult [continuous_intros] = bounded_bilinear.continuous_on [OF bounded_bilinear_mult] lemmas tendsto_mult_zero = bounded_bilinear.tendsto_zero [OF bounded_bilinear_mult] lemmas tendsto_mult_left_zero = bounded_bilinear.tendsto_left_zero [OF bounded_bilinear_mult] lemmas tendsto_mult_right_zero = bounded_bilinear.tendsto_right_zero [OF bounded_bilinear_mult] lemma continuous_mult_left: fixes c::"'a::real_normed_algebra" shows "continuous F f \<Longrightarrow> continuous F (\<lambda>x. c * f x)" by (rule continuous_mult [OF continuous_const]) lemma continuous_mult_right: fixes c::"'a::real_normed_algebra" shows "continuous F f \<Longrightarrow> continuous F (\<lambda>x. f x * c)" by (rule continuous_mult [OF _ continuous_const]) lemma continuous_on_mult_left: fixes c::"'a::real_normed_algebra" shows "continuous_on s f \<Longrightarrow> continuous_on s (\<lambda>x. c * f x)" by (rule continuous_on_mult [OF continuous_on_const]) lemma continuous_on_mult_right: fixes c::"'a::real_normed_algebra" shows "continuous_on s f \<Longrightarrow> continuous_on s (\<lambda>x. f x * c)" by (rule continuous_on_mult [OF _ continuous_on_const]) lemma continuous_on_mult_const [simp]: fixes c::"'a::real_normed_algebra" shows "continuous_on s ((*) c)" by (intro continuous_on_mult_left continuous_on_id) lemma tendsto_divide_zero: fixes c :: "'a::real_normed_field" shows "(f \<longlongrightarrow> 0) F \<Longrightarrow> ((\<lambda>x. f x / c) \<longlongrightarrow> 0) F" by (cases "c=0") (simp_all add: divide_inverse tendsto_mult_left_zero) lemma tendsto_power [tendsto_intros]: "(f \<longlongrightarrow> a) F \<Longrightarrow> ((\<lambda>x. f x ^ n) \<longlongrightarrow> a ^ n) F" for f :: "'a \<Rightarrow> 'b::{power,real_normed_algebra}" by (induct n) (simp_all add: tendsto_mult) lemma tendsto_null_power: "\<lbrakk>(f \<longlongrightarrow> 0) F; 0 < n\<rbrakk> \<Longrightarrow> ((\<lambda>x. f x ^ n) \<longlongrightarrow> 0) F" for f :: "'a \<Rightarrow> 'b::{power,real_normed_algebra_1}" using tendsto_power [of f 0 F n] by (simp add: power_0_left) lemma continuous_power [continuous_intros]: "continuous F f \<Longrightarrow> continuous F (\<lambda>x. (f x)^n)" for f :: "'a::t2_space \<Rightarrow> 'b::{power,real_normed_algebra}" unfolding continuous_def by (rule tendsto_power) lemma continuous_on_power [continuous_intros]: fixes f :: "_ \<Rightarrow> 'b::{power,real_normed_algebra}" shows "continuous_on s f \<Longrightarrow> continuous_on s (\<lambda>x. (f x)^n)" unfolding continuous_on_def by (auto intro: tendsto_power) lemma tendsto_prod [tendsto_intros]: fixes f :: "'a \<Rightarrow> 'b \<Rightarrow> 'c::{real_normed_algebra,comm_ring_1}" shows "(\<And>i. i \<in> S \<Longrightarrow> (f i \<longlongrightarrow> L i) F) \<Longrightarrow> ((\<lambda>x. \<Prod>i\<in>S. f i x) \<longlongrightarrow> (\<Prod>i\<in>S. L i)) F" by (induct S rule: infinite_finite_induct) (simp_all add: tendsto_mult) lemma continuous_prod [continuous_intros]: fixes f :: "'a \<Rightarrow> 'b::t2_space \<Rightarrow> 'c::{real_normed_algebra,comm_ring_1}" shows "(\<And>i. i \<in> S \<Longrightarrow> continuous F (f i)) \<Longrightarrow> continuous F (\<lambda>x. \<Prod>i\<in>S. f i x)" unfolding continuous_def by (rule tendsto_prod) lemma continuous_on_prod [continuous_intros]: fixes f :: "'a \<Rightarrow> _ \<Rightarrow> 'c::{real_normed_algebra,comm_ring_1}" shows "(\<And>i. i \<in> S \<Longrightarrow> continuous_on s (f i)) \<Longrightarrow> continuous_on s (\<lambda>x. \<Prod>i\<in>S. f i x)" unfolding continuous_on_def by (auto intro: tendsto_prod) lemma tendsto_of_real_iff: "((\<lambda>x. of_real (f x) :: 'a::real_normed_div_algebra) \<longlongrightarrow> of_real c) F \<longleftrightarrow> (f \<longlongrightarrow> c) F" unfolding tendsto_iff by simp lemma tendsto_add_const_iff: "((\<lambda>x. c + f x :: 'a::real_normed_vector) \<longlongrightarrow> c + d) F \<longleftrightarrow> (f \<longlongrightarrow> d) F" using tendsto_add[OF tendsto_const[of c], of f d] and tendsto_add[OF tendsto_const[of "-c"], of "\<lambda>x. c + f x" "c + d"] by auto class topological_monoid_mult = topological_semigroup_mult + monoid_mult class topological_comm_monoid_mult = topological_monoid_mult + comm_monoid_mult lemma tendsto_power_strong [tendsto_intros]: fixes f :: "_ \<Rightarrow> 'b :: topological_monoid_mult" assumes "(f \<longlongrightarrow> a) F" "(g \<longlongrightarrow> b) F" shows "((\<lambda>x. f x ^ g x) \<longlongrightarrow> a ^ b) F" proof - have "((\<lambda>x. f x ^ b) \<longlongrightarrow> a ^ b) F" by (induction b) (auto intro: tendsto_intros assms) also from assms(2) have "eventually (\<lambda>x. g x = b) F" by (simp add: nhds_discrete filterlim_principal) hence "eventually (\<lambda>x. f x ^ b = f x ^ g x) F" by eventually_elim simp hence "((\<lambda>x. f x ^ b) \<longlongrightarrow> a ^ b) F \<longleftrightarrow> ((\<lambda>x. f x ^ g x) \<longlongrightarrow> a ^ b) F" by (intro filterlim_cong refl) finally show ?thesis . qed lemma continuous_mult' [continuous_intros]: fixes f g :: "_ \<Rightarrow> 'b::topological_semigroup_mult" shows "continuous F f \<Longrightarrow> continuous F g \<Longrightarrow> continuous F (\<lambda>x. f x * g x)" unfolding continuous_def by (rule tendsto_mult) lemma continuous_power' [continuous_intros]: fixes f :: "_ \<Rightarrow> 'b::topological_monoid_mult" shows "continuous F f \<Longrightarrow> continuous F g \<Longrightarrow> continuous F (\<lambda>x. f x ^ g x)" unfolding continuous_def by (rule tendsto_power_strong) auto lemma continuous_on_mult' [continuous_intros]: fixes f g :: "_ \<Rightarrow> 'b::topological_semigroup_mult" shows "continuous_on A f \<Longrightarrow> continuous_on A g \<Longrightarrow> continuous_on A (\<lambda>x. f x * g x)" unfolding continuous_on_def by (auto intro: tendsto_mult) lemma continuous_on_power' [continuous_intros]: fixes f :: "_ \<Rightarrow> 'b::topological_monoid_mult" shows "continuous_on A f \<Longrightarrow> continuous_on A g \<Longrightarrow> continuous_on A (\<lambda>x. f x ^ g x)" unfolding continuous_on_def by (auto intro: tendsto_power_strong) lemma tendsto_mult_one: fixes f g :: "_ \<Rightarrow> 'b::topological_monoid_mult" shows "(f \<longlongrightarrow> 1) F \<Longrightarrow> (g \<longlongrightarrow> 1) F \<Longrightarrow> ((\<lambda>x. f x * g x) \<longlongrightarrow> 1) F" by (drule (1) tendsto_mult) simp lemma tendsto_prod' [tendsto_intros]: fixes f :: "'a \<Rightarrow> 'b \<Rightarrow> 'c::topological_comm_monoid_mult" shows "(\<And>i. i \<in> I \<Longrightarrow> (f i \<longlongrightarrow> a i) F) \<Longrightarrow> ((\<lambda>x. \<Prod>i\<in>I. f i x) \<longlongrightarrow> (\<Prod>i\<in>I. a i)) F" by (induct I rule: infinite_finite_induct) (simp_all add: tendsto_mult) lemma tendsto_one_prod': fixes f :: "'a \<Rightarrow> 'b \<Rightarrow> 'c::topological_comm_monoid_mult" assumes "\<And>i. i \<in> I \<Longrightarrow> ((\<lambda>x. f x i) \<longlongrightarrow> 1) F" shows "((\<lambda>i. prod (f i) I) \<longlongrightarrow> 1) F" using tendsto_prod' [of I "\<lambda>x y. f y x" "\<lambda>x. 1"] assms by simp lemma continuous_prod' [continuous_intros]: fixes f :: "'a \<Rightarrow> 'b::t2_space \<Rightarrow> 'c::topological_comm_monoid_mult" shows "(\<And>i. i \<in> I \<Longrightarrow> continuous F (f i)) \<Longrightarrow> continuous F (\<lambda>x. \<Prod>i\<in>I. f i x)" unfolding continuous_def by (rule tendsto_prod') lemma continuous_on_prod' [continuous_intros]: fixes f :: "'a \<Rightarrow> 'b::topological_space \<Rightarrow> 'c::topological_comm_monoid_mult" shows "(\<And>i. i \<in> I \<Longrightarrow> continuous_on S (f i)) \<Longrightarrow> continuous_on S (\<lambda>x. \<Prod>i\<in>I. f i x)" unfolding continuous_on_def by (auto intro: tendsto_prod') instance nat :: topological_comm_monoid_mult by standard (simp add: nhds_discrete principal_prod_principal filterlim_principal eventually_principal) instance int :: topological_comm_monoid_mult by standard (simp add: nhds_discrete principal_prod_principal filterlim_principal eventually_principal) class comm_real_normed_algebra_1 = real_normed_algebra_1 + comm_monoid_mult context real_normed_field begin subclass comm_real_normed_algebra_1 proof from norm_mult[of "1 :: 'a" 1] show "norm 1 = 1" by simp qed (simp_all add: norm_mult) end subsubsection \<open>Inverse and division\<close> lemma (in bounded_bilinear) Zfun_prod_Bfun: assumes f: "Zfun f F" and g: "Bfun g F" shows "Zfun (\<lambda>x. f x ** g x) F" proof - obtain K where K: "0 \<le> K" and norm_le: "\<And>x y. norm (x ** y) \<le> norm x * norm y * K" using nonneg_bounded by blast obtain B where B: "0 < B" and norm_g: "eventually (\<lambda>x. norm (g x) \<le> B) F" using g by (rule BfunE) have "eventually (\<lambda>x. norm (f x ** g x) \<le> norm (f x) * (B * K)) F" using norm_g proof eventually_elim case (elim x) have "norm (f x ** g x) \<le> norm (f x) * norm (g x) * K" by (rule norm_le) also have "\<dots> \<le> norm (f x) * B * K" by (intro mult_mono' order_refl norm_g norm_ge_zero mult_nonneg_nonneg K elim) also have "\<dots> = norm (f x) * (B * K)" by (rule mult.assoc) finally show "norm (f x ** g x) \<le> norm (f x) * (B * K)" . qed with f show ?thesis by (rule Zfun_imp_Zfun) qed lemma (in bounded_bilinear) Bfun_prod_Zfun: assumes f: "Bfun f F" and g: "Zfun g F" shows "Zfun (\<lambda>x. f x ** g x) F" using flip g f by (rule bounded_bilinear.Zfun_prod_Bfun) lemma Bfun_inverse: fixes a :: "'a::real_normed_div_algebra" assumes f: "(f \<longlongrightarrow> a) F" assumes a: "a \<noteq> 0" shows "Bfun (\<lambda>x. inverse (f x)) F" proof - from a have "0 < norm a" by simp then have "\<exists>r>0. r < norm a" by (rule dense) then obtain r where r1: "0 < r" and r2: "r < norm a" by blast have "eventually (\<lambda>x. dist (f x) a < r) F" using tendstoD [OF f r1] by blast then have "eventually (\<lambda>x. norm (inverse (f x)) \<le> inverse (norm a - r)) F" proof eventually_elim case (elim x) then have 1: "norm (f x - a) < r" by (simp add: dist_norm) then have 2: "f x \<noteq> 0" using r2 by auto then have "norm (inverse (f x)) = inverse (norm (f x))" by (rule nonzero_norm_inverse) also have "\<dots> \<le> inverse (norm a - r)" proof (rule le_imp_inverse_le) show "0 < norm a - r" using r2 by simp have "norm a - norm (f x) \<le> norm (a - f x)" by (rule norm_triangle_ineq2) also have "\<dots> = norm (f x - a)" by (rule norm_minus_commute) also have "\<dots> < r" using 1 . finally show "norm a - r \<le> norm (f x)" by simp qed finally show "norm (inverse (f x)) \<le> inverse (norm a - r)" . qed then show ?thesis by (rule BfunI) qed lemma tendsto_inverse [tendsto_intros]: fixes a :: "'a::real_normed_div_algebra" assumes f: "(f \<longlongrightarrow> a) F" and a: "a \<noteq> 0" shows "((\<lambda>x. inverse (f x)) \<longlongrightarrow> inverse a) F" proof - from a have "0 < norm a" by simp with f have "eventually (\<lambda>x. dist (f x) a < norm a) F" by (rule tendstoD) then have "eventually (\<lambda>x. f x \<noteq> 0) F" unfolding dist_norm by (auto elim!: eventually_mono) with a have "eventually (\<lambda>x. inverse (f x) - inverse a = - (inverse (f x) * (f x - a) * inverse a)) F" by (auto elim!: eventually_mono simp: inverse_diff_inverse) moreover have "Zfun (\<lambda>x. - (inverse (f x) * (f x - a) * inverse a)) F" by (intro Zfun_minus Zfun_mult_left bounded_bilinear.Bfun_prod_Zfun [OF bounded_bilinear_mult] Bfun_inverse [OF f a] f [unfolded tendsto_Zfun_iff]) ultimately show ?thesis unfolding tendsto_Zfun_iff by (rule Zfun_ssubst) qed lemma continuous_inverse: fixes f :: "'a::t2_space \<Rightarrow> 'b::real_normed_div_algebra" assumes "continuous F f" and "f (Lim F (\<lambda>x. x)) \<noteq> 0" shows "continuous F (\<lambda>x. inverse (f x))" using assms unfolding continuous_def by (rule tendsto_inverse) lemma continuous_at_within_inverse[continuous_intros]: fixes f :: "'a::t2_space \<Rightarrow> 'b::real_normed_div_algebra" assumes "continuous (at a within s) f" and "f a \<noteq> 0" shows "continuous (at a within s) (\<lambda>x. inverse (f x))" using assms unfolding continuous_within by (rule tendsto_inverse) lemma continuous_on_inverse[continuous_intros]: fixes f :: "'a::topological_space \<Rightarrow> 'b::real_normed_div_algebra" assumes "continuous_on s f" and "\<forall>x\<in>s. f x \<noteq> 0" shows "continuous_on s (\<lambda>x. inverse (f x))" using assms unfolding continuous_on_def by (blast intro: tendsto_inverse) lemma tendsto_divide [tendsto_intros]: fixes a b :: "'a::real_normed_field" shows "(f \<longlongrightarrow> a) F \<Longrightarrow> (g \<longlongrightarrow> b) F \<Longrightarrow> b \<noteq> 0 \<Longrightarrow> ((\<lambda>x. f x / g x) \<longlongrightarrow> a / b) F" by (simp add: tendsto_mult tendsto_inverse divide_inverse) lemma continuous_divide: fixes f g :: "'a::t2_space \<Rightarrow> 'b::real_normed_field" assumes "continuous F f" and "continuous F g" and "g (Lim F (\<lambda>x. x)) \<noteq> 0" shows "continuous F (\<lambda>x. (f x) / (g x))" using assms unfolding continuous_def by (rule tendsto_divide) lemma continuous_at_within_divide[continuous_intros]: fixes f g :: "'a::t2_space \<Rightarrow> 'b::real_normed_field" assumes "continuous (at a within s) f" "continuous (at a within s) g" and "g a \<noteq> 0" shows "continuous (at a within s) (\<lambda>x. (f x) / (g x))" using assms unfolding continuous_within by (rule tendsto_divide) lemma isCont_divide[continuous_intros, simp]: fixes f g :: "'a::t2_space \<Rightarrow> 'b::real_normed_field" assumes "isCont f a" "isCont g a" "g a \<noteq> 0" shows "isCont (\<lambda>x. (f x) / g x) a" using assms unfolding continuous_at by (rule tendsto_divide) lemma continuous_on_divide[continuous_intros]: fixes f :: "'a::topological_space \<Rightarrow> 'b::real_normed_field" assumes "continuous_on s f" "continuous_on s g" and "\<forall>x\<in>s. g x \<noteq> 0" shows "continuous_on s (\<lambda>x. (f x) / (g x))" using assms unfolding continuous_on_def by (blast intro: tendsto_divide) lemma tendsto_power_int [tendsto_intros]: fixes a :: "'a::real_normed_div_algebra" assumes f: "(f \<longlongrightarrow> a) F" and a: "a \<noteq> 0" shows "((\<lambda>x. power_int (f x) n) \<longlongrightarrow> power_int a n) F" using assms by (cases n rule: int_cases4) (auto intro!: tendsto_intros simp: power_int_minus) lemma continuous_power_int: fixes f :: "'a::t2_space \<Rightarrow> 'b::real_normed_div_algebra" assumes "continuous F f" and "f (Lim F (\<lambda>x. x)) \<noteq> 0" shows "continuous F (\<lambda>x. power_int (f x) n)" using assms unfolding continuous_def by (rule tendsto_power_int) lemma continuous_at_within_power_int[continuous_intros]: fixes f :: "'a::t2_space \<Rightarrow> 'b::real_normed_div_algebra" assumes "continuous (at a within s) f" and "f a \<noteq> 0" shows "continuous (at a within s) (\<lambda>x. power_int (f x) n)" using assms unfolding continuous_within by (rule tendsto_power_int) lemma continuous_on_power_int [continuous_intros]: fixes f :: "'a::topological_space \<Rightarrow> 'b::real_normed_div_algebra" assumes "continuous_on s f" and "\<forall>x\<in>s. f x \<noteq> 0" shows "continuous_on s (\<lambda>x. power_int (f x) n)" using assms unfolding continuous_on_def by (blast intro: tendsto_power_int) lemma tendsto_sgn [tendsto_intros]: "(f \<longlongrightarrow> l) F \<Longrightarrow> l \<noteq> 0 \<Longrightarrow> ((\<lambda>x. sgn (f x)) \<longlongrightarrow> sgn l) F" for l :: "'a::real_normed_vector" unfolding sgn_div_norm by (simp add: tendsto_intros) lemma continuous_sgn: fixes f :: "'a::t2_space \<Rightarrow> 'b::real_normed_vector" assumes "continuous F f" and "f (Lim F (\<lambda>x. x)) \<noteq> 0" shows "continuous F (\<lambda>x. sgn (f x))" using assms unfolding continuous_def by (rule tendsto_sgn) lemma continuous_at_within_sgn[continuous_intros]: fixes f :: "'a::t2_space \<Rightarrow> 'b::real_normed_vector" assumes "continuous (at a within s) f" and "f a \<noteq> 0" shows "continuous (at a within s) (\<lambda>x. sgn (f x))" using assms unfolding continuous_within by (rule tendsto_sgn) lemma isCont_sgn[continuous_intros]: fixes f :: "'a::t2_space \<Rightarrow> 'b::real_normed_vector" assumes "isCont f a" and "f a \<noteq> 0" shows "isCont (\<lambda>x. sgn (f x)) a" using assms unfolding continuous_at by (rule tendsto_sgn) lemma continuous_on_sgn[continuous_intros]: fixes f :: "'a::topological_space \<Rightarrow> 'b::real_normed_vector" assumes "continuous_on s f" and "\<forall>x\<in>s. f x \<noteq> 0" shows "continuous_on s (\<lambda>x. sgn (f x))" using assms unfolding continuous_on_def by (blast intro: tendsto_sgn) lemma filterlim_at_infinity: fixes f :: "_ \<Rightarrow> 'a::real_normed_vector" assumes "0 \<le> c" shows "(LIM x F. f x :> at_infinity) \<longleftrightarrow> (\<forall>r>c. eventually (\<lambda>x. r \<le> norm (f x)) F)" unfolding filterlim_iff eventually_at_infinity proof safe fix P :: "'a \<Rightarrow> bool" fix b assume *: "\<forall>r>c. eventually (\<lambda>x. r \<le> norm (f x)) F" assume P: "\<forall>x. b \<le> norm x \<longrightarrow> P x" have "max b (c + 1) > c" by auto with * have "eventually (\<lambda>x. max b (c + 1) \<le> norm (f x)) F" by auto then show "eventually (\<lambda>x. P (f x)) F" proof eventually_elim case (elim x) with P show "P (f x)" by auto qed qed force lemma filterlim_at_infinity_imp_norm_at_top: fixes F assumes "filterlim f at_infinity F" shows "filterlim (\<lambda>x. norm (f x)) at_top F" proof - { fix r :: real have "\<forall>\<^sub>F x in F. r \<le> norm (f x)" using filterlim_at_infinity[of 0 f F] assms by (cases "r > 0") (auto simp: not_less intro: always_eventually order.trans[OF _ norm_ge_zero]) } thus ?thesis by (auto simp: filterlim_at_top) qed lemma filterlim_norm_at_top_imp_at_infinity: fixes F assumes "filterlim (\<lambda>x. norm (f x)) at_top F" shows "filterlim f at_infinity F" using filterlim_at_infinity[of 0 f F] assms by (auto simp: filterlim_at_top) lemma filterlim_norm_at_top: "filterlim norm at_top at_infinity" by (rule filterlim_at_infinity_imp_norm_at_top) (rule filterlim_ident) lemma filterlim_at_infinity_conv_norm_at_top: "filterlim f at_infinity G \<longleftrightarrow> filterlim (\<lambda>x. norm (f x)) at_top G" by (auto simp: filterlim_at_infinity[OF order.refl] filterlim_at_top_gt[of _ _ 0]) lemma eventually_not_equal_at_infinity: "eventually (\<lambda>x. x \<noteq> (a :: 'a :: {real_normed_vector})) at_infinity" proof - from filterlim_norm_at_top[where 'a = 'a] have "\<forall>\<^sub>F x in at_infinity. norm a < norm (x::'a)" by (auto simp: filterlim_at_top_dense) thus ?thesis by eventually_elim auto qed lemma filterlim_int_of_nat_at_topD: fixes F assumes "filterlim (\<lambda>x. f (int x)) F at_top" shows "filterlim f F at_top" proof - have "filterlim (\<lambda>x. f (int (nat x))) F at_top" by (rule filterlim_compose[OF assms filterlim_nat_sequentially]) also have "?this \<longleftrightarrow> filterlim f F at_top" by (intro filterlim_cong refl eventually_mono [OF eventually_ge_at_top[of "0::int"]]) auto finally show ?thesis . qed lemma filterlim_int_sequentially [tendsto_intros]: "filterlim int at_top sequentially" unfolding filterlim_at_top proof fix C :: int show "eventually (\<lambda>n. int n \<ge> C) at_top" using eventually_ge_at_top[of "nat \<lceil>C\<rceil>"] by eventually_elim linarith qed lemma filterlim_real_of_int_at_top [tendsto_intros]: "filterlim real_of_int at_top at_top" unfolding filterlim_at_top proof fix C :: real show "eventually (\<lambda>n. real_of_int n \<ge> C) at_top" using eventually_ge_at_top[of "\<lceil>C\<rceil>"] by eventually_elim linarith qed lemma filterlim_abs_real: "filterlim (abs::real \<Rightarrow> real) at_top at_top" proof (subst filterlim_cong[OF refl refl]) from eventually_ge_at_top[of "0::real"] show "eventually (\<lambda>x::real. \<bar>x\<bar> = x) at_top" by eventually_elim simp qed (simp_all add: filterlim_ident) lemma filterlim_of_real_at_infinity [tendsto_intros]: "filterlim (of_real :: real \<Rightarrow> 'a :: real_normed_algebra_1) at_infinity at_top" by (intro filterlim_norm_at_top_imp_at_infinity) (auto simp: filterlim_abs_real) lemma not_tendsto_and_filterlim_at_infinity: fixes c :: "'a::real_normed_vector" assumes "F \<noteq> bot" and "(f \<longlongrightarrow> c) F" and "filterlim f at_infinity F" shows False proof - from tendstoD[OF assms(2), of "1/2"] have "eventually (\<lambda>x. dist (f x) c < 1/2) F" by simp moreover from filterlim_at_infinity[of "norm c" f F] assms(3) have "eventually (\<lambda>x. norm (f x) \<ge> norm c + 1) F" by simp ultimately have "eventually (\<lambda>x. False) F" proof eventually_elim fix x assume A: "dist (f x) c < 1/2" assume "norm (f x) \<ge> norm c + 1" also have "norm (f x) = dist (f x) 0" by simp also have "\<dots> \<le> dist (f x) c + dist c 0" by (rule dist_triangle) finally show False using A by simp qed with assms show False by simp qed lemma filterlim_at_infinity_imp_not_convergent: assumes "filterlim f at_infinity sequentially" shows "\<not> convergent f" by (rule notI, rule not_tendsto_and_filterlim_at_infinity[OF _ _ assms]) (simp_all add: convergent_LIMSEQ_iff) lemma filterlim_at_infinity_imp_eventually_ne: assumes "filterlim f at_infinity F" shows "eventually (\<lambda>z. f z \<noteq> c) F" proof - have "norm c + 1 > 0" by (intro add_nonneg_pos) simp_all with filterlim_at_infinity[OF order.refl, of f F] assms have "eventually (\<lambda>z. norm (f z) \<ge> norm c + 1) F" by blast then show ?thesis by eventually_elim auto qed lemma tendsto_of_nat [tendsto_intros]: "filterlim (of_nat :: nat \<Rightarrow> 'a::real_normed_algebra_1) at_infinity sequentially" proof (subst filterlim_at_infinity[OF order.refl], intro allI impI) fix r :: real assume r: "r > 0" define n where "n = nat \<lceil>r\<rceil>" from r have n: "\<forall>m\<ge>n. of_nat m \<ge> r" unfolding n_def by linarith from eventually_ge_at_top[of n] show "eventually (\<lambda>m. norm (of_nat m :: 'a) \<ge> r) sequentially" by eventually_elim (use n in simp_all) qed subsection \<open>Relate \<^const>\<open>at\<close>, \<^const>\<open>at_left\<close> and \<^const>\<open>at_right\<close>\<close> text \<open> This lemmas are useful for conversion between \<^term>\<open>at x\<close> to \<^term>\<open>at_left x\<close> and \<^term>\<open>at_right x\<close> and also \<^term>\<open>at_right 0\<close>. \<close> lemmas filterlim_split_at_real = filterlim_split_at[where 'a=real] lemma filtermap_nhds_shift: "filtermap (\<lambda>x. x - d) (nhds a) = nhds (a - d)" for a d :: "'a::real_normed_vector" by (rule filtermap_fun_inverse[where g="\<lambda>x. x + d"]) (auto intro!: tendsto_eq_intros filterlim_ident) lemma filtermap_nhds_minus: "filtermap (\<lambda>x. - x) (nhds a) = nhds (- a)" for a :: "'a::real_normed_vector" by (rule filtermap_fun_inverse[where g=uminus]) (auto intro!: tendsto_eq_intros filterlim_ident) lemma filtermap_at_shift: "filtermap (\<lambda>x. x - d) (at a) = at (a - d)" for a d :: "'a::real_normed_vector" by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_shift[symmetric]) lemma filtermap_at_right_shift: "filtermap (\<lambda>x. x - d) (at_right a) = at_right (a - d)" for a d :: "real" by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_shift[symmetric]) lemma at_right_to_0: "at_right a = filtermap (\<lambda>x. x + a) (at_right 0)" for a :: real using filtermap_at_right_shift[of "-a" 0] by simp lemma filterlim_at_right_to_0: "filterlim f F (at_right a) \<longleftrightarrow> filterlim (\<lambda>x. f (x + a)) F (at_right 0)" for a :: real unfolding filterlim_def filtermap_filtermap at_right_to_0[of a] .. lemma eventually_at_right_to_0: "eventually P (at_right a) \<longleftrightarrow> eventually (\<lambda>x. P (x + a)) (at_right 0)" for a :: real unfolding at_right_to_0[of a] by (simp add: eventually_filtermap) lemma at_to_0: "at a = filtermap (\<lambda>x. x + a) (at 0)" for a :: "'a::real_normed_vector" using filtermap_at_shift[of "-a" 0] by simp lemma filterlim_at_to_0: "filterlim f F (at a) \<longleftrightarrow> filterlim (\<lambda>x. f (x + a)) F (at 0)" for a :: "'a::real_normed_vector" unfolding filterlim_def filtermap_filtermap at_to_0[of a] .. lemma eventually_at_to_0: "eventually P (at a) \<longleftrightarrow> eventually (\<lambda>x. P (x + a)) (at 0)" for a :: "'a::real_normed_vector" unfolding at_to_0[of a] by (simp add: eventually_filtermap) lemma filtermap_at_minus: "filtermap (\<lambda>x. - x) (at a) = at (- a)" for a :: "'a::real_normed_vector" by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_minus[symmetric]) lemma at_left_minus: "at_left a = filtermap (\<lambda>x. - x) (at_right (- a))" for a :: real by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_minus[symmetric]) lemma at_right_minus: "at_right a = filtermap (\<lambda>x. - x) (at_left (- a))" for a :: real by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_minus[symmetric]) lemma filterlim_at_left_to_right: "filterlim f F (at_left a) \<longleftrightarrow> filterlim (\<lambda>x. f (- x)) F (at_right (-a))" for a :: real unfolding filterlim_def filtermap_filtermap at_left_minus[of a] .. lemma eventually_at_left_to_right: "eventually P (at_left a) \<longleftrightarrow> eventually (\<lambda>x. P (- x)) (at_right (-a))" for a :: real unfolding at_left_minus[of a] by (simp add: eventually_filtermap) lemma filterlim_uminus_at_top_at_bot: "LIM x at_bot. - x :: real :> at_top" unfolding filterlim_at_top eventually_at_bot_dense by (metis leI minus_less_iff order_less_asym) lemma filterlim_uminus_at_bot_at_top: "LIM x at_top. - x :: real :> at_bot" unfolding filterlim_at_bot eventually_at_top_dense by (metis leI less_minus_iff order_less_asym) lemma at_bot_mirror : shows "(at_bot::('a::{ordered_ab_group_add,linorder} filter)) = filtermap uminus at_top" apply (rule filtermap_fun_inverse[of uminus, symmetric]) subgoal unfolding filterlim_at_top filterlim_at_bot eventually_at_bot_linorder using le_minus_iff by auto subgoal unfolding filterlim_at_bot eventually_at_top_linorder using minus_le_iff by auto by auto lemma at_top_mirror : shows "(at_top::('a::{ordered_ab_group_add,linorder} filter)) = filtermap uminus at_bot" apply (subst at_bot_mirror) by (auto simp: filtermap_filtermap) lemma filterlim_at_top_mirror: "(LIM x at_top. f x :> F) \<longleftrightarrow> (LIM x at_bot. f (-x::real) :> F)" unfolding filterlim_def at_top_mirror filtermap_filtermap .. lemma filterlim_at_bot_mirror: "(LIM x at_bot. f x :> F) \<longleftrightarrow> (LIM x at_top. f (-x::real) :> F)" unfolding filterlim_def at_bot_mirror filtermap_filtermap .. lemma filterlim_uminus_at_top: "(LIM x F. f x :> at_top) \<longleftrightarrow> (LIM x F. - (f x) :: real :> at_bot)" using filterlim_compose[OF filterlim_uminus_at_bot_at_top, of f F] and filterlim_compose[OF filterlim_uminus_at_top_at_bot, of "\<lambda>x. - f x" F] by auto lemma tendsto_at_botI_sequentially: fixes f :: "real \<Rightarrow> 'b::first_countable_topology" assumes *: "\<And>X. filterlim X at_bot sequentially \<Longrightarrow> (\<lambda>n. f (X n)) \<longlonglongrightarrow> y" shows "(f \<longlongrightarrow> y) at_bot" unfolding filterlim_at_bot_mirror proof (rule tendsto_at_topI_sequentially) fix X :: "nat \<Rightarrow> real" assume "filterlim X at_top sequentially" thus "(\<lambda>n. f (-X n)) \<longlonglongrightarrow> y" by (intro *) (auto simp: filterlim_uminus_at_top) qed lemma filterlim_at_infinity_imp_filterlim_at_top: assumes "filterlim (f :: 'a \<Rightarrow> real) at_infinity F" assumes "eventually (\<lambda>x. f x > 0) F" shows "filterlim f at_top F" proof - from assms(2) have *: "eventually (\<lambda>x. norm (f x) = f x) F" by eventually_elim simp from assms(1) show ?thesis unfolding filterlim_at_infinity_conv_norm_at_top by (subst (asm) filterlim_cong[OF refl refl *]) qed lemma filterlim_at_infinity_imp_filterlim_at_bot: assumes "filterlim (f :: 'a \<Rightarrow> real) at_infinity F" assumes "eventually (\<lambda>x. f x < 0) F" shows "filterlim f at_bot F" proof - from assms(2) have *: "eventually (\<lambda>x. norm (f x) = -f x) F" by eventually_elim simp from assms(1) have "filterlim (\<lambda>x. - f x) at_top F" unfolding filterlim_at_infinity_conv_norm_at_top by (subst (asm) filterlim_cong[OF refl refl *]) thus ?thesis by (simp add: filterlim_uminus_at_top) qed lemma filterlim_uminus_at_bot: "(LIM x F. f x :> at_bot) \<longleftrightarrow> (LIM x F. - (f x) :: real :> at_top)" unfolding filterlim_uminus_at_top by simp lemma filterlim_inverse_at_top_right: "LIM x at_right (0::real). inverse x :> at_top" unfolding filterlim_at_top_gt[where c=0] eventually_at_filter proof safe fix Z :: real assume [arith]: "0 < Z" then have "eventually (\<lambda>x. x < inverse Z) (nhds 0)" by (auto simp: eventually_nhds_metric dist_real_def intro!: exI[of _ "\<bar>inverse Z\<bar>"]) then show "eventually (\<lambda>x. x \<noteq> 0 \<longrightarrow> x \<in> {0<..} \<longrightarrow> Z \<le> inverse x) (nhds 0)" by (auto elim!: eventually_mono simp: inverse_eq_divide field_simps) qed lemma tendsto_inverse_0: fixes x :: "_ \<Rightarrow> 'a::real_normed_div_algebra" shows "(inverse \<longlongrightarrow> (0::'a)) at_infinity" unfolding tendsto_Zfun_iff diff_0_right Zfun_def eventually_at_infinity proof safe fix r :: real assume "0 < r" show "\<exists>b. \<forall>x. b \<le> norm x \<longrightarrow> norm (inverse x :: 'a) < r" proof (intro exI[of _ "inverse (r / 2)"] allI impI) fix x :: 'a from \<open>0 < r\<close> have "0 < inverse (r / 2)" by simp also assume *: "inverse (r / 2) \<le> norm x" finally show "norm (inverse x) < r" using * \<open>0 < r\<close> by (subst nonzero_norm_inverse) (simp_all add: inverse_eq_divide field_simps) qed qed lemma tendsto_add_filterlim_at_infinity: fixes c :: "'b::real_normed_vector" and F :: "'a filter" assumes "(f \<longlongrightarrow> c) F" and "filterlim g at_infinity F" shows "filterlim (\<lambda>x. f x + g x) at_infinity F" proof (subst filterlim_at_infinity[OF order_refl], safe) fix r :: real assume r: "r > 0" from assms(1) have "((\<lambda>x. norm (f x)) \<longlongrightarrow> norm c) F" by (rule tendsto_norm) then have "eventually (\<lambda>x. norm (f x) < norm c + 1) F" by (rule order_tendstoD) simp_all moreover from r have "r + norm c + 1 > 0" by (intro add_pos_nonneg) simp_all with assms(2) have "eventually (\<lambda>x. norm (g x) \<ge> r + norm c + 1) F" unfolding filterlim_at_infinity[OF order_refl] by (elim allE[of _ "r + norm c + 1"]) simp_all ultimately show "eventually (\<lambda>x. norm (f x + g x) \<ge> r) F" proof eventually_elim fix x :: 'a assume A: "norm (f x) < norm c + 1" and B: "r + norm c + 1 \<le> norm (g x)" from A B have "r \<le> norm (g x) - norm (f x)" by simp also have "norm (g x) - norm (f x) \<le> norm (g x + f x)" by (rule norm_diff_ineq) finally show "r \<le> norm (f x + g x)" by (simp add: add_ac) qed qed lemma tendsto_add_filterlim_at_infinity': fixes c :: "'b::real_normed_vector" and F :: "'a filter" assumes "filterlim f at_infinity F" and "(g \<longlongrightarrow> c) F" shows "filterlim (\<lambda>x. f x + g x) at_infinity F" by (subst add.commute) (rule tendsto_add_filterlim_at_infinity assms)+ lemma filterlim_inverse_at_right_top: "LIM x at_top. inverse x :> at_right (0::real)" unfolding filterlim_at by (auto simp: eventually_at_top_dense) (metis tendsto_inverse_0 filterlim_mono at_top_le_at_infinity order_refl) lemma filterlim_inverse_at_top: "(f \<longlongrightarrow> (0 :: real)) F \<Longrightarrow> eventually (\<lambda>x. 0 < f x) F \<Longrightarrow> LIM x F. inverse (f x) :> at_top" by (intro filterlim_compose[OF filterlim_inverse_at_top_right]) (simp add: filterlim_def eventually_filtermap eventually_mono at_within_def le_principal) lemma filterlim_inverse_at_bot_neg: "LIM x (at_left (0::real)). inverse x :> at_bot" by (simp add: filterlim_inverse_at_top_right filterlim_uminus_at_bot filterlim_at_left_to_right) lemma filterlim_inverse_at_bot: "(f \<longlongrightarrow> (0 :: real)) F \<Longrightarrow> eventually (\<lambda>x. f x < 0) F \<Longrightarrow> LIM x F. inverse (f x) :> at_bot" unfolding filterlim_uminus_at_bot inverse_minus_eq[symmetric] by (rule filterlim_inverse_at_top) (simp_all add: tendsto_minus_cancel_left[symmetric]) lemma at_right_to_top: "(at_right (0::real)) = filtermap inverse at_top" by (intro filtermap_fun_inverse[symmetric, where g=inverse]) (auto intro: filterlim_inverse_at_top_right filterlim_inverse_at_right_top) lemma eventually_at_right_to_top: "eventually P (at_right (0::real)) \<longleftrightarrow> eventually (\<lambda>x. P (inverse x)) at_top" unfolding at_right_to_top eventually_filtermap .. lemma filterlim_at_right_to_top: "filterlim f F (at_right (0::real)) \<longleftrightarrow> (LIM x at_top. f (inverse x) :> F)" unfolding filterlim_def at_right_to_top filtermap_filtermap .. lemma at_top_to_right: "at_top = filtermap inverse (at_right (0::real))" unfolding at_right_to_top filtermap_filtermap inverse_inverse_eq filtermap_ident .. lemma eventually_at_top_to_right: "eventually P at_top \<longleftrightarrow> eventually (\<lambda>x. P (inverse x)) (at_right (0::real))" unfolding at_top_to_right eventually_filtermap .. lemma filterlim_at_top_to_right: "filterlim f F at_top \<longleftrightarrow> (LIM x (at_right (0::real)). f (inverse x) :> F)" unfolding filterlim_def at_top_to_right filtermap_filtermap .. lemma filterlim_inverse_at_infinity: fixes x :: "_ \<Rightarrow> 'a::{real_normed_div_algebra, division_ring}" shows "filterlim inverse at_infinity (at (0::'a))" unfolding filterlim_at_infinity[OF order_refl] proof safe fix r :: real assume "0 < r" then show "eventually (\<lambda>x::'a. r \<le> norm (inverse x)) (at 0)" unfolding eventually_at norm_inverse by (intro exI[of _ "inverse r"]) (auto simp: norm_conv_dist[symmetric] field_simps inverse_eq_divide) qed lemma filterlim_inverse_at_iff: fixes g :: "'a \<Rightarrow> 'b::{real_normed_div_algebra, division_ring}" shows "(LIM x F. inverse (g x) :> at 0) \<longleftrightarrow> (LIM x F. g x :> at_infinity)" unfolding filterlim_def filtermap_filtermap[symmetric] proof assume "filtermap g F \<le> at_infinity" then have "filtermap inverse (filtermap g F) \<le> filtermap inverse at_infinity" by (rule filtermap_mono) also have "\<dots> \<le> at 0" using tendsto_inverse_0[where 'a='b] by (auto intro!: exI[of _ 1] simp: le_principal eventually_filtermap filterlim_def at_within_def eventually_at_infinity) finally show "filtermap inverse (filtermap g F) \<le> at 0" . next assume "filtermap inverse (filtermap g F) \<le> at 0" then have "filtermap inverse (filtermap inverse (filtermap g F)) \<le> filtermap inverse (at 0)" by (rule filtermap_mono) with filterlim_inverse_at_infinity show "filtermap g F \<le> at_infinity" by (auto intro: order_trans simp: filterlim_def filtermap_filtermap) qed lemma tendsto_mult_filterlim_at_infinity: fixes c :: "'a::real_normed_field" assumes "(f \<longlongrightarrow> c) F" "c \<noteq> 0" assumes "filterlim g at_infinity F" shows "filterlim (\<lambda>x. f x * g x) at_infinity F" proof - have "((\<lambda>x. inverse (f x) * inverse (g x)) \<longlongrightarrow> inverse c * 0) F" by (intro tendsto_mult tendsto_inverse assms filterlim_compose[OF tendsto_inverse_0]) then have "filterlim (\<lambda>x. inverse (f x) * inverse (g x)) (at (inverse c * 0)) F" unfolding filterlim_at using assms by (auto intro: filterlim_at_infinity_imp_eventually_ne tendsto_imp_eventually_ne eventually_conj) then show ?thesis by (subst filterlim_inverse_at_iff[symmetric]) simp_all qed lemma tendsto_inverse_0_at_top: "LIM x F. f x :> at_top \<Longrightarrow> ((\<lambda>x. inverse (f x) :: real) \<longlongrightarrow> 0) F" by (metis filterlim_at filterlim_mono[OF _ at_top_le_at_infinity order_refl] filterlim_inverse_at_iff) lemma real_tendsto_divide_at_top: fixes c::"real" assumes "(f \<longlongrightarrow> c) F" assumes "filterlim g at_top F" shows "((\<lambda>x. f x / g x) \<longlongrightarrow> 0) F" by (auto simp: divide_inverse_commute intro!: tendsto_mult[THEN tendsto_eq_rhs] tendsto_inverse_0_at_top assms) lemma mult_nat_left_at_top: "c > 0 \<Longrightarrow> filterlim (\<lambda>x. c * x) at_top sequentially" for c :: nat by (rule filterlim_subseq) (auto simp: strict_mono_def) lemma mult_nat_right_at_top: "c > 0 \<Longrightarrow> filterlim (\<lambda>x. x * c) at_top sequentially" for c :: nat by (rule filterlim_subseq) (auto simp: strict_mono_def) lemma filterlim_times_pos: "LIM x F1. c * f x :> at_right l" if "filterlim f (at_right p) F1" "0 < c" "l = c * p" for c::"'a::{linordered_field, linorder_topology}" unfolding filterlim_iff proof safe fix P assume "\<forall>\<^sub>F x in at_right l. P x" then obtain d where "c * p < d" "\<And>y. y > c * p \<Longrightarrow> y < d \<Longrightarrow> P y" unfolding \<open>l = _ \<close> eventually_at_right_field by auto then have "\<forall>\<^sub>F a in at_right p. P (c * a)" by (auto simp: eventually_at_right_field \<open>0 < c\<close> field_simps intro!: exI[where x="d/c"]) from that(1)[unfolded filterlim_iff, rule_format, OF this] show "\<forall>\<^sub>F x in F1. P (c * f x)" . qed lemma filtermap_nhds_times: "c \<noteq> 0 \<Longrightarrow> filtermap (times c) (nhds a) = nhds (c * a)" for a c :: "'a::real_normed_field" by (rule filtermap_fun_inverse[where g="\<lambda>x. inverse c * x"]) (auto intro!: tendsto_eq_intros filterlim_ident) lemma filtermap_times_pos_at_right: fixes c::"'a::{linordered_field, linorder_topology}" assumes "c > 0" shows "filtermap (times c) (at_right p) = at_right (c * p)" using assms by (intro filtermap_fun_inverse[where g="\<lambda>x. inverse c * x"]) (auto intro!: filterlim_ident filterlim_times_pos) lemma at_to_infinity: "(at (0::'a::{real_normed_field,field})) = filtermap inverse at_infinity" proof (rule antisym) have "(inverse \<longlongrightarrow> (0::'a)) at_infinity" by (fact tendsto_inverse_0) then show "filtermap inverse at_infinity \<le> at (0::'a)" using filterlim_def filterlim_ident filterlim_inverse_at_iff by fastforce next have "filtermap inverse (filtermap inverse (at (0::'a))) \<le> filtermap inverse at_infinity" using filterlim_inverse_at_infinity unfolding filterlim_def by (rule filtermap_mono) then show "at (0::'a) \<le> filtermap inverse at_infinity" by (simp add: filtermap_ident filtermap_filtermap) qed lemma lim_at_infinity_0: fixes l :: "'a::{real_normed_field,field}" shows "(f \<longlongrightarrow> l) at_infinity \<longleftrightarrow> ((f \<circ> inverse) \<longlongrightarrow> l) (at (0::'a))" by (simp add: tendsto_compose_filtermap at_to_infinity filtermap_filtermap) lemma lim_zero_infinity: fixes l :: "'a::{real_normed_field,field}" shows "((\<lambda>x. f(1 / x)) \<longlongrightarrow> l) (at (0::'a)) \<Longrightarrow> (f \<longlongrightarrow> l) at_infinity" by (simp add: inverse_eq_divide lim_at_infinity_0 comp_def) text \<open> We only show rules for multiplication and addition when the functions are either against a real value or against infinity. Further rules are easy to derive by using @{thm filterlim_uminus_at_top}. \<close> lemma filterlim_tendsto_pos_mult_at_top: assumes f: "(f \<longlongrightarrow> c) F" and c: "0 < c" and g: "LIM x F. g x :> at_top" shows "LIM x F. (f x * g x :: real) :> at_top" unfolding filterlim_at_top_gt[where c=0] proof safe fix Z :: real assume "0 < Z" from f \<open>0 < c\<close> have "eventually (\<lambda>x. c / 2 < f x) F" by (auto dest!: tendstoD[where e="c / 2"] elim!: eventually_mono simp: dist_real_def abs_real_def split: if_split_asm) moreover from g have "eventually (\<lambda>x. (Z / c * 2) \<le> g x) F" unfolding filterlim_at_top by auto ultimately show "eventually (\<lambda>x. Z \<le> f x * g x) F" proof eventually_elim case (elim x) with \<open>0 < Z\<close> \<open>0 < c\<close> have "c / 2 * (Z / c * 2) \<le> f x * g x" by (intro mult_mono) (auto simp: zero_le_divide_iff) with \<open>0 < c\<close> show "Z \<le> f x * g x" by simp qed qed lemma filterlim_at_top_mult_at_top: assumes f: "LIM x F. f x :> at_top" and g: "LIM x F. g x :> at_top" shows "LIM x F. (f x * g x :: real) :> at_top" unfolding filterlim_at_top_gt[where c=0] proof safe fix Z :: real assume "0 < Z" from f have "eventually (\<lambda>x. 1 \<le> f x) F" unfolding filterlim_at_top by auto moreover from g have "eventually (\<lambda>x. Z \<le> g x) F" unfolding filterlim_at_top by auto ultimately show "eventually (\<lambda>x. Z \<le> f x * g x) F" proof eventually_elim case (elim x) with \<open>0 < Z\<close> have "1 * Z \<le> f x * g x" by (intro mult_mono) (auto simp: zero_le_divide_iff) then show "Z \<le> f x * g x" by simp qed qed lemma filterlim_at_top_mult_tendsto_pos: assumes f: "(f \<longlongrightarrow> c) F" and c: "0 < c" and g: "LIM x F. g x :> at_top" shows "LIM x F. (g x * f x:: real) :> at_top" by (auto simp: mult.commute intro!: filterlim_tendsto_pos_mult_at_top f c g) lemma filterlim_tendsto_pos_mult_at_bot: fixes c :: real assumes "(f \<longlongrightarrow> c) F" "0 < c" "filterlim g at_bot F" shows "LIM x F. f x * g x :> at_bot" using filterlim_tendsto_pos_mult_at_top[OF assms(1,2), of "\<lambda>x. - g x"] assms(3) unfolding filterlim_uminus_at_bot by simp lemma filterlim_tendsto_neg_mult_at_bot: fixes c :: real assumes c: "(f \<longlongrightarrow> c) F" "c < 0" and g: "filterlim g at_top F" shows "LIM x F. f x * g x :> at_bot" using c filterlim_tendsto_pos_mult_at_top[of "\<lambda>x. - f x" "- c" F, OF _ _ g] unfolding filterlim_uminus_at_bot tendsto_minus_cancel_left by simp lemma filterlim_pow_at_top: fixes f :: "'a \<Rightarrow> real" assumes "0 < n" and f: "LIM x F. f x :> at_top" shows "LIM x F. (f x)^n :: real :> at_top" using \<open>0 < n\<close> proof (induct n) case 0 then show ?case by simp next case (Suc n) with f show ?case by (cases "n = 0") (auto intro!: filterlim_at_top_mult_at_top) qed lemma filterlim_pow_at_bot_even: fixes f :: "real \<Rightarrow> real" shows "0 < n \<Longrightarrow> LIM x F. f x :> at_bot \<Longrightarrow> even n \<Longrightarrow> LIM x F. (f x)^n :> at_top" using filterlim_pow_at_top[of n "\<lambda>x. - f x" F] by (simp add: filterlim_uminus_at_top) lemma filterlim_pow_at_bot_odd: fixes f :: "real \<Rightarrow> real" shows "0 < n \<Longrightarrow> LIM x F. f x :> at_bot \<Longrightarrow> odd n \<Longrightarrow> LIM x F. (f x)^n :> at_bot" using filterlim_pow_at_top[of n "\<lambda>x. - f x" F] by (simp add: filterlim_uminus_at_bot) lemma filterlim_power_at_infinity [tendsto_intros]: fixes F and f :: "'a \<Rightarrow> 'b :: real_normed_div_algebra" assumes "filterlim f at_infinity F" "n > 0" shows "filterlim (\<lambda>x. f x ^ n) at_infinity F" by (rule filterlim_norm_at_top_imp_at_infinity) (auto simp: norm_power intro!: filterlim_pow_at_top assms intro: filterlim_at_infinity_imp_norm_at_top) lemma filterlim_tendsto_add_at_top: assumes f: "(f \<longlongrightarrow> c) F" and g: "LIM x F. g x :> at_top" shows "LIM x F. (f x + g x :: real) :> at_top" unfolding filterlim_at_top_gt[where c=0] proof safe fix Z :: real assume "0 < Z" from f have "eventually (\<lambda>x. c - 1 < f x) F" by (auto dest!: tendstoD[where e=1] elim!: eventually_mono simp: dist_real_def) moreover from g have "eventually (\<lambda>x. Z - (c - 1) \<le> g x) F" unfolding filterlim_at_top by auto ultimately show "eventually (\<lambda>x. Z \<le> f x + g x) F" by eventually_elim simp qed lemma LIM_at_top_divide: fixes f g :: "'a \<Rightarrow> real" assumes f: "(f \<longlongrightarrow> a) F" "0 < a" and g: "(g \<longlongrightarrow> 0) F" "eventually (\<lambda>x. 0 < g x) F" shows "LIM x F. f x / g x :> at_top" unfolding divide_inverse by (rule filterlim_tendsto_pos_mult_at_top[OF f]) (rule filterlim_inverse_at_top[OF g]) lemma filterlim_at_top_add_at_top: assumes f: "LIM x F. f x :> at_top" and g: "LIM x F. g x :> at_top" shows "LIM x F. (f x + g x :: real) :> at_top" unfolding filterlim_at_top_gt[where c=0] proof safe fix Z :: real assume "0 < Z" from f have "eventually (\<lambda>x. 0 \<le> f x) F" unfolding filterlim_at_top by auto moreover from g have "eventually (\<lambda>x. Z \<le> g x) F" unfolding filterlim_at_top by auto ultimately show "eventually (\<lambda>x. Z \<le> f x + g x) F" by eventually_elim simp qed lemma tendsto_divide_0: fixes f :: "_ \<Rightarrow> 'a::{real_normed_div_algebra, division_ring}" assumes f: "(f \<longlongrightarrow> c) F" and g: "LIM x F. g x :> at_infinity" shows "((\<lambda>x. f x / g x) \<longlongrightarrow> 0) F" using tendsto_mult[OF f filterlim_compose[OF tendsto_inverse_0 g]] by (simp add: divide_inverse) lemma linear_plus_1_le_power: fixes x :: real assumes x: "0 \<le> x" shows "real n * x + 1 \<le> (x + 1) ^ n" proof (induct n) case 0 then show ?case by simp next case (Suc n) from x have "real (Suc n) * x + 1 \<le> (x + 1) * (real n * x + 1)" by (simp add: field_simps) also have "\<dots> \<le> (x + 1)^Suc n" using Suc x by (simp add: mult_left_mono) finally show ?case . qed lemma filterlim_realpow_sequentially_gt1: fixes x :: "'a :: real_normed_div_algebra" assumes x[arith]: "1 < norm x" shows "LIM n sequentially. x ^ n :> at_infinity" proof (intro filterlim_at_infinity[THEN iffD2] allI impI) fix y :: real assume "0 < y" have "0 < norm x - 1" by simp then obtain N :: nat where "y < real N * (norm x - 1)" by (blast dest: reals_Archimedean3) also have "\<dots> \<le> real N * (norm x - 1) + 1" by simp also have "\<dots> \<le> (norm x - 1 + 1) ^ N" by (rule linear_plus_1_le_power) simp also have "\<dots> = norm x ^ N" by simp finally have "\<forall>n\<ge>N. y \<le> norm x ^ n" by (metis order_less_le_trans power_increasing order_less_imp_le x) then show "eventually (\<lambda>n. y \<le> norm (x ^ n)) sequentially" unfolding eventually_sequentially by (auto simp: norm_power) qed simp lemma filterlim_divide_at_infinity: fixes f g :: "'a \<Rightarrow> 'a :: real_normed_field" assumes "filterlim f (nhds c) F" "filterlim g (at 0) F" "c \<noteq> 0" shows "filterlim (\<lambda>x. f x / g x) at_infinity F" proof - have "filterlim (\<lambda>x. f x * inverse (g x)) at_infinity F" by (intro tendsto_mult_filterlim_at_infinity[OF assms(1,3)] filterlim_compose [OF filterlim_inverse_at_infinity assms(2)]) thus ?thesis by (simp add: field_simps) qed subsection \<open>Floor and Ceiling\<close> lemma eventually_floor_less: fixes f :: "'a \<Rightarrow> 'b::{order_topology,floor_ceiling}" assumes f: "(f \<longlongrightarrow> l) F" and l: "l \<notin> \<int>" shows "\<forall>\<^sub>F x in F. of_int (floor l) < f x" by (intro order_tendstoD[OF f]) (metis Ints_of_int antisym_conv2 floor_correct l) lemma eventually_less_ceiling: fixes f :: "'a \<Rightarrow> 'b::{order_topology,floor_ceiling}" assumes f: "(f \<longlongrightarrow> l) F" and l: "l \<notin> \<int>" shows "\<forall>\<^sub>F x in F. f x < of_int (ceiling l)" by (intro order_tendstoD[OF f]) (metis Ints_of_int l le_of_int_ceiling less_le) lemma eventually_floor_eq: fixes f::"'a \<Rightarrow> 'b::{order_topology,floor_ceiling}" assumes f: "(f \<longlongrightarrow> l) F" and l: "l \<notin> \<int>" shows "\<forall>\<^sub>F x in F. floor (f x) = floor l" using eventually_floor_less[OF assms] eventually_less_ceiling[OF assms] by eventually_elim (meson floor_less_iff less_ceiling_iff not_less_iff_gr_or_eq) lemma eventually_ceiling_eq: fixes f::"'a \<Rightarrow> 'b::{order_topology,floor_ceiling}" assumes f: "(f \<longlongrightarrow> l) F" and l: "l \<notin> \<int>" shows "\<forall>\<^sub>F x in F. ceiling (f x) = ceiling l" using eventually_floor_less[OF assms] eventually_less_ceiling[OF assms] by eventually_elim (meson floor_less_iff less_ceiling_iff not_less_iff_gr_or_eq) lemma tendsto_of_int_floor: fixes f::"'a \<Rightarrow> 'b::{order_topology,floor_ceiling}" assumes "(f \<longlongrightarrow> l) F" and "l \<notin> \<int>" shows "((\<lambda>x. of_int (floor (f x)) :: 'c::{ring_1,topological_space}) \<longlongrightarrow> of_int (floor l)) F" using eventually_floor_eq[OF assms] by (simp add: eventually_mono topological_tendstoI) lemma tendsto_of_int_ceiling: fixes f::"'a \<Rightarrow> 'b::{order_topology,floor_ceiling}" assumes "(f \<longlongrightarrow> l) F" and "l \<notin> \<int>" shows "((\<lambda>x. of_int (ceiling (f x)):: 'c::{ring_1,topological_space}) \<longlongrightarrow> of_int (ceiling l)) F" using eventually_ceiling_eq[OF assms] by (simp add: eventually_mono topological_tendstoI) lemma continuous_on_of_int_floor: "continuous_on (UNIV - \<int>::'a::{order_topology, floor_ceiling} set) (\<lambda>x. of_int (floor x)::'b::{ring_1, topological_space})" unfolding continuous_on_def by (auto intro!: tendsto_of_int_floor) lemma continuous_on_of_int_ceiling: "continuous_on (UNIV - \<int>::'a::{order_topology, floor_ceiling} set) (\<lambda>x. of_int (ceiling x)::'b::{ring_1, topological_space})" unfolding continuous_on_def by (auto intro!: tendsto_of_int_ceiling) subsection \<open>Limits of Sequences\<close> lemma [trans]: "X = Y \<Longrightarrow> Y \<longlonglongrightarrow> z \<Longrightarrow> X \<longlonglongrightarrow> z" by simp lemma LIMSEQ_iff: fixes L :: "'a::real_normed_vector" shows "(X \<longlonglongrightarrow> L) = (\<forall>r>0. \<exists>no. \<forall>n \<ge> no. norm (X n - L) < r)" unfolding lim_sequentially dist_norm .. lemma LIMSEQ_I: "(\<And>r. 0 < r \<Longrightarrow> \<exists>no. \<forall>n\<ge>no. norm (X n - L) < r) \<Longrightarrow> X \<longlonglongrightarrow> L" for L :: "'a::real_normed_vector" by (simp add: LIMSEQ_iff) lemma LIMSEQ_D: "X \<longlonglongrightarrow> L \<Longrightarrow> 0 < r \<Longrightarrow> \<exists>no. \<forall>n\<ge>no. norm (X n - L) < r" for L :: "'a::real_normed_vector" by (simp add: LIMSEQ_iff) lemma LIMSEQ_linear: "X \<longlonglongrightarrow> x \<Longrightarrow> l > 0 \<Longrightarrow> (\<lambda> n. X (n * l)) \<longlonglongrightarrow> x" unfolding tendsto_def eventually_sequentially by (metis div_le_dividend div_mult_self1_is_m le_trans mult.commute) text \<open>Transformation of limit.\<close> lemma Lim_transform: "(g \<longlongrightarrow> a) F \<Longrightarrow> ((\<lambda>x. f x - g x) \<longlongrightarrow> 0) F \<Longrightarrow> (f \<longlongrightarrow> a) F" for a b :: "'a::real_normed_vector" using tendsto_add [of g a F "\<lambda>x. f x - g x" 0] by simp lemma Lim_transform2: "(f \<longlongrightarrow> a) F \<Longrightarrow> ((\<lambda>x. f x - g x) \<longlongrightarrow> 0) F \<Longrightarrow> (g \<longlongrightarrow> a) F" for a b :: "'a::real_normed_vector" by (erule Lim_transform) (simp add: tendsto_minus_cancel) proposition Lim_transform_eq: "((\<lambda>x. f x - g x) \<longlongrightarrow> 0) F \<Longrightarrow> (f \<longlongrightarrow> a) F \<longleftrightarrow> (g \<longlongrightarrow> a) F" for a :: "'a::real_normed_vector" using Lim_transform Lim_transform2 by blast lemma Lim_transform_eventually: "\<lbrakk>(f \<longlongrightarrow> l) F; eventually (\<lambda>x. f x = g x) F\<rbrakk> \<Longrightarrow> (g \<longlongrightarrow> l) F" using eventually_elim2 by (fastforce simp add: tendsto_def) lemma Lim_transform_within: assumes "(f \<longlongrightarrow> l) (at x within S)" and "0 < d" and "\<And>x'. x'\<in>S \<Longrightarrow> 0 < dist x' x \<Longrightarrow> dist x' x < d \<Longrightarrow> f x' = g x'" shows "(g \<longlongrightarrow> l) (at x within S)" proof (rule Lim_transform_eventually) show "eventually (\<lambda>x. f x = g x) (at x within S)" using assms by (auto simp: eventually_at) show "(f \<longlongrightarrow> l) (at x within S)" by fact qed lemma filterlim_transform_within: assumes "filterlim g G (at x within S)" assumes "G \<le> F" "0<d" "(\<And>x'. x' \<in> S \<Longrightarrow> 0 < dist x' x \<Longrightarrow> dist x' x < d \<Longrightarrow> f x' = g x') " shows "filterlim f F (at x within S)" using assms apply (elim filterlim_mono_eventually) unfolding eventually_at by auto text \<open>Common case assuming being away from some crucial point like 0.\<close> lemma Lim_transform_away_within: fixes a b :: "'a::t1_space" assumes "a \<noteq> b" and "\<forall>x\<in>S. x \<noteq> a \<and> x \<noteq> b \<longrightarrow> f x = g x" and "(f \<longlongrightarrow> l) (at a within S)" shows "(g \<longlongrightarrow> l) (at a within S)" proof (rule Lim_transform_eventually) show "(f \<longlongrightarrow> l) (at a within S)" by fact show "eventually (\<lambda>x. f x = g x) (at a within S)" unfolding eventually_at_topological by (rule exI [where x="- {b}"]) (simp add: open_Compl assms) qed lemma Lim_transform_away_at: fixes a b :: "'a::t1_space" assumes ab: "a \<noteq> b" and fg: "\<forall>x. x \<noteq> a \<and> x \<noteq> b \<longrightarrow> f x = g x" and fl: "(f \<longlongrightarrow> l) (at a)" shows "(g \<longlongrightarrow> l) (at a)" using Lim_transform_away_within[OF ab, of UNIV f g l] fg fl by simp text \<open>Alternatively, within an open set.\<close> lemma Lim_transform_within_open: assumes "(f \<longlongrightarrow> l) (at a within T)" and "open s" and "a \<in> s" and "\<And>x. x\<in>s \<Longrightarrow> x \<noteq> a \<Longrightarrow> f x = g x" shows "(g \<longlongrightarrow> l) (at a within T)" proof (rule Lim_transform_eventually) show "eventually (\<lambda>x. f x = g x) (at a within T)" unfolding eventually_at_topological using assms by auto show "(f \<longlongrightarrow> l) (at a within T)" by fact qed text \<open>A congruence rule allowing us to transform limits assuming not at point.\<close> (* FIXME: Only one congruence rule for tendsto can be used at a time! *) lemma Lim_cong_within(*[cong add]*): assumes "a = b" and "x = y" and "S = T" and "\<And>x. x \<noteq> b \<Longrightarrow> x \<in> T \<Longrightarrow> f x = g x" shows "(f \<longlongrightarrow> x) (at a within S) \<longleftrightarrow> (g \<longlongrightarrow> y) (at b within T)" unfolding tendsto_def eventually_at_topological using assms by simp lemma Lim_cong_at(*[cong add]*): assumes "a = b" "x = y" and "\<And>x. x \<noteq> a \<Longrightarrow> f x = g x" shows "((\<lambda>x. f x) \<longlongrightarrow> x) (at a) \<longleftrightarrow> ((g \<longlongrightarrow> y) (at a))" unfolding tendsto_def eventually_at_topological using assms by simp text \<open>An unbounded sequence's inverse tends to 0.\<close> lemma LIMSEQ_inverse_zero: assumes "\<And>r::real. \<exists>N. \<forall>n\<ge>N. r < X n" shows "(\<lambda>n. inverse (X n)) \<longlonglongrightarrow> 0" apply (rule filterlim_compose[OF tendsto_inverse_0]) by (metis assms eventually_at_top_linorderI filterlim_at_top_dense filterlim_at_top_imp_at_infinity) text \<open>The sequence \<^term>\<open>1/n\<close> tends to 0 as \<^term>\<open>n\<close> tends to infinity.\<close> lemma LIMSEQ_inverse_real_of_nat: "(\<lambda>n. inverse (real (Suc n))) \<longlonglongrightarrow> 0" by (metis filterlim_compose tendsto_inverse_0 filterlim_mono order_refl filterlim_Suc filterlim_compose[OF filterlim_real_sequentially] at_top_le_at_infinity) text \<open> The sequence \<^term>\<open>r + 1/n\<close> tends to \<^term>\<open>r\<close> as \<^term>\<open>n\<close> tends to infinity is now easily proved. \<close> lemma LIMSEQ_inverse_real_of_nat_add: "(\<lambda>n. r + inverse (real (Suc n))) \<longlonglongrightarrow> r" using tendsto_add [OF tendsto_const LIMSEQ_inverse_real_of_nat] by auto lemma LIMSEQ_inverse_real_of_nat_add_minus: "(\<lambda>n. r + -inverse (real (Suc n))) \<longlonglongrightarrow> r" using tendsto_add [OF tendsto_const tendsto_minus [OF LIMSEQ_inverse_real_of_nat]] by auto lemma LIMSEQ_inverse_real_of_nat_add_minus_mult: "(\<lambda>n. r * (1 + - inverse (real (Suc n)))) \<longlonglongrightarrow> r" using tendsto_mult [OF tendsto_const LIMSEQ_inverse_real_of_nat_add_minus [of 1]] by auto lemma lim_inverse_n: "((\<lambda>n. inverse(of_nat n)) \<longlongrightarrow> (0::'a::real_normed_field)) sequentially" using lim_1_over_n by (simp add: inverse_eq_divide) lemma lim_inverse_n': "((\<lambda>n. 1 / n) \<longlongrightarrow> 0) sequentially" using lim_inverse_n by (simp add: inverse_eq_divide) lemma LIMSEQ_Suc_n_over_n: "(\<lambda>n. of_nat (Suc n) / of_nat n :: 'a :: real_normed_field) \<longlonglongrightarrow> 1" proof (rule Lim_transform_eventually) show "eventually (\<lambda>n. 1 + inverse (of_nat n :: 'a) = of_nat (Suc n) / of_nat n) sequentially" using eventually_gt_at_top[of "0::nat"] by eventually_elim (simp add: field_simps) have "(\<lambda>n. 1 + inverse (of_nat n) :: 'a) \<longlonglongrightarrow> 1 + 0" by (intro tendsto_add tendsto_const lim_inverse_n) then show "(\<lambda>n. 1 + inverse (of_nat n) :: 'a) \<longlonglongrightarrow> 1" by simp qed lemma LIMSEQ_n_over_Suc_n: "(\<lambda>n. of_nat n / of_nat (Suc n) :: 'a :: real_normed_field) \<longlonglongrightarrow> 1" proof (rule Lim_transform_eventually) show "eventually (\<lambda>n. inverse (of_nat (Suc n) / of_nat n :: 'a) = of_nat n / of_nat (Suc n)) sequentially" using eventually_gt_at_top[of "0::nat"] by eventually_elim (simp add: field_simps del: of_nat_Suc) have "(\<lambda>n. inverse (of_nat (Suc n) / of_nat n :: 'a)) \<longlonglongrightarrow> inverse 1" by (intro tendsto_inverse LIMSEQ_Suc_n_over_n) simp_all then show "(\<lambda>n. inverse (of_nat (Suc n) / of_nat n :: 'a)) \<longlonglongrightarrow> 1" by simp qed subsection \<open>Convergence on sequences\<close> lemma convergent_cong: assumes "eventually (\<lambda>x. f x = g x) sequentially" shows "convergent f \<longleftrightarrow> convergent g" unfolding convergent_def by (subst filterlim_cong[OF refl refl assms]) (rule refl) lemma convergent_Suc_iff: "convergent (\<lambda>n. f (Suc n)) \<longleftrightarrow> convergent f" by (auto simp: convergent_def filterlim_sequentially_Suc) lemma convergent_ignore_initial_segment: "convergent (\<lambda>n. f (n + m)) = convergent f" proof (induct m arbitrary: f) case 0 then show ?case by simp next case (Suc m) have "convergent (\<lambda>n. f (n + Suc m)) \<longleftrightarrow> convergent (\<lambda>n. f (Suc n + m))" by simp also have "\<dots> \<longleftrightarrow> convergent (\<lambda>n. f (n + m))" by (rule convergent_Suc_iff) also have "\<dots> \<longleftrightarrow> convergent f" by (rule Suc) finally show ?case . qed lemma convergent_add: fixes X Y :: "nat \<Rightarrow> 'a::topological_monoid_add" assumes "convergent (\<lambda>n. X n)" and "convergent (\<lambda>n. Y n)" shows "convergent (\<lambda>n. X n + Y n)" using assms unfolding convergent_def by (blast intro: tendsto_add) lemma convergent_sum: fixes X :: "'a \<Rightarrow> nat \<Rightarrow> 'b::topological_comm_monoid_add" shows "(\<And>i. i \<in> A \<Longrightarrow> convergent (\<lambda>n. X i n)) \<Longrightarrow> convergent (\<lambda>n. \<Sum>i\<in>A. X i n)" by (induct A rule: infinite_finite_induct) (simp_all add: convergent_const convergent_add) lemma (in bounded_linear) convergent: assumes "convergent (\<lambda>n. X n)" shows "convergent (\<lambda>n. f (X n))" using assms unfolding convergent_def by (blast intro: tendsto) lemma (in bounded_bilinear) convergent: assumes "convergent (\<lambda>n. X n)" and "convergent (\<lambda>n. Y n)" shows "convergent (\<lambda>n. X n ** Y n)" using assms unfolding convergent_def by (blast intro: tendsto) lemma convergent_minus_iff: fixes X :: "nat \<Rightarrow> 'a::topological_group_add" shows "convergent X \<longleftrightarrow> convergent (\<lambda>n. - X n)" unfolding convergent_def by (force dest: tendsto_minus) lemma convergent_diff: fixes X Y :: "nat \<Rightarrow> 'a::topological_group_add" assumes "convergent (\<lambda>n. X n)" assumes "convergent (\<lambda>n. Y n)" shows "convergent (\<lambda>n. X n - Y n)" using assms unfolding convergent_def by (blast intro: tendsto_diff) lemma convergent_norm: assumes "convergent f" shows "convergent (\<lambda>n. norm (f n))" proof - from assms have "f \<longlonglongrightarrow> lim f" by (simp add: convergent_LIMSEQ_iff) then have "(\<lambda>n. norm (f n)) \<longlonglongrightarrow> norm (lim f)" by (rule tendsto_norm) then show ?thesis by (auto simp: convergent_def) qed lemma convergent_of_real: "convergent f \<Longrightarrow> convergent (\<lambda>n. of_real (f n) :: 'a::real_normed_algebra_1)" unfolding convergent_def by (blast intro!: tendsto_of_real) lemma convergent_add_const_iff: "convergent (\<lambda>n. c + f n :: 'a::topological_ab_group_add) \<longleftrightarrow> convergent f" proof assume "convergent (\<lambda>n. c + f n)" from convergent_diff[OF this convergent_const[of c]] show "convergent f" by simp next assume "convergent f" from convergent_add[OF convergent_const[of c] this] show "convergent (\<lambda>n. c + f n)" by simp qed lemma convergent_add_const_right_iff: "convergent (\<lambda>n. f n + c :: 'a::topological_ab_group_add) \<longleftrightarrow> convergent f" using convergent_add_const_iff[of c f] by (simp add: add_ac) lemma convergent_diff_const_right_iff: "convergent (\<lambda>n. f n - c :: 'a::topological_ab_group_add) \<longleftrightarrow> convergent f" using convergent_add_const_right_iff[of f "-c"] by (simp add: add_ac) lemma convergent_mult: fixes X Y :: "nat \<Rightarrow> 'a::topological_semigroup_mult" assumes "convergent (\<lambda>n. X n)" and "convergent (\<lambda>n. Y n)" shows "convergent (\<lambda>n. X n * Y n)" using assms unfolding convergent_def by (blast intro: tendsto_mult) lemma convergent_mult_const_iff: assumes "c \<noteq> 0" shows "convergent (\<lambda>n. c * f n :: 'a::{field,topological_semigroup_mult}) \<longleftrightarrow> convergent f" proof assume "convergent (\<lambda>n. c * f n)" from assms convergent_mult[OF this convergent_const[of "inverse c"]] show "convergent f" by (simp add: field_simps) next assume "convergent f" from convergent_mult[OF convergent_const[of c] this] show "convergent (\<lambda>n. c * f n)" by simp qed lemma convergent_mult_const_right_iff: fixes c :: "'a::{field,topological_semigroup_mult}" assumes "c \<noteq> 0" shows "convergent (\<lambda>n. f n * c) \<longleftrightarrow> convergent f" using convergent_mult_const_iff[OF assms, of f] by (simp add: mult_ac) lemma convergent_imp_Bseq: "convergent f \<Longrightarrow> Bseq f" by (simp add: Cauchy_Bseq convergent_Cauchy) text \<open>A monotone sequence converges to its least upper bound.\<close> lemma LIMSEQ_incseq_SUP: fixes X :: "nat \<Rightarrow> 'a::{conditionally_complete_linorder,linorder_topology}" assumes u: "bdd_above (range X)" and X: "incseq X" shows "X \<longlonglongrightarrow> (SUP i. X i)" by (rule order_tendstoI) (auto simp: eventually_sequentially u less_cSUP_iff intro: X[THEN incseqD] less_le_trans cSUP_lessD[OF u]) lemma LIMSEQ_decseq_INF: fixes X :: "nat \<Rightarrow> 'a::{conditionally_complete_linorder, linorder_topology}" assumes u: "bdd_below (range X)" and X: "decseq X" shows "X \<longlonglongrightarrow> (INF i. X i)" by (rule order_tendstoI) (auto simp: eventually_sequentially u cINF_less_iff intro: X[THEN decseqD] le_less_trans less_cINF_D[OF u]) text \<open>Main monotonicity theorem.\<close> lemma Bseq_monoseq_convergent: "Bseq X \<Longrightarrow> monoseq X \<Longrightarrow> convergent X" for X :: "nat \<Rightarrow> real" by (auto simp: monoseq_iff convergent_def intro: LIMSEQ_decseq_INF LIMSEQ_incseq_SUP dest: Bseq_bdd_above Bseq_bdd_below) lemma Bseq_mono_convergent: "Bseq X \<Longrightarrow> (\<forall>m n. m \<le> n \<longrightarrow> X m \<le> X n) \<Longrightarrow> convergent X" for X :: "nat \<Rightarrow> real" by (auto intro!: Bseq_monoseq_convergent incseq_imp_monoseq simp: incseq_def) lemma monoseq_imp_convergent_iff_Bseq: "monoseq f \<Longrightarrow> convergent f \<longleftrightarrow> Bseq f" for f :: "nat \<Rightarrow> real" using Bseq_monoseq_convergent[of f] convergent_imp_Bseq[of f] by blast lemma Bseq_monoseq_convergent'_inc: fixes f :: "nat \<Rightarrow> real" shows "Bseq (\<lambda>n. f (n + M)) \<Longrightarrow> (\<And>m n. M \<le> m \<Longrightarrow> m \<le> n \<Longrightarrow> f m \<le> f n) \<Longrightarrow> convergent f" by (subst convergent_ignore_initial_segment [symmetric, of _ M]) (auto intro!: Bseq_monoseq_convergent simp: monoseq_def) lemma Bseq_monoseq_convergent'_dec: fixes f :: "nat \<Rightarrow> real" shows "Bseq (\<lambda>n. f (n + M)) \<Longrightarrow> (\<And>m n. M \<le> m \<Longrightarrow> m \<le> n \<Longrightarrow> f m \<ge> f n) \<Longrightarrow> convergent f" by (subst convergent_ignore_initial_segment [symmetric, of _ M]) (auto intro!: Bseq_monoseq_convergent simp: monoseq_def) lemma Cauchy_iff: "Cauchy X \<longleftrightarrow> (\<forall>e>0. \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. norm (X m - X n) < e)" for X :: "nat \<Rightarrow> 'a::real_normed_vector" unfolding Cauchy_def dist_norm .. lemma CauchyI: "(\<And>e. 0 < e \<Longrightarrow> \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. norm (X m - X n) < e) \<Longrightarrow> Cauchy X" for X :: "nat \<Rightarrow> 'a::real_normed_vector" by (simp add: Cauchy_iff) lemma CauchyD: "Cauchy X \<Longrightarrow> 0 < e \<Longrightarrow> \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. norm (X m - X n) < e" for X :: "nat \<Rightarrow> 'a::real_normed_vector" by (simp add: Cauchy_iff) lemma incseq_convergent: fixes X :: "nat \<Rightarrow> real" assumes "incseq X" and "\<forall>i. X i \<le> B" obtains L where "X \<longlonglongrightarrow> L" "\<forall>i. X i \<le> L" proof atomize_elim from incseq_bounded[OF assms] \<open>incseq X\<close> Bseq_monoseq_convergent[of X] obtain L where "X \<longlonglongrightarrow> L" by (auto simp: convergent_def monoseq_def incseq_def) with \<open>incseq X\<close> show "\<exists>L. X \<longlonglongrightarrow> L \<and> (\<forall>i. X i \<le> L)" by (auto intro!: exI[of _ L] incseq_le) qed lemma decseq_convergent: fixes X :: "nat \<Rightarrow> real" assumes "decseq X" and "\<forall>i. B \<le> X i" obtains L where "X \<longlonglongrightarrow> L" "\<forall>i. L \<le> X i" proof atomize_elim from decseq_bounded[OF assms] \<open>decseq X\<close> Bseq_monoseq_convergent[of X] obtain L where "X \<longlonglongrightarrow> L" by (auto simp: convergent_def monoseq_def decseq_def) with \<open>decseq X\<close> show "\<exists>L. X \<longlonglongrightarrow> L \<and> (\<forall>i. L \<le> X i)" by (auto intro!: exI[of _ L] decseq_ge) qed lemma monoseq_convergent: fixes X :: "nat \<Rightarrow> real" assumes X: "monoseq X" and B: "\<And>i. \<bar>X i\<bar> \<le> B" obtains L where "X \<longlonglongrightarrow> L" using X unfolding monoseq_iff proof assume "incseq X" show thesis using abs_le_D1 [OF B] incseq_convergent [OF \<open>incseq X\<close>] that by meson next assume "decseq X" show thesis using decseq_convergent [OF \<open>decseq X\<close>] that by (metis B abs_le_iff add.inverse_inverse neg_le_iff_le) qed subsection \<open>Power Sequences\<close> lemma Bseq_realpow: "0 \<le> x \<Longrightarrow> x \<le> 1 \<Longrightarrow> Bseq (\<lambda>n. x ^ n)" for x :: real by (metis decseq_bounded decseq_def power_decreasing zero_le_power) lemma monoseq_realpow: "0 \<le> x \<Longrightarrow> x \<le> 1 \<Longrightarrow> monoseq (\<lambda>n. x ^ n)" for x :: real using monoseq_def power_decreasing by blast lemma convergent_realpow: "0 \<le> x \<Longrightarrow> x \<le> 1 \<Longrightarrow> convergent (\<lambda>n. x ^ n)" for x :: real by (blast intro!: Bseq_monoseq_convergent Bseq_realpow monoseq_realpow) lemma LIMSEQ_inverse_realpow_zero: "1 < x \<Longrightarrow> (\<lambda>n. inverse (x ^ n)) \<longlonglongrightarrow> 0" for x :: real by (rule filterlim_compose[OF tendsto_inverse_0 filterlim_realpow_sequentially_gt1]) simp lemma LIMSEQ_realpow_zero: fixes x :: real assumes "0 \<le> x" "x < 1" shows "(\<lambda>n. x ^ n) \<longlonglongrightarrow> 0" proof (cases "x = 0") case False with \<open>0 \<le> x\<close> have x0: "0 < x" by simp then have "1 < inverse x" using \<open>x < 1\<close> by (rule one_less_inverse) then have "(\<lambda>n. inverse (inverse x ^ n)) \<longlonglongrightarrow> 0" by (rule LIMSEQ_inverse_realpow_zero) then show ?thesis by (simp add: power_inverse) next case True show ?thesis by (rule LIMSEQ_imp_Suc) (simp add: True) qed lemma LIMSEQ_power_zero [tendsto_intros]: "norm x < 1 \<Longrightarrow> (\<lambda>n. x ^ n) \<longlonglongrightarrow> 0" for x :: "'a::real_normed_algebra_1" apply (drule LIMSEQ_realpow_zero [OF norm_ge_zero]) by (simp add: Zfun_le norm_power_ineq tendsto_Zfun_iff) lemma LIMSEQ_divide_realpow_zero: "1 < x \<Longrightarrow> (\<lambda>n. a / (x ^ n) :: real) \<longlonglongrightarrow> 0" by (rule tendsto_divide_0 [OF tendsto_const filterlim_realpow_sequentially_gt1]) simp lemma tendsto_power_zero: fixes x::"'a::real_normed_algebra_1" assumes "filterlim f at_top F" assumes "norm x < 1" shows "((\<lambda>y. x ^ (f y)) \<longlongrightarrow> 0) F" proof (rule tendstoI) fix e::real assume "0 < e" from tendstoD[OF LIMSEQ_power_zero[OF \<open>norm x < 1\<close>] \<open>0 < e\<close>] have "\<forall>\<^sub>F xa in sequentially. norm (x ^ xa) < e" by simp then obtain N where N: "norm (x ^ n) < e" if "n \<ge> N" for n by (auto simp: eventually_sequentially) have "\<forall>\<^sub>F i in F. f i \<ge> N" using \<open>filterlim f sequentially F\<close> by (simp add: filterlim_at_top) then show "\<forall>\<^sub>F i in F. dist (x ^ f i) 0 < e" by eventually_elim (auto simp: N) qed text \<open>Limit of \<^term>\<open>c^n\<close> for \<^term>\<open>\<bar>c\<bar> < 1\<close>.\<close> lemma LIMSEQ_abs_realpow_zero: "\<bar>c\<bar> < 1 \<Longrightarrow> (\<lambda>n. \<bar>c\<bar> ^ n :: real) \<longlonglongrightarrow> 0" by (rule LIMSEQ_realpow_zero [OF abs_ge_zero]) lemma LIMSEQ_abs_realpow_zero2: "\<bar>c\<bar> < 1 \<Longrightarrow> (\<lambda>n. c ^ n :: real) \<longlonglongrightarrow> 0" by (rule LIMSEQ_power_zero) simp subsection \<open>Limits of Functions\<close> lemma LIM_eq: "f \<midarrow>a\<rightarrow> L = (\<forall>r>0. \<exists>s>0. \<forall>x. x \<noteq> a \<and> norm (x - a) < s \<longrightarrow> norm (f x - L) < r)" for a :: "'a::real_normed_vector" and L :: "'b::real_normed_vector" by (simp add: LIM_def dist_norm) lemma LIM_I: "(\<And>r. 0 < r \<Longrightarrow> \<exists>s>0. \<forall>x. x \<noteq> a \<and> norm (x - a) < s \<longrightarrow> norm (f x - L) < r) \<Longrightarrow> f \<midarrow>a\<rightarrow> L" for a :: "'a::real_normed_vector" and L :: "'b::real_normed_vector" by (simp add: LIM_eq) lemma LIM_D: "f \<midarrow>a\<rightarrow> L \<Longrightarrow> 0 < r \<Longrightarrow> \<exists>s>0.\<forall>x. x \<noteq> a \<and> norm (x - a) < s \<longrightarrow> norm (f x - L) < r" for a :: "'a::real_normed_vector" and L :: "'b::real_normed_vector" by (simp add: LIM_eq) lemma LIM_offset: "f \<midarrow>a\<rightarrow> L \<Longrightarrow> (\<lambda>x. f (x + k)) \<midarrow>(a - k)\<rightarrow> L" for a :: "'a::real_normed_vector" by (simp add: filtermap_at_shift[symmetric, of a k] filterlim_def filtermap_filtermap) lemma LIM_offset_zero: "f \<midarrow>a\<rightarrow> L \<Longrightarrow> (\<lambda>h. f (a + h)) \<midarrow>0\<rightarrow> L" for a :: "'a::real_normed_vector" by (drule LIM_offset [where k = a]) (simp add: add.commute) lemma LIM_offset_zero_cancel: "(\<lambda>h. f (a + h)) \<midarrow>0\<rightarrow> L \<Longrightarrow> f \<midarrow>a\<rightarrow> L" for a :: "'a::real_normed_vector" by (drule LIM_offset [where k = "- a"]) simp lemma LIM_offset_zero_iff: "f \<midarrow>a\<rightarrow> L \<longleftrightarrow> (\<lambda>h. f (a + h)) \<midarrow>0\<rightarrow> L" for f :: "'a :: real_normed_vector \<Rightarrow> _" using LIM_offset_zero_cancel[of f a L] LIM_offset_zero[of f L a] by auto lemma tendsto_offset_zero_iff: fixes f :: "'a :: real_normed_vector \<Rightarrow> _" assumes "a \<in> S" "open S" shows "(f \<longlongrightarrow> L) (at a within S) \<longleftrightarrow> ((\<lambda>h. f (a + h)) \<longlongrightarrow> L) (at 0)" by (metis LIM_offset_zero_iff assms tendsto_within_open) lemma LIM_zero: "(f \<longlongrightarrow> l) F \<Longrightarrow> ((\<lambda>x. f x - l) \<longlongrightarrow> 0) F" for f :: "'a \<Rightarrow> 'b::real_normed_vector" unfolding tendsto_iff dist_norm by simp lemma LIM_zero_cancel: fixes f :: "'a \<Rightarrow> 'b::real_normed_vector" shows "((\<lambda>x. f x - l) \<longlongrightarrow> 0) F \<Longrightarrow> (f \<longlongrightarrow> l) F" unfolding tendsto_iff dist_norm by simp lemma LIM_zero_iff: "((\<lambda>x. f x - l) \<longlongrightarrow> 0) F = (f \<longlongrightarrow> l) F" for f :: "'a \<Rightarrow> 'b::real_normed_vector" unfolding tendsto_iff dist_norm by simp lemma LIM_imp_LIM: fixes f :: "'a::topological_space \<Rightarrow> 'b::real_normed_vector" fixes g :: "'a::topological_space \<Rightarrow> 'c::real_normed_vector" assumes f: "f \<midarrow>a\<rightarrow> l" and le: "\<And>x. x \<noteq> a \<Longrightarrow> norm (g x - m) \<le> norm (f x - l)" shows "g \<midarrow>a\<rightarrow> m" by (rule metric_LIM_imp_LIM [OF f]) (simp add: dist_norm le) lemma LIM_equal2: fixes f g :: "'a::real_normed_vector \<Rightarrow> 'b::topological_space" assumes "0 < R" and "\<And>x. x \<noteq> a \<Longrightarrow> norm (x - a) < R \<Longrightarrow> f x = g x" shows "g \<midarrow>a\<rightarrow> l \<Longrightarrow> f \<midarrow>a\<rightarrow> l" by (rule metric_LIM_equal2 [OF _ assms]) (simp_all add: dist_norm) lemma LIM_compose2: fixes a :: "'a::real_normed_vector" assumes f: "f \<midarrow>a\<rightarrow> b" and g: "g \<midarrow>b\<rightarrow> c" and inj: "\<exists>d>0. \<forall>x. x \<noteq> a \<and> norm (x - a) < d \<longrightarrow> f x \<noteq> b" shows "(\<lambda>x. g (f x)) \<midarrow>a\<rightarrow> c" by (rule metric_LIM_compose2 [OF f g inj [folded dist_norm]]) lemma real_LIM_sandwich_zero: fixes f g :: "'a::topological_space \<Rightarrow> real" assumes f: "f \<midarrow>a\<rightarrow> 0" and 1: "\<And>x. x \<noteq> a \<Longrightarrow> 0 \<le> g x" and 2: "\<And>x. x \<noteq> a \<Longrightarrow> g x \<le> f x" shows "g \<midarrow>a\<rightarrow> 0" proof (rule LIM_imp_LIM [OF f]) (* FIXME: use tendsto_sandwich *) fix x assume x: "x \<noteq> a" with 1 have "norm (g x - 0) = g x" by simp also have "g x \<le> f x" by (rule 2 [OF x]) also have "f x \<le> \<bar>f x\<bar>" by (rule abs_ge_self) also have "\<bar>f x\<bar> = norm (f x - 0)" by simp finally show "norm (g x - 0) \<le> norm (f x - 0)" . qed subsection \<open>Continuity\<close> lemma LIM_isCont_iff: "(f \<midarrow>a\<rightarrow> f a) = ((\<lambda>h. f (a + h)) \<midarrow>0\<rightarrow> f a)" for f :: "'a::real_normed_vector \<Rightarrow> 'b::topological_space" by (rule iffI [OF LIM_offset_zero LIM_offset_zero_cancel]) lemma isCont_iff: "isCont f x = (\<lambda>h. f (x + h)) \<midarrow>0\<rightarrow> f x" for f :: "'a::real_normed_vector \<Rightarrow> 'b::topological_space" by (simp add: isCont_def LIM_isCont_iff) lemma isCont_LIM_compose2: fixes a :: "'a::real_normed_vector" assumes f [unfolded isCont_def]: "isCont f a" and g: "g \<midarrow>f a\<rightarrow> l" and inj: "\<exists>d>0. \<forall>x. x \<noteq> a \<and> norm (x - a) < d \<longrightarrow> f x \<noteq> f a" shows "(\<lambda>x. g (f x)) \<midarrow>a\<rightarrow> l" by (rule LIM_compose2 [OF f g inj]) lemma isCont_norm [simp]: "isCont f a \<Longrightarrow> isCont (\<lambda>x. norm (f x)) a" for f :: "'a::t2_space \<Rightarrow> 'b::real_normed_vector" by (fact continuous_norm) lemma isCont_rabs [simp]: "isCont f a \<Longrightarrow> isCont (\<lambda>x. \<bar>f x\<bar>) a" for f :: "'a::t2_space \<Rightarrow> real" by (fact continuous_rabs) lemma isCont_add [simp]: "isCont f a \<Longrightarrow> isCont g a \<Longrightarrow> isCont (\<lambda>x. f x + g x) a" for f :: "'a::t2_space \<Rightarrow> 'b::topological_monoid_add" by (fact continuous_add) lemma isCont_minus [simp]: "isCont f a \<Longrightarrow> isCont (\<lambda>x. - f x) a" for f :: "'a::t2_space \<Rightarrow> 'b::real_normed_vector" by (fact continuous_minus) lemma isCont_diff [simp]: "isCont f a \<Longrightarrow> isCont g a \<Longrightarrow> isCont (\<lambda>x. f x - g x) a" for f :: "'a::t2_space \<Rightarrow> 'b::real_normed_vector" by (fact continuous_diff) lemma isCont_mult [simp]: "isCont f a \<Longrightarrow> isCont g a \<Longrightarrow> isCont (\<lambda>x. f x * g x) a" for f g :: "'a::t2_space \<Rightarrow> 'b::real_normed_algebra" by (fact continuous_mult) lemma (in bounded_linear) isCont: "isCont g a \<Longrightarrow> isCont (\<lambda>x. f (g x)) a" by (fact continuous) lemma (in bounded_bilinear) isCont: "isCont f a \<Longrightarrow> isCont g a \<Longrightarrow> isCont (\<lambda>x. f x ** g x) a" by (fact continuous) lemmas isCont_scaleR [simp] = bounded_bilinear.isCont [OF bounded_bilinear_scaleR] lemmas isCont_of_real [simp] = bounded_linear.isCont [OF bounded_linear_of_real] lemma isCont_power [simp]: "isCont f a \<Longrightarrow> isCont (\<lambda>x. f x ^ n) a" for f :: "'a::t2_space \<Rightarrow> 'b::{power,real_normed_algebra}" by (fact continuous_power) lemma isCont_sum [simp]: "\<forall>i\<in>A. isCont (f i) a \<Longrightarrow> isCont (\<lambda>x. \<Sum>i\<in>A. f i x) a" for f :: "'a \<Rightarrow> 'b::t2_space \<Rightarrow> 'c::topological_comm_monoid_add" by (auto intro: continuous_sum) subsection \<open>Uniform Continuity\<close> lemma uniformly_continuous_on_def: fixes f :: "'a::metric_space \<Rightarrow> 'b::metric_space" shows "uniformly_continuous_on s f \<longleftrightarrow> (\<forall>e>0. \<exists>d>0. \<forall>x\<in>s. \<forall>x'\<in>s. dist x' x < d \<longrightarrow> dist (f x') (f x) < e)" unfolding uniformly_continuous_on_uniformity uniformity_dist filterlim_INF filterlim_principal eventually_inf_principal by (force simp: Ball_def uniformity_dist[symmetric] eventually_uniformity_metric) abbreviation isUCont :: "['a::metric_space \<Rightarrow> 'b::metric_space] \<Rightarrow> bool" where "isUCont f \<equiv> uniformly_continuous_on UNIV f" lemma isUCont_def: "isUCont f \<longleftrightarrow> (\<forall>r>0. \<exists>s>0. \<forall>x y. dist x y < s \<longrightarrow> dist (f x) (f y) < r)" by (auto simp: uniformly_continuous_on_def dist_commute) lemma isUCont_isCont: "isUCont f \<Longrightarrow> isCont f x" by (drule uniformly_continuous_imp_continuous) (simp add: continuous_on_eq_continuous_at) lemma uniformly_continuous_on_Cauchy: fixes f :: "'a::metric_space \<Rightarrow> 'b::metric_space" assumes "uniformly_continuous_on S f" "Cauchy X" "\<And>n. X n \<in> S" shows "Cauchy (\<lambda>n. f (X n))" using assms unfolding uniformly_continuous_on_def by (meson Cauchy_def) lemma isUCont_Cauchy: "isUCont f \<Longrightarrow> Cauchy X \<Longrightarrow> Cauchy (\<lambda>n. f (X n))" by (rule uniformly_continuous_on_Cauchy[where S=UNIV and f=f]) simp_all lemma uniformly_continuous_imp_Cauchy_continuous: fixes f :: "'a::metric_space \<Rightarrow> 'b::metric_space" shows "\<lbrakk>uniformly_continuous_on S f; Cauchy \<sigma>; \<And>n. (\<sigma> n) \<in> S\<rbrakk> \<Longrightarrow> Cauchy(f \<circ> \<sigma>)" by (simp add: uniformly_continuous_on_def Cauchy_def) meson lemma (in bounded_linear) isUCont: "isUCont f" unfolding isUCont_def dist_norm proof (intro allI impI) fix r :: real assume r: "0 < r" obtain K where K: "0 < K" and norm_le: "norm (f x) \<le> norm x * K" for x using pos_bounded by blast show "\<exists>s>0. \<forall>x y. norm (x - y) < s \<longrightarrow> norm (f x - f y) < r" proof (rule exI, safe) from r K show "0 < r / K" by simp next fix x y :: 'a assume xy: "norm (x - y) < r / K" have "norm (f x - f y) = norm (f (x - y))" by (simp only: diff) also have "\<dots> \<le> norm (x - y) * K" by (rule norm_le) also from K xy have "\<dots> < r" by (simp only: pos_less_divide_eq) finally show "norm (f x - f y) < r" . qed qed lemma (in bounded_linear) Cauchy: "Cauchy X \<Longrightarrow> Cauchy (\<lambda>n. f (X n))" by (rule isUCont [THEN isUCont_Cauchy]) lemma LIM_less_bound: fixes f :: "real \<Rightarrow> real" assumes ev: "b < x" "\<forall> x' \<in> { b <..< x}. 0 \<le> f x'" and "isCont f x" shows "0 \<le> f x" proof (rule tendsto_lowerbound) show "(f \<longlongrightarrow> f x) (at_left x)" using \<open>isCont f x\<close> by (simp add: filterlim_at_split isCont_def) show "eventually (\<lambda>x. 0 \<le> f x) (at_left x)" using ev by (auto simp: eventually_at dist_real_def intro!: exI[of _ "x - b"]) qed simp subsection \<open>Nested Intervals and Bisection -- Needed for Compactness\<close> lemma nested_sequence_unique: assumes "\<forall>n. f n \<le> f (Suc n)" "\<forall>n. g (Suc n) \<le> g n" "\<forall>n. f n \<le> g n" "(\<lambda>n. f n - g n) \<longlonglongrightarrow> 0" shows "\<exists>l::real. ((\<forall>n. f n \<le> l) \<and> f \<longlonglongrightarrow> l) \<and> ((\<forall>n. l \<le> g n) \<and> g \<longlonglongrightarrow> l)" proof - have "incseq f" unfolding incseq_Suc_iff by fact have "decseq g" unfolding decseq_Suc_iff by fact have "f n \<le> g 0" for n proof - from \<open>decseq g\<close> have "g n \<le> g 0" by (rule decseqD) simp with \<open>\<forall>n. f n \<le> g n\<close>[THEN spec, of n] show ?thesis by auto qed then obtain u where "f \<longlonglongrightarrow> u" "\<forall>i. f i \<le> u" using incseq_convergent[OF \<open>incseq f\<close>] by auto moreover have "f 0 \<le> g n" for n proof - from \<open>incseq f\<close> have "f 0 \<le> f n" by (rule incseqD) simp with \<open>\<forall>n. f n \<le> g n\<close>[THEN spec, of n] show ?thesis by simp qed then obtain l where "g \<longlonglongrightarrow> l" "\<forall>i. l \<le> g i" using decseq_convergent[OF \<open>decseq g\<close>] by auto moreover note LIMSEQ_unique[OF assms(4) tendsto_diff[OF \<open>f \<longlonglongrightarrow> u\<close> \<open>g \<longlonglongrightarrow> l\<close>]] ultimately show ?thesis by auto qed lemma Bolzano[consumes 1, case_names trans local]: fixes P :: "real \<Rightarrow> real \<Rightarrow> bool" assumes [arith]: "a \<le> b" and trans: "\<And>a b c. P a b \<Longrightarrow> P b c \<Longrightarrow> a \<le> b \<Longrightarrow> b \<le> c \<Longrightarrow> P a c" and local: "\<And>x. a \<le> x \<Longrightarrow> x \<le> b \<Longrightarrow> \<exists>d>0. \<forall>a b. a \<le> x \<and> x \<le> b \<and> b - a < d \<longrightarrow> P a b" shows "P a b" proof - define bisect where "bisect = rec_nat (a, b) (\<lambda>n (x, y). if P x ((x+y) / 2) then ((x+y)/2, y) else (x, (x+y)/2))" define l u where "l n = fst (bisect n)" and "u n = snd (bisect n)" for n have l[simp]: "l 0 = a" "\<And>n. l (Suc n) = (if P (l n) ((l n + u n) / 2) then (l n + u n) / 2 else l n)" and u[simp]: "u 0 = b" "\<And>n. u (Suc n) = (if P (l n) ((l n + u n) / 2) then u n else (l n + u n) / 2)" by (simp_all add: l_def u_def bisect_def split: prod.split) have [simp]: "l n \<le> u n" for n by (induct n) auto have "\<exists>x. ((\<forall>n. l n \<le> x) \<and> l \<longlonglongrightarrow> x) \<and> ((\<forall>n. x \<le> u n) \<and> u \<longlonglongrightarrow> x)" proof (safe intro!: nested_sequence_unique) show "l n \<le> l (Suc n)" "u (Suc n) \<le> u n" for n by (induct n) auto next have "l n - u n = (a - b) / 2^n" for n by (induct n) (auto simp: field_simps) then show "(\<lambda>n. l n - u n) \<longlonglongrightarrow> 0" by (simp add: LIMSEQ_divide_realpow_zero) qed fact then obtain x where x: "\<And>n. l n \<le> x" "\<And>n. x \<le> u n" and "l \<longlonglongrightarrow> x" "u \<longlonglongrightarrow> x" by auto obtain d where "0 < d" and d: "a \<le> x \<Longrightarrow> x \<le> b \<Longrightarrow> b - a < d \<Longrightarrow> P a b" for a b using \<open>l 0 \<le> x\<close> \<open>x \<le> u 0\<close> local[of x] by auto show "P a b" proof (rule ccontr) assume "\<not> P a b" have "\<not> P (l n) (u n)" for n proof (induct n) case 0 then show ?case by (simp add: \<open>\<not> P a b\<close>) next case (Suc n) with trans[of "l n" "(l n + u n) / 2" "u n"] show ?case by auto qed moreover { have "eventually (\<lambda>n. x - d / 2 < l n) sequentially" using \<open>0 < d\<close> \<open>l \<longlonglongrightarrow> x\<close> by (intro order_tendstoD[of _ x]) auto moreover have "eventually (\<lambda>n. u n < x + d / 2) sequentially" using \<open>0 < d\<close> \<open>u \<longlonglongrightarrow> x\<close> by (intro order_tendstoD[of _ x]) auto ultimately have "eventually (\<lambda>n. P (l n) (u n)) sequentially" proof eventually_elim case (elim n) from add_strict_mono[OF this] have "u n - l n < d" by simp with x show "P (l n) (u n)" by (rule d) qed } ultimately show False by simp qed qed lemma compact_Icc[simp, intro]: "compact {a .. b::real}" proof (cases "a \<le> b", rule compactI) fix C assume C: "a \<le> b" "\<forall>t\<in>C. open t" "{a..b} \<subseteq> \<Union>C" define T where "T = {a .. b}" from C(1,3) show "\<exists>C'\<subseteq>C. finite C' \<and> {a..b} \<subseteq> \<Union>C'" proof (induct rule: Bolzano) case (trans a b c) then have *: "{a..c} = {a..b} \<union> {b..c}" by auto with trans obtain C1 C2 where "C1\<subseteq>C" "finite C1" "{a..b} \<subseteq> \<Union>C1" "C2\<subseteq>C" "finite C2" "{b..c} \<subseteq> \<Union>C2" by auto with trans show ?case unfolding * by (intro exI[of _ "C1 \<union> C2"]) auto next case (local x) with C have "x \<in> \<Union>C" by auto with C(2) obtain c where "x \<in> c" "open c" "c \<in> C" by auto then obtain e where "0 < e" "{x - e <..< x + e} \<subseteq> c" by (auto simp: open_dist dist_real_def subset_eq Ball_def abs_less_iff) with \<open>c \<in> C\<close> show ?case by (safe intro!: exI[of _ "e/2"] exI[of _ "{c}"]) auto qed qed simp lemma continuous_image_closed_interval: fixes a b and f :: "real \<Rightarrow> real" defines "S \<equiv> {a..b}" assumes "a \<le> b" and f: "continuous_on S f" shows "\<exists>c d. f`S = {c..d} \<and> c \<le> d" proof - have S: "compact S" "S \<noteq> {}" using \<open>a \<le> b\<close> by (auto simp: S_def) obtain c where "c \<in> S" "\<forall>d\<in>S. f d \<le> f c" using continuous_attains_sup[OF S f] by auto moreover obtain d where "d \<in> S" "\<forall>c\<in>S. f d \<le> f c" using continuous_attains_inf[OF S f] by auto moreover have "connected (f`S)" using connected_continuous_image[OF f] connected_Icc by (auto simp: S_def) ultimately have "f ` S = {f d .. f c} \<and> f d \<le> f c" by (auto simp: connected_iff_interval) then show ?thesis by auto qed lemma open_Collect_positive: fixes f :: "'a::topological_space \<Rightarrow> real" assumes f: "continuous_on s f" shows "\<exists>A. open A \<and> A \<inter> s = {x\<in>s. 0 < f x}" using continuous_on_open_invariant[THEN iffD1, OF f, rule_format, of "{0 <..}"] by (auto simp: Int_def field_simps) lemma open_Collect_less_Int: fixes f g :: "'a::topological_space \<Rightarrow> real" assumes f: "continuous_on s f" and g: "continuous_on s g" shows "\<exists>A. open A \<and> A \<inter> s = {x\<in>s. f x < g x}" using open_Collect_positive[OF continuous_on_diff[OF g f]] by (simp add: field_simps) subsection \<open>Boundedness of continuous functions\<close> text\<open>By bisection, function continuous on closed interval is bounded above\<close> lemma isCont_eq_Ub: fixes f :: "real \<Rightarrow> 'a::linorder_topology" shows "a \<le> b \<Longrightarrow> \<forall>x::real. a \<le> x \<and> x \<le> b \<longrightarrow> isCont f x \<Longrightarrow> \<exists>M. (\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> f x \<le> M) \<and> (\<exists>x. a \<le> x \<and> x \<le> b \<and> f x = M)" using continuous_attains_sup[of "{a..b}" f] by (auto simp: continuous_at_imp_continuous_on Ball_def Bex_def) lemma isCont_eq_Lb: fixes f :: "real \<Rightarrow> 'a::linorder_topology" shows "a \<le> b \<Longrightarrow> \<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> isCont f x \<Longrightarrow> \<exists>M. (\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> M \<le> f x) \<and> (\<exists>x. a \<le> x \<and> x \<le> b \<and> f x = M)" using continuous_attains_inf[of "{a..b}" f] by (auto simp: continuous_at_imp_continuous_on Ball_def Bex_def) lemma isCont_bounded: fixes f :: "real \<Rightarrow> 'a::linorder_topology" shows "a \<le> b \<Longrightarrow> \<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> isCont f x \<Longrightarrow> \<exists>M. \<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> f x \<le> M" using isCont_eq_Ub[of a b f] by auto lemma isCont_has_Ub: fixes f :: "real \<Rightarrow> 'a::linorder_topology" shows "a \<le> b \<Longrightarrow> \<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> isCont f x \<Longrightarrow> \<exists>M. (\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> f x \<le> M) \<and> (\<forall>N. N < M \<longrightarrow> (\<exists>x. a \<le> x \<and> x \<le> b \<and> N < f x))" using isCont_eq_Ub[of a b f] by auto (*HOL style here: object-level formulations*) lemma IVT_objl: "(f a \<le> y \<and> y \<le> f b \<and> a \<le> b \<and> (\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> isCont f x)) \<longrightarrow> (\<exists>x. a \<le> x \<and> x \<le> b \<and> f x = y)" for a y :: real by (blast intro: IVT) lemma IVT2_objl: "(f b \<le> y \<and> y \<le> f a \<and> a \<le> b \<and> (\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> isCont f x)) \<longrightarrow> (\<exists>x. a \<le> x \<and> x \<le> b \<and> f x = y)" for b y :: real by (blast intro: IVT2) lemma isCont_Lb_Ub: fixes f :: "real \<Rightarrow> real" assumes "a \<le> b" "\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> isCont f x" shows "\<exists>L M. (\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> L \<le> f x \<and> f x \<le> M) \<and> (\<forall>y. L \<le> y \<and> y \<le> M \<longrightarrow> (\<exists>x. a \<le> x \<and> x \<le> b \<and> (f x = y)))" proof - obtain M where M: "a \<le> M" "M \<le> b" "\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> f x \<le> f M" using isCont_eq_Ub[OF assms] by auto obtain L where L: "a \<le> L" "L \<le> b" "\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> f L \<le> f x" using isCont_eq_Lb[OF assms] by auto have "(\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> f L \<le> f x \<and> f x \<le> f M)" using M L by simp moreover have "(\<forall>y. f L \<le> y \<and> y \<le> f M \<longrightarrow> (\<exists>x\<ge>a. x \<le> b \<and> f x = y))" proof (cases "L \<le> M") case True then show ?thesis using IVT[of f L _ M] M L assms by (metis order.trans) next case False then show ?thesis using IVT2[of f L _ M] by (metis L(2) M(1) assms(2) le_cases order.trans) qed ultimately show ?thesis by blast qed text \<open>Continuity of inverse function.\<close> lemma isCont_inverse_function: fixes f g :: "real \<Rightarrow> real" assumes d: "0 < d" and inj: "\<And>z. \<bar>z-x\<bar> \<le> d \<Longrightarrow> g (f z) = z" and cont: "\<And>z. \<bar>z-x\<bar> \<le> d \<Longrightarrow> isCont f z" shows "isCont g (f x)" proof - let ?A = "f (x - d)" let ?B = "f (x + d)" let ?D = "{x - d..x + d}" have f: "continuous_on ?D f" using cont by (intro continuous_at_imp_continuous_on ballI) auto then have g: "continuous_on (f`?D) g" using inj by (intro continuous_on_inv) auto from d f have "{min ?A ?B <..< max ?A ?B} \<subseteq> f ` ?D" by (intro connected_contains_Ioo connected_continuous_image) (auto split: split_min split_max) with g have "continuous_on {min ?A ?B <..< max ?A ?B} g" by (rule continuous_on_subset) moreover have "(?A < f x \<and> f x < ?B) \<or> (?B < f x \<and> f x < ?A)" using d inj by (intro continuous_inj_imp_mono[OF _ _ f] inj_on_imageI2[of g, OF inj_onI]) auto then have "f x \<in> {min ?A ?B <..< max ?A ?B}" by auto ultimately show ?thesis by (simp add: continuous_on_eq_continuous_at) qed lemma isCont_inverse_function2: fixes f g :: "real \<Rightarrow> real" shows "\<lbrakk>a < x; x < b; \<And>z. \<lbrakk>a \<le> z; z \<le> b\<rbrakk> \<Longrightarrow> g (f z) = z; \<And>z. \<lbrakk>a \<le> z; z \<le> b\<rbrakk> \<Longrightarrow> isCont f z\<rbrakk> \<Longrightarrow> isCont g (f x)" apply (rule isCont_inverse_function [where f=f and d="min (x - a) (b - x)"]) apply (simp_all add: abs_le_iff) done text \<open>Bartle/Sherbert: Introduction to Real Analysis, Theorem 4.2.9, p. 110.\<close> lemma LIM_fun_gt_zero: "f \<midarrow>c\<rightarrow> l \<Longrightarrow> 0 < l \<Longrightarrow> \<exists>r. 0 < r \<and> (\<forall>x. x \<noteq> c \<and> \<bar>c - x\<bar> < r \<longrightarrow> 0 < f x)" for f :: "real \<Rightarrow> real" by (force simp: dest: LIM_D) lemma LIM_fun_less_zero: "f \<midarrow>c\<rightarrow> l \<Longrightarrow> l < 0 \<Longrightarrow> \<exists>r. 0 < r \<and> (\<forall>x. x \<noteq> c \<and> \<bar>c - x\<bar> < r \<longrightarrow> f x < 0)" for f :: "real \<Rightarrow> real" by (drule LIM_D [where r="-l"]) force+ lemma LIM_fun_not_zero: "f \<midarrow>c\<rightarrow> l \<Longrightarrow> l \<noteq> 0 \<Longrightarrow> \<exists>r. 0 < r \<and> (\<forall>x. x \<noteq> c \<and> \<bar>c - x\<bar> < r \<longrightarrow> f x \<noteq> 0)" for f :: "real \<Rightarrow> real" using LIM_fun_gt_zero[of f l c] LIM_fun_less_zero[of f l c] by (auto simp: neq_iff) end
theory RelationalIncorrectness imports "HOL-IMP.Big_Step" begin (* Author: Toby Murray *) section "Under-Approximate Relational Judgement" text {* This is the relational analogue of OHearn's~\cite{OHearn_19} and de Vries \& Koutavas'~\cite{deVries_Koutavas_11} judgements. Note that in our case it doesn't really make sense to talk about ``erroneous'' states: the presence of an error can be seen only by the violation of a relation. Unlike O'Hearn, we cannot encode it directly into the semantics of our programs, without giving them a relational semantics. We use the standard big step semantics of IMP unchanged. *} type_synonym rassn = "state \<Rightarrow> state \<Rightarrow> bool" definition ir_valid :: "rassn \<Rightarrow> com \<Rightarrow> com \<Rightarrow> rassn \<Rightarrow> bool" where "ir_valid P c c' Q \<equiv> (\<forall> t t'. Q t t' \<longrightarrow> (\<exists>s s'. P s s' \<and> (c,s) \<Rightarrow> t \<and> (c',s') \<Rightarrow> t'))" section "Rules of the Logic" definition flip :: "rassn \<Rightarrow> rassn" where "flip P \<equiv> \<lambda>s s'. P s' s" inductive ir_hoare :: "rassn \<Rightarrow> com \<Rightarrow> com \<Rightarrow> rassn \<Rightarrow> bool" where ir_Skip: "(\<And>t t'. Q t t' \<Longrightarrow> \<exists>s'. P t s' \<and> (c',s') \<Rightarrow> t') \<Longrightarrow> ir_hoare P SKIP c' Q" | ir_If_True: "ir_hoare (\<lambda>s s'. P s s' \<and> bval b s) c\<^sub>1 c' Q \<Longrightarrow> ir_hoare P (IF b THEN c\<^sub>1 ELSE c\<^sub>2) c' Q" | ir_If_False: "ir_hoare (\<lambda>s s'. P s s' \<and> \<not> bval b s) c\<^sub>2 c' Q \<Longrightarrow> ir_hoare P (IF b THEN c\<^sub>1 ELSE c\<^sub>2) c' Q" | ir_Seq1: "ir_hoare P c c' Q \<Longrightarrow> ir_hoare Q d SKIP R \<Longrightarrow> ir_hoare P (Seq c d) c' R" | ir_Assign: "ir_hoare (\<lambda>t t'. \<exists> v. P (t(x := v)) t' \<and> (t x) = aval e (t(x := v))) SKIP c' Q \<Longrightarrow> ir_hoare P (Assign x e) c' Q" | ir_While_False: "ir_hoare (\<lambda>s s'. P s s' \<and> \<not> bval b s) SKIP c' Q \<Longrightarrow> ir_hoare P (WHILE b DO c) c' Q" | ir_While_True: "ir_hoare (\<lambda>s s'. P s s' \<and> bval b s) (c;; WHILE b DO c) c' Q \<Longrightarrow> ir_hoare P (WHILE b DO c) c' Q" | ir_While_backwards_frontier: "(\<And>n. ir_hoare (\<lambda> s s'. P n s s' \<and> bval b s) c SKIP (P (Suc n))) \<Longrightarrow> ir_hoare (\<lambda>s s'. \<exists>n. P n s s') (WHILE b DO c) c' Q \<Longrightarrow> ir_hoare (P 0) (WHILE b DO c) c' Q" | ir_conseq: "ir_hoare P c c' Q \<Longrightarrow> (\<And>s s'. P s s' \<Longrightarrow> P' s s') \<Longrightarrow> (\<And>s s'. Q' s s' \<Longrightarrow> Q s s') \<Longrightarrow> ir_hoare P' c c' Q'" | ir_disj: "ir_hoare P\<^sub>1 c c' Q\<^sub>1 \<Longrightarrow> ir_hoare P\<^sub>2 c c' Q\<^sub>2 \<Longrightarrow> ir_hoare (\<lambda>s s'. P\<^sub>1 s s' \<or> P\<^sub>2 s s') c c' (\<lambda> t t'. Q\<^sub>1 t t' \<or> Q\<^sub>2 t t')" | ir_sym: "ir_hoare (flip P) c c' (flip Q) \<Longrightarrow> ir_hoare P c' c Q" section "Simple Derived Rules" lemma meh_simp[simp]: "(SKIP, s') \<Rightarrow> t' = (s' = t')" by auto lemma ir_pre: "ir_hoare P c c' Q \<Longrightarrow> (\<And>s s'. P s s' \<Longrightarrow> P' s s') \<Longrightarrow> ir_hoare P' c c' Q" by(erule ir_conseq, blast+) lemma ir_post: "ir_hoare P c c' Q \<Longrightarrow> (\<And>s s'. Q' s s' \<Longrightarrow> Q s s') \<Longrightarrow> ir_hoare P c c' Q'" by(erule ir_conseq, blast+) section "Soundness" lemma Skip_ir_valid[intro]: "(\<And>t t'. Q t t' \<Longrightarrow> \<exists>s'. P t s' \<and> (c', s') \<Rightarrow> t') \<Longrightarrow> ir_valid P SKIP c' Q" by(auto simp: ir_valid_def) lemma sym_ir_valid[intro]: "ir_valid (flip P) c' c (flip Q) \<Longrightarrow> ir_valid P c c' Q" by(fastforce simp: ir_valid_def flip_def) lemma If_True_ir_valid[intro]: "ir_valid (\<lambda>a c. P a c \<and> bval b a) c\<^sub>1 c' Q \<Longrightarrow> ir_valid P (IF b THEN c\<^sub>1 ELSE c\<^sub>2) c' Q" by(fastforce simp: ir_valid_def) lemma If_False_ir_valid[intro]: "ir_valid (\<lambda>a c. P a c \<and> \<not> bval b a) c\<^sub>2 c' Q \<Longrightarrow> ir_valid P (IF b THEN c\<^sub>1 ELSE c\<^sub>2) c' Q" by(fastforce simp: ir_valid_def) lemma Seq1_ir_valid[intro]: "ir_valid P c c' Q \<Longrightarrow> ir_valid Q d SKIP R \<Longrightarrow> ir_valid P (c;; d) c' R" by(fastforce simp: ir_valid_def) lemma Seq2_ir_valid[intro]: "ir_valid P c SKIP Q \<Longrightarrow> ir_valid Q d c' R \<Longrightarrow> ir_valid P (c;; d) c' R" by(fastforce simp: ir_valid_def) lemma Seq_ir_valid[intro]: "ir_valid P c c' Q \<Longrightarrow> ir_valid Q d d' R \<Longrightarrow> ir_valid P (c;; d) (c';; d') R" by(fastforce simp: ir_valid_def) lemma Assign_blah[intro]: "t x = aval e (t(x := v)) \<Longrightarrow> (x ::= e, t(x := v)) \<Rightarrow> t" using Assign by (metis fun_upd_triv fun_upd_upd) lemma Assign_ir_valid[intro]: "ir_valid (\<lambda>t t'. \<exists> v. P (t(x := v)) t' \<and> (t x) = aval e (t(x := v))) SKIP c' Q \<Longrightarrow> ir_valid P (Assign x e) c' Q" by(fastforce simp: ir_valid_def) lemma While_False_ir_valid[intro]: "ir_valid (\<lambda>s s'. P s s' \<and> \<not> bval b s) SKIP c' Q \<Longrightarrow> ir_valid P (WHILE b DO c) c' Q" by(fastforce simp: ir_valid_def) lemma While_True_ir_valid[intro]: "ir_valid (\<lambda>s s'. P s s' \<and> bval b s) (Seq c (WHILE b DO c)) c' Q \<Longrightarrow> ir_valid P (WHILE b DO c) c' Q" by(clarsimp simp: ir_valid_def, blast) lemma While_backwards_frontier_ir_valid': assumes asm: "\<And>n. \<forall>t t'. P (k + Suc n) t t' \<longrightarrow> (\<exists>s. P (k + n) s t' \<and> bval b s \<and> (c, s) \<Rightarrow> t)" assumes last: "\<forall>t t'. Q t t' \<longrightarrow> (\<exists>s s'. (\<exists>n. P (k + n) s s') \<and> (WHILE b DO c, s) \<Rightarrow> t \<and> (c', s') \<Rightarrow> t')" assumes post: "Q t t'" shows "\<exists>s s'. P k s s' \<and> (WHILE b DO c, s) \<Rightarrow> t \<and> (c', s') \<Rightarrow> t'" proof - from post last obtain s s' n where "P (k + n) s s'" "(WHILE b DO c, s) \<Rightarrow> t" "(c', s') \<Rightarrow> t'" by blast with asm show ?thesis proof(induction n arbitrary: k t t') case 0 then show ?case by (metis WhileFalse WhileTrue add.right_neutral) next case (Suc n) from Suc obtain r r' where final_iteration: "P (Suc k) r r'" "(WHILE b DO c, r) \<Rightarrow> t" "(c', r') \<Rightarrow> t'" by (metis add_Suc_shift) from final_iteration(1) obtain q q' where "P k q r' \<and> bval b q \<and> (c, q) \<Rightarrow> r" by (metis Nat.add_0_right Suc.prems(1) plus_1_eq_Suc semiring_normalization_rules(24)) with final_iteration show ?case by blast qed qed lemma While_backwards_frontier_ir_valid[intro]: "(\<And>n. ir_valid (\<lambda> s s'. P n s s' \<and> bval b s) c SKIP (P (Suc n))) \<Longrightarrow> ir_valid (\<lambda>s s'. \<exists>n. P n s s') (WHILE b DO c) c' Q \<Longrightarrow> ir_valid (P 0) (WHILE b DO c) c' Q" by(auto simp: meh_simp ir_valid_def intro: While_backwards_frontier_ir_valid') lemma conseq_ir_valid: "ir_valid P c c' Q \<Longrightarrow> (\<And>s s'. P s s' \<Longrightarrow> P' s s') \<Longrightarrow> (\<And>s s'. Q' s s' \<Longrightarrow> Q s s') \<Longrightarrow> ir_valid P' c c' Q'" by(clarsimp simp: ir_valid_def, blast) lemma disj_ir_valid[intro]: "ir_valid P\<^sub>1 c c' Q\<^sub>1 \<Longrightarrow> ir_valid P\<^sub>2 c c' Q\<^sub>2 \<Longrightarrow> ir_valid (\<lambda>s s'. P\<^sub>1 s s' \<or> P\<^sub>2 s s') c c' (\<lambda> t t'. Q\<^sub>1 t t' \<or> Q\<^sub>2 t t')" by(fastforce simp: ir_valid_def) theorem soundness: "ir_hoare P c c' Q \<Longrightarrow> ir_valid P c c' Q" apply(induction rule: ir_hoare.induct) apply(blast intro!: Skip_ir_valid) by (blast intro: conseq_ir_valid)+ section "Completeness" lemma ir_Skip_Skip[intro]: "ir_hoare P SKIP SKIP P" by(rule ir_Skip, simp) lemma ir_hoare_Skip_Skip[simp]: "ir_hoare P SKIP SKIP Q = (\<forall>s s'. Q s s' \<longrightarrow> P s s')" using soundness ir_valid_def meh_simp ir_conseq ir_Skip by metis lemma ir_valid_Seq1: "ir_valid P (c1;; c2) c' Q \<Longrightarrow> ir_valid P c1 c' (\<lambda>t t'. \<exists>s s'. P s s' \<and> (c1,s) \<Rightarrow> t \<and> (c',s') \<Rightarrow> t' \<and> (\<exists>u. (c2,t) \<Rightarrow> u \<and> Q u t'))" by(auto simp: ir_valid_def) lemma ir_valid_Seq1': "ir_valid P (c1;; c2) c' Q \<Longrightarrow> ir_valid (\<lambda>t t'. \<exists>s s'. P s s' \<and> (c1,s) \<Rightarrow> t \<and> (c',s') \<Rightarrow> t' \<and> (\<exists>u. (c2,t) \<Rightarrow> u \<and> Q u t')) c2 SKIP Q" by(clarsimp simp: ir_valid_def, meson SeqE) lemma ir_valid_track_history: "ir_valid P c c' Q \<Longrightarrow> ir_valid P c c' (\<lambda>t t'. Q s s' \<and> (\<exists>s s'. P s s' \<and> (c,s) \<Rightarrow> t \<and> (c',s') \<Rightarrow> t'))" by(auto simp: ir_valid_def) lemma ir_valid_If: "ir_valid (\<lambda>s s'. P s s') (IF b THEN c1 ELSE c2) c' Q \<Longrightarrow> ir_valid (\<lambda>s s'. P s s' \<and> bval b s) c1 c' (\<lambda>t t'. Q t t' \<and> (\<exists>s s'. P s s' \<and> (c1,s) \<Rightarrow> t \<and> (c',s') \<Rightarrow> t' \<and> bval b s)) \<and> ir_valid (\<lambda>s s'. P s s' \<and> \<not> bval b s) c2 c' (\<lambda>t t'. Q t t' \<and> (\<exists>s s'. P s s' \<and> (c2,s) \<Rightarrow> t \<and> (c',s') \<Rightarrow> t' \<and> \<not> bval b s))" by(clarsimp simp: ir_valid_def, blast) text {* Inspired by the ``@{text "p(n) = {\<sigma> | you can get back from \<sigma> to some state in p by executing C backwards n times}"}'' part of OHearn~\cite{OHearn_19}. *} primrec get_back where "get_back P b c 0 = (\<lambda>t t'. P t t')" | "get_back P b c (Suc n) = (\<lambda>t t'. \<exists>s. (c,s) \<Rightarrow> t \<and> bval b s \<and> get_back P b c n s t')" (* Currently not used anywhere *) lemma ir_valid_get_back: "ir_valid (get_back P b c (Suc k)) (WHILE b DO c) c' Q \<Longrightarrow> ir_valid (get_back P b c k) (WHILE b DO c) c' Q" proof(induct k) case 0 then show ?case by(clarsimp simp: ir_valid_def, blast) next case (Suc k) then show ?case using WhileTrue get_back.simps(2) ir_valid_def by smt qed (* both this an the next one get used in the completeness proof *) lemma ir_valid_While1: "ir_valid (get_back P b c k) (WHILE b DO c) c' Q \<Longrightarrow> (ir_valid (\<lambda>s s'. get_back P b c k s s' \<and> bval b s) c SKIP (\<lambda>t t'. get_back P b c (Suc k) t t' \<and> (\<exists>u u'. (WHILE b DO c,t) \<Rightarrow> u \<and> (c',t') \<Rightarrow> u' \<and> Q u u')))" proof (subst ir_valid_def, clarsimp) fix t t' s u u' assume "ir_valid (get_back P b c k) (WHILE b DO c) c' Q" "(WHILE b DO c, t) \<Rightarrow> u" "(c, s) \<Rightarrow> t" "(c', t') \<Rightarrow> u'" "Q u u'" "bval b s" "get_back P b c k s t'" thus "\<exists>s. get_back P b c k s t' \<and> bval b s \<and> (c, s) \<Rightarrow> t" proof(induction k arbitrary: t t' s u u') case 0 then show ?case by auto next case (Suc k) show ?case using Suc.prems(3) Suc.prems(6) Suc.prems(7) by blast qed qed lemma ir_valid_While3: "ir_valid (get_back P b c k) (WHILE b DO c) c' Q \<Longrightarrow> (ir_valid (\<lambda>s s'. get_back P b c k s s' \<and> bval b s) c c' (\<lambda>t t'. (\<exists>s'. (c',s') \<Rightarrow> t' \<and> get_back P b c (Suc k) t s' \<and> (\<exists>u. (WHILE b DO c,t) \<Rightarrow> u \<and> Q u t'))))" apply(subst ir_valid_def, clarsimp) proof - fix t t' s' s u assume "ir_valid (get_back P b c k) (WHILE b DO c) c' Q" "(WHILE b DO c, t) \<Rightarrow> u" "(c, s) \<Rightarrow> t" "(c', s') \<Rightarrow> t'" "Q u t'" "bval b s" "get_back P b c k s s'" thus "\<exists>s s'. get_back P b c k s s' \<and> bval b s \<and> (c, s) \<Rightarrow> t \<and> (c',s') \<Rightarrow> t'" proof(induction k arbitrary: t t' s' s u) case 0 then show ?case by auto next case (Suc k) show ?case using Suc.prems(3) Suc.prems(4) Suc.prems(6) Suc.prems(7) by blast qed qed (* not used anywhere *) lemma ir_valid_While2: "ir_valid P (WHILE b DO c) c' Q \<Longrightarrow> ir_valid (\<lambda>s s'. P s s' \<and> \<not> bval b s) SKIP c' (\<lambda>t t'. Q t t' \<and> (\<exists>s'. (c',s') \<Rightarrow> t' \<and> P t s' \<and> \<not> bval b t))" by(clarsimp simp: ir_valid_def, blast) lemma assign_upd_blah: "(\<lambda>a. if a = x1 then s x1 else (s(x1 := aval x2 s)) a) = s" by(rule ext, auto) lemma Assign_complete: assumes v: "ir_valid P (x1 ::= x2) c' Q" assumes q: "Q t t'" shows "\<exists>s'. (\<exists>v. P (t(x1 := v)) s' \<and> t x1 = aval x2 (t(x1 := v))) \<and> (c', s') \<Rightarrow> t'" proof - from v and q obtain s s' where a: "P s s' \<and> (x1 ::= x2,s) \<Rightarrow> t \<and> (c',s') \<Rightarrow> t'" using ir_valid_def by smt hence "P (\<lambda>a. if a = x1 then s x1 else (s(x1 := aval x2 s)) a) s' \<and> aval x2 s = aval x2 (s(x1 := s x1))" using assign_upd_blah by simp thus ?thesis using assign_upd_blah a by (metis AssignE fun_upd_same fun_upd_triv fun_upd_upd) qed lemmas ir_Skip_sym = ir_sym[OF ir_Skip, simplified flip_def] theorem completeness: "ir_valid P c c' Q \<Longrightarrow> ir_hoare P c c' Q" proof(induct c arbitrary: P c' Q) case SKIP show ?case apply(rule ir_Skip) using SKIP by(fastforce simp: ir_valid_def) next case (Assign x1 x2) show ?case apply(rule ir_Assign) apply(rule ir_Skip) using Assign_complete Assign by blast next case (Seq c1 c2) have a: "ir_hoare P c1 c' (\<lambda>t t'. \<exists>s s'. P s s' \<and> (c1, s) \<Rightarrow> t \<and> (c', s') \<Rightarrow> t' \<and> (\<exists>u. (c2, t) \<Rightarrow> u \<and> Q u t'))" using ir_valid_Seq1 Seq by blast show ?case apply(rule ir_Seq1) apply (blast intro: a) apply(rule ir_Skip_sym) by(metis SeqE ir_valid_def Seq) next case (If x1 c1 c2) have t: "ir_hoare (\<lambda>s s'. P s s' \<and> bval x1 s) c1 c' (\<lambda>t t'. Q t t' \<and> (\<exists>s s'. P s s' \<and> (c1, s) \<Rightarrow> t \<and> (c', s') \<Rightarrow> t' \<and> bval x1 s))" and f: " ir_hoare (\<lambda>s s'. P s s' \<and> \<not> bval x1 s) c2 c' (\<lambda>t t'. Q t t' \<and> (\<exists>s s'. P s s' \<and> (c2, s) \<Rightarrow> t \<and> (c', s') \<Rightarrow> t' \<and> \<not> bval x1 s))" using ir_valid_If If by blast+ show ?case (* consider both cases of the if via conseq, disj, then _True and _False *) apply(rule ir_conseq) apply(rule ir_disj) apply(rule ir_If_True,fastforce intro: t) apply(rule ir_If_False, fastforce intro: f) apply blast by (smt IfE ir_valid_def If) next case (While x1 c) have a: "\<And>n. ir_hoare (\<lambda>s s'. get_back P x1 c n s s' \<and> bval x1 s) c SKIP (get_back P x1 c (Suc n))" using ir_valid_While1 While by (smt get_back.simps(2) ir_valid_def meh_simp) have b: "ir_hoare (\<lambda>s s'. P s s' \<and> bval x1 s) c c' (\<lambda>t t'. \<exists>s'. (c', s') \<Rightarrow> t' \<and> (\<exists>s. (c, s) \<Rightarrow> t \<and> bval x1 s \<and> P s s') \<and> (\<exists>u. (WHILE x1 DO c, t) \<Rightarrow> u \<and> Q u t'))" using ir_valid_While3[where k=0,simplified] While by blast have gb: "\<And>t t'. Q t t' \<and> (\<exists>s'. (c', s') \<Rightarrow> t' \<and> P t s' \<and> \<not> bval x1 t) \<Longrightarrow> \<exists>s'. ((\<exists>n. get_back P x1 c n t s') \<and> \<not> bval x1 t) \<and> (c', s') \<Rightarrow> t'" by (meson get_back.simps(1)) show ?case (* use the frontier rule much as in OHearn POPL *) apply(rule ir_conseq) apply(rule_tac P="get_back P x1 c" in ir_While_backwards_frontier) apply(blast intro: a) (* consider both cases of the While via conseq, disj, then _True and _False *) apply(rule ir_conseq) apply(rule ir_disj) apply(rule_tac P="\<lambda>s s'. \<exists>n. get_back P x1 c n s s'" and Q="(\<lambda>t t'. Q t t' \<and> (\<exists>s'. (c', s') \<Rightarrow> t' \<and> P t s' \<and> \<not> bval x1 t))" in ir_While_False) apply(rule ir_Skip, blast intro: gb) apply(rule ir_While_True) apply(rule ir_Seq1[OF b]) apply(rule ir_Skip_sym) apply(fastforce) apply (metis get_back.simps(1)) apply assumption apply simp by (metis While.prems WhileE ir_valid_def) qed section "A Decomposition Principle: Proofs via Under-Approximate Hoare Logic" text {* We show the under-approximate analogue holds for Beringer's~\cite{Beringer_11} decomposition principle for over-approximate relational logic. *} definition decomp :: "rassn \<Rightarrow> com \<Rightarrow> com \<Rightarrow> rassn \<Rightarrow> rassn" where "decomp P c c' Q \<equiv> \<lambda>t s'. \<exists>s t'. P s s' \<and> (c,s) \<Rightarrow> t \<and> (c',s') \<Rightarrow> t' \<and> Q t t'" lemma ir_valid_decomp1: "ir_valid P c c' Q \<Longrightarrow> ir_valid P c SKIP (decomp P c c' Q) \<and> ir_valid (decomp P c c' Q) SKIP c' Q" by(fastforce simp: ir_valid_def meh_simp decomp_def) lemma ir_valid_decomp2: "ir_valid P c SKIP R \<and> ir_valid R SKIP c' Q \<Longrightarrow> ir_valid P c c' Q" by(fastforce simp: ir_valid_def meh_simp decomp_def) lemma ir_valid_decomp: "ir_valid P c c' Q = (ir_valid P c SKIP (decomp P c c' Q) \<and> ir_valid (decomp P c c' Q) SKIP c' Q)" using ir_valid_decomp1 ir_valid_decomp2 by blast text {* Completeness with soundness means we can prove proof rules about @{term ir_hoare} in terms of @{term ir_valid}. *} lemma ir_to_Skip: "ir_hoare P c c' Q = (ir_hoare P c SKIP (decomp P c c' Q) \<and> ir_hoare (decomp P c c' Q) SKIP c' Q)" using soundness completeness ir_valid_decomp by meson text {* O'Hearn's under-approximate Hoare triple, for the ``ok'' case (since that is the only case we have) This is also likely the same as from the "Reverse Hoare Logic" paper (SEFM). *} type_synonym assn = "state \<Rightarrow> bool" definition ohearn :: "assn \<Rightarrow> com \<Rightarrow> assn \<Rightarrow> bool" where "ohearn P c Q \<equiv> (\<forall>t. Q t \<longrightarrow> (\<exists>s. P s \<and> (c,s) \<Rightarrow> t))" lemma fold_ohearn2: "ir_valid P SKIP c' Q = (\<forall>t. ohearn (P t) c' (Q t))" by(simp add: ir_valid_def ohearn_def) theorem relational_via_hoare: "ir_hoare P c c' Q = ((\<forall>t'. ohearn (\<lambda>t. P t t') c (\<lambda>t. decomp P c c' Q t t')) \<and> (\<forall>t. ohearn (decomp P c c' Q t) c' (Q t)))" proof - have a: "\<And>P c c' Q. ir_hoare P c c' Q = ir_valid P c c' Q" using soundness completeness by auto show ?thesis using ir_to_Skip a fold_ohearn1 fold_ohearn2 by metis qed section "Deriving Proof Rules from Completeness" text {* Note that we can more easily derive proof rules sometimes by appealing to the corresponding properties of @{term ir_valid} than from the proof rules directly. We see more examples of this later on when we consider examples. *} lemma ir_Seq2: "ir_hoare P c SKIP Q \<Longrightarrow> ir_hoare Q d c' R \<Longrightarrow> ir_hoare P (Seq c d) c' R" using soundness completeness Seq2_ir_valid by metis lemma ir_Seq: "ir_hoare P c c' Q \<Longrightarrow> ir_hoare Q d d' R \<Longrightarrow> ir_hoare P (Seq c d) (Seq c' d') R" using soundness completeness Seq_ir_valid by metis section "Examples" subsection "Some Derived Proof Rules" text {* First derive some proof rules -- here not by appealing to completeness but just using the existing rules *} lemma ir_If_True_False: "ir_hoare (\<lambda>s s'. P s s' \<and> bval b s \<and> \<not> bval b' s') c\<^sub>1 c\<^sub>2' Q \<Longrightarrow> ir_hoare P (IF b THEN c\<^sub>1 ELSE c\<^sub>2) (IF b' THEN c\<^sub>1' ELSE c\<^sub>2') Q" apply(rule ir_If_True) apply(rule ir_sym) apply(rule ir_If_False) apply(rule ir_sym) by(simp add: flip_def) lemma ir_Assign_Assign: "ir_hoare P (x ::= e) (x' ::= e') (\<lambda>t t'. \<exists>v v'. P (t(x := v)) (t'(x' := v')) \<and> t x = aval e (t(x := v)) \<and> t' x' = aval e' (t'(x' := v')))" apply(rule ir_Assign) apply(rule ir_sym) apply(rule ir_Assign) by(simp add: flip_def, auto) subsection "prog1" text {* A tiny insecure program. Note that we only need to reason on one path through this program to detect that it is insecure. *} abbreviation low_eq :: rassn where "low_eq s s' \<equiv> s ''low'' = s' ''low''" abbreviation low_neq :: rassn where "low_neq s s' \<equiv> \<not> low_eq s s'" definition prog1 :: com where "prog1 \<equiv> (IF (Less (N 0) (V ''x'')) THEN (Assign ''low'' (N 1)) ELSE (Assign ''low'' (N 0)))" text {* We prove that @{term prog1} is definitely insecure. To do that, we need to find some non-empty post-relation that implies insecurity. The following property encodes the idea that the post-relation is non-empty, i.e. represents a feasible pair of execution paths. *} definition nontrivial :: "rassn \<Rightarrow> bool" where "nontrivial Q \<equiv> (\<exists>t t'. Q t t')" text {* Note the property we prove here explicitly encodes the fact that the postcondition can be anything that implies insecurity, i.e. implies @{term low_neq}. In particular we should not necessarily expect it to cover the entirely of all states that satisfy @{term low_neq}. Also note that we also have to prove that the postcondition is non-trivial. This is necessary to make sure that the violation we find is not an infeasible path. *} lemma prog1: "\<exists>Q. ir_hoare low_eq prog1 prog1 Q \<and> (\<forall>s s'. Q s s' \<longrightarrow> low_neq s s') \<and> nontrivial Q" apply(rule exI) apply(rule conjI) apply(simp add: prog1_def) apply(rule ir_If_True_False) apply(rule ir_Assign_Assign) apply(rule conjI) apply auto[1] apply(clarsimp simp: nontrivial_def) apply(rule_tac x="\<lambda>v. 1" in exI) apply simp apply(rule_tac x="\<lambda>v. 0" in exI) by auto subsection "More Derived Proof Rules for Examples" definition BEq :: "aexp \<Rightarrow> aexp \<Rightarrow> bexp" where "BEq a b \<equiv> And (Less a (Plus b (N 1))) (Less b (Plus a (N 1)))" lemma BEq_aval[simp]: "bval (BEq a b) s = ((aval a s) = (aval b s))" by(auto simp add: BEq_def) lemma ir_If_True_True: "ir_hoare (\<lambda>s s'. P s s' \<and> bval b s \<and> bval b' s') c\<^sub>1 c\<^sub>1' Q\<^sub>1 \<Longrightarrow> ir_hoare P (IF b THEN c\<^sub>1 ELSE c\<^sub>2) (IF b' THEN c\<^sub>1' ELSE c\<^sub>2') (\<lambda>t t'. Q\<^sub>1 t t')" by(simp add: ir_If_True ir_sym flip_def) lemma ir_If_False_False: "ir_hoare (\<lambda>s s'. P s s' \<and> \<not> bval b s \<and> \<not> bval b' s') c\<^sub>2 c\<^sub>2' Q\<^sub>2 \<Longrightarrow> ir_hoare P (IF b THEN c\<^sub>1 ELSE c\<^sub>2) (IF b' THEN c\<^sub>1' ELSE c\<^sub>2') (\<lambda>t t'. Q\<^sub>2 t t')" by(simp add: ir_If_False ir_sym flip_def) lemma ir_If': "ir_hoare (\<lambda>s s'. P s s' \<and> bval b s \<and> bval b' s') c\<^sub>1 c\<^sub>1' Q\<^sub>1 \<Longrightarrow> ir_hoare (\<lambda>s s'. P s s' \<and> \<not> bval b s \<and> \<not> bval b' s') c\<^sub>2 c\<^sub>2' Q\<^sub>2 \<Longrightarrow> ir_hoare P (IF b THEN c\<^sub>1 ELSE c\<^sub>2) (IF b' THEN c\<^sub>1' ELSE c\<^sub>2') (\<lambda>t t'. Q\<^sub>1 t t' \<or> Q\<^sub>2 t t')" apply(rule ir_pre) apply(rule ir_disj) apply(rule ir_If_True_True) apply assumption apply(rule ir_If_False_False) apply assumption apply blast done lemma ir_While_triv: "ir_hoare (\<lambda>s s'. P s s' \<and> \<not> bval b s \<and> \<not> bval b' s') SKIP SKIP Q\<^sub>2 \<Longrightarrow> ir_hoare P (WHILE b DO c) (WHILE b' DO c') (\<lambda>s s'. (Q\<^sub>2 s s'))" by(simp add: ir_While_False ir_sym flip_def) lemma ir_While': "ir_hoare (\<lambda>s s'. P s s' \<and> bval b s \<and> bval b' s') (c;;WHILE b DO c) (c';;WHILE b' DO c') Q\<^sub>1 \<Longrightarrow> ir_hoare (\<lambda>s s'. P s s' \<and> \<not> bval b s \<and> \<not> bval b' s') SKIP SKIP Q\<^sub>2 \<Longrightarrow> ir_hoare P (WHILE b DO c) (WHILE b' DO c') (\<lambda>s s'. (Q\<^sub>1 s s' \<or> Q\<^sub>2 s s'))" apply(rule ir_pre) apply(rule ir_disj) apply(rule ir_While_True) apply(rule ir_sym) apply(simp add: flip_def) apply(rule ir_While_True) apply(rule ir_sym) apply(simp add: flip_def) apply(rule ir_While_triv) apply assumption apply simp done subsection "client0" definition low_eq_strong where "low_eq_strong s s' \<equiv> (s ''high'' \<noteq> s' ''high'') \<and> low_eq s s'" lemma low_eq_strong_upd[simp]: "var \<noteq> ''high'' \<and> var \<noteq> ''low'' \<Longrightarrow> low_eq_strong(s(var := v)) (s'(var := v')) = low_eq_strong s s'" by(auto simp: low_eq_strong_def) text {* A variation on client0 from O'Hearn~\cite{OHearn_19}: how to reason about loops via a single unfolding *} definition client0 :: com where "client0 \<equiv> (Assign ''x'' (N 0);; (While (Less (N 0) (V ''n'')) ((Assign ''x'' (Plus (V ''x'') (V ''n'')));; (Assign ''n'' (V ''nondet''))));; (If (BEq (V ''x'') (N 2000000)) (Assign ''low'' (V ''high'')) SKIP))" lemma client0: "\<exists>Q. ir_hoare low_eq client0 client0 Q \<and> (\<forall>s s'. Q s s' \<longrightarrow> low_neq s s') \<and> nontrivial Q" apply(rule exI, rule conjI, simp add: client0_def) apply(rule_tac P=low_eq_strong in ir_pre) apply(rule ir_Seq) apply(rule ir_Seq) apply(rule ir_Assign_Assign) apply clarsimp apply(rule ir_While') apply clarsimp apply(rule ir_Seq) apply(rule ir_Seq) apply(rule ir_Assign_Assign) apply(rule ir_Assign_Assign) apply clarsimp apply(rule ir_While_triv) apply clarsimp apply assumption apply clarsimp apply assumption apply(rule ir_If_True_True) apply(rule ir_Assign_Assign) apply(fastforce simp: low_eq_strong_def) apply(rule conjI) apply(clarsimp simp: low_eq_strong_def split: if_splits) (* ugh having to manually do constraint solving here... *) apply(clarsimp simp: low_eq_strong_def nontrivial_def) apply(rule_tac x="\<lambda>v. if v = ''x'' then 2000000 else if v = ''high'' then 1 else if v = ''n'' then -1 else if v = ''nondet'' then -1 else if v = ''low'' then 1 else undefined" in exI) apply(rule_tac x="\<lambda>v. if v = ''x'' then 2000000 else if v = ''high'' then 0 else if v = ''n'' then -1 else if v = ''nondet'' then -1 else if v = ''low'' then 0 else undefined" in exI) apply clarsimp done (* Not needed? *) lemma ir_While_backwards: "(\<And>n. ir_hoare (\<lambda> s s'. P n s s' \<and> bval b s) c SKIP (P (Suc n))) \<Longrightarrow> ir_hoare (\<lambda>s s'. \<exists>n. P n s s' \<and> \<not> bval b s) SKIP c' Q \<Longrightarrow> ir_hoare (P 0) (WHILE b DO c) c' Q" apply(rule ir_While_backwards_frontier) apply assumption apply(rule ir_While_False) apply auto done subsection "Derive a variant of the backwards variant rule" text {* Here we appeal to completeness again to derive this rule from the corresponding property about @{term ir_valid}. *} subsection "A variant of the frontier rule" text {* Agin we derive this rule by appealing to completeness and the corresponding property of @{term ir_valid} *} lemma While_backwards_frontier_both_ir_valid': assumes asm: "\<And>n. \<forall>t t'. P (k + Suc n) t t' \<longrightarrow> (\<exists>s s'. P (k + n) s s' \<and> bval b s \<and> bval b' s' \<and> (c, s) \<Rightarrow> t \<and> (c', s') \<Rightarrow> t')" assumes last: "\<forall>t t'. Q t t' \<longrightarrow> (\<exists>s s'. (\<exists>n. P (k + n) s s') \<and> (WHILE b DO c, s) \<Rightarrow> t \<and> (WHILE b' DO c', s') \<Rightarrow> t')" assumes post: "Q t t'" shows "\<exists>s s'. P k s s' \<and> (WHILE b DO c, s) \<Rightarrow> t \<and> (WHILE b' DO c', s') \<Rightarrow> t'" proof - from post last obtain s s' n where "P (k + n) s s'" "(WHILE b DO c, s) \<Rightarrow> t" "(WHILE b' DO c', s') \<Rightarrow> t'" by blast with asm show ?thesis proof(induction n arbitrary: k t t') case 0 then show ?case by (metis WhileFalse WhileTrue add.right_neutral) next case (Suc n) from Suc obtain r r' where final_iteration: "P (Suc k) r r'" "(WHILE b DO c, r) \<Rightarrow> t" "(WHILE b' DO c', r') \<Rightarrow> t'" by (metis add_Suc_shift) from final_iteration(1) obtain q q' where "P k q q' \<and> bval b q \<and> bval b' q' \<and> (c, q) \<Rightarrow> r \<and> (c', q') \<Rightarrow> r'" by (metis Nat.add_0_right Suc.prems(1) plus_1_eq_Suc semiring_normalization_rules(24)) with final_iteration show ?case by blast qed qed lemma While_backwards_frontier_both_ir_valid[intro]: "(\<And>n. ir_valid (\<lambda> s s'. P n s s' \<and> bval b s \<and> bval b' s') c c' (P (Suc n))) \<Longrightarrow> ir_valid (\<lambda>s s'. \<exists>n. P n s s') (WHILE b DO c) (WHILE b' DO c') Q \<Longrightarrow> ir_valid (P 0) (WHILE b DO c) (WHILE b' DO c') (\<lambda>s s'. Q s s')" by(auto simp: ir_valid_def intro: While_backwards_frontier_both_ir_valid') lemma ir_While_backwards_frontier_both: "\<lbrakk>\<And>n. ir_hoare (\<lambda>s s'. P n s s' \<and> bval b s \<and> bval b' s') c c' (P (Suc n)); ir_hoare (\<lambda>s s'. \<exists>n. P n s s') (WHILE b DO c) (WHILE b' DO c') Q\<rbrakk> \<Longrightarrow> ir_hoare (P 0) (WHILE b DO c) (WHILE b' DO c') (\<lambda>s s'. Q s s')" using soundness completeness While_backwards_frontier_both_ir_valid by auto text {* The following rule then follows easily as a special case *} lemma ir_While_backwards_both: "(\<And>n. ir_hoare (\<lambda> s s'. P n s s' \<and> bval b s \<and> bval b' s') c c' (P (Suc n))) \<Longrightarrow> ir_hoare (P 0) (WHILE b DO c) (WHILE b' DO c') (\<lambda>s s'. \<exists>n. P n s s' \<and> \<not> bval b s \<and> \<not> bval b' s')" apply(rule ir_While_backwards_frontier_both) apply blast by(simp add: ir_While_False ir_sym flip_def) subsection "client1" text {* An example roughly equivalent to cient1 from O'Hearn~\cite{OHearn_19}0 In particular we use the backwards variant rule to reason about the loop. *} definition client1 :: com where "client1 \<equiv> (Assign ''x'' (N 0);; (While (Less (V ''x'') (V ''n'')) ((Assign ''x'' (Plus (V ''x'') (N 1)))));; (If (BEq (V ''x'') (N 2000000)) (Assign ''low'' (V ''high'')) SKIP))" lemma client1: "\<exists>Q. ir_hoare low_eq client1 client1 Q \<and> (\<forall>s s'. Q s s' \<longrightarrow> low_neq s s') \<and> nontrivial Q" apply(rule exI, rule conjI, simp add: client1_def) apply(rule_tac P=low_eq_strong in ir_pre) apply(rule ir_Seq) apply(rule ir_Seq) apply(rule ir_Assign_Assign) apply clarsimp apply(rule ir_pre) apply(rule ir_While_backwards_both[where P="\<lambda>n s s'. low_eq_strong s s' \<and> s ''x'' = int n \<and> s' ''x'' = int n \<and> int n \<le> s ''n'' \<and> int n \<le> s' ''n''"]) apply(rule ir_post) apply(rule ir_Assign_Assign) apply clarsimp apply clarsimp apply(rule ir_If_True_True) apply(rule ir_Assign_Assign) apply(fastforce simp: low_eq_strong_def) apply(rule conjI) apply(clarsimp simp: low_eq_strong_def split: if_splits) apply clarsimp (* ugh having to manually do constraint solving here... *) apply(clarsimp simp: low_eq_strong_def nontrivial_def) apply(rule_tac x="\<lambda>v. if v = ''x'' then 2000000 else if v = ''high'' then 1 else if v = ''n'' then 2000000 else if v = ''nondet'' then -1 else if v = ''low'' then 1 else undefined" in exI) apply(rule_tac x="\<lambda>v. if v = ''x'' then 2000000 else if v = ''high'' then 0 else if v = ''n'' then 2000000 else if v = ''nondet'' then -1 else if v = ''low'' then 0 else undefined" in exI) apply clarsimp done subsection "client2" text {* An example akin to client2 from O'Hearn~\cite{OHearn_19}. Note that this example is carefully written to show use of the frontier rule first to reason up to the broken loop iteration, and then we unfold the loop at that point to reason about the broken iteration, and then use the plain backwards variant rule to reason over the remainder of the loop. *} definition client2 :: com where "client2 \<equiv> (Assign ''x'' (N 0);; (While (Less (V ''x'') (N 4000000)) ((Assign ''x'' (Plus (V ''x'') (N 1)));; (If (BEq (V ''x'') (N 2000000)) (Assign ''low'' (V ''high'')) SKIP)) ) )" lemma client2: "\<exists>Q. ir_hoare low_eq client2 client2 Q \<and> (\<forall>s s'. Q s s' \<longrightarrow> low_neq s s') \<and> nontrivial Q" apply(rule exI, rule conjI, simp add: client2_def) apply(rule_tac P=low_eq_strong in ir_pre) apply(rule ir_Seq) apply(rule ir_Assign_Assign) apply clarsimp apply(rule ir_pre) apply(rule ir_While_backwards_frontier_both[where P="\<lambda>n s s'. low_eq_strong s s' \<and> s ''x'' = int n \<and> s' ''x'' = int n \<and> s ''x'' \<ge> 0 \<and> s ''x'' \<le> 2000000 - 1 \<and> s' ''x'' \<ge> 0 \<and> s' ''x'' \<le> 2000000 - 1"]) apply(rule ir_Seq) apply(rule ir_Assign_Assign) apply clarsimp apply(rule ir_post) apply(rule ir_If') apply(rule ir_Assign_Assign) apply(rule ir_Skip_Skip) apply clarsimp apply clarsimp apply(rule ir_While') apply clarsimp apply(rule ir_Seq) apply(rule ir_Seq) apply(rule ir_Assign_Assign) apply(rule ir_If_True_True) apply(rule ir_Assign_Assign) apply clarsimp apply(rule ir_pre) apply(rule ir_While_backwards_both[where P="\<lambda>n s s'. s ''x'' = 2000000 + int n \<and> s' ''x'' = 2000000 + int n \<and> s ''x'' \<ge> 2000000 \<and> s ''x'' \<le> 4000000 \<and> s' ''x'' \<ge> 2000000 \<and> s' ''x'' \<le> 4000000 \<and> s ''low'' = s ''high'' \<and> s' ''low'' = s' ''high'' \<and> s ''high'' \<noteq> s' ''high''"]) apply(rule ir_Seq) apply(rule ir_Assign_Assign) apply(rule ir_If_False_False) apply fastforce apply (fastforce simp: low_eq_strong_def) apply fastforce apply(fastforce simp: low_eq_strong_def) apply(fastforce simp: low_eq_strong_def) apply(rule conjI) apply(clarsimp simp: low_eq_strong_def split: if_splits) apply clarsimp (* ugh having to manually do constraint solving here... *) apply(clarsimp simp: low_eq_strong_def nontrivial_def) apply(rule_tac x="\<lambda>v. if v = ''x'' then 4000000 else if v = ''high'' then 1 else if v = ''n'' then 2000000 else if v = ''nondet'' then -1 else if v = ''low'' then 1 else undefined" in exI) apply(rule_tac x="\<lambda>v. if v = ''x'' then 4000000 else if v = ''high'' then 0 else if v = ''n'' then 2000000 else if v = ''nondet'' then -1 else if v = ''low'' then 0 else undefined" in exI) apply clarsimp done end
import Kenny_comm_alg.temp universe u namespace is_ideal variables {α : Type u} [comm_ring α] (S S₁ S₂ S₃ S₄ T T₁ T₂ : set α) variables [is_ideal S] [is_ideal S₁] [is_ideal S₂] [is_ideal S₃] [is_ideal S₄] @[reducible] def add_ideal : set α := { x | ∃ y z, y ∈ T₁ ∧ z ∈ T₂ ∧ x = y + z } infix + := add_ideal variables {S₁ S₂} instance add.is_ideal : is_ideal (S₁ + S₂) := { zero_ := ⟨0, 0, is_ideal.zero S₁, is_ideal.zero S₂, by simp⟩, add_ := λ x₁ x₂ ⟨y₁, z₁, hy₁, hz₁, hx₁⟩ ⟨y₂, z₂, hy₂, hz₂, hx₂⟩, ⟨y₁ + y₂, z₁ + z₂, is_ideal.add hy₁ hy₂, is_ideal.add hz₁ hz₂, by simp [hx₁, hx₂]⟩, smul := λ x₁ x₂ ⟨y, z, hy, hz, hx⟩, ⟨x₁ * y, x₁ * z, mul_left hy, mul_left hz, by simp [hx, mul_add]⟩ } theorem subset_add_left : S₁ ⊆ S₁ + S₂ := λ x hx, ⟨x, 0, hx, is_ideal.zero S₂, eq.symm $ add_zero x⟩ theorem subset_add_right : S₂ ⊆ S₁ + S₂ := λ x hx, ⟨0, x, is_ideal.zero S₁, hx, eq.symm $ zero_add x⟩ theorem add_self : S₁ + S₁ = S₁ := set.ext $ λ x, ⟨λ ⟨y, z, hy, hz, hx⟩, set.mem_of_eq_of_mem hx $ is_ideal.add hy hz, λ hx, subset_add_left hx⟩ @[reducible] def mul_ideal : set α := span { x | ∃ y z, y ∈ T₁ ∧ z ∈ T₂ ∧ x = y * z} infix * := mul_ideal instance mul.is_ideal : is_ideal (S₁ * S₂) := { ..is_submodule_span } instance inter.is_ideal : is_ideal (S₁ ∩ S₂) := { zero_ := ⟨is_ideal.zero S₁, is_ideal.zero S₂⟩, add_ := λ x y ⟨hx1, hx2⟩ ⟨hy1, hy2⟩, ⟨is_ideal.add hx1 hy1, is_ideal.add hx2 hy2⟩, smul := λ x y ⟨hy1, hy2⟩, ⟨mul_left hy1, mul_left hy2⟩ } instance sInter.is_ideal (S : set $ set α) (h : ∀ A ∈ S, is_ideal A) : is_ideal (⋂₀ S) := { zero_ := λ A ha, @@is_ideal.zero _ A (h A ha), add_ := λ x y hx hy A ha, @@is_ideal.add _ (h A ha) (hx A ha) (hy A ha), smul := λ x y hy A ha, @@mul_left _ (h A ha) (hy A ha) } instance sInter'.is_ideal (SS : set $ {S : set α // is_ideal S}) : is_ideal {x | ∀ S:{S : set α // is_ideal S}, S ∈ SS → x ∈ S.val} := { zero_ := λ A ha, @@is_ideal.zero _ A.1 A.2, add_ := λ x y hx hy A ha, @@is_ideal.add _ A.2 (hx A ha) (hy A ha), smul := λ x y hy A ha, @@mul_left _ A.2 (hy A ha) } variables {S₁ S₂ S₃ S₄} theorem mem_add {x y : α} : x ∈ S₁ → y ∈ S₂ → x + y ∈ S₁ + S₂ := λ hx hy, ⟨x, y, hx, hy, rfl⟩ theorem mem_mul {x y : α} : x ∈ S₁ → y ∈ S₂ → x * y ∈ S₁ * S₂ := λ hx hy, subset_span ⟨x, y, hx, hy, rfl⟩ theorem add_comm : S₁ + S₂ = S₂ + S₁ := set.ext $ λ x, ⟨λ ⟨y, z, hy, hz, hx⟩, ⟨z, y, hz, hy, add_comm y z ▸ hx⟩, λ ⟨y, z, hy, hz, hx⟩, ⟨z, y, hz, hy, add_comm y z ▸ hx⟩⟩ lemma span_ext {T₁ T₂ : set α} : (∀ x, x ∈ T₁ ↔ x ∈ T₂) → span T₁ = span T₂ := λ hx, congr_arg span $ set.ext hx theorem mul_comm : S₁ * S₂ = S₂ * S₁ := span_ext $ λ x, ⟨λ ⟨y, z, hy, hz, hx⟩, ⟨z, y, hz, hy, mul_comm y z ▸ hx⟩, λ ⟨y, z, hy, hz, hx⟩, ⟨z, y, hz, hy, mul_comm y z ▸ hx⟩⟩ theorem add_assoc : (S₁ + S₂) + S₃ = S₁ + (S₂ + S₃) := set.ext $ λ x, ⟨λ ⟨pq, r, ⟨p, q, hp, hq, hpq⟩, hr, hx⟩, ⟨p, q + r, hp, ⟨q, r, hq, hr, rfl⟩, add_assoc p q r ▸ hpq ▸ hx⟩, λ ⟨p, qr, hp, ⟨q, r, hq, hr, hqr⟩, hx⟩, ⟨p + q, r, ⟨p, q, hp, hq, rfl⟩, hr, (add_assoc p q r).symm ▸ hqr ▸ hx⟩⟩ theorem mul_subset_left : S₁ * S₂ ⊆ S₁ := span_minimal _inst_3.to_is_submodule $ λ z ⟨p, q, hp, hq, hz⟩, calc z = p * q : hz ... ∈ S₁ : mul_right hp theorem mul_subset_right : S₁ * S₂ ⊆ S₂ := span_minimal _inst_4.to_is_submodule $ λ z ⟨p, q, hp, hq, hz⟩, calc z = p * q : hz ... ∈ S₂ : mul_left hq theorem mul_subset_inter : S₁ * S₂ ⊆ S₁ ∩ S₂ := λ x hx, ⟨mul_subset_left hx, mul_subset_right hx⟩ theorem add_univ : S₁ + set.univ = set.univ := set.ext $ λ x, ⟨λ hx, show true,by trivial, λ hx, subset_add_right hx⟩ theorem univ_add : set.univ + S₁ = set.univ := set.ext $ λ x, ⟨λ hx, show true, by trivial, λ hx, subset_add_left hx⟩ theorem add_zero : S₁ + ({0}:set α) = S₁ := set.ext $ λ x, ⟨λ ⟨y, z, hy, hz, hx⟩, by simp at hz; simp [hz] at hx; simpa [hx], λ hx, subset_add_left hx⟩ theorem zero_add : ({0}:set α) + S₁ = S₁ := set.ext $ λ x, ⟨λ ⟨y, z, hy, hz, hx⟩, by simp at hy; simp [hy] at hx; simpa [hx], λ hx, subset_add_right hx⟩ lemma subset_span_of_subset {T₁ T₂ : set α} : T₁ ⊆ T₂ → T₁ ⊆ span T₂ := λ h, set.subset.trans h subset_span theorem mul_univ : S₁ * set.univ = S₁ := span_eq _inst_3.to_is_submodule (λ x ⟨y, z, hy, hz, hx⟩, by rw hx; exact mul_right hy) (subset_span_of_subset $ λ x hx, ⟨x, 1, hx, show true, by trivial, eq.symm $ mul_one x⟩) theorem univ_mul : set.univ * S₁ = S₁ := span_eq _inst_3.to_is_submodule (λ x ⟨y, z, hy, hz, hx⟩, by rw hx; exact mul_left hz) (subset_span_of_subset $ λ x hx, ⟨1, x, show true, by trivial, hx, eq.symm $ one_mul x⟩) theorem mul_zero : S₁ * ({0}:set α) = ({0}:set α) := span_eq is_submodule.single_zero (λ x ⟨y, z, hy, hz, hx⟩, by simp at hz; simp [hx, hz]) (subset_span_of_subset $ λ x hx, ⟨0, 0, by simp at hx; simp [hx, is_ideal.zero]⟩) theorem zero_mul : ({0}:set α) * S₁ = ({0}:set α) := span_eq is_submodule.single_zero (λ x ⟨y, z, hy, hz, hx⟩, by simp at hy; simp [hx, hy]) (subset_span_of_subset $ λ x hx, ⟨0, 0, by simp at hx; simp [hx, is_ideal.zero]⟩) /- (0,2) -> (x+y, 0) (1,0) -> (0, 1) [(x+y)^(1+0-1) = (0)*x^1+(1)*y^0] (1,1) -> (1, 1) [(x+y)^(1+1-1) = (1)*x^1+(1)*y^1] (1,2) -> (x+2y, 1) [(x+y)^(1+2-1) = (x+2y)*x^1+(1)*y^2] (1,3) -> (x^2+3xy+3y^2, 1) [(x+y)^3 = (x^2+3xy+3y^2)*x^1+(1)*y^3] (2,2) -> (x+3y, y+3x) (3,2) -> (x+4y, y^2+4xy+6x^2) (4,1) -> (1, y^3+4xy^2+6x^2y+4x^3) (4,2) -> (x+5y, y^3+5xy^2+10x^2y+10x^3) (4,3) -> (x^2+6xy+15y^2, y^3+6xy^2+14x^2y+20x^3) (4,4) -> (x^3+7x^2y+21xy^2+35y^3, y^3+7xy^2+21x^2y+35x^3) (x,y,1,0) : 0 (x,y,1,1) : 1 = 0*(x+y) + 1*y^0 (x,y,1,2) : x+2y = 1*(x+y) + 1*y^1 (x,y,1,3) : x^2+3xy+3y^2 = (x+2y)*(x+y) + 1*y^2 (y,x,2,3): y^2+4xy+6x^2 = (y+3x)(y+x) + 3x^2 (y,x,2,4): y^3+5xy^2+10x^2y+10x^3 = (y^2+4xy+6x^2)(y+x) + 4x^3 A(x,y,4,3) = A(x,y,4,2)*(x+y)+(5C2)y^3 A(x,y,4,4) = A(x,y,4,3)*(x+y)+(6C3)y^3 (x+y)^(4+3-1) = x^4(x^2+6xy+15y^2) + y^3(y^3+6xy^2+15x^2y+20x^3) (x+y)^(5+3-1) = (x^4(x^2+6xy+15y^2) + y^3(y^3+6xy^2+15x^2y+20x^3))(x+y) = x^5(x^2+6xy+15y^2) + x^4(x^2+6xy+15y^2)y + y^3(y^3+6xy^2+15x^2y+20x^3)(x+y) = x^5(x^2+6xy+15y^2) + x^4(x^2+6xy+15y^2)y + y^3(y^3+6xy^2+15x^2y+20x^3)(x+y) (x+y)^(1+2+1) = (x^2+4xy+6y^2)*x^2 + (y+4x)*y^3 (x+y)^(1+1+1) = (x+3y)*x^2 + (y+3x)*y^2 (x+y)^(1+0+1) = (1)*x^2 + (y+2x)*y^1 (x+y)^(0+0+1) = (1)*x^1 + (1)*y^1 A(x,y,0,0) = 1 A(x,y,0,1) = x+2y = (1)*(x+y)+y A(x,y,0,2) = x^2+3xy+3y^2 A(x,y,0,3) = x^3+4x^2y+6xy^2+4y^3 = A(x,y,0,2)*(x+y)+y^3 A(x,y,1,0) = 1 A(x,y,1,1) = x+3y = (1)*(x+y)+2y A(x,y,1,2) = x^2+4xy+6y^2 = (x+3y)*(x+y)+3y^2 [remark: 3C1] A(x,y,1,3) = x^3+5x^2y+10xy^2+10y^3 A(x,y,2,0) = 1 A(x,y,2,1) = x+4y A(x,y,2,2) = x^2+5xy+10y^2 A(x,y,2,3) = x^3+6x^2y+15xy^2+20y^3 = A(x,y,1,3) + y*A(x,y,2,2) -/ def some_binomial_boi (x y : α) : nat → nat → α | m 0 := 1 | 0 (n+1) := (some_binomial_boi 0 n) * (x + y) + y^(n+1) | (m+1) (n+1) := some_binomial_boi m (n+1) + y * some_binomial_boi (m+1) n lemma some_lemma_boi (x y : α) (n : nat) : some_binomial_boi x y n 0 = 1 := by cases n; refl theorem some_binomial_theorem_boi (x y : α) (m n : nat) : (x + y)^(m+n+1) = (some_binomial_boi x y m n)*x^(m+1) + (some_binomial_boi y x n m)*y^(n+1) := begin induction m with m m_ih generalizing n; induction n with n n_ih, { simp [some_binomial_boi] }, { rw nat.zero_add at n_ih ⊢, unfold pow at n_ih ⊢, unfold monoid.pow at n_ih ⊢, rw n_ih, unfold some_binomial_boi, rw some_lemma_boi, unfold pow, unfold monoid.pow, ring }, { specialize m_ih 0, simp [pow_succ] at m_ih ⊢, rw m_ih, unfold some_binomial_boi, rw some_lemma_boi, unfold pow, unfold monoid.pow, ring }, { calc (x + y) ^ (nat.succ m + nat.succ n + 1) = x * (x + y) ^ (m + (n + 1) + 1) + y * (x + y) ^ (nat.succ m + n + 1) : by rw [pow_succ, add_mul]; simp [nat.succ_eq_add_one] ... = x * (some_binomial_boi x y m (n + 1) * x ^ (m + 1) + some_binomial_boi y x (n + 1) m * y ^ ((n + 1) + 1)) + y * (some_binomial_boi x y (nat.succ m) n * x ^ (nat.succ m + 1) + some_binomial_boi y x n (nat.succ m) * y ^ (n + 1)) : by rw [m_ih, n_ih] ... = some_binomial_boi x y (nat.succ m) (nat.succ n) * x ^ (nat.succ m + 1) + some_binomial_boi y x (nat.succ n) (nat.succ m) * y ^ (nat.succ n + 1) : by unfold some_binomial_boi; unfold pow; unfold monoid.pow; simp [nat.succ_eq_add_one]; ring SOP; ac_refl } end def radical : set α := {x | ∃ n : ℕ, x ^ (n+1) ∈ S} instance radical.is_ideal : is_ideal (radical S) := { zero_ := ⟨0, by simp [is_ideal.zero]⟩, add_ := λ x y ⟨m, hxms⟩ ⟨n, hyns⟩, ⟨m + n, by rw some_binomial_theorem_boi; exact is_ideal.add (is_ideal.mul_left hxms) (is_ideal.mul_left hyns)⟩, smul := λ x y ⟨n, hyns⟩, ⟨n, by dsimp [(•)]; rw mul_pow; exact is_ideal.mul_left hyns⟩ } theorem subset_radical : S ⊆ radical S := λ x hx, ⟨0, by simpa⟩ end is_ideal
# --------------------------------------------------------------------------- # Two-way Tanimoto algorithm: prediction accuracy for 2-Tanimoto_analysis.r # --------------------------------------------------------------------------- tanimoto_accuracy <- function(Tanimoto_analysis, predict.only = FALSE, empirical.only = FALSE) { load("./RData/interactions_source.RData") source("./Script/prediction_matrix.r") source("./Script/empirical_matrix.r") source("./Script/prediction_accuracy.r") accuracy <- matrix(ncol = 12, nrow = length(Tanimoto_analysis) * length(Tanimoto_analysis[[1]]) * length(Tanimoto_analysis[[1]][[1]]) * length(Tanimoto_analysis[[1]][[1]][[1]]), data = 0, dimnames = list(c(), c('MW','K','wt','Cm','a','b','c','d','TSS','ScoreY1','ScoreY0','FSS'))) iteration <- 1 for(n in 1: length(Tanimoto_analysis)) { #loop through MW values for(m in 1: length(Tanimoto_analysis[[1]])) { # loop through K values for(i in 1:length(Tanimoto_analysis[[1]][[1]])){ #1st loop for all types of wt values for(j in 1:length(Tanimoto_analysis[[1]][[1]][[1]])) { #2nd loop for all C[i] # Arguments: S1 <- Tanimoto_analysis[[n]][[m]][[i]][[j]][, 'consumer'] predictions <- Tanimoto_analysis[[n]][[m]][[i]][[j]] interactions_source <- interactions_sources source <- names(Tanimoto_analysis[[n]][[m]][[i]])[j] accuracy[iteration, 'MW'] <- names(Tanimoto_analysis)[n] accuracy[iteration, 'K'] <- names(Tanimoto_analysis[[n]])[m] accuracy[iteration, 'wt'] <- names(Tanimoto_analysis[[n]][[m]])[i] accuracy[iteration, 'Cm'] <- names(Tanimoto_analysis[[n]][[m]][[i]])[j] accuracy[iteration, 5:12] <- prediction_accuracy(predicted = prediction_matrix(S1 = S1, predictions = predictions, predict.only = predict.only, empirical.only = empirical.only), empirical = empirical_matrix(S1 = S1, interactions_source = interactions_source, source = source)) iteration <- iteration + 1 remove(S1, predictions, interactions_source, source) }#j }#i }#m }#n return(accuracy) }#Tanimoto_accuracy function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SchorsCV - modification of the PlushCV % Author: % Philipp Kulin [email protected] % % PlushCV - One Page Two Column Resume % LaTeX Template % Version 1.0 (11/28/2021) % % Author: % Shubham Mazumder (http://mazumder.me) % % Hacked together from: % https://github.com/deedydas/Deedy-Resume % % IMPORTANT: THIS TEMPLATE NEEDS TO BE COMPILED WITH XeLaTeX % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TODO: % 1. Figure out a smoother way for the document to flow onto the next page. % 3. Add more icon options % 4. Fix hacky left alignment on contact line % 5. Remove Hacky fix for awkward extra vertical space % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CHANGELOG: % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Known Issues: % 1. Overflows onto second page if any column's contents are more than the vertical limit. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%Icons: %%Main: https://icons8.com/icons/carbon-copy %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \documentclass[]{schorscv} \usepackage{fancyhdr} \pagestyle{fancy} \fancyhf{} \begin{document} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TITLE NAME % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \namesection{Philipp}{Kulin}{Golang Software Engineer}{\contactline{\href{https://github.com/schors}{schors}}{\href{https://www.linkedin.com/in/schors}{schors}}{\href{mailto:[email protected]}{[email protected]}}} % \namesection{Firstname}{Lastname}{Full Stack Software Engineer}{\contactline{\href{https://www.mazumder.me}{mazumder.me}}{\href{https://www.github.com/sansquoi}{sansquoi}}{\href{https://www.linkedin.com/mazumders}{mazumders}}{\href{mailto:[email protected]}{[email protected]}}{\href{tel:+1999999999}{9999999999}}} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % COLUMN ONE % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{minipage}[t]{0.70\textwidth} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % EXPERIENCE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \section{Experience} \runsubsection{SPbEC Mining} \descript{| Golang Software Engineer} \location{Oct 2020 – Current | St.Petersburg, Russia} \vspace{\topsep} % Hacky fix for awkward extra vertical space \begin{tightemize} \sectionsep \item Development of interaction with embedded devices (RS485, whatever) \item Designing of services which communicate with special mining equipment \item Personnel training \item Work directly at the mines if required \end{tightemize} \sectionsep \runsubsection{DiPHOST.Ru} \descript{| CEO, System Administrator, System Architect} \location{Aug 2006 – Oct 2020 | St.Petersburg, Russia} \begin{tightemize} \sectionsep \item Designing, implementing and deploing the web hosting control panel \item Designing and implementing the web hosting architecture \item Web hosting operations \item Active participation in major industry conferences \end{tightemize} \sectionsep \runsubsection{Efind.Ru} \descript{| Software Developer | System Administrator} \location{Nov 2006 – Sep 2009 | St.Petersburg, Russia} \begin{tightemize} \sectionsep \item Designing and implementing a new version of the crawler engine in Python \item Designing and implementing of own stock search base \item Installation, configuration and maintenance of company servers \end{tightemize} \sectionsep \runsubsection{PeterHost.Ru} \descript{| Software Developer | System Administrator | Heroic support} \location{Apr 2002 – Nov 2006 | St.Petersburg, Russia} \begin{tightemize} \sectionsep \item Designing and implementing the webhosting control panel from the ground \item Designing and implementing a shared-hosting services from the ground \item Deploiment the Nginx webserver on the webhosting. Nginx promotion \item Communicating with customers, configuring servers, solving emerging issues \item Heroic technical support for webhosting customers \item Active participation in major industry conferences \end{tightemize} \sectionsep \runsubsection{CSRI Electropribor} \descript{| Software Developer} \location{Apr 1997 – Apr 2002 | St.Petersburg, Russia} \begin{tightemize} \sectionsep \item Repair of computer equipment \item Programming equipment for marine navigation systems \item Migratinging applications from the PDP-11 arch to IPM PC and back \item Support for the possibility of online games between departments during the rest \end{tightemize} \sectionsep %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Projects %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \section{Projects} \runsubsection{Usher-II} \descript{| Golang | Python} \location{2017 - Current} \begingroup \setbox0=\hbox{ \includegraphics[scale=0.1,trim={0 1.25cm -0.4cm 0cm}]{icons/main/home.png}\hspace{0.3cm}\href{https://usher2.club}{https://usher2.club} } \parbox{\wd0}{\box0}\endgroup \sectionsep \begin{tightemize} \item Monitoring Roskomnadzor dump (part of Russia blacklist) \item Development and maintenance telegram bot which search in the "dump" \end{tightemize} \sectionsep %\runsubsection{Speech-enabled Chatbot} %\descript{| C\#, Microsoft Bot Framework} %\location{2018} %\begin{tightemize} %\item Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin ullamcorper venenatis nisi at suscipit. Vestibulum vel odio in diam ultrices posuere. Cras suscipit faucibus ullamcorper. %\item Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin ullamcorper venenatis nisi at suscipit. %\end{tightemize} %\sectionsep %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % AWARDS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % \section{Awards} % \begin{tabular}{rll} % 2020 & Finalist & Lorem Ipsum\\ % 2018 & $2^{nd}$ & Dolor Sit Amet\\ % 2015 & Finalist & Cras posuere\\ % \\ % \end{tabular} % \sectionsep %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % COLUMN TWO % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \end{minipage} \hfill \begin{minipage}[t]{0.25\textwidth} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SKILLS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \section{Skills} \subsection{Programming} \sectionsep \location{Proficient:} Golang \textbullet{} C \textbullet{} Python \\ \sectionsep \location{Experienced:} Perl \textbullet{} \LaTeX\ \\ \sectionsep \location{Familiar:} Shell \textbullet{} Javascript \\ HTML \textbullet{} CSS \\ \sectionsep \location{Legacy:} Fortran \textbullet{} Basic \textbullet{} Turbo Pascal \\ MACRO-11 \\ \sectionsep \sectionsep \subsection{System administration} \sectionsep FreeBSD \textbullet{} Linux \textbullet{} ZFS \\ Docker \textbullet{} LAMP \textbullet{} NGINX \\ DNS/DNSSEC/DoH/DoT/DoQ \\ MySQL \textbullet{} Postgress \\ \sectionsep \sectionsep \subsection{Tools/Platforms} \sectionsep Git \textbullet{} vim \textbullet{} VS Code \\ Prometheus metrics \textbullet{} Grafana \\ \sectionsep \sectionsep %\subsection{Strengths} %\sectionsep %\textbullet{} Multiple platforms and languages \\ %\textbullet{} There are no problems with any programming languages \\ %\textbullet{} Transferring programs between different environments \\ %\textbullet{} The ability to see "a whole picture" \\ %\sectionsep %\sectionsep %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % LANGUAGES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \section{Languages} \sectionsep \textbullet{} \textbf{Russian} native \\ \textbullet{} \textbf{English} B1 (Intermediate) \\ \sectionsep \sectionsep %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % EDUCATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \section{Education} \subsection{Peter the Great \\ St.Petersburg \\ Polytechnic University} \descript{Automation of technological processes and productions} \location{Sep 1993 - 1996} Incomplete education \\ \sectionsep %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % LOCATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \section{Location} \subsection{Current} \location{St.Petersburg, Russia} \sectionsep \subsection{Preffered} Finland \textbullet{} Lithuania \textbullet{} Estonia \\ Sweden \textbullet{} EU \textbullet{} USA \textbullet{} Canada \\ Cyprus \textbullet{} Chile \\ \sectionsep % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % REFERENCES % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %\section{References} %\href{https://www.linkedin.com/company/john-doe/}{\textbf{John Doe}, Senior Software Developer, Tyrell Corp} %\begingroup %\setbox0=\hbox{ %\includegraphics[scale=0.1,trim={0 1cm 0cm 0cm}]{icons/main/mail.png}\hspace{0.3cm} [email protected] %} %\parbox{\wd0}{\box0} %\endgroup %\begingroup %\setbox0=\hbox{ %\includegraphics[scale=0.1,trim={0 1.25cm -0.4cm 0cm}]{icons/main/phone.png}\hspace{0.3cm}+19999999999 %} %\parbox{\wd0}{\box0}\endgroup %\\ %\sectionsep %\href{https://www.linkedin.com/company/john-doe/}{\textbf{Jane Doe}}, Senior Software Developer, Primatech %\\ %\begingroup %\setbox0=\hbox{ %\includegraphics[scale=0.1,trim={0 1cm 0cm 0cm}]{icons/main/mail.png}\hspace{0.3cm} [email protected] %} %\parbox{\wd0}{\box0} %\endgroup %\begingroup %\setbox0=\hbox{ %\includegraphics[scale=0.1,trim={0 1.25cm -0.4cm 0cm}]{icons/main/phone.png}\hspace{0.3cm}+19999999999 %} %\parbox{\wd0}{\box0}\endgroup %\\ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % COURSEWORK %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % \section{Coursework} % \subsection{Graduate} % Graduate Algorithms \textbullet{}\\ % Advanced Computer Architecture \textbullet{}\\ % Operating Systems \textbullet{}\\ % Artificial Intelligence \textbullet{}\\ % Visualization For Scientific Data \\ % \sectionsep % \subsection{Undergraduate} % Database Management Systems \textbullet{}\\ % Object Oriented Analysis and Design \textbullet{}\\ % Artificial Intelligence and Expert Systems \textbullet{}\\ % Scripting Languages and Web Tech \textbullet{}\\ % Software Engineering \\ \end{minipage} \end{document} \documentclass[]{article}
// cppray.cpp : Defines the entry point for the application. // #include "cppray.h" #include <boost/lambda/lambda.hpp> void RenderFrame(const shared_ptr<RayTraceRenderData> &renderData, const shared_ptr<Scene> &scene, const string &outputFilePath) { { LogTimer renderResult("total render time: "); SceneRenderer sceneRenderer; auto pixelArray = sceneRenderer.RenderScene(renderData, scene); pixelArray->SaveAsPng(outputFilePath); } } void RenderAnimation(const shared_ptr<RayTraceRenderData> &renderData, const shared_ptr<Scene> &scene, const string &outputContentRoot) { int numFrames = 60; double cameraRadius = 15.0; double theta = 0; // boost::math::constants::pi<double>() / 2.0; // xy plane double tickAngleDegrees = 360 / numFrames; for (int i = 1; i <= numFrames; i++) { // todo: path.combine to check for full path, ensure path separators, etc. stringstream outputFilePathStream; outputFilePathStream << outputContentRoot << "cppray" << i << ".png"; string outputFilePath = outputFilePathStream.str(); // string outputFilePath = outputContentRoot + "cppray.png"; /* You can simply rotate your setup: let ϕ∈[0,2π] parametrize your circle like you did, but use θ∈[0,π2] to describe the rotation of your plane. Then you can use x=rcosϕcosθ y=rsinϕ z=rcosϕsinθ For θ=0 this gives a circle in the xy plane, and for θ=π/2 the circle lies in the zy plane. */ double currentAngleDegrees = tickAngleDegrees * (i - 1); double phi = currentAngleDegrees * boost::math::constants::pi<double>() / 180; double x = cameraRadius * cos(phi) * cos(theta); double y = cameraRadius * sin(phi); double z = -cameraRadius; // cameraRadius * cos(phi) * sin(theta); x = (double)i; y = (double)i; POS_VECTOR cameraPos = {x, y, z}; cout << "x: " << x << " y: " << y << " z: " << z << endl; scene->GetCamera()->SetPosition(cameraPos); cout << "starting rendering..." << i << endl; RenderFrame(renderData, scene, outputFilePath); } } int main() { string inputContentRoot = "../content/"; string outputContentRoot = "/Users/mzuber/repos/cppray/output/"; // directory.CreateDirectory(outputContentRoot); const int processorCount = 8; const int width = 400; const int height = 400; const int rayTraceDepth = 5; POS_VECTOR cameraPos = {60.0, 7.5, 150.0}; POS_VECTOR cameraLookAt = {-0.1, 0.1, 0.0}; POS_VECTOR cameraUp = {0.0, 0.0, 1.0}; double cameraFov = 50.0; COLOR_VECTOR backgroundColor = {0.0, 0.0, 0.0}; double backgroundAmbience = 0.2; double sphereRadius = 2.0; double sphereDistanceIncrement = 4.0; int numSpheresPerAxis = 10; bool showPlane = true; POS_VECTOR planePos = {1.0, 0.0, 0.0}; double planeDVal = 0.0; auto renderData = make_shared<RayTraceRenderData>( width, height, rayTraceDepth, processorCount, inputContentRoot); // auto scene = SceneFactory::CreateMarblesScene(); auto scene = SceneFactory::CreateMarblesSceneWithParameters( cameraPos, cameraLookAt, cameraUp, cameraFov, backgroundColor, backgroundAmbience, sphereRadius, sphereDistanceIncrement, numSpheresPerAxis, showPlane, planePos, planeDVal); bool animation = false; if (animation) { RenderAnimation(renderData, scene, outputContentRoot); } else { string outputFilePath = outputContentRoot + "cppray.png"; RenderFrame(renderData, scene, outputFilePath); } return 0; }
function RHS = SliceMultiProd(M, X) % function RHS = SliceMultiProd(M, X) % % PURPOSE: Multiple matrix product. This function performs the same % task as MULTIPROD but works on different shaping convention % for input/output matrices % % INPUT % M : 3D array (m x n x p) % X : 3D array (n x q x p) % OUTPUT % RHS: 3D array (m x q x p) % % Compute p matrix products: % M(:,:,k) * X(:,:,k) = RHS(:,:,k) for all k=1,2,...,p % % NOTE -- Special call with X: common right matrix % Input argument X can be contracted as (n x q), and automatically % expanded by the function % M is 3D array (m x n x p) % X is 2D array (n x q) % RHS is 3D array (m x q x p) % M(:,:,k) * X = RHS(:,:,k) for all k=1,2,...,p % % See also: MultiProd, SliceMultiSolver % % Author: Bruno Luong <[email protected]> % History: original 11-August-2009 X = permute(X, [1 3 2]); RHS = MultiProd(M, X); if size(M,3)>1 RHS = permute(RHS, [1 3 2]); end
Exercise material of the MSc-level course **Numerical Methods in Geotechnical Engineering**. Held at Technische Universität Bergakademie Freiberg. Comments to: *Prof. Dr. Thomas Nagel Chair of Soil Mechanics and Foundation Engineering Geotechnical Institute Technische Universität Bergakademie Freiberg.* https://tu-freiberg.de/en/soilmechanics ```python import numpy as np import matplotlib.pyplot as plt #Some plot settings plt.style.use('seaborn-deep') plt.rcParams['lines.linewidth']= 2.0 plt.rcParams['lines.color']= 'black' plt.rcParams['legend.frameon']=True plt.rcParams['font.family'] = 'serif' plt.rcParams['legend.fontsize']=14 plt.rcParams['font.size'] = 14 plt.rcParams['axes.spines.right'] = False plt.rcParams['axes.spines.top'] = False plt.rcParams['axes.spines.left'] = True plt.rcParams['axes.spines.bottom'] = True plt.rcParams['axes.axisbelow'] = True plt.rcParams['figure.figsize'] = (12, 6) ``` # Exercise 7 - 1D Consolidation, Terzaghi: Crank-Nicolson version ## Governing differential equation Neglecting lateral displacements and fluid flow $$ \epsilon_{xx} = \epsilon_{yy} = 0 \quad \text{and} \quad q_x = q_y = 0 $$ the volume balance simplifies to $$ \dot{\epsilon}_{zz} = \frac{\partial q_z}{\partial z} $$ Now we substitute the constitutive law (linear elasticity) of the solid and Darcy's law for the fluid motion into the volume balance and get $$ \dot{\sigma}_{zz}^\text{eff} = E_\text{S} \dot{\epsilon}_{zz} \quad \text{and} \quad \frac{\partial q_z}{\partial z} = - \frac{k}{\mu_\text{F}} \frac{\partial^2 p}{\partial z^2} \quad \text{ergibt} \quad \frac{\dot{\sigma}_{zz}^\text{eff}}{E_\text{S}} = - \frac{k}{\mu_\text{F}} \frac{\partial^2 p}{\partial z^2} $$ Assuming constant total stress (constant external loads) we find with the use of the effective stress principle $$ \sigma_{zz} = \sigma_{zz}^\text{eff} + p = \text{const} \quad \rightarrow \quad \dot{\sigma}_{zz} = 0 = \dot{\sigma}_{zz}^\text{eff} + \dot{p} $$ Substitution yields the partial, linear and homogeneous differential equation $$ \dot{p} = \frac{E_\text{S} k}{\mu_\text{F}} p_{,zz} = \frac{E_\text{S} K_\text{D}}{\gamma_\text{F}} p_{,zz} = c_\text{v} p_{,zz} \quad \text{with } K_\text{D} = \frac{k\rho_\text{F} g}{\mu_\text{F}} $$ $[k] = \text{m}^2$: intrinsic permeability $[K_\text{D}] = \text{m s}^{-1}$: hydraulic conductivity $[c_\text{v}] = \text{m}^2\text{s}^{-1}$: coefficient of consolidation ## Weak form The pore pressure can have (the essential/Dirichlet) boundary conditions in the form: $$ p = \bar{p}\ \forall z \in \partial \Omega_\mathrm{D} $$ We now introduce a test function $\eta$ which vanishes where the pore pressure is given $$ \eta = 0\ \forall z \in \partial \Omega_\mathrm{D} $$ and construct the weak form (using integration by parts): \begin{align} 0 &= \int \limits_0^H \eta \left[\dot{p} - c_\text{v} p_{,zz} \right] \text{d}z \\ &= \int \limits_0^H \left[\eta \dot{p} - \left( \eta c_\text{v} p_{,z} \right)_{,z} + \eta_{,z} c_\text{v} p_{,z} \right] \, \text{d}z \\ &= \int \limits_0^H \left[\eta \dot{p} + \eta_{,z} c_\text{v} p_{,z} \right] \, \text{d}z + \left[ \eta E_\text{S} q_z \right]^H_0 \end{align} where the natural/Neumann boundary conditions have appeared. ## Finite elements in 1D We have a soil column of height $H$ on top of the bed rock at $z=0$. We first create an element class. An element knows the number of nodes it has, their IDs in the global node vector, and the coordinates of its nodes. Linear elements have 2 nodes and 2 quadrature points, quadratic elements 3 nodes and 3 quadrature points. The natural coordinates of the element run from -1 to 1, and the quadrature points and weights are directly taken from Numpy. ```python #element class class line_element():#local coordinates go from -1 to 1 #takes number of nodes, global nodal coordinates, global node ids def __init__(self, nnodes=2, ncoords=[0.,1.], nids=[0,1]): self.__nnodes = nnodes if (len(ncoords) != self.__nnodes): raise Exception("Number of coordinates does not match number \ of nodes of element (%i vs of %i)" %(self.__nnodes,len(ncoords))) else: self.__coords = np.array(ncoords) self.__natural_coords = (self.__coords-self.__coords[0])/(self.__coords[-1]-self.__coords[0])*2. - 1. if (len(nids) != self.__nnodes): raise Exception("Number of node IDs does not match number \ of nodes of element (%i vs of %i)" %(self.__nnodes,len(nids))) else: self.__global_ids = np.array(nids) self.__quad_degree = self.__nnodes self.__quad_points, self.__quad_weights = np.polynomial.legendre.leggauss(self.__quad_degree) ``` Next, we wish to generate a one-dimensional mesh by specifying the length of a line, the number of elements into which the mesh is to be split, and the number of nodes per element. ```python def number_of_nodes(nelems,nodes_per_elem): return nelems*nodes_per_elem - (nelems - 1) def generate_mesh(domain_length,nelems,nodes_per_elem): nn = number_of_nodes(nelems,nodes_per_elem) #coordinate vector of global nodes global_nodal_coordinates = np.linspace(0.,domain_length,nn) global_solution = np.array([0.]*nn) #generate elements element_vector = [] for i in range(nelems): node_start = (nodes_per_elem-1)*i element_vector.append( line_element(nodes_per_elem, global_nodal_coordinates[node_start:node_start+nodes_per_elem], list(range(node_start,node_start+nodes_per_elem)))) return global_nodal_coordinates, element_vector, global_solution ``` ## Shape functions in 1D As in exercise 06, we allow linear and higher-order shape functions. ```python #N def shape_function(element_order,xi): if (element_order == 2): #-1,1 return np.array([(1.-xi)/2., (1.+xi)/2.]) elif (element_order == 3): #-1, 0, 1 return np.array([(xi - 1.)*xi/2., (1-xi)*(1+xi), (1+xi)*xi/2.]) #dN_dxi def dshape_function_dxi(element_order,xi): if (element_order == 2): #-1,1 return np.array([-0.5*xi/xi, 0.5*xi/xi]) #xi only later for plotting dimensions elif (element_order == 3):#-1,0,1 return np.array([xi - 0.5,-2.*xi,xi + 0.5]) #dz_dxi def element_jacobian(element,xi): element_order = element._line_element__nnodes Jacobian = 0. Jacobian += dshape_function_dxi(element_order,xi).dot(element._line_element__coords) return Jacobian #dN_dz def grad_shape_function(element,xi): element_order = element._line_element__nnodes Jac = element_jacobian(element,xi) return dshape_function_dxi(element_order,xi)/Jac ``` ## Time and space discretization, Picard iterations Using a forward Euler approach for simplicity we find the time-discrete weak form as ($p_{n+1} \equiv p$) $$ \int \limits_0^H \left[ N_i \frac{1}{\Delta t} N_k + \nabla N_i \frac{c_\text{v}}{2} \nabla N_k\right] \, \text{d}z\ \hat{p}_k = N_{n_\text{n}} E_\text{S} \bar{q}_z|_{z=H} \delta_{n_\text{n}i} - N_{n_\text{n}} E_\text{S} \bar{q}_z|_{z=0} \delta_{i0} + \int \limits_0^H N_i \frac{1}{\Delta t} N_k \, \text{d}z\ \hat{p}_{n,k} - \int \limits_0^H \left[ \nabla N_i \frac{c_\text{v}}{2} \nabla N_k \right] \, \text{d}z\ \hat{p}_{n,k} $$ which leaves us with $n_\text{n}$ equations for the $n_\text{n}$ unknown nodal pressures $\hat{p}_k$. If any coefficients in the above are taken as pressure-dependent, the system could be solved repeatedly usind Picard iterations. For strong non-linearities, a Newton linearization would typically be used. What we require now is the local assembler to calculate the stiffness matrix and the local right-hand side. Local integration is performed by Gauss quadrature: $$ \int \limits_{-1}^1 f(\xi)\,\text{d}\xi \approx \sum \limits_{i=1}^{n_\text{gp}} f(\xi_i) w_i $$ ## Local assember ```python def Stiffness(z): E0 = 5.e6 #Pa return E0 def Conductivity(z): kf = 1.e-9#m/s return kf def SpecificWeight(z): g = 9.81 #m/s² rhow = 1000. #kg/m³ return g*rhow def ConsolidationCoeff(z):#m²/s return Stiffness(z)*Conductivity(z)/SpecificWeight(z) ``` ```python def local_assembler(elem,dt,prev_sol): element_order = elem._line_element__nnodes K_loc = np.zeros((element_order,element_order)) b_loc = np.zeros(element_order) z_nodes = elem._line_element__coords for i in range(elem._line_element__quad_degree): #local integration point coordinate xi = elem._line_element__quad_points[i] #shape function N = shape_function(element_order,xi) #gradient of shape function dN_dX = grad_shape_function(elem,xi) #determinant of Jacobian detJ = np.abs(element_jacobian(elem,xi)) #integration weight w = elem._line_element__quad_weights[i] #global integration point coordinate (for spatially varying properties) z_glob = np.dot(N,z_nodes) #evaluation of local material/structural properties E = Stiffness(z_glob) #evaluation of local body force CV = ConsolidationCoeff(z_glob) #assembly of local stiffness matrix K_loc += (np.outer(N,N) / dt + np.outer(dN_dX,dN_dX) * CV/2)* w * detJ #assembly of local RHS p_prev = np.dot(N,prev_sol)#pressure in integration point grad_p_prev = np.dot(dN_dX,prev_sol) b_loc += (N * p_prev/dt - dN_dX * CV/2 * grad_p_prev) * w * detJ return K_loc,b_loc ``` ## Global assembly Now we can construct the global matrix system $\mathbf{K}\mathbf{u} = \mathbf{f}$ or $\mathbf{A}\mathbf{x}=\mathbf{b}$ (see lecture script). ```python def global_assembler(nodes,elements,solution,dt): K_glob = np.zeros((len(nodes),len(nodes))) b_glob = np.zeros(len(nodes)) for i,elem in enumerate(elements): start_id = elem._line_element__global_ids[0] end_id = elem._line_element__global_ids[-1] K_i, b_i = local_assembler(elem,dt,solution[start_id:end_id+1]) K_glob[start_id:end_id+1,start_id:end_id+1] += K_i b_glob[start_id:end_id+1] += b_i return K_glob, b_glob ``` ## Application of boundary conditions First we apply flux boundary conditions ```python def apply_Neumann_bc(b_glob,node_id,value): b_glob[node_id] += value return b_glob ``` Then we apply Dirichlet bc ```python def apply_Dirichlet_bc(K_glob,b_glob,node_id,value): K_glob[node_id,:] = 0.# = K_glob[:,node_id] = 0. K_glob[node_id,node_id] = 1. b_glob[node_id] = value return K_glob, b_glob ``` ## Application of initial conditions Since we're dealing with a time-dependent problem (rate problem) we require initial conditions for the pore pressure, i.e. $p_0 = p(t=0)\ \forall\ z$. Due to the very specific assumptions in deriving this consolidation equation, the initial pressure is given by the (suddenly) applied load: $$ p_0 = \sigma_{zz} = \text{const.} $$ ```python def apply_initial_conditions(solution,sig_v): solution *= 0. solution += sig_v return ``` ## Time loop and problem solution We now establish the time loop and in each time step perform the global assembly, apply a vanishing traction on the top and constrain the displacement at the bottom to zero. ```python def time_loop(dt,nodes,elements,solution): #Startwerte t_end = 100*24*60*60 #s absolute_tolerance = 1.e-6 apply_initial_conditions(solution,200.e3) y = [solution] #create a list that will hold the solution vectors at all time points times = np.array([0.]) # while times[-1]+dt < t_end: #repeat the loop as long as the final time step is below the end point times = np.append(times,times[-1]+dt) #here define the next time point as the previous time point plus the time increment dt K, f = global_assembler(nodes,elements,y[-1],dt) #f = apply_Neumann_bc(f,len(nodes)-1,0) K, f = apply_Dirichlet_bc(K, f, len(nodes)-1, 0.)#free draining top solution = np.linalg.solve(K,f) y.append(solution) #append the new found solution to the solution vector return times, y ``` ```python #spatial discretization H = 10. nel = 20 n_per_el = 3 nodes,elements,solution=generate_mesh(H,nel,n_per_el) ``` ```python times, sols = time_loop(24*60.*60.,nodes,elements,solution) ``` ```python plt.xlabel('$z$ / m') plt.ylabel('$p$ / kPa') plt.title('Finite element solution') plt.plot(nodes, sols[0]/1.e3, marker='o', label='$t = %i$ h' %(times[0]/60/60)) plt.plot(nodes, sols[1]/1.e3, marker='o', label='$t = %i$ h' %(times[1]/60/60)) plt.plot(nodes, sols[10]/1.e3, marker='o', label='$t = %i$ h' %(times[10]/60/60)) plt.plot(nodes, sols[-1]/1.e3, marker='o', label='$t = %i$ d' %(times[-1]/60/60/24)) #plt.plot(nodes, sols[200]/1.e3, marker='o', label='$t = %i$ d' %(times[200]/60/60/24)) #plt.plot(nodes, sols[-1]/1.e3, marker='o', label='$t = %i$ d' %(times[-1]/60/60/24)) plt.legend(); ``` ### Convergence study Let's do a simple convergence study. ```python dts = [12*3600,24.*3600,48.*3600] nels = [10,20,40] H = 10. fig, ax = plt.subplots(nrows=3,ncols=3,figsize=(18,18)) for i,dt in enumerate(dts): for j,nel in enumerate(nels): #print("Running (n,dt) combination ", dt, nel) number_of_elements = nel nodes_per_element = 2 nodes,elements,solution=generate_mesh(H,number_of_elements,nodes_per_element) times, sols = time_loop(dt,nodes,elements,solution) ax[i][j].plot(nodes, sols[0]/1.e3, marker='o', label='$t = %i$ h' %(times[0]/60/60)) ax[i][j].plot(nodes, sols[1]/1.e3, marker='o', label='$t = %i$ h' %(times[1]/60/60)) ax[i][j].plot(nodes, sols[10]/1.e3, marker='o', label='$t = %i$ h' %(times[10]/60/60)) ax[i][j].plot(nodes, sols[-1]/1.e3, marker='o', label='$t = %i$ d' %(times[10]/60/60/24)) ax[i][j].set_xlabel('$z$ / m') ax[i][j].set_ylabel('$p$ / kPa') ax[i][j].set_title('dt = %i h, nel = %i' %(dt/3600,nel)) ax[i][j].legend(fontsize=10) fig.tight_layout() ``` We observe that time step size and discretization size act together, and that unsuitable choices can lead to unphysical oscillations. ## Tasks * What happens if you switch the element order to 3 in the last example? * Explicit solutions can be coded so as to avoid matrix inversion. ```python ```
{-# OPTIONS --safe --without-K #-} open import Relation.Binary module Data.List.Membership.Setoid.Distinct where open import Data.List as List using (List; []; _∷_; _++_) open import Data.List.Any as Any hiding (map; head; tail) open import Data.List.Any.Properties open import Relation.Binary.PropositionalEquality as P using (_≡_) open import Function open import Function.Equivalence using (_⇔_; equivalence) open import Function.Equality using (_⟨$⟩_) open import Function.Inverse using () open import Function.Injection using (_↣_; Injection) open import Data.Product hiding (map) open import Data.Sum hiding (map) import Level as L open import Data.Fin as Fin using (Fin) open import Data.Nat as ℕ module _ {a p} {S : Setoid a p} where open Setoid S renaming (Carrier to A) open import Data.List.Membership.Setoid (S) open import Data.List.Membership.Setoid.Properties open import Data.List.Membership.Setoid.Disjoint (S) renaming (Disjoint to _⋈_) open import Data.List.Membership.Setoid.Trans (S) open import Data.Empty data Distinct : List A → Set (a L.⊔ p) where distinct-[] : Distinct [] _distinct-∷_by_ : ∀ x {xs} → Distinct xs → x ∉ xs → Distinct (x ∷ xs) head : ∀ {x}{xs : List A} → Distinct (x ∷ xs) → A head (x distinct-∷ _ by _) = x tail : ∀ {x}{xs : List A} → Distinct (x ∷ xs) → Distinct xs tail (_ distinct-∷ dis by _) = dis head∉tail : ∀ {x}{xs : List A} → Distinct (x ∷ xs) → x ∉ xs head∉tail (_ distinct-∷ _ by x∉xs) = x∉xs distinct-[_] : ∀ x → Distinct (List.[ x ]) distinct-[ x ] = x distinct-∷ distinct-[] by (λ ()) ⋈-++ : ∀ (xs ys : List A) → Distinct (xs ++ ys) ⇔ (Distinct xs × Distinct ys × xs ⋈ ys) ⋈-++ xs ys = equivalence to from where to : ∀ {xs ys : List A} → Distinct (xs ++ ys) → (Distinct xs × Distinct ys × xs ⋈ ys) to {[]} dys = distinct-[] , dys , disjoint-[]ʳ to {x ∷ xs} {ys} (.x distinct-∷ dis by x∉xsys) with to {xs = xs} dis ... | dxs , dys , xs⋈ys = x distinct-∷ dxs by (λ x∈xs → x∉xsys (++⁺ˡ x∈xs)) , dys , λ { (here px) ∈ys → x∉xsys (++⁺ʳ xs (≈-trans-∈ (sym px) ∈ys)) ; (there ∈xs) ∈ys → xs⋈ys ∈xs ∈ys} from : ∀ {xs ys : List A} → (Distinct xs × Distinct ys × xs ⋈ ys) → Distinct (xs ++ ys) from (distinct-[] , dys , xs⋈ys) = dys from {xs = .x ∷ xs} ((x distinct-∷ dxs by x∉xs) , dys , xxs⋈ys) with from (dxs , dys , xxs⋈ys ∘ there) ... | dxsys = x distinct-∷ dxsys by λ x∈xsys → case ++⁻ xs x∈xsys of λ { (inj₁ x∈xs) → x∉xs x∈xs ; (inj₂ x∈ys) → xxs⋈ys (here refl) x∈ys} lookup-injective : {xs : List A}(dxs : Distinct xs) → ∀ {i j} → List.lookup xs i ≡ List.lookup xs j → i ≡ j lookup-injective distinct-[] {()} {()} _ lookup-injective (x distinct-∷ dxs by x∉xs) {Fin.zero} {Fin.zero} _ = P.refl lookup-injective (x distinct-∷ dxs by x∉xs) {Fin.suc i} {Fin.suc j} eq = P.cong Fin.suc (lookup-injective dxs eq) lookup-injective {xs} (x distinct-∷ dxs by x∉xs) {Fin.zero} {Fin.suc j} eq rewrite eq = ⊥-elim (x∉xs (∈-lookup S _ j)) lookup-injective (x distinct-∷ dxs by x∉xs) {Fin.suc i} {Fin.zero} eq rewrite P.sym eq = ⊥-elim (x∉xs (∈-lookup S _ i)) module _ {a₁ a₂ p₁ p₂}{S₁ : Setoid a₁ p₁} {S₂ : Setoid a₂ p₂} where open Setoid S₁ renaming (Carrier to A) using () open Setoid S₂ renaming (Carrier to B) using () open import Data.List.Membership.Setoid (S₂) renaming (_∉_ to _∉₂_) using () open import Data.List.Membership.Setoid.Properties open import Data.List.Membership.Setoid.Trans (S₁) map : (f : Injection S₁ S₂) → ∀ {xs : List A} → Distinct {S = S₁} xs → Distinct {S = S₂} (List.map (Injection.to f ⟨$⟩_) xs) map f {[]} distinct-[] = distinct-[] map f {.x ∷ xs} (x distinct-∷ dis by x∉xs) = fx distinct-∷ map f dis by lemma where fx = Injection.to f ⟨$⟩ x lemma : fx ∉₂ List.map (Injection.to f ⟨$⟩_) xs lemma p with ∈-map⁻ S₁ S₂ p ... | _ , y∈xs , fx≈fy = x∉xs (≈-trans-∈ (Injection.injective f fx≈fy) y∈xs)
[GOAL] C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 ⊢ IsLocallySurjective T ↔ ∀ (x : ↑X), Function.Surjective ↑((stalkFunctor C x).map T) [PROOFSTEP] constructor [GOAL] case mp C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 ⊢ IsLocallySurjective T → ∀ (x : ↑X), Function.Surjective ↑((stalkFunctor C x).map T) [PROOFSTEP] intro hT [GOAL] case mpr C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 ⊢ (∀ (x : ↑X), Function.Surjective ↑((stalkFunctor C x).map T)) → IsLocallySurjective T [PROOFSTEP] intro hT [GOAL] case mp C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 hT : IsLocallySurjective T ⊢ ∀ (x : ↑X), Function.Surjective ↑((stalkFunctor C x).map T) [PROOFSTEP] intro x g [GOAL] case mp C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 hT : IsLocallySurjective T x : ↑X g : (forget C).obj ((stalkFunctor C x).obj 𝒢) ⊢ ∃ a, ↑((stalkFunctor C x).map T) a = g [PROOFSTEP] obtain ⟨U, hxU, t, rfl⟩ := 𝒢.germ_exist x g [GOAL] case mp.intro.intro.intro C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 hT : IsLocallySurjective T x : ↑X U : Opens ↑X hxU : x ∈ U t : (forget C).obj (𝒢.obj (op U)) ⊢ ∃ a, ↑((stalkFunctor C x).map T) a = ↑(germ 𝒢 { val := x, property := hxU }) t [PROOFSTEP] rcases hT U t x hxU with ⟨V, ι, ⟨s, h_eq⟩, hxV⟩ -- Then the germ of s maps to g. [GOAL] case mp.intro.intro.intro.intro.intro.intro.intro C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 hT : IsLocallySurjective T x : ↑X U : Opens ↑X hxU : x ∈ U t : (forget C).obj (𝒢.obj (op U)) V : Opens ↑X ι : V ⟶ U hxV : x ∈ V s : (forget C).obj (ℱ.obj (op V)) h_eq : ↑(NatTrans.app T (op V)) s = ↑(𝒢.map ι.op) t ⊢ ∃ a, ↑((stalkFunctor C x).map T) a = ↑(germ 𝒢 { val := x, property := hxU }) t [PROOFSTEP] use ℱ.germ ⟨x, hxV⟩ s [GOAL] case h C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 hT : IsLocallySurjective T x : ↑X U : Opens ↑X hxU : x ∈ U t : (forget C).obj (𝒢.obj (op U)) V : Opens ↑X ι : V ⟶ U hxV : x ∈ V s : (forget C).obj (ℱ.obj (op V)) h_eq : ↑(NatTrans.app T (op V)) s = ↑(𝒢.map ι.op) t ⊢ ↑((stalkFunctor C x).map T) (↑(germ ℱ { val := x, property := hxV }) s) = ↑(germ 𝒢 { val := x, property := hxU }) t [PROOFSTEP] convert stalkFunctor_map_germ_apply V ⟨x, hxV⟩ T s using 1 [GOAL] case h.e'_3.h C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 hT : IsLocallySurjective T x : ↑X U : Opens ↑X hxU : x ∈ U t : (forget C).obj (𝒢.obj (op U)) V : Opens ↑X ι : V ⟶ U hxV : x ∈ V s : (forget C).obj (ℱ.obj (op V)) h_eq : ↑(NatTrans.app T (op V)) s = ↑(𝒢.map ι.op) t e_1✝ : (forget C).obj ((stalkFunctor C x).obj 𝒢) = (forget C).obj (Limits.colim.obj ((OpenNhds.inclusion ↑{ val := x, property := hxV }).op ⋙ 𝒢)) ⊢ ↑(germ 𝒢 { val := x, property := hxU }) t = ↑(Limits.colimit.ι ((OpenNhds.inclusion ↑{ val := x, property := hxV }).op ⋙ 𝒢) (op { obj := V, property := (_ : ↑{ val := x, property := hxV } ∈ V) })) (↑(NatTrans.app T (op V)) s) [PROOFSTEP] simpa [h_eq] using (germ_res_apply 𝒢 ι ⟨x, hxV⟩ t).symm [GOAL] case mpr C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 hT : ∀ (x : ↑X), Function.Surjective ↑((stalkFunctor C x).map T) ⊢ IsLocallySurjective T [PROOFSTEP] intro U t x hxU [GOAL] case mpr C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 hT : ∀ (x : ↑X), Function.Surjective ↑((stalkFunctor C x).map T) U : Opens ↑X t : (forget C).obj (𝒢.obj (op U)) x : ↑X hxU : x ∈ U ⊢ ∃ U_1 f, (imageSieve T t).arrows f ∧ x ∈ U_1 [PROOFSTEP] set t_x := 𝒢.germ ⟨x, hxU⟩ t with ht_x [GOAL] case mpr C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 hT : ∀ (x : ↑X), Function.Surjective ↑((stalkFunctor C x).map T) U : Opens ↑X t : (forget C).obj (𝒢.obj (op U)) x : ↑X hxU : x ∈ U t_x : (forget C).obj (stalk 𝒢 ↑{ val := x, property := hxU }) := ↑(germ 𝒢 { val := x, property := hxU }) t ht_x : t_x = ↑(germ 𝒢 { val := x, property := hxU }) t ⊢ ∃ U_1 f, (imageSieve T t).arrows f ∧ x ∈ U_1 [PROOFSTEP] obtain ⟨s_x, hs_x : ((stalkFunctor C x).map T) s_x = t_x⟩ := hT x t_x [GOAL] case mpr.intro C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 hT : ∀ (x : ↑X), Function.Surjective ↑((stalkFunctor C x).map T) U : Opens ↑X t : (forget C).obj (𝒢.obj (op U)) x : ↑X hxU : x ∈ U t_x : (forget C).obj (stalk 𝒢 ↑{ val := x, property := hxU }) := ↑(germ 𝒢 { val := x, property := hxU }) t ht_x : t_x = ↑(germ 𝒢 { val := x, property := hxU }) t s_x : (forget C).obj ((stalkFunctor C x).obj ℱ) hs_x : ↑((stalkFunctor C x).map T) s_x = t_x ⊢ ∃ U_1 f, (imageSieve T t).arrows f ∧ x ∈ U_1 [PROOFSTEP] obtain ⟨V, hxV, s, rfl⟩ := ℱ.germ_exist x s_x [GOAL] case mpr.intro.intro.intro.intro C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 hT : ∀ (x : ↑X), Function.Surjective ↑((stalkFunctor C x).map T) U : Opens ↑X t : (forget C).obj (𝒢.obj (op U)) x : ↑X hxU : x ∈ U t_x : (forget C).obj (stalk 𝒢 ↑{ val := x, property := hxU }) := ↑(germ 𝒢 { val := x, property := hxU }) t ht_x : t_x = ↑(germ 𝒢 { val := x, property := hxU }) t V : Opens ↑X hxV : x ∈ V s : (forget C).obj (ℱ.obj (op V)) hs_x : ↑((stalkFunctor C x).map T) (↑(germ ℱ { val := x, property := hxV }) s) = t_x ⊢ ∃ U_1 f, (imageSieve T t).arrows f ∧ x ∈ U_1 [PROOFSTEP] have key_W := 𝒢.germ_eq x hxV hxU (T.app _ s) t <| by convert hs_x using 1 symm convert stalkFunctor_map_germ_apply _ _ _ s [GOAL] C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 hT : ∀ (x : ↑X), Function.Surjective ↑((stalkFunctor C x).map T) U : Opens ↑X t : (forget C).obj (𝒢.obj (op U)) x : ↑X hxU : x ∈ U t_x : (forget C).obj (stalk 𝒢 ↑{ val := x, property := hxU }) := ↑(germ 𝒢 { val := x, property := hxU }) t ht_x : t_x = ↑(germ 𝒢 { val := x, property := hxU }) t V : Opens ↑X hxV : x ∈ V s : (forget C).obj (ℱ.obj (op V)) hs_x : ↑((stalkFunctor C x).map T) (↑(germ ℱ { val := x, property := hxV }) s) = t_x ⊢ ↑(germ 𝒢 { val := x, property := hxV }) (↑(NatTrans.app T (op V)) s) = ↑(germ 𝒢 { val := x, property := hxU }) t [PROOFSTEP] convert hs_x using 1 [GOAL] case h.e'_2.h C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 hT : ∀ (x : ↑X), Function.Surjective ↑((stalkFunctor C x).map T) U : Opens ↑X t : (forget C).obj (𝒢.obj (op U)) x : ↑X hxU : x ∈ U t_x : (forget C).obj (stalk 𝒢 ↑{ val := x, property := hxU }) := ↑(germ 𝒢 { val := x, property := hxU }) t ht_x : t_x = ↑(germ 𝒢 { val := x, property := hxU }) t V : Opens ↑X hxV : x ∈ V s : (forget C).obj (ℱ.obj (op V)) hs_x : ↑((stalkFunctor C x).map T) (↑(germ ℱ { val := x, property := hxV }) s) = t_x e_1✝ : (fun x_1 => (forget C).obj (stalk 𝒢 ↑{ val := x, property := hxV })) (↑(NatTrans.app T (op V)) s) = (fun x_1 => (forget C).obj ((stalkFunctor C x).obj 𝒢)) (↑(germ ℱ { val := x, property := hxV }) s) ⊢ ↑(germ 𝒢 { val := x, property := hxV }) (↑(NatTrans.app T (op V)) s) = ↑((stalkFunctor C x).map T) (↑(germ ℱ { val := x, property := hxV }) s) [PROOFSTEP] symm [GOAL] case h.e'_2.h C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 hT : ∀ (x : ↑X), Function.Surjective ↑((stalkFunctor C x).map T) U : Opens ↑X t : (forget C).obj (𝒢.obj (op U)) x : ↑X hxU : x ∈ U t_x : (forget C).obj (stalk 𝒢 ↑{ val := x, property := hxU }) := ↑(germ 𝒢 { val := x, property := hxU }) t ht_x : t_x = ↑(germ 𝒢 { val := x, property := hxU }) t V : Opens ↑X hxV : x ∈ V s : (forget C).obj (ℱ.obj (op V)) hs_x : ↑((stalkFunctor C x).map T) (↑(germ ℱ { val := x, property := hxV }) s) = t_x e_1✝ : (fun x_1 => (forget C).obj (stalk 𝒢 ↑{ val := x, property := hxV })) (↑(NatTrans.app T (op V)) s) = (fun x_1 => (forget C).obj ((stalkFunctor C x).obj 𝒢)) (↑(germ ℱ { val := x, property := hxV }) s) ⊢ ↑((stalkFunctor C x).map T) (↑(germ ℱ { val := x, property := hxV }) s) = ↑(germ 𝒢 { val := x, property := hxV }) (↑(NatTrans.app T (op V)) s) [PROOFSTEP] convert stalkFunctor_map_germ_apply _ _ _ s [GOAL] case mpr.intro.intro.intro.intro C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 hT : ∀ (x : ↑X), Function.Surjective ↑((stalkFunctor C x).map T) U : Opens ↑X t : (forget C).obj (𝒢.obj (op U)) x : ↑X hxU : x ∈ U t_x : (forget C).obj (stalk 𝒢 ↑{ val := x, property := hxU }) := ↑(germ 𝒢 { val := x, property := hxU }) t ht_x : t_x = ↑(germ 𝒢 { val := x, property := hxU }) t V : Opens ↑X hxV : x ∈ V s : (forget C).obj (ℱ.obj (op V)) hs_x : ↑((stalkFunctor C x).map T) (↑(germ ℱ { val := x, property := hxV }) s) = t_x key_W : ∃ W _m iU iV, ↑(𝒢.map iU.op) (↑(NatTrans.app T (op V)) s) = ↑(𝒢.map iV.op) t ⊢ ∃ U_1 f, (imageSieve T t).arrows f ∧ x ∈ U_1 [PROOFSTEP] obtain ⟨W, hxW, hWV, hWU, h_eq⟩ := key_W [GOAL] case mpr.intro.intro.intro.intro.intro.intro.intro.intro C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 hT : ∀ (x : ↑X), Function.Surjective ↑((stalkFunctor C x).map T) U : Opens ↑X t : (forget C).obj (𝒢.obj (op U)) x : ↑X hxU : x ∈ U t_x : (forget C).obj (stalk 𝒢 ↑{ val := x, property := hxU }) := ↑(germ 𝒢 { val := x, property := hxU }) t ht_x : t_x = ↑(germ 𝒢 { val := x, property := hxU }) t V : Opens ↑X hxV : x ∈ V s : (forget C).obj (ℱ.obj (op V)) hs_x : ↑((stalkFunctor C x).map T) (↑(germ ℱ { val := x, property := hxV }) s) = t_x W : Opens ↑X hxW : x ∈ W hWV : W ⟶ V hWU : W ⟶ U h_eq : ↑(𝒢.map hWV.op) (↑(NatTrans.app T (op V)) s) = ↑(𝒢.map hWU.op) t ⊢ ∃ U_1 f, (imageSieve T t).arrows f ∧ x ∈ U_1 [PROOFSTEP] refine' ⟨W, hWU, ⟨ℱ.map hWV.op s, _⟩, hxW⟩ [GOAL] case mpr.intro.intro.intro.intro.intro.intro.intro.intro C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 hT : ∀ (x : ↑X), Function.Surjective ↑((stalkFunctor C x).map T) U : Opens ↑X t : (forget C).obj (𝒢.obj (op U)) x : ↑X hxU : x ∈ U t_x : (forget C).obj (stalk 𝒢 ↑{ val := x, property := hxU }) := ↑(germ 𝒢 { val := x, property := hxU }) t ht_x : t_x = ↑(germ 𝒢 { val := x, property := hxU }) t V : Opens ↑X hxV : x ∈ V s : (forget C).obj (ℱ.obj (op V)) hs_x : ↑((stalkFunctor C x).map T) (↑(germ ℱ { val := x, property := hxV }) s) = t_x W : Opens ↑X hxW : x ∈ W hWV : W ⟶ V hWU : W ⟶ U h_eq : ↑(𝒢.map hWV.op) (↑(NatTrans.app T (op V)) s) = ↑(𝒢.map hWU.op) t ⊢ ↑(NatTrans.app T (op W)) (↑(ℱ.map hWV.op) s) = ↑(𝒢.map hWU.op) t [PROOFSTEP] convert h_eq using 1 [GOAL] case h.e'_2 C : Type u inst✝³ : Category.{v, u} C inst✝² : ConcreteCategory C X : TopCat ℱ 𝒢 : Presheaf C X inst✝¹ : Limits.HasColimits C inst✝ : Limits.PreservesFilteredColimits (forget C) T : ℱ ⟶ 𝒢 hT : ∀ (x : ↑X), Function.Surjective ↑((stalkFunctor C x).map T) U : Opens ↑X t : (forget C).obj (𝒢.obj (op U)) x : ↑X hxU : x ∈ U t_x : (forget C).obj (stalk 𝒢 ↑{ val := x, property := hxU }) := ↑(germ 𝒢 { val := x, property := hxU }) t ht_x : t_x = ↑(germ 𝒢 { val := x, property := hxU }) t V : Opens ↑X hxV : x ∈ V s : (forget C).obj (ℱ.obj (op V)) hs_x : ↑((stalkFunctor C x).map T) (↑(germ ℱ { val := x, property := hxV }) s) = t_x W : Opens ↑X hxW : x ∈ W hWV : W ⟶ V hWU : W ⟶ U h_eq : ↑(𝒢.map hWV.op) (↑(NatTrans.app T (op V)) s) = ↑(𝒢.map hWU.op) t ⊢ ↑(NatTrans.app T (op W)) (↑(ℱ.map hWV.op) s) = ↑(𝒢.map hWV.op) (↑(NatTrans.app T (op V)) s) [PROOFSTEP] simp only [← comp_apply, T.naturality]