Datasets:
AI4M
/

text
stringlengths
0
3.34M
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======================================================================= SUBROUTINE ORDIX (NORD, IXORD, LOLD, IOLD, ISCR, INEW) C======================================================================= C --*** ORDIX *** (GJOIN) Order a list according to indices C -- Written by Amy Gilkey - revised 09/29/87 C -- C --ORDIX orders a list according to a list of indices. C -- C --Parameters: C -- NORD - IN - the number of indices C -- IXORD - IN - the indices of the ordered items C -- LOLD - IN - the length of IOLD C -- IOLD - IN - the unordered list C -- ISCR - SCRATCH - size = LOLD C -- INEW - OUT - the ordered list INTEGER IXORD(*) INTEGER IOLD(*) INTEGER ISCR(*) INTEGER INEW(*) DO 100 I = 1, LOLD ISCR(I) = IOLD(I) 100 CONTINUE DO 110 I = 1, NORD INEW(I) = ISCR(IXORD(I)) 110 CONTINUE RETURN END
(* Property from Case-Analysis for Rippling and Inductive Proof, Moa Johansson, Lucas Dixon and Alan Bundy, ITP 2010. This Isabelle theory is produced using the TIP tool offered at the following website: https://github.com/tip-org/tools This file was originally provided as part of TIP benchmark at the following website: https://github.com/tip-org/benchmarks Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly to make it compatible with Isabelle2017.*) theory TIP_prop_62 imports "../../Test_Base" begin datatype 'a list = nil2 | cons2 "'a" "'a list" datatype Nat = Z | S "Nat" fun last :: "Nat list => Nat" where "last (nil2) = Z" | "last (cons2 y (nil2)) = y" | "last (cons2 y (cons2 x2 x3)) = last (cons2 x2 x3)" theorem property0 : "((case xs of nil2 => True | cons2 y z => False) ==> ((last (cons2 x xs)) = (last xs)))" oops end
{-| Module: MachineLearning.PCA Description: Principal Component Analysis. Copyright: (c) Alexander Ignatyev, 2017-2018. License: BSD-3 Stability: experimental Portability: POSIX Principal Component Analysis (PCA) - dimensionality reduction algorithm. It is mostly used to speed up supervising learning (Regression, Classification, etc) and visualization of data. -} module MachineLearning.PCA ( getDimReducer , getDimReducer_rv ) where import Prelude hiding ((<>)) import Data.Maybe (fromMaybe) import qualified Data.Vector.Storable as V import qualified Numeric.LinearAlgebra as LA import Numeric.LinearAlgebra ((<>), (??)) import qualified MachineLearning as ML import MachineLearning.Types (R, Vector, Matrix) -- | Computes "covariance matrix". covarianceMatrix :: Matrix -> Matrix covarianceMatrix x = ((LA.tr x) <> x) / (fromIntegral $ LA.rows x) -- | Compute eigenvectors (matrix U) and singular values (matrix S) of the given covariance matrix. pca :: Matrix -> (Matrix, Vector) pca x = (u, s) where sigma = covarianceMatrix x (u, s, _) = LA.svd sigma -- | Gets dimensionality reduction function, retained variance (0..1) and reduced X -- for given matrix X and number of dimensions to retain. getDimReducer :: Matrix -> Int -> (Matrix -> Matrix, R, Matrix) getDimReducer x k = (reducer, retainedVariance, reducer xNorm) where muSigma = ML.meanStddev x xNorm = ML.featureNormalization muSigma x (u, s) = pca xNorm u' = u ?? (LA.All, LA.Take k) reducer xx = (ML.featureNormalization muSigma xx) <> u' retainedVariance = (V.sum $ V.slice 0 k s) / (V.sum s) -- | Gets dimensionality reduction function, retained number of dimensions and reduced X -- for given matrix X and variance to retain (0..1]. getDimReducer_rv :: Matrix -> R -> (Matrix -> Matrix, Int, Matrix) getDimReducer_rv x rv = (reducer, k, reducer xNorm) where muSigma = ML.meanStddev x xNorm = ML.featureNormalization muSigma x (u, s) = pca xNorm sum_s = V.sum s variances = (V.scanl' (+) 0 s) / (LA.scalar sum_s) k = fromMaybe ((V.length s) - 1) $ V.findIndex (\v -> v >= rv) variances u' = u ?? (LA.All, LA.Take k) reducer xx = (ML.featureNormalization muSigma xx) <> u'
[STATEMENT] lemma compatTstSyntactic[simp]: "tstSec tst = Lo \<Longrightarrow> Example_PL.compatTst tst" [PROOF STATE] proof (prove) goal (1 subgoal): 1. tstSec tst = Lo \<Longrightarrow> Example_PL.compatTst tst [PROOF STEP] unfolding Example_PL.compatTst_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. tstSec tst = Lo \<Longrightarrow> \<forall>s t. Example_PL.indisAbbrev s t \<longrightarrow> tval tst s = tval tst t [PROOF STEP] by (induct tst) (simp_all, safe del: iffI intro!: arg_cong2[where f="(=)"] arg_cong2[where f="(<) :: nat \<Rightarrow> nat \<Rightarrow> bool"] exprSec_Lo_eval_eq)
Formal statement is: lemma connected_component_idemp: "connected_component_set (connected_component_set S x) x = connected_component_set S x" Informal statement is: The connected component of a point $x$ in a set $S$ is the same as the connected component of $x$ in the connected component of $x$ in $S$.
module Examples import Data.Nat import Data.Vect import Data.List import LinearTypes import Control.Linear.LIO import Unitary import QStateT import System.Random import Injection import Complex import QuantumOp ------------------------ Example of circuits built with unitary contructors ----------------------- -- These functions only use the 4 constructors of the Unitary data type : IdGate, H, P, and CNOT ||| Put two qubits initally in state |00> in the Bell state public export toBellBasis : Unitary 2 toBellBasis = CNOT 0 1 (H 0 IdGate) ||| Draw the circuit toBellBasis using draw function export drawToBellBasis : IO () drawToBellBasis = do putStrLn "\nDrawing ToBellBasis: \nCNOT 0 1 (H 0 IdGate)" draw toBellBasis constructorsExample : Unitary 3 constructorsExample = H 1 (P (pi/2) 2 (CNOT 2 0 IdGate)) drawConstructorsExample : IO () drawConstructorsExample = do putStrLn "An example of circuit built with H, P and CNOT constructors :" putStrLn " H 1 (P (pi/2) 2 (CNOT 2 0 IdGate))" draw constructorsExample ---------------------------------- Examples using composition ------------------------------------- -- Sequential composition of unitary circuits compose_example1 : Unitary 1 compose_example1 = TGate . HGate compose_example2 : Unitary 2 compose_example2 = (H 1 IdGate) . (P pi 0 IdGate) . toBellBasis drawComposeExamples : IO () drawComposeExamples = do putStrLn "Examples using composition" putStrLn "Example 1 : TGate . HGate" draw compose_example1 putStrLn "Example 2 : (H 1 IdGate) . (P pi 0 IdGate) . toBellBasis" draw compose_example2 ------------------------------------ Examples using tensor product -------------------------------- -- Parallel composition (ie tensor product) of unitary circuits ||| Example using the # operator for tensor product tensorExample1 : Unitary 4 tensorExample1 = HGate # PGate pi # CNOTGate ||| Example using tensorn function : |||Make n tensor products of the same unitary of size 1 tensornExample : Unitary 3 tensornExample = tensorn 3 HGate ||| Example using tensorMapSimple function ||| Tensor product of a Vector of single-qubit Unitary operators tensorMapSimpleExample : Unitary 3 tensorMapSimpleExample = tensorMapSimple [HGate, PGate pi, HGate] ||| Example using tensorMap function ||| Tensor product of a Vector of Unitary operators tensorMapExample : Unitary 6 tensorMapExample = tensorMap [CNOTGate, toBellBasis, CNOTGate] drawTensorExamples : IO () drawTensorExamples = do putStrLn "Examples using tensor product" putStrLn "Example 1 : HGate # PGate pi # CNOTGate" draw tensorExample1 putStrLn "Example 2 : tensorn 3 HGate" draw tensornExample putStrLn "Example 3 : tensorMapSimple [HGate, PGate pi, HGate]" draw tensorMapSimpleExample putStrLn "Example 4 : tensorMap [CNOTGate, toBellBasis, CNOTGate]" draw tensorMapExample ||| Another version of toBellBasis using composition and tensor product toBellBasis2 : Unitary 2 toBellBasis2 = CNOTGate . (HGate # IdGate) drawToBellBasis2 : IO () drawToBellBasis2 = do putStrLn "\nAnother possibility for toBellBasis: \nCNOTGate . (HGate # IdGate)" draw toBellBasis2 ---------------------------------------- Examples using adjoint ----------------------------------- -- The adjoint of a unitary circuit is the inverse unitary circuit adjoint_example1 : Unitary 2 adjoint_example1 = adjoint toBellBasis adjoint_example2 : Unitary 3 adjoint_example2 = adjoint toffoli drawAdjointExamples : IO () drawAdjointExamples = do putStrLn "Examples using adjoint" putStrLn "Example 1 : adjoint toBellBasis" draw adjoint_example1 putStrLn "Example 2 : adjoint toffoli" draw adjoint_example2 ||| Draw an example of circuit using tensor, compose and adjoint export exampleComposeTensor1 : IO () exampleComposeTensor1 = do putStrLn "\nAn example of usage of compose, tensor and adjoint: \n(adjoint toBellBasis # IdGate) . (TGate # toBellBasis)" let circuit = (adjoint toBellBasis # IdGate) . (TGate # toBellBasis) draw circuit ---------------------------------------- Examples using apply ------------------------------------- -- Apply : apply a smaller unitary circuit of size i to a bigger one of size n, giving the vector v of wire indices on which we wish to apply the smaller circuit U : Unitary 3 U = HGate # IdGate {n = 1} # (PGate pi) apply_example1 : Unitary 3 apply_example1 = apply toBellBasis U [0,1] apply_example2 : Unitary 3 apply_example2 = apply toBellBasis U [0,2] apply_example3 : Unitary 3 apply_example3 = apply toBellBasis U [2,0] apply_example4 : Unitary 3 apply_example4 = apply toBellBasis U [2,1] apply_example5 : Unitary 3 apply_example5 = apply toffoli IdGate [2,0,1] drawApplyExamples : IO () drawApplyExamples = do putStrLn "\nApply Examples \nU = HGate # IdGate {n = 1} # (PGate pi)\n" putStrLn "Example 1 : apply toBellBasis U [0,1]" draw apply_example1 putStrLn "Example 2 : apply toBellBasis U [0,2]" draw apply_example2 putStrLn "Example 3 : apply toBellBasis U [2,0]" draw apply_example3 putStrLn "Example 4 : apply toBellBasis U [2,1]" draw apply_example4 putStrLn "Example 5 : apply toffoli [2,0,1]" draw apply_example5 -------------------------------------- Example using controlled ----------------------------------- -- Compute the controlled version of a unitary circuit controlled_example1 : Unitary 2 controlled_example1 = controlled TGate ||| Example using multipleQubitControlledNOT ||| Makes a multiple qubit CNOT gate : control on the first n qubits, target on the last multipleQubitsCNOTExample : Unitary 4 multipleQubitsCNOTExample = multipleQubitControlledNOT 4 --------------------------------- Examples of parametrized circuits ------------------------------- -- Unitary circuits can be parametrized by classical information parametrized_example1 : Bool -> Unitary 1 parametrized_example1 b = if b then HGate else PGate pi parametrized_example2 : Bool -> Bool -> Double -> Unitary 2 parametrized_example2 b1 b2 p = CNOTGate . (if b1 then H 0 IdGate else IdGate) . (if b2 then IdGate else P p 1 IdGate) drawParamExamples : IO () drawParamExamples = do putStrLn "Examples of circuits parametrized by classical data" putStrLn "Example 1 : for b : bool , if b then HGate else PGate pi" putStrLn "For b = True : " draw (parametrized_example1 True) putStrLn "For b = False : " draw (parametrized_example1 False) putStrLn "Example 2 : for b1, b2 : Bool and p : Double , CNOTGate . (if b1 then H 0 IdGate else IdGate) . (if b2 then IdGate else P p 1 IdGate)" putStrLn "For b1 = True, b2 = False, p = pi/2" draw (parametrized_example2 True False (pi/2)) ------------------------------------ Example of depth computation --------------------------------- -- Compute the depth of a circuit depthExample1 : Unitary 3 depthExample1 = CNOT 0 1 $ CNOT 2 1 $ H 1 $ CNOT 0 2 IdGate depthExample2 : Unitary 3 depthExample2 = H 2 $ H 1 $ H 0 $ H 1 IdGate depthExample3 : Unitary 3 depthExample3 = CNOT 1 2 $ CNOT 0 2 $ CNOT 0 1 $ H 1 $ P pi 1 $ H 1 IdGate drawDepthExamples : IO () drawDepthExamples = do putStrLn "Examples of depth computation" putStrLn "The depth of the following circuit" draw depthExample1 putStrLn ("is " ++ show (depth depthExample1)) putStrLn "\n\nThe depth of the following circuit" draw depthExample2 putStrLn $ "is " ++ show (depth depthExample2) putStrLn "\n\nThe depth of the following circuit" draw depthExample3 putStrLn $ "is " ++ show (depth depthExample3) ----------------------------------- Examples of quantum operations -------------------------------- ||| Sequencing quantum operations using run ||| quantum_operation4 : QuantumOp t => IO (Vect 3 Bool) quantum_operation4 = run (do [q1,q2] <- newQubits {t=t} 2 --create 2 new qubits q1 and q2 [q1,q2] <- applyUnitary [q1,q2] toBellBasis --apply the toBellBasis unitary circuit to q1 and q2 q3 <- newQubit --create 1 new qubit q3 [q1,q3,q2] <- applyUnitary [q1,q3,q2] toffoli --apply toffoli gate on q1, q3 and q2 [b2] <- measure [q2] --measure q2 (q3 # q1) <- applyCNOT q3 q1 --apply CNOT on q3 and q1 [b1,b3] <- measure [q1,q3] --measure q1 and q3 pure [b1,b2,b3] --return the results ) drawQuantumOp : IO () drawQuantumOp = do [b1,b2,b3] <- quantum_operation4 {t = SimulatedOp} putStrLn "\n\nExecuting an example of quantum operations : sequencing quantum operations using run" putStrLn "Create 2 qubits q1 and q2" putStrLn "Apply `toBellBasis` circuit on q1 and q2" putStrLn "Create one new qubit q3" putStrLn "Apply the toffoli gate on q1,q3 and q2" putStrLn $ "Measure q2 : result is " ++ show b2 putStrLn "Apply CNOT on q3 and q1" putStrLn $ "Measure q1 and q3 : results are " ++ show b1 ++ " and " ++ show b3 ------------------------------------ Draw all example circuits ------------------------------------ export drawExamples : IO () drawExamples = do drawToBellBasis drawConstructorsExample drawComposeExamples drawTensorExamples drawToBellBasis2 drawAdjointExamples exampleComposeTensor1 drawApplyExamples drawParamExamples drawDepthExamples drawQuantumOp
library(tidyverse) library(data.table) library(readxl) library(scales) library(ggrepel) library(ggforce) library(gganimate) library(gifski) library(xts) library(roll) library(rnaturalearth) library(rnaturalearthdata) library(countrycode) library(cowplot) options(na.action = na.exclude) setwd("~/Public_Policy_Upd/Projects/Inequality") get_period_growth = function(start, end, periods) { period_avg_growth = (end / start)^(1/periods) - 1 return(period_avg_growth) } ##### get polity data ##### polity_political_violence = read_excel('data/MEPVv2018.xls') polity_coups = read_excel('data/CSPCoupsAnnualv2018 (1).xls') polity_v = read_excel( "data/polity iv data.xls" ) filter(polity_political_violence, str_detect(country %>% tolower(), 'vietnam')) %>% pull(country) %>% unique() filter(polity_political_violence, str_detect(country %>% tolower(), 'cambodia')) %>% pull(country) %>% unique() filter(polity_political_violence, str_detect(country %>% tolower(), 'laos')) %>% pull(country) %>% unique() polity_v_fin = left_join(polity_v, polity_coups) %>% left_join(polity_political_violence) %>% mutate( country = recode(country, UAE = 'United Arab Emirates', Bosnia = "Bosnia and Herzegovina", `Congo Brazzaville` = 'Congo', `Congo Kinshasa` = 'D.R. of the Congo', `Korea South` = 'South Korea', `Korea North` = 'North Korea', `USSR` = 'Former USSR') ) world_map <- ne_countries(scale = "medium", returnclass = "sf") %>% mutate( name = recode(name, `Dem. Rep. Korea` = 'South Korea', `Czech Rep.` = 'Czech Republic', `Slovakia` = 'Slovak Republic', `Bosnia and Herz.` = 'Bosnia and Herzegovina', `Macedonia` = 'North Macedonia', `Dem. Rep. Congo` = "D.R. of the Congo", `S. Sudan` = 'South Sudan', `Eq. Guinea`="Equatorial Guinea", `Central African Rep.` = "Central African Republic", `North Macedonia` = 'Macedonia', `Myanmar` = 'Myanmar (Burma)', `N. Cyprus` = 'Cyprus', `Lao PDR` = 'Laos' ) ) world_map$name = ifelse(str_detect(world_map$name, 'Ivoire'), "Cote D'Ivoire", world_map$name) #### get historical gdp stats and join everything ##### historical_gdp_stats = read_excel("data/angus maddison historical gdp statistics.xlsx", 'Full data') %>% mutate( country = recode(country, `Bolivia (Plurinational State of)` = 'Bolivia', `Russian Federation` = 'Russia', `Viet Nam` = 'Vietnam', `D.P.R. of Korea` = 'North Korea', `Republic of Korea` = 'South Korea', `Syrian Arab Republic` = 'Syria', `Iran (Islamic Republic of)` = 'Iran', `Lao People's DR` = 'Laos', # `Former USSR` = 'USSR', `Sudan (Former)` = 'Sudan', `Myanmar` = 'Myanmar (Burma)', `Slovakia` = 'Slovak Republic', `Venezuela (Bolivarian Republic of)` = 'Venezuela', `Taiwan, Province of China` = 'Taiwan', `TFYR of Macedonia` = 'Macedonia', # `D.R. of the Congo`='Congo Kinshasa', # `Congo` = 'Congo-Brazzaville', `Republic of Moldova` = 'Moldova', `Dominica` = 'Dominican Republic', `U.R. of Tanzania: Mainland` = 'Tanzania', `China, Hong Kong SAR` = 'Hong Kong' ) ) %>% arrange(countrycode, year) %>% data.table() historical_gdp_stats_growth = historical_gdp_stats[, { # china = filter(historical_gdp_stats, country == 'China') # attach(china) # detach(china) # the_dat = data.frame(year, cgdppc, rgdpnapc, pop) full_year_df = data.frame( year = min(year, na.rm = T):max(year, na.rm = T) ) %>% left_join( the_dat ) %>% mutate( rgdpnapc_interpolated = na.approx(rgdpnapc, na.rm = F), lag_1_rgdpnapc = lag(rgdpnapc, 1), lag_2_rgdpnapc = lag(rgdpnapc, 2), lag_5_rgdpnapc = lag(rgdpnapc, 5), lag_10_rgdpnapc = lag(rgdpnapc, 10), lag_10_rgdpnapc_interpolated = lag(rgdpnapc_interpolated, 10), pop_interpolated = na.approx(pop, na.rm = F), real_gdp_cap_growth = (rgdpnapc - lag(rgdpnapc, 1))/ lag(rgdpnapc, 1), real_gdp_cap_growth_interp = (rgdpnapc_interpolated - lag(rgdpnapc_interpolated, 1))/ lag(rgdpnapc_interpolated, 1), roll_5_real_gdp_cap_growth_interp = roll_mean(real_gdp_cap_growth_interp, 5), lag_5_roll_5_real_gdp_cap_growth_interp = lag(roll_5_real_gdp_cap_growth_interp, 5), pop_growth = (pop - lag(pop, 1)) / lag(pop, 1), pop_growth_interp = (pop_interpolated - lag(pop_interpolated, 1)) / lag(pop_interpolated, 1), lagged_real_gdp_cap_growth = lag(real_gdp_cap_growth, 1), lagged_real_gdp_cap_growth_interp = lag(real_gdp_cap_growth_interp, 1) ) full_year_df }, by = list(country)] %>% full_join( polity_v_fin, by = c('country', 'year') ) %>% mutate( polity2 = ifelse(polity2 %in% c(-88, -66), NA, polity2), polity_desc = ifelse(between(polity2, -5, 5), 'Anocracy (mixed)', ifelse(polity2 > 5, 'Democracy', 'Autocracy')), polity_desc = factor(polity_desc, levels = c('Autocracy', 'Anocracy (mixed)', 'Democracy')), autocratic_shift = change < 0 & sign(polity2) != sign(prior) & is.na(interim), n_coups = scoup1 + atcoup2, had_civil_war = civwar > 0 ) %>% arrange(country, year) historical_gdp_stats_growth_rollstats = historical_gdp_stats_growth[, { lagged_polity2 = lag(polity2, 1) mean_real_gdp_cap_growth_interp_10 = roll_mean(real_gdp_cap_growth_interp, 10) list( year = year, mean_real_gdp_cap_growth_interp_10 = mean_real_gdp_cap_growth_interp_10, lagged_mean_real_gdp_cap_growth_interp_10 = lag(mean_real_gdp_cap_growth_interp_10, 1), n_polity_changes_last_20_years = roll_sum(polity2 - lagged_polity2 != 0, 20), lagged_polity2 = lagged_polity2, n_autocratic_shifts_last_10_years = roll_sum(autocratic_shift, 10), n_coup_attempts_last_10_years = roll_sum(atcoup2, 10), n_coups_last_10_years = roll_sum(scoup1, 10), n_civil_war_years_last_10_years = roll_sum(civwar > 0, 10) ) }, by = list(country)] stats_by_country = historical_gdp_stats_growth[,{ list( anocracy_years = sum(between(polity2, -5, 5), na.rm = T), democracy_years = sum(polity2 > 5, na.rm = T), autocracy_years = sum(polity2 < -5, na.rm = T), civ_war_denom = sum(!is.na(civwar)), n_civil_war_years = sum(civwar > 0, na.rm = T), avg_polity2 = mean(polity2, na.rm = T), max_polity2 = max(polity2, na.rm = T), min_polity2 = min(polity2, na.rm = T), transition_periods = sum(is.na(polity2)), n_coup_attempts = sum(atcoup2, na.rm = T), n_successful_coups = sum(scoup1, na.rm = T) ) }, by = list(country)] polity_income_years = c(1850, 1900, seq(1950, 2010, by = 10), 2015) wide_income_polity_stats = historical_gdp_stats_growth %>% filter(year %in% polity_income_years) %>% select(-polity) %>% rename(income = rgdpnapc_interpolated, polity = polity2) %>% pivot_wider(id_cols = c('country'), values_from = c('polity', 'income', 'pop'), names_from = 'year', values_fn = mean) stats_by_country = left_join( stats_by_country, wide_income_polity_stats ) %>% dplyr::mutate( pct_civil_war_years = n_civil_war_years / civ_war_denom, percent_democracy_years = democracy_years / (anocracy_years + democracy_years + autocracy_years), coup_war_score = (n_civil_war_years > 0) + (n_coup_attempts > 0 | n_successful_coups > 0), growth_1850_2015 = get_period_growth(income_1850, income_2015, 2015 - 1850 + 1), growth_1900_2015 = get_period_growth(income_1900, income_2015, 2015 - 1900 + 1), growth_1950_2015 = get_period_growth(income_1950, income_2015, 2015 - 1950 + 1), percentile_1900 = cume_dist(income_1900), percentile_2015 = cume_dist(income_2015) ) stats_by_year = group_by(historical_gdp_stats_growth, year) %>% summarize( annual_income_95 = quantile(rgdpnapc, probs = 0.95, na.rm = T), annual_income_max = max(rgdpnapc, na.rm = T), annual_income_median = quantile(rgdpnapc, probs = 0.5, na.rm = T), avg_world_gdp_growth = mean(real_gdp_cap_growth, na.rm = T) ) historical_gdp_stats_growth_fin = left_join( historical_gdp_stats_growth, stats_by_country ) %>% left_join( stats_by_year ) %>% left_join( historical_gdp_stats_growth_rollstats ) %>% mutate( percent_of_max_income = rgdpnapc_interpolated / annual_income_max, had_attempted_coup = atcoup2 > 0, had_successful_coup = scoup1 > 0, civwar_factor = factor(civwar), log_lag_10_rgdpnapc_interpolated = log(lag_10_rgdpnapc_interpolated), log_rgdpnapc_interpolated = log(rgdpnapc_interpolated), percent_polity_changes_20 = n_polity_changes_last_20_years / 20 ) ##### quick model for per capita gdp #### filter(historical_gdp_stats_growth_fin, country == 'Argentina', between(year, 1940, 1980)) %>% select(year, scoup1, atcoup2 ) names(historical_gdp_stats_growth_fin) full_mod = lm(log_rgdpnapc_interpolated ~ log_lag_10_rgdpnapc_interpolated + avg_world_gdp_growth + lag_5_roll_5_real_gdp_cap_growth_interp + percent_of_max_income + year + polity2 + had_attempted_coup + civwar_factor + had_successful_coup + percent_polity_changes_20, data = historical_gdp_stats_growth_fin) summary(full_mod) plot(full_mod) polity_with_coups_wars = lm(log_rgdpnapc_interpolated ~ log_lag_10_rgdpnapc_interpolated + percent_of_max_income * polity2 + had_attempted_coup + had_successful_coup + I(civwar > 0) + lag_5_roll_5_real_gdp_cap_growth_interp + avg_world_gdp_growth + year, data = historical_gdp_stats_growth_fin %>% filter(year <= 2005)) summary(polity_with_coups_wars) pure_polity_mod = lm(log_rgdpnapc_interpolated ~ log_lag_10_rgdpnapc_interpolated + percent_of_max_income + polity_desc*polity2 + percent_polity_changes_20 + lag_5_roll_5_real_gdp_cap_growth_interp + avg_world_gdp_growth + year, data = historical_gdp_stats_growth_fin %>% filter(year <= 2005)) summary(pure_polity_mod) predict(pure_polity_mod, newdata = overall_means %>% mutate( log_lag_10_rgdpnapc_interpolated = log(6211.999), avg_world_gdp_growth = 0.015, year = 2015, lagged_mean_real_gdp_cap_growth_interp_10 = 0.06, polity2 = -7 ) ) %>% exp() anova(pure_polity_mod, polity_desc_mod) roll_mod = lm(log(rgdpnapc) ~ log(lag_10_rgdpnapc) + avg_world_gdp_growth + I(rgdpnapc / annual_income_max) + year + polity2 + I(n_coup_attempts_last_10_years > 0) + I(n_civil_war_years_last_10_years > 0) + I(n_coups_last_10_years > 0), data = historical_gdp_stats_growth_fin) levels(historical_gdp_stats_growth_fin$polity_desc) historical_gdp_stats_growth_fin$predicted_income_polity_mod = predict(pure_polity_mod, newdata = historical_gdp_stats_growth_fin %>% mutate( # polity2 = ifelse(country == 'Argentina', 10, polity2), # polity_desc = ifelse(country == 'Argentina', levels(historical_gdp_stats_growth_fin$polity_desc)[3], polity_desc), # polity_desc = factor(polity_desc) ) ) ggplot(historical_gdp_stats_growth_fin, aes(predicted_income_polity_mod %>% exp(), rgdpnapc)) + facet_wrap(~year <= 2005) + geom_point() historical_gdp_stats_growth_fin %>% filter(country %in% c('Argentina', 'United States', 'Botswana', 'Japan', 'South Korea'), year > 1850) %>% ggplot(aes(year)) + geom_line(aes(y = predicted_income_full_mod %>% exp(), colour = country), linetype = 'dashed') + geom_line(aes(y = rgdpnapc, colour = country)) historical_gdp_stats_growth_fin %>% filter(country %in% c('Argentina', 'United States', 'Botswana', 'Japan', 'South Korea', 'China'), year > 1850) %>% ggplot(aes(year)) + facet_wrap(~country) + geom_line(aes(y = predicted_income_polity_mod %>% exp(), colour = country), linetype = 'dashed') + geom_line(aes(y = rgdpnapc_interpolated, colour = country)) filter(historical_gdp_stats_growth_fin, country == 'China') %>% View() filter(historical_gdp_stats_growth, country %in% c('United States', 'United Kingdom', 'Argentina'), between(year, 1890, 1900) | between(year, 1930, 1940)) %>% select(country, year, rgdpnapc) %>% pivot_wider(names_from = "country", values_from = 'rgdpnapc') %>% View() setwd('output') ##### US vs. Argentina growth, polity ##### us_argentine_comparison = filter(historical_gdp_stats_growth %>% filter(between(year, 1850, 2015)), country %in% c('United States', 'Argentina'), !is.na(rgdpnapc)) %>% mutate(label = ifelse(year == max(year), country, NA)) argentina_greater_us = us_argentine_comparison %>% select(country, year, rgdpnapc) %>% pivot_wider(id_cols = c('country', 'year'), values_from = 'rgdpnapc', names_from = 'country') %>% filter(Argentina > `United States`) argentina_rect = data.frame( xmin = min(argentina_greater_us$year), xmax = max(argentina_greater_us$year) ) argentine_coups_regime_changes = filter(us_argentine_comparison, n_coups > 0 | autocratic_shift ) %>% as.data.frame() %>% mutate( label = ifelse(scoup1 > 0, "Success", ifelse(n_coups > 0, "Failure", NA)), coup_label = ifelse(scoup1 > 0, "Coup", ifelse(n_coups > 0, "Attempted Coup", NA)), coup_label = ifelse(scoup1 > 1, 'Multiple\nSuccessful Coups', coup_label) ) argentina_rects = tribble( ~xmin, ~xmax, min(argentina_greater_us$year), max(argentina_greater_us$year), min(argentine_coups_regime_changes$year), max(argentine_coups_regime_changes$year) ) n_coups = filter(argentine_coups_regime_changes, n_coups > 0) %>% pull(n_coups) %>% sum() n_successful_coups = filter(argentine_coups_regime_changes, n_coups > 0) %>% pull(scoup1) %>% sum() n_autocratic_shifts = filter(argentine_coups_regime_changes, autocratic_shift) %>% nrow() # # anim = # growth_comparison_dat %>% filter(days_since_case_100 >=0) %>% # ggplot(aes(days_since_case_100, value, colour = country_region)) + # geom_line(size = 1) + # geom_point(size = 2) + # transition_reveal(days_since_case_100) + # coord_cartesian(clip = 'off') + # labs( # title = paste0('COVID-19 Cases by Day, Through ', format(max(growth_comparison_dat$date_upd), '%B %d')), # y = 'Case Count\n', # x = '\nDays Since Case 100', # subtitle = 'Diverging paths illustrate the varied effectiveness of public health responses.', # caption = 'Chart: Taylor G. White\nData: Johns Hopkins CSSE') + # theme_minimal() + # scale_y_continuous(labels = comma) + # scale_x_continuous(breaks = seq(0, 60, by = 10)) + # theme( # plot.caption = element_text(size = 10, hjust = 0), # legend.position = 'bottom' # ) + # theme(plot.margin = margin(5.5, 10, 5.5, 5.5), plot.subtitle = element_text(size=11, face = 'italic')) + # scale_colour_hue(name = 'Country', labels = c('Korea, South' = 'South Korea')) + # geom_segment(aes(xend = max(days_since_case_100) + 1, yend = value, group = country_region), linetype = 2, colour = 'grey') + # geom_point(size = 2) + # geom_text_repel(aes(x = max(days_since_case_100) + 1, label = comma(value)), hjust = 0, size = 3, # vjust = -0.5, # show.legend = F) + # geom_text_repel(data = key_dates, aes(x =days_since_case_100, y = c(60000, 70000, 80000), label = action), hjust = 0, size = 3, # vjust = -0.5, # show.legend = F) + # geom_vline(data = key_dates, # aes(xintercept = days_since_case_100, colour = country_region), size = 0.5, linetype = 'dashed', show.legend = F) # # animate(anim, nframes = 300, # renderer = gifski_renderer("output/covid_case_growth_comparison.gif"), # height = 6, width = 6, units = 'in', type = 'cairo-png', res = 200) argentina_rects_anim = tibble( year = argentina_rects[2,]$xmin:argentina_rects[2,]$xmax %>% as.numeric(), start_year = argentina_rects[2,]$xmin ) animated_us_argentina = us_argentine_comparison %>% ggplot(aes(group = country)) + theme_bw() + transition_reveal(year) + geom_rect(data = argentina_rects_anim, aes(xmin = min(year), xmax = year, ymin = 0, group = seq_along(year), ymax = 55000), fill = 'gray90') + geom_line(aes(year, rgdpnapc)) + geom_text(data = argentina_greater_us, aes(x = year, y = Argentina * 2, label = "Argentina's income briefly passes the U.S.", group = NA)) + geom_text(data = argentina_rects_anim, aes(x = mean(argentina_rects_anim$year), y = 55000, label = sprintf("Argentina:\n%s autocratic shifts, %s coups d'etat (%s attempted)", n_autocratic_shifts, n_successful_coups, n_coups), group = seq_along(year))) + geom_segment(data = argentina_greater_us, aes(x = year, xend = year, y = Argentina, yend = Argentina * 2, group = NA)) + # geom_point(data = argentine_coups_regime_changes %>% filter(!is.na(label)), aes(year, rgdpnapc, shape = label), size = 4) + geom_point(aes(year, rgdpnapc, colour = polity_desc, group = seq_along(year)), size = 1.5) + scale_shape_manual(name = "Coups d'Etat",values = c("Success" = 8, "Failure" = 5)) + # facet_zoom(xlim = c(1890, 1910), ylim = c(3000, 7000), horizontal = FALSE) + scale_alpha(guide = F) + scale_colour_manual(name = "Type of Government", values = c('Autocracy' = '#e61938', 'Anocracy (mixed)' = 'darkgray', 'Democracy' = '#0045a1')) + guides(colour = guide_legend(override.aes = list(size = 5))) + # annotate('text', x = mean(argentina_greater_us$year), y = 55000, label = "Argentina's income surpasses U.S., 1894-1896", angle = 0, vjust = -0.5) + # annotate('text', x = mean(argentine_coups_regime_changes$year), y = 55000, label = sprintf("%s autocratic shifts, %s coups d'etat (%s attempted)", n_autocratic_shifts, n_successful_coups, n_coups), angle = 0, vjust = -0.5) + # scale_colour_gradient2(name = 'Polity V Score\n>0 is Democratic',low = '#e61938', high = '#0045a1', mid = 'gray', midpoint = 0) + # scale_colour_hue(name = 'Democratic', labels = c('TRUE' = 'Yes', 'FALSE' = 'No')) + geom_label_repel(aes(year, rgdpnapc, label = country), nudge_x = 1, na.rm = T, nudge_y = 3) + scale_y_continuous(labels = dollar, breaks = seq(0, 50000, by = 10000)) + scale_x_continuous(breaks = seq(1850, 2015, by = 10)) + labs( y = 'Real GDP Per Capita (2011 USD)\n', x = '', title = 'Democracy and Economic Prosperity', subtitle = 'Comparing divergent political and economic paths of the U.S. and Argentina', caption = 'Chart: Taylor G. White (@t_g_white)\nData: Polity Project, Maddison Project' ) + theme_minimal() + theme( legend.background = element_rect(fill = 'white'), legend.position = c(0.15, 0.9), axis.text = element_text(size = 11), axis.title = element_text(size = 14), plot.subtitle = element_text(size = 15), legend.text = element_text(size = 9), legend.title = element_text(size = 10), plot.caption = element_text(size = 11, face = 'italic', hjust = 0), title = element_text(size = 18) ) # # animate(animated_us_argentina, nframes = 200, # renderer = gifski_renderer("argentina_vs_us_income_comparison.gif"), # height = 8, width = 8, units = 'in', type = 'cairo-png', res = 150, start_pause = 4, end_pause = 20) # argentina_stats = filter(stats_by_country, country == 'Argentina') %>% as.data.frame() dollar_label_func = function(x) { dollar(round(x, 0)) } ggplot(stats_by_country, aes(income_1900, income_2015)) + theme_bw() + # geom_vline(aes(xintercept = ifelse(country == 'Argentina', income_1900, NA)), na.rm = T, linetype = 'dashed') + # geom_hline(aes(yintercept = ifelse(country == 'Argentina', income_2015, NA)), na.rm = T, linetype = 'dashed') + geom_segment(data = argentina_stats, aes(x = income_1900, xend = 8000, y = income_2015, yend = 15000), colour = 'orange') + geom_label(data = argentina_stats, aes(x = 8000, y = 15000, label = sprintf("Argentina's Income was in the %sth percentile in 1900, but fell to the %sth percentile by 2015.", round(percentile_1900*100), round(percentile_2015 * 100)) %>% str_wrap(32) )) + # annotate('text', x = 8000, y = 15000, label = sprintf("Argentina's Income was in the %sth percentile in 1900", round(argentina_stats$percentile_1900*100)) %>% str_wrap(32)) + # geom_segment(aes(x = 0, xend = ifelse(country == 'Argentina', income_1900, NA), y = ifelse(country == 'Argentina', income_2015, NA), yend = ifelse(country == 'Argentina', income_2015, NA)), na.rm = T, linetype = 'dashed') + # geom_segment(aes(y = 0, yend = ifelse(country == 'Argentina', income_2015, NA), x = ifelse(country == 'Argentina', income_1900, NA), xend = ifelse(country == 'Argentina', income_1900, NA)), na.rm = T, linetype = 'dashed') + labs( x = 'Log Real Per Capita GDP in 1900\n(2011 USD)', y = 'Log Real Per Capita GDP in 2015\n(2011 USD)', title = 'Per Capita Income in 1900 vs. 2015' ) + # geom_label_repel(aes(label = ifelse(country %in% c('Argentina', 'United States'), country, NA)), na.rm = T) + scale_x_continuous(labels = dollar_label_func, trans = 'log') + scale_y_continuous(labels = dollar_label_func, trans = 'log') + stat_smooth(method = 'lm', se = F) + geom_point() us_argentine_comparison %>% ggplot() + theme_bw() + # annotation_custom(grob = ggplotGrob(historical_income_plot), xmin = 1850, xmax = 1900, ymin = 20e3, ymax = 55e3) + geom_label_repel(aes(year, rgdpnapc, label = label), nudge_x = 1, na.rm = T, nudge_y = 3e3, segment.colour = 'orange') + geom_rect(data = argentina_rects[2,], aes(xmin = xmin, xmax = xmax, ymin = 0, ymax = 55000), alpha = 0.25, fill = 'gray90', colour = 'black', linetype = 'dashed') + geom_text_repel(data = argentina_greater_us %>% head(1), aes(x = year, y = Argentina), label = "Argentina's income\nbriefly surpassed the U.S.", nudge_y = 10e3) + geom_line(aes(year, rgdpnapc, group = country)) + # geom_point(data = argentine_coups_regime_changes %>% filter(!is.na(label)), aes(year, rgdpnapc, shape = label), size = 4) + geom_text_repel(data = argentine_coups_regime_changes %>% filter(scoup1 > 0), aes(year, rgdpnapc, label = coup_label), size = 3, segment.colour = 'orange', nudge_y = -4e3) + geom_point(aes(year, rgdpnapc, colour = polity_desc), size = 1.5) + scale_shape_manual(name = "Coups d'Etat",values = c("Success" = 8, "Failure" = 5)) + # facet_zoom(xlim = c(1890, 1910), ylim = c(3000, 7000), horizontal = FALSE) + scale_alpha(guide = F) + scale_colour_manual(name = "Type of Government", values = c('Autocracy' = '#e61938', 'Anocracy (mixed)' = 'gray', 'Democracy' = '#0045a1')) + # annotate('text', x = mean(argentina_greater_us$year), y = 55000, label = "Argentina's income surpasses U.S., 1894-1896", angle = 0, vjust = -0.5) + annotate('text', x = mean(argentine_coups_regime_changes$year), y = 55000, label = sprintf("%s autocratic shifts, %s coups d'etat (%s attempted)", n_autocratic_shifts, n_successful_coups, n_coups), angle = 0, vjust = -0.5) + # scale_colour_gradient2(name = 'Polity V Score\n>0 is Democratic',low = '#e61938', high = '#0045a1', mid = 'gray', midpoint = 0) + # scale_colour_hue(name = 'Democratic', labels = c('TRUE' = 'Yes', 'FALSE' = 'No')) + scale_y_continuous(labels = dollar, breaks = seq(0, 50000, by = 10000)) + scale_x_continuous(breaks = seq(1850, 2015, by = 10)) + labs( y = 'Real GDP Per Capita (2011 USD)\n', x = '', title = 'Political Power and Stability vs. Economic Prosperity', subtitle = 'Comparing divergent political and economic paths of the U.S. and Argentina, 1850-2015', caption = 'Chart: Taylor G. White (@t_g_white)\nData: Polity Project, Maddison Project' ) + theme_minimal() + theme( # legend.background = element_rect(fill = 'white'), # legend.position = c(0.10, 0.90), legend.position = 'bottom', axis.text = element_text(size = 12), axis.title = element_text(size = 16), plot.subtitle = element_text(size = 18), legend.text = element_text(size = 11), legend.title = element_text(size = 12), plot.caption = element_text(size = 13, face = 'italic', hjust = 0), title = element_text(size = 26) ) ggsave('us vs argentina paths.png', height = 9, width = 12, units = 'in', dpi = 600) ##### South Korea vs North Korea ##### filter(historical_gdp_stats_growth %>% filter(between(year, 1950, 2015)), country %in% c('South Korea', 'North Korea'), !is.na(rgdpnapc)) %>% mutate(label = ifelse(year == max(year), country, NA)) %>% ggplot(aes(year, rgdpnapc)) + theme_bw() + geom_line(aes(group = country)) + geom_point(aes(colour = polity_desc), size = 1.5) + scale_alpha(guide = F) + scale_colour_manual(name = "Type of Government", values = c('Autocracy' = '#e61938', 'Anocracy (mixed)' = 'gray', 'Democracy' = '#0045a1')) + # scale_colour_gradient2(name = 'Polity V Score\n>0 is Democratic',low = '#e61938', high = '#0045a1', mid = 'gray', midpoint = 0) + # scale_colour_hue(name = 'Democratic', labels = c('TRUE' = 'Yes', 'FALSE' = 'No')) + geom_label_repel(aes(label = label), nudge_x = 1, na.rm = T, nudge_y = 2) + scale_y_continuous(labels = dollar) + scale_x_continuous(breaks = seq(1950, 2015, by = 5)) + labs( y = 'Real GDP Per Capita (2011 USD)\n', x = '', title = 'Political Power and Stability vs. Economic Prosperity', subtitle = 'Comparing diverging political and economic paths of North and South Korea, 1950-2015', caption = 'Chart: Taylor G. White\nData: Polity Project, Maddison Project' ) + theme_minimal() + theme( legend.background = element_rect(fill = 'white'), legend.position = c(0.10, 0.875), axis.text = element_text(size = 12), axis.title = element_text(size = 16), plot.subtitle = element_text(size = 18), legend.text = element_text(size = 11), legend.title = element_text(size = 12), plot.caption = element_text(size = 13, face = 'italic', hjust = 0), title = element_text(size = 26) ) ggsave('north vs. south korea paths.png', height = 9, width = 12, units = 'in', dpi = 600) ##### USA vs USSR ##### ##### South Korea vs North Korea ##### filter(historical_gdp_stats_growth %>% filter(between(year, 1850, 2015)), country %in% c('USSR', 'Russia', 'United States'), !is.na(rgdpnapc)) %>% mutate(label = ifelse(year == max(year), country, NA)) %>% ggplot(aes(year, rgdpnapc)) + theme_bw() + geom_line(aes(group = country)) + geom_point(aes(colour = polity_desc), size = 1.5) + scale_alpha(guide = F) + scale_colour_manual(name = "Type of Government", values = c('Autocracy' = '#e61938', 'Anocracy (mixed)' = 'gray', 'Democracy' = '#0045a1')) + # scale_colour_gradient2(name = 'Polity V Score\n>0 is Democratic',low = '#e61938', high = '#0045a1', mid = 'gray', midpoint = 0) + # scale_colour_hue(name = 'Democratic', labels = c('TRUE' = 'Yes', 'FALSE' = 'No')) + geom_label_repel(aes(label = label), nudge_x = 1, na.rm = T, nudge_y = 3) + scale_y_continuous(labels = dollar) + scale_x_continuous(breaks = seq(1850, 2015, by = 10)) + labs( y = 'Real GDP Per Capita (2011 USD)\n', x = '', title = 'Political Power and Stability vs. Economic Prosperity', subtitle = 'Comparing divergent political and economic paths of the U.S. and Russia/USSR, 1850-2015', caption = 'Chart: Taylor G. White\nData: Polity Project, Maddison Project' ) + theme_minimal() + theme( legend.background = element_rect(fill = 'white'), legend.position = c(0.10, 0.875), axis.text = element_text(size = 12), axis.title = element_text(size = 16), plot.subtitle = element_text(size = 18), legend.text = element_text(size = 11), legend.title = element_text(size = 12), plot.caption = element_text(size = 13, face = 'italic', hjust = 0), title = element_text(size = 26) ) ggsave('russia+ussr versus US.png', height = 9, width = 12, units = 'in', dpi = 600) ##### UK versus Australia ##### filter(historical_gdp_stats_growth %>% filter(between(year, 1850, 2015)), country %in% c('Australia', 'United Kingdom'), !is.na(rgdpnapc)) %>% mutate(label = ifelse(year == max(year), country, NA)) %>% ggplot(aes(year, rgdpnapc)) + theme_bw() + geom_line(aes(colour = country)) + geom_point(aes(size = polity2, shape = polity_desc, colour = country)) + scale_size(range = c(0, 2.55)) + # scale_alpha(guide = F) + # scale_colour_manual(name = "Type of Government", values = c('Autocracy' = '#e61938', 'Anocracy (mixed)' = 'gray', 'Democracy' = '#0045a1')) + # scale_colour_gradient2(name = 'Polity V Score\n>0 is Democratic',low = '#e61938', high = '#0045a1', mid = 'gray', midpoint = 0) + # scale_colour_hue(name = 'Democratic', labels = c('TRUE' = 'Yes', 'FALSE' = 'No')) + geom_label_repel(aes(label = label), nudge_x = 1, na.rm = T, nudge_y = 3) + scale_y_continuous(labels = dollar) + scale_x_continuous(breaks = seq(1850, 2015, by = 10)) + labs( y = 'Real GDP Per Capita (2011 USD)\n', x = '', title = 'Political Power and Stability vs. Economic Prosperity', subtitle = 'Comparing divergent political and economic paths of the U.S. and Russia/USSR, 1850-2015', caption = 'Chart: Taylor G. White\nData: Polity Project, Maddison Project' ) + theme_minimal() + theme( legend.background = element_rect(fill = 'white'), legend.position = c(0.10, 0.875), axis.text = element_text(size = 12), axis.title = element_text(size = 16), plot.subtitle = element_text(size = 18), legend.text = element_text(size = 11), legend.title = element_text(size = 12), plot.caption = element_text(size = 13, face = 'italic', hjust = 0), title = element_text(size = 26) ) ggsave('russia+ussr versus US.png', height = 9, width = 12, units = 'in', dpi = 600) ##### median income by polity type ##### filter(historical_gdp_stats_growth, is.na(polity_desc)) %>% select(country, year, polity2, interim, prior, regtrans) %>% filter(year > 1800) %>%View() growth_by_polity_type = group_by(historical_gdp_stats_growth, year, polity_desc) %>% filter(year >= 1800) %>% summarize( countries_with_coups = n_distinct(country[n_coups > 0]), median_rgdpnapc = median(rgdpnapc, na.rm = T), median_growth = median(real_gdp_cap_growth, na.rm = T), obs = length(!is.na(rgdpnapc)) ) ggplot(growth_by_polity_type, aes(year, median_rgdpnapc )) + geom_line(aes(colour = polity_desc)) + geom_point(aes(colour = polity_desc, alpha = obs, size = obs)) top_incomes_by_year = group_by(year) %>% top_n(20, rgdpnapc) top_n(historical_gdp_stats_growth, 10, rgdpnapc) historical_gdp_stats_growth %>% filter(year >= 1800, pop >= 1000) %>% ggplot(aes(factor(cyl), mpg)) + geom_boxplot() + # Here comes the gganimate code transition_states( gear, transition_length = 2, state_length = 1 ) + enter_fade() + exit_shrink() + ease_aes('sine-in-out') ##### global trends, democracy and growth ##### annual_gdp_cap_leaders = group_by(historical_gdp_stats_growth, year) %>% summarize( polity_median = median(polity2, na.rm = T), polity_90th_percentile = quantile(polity2, probs = 0.9, na.rm = T), annual_income_25th_percentile = quantile(cgdppc, probs = 0.25, na.rm = T), annual_income_median = quantile(cgdppc, probs = 0.5, na.rm = T), annual_income_75th_percentile = quantile(cgdppc, probs = 0.75, na.rm = T), annual_income_90th_percentile = quantile(cgdppc, probs = 0.9, na.rm = T) ) %>% mutate( top_median_ratio = annual_income_90th_percentile / annual_income_median ) ggplot(annual_gdp_cap_leaders, aes(polity_median, log(annual_income_median))) + geom_point() + stat_smooth(method = 'lm') ggplot(annual_gdp_cap_leaders, aes(polity_90th_percentile, log(annual_income_90th_percentile))) + geom_point() + stat_smooth(method = 'lm') ggplot(annual_gdp_cap_leaders, aes(year, top_median_ratio)) + geom_bar(stat = 'identity') annual_gdp_cap_leaders %>% pivot_longer(cols = c('annual_income_90th_percentile', 'annual_income_median', 'annual_income_75th_percentile', 'annual_income_25th_percentile')) %>% ggplot(aes(year, colour = name)) + geom_line( aes(y = value) ) + scale_colour_brewer(palette = 'Set1', labels = c('annual_income_90th_percentile' = '90%', 'annual_income_median' = '50%', 'annual_income_75th_percentile' = '75%', 'annual_income_25th_percentile' = '25%') ) ggplot(annual_gdp_cap_leaders, aes(year)) + geom_line( aes(y = polity_90th_percentile) ) + geom_line( aes(y = polity_median), colour = 'blue' ) + geom_vline(aes(xintercept = 1989)) group_by(historical_gdp_stats_growth %>% filter(year >= 1800), country) %>% summarize( obs = n(), mean_real_gdp_cap_growth = mean(real_gdp_cap_growth, na.rm = T), sd_read_gdp_growth = sd(real_gdp_cap_growth, na.rm = T), n_recessions = sum(real_gdp_cap_growth < 0, na.rm = T) ) %>% View() table(historical_gdp_stats$country) us = filter(historical_gdp_stats_growth, country %in% c('Argentina', 'United States', 'United Kingdom', 'Botswana', 'South Africa', 'Japan', 'Germany', 'West Germany')) ggplot(us %>% filter(between(year, 1800, 2016)), aes(year, rgdpnapc)) + facet_wrap(~country) + geom_point(aes(colour = polity2 > 0)) table(historical_gdp_stats_growth$country) ##### coups, civil wars, and population/income impacts ##### ##### how likely are coups to cluster in time? ##### # for each year with a coup, find how many coups preceded and followed? e = exp(1) ggplot(stats_by_country, aes(income_1850, income_2015, size = pop_2015)) + geom_point(aes(colour = factor(coup_war_score))) + scale_y_continuous(labels = dollar) + scale_x_continuous(labels = dollar) + stat_smooth( se = F, span = 1) # scale_y_continuous(trans = log_trans(), # # labels = dollar, # breaks = trans_breaks("log", function(x) e^x), # labels = trans_format("log", math_format(e^.x))) + # scale_x_continuous(trans = log_trans(), # # labels = dollar, # breaks = trans_breaks("log", function(x) e^x), # labels = trans_format("log", math_format(e))) ggplot(stats_by_country, aes(pop_avg_growth, period_avg_growth )) + geom_point() names(stats_by_country) ggplot(stats_by_country, aes(income_1850, income_2015)) + geom_point(aes(fill = percent_democracy_years ), pch = 21, size = 5) + scale_fill_viridis_c() ggplot(stats_by_country, aes(income_1850, income_2015)) + geom_point(aes(fill = avg_polity2 ), pch = 21, size = 5) + geom_text_repel(aes(label = country)) + # scale_fill_gradient2(low = 'red', mid = 'gray', high= 'blue', midpoint = 5) + scale_fill_viridis_c(option = 'A') + scale_colour_viridis_c() filter(stats_by_country, !is.na(income_1900) & !is.na(income_2015)) %>% ungroup() %>% summarize( the_cor = cor(income_1900, income_2015), log_cor = cor(log(income_1900), log(income_2015)) ) cor(stats_by_country$income_1900, stats_by_country$income_2015) names(historical_gdp_stats_growth) names(stats_by_country) filter(stats_by_country, coup_war_score > 0) simple_growth_model = lm(real_gdp_cap_growth ~ year + autocratic_shift + polity_desc + lagged_real_gdp_cap_growth, data = historical_gdp_stats_growth) summary(simple_growth_model) ggplot(historical_gdp_stats_growth, aes(lagged_real_gdp_cap_growth, real_gdp_cap_growth, colour = year > 1965)) + geom_point(alpha = 0.5) + stat_smooth(se = F, method = 'lm') + facet_wrap(~year > 1965) ggplot(historical_gdp_stats_growth, aes(lagged_real_gdp_cap_growth, real_gdp_cap_growth)) + geom_point(alpha = 0.5, aes(colour = polity2)) + scale_colour_gradient2(low = 'red', mid = 'gray', high= 'blue', midpoint = 5) + stat_smooth(se = F, method = 'lm') + facet_wrap(~year > 1975) historical_gdp_stats_growth$polity2 ##### map coups, civil wars ##### polity_income_vars = expand.grid( var = c('income', 'polity', 'pop'), year = c(seq(1960, 2010, by = 10), 2015) ) %>% arrange(var, year) %>% mutate( var_combo = paste(var, year, sep = '_') ) stats_by_country$pop_1960 stats_by_country_long = pivot_longer( stats_by_country %>% as.data.frame(), cols = polity_income_vars$var_combo, names_to = 'variable', values_to = 'value' ) stats_by_country_map = left_join(world_map, stats_by_country, by = c('name' = 'country')) ggplot(stats_by_country_map) + geom_sf(aes(fill = n_civil_war_years > 0)) + geom_sf_label(aes(label = ifelse(is.na(n_civil_war_years), name, NA)), na.rm = T) + scale_fill_viridis_d() names(stats_by_country_map) ggplot(stats_by_country_map) + geom_sf(aes(fill = n_coup_attempts + n_successful_coups + n_civil_war_years > 0)) + # geom_sf_label(aes(label = ifelse(is.na(n_civil_war_years), name, NA)), na.rm = T) + scale_fill_viridis_d() ggplot(stats_by_country_map) + geom_sf(aes(fill = income_2015 %>% log())) + # geom_sf_label(aes(label = ifelse(is.na(n_civil_war_years), name, NA)), na.rm = T) + scale_fill_viridis_c() stats_by_country_map_long = left_join(world_map, stats_by_country_long, by = c('name' = 'country')) filter(stats_by_country_map_long %>% filter(str_detect(variable, 'income')), continent == 'Africa') %>% ggplot() + facet_wrap(~str_replace(variable, '_', " ") %>% str_to_title()) + geom_sf(aes(fill = value)) + scale_fill_viridis_c() filter(stats_by_country_map_long %>% filter(str_detect(variable, 'polity')), continent == 'Africa') %>% ggplot() + facet_wrap(~str_replace(variable, '_', " ") %>% str_to_title()) + geom_sf(aes(fill = value)) + scale_fill_gradient2(low = 'red', high = 'blue', mid = 'gray', midpoint = 0) maps_by_continent = lapply(unique(stats_by_country_map$continent), function(the_continent){ # the_continent = 'North America' cont_sub = filter(stats_by_country_map, continent == the_continent) the_plot = ggplot(cont_sub) + geom_sf(aes(fill = avg_polity2)) + scale_fill_viridis_c() + geom_sf_label(aes(label = ifelse(is.na(avg_polity2), name, NA)), na.rm = T) return(the_plot) }) cowplot::plot_grid(plotlist = maps_by_continent) View(polity_v_fin) filter(polity_v_fin, country == 'Kazakhstan') %>% pull(polity2) View(stats_by_country)
Formal statement is: lemma interior_injective_linear_image: fixes f :: "'a::euclidean_space \<Rightarrow> 'a::euclidean_space" assumes "linear f" "inj f" shows "interior(f ` S) = f ` (interior S)" Informal statement is: If $f$ is a linear injection, then the interior of the image of a set $S$ is the image of the interior of $S$.
{-# OPTIONS --without-K --safe #-} open import Categories.Category open import Categories.Category.Monoidal -- the definition used here is not very similar to what one usually sees in nLab or -- any textbook. the difference is that usually closed monoidal category is defined -- through a right adjoint of -⊗X, which is [X,-]. then there is an induced bifunctor -- [-,-]. -- -- but in proof relevant context, the induced bifunctor [-,-] does not have to be -- exactly the intended bifunctor! in fact, one can probably only show that the -- intended bifunctor is only naturally isomorphic to the induced one, which is -- significantly weaker. -- -- the approach taken here as an alternative is to BEGIN with a bifunctor -- already. however, is it required to have mates between any given two adjoints. this -- definition can be shown equivalent to the previous one but just works better. module Categories.Category.Monoidal.Closed {o ℓ e} {C : Category o ℓ e} (M : Monoidal C) where private module C = Category C open Category C variable X Y A B : Obj open import Level open import Data.Product using (_,_) open import Categories.Adjoint open import Categories.Adjoint.Mate open import Categories.Functor renaming (id to idF) open import Categories.Functor.Bifunctor open import Categories.Functor.Hom open import Categories.Category.Instance.Setoids open import Categories.NaturalTransformation hiding (id) open import Categories.NaturalTransformation.Properties open import Categories.NaturalTransformation.NaturalIsomorphism as NI record Closed : Set (levelOfTerm M) where open Monoidal M public field [-,-] : Bifunctor C.op C C adjoint : (-⊗ X) ⊣ appˡ [-,-] X mate : (f : X ⇒ Y) → Mate (adjoint {X}) (adjoint {Y}) (appʳ-nat ⊗ f) (appˡ-nat [-,-] f) module [-,-] = Functor [-,-] module adjoint {X} = Adjoint (adjoint {X}) module mate {X Y} f = Mate (mate {X} {Y} f) [_,-] : Obj → Functor C C [_,-] = appˡ [-,-] [-,_] : Obj → Functor C.op C [-,_] = appʳ [-,-] [_,_]₀ : Obj → Obj → Obj [ X , Y ]₀ = [-,-].F₀ (X , Y) [_,_]₁ : A ⇒ B → X ⇒ Y → [ B , X ]₀ ⇒ [ A , Y ]₀ [ f , g ]₁ = [-,-].F₁ (f , g) Hom[-⊗_,-] : ∀ X → Bifunctor C.op C (Setoids ℓ e) Hom[-⊗ X ,-] = adjoint.Hom[L-,-] {X} Hom[-,[_,-]] : ∀ X → Bifunctor C.op C (Setoids ℓ e) Hom[-,[ X ,-]] = adjoint.Hom[-,R-] {X} Hom-NI : ∀ {X : Obj} → NaturalIsomorphism Hom[-⊗ X ,-] Hom[-,[ X ,-]] Hom-NI = Hom-NI′ adjoint
{-# OPTIONS --cubical --safe --no-import-sorts #-} module Cubical.Data.Fin.Recursive where open import Cubical.Data.Fin.Recursive.Base public open import Cubical.Data.Fin.Recursive.Properties public
from selenium import webdriver from selenium.common.exceptions import NoSuchElementException, InvalidArgumentException from PyPDF2 import PdfFileReader from pdf2image import convert_from_path import numpy as np from PIL import Image import sys import base64
lemma filtermap_nhds_shift: "filtermap (\<lambda>x. x - d) (nhds a) = nhds (a - d)" for a d :: "'a::real_normed_vector"
Require Import Arith Omega. Require Import List. Require Import Sorted. Definition P {A} (u v : list A) := exists x, In x u /\ In x v. Definition Spec (f : list nat -> list nat -> bool) := forall u v, StronglySorted (lt) u -> StronglySorted (lt) v -> if f u v then P u v else ~ P u v. Definition Spec' (f : list nat * list nat -> bool) := forall uv, StronglySorted (lt) (fst uv) -> StronglySorted (lt) (snd uv) -> if f uv then P (fst uv) (snd uv) else ~ P (fst uv) (snd uv). Require Import Recdef. Definition totallen (uv : list nat * list nat) := length (fst uv) + length (snd uv). Function intp (uv : list nat * list nat) {measure totallen} : bool := match fst uv with | nil => false | x :: xs => match snd uv with | nil => false | y :: ys => match lt_eq_lt_dec x y with | inleft (left _) (* x < y *) => intp (xs, y :: ys) | inleft (right _) (* x = y *) => true | inright _ (* x > y *) => intp (x :: xs, ys) end end end. unfold totallen; intros; destruct uv; simpl in *; subst; simpl. omega. unfold totallen; intros; destruct uv; simpl in *; subst; simpl. omega. Defined. Check (intp_ind (fun uv b => if b then P (fst uv) (snd uv) else ~ P (fst uv) (snd uv))). Lemma not_P_nil {A} (v : list A) : ~ P nil v. Proof. unfold P; intros [x [l r]]. inversion l. Qed. Lemma not_P_nil2 {A} (v : list A) : ~ P v nil. Proof. unfold P; intros [x [l r]]. inversion r. Qed. Lemma P_head {A} (v : A) (us vs : list A) : P (v :: us) (v :: vs). Proof. exists v; split; constructor; reflexivity. Qed. Lemma In_lemma (x a0 : nat) (v : list nat) : StronglySorted lt (a0 :: v) -> x < a0 -> ~In x (a0 :: v). Proof. intros S l I. inversion I; subst. omega. destruct v. inversion H. inversion S; subst. destruct (Forall_forall (lt a0) (n :: v)) as [Lemma _]. pose (Lemma H3 x H). omega. Qed. Theorem intp_Spec : Spec' intp. Proof. unfold Spec'. intros uv. apply (intp_ind (fun uv b => StronglySorted lt (fst uv) -> StronglySorted lt (snd uv) -> if b then P (fst uv) (snd uv) else ~ P (fst uv) (snd uv))); simpl; intros; repeat match goal with | [ uv : (?a * ?b)%type |- _ ] => destruct uv end; simpl in *; subst. apply not_P_nil. apply not_P_nil2. unfold P in *. destruct (intp (xs, y :: ys)). Focus 1. assert (StronglySorted lt xs) as H2. inversion H0; assumption. destruct (H H2 H1) as [x' [L R]]. exists x'; split. right; assumption. assumption. Focus 1. assert (StronglySorted lt xs) as H2. inversion H0; assumption. intro H3; apply (H H2 H1); clear H. destruct H3 as [x' [L R]]. inversion L; subst. pose (In_lemma _ _ _ H1 _x R) as f. elim f. exists x'; split; assumption. unfold P in *. exists y; split; constructor; reflexivity. unfold P in *. destruct (intp (x :: xs, ys)). Focus 1. assert (StronglySorted lt ys) as H2. inversion H1; assumption. destruct (H H0 H2) as [x' [L R]]. exists x'; split. assumption. right; assumption. Focus 1. assert (StronglySorted lt ys) as H2. inversion H1; assumption. intro H3; apply (H H0 H2); clear H. destruct H3 as [x' [L R]]. inversion R; subst. pose (In_lemma _ _ _ H0 _x L) as f. elim f. exists x'; split; assumption. Qed. Extraction Language Ocaml. Extraction intp. (**** (** val intp : (nat list, nat list) prod -> bool **) let rec intp uv = match fst uv with | Nil -> False | Cons (x, xs) -> (match snd uv with | Nil -> False | Cons (y, ys) -> (match lt_eq_lt_dec x y with | Inleft s -> (match s with | Left -> intp (Pair (xs, (Cons (y, ys)))) | Right -> True) | Inright -> intp (Pair ((Cons (x, xs)), ys)))) ***)
[STATEMENT] lemma term_subst_eq: assumes "\<And>x. x \<in> vars_term t \<Longrightarrow> \<sigma> x = \<tau> x" shows "t \<cdot> \<sigma> = t \<cdot> \<tau>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. t \<cdot> \<sigma> = t \<cdot> \<tau> [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: ?x \<in> vars_term t \<Longrightarrow> \<sigma> ?x = \<tau> ?x goal (1 subgoal): 1. t \<cdot> \<sigma> = t \<cdot> \<tau> [PROOF STEP] by (induct t) (auto)
[STATEMENT] lemma degree_monom0'[simp]: "degree (monom 0 b) = 0" [PROOF STATE] proof (prove) goal (1 subgoal): 1. degree (monom (0::'a) b) = 0 [PROOF STEP] by auto
(* !!! WARNING: AUTO GENERATED. DO NOT MODIFY !!! *) Require Import Coq.Logic.FunctionalExtensionality. Require Import Coq.Program.Equality. Require Export Metalib.Metatheory. Require Export Metalib.LibLNgen. Require Export Syntax_ott. (** NOTE: Auxiliary theorems are hidden in generated documentation. In general, there is a [_rec] version of every lemma involving [open] and [close]. *) (* *********************************************************************** *) (** * Induction principles for nonterminals *) Scheme ty_ind' := Induction for ty Sort Prop. Definition ty_mutind := fun H1 H2 H3 H4 H5 H6 H7 H8 => ty_ind' H1 H2 H3 H4 H5 H6 H7 H8. Scheme ty_rec' := Induction for ty Sort Set. Definition ty_mutrec := fun H1 H2 H3 H4 H5 H6 H7 H8 => ty_rec' H1 H2 H3 H4 H5 H6 H7 H8. Scheme co_ind' := Induction for co Sort Prop. Definition co_mutind := fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 => co_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14. Scheme co_rec' := Induction for co Sort Set. Definition co_mutrec := fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 => co_rec' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14. Scheme exp_ind' := Induction for exp Sort Prop. Definition exp_mutind := fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 => exp_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11. Scheme exp_rec' := Induction for exp Sort Set. Definition exp_mutrec := fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 => exp_rec' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11. (* *********************************************************************** *) (** * Close *) Fixpoint close_ty_wrt_ty_rec (n1 : nat) (X1 : typvar) (T1 : ty) {struct T1} : ty := match T1 with | ty_nat => ty_nat | ty_unit => ty_unit | ty_var_f X2 => if (X1 == X2) then (ty_var_b n1) else (ty_var_f X2) | ty_var_b n2 => if (lt_ge_dec n2 n1) then (ty_var_b n2) else (ty_var_b (S n2)) | ty_arrow T2 T3 => ty_arrow (close_ty_wrt_ty_rec n1 X1 T2) (close_ty_wrt_ty_rec n1 X1 T3) | ty_prod T2 T3 => ty_prod (close_ty_wrt_ty_rec n1 X1 T2) (close_ty_wrt_ty_rec n1 X1 T3) | ty_all T2 => ty_all (close_ty_wrt_ty_rec (S n1) X1 T2) end. Definition close_ty_wrt_ty X1 T1 := close_ty_wrt_ty_rec 0 X1 T1. Fixpoint close_exp_wrt_ty_rec (n1 : nat) (X1 : typvar) (e1 : exp) {struct e1} : exp := match e1 with | exp_var_f x1 => exp_var_f x1 | exp_var_b n2 => exp_var_b n2 | exp_unit => exp_unit | exp_lit i1 => exp_lit i1 | exp_abs e2 => exp_abs (close_exp_wrt_ty_rec n1 X1 e2) | exp_app e2 e3 => exp_app (close_exp_wrt_ty_rec n1 X1 e2) (close_exp_wrt_ty_rec n1 X1 e3) | exp_pair e2 e3 => exp_pair (close_exp_wrt_ty_rec n1 X1 e2) (close_exp_wrt_ty_rec n1 X1 e3) | exp_capp c1 e2 => exp_capp c1 (close_exp_wrt_ty_rec n1 X1 e2) | exp_tabs e2 => exp_tabs (close_exp_wrt_ty_rec (S n1) X1 e2) | exp_tapp e2 T1 => exp_tapp (close_exp_wrt_ty_rec n1 X1 e2) (close_ty_wrt_ty_rec n1 X1 T1) end. Fixpoint close_exp_wrt_exp_rec (n1 : nat) (x1 : expvar) (e1 : exp) {struct e1} : exp := match e1 with | exp_var_f x2 => if (x1 == x2) then (exp_var_b n1) else (exp_var_f x2) | exp_var_b n2 => if (lt_ge_dec n2 n1) then (exp_var_b n2) else (exp_var_b (S n2)) | exp_unit => exp_unit | exp_lit i1 => exp_lit i1 | exp_abs e2 => exp_abs (close_exp_wrt_exp_rec (S n1) x1 e2) | exp_app e2 e3 => exp_app (close_exp_wrt_exp_rec n1 x1 e2) (close_exp_wrt_exp_rec n1 x1 e3) | exp_pair e2 e3 => exp_pair (close_exp_wrt_exp_rec n1 x1 e2) (close_exp_wrt_exp_rec n1 x1 e3) | exp_capp c1 e2 => exp_capp c1 (close_exp_wrt_exp_rec n1 x1 e2) | exp_tabs e2 => exp_tabs (close_exp_wrt_exp_rec n1 x1 e2) | exp_tapp e2 T1 => exp_tapp (close_exp_wrt_exp_rec n1 x1 e2) T1 end. Definition close_exp_wrt_ty X1 e1 := close_exp_wrt_ty_rec 0 X1 e1. Definition close_exp_wrt_exp x1 e1 := close_exp_wrt_exp_rec 0 x1 e1. (* *********************************************************************** *) (** * Size *) Fixpoint size_ty (T1 : ty) {struct T1} : nat := match T1 with | ty_nat => 1 | ty_unit => 1 | ty_var_f X1 => 1 | ty_var_b n1 => 1 | ty_arrow T2 T3 => 1 + (size_ty T2) + (size_ty T3) | ty_prod T2 T3 => 1 + (size_ty T2) + (size_ty T3) | ty_all T2 => 1 + (size_ty T2) end. Fixpoint size_co (c1 : co) {struct c1} : nat := match c1 with | co_id => 1 | co_trans c2 c3 => 1 + (size_co c2) + (size_co c3) | co_top => 1 | co_bot => 1 | co_arr c2 c3 => 1 + (size_co c2) + (size_co c3) | co_pair c2 c3 => 1 + (size_co c2) + (size_co c3) | co_proj1 => 1 | co_proj2 => 1 | co_forall c2 => 1 + (size_co c2) | co_distArr => 1 | co_topArr => 1 | co_topAll => 1 | co_distPoly => 1 end. Fixpoint size_exp (e1 : exp) {struct e1} : nat := match e1 with | exp_var_f x1 => 1 | exp_var_b n1 => 1 | exp_unit => 1 | exp_lit i1 => 1 | exp_abs e2 => 1 + (size_exp e2) | exp_app e2 e3 => 1 + (size_exp e2) + (size_exp e3) | exp_pair e2 e3 => 1 + (size_exp e2) + (size_exp e3) | exp_capp c1 e2 => 1 + (size_co c1) + (size_exp e2) | exp_tabs e2 => 1 + (size_exp e2) | exp_tapp e2 T1 => 1 + (size_exp e2) + (size_ty T1) end. (* *********************************************************************** *) (** * Degree *) (** These define only an upper bound, not a strict upper bound. *) Inductive degree_ty_wrt_ty : nat -> ty -> Prop := | degree_wrt_ty_ty_nat : forall n1, degree_ty_wrt_ty n1 (ty_nat) | degree_wrt_ty_ty_unit : forall n1, degree_ty_wrt_ty n1 (ty_unit) | degree_wrt_ty_ty_var_f : forall n1 X1, degree_ty_wrt_ty n1 (ty_var_f X1) | degree_wrt_ty_ty_var_b : forall n1 n2, lt n2 n1 -> degree_ty_wrt_ty n1 (ty_var_b n2) | degree_wrt_ty_ty_arrow : forall n1 T1 T2, degree_ty_wrt_ty n1 T1 -> degree_ty_wrt_ty n1 T2 -> degree_ty_wrt_ty n1 (ty_arrow T1 T2) | degree_wrt_ty_ty_prod : forall n1 T1 T2, degree_ty_wrt_ty n1 T1 -> degree_ty_wrt_ty n1 T2 -> degree_ty_wrt_ty n1 (ty_prod T1 T2) | degree_wrt_ty_ty_all : forall n1 T1, degree_ty_wrt_ty (S n1) T1 -> degree_ty_wrt_ty n1 (ty_all T1). Scheme degree_ty_wrt_ty_ind' := Induction for degree_ty_wrt_ty Sort Prop. Definition degree_ty_wrt_ty_mutind := fun H1 H2 H3 H4 H5 H6 H7 H8 => degree_ty_wrt_ty_ind' H1 H2 H3 H4 H5 H6 H7 H8. Hint Constructors degree_ty_wrt_ty : core lngen. Inductive degree_exp_wrt_ty : nat -> exp -> Prop := | degree_wrt_ty_exp_var_f : forall n1 x1, degree_exp_wrt_ty n1 (exp_var_f x1) | degree_wrt_ty_exp_var_b : forall n1 n2, degree_exp_wrt_ty n1 (exp_var_b n2) | degree_wrt_ty_exp_unit : forall n1, degree_exp_wrt_ty n1 (exp_unit) | degree_wrt_ty_exp_lit : forall n1 i1, degree_exp_wrt_ty n1 (exp_lit i1) | degree_wrt_ty_exp_abs : forall n1 e1, degree_exp_wrt_ty n1 e1 -> degree_exp_wrt_ty n1 (exp_abs e1) | degree_wrt_ty_exp_app : forall n1 e1 e2, degree_exp_wrt_ty n1 e1 -> degree_exp_wrt_ty n1 e2 -> degree_exp_wrt_ty n1 (exp_app e1 e2) | degree_wrt_ty_exp_pair : forall n1 e1 e2, degree_exp_wrt_ty n1 e1 -> degree_exp_wrt_ty n1 e2 -> degree_exp_wrt_ty n1 (exp_pair e1 e2) | degree_wrt_ty_exp_capp : forall n1 c1 e1, degree_exp_wrt_ty n1 e1 -> degree_exp_wrt_ty n1 (exp_capp c1 e1) | degree_wrt_ty_exp_tabs : forall n1 e1, degree_exp_wrt_ty (S n1) e1 -> degree_exp_wrt_ty n1 (exp_tabs e1) | degree_wrt_ty_exp_tapp : forall n1 e1 T1, degree_exp_wrt_ty n1 e1 -> degree_ty_wrt_ty n1 T1 -> degree_exp_wrt_ty n1 (exp_tapp e1 T1). Inductive degree_exp_wrt_exp : nat -> exp -> Prop := | degree_wrt_exp_exp_var_f : forall n1 x1, degree_exp_wrt_exp n1 (exp_var_f x1) | degree_wrt_exp_exp_var_b : forall n1 n2, lt n2 n1 -> degree_exp_wrt_exp n1 (exp_var_b n2) | degree_wrt_exp_exp_unit : forall n1, degree_exp_wrt_exp n1 (exp_unit) | degree_wrt_exp_exp_lit : forall n1 i1, degree_exp_wrt_exp n1 (exp_lit i1) | degree_wrt_exp_exp_abs : forall n1 e1, degree_exp_wrt_exp (S n1) e1 -> degree_exp_wrt_exp n1 (exp_abs e1) | degree_wrt_exp_exp_app : forall n1 e1 e2, degree_exp_wrt_exp n1 e1 -> degree_exp_wrt_exp n1 e2 -> degree_exp_wrt_exp n1 (exp_app e1 e2) | degree_wrt_exp_exp_pair : forall n1 e1 e2, degree_exp_wrt_exp n1 e1 -> degree_exp_wrt_exp n1 e2 -> degree_exp_wrt_exp n1 (exp_pair e1 e2) | degree_wrt_exp_exp_capp : forall n1 c1 e1, degree_exp_wrt_exp n1 e1 -> degree_exp_wrt_exp n1 (exp_capp c1 e1) | degree_wrt_exp_exp_tabs : forall n1 e1, degree_exp_wrt_exp n1 e1 -> degree_exp_wrt_exp n1 (exp_tabs e1) | degree_wrt_exp_exp_tapp : forall n1 e1 T1, degree_exp_wrt_exp n1 e1 -> degree_exp_wrt_exp n1 (exp_tapp e1 T1). Scheme degree_exp_wrt_ty_ind' := Induction for degree_exp_wrt_ty Sort Prop. Definition degree_exp_wrt_ty_mutind := fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 => degree_exp_wrt_ty_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11. Scheme degree_exp_wrt_exp_ind' := Induction for degree_exp_wrt_exp Sort Prop. Definition degree_exp_wrt_exp_mutind := fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 => degree_exp_wrt_exp_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11. Hint Constructors degree_exp_wrt_ty : core lngen. Hint Constructors degree_exp_wrt_exp : core lngen. (* *********************************************************************** *) (** * Local closure (version in [Set], induction principles) *) Inductive lc_set_ty : ty -> Set := | lc_set_ty_nat : lc_set_ty (ty_nat) | lc_set_ty_unit : lc_set_ty (ty_unit) | lc_set_ty_var_f : forall X1, lc_set_ty (ty_var_f X1) | lc_set_ty_arrow : forall T1 T2, lc_set_ty T1 -> lc_set_ty T2 -> lc_set_ty (ty_arrow T1 T2) | lc_set_ty_prod : forall T1 T2, lc_set_ty T1 -> lc_set_ty T2 -> lc_set_ty (ty_prod T1 T2) | lc_set_ty_all : forall T1, (forall X1 : typvar, lc_set_ty (open_ty_wrt_ty T1 (ty_var_f X1))) -> lc_set_ty (ty_all T1). Scheme lc_ty_ind' := Induction for lc_ty Sort Prop. Definition lc_ty_mutind := fun H1 H2 H3 H4 H5 H6 H7 => lc_ty_ind' H1 H2 H3 H4 H5 H6 H7. Scheme lc_set_ty_ind' := Induction for lc_set_ty Sort Prop. Definition lc_set_ty_mutind := fun H1 H2 H3 H4 H5 H6 H7 => lc_set_ty_ind' H1 H2 H3 H4 H5 H6 H7. Scheme lc_set_ty_rec' := Induction for lc_set_ty Sort Set. Definition lc_set_ty_mutrec := fun H1 H2 H3 H4 H5 H6 H7 => lc_set_ty_rec' H1 H2 H3 H4 H5 H6 H7. Hint Constructors lc_ty : core lngen. Hint Constructors lc_set_ty : core lngen. Inductive lc_set_exp : exp -> Set := | lc_set_exp_var_f : forall x1, lc_set_exp (exp_var_f x1) | lc_set_exp_unit : lc_set_exp (exp_unit) | lc_set_exp_lit : forall i1, lc_set_exp (exp_lit i1) | lc_set_exp_abs : forall e1, (forall x1 : expvar, lc_set_exp (open_exp_wrt_exp e1 (exp_var_f x1))) -> lc_set_exp (exp_abs e1) | lc_set_exp_app : forall e1 e2, lc_set_exp e1 -> lc_set_exp e2 -> lc_set_exp (exp_app e1 e2) | lc_set_exp_pair : forall e1 e2, lc_set_exp e1 -> lc_set_exp e2 -> lc_set_exp (exp_pair e1 e2) | lc_set_exp_capp : forall c1 e1, lc_set_exp e1 -> lc_set_exp (exp_capp c1 e1) | lc_set_exp_tabs : forall e1, (forall X1 : typvar, lc_set_exp (open_exp_wrt_ty e1 (ty_var_f X1))) -> lc_set_exp (exp_tabs e1) | lc_set_exp_tapp : forall e1 T1, lc_set_exp e1 -> lc_set_ty T1 -> lc_set_exp (exp_tapp e1 T1). Scheme lc_exp_ind' := Induction for lc_exp Sort Prop. Definition lc_exp_mutind := fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 => lc_exp_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10. Scheme lc_set_exp_ind' := Induction for lc_set_exp Sort Prop. Definition lc_set_exp_mutind := fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 => lc_set_exp_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10. Scheme lc_set_exp_rec' := Induction for lc_set_exp Sort Set. Definition lc_set_exp_mutrec := fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 => lc_set_exp_rec' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10. Hint Constructors lc_exp : core lngen. Hint Constructors lc_set_exp : core lngen. (* *********************************************************************** *) (** * Body *) Definition body_ty_wrt_ty T1 := forall X1, lc_ty (open_ty_wrt_ty T1 (ty_var_f X1)). Hint Unfold body_ty_wrt_ty. Definition body_exp_wrt_ty e1 := forall X1, lc_exp (open_exp_wrt_ty e1 (ty_var_f X1)). Definition body_exp_wrt_exp e1 := forall x1, lc_exp (open_exp_wrt_exp e1 (exp_var_f x1)). Hint Unfold body_exp_wrt_ty. Hint Unfold body_exp_wrt_exp. (* *********************************************************************** *) (** * Tactic support *) (** Additional hint declarations. *) Hint Resolve @plus_le_compat : lngen. (** Redefine some tactics. *) Ltac default_case_split ::= first [ progress destruct_notin | progress destruct_sum | progress safe_f_equal ]. (* *********************************************************************** *) (** * Theorems about [size] *) Ltac default_auto ::= auto with arith lngen; tauto. Ltac default_autorewrite ::= fail. (* begin hide *) Lemma size_ty_min_mutual : (forall T1, 1 <= size_ty T1). Proof. apply_mutual_ind ty_mutind; default_simp. Qed. (* end hide *) Lemma size_ty_min : forall T1, 1 <= size_ty T1. Proof. pose proof size_ty_min_mutual as H; intuition eauto. Qed. Hint Resolve size_ty_min : lngen. (* begin hide *) Lemma size_co_min_mutual : (forall c1, 1 <= size_co c1). Proof. apply_mutual_ind co_mutind; default_simp. Qed. (* end hide *) Lemma size_co_min : forall c1, 1 <= size_co c1. Proof. pose proof size_co_min_mutual as H; intuition eauto. Qed. Hint Resolve size_co_min : lngen. (* begin hide *) Lemma size_exp_min_mutual : (forall e1, 1 <= size_exp e1). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma size_exp_min : forall e1, 1 <= size_exp e1. Proof. pose proof size_exp_min_mutual as H; intuition eauto. Qed. Hint Resolve size_exp_min : lngen. (* begin hide *) Lemma size_ty_close_ty_wrt_ty_rec_mutual : (forall T1 X1 n1, size_ty (close_ty_wrt_ty_rec n1 X1 T1) = size_ty T1). Proof. apply_mutual_ind ty_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma size_ty_close_ty_wrt_ty_rec : forall T1 X1 n1, size_ty (close_ty_wrt_ty_rec n1 X1 T1) = size_ty T1. Proof. pose proof size_ty_close_ty_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve size_ty_close_ty_wrt_ty_rec : lngen. Hint Rewrite size_ty_close_ty_wrt_ty_rec using solve [auto] : lngen. (* end hide *) (* begin hide *) Lemma size_exp_close_exp_wrt_ty_rec_mutual : (forall e1 X1 n1, size_exp (close_exp_wrt_ty_rec n1 X1 e1) = size_exp e1). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma size_exp_close_exp_wrt_ty_rec : forall e1 X1 n1, size_exp (close_exp_wrt_ty_rec n1 X1 e1) = size_exp e1. Proof. pose proof size_exp_close_exp_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve size_exp_close_exp_wrt_ty_rec : lngen. Hint Rewrite size_exp_close_exp_wrt_ty_rec using solve [auto] : lngen. (* end hide *) (* begin hide *) Lemma size_exp_close_exp_wrt_exp_rec_mutual : (forall e1 x1 n1, size_exp (close_exp_wrt_exp_rec n1 x1 e1) = size_exp e1). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma size_exp_close_exp_wrt_exp_rec : forall e1 x1 n1, size_exp (close_exp_wrt_exp_rec n1 x1 e1) = size_exp e1. Proof. pose proof size_exp_close_exp_wrt_exp_rec_mutual as H; intuition eauto. Qed. Hint Resolve size_exp_close_exp_wrt_exp_rec : lngen. Hint Rewrite size_exp_close_exp_wrt_exp_rec using solve [auto] : lngen. (* end hide *) Lemma size_ty_close_ty_wrt_ty : forall T1 X1, size_ty (close_ty_wrt_ty X1 T1) = size_ty T1. Proof. unfold close_ty_wrt_ty; default_simp. Qed. Hint Resolve size_ty_close_ty_wrt_ty : lngen. Hint Rewrite size_ty_close_ty_wrt_ty using solve [auto] : lngen. Lemma size_exp_close_exp_wrt_ty : forall e1 X1, size_exp (close_exp_wrt_ty X1 e1) = size_exp e1. Proof. unfold close_exp_wrt_ty; default_simp. Qed. Hint Resolve size_exp_close_exp_wrt_ty : lngen. Hint Rewrite size_exp_close_exp_wrt_ty using solve [auto] : lngen. Lemma size_exp_close_exp_wrt_exp : forall e1 x1, size_exp (close_exp_wrt_exp x1 e1) = size_exp e1. Proof. unfold close_exp_wrt_exp; default_simp. Qed. Hint Resolve size_exp_close_exp_wrt_exp : lngen. Hint Rewrite size_exp_close_exp_wrt_exp using solve [auto] : lngen. (* begin hide *) Lemma size_ty_open_ty_wrt_ty_rec_mutual : (forall T1 T2 n1, size_ty T1 <= size_ty (open_ty_wrt_ty_rec n1 T2 T1)). Proof. apply_mutual_ind ty_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma size_ty_open_ty_wrt_ty_rec : forall T1 T2 n1, size_ty T1 <= size_ty (open_ty_wrt_ty_rec n1 T2 T1). Proof. pose proof size_ty_open_ty_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve size_ty_open_ty_wrt_ty_rec : lngen. (* end hide *) (* begin hide *) Lemma size_exp_open_exp_wrt_ty_rec_mutual : (forall e1 T1 n1, size_exp e1 <= size_exp (open_exp_wrt_ty_rec n1 T1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma size_exp_open_exp_wrt_ty_rec : forall e1 T1 n1, size_exp e1 <= size_exp (open_exp_wrt_ty_rec n1 T1 e1). Proof. pose proof size_exp_open_exp_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve size_exp_open_exp_wrt_ty_rec : lngen. (* end hide *) (* begin hide *) Lemma size_exp_open_exp_wrt_exp_rec_mutual : (forall e1 e2 n1, size_exp e1 <= size_exp (open_exp_wrt_exp_rec n1 e2 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma size_exp_open_exp_wrt_exp_rec : forall e1 e2 n1, size_exp e1 <= size_exp (open_exp_wrt_exp_rec n1 e2 e1). Proof. pose proof size_exp_open_exp_wrt_exp_rec_mutual as H; intuition eauto. Qed. Hint Resolve size_exp_open_exp_wrt_exp_rec : lngen. (* end hide *) Lemma size_ty_open_ty_wrt_ty : forall T1 T2, size_ty T1 <= size_ty (open_ty_wrt_ty T1 T2). Proof. unfold open_ty_wrt_ty; default_simp. Qed. Hint Resolve size_ty_open_ty_wrt_ty : lngen. Lemma size_exp_open_exp_wrt_ty : forall e1 T1, size_exp e1 <= size_exp (open_exp_wrt_ty e1 T1). Proof. unfold open_exp_wrt_ty; default_simp. Qed. Hint Resolve size_exp_open_exp_wrt_ty : lngen. Lemma size_exp_open_exp_wrt_exp : forall e1 e2, size_exp e1 <= size_exp (open_exp_wrt_exp e1 e2). Proof. unfold open_exp_wrt_exp; default_simp. Qed. Hint Resolve size_exp_open_exp_wrt_exp : lngen. (* begin hide *) Lemma size_ty_open_ty_wrt_ty_rec_var_mutual : (forall T1 X1 n1, size_ty (open_ty_wrt_ty_rec n1 (ty_var_f X1) T1) = size_ty T1). Proof. apply_mutual_ind ty_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma size_ty_open_ty_wrt_ty_rec_var : forall T1 X1 n1, size_ty (open_ty_wrt_ty_rec n1 (ty_var_f X1) T1) = size_ty T1. Proof. pose proof size_ty_open_ty_wrt_ty_rec_var_mutual as H; intuition eauto. Qed. Hint Resolve size_ty_open_ty_wrt_ty_rec_var : lngen. Hint Rewrite size_ty_open_ty_wrt_ty_rec_var using solve [auto] : lngen. (* end hide *) (* begin hide *) Lemma size_exp_open_exp_wrt_ty_rec_var_mutual : (forall e1 X1 n1, size_exp (open_exp_wrt_ty_rec n1 (ty_var_f X1) e1) = size_exp e1). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma size_exp_open_exp_wrt_ty_rec_var : forall e1 X1 n1, size_exp (open_exp_wrt_ty_rec n1 (ty_var_f X1) e1) = size_exp e1. Proof. pose proof size_exp_open_exp_wrt_ty_rec_var_mutual as H; intuition eauto. Qed. Hint Resolve size_exp_open_exp_wrt_ty_rec_var : lngen. Hint Rewrite size_exp_open_exp_wrt_ty_rec_var using solve [auto] : lngen. (* end hide *) (* begin hide *) Lemma size_exp_open_exp_wrt_exp_rec_var_mutual : (forall e1 x1 n1, size_exp (open_exp_wrt_exp_rec n1 (exp_var_f x1) e1) = size_exp e1). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma size_exp_open_exp_wrt_exp_rec_var : forall e1 x1 n1, size_exp (open_exp_wrt_exp_rec n1 (exp_var_f x1) e1) = size_exp e1. Proof. pose proof size_exp_open_exp_wrt_exp_rec_var_mutual as H; intuition eauto. Qed. Hint Resolve size_exp_open_exp_wrt_exp_rec_var : lngen. Hint Rewrite size_exp_open_exp_wrt_exp_rec_var using solve [auto] : lngen. (* end hide *) Lemma size_ty_open_ty_wrt_ty_var : forall T1 X1, size_ty (open_ty_wrt_ty T1 (ty_var_f X1)) = size_ty T1. Proof. unfold open_ty_wrt_ty; default_simp. Qed. Hint Resolve size_ty_open_ty_wrt_ty_var : lngen. Hint Rewrite size_ty_open_ty_wrt_ty_var using solve [auto] : lngen. Lemma size_exp_open_exp_wrt_ty_var : forall e1 X1, size_exp (open_exp_wrt_ty e1 (ty_var_f X1)) = size_exp e1. Proof. unfold open_exp_wrt_ty; default_simp. Qed. Hint Resolve size_exp_open_exp_wrt_ty_var : lngen. Hint Rewrite size_exp_open_exp_wrt_ty_var using solve [auto] : lngen. Lemma size_exp_open_exp_wrt_exp_var : forall e1 x1, size_exp (open_exp_wrt_exp e1 (exp_var_f x1)) = size_exp e1. Proof. unfold open_exp_wrt_exp; default_simp. Qed. Hint Resolve size_exp_open_exp_wrt_exp_var : lngen. Hint Rewrite size_exp_open_exp_wrt_exp_var using solve [auto] : lngen. (* *********************************************************************** *) (** * Theorems about [degree] *) Ltac default_auto ::= auto with lngen; tauto. Ltac default_autorewrite ::= fail. (* begin hide *) Lemma degree_ty_wrt_ty_S_mutual : (forall n1 T1, degree_ty_wrt_ty n1 T1 -> degree_ty_wrt_ty (S n1) T1). Proof. apply_mutual_ind degree_ty_wrt_ty_mutind; default_simp. Qed. (* end hide *) Lemma degree_ty_wrt_ty_S : forall n1 T1, degree_ty_wrt_ty n1 T1 -> degree_ty_wrt_ty (S n1) T1. Proof. pose proof degree_ty_wrt_ty_S_mutual as H; intuition eauto. Qed. Hint Resolve degree_ty_wrt_ty_S : lngen. (* begin hide *) Lemma degree_exp_wrt_ty_S_mutual : (forall n1 e1, degree_exp_wrt_ty n1 e1 -> degree_exp_wrt_ty (S n1) e1). Proof. apply_mutual_ind degree_exp_wrt_ty_mutind; default_simp. Qed. (* end hide *) Lemma degree_exp_wrt_ty_S : forall n1 e1, degree_exp_wrt_ty n1 e1 -> degree_exp_wrt_ty (S n1) e1. Proof. pose proof degree_exp_wrt_ty_S_mutual as H; intuition eauto. Qed. Hint Resolve degree_exp_wrt_ty_S : lngen. (* begin hide *) Lemma degree_exp_wrt_exp_S_mutual : (forall n1 e1, degree_exp_wrt_exp n1 e1 -> degree_exp_wrt_exp (S n1) e1). Proof. apply_mutual_ind degree_exp_wrt_exp_mutind; default_simp. Qed. (* end hide *) Lemma degree_exp_wrt_exp_S : forall n1 e1, degree_exp_wrt_exp n1 e1 -> degree_exp_wrt_exp (S n1) e1. Proof. pose proof degree_exp_wrt_exp_S_mutual as H; intuition eauto. Qed. Hint Resolve degree_exp_wrt_exp_S : lngen. Lemma degree_ty_wrt_ty_O : forall n1 T1, degree_ty_wrt_ty O T1 -> degree_ty_wrt_ty n1 T1. Proof. induction n1; default_simp. Qed. Hint Resolve degree_ty_wrt_ty_O : lngen. Lemma degree_exp_wrt_ty_O : forall n1 e1, degree_exp_wrt_ty O e1 -> degree_exp_wrt_ty n1 e1. Proof. induction n1; default_simp. Qed. Hint Resolve degree_exp_wrt_ty_O : lngen. Lemma degree_exp_wrt_exp_O : forall n1 e1, degree_exp_wrt_exp O e1 -> degree_exp_wrt_exp n1 e1. Proof. induction n1; default_simp. Qed. Hint Resolve degree_exp_wrt_exp_O : lngen. (* begin hide *) Lemma degree_ty_wrt_ty_close_ty_wrt_ty_rec_mutual : (forall T1 X1 n1, degree_ty_wrt_ty n1 T1 -> degree_ty_wrt_ty (S n1) (close_ty_wrt_ty_rec n1 X1 T1)). Proof. apply_mutual_ind ty_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma degree_ty_wrt_ty_close_ty_wrt_ty_rec : forall T1 X1 n1, degree_ty_wrt_ty n1 T1 -> degree_ty_wrt_ty (S n1) (close_ty_wrt_ty_rec n1 X1 T1). Proof. pose proof degree_ty_wrt_ty_close_ty_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve degree_ty_wrt_ty_close_ty_wrt_ty_rec : lngen. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_ty_close_exp_wrt_ty_rec_mutual : (forall e1 X1 n1, degree_exp_wrt_ty n1 e1 -> degree_exp_wrt_ty (S n1) (close_exp_wrt_ty_rec n1 X1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_ty_close_exp_wrt_ty_rec : forall e1 X1 n1, degree_exp_wrt_ty n1 e1 -> degree_exp_wrt_ty (S n1) (close_exp_wrt_ty_rec n1 X1 e1). Proof. pose proof degree_exp_wrt_ty_close_exp_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve degree_exp_wrt_ty_close_exp_wrt_ty_rec : lngen. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_ty_close_exp_wrt_exp_rec_mutual : (forall e1 x1 n1 n2, degree_exp_wrt_ty n2 e1 -> degree_exp_wrt_ty n2 (close_exp_wrt_exp_rec n1 x1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_ty_close_exp_wrt_exp_rec : forall e1 x1 n1 n2, degree_exp_wrt_ty n2 e1 -> degree_exp_wrt_ty n2 (close_exp_wrt_exp_rec n1 x1 e1). Proof. pose proof degree_exp_wrt_ty_close_exp_wrt_exp_rec_mutual as H; intuition eauto. Qed. Hint Resolve degree_exp_wrt_ty_close_exp_wrt_exp_rec : lngen. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_exp_close_exp_wrt_ty_rec_mutual : (forall e1 X1 n1 n2, degree_exp_wrt_exp n2 e1 -> degree_exp_wrt_exp n2 (close_exp_wrt_ty_rec n1 X1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_exp_close_exp_wrt_ty_rec : forall e1 X1 n1 n2, degree_exp_wrt_exp n2 e1 -> degree_exp_wrt_exp n2 (close_exp_wrt_ty_rec n1 X1 e1). Proof. pose proof degree_exp_wrt_exp_close_exp_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve degree_exp_wrt_exp_close_exp_wrt_ty_rec : lngen. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_exp_close_exp_wrt_exp_rec_mutual : (forall e1 x1 n1, degree_exp_wrt_exp n1 e1 -> degree_exp_wrt_exp (S n1) (close_exp_wrt_exp_rec n1 x1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_exp_close_exp_wrt_exp_rec : forall e1 x1 n1, degree_exp_wrt_exp n1 e1 -> degree_exp_wrt_exp (S n1) (close_exp_wrt_exp_rec n1 x1 e1). Proof. pose proof degree_exp_wrt_exp_close_exp_wrt_exp_rec_mutual as H; intuition eauto. Qed. Hint Resolve degree_exp_wrt_exp_close_exp_wrt_exp_rec : lngen. (* end hide *) Lemma degree_ty_wrt_ty_close_ty_wrt_ty : forall T1 X1, degree_ty_wrt_ty 0 T1 -> degree_ty_wrt_ty 1 (close_ty_wrt_ty X1 T1). Proof. unfold close_ty_wrt_ty; default_simp. Qed. Hint Resolve degree_ty_wrt_ty_close_ty_wrt_ty : lngen. Lemma degree_exp_wrt_ty_close_exp_wrt_ty : forall e1 X1, degree_exp_wrt_ty 0 e1 -> degree_exp_wrt_ty 1 (close_exp_wrt_ty X1 e1). Proof. unfold close_exp_wrt_ty; default_simp. Qed. Hint Resolve degree_exp_wrt_ty_close_exp_wrt_ty : lngen. Lemma degree_exp_wrt_ty_close_exp_wrt_exp : forall e1 x1 n1, degree_exp_wrt_ty n1 e1 -> degree_exp_wrt_ty n1 (close_exp_wrt_exp x1 e1). Proof. unfold close_exp_wrt_exp; default_simp. Qed. Hint Resolve degree_exp_wrt_ty_close_exp_wrt_exp : lngen. Lemma degree_exp_wrt_exp_close_exp_wrt_ty : forall e1 X1 n1, degree_exp_wrt_exp n1 e1 -> degree_exp_wrt_exp n1 (close_exp_wrt_ty X1 e1). Proof. unfold close_exp_wrt_ty; default_simp. Qed. Hint Resolve degree_exp_wrt_exp_close_exp_wrt_ty : lngen. Lemma degree_exp_wrt_exp_close_exp_wrt_exp : forall e1 x1, degree_exp_wrt_exp 0 e1 -> degree_exp_wrt_exp 1 (close_exp_wrt_exp x1 e1). Proof. unfold close_exp_wrt_exp; default_simp. Qed. Hint Resolve degree_exp_wrt_exp_close_exp_wrt_exp : lngen. (* begin hide *) Lemma degree_ty_wrt_ty_close_ty_wrt_ty_rec_inv_mutual : (forall T1 X1 n1, degree_ty_wrt_ty (S n1) (close_ty_wrt_ty_rec n1 X1 T1) -> degree_ty_wrt_ty n1 T1). Proof. apply_mutual_ind ty_mutind; default_simp; eauto with lngen. Qed. (* end hide *) (* begin hide *) Lemma degree_ty_wrt_ty_close_ty_wrt_ty_rec_inv : forall T1 X1 n1, degree_ty_wrt_ty (S n1) (close_ty_wrt_ty_rec n1 X1 T1) -> degree_ty_wrt_ty n1 T1. Proof. pose proof degree_ty_wrt_ty_close_ty_wrt_ty_rec_inv_mutual as H; intuition eauto. Qed. Hint Immediate degree_ty_wrt_ty_close_ty_wrt_ty_rec_inv : lngen. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_ty_close_exp_wrt_ty_rec_inv_mutual : (forall e1 X1 n1, degree_exp_wrt_ty (S n1) (close_exp_wrt_ty_rec n1 X1 e1) -> degree_exp_wrt_ty n1 e1). Proof. apply_mutual_ind exp_mutind; default_simp; eauto with lngen. Qed. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_ty_close_exp_wrt_ty_rec_inv : forall e1 X1 n1, degree_exp_wrt_ty (S n1) (close_exp_wrt_ty_rec n1 X1 e1) -> degree_exp_wrt_ty n1 e1. Proof. pose proof degree_exp_wrt_ty_close_exp_wrt_ty_rec_inv_mutual as H; intuition eauto. Qed. Hint Immediate degree_exp_wrt_ty_close_exp_wrt_ty_rec_inv : lngen. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_ty_close_exp_wrt_exp_rec_inv_mutual : (forall e1 x1 n1 n2, degree_exp_wrt_ty n2 (close_exp_wrt_exp_rec n1 x1 e1) -> degree_exp_wrt_ty n2 e1). Proof. apply_mutual_ind exp_mutind; default_simp; eauto with lngen. Qed. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_ty_close_exp_wrt_exp_rec_inv : forall e1 x1 n1 n2, degree_exp_wrt_ty n2 (close_exp_wrt_exp_rec n1 x1 e1) -> degree_exp_wrt_ty n2 e1. Proof. pose proof degree_exp_wrt_ty_close_exp_wrt_exp_rec_inv_mutual as H; intuition eauto. Qed. Hint Immediate degree_exp_wrt_ty_close_exp_wrt_exp_rec_inv : lngen. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_exp_close_exp_wrt_ty_rec_inv_mutual : (forall e1 X1 n1 n2, degree_exp_wrt_exp n2 (close_exp_wrt_ty_rec n1 X1 e1) -> degree_exp_wrt_exp n2 e1). Proof. apply_mutual_ind exp_mutind; default_simp; eauto with lngen. Qed. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_exp_close_exp_wrt_ty_rec_inv : forall e1 X1 n1 n2, degree_exp_wrt_exp n2 (close_exp_wrt_ty_rec n1 X1 e1) -> degree_exp_wrt_exp n2 e1. Proof. pose proof degree_exp_wrt_exp_close_exp_wrt_ty_rec_inv_mutual as H; intuition eauto. Qed. Hint Immediate degree_exp_wrt_exp_close_exp_wrt_ty_rec_inv : lngen. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_exp_close_exp_wrt_exp_rec_inv_mutual : (forall e1 x1 n1, degree_exp_wrt_exp (S n1) (close_exp_wrt_exp_rec n1 x1 e1) -> degree_exp_wrt_exp n1 e1). Proof. apply_mutual_ind exp_mutind; default_simp; eauto with lngen. Qed. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_exp_close_exp_wrt_exp_rec_inv : forall e1 x1 n1, degree_exp_wrt_exp (S n1) (close_exp_wrt_exp_rec n1 x1 e1) -> degree_exp_wrt_exp n1 e1. Proof. pose proof degree_exp_wrt_exp_close_exp_wrt_exp_rec_inv_mutual as H; intuition eauto. Qed. Hint Immediate degree_exp_wrt_exp_close_exp_wrt_exp_rec_inv : lngen. (* end hide *) Lemma degree_ty_wrt_ty_close_ty_wrt_ty_inv : forall T1 X1, degree_ty_wrt_ty 1 (close_ty_wrt_ty X1 T1) -> degree_ty_wrt_ty 0 T1. Proof. unfold close_ty_wrt_ty; eauto with lngen. Qed. Hint Immediate degree_ty_wrt_ty_close_ty_wrt_ty_inv : lngen. Lemma degree_exp_wrt_ty_close_exp_wrt_ty_inv : forall e1 X1, degree_exp_wrt_ty 1 (close_exp_wrt_ty X1 e1) -> degree_exp_wrt_ty 0 e1. Proof. unfold close_exp_wrt_ty; eauto with lngen. Qed. Hint Immediate degree_exp_wrt_ty_close_exp_wrt_ty_inv : lngen. Lemma degree_exp_wrt_ty_close_exp_wrt_exp_inv : forall e1 x1 n1, degree_exp_wrt_ty n1 (close_exp_wrt_exp x1 e1) -> degree_exp_wrt_ty n1 e1. Proof. unfold close_exp_wrt_exp; eauto with lngen. Qed. Hint Immediate degree_exp_wrt_ty_close_exp_wrt_exp_inv : lngen. Lemma degree_exp_wrt_exp_close_exp_wrt_ty_inv : forall e1 X1 n1, degree_exp_wrt_exp n1 (close_exp_wrt_ty X1 e1) -> degree_exp_wrt_exp n1 e1. Proof. unfold close_exp_wrt_ty; eauto with lngen. Qed. Hint Immediate degree_exp_wrt_exp_close_exp_wrt_ty_inv : lngen. Lemma degree_exp_wrt_exp_close_exp_wrt_exp_inv : forall e1 x1, degree_exp_wrt_exp 1 (close_exp_wrt_exp x1 e1) -> degree_exp_wrt_exp 0 e1. Proof. unfold close_exp_wrt_exp; eauto with lngen. Qed. Hint Immediate degree_exp_wrt_exp_close_exp_wrt_exp_inv : lngen. (* begin hide *) Lemma degree_ty_wrt_ty_open_ty_wrt_ty_rec_mutual : (forall T1 T2 n1, degree_ty_wrt_ty (S n1) T1 -> degree_ty_wrt_ty n1 T2 -> degree_ty_wrt_ty n1 (open_ty_wrt_ty_rec n1 T2 T1)). Proof. apply_mutual_ind ty_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma degree_ty_wrt_ty_open_ty_wrt_ty_rec : forall T1 T2 n1, degree_ty_wrt_ty (S n1) T1 -> degree_ty_wrt_ty n1 T2 -> degree_ty_wrt_ty n1 (open_ty_wrt_ty_rec n1 T2 T1). Proof. pose proof degree_ty_wrt_ty_open_ty_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve degree_ty_wrt_ty_open_ty_wrt_ty_rec : lngen. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_ty_open_exp_wrt_ty_rec_mutual : (forall e1 T1 n1, degree_exp_wrt_ty (S n1) e1 -> degree_ty_wrt_ty n1 T1 -> degree_exp_wrt_ty n1 (open_exp_wrt_ty_rec n1 T1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_ty_open_exp_wrt_ty_rec : forall e1 T1 n1, degree_exp_wrt_ty (S n1) e1 -> degree_ty_wrt_ty n1 T1 -> degree_exp_wrt_ty n1 (open_exp_wrt_ty_rec n1 T1 e1). Proof. pose proof degree_exp_wrt_ty_open_exp_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve degree_exp_wrt_ty_open_exp_wrt_ty_rec : lngen. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_ty_open_exp_wrt_exp_rec_mutual : (forall e1 e2 n1 n2, degree_exp_wrt_ty n1 e1 -> degree_exp_wrt_ty n1 e2 -> degree_exp_wrt_ty n1 (open_exp_wrt_exp_rec n2 e2 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_ty_open_exp_wrt_exp_rec : forall e1 e2 n1 n2, degree_exp_wrt_ty n1 e1 -> degree_exp_wrt_ty n1 e2 -> degree_exp_wrt_ty n1 (open_exp_wrt_exp_rec n2 e2 e1). Proof. pose proof degree_exp_wrt_ty_open_exp_wrt_exp_rec_mutual as H; intuition eauto. Qed. Hint Resolve degree_exp_wrt_ty_open_exp_wrt_exp_rec : lngen. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_exp_open_exp_wrt_ty_rec_mutual : (forall e1 T1 n1 n2, degree_exp_wrt_exp n1 e1 -> degree_exp_wrt_exp n1 (open_exp_wrt_ty_rec n2 T1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_exp_open_exp_wrt_ty_rec : forall e1 T1 n1 n2, degree_exp_wrt_exp n1 e1 -> degree_exp_wrt_exp n1 (open_exp_wrt_ty_rec n2 T1 e1). Proof. pose proof degree_exp_wrt_exp_open_exp_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve degree_exp_wrt_exp_open_exp_wrt_ty_rec : lngen. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_exp_open_exp_wrt_exp_rec_mutual : (forall e1 e2 n1, degree_exp_wrt_exp (S n1) e1 -> degree_exp_wrt_exp n1 e2 -> degree_exp_wrt_exp n1 (open_exp_wrt_exp_rec n1 e2 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_exp_open_exp_wrt_exp_rec : forall e1 e2 n1, degree_exp_wrt_exp (S n1) e1 -> degree_exp_wrt_exp n1 e2 -> degree_exp_wrt_exp n1 (open_exp_wrt_exp_rec n1 e2 e1). Proof. pose proof degree_exp_wrt_exp_open_exp_wrt_exp_rec_mutual as H; intuition eauto. Qed. Hint Resolve degree_exp_wrt_exp_open_exp_wrt_exp_rec : lngen. (* end hide *) Lemma degree_ty_wrt_ty_open_ty_wrt_ty : forall T1 T2, degree_ty_wrt_ty 1 T1 -> degree_ty_wrt_ty 0 T2 -> degree_ty_wrt_ty 0 (open_ty_wrt_ty T1 T2). Proof. unfold open_ty_wrt_ty; default_simp. Qed. Hint Resolve degree_ty_wrt_ty_open_ty_wrt_ty : lngen. Lemma degree_exp_wrt_ty_open_exp_wrt_ty : forall e1 T1, degree_exp_wrt_ty 1 e1 -> degree_ty_wrt_ty 0 T1 -> degree_exp_wrt_ty 0 (open_exp_wrt_ty e1 T1). Proof. unfold open_exp_wrt_ty; default_simp. Qed. Hint Resolve degree_exp_wrt_ty_open_exp_wrt_ty : lngen. Lemma degree_exp_wrt_ty_open_exp_wrt_exp : forall e1 e2 n1, degree_exp_wrt_ty n1 e1 -> degree_exp_wrt_ty n1 e2 -> degree_exp_wrt_ty n1 (open_exp_wrt_exp e1 e2). Proof. unfold open_exp_wrt_exp; default_simp. Qed. Hint Resolve degree_exp_wrt_ty_open_exp_wrt_exp : lngen. Lemma degree_exp_wrt_exp_open_exp_wrt_ty : forall e1 T1 n1, degree_exp_wrt_exp n1 e1 -> degree_exp_wrt_exp n1 (open_exp_wrt_ty e1 T1). Proof. unfold open_exp_wrt_ty; default_simp. Qed. Hint Resolve degree_exp_wrt_exp_open_exp_wrt_ty : lngen. Lemma degree_exp_wrt_exp_open_exp_wrt_exp : forall e1 e2, degree_exp_wrt_exp 1 e1 -> degree_exp_wrt_exp 0 e2 -> degree_exp_wrt_exp 0 (open_exp_wrt_exp e1 e2). Proof. unfold open_exp_wrt_exp; default_simp. Qed. Hint Resolve degree_exp_wrt_exp_open_exp_wrt_exp : lngen. (* begin hide *) Lemma degree_ty_wrt_ty_open_ty_wrt_ty_rec_inv_mutual : (forall T1 T2 n1, degree_ty_wrt_ty n1 (open_ty_wrt_ty_rec n1 T2 T1) -> degree_ty_wrt_ty (S n1) T1). Proof. apply_mutual_ind ty_mutind; default_simp; eauto with lngen. Qed. (* end hide *) (* begin hide *) Lemma degree_ty_wrt_ty_open_ty_wrt_ty_rec_inv : forall T1 T2 n1, degree_ty_wrt_ty n1 (open_ty_wrt_ty_rec n1 T2 T1) -> degree_ty_wrt_ty (S n1) T1. Proof. pose proof degree_ty_wrt_ty_open_ty_wrt_ty_rec_inv_mutual as H; intuition eauto. Qed. Hint Immediate degree_ty_wrt_ty_open_ty_wrt_ty_rec_inv : lngen. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_ty_open_exp_wrt_ty_rec_inv_mutual : (forall e1 T1 n1, degree_exp_wrt_ty n1 (open_exp_wrt_ty_rec n1 T1 e1) -> degree_exp_wrt_ty (S n1) e1). Proof. apply_mutual_ind exp_mutind; default_simp; eauto with lngen. Qed. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_ty_open_exp_wrt_ty_rec_inv : forall e1 T1 n1, degree_exp_wrt_ty n1 (open_exp_wrt_ty_rec n1 T1 e1) -> degree_exp_wrt_ty (S n1) e1. Proof. pose proof degree_exp_wrt_ty_open_exp_wrt_ty_rec_inv_mutual as H; intuition eauto. Qed. Hint Immediate degree_exp_wrt_ty_open_exp_wrt_ty_rec_inv : lngen. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_ty_open_exp_wrt_exp_rec_inv_mutual : (forall e1 e2 n1 n2, degree_exp_wrt_ty n1 (open_exp_wrt_exp_rec n2 e2 e1) -> degree_exp_wrt_ty n1 e1). Proof. apply_mutual_ind exp_mutind; default_simp; eauto with lngen. Qed. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_ty_open_exp_wrt_exp_rec_inv : forall e1 e2 n1 n2, degree_exp_wrt_ty n1 (open_exp_wrt_exp_rec n2 e2 e1) -> degree_exp_wrt_ty n1 e1. Proof. pose proof degree_exp_wrt_ty_open_exp_wrt_exp_rec_inv_mutual as H; intuition eauto. Qed. Hint Immediate degree_exp_wrt_ty_open_exp_wrt_exp_rec_inv : lngen. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_exp_open_exp_wrt_ty_rec_inv_mutual : (forall e1 T1 n1 n2, degree_exp_wrt_exp n1 (open_exp_wrt_ty_rec n2 T1 e1) -> degree_exp_wrt_exp n1 e1). Proof. apply_mutual_ind exp_mutind; default_simp; eauto with lngen. Qed. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_exp_open_exp_wrt_ty_rec_inv : forall e1 T1 n1 n2, degree_exp_wrt_exp n1 (open_exp_wrt_ty_rec n2 T1 e1) -> degree_exp_wrt_exp n1 e1. Proof. pose proof degree_exp_wrt_exp_open_exp_wrt_ty_rec_inv_mutual as H; intuition eauto. Qed. Hint Immediate degree_exp_wrt_exp_open_exp_wrt_ty_rec_inv : lngen. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_exp_open_exp_wrt_exp_rec_inv_mutual : (forall e1 e2 n1, degree_exp_wrt_exp n1 (open_exp_wrt_exp_rec n1 e2 e1) -> degree_exp_wrt_exp (S n1) e1). Proof. apply_mutual_ind exp_mutind; default_simp; eauto with lngen. Qed. (* end hide *) (* begin hide *) Lemma degree_exp_wrt_exp_open_exp_wrt_exp_rec_inv : forall e1 e2 n1, degree_exp_wrt_exp n1 (open_exp_wrt_exp_rec n1 e2 e1) -> degree_exp_wrt_exp (S n1) e1. Proof. pose proof degree_exp_wrt_exp_open_exp_wrt_exp_rec_inv_mutual as H; intuition eauto. Qed. Hint Immediate degree_exp_wrt_exp_open_exp_wrt_exp_rec_inv : lngen. (* end hide *) Lemma degree_ty_wrt_ty_open_ty_wrt_ty_inv : forall T1 T2, degree_ty_wrt_ty 0 (open_ty_wrt_ty T1 T2) -> degree_ty_wrt_ty 1 T1. Proof. unfold open_ty_wrt_ty; eauto with lngen. Qed. Hint Immediate degree_ty_wrt_ty_open_ty_wrt_ty_inv : lngen. Lemma degree_exp_wrt_ty_open_exp_wrt_ty_inv : forall e1 T1, degree_exp_wrt_ty 0 (open_exp_wrt_ty e1 T1) -> degree_exp_wrt_ty 1 e1. Proof. unfold open_exp_wrt_ty; eauto with lngen. Qed. Hint Immediate degree_exp_wrt_ty_open_exp_wrt_ty_inv : lngen. Lemma degree_exp_wrt_ty_open_exp_wrt_exp_inv : forall e1 e2 n1, degree_exp_wrt_ty n1 (open_exp_wrt_exp e1 e2) -> degree_exp_wrt_ty n1 e1. Proof. unfold open_exp_wrt_exp; eauto with lngen. Qed. Hint Immediate degree_exp_wrt_ty_open_exp_wrt_exp_inv : lngen. Lemma degree_exp_wrt_exp_open_exp_wrt_ty_inv : forall e1 T1 n1, degree_exp_wrt_exp n1 (open_exp_wrt_ty e1 T1) -> degree_exp_wrt_exp n1 e1. Proof. unfold open_exp_wrt_ty; eauto with lngen. Qed. Hint Immediate degree_exp_wrt_exp_open_exp_wrt_ty_inv : lngen. Lemma degree_exp_wrt_exp_open_exp_wrt_exp_inv : forall e1 e2, degree_exp_wrt_exp 0 (open_exp_wrt_exp e1 e2) -> degree_exp_wrt_exp 1 e1. Proof. unfold open_exp_wrt_exp; eauto with lngen. Qed. Hint Immediate degree_exp_wrt_exp_open_exp_wrt_exp_inv : lngen. (* *********************************************************************** *) (** * Theorems about [open] and [close] *) Ltac default_auto ::= auto with lngen brute_force; tauto. Ltac default_autorewrite ::= fail. (* begin hide *) Lemma close_ty_wrt_ty_rec_inj_mutual : (forall T1 T2 X1 n1, close_ty_wrt_ty_rec n1 X1 T1 = close_ty_wrt_ty_rec n1 X1 T2 -> T1 = T2). Proof. apply_mutual_ind ty_mutind; intros; match goal with | |- _ = ?term => destruct term end; default_simp; eauto with lngen. Qed. (* end hide *) (* begin hide *) Lemma close_ty_wrt_ty_rec_inj : forall T1 T2 X1 n1, close_ty_wrt_ty_rec n1 X1 T1 = close_ty_wrt_ty_rec n1 X1 T2 -> T1 = T2. Proof. pose proof close_ty_wrt_ty_rec_inj_mutual as H; intuition eauto. Qed. Hint Immediate close_ty_wrt_ty_rec_inj : lngen. (* end hide *) (* begin hide *) Lemma close_exp_wrt_ty_rec_inj_mutual : (forall e1 e2 X1 n1, close_exp_wrt_ty_rec n1 X1 e1 = close_exp_wrt_ty_rec n1 X1 e2 -> e1 = e2). Proof. apply_mutual_ind exp_mutind; intros; match goal with | |- _ = ?term => destruct term end; default_simp; eauto with lngen. Qed. (* end hide *) (* begin hide *) Lemma close_exp_wrt_ty_rec_inj : forall e1 e2 X1 n1, close_exp_wrt_ty_rec n1 X1 e1 = close_exp_wrt_ty_rec n1 X1 e2 -> e1 = e2. Proof. pose proof close_exp_wrt_ty_rec_inj_mutual as H; intuition eauto. Qed. Hint Immediate close_exp_wrt_ty_rec_inj : lngen. (* end hide *) (* begin hide *) Lemma close_exp_wrt_exp_rec_inj_mutual : (forall e1 e2 x1 n1, close_exp_wrt_exp_rec n1 x1 e1 = close_exp_wrt_exp_rec n1 x1 e2 -> e1 = e2). Proof. apply_mutual_ind exp_mutind; intros; match goal with | |- _ = ?term => destruct term end; default_simp; eauto with lngen. Qed. (* end hide *) (* begin hide *) Lemma close_exp_wrt_exp_rec_inj : forall e1 e2 x1 n1, close_exp_wrt_exp_rec n1 x1 e1 = close_exp_wrt_exp_rec n1 x1 e2 -> e1 = e2. Proof. pose proof close_exp_wrt_exp_rec_inj_mutual as H; intuition eauto. Qed. Hint Immediate close_exp_wrt_exp_rec_inj : lngen. (* end hide *) Lemma close_ty_wrt_ty_inj : forall T1 T2 X1, close_ty_wrt_ty X1 T1 = close_ty_wrt_ty X1 T2 -> T1 = T2. Proof. unfold close_ty_wrt_ty; eauto with lngen. Qed. Hint Immediate close_ty_wrt_ty_inj : lngen. Lemma close_exp_wrt_ty_inj : forall e1 e2 X1, close_exp_wrt_ty X1 e1 = close_exp_wrt_ty X1 e2 -> e1 = e2. Proof. unfold close_exp_wrt_ty; eauto with lngen. Qed. Hint Immediate close_exp_wrt_ty_inj : lngen. Lemma close_exp_wrt_exp_inj : forall e1 e2 x1, close_exp_wrt_exp x1 e1 = close_exp_wrt_exp x1 e2 -> e1 = e2. Proof. unfold close_exp_wrt_exp; eauto with lngen. Qed. Hint Immediate close_exp_wrt_exp_inj : lngen. (* begin hide *) Lemma close_ty_wrt_ty_rec_open_ty_wrt_ty_rec_mutual : (forall T1 X1 n1, X1 `notin` fv_ty_in_ty T1 -> close_ty_wrt_ty_rec n1 X1 (open_ty_wrt_ty_rec n1 (ty_var_f X1) T1) = T1). Proof. apply_mutual_ind ty_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma close_ty_wrt_ty_rec_open_ty_wrt_ty_rec : forall T1 X1 n1, X1 `notin` fv_ty_in_ty T1 -> close_ty_wrt_ty_rec n1 X1 (open_ty_wrt_ty_rec n1 (ty_var_f X1) T1) = T1. Proof. pose proof close_ty_wrt_ty_rec_open_ty_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve close_ty_wrt_ty_rec_open_ty_wrt_ty_rec : lngen. Hint Rewrite close_ty_wrt_ty_rec_open_ty_wrt_ty_rec using solve [auto] : lngen. (* end hide *) (* begin hide *) Lemma close_exp_wrt_ty_rec_open_exp_wrt_ty_rec_mutual : (forall e1 X1 n1, X1 `notin` fv_ty_in_exp e1 -> close_exp_wrt_ty_rec n1 X1 (open_exp_wrt_ty_rec n1 (ty_var_f X1) e1) = e1). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma close_exp_wrt_ty_rec_open_exp_wrt_ty_rec : forall e1 X1 n1, X1 `notin` fv_ty_in_exp e1 -> close_exp_wrt_ty_rec n1 X1 (open_exp_wrt_ty_rec n1 (ty_var_f X1) e1) = e1. Proof. pose proof close_exp_wrt_ty_rec_open_exp_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve close_exp_wrt_ty_rec_open_exp_wrt_ty_rec : lngen. Hint Rewrite close_exp_wrt_ty_rec_open_exp_wrt_ty_rec using solve [auto] : lngen. (* end hide *) (* begin hide *) Lemma close_exp_wrt_exp_rec_open_exp_wrt_exp_rec_mutual : (forall e1 x1 n1, x1 `notin` fv_exp_in_exp e1 -> close_exp_wrt_exp_rec n1 x1 (open_exp_wrt_exp_rec n1 (exp_var_f x1) e1) = e1). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma close_exp_wrt_exp_rec_open_exp_wrt_exp_rec : forall e1 x1 n1, x1 `notin` fv_exp_in_exp e1 -> close_exp_wrt_exp_rec n1 x1 (open_exp_wrt_exp_rec n1 (exp_var_f x1) e1) = e1. Proof. pose proof close_exp_wrt_exp_rec_open_exp_wrt_exp_rec_mutual as H; intuition eauto. Qed. Hint Resolve close_exp_wrt_exp_rec_open_exp_wrt_exp_rec : lngen. Hint Rewrite close_exp_wrt_exp_rec_open_exp_wrt_exp_rec using solve [auto] : lngen. (* end hide *) Lemma close_ty_wrt_ty_open_ty_wrt_ty : forall T1 X1, X1 `notin` fv_ty_in_ty T1 -> close_ty_wrt_ty X1 (open_ty_wrt_ty T1 (ty_var_f X1)) = T1. Proof. unfold close_ty_wrt_ty; unfold open_ty_wrt_ty; default_simp. Qed. Hint Resolve close_ty_wrt_ty_open_ty_wrt_ty : lngen. Hint Rewrite close_ty_wrt_ty_open_ty_wrt_ty using solve [auto] : lngen. Lemma close_exp_wrt_ty_open_exp_wrt_ty : forall e1 X1, X1 `notin` fv_ty_in_exp e1 -> close_exp_wrt_ty X1 (open_exp_wrt_ty e1 (ty_var_f X1)) = e1. Proof. unfold close_exp_wrt_ty; unfold open_exp_wrt_ty; default_simp. Qed. Hint Resolve close_exp_wrt_ty_open_exp_wrt_ty : lngen. Hint Rewrite close_exp_wrt_ty_open_exp_wrt_ty using solve [auto] : lngen. Lemma close_exp_wrt_exp_open_exp_wrt_exp : forall e1 x1, x1 `notin` fv_exp_in_exp e1 -> close_exp_wrt_exp x1 (open_exp_wrt_exp e1 (exp_var_f x1)) = e1. Proof. unfold close_exp_wrt_exp; unfold open_exp_wrt_exp; default_simp. Qed. Hint Resolve close_exp_wrt_exp_open_exp_wrt_exp : lngen. Hint Rewrite close_exp_wrt_exp_open_exp_wrt_exp using solve [auto] : lngen. (* begin hide *) Lemma open_ty_wrt_ty_rec_close_ty_wrt_ty_rec_mutual : (forall T1 X1 n1, open_ty_wrt_ty_rec n1 (ty_var_f X1) (close_ty_wrt_ty_rec n1 X1 T1) = T1). Proof. apply_mutual_ind ty_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma open_ty_wrt_ty_rec_close_ty_wrt_ty_rec : forall T1 X1 n1, open_ty_wrt_ty_rec n1 (ty_var_f X1) (close_ty_wrt_ty_rec n1 X1 T1) = T1. Proof. pose proof open_ty_wrt_ty_rec_close_ty_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve open_ty_wrt_ty_rec_close_ty_wrt_ty_rec : lngen. Hint Rewrite open_ty_wrt_ty_rec_close_ty_wrt_ty_rec using solve [auto] : lngen. (* end hide *) (* begin hide *) Lemma open_exp_wrt_ty_rec_close_exp_wrt_ty_rec_mutual : (forall e1 X1 n1, open_exp_wrt_ty_rec n1 (ty_var_f X1) (close_exp_wrt_ty_rec n1 X1 e1) = e1). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma open_exp_wrt_ty_rec_close_exp_wrt_ty_rec : forall e1 X1 n1, open_exp_wrt_ty_rec n1 (ty_var_f X1) (close_exp_wrt_ty_rec n1 X1 e1) = e1. Proof. pose proof open_exp_wrt_ty_rec_close_exp_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve open_exp_wrt_ty_rec_close_exp_wrt_ty_rec : lngen. Hint Rewrite open_exp_wrt_ty_rec_close_exp_wrt_ty_rec using solve [auto] : lngen. (* end hide *) (* begin hide *) Lemma open_exp_wrt_exp_rec_close_exp_wrt_exp_rec_mutual : (forall e1 x1 n1, open_exp_wrt_exp_rec n1 (exp_var_f x1) (close_exp_wrt_exp_rec n1 x1 e1) = e1). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma open_exp_wrt_exp_rec_close_exp_wrt_exp_rec : forall e1 x1 n1, open_exp_wrt_exp_rec n1 (exp_var_f x1) (close_exp_wrt_exp_rec n1 x1 e1) = e1. Proof. pose proof open_exp_wrt_exp_rec_close_exp_wrt_exp_rec_mutual as H; intuition eauto. Qed. Hint Resolve open_exp_wrt_exp_rec_close_exp_wrt_exp_rec : lngen. Hint Rewrite open_exp_wrt_exp_rec_close_exp_wrt_exp_rec using solve [auto] : lngen. (* end hide *) Lemma open_ty_wrt_ty_close_ty_wrt_ty : forall T1 X1, open_ty_wrt_ty (close_ty_wrt_ty X1 T1) (ty_var_f X1) = T1. Proof. unfold close_ty_wrt_ty; unfold open_ty_wrt_ty; default_simp. Qed. Hint Resolve open_ty_wrt_ty_close_ty_wrt_ty : lngen. Hint Rewrite open_ty_wrt_ty_close_ty_wrt_ty using solve [auto] : lngen. Lemma open_exp_wrt_ty_close_exp_wrt_ty : forall e1 X1, open_exp_wrt_ty (close_exp_wrt_ty X1 e1) (ty_var_f X1) = e1. Proof. unfold close_exp_wrt_ty; unfold open_exp_wrt_ty; default_simp. Qed. Hint Resolve open_exp_wrt_ty_close_exp_wrt_ty : lngen. Hint Rewrite open_exp_wrt_ty_close_exp_wrt_ty using solve [auto] : lngen. Lemma open_exp_wrt_exp_close_exp_wrt_exp : forall e1 x1, open_exp_wrt_exp (close_exp_wrt_exp x1 e1) (exp_var_f x1) = e1. Proof. unfold close_exp_wrt_exp; unfold open_exp_wrt_exp; default_simp. Qed. Hint Resolve open_exp_wrt_exp_close_exp_wrt_exp : lngen. Hint Rewrite open_exp_wrt_exp_close_exp_wrt_exp using solve [auto] : lngen. (* begin hide *) Lemma open_ty_wrt_ty_rec_inj_mutual : (forall T2 T1 X1 n1, X1 `notin` fv_ty_in_ty T2 -> X1 `notin` fv_ty_in_ty T1 -> open_ty_wrt_ty_rec n1 (ty_var_f X1) T2 = open_ty_wrt_ty_rec n1 (ty_var_f X1) T1 -> T2 = T1). Proof. apply_mutual_ind ty_mutind; intros; match goal with | |- _ = ?term => destruct term end; default_simp; eauto with lngen. Qed. (* end hide *) (* begin hide *) Lemma open_ty_wrt_ty_rec_inj : forall T2 T1 X1 n1, X1 `notin` fv_ty_in_ty T2 -> X1 `notin` fv_ty_in_ty T1 -> open_ty_wrt_ty_rec n1 (ty_var_f X1) T2 = open_ty_wrt_ty_rec n1 (ty_var_f X1) T1 -> T2 = T1. Proof. pose proof open_ty_wrt_ty_rec_inj_mutual as H; intuition eauto. Qed. Hint Immediate open_ty_wrt_ty_rec_inj : lngen. (* end hide *) (* begin hide *) Lemma open_exp_wrt_ty_rec_inj_mutual : (forall e2 e1 X1 n1, X1 `notin` fv_ty_in_exp e2 -> X1 `notin` fv_ty_in_exp e1 -> open_exp_wrt_ty_rec n1 (ty_var_f X1) e2 = open_exp_wrt_ty_rec n1 (ty_var_f X1) e1 -> e2 = e1). Proof. apply_mutual_ind exp_mutind; intros; match goal with | |- _ = ?term => destruct term end; default_simp; eauto with lngen. Qed. (* end hide *) (* begin hide *) Lemma open_exp_wrt_ty_rec_inj : forall e2 e1 X1 n1, X1 `notin` fv_ty_in_exp e2 -> X1 `notin` fv_ty_in_exp e1 -> open_exp_wrt_ty_rec n1 (ty_var_f X1) e2 = open_exp_wrt_ty_rec n1 (ty_var_f X1) e1 -> e2 = e1. Proof. pose proof open_exp_wrt_ty_rec_inj_mutual as H; intuition eauto. Qed. Hint Immediate open_exp_wrt_ty_rec_inj : lngen. (* end hide *) (* begin hide *) Lemma open_exp_wrt_exp_rec_inj_mutual : (forall e2 e1 x1 n1, x1 `notin` fv_exp_in_exp e2 -> x1 `notin` fv_exp_in_exp e1 -> open_exp_wrt_exp_rec n1 (exp_var_f x1) e2 = open_exp_wrt_exp_rec n1 (exp_var_f x1) e1 -> e2 = e1). Proof. apply_mutual_ind exp_mutind; intros; match goal with | |- _ = ?term => destruct term end; default_simp; eauto with lngen. Qed. (* end hide *) (* begin hide *) Lemma open_exp_wrt_exp_rec_inj : forall e2 e1 x1 n1, x1 `notin` fv_exp_in_exp e2 -> x1 `notin` fv_exp_in_exp e1 -> open_exp_wrt_exp_rec n1 (exp_var_f x1) e2 = open_exp_wrt_exp_rec n1 (exp_var_f x1) e1 -> e2 = e1. Proof. pose proof open_exp_wrt_exp_rec_inj_mutual as H; intuition eauto. Qed. Hint Immediate open_exp_wrt_exp_rec_inj : lngen. (* end hide *) Lemma open_ty_wrt_ty_inj : forall T2 T1 X1, X1 `notin` fv_ty_in_ty T2 -> X1 `notin` fv_ty_in_ty T1 -> open_ty_wrt_ty T2 (ty_var_f X1) = open_ty_wrt_ty T1 (ty_var_f X1) -> T2 = T1. Proof. unfold open_ty_wrt_ty; eauto with lngen. Qed. Hint Immediate open_ty_wrt_ty_inj : lngen. Lemma open_exp_wrt_ty_inj : forall e2 e1 X1, X1 `notin` fv_ty_in_exp e2 -> X1 `notin` fv_ty_in_exp e1 -> open_exp_wrt_ty e2 (ty_var_f X1) = open_exp_wrt_ty e1 (ty_var_f X1) -> e2 = e1. Proof. unfold open_exp_wrt_ty; eauto with lngen. Qed. Hint Immediate open_exp_wrt_ty_inj : lngen. Lemma open_exp_wrt_exp_inj : forall e2 e1 x1, x1 `notin` fv_exp_in_exp e2 -> x1 `notin` fv_exp_in_exp e1 -> open_exp_wrt_exp e2 (exp_var_f x1) = open_exp_wrt_exp e1 (exp_var_f x1) -> e2 = e1. Proof. unfold open_exp_wrt_exp; eauto with lngen. Qed. Hint Immediate open_exp_wrt_exp_inj : lngen. (* *********************************************************************** *) (** * Theorems about [lc] *) Ltac default_auto ::= auto with lngen brute_force; tauto. Ltac default_autorewrite ::= autorewrite with lngen. (* begin hide *) Lemma degree_ty_wrt_ty_of_lc_ty_mutual : (forall T1, lc_ty T1 -> degree_ty_wrt_ty 0 T1). Proof. apply_mutual_ind lc_ty_mutind; intros; let X1 := fresh "X1" in pick_fresh X1; repeat (match goal with | H1 : _, H2 : _ |- _ => specialize H1 with H2 end); default_simp; eauto with lngen. Qed. (* end hide *) Lemma degree_ty_wrt_ty_of_lc_ty : forall T1, lc_ty T1 -> degree_ty_wrt_ty 0 T1. Proof. pose proof degree_ty_wrt_ty_of_lc_ty_mutual as H; intuition eauto. Qed. Hint Resolve degree_ty_wrt_ty_of_lc_ty : lngen. (* begin hide *) Lemma degree_exp_wrt_ty_of_lc_exp_mutual : (forall e1, lc_exp e1 -> degree_exp_wrt_ty 0 e1). Proof. apply_mutual_ind lc_exp_mutind; intros; let X1 := fresh "X1" in pick_fresh X1; let x1 := fresh "x1" in pick_fresh x1; repeat (match goal with | H1 : _, H2 : _ |- _ => specialize H1 with H2 end); default_simp; eauto with lngen. Qed. (* end hide *) Lemma degree_exp_wrt_ty_of_lc_exp : forall e1, lc_exp e1 -> degree_exp_wrt_ty 0 e1. Proof. pose proof degree_exp_wrt_ty_of_lc_exp_mutual as H; intuition eauto. Qed. Hint Resolve degree_exp_wrt_ty_of_lc_exp : lngen. (* begin hide *) Lemma degree_exp_wrt_exp_of_lc_exp_mutual : (forall e1, lc_exp e1 -> degree_exp_wrt_exp 0 e1). Proof. apply_mutual_ind lc_exp_mutind; intros; let X1 := fresh "X1" in pick_fresh X1; let x1 := fresh "x1" in pick_fresh x1; repeat (match goal with | H1 : _, H2 : _ |- _ => specialize H1 with H2 end); default_simp; eauto with lngen. Qed. (* end hide *) Lemma degree_exp_wrt_exp_of_lc_exp : forall e1, lc_exp e1 -> degree_exp_wrt_exp 0 e1. Proof. pose proof degree_exp_wrt_exp_of_lc_exp_mutual as H; intuition eauto. Qed. Hint Resolve degree_exp_wrt_exp_of_lc_exp : lngen. (* begin hide *) Lemma lc_ty_of_degree_size_mutual : forall i1, (forall T1, size_ty T1 = i1 -> degree_ty_wrt_ty 0 T1 -> lc_ty T1). Proof. intros i1; pattern i1; apply lt_wf_rec; clear i1; intros i1 H1; apply_mutual_ind ty_mutind; default_simp; (* non-trivial cases *) constructor; default_simp; eapply_first_lt_hyp; (* instantiate the size *) match goal with | |- _ = _ => reflexivity | _ => idtac end; instantiate; (* everything should be easy now *) default_simp. Qed. (* end hide *) Lemma lc_ty_of_degree : forall T1, degree_ty_wrt_ty 0 T1 -> lc_ty T1. Proof. intros T1; intros; pose proof (lc_ty_of_degree_size_mutual (size_ty T1)); intuition eauto. Qed. Hint Resolve lc_ty_of_degree : lngen. (* begin hide *) Lemma lc_exp_of_degree_size_mutual : forall i1, (forall e1, size_exp e1 = i1 -> degree_exp_wrt_ty 0 e1 -> degree_exp_wrt_exp 0 e1 -> lc_exp e1). Proof. intros i1; pattern i1; apply lt_wf_rec; clear i1; intros i1 H1; apply_mutual_ind exp_mutind; default_simp; (* non-trivial cases *) constructor; default_simp; eapply_first_lt_hyp; (* instantiate the size *) match goal with | |- _ = _ => reflexivity | _ => idtac end; instantiate; (* everything should be easy now *) default_simp. Qed. (* end hide *) Lemma lc_exp_of_degree : forall e1, degree_exp_wrt_ty 0 e1 -> degree_exp_wrt_exp 0 e1 -> lc_exp e1. Proof. intros e1; intros; pose proof (lc_exp_of_degree_size_mutual (size_exp e1)); intuition eauto. Qed. Hint Resolve lc_exp_of_degree : lngen. Ltac ty_lc_exists_tac := repeat (match goal with | H : _ |- _ => let J1 := fresh in pose proof H as J1; apply degree_ty_wrt_ty_of_lc_ty in J1; clear H end). Ltac co_lc_exists_tac := repeat (match goal with | H : _ |- _ => fail 1 end). Ltac exp_lc_exists_tac := repeat (match goal with | H : _ |- _ => let J1 := fresh in pose proof H as J1; apply degree_exp_wrt_ty_of_lc_exp in J1; let J2 := fresh in pose proof H as J2; apply degree_exp_wrt_exp_of_lc_exp in J2; clear H end). Lemma lc_ty_all_exists : forall X1 T1, lc_ty (open_ty_wrt_ty T1 (ty_var_f X1)) -> lc_ty (ty_all T1). Proof. intros; ty_lc_exists_tac; eauto with lngen. Qed. Lemma lc_exp_abs_exists : forall x1 e1, lc_exp (open_exp_wrt_exp e1 (exp_var_f x1)) -> lc_exp (exp_abs e1). Proof. intros; exp_lc_exists_tac; eauto with lngen. Qed. Lemma lc_exp_tabs_exists : forall X1 e1, lc_exp (open_exp_wrt_ty e1 (ty_var_f X1)) -> lc_exp (exp_tabs e1). Proof. intros; exp_lc_exists_tac; eauto with lngen. Qed. Hint Extern 1 (lc_ty (ty_all _)) => let X1 := fresh in pick_fresh X1; apply (lc_ty_all_exists X1). Hint Extern 1 (lc_exp (exp_abs _)) => let x1 := fresh in pick_fresh x1; apply (lc_exp_abs_exists x1). Hint Extern 1 (lc_exp (exp_tabs _)) => let X1 := fresh in pick_fresh X1; apply (lc_exp_tabs_exists X1). Lemma lc_body_ty_wrt_ty : forall T1 T2, body_ty_wrt_ty T1 -> lc_ty T2 -> lc_ty (open_ty_wrt_ty T1 T2). Proof. unfold body_ty_wrt_ty; default_simp; let X1 := fresh "x" in pick_fresh X1; specialize_all X1; ty_lc_exists_tac; eauto with lngen. Qed. Hint Resolve lc_body_ty_wrt_ty : lngen. Lemma lc_body_exp_wrt_ty : forall e1 T1, body_exp_wrt_ty e1 -> lc_ty T1 -> lc_exp (open_exp_wrt_ty e1 T1). Proof. unfold body_exp_wrt_ty; default_simp; let X1 := fresh "x" in pick_fresh X1; specialize_all X1; exp_lc_exists_tac; eauto with lngen. Qed. Hint Resolve lc_body_exp_wrt_ty : lngen. Lemma lc_body_exp_wrt_exp : forall e1 e2, body_exp_wrt_exp e1 -> lc_exp e2 -> lc_exp (open_exp_wrt_exp e1 e2). Proof. unfold body_exp_wrt_exp; default_simp; let x1 := fresh "x" in pick_fresh x1; specialize_all x1; exp_lc_exists_tac; eauto with lngen. Qed. Hint Resolve lc_body_exp_wrt_exp : lngen. Lemma lc_body_ty_all_1 : forall T1, lc_ty (ty_all T1) -> body_ty_wrt_ty T1. Proof. default_simp. Qed. Hint Resolve lc_body_ty_all_1 : lngen. Lemma lc_body_exp_abs_1 : forall e1, lc_exp (exp_abs e1) -> body_exp_wrt_exp e1. Proof. default_simp. Qed. Hint Resolve lc_body_exp_abs_1 : lngen. Lemma lc_body_exp_tabs_1 : forall e1, lc_exp (exp_tabs e1) -> body_exp_wrt_ty e1. Proof. default_simp. Qed. Hint Resolve lc_body_exp_tabs_1 : lngen. (* begin hide *) Lemma lc_ty_unique_mutual : (forall T1 (proof2 proof3 : lc_ty T1), proof2 = proof3). Proof. apply_mutual_ind lc_ty_mutind; intros; let proof1 := fresh "proof1" in rename_last_into proof1; dependent destruction proof1; f_equal; default_simp; auto using @functional_extensionality_dep with lngen. Qed. (* end hide *) Lemma lc_ty_unique : forall T1 (proof2 proof3 : lc_ty T1), proof2 = proof3. Proof. pose proof lc_ty_unique_mutual as H; intuition eauto. Qed. Hint Resolve lc_ty_unique : lngen. (* begin hide *) Lemma lc_exp_unique_mutual : (forall e1 (proof2 proof3 : lc_exp e1), proof2 = proof3). Proof. apply_mutual_ind lc_exp_mutind; intros; let proof1 := fresh "proof1" in rename_last_into proof1; dependent destruction proof1; f_equal; default_simp; auto using @functional_extensionality_dep with lngen. Qed. (* end hide *) Lemma lc_exp_unique : forall e1 (proof2 proof3 : lc_exp e1), proof2 = proof3. Proof. pose proof lc_exp_unique_mutual as H; intuition eauto. Qed. Hint Resolve lc_exp_unique : lngen. (* begin hide *) Lemma lc_ty_of_lc_set_ty_mutual : (forall T1, lc_set_ty T1 -> lc_ty T1). Proof. apply_mutual_ind lc_set_ty_mutind; default_simp. Qed. (* end hide *) Lemma lc_ty_of_lc_set_ty : forall T1, lc_set_ty T1 -> lc_ty T1. Proof. pose proof lc_ty_of_lc_set_ty_mutual as H; intuition eauto. Qed. Hint Resolve lc_ty_of_lc_set_ty : lngen. (* begin hide *) Lemma lc_exp_of_lc_set_exp_mutual : (forall e1, lc_set_exp e1 -> lc_exp e1). Proof. apply_mutual_ind lc_set_exp_mutind; default_simp. Qed. (* end hide *) Lemma lc_exp_of_lc_set_exp : forall e1, lc_set_exp e1 -> lc_exp e1. Proof. pose proof lc_exp_of_lc_set_exp_mutual as H; intuition eauto. Qed. Hint Resolve lc_exp_of_lc_set_exp : lngen. (* begin hide *) Lemma lc_set_ty_of_lc_ty_size_mutual : forall i1, (forall T1, size_ty T1 = i1 -> lc_ty T1 -> lc_set_ty T1). Proof. intros i1; pattern i1; apply lt_wf_rec; clear i1; intros i1 H1; apply_mutual_ind ty_mutrec; default_simp; try solve [assert False by default_simp; tauto]; (* non-trivial cases *) constructor; default_simp; try first [apply lc_set_ty_of_lc_ty]; default_simp; eapply_first_lt_hyp; (* instantiate the size *) match goal with | |- _ = _ => reflexivity | _ => idtac end; instantiate; (* everything should be easy now *) default_simp. Qed. (* end hide *) Lemma lc_set_ty_of_lc_ty : forall T1, lc_ty T1 -> lc_set_ty T1. Proof. intros T1; intros; pose proof (lc_set_ty_of_lc_ty_size_mutual (size_ty T1)); intuition eauto. Qed. Hint Resolve lc_set_ty_of_lc_ty : lngen. (* begin hide *) Lemma lc_set_exp_of_lc_exp_size_mutual : forall i1, (forall e1, size_exp e1 = i1 -> lc_exp e1 -> lc_set_exp e1). Proof. intros i1; pattern i1; apply lt_wf_rec; clear i1; intros i1 H1; apply_mutual_ind exp_mutrec; default_simp; try solve [assert False by default_simp; tauto]; (* non-trivial cases *) constructor; default_simp; try first [apply lc_set_ty_of_lc_ty | apply lc_set_co_of_lc_co | apply lc_set_exp_of_lc_exp]; default_simp; eapply_first_lt_hyp; (* instantiate the size *) match goal with | |- _ = _ => reflexivity | _ => idtac end; instantiate; (* everything should be easy now *) default_simp. Qed. (* end hide *) Lemma lc_set_exp_of_lc_exp : forall e1, lc_exp e1 -> lc_set_exp e1. Proof. intros e1; intros; pose proof (lc_set_exp_of_lc_exp_size_mutual (size_exp e1)); intuition eauto. Qed. Hint Resolve lc_set_exp_of_lc_exp : lngen. (* *********************************************************************** *) (** * More theorems about [open] and [close] *) Ltac default_auto ::= auto with lngen; tauto. Ltac default_autorewrite ::= fail. (* begin hide *) Lemma close_ty_wrt_ty_rec_degree_ty_wrt_ty_mutual : (forall T1 X1 n1, degree_ty_wrt_ty n1 T1 -> X1 `notin` fv_ty_in_ty T1 -> close_ty_wrt_ty_rec n1 X1 T1 = T1). Proof. apply_mutual_ind ty_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma close_ty_wrt_ty_rec_degree_ty_wrt_ty : forall T1 X1 n1, degree_ty_wrt_ty n1 T1 -> X1 `notin` fv_ty_in_ty T1 -> close_ty_wrt_ty_rec n1 X1 T1 = T1. Proof. pose proof close_ty_wrt_ty_rec_degree_ty_wrt_ty_mutual as H; intuition eauto. Qed. Hint Resolve close_ty_wrt_ty_rec_degree_ty_wrt_ty : lngen. Hint Rewrite close_ty_wrt_ty_rec_degree_ty_wrt_ty using solve [auto] : lngen. (* end hide *) (* begin hide *) Lemma close_exp_wrt_ty_rec_degree_exp_wrt_ty_mutual : (forall e1 X1 n1, degree_exp_wrt_ty n1 e1 -> X1 `notin` fv_ty_in_exp e1 -> close_exp_wrt_ty_rec n1 X1 e1 = e1). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma close_exp_wrt_ty_rec_degree_exp_wrt_ty : forall e1 X1 n1, degree_exp_wrt_ty n1 e1 -> X1 `notin` fv_ty_in_exp e1 -> close_exp_wrt_ty_rec n1 X1 e1 = e1. Proof. pose proof close_exp_wrt_ty_rec_degree_exp_wrt_ty_mutual as H; intuition eauto. Qed. Hint Resolve close_exp_wrt_ty_rec_degree_exp_wrt_ty : lngen. Hint Rewrite close_exp_wrt_ty_rec_degree_exp_wrt_ty using solve [auto] : lngen. (* end hide *) (* begin hide *) Lemma close_exp_wrt_exp_rec_degree_exp_wrt_exp_mutual : (forall e1 x1 n1, degree_exp_wrt_exp n1 e1 -> x1 `notin` fv_exp_in_exp e1 -> close_exp_wrt_exp_rec n1 x1 e1 = e1). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma close_exp_wrt_exp_rec_degree_exp_wrt_exp : forall e1 x1 n1, degree_exp_wrt_exp n1 e1 -> x1 `notin` fv_exp_in_exp e1 -> close_exp_wrt_exp_rec n1 x1 e1 = e1. Proof. pose proof close_exp_wrt_exp_rec_degree_exp_wrt_exp_mutual as H; intuition eauto. Qed. Hint Resolve close_exp_wrt_exp_rec_degree_exp_wrt_exp : lngen. Hint Rewrite close_exp_wrt_exp_rec_degree_exp_wrt_exp using solve [auto] : lngen. (* end hide *) Lemma close_ty_wrt_ty_lc_ty : forall T1 X1, lc_ty T1 -> X1 `notin` fv_ty_in_ty T1 -> close_ty_wrt_ty X1 T1 = T1. Proof. unfold close_ty_wrt_ty; default_simp. Qed. Hint Resolve close_ty_wrt_ty_lc_ty : lngen. Hint Rewrite close_ty_wrt_ty_lc_ty using solve [auto] : lngen. Lemma close_exp_wrt_ty_lc_exp : forall e1 X1, lc_exp e1 -> X1 `notin` fv_ty_in_exp e1 -> close_exp_wrt_ty X1 e1 = e1. Proof. unfold close_exp_wrt_ty; default_simp. Qed. Hint Resolve close_exp_wrt_ty_lc_exp : lngen. Hint Rewrite close_exp_wrt_ty_lc_exp using solve [auto] : lngen. Lemma close_exp_wrt_exp_lc_exp : forall e1 x1, lc_exp e1 -> x1 `notin` fv_exp_in_exp e1 -> close_exp_wrt_exp x1 e1 = e1. Proof. unfold close_exp_wrt_exp; default_simp. Qed. Hint Resolve close_exp_wrt_exp_lc_exp : lngen. Hint Rewrite close_exp_wrt_exp_lc_exp using solve [auto] : lngen. (* begin hide *) Lemma open_ty_wrt_ty_rec_degree_ty_wrt_ty_mutual : (forall T2 T1 n1, degree_ty_wrt_ty n1 T2 -> open_ty_wrt_ty_rec n1 T1 T2 = T2). Proof. apply_mutual_ind ty_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma open_ty_wrt_ty_rec_degree_ty_wrt_ty : forall T2 T1 n1, degree_ty_wrt_ty n1 T2 -> open_ty_wrt_ty_rec n1 T1 T2 = T2. Proof. pose proof open_ty_wrt_ty_rec_degree_ty_wrt_ty_mutual as H; intuition eauto. Qed. Hint Resolve open_ty_wrt_ty_rec_degree_ty_wrt_ty : lngen. Hint Rewrite open_ty_wrt_ty_rec_degree_ty_wrt_ty using solve [auto] : lngen. (* end hide *) (* begin hide *) Lemma open_exp_wrt_ty_rec_degree_exp_wrt_ty_mutual : (forall e1 T1 n1, degree_exp_wrt_ty n1 e1 -> open_exp_wrt_ty_rec n1 T1 e1 = e1). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma open_exp_wrt_ty_rec_degree_exp_wrt_ty : forall e1 T1 n1, degree_exp_wrt_ty n1 e1 -> open_exp_wrt_ty_rec n1 T1 e1 = e1. Proof. pose proof open_exp_wrt_ty_rec_degree_exp_wrt_ty_mutual as H; intuition eauto. Qed. Hint Resolve open_exp_wrt_ty_rec_degree_exp_wrt_ty : lngen. Hint Rewrite open_exp_wrt_ty_rec_degree_exp_wrt_ty using solve [auto] : lngen. (* end hide *) (* begin hide *) Lemma open_exp_wrt_exp_rec_degree_exp_wrt_exp_mutual : (forall e2 e1 n1, degree_exp_wrt_exp n1 e2 -> open_exp_wrt_exp_rec n1 e1 e2 = e2). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma open_exp_wrt_exp_rec_degree_exp_wrt_exp : forall e2 e1 n1, degree_exp_wrt_exp n1 e2 -> open_exp_wrt_exp_rec n1 e1 e2 = e2. Proof. pose proof open_exp_wrt_exp_rec_degree_exp_wrt_exp_mutual as H; intuition eauto. Qed. Hint Resolve open_exp_wrt_exp_rec_degree_exp_wrt_exp : lngen. Hint Rewrite open_exp_wrt_exp_rec_degree_exp_wrt_exp using solve [auto] : lngen. (* end hide *) Lemma open_ty_wrt_ty_lc_ty : forall T2 T1, lc_ty T2 -> open_ty_wrt_ty T2 T1 = T2. Proof. unfold open_ty_wrt_ty; default_simp. Qed. Hint Resolve open_ty_wrt_ty_lc_ty : lngen. Hint Rewrite open_ty_wrt_ty_lc_ty using solve [auto] : lngen. Lemma open_exp_wrt_ty_lc_exp : forall e1 T1, lc_exp e1 -> open_exp_wrt_ty e1 T1 = e1. Proof. unfold open_exp_wrt_ty; default_simp. Qed. Hint Resolve open_exp_wrt_ty_lc_exp : lngen. Hint Rewrite open_exp_wrt_ty_lc_exp using solve [auto] : lngen. Lemma open_exp_wrt_exp_lc_exp : forall e2 e1, lc_exp e2 -> open_exp_wrt_exp e2 e1 = e2. Proof. unfold open_exp_wrt_exp; default_simp. Qed. Hint Resolve open_exp_wrt_exp_lc_exp : lngen. Hint Rewrite open_exp_wrt_exp_lc_exp using solve [auto] : lngen. (* *********************************************************************** *) (** * Theorems about [fv] *) Ltac default_auto ::= auto with set lngen; tauto. Ltac default_autorewrite ::= autorewrite with lngen. (* begin hide *) Lemma fv_ty_in_ty_close_ty_wrt_ty_rec_mutual : (forall T1 X1 n1, fv_ty_in_ty (close_ty_wrt_ty_rec n1 X1 T1) [=] remove X1 (fv_ty_in_ty T1)). Proof. apply_mutual_ind ty_mutind; default_simp; fsetdec. Qed. (* end hide *) (* begin hide *) Lemma fv_ty_in_ty_close_ty_wrt_ty_rec : forall T1 X1 n1, fv_ty_in_ty (close_ty_wrt_ty_rec n1 X1 T1) [=] remove X1 (fv_ty_in_ty T1). Proof. pose proof fv_ty_in_ty_close_ty_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_ty_close_ty_wrt_ty_rec : lngen. Hint Rewrite fv_ty_in_ty_close_ty_wrt_ty_rec using solve [auto] : lngen. (* end hide *) (* begin hide *) Lemma fv_ty_in_exp_close_exp_wrt_ty_rec_mutual : (forall e1 X1 n1, fv_ty_in_exp (close_exp_wrt_ty_rec n1 X1 e1) [=] remove X1 (fv_ty_in_exp e1)). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) (* begin hide *) Lemma fv_ty_in_exp_close_exp_wrt_ty_rec : forall e1 X1 n1, fv_ty_in_exp (close_exp_wrt_ty_rec n1 X1 e1) [=] remove X1 (fv_ty_in_exp e1). Proof. pose proof fv_ty_in_exp_close_exp_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_exp_close_exp_wrt_ty_rec : lngen. Hint Rewrite fv_ty_in_exp_close_exp_wrt_ty_rec using solve [auto] : lngen. (* end hide *) (* begin hide *) Lemma fv_ty_in_exp_close_exp_wrt_exp_rec_mutual : (forall e1 x1 n1, fv_ty_in_exp (close_exp_wrt_exp_rec n1 x1 e1) [=] fv_ty_in_exp e1). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) (* begin hide *) Lemma fv_ty_in_exp_close_exp_wrt_exp_rec : forall e1 x1 n1, fv_ty_in_exp (close_exp_wrt_exp_rec n1 x1 e1) [=] fv_ty_in_exp e1. Proof. pose proof fv_ty_in_exp_close_exp_wrt_exp_rec_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_exp_close_exp_wrt_exp_rec : lngen. Hint Rewrite fv_ty_in_exp_close_exp_wrt_exp_rec using solve [auto] : lngen. (* end hide *) (* begin hide *) Lemma fv_exp_in_exp_close_exp_wrt_ty_rec_mutual : (forall e1 X1 n1, fv_exp_in_exp (close_exp_wrt_ty_rec n1 X1 e1) [=] fv_exp_in_exp e1). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) (* begin hide *) Lemma fv_exp_in_exp_close_exp_wrt_ty_rec : forall e1 X1 n1, fv_exp_in_exp (close_exp_wrt_ty_rec n1 X1 e1) [=] fv_exp_in_exp e1. Proof. pose proof fv_exp_in_exp_close_exp_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve fv_exp_in_exp_close_exp_wrt_ty_rec : lngen. Hint Rewrite fv_exp_in_exp_close_exp_wrt_ty_rec using solve [auto] : lngen. (* end hide *) (* begin hide *) Lemma fv_exp_in_exp_close_exp_wrt_exp_rec_mutual : (forall e1 x1 n1, fv_exp_in_exp (close_exp_wrt_exp_rec n1 x1 e1) [=] remove x1 (fv_exp_in_exp e1)). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) (* begin hide *) Lemma fv_exp_in_exp_close_exp_wrt_exp_rec : forall e1 x1 n1, fv_exp_in_exp (close_exp_wrt_exp_rec n1 x1 e1) [=] remove x1 (fv_exp_in_exp e1). Proof. pose proof fv_exp_in_exp_close_exp_wrt_exp_rec_mutual as H; intuition eauto. Qed. Hint Resolve fv_exp_in_exp_close_exp_wrt_exp_rec : lngen. Hint Rewrite fv_exp_in_exp_close_exp_wrt_exp_rec using solve [auto] : lngen. (* end hide *) Lemma fv_ty_in_ty_close_ty_wrt_ty : forall T1 X1, fv_ty_in_ty (close_ty_wrt_ty X1 T1) [=] remove X1 (fv_ty_in_ty T1). Proof. unfold close_ty_wrt_ty; default_simp. Qed. Hint Resolve fv_ty_in_ty_close_ty_wrt_ty : lngen. Hint Rewrite fv_ty_in_ty_close_ty_wrt_ty using solve [auto] : lngen. Lemma fv_ty_in_exp_close_exp_wrt_ty : forall e1 X1, fv_ty_in_exp (close_exp_wrt_ty X1 e1) [=] remove X1 (fv_ty_in_exp e1). Proof. unfold close_exp_wrt_ty; default_simp. Qed. Hint Resolve fv_ty_in_exp_close_exp_wrt_ty : lngen. Hint Rewrite fv_ty_in_exp_close_exp_wrt_ty using solve [auto] : lngen. Lemma fv_ty_in_exp_close_exp_wrt_exp : forall e1 x1, fv_ty_in_exp (close_exp_wrt_exp x1 e1) [=] fv_ty_in_exp e1. Proof. unfold close_exp_wrt_exp; default_simp. Qed. Hint Resolve fv_ty_in_exp_close_exp_wrt_exp : lngen. Hint Rewrite fv_ty_in_exp_close_exp_wrt_exp using solve [auto] : lngen. Lemma fv_exp_in_exp_close_exp_wrt_ty : forall e1 X1, fv_exp_in_exp (close_exp_wrt_ty X1 e1) [=] fv_exp_in_exp e1. Proof. unfold close_exp_wrt_ty; default_simp. Qed. Hint Resolve fv_exp_in_exp_close_exp_wrt_ty : lngen. Hint Rewrite fv_exp_in_exp_close_exp_wrt_ty using solve [auto] : lngen. Lemma fv_exp_in_exp_close_exp_wrt_exp : forall e1 x1, fv_exp_in_exp (close_exp_wrt_exp x1 e1) [=] remove x1 (fv_exp_in_exp e1). Proof. unfold close_exp_wrt_exp; default_simp. Qed. Hint Resolve fv_exp_in_exp_close_exp_wrt_exp : lngen. Hint Rewrite fv_exp_in_exp_close_exp_wrt_exp using solve [auto] : lngen. (* begin hide *) Lemma fv_ty_in_ty_open_ty_wrt_ty_rec_lower_mutual : (forall T1 T2 n1, fv_ty_in_ty T1 [<=] fv_ty_in_ty (open_ty_wrt_ty_rec n1 T2 T1)). Proof. apply_mutual_ind ty_mutind; default_simp; fsetdec. Qed. (* end hide *) (* begin hide *) Lemma fv_ty_in_ty_open_ty_wrt_ty_rec_lower : forall T1 T2 n1, fv_ty_in_ty T1 [<=] fv_ty_in_ty (open_ty_wrt_ty_rec n1 T2 T1). Proof. pose proof fv_ty_in_ty_open_ty_wrt_ty_rec_lower_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_ty_open_ty_wrt_ty_rec_lower : lngen. (* end hide *) (* begin hide *) Lemma fv_ty_in_exp_open_exp_wrt_ty_rec_lower_mutual : (forall e1 T1 n1, fv_ty_in_exp e1 [<=] fv_ty_in_exp (open_exp_wrt_ty_rec n1 T1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) (* begin hide *) Lemma fv_ty_in_exp_open_exp_wrt_ty_rec_lower : forall e1 T1 n1, fv_ty_in_exp e1 [<=] fv_ty_in_exp (open_exp_wrt_ty_rec n1 T1 e1). Proof. pose proof fv_ty_in_exp_open_exp_wrt_ty_rec_lower_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_exp_open_exp_wrt_ty_rec_lower : lngen. (* end hide *) (* begin hide *) Lemma fv_ty_in_exp_open_exp_wrt_exp_rec_lower_mutual : (forall e1 e2 n1, fv_ty_in_exp e1 [<=] fv_ty_in_exp (open_exp_wrt_exp_rec n1 e2 e1)). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) (* begin hide *) Lemma fv_ty_in_exp_open_exp_wrt_exp_rec_lower : forall e1 e2 n1, fv_ty_in_exp e1 [<=] fv_ty_in_exp (open_exp_wrt_exp_rec n1 e2 e1). Proof. pose proof fv_ty_in_exp_open_exp_wrt_exp_rec_lower_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_exp_open_exp_wrt_exp_rec_lower : lngen. (* end hide *) (* begin hide *) Lemma fv_exp_in_exp_open_exp_wrt_ty_rec_lower_mutual : (forall e1 T1 n1, fv_exp_in_exp e1 [<=] fv_exp_in_exp (open_exp_wrt_ty_rec n1 T1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) (* begin hide *) Lemma fv_exp_in_exp_open_exp_wrt_ty_rec_lower : forall e1 T1 n1, fv_exp_in_exp e1 [<=] fv_exp_in_exp (open_exp_wrt_ty_rec n1 T1 e1). Proof. pose proof fv_exp_in_exp_open_exp_wrt_ty_rec_lower_mutual as H; intuition eauto. Qed. Hint Resolve fv_exp_in_exp_open_exp_wrt_ty_rec_lower : lngen. (* end hide *) (* begin hide *) Lemma fv_exp_in_exp_open_exp_wrt_exp_rec_lower_mutual : (forall e1 e2 n1, fv_exp_in_exp e1 [<=] fv_exp_in_exp (open_exp_wrt_exp_rec n1 e2 e1)). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) (* begin hide *) Lemma fv_exp_in_exp_open_exp_wrt_exp_rec_lower : forall e1 e2 n1, fv_exp_in_exp e1 [<=] fv_exp_in_exp (open_exp_wrt_exp_rec n1 e2 e1). Proof. pose proof fv_exp_in_exp_open_exp_wrt_exp_rec_lower_mutual as H; intuition eauto. Qed. Hint Resolve fv_exp_in_exp_open_exp_wrt_exp_rec_lower : lngen. (* end hide *) Lemma fv_ty_in_ty_open_ty_wrt_ty_lower : forall T1 T2, fv_ty_in_ty T1 [<=] fv_ty_in_ty (open_ty_wrt_ty T1 T2). Proof. unfold open_ty_wrt_ty; default_simp. Qed. Hint Resolve fv_ty_in_ty_open_ty_wrt_ty_lower : lngen. Lemma fv_ty_in_exp_open_exp_wrt_ty_lower : forall e1 T1, fv_ty_in_exp e1 [<=] fv_ty_in_exp (open_exp_wrt_ty e1 T1). Proof. unfold open_exp_wrt_ty; default_simp. Qed. Hint Resolve fv_ty_in_exp_open_exp_wrt_ty_lower : lngen. Lemma fv_ty_in_exp_open_exp_wrt_exp_lower : forall e1 e2, fv_ty_in_exp e1 [<=] fv_ty_in_exp (open_exp_wrt_exp e1 e2). Proof. unfold open_exp_wrt_exp; default_simp. Qed. Hint Resolve fv_ty_in_exp_open_exp_wrt_exp_lower : lngen. Lemma fv_exp_in_exp_open_exp_wrt_ty_lower : forall e1 T1, fv_exp_in_exp e1 [<=] fv_exp_in_exp (open_exp_wrt_ty e1 T1). Proof. unfold open_exp_wrt_ty; default_simp. Qed. Hint Resolve fv_exp_in_exp_open_exp_wrt_ty_lower : lngen. Lemma fv_exp_in_exp_open_exp_wrt_exp_lower : forall e1 e2, fv_exp_in_exp e1 [<=] fv_exp_in_exp (open_exp_wrt_exp e1 e2). Proof. unfold open_exp_wrt_exp; default_simp. Qed. Hint Resolve fv_exp_in_exp_open_exp_wrt_exp_lower : lngen. (* begin hide *) Lemma fv_ty_in_ty_open_ty_wrt_ty_rec_upper_mutual : (forall T1 T2 n1, fv_ty_in_ty (open_ty_wrt_ty_rec n1 T2 T1) [<=] fv_ty_in_ty T2 `union` fv_ty_in_ty T1). Proof. apply_mutual_ind ty_mutind; default_simp; fsetdec. Qed. (* end hide *) (* begin hide *) Lemma fv_ty_in_ty_open_ty_wrt_ty_rec_upper : forall T1 T2 n1, fv_ty_in_ty (open_ty_wrt_ty_rec n1 T2 T1) [<=] fv_ty_in_ty T2 `union` fv_ty_in_ty T1. Proof. pose proof fv_ty_in_ty_open_ty_wrt_ty_rec_upper_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_ty_open_ty_wrt_ty_rec_upper : lngen. (* end hide *) (* begin hide *) Lemma fv_ty_in_exp_open_exp_wrt_ty_rec_upper_mutual : (forall e1 T1 n1, fv_ty_in_exp (open_exp_wrt_ty_rec n1 T1 e1) [<=] fv_ty_in_ty T1 `union` fv_ty_in_exp e1). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) (* begin hide *) Lemma fv_ty_in_exp_open_exp_wrt_ty_rec_upper : forall e1 T1 n1, fv_ty_in_exp (open_exp_wrt_ty_rec n1 T1 e1) [<=] fv_ty_in_ty T1 `union` fv_ty_in_exp e1. Proof. pose proof fv_ty_in_exp_open_exp_wrt_ty_rec_upper_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_exp_open_exp_wrt_ty_rec_upper : lngen. (* end hide *) (* begin hide *) Lemma fv_ty_in_exp_open_exp_wrt_exp_rec_upper_mutual : (forall e1 e2 n1, fv_ty_in_exp (open_exp_wrt_exp_rec n1 e2 e1) [<=] fv_ty_in_exp e2 `union` fv_ty_in_exp e1). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) (* begin hide *) Lemma fv_ty_in_exp_open_exp_wrt_exp_rec_upper : forall e1 e2 n1, fv_ty_in_exp (open_exp_wrt_exp_rec n1 e2 e1) [<=] fv_ty_in_exp e2 `union` fv_ty_in_exp e1. Proof. pose proof fv_ty_in_exp_open_exp_wrt_exp_rec_upper_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_exp_open_exp_wrt_exp_rec_upper : lngen. (* end hide *) (* begin hide *) Lemma fv_exp_in_exp_open_exp_wrt_ty_rec_upper_mutual : (forall e1 T1 n1, fv_exp_in_exp (open_exp_wrt_ty_rec n1 T1 e1) [<=] fv_exp_in_exp e1). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) (* begin hide *) Lemma fv_exp_in_exp_open_exp_wrt_ty_rec_upper : forall e1 T1 n1, fv_exp_in_exp (open_exp_wrt_ty_rec n1 T1 e1) [<=] fv_exp_in_exp e1. Proof. pose proof fv_exp_in_exp_open_exp_wrt_ty_rec_upper_mutual as H; intuition eauto. Qed. Hint Resolve fv_exp_in_exp_open_exp_wrt_ty_rec_upper : lngen. (* end hide *) (* begin hide *) Lemma fv_exp_in_exp_open_exp_wrt_exp_rec_upper_mutual : (forall e1 e2 n1, fv_exp_in_exp (open_exp_wrt_exp_rec n1 e2 e1) [<=] fv_exp_in_exp e2 `union` fv_exp_in_exp e1). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) (* begin hide *) Lemma fv_exp_in_exp_open_exp_wrt_exp_rec_upper : forall e1 e2 n1, fv_exp_in_exp (open_exp_wrt_exp_rec n1 e2 e1) [<=] fv_exp_in_exp e2 `union` fv_exp_in_exp e1. Proof. pose proof fv_exp_in_exp_open_exp_wrt_exp_rec_upper_mutual as H; intuition eauto. Qed. Hint Resolve fv_exp_in_exp_open_exp_wrt_exp_rec_upper : lngen. (* end hide *) Lemma fv_ty_in_ty_open_ty_wrt_ty_upper : forall T1 T2, fv_ty_in_ty (open_ty_wrt_ty T1 T2) [<=] fv_ty_in_ty T2 `union` fv_ty_in_ty T1. Proof. unfold open_ty_wrt_ty; default_simp. Qed. Hint Resolve fv_ty_in_ty_open_ty_wrt_ty_upper : lngen. Lemma fv_ty_in_exp_open_exp_wrt_ty_upper : forall e1 T1, fv_ty_in_exp (open_exp_wrt_ty e1 T1) [<=] fv_ty_in_ty T1 `union` fv_ty_in_exp e1. Proof. unfold open_exp_wrt_ty; default_simp. Qed. Hint Resolve fv_ty_in_exp_open_exp_wrt_ty_upper : lngen. Lemma fv_ty_in_exp_open_exp_wrt_exp_upper : forall e1 e2, fv_ty_in_exp (open_exp_wrt_exp e1 e2) [<=] fv_ty_in_exp e2 `union` fv_ty_in_exp e1. Proof. unfold open_exp_wrt_exp; default_simp. Qed. Hint Resolve fv_ty_in_exp_open_exp_wrt_exp_upper : lngen. Lemma fv_exp_in_exp_open_exp_wrt_ty_upper : forall e1 T1, fv_exp_in_exp (open_exp_wrt_ty e1 T1) [<=] fv_exp_in_exp e1. Proof. unfold open_exp_wrt_ty; default_simp. Qed. Hint Resolve fv_exp_in_exp_open_exp_wrt_ty_upper : lngen. Lemma fv_exp_in_exp_open_exp_wrt_exp_upper : forall e1 e2, fv_exp_in_exp (open_exp_wrt_exp e1 e2) [<=] fv_exp_in_exp e2 `union` fv_exp_in_exp e1. Proof. unfold open_exp_wrt_exp; default_simp. Qed. Hint Resolve fv_exp_in_exp_open_exp_wrt_exp_upper : lngen. (* begin hide *) Lemma fv_ty_in_ty_subst_ty_in_ty_fresh_mutual : (forall T1 T2 X1, X1 `notin` fv_ty_in_ty T1 -> fv_ty_in_ty (subst_ty_in_ty T2 X1 T1) [=] fv_ty_in_ty T1). Proof. apply_mutual_ind ty_mutind; default_simp; fsetdec. Qed. (* end hide *) Lemma fv_ty_in_ty_subst_ty_in_ty_fresh : forall T1 T2 X1, X1 `notin` fv_ty_in_ty T1 -> fv_ty_in_ty (subst_ty_in_ty T2 X1 T1) [=] fv_ty_in_ty T1. Proof. pose proof fv_ty_in_ty_subst_ty_in_ty_fresh_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_ty_subst_ty_in_ty_fresh : lngen. Hint Rewrite fv_ty_in_ty_subst_ty_in_ty_fresh using solve [auto] : lngen. (* begin hide *) Lemma fv_ty_in_exp_subst_ty_in_exp_fresh_mutual : (forall e1 T1 X1, X1 `notin` fv_ty_in_exp e1 -> fv_ty_in_exp (subst_ty_in_exp T1 X1 e1) [=] fv_ty_in_exp e1). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) Lemma fv_ty_in_exp_subst_ty_in_exp_fresh : forall e1 T1 X1, X1 `notin` fv_ty_in_exp e1 -> fv_ty_in_exp (subst_ty_in_exp T1 X1 e1) [=] fv_ty_in_exp e1. Proof. pose proof fv_ty_in_exp_subst_ty_in_exp_fresh_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_exp_subst_ty_in_exp_fresh : lngen. Hint Rewrite fv_ty_in_exp_subst_ty_in_exp_fresh using solve [auto] : lngen. (* begin hide *) Lemma fv_ty_in_exp_subst_exp_in_exp_fresh_mutual : (forall e1 T1 X1, fv_exp_in_exp (subst_ty_in_exp T1 X1 e1) [=] fv_exp_in_exp e1). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) Lemma fv_ty_in_exp_subst_exp_in_exp_fresh : forall e1 T1 X1, fv_exp_in_exp (subst_ty_in_exp T1 X1 e1) [=] fv_exp_in_exp e1. Proof. pose proof fv_ty_in_exp_subst_exp_in_exp_fresh_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_exp_subst_exp_in_exp_fresh : lngen. Hint Rewrite fv_ty_in_exp_subst_exp_in_exp_fresh using solve [auto] : lngen. (* begin hide *) Lemma fv_exp_in_exp_subst_exp_in_exp_fresh_mutual : (forall e1 e2 x1, x1 `notin` fv_exp_in_exp e1 -> fv_exp_in_exp (subst_exp_in_exp e2 x1 e1) [=] fv_exp_in_exp e1). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) Lemma fv_exp_in_exp_subst_exp_in_exp_fresh : forall e1 e2 x1, x1 `notin` fv_exp_in_exp e1 -> fv_exp_in_exp (subst_exp_in_exp e2 x1 e1) [=] fv_exp_in_exp e1. Proof. pose proof fv_exp_in_exp_subst_exp_in_exp_fresh_mutual as H; intuition eauto. Qed. Hint Resolve fv_exp_in_exp_subst_exp_in_exp_fresh : lngen. Hint Rewrite fv_exp_in_exp_subst_exp_in_exp_fresh using solve [auto] : lngen. (* begin hide *) Lemma fv_ty_in_ty_subst_ty_in_ty_lower_mutual : (forall T1 T2 X1, remove X1 (fv_ty_in_ty T1) [<=] fv_ty_in_ty (subst_ty_in_ty T2 X1 T1)). Proof. apply_mutual_ind ty_mutind; default_simp; fsetdec. Qed. (* end hide *) Lemma fv_ty_in_ty_subst_ty_in_ty_lower : forall T1 T2 X1, remove X1 (fv_ty_in_ty T1) [<=] fv_ty_in_ty (subst_ty_in_ty T2 X1 T1). Proof. pose proof fv_ty_in_ty_subst_ty_in_ty_lower_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_ty_subst_ty_in_ty_lower : lngen. (* begin hide *) Lemma fv_ty_in_exp_subst_ty_in_exp_lower_mutual : (forall e1 T1 X1, remove X1 (fv_ty_in_exp e1) [<=] fv_ty_in_exp (subst_ty_in_exp T1 X1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) Lemma fv_ty_in_exp_subst_ty_in_exp_lower : forall e1 T1 X1, remove X1 (fv_ty_in_exp e1) [<=] fv_ty_in_exp (subst_ty_in_exp T1 X1 e1). Proof. pose proof fv_ty_in_exp_subst_ty_in_exp_lower_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_exp_subst_ty_in_exp_lower : lngen. (* begin hide *) Lemma fv_ty_in_exp_subst_exp_in_exp_lower_mutual : (forall e1 e2 x1, fv_ty_in_exp e1 [<=] fv_ty_in_exp (subst_exp_in_exp e2 x1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) Lemma fv_ty_in_exp_subst_exp_in_exp_lower : forall e1 e2 x1, fv_ty_in_exp e1 [<=] fv_ty_in_exp (subst_exp_in_exp e2 x1 e1). Proof. pose proof fv_ty_in_exp_subst_exp_in_exp_lower_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_exp_subst_exp_in_exp_lower : lngen. (* begin hide *) Lemma fv_exp_in_exp_subst_ty_in_exp_lower_mutual : (forall e1 T1 X1, fv_exp_in_exp e1 [<=] fv_exp_in_exp (subst_ty_in_exp T1 X1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) Lemma fv_exp_in_exp_subst_ty_in_exp_lower : forall e1 T1 X1, fv_exp_in_exp e1 [<=] fv_exp_in_exp (subst_ty_in_exp T1 X1 e1). Proof. pose proof fv_exp_in_exp_subst_ty_in_exp_lower_mutual as H; intuition eauto. Qed. Hint Resolve fv_exp_in_exp_subst_ty_in_exp_lower : lngen. (* begin hide *) Lemma fv_exp_in_exp_subst_exp_in_exp_lower_mutual : (forall e1 e2 x1, remove x1 (fv_exp_in_exp e1) [<=] fv_exp_in_exp (subst_exp_in_exp e2 x1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) Lemma fv_exp_in_exp_subst_exp_in_exp_lower : forall e1 e2 x1, remove x1 (fv_exp_in_exp e1) [<=] fv_exp_in_exp (subst_exp_in_exp e2 x1 e1). Proof. pose proof fv_exp_in_exp_subst_exp_in_exp_lower_mutual as H; intuition eauto. Qed. Hint Resolve fv_exp_in_exp_subst_exp_in_exp_lower : lngen. (* begin hide *) Lemma fv_ty_in_ty_subst_ty_in_ty_notin_mutual : (forall T1 T2 X1 X2, X2 `notin` fv_ty_in_ty T1 -> X2 `notin` fv_ty_in_ty T2 -> X2 `notin` fv_ty_in_ty (subst_ty_in_ty T2 X1 T1)). Proof. apply_mutual_ind ty_mutind; default_simp; fsetdec. Qed. (* end hide *) Lemma fv_ty_in_ty_subst_ty_in_ty_notin : forall T1 T2 X1 X2, X2 `notin` fv_ty_in_ty T1 -> X2 `notin` fv_ty_in_ty T2 -> X2 `notin` fv_ty_in_ty (subst_ty_in_ty T2 X1 T1). Proof. pose proof fv_ty_in_ty_subst_ty_in_ty_notin_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_ty_subst_ty_in_ty_notin : lngen. (* begin hide *) Lemma fv_ty_in_exp_subst_ty_in_exp_notin_mutual : (forall e1 T1 X1 X2, X2 `notin` fv_ty_in_exp e1 -> X2 `notin` fv_ty_in_ty T1 -> X2 `notin` fv_ty_in_exp (subst_ty_in_exp T1 X1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) Lemma fv_ty_in_exp_subst_ty_in_exp_notin : forall e1 T1 X1 X2, X2 `notin` fv_ty_in_exp e1 -> X2 `notin` fv_ty_in_ty T1 -> X2 `notin` fv_ty_in_exp (subst_ty_in_exp T1 X1 e1). Proof. pose proof fv_ty_in_exp_subst_ty_in_exp_notin_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_exp_subst_ty_in_exp_notin : lngen. (* begin hide *) Lemma fv_ty_in_exp_subst_exp_in_exp_notin_mutual : (forall e1 e2 x1 X1, X1 `notin` fv_ty_in_exp e1 -> X1 `notin` fv_ty_in_exp e2 -> X1 `notin` fv_ty_in_exp (subst_exp_in_exp e2 x1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) Lemma fv_ty_in_exp_subst_exp_in_exp_notin : forall e1 e2 x1 X1, X1 `notin` fv_ty_in_exp e1 -> X1 `notin` fv_ty_in_exp e2 -> X1 `notin` fv_ty_in_exp (subst_exp_in_exp e2 x1 e1). Proof. pose proof fv_ty_in_exp_subst_exp_in_exp_notin_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_exp_subst_exp_in_exp_notin : lngen. (* begin hide *) Lemma fv_exp_in_exp_subst_ty_in_exp_notin_mutual : (forall e1 T1 X1 x1, x1 `notin` fv_exp_in_exp e1 -> x1 `notin` fv_exp_in_exp (subst_ty_in_exp T1 X1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) Lemma fv_exp_in_exp_subst_ty_in_exp_notin : forall e1 T1 X1 x1, x1 `notin` fv_exp_in_exp e1 -> x1 `notin` fv_exp_in_exp (subst_ty_in_exp T1 X1 e1). Proof. pose proof fv_exp_in_exp_subst_ty_in_exp_notin_mutual as H; intuition eauto. Qed. Hint Resolve fv_exp_in_exp_subst_ty_in_exp_notin : lngen. (* begin hide *) Lemma fv_exp_in_exp_subst_exp_in_exp_notin_mutual : (forall e1 e2 x1 x2, x2 `notin` fv_exp_in_exp e1 -> x2 `notin` fv_exp_in_exp e2 -> x2 `notin` fv_exp_in_exp (subst_exp_in_exp e2 x1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) Lemma fv_exp_in_exp_subst_exp_in_exp_notin : forall e1 e2 x1 x2, x2 `notin` fv_exp_in_exp e1 -> x2 `notin` fv_exp_in_exp e2 -> x2 `notin` fv_exp_in_exp (subst_exp_in_exp e2 x1 e1). Proof. pose proof fv_exp_in_exp_subst_exp_in_exp_notin_mutual as H; intuition eauto. Qed. Hint Resolve fv_exp_in_exp_subst_exp_in_exp_notin : lngen. (* begin hide *) Lemma fv_ty_in_ty_subst_ty_in_ty_upper_mutual : (forall T1 T2 X1, fv_ty_in_ty (subst_ty_in_ty T2 X1 T1) [<=] fv_ty_in_ty T2 `union` remove X1 (fv_ty_in_ty T1)). Proof. apply_mutual_ind ty_mutind; default_simp; fsetdec. Qed. (* end hide *) Lemma fv_ty_in_ty_subst_ty_in_ty_upper : forall T1 T2 X1, fv_ty_in_ty (subst_ty_in_ty T2 X1 T1) [<=] fv_ty_in_ty T2 `union` remove X1 (fv_ty_in_ty T1). Proof. pose proof fv_ty_in_ty_subst_ty_in_ty_upper_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_ty_subst_ty_in_ty_upper : lngen. (* begin hide *) Lemma fv_ty_in_exp_subst_ty_in_exp_upper_mutual : (forall e1 T1 X1, fv_ty_in_exp (subst_ty_in_exp T1 X1 e1) [<=] fv_ty_in_ty T1 `union` remove X1 (fv_ty_in_exp e1)). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) Lemma fv_ty_in_exp_subst_ty_in_exp_upper : forall e1 T1 X1, fv_ty_in_exp (subst_ty_in_exp T1 X1 e1) [<=] fv_ty_in_ty T1 `union` remove X1 (fv_ty_in_exp e1). Proof. pose proof fv_ty_in_exp_subst_ty_in_exp_upper_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_exp_subst_ty_in_exp_upper : lngen. (* begin hide *) Lemma fv_ty_in_exp_subst_exp_in_exp_upper_mutual : (forall e1 e2 x1, fv_ty_in_exp (subst_exp_in_exp e2 x1 e1) [<=] fv_ty_in_exp e2 `union` fv_ty_in_exp e1). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) Lemma fv_ty_in_exp_subst_exp_in_exp_upper : forall e1 e2 x1, fv_ty_in_exp (subst_exp_in_exp e2 x1 e1) [<=] fv_ty_in_exp e2 `union` fv_ty_in_exp e1. Proof. pose proof fv_ty_in_exp_subst_exp_in_exp_upper_mutual as H; intuition eauto. Qed. Hint Resolve fv_ty_in_exp_subst_exp_in_exp_upper : lngen. (* begin hide *) Lemma fv_exp_in_exp_subst_ty_in_exp_upper_mutual : (forall e1 T1 X1, fv_exp_in_exp (subst_ty_in_exp T1 X1 e1) [<=] fv_exp_in_exp e1). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) Lemma fv_exp_in_exp_subst_ty_in_exp_upper : forall e1 T1 X1, fv_exp_in_exp (subst_ty_in_exp T1 X1 e1) [<=] fv_exp_in_exp e1. Proof. pose proof fv_exp_in_exp_subst_ty_in_exp_upper_mutual as H; intuition eauto. Qed. Hint Resolve fv_exp_in_exp_subst_ty_in_exp_upper : lngen. (* begin hide *) Lemma fv_exp_in_exp_subst_exp_in_exp_upper_mutual : (forall e1 e2 x1, fv_exp_in_exp (subst_exp_in_exp e2 x1 e1) [<=] fv_exp_in_exp e2 `union` remove x1 (fv_exp_in_exp e1)). Proof. apply_mutual_ind exp_mutind; default_simp; fsetdec. Qed. (* end hide *) Lemma fv_exp_in_exp_subst_exp_in_exp_upper : forall e1 e2 x1, fv_exp_in_exp (subst_exp_in_exp e2 x1 e1) [<=] fv_exp_in_exp e2 `union` remove x1 (fv_exp_in_exp e1). Proof. pose proof fv_exp_in_exp_subst_exp_in_exp_upper_mutual as H; intuition eauto. Qed. Hint Resolve fv_exp_in_exp_subst_exp_in_exp_upper : lngen. (* *********************************************************************** *) (** * Theorems about [subst] *) Ltac default_auto ::= auto with lngen brute_force; tauto. Ltac default_autorewrite ::= autorewrite with lngen. (* begin hide *) Lemma subst_ty_in_ty_close_ty_wrt_ty_rec_mutual : (forall T2 T1 X1 X2 n1, degree_ty_wrt_ty n1 T1 -> X1 <> X2 -> X2 `notin` fv_ty_in_ty T1 -> subst_ty_in_ty T1 X1 (close_ty_wrt_ty_rec n1 X2 T2) = close_ty_wrt_ty_rec n1 X2 (subst_ty_in_ty T1 X1 T2)). Proof. apply_mutual_ind ty_mutind; default_simp. Qed. (* end hide *) Lemma subst_ty_in_ty_close_ty_wrt_ty_rec : forall T2 T1 X1 X2 n1, degree_ty_wrt_ty n1 T1 -> X1 <> X2 -> X2 `notin` fv_ty_in_ty T1 -> subst_ty_in_ty T1 X1 (close_ty_wrt_ty_rec n1 X2 T2) = close_ty_wrt_ty_rec n1 X2 (subst_ty_in_ty T1 X1 T2). Proof. pose proof subst_ty_in_ty_close_ty_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_ty_close_ty_wrt_ty_rec : lngen. (* begin hide *) Lemma subst_ty_in_exp_close_exp_wrt_ty_rec_mutual : (forall e1 T1 X1 X2 n1, degree_ty_wrt_ty n1 T1 -> X1 <> X2 -> X2 `notin` fv_ty_in_ty T1 -> subst_ty_in_exp T1 X1 (close_exp_wrt_ty_rec n1 X2 e1) = close_exp_wrt_ty_rec n1 X2 (subst_ty_in_exp T1 X1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_ty_in_exp_close_exp_wrt_ty_rec : forall e1 T1 X1 X2 n1, degree_ty_wrt_ty n1 T1 -> X1 <> X2 -> X2 `notin` fv_ty_in_ty T1 -> subst_ty_in_exp T1 X1 (close_exp_wrt_ty_rec n1 X2 e1) = close_exp_wrt_ty_rec n1 X2 (subst_ty_in_exp T1 X1 e1). Proof. pose proof subst_ty_in_exp_close_exp_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_exp_close_exp_wrt_ty_rec : lngen. (* begin hide *) Lemma subst_ty_in_exp_close_exp_wrt_exp_rec_mutual : (forall e1 T1 x1 X1 n1, subst_ty_in_exp T1 x1 (close_exp_wrt_exp_rec n1 X1 e1) = close_exp_wrt_exp_rec n1 X1 (subst_ty_in_exp T1 x1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_ty_in_exp_close_exp_wrt_exp_rec : forall e1 T1 x1 X1 n1, subst_ty_in_exp T1 x1 (close_exp_wrt_exp_rec n1 X1 e1) = close_exp_wrt_exp_rec n1 X1 (subst_ty_in_exp T1 x1 e1). Proof. pose proof subst_ty_in_exp_close_exp_wrt_exp_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_exp_close_exp_wrt_exp_rec : lngen. (* begin hide *) Lemma subst_exp_in_exp_close_exp_wrt_ty_rec_mutual : (forall e2 e1 X1 x1 n1, degree_exp_wrt_ty n1 e1 -> x1 `notin` fv_ty_in_exp e1 -> subst_exp_in_exp e1 X1 (close_exp_wrt_ty_rec n1 x1 e2) = close_exp_wrt_ty_rec n1 x1 (subst_exp_in_exp e1 X1 e2)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_exp_in_exp_close_exp_wrt_ty_rec : forall e2 e1 X1 x1 n1, degree_exp_wrt_ty n1 e1 -> x1 `notin` fv_ty_in_exp e1 -> subst_exp_in_exp e1 X1 (close_exp_wrt_ty_rec n1 x1 e2) = close_exp_wrt_ty_rec n1 x1 (subst_exp_in_exp e1 X1 e2). Proof. pose proof subst_exp_in_exp_close_exp_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_exp_in_exp_close_exp_wrt_ty_rec : lngen. (* begin hide *) Lemma subst_exp_in_exp_close_exp_wrt_exp_rec_mutual : (forall e2 e1 x1 x2 n1, degree_exp_wrt_exp n1 e1 -> x1 <> x2 -> x2 `notin` fv_exp_in_exp e1 -> subst_exp_in_exp e1 x1 (close_exp_wrt_exp_rec n1 x2 e2) = close_exp_wrt_exp_rec n1 x2 (subst_exp_in_exp e1 x1 e2)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_exp_in_exp_close_exp_wrt_exp_rec : forall e2 e1 x1 x2 n1, degree_exp_wrt_exp n1 e1 -> x1 <> x2 -> x2 `notin` fv_exp_in_exp e1 -> subst_exp_in_exp e1 x1 (close_exp_wrt_exp_rec n1 x2 e2) = close_exp_wrt_exp_rec n1 x2 (subst_exp_in_exp e1 x1 e2). Proof. pose proof subst_exp_in_exp_close_exp_wrt_exp_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_exp_in_exp_close_exp_wrt_exp_rec : lngen. Lemma subst_ty_in_ty_close_ty_wrt_ty : forall T2 T1 X1 X2, lc_ty T1 -> X1 <> X2 -> X2 `notin` fv_ty_in_ty T1 -> subst_ty_in_ty T1 X1 (close_ty_wrt_ty X2 T2) = close_ty_wrt_ty X2 (subst_ty_in_ty T1 X1 T2). Proof. unfold close_ty_wrt_ty; default_simp. Qed. Hint Resolve subst_ty_in_ty_close_ty_wrt_ty : lngen. Lemma subst_ty_in_exp_close_exp_wrt_ty : forall e1 T1 X1 X2, lc_ty T1 -> X1 <> X2 -> X2 `notin` fv_ty_in_ty T1 -> subst_ty_in_exp T1 X1 (close_exp_wrt_ty X2 e1) = close_exp_wrt_ty X2 (subst_ty_in_exp T1 X1 e1). Proof. unfold close_exp_wrt_ty; default_simp. Qed. Hint Resolve subst_ty_in_exp_close_exp_wrt_ty : lngen. Lemma subst_ty_in_exp_close_exp_wrt_exp : forall e1 T1 x1 X1, lc_ty T1 -> subst_ty_in_exp T1 x1 (close_exp_wrt_exp X1 e1) = close_exp_wrt_exp X1 (subst_ty_in_exp T1 x1 e1). Proof. unfold close_exp_wrt_exp; default_simp. Qed. Hint Resolve subst_ty_in_exp_close_exp_wrt_exp : lngen. Lemma subst_exp_in_exp_close_exp_wrt_ty : forall e2 e1 X1 x1, lc_exp e1 -> x1 `notin` fv_ty_in_exp e1 -> subst_exp_in_exp e1 X1 (close_exp_wrt_ty x1 e2) = close_exp_wrt_ty x1 (subst_exp_in_exp e1 X1 e2). Proof. unfold close_exp_wrt_ty; default_simp. Qed. Hint Resolve subst_exp_in_exp_close_exp_wrt_ty : lngen. Lemma subst_exp_in_exp_close_exp_wrt_exp : forall e2 e1 x1 x2, lc_exp e1 -> x1 <> x2 -> x2 `notin` fv_exp_in_exp e1 -> subst_exp_in_exp e1 x1 (close_exp_wrt_exp x2 e2) = close_exp_wrt_exp x2 (subst_exp_in_exp e1 x1 e2). Proof. unfold close_exp_wrt_exp; default_simp. Qed. Hint Resolve subst_exp_in_exp_close_exp_wrt_exp : lngen. (* begin hide *) Lemma subst_ty_in_ty_degree_ty_wrt_ty_mutual : (forall T1 T2 X1 n1, degree_ty_wrt_ty n1 T1 -> degree_ty_wrt_ty n1 T2 -> degree_ty_wrt_ty n1 (subst_ty_in_ty T2 X1 T1)). Proof. apply_mutual_ind ty_mutind; default_simp. Qed. (* end hide *) Lemma subst_ty_in_ty_degree_ty_wrt_ty : forall T1 T2 X1 n1, degree_ty_wrt_ty n1 T1 -> degree_ty_wrt_ty n1 T2 -> degree_ty_wrt_ty n1 (subst_ty_in_ty T2 X1 T1). Proof. pose proof subst_ty_in_ty_degree_ty_wrt_ty_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_ty_degree_ty_wrt_ty : lngen. (* begin hide *) Lemma subst_ty_in_exp_degree_exp_wrt_ty_mutual : (forall e1 T1 X1 n1, degree_exp_wrt_ty n1 e1 -> degree_ty_wrt_ty n1 T1 -> degree_exp_wrt_ty n1 (subst_ty_in_exp T1 X1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_ty_in_exp_degree_exp_wrt_ty : forall e1 T1 X1 n1, degree_exp_wrt_ty n1 e1 -> degree_ty_wrt_ty n1 T1 -> degree_exp_wrt_ty n1 (subst_ty_in_exp T1 X1 e1). Proof. pose proof subst_ty_in_exp_degree_exp_wrt_ty_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_exp_degree_exp_wrt_ty : lngen. (* begin hide *) Lemma subst_ty_in_exp_degree_exp_wrt_exp_mutual : (forall e1 T1 X1 n1, degree_exp_wrt_exp n1 e1 -> degree_exp_wrt_exp n1 (subst_ty_in_exp T1 X1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_ty_in_exp_degree_exp_wrt_exp : forall e1 T1 X1 n1, degree_exp_wrt_exp n1 e1 -> degree_exp_wrt_exp n1 (subst_ty_in_exp T1 X1 e1). Proof. pose proof subst_ty_in_exp_degree_exp_wrt_exp_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_exp_degree_exp_wrt_exp : lngen. (* begin hide *) Lemma subst_exp_in_exp_degree_exp_wrt_ty_mutual : (forall e1 e2 x1 n1, degree_exp_wrt_ty n1 e1 -> degree_exp_wrt_ty n1 e2 -> degree_exp_wrt_ty n1 (subst_exp_in_exp e2 x1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_exp_in_exp_degree_exp_wrt_ty : forall e1 e2 x1 n1, degree_exp_wrt_ty n1 e1 -> degree_exp_wrt_ty n1 e2 -> degree_exp_wrt_ty n1 (subst_exp_in_exp e2 x1 e1). Proof. pose proof subst_exp_in_exp_degree_exp_wrt_ty_mutual as H; intuition eauto. Qed. Hint Resolve subst_exp_in_exp_degree_exp_wrt_ty : lngen. (* begin hide *) Lemma subst_exp_in_exp_degree_exp_wrt_exp_mutual : (forall e1 e2 x1 n1, degree_exp_wrt_exp n1 e1 -> degree_exp_wrt_exp n1 e2 -> degree_exp_wrt_exp n1 (subst_exp_in_exp e2 x1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_exp_in_exp_degree_exp_wrt_exp : forall e1 e2 x1 n1, degree_exp_wrt_exp n1 e1 -> degree_exp_wrt_exp n1 e2 -> degree_exp_wrt_exp n1 (subst_exp_in_exp e2 x1 e1). Proof. pose proof subst_exp_in_exp_degree_exp_wrt_exp_mutual as H; intuition eauto. Qed. Hint Resolve subst_exp_in_exp_degree_exp_wrt_exp : lngen. (* begin hide *) Lemma subst_ty_in_ty_fresh_eq_mutual : (forall T2 T1 X1, X1 `notin` fv_ty_in_ty T2 -> subst_ty_in_ty T1 X1 T2 = T2). Proof. apply_mutual_ind ty_mutind; default_simp. Qed. (* end hide *) Lemma subst_ty_in_ty_fresh_eq : forall T2 T1 X1, X1 `notin` fv_ty_in_ty T2 -> subst_ty_in_ty T1 X1 T2 = T2. Proof. pose proof subst_ty_in_ty_fresh_eq_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_ty_fresh_eq : lngen. Hint Rewrite subst_ty_in_ty_fresh_eq using solve [auto] : lngen. (* begin hide *) Lemma subst_ty_in_exp_fresh_eq_mutual : (forall e1 T1 X1, X1 `notin` fv_ty_in_exp e1 -> subst_ty_in_exp T1 X1 e1 = e1). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_ty_in_exp_fresh_eq : forall e1 T1 X1, X1 `notin` fv_ty_in_exp e1 -> subst_ty_in_exp T1 X1 e1 = e1. Proof. pose proof subst_ty_in_exp_fresh_eq_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_exp_fresh_eq : lngen. Hint Rewrite subst_ty_in_exp_fresh_eq using solve [auto] : lngen. (* begin hide *) Lemma subst_exp_in_exp_fresh_eq_mutual : (forall e2 e1 x1, x1 `notin` fv_exp_in_exp e2 -> subst_exp_in_exp e1 x1 e2 = e2). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_exp_in_exp_fresh_eq : forall e2 e1 x1, x1 `notin` fv_exp_in_exp e2 -> subst_exp_in_exp e1 x1 e2 = e2. Proof. pose proof subst_exp_in_exp_fresh_eq_mutual as H; intuition eauto. Qed. Hint Resolve subst_exp_in_exp_fresh_eq : lngen. Hint Rewrite subst_exp_in_exp_fresh_eq using solve [auto] : lngen. (* begin hide *) Lemma subst_ty_in_ty_fresh_same_mutual : (forall T2 T1 X1, X1 `notin` fv_ty_in_ty T1 -> X1 `notin` fv_ty_in_ty (subst_ty_in_ty T1 X1 T2)). Proof. apply_mutual_ind ty_mutind; default_simp. Qed. (* end hide *) Lemma subst_ty_in_ty_fresh_same : forall T2 T1 X1, X1 `notin` fv_ty_in_ty T1 -> X1 `notin` fv_ty_in_ty (subst_ty_in_ty T1 X1 T2). Proof. pose proof subst_ty_in_ty_fresh_same_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_ty_fresh_same : lngen. (* begin hide *) Lemma subst_ty_in_exp_fresh_same_mutual : (forall e1 T1 X1, X1 `notin` fv_ty_in_ty T1 -> X1 `notin` fv_ty_in_exp (subst_ty_in_exp T1 X1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_ty_in_exp_fresh_same : forall e1 T1 X1, X1 `notin` fv_ty_in_ty T1 -> X1 `notin` fv_ty_in_exp (subst_ty_in_exp T1 X1 e1). Proof. pose proof subst_ty_in_exp_fresh_same_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_exp_fresh_same : lngen. (* begin hide *) Lemma subst_exp_in_exp_fresh_same_mutual : (forall e2 e1 x1, x1 `notin` fv_exp_in_exp e1 -> x1 `notin` fv_exp_in_exp (subst_exp_in_exp e1 x1 e2)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_exp_in_exp_fresh_same : forall e2 e1 x1, x1 `notin` fv_exp_in_exp e1 -> x1 `notin` fv_exp_in_exp (subst_exp_in_exp e1 x1 e2). Proof. pose proof subst_exp_in_exp_fresh_same_mutual as H; intuition eauto. Qed. Hint Resolve subst_exp_in_exp_fresh_same : lngen. (* begin hide *) Lemma subst_ty_in_ty_fresh_mutual : (forall T2 T1 X1 X2, X1 `notin` fv_ty_in_ty T2 -> X1 `notin` fv_ty_in_ty T1 -> X1 `notin` fv_ty_in_ty (subst_ty_in_ty T1 X2 T2)). Proof. apply_mutual_ind ty_mutind; default_simp. Qed. (* end hide *) Lemma subst_ty_in_ty_fresh : forall T2 T1 X1 X2, X1 `notin` fv_ty_in_ty T2 -> X1 `notin` fv_ty_in_ty T1 -> X1 `notin` fv_ty_in_ty (subst_ty_in_ty T1 X2 T2). Proof. pose proof subst_ty_in_ty_fresh_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_ty_fresh : lngen. (* begin hide *) Lemma subst_ty_in_exp_fresh_mutual : (forall e1 T1 X1 X2, X1 `notin` fv_ty_in_exp e1 -> X1 `notin` fv_ty_in_ty T1 -> X1 `notin` fv_ty_in_exp (subst_ty_in_exp T1 X2 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_ty_in_exp_fresh : forall e1 T1 X1 X2, X1 `notin` fv_ty_in_exp e1 -> X1 `notin` fv_ty_in_ty T1 -> X1 `notin` fv_ty_in_exp (subst_ty_in_exp T1 X2 e1). Proof. pose proof subst_ty_in_exp_fresh_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_exp_fresh : lngen. (* begin hide *) Lemma subst_exp_in_exp_fresh_mutual : (forall e2 e1 x1 x2, x1 `notin` fv_exp_in_exp e2 -> x1 `notin` fv_exp_in_exp e1 -> x1 `notin` fv_exp_in_exp (subst_exp_in_exp e1 x2 e2)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_exp_in_exp_fresh : forall e2 e1 x1 x2, x1 `notin` fv_exp_in_exp e2 -> x1 `notin` fv_exp_in_exp e1 -> x1 `notin` fv_exp_in_exp (subst_exp_in_exp e1 x2 e2). Proof. pose proof subst_exp_in_exp_fresh_mutual as H; intuition eauto. Qed. Hint Resolve subst_exp_in_exp_fresh : lngen. Lemma subst_ty_in_ty_lc_ty : forall T1 T2 X1, lc_ty T1 -> lc_ty T2 -> lc_ty (subst_ty_in_ty T2 X1 T1). Proof. default_simp. Qed. Hint Resolve subst_ty_in_ty_lc_ty : lngen. Lemma subst_ty_in_exp_lc_exp : forall e1 T1 X1, lc_exp e1 -> lc_ty T1 -> lc_exp (subst_ty_in_exp T1 X1 e1). Proof. default_simp. Qed. Hint Resolve subst_ty_in_exp_lc_exp : lngen. Lemma subst_exp_in_exp_lc_exp : forall e1 e2 x1, lc_exp e1 -> lc_exp e2 -> lc_exp (subst_exp_in_exp e2 x1 e1). Proof. default_simp. Qed. Hint Resolve subst_exp_in_exp_lc_exp : lngen. (* begin hide *) Lemma subst_ty_in_ty_open_ty_wrt_ty_rec_mutual : (forall T3 T1 T2 X1 n1, lc_ty T1 -> subst_ty_in_ty T1 X1 (open_ty_wrt_ty_rec n1 T2 T3) = open_ty_wrt_ty_rec n1 (subst_ty_in_ty T1 X1 T2) (subst_ty_in_ty T1 X1 T3)). Proof. apply_mutual_ind ty_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma subst_ty_in_ty_open_ty_wrt_ty_rec : forall T3 T1 T2 X1 n1, lc_ty T1 -> subst_ty_in_ty T1 X1 (open_ty_wrt_ty_rec n1 T2 T3) = open_ty_wrt_ty_rec n1 (subst_ty_in_ty T1 X1 T2) (subst_ty_in_ty T1 X1 T3). Proof. pose proof subst_ty_in_ty_open_ty_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_ty_open_ty_wrt_ty_rec : lngen. (* end hide *) (* begin hide *) Lemma subst_ty_in_exp_open_exp_wrt_ty_rec_mutual : (forall e1 T1 T2 X1 n1, lc_ty T1 -> subst_ty_in_exp T1 X1 (open_exp_wrt_ty_rec n1 T2 e1) = open_exp_wrt_ty_rec n1 (subst_ty_in_ty T1 X1 T2) (subst_ty_in_exp T1 X1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma subst_ty_in_exp_open_exp_wrt_ty_rec : forall e1 T1 T2 X1 n1, lc_ty T1 -> subst_ty_in_exp T1 X1 (open_exp_wrt_ty_rec n1 T2 e1) = open_exp_wrt_ty_rec n1 (subst_ty_in_ty T1 X1 T2) (subst_ty_in_exp T1 X1 e1). Proof. pose proof subst_ty_in_exp_open_exp_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_exp_open_exp_wrt_ty_rec : lngen. (* end hide *) (* begin hide *) Lemma subst_ty_in_exp_open_exp_wrt_exp_rec_mutual : (forall e2 T1 e1 X1 n1, subst_ty_in_exp T1 X1 (open_exp_wrt_exp_rec n1 e1 e2) = open_exp_wrt_exp_rec n1 (subst_ty_in_exp T1 X1 e1) (subst_ty_in_exp T1 X1 e2)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma subst_ty_in_exp_open_exp_wrt_exp_rec : forall e2 T1 e1 X1 n1, subst_ty_in_exp T1 X1 (open_exp_wrt_exp_rec n1 e1 e2) = open_exp_wrt_exp_rec n1 (subst_ty_in_exp T1 X1 e1) (subst_ty_in_exp T1 X1 e2). Proof. pose proof subst_ty_in_exp_open_exp_wrt_exp_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_exp_open_exp_wrt_exp_rec : lngen. (* end hide *) (* begin hide *) Lemma subst_exp_in_exp_open_exp_wrt_ty_rec_mutual : (forall e2 e1 T1 x1 n1, lc_exp e1 -> subst_exp_in_exp e1 x1 (open_exp_wrt_ty_rec n1 T1 e2) = open_exp_wrt_ty_rec n1 T1 (subst_exp_in_exp e1 x1 e2)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma subst_exp_in_exp_open_exp_wrt_ty_rec : forall e2 e1 T1 x1 n1, lc_exp e1 -> subst_exp_in_exp e1 x1 (open_exp_wrt_ty_rec n1 T1 e2) = open_exp_wrt_ty_rec n1 T1 (subst_exp_in_exp e1 x1 e2). Proof. pose proof subst_exp_in_exp_open_exp_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_exp_in_exp_open_exp_wrt_ty_rec : lngen. (* end hide *) (* begin hide *) Lemma subst_exp_in_exp_open_exp_wrt_exp_rec_mutual : (forall e3 e1 e2 x1 n1, lc_exp e1 -> subst_exp_in_exp e1 x1 (open_exp_wrt_exp_rec n1 e2 e3) = open_exp_wrt_exp_rec n1 (subst_exp_in_exp e1 x1 e2) (subst_exp_in_exp e1 x1 e3)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma subst_exp_in_exp_open_exp_wrt_exp_rec : forall e3 e1 e2 x1 n1, lc_exp e1 -> subst_exp_in_exp e1 x1 (open_exp_wrt_exp_rec n1 e2 e3) = open_exp_wrt_exp_rec n1 (subst_exp_in_exp e1 x1 e2) (subst_exp_in_exp e1 x1 e3). Proof. pose proof subst_exp_in_exp_open_exp_wrt_exp_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_exp_in_exp_open_exp_wrt_exp_rec : lngen. (* end hide *) Lemma subst_ty_in_ty_open_ty_wrt_ty : forall T3 T1 T2 X1, lc_ty T1 -> subst_ty_in_ty T1 X1 (open_ty_wrt_ty T3 T2) = open_ty_wrt_ty (subst_ty_in_ty T1 X1 T3) (subst_ty_in_ty T1 X1 T2). Proof. unfold open_ty_wrt_ty; default_simp. Qed. Hint Resolve subst_ty_in_ty_open_ty_wrt_ty : lngen. Lemma subst_ty_in_exp_open_exp_wrt_ty : forall e1 T1 T2 X1, lc_ty T1 -> subst_ty_in_exp T1 X1 (open_exp_wrt_ty e1 T2) = open_exp_wrt_ty (subst_ty_in_exp T1 X1 e1) (subst_ty_in_ty T1 X1 T2). Proof. unfold open_exp_wrt_ty; default_simp. Qed. Hint Resolve subst_ty_in_exp_open_exp_wrt_ty : lngen. Lemma subst_ty_in_exp_open_exp_wrt_exp : forall e2 T1 e1 X1, subst_ty_in_exp T1 X1 (open_exp_wrt_exp e2 e1) = open_exp_wrt_exp (subst_ty_in_exp T1 X1 e2) (subst_ty_in_exp T1 X1 e1). Proof. unfold open_exp_wrt_exp; default_simp. Qed. Hint Resolve subst_ty_in_exp_open_exp_wrt_exp : lngen. Lemma subst_exp_in_exp_open_exp_wrt_ty : forall e2 e1 T1 x1, lc_exp e1 -> subst_exp_in_exp e1 x1 (open_exp_wrt_ty e2 T1) = open_exp_wrt_ty (subst_exp_in_exp e1 x1 e2) T1. Proof. unfold open_exp_wrt_ty; default_simp. Qed. Hint Resolve subst_exp_in_exp_open_exp_wrt_ty : lngen. Lemma subst_exp_in_exp_open_exp_wrt_exp : forall e3 e1 e2 x1, lc_exp e1 -> subst_exp_in_exp e1 x1 (open_exp_wrt_exp e3 e2) = open_exp_wrt_exp (subst_exp_in_exp e1 x1 e3) (subst_exp_in_exp e1 x1 e2). Proof. unfold open_exp_wrt_exp; default_simp. Qed. Hint Resolve subst_exp_in_exp_open_exp_wrt_exp : lngen. Lemma subst_ty_in_ty_open_ty_wrt_ty_var : forall T2 T1 X1 X2, X1 <> X2 -> lc_ty T1 -> open_ty_wrt_ty (subst_ty_in_ty T1 X1 T2) (ty_var_f X2) = subst_ty_in_ty T1 X1 (open_ty_wrt_ty T2 (ty_var_f X2)). Proof. intros; rewrite subst_ty_in_ty_open_ty_wrt_ty; default_simp. Qed. Hint Resolve subst_ty_in_ty_open_ty_wrt_ty_var : lngen. Lemma subst_ty_in_exp_open_exp_wrt_ty_var : forall e1 T1 X1 X2, X1 <> X2 -> lc_ty T1 -> open_exp_wrt_ty (subst_ty_in_exp T1 X1 e1) (ty_var_f X2) = subst_ty_in_exp T1 X1 (open_exp_wrt_ty e1 (ty_var_f X2)). Proof. intros; rewrite subst_ty_in_exp_open_exp_wrt_ty; default_simp. Qed. Hint Resolve subst_ty_in_exp_open_exp_wrt_ty_var : lngen. Lemma subst_ty_in_exp_open_exp_wrt_exp_var : forall e1 T1 X1 x1, open_exp_wrt_exp (subst_ty_in_exp T1 X1 e1) (exp_var_f x1) = subst_ty_in_exp T1 X1 (open_exp_wrt_exp e1 (exp_var_f x1)). Proof. intros; rewrite subst_ty_in_exp_open_exp_wrt_exp; default_simp. Qed. Hint Resolve subst_ty_in_exp_open_exp_wrt_exp_var : lngen. Lemma subst_exp_in_exp_open_exp_wrt_ty_var : forall e2 e1 x1 X1, lc_exp e1 -> open_exp_wrt_ty (subst_exp_in_exp e1 x1 e2) (ty_var_f X1) = subst_exp_in_exp e1 x1 (open_exp_wrt_ty e2 (ty_var_f X1)). Proof. intros; rewrite subst_exp_in_exp_open_exp_wrt_ty; default_simp. Qed. Hint Resolve subst_exp_in_exp_open_exp_wrt_ty_var : lngen. Lemma subst_exp_in_exp_open_exp_wrt_exp_var : forall e2 e1 x1 x2, x1 <> x2 -> lc_exp e1 -> open_exp_wrt_exp (subst_exp_in_exp e1 x1 e2) (exp_var_f x2) = subst_exp_in_exp e1 x1 (open_exp_wrt_exp e2 (exp_var_f x2)). Proof. intros; rewrite subst_exp_in_exp_open_exp_wrt_exp; default_simp. Qed. Hint Resolve subst_exp_in_exp_open_exp_wrt_exp_var : lngen. (* begin hide *) Lemma subst_ty_in_ty_spec_rec_mutual : (forall T1 T2 X1 n1, subst_ty_in_ty T2 X1 T1 = open_ty_wrt_ty_rec n1 T2 (close_ty_wrt_ty_rec n1 X1 T1)). Proof. apply_mutual_ind ty_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma subst_ty_in_ty_spec_rec : forall T1 T2 X1 n1, subst_ty_in_ty T2 X1 T1 = open_ty_wrt_ty_rec n1 T2 (close_ty_wrt_ty_rec n1 X1 T1). Proof. pose proof subst_ty_in_ty_spec_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_ty_spec_rec : lngen. (* end hide *) (* begin hide *) Lemma subst_ty_in_exp_spec_rec_mutual : (forall e1 T1 X1 n1, subst_ty_in_exp T1 X1 e1 = open_exp_wrt_ty_rec n1 T1 (close_exp_wrt_ty_rec n1 X1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma subst_ty_in_exp_spec_rec : forall e1 T1 X1 n1, subst_ty_in_exp T1 X1 e1 = open_exp_wrt_ty_rec n1 T1 (close_exp_wrt_ty_rec n1 X1 e1). Proof. pose proof subst_ty_in_exp_spec_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_exp_spec_rec : lngen. (* end hide *) (* begin hide *) Lemma subst_exp_in_exp_spec_rec_mutual : (forall e1 e2 x1 n1, subst_exp_in_exp e2 x1 e1 = open_exp_wrt_exp_rec n1 e2 (close_exp_wrt_exp_rec n1 x1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) (* begin hide *) Lemma subst_exp_in_exp_spec_rec : forall e1 e2 x1 n1, subst_exp_in_exp e2 x1 e1 = open_exp_wrt_exp_rec n1 e2 (close_exp_wrt_exp_rec n1 x1 e1). Proof. pose proof subst_exp_in_exp_spec_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_exp_in_exp_spec_rec : lngen. (* end hide *) Lemma subst_ty_in_ty_spec : forall T1 T2 X1, subst_ty_in_ty T2 X1 T1 = open_ty_wrt_ty (close_ty_wrt_ty X1 T1) T2. Proof. unfold close_ty_wrt_ty; unfold open_ty_wrt_ty; default_simp. Qed. Hint Resolve subst_ty_in_ty_spec : lngen. Lemma subst_ty_in_exp_spec : forall e1 T1 X1, subst_ty_in_exp T1 X1 e1 = open_exp_wrt_ty (close_exp_wrt_ty X1 e1) T1. Proof. unfold close_exp_wrt_ty; unfold open_exp_wrt_ty; default_simp. Qed. Hint Resolve subst_ty_in_exp_spec : lngen. Lemma subst_exp_in_exp_spec : forall e1 e2 x1, subst_exp_in_exp e2 x1 e1 = open_exp_wrt_exp (close_exp_wrt_exp x1 e1) e2. Proof. unfold close_exp_wrt_exp; unfold open_exp_wrt_exp; default_simp. Qed. Hint Resolve subst_exp_in_exp_spec : lngen. (* begin hide *) Lemma subst_ty_in_ty_subst_ty_in_ty_mutual : (forall T1 T2 T3 X2 X1, X2 `notin` fv_ty_in_ty T2 -> X2 <> X1 -> subst_ty_in_ty T2 X1 (subst_ty_in_ty T3 X2 T1) = subst_ty_in_ty (subst_ty_in_ty T2 X1 T3) X2 (subst_ty_in_ty T2 X1 T1)). Proof. apply_mutual_ind ty_mutind; default_simp. Qed. (* end hide *) Lemma subst_ty_in_ty_subst_ty_in_ty : forall T1 T2 T3 X2 X1, X2 `notin` fv_ty_in_ty T2 -> X2 <> X1 -> subst_ty_in_ty T2 X1 (subst_ty_in_ty T3 X2 T1) = subst_ty_in_ty (subst_ty_in_ty T2 X1 T3) X2 (subst_ty_in_ty T2 X1 T1). Proof. pose proof subst_ty_in_ty_subst_ty_in_ty_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_ty_subst_ty_in_ty : lngen. (* begin hide *) Lemma subst_ty_in_exp_subst_ty_in_exp_mutual : (forall e1 T1 T2 X2 X1, X2 `notin` fv_ty_in_ty T1 -> X2 <> X1 -> subst_ty_in_exp T1 X1 (subst_ty_in_exp T2 X2 e1) = subst_ty_in_exp (subst_ty_in_ty T1 X1 T2) X2 (subst_ty_in_exp T1 X1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_ty_in_exp_subst_ty_in_exp : forall e1 T1 T2 X2 X1, X2 `notin` fv_ty_in_ty T1 -> X2 <> X1 -> subst_ty_in_exp T1 X1 (subst_ty_in_exp T2 X2 e1) = subst_ty_in_exp (subst_ty_in_ty T1 X1 T2) X2 (subst_ty_in_exp T1 X1 e1). Proof. pose proof subst_ty_in_exp_subst_ty_in_exp_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_exp_subst_ty_in_exp : lngen. (* begin hide *) Lemma subst_ty_in_exp_subst_exp_in_exp_mutual : (forall e1 T1 e2 x1 X1, subst_ty_in_exp T1 X1 (subst_exp_in_exp e2 x1 e1) = subst_exp_in_exp (subst_ty_in_exp T1 X1 e2) x1 (subst_ty_in_exp T1 X1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_ty_in_exp_subst_exp_in_exp : forall e1 T1 e2 x1 X1, subst_ty_in_exp T1 X1 (subst_exp_in_exp e2 x1 e1) = subst_exp_in_exp (subst_ty_in_exp T1 X1 e2) x1 (subst_ty_in_exp T1 X1 e1). Proof. pose proof subst_ty_in_exp_subst_exp_in_exp_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_exp_subst_exp_in_exp : lngen. (* begin hide *) Lemma subst_exp_in_exp_subst_ty_in_exp_mutual : (forall e1 e2 T1 X1 x1, X1 `notin` fv_ty_in_exp e2 -> subst_exp_in_exp e2 x1 (subst_ty_in_exp T1 X1 e1) = subst_ty_in_exp T1 X1 (subst_exp_in_exp e2 x1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_exp_in_exp_subst_ty_in_exp : forall e1 e2 T1 X1 x1, X1 `notin` fv_ty_in_exp e2 -> subst_exp_in_exp e2 x1 (subst_ty_in_exp T1 X1 e1) = subst_ty_in_exp T1 X1 (subst_exp_in_exp e2 x1 e1). Proof. pose proof subst_exp_in_exp_subst_ty_in_exp_mutual as H; intuition eauto. Qed. Hint Resolve subst_exp_in_exp_subst_ty_in_exp : lngen. (* begin hide *) Lemma subst_exp_in_exp_subst_exp_in_exp_mutual : (forall e1 e2 e3 x2 x1, x2 `notin` fv_exp_in_exp e2 -> x2 <> x1 -> subst_exp_in_exp e2 x1 (subst_exp_in_exp e3 x2 e1) = subst_exp_in_exp (subst_exp_in_exp e2 x1 e3) x2 (subst_exp_in_exp e2 x1 e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_exp_in_exp_subst_exp_in_exp : forall e1 e2 e3 x2 x1, x2 `notin` fv_exp_in_exp e2 -> x2 <> x1 -> subst_exp_in_exp e2 x1 (subst_exp_in_exp e3 x2 e1) = subst_exp_in_exp (subst_exp_in_exp e2 x1 e3) x2 (subst_exp_in_exp e2 x1 e1). Proof. pose proof subst_exp_in_exp_subst_exp_in_exp_mutual as H; intuition eauto. Qed. Hint Resolve subst_exp_in_exp_subst_exp_in_exp : lngen. (* begin hide *) Lemma subst_ty_in_ty_close_ty_wrt_ty_rec_open_ty_wrt_ty_rec_mutual : (forall T2 T1 X1 X2 n1, X2 `notin` fv_ty_in_ty T2 -> X2 `notin` fv_ty_in_ty T1 -> X2 <> X1 -> degree_ty_wrt_ty n1 T1 -> subst_ty_in_ty T1 X1 T2 = close_ty_wrt_ty_rec n1 X2 (subst_ty_in_ty T1 X1 (open_ty_wrt_ty_rec n1 (ty_var_f X2) T2))). Proof. apply_mutual_ind ty_mutrec; default_simp. Qed. (* end hide *) (* begin hide *) Lemma subst_ty_in_ty_close_ty_wrt_ty_rec_open_ty_wrt_ty_rec : forall T2 T1 X1 X2 n1, X2 `notin` fv_ty_in_ty T2 -> X2 `notin` fv_ty_in_ty T1 -> X2 <> X1 -> degree_ty_wrt_ty n1 T1 -> subst_ty_in_ty T1 X1 T2 = close_ty_wrt_ty_rec n1 X2 (subst_ty_in_ty T1 X1 (open_ty_wrt_ty_rec n1 (ty_var_f X2) T2)). Proof. pose proof subst_ty_in_ty_close_ty_wrt_ty_rec_open_ty_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_ty_close_ty_wrt_ty_rec_open_ty_wrt_ty_rec : lngen. (* end hide *) (* begin hide *) Lemma subst_ty_in_exp_close_exp_wrt_ty_rec_open_exp_wrt_ty_rec_mutual : (forall e1 T1 X1 X2 n1, X2 `notin` fv_ty_in_exp e1 -> X2 `notin` fv_ty_in_ty T1 -> X2 <> X1 -> degree_ty_wrt_ty n1 T1 -> subst_ty_in_exp T1 X1 e1 = close_exp_wrt_ty_rec n1 X2 (subst_ty_in_exp T1 X1 (open_exp_wrt_ty_rec n1 (ty_var_f X2) e1))). Proof. apply_mutual_ind exp_mutrec; default_simp. Qed. (* end hide *) (* begin hide *) Lemma subst_ty_in_exp_close_exp_wrt_ty_rec_open_exp_wrt_ty_rec : forall e1 T1 X1 X2 n1, X2 `notin` fv_ty_in_exp e1 -> X2 `notin` fv_ty_in_ty T1 -> X2 <> X1 -> degree_ty_wrt_ty n1 T1 -> subst_ty_in_exp T1 X1 e1 = close_exp_wrt_ty_rec n1 X2 (subst_ty_in_exp T1 X1 (open_exp_wrt_ty_rec n1 (ty_var_f X2) e1)). Proof. pose proof subst_ty_in_exp_close_exp_wrt_ty_rec_open_exp_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_exp_close_exp_wrt_ty_rec_open_exp_wrt_ty_rec : lngen. (* end hide *) (* begin hide *) Lemma subst_ty_in_exp_close_exp_wrt_exp_rec_open_exp_wrt_exp_rec_mutual : (forall e1 T1 X1 x1 n1, x1 `notin` fv_exp_in_exp e1 -> subst_ty_in_exp T1 X1 e1 = close_exp_wrt_exp_rec n1 x1 (subst_ty_in_exp T1 X1 (open_exp_wrt_exp_rec n1 (exp_var_f x1) e1))). Proof. apply_mutual_ind exp_mutrec; default_simp. Qed. (* end hide *) (* begin hide *) Lemma subst_ty_in_exp_close_exp_wrt_exp_rec_open_exp_wrt_exp_rec : forall e1 T1 X1 x1 n1, x1 `notin` fv_exp_in_exp e1 -> subst_ty_in_exp T1 X1 e1 = close_exp_wrt_exp_rec n1 x1 (subst_ty_in_exp T1 X1 (open_exp_wrt_exp_rec n1 (exp_var_f x1) e1)). Proof. pose proof subst_ty_in_exp_close_exp_wrt_exp_rec_open_exp_wrt_exp_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_exp_close_exp_wrt_exp_rec_open_exp_wrt_exp_rec : lngen. (* end hide *) (* begin hide *) Lemma subst_exp_in_exp_close_exp_wrt_ty_rec_open_exp_wrt_ty_rec_mutual : (forall e2 e1 x1 X1 n1, X1 `notin` fv_ty_in_exp e2 -> X1 `notin` fv_ty_in_exp e1 -> degree_exp_wrt_ty n1 e1 -> subst_exp_in_exp e1 x1 e2 = close_exp_wrt_ty_rec n1 X1 (subst_exp_in_exp e1 x1 (open_exp_wrt_ty_rec n1 (ty_var_f X1) e2))). Proof. apply_mutual_ind exp_mutrec; default_simp. Qed. (* end hide *) (* begin hide *) Lemma subst_exp_in_exp_close_exp_wrt_ty_rec_open_exp_wrt_ty_rec : forall e2 e1 x1 X1 n1, X1 `notin` fv_ty_in_exp e2 -> X1 `notin` fv_ty_in_exp e1 -> degree_exp_wrt_ty n1 e1 -> subst_exp_in_exp e1 x1 e2 = close_exp_wrt_ty_rec n1 X1 (subst_exp_in_exp e1 x1 (open_exp_wrt_ty_rec n1 (ty_var_f X1) e2)). Proof. pose proof subst_exp_in_exp_close_exp_wrt_ty_rec_open_exp_wrt_ty_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_exp_in_exp_close_exp_wrt_ty_rec_open_exp_wrt_ty_rec : lngen. (* end hide *) (* begin hide *) Lemma subst_exp_in_exp_close_exp_wrt_exp_rec_open_exp_wrt_exp_rec_mutual : (forall e2 e1 x1 x2 n1, x2 `notin` fv_exp_in_exp e2 -> x2 `notin` fv_exp_in_exp e1 -> x2 <> x1 -> degree_exp_wrt_exp n1 e1 -> subst_exp_in_exp e1 x1 e2 = close_exp_wrt_exp_rec n1 x2 (subst_exp_in_exp e1 x1 (open_exp_wrt_exp_rec n1 (exp_var_f x2) e2))). Proof. apply_mutual_ind exp_mutrec; default_simp. Qed. (* end hide *) (* begin hide *) Lemma subst_exp_in_exp_close_exp_wrt_exp_rec_open_exp_wrt_exp_rec : forall e2 e1 x1 x2 n1, x2 `notin` fv_exp_in_exp e2 -> x2 `notin` fv_exp_in_exp e1 -> x2 <> x1 -> degree_exp_wrt_exp n1 e1 -> subst_exp_in_exp e1 x1 e2 = close_exp_wrt_exp_rec n1 x2 (subst_exp_in_exp e1 x1 (open_exp_wrt_exp_rec n1 (exp_var_f x2) e2)). Proof. pose proof subst_exp_in_exp_close_exp_wrt_exp_rec_open_exp_wrt_exp_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_exp_in_exp_close_exp_wrt_exp_rec_open_exp_wrt_exp_rec : lngen. (* end hide *) Lemma subst_ty_in_ty_close_ty_wrt_ty_open_ty_wrt_ty : forall T2 T1 X1 X2, X2 `notin` fv_ty_in_ty T2 -> X2 `notin` fv_ty_in_ty T1 -> X2 <> X1 -> lc_ty T1 -> subst_ty_in_ty T1 X1 T2 = close_ty_wrt_ty X2 (subst_ty_in_ty T1 X1 (open_ty_wrt_ty T2 (ty_var_f X2))). Proof. unfold close_ty_wrt_ty; unfold open_ty_wrt_ty; default_simp. Qed. Hint Resolve subst_ty_in_ty_close_ty_wrt_ty_open_ty_wrt_ty : lngen. Lemma subst_ty_in_exp_close_exp_wrt_ty_open_exp_wrt_ty : forall e1 T1 X1 X2, X2 `notin` fv_ty_in_exp e1 -> X2 `notin` fv_ty_in_ty T1 -> X2 <> X1 -> lc_ty T1 -> subst_ty_in_exp T1 X1 e1 = close_exp_wrt_ty X2 (subst_ty_in_exp T1 X1 (open_exp_wrt_ty e1 (ty_var_f X2))). Proof. unfold close_exp_wrt_ty; unfold open_exp_wrt_ty; default_simp. Qed. Hint Resolve subst_ty_in_exp_close_exp_wrt_ty_open_exp_wrt_ty : lngen. Lemma subst_ty_in_exp_close_exp_wrt_exp_open_exp_wrt_exp : forall e1 T1 X1 x1, x1 `notin` fv_exp_in_exp e1 -> lc_ty T1 -> subst_ty_in_exp T1 X1 e1 = close_exp_wrt_exp x1 (subst_ty_in_exp T1 X1 (open_exp_wrt_exp e1 (exp_var_f x1))). Proof. unfold close_exp_wrt_exp; unfold open_exp_wrt_exp; default_simp. Qed. Hint Resolve subst_ty_in_exp_close_exp_wrt_exp_open_exp_wrt_exp : lngen. Lemma subst_exp_in_exp_close_exp_wrt_ty_open_exp_wrt_ty : forall e2 e1 x1 X1, X1 `notin` fv_ty_in_exp e2 -> X1 `notin` fv_ty_in_exp e1 -> lc_exp e1 -> subst_exp_in_exp e1 x1 e2 = close_exp_wrt_ty X1 (subst_exp_in_exp e1 x1 (open_exp_wrt_ty e2 (ty_var_f X1))). Proof. unfold close_exp_wrt_ty; unfold open_exp_wrt_ty; default_simp. Qed. Hint Resolve subst_exp_in_exp_close_exp_wrt_ty_open_exp_wrt_ty : lngen. Lemma subst_exp_in_exp_close_exp_wrt_exp_open_exp_wrt_exp : forall e2 e1 x1 x2, x2 `notin` fv_exp_in_exp e2 -> x2 `notin` fv_exp_in_exp e1 -> x2 <> x1 -> lc_exp e1 -> subst_exp_in_exp e1 x1 e2 = close_exp_wrt_exp x2 (subst_exp_in_exp e1 x1 (open_exp_wrt_exp e2 (exp_var_f x2))). Proof. unfold close_exp_wrt_exp; unfold open_exp_wrt_exp; default_simp. Qed. Hint Resolve subst_exp_in_exp_close_exp_wrt_exp_open_exp_wrt_exp : lngen. Lemma subst_ty_in_ty_ty_all : forall X2 T2 T1 X1, lc_ty T1 -> X2 `notin` fv_ty_in_ty T1 `union` fv_ty_in_ty T2 `union` singleton X1 -> subst_ty_in_ty T1 X1 (ty_all T2) = ty_all (close_ty_wrt_ty X2 (subst_ty_in_ty T1 X1 (open_ty_wrt_ty T2 (ty_var_f X2)))). Proof. default_simp. Qed. Hint Resolve subst_ty_in_ty_ty_all : lngen. Lemma subst_ty_in_exp_exp_abs : forall x1 e1 T1 X1, lc_ty T1 -> x1 `notin` fv_exp_in_exp e1 -> subst_ty_in_exp T1 X1 (exp_abs e1) = exp_abs (close_exp_wrt_exp x1 (subst_ty_in_exp T1 X1 (open_exp_wrt_exp e1 (exp_var_f x1)))). Proof. default_simp. Qed. Hint Resolve subst_ty_in_exp_exp_abs : lngen. Lemma subst_ty_in_exp_exp_tabs : forall X2 e1 T1 X1, lc_ty T1 -> X2 `notin` fv_ty_in_ty T1 `union` fv_ty_in_exp e1 `union` singleton X1 -> subst_ty_in_exp T1 X1 (exp_tabs e1) = exp_tabs (close_exp_wrt_ty X2 (subst_ty_in_exp T1 X1 (open_exp_wrt_ty e1 (ty_var_f X2)))). Proof. default_simp. Qed. Hint Resolve subst_ty_in_exp_exp_tabs : lngen. Lemma subst_exp_in_exp_exp_abs : forall x2 e2 e1 x1, lc_exp e1 -> x2 `notin` fv_exp_in_exp e1 `union` fv_exp_in_exp e2 `union` singleton x1 -> subst_exp_in_exp e1 x1 (exp_abs e2) = exp_abs (close_exp_wrt_exp x2 (subst_exp_in_exp e1 x1 (open_exp_wrt_exp e2 (exp_var_f x2)))). Proof. default_simp. Qed. Hint Resolve subst_exp_in_exp_exp_abs : lngen. Lemma subst_exp_in_exp_exp_tabs : forall X1 e2 e1 x1, lc_exp e1 -> X1 `notin` fv_ty_in_exp e1 `union` fv_ty_in_exp e2 -> subst_exp_in_exp e1 x1 (exp_tabs e2) = exp_tabs (close_exp_wrt_ty X1 (subst_exp_in_exp e1 x1 (open_exp_wrt_ty e2 (ty_var_f X1)))). Proof. default_simp. Qed. Hint Resolve subst_exp_in_exp_exp_tabs : lngen. (* begin hide *) Lemma subst_ty_in_ty_intro_rec_mutual : (forall T1 X1 T2 n1, X1 `notin` fv_ty_in_ty T1 -> open_ty_wrt_ty_rec n1 T2 T1 = subst_ty_in_ty T2 X1 (open_ty_wrt_ty_rec n1 (ty_var_f X1) T1)). Proof. apply_mutual_ind ty_mutind; default_simp. Qed. (* end hide *) Lemma subst_ty_in_ty_intro_rec : forall T1 X1 T2 n1, X1 `notin` fv_ty_in_ty T1 -> open_ty_wrt_ty_rec n1 T2 T1 = subst_ty_in_ty T2 X1 (open_ty_wrt_ty_rec n1 (ty_var_f X1) T1). Proof. pose proof subst_ty_in_ty_intro_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_ty_intro_rec : lngen. Hint Rewrite subst_ty_in_ty_intro_rec using solve [auto] : lngen. (* begin hide *) Lemma subst_ty_in_exp_intro_rec_mutual : (forall e1 X1 T1 n1, X1 `notin` fv_ty_in_exp e1 -> open_exp_wrt_ty_rec n1 T1 e1 = subst_ty_in_exp T1 X1 (open_exp_wrt_ty_rec n1 (ty_var_f X1) e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_ty_in_exp_intro_rec : forall e1 X1 T1 n1, X1 `notin` fv_ty_in_exp e1 -> open_exp_wrt_ty_rec n1 T1 e1 = subst_ty_in_exp T1 X1 (open_exp_wrt_ty_rec n1 (ty_var_f X1) e1). Proof. pose proof subst_ty_in_exp_intro_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_ty_in_exp_intro_rec : lngen. Hint Rewrite subst_ty_in_exp_intro_rec using solve [auto] : lngen. (* begin hide *) Lemma subst_exp_in_exp_intro_rec_mutual : (forall e1 x1 e2 n1, x1 `notin` fv_exp_in_exp e1 -> open_exp_wrt_exp_rec n1 e2 e1 = subst_exp_in_exp e2 x1 (open_exp_wrt_exp_rec n1 (exp_var_f x1) e1)). Proof. apply_mutual_ind exp_mutind; default_simp. Qed. (* end hide *) Lemma subst_exp_in_exp_intro_rec : forall e1 x1 e2 n1, x1 `notin` fv_exp_in_exp e1 -> open_exp_wrt_exp_rec n1 e2 e1 = subst_exp_in_exp e2 x1 (open_exp_wrt_exp_rec n1 (exp_var_f x1) e1). Proof. pose proof subst_exp_in_exp_intro_rec_mutual as H; intuition eauto. Qed. Hint Resolve subst_exp_in_exp_intro_rec : lngen. Hint Rewrite subst_exp_in_exp_intro_rec using solve [auto] : lngen. Lemma subst_ty_in_ty_intro : forall X1 T1 T2, X1 `notin` fv_ty_in_ty T1 -> open_ty_wrt_ty T1 T2 = subst_ty_in_ty T2 X1 (open_ty_wrt_ty T1 (ty_var_f X1)). Proof. unfold open_ty_wrt_ty; default_simp. Qed. Hint Resolve subst_ty_in_ty_intro : lngen. Lemma subst_ty_in_exp_intro : forall X1 e1 T1, X1 `notin` fv_ty_in_exp e1 -> open_exp_wrt_ty e1 T1 = subst_ty_in_exp T1 X1 (open_exp_wrt_ty e1 (ty_var_f X1)). Proof. unfold open_exp_wrt_ty; default_simp. Qed. Hint Resolve subst_ty_in_exp_intro : lngen. Lemma subst_exp_in_exp_intro : forall x1 e1 e2, x1 `notin` fv_exp_in_exp e1 -> open_exp_wrt_exp e1 e2 = subst_exp_in_exp e2 x1 (open_exp_wrt_exp e1 (exp_var_f x1)). Proof. unfold open_exp_wrt_exp; default_simp. Qed. Hint Resolve subst_exp_in_exp_intro : lngen. (* *********************************************************************** *) (** * "Restore" tactics *) Ltac default_auto ::= auto; tauto. Ltac default_autorewrite ::= fail.
= = = Cast = = =
module Test.Hamming import Data.Vect import Test.Assertions import System import Hamming collect : {default 0 acc : Nat} -> (List (IO Bool)) -> IO Nat collect {acc} [] = pure acc collect {acc} (test :: tests) = do bool <- test case bool of True => collect {acc=acc} tests False => collect {acc=S acc} tests export runTests : IO () runTests = do let empty = the (Vect _ Nucleotide) [] count <- collect [ assertEquals (hamming_distance [A] [A]) 0 , assertEquals (hamming_distance [G,G,A,C,T,G,A] [G,G,A,C,T,G,A]) 0 , assertEquals (hamming_distance [A] [G]) 1 , assertEquals (hamming_distance [A,G] [C,T]) 2 , assertEquals (hamming_distance [A,T] [C,T]) 1 , assertEquals (hamming_distance [G,G,A,C,G] [G,G,T,C,G]) 1 , assertEquals (hamming_distance [A,C,C,A,G,G,G] [A,C,T,A,T,G,G]) 2 , assertEquals (hamming_distance [A,G,A] [A,G,G]) 1 , assertEquals (hamming_distance [A,G,G] [A,G,A]) 1 , assertEquals (hamming_distance [T,A,G] [G,A,T]) 2 , assertEquals (hamming_distance [G,A,T,A,C,A] [G,C,A,T,A,A]) 4 , assertEquals (hamming_distance [G,G,A,C,G,G,A,T,T,C,T,G] [A,G,G,A,C,G,G,A,T,T,C,T]) 9 , assertEquals (hamming_distance empty empty) 0 , assertEquals version "1.0.0" ] case count of Z => exitSuccess _ => exitFailure
(* Title: JinjaThreads/Common/Exceptions.thy Author: Gerwin Klein, Martin Strecker, Andreas Lochbihler Based on the Jinja theory Common/Exceptions.thy by Gerwin Klein and Martin Strecker *) section \<open>Exceptions\<close> theory Exceptions imports Value begin definition NullPointer :: cname where [code_unfold]: "NullPointer = STR ''java/lang/NullPointerException''" definition ClassCast :: cname where [code_unfold]: "ClassCast = STR ''java/lang/ClassCastException''" definition OutOfMemory :: cname where [code_unfold]: "OutOfMemory = STR ''java/lang/OutOfMemoryError''" definition ArrayIndexOutOfBounds :: cname where [code_unfold]: "ArrayIndexOutOfBounds = STR ''java/lang/ArrayIndexOutOfBoundsException''" definition ArrayStore :: cname where [code_unfold]: "ArrayStore = STR ''java/lang/ArrayStoreException''" definition NegativeArraySize :: cname where [code_unfold]: "NegativeArraySize = STR ''java/lang/NegativeArraySizeException''" definition ArithmeticException :: cname where [code_unfold]: "ArithmeticException = STR ''java/lang/ArithmeticException''" definition IllegalMonitorState :: cname where [code_unfold]: "IllegalMonitorState = STR ''java/lang/IllegalMonitorStateException''" definition IllegalThreadState :: cname where [code_unfold]: "IllegalThreadState = STR ''java/lang/IllegalThreadStateException''" definition InterruptedException :: cname where [code_unfold]: "InterruptedException = STR ''java/lang/InterruptedException''" definition sys_xcpts_list :: "cname list" where "sys_xcpts_list = [NullPointer, ClassCast, OutOfMemory, ArrayIndexOutOfBounds, ArrayStore, NegativeArraySize, ArithmeticException, IllegalMonitorState, IllegalThreadState, InterruptedException]" definition sys_xcpts :: "cname set" where [code_unfold]: "sys_xcpts = set sys_xcpts_list" definition wf_syscls :: "'m prog \<Rightarrow> bool" where "wf_syscls P \<equiv> (\<forall>C \<in> {Object, Throwable, Thread}. is_class P C) \<and> (\<forall>C \<in> sys_xcpts. P \<turnstile> C \<preceq>\<^sup>* Throwable)" subsection "System exceptions" lemma sys_xcpts_cases [consumes 1, cases set]: "\<lbrakk> C \<in> sys_xcpts; P NullPointer; P OutOfMemory; P ClassCast; P ArrayIndexOutOfBounds; P ArrayStore; P NegativeArraySize; P ArithmeticException; P IllegalMonitorState; P IllegalThreadState; P InterruptedException \<rbrakk> \<Longrightarrow> P C" by (auto simp add: sys_xcpts_def sys_xcpts_list_def) lemma OutOfMemory_not_Object[simp]: "OutOfMemory \<noteq> Object" by(simp add: OutOfMemory_def Object_def) lemma ClassCast_not_Object[simp]: "ClassCast \<noteq> Object" by(simp add: ClassCast_def Object_def) lemma NullPointer_not_Object[simp]: "NullPointer \<noteq> Object" by(simp add: NullPointer_def Object_def) lemma ArrayIndexOutOfBounds_not_Object[simp]: "ArrayIndexOutOfBounds \<noteq> Object" by(simp add: ArrayIndexOutOfBounds_def Object_def) lemma ArrayStore_not_Object[simp]: "ArrayStore \<noteq> Object" by(simp add: ArrayStore_def Object_def) lemma NegativeArraySize_not_Object[simp]: "NegativeArraySize \<noteq> Object" by(simp add: NegativeArraySize_def Object_def) lemma ArithmeticException_not_Object[simp]: "ArithmeticException \<noteq> Object" by(simp add: ArithmeticException_def Object_def) lemma IllegalMonitorState_not_Object[simp]: "IllegalMonitorState \<noteq> Object" by(simp add: IllegalMonitorState_def Object_def) lemma IllegalThreadState_not_Object[simp]: "IllegalThreadState \<noteq> Object" by(simp add: IllegalThreadState_def Object_def) lemma InterruptedException_not_Object[simp]: "InterruptedException \<noteq> Object" by(simp add: InterruptedException_def Object_def) lemma sys_xcpts_neqs_aux: "NullPointer \<noteq> ClassCast" "NullPointer \<noteq> OutOfMemory" "NullPointer \<noteq> ArrayIndexOutOfBounds" "NullPointer \<noteq> ArrayStore" "NullPointer \<noteq> NegativeArraySize" "NullPointer \<noteq> IllegalMonitorState" "NullPointer \<noteq> IllegalThreadState" "NullPointer \<noteq> InterruptedException" "NullPointer \<noteq> ArithmeticException" "ClassCast \<noteq> OutOfMemory" "ClassCast \<noteq> ArrayIndexOutOfBounds" "ClassCast \<noteq> ArrayStore" "ClassCast \<noteq> NegativeArraySize" "ClassCast \<noteq> IllegalMonitorState" "ClassCast \<noteq> IllegalThreadState" "ClassCast \<noteq> InterruptedException" "ClassCast \<noteq> ArithmeticException" "OutOfMemory \<noteq> ArrayIndexOutOfBounds" "OutOfMemory \<noteq> ArrayStore" "OutOfMemory \<noteq> NegativeArraySize" "OutOfMemory \<noteq> IllegalMonitorState" "OutOfMemory \<noteq> IllegalThreadState" "OutOfMemory \<noteq> InterruptedException" "OutOfMemory \<noteq> ArithmeticException" "ArrayIndexOutOfBounds \<noteq> ArrayStore" "ArrayIndexOutOfBounds \<noteq> NegativeArraySize" "ArrayIndexOutOfBounds \<noteq> IllegalMonitorState" "ArrayIndexOutOfBounds \<noteq> IllegalThreadState" "ArrayIndexOutOfBounds \<noteq> InterruptedException" "ArrayIndexOutOfBounds \<noteq> ArithmeticException" "ArrayStore \<noteq> NegativeArraySize" "ArrayStore \<noteq> IllegalMonitorState" "ArrayStore \<noteq> IllegalThreadState" "ArrayStore \<noteq> InterruptedException" "ArrayStore \<noteq> ArithmeticException" "NegativeArraySize \<noteq> IllegalMonitorState" "NegativeArraySize \<noteq> IllegalThreadState" "NegativeArraySize \<noteq> InterruptedException" "NegativeArraySize \<noteq> ArithmeticException" "IllegalMonitorState \<noteq> IllegalThreadState" "IllegalMonitorState \<noteq> InterruptedException" "IllegalMonitorState \<noteq> ArithmeticException" "IllegalThreadState \<noteq> InterruptedException" "IllegalThreadState \<noteq> ArithmeticException" "InterruptedException \<noteq> ArithmeticException" by(simp_all add: NullPointer_def ClassCast_def OutOfMemory_def ArrayIndexOutOfBounds_def ArrayStore_def NegativeArraySize_def IllegalMonitorState_def IllegalThreadState_def InterruptedException_def ArithmeticException_def) lemmas sys_xcpts_neqs = sys_xcpts_neqs_aux sys_xcpts_neqs_aux[symmetric] lemma Thread_neq_sys_xcpts_aux: "Thread \<noteq> NullPointer" "Thread \<noteq> ClassCast" "Thread \<noteq> OutOfMemory" "Thread \<noteq> ArrayIndexOutOfBounds" "Thread \<noteq> ArrayStore" "Thread \<noteq> NegativeArraySize" "Thread \<noteq> ArithmeticException" "Thread \<noteq> IllegalMonitorState" "Thread \<noteq> IllegalThreadState" "Thread \<noteq> InterruptedException" by(simp_all add: Thread_def NullPointer_def ClassCast_def OutOfMemory_def ArrayIndexOutOfBounds_def ArrayStore_def NegativeArraySize_def IllegalMonitorState_def IllegalThreadState_def InterruptedException_def ArithmeticException_def) lemmas Thread_neq_sys_xcpts = Thread_neq_sys_xcpts_aux Thread_neq_sys_xcpts_aux[symmetric] subsection \<open>Well-formedness for system classes and exceptions\<close> lemma assumes "wf_syscls P" shows wf_syscls_class_Object: "\<exists>C fs ms. class P Object = Some (C,fs,ms)" and wf_syscls_class_Thread: "\<exists>C fs ms. class P Thread = Some (C,fs,ms)" using assms by(auto simp: map_of_SomeI wf_syscls_def is_class_def) lemma [simp]: assumes "wf_syscls P" shows wf_syscls_is_class_Object: "is_class P Object" and wf_syscls_is_class_Thread: "is_class P Thread" using assms by(simp_all add: is_class_def wf_syscls_class_Object wf_syscls_class_Thread) lemma wf_syscls_xcpt_subcls_Throwable: "\<lbrakk> C \<in> sys_xcpts; wf_syscls P \<rbrakk> \<Longrightarrow> P \<turnstile> C \<preceq>\<^sup>* Throwable" by(simp add: wf_syscls_def is_class_def class_def) lemma wf_syscls_is_class_Throwable: "wf_syscls P \<Longrightarrow> is_class P Throwable" by(auto simp add: wf_syscls_def is_class_def class_def map_of_SomeI) lemma wf_syscls_is_class_sub_Throwable: "\<lbrakk> wf_syscls P; P \<turnstile> C \<preceq>\<^sup>* Throwable \<rbrakk> \<Longrightarrow> is_class P C" by(erule subcls_is_class1)(erule wf_syscls_is_class_Throwable) lemma wf_syscls_is_class_xcpt: "\<lbrakk> C \<in> sys_xcpts; wf_syscls P \<rbrakk> \<Longrightarrow> is_class P C" by(blast intro: wf_syscls_is_class_sub_Throwable wf_syscls_xcpt_subcls_Throwable) lemma wf_syscls_code [code]: "wf_syscls P \<longleftrightarrow> (\<forall>C \<in> set [Object, Throwable, Thread]. is_class P C) \<and> (\<forall>C \<in> sys_xcpts. P \<turnstile> C \<preceq>\<^sup>* Throwable)" by(simp only: wf_syscls_def) simp end
module AccuracyAtTop using ChainRulesCore using LinearAlgebra using Statistics using Distributions: Sampleable, Univariate, Continuous, Uniform using Random: AbstractRNG export All, Neg, Pos, LogUniform export Maximum, Minimum, Quantile, Kth, SampledQuantile export objective, predict, FNRate, FPRate, FNFPRate export AccAtTop, DeepTopPush, DeepTopPushK, PatMat, PatMatNP export hinge, quadratic, threshold, find_threshold export buffer, buffer_ts, buffer_inds, reset_buffer!, update_buffer!, BatchPartition # custom types abstract type Objective end abstract type Threshold end abstract type Indices end struct All <: Indices end struct Pos <: Indices end struct Neg <: Indices end Base.show(io::IO, ::Type{All}) = print(io, "all") Base.show(io::IO, ::Type{Neg}) = print(io, "negative") Base.show(io::IO, ::Type{Pos}) = print(io, "positive") include("thresholds.jl") include("objectives.jl") include("utilities.jl") # buffer const LAST_THRESHOLD = Ref{Vector{Float32}}([Inf32]) const LAST_THRESHOLD_IND = Ref{Vector{Int}}([1]) buffer() = LAST_THRESHOLD[], LAST_THRESHOLD_IND[] buffer_ts() = LAST_THRESHOLD[] buffer_inds() = LAST_THRESHOLD_IND[] function reset_buffer!() LAST_THRESHOLD[] = [Inf32] LAST_THRESHOLD_IND[] = [1] return end function update_buffer!(t, ind) LAST_THRESHOLD[] = [Vector(t)...,] LAST_THRESHOLD_IND[] = [Vector(ind)...,] return end end # module
import gbp import wave import whgo #import hog import time import cv2 import centrist import numpy as np import os directory = "/media/neduchal/data2/datasety/miniplaces/images" train_names = open("filelist.txt", "r").read().split("\n") if len(train_names[-1]) == 0: train_names = train_names[:-1] test_names = train_names[0:100] gbp_times = [] centrist_times = [] whgo_times = [] wave_times = [] cl = centrist.load() for t in test_names: fn = os.path.join(directory, t[7:]) img = cv2.imread(fn) # print(fn) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # GBP start = time.time() gbp.gbp(gray) gbp_times.append(time.time() - start) # CENTRIST start = time.time() centrist.centrist_im(cl, gray) centrist_times.append(time.time() - start) # WHGO start = time.time() whgo.whgo(gray, 16) whgo_times.append(time.time() - start) # WAVE start = time.time() wave.wave(gray) wave_times.append(time.time() - start) print("GBP time", np.mean(gbp_times)) print("CENTRIST time", np.mean(centrist_times)) print("WHGO time", np.mean(whgo_times)) print("WAVE time", np.mean(wave_times))
(* Copyright (C) 2017 M.A.L. Marques This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *) (* type: lda_exc *) params_a_alpha := 1: $include "lda_x.mpl" beta := rs -> (9*Pi/4)^(1/3)/(rs*M_C): phi := rs -> 1 - 1.5*(sqrt(1 + beta(rs)^2)/beta(rs) - arcsinh(beta(rs))/beta(rs)^2)^2: f := (rs, z) -> f_lda_x(rs, z)*phi(rs):
module CTL.Modalities.EF where open import FStream.Core open import Library -- Possibly sometime : s₀ ⊧ φ ⇔ ∃ s₀ R s₁ R ... ∃ i . sᵢ ⊧ φ data EF' {ℓ₁ ℓ₂} {C : Container ℓ₁} (props : FStream' C (Set ℓ₂)) : Set (ℓ₁ ⊔ ℓ₂) where alreadyE : head props → EF' props notYetE : E (fmap EF' (inF (tail props))) → EF' props open EF' EF : ∀ {ℓ₁ ℓ₂} {C : Container ℓ₁} → FStream C (Set ℓ₂) → Set (ℓ₁ ⊔ ℓ₂) EF props = APred EF' (inF props) mutual EFₛ' : ∀ {i ℓ₁ ℓ₂} {C : Container ℓ₁} → FStream' C (Set ℓ₂) → FStream' {i} C (Set (ℓ₁ ⊔ ℓ₂)) head (EFₛ' props) = EF' props tail (EFₛ' props) = EFₛ (tail props) EFₛ : ∀ {i ℓ₁ ℓ₂} {C : Container ℓ₁} → FStream C (Set ℓ₂) → FStream {i} C (Set (ℓ₁ ⊔ ℓ₂)) inF (EFₛ props) = fmap EFₛ' (inF props)
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 SUBROUTINE INHOLE (MR, N7, N29, JPNTR, IIN, IFOUND, IFHOLE, NHPR, & IHLIST, MERGE, NOROOM) C*********************************************************************** C SUBROUTINE INHOLE = INPUTS A REGION'S HOLES INTO THE DATABASE C*********************************************************************** DIMENSION IFHOLE(MR), NHPR(MR), IHLIST(MR*2) DIMENSION IIN(IFOUND) LOGICAL NOROOM, MERGE NOROOM = .TRUE. C ADD THE REGION INTO THE DATABASE J = JPNTR IFHOLE(J) = N29 + 1 DO 100 I = 1, IFOUND JJ = IIN(I) IF (JJ .EQ. 0) GO TO 110 N29 = N29 + 1 IF (N29 .GT. MR*2) RETURN IHLIST(N29) = JJ 100 CONTINUE 110 CONTINUE NHPR(J) = N29 - IFHOLE(J) + 1 IF (NHPR(J) .LT. 1) THEN WRITE(*, 10000) J N29 = IFHOLE(J) - 1 END IF NOROOM = .FALSE. RETURN 10000 FORMAT(' REGION:', I5, ' HAS LESS THAN ONE HOLE', /, & ' THE HOLES FOR THIS REGION WILL NOT BE INPUT INTO DATABASE') END
# Homework (Chapter 5) - 201601639 홍승현 - 연습문제 2, 3, 5 ## 연습문제 2 softmax를 적용한 후 출력이`(0.001, 0.9, 0.001, 0.098)^T`이고 레이블 정보가 `(0, 0, 0, 1)^T`일 때, 세가지 목적함수, 평균제곱 오차, 교차 엔트로피, 로그우도를 계산하시오. 행렬 연산을 수월하게 하기 위해 `numpy`를 사용하였다. ```python import numpy as np ``` ```python from sympy import * # 수식 표현을 위해 임포트 ``` ```python softmax_output = np.array([[0.001, 0.9, 0.001, 0.098]]).T label = np.array([[0, 0, 0, 1]]).T ``` ```python pprint(Eq(Symbol("softmax(x)"), Matrix(softmax_output), evaluate=False)) pprint(Eq(Symbol("label(x)"), Matrix(label), evaluate=False)) ``` ⎡0.001⎤ ⎢ ⎥ ⎢ 0.9 ⎥ softmax(x) = ⎢ ⎥ ⎢0.001⎥ ⎢ ⎥ ⎣0.098⎦ ⎡0⎤ ⎢ ⎥ ⎢0⎥ label(x) = ⎢ ⎥ ⎢0⎥ ⎢ ⎥ ⎣1⎦ ```python def mean_squared_error(y, t): return 0.5 * np.sum((y-t)**2) def cross_entropy_error(y, t): return -np.sum(y*np.log2(t)) ``` 1. MSE (평균제곱오차) ```python pprint(Eq(Symbol("MSE"), mean_squared_error(label, softmax_output))) ``` MSE = 0.811803 2. CCE (교차 엔트로피) ```python pprint(Eq(Symbol("CEE"), cross_entropy_error(label, softmax_output))) ``` CEE = 3.35107444054688 3. 로그우도 ```python log_likelihood = -np.log2(softmax_output) for i in range(log_likelihood.shape[0]): pprint(Eq(Symbol(f"o_{i}e"), Matrix(log_likelihood[i]), evaluate=False)) ``` o₀ₑ = [9.96578428466209] o₁ₑ = [0.15200309344505] o₂ₑ = [9.96578428466209] o₃ₑ = [3.35107444054688] ## 연습문제 3 [예제 5-1]에서 `λ = 0.1`, `λ = 0.5`일 때를 계산하고 λ에 따른 효과를 설명하시오. 이 때 [그림 5-21]을 활용하시오. ```python # 훈련집합 X = np.array([[1, 1], [2, 3], [3, 3]]) # label Y = np.array([[3.0, 7.0, 8.8]]).T pprint(Eq(Symbol("X"), Matrix(X), evaluate=False)) pprint(Eq(Symbol("Y"), Matrix(Y), evaluate=False)) ``` ⎡1 1⎤ ⎢ ⎥ X = ⎢2 3⎥ ⎢ ⎥ ⎣3 3⎦ ⎡3.0⎤ ⎢ ⎥ Y = ⎢7.0⎥ ⎢ ⎥ ⎣8.8⎦ ```python def ridge_regression(x, y, lamb): return np.linalg.inv(x.T.dot(x)+2*lamb*np.identity(2)).dot(x.T).dot(y) ``` ### λ = 0.25일 때 (기존 예제) ```python t = ridge_regression(X, Y, lamb=0.25) pprint(Eq(Symbol("λ_(025)"), Matrix(t), evaluate=False)) ``` ⎡1.49158878504673⎤ λ₍₀₂₅₎ = ⎢ ⎥ ⎣1.3607476635514 ⎦ ### λ = 0.1일 때 ```python t = ridge_regression(X, Y, lamb=0.1) pprint(Eq(Symbol("λ_(01)"), Matrix(t), evaluate=False)) ``` ⎡1.61538461538462⎤ λ₍₀₁₎ = ⎢ ⎥ ⎣1.27884615384616⎦ ### λ = 0.5일 때 ```python t = ridge_regression(X, Y, lamb=0.5) pprint(Eq(Symbol("λ_(05)"), Matrix(t), evaluate=False)) ``` ⎡1.4⎤ λ₍₀₅₎ = ⎢ ⎥ ⎣1.4⎦ ### λ = 0일 때 (기존 목적함수와 동일) ```python t = ridge_regression(X, Y, lamb=0) pprint(Eq(Symbol("λ_(05)"), Matrix(t), evaluate=False)) ``` ⎡1.82000000000001⎤ λ₍₀₅₎ = ⎢ ⎥ ⎣1.11999999999998⎦ ## 결론 - 위 값에 따라 `λ`가 기존 가중치를 원점에 소폭 가깝게 당긴 후 갱신한다는 것을 확인할 수 있다. ## 연습문제 5 혈압, 키, 몸무게가 특징벡터를 이룬다. 다음과 같이 훈련집합이 주어졌다. ```python train_data = np.array([[[121], [1.72], [69.0]], [[140], [1.62], [63.2]], [[120], [1.70], [59.0]], [[131], [1.80], [82.0]], [[101], [1.78], [73.5]]]) for i in range(train_data.shape[0]): pprint(Matrix(train_data[i])) ``` ⎡121.0⎤ ⎢ ⎥ ⎢1.72 ⎥ ⎢ ⎥ ⎣69.0 ⎦ ⎡140.0⎤ ⎢ ⎥ ⎢1.62 ⎥ ⎢ ⎥ ⎣63.2 ⎦ ⎡120.0⎤ ⎢ ⎥ ⎢ 1.7 ⎥ ⎢ ⎥ ⎣59.0 ⎦ ⎡131.0⎤ ⎢ ⎥ ⎢ 1.8 ⎥ ⎢ ⎥ ⎣82.0 ⎦ ⎡101.0⎤ ⎢ ⎥ ⎢1.78 ⎥ ⎢ ⎥ ⎣73.5 ⎦ ### 1. 퍼셉트론의 가중치 벡터가 `(-0.01, 0.5, -0.23)^T`이고 바이어스가 0이라고 했을 때, 훈련집합을 가지고 규모 문제를 설명하시오. ```python weight = np.array([[-0.01, 0.5, -0.23]]).T pprint(Eq(Symbol("weight"), Matrix(weight), evaluate=False)) ``` ⎡-0.01⎤ ⎢ ⎥ weight = ⎢ 0.5 ⎥ ⎢ ⎥ ⎣-0.23⎦ #### 각 훈련집합을 가중치로 곱한 값은 다음과 같다. ```python for train_set in train_data: print(np.sum(train_set*weight)) ``` -16.220000000000002 -15.126000000000001 -13.92 -19.27 -17.025000000000002 이를 `step function`으로 적용하였을 경우 ```python for train_set in train_data: print(np.heaviside(np.sum(train_set*weight), -999)) ``` 0.0 0.0 0.0 0.0 0.0 #### 중간결과 - 혈압, 키, 몸무게의 경우 단위에 따라 값의 규모가 확연하게 차이가 난다. - 예를 들어, 키가 178cm와 162cm의 차이는 16cm 만큼의 차이가 발생하지만 단위로 인해 특징값 차이는 불과 **0.16**밖에 차이가 나지 않는다. 또한 특징값이 모두 양수인 점을 비롯해 이러한 데이터는 수렴 속도가 굉장히 느려질 수 밖에 없다. - 결국, 서로의 단위로 인한 규모가 다양하여 `step function`을 적용했으나 전부 `0`으로 수렴하는 것을 확인할 수 있다. ### 2. 식 (5.9)의 전처리를 적용한 후의 훈련집합을 쓰시오. ```python pre_processing_data = (train_data - np.mean(train_data, axis=0)) / np.std(train_data, axis=0) ``` ```python for data in pre_processing_data: pprint(Matrix(data)) ``` ⎡-0.122772186962938 ⎤ ⎢ ⎥ ⎢-0.0627455805138124⎥ ⎢ ⎥ ⎣-0.0423472957199062⎦ ⎡ 1.33514753322196 ⎤ ⎢ ⎥ ⎢-1.63138509335921 ⎥ ⎢ ⎥ ⎣-0.764742340353592⎦ ⎡-0.199504803814775⎤ ⎢ ⎥ ⎢-0.376473483082892⎥ ⎢ ⎥ ⎣-1.28785599336419 ⎦ ⎡0.644553981555428⎤ ⎢ ⎥ ⎢1.19216602976251 ⎥ ⎢ ⎥ ⎣1.57681401121767 ⎦ ⎡-1.65742452399967⎤ ⎢ ⎥ ⎢0.878438127193427⎥ ⎢ ⎥ ⎣0.518131618220023⎦ ### 3. 전처리가 규모 문제를 완화하는지를 설명하시오. #### 정규화한 훈련집합에 가중치를 곱했을 경우 ```python for train_set in pre_processing_data: print(np.sum(train_set*weight)) ``` -0.02040519037169842 -0.6531532837304969 0.10996518497046617 0.2269702524856353 0.3366230366461046 `step function`을 적용하면 다음과 같다. ```python for train_set in pre_processing_data: print(np.heaviside(np.sum(train_set*weight), -999)) ``` 0.0 0.0 1.0 1.0 1.0 ### 결론 - 특징의 규모가 달라 이를 정규화 하면 각 값의 변화에 따라 걸맞게 변화되는 것을 확인할 수 있다. - 이를 통해 어떤 특징이 다른 특징보다 더 중요하게 작용한다는 것을 알고 있을 경우 규모 조절에 `정규화`를 활용할 수 있다.
import unittest import numpy as np import numpy.testing as npt import flavio from .fits import * from flavio.classes import * from flavio.statistics.probability import * from flavio.config import config import scipy.stats import copy import os import tempfile def fit_wc_fct_error(X): raise ValueError("Oops ... this should not have happened") class TestClasses(unittest.TestCase): def test_fit_class(self): o = Observable( 'test_obs' ) d = NormalDistribution(4.2, 0.2) par = copy.deepcopy(flavio.parameters.default_parameters) par.set_constraint('m_b', '4.2+-0.2') par.set_constraint('m_c', '1.2+-0.1') with self.assertRaises(AssertionError): # unconstrained observable Fit('test_fit_1', par, ['m_b'], ['m_c'], ['test_obs']) m = Measurement( 'measurement of test_obs' ) m.add_constraint(['test_obs'], d) with self.assertRaises(AssertionError): # same parameter as fit and nuisance Fit('test_fit_1', par, ['m_b'], ['m_b'], ['test_obs']) with self.assertRaises(AssertionError): # non-existent nuisance parameter Fit('test_fit_1', par, [], ['blabla'], ['test_obs']) def wc_fct(C): return {'CVLL_bsbs': C} with self.assertRaises(ValueError): # specify include_measurements and exclude_measurements simultaneously Fit('test_fit_1', par, ['m_b'], ['m_c'], ['test_obs'], fit_wc_function=wc_fct, include_measurements=['measurement of test_obs'], exclude_measurements=['measurement of test_obs']) fit = Fit('test_fit_1', par, ['m_b'], ['m_c'], ['test_obs'], fit_wc_function=wc_fct) self.assertEqual(fit.fit_parameters, ['m_b']) self.assertEqual(fit.nuisance_parameters, ['m_c']) self.assertEqual(fit.fit_wc_names, ('C',)) self.assertEqual(fit.get_measurements, ['measurement of test_obs']) self.assertEqual(fit.get_central_fit_parameters, [4.2]) self.assertEqual(fit.get_central_nuisance_parameters, [1.2]) # removing dummy instances Fit.del_instance('test_fit_1') Observable.del_instance('test_obs') Measurement.del_instance('measurement of test_obs') def test_correlation_warning(self): o1 = Observable( 'test_obs 1' ) o2 = Observable( 'test_obs 2' ) d1 = MultivariateNormalDistribution([1,2],[[1,0],[0,2]]) d2 = MultivariateNormalDistribution([1,2],[[1,0],[0,2]]) par = flavio.default_parameters m1 = Measurement( '1st measurement of test_obs 1 and 2' ) m1.add_constraint(['test_obs 1', 'test_obs 2'], d1) # this should not prompt a warning Fit('test_fit_1', par, [], [], observables=['test_obs 1']) m2 = Measurement( '2nd measurement of test_obs 1 and 2' ) m2.add_constraint(['test_obs 1', 'test_obs 2'], d2) # this should now prompt a warning with self.assertWarnsRegex(UserWarning, ".*test_fit_1.*test_obs 2.*test_obs 1.*"): Fit('test_fit_1', par, [], [], observables=['test_obs 1']) Fit.del_instance('test_fit_1') Observable.del_instance('test_obs 1') Observable.del_instance('test_obs 2') Measurement.del_instance('1st measurement of test_obs 1 and 2') Measurement.del_instance('2nd measurement of test_obs 1 and 2') def test_bayesian_fit_class(self): o = Observable( 'test_obs 2' ) o.arguments = ['q2'] def f(wc_obj, par_dict, q2): return par_dict['m_b']*2 *q2 pr = Prediction( 'test_obs 2', f ) d = NormalDistribution(4.2, 0.2) m = Measurement( 'measurement of test_obs 2' ) m.add_constraint([('test_obs 2', 3)], d) par = copy.deepcopy(flavio.parameters.default_parameters) par.set_constraint('m_b', '4.2+-0.2') par.set_constraint('m_c', '1.2+-0.1') par.set_constraint('m_s', '0.10(5)') wc = flavio.physics.eft.WilsonCoefficients() def wc_fct(CL, CR): return {'CVLL_bsbs': CL, 'CVRR_bsbs': CR} fit = BayesianFit('bayesian_test_fit_1', par, ['m_b','m_c'], ['m_s'], [('test_obs 2',3)], fit_wc_function=wc_fct) self.assertEqual(fit.get_measurements, ['measurement of test_obs 2']) self.assertEqual(fit.dimension, 5) # test from array to dict ... d = fit.array_to_dict(np.array([1.,2.,3.,4.,5.])) self.assertEqual(d, {'nuisance_parameters': {'m_s': 3.0}, 'fit_parameters': {'m_c': 2.0, 'm_b': 1.0}, 'fit_wc': {'CL': 4.0, 'CR': 5.0}}) # ... and back np.testing.assert_array_equal(fit.dict_to_array(d), np.array([1.,2.,3.,4.,5.])) self.assertEqual(fit.get_random.shape, (5,)) fit.log_prior_parameters(np.array([4.5,1.0,0.08,4.,5.])) fit.get_predictions(np.array([4.5,1.0,0.08,4.,5.])) fit.log_likelihood_exp(np.array([4.5,1.0,0.08,4.,5.])) # removing dummy instances BayesianFit.del_instance('bayesian_test_fit_1') Observable.del_instance('test_obs 2') Measurement.del_instance('measurement of test_obs 2') def test_fastfit(self): # dummy observables o1 = Observable( 'test_obs 1' ) o2 = Observable( 'test_obs 2' ) # dummy predictions def f1(wc_obj, par_dict): return par_dict['m_b'] def f2(wc_obj, par_dict): return 2.5 Prediction( 'test_obs 1', f1 ) Prediction( 'test_obs 2', f2 ) d1 = NormalDistribution(5, 0.2) cov2 = [[0.1**2, 0.5*0.1*0.3], [0.5*0.1*0.3, 0.3**2]] d2 = MultivariateNormalDistribution([6,2], cov2) m1 = Measurement( 'measurement 1 of test_obs 1' ) m2 = Measurement( 'measurement 2 of test_obs 1 and test_obs 2' ) m1.add_constraint(['test_obs 1'], d1) m2.add_constraint(['test_obs 1', 'test_obs 2'], d2) fit2 = FastFit('fastfit_test_2', flavio.default_parameters, ['m_b'], [], ['test_obs 1', 'test_obs 2']) # fit with only a single observable and measurement fit1 = FastFit('fastfit_test_1', flavio.default_parameters, ['m_b'], [], ['test_obs 2',]) for fit in (fit2, fit1): fit.make_measurement() centr_cov_exp_before = fit._exp_central_covariance filename = os.path.join(tempfile.gettempdir(), 'tmp.p') fit.save_exp_central_covariance(filename) fit.load_exp_central_covariance(filename) centr_cov_exp_after = fit._exp_central_covariance npt.assert_array_equal(centr_cov_exp_before[0], centr_cov_exp_after[0]) npt.assert_array_equal(centr_cov_exp_before[1], centr_cov_exp_after[1]) os.remove(filename) cov_before = fit._sm_covariance filename = os.path.join(tempfile.gettempdir(), 'tmp-no-p') fit.save_sm_covariance(filename) fit.load_sm_covariance(filename) cov_after = fit._sm_covariance npt.assert_array_equal(cov_before, cov_after) os.remove(filename) filename = os.path.join(tempfile.gettempdir(), 'tmp.p') fit.save_sm_covariance(filename) fit.load_sm_covariance(filename) cov_after = fit._sm_covariance npt.assert_array_equal(cov_before, cov_after) os.remove(filename) fit = fit2 # the following is only for fit2 cov_weighted = [[0.008, 0.012],[0.012,0.0855]] mean_weighted = [5.8, 1.7] exact_log_likelihood = scipy.stats.multivariate_normal.logpdf([5.9, 2.5], mean_weighted, cov_weighted) self.assertAlmostEqual(fit.log_likelihood([5.9]), exact_log_likelihood, delta=0.8) self.assertAlmostEqual(fit.best_fit()['x'], 5.9, delta=0.1) # removing dummy instances FastFit.del_instance('fastfit_test_1') FastFit.del_instance('fastfit_test_2') Observable.del_instance('test_obs 1') Observable.del_instance('test_obs 2') Measurement.del_instance('measurement 1 of test_obs 1') Measurement.del_instance('measurement 2 of test_obs 1 and test_obs 2') def test_fastfit_covariance_sm(self): # This test is to assure that calling make_measurement does not # actually call the fit_wc_function # dummy observables o1 = Observable( 'test_obs 1' ) # dummy predictions def f1(wc_obj, par_dict): return par_dict['m_b'] Prediction( 'test_obs 1', f1 ) d1 = NormalDistribution(5, 0.2) m1 = Measurement( 'measurement 1 of test_obs 1' ) m1.add_constraint(['test_obs 1'], d1) def fit_wc_fct_tmp(X): pass fit = FastFit('fastfit_test_1', flavio.default_parameters, ['m_b'], [], ['test_obs 1'], fit_wc_function=fit_wc_fct_tmp) fit.fit_wc_function = fit_wc_fct_error fit.fit_wc_names = tuple(inspect.signature(fit.fit_wc_function).parameters.keys()) fit.make_measurement() # single thread calculation FastFit.del_instance('fastfit_test_1') fit = FastFit('fastfit_test_1', flavio.default_parameters, ['m_b'], [], ['test_obs 1'], fit_wc_function=fit_wc_fct_tmp) fit.fit_wc_function = fit_wc_fct_error fit.fit_wc_names = tuple(inspect.signature(fit.fit_wc_function).parameters.keys()) fit.make_measurement(threads=2) # multi thread calculation FastFit.del_instance('fastfit_test_1') Observable.del_instance('test_obs 1') Measurement.del_instance('measurement 1 of test_obs 1') def test_frequentist_fit_class(self): o = Observable( 'test_obs 2' ) o.arguments = ['q2'] def f(wc_obj, par_dict, q2): return par_dict['m_b']*2 *q2 pr = Prediction( 'test_obs 2', f ) d = NormalDistribution(4.2, 0.2) m = Measurement( 'measurement of test_obs 2' ) m.add_constraint([('test_obs 2', 3)], d) par = copy.deepcopy(flavio.parameters.default_parameters) par.set_constraint('m_b', '4.2+-0.2') par.set_constraint('m_c', '1.2+-0.1') par.set_constraint('m_s', '0.10(5)') wc = flavio.physics.eft.WilsonCoefficients() def wc_fct(CL, CR): return {'CVLL_bsbs': CL, 'CVRR_bsbs': CR} fit = FrequentistFit('frequentist_test_fit_1', par, ['m_b','m_c'], ['m_s'], [('test_obs 2',3)], fit_wc_function=wc_fct) self.assertEqual(fit.get_measurements, ['measurement of test_obs 2']) self.assertEqual(fit.dimension, 5) # test from array to dict ... d = fit.array_to_dict(np.array([1.,2.,3.,4.,5.])) self.assertEqual(d, {'nuisance_parameters': {'m_s': 3.0}, 'fit_parameters': {'m_c': 2.0, 'm_b': 1.0}, 'fit_wc': {'CL': 4.0, 'CR': 5.0}}) # ... and back np.testing.assert_array_equal(fit.dict_to_array(d), np.array([1.,2.,3.,4.,5.])) fit.log_prior_parameters(np.array([4.5,1.0,0.08,4.,5.])) fit.get_predictions(np.array([4.5,1.0,0.08,4.,5.])) fit.log_likelihood_exp(np.array([4.5,1.0,0.08,4.,5.])) fit.log_likelihood(np.array([4.5,1.0,0.08,4.,5.])) # removing dummy instances FrequentistFit.del_instance('frequentist_test_fit_1') Observable.del_instance('test_obs 2') Measurement.del_instance('measurement of test_obs 2') def test_yaml_load(self): # minimal example fit = FastFit.load(r""" name: my test fit observables: - eps_K """) self.assertEqual(fit.name, 'my test fit') self.assertListEqual(fit.observables, ['eps_K']) # torture example fit = FastFit.load(r""" name: my test fit 2 observables: - name: <dBR/dq2>(B0->K*mumu) q2min: 1.1 q2max: 6 - [<dBR/dq2>(B0->K*mumu), 15, 19] nuisance_parameters: - Vub - Vcb fit_parameters: - gamma input_scale: 1000 fit_wc_eft: SMEFT fit_wc_basis: Warsaw include_measurements: - LHCb B0->K*mumu BR 2016 """) self.assertEqual(fit.name, 'my test fit 2') self.assertListEqual(fit.observables, [('<dBR/dq2>(B0->K*mumu)', 1.1, 6), ('<dBR/dq2>(B0->K*mumu)', 15, 19)]) # dump and load back again fit = FastFit.load(fit.dump().replace('my test fit 2', 'my test fit 2.1')) self.assertEqual(fit.name, 'my test fit 2.1') self.assertListEqual(fit.observables, [('<dBR/dq2>(B0->K*mumu)', 1.1, 6), ('<dBR/dq2>(B0->K*mumu)', 15, 19)]) def test_load_function(self): fit = FastFit.load(r""" name: my test fit 3 observables: - [<dBR/dq2>(B0->K*mumu), 15, 19] input_scale: 1000 fit_wc_eft: SMEFT fit_wc_basis: Warsaw fit_wc_function: args: - C9_bsmumu - C10_bsmumu """) self.assertTupleEqual(fit.fit_wc_names, ('C9_bsmumu', 'C10_bsmumu')) self.assertDictEqual(fit.fit_wc_function(1, 2), {'C9_bsmumu': 1, 'C10_bsmumu': 2}) # dump and load back again s = fit.dump().replace('my test fit 3', 'my test fit 3.1') fit = FastFit.load(s) self.assertTupleEqual(fit.fit_wc_names, ('C9_bsmumu', 'C10_bsmumu')) self.assertDictEqual(fit.fit_wc_function(1, 2), {'C9_bsmumu': 1, 'C10_bsmumu': 2}) fit = FastFit.load(r""" name: my test fit 5 observables: - [<dBR/dq2>(B0->K*mumu), 15, 19] input_scale: 1000 fit_wc_eft: SMEFT fit_wc_basis: Warsaw fit_wc_function: args: - C9 - C10 return: C9_bsmumu: 10 * C9 C10_bsmumu: 30 * C10 """) self.assertTupleEqual(fit.fit_wc_names, ('C9', 'C10')) self.assertDictEqual(fit.fit_wc_function(1, 2), {'C9_bsmumu': 10, 'C10_bsmumu': 60}) fit = FastFit.load(r""" name: my test fit 4 observables: - [<dBR/dq2>(B0->K*mumu), 15, 19] input_scale: 1000 fit_wc_eft: SMEFT fit_wc_basis: Warsaw fit_wc_function: code: | def f(C9, C10): return {'C9_bsmumu': 10 * C9, 'C10_bsmumu': 30 * C10} """) self.assertTupleEqual(fit.fit_wc_names, ('C9', 'C10')) self.assertDictEqual(fit.fit_wc_function(1, 2), {'C9_bsmumu': 10, 'C10_bsmumu': 60}) # dump and load back again s = fit.dump().replace('my test fit 4', 'my test fit 4.1') fit = FastFit.load(s) self.assertTupleEqual(fit.fit_wc_names, ('C9', 'C10')) self.assertDictEqual(fit.fit_wc_function(1, 2), {'C9_bsmumu': 10, 'C10_bsmumu': 60}) fit = FastFit.load(r""" name: my test fit 5 observables: - [<dBR/dq2>(B0->K*mumu), 15, 19] input_scale: 1000 fit_wc_eft: SMEFT fit_wc_basis: Warsaw fit_wc_function: code: | from math import sqrt def f(C9, C10): return {'C9_bsmumu': 10 * sqrt(C9), 'C10_bsmumu': 30 * C10} """) self.assertTupleEqual(fit.fit_wc_names, ('C9', 'C10')) self.assertDictEqual(fit.fit_wc_function(4, 2), {'C9_bsmumu': 20.0, 'C10_bsmumu': 60}) # dump and load back again s = fit.dump().replace('my test fit 5', 'my test fit 5.1') fit = FastFit.load(s) self.assertTupleEqual(fit.fit_wc_names, ('C9', 'C10')) self.assertDictEqual(fit.fit_wc_function(4, 2), {'C9_bsmumu': 20., 'C10_bsmumu': 60}) def myf(C9, C10): return {'C9_bsmumu': 10 * C9, 'C10_bsmumu': 30 * C10} fit = FastFit('my test fit 6', observables=[('<dBR/dq2>(B0->K*mumu)', 15, 19)], input_scale=1000, fit_wc_eft='SMEFT', fit_wc_basis='Warsaw', fit_wc_function=myf) s = fit.dump() fit = FastFit.load(s) self.assertTupleEqual(fit.fit_wc_names, ('C9', 'C10')) self.assertDictEqual(fit.fit_wc_function(1, 2), {'C9_bsmumu': 10, 'C10_bsmumu': 60}) from math import floor def myf(C9, C10): return {'C9_bsmumu': floor(C9), 'C10_bsmumu': 30 * C10} fit = FastFit('my test fit 7', observables=[('<dBR/dq2>(B0->K*mumu)', 15, 19)], input_scale=1000, fit_wc_eft='SMEFT', fit_wc_basis='Warsaw', fit_wc_function=myf) s = fit.dump() fit = FastFit.load(s) self.assertTupleEqual(fit.fit_wc_names, ('C9', 'C10')) self.assertDictEqual(fit.fit_wc_function(2.123, 2), {'C9_bsmumu': 2, 'C10_bsmumu': 60}) def myf(C9, C10): return {'C9_bsmumu': abs(C9), 'C10_bsmumu': 30 * C10} fit = FastFit('my test fit 8', observables=[('<dBR/dq2>(B0->K*mumu)', 15, 19)], input_scale=1000, fit_wc_eft='SMEFT', fit_wc_basis='Warsaw', fit_wc_function=myf) s = fit.dump() fit = FastFit.load(s) self.assertTupleEqual(fit.fit_wc_names, ('C9', 'C10')) self.assertDictEqual(fit.fit_wc_function(-1, 2), {'C9_bsmumu': 1, 'C10_bsmumu': 60}) def test_yaml_load_par(self): # don't modify parameters mb = flavio.default_parameters.get_central('m_b') fit = FastFit.load(r""" name: my test fit 7 observables: - eps_K """) self.assertEqual(fit.par_obj.get_central('m_b'), mb) # modify m_b fit = FastFit.load(r""" name: my test fit 8 par_obj: - m_b: 4 +- 0.2 observables: - eps_K """) self.assertEqual(fit.par_obj.get_central('m_b'), 4) # different way to write the same thing fit = FastFit.load(r""" name: my test fit 9 par_obj: - parameters: - m_b values: - distribution: normal central_value: 4 standard_deviation: 0.2 observables: - eps_K """) self.assertEqual(fit.par_obj.get_central('m_b'), 4) # check that we haven't accidentally modified the default parameters self.assertEqual(flavio.default_parameters.get_central('m_b'), mb) def test_yaml_dump_par(self): # don't modify parameters par = flavio.default_parameters.copy() par.set_constraint('m_b', '[2,4]') fit_par = FastFit('my test fit 10', observables=['eps_K'], par_obj=par) dumpdict = flavio.io.yaml.load_include(fit_par.dump()) self.assertIn('par_obj', dumpdict) self.assertEqual(len(dumpdict['par_obj']), 1) self.assertDictEqual(dumpdict['par_obj'][0], { 'parameters': ['m_b'], 'values': {'distribution': 'uniform', 'central_value': 3, 'half_range': 1} }) # default parameters fit_def = FastFit('my test fit 11', observables=['eps_K']) dumpdict = flavio.io.yaml.load_include(fit_def.dump()) self.assertNotIn('par_obj', dumpdict)
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.pi.algebra import algebra.hom.group import algebra.order.group.instances import algebra.order.monoid.with_zero.defs import order.hom.basic /-! # Ordered monoid and group homomorphisms > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines morphisms between (additive) ordered monoids. ## Types of morphisms * `order_add_monoid_hom`: Ordered additive monoid homomorphisms. * `order_monoid_hom`: Ordered monoid homomorphisms. * `order_monoid_with_zero_hom`: Ordered monoid with zero homomorphisms. ## Typeclasses * `order_add_monoid_hom_class` * `order_monoid_hom_class` * `order_monoid_with_zero_hom_class` ## Notation * `→+o`: Bundled ordered additive monoid homs. Also use for additive groups homs. * `→*o`: Bundled ordered monoid homs. Also use for groups homs. * `→*₀o`: Bundled ordered monoid with zero homs. Also use for groups with zero homs. ## Implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `order_group_hom` -- the idea is that `order_monoid_hom` is used. The constructor for `order_monoid_hom` needs a proof of `map_one` as well as `map_mul`; a separate constructor `order_monoid_hom.mk'` will construct ordered group homs (i.e. ordered monoid homs between ordered groups) given only a proof that multiplication is preserved, Implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type `order_monoid_hom`. When they can be inferred from the type it is faster to use this method than to use type class inference. ## Tags ordered monoid, ordered group, monoid with zero -/ open function variables {F α β γ δ : Type*} section add_monoid /-- `α →+o β` is the type of monotone functions `α → β` that preserve the `ordered_add_comm_monoid` structure. `order_add_monoid_hom` is also used for ordered group homomorphisms. When possible, instead of parametrizing results over `(f : α →+o β)`, you should parametrize over `(F : Type*) [order_add_monoid_hom_class F α β] (f : F)`. When you extend this structure, make sure to extend `order_add_monoid_hom_class`. -/ structure order_add_monoid_hom (α β : Type*) [preorder α] [preorder β] [add_zero_class α] [add_zero_class β] extends α →+ β := (monotone' : monotone to_fun) infixr ` →+o `:25 := order_add_monoid_hom section set_option old_structure_cmd true /-- `order_add_monoid_hom_class F α β` states that `F` is a type of ordered monoid homomorphisms. You should also extend this typeclass when you extend `order_add_monoid_hom`. -/ @[ancestor add_monoid_hom_class] class order_add_monoid_hom_class (F : Type*) (α β : out_param $ Type*) [preorder α] [preorder β] [add_zero_class α] [add_zero_class β] extends add_monoid_hom_class F α β := (monotone (f : F) : monotone f) end -- Instances and lemmas are defined below through `@[to_additive]`. end add_monoid section monoid variables [preorder α] [preorder β] [mul_one_class α] [mul_one_class β] /-- `α →*o β` is the type of functions `α → β` that preserve the `ordered_comm_monoid` structure. `order_monoid_hom` is also used for ordered group homomorphisms. When possible, instead of parametrizing results over `(f : α →*o β)`, you should parametrize over `(F : Type*) [order_monoid_hom_class F α β] (f : F)`. When you extend this structure, make sure to extend `order_monoid_hom_class`. -/ @[to_additive] structure order_monoid_hom (α β : Type*) [preorder α] [preorder β] [mul_one_class α] [mul_one_class β] extends α →* β := (monotone' : monotone to_fun) infixr ` →*o `:25 := order_monoid_hom section set_option old_structure_cmd true /-- `order_monoid_hom_class F α β` states that `F` is a type of ordered monoid homomorphisms. You should also extend this typeclass when you extend `order_monoid_hom`. -/ @[ancestor monoid_hom_class, to_additive] class order_monoid_hom_class (F : Type*) (α β : out_param $ Type*) [preorder α] [preorder β] [mul_one_class α] [mul_one_class β] extends monoid_hom_class F α β := (monotone (f : F) : monotone f) end @[priority 100, to_additive] -- See note [lower instance priority] instance order_monoid_hom_class.to_order_hom_class [order_monoid_hom_class F α β] : order_hom_class F α β := { map_rel := order_monoid_hom_class.monotone, .. ‹order_monoid_hom_class F α β› } @[to_additive] instance [order_monoid_hom_class F α β] : has_coe_t F (α →*o β) := ⟨λ f, { to_fun := f, map_one' := map_one f, map_mul' := map_mul f, monotone' := order_monoid_hom_class.monotone _ }⟩ end monoid section monoid_with_zero variables [preorder α] [preorder β] [mul_zero_one_class α] [mul_zero_one_class β] /-- `order_monoid_with_zero_hom α β` is the type of functions `α → β` that preserve the `monoid_with_zero` structure. `order_monoid_with_zero_hom` is also used for group homomorphisms. When possible, instead of parametrizing results over `(f : α →+ β)`, you should parametrize over `(F : Type*) [order_monoid_with_zero_hom_class F α β] (f : F)`. When you extend this structure, make sure to extend `order_monoid_with_zero_hom_class`. -/ structure order_monoid_with_zero_hom (α β : Type*) [preorder α] [preorder β] [mul_zero_one_class α] [mul_zero_one_class β] extends α →*₀ β := (monotone' : monotone to_fun) infixr ` →*₀o `:25 := order_monoid_with_zero_hom section set_option old_structure_cmd true /-- `order_monoid_with_zero_hom_class F α β` states that `F` is a type of ordered monoid with zero homomorphisms. You should also extend this typeclass when you extend `order_monoid_with_zero_hom`. -/ class order_monoid_with_zero_hom_class (F : Type*) (α β : out_param $ Type*) [preorder α] [preorder β] [mul_zero_one_class α] [mul_zero_one_class β] extends monoid_with_zero_hom_class F α β := (monotone (f : F) : monotone f) end @[priority 100] -- See note [lower instance priority] instance order_monoid_with_zero_hom_class.to_order_monoid_hom_class [order_monoid_with_zero_hom_class F α β] : order_monoid_hom_class F α β := { .. ‹order_monoid_with_zero_hom_class F α β› } instance [order_monoid_with_zero_hom_class F α β] : has_coe_t F (α →*₀o β) := ⟨λ f, { to_fun := f, map_one' := map_one f, map_zero' := map_zero f, map_mul' := map_mul f, monotone' := order_monoid_with_zero_hom_class.monotone _ }⟩ end monoid_with_zero section ordered_add_comm_monoid variables [ordered_add_comm_monoid α] [ordered_add_comm_monoid β] [order_add_monoid_hom_class F α β] (f : F) {a : α} include β lemma map_nonneg (ha : 0 ≤ a) : 0 ≤ f a := by { rw ←map_zero f, exact order_hom_class.mono _ ha } lemma map_nonpos (ha : a ≤ 0) : f a ≤ 0 := by { rw ←map_zero f, exact order_hom_class.mono _ ha } end ordered_add_comm_monoid section ordered_add_comm_group variables [ordered_add_comm_group α] [ordered_add_comm_monoid β] [add_monoid_hom_class F α β] (f : F) lemma monotone_iff_map_nonneg : monotone (f : α → β) ↔ ∀ a, 0 ≤ a → 0 ≤ f a := ⟨λ h a, by { rw ←map_zero f, apply h }, λ h a b hl, by { rw [←sub_add_cancel b a, map_add f], exact le_add_of_nonneg_left (h _ $ sub_nonneg.2 hl) }⟩ lemma antitone_iff_map_nonpos : antitone (f : α → β) ↔ ∀ a, 0 ≤ a → f a ≤ 0 := monotone_to_dual_comp_iff.symm.trans $ monotone_iff_map_nonneg _ lemma monotone_iff_map_nonpos : monotone (f : α → β) ↔ ∀ a ≤ 0, f a ≤ 0 := antitone_comp_of_dual_iff.symm.trans $ antitone_iff_map_nonpos _ lemma antitone_iff_map_nonneg : antitone (f : α → β) ↔ ∀ a ≤ 0, 0 ≤ f a := monotone_comp_of_dual_iff.symm.trans $ monotone_iff_map_nonneg _ variable [covariant_class β β (+) (<)] lemma strict_mono_iff_map_pos : strict_mono (f : α → β) ↔ ∀ a, 0 < a → 0 < f a := ⟨λ h a, by { rw ←map_zero f, apply h }, λ h a b hl, by { rw [←sub_add_cancel b a, map_add f], exact lt_add_of_pos_left _ (h _ $ sub_pos.2 hl) }⟩ lemma strict_anti_iff_map_neg : strict_anti (f : α → β) ↔ ∀ a, 0 < a → f a < 0 := strict_mono_to_dual_comp_iff.symm.trans $ strict_mono_iff_map_pos _ lemma strict_mono_iff_map_neg : strict_mono (f : α → β) ↔ ∀ a < 0, f a < 0 := strict_anti_comp_of_dual_iff.symm.trans $ strict_anti_iff_map_neg _ lemma strict_anti_iff_map_pos : strict_anti (f : α → β) ↔ ∀ a < 0, 0 < f a := strict_mono_comp_of_dual_iff.symm.trans $ strict_mono_iff_map_pos _ end ordered_add_comm_group namespace order_monoid_hom section preorder variables [preorder α] [preorder β] [preorder γ] [preorder δ] [mul_one_class α] [mul_one_class β] [mul_one_class γ] [mul_one_class δ] {f g : α →*o β} @[to_additive] instance : order_monoid_hom_class (α →*o β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_mul := λ f, f.map_mul', map_one := λ f, f.map_one', monotone := λ f, f.monotone' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ @[to_additive "Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly."] instance : has_coe_to_fun (α →*o β) (λ _, α → β) := fun_like.has_coe_to_fun -- Other lemmas should be accessed through the `fun_like` API @[ext, to_additive] lemma ext (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h @[to_additive] lemma to_fun_eq_coe (f : α →*o β) : f.to_fun = (f : α → β) := rfl @[simp, to_additive] lemma coe_mk (f : α →* β) (h) : (order_monoid_hom.mk f h : α → β) = f := rfl @[simp, to_additive] lemma mk_coe (f : α →*o β) (h) : order_monoid_hom.mk (f : α →* β) h = f := by { ext, refl } /-- Reinterpret an ordered monoid homomorphism as an order homomorphism. -/ @[to_additive "Reinterpret an ordered additive monoid homomorphism as an order homomorphism."] def to_order_hom (f : α →*o β) : α →o β := { ..f } @[simp, to_additive] lemma coe_monoid_hom (f : α →*o β) : ((f : α →* β) : α → β) = f := rfl @[simp, to_additive] lemma coe_order_hom (f : α →*o β) : ((f : α →o β) : α → β) = f := rfl @[to_additive] lemma to_monoid_hom_injective : injective (to_monoid_hom : _ → α →* β) := λ f g h, ext $ by convert fun_like.ext_iff.1 h @[to_additive] lemma to_order_hom_injective : injective (to_order_hom : _ → α →o β) := λ f g h, ext $ by convert fun_like.ext_iff.1 h /-- Copy of an `order_monoid_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ @[to_additive "Copy of an `order_monoid_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities."] protected def copy (f : α →*o β) (f' : α → β) (h : f' = f) : α →*o β := { to_fun := f', monotone' := h.symm.subst f.monotone', ..f.to_monoid_hom.copy f' h } @[simp, to_additive] lemma coe_copy (f : α →*o β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl @[to_additive] lemma copy_eq (f : α →*o β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- The identity map as an ordered monoid homomorphism. -/ @[to_additive "The identity map as an ordered additive monoid homomorphism."] protected def id : α →*o α := { ..monoid_hom.id α, ..order_hom.id } @[simp, to_additive] lemma coe_id : ⇑(order_monoid_hom.id α) = id := rfl @[to_additive] instance : inhabited (α →*o α) := ⟨order_monoid_hom.id α⟩ variables {α} /-- Composition of `order_monoid_hom`s as an `order_monoid_hom`. -/ @[to_additive "Composition of `order_add_monoid_hom`s as an `order_add_monoid_hom`"] def comp (f : β →*o γ) (g : α →*o β) : α →*o γ := { ..f.to_monoid_hom.comp (g : α →* β), ..f.to_order_hom.comp (g : α →o β) } @[simp, to_additive] lemma coe_comp (f : β →*o γ) (g : α →*o β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp, to_additive] lemma comp_apply (f : β →*o γ) (g : α →*o β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp, to_additive] lemma coe_comp_monoid_hom (f : β →*o γ) (g : α →*o β) : (f.comp g : α →* γ) = (f : β →* γ).comp g := rfl @[simp, to_additive] lemma coe_comp_order_hom (f : β →*o γ) (g : α →*o β) : (f.comp g : α →o γ) = (f : β →o γ).comp g := rfl @[simp, to_additive] lemma comp_assoc (f : γ →*o δ) (g : β →*o γ) (h : α →*o β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp, to_additive] lemma comp_id (f : α →*o β) : f.comp (order_monoid_hom.id α) = f := ext $ λ a, rfl @[simp, to_additive] lemma id_comp (f : α →*o β) : (order_monoid_hom.id β).comp f = f := ext $ λ a, rfl @[to_additive] lemma cancel_right {g₁ g₂ : β →*o γ} {f : α →*o β} (hf : function.surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ @[to_additive] lemma cancel_left {g : β →*o γ} {f₁ f₂ : α →*o β} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ /-- `1` is the homomorphism sending all elements to `1`. -/ @[to_additive "`1` is the homomorphism sending all elements to `1`."] instance : has_one (α →*o β) := ⟨{ monotone' := monotone_const, ..(1 : α →* β) }⟩ @[simp, to_additive] @[simp, to_additive] lemma one_comp (f : α →*o β) : (1 : β →*o γ).comp f = 1 := rfl @[simp, to_additive] lemma comp_one (f : β →*o γ) : f.comp (1 : α →*o β) = 1 := by { ext, exact map_one f } end preorder section mul variables [ordered_comm_monoid α] [ordered_comm_monoid β] [ordered_comm_monoid γ] /-- For two ordered monoid morphisms `f` and `g`, their product is the ordered monoid morphism sending `a` to `f a * g a`. -/ @[to_additive "For two ordered additive monoid morphisms `f` and `g`, their product is the ordered additive monoid morphism sending `a` to `f a + g a`."] instance : has_mul (α →*o β) := ⟨λ f g, { monotone' := f.monotone'.mul' g.monotone', ..(f * g : α →* β) }⟩ @[simp, to_additive] lemma coe_mul (f g : α →*o β) : ⇑(f * g) = f * g := rfl @[simp, to_additive] lemma mul_apply (f g : α →*o β) (a : α) : (f * g) a = f a * g a := rfl @[to_additive] lemma mul_comp (g₁ g₂ : β →*o γ) (f : α →*o β) : (g₁ * g₂).comp f = g₁.comp f * g₂.comp f := rfl @[to_additive] lemma comp_mul (g : β →*o γ) (f₁ f₂ : α →*o β) : g.comp (f₁ * f₂) = g.comp f₁ * g.comp f₂ := by { ext, exact map_mul g _ _ } end mul section ordered_comm_monoid variables {hα : ordered_comm_monoid α} {hβ : ordered_comm_monoid β} include hα hβ @[simp, to_additive] lemma to_monoid_hom_eq_coe (f : α →*o β) : f.to_monoid_hom = f := by { ext, refl } @[simp, to_additive] lemma to_order_hom_eq_coe (f : α →*o β) : f.to_order_hom = f := rfl end ordered_comm_monoid section ordered_comm_group variables {hα : ordered_comm_group α} {hβ : ordered_comm_group β} include hα hβ /-- Makes an ordered group homomorphism from a proof that the map preserves multiplication. -/ @[to_additive "Makes an ordered additive group homomorphism from a proof that the map preserves addition.", simps {fully_applied := ff}] def mk' (f : α → β) (hf : monotone f) (map_mul : ∀ a b : α, f (a * b) = f a * f b) : α →*o β := { monotone' := hf, ..monoid_hom.mk' f map_mul } end ordered_comm_group end order_monoid_hom namespace order_monoid_with_zero_hom section preorder variables [preorder α] [preorder β] [preorder γ] [preorder δ] [mul_zero_one_class α] [mul_zero_one_class β] [mul_zero_one_class γ] [mul_zero_one_class δ] {f g : α →*₀o β} instance : order_monoid_with_zero_hom_class (α →*₀o β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_mul := λ f, f.map_mul', map_one := λ f, f.map_one', map_zero := λ f, f.map_zero', monotone := λ f, f.monotone' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (α →*₀o β) (λ _, α → β) := fun_like.has_coe_to_fun -- Other lemmas should be accessed through the `fun_like` API @[ext] lemma ext (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h lemma to_fun_eq_coe (f : α →*₀o β) : f.to_fun = (f : α → β) := rfl @[simp] lemma coe_mk (f : α →*₀ β) (h) : (order_monoid_with_zero_hom.mk f h : α → β) = f := rfl @[simp] lemma mk_coe (f : α →*₀o β) (h) : order_monoid_with_zero_hom.mk (f : α →*₀ β) h = f := by { ext, refl } /-- Reinterpret an ordered monoid with zero homomorphism as an order monoid homomorphism. -/ def to_order_monoid_hom (f : α →*₀o β) : α →*o β := { ..f } @[simp] lemma coe_monoid_with_zero_hom (f : α →*₀o β) : ⇑(f : α →*₀ β) = f := rfl @[simp] lemma coe_order_monoid_hom (f : α →*₀o β) : ⇑(f : α →*o β) = f := rfl lemma to_order_monoid_hom_injective : injective (to_order_monoid_hom : _ → α →*o β) := λ f g h, ext $ by convert fun_like.ext_iff.1 h lemma to_monoid_with_zero_hom_injective : injective (to_monoid_with_zero_hom : _ → α →*₀ β) := λ f g h, ext $ by convert fun_like.ext_iff.1 h /-- Copy of an `order_monoid_with_zero_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : α →*₀o β) (f' : α → β) (h : f' = f) : α →*o β := { to_fun := f', .. f.to_order_monoid_hom.copy f' h, .. f.to_monoid_with_zero_hom.copy f' h } @[simp] lemma coe_copy (f : α →*₀o β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : α →*₀o β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- The identity map as an ordered monoid with zero homomorphism. -/ protected def id : α →*₀o α := { ..monoid_with_zero_hom.id α, ..order_hom.id } @[simp] lemma coe_id : ⇑(order_monoid_with_zero_hom.id α) = id := rfl instance : inhabited (α →*₀o α) := ⟨order_monoid_with_zero_hom.id α⟩ variables {α} /-- Composition of `order_monoid_with_zero_hom`s as an `order_monoid_with_zero_hom`. -/ def comp (f : β →*₀o γ) (g : α →*₀o β) : α →*₀o γ := { ..f.to_monoid_with_zero_hom.comp (g : α →*₀ β), ..f.to_order_monoid_hom.comp (g : α →*o β) } @[simp] lemma coe_comp (f : β →*₀o γ) (g : α →*₀o β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] lemma comp_apply (f : β →*₀o γ) (g : α →*₀o β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma coe_comp_monoid_with_zero_hom (f : β →*₀o γ) (g : α →*₀o β) : (f.comp g : α →*₀ γ) = (f : β →*₀ γ).comp g := rfl @[simp] lemma coe_comp_order_monoid_hom (f : β →*₀o γ) (g : α →*₀o β) : (f.comp g : α →*o γ) = (f : β →*o γ).comp g := rfl @[simp] lemma comp_assoc (f : γ →*₀o δ) (g : β →*₀o γ) (h : α →*₀o β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : α →*₀o β) : f.comp (order_monoid_with_zero_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : α →*₀o β) : (order_monoid_with_zero_hom.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : β →*₀o γ} {f : α →*₀o β} (hf : function.surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : β →*₀o γ} {f₁ f₂ : α →*₀o β} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end preorder section mul variables [linear_ordered_comm_monoid_with_zero α] [linear_ordered_comm_monoid_with_zero β] [linear_ordered_comm_monoid_with_zero γ] /-- For two ordered monoid morphisms `f` and `g`, their product is the ordered monoid morphism sending `a` to `f a * g a`. -/ instance : has_mul (α →*₀o β) := ⟨λ f g, { monotone' := f.monotone'.mul' g.monotone', ..(f * g : α →*₀ β) }⟩ @[simp] lemma coe_mul (f g : α →*₀o β) : ⇑(f * g) = f * g := rfl @[simp] lemma mul_apply (f g : α →*₀o β) (a : α) : (f * g) a = f a * g a := rfl lemma mul_comp (g₁ g₂ : β →*₀o γ) (f : α →*₀o β) : (g₁ * g₂).comp f = g₁.comp f * g₂.comp f := rfl lemma comp_mul (g : β →*₀o γ) (f₁ f₂ : α →*₀o β) : g.comp (f₁ * f₂) = g.comp f₁ * g.comp f₂ := ext $ λ _, map_mul g _ _ end mul section linear_ordered_comm_monoid_with_zero variables {hα : preorder α} {hα' : mul_zero_one_class α} {hβ : preorder β} {hβ' : mul_zero_one_class β} include hα hα' hβ hβ' @[simp] lemma to_monoid_with_zero_hom_eq_coe (f : α →*₀o β) : f.to_monoid_with_zero_hom = f := by { ext, refl } @[simp] lemma to_order_monoid_hom_eq_coe (f : α →*₀o β) : f.to_order_monoid_hom = f := rfl end linear_ordered_comm_monoid_with_zero end order_monoid_with_zero_hom
import numpy as np from numpy import ndarray from typing import Callable, Tuple from pynverse import inversefunc from scipy.stats import chi2 from basic.types import vector, matrix, Configuration, elemental, TP_HOTELLING from basic.decorators import document, type_checker import basic.docfunc as doc import copy def _mvn_params(x: matrix) -> Tuple[vector, matrix]: return x.mean(axis=0), np.cov(x.T, bias=True) def _upper_domain(func: Callable, heuristic_step: float = 10) -> int: upper = heuristic_step while True: try: res = inversefunc(func, y_values=1, domain=[0, upper]) except ValueError: upper += heuristic_step # heuristically increase upper of domain else: return res def hotelling_threshold(df: int, level: float = 0.05) -> float: """calculate the threshold of chi2 distribution, by a given test level""" dis = chi2(df=df) upper = _upper_domain(dis.cdf, 10) return inversefunc(dis.cdf, y_values=1-level, domain=[0, upper]) def a(x: matrix, miu: vector, sigma: matrix) -> ndarray: res = [] m_inv = np.array(np.matrix(sigma).I) # inverse matrix for i in range(len(x)): _ = x[i] - miu res.append(np.matmul(np.matmul(_, m_inv), _.T)) return np.array(res) @document(doc.en_Hotelling) class Hotelling: settings: Configuration = { 'model_import': np.array([]), # ndarray, matrix-like 'level': 0.05, # float, 0~1 'data_import': np.array([]), # ndarray, matrix-like } @type_checker(in_class=True, kwargs_types=TP_HOTELLING, elemental_types=elemental) def __init__(self, **settings: Configuration): assert np.all([k in settings.keys() for k in ['model_import']]) == 1, 'missing required arg model_import.' self.settings.update({k: v for k, v in settings.items()}) self.model = self.settings.get('model_import') self.mean, self.sigma = _mvn_params(self.model) self.threshold = hotelling_threshold(self.model.shape[1], self.settings.get('level')) @type_checker(in_class=True, kwargs_types=TP_HOTELLING, elemental_types=elemental) @document(doc.en_Hotelling_predict) def predict(self, **settings: Configuration): assert np.all([k in settings.keys() for k in ['data_import']]) == 1, 'missing required arg data_import.' _settings = copy.deepcopy(self.settings) _settings.update({k: v for k, v in settings.items()}) return a(_settings.get('data_import'), self.mean, self.sigma) <= self.threshold if __name__ == '__main__': pass
function same=strcomp(str1,str2) %A local strcmp routine. Used. Not sure why. Left over from 1996. % % same=strcomp(str1,str2); % %Returns 1 if str1 == str2 %Returns 0 otherwise. % %4/12/96 gmb Why did I have to write this? % if length(str1)~=length(str2) same=0; return end for i=1:length(str1) if (str1(i)~=str2(i)) same=0; return end end same=1;
Formal statement is: lemma open_Collect_const: "open {x. P}" Informal statement is: The set of all $x$ such that $P$ is open.
-- MIT License -- Copyright (c) 2021 Luca Ciccone and Luca Padovani -- Permission is hereby granted, free of charge, to any person -- obtaining a copy of this software and associated documentation -- files (the "Software"), to deal in the Software without -- restriction, including without limitation the rights to use, -- copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the -- Software is furnished to do so, subject to the following -- conditions: -- The above copyright notice and this permission notice shall be -- included in all copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -- OTHER DEALINGS IN THE SOFTWARE. {-# OPTIONS --guardedness --sized-types #-} open import Size open import Data.Empty open import Data.Product open import Data.Sum open import Data.List using ([]; _∷_; _∷ʳ_; _++_) open import Codata.Thunk open import Relation.Nullary open import Relation.Nullary.Negation using (contraposition) open import Relation.Unary using (_∈_; _⊆_) open import Relation.Binary.PropositionalEquality using (_≡_; _≢_; refl) open import Function.Base using (case_of_) open import Common module Subtyping {ℙ : Set} (message : Message ℙ) where open Message message open import Trace message open import SessionType message open import Transitions message open import Session message open import Compliance message open import HasTrace message data Sub : SessionType -> SessionType -> Size -> Set where nil<:any : ∀{T i} -> Sub nil T i end<:def : ∀{T S i} (e : End T) (def : Defined S) -> Sub T S i inp<:inp : ∀{f g i} (inc : dom f ⊆ dom g) (F : (x : ℙ) -> Thunk (Sub (f x .force) (g x .force)) i) -> Sub (inp f) (inp g) i out<:out : ∀{f g i} (W : Witness g) (inc : dom g ⊆ dom f) (F : ∀{x} (!x : x ∈ dom g) -> Thunk (Sub (f x .force) (g x .force)) i) -> Sub (out f) (out g) i _<:_ : SessionType -> SessionType -> Set _<:_ T S = Sub T S ∞ sub-defined : ∀{T S} -> T <: S -> Defined T -> Defined S sub-defined (end<:def _ def) _ = def sub-defined (inp<:inp _ _) _ = inp sub-defined (out<:out _ _ _) _ = out sub-sound : ∀{T S R} -> Compliance (R # T) -> T <: S -> ∞Compliance (R # S) force (sub-sound (win#def w def) sub) = win#def w (sub-defined sub def) force (sub-sound (out#inp (_ , !x) F) (end<:def (inp U) def)) with U _ (proj₂ (compliance->defined (F !x .force))) ... | () force (sub-sound (out#inp (_ , !x) F) (inp<:inp _ G)) = out#inp (_ , !x) λ !x -> sub-sound (F !x .force) (G _ .force) force (sub-sound (inp#out (_ , !x) F) (end<:def (out U) def)) = ⊥-elim (U _ !x) force (sub-sound (inp#out (_ , !x) F) (out<:out {f} {g} (_ , !y) inc G)) = inp#out (_ , !y) λ !x -> sub-sound (F (inc !x) .force) (G !x .force) SubtypingQ : SessionType -> SessionType -> Set SubtypingQ T S = ∀{R} -> Compliance (R # T) -> Compliance (R # S) if-eq : ℙ -> SessionType -> SessionType -> Continuation force (if-eq x T S y) with x ?= y ... | yes _ = T ... | no _ = S input* : SessionType input* = inp λ _ -> λ where .force -> win input : ℙ -> SessionType -> SessionType -> SessionType input x T S = inp (if-eq x T S) input*-but : ℙ -> SessionType input*-but x = input x nil win output : ℙ -> SessionType -> SessionType -> SessionType output x T S = out (if-eq x T S) input-if-eq-comp : ∀{f x T} -> Compliance (T # f x .force) -> ∀{y} (!y : y ∈ dom f) -> ∞Compliance (if-eq x T win y .force # f y .force) force (input-if-eq-comp {_} {x} comp {y} !y) with x ?= y ... | yes refl = comp ... | no neq = win#def Win-win !y output-if-eq-comp : ∀{f : Continuation}{x}{T} -> Compliance (T # f x .force) -> ∀{y} (!y : y ∈ dom (if-eq x T nil)) -> ∞Compliance (if-eq x T nil y .force # f y .force) force (output-if-eq-comp {_} {x} comp {y} !y) with x ?= y ... | yes refl = comp force (output-if-eq-comp {_} {x} comp {y} ()) | no neq input*-comp : ∀{f} (W : Witness f) -> Compliance (input* # out f) input*-comp W = inp#out W λ !x -> λ where .force -> win#def Win-win !x input*-but-comp : ∀{f x} (W : Witness f) (N : ¬ x ∈ dom f) -> Compliance (input*-but x # out f) input*-but-comp {f} {x} W N = inp#out W aux where aux : ∀{y : ℙ} -> (fy : y ∈ dom f) -> ∞Compliance (if-eq x nil win y .force # f y .force) force (aux {y} fy) with x ?= y ... | yes refl = ⊥-elim (N fy) ... | no neq = win#def Win-win fy ∈-output-if-eq : ∀{R} (x : ℙ) -> Defined R -> x ∈ dom (if-eq x R nil) ∈-output-if-eq x def with x ?= x ... | yes refl = def ... | no neq = ⊥-elim (neq refl) input-comp : ∀{g x R} -> Compliance (R # g x .force) -> Compliance (input x R win # out g) input-comp {g} {x} comp = inp#out (x , proj₂ (compliance->defined comp)) (input-if-eq-comp {g} comp) output-comp : ∀{f x R} -> Compliance (R # f x .force) -> Compliance (output x R nil # inp f) output-comp {f} {x} comp = out#inp (_ , ∈-output-if-eq x (proj₁ (compliance->defined comp))) (output-if-eq-comp {f} comp) sub-inp-inp : ∀{f g} (spec : SubtypingQ (inp f) (inp g)) (x : ℙ) -> SubtypingQ (f x .force) (g x .force) sub-inp-inp spec x comp with spec (output-comp comp) ... | win#def (out U) def = ⊥-elim (U _ (∈-output-if-eq x (proj₁ (compliance->defined comp)))) ... | out#inp (y , fy) F with F fy .force ... | comp' with x ?= y ... | yes refl = comp' sub-inp-inp spec x comp | out#inp (y , fy) F | win#def () def | no neq sub-out-out : ∀{f g} (spec : SubtypingQ (out f) (out g)) -> ∀{x} -> x ∈ dom g -> SubtypingQ (f x .force) (g x .force) sub-out-out spec {x} gx comp with spec (input-comp comp) ... | inp#out W F with F gx .force ... | comp' with x ?= x ... | yes refl = comp' ... | no neq = ⊥-elim (neq refl) sub-out->def : ∀{f g} (spec : SubtypingQ (out f) (out g)) (Wf : Witness f) -> ∀{x} (gx : x ∈ dom g) -> x ∈ dom f sub-out->def {f} spec Wf {x} gx with x ∈? f ... | yes fx = fx ... | no nfx with spec (input*-but-comp Wf nfx) ... | inp#out W F with F gx .force ... | res with x ?= x sub-out->def {f} spec Wf {x} gx | no nfx | inp#out W F | win#def () def | yes refl ... | no neq = ⊥-elim (neq refl) sub-inp->def : ∀{f g} (spec : SubtypingQ (inp f) (inp g)) -> ∀{x} (fx : x ∈ dom f) -> x ∈ dom g sub-inp->def {f} spec {x} fx with spec {output x win nil} (output-comp (win#def Win-win fx)) ... | win#def (out U) def = ⊥-elim (U _ (∈-output-if-eq x out)) ... | out#inp W F with F (∈-output-if-eq x out) .force ... | comp = proj₂ (compliance->defined comp) sub-complete : ∀{T S i} -> SubtypingQ T S -> Thunk (Sub T S) i force (sub-complete {nil} {_} spec) = nil<:any force (sub-complete {inp f} {nil} spec) with spec {win} (win#def Win-win inp) ... | win#def _ () force (sub-complete {inp _} {inp _} spec) = inp<:inp (sub-inp->def spec) λ x -> sub-complete (sub-inp-inp spec x) force (sub-complete {inp f} {out _} spec) with Empty? f ... | inj₁ U = end<:def (inp U) out ... | inj₂ (x , ?x) with spec {output x win nil} (output-comp (win#def Win-win ?x)) ... | win#def (out U) def = ⊥-elim (U x (∈-output-if-eq x out)) force (sub-complete {out f} {nil} spec) with spec {win} (win#def Win-win out) ... | win#def _ () force (sub-complete {out f} {inp _} spec) with Empty? f ... | inj₁ U = end<:def (out U) inp ... | inj₂ W with spec {input*} (input*-comp W) ... | win#def () _ force (sub-complete {out f} {out g} spec) with Empty? f ... | inj₁ Uf = end<:def (out Uf) out ... | inj₂ Wf with Empty? g ... | inj₂ Wg = out<:out Wg (sub-out->def spec Wf) λ !x -> sub-complete (sub-out-out spec !x) ... | inj₁ Ug with spec {input*} (input*-comp Wf) ... | inp#out (_ , !x) F = ⊥-elim (Ug _ !x) SubtypingQ->SubtypingS : ∀{T S} -> SubtypingQ T S -> SubtypingS T S SubtypingQ->SubtypingS spec comp = compliance-sound (spec (compliance-complete comp .force)) SubtypingS->SubtypingQ : ∀{T S} -> SubtypingS T S -> SubtypingQ T S SubtypingS->SubtypingQ spec comp = compliance-complete (spec (compliance-sound comp)) .force sub-excluded : ∀{T S φ} (sub : T <: S) (tφ : T HasTrace φ) (nsφ : ¬ S HasTrace φ) -> ∃[ ψ ] ∃[ x ] (ψ ⊑ φ × T HasTrace ψ × S HasTrace ψ × T HasTrace (ψ ∷ʳ O x) × ¬ S HasTrace (ψ ∷ʳ O x)) sub-excluded nil<:any tφ nsφ = ⊥-elim (nil-has-no-trace tφ) sub-excluded (end<:def e def) tφ nsφ with end-has-empty-trace e tφ ... | eq rewrite eq = ⊥-elim (nsφ (_ , def , refl)) sub-excluded (inp<:inp inc F) (_ , tdef , refl) nsφ = ⊥-elim (nsφ (_ , inp , refl)) sub-excluded (inp<:inp {f} {g} inc F) (_ , tdef , step inp tr) nsφ = let ψ , x , pre , tψ , sψ , tψx , nψx = sub-excluded (F _ .force) (_ , tdef , tr) (contraposition inp-has-trace nsφ) in _ , _ , some pre , inp-has-trace tψ , inp-has-trace sψ , inp-has-trace tψx , inp-has-no-trace nψx sub-excluded (out<:out W inc F) (_ , tdef , refl) nsφ = ⊥-elim (nsφ (_ , out , refl)) sub-excluded (out<:out {f} {g} W inc F) (_ , tdef , step (out {_} {x} fx) tr) nsφ with x ∈? g ... | yes gx = let ψ , x , pre , tψ , sψ , tψx , nψx = sub-excluded (F gx .force) (_ , tdef , tr) (contraposition out-has-trace nsφ) in _ , _ , some pre , out-has-trace tψ , out-has-trace sψ , out-has-trace tψx , out-has-no-trace nψx ... | no ngx = [] , _ , none , (_ , out , refl) , (_ , out , refl) , (_ , fx , step (out fx) refl) , λ { (_ , _ , step (out gx) _) → ⊥-elim (ngx gx) } sub-after : ∀{T S φ} (tφ : T HasTrace φ) (sφ : S HasTrace φ) -> T <: S -> after tφ <: after sφ sub-after (_ , _ , refl) (_ , _ , refl) sub = sub sub-after tφ@(_ , _ , step inp _) (_ , _ , step inp _) (end<:def e _) with end-has-empty-trace e tφ ... | () sub-after (_ , tdef , step inp tr) (_ , sdef , step inp sr) (inp<:inp _ F) = sub-after (_ , tdef , tr) (_ , sdef , sr) (F _ .force) sub-after tφ@(_ , _ , step (out _) _) (_ , _ , step (out _) _) (end<:def e _) with end-has-empty-trace e tφ ... | () sub-after (_ , tdef , step (out _) tr) (_ , sdef , step (out gx) sr) (out<:out _ _ F) = sub-after (_ , tdef , tr) (_ , sdef , sr) (F gx .force) sub-simulation : ∀{R R' T S S' φ} (comp : Compliance (R # T)) (sub : T <: S) (rr : Transitions R (co-trace φ) R') (sr : Transitions S φ S') -> ∃[ T' ] (Transitions T φ T' × T' <: S') sub-simulation comp sub refl refl = _ , refl , sub sub-simulation (win#def (out U) def) sub (step (out hx) rr) (step inp sr) = ⊥-elim (U _ hx) sub-simulation (out#inp W F) (end<:def (inp U) def) (step (out hx) rr) (step inp sr) with F hx .force ... | comp = ⊥-elim (U _ (proj₂ (compliance->defined comp))) sub-simulation (out#inp W F) (inp<:inp inc G) (step (out hx) rr) (step inp sr) = let _ , tr , sub = sub-simulation (F hx .force) (G _ . force) rr sr in _ , step inp tr , sub sub-simulation (inp#out {h} {f} (_ , fx) F) (end<:def (out U) def) (step inp rr) (step (out gx) sr) with F fx .force ... | comp = ⊥-elim (U _ (proj₂ (compliance->defined comp))) sub-simulation (inp#out W F) (out<:out W₁ inc G) (step inp rr) (step (out fx) sr) = let _ , tr , sub = sub-simulation (F (inc fx) .force) (G fx .force) rr sr in _ , step (out (inc fx)) tr , sub
\documentclass{article} \usepackage{balance} % For balanced columns on the last page \begin{document} \title{Sunshine of Your Gov: Predicting Future Salaries of Ontario Public Servants} \author{Thomas Sattolo} \maketitle \section{Data Transformation} The full dataset is quite large, over a million entries, and spans 22 years. Importantly, it was never designed to be used for any sort of data science work. Consequently, data cleaning was onerous and time consuming. What we started with was a list of names and with each name is a sector, a job title, an employer and a salary. \subsection{Sectors, Employers and Job Titles} Examples of sectors are "Crown Agencies", "Hospitals" and "Universities", i.e. "Hospitals" is literally one of the sectors employees are sorted into; specific hospitals are employers. Individual universities, government departments, cites and the like are also employers. None of these---sectors, employers and universities--- are standardized in any way. An Employer being 'fanshawe' in one year 'fanshawe college' in another or a sector being 'government of ontario : legislative assembly' one year 'government of ontario - legislative assembly \& offices' the next is commonplace. The same sort of thing happens with job titles. The first thing to that needed to be done was transform the sector, employer and job title columns into categorical variables that aggregate all the different names that are used for the same organization into a single category. The number of unique sectors is only twelve, all years combined, so it's practical to simply figure it out manually. Employers and job titles on the other hand number in the tens of thousands so an automated approach is required (note that the number of unique employers and Job titles was not known until after the categorization was done). To begin, we did some obvious things like removing punctuation and making every character lowercase. This is followed up by some more advanced natural language processing technique to remove function words, correct spelling mistakes and strip words to their roots. The latter makes 'taxable' become tax and 'governing' 'govern', etc. Spelling correction had mixed results. First of all, it didn't usually output something sensible when the input word was in French, which was actually quite common. The same is true of proper nouns which some pathological results like 'Landlord Flaming' for 'Sandford Flemming'. Of course, this is not great but since it's deterministic it ought not to a serious problem: 'puckering' matches 'puckering' just as obviously as 'pickering' matches 'pickering', but random spelling errors would be hard to deal with in any other way. With this we need to define the distance between strings. We used three different measures; The idea is that is a match is close enough by any of them, a match is detected These were: \begin{enumerate} \item Jaccard Distance: the percent of words that are the same. \item Ratcliff and Obershelp Gestalt Pattern Matching: recursively finds longest matching sequences in both strings. \item Modified Jaccard Distance, the same as Jaccard Distance but non-matching words that represent more than 2\% (an arbitrary threshold) percent of the words in the are ignored. This the goal of this modification id to exclude things like 'college' and 'city' making 'city of toronto' a match for 'toronto'. \end{enumerate} These measure can be used to match employers and job titles from given year to those in the next year and so on for every year in the dataset. In other words, for each year every employer is compared to the all employers found in previous years. If a match is found that's at least 75\% we consider the two employers to be the same. If more than one such match is found, the strongest match is used (of any of the measures). In case of a tie one measure has to take priority; we chose plain Jaccard Distance. So far the treatment of Employers and Job Titles has been the same, but at this point they diverge slightly. For employers, we assume that distinct employer strings in a given year are truly distinct. So two employers whose strings do not match exactly cannot be the same. No such assumption is made for job titles. And that's how we got properly categorical data for job titles and employers. \subsection{Names} The next step is to track names, i.e figure out which entries are for the same person. Again, we have to define how names will be compared. If any on the following is true for a pair of names they are considered to be a match: \begin{enumerate} \item Exact match, including initials. \item Same first name, same last name. \item No first name, Same first initial, same last name. \item First initial same as first letter of first name, same last name. \end{enumerate} Otherwise, a Ratcliff Obershelp Gestalt distance of 85\% also makes two name a match. From here, the process is similar to that for employers; including, naturally, the assumption that all entries in a given year are truly distinct. For each name in each we look for matches among the entries from the previous year that have the same employer and job title. If none are found, we expand the search to those with the same employer only. If multiple matches are found in either search we have to break the tie (because two entries in the same year can't be for the same person). The first match types in the above list trump those lower down, so an exact match takes priority over a match of first and last names and so on. If both conflicting matches were detected using Gestalt pattern matching, the closer match wins. If these steps fail to resolve the dilemma, we simply take the entry with the closest salary. \subsection{Gender} Our dataset is somewhat odd in that it is not anonymized. We're provided with people's full names which allows us to make a few inferences about who they are. First among these is to determine everyone's likely gender. Many, presumably most, cultures tend to give different names to little boys and little girls. This is certainly true for Westerners, who obviously form the majority of the dataset. Fortunately this work has been done by Kensuke Muraki \cite{GenderProj}. Chicksexer (a reference to baby chickens, not women) is a publicly available, fully trained model that will take a persons full name and output an estimate the probability of a person with that name being male or female. As a sanity check, we verified that the results were reasonable with some names of people with known gender (people involved with this project and members of the cabinet). \begin{enumerate} \item Thomas Sattolo: Male: 1.0 \item Justin Trudeau: Male: 1.0 \item Catherine Mckenna: Female 1.0 \item Harjit Sajjan: Male 1.0 \item Bardish Chagger Female 0.88 \item Ahmed Hussen: Male 1.0 \item Carolyn Bennett: Female 1.0 \end{enumerate} All of these match reality. \subsection{Ethnicity} Names are also informative about people's ethnicity. Once again, this a project to extract this information is available. Sood and Laohaprapanon's project Ethnicolr \cite{EthnicityProj} takes a full name outputs an estimate of the probability that a person's ethnicity is any of the following: \begin{enumerate} \item EastAsian \item Japanese \item IndianSubContinent \item Africans \item Muslim \item British \item EastEuropean \item Jewish \item French \item Germanic \item Hispanic \item Italian \item Nordic \end{enumerate} And using the same names as before we can check the reasonableness of the results (only categories assigned a probability greater than 10\% are included) \begin{enumerate} \item Thomas Sattolo: Italian 0.55, British: 0.24 \item Justin Trudeau: French: 0.69 \item Catherine McKenna: British: 0.84 \item Harjit Sajjan: IndianSubContinent: 0.87 \item Bardish Chagger: British: 0.85 \item Ahmed Hussen: Muslim: 0.74, Africans: 0.13 \item Carolyn Bennett: British 0.72, Jewish; 0.15 \end{enumerate} Once again, all of these seem reasonable, except for one. The result for Bardish Chagger is a complete mistake. \section{Prediction Model} One of the goal of this project was to create a model to predict future salaries of employees. Each employees salary throughout the years form a time series. The earlier years of these series can be used as the input of a neural network with the later years used as labels and the network should learn the patterns in a set of input time series and hopefully this will translate into a ability to predict salary growth of other people. The demographic can also easily be fed into the network. Making use of the data we gathered on sectors, employers and job titles is less obvious because it is all categorical, with many categories. One-hot encoding works as a means of inputting categorical information into a neural network, but doing this with all employers and job titles that exist in the dataset would mean having 10,000 dimensional input. This is not feasible, so what was done was to keep only the 100 most common employers and job titles and one-hot encode those. This isn't great because it does involve a significant loss of information, but there's no other obvious way to include employers and job titles in the model. By taking this data and using it to train a neural network using Tensorflow, we were able to consistently predict future salaries with a mean squared error of roughly 0.25 (on zero mean unit variance input). This is not significantly better than simply linearly extrapolating from past salaries on each individual to predict the future. These results were not affected significantly by changes to the neural network architecture. Whether it was a small single layer network with 30 hidden units or a larger multilayer perceptron with 100 hidden units per layer, 0.25 was the best mean squared error we could get on the validation set. That we failed to usefully predict salary growth does not prove that doing so is impossible, but does suggest that the data we used on employers, job titles and demographics has only a weak effect on a salary changes (though not necessarily on the salaries themselves). It is worth noting that the average yearly change in salary for provincial employees is surprisingly large at \$8312. \bibliographystyle{ACM-Reference-Format} \bibliography{finalpaper} \end{document}
{-# OPTIONS --cubical --safe #-} module Cubical.Data.Bool.Base where open import Cubical.Core.Everything open import Cubical.Foundations.Prelude open import Cubical.Data.Empty open import Cubical.Relation.Nullary open import Cubical.Relation.Nullary.DecidableEq -- Obtain the booleans open import Agda.Builtin.Bool public infixr 6 _and_ infixr 5 _or_ not : Bool → Bool not true = false not false = true _or_ : Bool → Bool → Bool false or false = false false or true = true true or false = true true or true = true _and_ : Bool → Bool → Bool false and false = false false and true = false true and false = false true and true = true caseBool : ∀ {ℓ} → {A : Type ℓ} → (a0 aS : A) → Bool → A caseBool att aff true = att caseBool att aff false = aff _≟_ : Discrete Bool false ≟ false = yes refl false ≟ true = no λ p → subst (caseBool ⊥ Bool) p true true ≟ false = no λ p → subst (caseBool Bool ⊥) p true true ≟ true = yes refl Dec→Bool : ∀ {ℓ} {A : Type ℓ} → Dec A → Bool Dec→Bool (yes p) = true Dec→Bool (no ¬p) = false
(* Title: HOL/Auth/n_moesi_lemma_inv__2_on_rules.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_moesi Protocol Case Study*} theory n_moesi_lemma_inv__2_on_rules imports n_moesi_lemma_on_inv__2 begin section{*All lemmas on causal relation between inv__2*} lemma lemma_inv__2_on_rules: assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__2 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" proof - have c1: "(\<exists> i. i\<le>N\<and>r=n_rule_t1 i)\<or> (\<exists> i. i\<le>N\<and>r=n_rule_t2 N i)\<or> (\<exists> i. i\<le>N\<and>r=n_rul_t3 N i)\<or> (\<exists> i. i\<le>N\<and>r=n_rul_t4 N i)\<or> (\<exists> i. i\<le>N\<and>r=n_rul_t5 N i)" apply (cut_tac b1, auto) done moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_rule_t1 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_rule_t1Vsinv__2) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_rule_t2 N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_rule_t2Vsinv__2) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_rul_t3 N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_rul_t3Vsinv__2) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_rul_t4 N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_rul_t4Vsinv__2) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_rul_t5 N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_rul_t5Vsinv__2) done } ultimately show "invHoldForRule s f r (invariants N)" by satx qed end
State Before: α : Type u_1 β✝ : Type ?u.20071 inst✝¹ : LinearOrder α x y : α β : Type u_2 inst✝ : LinearOrder β x' y' : β h : cmp x y = cmp x' y' ⊢ x < y ↔ x' < y' State After: no goals Tactic: rw [← cmp_eq_lt_iff, ← cmp_eq_lt_iff, h]
lemma metric_LIMSEQ_D: "X \<longlonglongrightarrow> L \<Longrightarrow> 0 < r \<Longrightarrow> \<exists>no. \<forall>n\<ge>no. dist (X n) L < r" for L :: "'a::metric_space"
[STATEMENT] lemma diff_is_semialgebraic: assumes "is_semialgebraic n A" assumes "is_semialgebraic n B" shows "is_semialgebraic n (A - B)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. is_semialgebraic n (A - B) [PROOF STEP] apply(rule is_semialgebraicI) [PROOF STATE] proof (prove) goal (1 subgoal): 1. A - B \<in> semialg_sets n [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: is_semialgebraic n A is_semialgebraic n B goal (1 subgoal): 1. A - B \<in> semialg_sets n [PROOF STEP] unfolding semialg_sets_def [PROOF STATE] proof (prove) using this: is_semialgebraic n A is_semialgebraic n B goal (1 subgoal): 1. A - B \<in> gen_boolean_algebra (carrier (Q\<^sub>p\<^bsup>n\<^esup>)) (Collect (is_basic_semialg n)) [PROOF STEP] using gen_boolean_algebra_diff is_semialgebraicE semialg_sets_def [PROOF STATE] proof (prove) using this: is_semialgebraic n A is_semialgebraic n B \<lbrakk>?A \<in> gen_boolean_algebra ?S ?B; ?C \<in> gen_boolean_algebra ?S ?B\<rbrakk> \<Longrightarrow> ?A - ?C \<in> gen_boolean_algebra ?S ?B is_semialgebraic ?n ?S \<Longrightarrow> ?S \<in> semialg_sets ?n semialg_sets ?n = gen_boolean_algebra (carrier (Q\<^sub>p\<^bsup>?n\<^esup>)) {S. is_basic_semialg ?n S} goal (1 subgoal): 1. A - B \<in> gen_boolean_algebra (carrier (Q\<^sub>p\<^bsup>n\<^esup>)) (Collect (is_basic_semialg n)) [PROOF STEP] by blast
\documentclass[11pt]{article} \usepackage[utf8]{inputenc} %common math and LaTeX packages \usepackage{amsmath,amsthm,amsfonts,amssymb,amscd} \usepackage{multirow,booktabs} \usepackage[table]{xcolor} \usepackage{multirow} \usepackage{fullpage} \usepackage{lastpage} \usepackage{enumitem} \usepackage{fancyhdr} \usepackage{mathrsfs} \usepackage{wrapfig} \usepackage{setspace} \usepackage{calc} \usepackage{multicol} \usepackage{cancel} \usepackage[retainorgcmds]{IEEEtrantools} \usepackage[margin=1in]{geometry} \usepackage{amsmath} \newlength{\tabcont} \setlength{\parindent}{0.0in} \setlength{\parskip}{0.0in} \usepackage{empheq} %shaded environment for important equations/notes \usepackage{mdframed} \colorlet{shaded}{blue!15} \colorlet{shadedtext}{black} \newenvironment{shaded} { \raggedright \color{shadedtext}% }{} \surroundwithmdframed[ hidealllines=true, backgroundcolor=shaded ]{shaded} %page geometry definitions \usepackage[most]{tcolorbox} \usepackage{xcolor} \parindent 0in \parskip 6pt \geometry{margin=1in, headsep=0.25in} %custom theorem definitions \theoremstyle{definition} \newtheorem{innercustomgeneric}{\customgenericname} \providecommand{\customgenericname}{} \newcommand{\newcustomtheorem}[2]{% \newenvironment{#1}[1] {% \renewcommand\customgenericname{#2}% \renewcommand\theinnercustomgeneric{##1}% \innercustomgeneric } {\endinnercustomgeneric} } \newcustomtheorem{thm}{Theorem} \newcustomtheorem{lem}{Lemma} \newcustomtheorem{defn}{Definition} \newcustomtheorem{prop}{Proposition} \newcustomtheorem{exer}{Exercise} \newcustomtheorem{note}{Note} \renewcommand{\qedsymbol}{$\blacksquare$} \let\a\alpha \let\b\beta \let\g\gamma \let\e\varepsilon \let\t\theta \newcommand{\R}{\mathbb{R}} \newcommand{\Q}{\mathbb{Q}} \newcommand{\Z}{\mathbb{Z}} \newcommand{\N}{\mathbb{N}} \newcommand{\PP}{\mathcal{P}} \newcommand{\C}{\mathcal{C}} \newcommand{\Lagr}{\mathcal{L}} \begin{document} %document header \begin{center} {\LARGE \bf ME 226 - Mechanical Measurements}\\ {Instructor: \textit{Prof. Dipanshu Bansal}}\\ Last updated \today \\~\\ {\large \bf Om Prabhu}\\ Undergraduate, Department of Mechanical Engineering\\ Indian Institute of Technology Bombay\\~\\ \textsc{Note To Reader} \end{center} \vspace{-6pt} This document is a compilation of the notes I made while taking the course ME 226 (Mechanical Measurements) in my 4$^{\text{th}}$ semester at IIT Bombay. It is not a substitute for any formal lecture or textbook on the subject, since I pretty much overlook all the theory parts. If you have any suggestions and/or spot any errors, you know where to contact me. \vspace{-3mm} \hrulefill \section{Introduction \& Basic Concepts} \textbf{\large Some definitions:} \vspace{-3.5mm} \begin{itemize} \itemsep-0.2em \item[$-$] sensitivity: slope of the output vs input curve for an instrument \item[$-$] span: difference between maximum and minimum possible measurements for an instrument \item[$-$] range: difference between maximum and minimum deflection for an instrument \item[$-$] resolution: smallest measurable change in input \item[$-$] threshold: smallest measurable input \item[$-$] hysteresis: inability of instrument to give repeatable results during loading and unloading (hysteresis loss = area under the input-output curve) \end{itemize} \vspace{-3.5mm} Error in an instrument is a combination of 2 factors - bias (correctable by calibration) and imprecision (permanent component caused due to human error). \vspace{-3.5mm} \begin{wrapfigure}[7]{L}{0.4\textwidth} \includegraphics[width=0.35\textwidth]{error.jpeg} \end{wrapfigure} \hspace{0.37\textwidth} I $-$ no bias, no imprecision II $-$ bias, no imprecision III $-$ no bias, imprecision IV $-$ bias, imprecision Additionally, results should be fairly repeatable (i.e. repeating the measurements should yield similar values). \textbf{\large Basic Statistics:} $$\text{probability density function}=\frac{\text{(number of readings in an interval)}}{\text{(total number of readings)}\times\text{(width of interval)}}$$ Plot pdf as a function of interval length $-$ area under the curve is 1. On dividing the data into very small intervals, the pdf is a continuous function $f(x)$ such that $\displaystyle P(a<x<b)=\int_a^b f(x)\text{d}x$. In practice, many measurement sets are very close to the Gaussian distribution $\displaystyle f(x)=\frac{1}{\sqrt{2\pi}\sigma}e^{-\frac{(x-\mu)^2}{2\sigma^2}}$. For an ideal condition $-\infty<x<\infty$, but instruments cannot have infinite range. \begin{center} \begin{tabular}{l|cc} & for a population & for a sample\\ \hline mean value & $\displaystyle \mu=\frac{\displaystyle\sum_{i=1}^Nx_i}{N}$ & $\displaystyle \bar{X}=\frac{\displaystyle\sum_{i=1}^nx_i}{n}$\\ variance & $\displaystyle\sigma^2=\frac{\displaystyle\sum_{i=1}^N(x_i-\mu)^2}{N}$ & $\displaystyle s^2=\frac{\displaystyle\sum_{i=1}^n(x_i-\bar{X})^2}{n-1}$\\ \end{tabular} \end{center} A population refers to a continuous data distribution whereas a sample refers to the fixed number of discrete data points. 68\%, 95\%, 99.7\% readings lie in the $\pm\sigma,\pm 2\sigma,\pm 3\sigma$ range respectively. \vspace{2mm} \textbf{\large Method of Least Squares:} Assume a linear fit $y=mx+c$. We define the error $\displaystyle E=\sum_{k=1}^N\left((mx_k+c)-y_k\right)^2$. In order to minimize the error, $$\frac{\partial E}{\partial m}=0\implies \sum 2(mx_k+c-y_k)x_k=0$$ $$\frac{\partial E}{\partial c}=0\implies \sum 2(mx_k+c-y_k)=0$$ Solving this as a system of linear equations, we get \begin{align*} m&=\frac{1}{D}\left(N\sum x_ky_k-\sum x_k\sum y_k\right)\\ c&=\frac{1}{D}\left(N\sum x_k^2\sum y_k-\sum x_k\sum x_ky_k\right)\\ D&=N\sum x_k^2-\left(\sum x_k\right)^2 \end{align*} The variances in $y,x,m,c$ are calculated using the following formulae: \vspace{-3.5mm} \begin{center} \begin{tabular}{cc} $\displaystyle s_y^2=\frac{1}{N-2}\sum \left(mx_k+c-y_k\right)^2$ & $\displaystyle s_x^2=\frac{s_y^2}{m^2}$\\~\\ \vspace{-3.5mm} $\displaystyle s_m^2=\frac{Ns_y^2}{N\sum x_k^2-\left(\sum x_k\right)^2}$ & $\displaystyle s_c^2=\frac{s_y^2\sum x_k^2}{N\sum x_k^2-\left(\sum x_k\right)^2}$\\ \end{tabular} \end{center} \textbf{\large The Error Function:} We have the Gaussian distribution given by $\displaystyle f(x)=\frac{1}{\sqrt{2\pi}\sigma}e^{-\frac{(x-\mu)^2}{2\sigma^2}}$. Define $\eta=\dfrac{x-\mu}{\sigma\sqrt{2}}$. The error function is defined as $\displaystyle\text{er}f(\eta)=\frac{2}{\sqrt{\pi}}\int_0^{\eta}e^{-t^2}\text{d}t$. It follows that $\text{er}f(-\eta)=-\text{er}f(\eta)$. $$P(X<x)=F(x)=\frac{1}{2}(1+\text{er}f(\eta))$$ $$P(x_1<X<x_2)=F(x_2)-F(x_1)=\frac{1}{2}(\text{er}f(\eta_2)-\text{er}f(\eta_1))$$ \newpage A table for error function values is as follows: \vspace{-8mm} \begin{center} \includegraphics{erf.jpg} \end{center} \vspace{-3.5mm} \textbf{\large Combination of Component Errors:} Measured quantities are often influenced by a combination of other measured quantities (for example, stored potential energy = $\rho gh$). Let quantity $P=f(u_1,u_2,\dots,u_n)$ with individual errors $\Delta u_1,\Delta u_2,\dots,\Delta u_n$. $$\text{absolute error}=\Delta P=\left|\frac{\partial f}{\partial u_1}\Delta u_1\right|+\left|\frac{\partial f}{\partial u_2}\Delta u_2\right|+\dots+\left|\frac{\partial f}{\partial u_n}\Delta u_n\right|$$ $$\text{root sum square error}=E_{RSS}=\sqrt{\left(\frac{\partial f}{\partial u_1}\Delta u_1\right)^2+\left(\frac{\partial f}{\partial u_2}\Delta u_2\right)^2+\dots+\left(\frac{\partial f}{\partial u_n}\Delta u_n\right)^2}$$ For $N$ measurements of each of the quantities, $$\sigma_P^2=\left(\frac{\partial f}{\partial u_1}\right)\sigma_1^2+\left(\frac{\partial f}{\partial u_2}\right)\sigma_2^2+\dots+\left(\frac{\partial f}{\partial u_n}\right)\sigma_n^2$$ \textbf{\large Error Analysis of Voltmeters and Ammeters:} For a voltmeter, we first calculate the equivalent resistance $R_{eq}$ across the points where the voltmeter is to be connected. Then, $$\text{measured voltage }E_m=\frac{R_{m}}{R_m+R_{eq}}E_0\text{ }\text{ and }\text{ }\text{error }\epsilon=1-\frac{E_m}{E_0}=\frac{R_{eq}}{R_m+R_{eq}}$$ For an ammeter, we again calculate $R_{eq}$ (this time the meter will be in series with the rest of the circuit). Then, $$\text{measured current }I_m=\frac{R_{eq}}{R_m+R_{eq}}I_u\text{ }\text{ and }\text{ }\text{error }\epsilon=1-\frac{I_m}{I_u}=\frac{R_m}{R_m+R_{eq}}$$ \section{Dynamic Characteristics} General mathematical model (input $q_i\rightarrow$ output $q_0$) of a system can be represented by: $$a_{n}\frac{\text{d}^{n}q_{0}}{\text{d}t^{n}}+a_{n-1}\frac{\text{d}^{n-1}q_{0}}{\text{d}t^{n-1}}+\dots+a_{1}\frac{\text{d}q_{0}}{\text{d}t}+a_0q_0=b_{m}\frac{\text{d}^{m}q_{i}}{\text{d}t^{m}}+b_{m-1}\frac{\text{d}^{m-1}q_{i}}{\text{d}t^{m-1}}+\dots+b_{1}\frac{\text{d}q_{i}}{\text{d}t}+b_0q_i$$ Normally we don't specify the input derivatives, so we replace the RHS by just $q_i$. Sometimes we may also need to employ techniques like the Laplace transform to solve certain problems. \vspace{-2mm} \begin{center} \includegraphics[width=0.8\textwidth]{laplace.jpg} \end{center} \textbf{\large Zero Order Systems:} The general equation can be written as $a_0q_0=b_0q_i\implies q_0=\dfrac{b_0}{a_0}q_i=Kq_i$. \vspace{-2mm} \begin{itemize} \itemsep-0em \item[$-$] $K$ is the static sensitivity of the system \item[$-$] output is instantaneous with respect to input (i.e. $\phi=0$) \end{itemize} \vspace{-4mm} An example of a zero order system is a potentiometer. The emf $e_0=\dfrac{x}{L}E_b$ is a function of only variable, i.e. distance of the sliding contact. \newpage \subsection{First Order Systems} The general equation characterizing a first order system is: \begin{align*} a_1\frac{\text{d}q_0}{\text{d}t}+a_0q_0&=b_0q_i\\ \therefore \frac{a_1}{a_0}\frac{\text{d}q_0}{\text{d}t}+q_0&=\frac{b_0}{a_0}q_i\\ \therefore (\tau D+1)q_0=Kq_i\implies & \frac{q_0}{q_i}(D)=\frac{K}{1+\tau D} \end{align*} $\tau$ is the time constant whereas $K$ is the static sensitivity of the system. With certain assumptions, we can model a thermometer as a 1$^{\text{st}}$ order system. Its relies on thermal expansion of the liquid column in response to changes in the surrounding temperature. $$\left.\begin{array}{r} \b=\text{coefficient of volume expansion}\\ V=\text{volume of bulb}\\ A_c=\text{cross-sectional area of capillary}\\ \rho=\text{density of thermometer fluid}\\ C_p=\text{specific heat capacity of thermometer fluid}\\ h=\text{heat transfer coefficient}\\ A_s=\text{surface area of bulb} \end{array}\right\rbrace K=\frac{\b V}{A_c}\text{ }\text{ and }\text{ }\tau=\frac{\rho C_pV}{hA_s} $$ The differential equation obtained is: $$\frac{\text{d}T}{\text{d}t}+\frac{hA_s}{\rho C_pV}T=\frac{hA_sT_f}{\rho C_pV}\implies \frac{\text{d}y}{\text{d}t}+p(t)y=g(t)$$ $$y(t)=\frac{\int e^{\int p(t)\text{d}t}g(t)\text{d}t+C}{e^{\int p(t)\text{d}t}}\implies T=T_f+(T_0-T_f)e^{-t/\tau}$$ \textbf{\large Step Response:} For a step response, the input $q_i$ is constant. Hence, the governing equation is: $$(\tau D+1)q_0=Kq_i\implies q_0=Kq_i +Ce^{-t/\tau})$$ For zero initial conditions, we have $q_0=Kq_i(1-e^{-t/\tau})$. Thus, the response time depends only on the value of $\tau$. The error for a step response can be written as $$e_m=Kq_i-q_0=Kq_ie^{-t/\tau}$$ \vspace{-3mm} \begin{center} \includegraphics[width=0.49\textwidth]{firstorder_stepresponse.jpg} \includegraphics[width=0.49\textwidth]{firstorder_steperror.jpg} \end{center} \newpage \textbf{\large Ramp Response:} The governing equation is $(\tau D+1)q_0=Kq_{iramp}t$. Applying the Laplace transform, we get $$q_0=\frac{Kq_{iramp}t}{(1+\tau D)}\implies Q_0(s)=\frac{Kq_{iramp}}{s^2(1+\tau s)}\implies \frac{Q_0(s)}{Kq_{iramp}}=\frac{1}{s^2}-\frac{\tau}{s}+\frac{1}{s+\frac{1}{\tau}}$$ Inverting the Laplace transform, we finally get $$q_0(t)=Kq_{iramp}(t-\tau)+Kq_{iramp}\tau e^{-t/\tau}\text{ }\text{ and }\text{ }e_m=Kq_{iramp}\tau(1-e^{-t/\tau})$$ The steady state error (i.e. component of error that stays constant with time) is given by $e_{ss}=Kq_{iramp}\tau$ (often we assume $K=1$). The transient error eventually converges to 0, thus there is always an error of $e_{ss}$ even for very large values of time. \textbf{\large Impulse Response:} We initially assume a step input of magnitude $A/T$ applied for time $T$. The impulse response can then be found in the limit $T\to 0$. \begin{align*} q_0=\frac{A}{T}(1-e^{-t/\tau})&\text{ for }0\leqslant t\leqslant T\\ q_0=\frac{A(1-e^{-T/\tau})e^{-t/\tau}}{Te^{-T/\tau}}&\text{ for }t>T \end{align*} In the limit $T\to 0$, we get the impulse response as $$q_0=\frac{A}{T}e^{-t/\tau}$$ \textbf{Frequency Response:} $$\frac{q_0}{Kq_i}=\frac{1}{1+\tau D}=\frac{1}{1+j\tau\omega}\implies \frac{q_0}{Kq_i}=\frac{1}{\sqrt{1+\tau^2\omega^2}};\text{ }\phi=\arctan(-\tau\omega)$$ $$\therefore\text{ for input }q_i=a\sin(\omega t)\rightarrow \text{output }q_0=\frac{a}{\sqrt{1+\tau^2\omega^2}}\sin(\omega t+\phi)$$ As observed, the frequency response has a magnitude as well as a phase difference associated with it. An ideal frequency response would have $\dfrac{q_0}{Kq_i}=1$ and $\phi=0$. \subsection{Second Order Systems} The general equation characterizing a second order system is: \begin{align*} a_2\frac{\text{d}^2q_0}{\text{d}t^2}+a_1\frac{\text{d}q_0}{\text{d}t}+a_0q_0&=b_0q_i\\ \therefore \frac{a_2}{a_0}\frac{\text{d}^2q_0}{\text{d}t^2}+\frac{a_1}{a_0}\frac{\text{d}q_0}{\text{d}t}+q_0&=\frac{b_0}{a_0}q_i \end{align*} A very common example of a second order system is that of a mass, spring and damper. The force applied by the spring depends on the displacement $x$ while the force applied by the damper depends on the velocity $v$. \newpage $$m\frac{\text{d}^2x}{\text{d}t^2}=F-Kx-B\frac{\text{d}x}{\text{d}t}\implies (mD^2+BD+K)x=F\implies \left(\frac{m}{k}D^2+\frac{B}{K}D+1\right)x=\frac{F}{K}$$ Replacing $\displaystyle \omega_n=\sqrt{\frac{K}{m}}$ and $\displaystyle \zeta=\frac{B}{2\sqrt{mK}}$, we get $$\left(\frac{D^2}{\omega_n^2}+\frac{2\zeta D}{\omega_n}+1\right)x=\frac{F}{k}$$ \textbf{\large Step, Ramp \& Impulse Responses:} All of the following equations can be derived using the fundamental differential equation $$\ddot{y}+2\zeta\omega_n\dot{y}+\omega_n^2y=f(t)$$ \begin{center} \includegraphics[width=\textwidth]{secondorder_response.jpg} \end{center} \begin{itemize} \itemsep0em \item[$-$] damped natural frequency $\omega_d=\sqrt{1-\zeta^2}\omega_n$ for $0\leqslant\zeta<1$ \item[$-$] phase angle $\psi=\arctan(\dfrac{\zeta}{\sqrt{1-\zeta^2}})$ for $0\leqslant\zeta<1$ \item[$-$] time constants for overdamped ($\zeta>1$) systems are $$\tau_1=\frac{1}{\zeta\omega_n-\sqrt{\zeta^2-1}\omega_n}\text{ and }\tau_2=\frac{1}{\zeta\omega_n+\sqrt{\zeta^2-1}\omega_n}$$ \end{itemize} The impulse response can be found by simply differentiating the step response. Similarly, the ramp response can be found by integrating the step response. For a ramp response, the steady state error is given by $$e_{m,ss}=\frac{2\zeta q_{iramp}}{\omega_n}$$ Some important observations from the above equations are as follows: \vspace{-3mm} \begin{itemize} \itemsep-0.1em \item[$-$] overdamped systems have a sluggish response (i.e. large time delay to reach desired output) \item[$-$] underdamped system have an oscillatory response depending on the damping coefficient \item[$-$] critically damped systems have the most desirable performance \item[$-$] in most systems, $\omega_nt$ is determined by the response, so we often try to design $\omega_n$ to be as large as possible \item[$-$] most commercial systems tend to use $0.6<\zeta<0.7$, since the system gives $\approx 90\%$ accuracy at $\omega_nt=2.5$ \end{itemize} \textbf{\large Frequency Response:} The general equation for frequency response of a second order system is: $$\left(\frac{D^2}{\omega_n^2}+\frac{2\zeta D}{\omega_n}+1\right)q_0=Kq_i\implies \frac{q_0}{Kq_i}=\frac{1}{\dfrac{D^2}{\omega_n^2}+\dfrac{2\zeta D}{\omega_n}+1}\implies \frac{q_0}{Kq_i}=\frac{1}{\dfrac{-\omega^2}{\omega_n^2}+\dfrac{2\zeta\omega}{\omega_n}j+1}$$ $$\therefore \frac{q_0}{Kq_i}=\frac{1}{\sqrt{\left(1-\dfrac{\omega^2}{\omega_n^2}\right)^2+\left(\dfrac{2\zeta\omega}{\omega_n}\right)^2}};\text{ }\phi=\arctan\left[\frac{-2\zeta}{\dfrac{\omega_n}{\omega}-\dfrac{\omega}{\omega_n}}\right]$$ When $\omega/\omega_n$ is small, the response for $0.6<\zeta<0.7$ is satisfactory. Also when the system frequency matches the natural frequency of the device, resonance occurs in which $\phi=0$ and the amplitude rises. \subsection{Combination of Systems} For systems in series, their individual transfer functions are simply multiplied. For example, 2 first order systems in series give a second order system as follows: \begin{align*} \text{for }q_i=(\tau_1D+1)q_{01}&\text{ and }q_{01}=(\tau_2D+1)q_0\\ q_i=(\tau_1D+1)(\tau_2D+1)q_0\implies & q_i=(\tau_1\tau_2D^2+\tau_1D+\tau_2D+1)q_o \end{align*} Comparing this with the standard equation for a second order system, we get $\tau_1\tau_2=\dfrac{1}{\omega_n^2}$ and $\tau_1+\tau_1=\dfrac{2\zeta}{\omega_n}$. \end{document}
[STATEMENT] lemma closed_lattice: fixes A :: "(real ^ 'n) set" assumes "\<And>v i. v \<in> A \<Longrightarrow> v $ i \<in> \<int>" shows "closed A" [PROOF STATE] proof (prove) goal (1 subgoal): 1. closed A [PROOF STEP] proof (rule discrete_imp_closed[OF zero_less_one], safe, goal_cases) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x y. \<lbrakk>x \<in> A; y \<in> A; dist y x < 1\<rbrakk> \<Longrightarrow> y = x [PROOF STEP] case (1 x y) [PROOF STATE] proof (state) this: x \<in> A y \<in> A dist y x < 1 goal (1 subgoal): 1. \<And>x y. \<lbrakk>x \<in> A; y \<in> A; dist y x < 1\<rbrakk> \<Longrightarrow> y = x [PROOF STEP] have "x $ i = y $ i" for i [PROOF STATE] proof (prove) goal (1 subgoal): 1. x $ i = y $ i [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. x $ i = y $ i [PROOF STEP] from 1 and assms [PROOF STATE] proof (chain) picking this: x \<in> A y \<in> A dist y x < 1 ?v \<in> A \<Longrightarrow> ?v $ ?i \<in> \<int> [PROOF STEP] have "x $ i - y $ i \<in> \<int>" [PROOF STATE] proof (prove) using this: x \<in> A y \<in> A dist y x < 1 ?v \<in> A \<Longrightarrow> ?v $ ?i \<in> \<int> goal (1 subgoal): 1. x $ i - y $ i \<in> \<int> [PROOF STEP] by auto [PROOF STATE] proof (state) this: x $ i - y $ i \<in> \<int> goal (1 subgoal): 1. x $ i = y $ i [PROOF STEP] then [PROOF STATE] proof (chain) picking this: x $ i - y $ i \<in> \<int> [PROOF STEP] obtain m where m: "of_int m = (x $ i - y $ i)" [PROOF STATE] proof (prove) using this: x $ i - y $ i \<in> \<int> goal (1 subgoal): 1. (\<And>m. real_of_int m = x $ i - y $ i \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by (elim Ints_cases) auto [PROOF STATE] proof (state) this: real_of_int m = x $ i - y $ i goal (1 subgoal): 1. x $ i = y $ i [PROOF STEP] hence "of_int (abs m) = abs ((x - y) $ i)" [PROOF STATE] proof (prove) using this: real_of_int m = x $ i - y $ i goal (1 subgoal): 1. real_of_int \<bar>m\<bar> = \<bar>(x - y) $ i\<bar> [PROOF STEP] by simp [PROOF STATE] proof (state) this: real_of_int \<bar>m\<bar> = \<bar>(x - y) $ i\<bar> goal (1 subgoal): 1. x $ i = y $ i [PROOF STEP] also [PROOF STATE] proof (state) this: real_of_int \<bar>m\<bar> = \<bar>(x - y) $ i\<bar> goal (1 subgoal): 1. x $ i = y $ i [PROOF STEP] have "\<dots> \<le> norm (x - y)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<bar>(x - y) $ i\<bar> \<le> norm (x - y) [PROOF STEP] by (rule component_le_norm_cart) [PROOF STATE] proof (state) this: \<bar>(x - y) $ i\<bar> \<le> norm (x - y) goal (1 subgoal): 1. x $ i = y $ i [PROOF STEP] also [PROOF STATE] proof (state) this: \<bar>(x - y) $ i\<bar> \<le> norm (x - y) goal (1 subgoal): 1. x $ i = y $ i [PROOF STEP] have "\<dots> < of_int 1" [PROOF STATE] proof (prove) goal (1 subgoal): 1. norm (x - y) < real_of_int 1 [PROOF STEP] using 1 [PROOF STATE] proof (prove) using this: x \<in> A y \<in> A dist y x < 1 goal (1 subgoal): 1. norm (x - y) < real_of_int 1 [PROOF STEP] by (simp add: dist_norm norm_minus_commute) [PROOF STATE] proof (state) this: norm (x - y) < real_of_int 1 goal (1 subgoal): 1. x $ i = y $ i [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: real_of_int \<bar>m\<bar> < real_of_int 1 [PROOF STEP] have "abs m < 1" [PROOF STATE] proof (prove) using this: real_of_int \<bar>m\<bar> < real_of_int 1 goal (1 subgoal): 1. \<bar>m\<bar> < 1 [PROOF STEP] by (subst (asm) of_int_less_iff) [PROOF STATE] proof (state) this: \<bar>m\<bar> < 1 goal (1 subgoal): 1. x $ i = y $ i [PROOF STEP] thus "x $ i = y $ i" [PROOF STATE] proof (prove) using this: \<bar>m\<bar> < 1 goal (1 subgoal): 1. x $ i = y $ i [PROOF STEP] using m [PROOF STATE] proof (prove) using this: \<bar>m\<bar> < 1 real_of_int m = x $ i - y $ i goal (1 subgoal): 1. x $ i = y $ i [PROOF STEP] by simp [PROOF STATE] proof (state) this: x $ i = y $ i goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: x $ ?i = y $ ?i goal (1 subgoal): 1. \<And>x y. \<lbrakk>x \<in> A; y \<in> A; dist y x < 1\<rbrakk> \<Longrightarrow> y = x [PROOF STEP] thus "y = x" [PROOF STATE] proof (prove) using this: x $ ?i = y $ ?i goal (1 subgoal): 1. y = x [PROOF STEP] by (simp add: vec_eq_iff) [PROOF STATE] proof (state) this: y = x goal: No subgoals! [PROOF STEP] qed
module JSON2 using Dates, Parsers # for reading/writing javascript functions as value literals struct Function str::String end include("write.jl") include("read.jl") include("strings.jl") include("pretty.jl") ## JSON2.@format function getformats(nm; kwargs...) for (k, v) in pairs(kwargs) k == nm && return v end return NamedTuple() end macro format(T, expr) if occursin("keywordargs", string(expr)) || occursin("noargs", string(expr)) esc(:(JSON2.@format($T, $expr, $(Expr(:block))))) else esc(:(JSON2.@format($T, "", $expr))) end end """ JSON2.@format T [noargs|keywordargs] begin _field_ => (; options...) _field2_ => (; options...) end Specify a custom JSON formatting for a struct `T`. Options include: `name`: `jsontype`: `omitempty`: `exclude`: `default`: By default, the JSON input is expected to contain each field of a type and be in the same order as the type was defined. For example, the struct: ```julia struct T a::Int b::Int c::Union{Nothing, Int} end ``` Would have JSON like: ``` {"a": 0, "b": 1, "c": null} {"a": 0, "b": 1, "c": 2} {"a": 0, "b": 1, "c": null, "d": 3} // extra fields are ignored {"a": 0} // will work if T(a) constructor is defined {"a": 0, "b": 1} // will work if T(a, b) constructor is defined ``` That is, each field _must_ be present in the JSON input and match in position to the original struct definition. Extra arguments after the struct's own fieldtypes are ignored. Again, the default case is for JSON input that will have consistently ordered, always-present fields; for cases where the input JSON is _not_ well-ordered or if there is a possibility of a `null`, non-`Union{T, Nothing}` field, here's how to approach more advanced custom formatting: - If the input will always be consistenly-ordered, but fields may be missing (not `null`, but the field key isn't even available in the input), defaults can be provided like: ``` JSON2.@format T begin c => (default=0,) end ``` This says that, when reading from a JSON input, if field `c` isn't present, to set it's value to 0. - If the JSON input is not consistenly-ordered, there are two other options for allowing direct type parsing: ``` T(; a=0, b=0, c=0, kwargs...) = T(a, b, c) JSON2.@format T keywordargs begin ... end ``` Here we've defined a "keywordargs" constructor for `T` that essentially takes a default for each field as keyword arguments, then constructs `T`. During parsing, the JSON input will be parsed for any valid field key-values and the keyword constructor will be called with whatever arguments are parsed in whatever order. Note that we also included a catchall `kwargs...` in our constructor which can be used to "throw away" or ignore any extra fields in the JSON input. ``` mutable struct T a::Int b::Int c::Union{Nothing, Int} end T() = T(0, 0, 0) JSON2.@format T noargs begin ... end ``` In this case, we've made `T` a _mutable_ struct and defined a "noargs" constructor `T() = ...`; we then specified in `JSON2.@format T noargs` the `noargs` option. During parsing, an instance of `T` will first constructed using the "noargs" constructor, then fields will be set as they're parsed from the JSON input (hence why `mutable struct` is required). """ macro format(T, typetype, expr) args = filter(x->typeof(x) != LineNumberNode, expr.args) foreach(x->x.args[2] = QuoteNode(x.args[2]), args) anydefaults = any(z->:default in z, map(x->map(y->y.args[1], x.args[3].args), args)) wr = quote @generated function JSON2.write(io::IO, obj::$T) fieldformats = [JSON2.getformats(nm; $(args...)) for nm in fieldnames($T)] # @show fieldformats inds = Tuple(i for i = 1:length(fieldformats) if !get(fieldformats[i], :exclude, false)) names = Tuple(string(get(fieldformats[i], :name, fieldname($T, i))) for i in inds) omitempties = Tuple(get(fieldformats[i], :omitempty, false) for i in inds) converts = Tuple(JSON2.getconvert(get(fieldformats[i], :jsontype, fieldtype($T, i))) for i in inds) N = length(inds) ex = JSON2.generate_write_body(N, inds, names, omitempties, converts) # @show ex return ex end end if occursin("noargs", string(typetype)) q = esc(quote @generated function JSON2.read(io::IO, T::Type{$T}) N = fieldcount($T) fieldformats = Dict($(args...)) names = (; ((Symbol(get(get(fieldformats, nm, NamedTuple()), :name, nm)), nm) for nm in fieldnames($T) if !get(get(fieldformats, nm, NamedTuple()), :exclude, false))...) jsontypes = (; ((get(get(fieldformats, nm, NamedTuple()), :name, nm), get(get(fieldformats, nm, NamedTuple()), :jsontype, fieldtype($T, i))) for (i, nm) in enumerate(fieldnames($T)) if !get(get(fieldformats, nm, NamedTuple()), :exclude, false))...) defaults = (; ((get(get(fieldformats, nm, NamedTuple()), :name, nm), get(fieldformats, nm, NamedTuple())[:default]) for nm in fieldnames($T) if !get(get(fieldformats, nm, NamedTuple()), :exclude, false) && haskey(get(fieldformats, nm, NamedTuple()), :default))...) return JSON2.generate_read_body_noargs(N, names, jsontypes, defaults) end $wr end) elseif occursin("keywordargs", string(typetype)) q = esc(quote @generated function JSON2.read(io::IO, T::Type{$T}) N = fieldcount($T) fieldformats = Dict($(args...)) names = (; ((Symbol(get(get(fieldformats, nm, NamedTuple()), :name, nm)), nm) for nm in fieldnames($T) if !get(get(fieldformats, nm, NamedTuple()), :exclude, false) && haskey(get(fieldformats, nm, NamedTuple()), :name))...) types = (; ((get(get(fieldformats, nm, NamedTuple()), :name, nm), get(get(fieldformats, nm, NamedTuple()), :jsontype, fieldtype($T, i))) for (i, nm) in enumerate(fieldnames($T)) if !get(get(fieldformats, nm, NamedTuple()), :exclude, false))...) defaults = (; ((get(get(fieldformats, nm, NamedTuple()), :name, nm), get(fieldformats, nm, NamedTuple())[:default]) for nm in fieldnames($T) if !get(get(fieldformats, nm, NamedTuple()), :exclude, false) && haskey(get(fieldformats, nm, NamedTuple()), :default))...) q = quote JSON2.@expect '{' JSON2.wh!(io) keys = Symbol[] vals = Any[] JSON2.peekbyte(io) == JSON2.CLOSE_CURLY_BRACE && (JSON2.readbyte(io); @goto done) typemap = $types while true key = JSON2.read(io, Symbol) push!(keys, key) JSON2.wh!(io) JSON2.@expect ':' JSON2.wh!(io) push!(vals, JSON2.read(io, get(typemap, key, Any))) # recursively reads value JSON2.wh!(io) JSON2.@expectoneof ',' '}' b == JSON2.CLOSE_CURLY_BRACE && @goto done JSON2.wh!(io) end @label done return T(; $defaults..., NamedTuple{Tuple(keys)}(Tuple(vals))...) end # @show q return q end $wr end) elseif anydefaults q = esc(quote @generated function JSON2.read(io::IO, T::Type{$T}) N = fieldcount($T) fieldformats = Dict($(args...)) names = Tuple(Symbol(get(get(fieldformats, nm, NamedTuple()), :name, nm)) for nm in fieldnames($T) if !get(get(fieldformats, nm, NamedTuple()), :exclude, false)) types = Tuple(fieldtype($T, i) for i = 1:fieldcount($T) if !get(get(fieldformats, fieldname($T, i), NamedTuple()), :exclude, false)) jsontypes = Tuple(get(get(fieldformats, fieldname($T, i), NamedTuple()), :jsontype, fieldtype($T, i)) for i = 1:fieldcount($T) if !get(get(fieldformats, fieldname($T, i), NamedTuple()), :exclude, false)) defaults = (; ((get(get(fieldformats, nm, NamedTuple()), :name, nm), get(fieldformats, nm, NamedTuple())[:default]) for nm in fieldnames($T) if !get(get(fieldformats, nm, NamedTuple()), :exclude, false) && haskey(get(fieldformats, nm, NamedTuple()), :default))...) return JSON2.generate_missing_read_body(names, types, jsontypes, defaults) end $wr end) # @show q else q = esc(quote @generated function JSON2.read(io::IO, T::Type{$T}) fieldformats = Dict($(args...)) types = Tuple(fieldtype($T, i) for i = 1:fieldcount($T) if !get(get(fieldformats, fieldname($T, i), NamedTuple()), :exclude, false)) jsontypes = Tuple(get(get(fieldformats, fieldname($T, i), NamedTuple()), :jsontype, fieldtype($T, i)) for i = 1:fieldcount($T) if !get(get(fieldformats, fieldname($T, i), NamedTuple()), :exclude, false)) N = length(types) return JSON2.generate_default_read_body(N, types, jsontypes, $T <: NamedTuple) end $wr end) end # @show q return q end end # module
[STATEMENT] lemma scount_eq_0I: "alw (not P) \<omega> \<Longrightarrow> scount P \<omega> = 0" [PROOF STATE] proof (prove) goal (1 subgoal): 1. alw (\<lambda>xs. \<not> P xs) \<omega> \<Longrightarrow> scount P \<omega> = 0 [PROOF STEP] by (induct arbitrary: \<omega> rule: scount.fixp_induct) (auto simp: bot_enat_def intro!: admissible_all admissible_imp admissible_eq_mcontI mcont_const)
(* Title: HOL/Partial_Function.thy Author: Alexander Krauss, TU Muenchen *) section {* Partial Function Definitions *} theory Partial_Function imports Complete_Partial_Order Fun_Def_Base Option keywords "partial_function" :: thy_decl begin named_theorems partial_function_mono "monotonicity rules for partial function definitions" ML_file "Tools/Function/partial_function.ML" subsection {* Axiomatic setup *} text {* This techical locale constains the requirements for function definitions with ccpo fixed points. *} definition "fun_ord ord f g \<longleftrightarrow> (\<forall>x. ord (f x) (g x))" definition "fun_lub L A = (\<lambda>x. L {y. \<exists>f\<in>A. y = f x})" definition "img_ord f ord = (\<lambda>x y. ord (f x) (f y))" definition "img_lub f g Lub = (\<lambda>A. g (Lub (f ` A)))" lemma chain_fun: assumes A: "chain (fun_ord ord) A" shows "chain ord {y. \<exists>f\<in>A. y = f a}" (is "chain ord ?C") proof (rule chainI) fix x y assume "x \<in> ?C" "y \<in> ?C" then obtain f g where fg: "f \<in> A" "g \<in> A" and [simp]: "x = f a" "y = g a" by blast from chainD[OF A fg] show "ord x y \<or> ord y x" unfolding fun_ord_def by auto qed lemma call_mono[partial_function_mono]: "monotone (fun_ord ord) ord (\<lambda>f. f t)" by (rule monotoneI) (auto simp: fun_ord_def) lemma let_mono[partial_function_mono]: "(\<And>x. monotone orda ordb (\<lambda>f. b f x)) \<Longrightarrow> monotone orda ordb (\<lambda>f. Let t (b f))" by (simp add: Let_def) lemma if_mono[partial_function_mono]: "monotone orda ordb F \<Longrightarrow> monotone orda ordb G \<Longrightarrow> monotone orda ordb (\<lambda>f. if c then F f else G f)" unfolding monotone_def by simp definition "mk_less R = (\<lambda>x y. R x y \<and> \<not> R y x)" locale partial_function_definitions = fixes leq :: "'a \<Rightarrow> 'a \<Rightarrow> bool" fixes lub :: "'a set \<Rightarrow> 'a" assumes leq_refl: "leq x x" assumes leq_trans: "leq x y \<Longrightarrow> leq y z \<Longrightarrow> leq x z" assumes leq_antisym: "leq x y \<Longrightarrow> leq y x \<Longrightarrow> x = y" assumes lub_upper: "chain leq A \<Longrightarrow> x \<in> A \<Longrightarrow> leq x (lub A)" assumes lub_least: "chain leq A \<Longrightarrow> (\<And>x. x \<in> A \<Longrightarrow> leq x z) \<Longrightarrow> leq (lub A) z" lemma partial_function_lift: assumes "partial_function_definitions ord lb" shows "partial_function_definitions (fun_ord ord) (fun_lub lb)" (is "partial_function_definitions ?ordf ?lubf") proof - interpret partial_function_definitions ord lb by fact show ?thesis proof fix x show "?ordf x x" unfolding fun_ord_def by (auto simp: leq_refl) next fix x y z assume "?ordf x y" "?ordf y z" thus "?ordf x z" unfolding fun_ord_def by (force dest: leq_trans) next fix x y assume "?ordf x y" "?ordf y x" thus "x = y" unfolding fun_ord_def by (force intro!: dest: leq_antisym) next fix A f assume f: "f \<in> A" and A: "chain ?ordf A" thus "?ordf f (?lubf A)" unfolding fun_lub_def fun_ord_def by (blast intro: lub_upper chain_fun[OF A] f) next fix A :: "('b \<Rightarrow> 'a) set" and g :: "'b \<Rightarrow> 'a" assume A: "chain ?ordf A" and g: "\<And>f. f \<in> A \<Longrightarrow> ?ordf f g" show "?ordf (?lubf A) g" unfolding fun_lub_def fun_ord_def by (blast intro: lub_least chain_fun[OF A] dest: g[unfolded fun_ord_def]) qed qed lemma ccpo: assumes "partial_function_definitions ord lb" shows "class.ccpo lb ord (mk_less ord)" using assms unfolding partial_function_definitions_def mk_less_def by unfold_locales blast+ lemma partial_function_image: assumes "partial_function_definitions ord Lub" assumes inj: "\<And>x y. f x = f y \<Longrightarrow> x = y" assumes inv: "\<And>x. f (g x) = x" shows "partial_function_definitions (img_ord f ord) (img_lub f g Lub)" proof - let ?iord = "img_ord f ord" let ?ilub = "img_lub f g Lub" interpret partial_function_definitions ord Lub by fact show ?thesis proof fix A x assume "chain ?iord A" "x \<in> A" then have "chain ord (f ` A)" "f x \<in> f ` A" by (auto simp: img_ord_def intro: chainI dest: chainD) thus "?iord x (?ilub A)" unfolding inv img_lub_def img_ord_def by (rule lub_upper) next fix A x assume "chain ?iord A" and 1: "\<And>z. z \<in> A \<Longrightarrow> ?iord z x" then have "chain ord (f ` A)" by (auto simp: img_ord_def intro: chainI dest: chainD) thus "?iord (?ilub A) x" unfolding inv img_lub_def img_ord_def by (rule lub_least) (auto dest: 1[unfolded img_ord_def]) qed (auto simp: img_ord_def intro: leq_refl dest: leq_trans leq_antisym inj) qed context partial_function_definitions begin abbreviation "le_fun \<equiv> fun_ord leq" abbreviation "lub_fun \<equiv> fun_lub lub" abbreviation "fixp_fun \<equiv> ccpo.fixp lub_fun le_fun" abbreviation "mono_body \<equiv> monotone le_fun leq" abbreviation "admissible \<equiv> ccpo.admissible lub_fun le_fun" text {* Interpret manually, to avoid flooding everything with facts about orders *} lemma ccpo: "class.ccpo lub_fun le_fun (mk_less le_fun)" apply (rule ccpo) apply (rule partial_function_lift) apply (rule partial_function_definitions_axioms) done text {* The crucial fixed-point theorem *} lemma mono_body_fixp: "(\<And>x. mono_body (\<lambda>f. F f x)) \<Longrightarrow> fixp_fun F = F (fixp_fun F)" by (rule ccpo.fixp_unfold[OF ccpo]) (auto simp: monotone_def fun_ord_def) text {* Version with curry/uncurry combinators, to be used by package *} lemma fixp_rule_uc: fixes F :: "'c \<Rightarrow> 'c" and U :: "'c \<Rightarrow> 'b \<Rightarrow> 'a" and C :: "('b \<Rightarrow> 'a) \<Rightarrow> 'c" assumes mono: "\<And>x. mono_body (\<lambda>f. U (F (C f)) x)" assumes eq: "f \<equiv> C (fixp_fun (\<lambda>f. U (F (C f))))" assumes inverse: "\<And>f. C (U f) = f" shows "f = F f" proof - have "f = C (fixp_fun (\<lambda>f. U (F (C f))))" by (simp add: eq) also have "... = C (U (F (C (fixp_fun (\<lambda>f. U (F (C f)))))))" by (subst mono_body_fixp[of "%f. U (F (C f))", OF mono]) (rule refl) also have "... = F (C (fixp_fun (\<lambda>f. U (F (C f)))))" by (rule inverse) also have "... = F f" by (simp add: eq) finally show "f = F f" . qed text {* Fixpoint induction rule *} lemma fixp_induct_uc: fixes F :: "'c \<Rightarrow> 'c" and U :: "'c \<Rightarrow> 'b \<Rightarrow> 'a" and C :: "('b \<Rightarrow> 'a) \<Rightarrow> 'c" and P :: "('b \<Rightarrow> 'a) \<Rightarrow> bool" assumes mono: "\<And>x. mono_body (\<lambda>f. U (F (C f)) x)" assumes eq: "f \<equiv> C (fixp_fun (\<lambda>f. U (F (C f))))" assumes inverse: "\<And>f. U (C f) = f" assumes adm: "ccpo.admissible lub_fun le_fun P" and bot: "P (\<lambda>_. lub {})" assumes step: "\<And>f. P (U f) \<Longrightarrow> P (U (F f))" shows "P (U f)" unfolding eq inverse apply (rule ccpo.fixp_induct[OF ccpo adm]) apply (insert mono, auto simp: monotone_def fun_ord_def bot fun_lub_def)[2] by (rule_tac f="C x" in step, simp add: inverse) text {* Rules for @{term mono_body}: *} lemma const_mono[partial_function_mono]: "monotone ord leq (\<lambda>f. c)" by (rule monotoneI) (rule leq_refl) end subsection {* Flat interpretation: tailrec and option *} definition "flat_ord b x y \<longleftrightarrow> x = b \<or> x = y" definition "flat_lub b A = (if A \<subseteq> {b} then b else (THE x. x \<in> A - {b}))" lemma flat_interpretation: "partial_function_definitions (flat_ord b) (flat_lub b)" proof fix A x assume 1: "chain (flat_ord b) A" "x \<in> A" show "flat_ord b x (flat_lub b A)" proof cases assume "x = b" thus ?thesis by (simp add: flat_ord_def) next assume "x \<noteq> b" with 1 have "A - {b} = {x}" by (auto elim: chainE simp: flat_ord_def) then have "flat_lub b A = x" by (auto simp: flat_lub_def) thus ?thesis by (auto simp: flat_ord_def) qed next fix A z assume A: "chain (flat_ord b) A" and z: "\<And>x. x \<in> A \<Longrightarrow> flat_ord b x z" show "flat_ord b (flat_lub b A) z" proof cases assume "A \<subseteq> {b}" thus ?thesis by (auto simp: flat_lub_def flat_ord_def) next assume nb: "\<not> A \<subseteq> {b}" then obtain y where y: "y \<in> A" "y \<noteq> b" by auto with A have "A - {b} = {y}" by (auto elim: chainE simp: flat_ord_def) with nb have "flat_lub b A = y" by (auto simp: flat_lub_def) with z y show ?thesis by auto qed qed (auto simp: flat_ord_def) interpretation tailrec!: partial_function_definitions "flat_ord undefined" "flat_lub undefined" where "flat_lub undefined {} \<equiv> undefined" by (rule flat_interpretation)(simp add: flat_lub_def) interpretation option!: partial_function_definitions "flat_ord None" "flat_lub None" where "flat_lub None {} \<equiv> None" by (rule flat_interpretation)(simp add: flat_lub_def) abbreviation "tailrec_ord \<equiv> flat_ord undefined" abbreviation "mono_tailrec \<equiv> monotone (fun_ord tailrec_ord) tailrec_ord" lemma tailrec_admissible: "ccpo.admissible (fun_lub (flat_lub c)) (fun_ord (flat_ord c)) (\<lambda>a. \<forall>x. a x \<noteq> c \<longrightarrow> P x (a x))" proof(intro ccpo.admissibleI strip) fix A x assume chain: "Complete_Partial_Order.chain (fun_ord (flat_ord c)) A" and P [rule_format]: "\<forall>f\<in>A. \<forall>x. f x \<noteq> c \<longrightarrow> P x (f x)" and defined: "fun_lub (flat_lub c) A x \<noteq> c" from defined obtain f where f: "f \<in> A" "f x \<noteq> c" by(auto simp add: fun_lub_def flat_lub_def split: split_if_asm) hence "P x (f x)" by(rule P) moreover from chain f have "\<forall>f' \<in> A. f' x = c \<or> f' x = f x" by(auto 4 4 simp add: Complete_Partial_Order.chain_def flat_ord_def fun_ord_def) hence "fun_lub (flat_lub c) A x = f x" using f by(auto simp add: fun_lub_def flat_lub_def) ultimately show "P x (fun_lub (flat_lub c) A x)" by simp qed lemma fixp_induct_tailrec: fixes F :: "'c \<Rightarrow> 'c" and U :: "'c \<Rightarrow> 'b \<Rightarrow> 'a" and C :: "('b \<Rightarrow> 'a) \<Rightarrow> 'c" and P :: "'b \<Rightarrow> 'a \<Rightarrow> bool" and x :: "'b" assumes mono: "\<And>x. monotone (fun_ord (flat_ord c)) (flat_ord c) (\<lambda>f. U (F (C f)) x)" assumes eq: "f \<equiv> C (ccpo.fixp (fun_lub (flat_lub c)) (fun_ord (flat_ord c)) (\<lambda>f. U (F (C f))))" assumes inverse2: "\<And>f. U (C f) = f" assumes step: "\<And>f x y. (\<And>x y. U f x = y \<Longrightarrow> y \<noteq> c \<Longrightarrow> P x y) \<Longrightarrow> U (F f) x = y \<Longrightarrow> y \<noteq> c \<Longrightarrow> P x y" assumes result: "U f x = y" assumes defined: "y \<noteq> c" shows "P x y" proof - have "\<forall>x y. U f x = y \<longrightarrow> y \<noteq> c \<longrightarrow> P x y" by(rule partial_function_definitions.fixp_induct_uc[OF flat_interpretation, of _ U F C, OF mono eq inverse2]) (auto intro: step tailrec_admissible simp add: fun_lub_def flat_lub_def) thus ?thesis using result defined by blast qed lemma admissible_image: assumes pfun: "partial_function_definitions le lub" assumes adm: "ccpo.admissible lub le (P o g)" assumes inj: "\<And>x y. f x = f y \<Longrightarrow> x = y" assumes inv: "\<And>x. f (g x) = x" shows "ccpo.admissible (img_lub f g lub) (img_ord f le) P" proof (rule ccpo.admissibleI) fix A assume "chain (img_ord f le) A" then have ch': "chain le (f ` A)" by (auto simp: img_ord_def intro: chainI dest: chainD) assume "A \<noteq> {}" assume P_A: "\<forall>x\<in>A. P x" have "(P o g) (lub (f ` A))" using adm ch' proof (rule ccpo.admissibleD) fix x assume "x \<in> f ` A" with P_A show "(P o g) x" by (auto simp: inj[OF inv]) qed(simp add: `A \<noteq> {}`) thus "P (img_lub f g lub A)" unfolding img_lub_def by simp qed lemma admissible_fun: assumes pfun: "partial_function_definitions le lub" assumes adm: "\<And>x. ccpo.admissible lub le (Q x)" shows "ccpo.admissible (fun_lub lub) (fun_ord le) (\<lambda>f. \<forall>x. Q x (f x))" proof (rule ccpo.admissibleI) fix A :: "('b \<Rightarrow> 'a) set" assume Q: "\<forall>f\<in>A. \<forall>x. Q x (f x)" assume ch: "chain (fun_ord le) A" assume "A \<noteq> {}" hence non_empty: "\<And>a. {y. \<exists>f\<in>A. y = f a} \<noteq> {}" by auto show "\<forall>x. Q x (fun_lub lub A x)" unfolding fun_lub_def by (rule allI, rule ccpo.admissibleD[OF adm chain_fun[OF ch] non_empty]) (auto simp: Q) qed abbreviation "option_ord \<equiv> flat_ord None" abbreviation "mono_option \<equiv> monotone (fun_ord option_ord) option_ord" lemma bind_mono[partial_function_mono]: assumes mf: "mono_option B" and mg: "\<And>y. mono_option (\<lambda>f. C y f)" shows "mono_option (\<lambda>f. Option.bind (B f) (\<lambda>y. C y f))" proof (rule monotoneI) fix f g :: "'a \<Rightarrow> 'b option" assume fg: "fun_ord option_ord f g" with mf have "option_ord (B f) (B g)" by (rule monotoneD[of _ _ _ f g]) then have "option_ord (Option.bind (B f) (\<lambda>y. C y f)) (Option.bind (B g) (\<lambda>y. C y f))" unfolding flat_ord_def by auto also from mg have "\<And>y'. option_ord (C y' f) (C y' g)" by (rule monotoneD) (rule fg) then have "option_ord (Option.bind (B g) (\<lambda>y'. C y' f)) (Option.bind (B g) (\<lambda>y'. C y' g))" unfolding flat_ord_def by (cases "B g") auto finally (option.leq_trans) show "option_ord (Option.bind (B f) (\<lambda>y. C y f)) (Option.bind (B g) (\<lambda>y'. C y' g))" . qed lemma flat_lub_in_chain: assumes ch: "chain (flat_ord b) A " assumes lub: "flat_lub b A = a" shows "a = b \<or> a \<in> A" proof (cases "A \<subseteq> {b}") case True then have "flat_lub b A = b" unfolding flat_lub_def by simp with lub show ?thesis by simp next case False then obtain c where "c \<in> A" and "c \<noteq> b" by auto { fix z assume "z \<in> A" from chainD[OF ch `c \<in> A` this] have "z = c \<or> z = b" unfolding flat_ord_def using `c \<noteq> b` by auto } with False have "A - {b} = {c}" by auto with False have "flat_lub b A = c" by (auto simp: flat_lub_def) with `c \<in> A` lub show ?thesis by simp qed lemma option_admissible: "option.admissible (%(f::'a \<Rightarrow> 'b option). (\<forall>x y. f x = Some y \<longrightarrow> P x y))" proof (rule ccpo.admissibleI) fix A :: "('a \<Rightarrow> 'b option) set" assume ch: "chain option.le_fun A" and IH: "\<forall>f\<in>A. \<forall>x y. f x = Some y \<longrightarrow> P x y" from ch have ch': "\<And>x. chain option_ord {y. \<exists>f\<in>A. y = f x}" by (rule chain_fun) show "\<forall>x y. option.lub_fun A x = Some y \<longrightarrow> P x y" proof (intro allI impI) fix x y assume "option.lub_fun A x = Some y" from flat_lub_in_chain[OF ch' this[unfolded fun_lub_def]] have "Some y \<in> {y. \<exists>f\<in>A. y = f x}" by simp then have "\<exists>f\<in>A. f x = Some y" by auto with IH show "P x y" by auto qed qed lemma fixp_induct_option: fixes F :: "'c \<Rightarrow> 'c" and U :: "'c \<Rightarrow> 'b \<Rightarrow> 'a option" and C :: "('b \<Rightarrow> 'a option) \<Rightarrow> 'c" and P :: "'b \<Rightarrow> 'a \<Rightarrow> bool" assumes mono: "\<And>x. mono_option (\<lambda>f. U (F (C f)) x)" assumes eq: "f \<equiv> C (ccpo.fixp (fun_lub (flat_lub None)) (fun_ord option_ord) (\<lambda>f. U (F (C f))))" assumes inverse2: "\<And>f. U (C f) = f" assumes step: "\<And>f x y. (\<And>x y. U f x = Some y \<Longrightarrow> P x y) \<Longrightarrow> U (F f) x = Some y \<Longrightarrow> P x y" assumes defined: "U f x = Some y" shows "P x y" using step defined option.fixp_induct_uc[of U F C, OF mono eq inverse2 option_admissible] unfolding fun_lub_def flat_lub_def by(auto 9 2) declaration {* Partial_Function.init "tailrec" @{term tailrec.fixp_fun} @{term tailrec.mono_body} @{thm tailrec.fixp_rule_uc} @{thm tailrec.fixp_induct_uc} (SOME @{thm fixp_induct_tailrec[where c=undefined]}) *} declaration {* Partial_Function.init "option" @{term option.fixp_fun} @{term option.mono_body} @{thm option.fixp_rule_uc} @{thm option.fixp_induct_uc} (SOME @{thm fixp_induct_option}) *} hide_const (open) chain end
Formal statement is: lemma eventually_at_le: "eventually P (at a within S) \<longleftrightarrow> (\<exists>d>0. \<forall>x\<in>S. x \<noteq> a \<and> dist x a \<le> d \<longrightarrow> P x)" for a :: "'a::metric_space" Informal statement is: A property $P$ holds eventually at $a$ within $S$ if and only if there exists a positive real number $d$ such that for all $x \in S$ with $x \neq a$ and $d(x,a) \leq d$, $P(x)$ holds.
\chapter[Tagish and Tlingit Place Naming Traditions of Southwestern Yukon]{\vspace{-25pt}Tagish and Tlingit Place Naming Traditions of Southwestern Yukon: Evidence of Language Shift} \sethandle{10125/24845} % Author last name as it appears in the header \def\authorlast{Moore} % change author in three references below to the actual author name so that this name is unique and matches the \label commands just below and at the end of the chapter \renewcommand{\beginchapter}{\pageref{moore-ch-begin}} \renewcommand{\finishchapter}{\pageref{moore-ch-end}} \label{moore-ch-begin} \thispagestyle{firststyle} \chapauth{Patrick Moore} \affiliation{University of British Columbia} \authortoc{Patrick Moore} \section{Introduction} Indigenous place names from the southwestern Yukon reflect a historical shift from the widespread use of Tagish, a northern Dene (Athabaskan) language, to a predominance of Tlingit (a distantly related Na-Dene language). While language shift between indigenous languages has undoubtedly been a common process in many regions of North America, the southwestern Yukon is unusual in that the shift from Tagish to Tlingit occurred relatively recently. Research on indigenous place names has increased in recent years because of anthropological interest in the cultural conceptualization of place and space, and because of the extensive documentation of land use related to indigenous land claims. Most of this work has focused on the place names of particular groups and regions, but some studies have also examined the contested nature of place naming in relation to colonialism, competing languages, language shift, and the displacement of indigenous peoples (Young 2001; Berg and Vuolteenaho 2009; Hercus, Hodges and Simpson 2009; Weinreich 2011). This study focuses specifically on the evidence that Tagish and Tlingit place names provide concerning the history of Tagish and Tlingit interaction and language shift in the southwest Yukon. This region is unusual in that a large number of place names have been recorded in both languages providing an opportunity to examine the processes of language change and evidence that Tagish was formerly the dominant language in this region but was gradually replaced by Tlingit. While intermarriage between the coastal Tlingit and the adjacent Tagish of the Yukon interior was likely common even before the arrival of Europeans, Tlingits' control of the fur trade between the Pacific coast and the southern Yukon greatly increased their prestige and economic influence in the nineteenth century. Tagish adopted the Tlingit moiety and clan systems, and many adopted Tlingit personal names. According to Tagish speaker Daisy Smith (personal communication) by the late 1800s the remaining speakers of Tagish were all bilingual in Tlingit. The place names that form the basis of this study were originally recorded in both Tlingit and Tagish and identified on a map of the region by Angela Sidney and anthropologist Julie Cruikshank (Sidney 1980). Jeff Leer of the Alaska Native Language Center provided the Tlingit transcriptions of Sidney’s place names. For this article the transcriptions for the Tagish place names have been updated to a contemporary Tagish orthography developed by linguists working with the Yukon Native Language Centre\footnote{The symbols used in the Tagish alphabet are described on the Yukon Native Language Centre website at \url{http://www.ynlc.ca/tagish.shtml\#alphabet}} and the translations and transcriptions of the Tlingit place names were rechecked with Bessie Cooley, a Tlingit speaker from Teslin, Yukon.\footnote{The Tlingit orthography used here is the same as the system developed by Gillian Story and Constance Naish and described on the Sealaska Heritage Foundation website at \url{http://www.sealaskaheritage.org/sites/defaults/files/tlingit_alphabet.swf}. The Naish/Story orthography is used in this article because it was the writing system used by Sydney and Cruikshank in their 1980 publication and because it remains in popular use. An alternative orthography for Tlingit was later developed by Jeff Leer and popularized by the Yukon Native Language Centre in their publications.} The numbering of the examples is the same as in Sidney 1980, which is the source of all the place names in this chapter unless otherwise noted. By the early twentieth century Tlingit was the predominant indigenous language in the Carcross and Tagish regions of southwestern Yukon, although a few families continued to speak Tagish as well as Tlingit and to use it with their children as well. The area also experienced an influx of English speakers after 1898 as it was situated on the main route to the Klondike Gold Rush. Tagish children who grew up in the early 1900s, among them Daisy Smith, Johnny Johns, and Angela Sidney, became some of the last fluent speakers of Tagish, and as adults worked with linguists and anthropologists to document their languages and cultures in the last decades of the twentieth century. Lucy Wren (personal communication), one of the last people to acquire first-language fluency in the language, recalled that her parents spoke to her only in Tlingit, but that Tagish was still commonly used between the adults in her home, and she was able to learn the language even though her parents avoided using it with her. A small number of anthropologists and linguists documented Tagish language and culture the last half of the twentieth century. In the 1960s, anthropologist Catherine McClellan documented Tagish cultural practices, beliefs and stories (McClellan 1975, 2007). Later, linguists and anthropologists associated with the Yukon Native Languages Project, which became the Yukon Native Languages Centre, documented the Tagish language and Tagish traditions. Julie Cruikshank worked extensively with Mrs. Angela Sidney, a fluent speaker of both Tagish and Tlingit to document stories (Cruikshank 1989, 1992), genealogies (Sidney 1983), and place names (Sidney 1980). Victor Golla, Jeff Leer, John Ritter, and Patrick Moore worked with Tagish speakers, principally Angela Sidney and Lucy Wren, to record the language in the form of field notes, basic language lessons (Wren 2005-2007), and as audio and video recordings. Most of the Tagish language documentation is housed at the Yukon Native Language Centre, and a description of the Tagish alphabet, audio lessons, and audio storybooks are available from the Centre. A large number of Tagish recordings and written materials are also housed at the Alaska Native Language Archive of the Alaska Native Language Center and can be accessed online for non-commercial use. \section{General Evidence of Length of Occupancy and Extent of Later Interaction} The evidence from Tagish and Tlingit place names is consistent with the view that the area where Tlingit was spoken expanded, first northward within coastal Alaska and then into the interior. Jeff Leer (1979) has argued for a northward expansion of Tlingit, since conservative features, such as constricted vowels, are found only in the southern Tongass dialect of Tlingit. In contrast, the Tagish language may have had a long history of development in the area where it was spoken in recent times. Based on a comparative study of terms for \textit{stream} in Dene (Athabaskan) languages, James Kari (1996a, 1996b) has argued that the historic Dene homeland was in the region where contemporary Dene languages use [tu·] for \textit{stream}, an area that includes the region where Tagish was historically spoken. This conservative word for \textit{stream} is evident in many of the place names that Cruikshank recorded with Angela Sidney (1980).\\ Examples of Tagish place names with [tu·] for ‘stream’: \begin{exe} \exi{4.} McClintock River \sn Gēs Tū’è’ (Tagish) king salmon river \sn T’ahéeni (Tlingit) king salmon river \exi{26.} Squanga Creek \sn Dèsgwą̄gè Tū’è’ (Tagish) Squanga whitefish creek \sn Dasgwaanga Héeni (Tlingit) Squanga whitefish creek \end{exe} Sidney learned Tlingit and Tagish as first languages and was able to provide terms in both for 68\% of the 130 locations. She identified 14\% of the places with only a Tagish name and nearly the same percentage, 18\%, with only Tlingit names. Some of the place names are composed of words from both languages, which indicates the extent of Tagish-Tlingit bilingualism, borrowing, and code-switching.\\ Examples of place names composed from both Tagish and Tlingit terms: \begin{exe} \exi{19.} The single peak separated from Sinwaa, adjacent to the Tagish Road and the turn-off from the Alaska Highway to Atlin, B.C. \sn Shgáa T’ōh (Tlingit then Tagish) Sidney says that shgáa is the Tlingit name of an unidentified bird. Cooley was unfamiliar with the word. The word is almost certainly Tlingit in any case since the sh-g syllable onset violates Tagish but not Tlingit phonological constraints. T’ōh is Tagish for nest \exi{55.} Tagish Hill \sn Tā̀gish Tóoli (Tagish then Tlingit) Tā̀gish is the Tagish name for the Tagish narrows \sn Tóoli is Tlingit for grassy hill \exi{80.} Head of Tagish Narrows \sn Tā̀gish Sháak (Tagish then Tlingit) Tā̀gish is the Tagish name for the Tagish narrows \sn Sháak is Tlingit for \textit{headwaters} \end{exe} The map in Figure~\ref{moore-map} indicates the location of the Tagish and Tlingit named places that are cited in this article. The reference numbers for these places on the map and in the article are the same as used in Sidney’s (1980) book and accompanying map. \begin{figure}[h] \centering \includegraphics[width=0.9\textwidth]{figures/moore-fig1} \caption{Locations of Selected Tagish and Tlingit Named Places}\label{moore-map} \end{figure} \section{Place Name Evidence of Language Shift from Tagish to Tlingit} While all of the Tagish speakers were also fluent in Tlingit by the late 1800s, in the course of changing Tagish place names into Tlingit names they often modified the Tagish originals in ways that point to both Tagish as the source language and to the coastal connections of Tlingit. Some Tlingit place names (\textit{Sinwaa}, \textit{Nisaleen}) or parts of place names (\textit{Deisleen}) are not meaningful in Tlingit because they are based on the sound of the Tagish name. Some parts of Tagish names were omitted as they were translated into Tlingit, and in at least one case a Tlingit place name (\textit{Sheix’w X’aayi}) uses a term for a tree found in coastal southeast Alaska in a new sense in the interior. While the Tlingit place names recorded by Angela Sidney are often composed of the same meaningful elements as the Tagish place name, in some cases, such as 18 below, the Tlingit term is based on the Tagish words modified to conform to the Tlingit sound system. In this case the Tlingit place name is not composed of elements that are meaningful in Tlingit. Bessie Cooley (personal communication) says Sinwaa is also the name of a mountain near the Taku River (see also Nyman and Leer 1993 for confirmation of this term). It is possible that the Tlingit name for that mountain was also based on an Athabaskan name. Names referring to limestone, “grey rock,” may be common in Dene languages of this region. There is a Southern Tutchone name of the same form, \textit{Sima} (grey rock) which is the name of Golden Horn Mountain south of Whitehorse. The Tagish term from Lucy Wren is from the Tagish Literacy Workshop held in 1994 (Moore 1994: 15); the Tlingit term doesn’t mean limestone and is likely based on the sound of the Tagish word as it is only meaningful as a place name.\\ Tlingit place names based on the sound of the Tagish name: \begin{exe} \exi{18.} The mountain southeast of Jakes Corner between the Alaska Highway and the Atlin Road, excluding the first mountain peak. \sn Tsambā’a (Tagish, Angela Sidney) `grey ridge' \sn Tsē Mbā (Tagish, Lucy Wren) `grey rock' \sn Sinwaa (Tlingit from Athabaskan) \exi{28.} Teslin River \sn Dèdèslīnī̀ (Tagish) `water running off' \sn Deisleen Íxde Naadaayí `Teslin running downstream' \exi{33.} Nisutlin River \sn Dèslī́nī́ (Tagish) (flowing [water?]) \sn Nisaleen or Nilaseen (Tlingit) (probably from Athabaskan) \end{exe} Tlingit speaker Bessie Cooley suggested ‘sneaks’ as a meaning for the Tlingit term Nisaleen, but it appears to be based on a Tagish word that includes the stem –līn, used in reference to flowing water, as in 28. The stem for “flowing water” may be commonly used in Dene (Athabaskan) place names since it also appears in other well-known names such as Deline (“where waters flow”) the North Slavey (and official English) name for the village at the headwaters of the Great Bear River on Great Bear Lake, Northwest Territories. The Tagish term in 33 is similar to the Tlingit (and English) terms for the village of Teslin, Yukon. The Tlingit (and English) terms for Nisutlin are likely based on a related Athabaskan word that had slightly different prefixes. In other cases, such as 9 below, Sidney provided a Tlingit translation but indicated that the Tlingit place name wasn’t actually used to identify that location, and that everyone continued to use the Tagish term. The meaning of the Tlingit translation that Sydney provided for 9 below is unclear since Cooley was not familiar with the Tlingit term Keshuwaa (héeni means ‘stream’). Keshuwaa doesn’t mean ‘grayling’ which is t’áse or t’ási in interior Tlingit (likely from Athabaskan).\\ Tlingit translation not actually used as a place name designation: \begin{exe} \exi{9.} Grayling Creek \sn T’àse Mbèt (Tagish) `grayling food' \sn *Keshuwaa Héeni (Tlingit) (*The Tlingit translation is not used.) \end{exe} At least one of the Tlingit terms that Sidney used in place names, the term for ‘red alder’ sheix’w in 15 below, has a different meaning than it would on the coast and reflects the extension of meanings in a new biotic zone. There are no red alder in the interior, the coastal Tlingit term is used by Tlingit in the interior as the nearest equivalent to red willow. Since the Tagish remained in the same biotic region, this sort of semantic shifts is not evident in Tagish place names.\\ Coastal Tlingit term given a new meaning in the Yukon interior: \begin{exe} \exi{15.} Point on the west Side of Marsh Lake \sn K’àye Desdel Nī (Tagish) red willow point \sn Sheix’w X’aayi (Tlingit) red alder point \end{exe} \noindent In other cases the Tagish name was simplified when it was translated into Tlingit by leaving out part of the Tagish place name.\\ Tagish place names that are simplified in Tlingit: \begin{exe} \exi{16.} A point on the west side of Marsh Lake, near Tagish Bridge \sn K’àlā Nī (Tagish) `willow branches point' \sn K’ày’ lā Nī (Tagish) `willow branches point' \sn Ch’áal’ X’aayi (Tlingit) `willow point' \exi{17.} The mountain northeast of Jake’s corner, just north of the Alaska Highway \sn Tl’o K’ā̀’ Dzełè’ (Tagish) `grass blade mountain \sn Chookanshaa (Tlingit) `grass mountain \exi{40.} Point of land on Little Atlin Lake, just north of the narrows \sn Mbesh Te’èts’et Nī (Tagish) `where a knife fell into the water point \sn Lítaa Héent Uwaxixi (Tlingit) `where a knife fell into the water \exi{59.} Western extension of Jubilee Mountain \sn Kā̀’ Dḕtl’ōni Dzełè’ (Tagish) `where arrows are tied in a bundle mountain' \sn Chooneit Shaayí (Tlingit) `arrow mountain' (translation from Athabaskan) \end{exe} The Tlingit place name Kaa Léelk’u Shakanóox’u (below) may be a literal translation of the Tagish terms that loses the non-literal meaning of the Tagish original. In the case below the Tagish word for ling cod fish Kwachų̄ literally means “someone’s grandmother,” and when translated literally in Tlingit it loses the reference to the fish that live in the adjacent lake.\\ Place names that lose their non-literal meaning in translation to Tlingit: \begin{exe}\exi{22.} “Streak Mountain”, north of Squanga Lake. \sn Kwachų̄ Tsī̀ts’enè’ (Tagish) `ling cod skull' (literally someone’s grandmother’s skull) \sn Kaa Léelk’u Shakanóox’u (Tlingit) `one’s grandmother’s skull' \end{exe} In both Tagish and Kaska, the names of specific fish or the generic word for fish may be used instead of the word for lake. According to Jeff Leer (personal communication) this place naming convention is not used in coastal Tlingit, so its use in interior Tlingit is evidence of the adoption of Tagish place naming practices as terms were translated into Tlingit. Bessie Cooley cited examples of interior Tlingit place names that use \textit{xáadi} (fish) to identify a lake, including \textit{Kaa Léelk’u Xáadi} (somebody’s grandparent [ling cod] fish), a lake near the south end of Teslin Lake, Yukon and X’aaa Xáadi (red fish), a lake near Teslin, Yukon. Examples from Kaska include \textit{Tets’egelūgé’} (up the hill fish), Watson Lake, 128° 47' W, 60° 08' N; \textit{Dzǭą̄lūgé’} (small bird fish), Little Bird Slough, 131°54' W, 62° 02' N; \textit{Bédelūgé’} (food fish), a lake that is one of the sources of Blind Creek, 132°46' W, 62° 13' N, \textit{Eyānlūé’} (downstream people fish), No English name, 132° 01'W, 62° 08° N; \textit{Kūk’éhlūgé’} (next behind fish), No English name, 132° 31' W. 62° 31' W; Tāgeslūgé’ (middle fish), No English name, 132° 20' W, 62° 09' N; \textit{Tédāgīlūgé’} (up on top fish) No English name, 132° 44' W, 62° 04' N (Kaska Tribal Council 1997). Interestingly, most of the Kaska names that use \textit{lūge} or \textit{lūe} ‘fish’ as a designation for lakes (all the examples except \textit{Tets’egelūgé’}, which is in the Watson Lake area) are in the northern part of Kaska territory near Ross River, where there were formerly many speakers of Tagish. In example 20 below the Tagish place name uses \textit{tā̀słeyī̀ }(pike fish) to designate the lake, while the Tlingit place name uses \textit{áayi} (lake).\\ Tagish place name using a fish name instead of ‘lake’: \begin{exe} \exi{20.} Squan Lake half way between Jake’s Corner and Squanga Lake. (Skwáan is a Tlingit personal name belonging to the Deisheetaan Clan. The lake may have been named for Joe Squan, or for someone else who held this name). \sn Skwān Tā̀słéyī (Tagish) `Squan’s Pikefish' \sn Skwáan Áayi (Tlingit) `Squan’s Lake' \end{exe} \section{Conclusion} The Tagish and Tlingit place names recorded by Angela Sidney (1980) with Julie Cruikshank provide important evidence of both language shift from Tagish to Tlingit in this region of southwest Yukon, and an indication that most Tagish were fully bilingual in Tlingit. Most of the Tlingit place names Sidney recorded (68\%) are exact translations of the Tagish names (calques). There are also a number of place names that incorporate words from both languages, demonstrating that code switching and the use of loan words were common features associated with bilingualism. While most of the Tlingit place names are exact translations of the Tagish terms, the terms that differ provide evidence that the Tagish place names were in use prior to widespread language shift to Tlingit. The processes of simplification, basing Tlingit terms on the sound of Tagish terms, creating translated terms that lose their non-literal sense, adopting or failing to adopt different generic conventions (the use of “fish” for “lake”), and giving Tlingit terms a new semantic sense appropriate to their use in a new biotic zone are all processes that might be expected as a result of the expanded use of Tlingit. In addition to providing detailed information about traditional land and resource use, Sidney’s and Cruikshank’s documentation of the Tagish and Tlingit place names for 130 locations in southwestern Yukon also reveals much about the nature of Tagish and Tlingit bilingualism and local processes of language shift. %%%% REFERENCES %%%%%%%%%%%%%%% \refheading \begin{hang} Berg, Lawrence \& Jani Vuolteenaho. 2009. \textit{Critical Toponymies: The Contested Politics of Place Naming}. Farnham, England, Burlington, Vermont: Ashgate. Cruikshank, Julie. 1990. \textit{Life Lived Like a Story: Life Stories of Three Yukon Native Elders}. Vancouver: University of British Columbia Press. Cruikshank, Julie. 1998. \textit{The Social Life of Stories: Narrative and Knowledge in the Yukon Territory}. Lincoln: University of Nebraska Press. Hercus, Luise, Flavia Hodges \& Jane Simpson (eds.). 2009. \textit{Land is a Map: Placenames of Indigenous Origins in Australia}. Canberra: ANU Press. Leer, Jeff. 1979. \textit{Proto-Athabaskan Verb Stem Variation Part One: Phonology}. Fairbanks: Alaska Native Language Centre, University of Alaska Fairbanks. Kari, James. 1996a. A Preliminary View of Hydronymic Districts in Northern Athabaskan Prehistory. \textit{Names} 44(4). 253-271. Kari, James. 1996b. Names as Signs: The Distribution of ‘Stream’ and ‘Mountain’ in Alaska Athabaskan Languages. In Eloise Jelinek, Sally Midgette, Keren Rice \& Leslie Saxon (eds.), \textit{Athabaskan Language Studies: Essays in Honour of Robert Young}, 243-268. Albuquerque: University of New Mexico Press. Kaska Tribal Council 1997 Guzāgi Kūgé’: Our Language Book: Nouns, Kaska, Mountain Slavey and Sekani. Whitehorse: Kaska Tribal Council. McClellan, Catherine. 1975. \textit{My Old People Say: An Ethnographic Survey of Southern Yukon Territory, Parts 1 and 2}. Ottawa National Museum of Man. McClellan, Catherine. 2007. \textit{My Old People’s Stories: A Legacy for Yukon First Nations}. Whitehorse: Yukon Tourism and Culture. Moore, Patrick. 1994. \textit{Tagish Literacy Workshop}. Whitehorse, Yukon: Carcross Tagish First Nation. Nyman, Elizabeth \& Jeff Leer. 1993 \textit{Gágiwdułàt: Brought Forth to Reconfirm: the Legacy of a Taku River Tlingit Clan}. Whitehorse: Yukon Native Language Centre, Fairbanks: Alaska Native Language Center. Sidney, Angela. 1980. \textit{Place Names of the Tagish Region, Southern Yukon}. Whitehorse: Council for Yukon Indians. Sidney, Angela. 1983. \textit{Haa Shagóon: Our Family History}. Whitehorse, Yukon: Council for Yukon Indians. Weinreich, Uriel. 2011. \textit{Languages in Contact: French, German and Romansch in Twentieth-Century Switzerland}. Amsterdam, Philadelphia: John Benjamins. Wren, Lucy. n.d. \textit{Tagish Language Lessons}. Victoria British Columbia: FirstVoices, First Peoples Cultural Heritage Foundation. \url{http://www.firstvoices.com/explore/FV/sections/Data/Yukon/Tagish/Tagish}, accessed January 25, 2019. Wren, Lucy. 2005-2007. \textit{Tagish Language Lessons}. Whitehorse: Yukon Native Language Centre. \url{http://www.ynlc.ca/tagish.shtml\#lessons} accessed January 25, 2019. Young, Kee How. 2001. The Politics and Aesthetics of Placenames in Sarawak. \textit{Anthropological Quarterly} 80(1). 65-91. \end{hang} \orcidfooter{Patrick Moore}{}{} \label{moore-ch-end}
\documentclass[a4paper]{article} \usepackage{etoolbox} \usepackage[colorlinks,bookmarksopen,bookmarksnumbered,citecolor=red,urlcolor=red]{hyperref} \usepackage[affil-it]{authblk} \usepackage[cm]{fullpage} \usepackage{amsmath, amssymb, amsthm, amscd, mathtools, stmaryrd} \usepackage{fullpage} \usepackage{algorithm,algcompatible} \usepackage{listings} \usepackage{color} \usepackage{graphicx} \usepackage{multirow} \usepackage{subfig} \usepackage{mathrsfs} \usepackage{booktabs,tabularx} \usepackage{caption} % For diagrams \usepackage{tikz} \usetikzlibrary{matrix} %%%%%%%%% Custom math commands %%%%%%%%% \DeclarePairedDelimiter\norm{\lVert}{\rVert} \DeclarePairedDelimiter\jump{\llbracket}{\rrbracket} \DeclarePairedDelimiter\avg{\{\!\!\{}{\}\!\!\}} \DeclarePairedDelimiter{\both}{\lbrace}{\rbrace} \renewcommand{\vec}[1]{\boldsymbol{#1}} \newcommand{\zhat}{\hat{\vec{z}}} \newcommand{\rhat}{\hat{\vec{r}}} \newcommand{\ddt}[1]{\frac{\partial #1}{\partial t}} \newcommand{\Uspace}{\mathbb{U}} \newcommand{\Vspace}{\mathbb{V}} \newcommand{\Wspace}{\mathbb{W}} \newcommand{\Hdiv}{\texttt{HDiv}} \newcommand{\Hcurl}{\texttt{HCurl}} \newcommand{\thgsays}[1]{{\bfseries Thomas says:} {\color{blue} #1}} \newcommand{\cjcsays}[1]{{\bfseries Colin says:} {\color{red} #1}} \title{Code verification for the manuscript: ``Slate: extending Firedrake's domain-specific abstraction to hybridized solvers for geoscience and beyond''} \author[$\dagger$,1]{Thomas H. Gibson} \affil[1]{Department of Mathematics, Imperial College, South Kensington Campus, London SW7 2AZ} \affil[$\dagger$]{Email: \texttt{[email protected]}} \date{\today} \begin{document} \maketitle \section{Code verification}\label{subsec:hybridpoisson} To verify our computed results, we now perform a simple convergence study for a model Dirichlet problem. We seek a solution to the Poisson equation as a first-order system: \begin{align}\label{eq:modelpoisson} \boldsymbol{u} + \nabla p &= 0 \text{ in } \Omega = \lbrack 0, 1\rbrack^2, \\ \nabla\cdot\boldsymbol{u} &= f \text{ in } \Omega, \\ p &= p_0 \text{ on } \partial\Omega_D, \end{align} where $f$ and $p_0$ are chosen so that the analytic solution is the sinusoid $p(x, y) = \sin(\pi x)\sin(\pi y)$ and its negative gradient. We solve this problem by hybridizing the mixed formulation of \eqref{eq:modelpoisson}, and employ our static condensation preconditioner described in Section 4.1.1 of the manuscript. All results were obtained in serial, with MUMPS providing the LU factorization algorithms for the condensed trace system. Each mesh in our convergence study is obtained by generating a quadrilateral mesh with $2^r$ cells in each spatial direction, and dividing each quadrilateral cell into two equal simplicial elements. Once the solutions are obtained, we compute a post-processed scalar solution using the method described in Section 3.3.1 of the manuscript via Slate-generated kernels. Figure \ref{fig:h-rt-conv} displays the results for the hybridized Raviart-Thomas (RT) method. Our computations are in full agreement with the theory. \begin{figure}[!htbp] \centering \includegraphics[width=\textwidth]{HMM/HRT-convergence} \caption{Error convergence rates for our implementation of the hybridized RT method of orders 0, 1, 2, and 3. We observe the expected rates for the scalar and flux solutions of the standard RT method: $k+1$ in the $L^2$-error for both the scalar and flux approximations. Additionally, we see the effects of post-processing the scalar solution, yielding superconvergent $k+2$ rates.} \label{fig:h-rt-conv} \end{figure} We repeat this experiment for the LDG-H method with varying choices of $\tau$ in order to verify how $\tau$ influences the convergence rates, comparing with the expected rates for the LDG-H method given a particular order of $\tau$ (see Table \ref{table:ldg-h-rates} for a summary). In all our experiments, we use the post-processing methods described in Sections 3.3.1 and 3.3.2 to produce approximations $p_h^\star$ and $\boldsymbol{u}_h^\star$. Error convergence plots from our tests are shown in Figure \ref{fig:ldgh-conv} that confirm the expected rates. This rather sensitive test verifies that our software framework is generating correct code. \begin{table}[!htbp] \centering \caption{The expected convergence rates of the LDG-H method with a stability parameter $\tau$ of a particular order.} \begin{tabular}{ccccc} \hline parameter & \multicolumn{4}{c}{expected rates of convergence ($k \geq 1$)} \\ \cline{2-5} $\tau$ & $\norm{p - p_h}_{L^2(\Omega)}$ & $\norm{\boldsymbol{u} - \boldsymbol{u}_h}_{\boldsymbol{L}^2(\Omega)}$ & $\norm{p - p^\star_h}_{L^2(\Omega)}$ & $\norm{\boldsymbol{u} - \boldsymbol{u}^\star_h}_{\boldsymbol{L}^2(\Omega)}$ \\ \hline $\mathcal{O}(1)$ & $k+1$ & $k+1$ & $k+2$ & $k+1$ \\ \hline $\mathcal{O}(h)$ & $k$ & $k+1$ & $k+2$ & $k+1$ \\ \hline $\mathcal{O}\left(h^{-1}\right)$ & $k+1$ & $k$ & $k+1$ & $k$ \\ \hline \end{tabular} \label{table:ldg-h-rates} \end{table} \begin{figure}[!htbp] \centering \includegraphics[width=0.8\textwidth]{LDGH/LDGH-convergence} \caption{Error convergence rates for our implementation of the LDG-H method with $\tau = h$ and $\tau = \frac{1}{h}$. The expected sensitivity of this discretization subject to appropriate choices of stabilization parameter $\tau$ is verified. We see no change in the convergence rates between the scalar and post-processed scalar solutions when $\tau = \frac{1}{h}$. Superconvergence is achieved when taking $\tau = h$. The post-processed flux rates in both cases match the rates of the unprocessed flux.} \label{fig:ldgh-conv} \end{figure} \end{document}
State Before: R : Type u a b : R m n : ℕ inst✝ : Semiring R p q : R[X] ⊢ p * q = ∑ i in support p, sum q fun j a => ↑(monomial (i + j)) (coeff p i * a) State After: case a R : Type u a b : R m n : ℕ inst✝ : Semiring R p q : R[X] ⊢ (p * q).toFinsupp = (∑ i in support p, sum q fun j a => ↑(monomial (i + j)) (coeff p i * a)).toFinsupp Tactic: apply toFinsupp_injective State Before: case a R : Type u a b : R m n : ℕ inst✝ : Semiring R p q : R[X] ⊢ (p * q).toFinsupp = (∑ i in support p, sum q fun j a => ↑(monomial (i + j)) (coeff p i * a)).toFinsupp State After: case a.ofFinsupp R : Type u a b : R m n : ℕ inst✝ : Semiring R q : R[X] toFinsupp✝ : AddMonoidAlgebra R ℕ ⊢ ({ toFinsupp := toFinsupp✝ } * q).toFinsupp = (∑ i in support { toFinsupp := toFinsupp✝ }, sum q fun j a => ↑(monomial (i + j)) (coeff { toFinsupp := toFinsupp✝ } i * a)).toFinsupp Tactic: rcases p with ⟨⟩ State Before: case a.ofFinsupp R : Type u a b : R m n : ℕ inst✝ : Semiring R q : R[X] toFinsupp✝ : AddMonoidAlgebra R ℕ ⊢ ({ toFinsupp := toFinsupp✝ } * q).toFinsupp = (∑ i in support { toFinsupp := toFinsupp✝ }, sum q fun j a => ↑(monomial (i + j)) (coeff { toFinsupp := toFinsupp✝ } i * a)).toFinsupp State After: case a.ofFinsupp.ofFinsupp R : Type u a b : R m n : ℕ inst✝ : Semiring R toFinsupp✝¹ toFinsupp✝ : AddMonoidAlgebra R ℕ ⊢ ({ toFinsupp := toFinsupp✝¹ } * { toFinsupp := toFinsupp✝ }).toFinsupp = (∑ i in support { toFinsupp := toFinsupp✝¹ }, sum { toFinsupp := toFinsupp✝ } fun j a => ↑(monomial (i + j)) (coeff { toFinsupp := toFinsupp✝¹ } i * a)).toFinsupp Tactic: rcases q with ⟨⟩ State Before: case a.ofFinsupp.ofFinsupp R : Type u a b : R m n : ℕ inst✝ : Semiring R toFinsupp✝¹ toFinsupp✝ : AddMonoidAlgebra R ℕ ⊢ ({ toFinsupp := toFinsupp✝¹ } * { toFinsupp := toFinsupp✝ }).toFinsupp = (∑ i in support { toFinsupp := toFinsupp✝¹ }, sum { toFinsupp := toFinsupp✝ } fun j a => ↑(monomial (i + j)) (coeff { toFinsupp := toFinsupp✝¹ } i * a)).toFinsupp State After: case a.ofFinsupp.ofFinsupp R : Type u a b : R m n : ℕ inst✝ : Semiring R toFinsupp✝¹ toFinsupp✝ : AddMonoidAlgebra R ℕ ⊢ toFinsupp✝¹ * toFinsupp✝ = ∑ x in toFinsupp✝¹.support, ∑ x_1 in toFinsupp✝.support, Finsupp.single (x + x_1) (↑toFinsupp✝¹ x * ↑toFinsupp✝ x_1) Tactic: simp [support, sum, coeff, toFinsupp_sum] State Before: case a.ofFinsupp.ofFinsupp R : Type u a b : R m n : ℕ inst✝ : Semiring R toFinsupp✝¹ toFinsupp✝ : AddMonoidAlgebra R ℕ ⊢ toFinsupp✝¹ * toFinsupp✝ = ∑ x in toFinsupp✝¹.support, ∑ x_1 in toFinsupp✝.support, Finsupp.single (x + x_1) (↑toFinsupp✝¹ x * ↑toFinsupp✝ x_1) State After: no goals Tactic: rfl
function []=draw(f,a,b) % % draws f in the intervall [a,b] % x=linspace(a,b,100); y=feval(f,x); plot(x,y,'k-'); print -deps p
function [annualRet,annualCov,annualStd] = ComputeHistoricalStats(prices) returns = tick2ret(prices,[],'continuous'); numReturns = size(returns,1); [annualRet,annualCov] = geom2arith(mean(returns),cov(returns),numReturns); annualRet = annualRet'; annualStd = sqrt(diag(annualCov));
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 SUBROUTINE GETM3 (ML, MS, MNNPS, NS, ISLIST, NINT, IFLINE, NLPS, & ILLIST, LINKL, LINKS, X, Y, NID, NNPS, ANGLE, NPER, M1A, M1B, & M2A, M2B, M3A, M3B, XCEN, YCEN, CCW, ERR) C*********************************************************************** C SUBROUTINE GETM3 = GETS THE APPROPRIATE SIDE LENGTHS AND DIVISIONS C FOR A TRIANGULAR REGION C*********************************************************************** C SUBROUTINE CALLED BY: C QMESH = GENERATES QUAD ELEMENTS C*********************************************************************** C VARIABLES USED: C NNPS = ARRAY OF NUMBER OF NODES PER SIDE C CCW = .TRUE. IF THE SIDE IS ORIENTED CCW C NORM = .TRUE. IF THE FIRST SIDE IS TO BE TRIED AS THE BASE C*********************************************************************** DIMENSION NNPS (MNNPS), ISLIST (NS), LINKL (2, ML), LINKS (MS*2) DIMENSION NINT (ML), NLPS (MS), IFLINE (MS), ILLIST (MS*3) DIMENSION X (NPER), Y (NPER), NID (NPER), ANGLE (NPER) LOGICAL CCW, ERR C CALCULATE THE NUMBER OF NODES PER SIDE CALL NPS (ML, MS, MNNPS, NS, ISLIST, NINT, IFLINE, NLPS, ILLIST, & LINKL, LINKS, NNPS, ERR) IF (ERR) RETURN IF (.NOT. CCW) CALL IREVER (NNPS, NS) C FIND THE BEST CORNER NODES IN THE LIST CALL PICKM3 (NPER, X, Y, ANGLE, M1, M2, IFIRST) IF (IFIRST .NE. 1) CALL FQ_ROTATE (NPER, X, Y, NID, IFIRST) C NOW SORT THE LIST SO THE LONGEST SIDE IS FIRST M3 = NPER - M1 - M2 MMAX = MAX0 (M1, M2, M3) IF (M1 .EQ. MMAX)THEN CONTINUE ELSEIF (M2 .EQ. MMAX) THEN CALL FQ_ROTATE (NPER, X, Y, NID, M1 + 1) MHOLD = M1 M1 = M2 M2 = M3 M3 = MHOLD ELSEIF (M3 .EQ. MMAX) THEN CALL FQ_ROTATE (NPER, X, Y, NID, M1 + M2 + 1) MHOLD = M1 M1 = M3 M3 = M2 M2 = MHOLD ENDIF C SPLIT THE SIDES INTO LOGICAL DIVISIONS C IF (M2 .EQ. M3)THEN C M1A = (.5 * DBLE(M1)) + .001 C M1B = M1A C ELSEIF (M2 .LT. M3)THEN C FACT = DBLE(M2 - 1) / DBLE(M2 + M3 - 2) C M1A = FACT * M1 + .001 C M1A = MAX0 (M1A, 1) C M1A = MIN0 (M1A, M1-1) C M1B = M1 - M1A C ELSE C FACT = DBLE(M3 - 1) / DBLE(M2 + M3 - 2) C M1B = FACT * M1 + .001 C M1B = MAX0 (M1B, 1) C M1B = MIN0 (M1B, M1-1) C M1A = M1-M1B C ENDIF M1A = (M1 + M2 - M3) / 2 M1B = M1 - M1A M2A = M2 - M1A M2B = M1A M3A = M1B M3B = M3 - M3A ERR = .TRUE. IF (M3B .NE. M2A) THEN CALL MESSAGE('ERROR GENERATING TRIANGLE DIVISION POINT') RETURN ENDIF C DEFINE THE MIDDLE POINT AS THE AVERAGE OF PROPORIONAL DIVISIONS C OF SIDE DIVISION POINT TO OPPOSITE TRIANGLE CORNER LINES I1 = 1 I2 = M1 + 1 I3 = M1 + M2 + 1 J1 = I1 + M1A J2 = I2 + M2A J3 = I3 + M3A C FIND DISTANCES FROM CORNER TO CORNER, AND CORNERS TO SIDE DIVISIONS D1 = SQRT ( (X (I2) - X (I1)) **2 + (Y (I2) - Y (I1)) **2) D2 = SQRT ( (X (I3) - X (I2)) **2 + (Y (I3) - Y (I2)) **2) D3 = SQRT ( (X (I1) - X (I3)) **2 + (Y (I1) - Y (I3)) **2) D1A = SQRT ( (X (J1) - X (I1)) **2 + (Y (J1) - Y (I1)) **2) D1B = SQRT ( (X (I2) - X (J1)) **2 + (Y (I2) - Y (J1)) **2) D2A = SQRT ( (X (J2) - X (I2)) **2 + (Y (J2) - Y (I2)) **2) D2B = SQRT ( (X (I3) - X (J2)) **2 + (Y (I3) - Y (J2)) **2) D3A = SQRT ( (X (J3) - X (I3)) **2 + (Y (J3) - Y (I3)) **2) D3B = SQRT ( (X (I1) - X (J3)) **2 + (Y (I1) - Y (J3)) **2) C GET MIDPOINT TRIALS 1, 2, AND 3 AS PROPORTIONS PRO1 = .5 * ( (D3A / D3) + (D1B / D1)) X1 = X (J2) - (PRO1 * (X (J2) - X (I1))) Y1 = Y (J2) - (PRO1 * (Y (J2) - Y (I1))) PRO2 = .5 * ( (D2B / D2) + (D1A / D1)) X2 = X (J3) - (PRO2 * (X (J3) - X (I2))) Y2 = Y (J3) - (PRO2 * (Y (J3) - Y (I2))) PRO3 = .5 * ( (D2A / D2) + (D3B / D3)) X3 = X (J1) - (PRO3 * (X (J1) - X (I3))) Y3 = Y (J1) - (PRO3 * (Y (J1) - Y (I3))) C AVERAGE POINTS TO GET THE CENTER XCEN = (X1 + X2 + X3) / 3. YCEN = (Y1 + Y2 + Y3) / 3. ERR = .FALSE. RETURN END
MODULE m_uj2f USE m_juDFT ! ********************************************************************* ! * The calculation of slater integrals from u&j * ! * input in eV; output in htr. * ! *-------------------------------------------------------------------* ! * Extension to multiple U per atom type by G.M. 2017 * ! * Extension for uses beyond LDA+U by H.J 2019 * ! ********************************************************************* USE m_types IMPLICIT NONE INTERFACE uj2f PROCEDURE :: uj2f_simple, uj2f_spins END INTERFACE CONTAINS SUBROUTINE uj2f_simple(jspins,u_in,n_u,f0,f2,f4,f6) INTEGER, INTENT(IN) :: jspins INTEGER, INTENT(IN) :: n_u TYPE(t_utype), INTENT(IN) :: u_in(:) REAL, INTENT(OUT) :: f0(:),f2(:) REAL, INTENT(OUT) :: f4(:),f6(:) REAL :: f0Spins(n_u,jspins),f2Spins(n_u,jspins) REAL :: f4Spins(n_u,jspins),f6Spins(n_u,jspins) CALL uj2f_spins(jspins,u_in,n_u,f0Spins,f2Spins,f4Spins,f6Spins) f0 = (f0Spins(:,1) + f0Spins(:,jspins))/ 2.0 f2 = (f2Spins(:,1) + f2Spins(:,jspins))/ 2.0 f4 = (f4Spins(:,1) + f4Spins(:,jspins))/ 2.0 f6 = (f6Spins(:,1) + f6Spins(:,jspins))/ 2.0 END SUBROUTINE uj2f_simple SUBROUTINE uj2f_spins(jspins,u_in,n_u,f0,f2,f4,f6) INTEGER, INTENT(IN) :: jspins INTEGER, INTENT(IN) :: n_u TYPE(t_utype), INTENT(IN) :: u_in(:) REAL, INTENT(OUT) :: f0(:,:),f2(:,:) REAL, INTENT(OUT) :: f4(:,:),f6(:,:) INTEGER l,itype,ltest,ispin,i_u REAL u,j,a,ftest(4) LOGICAL l_exist l_exist=.FALSE. INQUIRE (file='slaterf',exist=l_exist) IF (l_exist) THEN ! ! --> f's have been calculated in cored ; read from file ! OPEN (45,file='slaterf',form='formatted',status='old') DO ispin = 1, jspins DO i_u = 1, n_u itype = u_in(i_u)%atomType l = u_in(i_u)%l f2(i_u,ispin)=0.0 ; f4(i_u,ispin)=0.0 ; f6(i_u,ispin)=0.0 100 READ (45,'(i3,4f20.10)') ltest,ftest(1:4) IF (ltest.EQ.l) THEN f0(i_u,ispin) = ftest(1) IF (l.GT.0) THEN f2(i_u,ispin) = ftest(2) IF (l.GT.1) THEN f4(i_u,ispin) = ftest(3) IF (l.GT.2) THEN f6(i_u,ispin) = ftest(4) END IF END IF END IF ELSE GOTO 100 END IF READ (45,'(i3,4f20.10)') ltest,ftest(1) ! IF (ltest.EQ.0) THEN ! f0(n,ispin) = f0(n,ispin) - ftest(1) ! ENDIF ! write(*,*) n,ispin,l,f0(n,ispin),f2(n,ispin), ! + f4(n,ispin),f6(n,ispin) END DO ! n_u ENDDO CLOSE (45) ELSE ! ! lda_u%l: orb.mom; lda_u%u,j: in eV ! DO i_u = 1, n_u itype = u_in(i_u)%atomType l = u_in(i_u)%l u = u_in(i_u)%u j = u_in(i_u)%j ! ! l.eq.0 : f0 = u (the l=0 and l=1 case approximated g.b.`01) ! IF (l.EQ.0) THEN f0(i_u,1) = u f2(i_u,1) = 0.0 f4(i_u,1) = 0.0 f6(i_u,1) = 0.0 IF (j>0.00001) CALL juDFT_error("lda+u: no magnetic s-states", calledby ="uj2f") ! ! l == 1 : j = f2 / 5 (from PRL 80,5758 g.b.) ! ELSE IF (l.EQ.1) THEN f0(i_u,1) = u f2(i_u,1) = 5.0*j f4(i_u,1) = 0.0 f6(i_u,1) = 0.0 ! ! l.eq.2 : 3d: j=(f2+f4)/14; f4/f2 = 0.625 ! ELSE IF (l.EQ.2) THEN ! PRINT*, 'd-states' f0(i_u,1) = u f2(i_u,1) = 14.0*j/1.625 f4(i_u,1) = f2(i_u,1)*0.625 f6(i_u,1) = 0.0 ! ! l.eq. 3 : 4f: j=(286f2+195f4+250f6)/6435; f2/f4 = 675/451; f2/f6=2025/1001 ! ELSE IF (l.EQ.3) THEN ! PRINT*, 'f-states' f0(i_u,1) = u a= 286.0 + 195.0*451.0/675.0 + 250.0*1001.0/2025.0 f2(i_u,1) = 6435.0*j/a f4(i_u,1) = 451.0/675.0*f2(i_u,1) f6(i_u,1) = 1001.0/2025.0*f2(i_u,1) ELSE CALL juDFT_error('lda+U is restricted to l<=3 !', calledby="uj2f") END IF IF (jspins.EQ.2) THEN f0(i_u,jspins) = f0(i_u,1) f2(i_u,jspins) = f2(i_u,1) f4(i_u,jspins) = f4(i_u,1) f6(i_u,jspins) = f6(i_u,1) ENDIF END DO ! n_u ENDIF END SUBROUTINE uj2f_spins END MODULE m_uj2f
#include <gsl/gsl_ntuple.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> struct data { double x; double y; double z; }; int main (void) { const gsl_rng_type * T; gsl_rng * r; struct data ntuple_row; int i; gsl_ntuple *ntuple = gsl_ntuple_create ("test.dat", &ntuple_row, sizeof (ntuple_row)); gsl_rng_env_setup (); T = gsl_rng_default; r = gsl_rng_alloc (T); for (i = 0; i < 10000; i++) { ntuple_row.x = gsl_ran_ugaussian (r); ntuple_row.y = gsl_ran_ugaussian (r); ntuple_row.z = gsl_ran_ugaussian (r); gsl_ntuple_write (ntuple); } gsl_ntuple_close (ntuple); gsl_rng_free (r); return 0; }
output_name <- "codeml_results_pvals_uncorrected.txt" output_name2 <- "codeml_results_pvals_corrected.txt" write(c("gene_number", "camponotus_un_p", "formica_un_p", "nylanderia_un_p", "lasius_un_p"), file=output_name, ncolumns=5, sep="\t") x <- list.files(pattern="*fasta") x2 <- list.files(pattern="*txt") x_numbers <- as.numeric(sapply(strsplit(x, "_"), "[[", 1)) library(stats) library(Biostrings) library(seqinr) for(a in 1:max(x_numbers)) { x_match <- match(paste(a, "_aligned_trimmed.fasta", sep=""), x) # see if fasta file exists if(!is.na(x_match)) { # if yes read it a_rep <- readDNAStringSet(paste(a, "_aligned_trimmed.fasta", sep="")) if(a_rep@ranges@width[1] >= 150) { # only use those that are at least 50 AAs (150 nucleotides) x_match <- match(paste(a, "_total_output.txt", sep=""), x2) if(!is.na(x_match)) { # read in codeml output a_results <- read.table(paste(a, "_total_output.txt", sep=""), fill = T, stringsAsFactors=F) a_null_lnl <- a_results[1,5] # get the null model lnL a_alt_lnl <- a_results[c(3,5,7,9), 5] # get the alt models' lnL a_LRT <- 2 * (a_alt_lnl - a_null_lnl) # calculate the LRT a_uncorrected_p <- pchisq(a_LRT, df=1, lower.tail=FALSE) # get p-values for the LRT values (chi-square two tail) a_output <- c(a, a_uncorrected_p) write(a_output, file=output_name, ncolumns=5, append=T, sep="\t") } } } } # read in previous output with p-values output <- read.table(output_name, sep="\t", stringsAsFactors=F, header=T) # calculate number of tests = number of genes * 4 tests number_comparisons <- nrow(output) * 4 # multiple testing correction of the p-values using Benjamini & Hochberg (1995) (fdr) output[,2] <- p.adjust(output[,2], method="fdr", n=number_comparisons) output[,3] <- p.adjust(output[,3], method="fdr", n=number_comparisons) output[,4] <- p.adjust(output[,4], method="fdr", n=number_comparisons) output[,5] <- p.adjust(output[,5], method="fdr", n=number_comparisons) # find minimum p-value for each gene and append that column to the output min_p <- apply(output[,2:5], 1, min) output <- cbind(output, min_p) plot(min_p, pch=19, cex=0.1) write.table(output, file=output_name2, sep="\t", quote=F, col.names=T, row.names=F) # make the 4 fold degenerate sites output directory dir.create("_4d_output") # remove all significant tests and any rows missing info filtered_output <- na.omit(output) filtered_output <- filtered_output[filtered_output$min_p > 0.05, ] # function to identify 4 fold degenerate sites codon_table <- read.table("codon_table.txt", header=T, stringsAsFactors=F) determine_4d <- function(xxxx) { # remove codons with N if(length(grep("N", xxxx)) == 0) { # check if matches have 4D sites and return them if(codon_table[match(xxxx[1], codon_table[,1]),3] == "no") { return("") } else if(codon_table[match(xxxx[1], codon_table[,1]),2] == codon_table[match(xxxx[2], codon_table[,1]),2] & codon_table[match(xxxx[1], codon_table[,1]),2] == codon_table[match(xxxx[3], codon_table[,1]),2] & codon_table[match(xxxx[1], codon_table[,1]),2] == codon_table[match(xxxx[4], codon_table[,1]),2]) { return_object <- substr(xxxx, 3, 3) } else { return("") } } } # loop to # read in multiple sequence alignments that are not under selection so as to get the four-fold degenerate sites # for a later phylogeny locus_results <- list() for(a in 1:nrow(filtered_output)) { a_rep <- read.fasta(paste(filtered_output[a,1], "_aligned_trimmed.fasta", sep="")) # determine how many codons and put into a list for each codon codons <- length(a_rep$camponotus) / 3 # make codon list codon_list <- list() for(b in 1:codons) { codon_list[[b]] <- c(paste(toupper(a_rep$camponotus[(b*3-2):(b*3)]), collapse=""), paste(toupper(a_rep$lasius[(b*3-2):(b*3)]), collapse=""), paste(toupper(a_rep$formica[(b*3-2):(b*3)]), collapse=""), paste(toupper(a_rep$nylanderia[(b*3-2):(b*3)]), collapse="")) } # use the determine_4d function to return four fold degenerate sites for this locus fourd_sites <- list() for(b in 1:length(codon_list)) { fourd_sites[[b]] <- determine_4d(codon_list[[b]]) } # remove null results fourd_sites2 <- list() for(b in 1:length(fourd_sites)) { if(b == 1) { b_count <- 1 } if(length(fourd_sites[[b]]) > 1) { fourd_sites2[[b_count]] <- fourd_sites[[b]] b_count <- b_count + 1 } } # add sites to overall results list locus_results[[a]] <- c(paste(sapply(fourd_sites2, "[[", 1), collapse=""), paste(sapply(fourd_sites2, "[[", 2), collapse=""), paste(sapply(fourd_sites2, "[[", 3), collapse=""), paste(sapply(fourd_sites2, "[[", 4), collapse="")) # print progress if(a %% 100 == 0) { print(a / nrow(filtered_output)) } } # concatenate results across loci camponotus <- paste(sapply(locus_results, "[[", 1), collapse="") lasius <- paste(sapply(locus_results, "[[", 2), collapse="") formica <- paste(sapply(locus_results, "[[", 3), collapse="") nylanderia <- paste(sapply(locus_results, "[[", 4), collapse="") # total of 806844 sites output_name <- "_total_4d_sites.fasta" write(">camponotus", file=output_name, ncolumns=1) write(camponotus, file=output_name, ncolumns=1, append=T) write(">lasius", file=output_name, ncolumns=1, append=T) write(lasius, file=output_name, ncolumns=1, append=T) write(">formica", file=output_name, ncolumns=1, append=T) write(formica, file=output_name, ncolumns=1, append=T) write(">nylanderia", file=output_name, ncolumns=1, append=T) write(nylanderia, file=output_name, ncolumns=1, append=T)
Have you ever found a parking spot, then realized you have no change in your wallet for the meter, or stood in the pouring rain fumbling for money at the parking pay station? Well, HonkMobile can change all that. Wilfrid Laurier University has entered into an agreement with HonkMobile — an app that provides a fast and convenient way to find and pay for parking — that will streamline parking for the Laurier community and visitors to Laurier’s Waterloo campus. The easy-to-use app lets motorists bypass the parking meter by allowing them to search and pay for parking from their smartphone. Users receive alerts 15 minutes before their parking session expires, giving them the opportunity to pay for additional time remotely. The app also stores and manages parking receipts. Using a single account, motorists can pay for parking anywhere HonkMobile is accepted across North America. To download the app or to learn more visit www.honkmobile.com.
function [data_mean,data_diff,md,sd] = bland_altman_x_gt(data1,data2) % Function to generate Bland Altman plots. Barry Greene, September 2008 % Bland, J.M., Altman, D.G. 'Statistical methods for assessing agreement ... % between two methods of clinical measurement'(1986) Lancet, 1 (8476), pp. 307-310. % % Inputs: data1: ground truth % data2: estimated % % Produces Bland Altman plot with mean difference and mean difference +/- % 2*SD difference lines. [m,n] = size(data1); if(n>m) data1 = data1'; end if(size(data1)~=size(data2)) error('Data matrices must be the same size') end data_mean = data1; % Mean of values from each instrument data_diff = data2 - data1; % Difference between data from each instrument md = mean(data_diff); % Mean of difference between instruments sd = std(data_diff); % Std dev of difference between instruments % figure; plot(data_mean,data_diff,'ok','MarkerSize',3,'LineWidth',1); % Bland Altman plot hold on; x = [min(data_mean),max(data_mean)]; y = md*ones(1,2); plot(x,y,'-k'); % Mean difference line y = md+2*sd*ones(1,2); plot(x,y,'--k'); % Mean plus 2*SD line % text(x(2),y(2),'+2 SD'); y = md-2*sd*ones(1,2); plot(x,y,'--k'); % Mean minus 2*SD line % text(x(2),y(2),'-2 SD'); % grid on % title('Bland Altman plot','FontSize',9) % xlabel('Mean of two measures','FontSize',8) % ylabel('Difference between two measures','FontSize',8)
The centre of a ball is in the ball if and only if the radius is non-negative.
20 top Pancake Wallpapers pics at these awesome group starting P letter. Desktop wallpapers were first introduced way back in the 1980s and have gained immense popularity since then. It is possible to come across more than 80 million sites on the web offering some sort of wallpaper.
import data.real.basic import tactic.ring structure complex := (re : ℝ) (im : ℝ) notation `ℂ` := complex -- constructor applied to projections theorem complex.eta (z : ℂ) : complex.mk (complex.re z) (complex.im z) = z := begin cases z with x y, dsimp, refl, end -- two complex numbers are equal if their real and imaginary parts are equal @[extensionality] theorem complex.ext (z1 z2 : ℂ) (hre : z1.re = z2.re) (him : z1.im = z2.im) : z1 = z2 := begin cases z1 with x y, cases z2 with a b, -- two ways to sort out the mess that hre and him -- have become dsimp at hre, change y = b at him, rw hre, rw him, end namespace complex def zero : ℂ := ⟨0, 0⟩ instance : has_zero ℂ := ⟨complex.zero⟩ @[simp] lemma zero_re : (0 : ℂ).re = 0 := rfl @[simp] lemma zero_im : (0 : ℂ).im = 0 := rfl def add (z w : ℂ) : ℂ := ⟨z.re + w.re, z.im + w.im⟩ instance : has_add ℂ := ⟨complex.add⟩ @[simp] lemma add_re (a b : ℂ) : (a + b).re = a.re + b.re := rfl @[simp] lemma add_im (a b : ℂ) : (a + b).im = a.im + b.im := rfl def neg (z : ℂ) : ℂ := ⟨-z.re, -z.im⟩ instance : has_neg ℂ := ⟨complex.neg⟩ @[simp] lemma neg_re (a : ℂ) : (-a).re = -a.re := rfl @[simp] lemma neg_im (a : ℂ) : (-a).im = -a.im := rfl def one : ℂ := ⟨1, 0⟩ instance : has_one ℂ := ⟨complex.one⟩ @[simp] lemma one_re : (1 : ℂ).re = 1 := rfl @[simp] lemma one_im : (1 : ℂ).im = 0 := rfl def mul (z w : ℂ) : ℂ := ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩ instance : has_mul ℂ := ⟨complex.mul⟩ @[simp] lemma mul_re (a b : ℂ) : (a * b).re = a.re * b.re - a.im * b.im := rfl @[simp] lemma mul_im (a b : ℂ) : (a * b).im = a.re * b.im + a.im * b.re := rfl instance : comm_ring ℂ := begin refine { zero := 0, add := (+), neg := has_neg.neg, one := 1, mul := (*), ..}; intros; ext; simp; ring end end complex -- end of namespace
Formal statement is: 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)" Informal statement is: If $f$ and $g$ are continuous functions from a set $S$ to a normed vector space $V$, then the function $h$ defined by $h(x) = f(x) \cdot g(x)$ is continuous.
(* Author: Manuel Eberl <[email protected]> *) theory Misc_Polynomial imports "~~/src/HOL/Library/Poly_Deriv" begin subsection {* Analysis *} lemma fun_eq_in_ivl: assumes "a \<le> b" "\<forall>x::real. a \<le> x \<and> x \<le> b \<longrightarrow> eventually (\<lambda>\<xi>. f \<xi> = f x) (at x)" shows "f a = f b" proof (rule connected_local_const) show "connected {a..b}" "a \<in> {a..b}" "b \<in> {a..b}" using `a \<le> b` by (auto intro: connected_Icc) show "\<forall>aa\<in>{a..b}. eventually (\<lambda>b. f aa = f b) (at aa within {a..b})" proof fix x assume "x \<in> {a..b}" with assms(2)[rule_format, of x] show "eventually (\<lambda>b. f x = f b) (at x within {a..b})" by (auto simp: eventually_at_filter elim: eventually_elim1) qed qed subsection {* Polynomials *} subsubsection {* General simplification lemmas *} lemma div_diff: fixes a :: "'a::ring_div" assumes "q dvd a" "q dvd b" shows "a div q - b div q = (a - b) div q" proof- from assms have "a div q + (-b div q) = (a + (-b)) div q" by (subst div_add, simp_all) thus ?thesis by (simp add: assms dvd_neg_div algebra_simps) qed lemma poly_gcd_right_idem: "gcd (gcd (p :: _ poly) q) q = gcd p q" by (rule poly_gcd_unique, simp_all add: poly_gcd_monic) lemma poly_gcd_left_idem: "gcd p (gcd (p :: _ poly) q) = gcd p q" by (rule poly_gcd_unique, simp_all add: poly_gcd_monic) lemma degree_power_eq: "(p::('a::idom) poly) \<noteq> 0 \<Longrightarrow> degree (p^n) = n * degree p" by (induction n, simp_all add: degree_mult_eq) lemma poly_altdef: "poly p (x::real) = (\<Sum>i\<le>degree p. coeff p i * x ^ i)" proof (induction p rule: pCons_induct) case (pCons a p) show ?case proof (cases "p = 0") case False let ?p' = "pCons a p" note poly_pCons[of a p x] also note pCons.IH also have "a + x * (\<Sum>i\<le>degree p. coeff p i * x ^ i) = coeff ?p' 0 * x^0 + (\<Sum>i\<le>degree p. coeff ?p' (Suc i) * x^Suc i)" by (simp add: field_simps setsum_right_distrib coeff_pCons) also note setsum_atMost_Suc_shift[symmetric] also note degree_pCons_eq[OF `p \<noteq> 0`, of a, symmetric] finally show ?thesis . qed simp qed simp lemma pderiv_div: assumes [simp]: "q dvd p" "q \<noteq> 0" shows "pderiv (p div q) = (q * pderiv p - p * pderiv q) div (q * q)" "q*q dvd (q * pderiv p - p * pderiv q)" proof- note pderiv_mult[of q "p div q"] also have "q * (p div q) = p" by (simp add: dvd_mult_div_cancel) finally have "q * pderiv (p div q) = q * pderiv p div q - p * pderiv q div q" by (simp add: algebra_simps dvd_div_mult[symmetric]) also have "... = (q * pderiv p - p * pderiv q) div q" by (rule div_diff, simp_all) finally have A: "pderiv (p div q) * q div q = (q * pderiv p - p * pderiv q) div q div q" by (simp add: algebra_simps) thus "pderiv (p div q) = (q * pderiv p - p * pderiv q) div (q * q)" by (simp add: algebra_simps poly_div_mult_right) from assms obtain r where "p = q * r" unfolding dvd_def by blast hence "q * pderiv p - p * pderiv q = (q * q) * pderiv r" by (simp add: algebra_simps pderiv_mult) thus "q*q dvd (q * pderiv p - p * pderiv q)" by simp qed subsubsection {* Divisibility of polynomials *} text {* Two polynomials that are coprime have no common roots. *} lemma coprime_imp_no_common_roots: assumes "coprime p q" shows "\<And>x. \<not>(poly p x = 0 \<and> poly q x = 0)" proof(clarify) fix x assume "poly p x = 0" "poly q x = 0" hence "[:-x,1:] dvd p" "[:-x,1:] dvd q" by (simp_all add: poly_eq_0_iff_dvd) hence "[:-x,1:] dvd gcd p q" by simp hence "poly (gcd p q) x = 0" by (simp add: poly_eq_0_iff_dvd) moreover from assms have "poly (gcd p q) x = 1" by simp ultimately show False by simp qed text {* Dividing two polynomials by their gcd makes them coprime. *} lemma div_gcd_coprime_poly: assumes "(p :: ('a::field) poly) \<noteq> 0 \<or> q \<noteq> 0" defines [simp]: "d \<equiv> gcd p q" shows "coprime (p div d) (q div d)" proof- let ?d' = "gcd (p div d) (q div d)" from assms have [simp]: "d \<noteq> 0" by simp { fix r assume "r dvd (p div d)" "r dvd (q div d)" then obtain s t where "p div d = r * s" "q div d = r * t" unfolding dvd_def by auto hence "d * (p div d) = d * (r * s)" "d * (q div d) = d * (r * t)" by simp_all hence A: "p = s * (r * d)" "q = t * (r * d)" by (auto simp add: algebra_simps dvd_mult_div_cancel) have "r * d dvd p" "r * d dvd q" by (subst A, rule dvd_triv_right)+ hence "d * r dvd d * 1" by (simp add: algebra_simps) hence "r dvd 1" using `d \<noteq> 0` by (subst (asm) dvd_mult_cancel_left, auto) } hence A: "?d' dvd 1" by simp from assms(1) have "p div d \<noteq> 0 \<or> q div d \<noteq> 0" by (auto simp: dvd_div_eq_mult) hence B: "coeff ?d' (degree ?d') = coeff 1 (degree 1)" using poly_gcd_monic[of "p div d" "q div d"] by simp from poly_dvd_antisym[OF B A one_dvd] show ?thesis . qed lemma poly_div: assumes "poly q x \<noteq> 0" and "q dvd p" shows "poly (p div q) x = poly p x / poly q x" proof- from assms have [simp]: "q \<noteq> 0" by force have "poly q x * poly (p div q) x = poly (q * (p div q)) x" by simp also have "q * (p div q) = p" using assms by (simp add: div_mult_swap) finally show "poly (p div q) x = poly p x / poly q x" using assms by (simp add: field_simps) qed text {* A function that gives witnesses for Bezout's lemma for polynomials. *} function bezw_poly where "bezw_poly (p::('a::field) poly) q = (if q = 0 then ([:inverse (coeff p (degree p)):], 0) else (case bezw_poly q (p mod q) of (r,s) \<Rightarrow> (s, r - s * (p div q))))" by (pat_completeness, simp_all) termination by (relation "measure (\<lambda>(x, y). if y = 0 then 0 else Suc (degree y))") (auto dest: degree_mod_less) declare bezw_poly.simps[simp del] text {* Bezout's lemma for polynomials. *} lemma bezout_poly: "gcd p q = fst (bezw_poly p q) * p + snd (bezw_poly p q) * q" proof (induction p q rule: gcd_poly.induct) case (goal1 p) show ?case by (subst bezw_poly.simps, simp add: gcd_poly.simps(1)) next case (goal2 q p) let ?b = "bezw_poly q (p mod q)" let ?b' = "bezw_poly p q" from goal2 have b'_b: "fst ?b' = snd ?b" "snd ?b' = fst ?b - snd ?b * (p div q)" by (subst bezw_poly.simps, simp split: prod.split)+ hence "fst ?b' * p + snd ?b' * q = snd ?b * p + (fst ?b - snd ?b * (p div q)) * q" by simp also have "... = fst ?b * q + snd ?b * (p - p div q * q)" by (simp add: algebra_simps) also have "p - p div q * q = p mod q" using mod_div_equality[of p q] by (simp add: algebra_simps) also have "fst ?b * q + snd ?b * (p mod q) = gcd q (p mod q)" using goal2 by simp also have "... = gcd p q" using goal2 by (subst gcd_poly.simps(2)[of q p], simp_all) finally show ?case .. qed lemma bezout_poly': "\<exists>r s. gcd (p::('a::field) poly) q = r*p+s*q" using bezout_poly by blast (* TODO: make this less ugly *) lemma poly_div_gcd_squarefree_aux: assumes "pderiv (p::('a::real_normed_field) poly) \<noteq> 0" defines "d \<equiv> gcd p (pderiv p)" shows "coprime (p div d) (pderiv (p div d))" and "\<And>x. poly (p div d) x = 0 \<longleftrightarrow> poly p x = 0" proof- from bezout_poly' obtain r s where rs: "d = r * p + s * pderiv p" unfolding d_def by blast def t \<equiv> "p div d" def [simp]: p' \<equiv> "pderiv p" def [simp]: d' \<equiv> "pderiv d" def u \<equiv> "p' div d" have A: "p = t * d" and B: "p' = u * d" by (simp_all add: t_def u_def dvd_mult_div_cancel d_def algebra_simps) from poly_squarefree_decomp[OF assms(1) A B[unfolded p'_def] rs] show "\<And>x. poly (p div d) x = 0 \<longleftrightarrow> poly p x = 0" by (auto simp: t_def) from rs have C: "s*t*d' = d * (1 - r*t - s*pderiv t)" by (simp add: A B algebra_simps pderiv_mult) from assms have [simp]: "p \<noteq> 0" "d \<noteq> 0" "t \<noteq> 0" by (force, force, subst (asm) A, force) have "\<And>x. \<lbrakk>x dvd t; x dvd (pderiv t)\<rbrakk> \<Longrightarrow> x dvd 1" proof- fix x assume "x dvd t" "x dvd (pderiv t)" then obtain v w where vw: "t = x*v" "pderiv t = x*w" unfolding dvd_def by blast def [simp]: x' \<equiv> "pderiv x" and [simp]: v' \<equiv> "pderiv v" from vw have "x*v' + v*x' = x*w" by (simp add: pderiv_mult) hence "v*x' = x*(w - v')" by (simp add: algebra_simps) hence "x dvd v*pderiv x" by simp then obtain y where y: "v*x' = x*y" unfolding dvd_def by force from `t \<noteq> 0` and vw have "x \<noteq> 0" by simp have x_pow_n_dvd_d: "\<And>n. x^n dvd d" proof- fix n show "x ^ n dvd d" proof (induction n, simp, rename_tac n, case_tac n) fix n assume "n = (0::nat)" from vw and C have "d = x*(d*r*v + d*s*w + s*v*d')" by (simp add: algebra_simps) with `n = 0` show "x^Suc n dvd d" by (force intro: dvdI) next fix n n' assume IH: "x^n dvd d" and "n = Suc n'" hence [simp]: "Suc n' = n" "x * x^n' = x^n" by simp_all def c \<equiv> "[:of_nat n:] :: 'a poly" from pderiv_power_Suc[of x n'] have [simp]: "pderiv (x^n) = c*x^n' * x'" unfolding c_def by (simp add: real_eq_of_nat) from IH obtain z where d: "d = x^n * z" unfolding dvd_def by blast def [simp]: z' \<equiv> "pderiv z" from d `d \<noteq> 0` have "x^n \<noteq> 0" "z \<noteq> 0" by force+ from C d have "x^n*z = z*r*v*x^Suc n + z*s*c*x^n*(v*x') + s*v*z'*x^Suc n + s*z*(v*x')*x^n + s*z*v'*x^Suc n" by (simp add: algebra_simps vw pderiv_mult) also have "... = x^n*x * (z*r*v + z*s*c*y + s*v*z' + s*z*y + s*z*v')" by (simp only: y, simp add: algebra_simps) finally have "z = x*(z*r*v+z*s*c*y+s*v*z'+s*z*y+s*z*v')" using `x^n \<noteq> 0` by force hence "x dvd z" by (metis dvd_triv_left) with d show "x^Suc n dvd d" by simp qed qed have "degree x = 0" proof (cases "degree x", simp) case (Suc n) hence "x \<noteq> 0" by auto with Suc have "degree (x ^ (Suc (degree d))) > degree d" by (subst degree_power_eq, simp_all) moreover from x_pow_n_dvd_d[of "Suc (degree d)"] and `d \<noteq> 0` have "degree (x^Suc (degree d)) \<le> degree d" by (simp add: dvd_imp_degree_le) ultimately show ?thesis by simp qed then obtain c where [simp]: "x = [:c:]" by (cases x, simp split: split_if_asm) moreover from `x \<noteq> 0` have "c \<noteq> 0" by simp ultimately show "x dvd 1" using dvdI[of 1 x "[:inverse c:]"] by (simp add: one_poly_def) qed thus "coprime t (pderiv t)" by (force intro: poly_gcd_unique[of 1 t "pderiv t"]) qed text {* Dividing a polynomial by its gcd with its derivative yields a squarefree polynomial with the same roots. *} lemma poly_div_gcd_squarefree: assumes "(p :: ('a::real_normed_field) poly) \<noteq> 0" defines "d \<equiv> gcd p (pderiv p)" shows "coprime (p div d) (pderiv (p div d))" (is ?A) and "\<And>x. poly (p div d) x = 0 \<longleftrightarrow> poly p x = 0" (is "\<And>x. ?B x") proof- have "?A \<and> (\<forall>x. ?B x)" proof (cases "pderiv p = 0") case False from poly_div_gcd_squarefree_aux[OF this] show ?thesis unfolding d_def by auto next case True then obtain c where [simp]: "p = [:c:]" using pderiv_iszero by blast from assms(1) have "c \<noteq> 0" by simp from True have "d = smult (inverse c) p" by (simp add: d_def gcd_poly.simps(1)) hence "p div d = [:c:]" using `c \<noteq> 0` by (simp add: div_smult_right assms(1) one_poly_def[symmetric]) thus ?thesis using `c \<noteq> 0` by (simp add: gcd_poly.simps(1) one_poly_def) qed thus ?A and "\<And>x. ?B x" by simp_all qed subsubsection {* Sign changes of a polynomial *} text {* If a polynomial has different signs at two points, it has a root inbetween. *} lemma poly_different_sign_imp_root: assumes "a < b" and "sgn (poly p a) \<noteq> sgn (poly p (b::real))" shows "\<exists>x. a \<le> x \<and> x \<le> b \<and> poly p x = 0" proof (cases "poly p a = 0 \<or> poly p b = 0") case True thus ?thesis using assms(1) by (elim disjE, rule_tac exI[of _ a], simp, rule_tac exI[of _ b], simp) next case False hence [simp]: "poly p a \<noteq> 0" "poly p b \<noteq> 0" by simp_all show ?thesis proof (cases "poly p a < 0") case True hence "sgn (poly p a) = -1" by simp with assms True have "poly p b > 0" by (auto simp: sgn_real_def split: split_if_asm) from poly_IVT_pos[OF `a < b` True this] guess x .. thus ?thesis by (intro exI[of _ x], simp) next case False hence "poly p a > 0" by (simp add: not_less less_eq_real_def) hence "sgn (poly p a) = 1" by simp with assms False have "poly p b < 0" by (auto simp: sgn_real_def not_less less_eq_real_def split: split_if_asm) from poly_IVT_neg[OF `a < b` `poly p a > 0` this] guess x .. thus ?thesis by (intro exI[of _ x], simp) qed qed lemma poly_different_sign_imp_root': assumes "sgn (poly p a) \<noteq> sgn (poly p (b::real))" shows "\<exists>x. poly p x = 0" using assms by (cases "a < b", auto dest!: poly_different_sign_imp_root simp: less_eq_real_def not_less) lemma no_roots_inbetween_imp_same_sign: assumes "a < b" "\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> poly p x \<noteq> (0::real)" shows "sgn (poly p a) = sgn (poly p b)" using poly_different_sign_imp_root assms by auto lemma no_roots_inbetween_imp_same_sign': assumes "a \<le> b" "\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> poly p x \<noteq> (0::real)" shows "sgn (poly p a) = sgn (poly p b)" using assms by (cases "a = b") (auto intro!: no_roots_inbetween_imp_same_sign) subsubsection {* Limits of polynomials *} lemma poly_neighbourhood_without_roots: assumes "(p :: real poly) \<noteq> 0" shows "eventually (\<lambda>x. poly p x \<noteq> 0) (at x\<^sub>0)" proof- { fix \<epsilon> :: real assume "\<epsilon> > 0" have fin: "finite {x. \<bar>x-x\<^sub>0\<bar> < \<epsilon> \<and> x \<noteq> x\<^sub>0 \<and> poly p x = 0}" using poly_roots_finite[OF assms] by simp with `\<epsilon> > 0`have "\<exists>\<delta>>0. \<delta>\<le>\<epsilon> \<and> (\<forall>x. \<bar>x-x\<^sub>0\<bar> < \<delta> \<and> x \<noteq> x\<^sub>0 \<longrightarrow> poly p x \<noteq> 0)" proof (induction "card {x. \<bar>x-x\<^sub>0\<bar> < \<epsilon> \<and> x \<noteq> x\<^sub>0 \<and> poly p x = 0}" arbitrary: \<epsilon> rule: less_induct) case (less \<epsilon>) let ?A = "{x. \<bar>x - x\<^sub>0\<bar> < \<epsilon> \<and> x \<noteq> x\<^sub>0 \<and> poly p x = 0}" show ?case proof (cases "card ?A") case 0 hence "?A = {}" using less by auto thus ?thesis using less(2) by (rule_tac exI[of _ \<epsilon>], auto) next case (Suc _) with less(3) have "{x. \<bar>x - x\<^sub>0\<bar> < \<epsilon> \<and> x \<noteq> x\<^sub>0 \<and> poly p x = 0} \<noteq> {}" by force then obtain x where x_props: "\<bar>x - x\<^sub>0\<bar> < \<epsilon>" "x \<noteq> x\<^sub>0" "poly p x = 0" by blast def \<epsilon>' \<equiv> "\<bar>x - x\<^sub>0\<bar> / 2" have "\<epsilon>' > 0" "\<epsilon>' < \<epsilon>" unfolding \<epsilon>'_def using x_props by simp_all from x_props(1,2) and `\<epsilon> > 0` have "x \<notin> {x'. \<bar>x' - x\<^sub>0\<bar> < \<epsilon>' \<and> x' \<noteq> x\<^sub>0 \<and> poly p x' = 0}" (is "_ \<notin> ?B") by (auto simp: \<epsilon>'_def) moreover from x_props have "x \<in> {x. \<bar>x - x\<^sub>0\<bar> < \<epsilon> \<and> x \<noteq> x\<^sub>0 \<and> poly p x = 0}" by blast ultimately have "?B \<subset> ?A" by auto hence "card ?B < card ?A" "finite ?B" by (rule psubset_card_mono[OF less(3)], blast intro: finite_subset[OF _ less(3)]) from less(1)[OF this(1) `\<epsilon>' > 0` this(2)] show ?thesis using `\<epsilon>' < \<epsilon>` by force qed qed } from this[of "1"] show ?thesis by (auto simp: eventually_at dist_real_def) qed lemma poly_neighbourhood_same_sign: assumes "poly p (x\<^sub>0 :: real) \<noteq> 0" shows "eventually (\<lambda>x. sgn (poly p x) = sgn (poly p x\<^sub>0)) (at x\<^sub>0)" proof (rule eventually_mono) have cont: "isCont (\<lambda>x. sgn (poly p x)) x\<^sub>0" by (rule isCont_sgn, rule poly_isCont, rule assms) thus "eventually (\<lambda>x. \<bar>sgn (poly p x) - sgn (poly p x\<^sub>0)\<bar> < 1) (at x\<^sub>0)" by (auto simp: isCont_def tendsto_iff dist_real_def) qed (auto simp add: sgn_real_def) lemma poly_lhopital: assumes "poly p (x::real) = 0" "poly q x = 0" "q \<noteq> 0" assumes "(\<lambda>x. poly (pderiv p) x / poly (pderiv q) x) -- x --> y" shows "(\<lambda>x. poly p x / poly q x) -- x --> y" using assms proof (rule_tac lhopital) have "isCont (poly p) x" "isCont (poly q) x" by simp_all with assms(1,2) show "poly p -- x --> 0" "poly q -- x --> 0" by (simp_all add: isCont_def) from `q \<noteq> 0` and `poly q x = 0` have "pderiv q \<noteq> 0" by (auto dest: pderiv_iszero) from poly_neighbourhood_without_roots[OF this] show "eventually (\<lambda>x. poly (pderiv q) x \<noteq> 0) (at x)" . qed (auto intro: poly_DERIV poly_neighbourhood_without_roots) lemma poly_roots_bounds: assumes "p \<noteq> 0" obtains l u where "l \<le> (u :: real)" and "poly p l \<noteq> 0" and "poly p u \<noteq> 0" and "{x. x > l \<and> x \<le> u \<and> poly p x = 0 } = {x. poly p x = 0}" and "\<And>x. x \<le> l \<Longrightarrow> sgn (poly p x) = sgn (poly p l)" and "\<And>x. x \<ge> u \<Longrightarrow> sgn (poly p x) = sgn (poly p u)" proof from assms have "finite {x. poly p x = 0}" (is "finite ?roots") using poly_roots_finite by fast let ?roots' = "insert 0 ?roots" def l \<equiv> "Min ?roots' - 1" def u \<equiv> "Max ?roots' + 1" from `finite ?roots` have A: "finite ?roots'" by auto from Min_le[OF this, of 0] and Max_ge[OF this, of 0] show "l \<le> u" by (simp add: l_def u_def) from Min_le[OF A] have l_props: "\<And>x. x\<le>l \<Longrightarrow> poly p x \<noteq> 0" by (fastforce simp: l_def) from Max_ge[OF A] have u_props: "\<And>x. x\<ge>u \<Longrightarrow> poly p x \<noteq> 0" by (fastforce simp: u_def) from l_props u_props show [simp]: "poly p l \<noteq> 0" "poly p u \<noteq> 0" by auto from l_props have "\<And>x. poly p x = 0 \<Longrightarrow> x > l" by (metis not_le) moreover from u_props have "\<And>x. poly p x = 0 \<Longrightarrow> x \<le> u" by (metis linear) ultimately show "{x. x > l \<and> x \<le> u \<and> poly p x = 0} = ?roots" by auto { fix x assume A: "x < l" "sgn (poly p x) \<noteq> sgn (poly p l)" with poly_IVT_pos[OF A(1), of p] poly_IVT_neg[OF A(1), of p] A(2) have False by (auto split: split_if_asm simp: sgn_real_def l_props not_less less_eq_real_def) } thus "\<And>x. x \<le> l \<Longrightarrow> sgn (poly p x) = sgn (poly p l)" by (case_tac "x = l", auto simp: less_eq_real_def) { fix x assume A: "x > u" "sgn (poly p x) \<noteq> sgn (poly p u)" with u_props poly_IVT_neg[OF A(1), of p] poly_IVT_pos[OF A(1), of p] A(2) have False by (auto split: split_if_asm simp: sgn_real_def l_props not_less less_eq_real_def) } thus "\<And>x. x \<ge> u \<Longrightarrow> sgn (poly p x) = sgn (poly p u)" by (case_tac "x = u", auto simp: less_eq_real_def) qed definition poly_inf :: "('a::real_normed_vector) poly \<Rightarrow> 'a" where "poly_inf p \<equiv> sgn (coeff p (degree p))" definition poly_neg_inf :: "('a::real_normed_vector) poly \<Rightarrow> 'a" where "poly_neg_inf p \<equiv> if even (degree p) then sgn (coeff p (degree p)) else -sgn (coeff p (degree p))" lemma poly_inf_0_iff[simp]: "poly_inf p = 0 \<longleftrightarrow> p = 0" "poly_neg_inf p = 0 \<longleftrightarrow> p = 0" by (auto simp: poly_inf_def poly_neg_inf_def sgn_zero_iff) lemma poly_inf_mult[simp]: fixes p :: "('a::real_normed_field) poly" shows "poly_inf (p*q) = poly_inf p * poly_inf q" "poly_neg_inf (p*q) = poly_neg_inf p * poly_neg_inf q" unfolding poly_inf_def poly_neg_inf_def by ((cases "p = 0 \<or> q = 0",auto simp: sgn_zero_iff degree_mult_eq[of p q] coeff_mult_degree_sum sgn_mult)[])+ lemma poly_neq_0_at_infinity: assumes "(p :: real poly) \<noteq> 0" shows "eventually (\<lambda>x. poly p x \<noteq> 0) at_infinity" proof- from poly_roots_bounds[OF assms] guess l u . note lu_props = this def b \<equiv> "max (-l) u" show ?thesis proof (subst eventually_at_infinity, rule exI[of _ b], clarsimp) fix x assume A: "\<bar>x\<bar> \<ge> b" and B: "poly p x = 0" show False proof (cases "x \<ge> 0") case True with A have "x \<ge> u" unfolding b_def by simp with lu_props(3, 6) show False by (metis sgn_zero_iff B) next case False with A have "x \<le> l" unfolding b_def by simp with lu_props(2, 5) show False by (metis sgn_zero_iff B) qed qed qed lemma poly_limit_aux: fixes p :: "real poly" defines "n \<equiv> degree p" shows "((\<lambda>x. poly p x / x ^ n) ---> coeff p n) at_infinity" proof (subst filterlim_cong, rule refl, rule refl) show "eventually (\<lambda>x. poly p x / x^n = (\<Sum>i\<le>n. coeff p i / x^(n-i))) at_infinity" proof (rule eventually_mono, clarify) show "eventually (\<lambda>x::real. x \<noteq> 0) at_infinity" by (simp add: eventually_at_infinity, rule exI[of _ 1], auto) fix x :: real assume [simp]: "x \<noteq> 0" show "poly p x / x ^ n = (\<Sum>i\<le>n. coeff p i / x ^ (n - i))" by (simp add: n_def setsum_divide_distrib power_diff poly_altdef) qed let ?a = "\<lambda>i. if i = n then coeff p n else 0" have "\<forall>i\<in>{..n}. ((\<lambda>x. coeff p i / x ^ (n - i)) ---> ?a i) at_infinity" proof fix i assume "i \<in> {..n}" hence "i \<le> n" by simp show "((\<lambda>x. coeff p i / x ^ (n - i)) ---> ?a i) at_infinity" proof (cases "i = n") case True thus ?thesis by (intro tendstoI, subst eventually_at_infinity, intro exI[of _ 1], simp add: dist_real_def) next case False hence "n - i > 0" using `i \<le> n` by simp from tendsto_inverse_0 and divide_real_def[of 1] have "((\<lambda>x. 1 / x :: real) ---> 0) at_infinity" by simp from tendsto_power[OF this, of "n - i"] have "((\<lambda>x::real. 1 / x ^ (n - i)) ---> 0) at_infinity" using `n - i > 0` by (simp add: power_0_left power_one_over) from tendsto_mult_right_zero[OF this, of "coeff p i"] have "((\<lambda>x. coeff p i / x ^ (n - i)) ---> 0) at_infinity" by (simp add: field_simps) thus ?thesis using False by simp qed qed hence "((\<lambda>x. \<Sum>i\<le>n. coeff p i / x^(n-i)) ---> (\<Sum>i\<le>n. ?a i)) at_infinity" by (force intro: tendsto_setsum) also have "(\<Sum>i\<le>n. ?a i) = coeff p n" by (subst setsum.delta, simp_all) finally show "((\<lambda>x. \<Sum>i\<le>n. coeff p i / x^(n-i)) ---> coeff p n) at_infinity" . qed lemma poly_at_top_at_top: fixes p :: "real poly" assumes "degree p \<ge> 1" "coeff p (degree p) > 0" shows "LIM x at_top. poly p x :> at_top" proof- let ?n = "degree p" def f \<equiv> "\<lambda>x::real. poly p x / x^?n" and g \<equiv> "\<lambda>x::real. x ^ ?n" from poly_limit_aux have "(f ---> coeff p (degree p)) at_top" using tendsto_mono at_top_le_at_infinity unfolding f_def by blast moreover from assms have "LIM x at_top. g x :> at_top" by (auto simp add: g_def intro!: filterlim_pow_at_top filterlim_ident) ultimately have "LIM x at_top. f x * g x :> at_top" using filterlim_tendsto_pos_mult_at_top assms by simp also have "eventually (\<lambda>x. f x * g x = poly p x) at_top" unfolding f_def g_def by (subst eventually_at_top_linorder, rule exI[of _ 1], simp add: poly_altdef field_simps setsum_right_distrib power_diff) note filterlim_cong[OF refl refl this] finally show ?thesis . qed lemma poly_at_bot_at_top: fixes p :: "real poly" assumes "degree p \<ge> 1" "coeff p (degree p) < 0" shows "LIM x at_top. poly p x :> at_bot" proof- from poly_at_top_at_top[of "-p"] and assms have "LIM x at_top. -poly p x :> at_top" by simp thus ?thesis by (simp add: filterlim_uminus_at_bot) qed lemma poly_lim_inf: "eventually (\<lambda>x::real. sgn (poly p x) = poly_inf p) at_top" proof (cases "degree p \<ge> 1") case False hence "degree p = 0" by simp then obtain c where "p = [:c:]" by (cases p, auto split: split_if_asm) thus ?thesis by (simp add: eventually_at_top_linorder poly_inf_def) next case True note deg = this let ?lc = "coeff p (degree p)" from True have "?lc \<noteq> 0" by force show ?thesis proof (cases "?lc > 0") case True from poly_at_top_at_top[OF deg this] obtain x\<^sub>0 where "\<And>x. x \<ge> x\<^sub>0 \<Longrightarrow> poly p x \<ge> 1" by (fastforce simp: filterlim_at_top eventually_at_top_linorder less_eq_real_def) hence "\<And>x. x \<ge> x\<^sub>0 \<Longrightarrow> sgn (poly p x) = 1" by force thus ?thesis by (simp only: eventually_at_top_linorder poly_inf_def, intro exI[of _ x\<^sub>0], simp add: True) next case False hence "?lc < 0" using `?lc \<noteq> 0` by linarith from poly_at_bot_at_top[OF deg this] obtain x\<^sub>0 where "\<And>x. x \<ge> x\<^sub>0 \<Longrightarrow> poly p x \<le> -1" by (fastforce simp: filterlim_at_bot eventually_at_top_linorder less_eq_real_def) hence "\<And>x. x \<ge> x\<^sub>0 \<Longrightarrow> sgn (poly p x) = -1" by force thus ?thesis by (simp only: eventually_at_top_linorder poly_inf_def, intro exI[of _ x\<^sub>0], simp add: `?lc < 0`) qed qed lemma poly_at_top_or_bot_at_bot: fixes p :: "real poly" assumes "degree p \<ge> 1" "coeff p (degree p) > 0" shows "LIM x at_bot. poly p x :> (if even (degree p) then at_top else at_bot)" proof- let ?n = "degree p" def f \<equiv> "\<lambda>x::real. poly p x / x ^ ?n" and g \<equiv> "\<lambda>x::real. x ^ ?n" from poly_limit_aux have "(f ---> coeff p (degree p)) at_bot" using tendsto_mono at_bot_le_at_infinity by (force simp: f_def) moreover from assms have "LIM x at_bot. g x :> (if even (degree p) then at_top else at_bot)" by (auto simp add: g_def split: split_if_asm intro: filterlim_pow_at_bot_even filterlim_pow_at_bot_odd filterlim_ident) ultimately have "LIM x at_bot. f x * g x :> (if even ?n then at_top else at_bot)" by (auto simp: assms intro: filterlim_tendsto_pos_mult_at_top filterlim_tendsto_pos_mult_at_bot) also have "eventually (\<lambda>x. f x * g x = poly p x) at_bot" unfolding f_def g_def by (subst eventually_at_bot_linorder, rule exI[of _ "-1"], simp add: poly_altdef field_simps setsum_right_distrib power_diff) note filterlim_cong[OF refl refl this] finally show ?thesis . qed lemma poly_at_bot_or_top_at_bot: fixes p :: "real poly" assumes "degree p \<ge> 1" "coeff p (degree p) < 0" shows "LIM x at_bot. poly p x :> (if even (degree p) then at_bot else at_top)" proof- from poly_at_top_or_bot_at_bot[of "-p"] and assms have "LIM x at_bot. -poly p x :> (if even (degree p) then at_top else at_bot)" by simp thus ?thesis by (auto simp: filterlim_uminus_at_bot) qed lemma poly_lim_neg_inf: "eventually (\<lambda>x::real. sgn (poly p x) = poly_neg_inf p) at_bot" proof (cases "degree p \<ge> 1") case False hence "degree p = 0" by simp then obtain c where "p = [:c:]" by (cases p, auto split: split_if_asm) thus ?thesis by (simp add: eventually_at_bot_linorder poly_neg_inf_def) next case True note deg = this let ?lc = "coeff p (degree p)" from True have "?lc \<noteq> 0" by force show ?thesis proof (cases "?lc > 0") case True note lc_pos = this show ?thesis proof (cases "even (degree p)") case True from poly_at_top_or_bot_at_bot[OF deg lc_pos] and True obtain x\<^sub>0 where "\<And>x. x \<le> x\<^sub>0 \<Longrightarrow> poly p x \<ge> 1" by (fastforce simp add: filterlim_at_top filterlim_at_bot eventually_at_bot_linorder less_eq_real_def) hence "\<And>x. x \<le> x\<^sub>0 \<Longrightarrow> sgn (poly p x) = 1" by force thus ?thesis by (simp add: True eventually_at_bot_linorder poly_neg_inf_def, intro exI[of _ x\<^sub>0], simp add: lc_pos) next case False from poly_at_top_or_bot_at_bot[OF deg lc_pos] and False obtain x\<^sub>0 where "\<And>x. x \<le> x\<^sub>0 \<Longrightarrow> poly p x \<le> -1" by (fastforce simp add: filterlim_at_bot eventually_at_bot_linorder less_eq_real_def) hence "\<And>x. x \<le> x\<^sub>0 \<Longrightarrow> sgn (poly p x) = -1" by force thus ?thesis by (simp add: False eventually_at_bot_linorder poly_neg_inf_def, intro exI[of _ x\<^sub>0], simp add: lc_pos) qed next case False hence lc_neg: "?lc < 0" using `?lc \<noteq> 0` by linarith show ?thesis proof (cases "even (degree p)") case True with poly_at_bot_or_top_at_bot[OF deg lc_neg] obtain x\<^sub>0 where "\<And>x. x \<le> x\<^sub>0 \<Longrightarrow> poly p x \<le> -1" by (fastforce simp: filterlim_at_bot eventually_at_bot_linorder less_eq_real_def) hence "\<And>x. x \<le> x\<^sub>0 \<Longrightarrow> sgn (poly p x) = -1" by force thus ?thesis by (simp only: True eventually_at_bot_linorder poly_neg_inf_def, intro exI[of _ x\<^sub>0], simp add: lc_neg) next case False with poly_at_bot_or_top_at_bot[OF deg lc_neg] obtain x\<^sub>0 where "\<And>x. x \<le> x\<^sub>0 \<Longrightarrow> poly p x \<ge> 1" by (fastforce simp: filterlim_at_top eventually_at_bot_linorder less_eq_real_def) hence "\<And>x. x \<le> x\<^sub>0 \<Longrightarrow> sgn (poly p x) = 1" by force thus ?thesis by (simp only: False eventually_at_bot_linorder poly_neg_inf_def, intro exI[of _ x\<^sub>0], simp add: lc_neg) qed qed qed subsubsection {* Signs of polynomials for sufficiently large values *} lemma polys_inf_sign_thresholds: assumes "finite (ps :: real poly set)" obtains l u where "l \<le> u" and "\<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> {x. l < x \<and> x \<le> u \<and> poly p x = 0} = {x. poly p x = 0}" and "\<And>p x. \<lbrakk>p \<in> ps; x \<ge> u\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_inf p" and "\<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_neg_inf p" proof- case goal1 have "\<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> ps \<and> x \<ge> u \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> ps \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p)" (is "\<exists>l u. ?P ps l u") proof (induction rule: finite_subset_induct[OF assms(1), where A = UNIV], simp) case goal1 show ?case by (intro exI[of _ 42], simp) next case (goal2 p ps) from goal2(4) obtain l u where lu_props: "?P ps l u" by blast from poly_lim_inf obtain u' where u'_props: "\<forall>x\<ge>u'. sgn (poly p x) = poly_inf p" by (force simp add: eventually_at_top_linorder) from poly_lim_neg_inf obtain l' where l'_props: "\<forall>x\<le>l'. sgn (poly p x) = poly_neg_inf p" by (force simp add: eventually_at_bot_linorder) show ?case by (rule exI[of _ "min l l'"], rule exI[of _ "max u u'"], insert lu_props l'_props u'_props, auto) qed then obtain l u where lu_props: "l \<le> u" "\<And>p x. p \<in> ps \<Longrightarrow> u \<le> x \<Longrightarrow> sgn (poly p x) = poly_inf p" "\<And>p x. p \<in> ps \<Longrightarrow> x \<le> l \<Longrightarrow> sgn (poly p x) = poly_neg_inf p" by blast moreover { fix p x assume A: "p \<in> ps" "p \<noteq> 0" "poly p x = 0" from A have "l < x" "x < u" by (auto simp: not_le[symmetric] dest: lu_props(2,3)) } note A = this have "\<And>p. p \<in> ps \<Longrightarrow> p \<noteq> 0 \<Longrightarrow> {x. l < x \<and> x \<le> u \<and> poly p x = 0} = {x. poly p x = 0}" by (auto dest: A) from goal1[OF lu_props(1) this lu_props(2,3)] show thesis . qed subsubsection {* Positivity of polynomials *} lemma poly_pos: "(\<forall>x::real. poly p x > 0) \<longleftrightarrow> poly_inf p = 1 \<and> (\<forall>x. poly p x \<noteq> 0)" proof (intro iffI conjI) assume A: "\<forall>x::real. poly p x > 0" have "\<And>x. poly p (x::real) > 0 \<Longrightarrow> poly p x \<noteq> 0" by simp with A show "\<forall>x::real. poly p x \<noteq> 0" by simp from poly_lim_inf obtain x where "sgn (poly p x) = poly_inf p" by (auto simp: eventually_at_top_linorder) with A show "poly_inf p = 1" by (simp add: sgn_real_def split: split_if_asm) next assume "poly_inf p = 1 \<and> (\<forall>x. poly p x \<noteq> 0)" hence A: "poly_inf p = 1" and B: "(\<forall>x. poly p x \<noteq> 0)" by simp_all from poly_lim_inf obtain x where C: "sgn (poly p x) = poly_inf p" by (auto simp: eventually_at_top_linorder) show "\<forall>x. poly p x > 0" proof (rule ccontr) assume "\<not>(\<forall>x. poly p x > 0)" then obtain x' where "poly p x' \<le> 0" by (auto simp: not_less) with A and C have "sgn (poly p x') \<noteq> sgn (poly p x)" by (auto simp: sgn_real_def split: split_if_asm) from poly_different_sign_imp_root'[OF this] and B show False by blast qed qed lemma poly_pos_greater: "(\<forall>x::real. x > a \<longrightarrow> poly p x > 0) \<longleftrightarrow> poly_inf p = 1 \<and> (\<forall>x. x > a \<longrightarrow> poly p x \<noteq> 0)" proof (intro iffI conjI) assume A: "\<forall>x::real. x > a \<longrightarrow> poly p x > 0" have "\<And>x. poly p (x::real) > 0 \<Longrightarrow> poly p x \<noteq> 0" by simp with A show "\<forall>x::real. x > a \<longrightarrow> poly p x \<noteq> 0" by auto from poly_lim_inf obtain x\<^sub>0 where "\<forall>x\<ge>x\<^sub>0. sgn (poly p x) = poly_inf p" by (auto simp: eventually_at_top_linorder) hence "poly_inf p = sgn (poly p (max x\<^sub>0 (a + 1)))" by simp also from A have "... = 1" by force finally show "poly_inf p = 1" . next assume "poly_inf p = 1 \<and> (\<forall>x. x > a \<longrightarrow> poly p x \<noteq> 0)" hence A: "poly_inf p = 1" and B: "(\<forall>x. x > a \<longrightarrow> poly p x \<noteq> 0)" by simp_all from poly_lim_inf obtain x\<^sub>0 where C: "\<forall>x\<ge>x\<^sub>0. sgn (poly p x) = poly_inf p" by (auto simp: eventually_at_top_linorder) hence "sgn (poly p (max x\<^sub>0 (a+1))) = poly_inf p" by simp with A have D: "sgn (poly p (max x\<^sub>0 (a+1))) = 1" by simp show "\<forall>x. x > a \<longrightarrow> poly p x > 0" proof (rule ccontr) assume "\<not>(\<forall>x. x > a \<longrightarrow> poly p x > 0)" then obtain x' where "x' > a" "poly p x' \<le> 0" by (auto simp: not_less) with A and D have E: "sgn (poly p x') \<noteq> sgn (poly p (max x\<^sub>0(a+1)))" by (auto simp: sgn_real_def split: split_if_asm) show False apply (cases x' "max x\<^sub>0 (a+1)" rule: linorder_cases) using B E `x' > a` apply (force dest!: poly_different_sign_imp_root[of _ _ p])+ done qed qed lemma poly_pos_geq: "(\<forall>x::real. x \<ge> a \<longrightarrow> poly p x > 0) \<longleftrightarrow> poly_inf p = 1 \<and> (\<forall>x. x \<ge> a \<longrightarrow> poly p x \<noteq> 0)" proof (intro iffI conjI) assume A: "\<forall>x::real. x \<ge> a \<longrightarrow> poly p x > 0" hence "\<forall>x::real. x > a \<longrightarrow> poly p x > 0" by simp also note poly_pos_greater finally have "poly_inf p = 1" "(\<forall>x>a. poly p x \<noteq> 0)" by simp_all moreover from A have "poly p a > 0" by simp ultimately show "poly_inf p = 1" "\<forall>x\<ge>a. poly p x \<noteq> 0" by (auto simp: less_eq_real_def) next assume "poly_inf p = 1 \<and> (\<forall>x. x \<ge> a \<longrightarrow> poly p x \<noteq> 0)" hence A: "poly_inf p = 1" and B: "poly p a \<noteq> 0" and C: "\<forall>x>a. poly p x \<noteq> 0" by simp_all from A and C and poly_pos_greater have "\<forall>x>a. poly p x > 0" by simp moreover with B C poly_IVT_pos[of a "a+1" p] have "poly p a > 0" by force ultimately show "\<forall>x\<ge>a. poly p x > 0" by (auto simp: less_eq_real_def) qed lemma poly_pos_less: "(\<forall>x::real. x < a \<longrightarrow> poly p x > 0) \<longleftrightarrow> poly_neg_inf p = 1 \<and> (\<forall>x. x < a \<longrightarrow> poly p x \<noteq> 0)" proof (intro iffI conjI) assume A: "\<forall>x::real. x < a \<longrightarrow> poly p x > 0" have "\<And>x. poly p (x::real) > 0 \<Longrightarrow> poly p x \<noteq> 0" by simp with A show "\<forall>x::real. x < a \<longrightarrow> poly p x \<noteq> 0" by auto from poly_lim_neg_inf obtain x\<^sub>0 where "\<forall>x\<le>x\<^sub>0. sgn (poly p x) = poly_neg_inf p" by (auto simp: eventually_at_bot_linorder) hence "poly_neg_inf p = sgn (poly p (min x\<^sub>0 (a - 1)))" by simp also from A have "... = 1" by force finally show "poly_neg_inf p = 1" . next assume "poly_neg_inf p = 1 \<and> (\<forall>x. x < a \<longrightarrow> poly p x \<noteq> 0)" hence A: "poly_neg_inf p = 1" and B: "(\<forall>x. x < a \<longrightarrow> poly p x \<noteq> 0)" by simp_all from poly_lim_neg_inf obtain x\<^sub>0 where C: "\<forall>x\<le>x\<^sub>0. sgn (poly p x) = poly_neg_inf p" by (auto simp: eventually_at_bot_linorder) hence "sgn (poly p (min x\<^sub>0 (a - 1))) = poly_neg_inf p" by simp with A have D: "sgn (poly p (min x\<^sub>0 (a - 1))) = 1" by simp show "\<forall>x. x < a \<longrightarrow> poly p x > 0" proof (rule ccontr) assume "\<not>(\<forall>x. x < a \<longrightarrow> poly p x > 0)" then obtain x' where "x' < a" "poly p x' \<le> 0" by (auto simp: not_less) with A and D have E: "sgn (poly p x') \<noteq> sgn (poly p (min x\<^sub>0 (a - 1)))" by (auto simp: sgn_real_def split: split_if_asm) show False apply (cases x' "min x\<^sub>0 (a - 1)" rule: linorder_cases) using B E `x' < a` apply (auto dest!: poly_different_sign_imp_root[of _ _ p])+ done qed qed lemma poly_pos_leq: "(\<forall>x::real. x \<le> a \<longrightarrow> poly p x > 0) \<longleftrightarrow> poly_neg_inf p = 1 \<and> (\<forall>x. x \<le> a \<longrightarrow> poly p x \<noteq> 0)" proof (intro iffI conjI) assume A: "\<forall>x::real. x \<le> a \<longrightarrow> poly p x > 0" hence "\<forall>x::real. x < a \<longrightarrow> poly p x > 0" by simp also note poly_pos_less finally have "poly_neg_inf p = 1" "(\<forall>x<a. poly p x \<noteq> 0)" by simp_all moreover from A have "poly p a > 0" by simp ultimately show "poly_neg_inf p = 1" "\<forall>x\<le>a. poly p x \<noteq> 0" by (auto simp: less_eq_real_def) next assume "poly_neg_inf p = 1 \<and> (\<forall>x. x \<le> a \<longrightarrow> poly p x \<noteq> 0)" hence A: "poly_neg_inf p = 1" and B: "poly p a \<noteq> 0" and C: "\<forall>x<a. poly p x \<noteq> 0" by simp_all from A and C and poly_pos_less have "\<forall>x<a. poly p x > 0" by simp moreover with B C poly_IVT_neg[of "a - 1" a p] have "poly p a > 0" by force ultimately show "\<forall>x\<le>a. poly p x > 0" by (auto simp: less_eq_real_def) qed lemma poly_pos_between_less_less: "(\<forall>x::real. a < x \<and> x < b \<longrightarrow> poly p x > 0) \<longleftrightarrow> (a \<ge> b \<or> poly p ((a+b)/2) > 0) \<and> (\<forall>x. a < x \<and> x < b \<longrightarrow> poly p x \<noteq> 0)" proof (intro iffI conjI) assume A: "\<forall>x. a < x \<and> x < b \<longrightarrow> poly p x > 0" have "\<And>x. poly p (x::real) > 0 \<Longrightarrow> poly p x \<noteq> 0" by simp with A show "\<forall>x::real. a < x \<and> x < b \<longrightarrow> poly p x \<noteq> 0" by auto from A show "a \<ge> b \<or> poly p ((a+b)/2) > 0" by (cases "a < b", auto) next assume "(b \<le> a \<or> 0 < poly p ((a+b)/2)) \<and> (\<forall>x. a<x \<and> x<b \<longrightarrow> poly p x \<noteq> 0)" hence A: "b \<le> a \<or> 0 < poly p ((a+b)/2)" and B: "\<forall>x. a<x \<and> x<b \<longrightarrow> poly p x \<noteq> 0" by simp_all show "\<forall>x. a < x \<and> x < b \<longrightarrow> poly p x > 0" proof (cases "a \<ge> b", simp, clarify, rule_tac ccontr, simp only: not_le not_less) fix x assume "a < b" "a < x" "x < b" "poly p x \<le> 0" with B have "poly p x < 0" by (simp add: less_eq_real_def) moreover from A and `a < b` have "poly p ((a+b)/2) > 0" by simp ultimately have "sgn (poly p x) \<noteq> sgn (poly p ((a+b)/2))" by simp thus False using B apply (cases x "(a+b)/2" rule: linorder_cases) apply (drule poly_different_sign_imp_root[of _ _ p], assumption, insert `a < b` `a < x` `x < b` , force) [] apply simp apply (drule poly_different_sign_imp_root[of _ _ p], simp, insert `a < b` `a < x` `x < b` , force) done qed qed lemma poly_pos_between_less_leq: "(\<forall>x::real. a < x \<and> x \<le> b \<longrightarrow> poly p x > 0) \<longleftrightarrow> (a \<ge> b \<or> poly p b > 0) \<and> (\<forall>x. a < x \<and> x \<le> b \<longrightarrow> poly p x \<noteq> 0)" proof (intro iffI conjI) assume A: "\<forall>x. a < x \<and> x \<le> b \<longrightarrow> poly p x > 0" have "\<And>x. poly p (x::real) > 0 \<Longrightarrow> poly p x \<noteq> 0" by simp with A show "\<forall>x::real. a < x \<and> x \<le> b \<longrightarrow> poly p x \<noteq> 0" by auto from A show "a \<ge> b \<or> poly p b > 0" by (cases "a < b", auto) next assume "(b \<le> a \<or> 0 < poly p b) \<and> (\<forall>x. a<x \<and> x\<le>b \<longrightarrow> poly p x \<noteq> 0)" hence A: "b \<le> a \<or> 0 < poly p b" and B: "\<forall>x. a<x \<and> x\<le>b \<longrightarrow> poly p x \<noteq> 0" by simp_all show "\<forall>x. a < x \<and> x \<le> b \<longrightarrow> poly p x > 0" proof (cases "a \<ge> b", simp, clarify, rule_tac ccontr, simp only: not_le not_less) fix x assume "a < b" "a < x" "x \<le> b" "poly p x \<le> 0" with B have "poly p x < 0" by (simp add: less_eq_real_def) moreover from A and `a < b` have "poly p b > 0" by simp ultimately have "x < b" using `x \<le> b` by (auto simp: less_eq_real_def) from `poly p x < 0` and `poly p b > 0` have "sgn (poly p x) \<noteq> sgn (poly p b)" by simp from poly_different_sign_imp_root[OF `x < b` this] and B and `x > a` show False by auto qed qed lemma poly_pos_between_leq_less: "(\<forall>x::real. a \<le> x \<and> x < b \<longrightarrow> poly p x > 0) \<longleftrightarrow> (a \<ge> b \<or> poly p a > 0) \<and> (\<forall>x. a \<le> x \<and> x < b \<longrightarrow> poly p x \<noteq> 0)" proof (intro iffI conjI) assume A: "\<forall>x. a \<le> x \<and> x < b \<longrightarrow> poly p x > 0" have "\<And>x. poly p (x::real) > 0 \<Longrightarrow> poly p x \<noteq> 0" by simp with A show "\<forall>x::real. a \<le> x \<and> x < b \<longrightarrow> poly p x \<noteq> 0" by auto from A show "a \<ge> b \<or> poly p a > 0" by (cases "a < b", auto) next assume "(b \<le> a \<or> 0 < poly p a) \<and> (\<forall>x. a\<le>x \<and> x<b \<longrightarrow> poly p x \<noteq> 0)" hence A: "b \<le> a \<or> 0 < poly p a" and B: "\<forall>x. a\<le>x \<and> x<b \<longrightarrow> poly p x \<noteq> 0" by simp_all show "\<forall>x. a \<le> x \<and> x < b \<longrightarrow> poly p x > 0" proof (cases "a \<ge> b", simp, clarify, rule_tac ccontr, simp only: not_le not_less) fix x assume "a < b" "a \<le> x" "x < b" "poly p x \<le> 0" with B have "poly p x < 0" by (simp add: less_eq_real_def) moreover from A and `a < b` have "poly p a > 0" by simp ultimately have "x > a" using `x \<ge> a` by (auto simp: less_eq_real_def) from `poly p x < 0` and `poly p a > 0` have "sgn (poly p a) \<noteq> sgn (poly p x)" by simp from poly_different_sign_imp_root[OF `x > a` this] and B and `x < b` show False by auto qed qed lemma poly_pos_between_leq_leq: "(\<forall>x::real. a \<le> x \<and> x \<le> b \<longrightarrow> poly p x > 0) \<longleftrightarrow> (a > b \<or> poly p a > 0) \<and> (\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> poly p x \<noteq> 0)" proof (intro iffI conjI) assume A: "\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> poly p x > 0" have "\<And>x. poly p (x::real) > 0 \<Longrightarrow> poly p x \<noteq> 0" by simp with A show "\<forall>x::real. a \<le> x \<and> x \<le> b \<longrightarrow> poly p x \<noteq> 0" by auto from A show "a > b \<or> poly p a > 0" by (cases "a \<le> b", auto) next assume "(b < a \<or> 0 < poly p a) \<and> (\<forall>x. a\<le>x \<and> x\<le>b \<longrightarrow> poly p x \<noteq> 0)" hence A: "b < a \<or> 0 < poly p a" and B: "\<forall>x. a\<le>x \<and> x\<le>b \<longrightarrow> poly p x \<noteq> 0" by simp_all show "\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> poly p x > 0" proof (cases "a > b", simp, clarify, rule_tac ccontr, simp only: not_le not_less) fix x assume "a \<le> b" "a \<le> x" "x \<le> b" "poly p x \<le> 0" with B have "poly p x < 0" by (simp add: less_eq_real_def) moreover from A and `a \<le> b` have "poly p a > 0" by simp ultimately have "x > a" using `x \<ge> a` by (auto simp: less_eq_real_def) from `poly p x < 0` and `poly p a > 0` have "sgn (poly p a) \<noteq> sgn (poly p x)" by simp from poly_different_sign_imp_root[OF `x > a` this] and B and `x \<le> b` show False by auto qed qed end
REBOL [ System: "Ren-C Language Interpreter and Run-time Environment" Title: "Canonical Words Where Order or Optimization in Lib Lookup Matters" Rights: { Copyright 2012-2021 Ren-C Open Source Contributors Copyright 2012 REBOL Technologies REBOL is a trademark of REBOL Technologies } License: { Licensed under the Apache License, Version 2.0 See: http://www.apache.org/licenses/LICENSE-2.0 } Purpose: { These are words that are used internally by Rebol, which and are canonized with small integer SYM_XXX constants. These constants can be quickly used in switch() statements, and a lookup table is on hand to turn SYM_XXX integers into the corresponding symbol pointer. The reason ordered words are kept in a separate file is that the symbol space overlaps with the names of natives and generics that are put into lib. Due to optimizations, this means words where the relative order matters need to establish their indexes in lib that the natives then must accomodate. Unordered words do not forcibly have slots in the optimized range of lib, so they are in a separate file. } ] ; The order of these don't matter, but getting to TRUE_VALUE and FALSE_VALUE ; quickly is useful. ; true false on off yes no blank blackhole newline space ; The `sys context` and `system object` are different things, which seems a ; bit confusing. Review. ; sys system lib ; Actual underlying words for cells in lone `/` paths and lone `.` tuples, ; allowing binding and execution of operations like division or identity. ; Having these looked up optimized in the fixed lib block is worthwhile. ; -slash-1- -dot-1- ; PARSE - These words must not be reserved above!! The range of consecutive ; index numbers are used by PARSE to detect keywords. ; set ; must be first first (SYM_SET referred to by GET_VAR() in %u-parse.c) let copy ; `copy x rule` deprecated, use `x: across rule` for this intent across collect ; Variant in Red, but Ren-C's acts SET-like, suggested by @rgchris keep some any ; no longer a parse keyword, use WHILE FURTHER further ; https://forum.rebol.info/t/1593 opt not ; turned to _not_ for SYM__NOT_, see TO-C-NAME for why this is weird and ; turned to _and_ for SYM__AND_, see TO-C-NAME for why this is weird ahead ; Ren-C addition (also in Red) remove insert change if ; deprecated: https://forum.rebol.info/t/968/7 fail reject while repeat limit seek ; Ren-C addition here ; Ren-C addition ?? | || accept break ; ^--prep words above return ; removed: https://github.com/metaeducation/ren-c/pull/898 ; v--match words below skip to thru quote ; !!! kept for compatibility, but use THE instead just lit-word! ; !!! simulated datatype constraint (a QUOTED! like 'x) lit-path! ; !!! simulated datatype costraint (a QUOTED! like 'x/y) refinement! ; !!! simulated datatype constraint (a PATH! like `/word`) predicate! ; !!! simulated datatype constraint (a TUPLE! like `.word`) blackhole! ; !!! simulated datatype constraint (the ISSUE! `#`) char! ; !!! simulated datatype constraint (single-element ISSUE!) match ; !!! no longer supported by PARSE3 do into only end ; must be last (SYM_END referred to by GET_VAR() in %u-parse.c) ; It is convenient to be able to say `for-each [_ x y] [1 2 3 ...] [...]` and ; let the blank indicate you are not interested in a value. This might be ; doable with a generalized "anonymous key" system. But for now it is assumed ; that all keys have unique symbols. ; ; To get the feature for today, we use some dummy symbols. They cannot be ; used alongside the actual names `dummy1`, `dummy2`, etc...but rather ; than pick a more esoteric name then `map-each [_ dummy1] ...` is just an ; error. Using simple names makes the frame more legible. ; dummy1 dummy2 dummy3 dummy4 dummy5 dummy6 dummy7 dummy8 dummy9
-- Example, ℤ is an Euclidean Domain. Here all the properties needed -- are already proved in Data.Integer.Properties. However, we will -- prove there is another divmod pair such that the rank estimation -- is more precise, see EucDomain2.agda. {-# OPTIONS --without-K --safe #-} module Integer.EucDomain where -- imports from stdlib. open import Relation.Nullary using (¬_) open import Relation.Binary.PropositionalEquality using (refl ; _≡_) open import Data.Nat using (_<_) open import Data.Integer using (_+_ ; _*_ ; -_ ; ℤ ; 0ℤ ; 1ℤ ; ∣_∣ ; +[1+_] ; -[1+_] ; +_) open import Data.Integer.DivMod renaming (_div_ to _divℤ_; _mod_ to _modℤ_ ; n%d<d to euc-rankℤ; a≡a%n+[a/n]*n to euc-eqℤ) open import Data.Integer.Properties using (+-*-isCommutativeRing ; *-cancelˡ-≡) open import Algebra.Definitions (_≡_ {A = ℤ}) using (AlmostLeftCancellative) -- imports from local. import EuclideanDomain open EuclideanDomain.Structures (_≡_ {A = ℤ}) open EuclideanDomain.Bundles -- You will notice the recurring pattern that I have to split on -- the divisor d, and use ¬ d ≡ 0ℤ to exclude the zero divisor -- case. And addtionally, I have to repeat similary codes -- twice. This is the price of the translation from ¬ a ≡ 0ℤ to -- NonZero a. I don't have a good way to avoid this. This become -- even more awkward when dealing with Gaussian integers since we -- have more constructor there (meaning more cases and more -- repeatitions). -- On the other hand, a translation from NonZero predicate to -- non-equaity ¬ d ≡ 0ℤ is quite easy. We will use this to define -- div and mod with instance predicate argument for 𝔾. -- I could use NonZero predicate in the definition of Euclidean -- Domain, but that will make the definition more complicated. Also -- the file "Algebra.Definition" using the same method as here to -- exclude zero, for example the definition of -- "AlmostLeftCancellative", so we also comply this convention. -- div with irrelevant instance argument replaced by non-equality -- argument. div : ∀ (n d : ℤ) -> ¬ d ≡ 0ℤ -> ℤ div n (+ 0) n0 with n0 refl ... | () div n d@(+[1+ n₁ ]) n0 = n divℤ d div n d@(-[1+_] n₁) n0 = n divℤ d -- mod with irrelevant instance argument replaced by non-equality -- argument. mod : ∀ (n d : ℤ) -> ¬ d ≡ 0ℤ -> ℤ mod n (+ 0) n0 with n0 refl ... | () mod n d@(+[1+ n₁ ]) n0 = + (n modℤ d) mod n d@(-[1+_] n₁) n0 = + (n modℤ d) -- Divident = reminder + quotient * divisor. euc-eq : ∀ (n d : ℤ) (n0 : ¬ d ≡ 0ℤ) -> let r = mod n d n0 in let q = div n d n0 in n ≡ r + q * d euc-eq n (+ 0) n0 with n0 refl ... | () euc-eq n d@(+[1+ n₁ ]) n0 = euc-eqℤ n d euc-eq n d@(-[1+_] n₁) n0 = euc-eqℤ n d -- The rank of the reminder is strictly smaller than the rank of the -- divisor. euc-rank : ∀ (n d : ℤ) (n0 : ¬ d ≡ 0ℤ) -> let r = mod n d n0 in let q = div n d n0 in ∣ r ∣ < ∣ d ∣ euc-rank n (+ 0) n0 with n0 refl ... | () euc-rank n d@(+[1+ n₁ ]) n0 = euc-rankℤ n d euc-rank n d@(-[1+_] n₁) n0 = euc-rankℤ n d -- Multiplication is left cancellative. *-alc-ℤ : AlmostLeftCancellative 0ℤ _*_ *-alc-ℤ {+ 0} j k n0 with n0 refl ... | () *-alc-ℤ {i@(+[1+ n ])} j k n0 = *-cancelˡ-≡ i j k *-alc-ℤ { i@(-[1+ n ])} j k n0 = *-cancelˡ-≡ i j k -- ℤ is an Euclidean Domain. +-*-isEuclideanDomain : IsEuclideanDomain _+_ _*_ -_ 0ℤ 1ℤ +-*-isEuclideanDomain = record { isCommutativeRing = +-*-isCommutativeRing ; *-alc = *-alc-ℤ ; div = div ; mod = mod ; rank = ∣_∣ ; euc-eq = euc-eq ; euc-rank = euc-rank } -- Bundle. +-*-euclideanDomain : EuclideanDomainBundle _ _ +-*-euclideanDomain = record { isEuclideanDomain = +-*-isEuclideanDomain }
{-# OPTIONS --cubical --safe --no-import-sorts #-} module Cubical.Algebra.Algebra.Base where open import Cubical.Foundations.Prelude open import Cubical.Foundations.Equiv open import Cubical.Foundations.Equiv.HalfAdjoint open import Cubical.Foundations.HLevels open import Cubical.Foundations.Isomorphism open import Cubical.Foundations.Function open import Cubical.Foundations.SIP open import Cubical.Data.Sigma open import Cubical.Structures.Axioms open import Cubical.Structures.Auto open import Cubical.Structures.Macro open import Cubical.Algebra.Module renaming (⟨_⟩ to ⟨_⟩m) open import Cubical.Algebra.Ring renaming (⟨_⟩ to ⟨_⟩r) open import Cubical.Algebra.AbGroup hiding (⟨_⟩) open import Cubical.Algebra.Group hiding (⟨_⟩) open import Cubical.Algebra.Monoid hiding (⟨_⟩) open Iso private variable ℓ : Level record IsAlgebra (R : Ring {ℓ}) {A : Type ℓ} (0a 1a : A) (_+_ _·_ : A → A → A) (-_ : A → A) (_⋆_ : ⟨ R ⟩r → A → A) : Type ℓ where constructor isalgebra open Ring R using (1r) renaming (_+_ to _+r_; _·_ to _·r_) field isLeftModule : IsLeftModule R 0a _+_ -_ _⋆_ ·-isMonoid : IsMonoid 1a _·_ dist : (x y z : A) → (x · (y + z) ≡ (x · y) + (x · z)) × ((x + y) · z ≡ (x · z) + (y · z)) ⋆-lassoc : (r : ⟨ R ⟩r) (x y : A) → (r ⋆ x) · y ≡ r ⋆ (x · y) ⋆-rassoc : (r : ⟨ R ⟩r) (x y : A) → r ⋆ (x · y) ≡ x · (r ⋆ y) open IsLeftModule isLeftModule public isRing : IsRing _ _ _ _ _ isRing = isring (IsLeftModule.+-isAbGroup isLeftModule) ·-isMonoid dist open IsRing isRing public hiding (_-_; +-assoc; +-lid; +-linv; +-rid; +-rinv; +-comm) record Algebra (R : Ring {ℓ}) : Type (ℓ-suc ℓ) where constructor algebra field Carrier : Type ℓ 0a : Carrier 1a : Carrier _+_ : Carrier → Carrier → Carrier _·_ : Carrier → Carrier → Carrier -_ : Carrier → Carrier _⋆_ : ⟨ R ⟩r → Carrier → Carrier isAlgebra : IsAlgebra R 0a 1a _+_ _·_ -_ _⋆_ open IsAlgebra isAlgebra public module commonExtractors {R : Ring {ℓ}} where ⟨_⟩ : Algebra R → Type ℓ ⟨_⟩ = Algebra.Carrier Algebra→Module : (A : Algebra R) → LeftModule R Algebra→Module (algebra A _ _ _ _ _ _ (isalgebra isLeftModule _ _ _ _)) = leftmodule A _ _ _ _ isLeftModule Algebra→Ring : (A : Algebra R) → Ring {ℓ} Algebra→Ring A = ring _ _ _ _ _ _ (IsAlgebra.isRing (Algebra.isAlgebra A)) Algebra→AbGroup : (A : Algebra R) → AbGroup {ℓ} Algebra→AbGroup A = LeftModule→AbGroup (Algebra→Module A) Algebra→Monoid : (A : Algebra R) → Monoid {ℓ} Algebra→Monoid A = Ring→Monoid (Algebra→Ring A) isSetAlgebra : (A : Algebra R) → isSet ⟨ A ⟩ isSetAlgebra A = isSetAbGroup (Algebra→AbGroup A) open Ring R using (1r; ·-ldist-+) renaming (_+_ to _+r_; _·_ to _·s_) makeIsAlgebra : {A : Type ℓ} {0a 1a : A} {_+_ _·_ : A → A → A} { -_ : A → A} {_⋆_ : ⟨ R ⟩r → A → A} (isSet-A : isSet A) (+-assoc : (x y z : A) → x + (y + z) ≡ (x + y) + z) (+-rid : (x : A) → x + 0a ≡ x) (+-rinv : (x : A) → x + (- x) ≡ 0a) (+-comm : (x y : A) → x + y ≡ y + x) (·-assoc : (x y z : A) → x · (y · z) ≡ (x · y) · z) (·-rid : (x : A) → x · 1a ≡ x) (·-lid : (x : A) → 1a · x ≡ x) (·-rdist-+ : (x y z : A) → x · (y + z) ≡ (x · y) + (x · z)) (·-ldist-+ : (x y z : A) → (x + y) · z ≡ (x · z) + (y · z)) (⋆-assoc : (r s : ⟨ R ⟩r) (x : A) → (r ·s s) ⋆ x ≡ r ⋆ (s ⋆ x)) (⋆-ldist : (r s : ⟨ R ⟩r) (x : A) → (r +r s) ⋆ x ≡ (r ⋆ x) + (s ⋆ x)) (⋆-rdist : (r : ⟨ R ⟩r) (x y : A) → r ⋆ (x + y) ≡ (r ⋆ x) + (r ⋆ y)) (⋆-lid : (x : A) → 1r ⋆ x ≡ x) (⋆-lassoc : (r : ⟨ R ⟩r) (x y : A) → (r ⋆ x) · y ≡ r ⋆ (x · y)) (⋆-rassoc : (r : ⟨ R ⟩r) (x y : A) → r ⋆ (x · y) ≡ x · (r ⋆ y)) → IsAlgebra R 0a 1a _+_ _·_ -_ _⋆_ makeIsAlgebra isSet-A +-assoc +-rid +-rinv +-comm ·-assoc ·-rid ·-lid ·-rdist-+ ·-ldist-+ ⋆-assoc ⋆-ldist ⋆-rdist ⋆-lid ⋆-lassoc ⋆-rassoc = isalgebra (makeIsLeftModule isSet-A +-assoc +-rid +-rinv +-comm ⋆-assoc ⋆-ldist ⋆-rdist ⋆-lid) (makeIsMonoid isSet-A ·-assoc ·-rid ·-lid) (λ x y z → ·-rdist-+ x y z , ·-ldist-+ x y z) ⋆-lassoc ⋆-rassoc open commonExtractors public record AlgebraEquiv {R : Ring {ℓ}} (A B : Algebra R) : Type ℓ where constructor algebraiso instance _ : Algebra R _ = A _ : Algebra R _ = B open Algebra {{...}} field e : ⟨ A ⟩ ≃ ⟨ B ⟩ isHom+ : (x y : ⟨ A ⟩) → equivFun e (x + y) ≡ equivFun e x + equivFun e y isHom· : (x y : ⟨ A ⟩) → equivFun e (x · y) ≡ equivFun e x · equivFun e y pres1 : equivFun e 1a ≡ 1a comm⋆ : (r : ⟨ R ⟩r) (x : ⟨ A ⟩) → equivFun e (r ⋆ x) ≡ r ⋆ equivFun e x record AlgebraHom {R : Ring {ℓ}} (A B : Algebra R) : Type ℓ where constructor algebrahom private instance _ : Algebra R _ = A _ : Algebra R _ = B open Algebra {{...}} field f : ⟨ A ⟩ → ⟨ B ⟩ isHom+ : (x y : ⟨ A ⟩) → f (x + y) ≡ f x + f y isHom· : (x y : ⟨ A ⟩) → f (x · y) ≡ f x · f y pres1 : f 1a ≡ 1a comm⋆ : (r : ⟨ R ⟩r) (x : ⟨ A ⟩) → f (r ⋆ x) ≡ r ⋆ f x pres0 : f 0a ≡ 0a pres0 = sym (Theory.+-idempotency→0 (Algebra→Ring B) (f 0a) (f 0a ≡⟨ cong f (sym (+-rid _)) ⟩ f (0a + 0a) ≡⟨ isHom+ _ _ ⟩ f 0a + f 0a ∎)) isHom- : (x : ⟨ A ⟩) → f (- x) ≡ - f x isHom- x = Theory.implicitInverse (Algebra→Ring B) (f x) (f (- x)) (f (x) + f (- x) ≡⟨ sym (isHom+ _ _) ⟩ f (x - x) ≡⟨ cong f (+-rinv _) ⟩ f 0a ≡⟨ pres0 ⟩ 0a ∎) _$a_ : {R : Ring {ℓ}} {A B : Algebra R} → AlgebraHom A B → ⟨ A ⟩ → ⟨ B ⟩ f $a x = AlgebraHom.f f x _∘a_ : {R : Ring {ℓ}} {A B C : Algebra R} → AlgebraHom B C → AlgebraHom A B → AlgebraHom A C _∘a_ {ℓ} {R} {A} {B} {C} (algebrahom f isHom+f isHom·f pres1f comm⋆f) (algebrahom g isHom+g isHom·g pres1g comm⋆g) = let open Algebra ⦃...⦄ instance _ : Algebra R _ = A _ : Algebra R _ = B _ : Algebra R _ = C in algebrahom (f ∘ g) (λ x y → f (g (x + y)) ≡⟨ cong f (isHom+g x y) ⟩ f (g x + g y) ≡⟨ isHom+f _ _ ⟩ f (g x) + f (g y) ∎) (λ x y → f (g (x · y)) ≡⟨ cong f (isHom·g x y) ⟩ f (g x · g y) ≡⟨ isHom·f _ _ ⟩ f (g x) · f (g y) ∎) (f (g 1a) ≡⟨ cong f pres1g ⟩ f 1a ≡⟨ pres1f ⟩ 1a ∎) λ r x → f (g (r ⋆ x)) ≡⟨ cong f (comm⋆g _ _) ⟩ f (r ⋆ (g x)) ≡⟨ comm⋆f _ _ ⟩ r ⋆ (f (g x)) ∎ module AlgebraΣTheory (R : Ring {ℓ}) where RawAlgebraStructure = λ (A : Type ℓ) → (A → A → A) × (A → A → A) × A × (⟨ R ⟩r → A → A) RawAlgebraEquivStr = AutoEquivStr RawAlgebraStructure rawAlgebraUnivalentStr : UnivalentStr _ RawAlgebraEquivStr rawAlgebraUnivalentStr = autoUnivalentStr RawAlgebraStructure open Ring R using (1r) renaming (_+_ to _+r_; _·_ to _·r_) open RingΣTheory open LeftModuleΣTheory R open MonoidΣTheory AlgebraAxioms : (A : Type ℓ) (str : RawAlgebraStructure A) → Type ℓ AlgebraAxioms A (_+_ , _·_ , 1a , _⋆_) = LeftModuleAxioms A (_+_ , _⋆_) × (MonoidAxioms A (1a , _·_)) × ((x y z : A) → (x · (y + z) ≡ (x · y) + (x · z)) × ((x + y) · z ≡ (x · z) + (y · z))) × ((r : ⟨ R ⟩r) (x y : A) → (r ⋆ x) · y ≡ r ⋆ (x · y)) × ((r : ⟨ R ⟩r) (x y : A) → r ⋆ (x · y) ≡ x · (r ⋆ y)) AlgebraStructure : Type ℓ → Type ℓ AlgebraStructure = AxiomsStructure RawAlgebraStructure AlgebraAxioms AlgebraΣ : Type (ℓ-suc ℓ) AlgebraΣ = TypeWithStr ℓ AlgebraStructure AlgebraEquivStr : StrEquiv AlgebraStructure ℓ AlgebraEquivStr = AxiomsEquivStr RawAlgebraEquivStr AlgebraAxioms isSetAlgebraΣ : (A : AlgebraΣ) → isSet _ isSetAlgebraΣ (A , _ , (isLeftModule , _ , _) ) = isSetLeftModuleΣ (A , _ , isLeftModule) isPropAlgebraAxioms : (A : Type ℓ) (s : RawAlgebraStructure A) → isProp (AlgebraAxioms A s) isPropAlgebraAxioms A (_+_ , _·_ , 1a , _⋆_) = isPropΣ (isPropLeftModuleAxioms A (_+_ , _⋆_)) (λ isLeftModule → isProp× (isPropMonoidAxioms A (1a , _·_)) (isProp× (isPropΠ3 (λ _ _ _ → isProp× ((isSetLeftModuleΣ (A , _ , isLeftModule)) _ _) ((isSetLeftModuleΣ (A , _ , isLeftModule)) _ _))) (isProp× (isPropΠ3 (λ _ _ _ → (isSetLeftModuleΣ (A , _ , isLeftModule)) _ _)) (isPropΠ3 (λ _ _ _ → (isSetLeftModuleΣ (A , _ , isLeftModule)) _ _))))) Algebra→AlgebraΣ : Algebra R → AlgebraΣ Algebra→AlgebraΣ (algebra A 0a 1a _+_ _·_ -_ _⋆_ (isalgebra isLeftModule isMonoid dist ⋆-lassoc ⋆-rassoc)) = A , (_+_ , _·_ , 1a , _⋆_) , (LeftModule→LeftModuleΣ (leftmodule A _ _ _ _ isLeftModule) .snd .snd) , Monoid→MonoidΣ (monoid A _ _ isMonoid) .snd .snd , dist , ⋆-lassoc , ⋆-rassoc AlgebraΣ→Algebra : AlgebraΣ → Algebra R AlgebraΣ→Algebra (A , (_+_ , _·_ , 1a , _⋆_) , isLeftModule , isMonoid , dist , lassoc , rassoc) = algebra A _ 1a _+_ _·_ _ _⋆_ (isalgebra (LeftModule.isLeftModule (LeftModuleΣ→LeftModule (A , (_ , isLeftModule)))) (Monoid.isMonoid (MonoidΣ→Monoid (A , (_ , isMonoid)))) dist lassoc rassoc) AlgebraIsoAlgebraΣ : Iso (Algebra R) AlgebraΣ AlgebraIsoAlgebraΣ = iso Algebra→AlgebraΣ AlgebraΣ→Algebra (λ _ → refl) helper where -- helper will be refl, if eta-equality is activated for all structure-records open MonoidΣTheory monoid-helper : retract (Monoid→MonoidΣ {ℓ}) MonoidΣ→Monoid monoid-helper = Iso.leftInv MonoidIsoMonoidΣ module-helper : retract (LeftModule→LeftModuleΣ) LeftModuleΣ→LeftModule module-helper = Iso.leftInv LeftModuleIsoLeftModuleΣ open Algebra helper : _ Carrier (helper a i) = Carrier a 0a (helper a i) = 0a a 1a (helper a i) = 1a a _+_ (helper a i) = _+_ a _·_ (helper a i) = _·_ a -_ (helper a i) = -_ a _⋆_ (helper a i) = _⋆_ a IsAlgebra.isLeftModule (isAlgebra (helper a i)) = LeftModule.isLeftModule (module-helper (leftmodule _ _ _ _ _ (isLeftModule a)) i) IsAlgebra.·-isMonoid (isAlgebra (helper a i)) = Monoid.isMonoid (monoid-helper (monoid _ _ _ (·-isMonoid a)) i) IsAlgebra.dist (isAlgebra (helper a i)) = dist a IsAlgebra.⋆-lassoc (isAlgebra (helper a i)) = ⋆-lassoc a IsAlgebra.⋆-rassoc (isAlgebra (helper a i)) = ⋆-rassoc a algebraUnivalentStr : UnivalentStr AlgebraStructure AlgebraEquivStr algebraUnivalentStr = axiomsUnivalentStr _ isPropAlgebraAxioms rawAlgebraUnivalentStr AlgebraΣPath : (M N : AlgebraΣ) → (M ≃[ AlgebraEquivStr ] N) ≃ (M ≡ N) AlgebraΣPath = SIP algebraUnivalentStr AlgebraEquivΣ : (M N : Algebra R) → Type ℓ AlgebraEquivΣ M N = Algebra→AlgebraΣ M ≃[ AlgebraEquivStr ] Algebra→AlgebraΣ N AlgebraEquivΣPath : {M N : Algebra R} → Iso (AlgebraEquiv M N) (AlgebraEquivΣ M N) fun AlgebraEquivΣPath (algebraiso e isHom+ isHom· pres1 comm⋆) = e , isHom+ , (isHom· , (pres1 , comm⋆)) inv AlgebraEquivΣPath (f , isHom+ , isHom· , pres1 , comm⋆) = algebraiso f isHom+ isHom· pres1 comm⋆ rightInv AlgebraEquivΣPath _ = refl leftInv AlgebraEquivΣPath _ = refl AlgebraPath : (M N : Algebra R) → (AlgebraEquiv M N) ≃ (M ≡ N) AlgebraPath M N = AlgebraEquiv M N ≃⟨ isoToEquiv AlgebraEquivΣPath ⟩ AlgebraEquivΣ M N ≃⟨ AlgebraΣPath _ _ ⟩ Algebra→AlgebraΣ M ≡ Algebra→AlgebraΣ N ≃⟨ isoToEquiv (invIso (congIso AlgebraIsoAlgebraΣ)) ⟩ M ≡ N ■ AlgebraPath : {R : Ring {ℓ}} (M N : Algebra R) → (AlgebraEquiv M N) ≃ (M ≡ N) AlgebraPath {ℓ} {R} = AlgebraΣTheory.AlgebraPath R module AlgebraTheory (R : Ring {ℓ}) (A : Algebra R) where open Ring R renaming (_+_ to _+r_) open Algebra A 0-actsNullifying : (x : ⟨ A ⟩) → 0r ⋆ x ≡ 0a 0-actsNullifying x = let idempotent-+ = 0r ⋆ x ≡⟨ cong (λ u → u ⋆ x) (sym (Theory.0-idempotent R)) ⟩ (0r +r 0r) ⋆ x ≡⟨ ⋆-ldist 0r 0r x ⟩ (0r ⋆ x) + (0r ⋆ x) ∎ in sym (Theory.+-idempotency→0 (Algebra→Ring A) (0r ⋆ x) idempotent-+)
#redirect Computer Science Instructional Facility
import argparse import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib.patches import Patch import numpy as np import os from matplotlib.pyplot import rcParams rcParams['font.family'] = 'serif' rcParams['font.serif'] = ['DejaVu Serif'] # dsp = 0, bram = 1, uram = 2 vu11p = [0, 1, 1, 0, 0, 0, 1, 0, 2, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 2, 0, 1, 0, 1, 0, 2, 0, 0, 1, 0, 1, 0, 2, 0, 0, 0, 0, 1, 0, 2, 0, 0, 0, 0, 0, 1, 1, 0] vu37p = [0, 1, 1, 0, 0, 0, 1, 0, 2, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 2, 0, 1, 0, 1, 0, 2, 0, 0, 1, 0, 1, 0, 2, 0, 0, 0, 0, 1, 0, 2, 0, 0, 0, 0, 0, 1, 1, 0] # Set up sizes gap = 40 # define colors dsp_col = '#F9E9A1' bram_col = '#94f0f1' uram_col = '#f2b1d8' dsp_block = '#ebc600' bram_block = '#5AB9EA' uram_block = '#bf4aa8' def readXDC(f): # a dict to put result in it dict = {} with open(f) as fp: line = fp.readline() while line: if not line.startswith('set_property'): line = fp.readline() continue line = line.replace('\t', ' ') site = line.split(' ')[2] cell = line.split('{')[1].split("}")[0] n = int(cell.split('[')[1].split(']')[0], 10) if dict.get(n) is None: dict[n] = [] dict[n].append([site, cell]) else: dict[n].append([site, cell]) line = fp.readline() return dict def drawDSP(ax, site, gap, color, yOffset=10): X = int(site.split('X', 1)[1].split('Y', 1)[0], 10) # base 10 Y = int(site.split('Y', 1)[1], 10) # base 10 count = 0 x = 10 for type in vu11p: # move x if type == 0: # DSP if count == X: break # time to go! x += 10 + gap count += 1 elif type == 1: # BRAM x += 10 + gap elif type == 2: # URAM x += 20 + gap y = Y * 19.2 + 2.1 + yOffset r = patches.Rectangle((x, y), 10, 15, facecolor=color) ax.add_patch(r) x_vertices = [x, x, x+10, x+10] y_vertices = [y, y+15, y, y+15] return x_vertices, y_vertices def drawBRAM(ax, site, gap, color, yOffset=10): X = int(site.split('X', 1)[1].split('Y', 1)[0], 10) # base 10 Y = int(site.split('Y', 1)[1], 10) # base 10 count = 0 x = 10 for type in vu11p: # move x if type == 0: # DSP x += 10 + gap elif type == 1: # BRAM if count == X: break # time to go! x += 10 + gap count += 1 elif type == 2: # URAM x += 20 + gap y = Y * 18.8 + 0.9 + yOffset r = patches.Rectangle((x, y), 10, 17, facecolor=color) ax.add_patch(r) x_vertices = [x, x, x + 10, x + 10] y_vertices = [y, y + 17, y, y + 17] return x_vertices, y_vertices def drawURAM(ax, site, gap, color, yOffset=10): X = int(site.split('X', 1)[1].split('Y', 1)[0], 10) # base 10 Y = int(site.split('Y', 1)[1], 10) # base 10 count = 0 x = 10 for type in vu11p: # move x if type == 0: # DSP x += 10 + gap elif type == 1: # BRAM x += 10 + gap elif type == 2: # URAM if count == X: break # time to go! x += 20 + gap count += 1 y = Y * 28.2 + 1.6 + yOffset r = patches.Rectangle((x, y), 20, 25, facecolor=color) ax.add_patch(r) x_vertices = [x, x, x + 20, x + 20] y_vertices = [y, y + 25, y, y + 25] return x_vertices, y_vertices def calcPolygon(input): length = input.shape[0] columns = {} for i in range(length): x = input[i, 0] y = input[i, 1] if columns.get(x) is None: columns[x] = [] columns[x].append(y) else: columns[x].append(y) up = [] down = [] sorted_keys = list(columns.keys()) list.sort(sorted_keys) for key in sorted_keys: thisColumn = columns.get(key) list.sort(thisColumn) up.append([key, thisColumn[-1]]) down.append([key, thisColumn[0]]) output = [] output += down up.reverse() output += up return output def drawTiles(ax, sites, color, alpha=0.1): vertices = calcPolygon(sites) polygon = patches.Polygon(vertices, True, facecolor=color, edgecolor=color, alpha=alpha) ax.add_patch(polygon) def drawTileHighlight(ax, sites): vertices = calcPolygon(sites) polygon = patches.Polygon(vertices, True, facecolor=(0,0,0,0.1), edgecolor='k', linewidth=2) ax.add_patch(polygon) def drawBackGround(ax, width, height, gap): dsp_color = dsp_col bram_color = bram_col uram_color = uram_col x = 10 # starting point y = 10 # bottom-left y for type in vu11p: r = patches.Rectangle if type == 0: # DSP r = patches.Rectangle((x, y), 10, height, facecolor=dsp_color) x += 10 + gap elif type == 1: # BRAM r = patches.Rectangle((x, y), 10, height, facecolor=bram_color) x += 10 + gap elif type == 2: # URAM r = patches.Rectangle((x, y), 20, height, facecolor=uram_color) x += 20 + gap ax.add_patch(r) def draw_png(filename, saveDir): dict = readXDC(filename) name = filename.split('/')[-1].split('.', 1)[0] if not os.path.exists(saveDir): os.makedirs(saveDir) keys = list(dict.keys()) # keys are integer, which is block index width = 560 + gap * (len(vu11p) - 1) height = 5414.4 if len(keys) > 80 else 1000 fontsize = 80 if len(keys) > 80 else 40 rcParams.update({'font.size': fontsize}) # draw transparent polygons on a new image fig, ax = plt.subplots(figsize=(256,100)) fig.set_size_inches(width / 100, height / 100) ax.set_xlim(0, width + 20) ax.set_ylim(0, height + 20) rect = patches.Rectangle((10, 10), width, height, linewidth=1, facecolor='#f6f6f6') ax.add_patch(rect) drawBackGround(ax, width, height, gap) for j in range(len(keys)): key = keys[j] entries = dict.get(key) sites = np.zeros(shape=(len(entries) * 4, 2)) for pair in entries: site = pair[0] x = 0 y = 0 if site.startswith('DSP'): x, y = drawDSP(ax, site, gap, dsp_block) elif site.startswith('RAMB'): x, y = drawBRAM(ax, site, gap, bram_block) elif site.startswith('URAM'): x, y = drawURAM(ax, site, gap, uram_block) for index in range(4): sites[entries.index(pair) * 4 + index, 0] = x[index] sites[entries.index(pair) * 4 + index, 1] = y[index] drawTiles(ax, sites, '#000000') # add axis legend_elements = [ Patch(facecolor=dsp_block, label='DSP48'), Patch(facecolor=bram_block, label='BRAM'), Patch(facecolor=uram_block, label='URAM') ] # ax.legend(handles=legend_elements, prop={'size':13}) # plt.savefig(saveDir + name + '.png', dpi=50) # plt.close() plt.savefig(saveDir + name + '.pdf') plt.close() print(saveDir + name + '.pdf') return saveDir + name + '.pdf' def draw_frame(ax, filename, iteration, method): dict = readXDC(filename) keys = list(dict.keys()) # keys are integer, which is block index width = 560 + gap * (len(vu11p) - 1) height = 5414.4 if len(keys) > 80 else 1000 # draw transparent polygons on a new image ax.set_xlim(0, width + 20) ax.set_ylim(0, height + 20) rect = patches.Rectangle((10, 10), width, height, linewidth=1, facecolor='#f6f6f6') ax.add_patch(rect) drawBackGround(ax, width, height, gap) for j in range(len(keys)): key = keys[j] entries = dict.get(key) sites = np.zeros(shape=(len(entries) * 4, 2)) for pair in entries: site = pair[0] x = 0 y = 0 if site.startswith('DSP'): x, y = drawDSP(ax, site, gap, dsp_block) elif site.startswith('RAMB'): x, y = drawBRAM(ax, site, gap, bram_block) elif site.startswith('URAM'): x, y = drawURAM(ax, site, gap, uram_block) for index in range(4): sites[entries.index(pair) * 4 + index, 0] = x[index] sites[entries.index(pair) * 4 + index, 1] = y[index] drawTiles(ax, sites, '#000000') ax.set_xlabel("iteration = {}".format(iteration), fontsize=20) ax.set_title(method, fontsize=30) ax.tick_params( axis='both', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom=False, # ticks along the bottom edge are off top=False, # ticks along the top edge are off left=False, right=False, labelleft=False, labelbottom=False # labels along the bottom edge are off) ) return ax if __name__ == "__main__": parser = argparse.ArgumentParser(description='Please input the result xdc file, visualization image output directory') parser.add_argument('filename', type=str, help='the result xdc file to visualize') parser.add_argument('dir', type=str, help='the output directory of visualization file') args = parser.parse_args() filename = args.filename saveDir = args.dir if not os.path.isdir(saveDir): os.makedirs(saveDir) draw_png(filename, saveDir)
(*Authors: Mohammad Abdulaziz*) theory Call_By_Prefixes imports IMP_Minus.Com Big_StepT begin abbreviation add_prefix :: "string \<Rightarrow> vname \<Rightarrow> vname" where "add_prefix p s \<equiv> p @ s" (*type_synonym pcom = "string \<Rightarrow> com"*) fun atomExp_add_prefix where "atomExp_add_prefix p (N a) = N a" | "atomExp_add_prefix p (V v) = V (add_prefix p v)" fun aexp_add_prefix where "aexp_add_prefix p (A a) = A (atomExp_add_prefix p a)" | "aexp_add_prefix p (Plus a b) = Plus (atomExp_add_prefix p a) (atomExp_add_prefix p b)" | "aexp_add_prefix p (Sub a b) = Sub (atomExp_add_prefix p a) (atomExp_add_prefix p b)" | "aexp_add_prefix p (Parity a) = Parity (atomExp_add_prefix p a)" | "aexp_add_prefix p (RightShift a) = RightShift (atomExp_add_prefix p a)" fun com_add_prefix where "com_add_prefix p SKIP = SKIP" |"com_add_prefix p (Assign v aexp) = (Assign (add_prefix p v) (aexp_add_prefix p aexp))" |"com_add_prefix p (Seq c1 c2) = (Seq (com_add_prefix p c1) (com_add_prefix p c2))" |"com_add_prefix p (If v c1 c2) = (If (add_prefix p v) (com_add_prefix p c1) (com_add_prefix p c2))" |"com_add_prefix p (While v c) = (While (add_prefix p v) (com_add_prefix p c))" (* abbreviation pcom_SKIP where "pcom_SKIP p \<equiv> SKIP" abbreviation pcom_Assign where "pcom_Assign v aexp p \<equiv> Assign (add_prefix p v) (aexp_add_prefix p aexp)" abbreviation pcom_Seq where "pcom_Seq a b p \<equiv> (a p) ;; (b p)" abbreviation pcom_If where "pcom_If v a b p \<equiv> If (add_prefix p v) (a p) (b p)" abbreviation pcom_While where "pcom_While v a p \<equiv> While (add_prefix p v) (a p)" abbreviation write_subprogram_param where "write_subprogram_param p' a b \<equiv> (\<lambda>p. Assign (add_prefix (p' @ p) a) (aexp_add_prefix p b))" abbreviation read_subprogram_param where "read_subprogram_param a p' b \<equiv> (\<lambda>p. Assign (add_prefix p a) (aexp_add_prefix (p' @ p) b))" abbreviation read_write_subprogram_param where "read_write_subprogram_param p' a p'' b \<equiv> (\<lambda>p. Assign (add_prefix (p' @ p) a) (aexp_add_prefix (p'' @ p) b))" unbundle no_com_syntax bundle pcom_syntax begin notation pcom_SKIP ("SKIP" [] 61) and pcom_Assign ("_ ::= _" [1000, 61] 61) and write_subprogram_param ("[_] _ ::= _" [1000, 61, 61] 61) and read_subprogram_param ("_ ::= [_] _" [1000, 61, 61] 61) and read_write_subprogram_param ("[_] _ ::= [_] _" [1000, 61, 61, 61] 61) and pcom_Seq ("_;;/ _" [60, 61] 60) and pcom_If ("(IF _/\<noteq>0 THEN _/ ELSE _)" [0, 0, 61] 61) and pcom_While ("(WHILE _/\<noteq>0 DO _)" [0, 61] 61) end bundle no_pcom_syntax begin no_notation pcom_SKIP ("SKIP" [] 61) and pcom_Assign ("_ ::= _" [1000, 61] 61) and write_subprogram_param ("[_] _ ::= _" [1000, 61, 61] 61) and read_subprogram_param ("_ ::= [_] _" [1000, 61, 61] 61) and read_write_subprogram_param ("[_] _ ::= [_] _" [1000, 61, 61, 61] 61) and pcom_Seq ("_;;/ _" [60, 61] 60) and pcom_If ("(IF _/\<noteq>0 THEN _/ ELSE _)" [0, 0, 61] 61) and pcom_While ("(WHILE _/\<noteq>0 DO _)" [0, 61] 61) end unbundle pcom_syntax*) lemma atomExp_add_prefix_valid: "(\<And>v. v \<in> set (atomExp_var x1) \<Longrightarrow> s1 v = s1' (add_prefix p v)) \<Longrightarrow> atomVal x1 s1 = atomVal (atomExp_add_prefix p x1) s1'" by (cases x1) auto lemma aexp_add_prefix_valid: "(\<And>v. v \<in> set (aexp_vars aexp) \<Longrightarrow> s1 v = s1' (add_prefix p v)) \<Longrightarrow> aval aexp s1 = aval (aexp_add_prefix p aexp) s1'" by (cases aexp) (auto simp: atomExp_add_prefix_valid) lemma atomExp_add_prefix_valid': "v \<in> set (atomExp_var (atomExp_add_prefix p x1)) \<Longrightarrow> \<exists>v'. v = p @ v'" by (cases x1) (auto simp:) lemma aexp_add_prefix_valid':"v \<in> set (aexp_vars (aexp_add_prefix p aexp)) \<Longrightarrow> \<exists>v'. v = p @ v'" by (cases aexp) (auto simp: atomExp_add_prefix_valid') lemma com_add_prefix_valid': "v \<in> set (all_variables (com_add_prefix p c)) \<Longrightarrow> \<exists>v'. v = p @ v'" by (induction p c rule: com_add_prefix.induct) (auto simp: aexp_add_prefix_valid') lemma atomExp_add_prefix_valid'': "add_prefix p1 v \<in> set (atomExp_var (atomExp_add_prefix (p1 @ p2) x1)) \<Longrightarrow> \<exists>v'. v = p2 @ v'" by (cases x1) (auto simp:) lemma aexp_add_prefix_valid'':"add_prefix p1 v \<in> set (aexp_vars (aexp_add_prefix (p1 @ p2) aexp)) \<Longrightarrow> \<exists>v'. v = p2 @ v'" by (cases aexp) (auto simp: atomExp_add_prefix_valid'') lemma com_add_prefix_valid'': "add_prefix p1 v \<in> set (all_variables (com_add_prefix (p1 @ p2) c)) \<Longrightarrow> \<exists>v'. v = p2 @ v'" by (induction "p1 @ p2" c arbitrary: p1 p2 rule: com_add_prefix.induct) (auto simp: aexp_add_prefix_valid'') lemma com_add_prefix_valid_subset: "add_prefix p1 v \<in> set (all_variables (com_add_prefix (p1 @ p2) c)) \<Longrightarrow> set p2 \<subseteq> set v" using com_add_prefix_valid'' by (metis set_append sup_ge1) abbreviation invoke_subprogram where "invoke_subprogram \<equiv> com_add_prefix" lemma atomExp_add_prefix_append: "atomExp_add_prefix p1 (atomExp_add_prefix p2 x1) = atomExp_add_prefix (add_prefix p1 p2) x1" by (cases x1) auto lemma aexp_add_prefix_append: "aexp_add_prefix p1 (aexp_add_prefix p2 aexp) = (aexp_add_prefix (add_prefix p1 p2) aexp)" by (cases aexp) (auto simp: atomExp_add_prefix_append) lemma invoke_subprogram_append: "invoke_subprogram p1 (invoke_subprogram p2 c) = (invoke_subprogram (p1 @ p2) c)" by (induction "(p1 @ p2)" c arbitrary: p1 p2 rule: com_add_prefix.induct) (auto simp: aexp_add_prefix_append) lemmas prefix_simps = com_add_prefix.simps aexp_add_prefix.simps atomExp_add_prefix.simps invoke_subprogram_append end
If $f$ is continuous at $a$, then $\lvert f \rvert$ is continuous at $a$.
/************************************************************************* * odil - Copyright (C) Universite de Strasbourg * Distributed under the terms of the CeCILL-B license, as published by * the CEA-CNRS-INRIA. Refer to the LICENSE file or to * http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html * for details. ************************************************************************/ #include <boost/python.hpp> #include "odil/webservices/Message.h" void wrap_webservices_Message() { using namespace boost::python; using namespace odil::webservices; class_<Message>( "Message", init<Message::Headers, std::string>(( arg("headers")=Message::Headers(), arg("body")="" ))) .def( "get_headers", &Message::get_headers, return_value_policy<copy_const_reference>()) .def("set_headers", &Message::set_headers) .def("has_header", &Message::has_header) .def( "get_header", &Message::get_header, return_value_policy<copy_const_reference>()) .def("set_header", &Message::set_header) .def( "get_body", &Message::get_body, return_value_policy<copy_const_reference>()) .def("set_body", &Message::set_body) ; }
(* Title: Lightweight Java, the definition Authors: Rok Strnisa <[email protected]>, 2006 Matthew Parkinson <[email protected]>, 2006 Maintainer: Note: This file should _not_ be modified directly. Please see the accompanying README file. *) (* generated by Ott 0.20.3 from: lj_common.ott lj_base.ott lj.ott *) theory Lightweight_Java_Definition imports Main "~~/src/HOL/Library/Multiset" begin (** warning: the backend selected ignores the file structure informations *) (** syntax *) type_synonym "j" = "nat" type_synonym "f" = "string" type_synonym "meth" = "string" type_synonym "var" = "string" type_synonym "dcl" = "string" type_synonym "oid" = "nat" datatype "fqn" = fqn_def "dcl" datatype "cl" = cl_object | cl_fqn "fqn" datatype "x" = x_var "var" | x_this datatype "vd" = vd_def "cl" "var" type_synonym "X" = "x list" datatype "ctx" = ctx_def type_synonym "vds" = "vd list" datatype "s" = s_block "s list" | s_ass "var" "x" | s_read "var" "x" "f" | s_write "x" "f" "x" | s_if "x" "x" "s" "s" | s_new "var" "ctx" "cl" | s_call "var" "x" "meth" "X" datatype "meth_sig" = meth_sig_def "cl" "meth" "vds" datatype "meth_body" = meth_body_def "s list" "x" datatype "fd" = fd_def "cl" "f" datatype "meth_def" = meth_def_def "meth_sig" "meth_body" type_synonym "fds" = "fd list" type_synonym "meth_defs" = "meth_def list" datatype "cld" = cld_def "dcl" "cl" "fds" "meth_defs" type_synonym "ctxcld" = "(ctx \<times> cld)" datatype "ty" = ty_top | ty_def "ctx" "dcl" datatype "v" = v_null | v_oid "oid" type_synonym "clds" = "cld list" type_synonym "ctxclds" = "ctxcld list" type_synonym "fs" = "f list" type_synonym "ty_opt" = "ty option" type_synonym "tys" = "ty list" type_synonym "L" = "x \<rightharpoonup> v" type_synonym "H" = "oid \<rightharpoonup> (ty \<times> (f \<rightharpoonup> v))" datatype "Exception" = ex_npe type_synonym "P" = "clds" type_synonym "ctxcld_opt" = "ctxcld option" type_synonym "nn" = "nat" type_synonym "ctxclds_opt" = "ctxclds option" type_synonym "fs_opt" = "fs option" type_synonym "meths" = "meth list" datatype "ty_opt_bot" = ty_opt_bot_opt "ty_opt" | ty_opt_bot_bot type_synonym "meth_def_opt" = "meth_def option" type_synonym "ctxmeth_def_opt" = "(ctx \<times> meth_def) option" datatype "mty" = mty_def "tys" "ty" type_synonym "\<Gamma>" = "x \<rightharpoonup> ty" type_synonym "v_opt" = "v option" datatype "config" = config_normal "P" "L" "H" "s list" | config_ex "P" "L" "H" "Exception" type_synonym "T" = "x \<rightharpoonup> x" (** library functions *) lemma [mono]:" (!! x. f x --> g x) ==> list_all (%b. b) (map f foo_list)--> list_all (%b. b) (map g foo_list) " apply(induct_tac foo_list, auto) done lemma [mono]: "split f p = f (fst p) (snd p)" by (simp add: split_def) (** definitions *) (*defns class_name_def *) inductive class_name :: "cld \<Rightarrow> dcl \<Rightarrow> bool" where (* defn class_name *) class_nameI: "class_name ((cld_def dcl cl fds meth_defs)) (dcl)" (*defns superclass_name_def *) inductive superclass_name :: "cld \<Rightarrow> cl \<Rightarrow> bool" where (* defn superclass_name *) superclass_nameI: "superclass_name ((cld_def dcl cl fds meth_defs)) (cl)" (*defns class_fields_def *) inductive class_fields :: "cld \<Rightarrow> fds \<Rightarrow> bool" where (* defn class_fields *) class_fieldsI: "class_fields ((cld_def dcl cl fds meth_defs)) (fds)" (*defns class_methods_def *) inductive class_methods :: "cld \<Rightarrow> meth_defs \<Rightarrow> bool" where (* defn class_methods *) class_methodsI: "class_methods ((cld_def dcl cl fds meth_defs)) (meth_defs)" (*defns method_name_def *) inductive method_name :: "meth_def \<Rightarrow> meth \<Rightarrow> bool" where (* defn method_name *) method_nameI: "method_name ((meth_def_def (meth_sig_def cl meth vds) meth_body)) (meth)" (*defns distinct_names_def *) inductive distinct_names :: "P \<Rightarrow> bool" where (* defn distinct_names *) dn_defI: "\<lbrakk> P = ((List.map (%((cld_XXX::cld),(dcl_XXX::dcl)).cld_XXX) cld_dcl_list)) ; list_all (\<lambda>f. f) ((List.map (%((cld_XXX::cld),(dcl_XXX::dcl)).class_name (cld_XXX) (dcl_XXX)) cld_dcl_list)) ; distinct ( ((List.map (%((cld_XXX::cld),(dcl_XXX::dcl)).dcl_XXX) cld_dcl_list)) ) \<rbrakk> \<Longrightarrow> distinct_names (P)" (*defns find_cld_def *) inductive find_cld :: "P \<Rightarrow> ctx \<Rightarrow> fqn \<Rightarrow> ctxcld_opt \<Rightarrow> bool" where (* defn find_cld *) fc_emptyI: "find_cld ( [] ) (ctx) (fqn) ( None )" | fc_cons_trueI: "\<lbrakk> P = ([(cld)] @ cld_list) ; cld = (cld_def dcl cl fds meth_defs) \<rbrakk> \<Longrightarrow> find_cld (P) (ctx) ((fqn_def dcl)) ( (Some ( ( ctx , cld ) )) )" | fc_cons_falseI: "\<lbrakk> cld = (cld_def dcl' cl fds meth_defs) ; (cl_fqn (fqn_def dcl)) \<noteq> (cl_fqn (fqn_def dcl')) ; find_cld ( (cld_list) ) (ctx) ((fqn_def dcl)) (ctxcld_opt)\<rbrakk> \<Longrightarrow> find_cld ( ([(cld)] @ cld_list) ) (ctx) ((fqn_def dcl)) (ctxcld_opt)" (*defns find_type_def *) inductive find_type :: "P \<Rightarrow> ctx \<Rightarrow> cl \<Rightarrow> ty_opt \<Rightarrow> bool" where (* defn find_type *) ft_objI: "find_type (P) (ctx) (cl_object) ( (Some ( ty_top )) )" | ft_nullI: "\<lbrakk>find_cld (P) (ctx) (fqn) ( None )\<rbrakk> \<Longrightarrow> find_type (P) (ctx) ((cl_fqn fqn)) ( None )" | ft_dclI: "\<lbrakk>find_cld (P) (ctx) ((fqn_def dcl)) ( (Some ( ( ctx' , cld ) )) )\<rbrakk> \<Longrightarrow> find_type (P) (ctx) ((cl_fqn (fqn_def dcl))) ( (Some ( (ty_def ctx' dcl) )) )" (*defns path_length_def *) inductive path_length :: "P \<Rightarrow> ctx \<Rightarrow> cl \<Rightarrow> nn \<Rightarrow> bool" where (* defn path_length *) pl_objI: "path_length (P) (ctx) (cl_object) ( 0 )" | pl_fqnI: "\<lbrakk>find_cld (P) (ctx) (fqn) ( (Some ( ( ctx' , cld ) )) ) ; superclass_name (cld) (cl) ; path_length (P) (ctx') (cl) (nn)\<rbrakk> \<Longrightarrow> path_length (P) (ctx) ((cl_fqn fqn)) ( ( nn + 1 ) )" (*defns acyclic_clds_def *) inductive acyclic_clds :: "P \<Rightarrow> bool" where (* defn acyclic_clds *) ac_defI: "\<lbrakk> \<forall> ctx fqn . ( ( (\<exists> ctx' cld . find_cld (P) (ctx) (fqn) ( (Some ( ( ctx' , cld ) )) ) ) ) \<longrightarrow> (\<exists> nn . path_length (P) (ctx) ((cl_fqn fqn)) (nn) ) ) \<rbrakk> \<Longrightarrow> acyclic_clds (P)" (*defns find_path_rec_def *) inductive find_path_rec :: "P \<Rightarrow> ctx \<Rightarrow> cl \<Rightarrow> ctxclds \<Rightarrow> ctxclds_opt \<Rightarrow> bool" where (* defn find_path_rec *) fpr_objI: "find_path_rec (P) (ctx) (cl_object) (ctxclds) ( Some ( ctxclds ) )" | fpr_nullI: "\<lbrakk> ( \<not> ( acyclic_clds (P) ) ) \<or> find_cld (P) (ctx) (fqn) ( None ) \<rbrakk> \<Longrightarrow> find_path_rec (P) (ctx) ((cl_fqn fqn)) (ctxclds) ( None )" | fpr_fqnI: "\<lbrakk> acyclic_clds (P) \<and> find_cld (P) (ctx) (fqn) ( (Some ( ( ctx' , cld ) )) ) ; superclass_name (cld) (cl) ; find_path_rec (P) (ctx') (cl) ( ctxclds @[ ( ctx' , cld ) ] ) (ctxclds_opt)\<rbrakk> \<Longrightarrow> find_path_rec (P) (ctx) ((cl_fqn fqn)) (ctxclds) (ctxclds_opt)" (*defns find_path_def *) inductive find_path :: "P \<Rightarrow> ctx \<Rightarrow> cl \<Rightarrow> ctxclds_opt \<Rightarrow> bool" where (* defn find_path *) fp_defI: "\<lbrakk>find_path_rec (P) (ctx) (cl) ( [] ) (ctxclds_opt)\<rbrakk> \<Longrightarrow> find_path (P) (ctx) (cl) (ctxclds_opt)" (*defns find_path_ty_def *) inductive find_path_ty :: "P \<Rightarrow> ty \<Rightarrow> ctxclds_opt \<Rightarrow> bool" where (* defn find_path_ty *) fpty_objI: "find_path_ty (P) (ty_top) ( Some ( [] ) )" | fpty_dclI: "\<lbrakk>find_path (P) (ctx) ((cl_fqn (fqn_def dcl))) (ctxclds_opt)\<rbrakk> \<Longrightarrow> find_path_ty (P) ((ty_def ctx dcl)) (ctxclds_opt)" (*defns fields_in_path_def *) inductive fields_in_path :: "ctxclds \<Rightarrow> fs \<Rightarrow> bool" where (* defn fields_in_path *) fip_emptyI: "fields_in_path ( [] ) ( [] )" | fip_consI: "\<lbrakk>class_fields (cld) ( ((List.map (%((cl_XXX::cl),(f_XXX::f)).(fd_def cl_XXX f_XXX)) cl_f_list)) ) ; fields_in_path ( (ctxcld_list) ) (fs) ; fs' = ( ((List.map (%((cl_XXX::cl),(f_XXX::f)).f_XXX) cl_f_list)) @ fs ) \<rbrakk> \<Longrightarrow> fields_in_path ( ([( ( ctx , cld ) )] @ ctxcld_list) ) (fs')" (*defns fields_def *) inductive fields :: "P \<Rightarrow> ty \<Rightarrow> fs_opt \<Rightarrow> bool" where (* defn fields *) fields_noneI: "\<lbrakk>find_path_ty (P) (ty) ( None )\<rbrakk> \<Longrightarrow> fields (P) (ty) ( None )" | fields_someI: "\<lbrakk>find_path_ty (P) (ty) ( Some ( ctxclds ) ) ; fields_in_path (ctxclds) (fs)\<rbrakk> \<Longrightarrow> fields (P) (ty) ( Some ( fs ) )" (*defns methods_in_path_def *) inductive methods_in_path :: "clds \<Rightarrow> meths \<Rightarrow> bool" where (* defn methods_in_path *) mip_emptyI: "methods_in_path ( [] ) ( [] )" | mip_consI: "\<lbrakk>class_methods (cld) ( ((List.map (%((meth_def_XXX::meth_def),(cl_XXX::cl),(meth_XXX::meth),(vds_XXX::vds),(meth_body_XXX::meth_body)).meth_def_XXX) meth_def_cl_meth_vds_meth_body_list)) ) ; list_all (\<lambda>f. f) ((List.map (%((meth_def_XXX::meth_def),(cl_XXX::cl),(meth_XXX::meth),(vds_XXX::vds),(meth_body_XXX::meth_body)). meth_def_XXX = (meth_def_def (meth_sig_def cl_XXX meth_XXX vds_XXX) meth_body_XXX) ) meth_def_cl_meth_vds_meth_body_list)) ; methods_in_path ( (cld_list) ) (meths') ; meths = ( ((List.map (%((meth_def_XXX::meth_def),(cl_XXX::cl),(meth_XXX::meth),(vds_XXX::vds),(meth_body_XXX::meth_body)).meth_XXX) meth_def_cl_meth_vds_meth_body_list)) @ meths' ) \<rbrakk> \<Longrightarrow> methods_in_path ( ([(cld)] @ cld_list) ) (meths)" (*defns methods_def *) inductive methods :: "P \<Rightarrow> ty \<Rightarrow> meths \<Rightarrow> bool" where (* defn methods *) methods_methodsI: "\<lbrakk>find_path_ty (P) (ty) ( Some ( ((List.map (%((ctx_XXX::ctx),(cld_XXX::cld)). ( ctx_XXX , cld_XXX ) ) ctx_cld_list)) ) ) ; methods_in_path ( ((List.map (%((ctx_XXX::ctx),(cld_XXX::cld)).cld_XXX) ctx_cld_list)) ) (meths)\<rbrakk> \<Longrightarrow> methods (P) (ty) (meths)" (*defns ftype_in_fds_def *) inductive ftype_in_fds :: "P \<Rightarrow> ctx \<Rightarrow> fds \<Rightarrow> f \<Rightarrow> ty_opt_bot \<Rightarrow> bool" where (* defn ftype_in_fds *) ftif_emptyI: "ftype_in_fds (P) (ctx) ( [] ) (f) ((ty_opt_bot_opt None ))" | ftif_cons_botI: "\<lbrakk>find_type (P) (ctx) (cl) ( None )\<rbrakk> \<Longrightarrow> ftype_in_fds (P) (ctx) ( ([((fd_def cl f))] @ fd_list) ) (f) (ty_opt_bot_bot)" | ftif_cons_trueI: "\<lbrakk>find_type (P) (ctx) (cl) ( (Some ( ty )) )\<rbrakk> \<Longrightarrow> ftype_in_fds (P) (ctx) ( ([((fd_def cl f))] @ fd_list) ) (f) ((ty_opt_bot_opt (Some ( ty )) ))" | ftif_cons_falseI: "\<lbrakk> f \<noteq> f' ; ftype_in_fds (P) (ctx) ( (fd_list) ) (f') (ty_opt_bot)\<rbrakk> \<Longrightarrow> ftype_in_fds (P) (ctx) ( ([((fd_def cl f))] @ fd_list) ) (f') (ty_opt_bot)" (*defns ftype_in_path_def *) inductive ftype_in_path :: "P \<Rightarrow> ctxclds \<Rightarrow> f \<Rightarrow> ty_opt \<Rightarrow> bool" where (* defn ftype_in_path *) ftip_emptyI: "ftype_in_path (P) ( [] ) (f) ( None )" | ftip_cons_botI: "\<lbrakk>class_fields (cld) (fds) ; ftype_in_fds (P) (ctx) (fds) (f) (ty_opt_bot_bot)\<rbrakk> \<Longrightarrow> ftype_in_path (P) ( ([( ( ctx , cld ) )] @ ctxcld_list) ) (f) ( None )" | ftip_cons_trueI: "\<lbrakk>class_fields (cld) (fds) ; ftype_in_fds (P) (ctx) (fds) (f) ((ty_opt_bot_opt (Some ( ty )) ))\<rbrakk> \<Longrightarrow> ftype_in_path (P) ( ([( ( ctx , cld ) )] @ ctxcld_list) ) (f) ( (Some ( ty )) )" | ftip_cons_falseI: "\<lbrakk>class_fields (cld) (fds) ; ftype_in_fds (P) (ctx) (fds) (f) ((ty_opt_bot_opt None )) ; ftype_in_path (P) ( (ctxcld_list) ) (f) (ty_opt)\<rbrakk> \<Longrightarrow> ftype_in_path (P) ( ([( ( ctx , cld ) )] @ ctxcld_list) ) (f) (ty_opt)" (*defns ftype_def *) inductive ftype :: "P \<Rightarrow> ty \<Rightarrow> f \<Rightarrow> ty \<Rightarrow> bool" where (* defn ftype *) ftypeI: "\<lbrakk>find_path_ty (P) (ty) ( Some ( ctxclds ) ) ; ftype_in_path (P) (ctxclds) (f) ( (Some ( ty' )) )\<rbrakk> \<Longrightarrow> ftype (P) (ty) (f) (ty')" (*defns find_meth_def_in_list_def *) inductive find_meth_def_in_list :: "meth_defs \<Rightarrow> meth \<Rightarrow> meth_def_opt \<Rightarrow> bool" where (* defn find_meth_def_in_list *) fmdil_emptyI: "find_meth_def_in_list ( [] ) (meth) ( None )" | fmdil_cons_trueI: "\<lbrakk> meth_def = (meth_def_def (meth_sig_def cl meth vds) meth_body) \<rbrakk> \<Longrightarrow> find_meth_def_in_list ( ([(meth_def)] @ meth_def_list) ) (meth) ( Some ( meth_def ) )" | fmdil_cons_falseI: "\<lbrakk> meth_def = (meth_def_def (meth_sig_def cl meth' vds) meth_body) ; meth \<noteq> meth' ; find_meth_def_in_list ( (meth_def_list) ) (meth) (meth_def_opt)\<rbrakk> \<Longrightarrow> find_meth_def_in_list ( ([(meth_def)] @ meth_def_list) ) (meth) (meth_def_opt)" (*defns find_meth_def_in_path_def *) inductive find_meth_def_in_path :: "ctxclds \<Rightarrow> meth \<Rightarrow> ctxmeth_def_opt \<Rightarrow> bool" where (* defn find_meth_def_in_path *) fmdip_emptyI: "find_meth_def_in_path ( [] ) (meth) ( (None::ctxmeth_def_opt) )" | fmdip_cons_trueI: "\<lbrakk>class_methods (cld) (meth_defs) ; find_meth_def_in_list (meth_defs) (meth) ( Some ( meth_def ) )\<rbrakk> \<Longrightarrow> find_meth_def_in_path ( ([( ( ctx , cld ) )] @ ctxcld_list) ) (meth) ( (Some ( ctx , meth_def )::ctxmeth_def_opt) )" | fmdip_cons_falseI: "\<lbrakk>class_methods (cld) (meth_defs) ; find_meth_def_in_list (meth_defs) (meth) ( None ) ; find_meth_def_in_path ( (ctxcld_list) ) (meth) (ctxmeth_def_opt)\<rbrakk> \<Longrightarrow> find_meth_def_in_path ( ([( ( ctx , cld ) )] @ ctxcld_list) ) (meth) (ctxmeth_def_opt)" (*defns find_meth_def_def *) inductive find_meth_def :: "P \<Rightarrow> ty \<Rightarrow> meth \<Rightarrow> ctxmeth_def_opt \<Rightarrow> bool" where (* defn find_meth_def *) fmd_nullI: "\<lbrakk>find_path_ty (P) (ty) ( None )\<rbrakk> \<Longrightarrow> find_meth_def (P) (ty) (meth) ( (None::ctxmeth_def_opt) )" | fmd_optI: "\<lbrakk>find_path_ty (P) (ty) ( Some ( ctxclds ) ) ; find_meth_def_in_path (ctxclds) (meth) (ctxmeth_def_opt)\<rbrakk> \<Longrightarrow> find_meth_def (P) (ty) (meth) (ctxmeth_def_opt)" (*defns mtype_def *) inductive mtype :: "P \<Rightarrow> ty \<Rightarrow> meth \<Rightarrow> mty \<Rightarrow> bool" where (* defn mtype *) mtypeI: "\<lbrakk>find_meth_def (P) (ty) (meth) ( (Some ( ctx , meth_def )::ctxmeth_def_opt) ) ; meth_def = (meth_def_def (meth_sig_def cl meth ((List.map (%((cl_XXX::cl),(var_XXX::var),(ty_XXX::ty)).(vd_def cl_XXX var_XXX)) cl_var_ty_list)) ) meth_body) ; find_type (P) (ctx) (cl) ( (Some ( ty' )) ) ; list_all (\<lambda>f. f) ((List.map (%((cl_XXX::cl),(var_XXX::var),(ty_XXX::ty)).find_type (P) (ctx) (cl_XXX) ( (Some ( ty_XXX )) )) cl_var_ty_list)) ; mty = (mty_def ((List.map (%((cl_XXX::cl),(var_XXX::var),(ty_XXX::ty)).ty_XXX) cl_var_ty_list)) ty') \<rbrakk> \<Longrightarrow> mtype (P) (ty) (meth) (mty)" (*defns sty_one_def *) inductive sty_one :: "P \<Rightarrow> ty \<Rightarrow> ty \<Rightarrow> bool" where (* defn one *) sty_objI: "\<lbrakk>find_path_ty (P) (ty) ( Some ( ctxclds ) )\<rbrakk> \<Longrightarrow> sty_one (P) (ty) (ty_top)" | sty_dclI: "\<lbrakk>find_path_ty (P) (ty) ( Some ( ((List.map (%((ctx_XXX::ctx),(cld_XXX::cld),(dcl_XXX::dcl)). ( ctx_XXX , cld_XXX ) ) ctx_cld_dcl_list)) ) ) ; list_all (\<lambda>f. f) ((List.map (%((ctx_XXX::ctx),(cld_XXX::cld),(dcl_XXX::dcl)).class_name (cld_XXX) (dcl_XXX)) ctx_cld_dcl_list)) ; ( ctx' , dcl' ) \<in> set ((List.map (%((ctx_XXX::ctx),(cld_XXX::cld),(dcl_XXX::dcl)).(ctx_XXX,dcl_XXX)) ctx_cld_dcl_list)) \<rbrakk> \<Longrightarrow> sty_one (P) (ty) ((ty_def ctx' dcl'))" (*defns sty_many_def *) inductive sty_many :: "P \<Rightarrow> tys \<Rightarrow> tys \<Rightarrow> bool" where (* defn many *) sty_manyI: "\<lbrakk> tys = ((List.map (%((ty_XXX::ty),(ty_'::ty)).ty_XXX) ty_ty'_list)) ; tys' = ((List.map (%((ty_XXX::ty),(ty_'::ty)).ty_') ty_ty'_list)) ; list_all (\<lambda>f. f) ((List.map (%((ty_XXX::ty),(ty_'::ty)).sty_one (P) (ty_XXX) (ty_')) ty_ty'_list)) \<rbrakk> \<Longrightarrow> sty_many (P) (tys) (tys')" (*defns sty_option_def *) inductive sty_option :: "P \<Rightarrow> ty_opt \<Rightarrow> ty_opt \<Rightarrow> bool" where (* defn option *) sty_optionI: "\<lbrakk> ty_opt = (Some ( ty )) ; ty_opt' = (Some ( ty' )) ; sty_one (P) (ty) (ty')\<rbrakk> \<Longrightarrow> sty_option (P) (ty_opt) (ty_opt')" (*defns well_formedness *) inductive wf_object :: "P \<Rightarrow> H \<Rightarrow> v_opt \<Rightarrow> ty_opt \<Rightarrow> bool" and wf_varstate :: "P \<Rightarrow> \<Gamma> \<Rightarrow> H \<Rightarrow> L \<Rightarrow> bool" and wf_heap :: "P \<Rightarrow> H \<Rightarrow> bool" and wf_config :: "\<Gamma> \<Rightarrow> config \<Rightarrow> bool" and wf_stmt :: "P \<Rightarrow> \<Gamma> \<Rightarrow> s \<Rightarrow> bool" and wf_meth :: "P \<Rightarrow> ty \<Rightarrow> meth_def \<Rightarrow> bool" and wf_class_common :: "P \<Rightarrow> ctx \<Rightarrow> dcl \<Rightarrow> cl \<Rightarrow> fds \<Rightarrow> meth_defs \<Rightarrow> bool" and wf_class :: "P \<Rightarrow> cld \<Rightarrow> bool" and wf_program :: "P \<Rightarrow> bool" where (* defn object *) wf_nullI: "\<lbrakk> ty_opt = (Some ( ty )) \<rbrakk> \<Longrightarrow> wf_object (P) (H) ( Some v_null ) (ty_opt)" | wf_objectI: "\<lbrakk>sty_option (P) ( (case H oid of None \<Rightarrow> None | Some tyfs \<Rightarrow> Some (fst tyfs)) ) (ty_opt)\<rbrakk> \<Longrightarrow> wf_object (P) (H) ( Some (v_oid oid) ) (ty_opt)" | (* defn varstate *) wf_varstateI: "\<lbrakk> finite (dom ( L )) ; \<forall> x \<in> dom \<Gamma> . wf_object (P) (H) ( L x ) ( \<Gamma> x ) \<rbrakk> \<Longrightarrow> wf_varstate (P) (\<Gamma>) (H) (L)" | (* defn heap *) wf_heapI: "\<lbrakk> finite (dom ( H )) ; \<forall> oid \<in> dom H . ( \<exists> ty . (case H oid of None \<Rightarrow> None | Some tyfs \<Rightarrow> Some (fst tyfs)) = (Some ( ty )) \<and> (\<exists> fs . fields (P) (ty) ( Some ( fs ) ) \<and> (\<forall> f \<in> set fs . \<exists> ty' . ( ftype (P) (ty) (f) (ty') \<and> wf_object (P) (H) ( (case H oid of None \<Rightarrow> None | Some tyfs \<Rightarrow> (snd tyfs) f ) ) ( (Some ( ty' )) ) ) ) ) ) \<rbrakk> \<Longrightarrow> wf_heap (P) (H)" | (* defn config *) wf_all_exI: "\<lbrakk>wf_program (P) ; wf_heap (P) (H) ; wf_varstate (P) (\<Gamma>) (H) (L)\<rbrakk> \<Longrightarrow> wf_config (\<Gamma>) ((config_ex P L H Exception))" | wf_allI: "\<lbrakk>wf_program (P) ; wf_heap (P) (H) ; wf_varstate (P) (\<Gamma>) (H) (L) ; list_all (\<lambda>f. f) ((List.map (%(s_XXX::s).wf_stmt (P) (\<Gamma>) (s_XXX)) s_list)) \<rbrakk> \<Longrightarrow> wf_config (\<Gamma>) ((config_normal P L H (s_list)))" | (* defn stmt *) wf_blockI: "\<lbrakk> list_all (\<lambda>f. f) ((List.map (%(s_XXX::s).wf_stmt (P) (\<Gamma>) (s_XXX)) s_list)) \<rbrakk> \<Longrightarrow> wf_stmt (P) (\<Gamma>) ((s_block (s_list)))" | wf_var_assignI: "\<lbrakk>sty_option (P) ( \<Gamma> x ) ( \<Gamma> (x_var var) )\<rbrakk> \<Longrightarrow> wf_stmt (P) (\<Gamma>) ((s_ass var x))" | wf_field_readI: "\<lbrakk> \<Gamma> x = (Some ( ty )) ; ftype (P) (ty) (f) (ty') ; sty_option (P) ( (Some ( ty' )) ) ( \<Gamma> (x_var var) )\<rbrakk> \<Longrightarrow> wf_stmt (P) (\<Gamma>) ((s_read var x f))" | wf_field_writeI: "\<lbrakk> \<Gamma> x = (Some ( ty )) ; ftype (P) (ty) (f) (ty') ; sty_option (P) ( \<Gamma> y ) ( (Some ( ty' )) )\<rbrakk> \<Longrightarrow> wf_stmt (P) (\<Gamma>) ((s_write x f y))" | wf_ifI: "\<lbrakk> sty_option (P) ( \<Gamma> x ) ( \<Gamma> y ) \<or> sty_option (P) ( \<Gamma> y ) ( \<Gamma> x ) ; wf_stmt (P) (\<Gamma>) (s1) ; wf_stmt (P) (\<Gamma>) (s2)\<rbrakk> \<Longrightarrow> wf_stmt (P) (\<Gamma>) ((s_if x y s1 s2))" | wf_newI: "\<lbrakk>find_type (P) (ctx) (cl) ( (Some ( ty )) ) ; sty_option (P) ( (Some ( ty )) ) ( \<Gamma> (x_var var) )\<rbrakk> \<Longrightarrow> wf_stmt (P) (\<Gamma>) ((s_new var ctx cl))" | wf_mcallI: "\<lbrakk> Y = ((List.map (%((y_XXX::x),(ty_XXX::ty)).y_XXX) y_ty_list)) ; \<Gamma> x = (Some ( ty )) ; mtype (P) (ty) (meth) ((mty_def ((List.map (%((y_XXX::x),(ty_XXX::ty)).ty_XXX) y_ty_list)) ty')) ; list_all (\<lambda>f. f) ((List.map (%((y_XXX::x),(ty_XXX::ty)).sty_option (P) ( \<Gamma> y_XXX ) ( (Some ( ty_XXX )) )) y_ty_list)) ; sty_option (P) ( (Some ( ty' )) ) ( \<Gamma> (x_var var) )\<rbrakk> \<Longrightarrow> wf_stmt (P) (\<Gamma>) ((s_call var x meth Y))" | (* defn meth *) wf_methodI: "\<lbrakk> distinct ( ((List.map (%((cl_XXX::cl),(var_XXX::var),(ty_XXX::ty)).var_XXX) cl_var_ty_list)) ) ; list_all (\<lambda>f. f) ((List.map (%((cl_XXX::cl),(var_XXX::var),(ty_XXX::ty)).find_type (P) (ctx) (cl_XXX) ( (Some ( ty_XXX )) )) cl_var_ty_list)) ; \<Gamma> = ( (map_of ( ((List.map (%((cl_XXX::cl),(var_XXX::var),(ty_XXX::ty)).((x_var var_XXX),ty_XXX)) cl_var_ty_list)) )) ( x_this \<mapsto> (ty_def ctx dcl) )) ; list_all (\<lambda>f. f) ((List.map (%(s_XXX::s).wf_stmt (P) (\<Gamma>) (s_XXX)) s_list)) ; find_type (P) (ctx) (cl) ( (Some ( ty )) ) ; sty_option (P) ( \<Gamma> y ) ( (Some ( ty )) )\<rbrakk> \<Longrightarrow> wf_meth (P) ((ty_def ctx dcl)) ((meth_def_def (meth_sig_def cl meth ((List.map (%((cl_XXX::cl),(var_XXX::var),(ty_XXX::ty)).(vd_def cl_XXX var_XXX)) cl_var_ty_list)) ) (meth_body_def (s_list) y)))" | (* defn class_common *) wf_class_commonI: "\<lbrakk>find_type (P) (ctx) (cl) ( (Some ( ty )) ) ; (ty_def ctx dcl) \<noteq> ty ; distinct ( ((List.map (%((cl_XXX::cl),(f_XXX::f),(ty_XXX::ty)).f_XXX) cl_f_ty_list)) ) ; fields (P) (ty) ( Some ( fs ) ) ; (set ((List.map (%((cl_XXX::cl),(f_XXX::f),(ty_XXX::ty)).f_XXX) cl_f_ty_list)) ) \<inter> (set fs ) = {} ; list_all (\<lambda>f. f) ((List.map (%((cl_XXX::cl),(f_XXX::f),(ty_XXX::ty)).find_type (P) (ctx) (cl_XXX) ( (Some ( ty_XXX )) )) cl_f_ty_list)) ; list_all (\<lambda>f. f) ((List.map (%((meth_def_XXX::meth_def),(meth_XXX::meth)).wf_meth (P) ((ty_def ctx dcl)) (meth_def_XXX)) meth_def_meth_list)) ; list_all (\<lambda>f. f) ((List.map (%((meth_def_XXX::meth_def),(meth_XXX::meth)).method_name (meth_def_XXX) (meth_XXX)) meth_def_meth_list)) ; distinct ( ((List.map (%((meth_def_XXX::meth_def),(meth_XXX::meth)).meth_XXX) meth_def_meth_list)) ) ; methods (P) (ty) ( ((List.map (%((meth_'::meth),(mty_XXX::mty),(mty_'::mty)).meth_') meth'_mty_mty'_list)) ) ; list_all (\<lambda>f. f) ((List.map (%((meth_'::meth),(mty_XXX::mty),(mty_'::mty)).mtype (P) ((ty_def ctx dcl)) (meth_') (mty_XXX)) meth'_mty_mty'_list)) ; list_all (\<lambda>f. f) ((List.map (%((meth_'::meth),(mty_XXX::mty),(mty_'::mty)).mtype (P) (ty) (meth_') (mty_')) meth'_mty_mty'_list)) ; list_all (\<lambda>f. f) ((List.map (%((meth_'::meth),(mty_XXX::mty),(mty_'::mty)). meth_' \<in> set ((List.map (%((meth_def_XXX::meth_def),(meth_XXX::meth)).meth_XXX) meth_def_meth_list)) \<longrightarrow> mty_XXX = mty_' ) meth'_mty_mty'_list)) \<rbrakk> \<Longrightarrow> wf_class_common (P) (ctx) (dcl) (cl) ( ((List.map (%((cl_XXX::cl),(f_XXX::f),(ty_XXX::ty)).(fd_def cl_XXX f_XXX)) cl_f_ty_list)) ) ( ((List.map (%((meth_def_XXX::meth_def),(meth_XXX::meth)).meth_def_XXX) meth_def_meth_list)) )" | (* defn class *) wf_classI: "\<lbrakk> (cld_def dcl cl fds meth_defs) \<in> set P ; wf_class_common (P) (ctx_def) (dcl) (cl) (fds) (meth_defs)\<rbrakk> \<Longrightarrow> wf_class (P) ((cld_def dcl cl fds meth_defs))" | (* defn program *) wf_programI: "\<lbrakk> P = (cld_list) ; distinct_names (P) ; list_all (\<lambda>f. f) ((List.map (%(cld_XXX::cld).wf_class (P) (cld_XXX)) cld_list)) ; acyclic_clds (P)\<rbrakk> \<Longrightarrow> wf_program (P)" (*defns var_trans *) inductive tr_s :: "T \<Rightarrow> s \<Rightarrow> s \<Rightarrow> bool" where (* defn tr_s *) tr_s_blockI: "\<lbrakk> list_all (\<lambda>f. f) ((List.map (%((s_XXX::s),(s_'::s)).tr_s (T) (s_XXX) (s_')) s_s'_list)) \<rbrakk> \<Longrightarrow> tr_s (T) ((s_block ((List.map (%((s_XXX::s),(s_'::s)).s_XXX) s_s'_list)))) ((s_block ((List.map (%((s_XXX::s),(s_'::s)).s_') s_s'_list))))" | tr_s_var_assignI: "\<lbrakk> (case T (x_var var ) of None \<Rightarrow> var | Some x' \<Rightarrow> (case x' of x_this \<Rightarrow> var | x_var var' \<Rightarrow> var')) = var' ; (case T x of None \<Rightarrow> x | Some x' \<Rightarrow> x') = x' \<rbrakk> \<Longrightarrow> tr_s (T) ((s_ass var x)) ((s_ass var' x'))" | tr_s_field_readI: "\<lbrakk> (case T (x_var var ) of None \<Rightarrow> var | Some x' \<Rightarrow> (case x' of x_this \<Rightarrow> var | x_var var' \<Rightarrow> var')) = var' ; (case T x of None \<Rightarrow> x | Some x' \<Rightarrow> x') = x' \<rbrakk> \<Longrightarrow> tr_s (T) ((s_read var x f)) ((s_read var' x' f))" | tr_s_field_writeI: "\<lbrakk> (case T x of None \<Rightarrow> x | Some x' \<Rightarrow> x') = x' ; (case T y of None \<Rightarrow> y | Some x' \<Rightarrow> x') = y' \<rbrakk> \<Longrightarrow> tr_s (T) ((s_write x f y)) ((s_write x' f y'))" | tr_s_ifI: "\<lbrakk> (case T x of None \<Rightarrow> x | Some x' \<Rightarrow> x') = x' ; (case T y of None \<Rightarrow> y | Some x' \<Rightarrow> x') = y' ; tr_s (T) (s1) (s1') ; tr_s (T) (s2) (s2')\<rbrakk> \<Longrightarrow> tr_s (T) ((s_if x y s1 s2)) ((s_if x' y' s1' s2'))" | tr_s_newI: "\<lbrakk> (case T (x_var var ) of None \<Rightarrow> var | Some x' \<Rightarrow> (case x' of x_this \<Rightarrow> var | x_var var' \<Rightarrow> var')) = var' \<rbrakk> \<Longrightarrow> tr_s (T) ((s_new var ctx cl)) ((s_new var' ctx cl))" | tr_s_mcallI: "\<lbrakk> (case T (x_var var ) of None \<Rightarrow> var | Some x' \<Rightarrow> (case x' of x_this \<Rightarrow> var | x_var var' \<Rightarrow> var')) = var' ; (case T x of None \<Rightarrow> x | Some x' \<Rightarrow> x') = x' ; list_all (\<lambda>f. f) ((List.map (%((y_XXX::x),(y_'::x)). (case T y_XXX of None \<Rightarrow> y_XXX | Some x' \<Rightarrow> x') = y_' ) y_y'_list)) \<rbrakk> \<Longrightarrow> tr_s (T) ((s_call var x meth ((List.map (%((y_XXX::x),(y_'::x)).y_XXX) y_y'_list)) )) ((s_call var' x' meth ((List.map (%((y_XXX::x),(y_'::x)).y_') y_y'_list)) ))" (*defns reduction *) inductive r_stmt :: "config \<Rightarrow> config \<Rightarrow> bool" where (* defn stmt *) r_blockI: "r_stmt ((config_normal P L H ([((s_block (s_list)))] @ s'_list))) ((config_normal P L H (s_list @ s'_list)))" | r_var_assignI: "\<lbrakk> L x = Some v \<rbrakk> \<Longrightarrow> r_stmt ((config_normal P L H ([((s_ass var x))] @ s_list))) ((config_normal P ( L ( (x_var var) \<mapsto> v )) H (s_list)))" | r_field_read_npeI: "\<lbrakk> L x = Some v_null \<rbrakk> \<Longrightarrow> r_stmt ((config_normal P L H ([((s_read var x f))] @ s_list))) ((config_ex P L H ex_npe))" | r_field_readI: "\<lbrakk> L x = Some (v_oid oid) ; (case H oid of None \<Rightarrow> None | Some tyfs \<Rightarrow> (snd tyfs) f ) = Some v \<rbrakk> \<Longrightarrow> r_stmt ((config_normal P L H ([((s_read var x f))] @ s_list))) ((config_normal P ( L ( (x_var var) \<mapsto> v )) H (s_list)))" | r_field_write_npeI: "\<lbrakk> L x = Some v_null \<rbrakk> \<Longrightarrow> r_stmt ((config_normal P L H ([((s_write x f y))] @ s_list))) ((config_ex P L H ex_npe))" | r_field_writeI: "\<lbrakk> L x = Some (v_oid oid) ; L y = Some v \<rbrakk> \<Longrightarrow> r_stmt ((config_normal P L H ([((s_write x f y))] @ s_list))) ((config_normal P L (case H oid of None \<Rightarrow> arbitrary | Some tyfs \<Rightarrow> (( H ( oid \<mapsto> (fst tyfs, snd tyfs ( f \<mapsto> v ))))::H)) (s_list)))" | r_if_trueI: "\<lbrakk> L x = Some v ; L y = Some w ; v = w \<rbrakk> \<Longrightarrow> r_stmt ((config_normal P L H ([((s_if x y s1 s2))] @ s'_list))) ((config_normal P L H ([(s1)] @ s'_list)))" | r_if_falseI: "\<lbrakk> L x = Some v ; L y = Some w ; v \<noteq> w \<rbrakk> \<Longrightarrow> r_stmt ((config_normal P L H ([((s_if x y s1 s2))] @ s'_list))) ((config_normal P L H ([(s2)] @ s'_list)))" | r_newI: "\<lbrakk>find_type (P) (ctx) (cl) ( (Some ( ty )) ) ; fields (P) (ty) ( Some ( (f_list) ) ) ; oid \<notin> dom H ; H' = (( H ( oid \<mapsto> ( ty , map_of ((List.map (%(f_XXX::f).(f_XXX,v_null)) f_list)) )))::H) \<rbrakk> \<Longrightarrow> r_stmt ((config_normal P L H ([((s_new var ctx cl))] @ s_list))) ((config_normal P ( L ( (x_var var) \<mapsto> (v_oid oid) )) H' (s_list)))" | r_mcall_npeI: "\<lbrakk> L x = Some v_null \<rbrakk> \<Longrightarrow> r_stmt ((config_normal P L H ([((s_call var x meth (y_list) ))] @ s_list))) ((config_ex P L H ex_npe))" | r_mcallI: "\<lbrakk> L x = Some (v_oid oid) ; (case H oid of None \<Rightarrow> None | Some tyfs \<Rightarrow> Some (fst tyfs)) = (Some ( ty )) ; find_meth_def (P) (ty) (meth) ( (Some ( ctx , (meth_def_def (meth_sig_def cl meth ((List.map (%((y_XXX::x),(cl_XXX::cl),(var_XXX::var),(var_'::var),(v_XXX::v)).(vd_def cl_XXX var_XXX)) y_cl_var_var'_v_list)) ) (meth_body_def ((List.map (%((s_''::s),(s_'::s)).s_') s''_s'_list)) y)) )::ctxmeth_def_opt) ) ; (set ((List.map (%((y_XXX::x),(cl_XXX::cl),(var_XXX::var),(var_'::var),(v_XXX::v)).(x_var var_')) y_cl_var_var'_v_list)) ) Int (dom L ) = {} ; distinct ( ((List.map (%((y_XXX::x),(cl_XXX::cl),(var_XXX::var),(var_'::var),(v_XXX::v)).var_') y_cl_var_var'_v_list)) ) ; x' \<notin> dom L ; x' \<notin> set ((List.map (%((y_XXX::x),(cl_XXX::cl),(var_XXX::var),(var_'::var),(v_XXX::v)).(x_var var_')) y_cl_var_var'_v_list)) ; list_all (\<lambda>f. f) ((List.map (%((y_XXX::x),(cl_XXX::cl),(var_XXX::var),(var_'::var),(v_XXX::v)). L y_XXX = Some v_XXX ) y_cl_var_var'_v_list)) ; L' = ( ( L ++ (map_of ( ((List.map (%((y_XXX::x),(cl_XXX::cl),(var_XXX::var),(var_'::var),(v_XXX::v)).((x_var var_'),v_XXX)) y_cl_var_var'_v_list)) ))) ( x' \<mapsto> (v_oid oid) )) ; T = ( (map_of ( ((List.map (%((y_XXX::x),(cl_XXX::cl),(var_XXX::var),(var_'::var),(v_XXX::v)).((x_var var_XXX),(x_var var_'))) y_cl_var_var'_v_list)) )) ( x_this \<mapsto> x' )) ; list_all (\<lambda>f. f) ((List.map (%((s_''::s),(s_'::s)).tr_s (T) (s_') (s_'')) s''_s'_list)) ; (case T y of None \<Rightarrow> y | Some x' \<Rightarrow> x') = y' \<rbrakk> \<Longrightarrow> r_stmt ((config_normal P L H ([((s_call var x meth ((List.map (%((y_XXX::x),(cl_XXX::cl),(var_XXX::var),(var_'::var),(v_XXX::v)).y_XXX) y_cl_var_var'_v_list)) ))] @ s_list))) ((config_normal P L' H ((List.map (%((s_''::s),(s_'::s)).s_'') s''_s'_list) @ [((s_ass var y'))] @ s_list)))" end
<h1 align=center style="color: #005496; font-size: 4.2em;">Machine Learning with Python</h1> <h2 align=center>Laboratory on Numpy / Matplotlib / Scikit-learn</h2> *** *** ## Introduction In the past few years, Python has become the de-facto standard programming language for data analytics. Python's success is due to several factors, but one major reason has been the availability of powerful, open-source libraries for scientific computation such as Numpy, Scipy and Matplotlib. Python is also the most popular programming language for machine learning, thanks to libraries such as Scikit-learn and TensorFlow. In this lecture we will explore the basics of Numpy, Matplotlib and Scikit-learn. The first is a library for data manipulation through the powerfull `numpy.ndarray` data structure; the second is useful for graphical visualization and plotting; the third is a general purpose library for machine learning, containing dozens of algorithms for classification, regression and clustering. In this lecture we assume familiarity with the Python programming language. If you are not familiar with the language, we advise you to look it up before carrying over to the next sections. Here are some useful links to learn about Python: - https://docs.python.org/3/tutorial/introduction.html - https://www.learnpython.org/ - http://www.scipy-lectures.org/ If you have never seen a page like this, it is a **Jupyther Notebook**. Here one can easily embed Python code and run it on the fly. You can run the code in a cell by selecting the cell and clicking the *Run* button (top). You can do the same using the **SHIFT+Enter** shortcut. You can modify the existing cells, run them and finally save your changes. ## Requirements 1. Python (preferably version > 3.3): https://www.python.org/downloads/ 2. Numpy, Scipy and Matplotlib: https://www.scipy.org/install.html 3. Scikit-learn: http://scikit-learn.org/stable/install.html ## References - https://docs.scipy.org/doc/numpy/ - https://docs.scipy.org/doc/scipy/reference/ - https://matplotlib.org/users/index.html - http://scikit-learn.org/stable/documentation.html # Numpy Numpy provides high-performance data structures for data manipulation and numeric computation. In particular, we will look at the `numpy.ndarray`, a data structure for manipulating vectors, matrices and tensors. Let's start by importing `numpy`: ```python # the np alias is very common import numpy as np ``` We can initialize a Numpy array from a Python list using the `numpy.array` function: ```python # if the argument is a list of numbers, the array will be a 1-dimensional vector a = np.array([1, 2, 3, 4, 5, 6]) a ``` array([1, 2, 3, 4, 5, 6]) ```python # if the argument is a list of lists, the array will be a 2-dimensional matrix M = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) M ``` array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16]]) Given a Numpy array, we can check its `shape`, a tuple containing the number of elements for each dimension: ```python a.shape ``` (6,) ```python M.shape ``` (4, 4) The size of an array is its total number of elements: ```python a.size ``` 6 ```python M.size ``` 16 We can do quite some nice things with Numpy arrays that are not possible with standard Python lists. ### Indexing Numpy array allow us to index arrays in quite advanced ways. ```python # A 1d vector can be indexed in all the common ways a[0] ``` 1 ```python a[1:3] ``` array([2, 3]) ```python a[0:5:2] ``` array([1, 3, 5]) ```python # Use a boolean mask mask = [True, False, False, True, True, False] a[mask] ``` array([1, 4, 5]) ```python # Access specific elements by passing a list of index a[[1, 4, 5]] ``` array([2, 5, 6]) The power of Numpy indexing capabilities starts showing up with 2d arrays: ```python # Access a single element of the matrix M[0, 1] ``` 2 ```python # Access an entire row M[1] ``` array([5, 6, 7, 8]) ```python # Access an entire column M[:,2] ``` array([ 3, 7, 11, 15]) ```python # Extract a sub-matrix M[1:3, 0:2] ``` array([[ 5, 6], [ 9, 10]]) ### Data manipulation We can manipulate data in several ways. ```python # Flatten a matrix M.flatten() ``` array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) ```python # Reshaping a matrix M.reshape(2, 8) ``` array([[ 1, 2, 3, 4, 5, 6, 7, 8], [ 9, 10, 11, 12, 13, 14, 15, 16]]) ```python # The last index can be automatically inferred using -1 M.reshape(2, -1) ``` array([[ 1, 2, 3, 4, 5, 6, 7, 8], [ 9, 10, 11, 12, 13, 14, 15, 16]]) ```python # Computing the max and the min M.max(), M.min() ``` (16, 1) ```python # Computing the mean and standard deviation M.mean(), M.std() ``` (8.5, 4.6097722286464435) ```python # Computing the sum along the rows M.sum(axis=1) ``` array([10, 26, 42, 58]) ### Linear algebra Numpy is very useful to all sort of numeric computation, especially linear algebra: ```python # Transpose M.T ``` array([[ 1, 5, 9, 13], [ 2, 6, 10, 14], [ 3, 7, 11, 15], [ 4, 8, 12, 16]]) ```python # Adding and multiplying a constant 10 * M + 5 ``` array([[ 15, 25, 35, 45], [ 55, 65, 75, 85], [ 95, 105, 115, 125], [135, 145, 155, 165]]) ```python # Element wise product b = np.array([-1, -2, 4, 6, 8, -4]) a * b ``` array([ -1, -4, 12, 24, 40, -24]) ```python # Dot product a.dot(b) ``` 47 ```python # More linear algebra in the package numpy.linalg # Determinant np.linalg.det(M) ``` 0.0 ```python # Eigenvalues np.linalg.eigvals(M) ``` array([ 3.62093727e+01, -2.20937271e+00, -3.36399340e-15, -2.27991821e-16]) ### Vector generation and sampling Numpy allows us to generate or randomly sample vectors: ```python # Generate an array with 0.5 spacing x = np.arange(-10, 10, 0.5) x ``` array([-10. , -9.5, -9. , -8.5, -8. , -7.5, -7. , -6.5, -6. , -5.5, -5. , -4.5, -4. , -3.5, -3. , -2.5, -2. , -1.5, -1. , -0.5, 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. , 5.5, 6. , 6.5, 7. , 7.5, 8. , 8.5, 9. , 9.5]) ```python # Generate an array with 20 equally spaced points x = np.linspace(-10, 10, 20) x ``` array([-10. , -8.94736842, -7.89473684, -6.84210526, -5.78947368, -4.73684211, -3.68421053, -2.63157895, -1.57894737, -0.52631579, 0.52631579, 1.57894737, 2.63157895, 3.68421053, 4.73684211, 5.78947368, 6.84210526, 7.89473684, 8.94736842, 10. ]) ```python # Sample a vector from a standardize normal distribution np.random.normal(size=(10,)) ``` array([ 1.44201973, -0.11330043, 0.08256323, -1.15813372, 0.15709646, -0.06512693, 0.90353507, 0.97059199, 0.57933141, 0.17082713]) ### Functions Numpy provides all sorts of mathematical functions we can apply to arrays ```python # Exponential function np.exp(x) ``` array([4.53999298e-05, 1.30079023e-04, 3.72699966e-04, 1.06785292e-03, 3.05959206e-03, 8.76628553e-03, 2.51169961e-02, 7.19647439e-02, 2.06192028e-01, 5.90777514e-01, 1.69268460e+00, 4.84984802e+00, 1.38956932e+01, 3.98136782e+01, 1.14073401e+02, 3.26840958e+02, 9.36458553e+02, 2.68312340e+03, 7.68763460e+03, 2.20264658e+04]) ```python # Sine np.sin(x) ``` array([ 0.54402111, -0.4594799 , -0.99916962, -0.53027082, 0.47389753, 0.99970104, 0.5163796 , -0.48818921, -0.99996678, -0.50235115, 0.50235115, 0.99996678, 0.48818921, -0.5163796 , -0.99970104, -0.47389753, 0.53027082, 0.99916962, 0.4594799 , -0.54402111]) ```python # A gaussian function y = np.exp(-(x ** 2)/2) y ``` array([1.92874985e-22, 4.13228632e-18, 2.92342653e-14, 6.82937941e-11, 5.26814324e-08, 1.34190319e-05, 1.12868324e-03, 3.13480292e-02, 2.87498569e-01, 8.70659634e-01, 8.70659634e-01, 2.87498569e-01, 3.13480292e-02, 1.12868324e-03, 1.34190319e-05, 5.26814324e-08, 6.82937941e-11, 2.92342653e-14, 4.13228632e-18, 1.92874985e-22]) # Matplotlib The above matrices provide little insight without the possibility of visualizing them properly. Matplotlib is a powerful library for data visualization. Let's plot the above function. ```python # the following line is only needed to show plots in the notebook %matplotlib inline import matplotlib.pyplot as plt x = np.linspace(-10, 10, 200) # get a sample of the x axis y = np.exp(-(x**2)/(2*1)) # compute the function for all points in the sample plt.plot(x, y) # add the curve to the plot plt.ylim(-0.05,1.05) # set bottom and top limits for y axis plt.show() # show the plot ``` We can also plot more than one line in the same figure and add a grid to the plot. ```python z = np.exp(-(x**2)/(2*10)) plt.grid() # add the grid under the curves plt.plot(x, y) # add the first curve to the plot plt.plot(x, z) # add the second curve to the plot plt.ylim(-0.05,1.05) # set bottom and top limits for y axis plt.show() # show the plot ``` We can also set several properties of the plot in this way: ```python plt.grid() plt.xlabel('x') # add a label to the x axis plt.ylabel('y') # add a label to the y axis plt.xticks(np.arange(-10, 11, 2)) # specify in which point to place a tick on the x axis plt.yticks(np.arange(0, 2.2, 0.2)) # and on the y axis # rs- stands for red, squared markers, solid line # yd-- stands for yellow, diamond markers, dashed line plt.plot(x, y, 'rs-', markevery=10, label='sigma=1') # add a style and a label and specify the gap plt.plot(x, z, 'yd--', markevery=10, label='sigma=10') # between markers for both curves plt.ylim(-0.05,1.05) # set bottom and top limits for y axis plt.legend() # add the legend (displays the labels of the curves) plt.show() # show the plot ``` Finally, we can save the plot into a png file in this way: ```python plt.grid() plt.xlabel('x') plt.ylabel('y') plt.xticks(np.arange(-10, 11, 2)) plt.yticks(np.arange(0, 2.2, 0.2)) plt.plot(x, y, 'rs-', markevery=10, label='sigma=1') plt.plot(x, z, 'yd--', markevery=10, label='sigma=10') plt.ylim(-0.05,1.05) # set bottom and top limits for y axis plt.legend() plt.savefig('plot.png', dpi=300) # saves the plot into the file plot.png with 300 dpi ``` # Scikit-learn Let's now dive into the real **Machine Learning** part. *Scikit-learn* is perhaps the most wide-spread library for Machine Learning in use nowadays, and most of its fame is due to its extreme simplicity. With Scikit-learn it is possible to easily manage datasets, and train a wide range of classifiers out-of-the-box. It is also useful for several other Machine Learning tasks such as regression, clustering, dimensionality reduction, and model selection. In the following we will see how to use Scikit-learn to load a dataset, train a classifier and perform validation and model selection. Scikit-learn comes with a range of popular reference datasets. Let's load and use the *Digits* dataset: ```python from sklearn.datasets import load_digits digits = load_digits() print(digits.DESCR) # print a description of the digits dataset ``` .. _digits_dataset: Optical recognition of handwritten digits dataset -------------------------------------------------- **Data Set Characteristics:** :Number of Instances: 5620 :Number of Attributes: 64 :Attribute Information: 8x8 image of integer pixels in the range 0..16. :Missing Attribute Values: None :Creator: E. Alpaydin (alpaydin '@' boun.edu.tr) :Date: July; 1998 This is a copy of the test set of the UCI ML hand-written digits datasets http://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits The data set contains images of hand-written digits: 10 classes where each class refers to a digit. Preprocessing programs made available by NIST were used to extract normalized bitmaps of handwritten digits from a preprinted form. From a total of 43 people, 30 contributed to the training set and different 13 to the test set. 32x32 bitmaps are divided into nonoverlapping blocks of 4x4 and the number of on pixels are counted in each block. This generates an input matrix of 8x8 where each element is an integer in the range 0..16. This reduces dimensionality and gives invariance to small distortions. For info on NIST preprocessing routines, see M. D. Garris, J. L. Blue, G. T. Candela, D. L. Dimmick, J. Geist, P. J. Grother, S. A. Janet, and C. L. Wilson, NIST Form-Based Handprint Recognition System, NISTIR 5469, 1994. .. topic:: References - C. Kaynak (1995) Methods of Combining Multiple Classifiers and Their Applications to Handwritten Digit Recognition, MSc Thesis, Institute of Graduate Studies in Science and Engineering, Bogazici University. - E. Alpaydin, C. Kaynak (1998) Cascading Classifiers, Kybernetika. - Ken Tang and Ponnuthurai N. Suganthan and Xi Yao and A. Kai Qin. Linear dimensionalityreduction using relevance weighted LDA. School of Electrical and Electronic Engineering Nanyang Technological University. 2005. - Claudio Gentile. A New Approximate Maximal Margin Classification Algorithm. NIPS. 2000. Let's take a look at the data: ```python X, y = digits.data, digits.target # The attributes of the first instance (notice it is a Numpy array) X[0] ``` array([ 0., 0., 5., 13., 9., 1., 0., 0., 0., 0., 13., 15., 10., 15., 5., 0., 0., 3., 15., 2., 0., 11., 8., 0., 0., 4., 12., 0., 0., 8., 8., 0., 0., 5., 8., 0., 0., 9., 8., 0., 0., 4., 11., 0., 1., 12., 7., 0., 0., 2., 14., 5., 10., 12., 0., 0., 0., 0., 6., 13., 10., 0., 0., 0.]) ```python # The label of the first instance y[0] ``` 0 Being a Numpy array, we can actually take a look at this image. We first need to reshape it into an 8x8 matrix and then use matplotlib. ```python x = X[0].reshape((8, 8)) plt.gray() # use a grayscale plt.matshow(x) # display a matrix of values plt.show() # show the figure ``` Now we want to train a classifier to recognize the digits from the images and then we want to evaluate it. In order to make a proper evaluation, we first need to split the dataset in two sets, one for training and one for testing. Scikit-learn helps us with that: ```python import sklearn # the lab PCs have an outdated version of scikit-learn, with different names for packages try: from sklearn.model_selection import train_test_split except ImportError: from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Let's check the length of the two sets len(X_train), len(X_test) ``` (1437, 360) Now we need a classifier. Let's use an **SVM**. A reminder: \begin{align} \min_{\boldsymbol{w}} \quad & \frac{1}{2}\|\boldsymbol{w}\|^2 + C \sum_{i\in|\mathcal{D}|} \xi_i \\ \forall (x_i, y_i) \in \mathcal{D} \quad & y_i ( \boldsymbol{w}^T x_i + b ) \ge 1 - \xi_i \end{align} ```python from sklearn.svm import SVC # Specify the parameters in the constructor. # C is the parameter of the primal problem of the SVM; # The rbf kernel is the Gaussian kernel; # The rbf kernel takes one parameter: gamma (gaussian width) clf = SVC(C=10, kernel='rbf', gamma=0.02) ``` Now the classifier can be trained and then used to predict unseen instances. ```python # Training clf.fit(X_train, y_train) # Prediction y_pred = clf.predict(X_test) y_pred ``` array([3, 3, 3, 7, 3, 1, 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 3, 3, 8, 3, 3, 3, 3, 3, 3, 3, 3, 3, 6, 3, 3, 9, 1, 3, 3, 6, 3, 4, 3, 6, 6, 3, 1, 3, 3, 3, 3, 3, 6, 3, 3, 3, 3, 3, 3, 0, 3, 3, 0, 1, 3, 3, 3, 3, 3, 5, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 0, 3, 4, 3, 3, 3, 3, 8, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 7, 7, 3, 3, 3, 3, 3, 3, 3, 7, 2, 6, 3, 3, 3, 3, 3, 7, 3, 3, 3, 3, 3, 3, 3, 6, 3, 4, 3, 3, 3, 3, 3, 3, 3, 3, 6, 3, 3, 3, 3, 3, 6, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 3, 1, 3, 7, 3, 2, 2, 3, 3, 8, 3, 3, 2, 3, 3, 6, 9, 3, 3, 1, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 1, 3, 3, 3, 3, 6, 1, 3, 6, 0, 4, 3, 2, 7, 3, 6, 3, 3, 3, 3, 3, 2, 3, 6, 3, 1, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 0, 3, 3, 3, 0, 1, 3, 4, 3, 1, 3, 3, 6, 0, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 9, 3, 3, 3, 3, 3, 3, 0, 3, 3, 3, 3, 0, 3, 3, 6, 3, 3, 3, 3, 3, 3, 2, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 7, 0, 6, 3, 3, 3, 3, 1, 3, 4, 3, 3, 7, 3, 3, 3, 3, 3, 3, 0, 7, 3, 3, 3, 3, 2, 7, 3, 1, 3, 7, 3, 3, 3, 3, 3]) Now we want to evaluate the performance of our classifier. A reminder: \begin{align} \text{Accuracy } &= \frac{\text{true-positive} + \text{true-negative}}{\text{all examples}} \\ \text{Precision } &= \frac{\text{true-positive}}{\text{true-positive} + \text{false-positive}} \\ \text{Recall } &= \frac{\text{true-positive}}{\text{true-positive} + \text{false-negative}} \\ F_1 &= \frac{2 \times \text{precision} \times \text{recall}}{\text{precision} + \text{recall}} \\ \end{align} In a multiclass classification Precision, Recall and $F_1$ are computed per class, considering the given class as positive and all others as negative. We can use Scikit-learn to compute and show these measures for all classes. ```python from sklearn import metrics report = metrics.classification_report(y_test, y_pred) # the support is the number of instances having the given label in y_test print(report) ``` precision recall f1-score support 0 1.00 0.39 0.57 33 1 1.00 0.61 0.76 28 2 1.00 0.36 0.53 33 3 0.12 1.00 0.22 34 4 1.00 0.20 0.33 46 5 1.00 0.02 0.04 47 6 1.00 0.49 0.65 35 7 1.00 0.35 0.52 34 8 1.00 0.10 0.18 30 9 1.00 0.07 0.14 40 micro avg 0.34 0.34 0.34 360 macro avg 0.91 0.36 0.39 360 weighted avg 0.92 0.34 0.37 360 Finally we can compute the accuracy of our classifier: ```python metrics.accuracy_score(y_test, y_pred) ``` 0.33611111111111114 Apparently our classifier performs a bit poorly out-of-sample. This is probably due to the random choice of the parameters for the classifier. We can do much better! We need to perform model selection, that is we need to search for better parameters for our classifier. In particular, we are going to perform a **cross-validation** on the training set and see how the classifier performs with different values of *gamma*. A $k$-fold cross-validation works like this: - Split the dataset $D$ in $k$ equally sized disjoint subsets $D_i$ - For $i \in [1, k]$ - Train the classifier on $T_i = D \setminus D_i$ - Compute the score (accuracy, precision, ...) on $D_i$ - Return the list of scores, one for each fold Scikit-learn helps us with this as well. We compute the cross-validated accuracy for all the possible values of *gamma* and select the *gamma* with the best average accuracy. ```python # Again, we have to add some code to have this run on the lab PCs try: from sklearn.model_selection import KFold, cross_val_score legacy = False except ImportError: from sklearn.cross_validation import KFold, cross_val_score legacy = True # 3-fold cross-validation # random_state ensures same split for each value of gamma # KFold has a different syntax for legacy versions of scikit-learn if legacy: kf = KFold(len(y_train),n_folds=3, shuffle=True, random_state=42) else: kf = KFold(n_splits=3, shuffle=True, random_state=42) gamma_values = [0.1, 0.05, 0.02, 0.01] accuracy_scores = [] # Do model selection over all the possible values of gamma for gamma in gamma_values: # Train a classifier with current gamma clf = SVC(C=10, kernel='rbf', gamma=gamma) # Compute cross-validated accuracy scores # So legacy.... if legacy: scores = cross_val_score(clf, X_train, y_train, cv=kf, scoring='accuracy') else: scores = cross_val_score(clf, X_train, y_train, cv=kf.split(X_train), scoring='accuracy') # Compute the mean accuracy and keep track of it accuracy_score = scores.mean() accuracy_scores.append(accuracy_score) # Get the gamma with highest mean accuracy best_index = np.array(accuracy_scores).argmax() best_gamma = gamma_values[best_index] # Train over the full training set with the best gamma clf = SVC(C=10, kernel='rbf', gamma=best_gamma) clf.fit(X_train, y_train) # Evaluate on the test set y_pred = clf.predict(X_test) accuracy = metrics.accuracy_score(y_test, y_pred) accuracy ``` 0.8138888888888889 Much better! Model selection allows us to fine-tune the parameters of a lerning algorithm to get the best performance. Let's now look at the **Learnig curve** of our classifier, in which we plot the training accuracy and the cross-validated accuracy for increasing number of examples. ```python try: from sklearn.model_selection import learning_curve except ImportError: from sklearn.learning_curve import learning_curve plt.figure() plt.title("Learning curve") plt.xlabel("Training examples") plt.ylabel("Score") plt.grid() clf = SVC(C=10, kernel='rbf', gamma=best_gamma) # Compute the scores of the learning curve # by default the (relative) dataset sizes are: 10%, 32.5%, 55%, 77.5%, 100% # The function automatuically executes a Kfold cross validation for each dataset size train_sizes, train_scores, val_scores = learning_curve(clf, X_train, y_train, scoring='accuracy', cv=3) # Get the mean and std of train and validation scores over the cv folds along the varying dataset sizes train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) val_scores_mean = np.mean(val_scores, axis=1) val_scores_std = np.std(val_scores, axis=1) # Plot the mean for the training scores plt.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training score") # Plot the std for the training scores plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color="r") # Plot the mean for the validation scores plt.plot(train_sizes, val_scores_mean, 'o-', color="g", label="Cross-validation score") # Plot the std for the validation scores plt.fill_between(train_sizes, val_scores_mean - val_scores_std, val_scores_mean + val_scores_std, alpha=0.1, color="g") plt.ylim(0.05,1.3) # set bottom and top limits for y axis plt.legend() plt.show() ``` Now we want to go even further. We can perform the above model selection procedure considering the *C* parameter as well. In general, this process over several parameters is called **grid search**, and Scikit-learn has an automated procedure to perform cross-validated grid search for any classifier. ```python try: from sklearn.model_selection import GridSearchCV except ImportError: from sklearn.grid_search import GridSearchCV possible_parameters = { 'C': [1e0, 1e1, 1e2, 1e3], 'gamma': [1e-1, 1e-2, 1e-3, 1e-4] } svc = SVC(kernel='rbf') # The GridSearchCV is itself a classifier # we fit the GridSearchCV with the training data # and then we use it to predict on the test set clf = GridSearchCV(svc, possible_parameters, n_jobs=4, cv=3) # n_jobs=4 means we parallelize the search over 4 threads clf.fit(X_train, y_train) y_pred = clf.predict(X_test) accuracy = metrics.accuracy_score(y_test, y_pred) accuracy ``` 0.9888888888888889 Nice! Now we have a classifier with a quite competitive accuracy. The state-of-the-art (on a very similar task) has accuracy around $0.9979$, achieved by using Neural Networks, which we will see in the next Lab. Stay tuned!
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"
Formal statement is: lemma inverse_scaleR_times [simp]: fixes a :: "'a::real_algebra_1" shows "(1 / numeral v) *\<^sub>R (numeral w * a) = (numeral w / numeral v) *\<^sub>R a" Informal statement is: For any real algebraic type $a$, and any numerals $v$ and $w$, we have $(1/v) \cdot (w \cdot a) = (w/v) \cdot a$.
(* File: Liouville_Numbers.thy Author: Manuel Eberl <[email protected]> The definition of Liouville numbers and their standard construction, plus the proof that any Liouville number is transcendental. *) theory Liouville_Numbers imports Complex_Main "HOL-Computational_Algebra.Polynomial" Liouville_Numbers_Misc begin (* TODO: Move definition of algebraic numbers out of Algebraic_Numbers to reduce unnecessary dependencies. *) text \<open> A Liouville number is a real number that can be approximated well -- but not perfectly -- by a sequence of rational numbers. ``Well``, in this context, means that the error of the $n$-th rational in the sequence is bounded by the $n$-th power of its denominator. Our approach will be the following: \begin{itemize} \item Liouville numbers cannot be rational. \item Any irrational algebraic number cannot be approximated in the Liouville sense \item Therefore, all Liouville numbers are transcendental. \item The standard construction fulfils all the properties of Liouville numbers. \end{itemize} \<close> subsection \<open>Definition of Liouville numbers\<close> text \<open> The following definitions and proofs are largely adapted from those in the Wikipedia article on Liouville numbers.~\<^cite>\<open>"wikipedia"\<close> \<close> text \<open> A Liouville number is a real number that can be approximated well -- but not perfectly -- by a sequence of rational numbers. The error of the $n$-th term $\frac{p_n}{q_n}$ is at most $q_n^{-n}$, where $p_n\in\isasymint$ and $q_n \in\isasymint_{\geq 2}$. We will say that such a number can be approximated in the Liouville sense. \<close> locale liouville = fixes x :: real and p q :: "nat \<Rightarrow> int" assumes approx_int_pos: "abs (x - p n / q n) > 0" and denom_gt_1: "q n > 1" and approx_int: "abs (x - p n / q n) < 1 / of_int (q n) ^ n" text \<open> First, we show that any Liouville number is irrational. \<close> lemma (in liouville) irrational: "x \<notin> \<rat>" proof assume "x \<in> \<rat>" then obtain c d :: int where d: "x = of_int c / of_int d" "d > 0" by (elim Rats_cases') simp define n where "n = Suc (nat \<lceil>log 2 d\<rceil>)" note q_gt_1 = denom_gt_1[of n] have neq: "c * q n \<noteq> d * p n" proof assume "c * q n = d * p n" hence "of_int (c * q n) = of_int (d * p n)" by (simp only: ) with approx_int_pos[of n] d q_gt_1 show False by (auto simp: field_simps) qed hence abs_pos: "0 < abs (c * q n - d * p n)" by simp from q_gt_1 d have "of_int d = 2 powr log 2 d" by (subst powr_log_cancel) simp_all also from d have "log 2 (of_int d) \<ge> log 2 1" by (subst log_le_cancel_iff) simp_all hence "2 powr log 2 d \<le> 2 powr of_nat (nat \<lceil>log 2 d\<rceil>)" by (intro powr_mono) simp_all also have "\<dots> = of_int (2 ^ nat \<lceil>log 2 d\<rceil>)" by (subst powr_realpow) simp_all finally have "d \<le> 2 ^ nat \<lceil>log 2 (of_int d)\<rceil>" by (subst (asm) of_int_le_iff) also have "\<dots> * q n \<le> q n ^ Suc (nat \<lceil>log 2 (of_int d)\<rceil>)" by (subst power_Suc, subst mult.commute, intro mult_left_mono power_mono, insert q_gt_1) simp_all also from q_gt_1 have "\<dots> = q n ^ n" by (simp add: n_def) finally have "1 / of_int (q n ^ n) \<le> 1 / real_of_int (d * q n)" using q_gt_1 d by (intro divide_left_mono Rings.mult_pos_pos of_int_pos, subst of_int_le_iff) simp_all also have "\<dots> \<le> of_int (abs (c * q n - d * p n)) / real_of_int (d * q n)" using q_gt_1 d abs_pos by (intro divide_right_mono) (linarith, simp) also have "\<dots> = abs (x - of_int (p n) / of_int (q n))" using q_gt_1 d(2) by (simp_all add: divide_simps d(1) mult_ac) finally show False using approx_int[of n] by simp qed text \<open> Next, any irrational algebraic number cannot be approximated with rational numbers in the Liouville sense. \<close> lemma liouville_irrational_algebraic: fixes x :: real assumes irrationsl: "x \<notin> \<rat>" and "algebraic x" obtains c :: real and n :: nat where "c > 0" and "\<And>(p::int) (q::int). q > 0 \<Longrightarrow> abs (x - p / q) > c / of_int q ^ n" proof - from \<open>algebraic x\<close> obtain p where p: "\<And>i. coeff p i \<in> \<int>" "p \<noteq> 0" "poly p x = 0" by (elim algebraicE) blast define n where "n = degree p" \<comment> \<open>The derivative of @{term p} is bounded within @{term "{x-1..x+1}"}.\<close> let ?f = "\<lambda>t. \<bar>poly (pderiv p) t\<bar>" define M where "M = (SUP t\<in>{x-1..x+1}. ?f t)" define roots where "roots = {x. poly p x = 0} - {x}" define A_set where "A_set = {1, 1/M} \<union> {abs (x' - x) |x'. x' \<in> roots}" define A' where "A' = Min A_set" define A where "A = A' / 2" \<comment> \<open>We define @{term A} to be a positive real number that is less than @{term 1}, @{term "1/M"} and any distance from @{term x} to another root of @{term p}.\<close> \<comment> \<open>Properties of @{term M}, our upper bound for the derivative of @{term p}:\<close> have "\<exists>s\<in>{x-1..x+1}. \<forall>y\<in>{x-1..x+1}. ?f s \<ge> ?f y" by (intro continuous_attains_sup) (auto intro!: continuous_intros) hence bdd: "bdd_above (?f ` {x-1..x+1})" by auto have M_pos: "M > 0" proof - from p have "pderiv p \<noteq> 0" by (auto dest!: pderiv_iszero) hence "finite {x. poly (pderiv p) x = 0}" using poly_roots_finite by blast moreover have "\<not>finite {x-1..x+1}" by (simp add: infinite_Icc) ultimately have "\<not>finite ({x-1..x+1} - {x. poly (pderiv p) x = 0})" by simp hence "{x-1..x+1} - {x. poly (pderiv p) x = 0} \<noteq> {}" by (intro notI) simp then obtain t where t: "t \<in> {x-1..x+1}" and "poly (pderiv p) t \<noteq> 0" by blast hence "0 < ?f t" by simp also from t and bdd have "\<dots> \<le> M" unfolding M_def by (rule cSUP_upper) finally show "M > 0" . qed have M_sup: "?f t \<le> M" if "t \<in> {x-1..x+1}" for t proof - from that and bdd show "?f t \<le> M" unfolding M_def by (rule cSUP_upper) qed \<comment> \<open>Properties of @{term A}:\<close> from p poly_roots_finite[of p] have "finite A_set" unfolding A_set_def roots_def by simp have "x \<notin> roots" unfolding roots_def by auto hence "A' > 0" using Min_gr_iff[OF \<open>finite A_set\<close>, folded A'_def, of 0] by (auto simp: A_set_def M_pos) hence A_pos: "A > 0" by (simp add: A_def) from \<open>A' > 0\<close> have "A < A'" by (simp add: A_def) moreover from Min_le[OF \<open>finite A_set\<close>, folded A'_def] have "A' \<le> 1" "A' \<le> 1/M" "\<And>x'. x' \<noteq> x \<Longrightarrow> poly p x' = 0 \<Longrightarrow> A' \<le> abs (x' - x)" unfolding A_set_def roots_def by auto ultimately have A_less: "A < 1" "A < 1/M" "\<And>x'. x' \<noteq> x \<Longrightarrow> poly p x' = 0 \<Longrightarrow> A < abs (x' - x)" by fastforce+ \<comment> \<open>Finally: no rational number can approximate @{term x} ``well enough''.\<close> have "\<forall>(a::int) (b :: int). b > 0 \<longrightarrow> \<bar>x - of_int a / of_int b\<bar> > A / of_int b ^ n" proof (intro allI impI, rule ccontr) fix a b :: int assume b: "b > 0" and "\<not>(A / of_int b ^ n < \<bar>x - of_int a / of_int b\<bar>)" hence ab: "abs (x - of_int a / of_int b) \<le> A / of_int b ^ n" by simp also from A_pos b have "A / of_int b ^ n \<le> A / 1" by (intro divide_left_mono) simp_all finally have ab': "abs (x - a / b) \<le> A" by simp also have "\<dots> \<le> 1" using A_less by simp finally have ab'': "a / b \<in> {x-1..x+1}" by auto have no_root: "poly p (a / b) \<noteq> 0" proof assume "poly p (a / b) = 0" moreover from \<open>x \<notin> \<rat>\<close> have "x \<noteq> a / b" by auto ultimately have "A < abs (a / b - x)" using A_less(3) by simp with ab' show False by simp qed have "\<exists>x0\<in>{x-1..x+1}. poly p (a / b) - poly p x = (a / b - x) * poly (pderiv p) x0" using ab'' by (intro poly_MVT') (auto simp: min_def max_def) with p obtain x0 :: real where x0: "x0 \<in> {x-1..x+1}" "poly p (a / b) = (a / b - x) * poly (pderiv p) x0" by auto from x0(2) no_root have deriv_pos: "poly (pderiv p) x0 \<noteq> 0" by auto from b p no_root have p_ab: "abs (poly p (a / b)) \<ge> 1 / of_int b ^ n" unfolding n_def by (intro int_poly_rat_no_root_ge) note ab also from A_less b have "A / of_int b ^ n < (1/M) / of_int b ^ n" by (intro divide_strict_right_mono) simp_all also have "\<dots> = (1 / b ^ n) / M" by simp also from M_pos ab p_ab have "\<dots> \<le> abs (poly p (a / b)) / M" by (intro divide_right_mono) simp_all also from deriv_pos M_pos x0(1) have "\<dots> \<le> abs (poly p (a / b)) / abs (poly (pderiv p) x0)" by (intro divide_left_mono M_sup) simp_all also have "\<bar>poly p (a / b)\<bar> = \<bar>a / b - x\<bar> * \<bar>poly (pderiv p) x0\<bar>" by (subst x0(2)) (simp add: abs_mult) with deriv_pos have "\<bar>poly p (a / b)\<bar> / \<bar>poly (pderiv p) x0\<bar> = \<bar>x - a / b\<bar>" by (subst nonzero_divide_eq_eq) simp_all finally show False by simp qed with A_pos show ?thesis using that[of A n] by blast qed text \<open> Since Liouville numbers are irrational, but can be approximated well by rational numbers in the Liouville sense, they must be transcendental. \<close> lemma (in liouville) transcendental: "\<not>algebraic x" proof assume "algebraic x" from liouville_irrational_algebraic[OF irrational this] obtain c n where cn: "c > 0" "\<And>p q. q > 0 \<Longrightarrow> c / real_of_int q ^ n < \<bar>x - real_of_int p / real_of_int q\<bar>" by auto define r where "r = nat \<lceil>log 2 (1 / c)\<rceil>" define m where "m = n + r" from cn(1) have "(1/c) = 2 powr log 2 (1/c)" by (subst powr_log_cancel) simp_all also have "log 2 (1/c) \<le> of_nat (nat \<lceil>log 2 (1/c)\<rceil>)" by linarith hence "2 powr log 2 (1/c) \<le> 2 powr \<dots>" by (intro powr_mono) simp_all also have "\<dots> = 2 ^ r" unfolding r_def by (simp add: powr_realpow) finally have "1 / (2^r) \<le> c" using cn(1) by (simp add: field_simps) have "abs (x - p m / q m) < 1 / of_int (q m) ^ m" by (rule approx_int) also have "\<dots> = (1 / of_int (q m) ^ r) * (1 / real_of_int (q m) ^ n)" by (simp add: m_def power_add) also from denom_gt_1[of m] have "1 / real_of_int (q m) ^ r \<le> 1 / 2 ^ r" by (intro divide_left_mono power_mono) simp_all also have "\<dots> \<le> c" by fact finally have "abs (x - p m / q m) < c / of_int (q m) ^ n" using denom_gt_1[of m] by - (simp_all add: divide_right_mono) with cn(2)[of "q m" "p m"] denom_gt_1[of m] show False by simp qed subsection \<open>Standard construction for Liouville numbers\<close> text \<open> We now define the standard construction for Liouville numbers. \<close> definition standard_liouville :: "(nat \<Rightarrow> int) \<Rightarrow> int \<Rightarrow> real" where "standard_liouville p q = (\<Sum>k. p k / of_int q ^ fact (Suc k))" lemma standard_liouville_summable: fixes p :: "nat \<Rightarrow> int" and q :: int assumes "q > 1" "range p \<subseteq> {0..<q}" shows "summable (\<lambda>k. p k / of_int q ^ fact (Suc k))" proof (rule summable_comparison_test') from assms(1) show "summable (\<lambda>n. (1 / q) ^ n)" by (intro summable_geometric) simp_all next fix n :: nat from assms have "p n \<in> {0..<q}" by blast with assms(1) have "norm (p n / of_int q ^ fact (Suc n)) \<le> q / of_int q ^ (fact (Suc n))" by (auto simp: field_simps) also from assms(1) have "\<dots> = 1 / of_int q ^ (fact (Suc n) - 1)" by (subst power_diff) (auto simp del: fact_Suc) also have "Suc n \<le> fact (Suc n)" by (rule fact_ge_self) with assms(1) have "1 / real_of_int q ^ (fact (Suc n) - 1) \<le> 1 / of_int q ^ n" by (intro divide_left_mono power_increasing) (auto simp del: fact_Suc simp add: algebra_simps) finally show "norm (p n / of_int q ^ fact (Suc n)) \<le> (1 / q) ^ n" by (simp add: power_divide) qed lemma standard_liouville_sums: assumes "q > 1" "range p \<subseteq> {0..<q}" shows "(\<lambda>k. p k / of_int q ^ fact (Suc k)) sums standard_liouville p q" using standard_liouville_summable[OF assms] unfolding standard_liouville_def by (simp add: summable_sums) text \<open> Now we prove that the standard construction indeed yields Liouville numbers. \<close> lemma standard_liouville_is_liouville: assumes "q > 1" "range p \<subseteq> {0..<q}" "frequently (\<lambda>n. p n \<noteq> 0) sequentially" defines "b \<equiv> \<lambda>n. q ^ fact (Suc n)" defines "a \<equiv> \<lambda>n. (\<Sum>k\<le>n. p k * q ^ (fact (Suc n) - fact (Suc k)))" shows "liouville (standard_liouville p q) a b" proof fix n :: nat from assms(1) have "1 < q ^ 1" by simp also from assms(1) have "\<dots> \<le> b n" unfolding b_def by (intro power_increasing) (simp_all del: fact_Suc) finally show "b n > 1" . note summable = standard_liouville_summable[OF assms(1,2)] let ?S = "\<Sum>k. p (k + n + 1) / of_int q ^ (fact (Suc (k + n + 1)))" let ?C = "(q - 1) / of_int q ^ (fact (n+2))" have "a n / b n = (\<Sum>k\<le>n. p k * (of_int q ^ (fact (n+1) - fact (k+1)) / of_int q ^ (fact (n+1))))" by (simp add: a_def b_def sum_divide_distrib of_int_sum) also have "\<dots> = (\<Sum>k\<le>n. p k / of_int q ^ (fact (Suc k)))" by (intro sum.cong refl, subst inverse_divide [symmetric], subst power_diff [symmetric]) (insert assms(1), simp_all add: divide_simps fact_mono_nat del: fact_Suc) also have "standard_liouville p q - \<dots> = ?S" unfolding standard_liouville_def by (subst diff_eq_eq) (intro suminf_split_initial_segment' summable) finally have "abs (standard_liouville p q - a n / b n) = abs ?S" by (simp only: ) moreover from assms have "?S \<ge> 0" by (intro suminf_nonneg allI divide_nonneg_pos summable_ignore_initial_segment summable) force+ ultimately have eq: "abs (standard_liouville p q - a n / b n) = ?S" by simp also have "?S \<le> (\<Sum>k. ?C * (1 / q) ^ k)" proof (intro suminf_le allI summable_ignore_initial_segment summable) from assms show "summable (\<lambda>k. ?C * (1 / q) ^ k)" by (intro summable_mult summable_geometric) simp_all next fix k :: nat from assms have "p (k + n + 1) \<le> q - 1" by force with \<open>q > 1\<close> have "p (k + n + 1) / of_int q ^ fact (Suc (k + n + 1)) \<le> (q - 1) / of_int q ^ (fact (Suc (k + n + 1)))" by (intro divide_right_mono) (simp_all del: fact_Suc) also from \<open>q > 1\<close> have "\<dots> \<le> (q - 1) / of_int q ^ (fact (n+2) + k)" using fact_ineq[of "n+2" k] by (intro divide_left_mono power_increasing) (simp_all add: add_ac) also have "\<dots> = ?C * (1 / q) ^ k" by (simp add: field_simps power_add del: fact_Suc) finally show "p (k + n + 1) / of_int q ^ fact (Suc (k + n + 1)) \<le> \<dots>" . qed also from assms have "\<dots> = ?C * (\<Sum>k. (1 / q) ^ k)" by (intro suminf_mult summable_geometric) simp_all also from assms have "(\<Sum>k. (1 / q) ^ k) = 1 / (1 - 1 / q)" by (intro suminf_geometric) simp_all also from assms(1) have "?C * \<dots> = of_int q ^ 1 / of_int q ^ fact (n + 2)" by (simp add: field_simps) also from assms(1) have "\<dots> \<le> of_int q ^ fact (n + 1) / of_int q ^ fact (n + 2)" by (intro divide_right_mono power_increasing) (simp_all add: field_simps del: fact_Suc) also from assms(1) have "\<dots> = 1 / (of_int q ^ (fact (n + 2) - fact (n + 1)))" by (subst power_diff) simp_all also have "fact (n + 2) - fact (n + 1) = (n + 1) * fact (n + 1)" by (simp add: algebra_simps) also from assms(1) have "1 / (of_int q ^ \<dots>) < 1 / (real_of_int q ^ (fact (n + 1) * n))" by (intro divide_strict_left_mono power_increasing mult_right_mono) simp_all also have "\<dots> = 1 / of_int (b n) ^ n" by (simp add: power_mult b_def power_divide del: fact_Suc) finally show "\<bar>standard_liouville p q - a n / b n\<bar> < 1 / of_int (b n) ^ n" . from assms(3) obtain k where k: "k \<ge> n + 1" "p k \<noteq> 0" by (auto simp: frequently_def eventually_at_top_linorder) define k' where "k' = k - n - 1" from assms k have "p k \<ge> 0" by force with k assms have k': "p (k' + n + 1) > 0" unfolding k'_def by force with assms(1,2) have "?S > 0" by (intro suminf_pos2[of _ k'] summable_ignore_initial_segment summable) (force intro!: divide_pos_pos divide_nonneg_pos)+ with eq show "\<bar>standard_liouville p q - a n / b n\<bar> > 0" by (simp only: ) qed text \<open> We can now show our main result: any standard Liouville number is transcendental. \<close> theorem transcendental_standard_liouville: assumes "q > 1" "range p \<subseteq> {0..<q}" "frequently (\<lambda>k. p k \<noteq> 0) sequentially" shows "\<not>algebraic (standard_liouville p q)" proof - from assms interpret liouville "standard_liouville p q" "\<lambda>n. (\<Sum>k\<le>n. p k * q ^ (fact (Suc n) - fact (Suc k)))" "\<lambda>n. q ^ fact (Suc n)" by (rule standard_liouville_is_liouville) from transcendental show ?thesis . qed text \<open> In particular: The the standard construction for constant sequences, such as the ``classic'' Liouville constant $\sum_{n=1}^\infty 10^{-n!} = 0.11000100\ldots$, are transcendental. This shows that Liouville numbers exists and therefore gives a concrete and elementary proof that transcendental numbers exist. \<close> corollary transcendental_standard_standard_liouville: "a \<in> {0<..<b} \<Longrightarrow> \<not>algebraic (standard_liouville (\<lambda>_. int a) (int b))" by (intro transcendental_standard_liouville) auto corollary transcendental_liouville_constant: "\<not>algebraic (standard_liouville (\<lambda>_. 1) 10)" by (intro transcendental_standard_liouville) auto end
Require Import GeoCoq.Axioms.continuity_axioms. Require Import GeoCoq.Tarski_dev.Definitions. Require Import Logic.ChoiceFacts. Section first_order. Context `{Tn:Tarski_neutral_dimensionless}. (** Dedekind's axiom of continuity implies the Tarski's axiom schema of continuity *) Lemma dedekind__fod : dedekind_s_axiom -> first_order_dedekind. Proof. intros dedekind Alpha Beta HAlpha HBeta HA. apply dedekind, HA. Qed. (** This is a type whose members describe first-order formulas *) Inductive tFOF := eq_fof1 : Tpoint -> Tpoint -> tFOF | bet_fof1 : Tpoint -> Tpoint -> Tpoint -> tFOF | cong_fof1 : Tpoint -> Tpoint -> Tpoint -> Tpoint -> tFOF | not_fof1 : tFOF -> tFOF | and_fof1 : tFOF -> tFOF -> tFOF | or_fof1 : tFOF -> tFOF -> tFOF | implies_fof1 : tFOF -> tFOF -> tFOF | forall_fof1 : (Tpoint -> tFOF) -> tFOF | exists_fof1 : (Tpoint -> tFOF) -> tFOF. (** This function interperts tFOF elements as Prop *) Fixpoint fof1_prop (F:tFOF) := match F with eq_fof1 A B => A = B | bet_fof1 A B C => Bet A B C | cong_fof1 A B C D => Cong A B C D | not_fof1 F1 => ~ fof1_prop F1 | and_fof1 F1 F2 => fof1_prop F1 /\ fof1_prop F2 | or_fof1 F1 F2 => fof1_prop F1 \/ fof1_prop F2 | implies_fof1 F1 F2 => fof1_prop F1 -> fof1_prop F2 | forall_fof1 P => forall A, fof1_prop (P A) | exists_fof1 P => exists A, fof1_prop (P A) end. (** Every first-order formula is equivalent to a Prop built with fof1_prop *) Lemma fof__fof1 : FunctionalChoice_on Tpoint tFOF -> forall F, FOF F -> exists F1, F <-> fof1_prop F1 . Proof. intros choice F HFOF. induction HFOF. - exists (eq_fof1 A B); intuition. - exists (bet_fof1 A B C); intuition. - exists (cong_fof1 A B C D); intuition. - destruct IHHFOF as [F1]. exists (not_fof1 F1). simpl; intuition. - destruct IHHFOF1 as [F1]; destruct IHHFOF2 as [F2]; exists (and_fof1 F1 F2); simpl; intuition. - destruct IHHFOF1 as [F1]; destruct IHHFOF2 as [F2]; exists (or_fof1 F1 F2); simpl; intuition. - destruct IHHFOF1 as [F1]; destruct IHHFOF2 as [F2]; exists (implies_fof1 F1 F2); simpl; intuition. - destruct (choice (fun A => (fun F1 => P A <-> fof1_prop F1)) H0) as [f]. exists (forall_fof1 f); simpl. split; intros HH A; apply H1, HH. - destruct (choice (fun A => (fun F1 => P A <-> fof1_prop F1)) H0) as [f]. exists (exists_fof1 f); simpl. split; intros [A HA]; exists A; apply H1, HA. Qed. (** Every Prop built with fof1_prop is a first-order formula *) Lemma fof1__fof : forall F1, FOF (fof1_prop F1). Proof. induction F1; constructor; assumption. Qed. End first_order.
! S08B-cant-assert-keyword-nonnull.f90 ! In 'c_action_actual_arg_spec', assertion 'keyword' != NULL is incorrect. ! CASE B: rule for 'substr_range_or_arg_list_suffix', alternative 2. ! ! An alternate return specifier as the second or following argument ! in an actual argument list causes the front end to fail an assertion. ! The subroutine definition for reference below is commented out because ! it causes front end to fail another assertion before showing this bug. ! subroutine g(k, *) ! integer :: k ! end subroutine program p call g(0, *100) ! assertion failure: 'keyword' is null 100 continue end program
function F = uminus(F) %UMINUS Unary minus for CHEBFUN3 objects. % -F negates the CHEBFUN3 object F. % % G = UMINUS(F) is called for the syntax '-F'. % % See also CHEBFUN3/UPLUS and CHEBFUN3/MINUS. % Copyright 2017 by The University of Oxford and The Chebfun Developers. % See http://www.chebfun.org/ for Chebfun information. F.core = -F.core; end
/- Copyright (c) 2019 The Flypitch Project. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jesse Han, Floris van Doorn -/ import .bvm open lattice universe u local infix ` ⟹ `:65 := lattice.imp local infix ` ⇔ `:50 := lattice.biimp local prefix `p𝒫`:65 := pSet.powerset namespace bSet section extras variables {𝔹 : Type u} [nontrivial_complete_boolean_algebra 𝔹] @[simp, cleanup]lemma insert1_bval_none {u v : bSet 𝔹} : (bSet.insert1 u ({v})).bval none = ⊤ := by refl @[simp, cleanup]lemma insert1_bval_some {u v : bSet 𝔹} {i} : (bSet.insert1 u {v}).bval (some i) = (bval {v}) i := by refl @[simp, cleanup]lemma insert1_func_none {u v : bSet 𝔹} : (bSet.insert1 u ({v})).func none = u := by refl @[simp, cleanup]lemma insert1_func_some {u v : bSet 𝔹} {i} : (bSet.insert1 u ({v})).func (some i) = (func {v}) i := by refl @[simp]lemma mem_singleton {x : bSet 𝔹} : ⊤ ≤ x ∈ᴮ {x} := by {rw[mem_unfold], apply bv_use none, unfold singleton, simp} lemma eq_of_mem_singleton' {x y : bSet 𝔹} : y ∈ᴮ {x} ≤ x =ᴮ y := by {rw[mem_unfold], apply bv_Or_elim, intro i, cases i, simp[bv_eq_symm], repeat{cases i}} lemma eq_of_mem_singleton {x y : bSet 𝔹} {c : 𝔹} (h : c ≤ y ∈ᴮ {x}) : c ≤ x =ᴮ y := le_trans h (by apply eq_of_mem_singleton') lemma eq_mem_singleton {x y : bSet 𝔹} {Γ : 𝔹} : Γ ≤ y ∈ᴮ {x} → Γ ≤ y =ᴮ x := λ _, bv_symm $ eq_of_mem_singleton ‹_› lemma eq_zero_of_mem_one {x : bSet 𝔹} {Γ : 𝔹} : Γ ≤ x ∈ᴮ 1 → Γ ≤ x =ᴮ 0 := begin intro H_mem, suffices : Γ ≤ x ∈ᴮ {0}, by exact eq_mem_singleton this, apply bv_rw' (bv_symm one_eq_singleton_zero), simpa end lemma mem_singleton_of_eq {x y : bSet 𝔹} {c : 𝔹} {h : c ≤ x =ᴮ y} : c ≤ y ∈ᴮ {x} := begin unfold singleton, unfold has_insert.insert, rw[mem_insert], simp, apply le_sup_left_of_le, rwa[bv_eq_symm] end lemma eq_inserted_of_eq_singleton {x y z : bSet 𝔹} : {x} =ᴮ bSet.insert1 y {z} ≤ x =ᴮ y := begin rw[bv_eq_unfold], apply bv_specialize_left none, apply bv_specialize_right none, unfold singleton, simp, rw[inf_sup_right], apply bv_or_elim, apply inf_le_left, apply inf_le_right_of_le, simp[eq_of_mem_singleton'] end lemma insert1_symm (y z : bSet 𝔹) : ⊤ ≤ bSet.insert1 y {z} =ᴮ bSet.insert1 z {y} := begin rw[bv_eq_unfold], apply le_inf; bv_intro i; simp; cases i; simp[-top_le_iff], {simp[bv_or_right]}, {cases i; [simp, repeat{cases i}]}, {simp[bv_or_right]}, {cases i; [simp, repeat{cases i}]} end lemma eq_inserted_of_eq_singleton' {x y z : bSet 𝔹} : {x} =ᴮ bSet.insert1 y {z} ≤ x =ᴮ z := by {apply bv_have_true (insert1_symm y z), apply le_trans, apply bv_eq_trans, apply eq_inserted_of_eq_singleton} def binary_union (x y : bSet 𝔹) : bSet 𝔹 := bv_union {x,y} -- note: maybe it's better to define this as a fiber product with a coherency condition? def binary_inter (x y : bSet 𝔹) : bSet 𝔹 := ⟨x.type, x.func, λ i, x.bval i ⊓ (x.func i) ∈ᴮ y⟩ infix ` ∩ᴮ `:81 := _root_.bSet.binary_inter @[simp, cleanup] lemma binary_inter_bval {x y : bSet 𝔹} {i : x.type} : (x ∩ᴮ y).bval i = x.bval i ⊓ (x.func i) ∈ᴮ y := rfl @[simp, cleanup] lemma binary_inter_type {x y : bSet 𝔹} : (x ∩ᴮ y).type = x.type := rfl @[simp, cleanup] lemma binary_inter_func {x y : bSet 𝔹} {i} : (x ∩ᴮ y).func i = x.func i := rfl lemma mem_binary_inter_iff {x y z : bSet 𝔹} {Γ} : Γ ≤ z ∈ᴮ (x ∩ᴮ y) ↔ (Γ ≤ z ∈ᴮ x ∧ Γ ≤ z ∈ᴮ y) := begin refine ⟨_,_⟩; intro H, { rw[mem_unfold] at H, refine ⟨_,_⟩, {bv_cases_at H i H_i, rw[mem_unfold], apply bv_use i, refine le_inf _ _, { exact bv_and.left (bv_and.left ‹_›) }, { exact bv_and.right ‹_› }}, { simp only with cleanup at *, bv_cases_at H i H_i, rw[mem_unfold], bv_split, bv_split, rw[mem_unfold] at H_i_left_right, bv_cases_at H_i_left_right j H_j, apply bv_use j, bv_split, from le_inf ‹_› (by bv_cc) } }, { rcases H with ⟨H₁,H₂⟩, rw mem_unfold at H₁ ⊢, bv_cases_at H₁ i H_i, apply bv_use i, rw[binary_inter_bval], bv_split, bv_split_goal, bv_cc }, end lemma subset_binary_inter_iff {x y z : bSet 𝔹} {Γ} : Γ ≤ z ⊆ᴮ x ∩ᴮ y ↔ (Γ ≤ z ⊆ᴮ x ∧ Γ ≤ z ⊆ᴮ y) := begin refine ⟨_,_⟩; intro H, { refine ⟨_,_⟩, { rw subset_unfold' at H ⊢, bv_intro w, bv_imp_intro Hw, exact (mem_binary_inter_iff.mp (H w ‹_›)).left }, { rw subset_unfold' at H ⊢, bv_intro w, bv_imp_intro Hw, exact (mem_binary_inter_iff.mp (H w ‹_›)).right }}, { cases H with H₁ H₂, rw subset_unfold', bv_intro w, bv_imp_intro Hw, rw mem_binary_inter_iff, refine ⟨_,_⟩, { exact mem_of_mem_subset H₁ ‹_› }, { exact mem_of_mem_subset H₂ ‹_› }} end lemma binary_inter_symm {x y : bSet 𝔹} {Γ} : Γ ≤ x ∩ᴮ y =ᴮ y ∩ᴮ x := begin apply mem_ext; {bv_intro z, bv_imp_intro H_mem, simp[mem_binary_inter_iff] at H_mem ⊢, simp*} end lemma B_congr_binary_inter_left {y : bSet 𝔹} : B_congr (λ x, x ∩ᴮ y) := begin intros x₁ x₂ Γ H_eq, dsimp, apply mem_ext; {bv_intro z, bv_imp_intro H_mem, simp[mem_binary_inter_iff] at *, cases H_mem, exact ⟨by bv_cc, ‹_›⟩ } end lemma B_congr_binary_inter_right {y : bSet 𝔹} : B_congr (λ x, y ∩ᴮ x) := begin intros x₁ x₂ Γ H_eq, dsimp, apply mem_ext; {bv_intro z, bv_imp_intro H_mem, simp[mem_binary_inter_iff] at *, cases H_mem, exact ⟨‹_›, by bv_cc⟩ } end lemma binary_inter_subset_left {x y : bSet 𝔹} {Γ} : Γ ≤ x ∩ᴮ y ⊆ᴮ x := by { rw[subset_unfold'], bv_intro z, bv_imp_intro Hz, from (mem_binary_inter_iff.mp Hz).left } lemma binary_inter_subset_right {x y : bSet 𝔹} {Γ} : Γ ≤ x ∩ᴮ y ⊆ᴮ y := begin suffices this : ∀ z (H : Γ ≤ y ∩ᴮ x ⊆ᴮ z), Γ ≤ x ∩ᴮ y ⊆ᴮ z, from this _ binary_inter_subset_left, exact λ z _, @bv_rw' 𝔹 _ (x ∩ᴮ y) (y ∩ᴮ x) _ (binary_inter_symm) (λ w, w ⊆ᴮ z) (by simp) ‹_› end lemma unordered_pair_symm (x y : bSet 𝔹) {Γ : 𝔹} : Γ ≤ {x,y} =ᴮ {y,x} := begin apply mem_ext; unfold has_insert.insert bSet.insert1; bv_intro; bv_imp_intro; {simp at *, bv_or_elim_at H, apply le_sup_right_of_le, apply mem_singleton_of_eq, from bv_symm H.left, apply le_sup_left_of_le, rw[bv_eq_symm], apply eq_of_mem_singleton, from ‹_›} end lemma binary_union_symm {x y : bSet 𝔹} {Γ} : Γ ≤ binary_union x y =ᴮ binary_union y x := begin simp[binary_union], apply mem_ext; bv_intro z; bv_imp_intro, have := (bv_union_spec_split {x, y} z).mp ‹_›, rw[bv_union_spec_split], bv_cases_at this w, bv_split_at this_1, apply bv_use w, refine le_inf _ ‹_›, apply bv_rw' (unordered_pair_symm _ _), simp, from ‹_›, have := unordered_pair_symm x y, show 𝔹, from Γ_1, let a := _, let b := _, change Γ_1 ≤ a =ᴮ b at this, change Γ_1 ≤ z ∈ᴮ bv_union a, suffices : Γ_1 ≤ bv_union a =ᴮ bv_union b, by {apply bv_rw' this, simpa}, exact B_congr_bv_union ‹_› end /-- The successor operation on sets (in particular von Neumman ordinals) -/ @[reducible]def succ (x : bSet 𝔹) := bSet.insert1 x x @[simp]lemma subset_succ {x : bSet 𝔹} {Γ} : Γ ≤ x ⊆ᴮ (succ x) := by { rw subset_unfold', bv_intro z, bv_imp_intro Hz, erw mem_insert1, bv_tauto } lemma succ_eq_binary_union {x : bSet 𝔹} {Γ} : Γ ≤ succ x =ᴮ binary_union {x} x := begin simp[succ, binary_union], apply mem_ext, {bv_intro z, simp, bv_imp_intro, bv_or_elim_at H, apply bv_rw' H.left, simp, apply (bv_union_spec_split _ x).mpr, apply bv_use ({x} : bSet 𝔹), refine le_inf _ (le_trans (le_top) mem_singleton), change _ ≤ _ ∈ᴮ insert _ _, simp, apply le_sup_right_of_le, from le_trans (le_top) mem_singleton, apply (bv_union_spec_split _ z).mpr, apply bv_use x, refine le_inf _ ‹_›, change _ ≤ _ ∈ᴮ insert _ _, simp}, {bv_intro z, simp, bv_imp_intro, rw[bv_union_spec_split] at H, bv_cases_at H y, bv_split, change Γ_2 ≤ _ ∈ᴮ insert _ _ at H_1_left, simp at H_1_left, bv_or_elim_at H_1_left, apply le_sup_right_of_le, apply bv_rw' (bv_symm ‹_›), simp, from ‹_›, apply le_sup_left_of_le, have : Γ_3 ≤ {x} =ᴮ y, apply eq_of_mem_singleton, from ‹_›, suffices : Γ_3 ≤ z ∈ᴮ {x}, rw[bv_eq_symm], apply eq_of_mem_singleton, from ‹_›, apply bv_rw' this, simp, from ‹_›} end lemma succ_eq_binary_union' {x : bSet 𝔹} {Γ} : Γ ≤ succ x =ᴮ binary_union x {x} := by {apply bv_rw' (@binary_union_symm 𝔹 _ x {x} Γ), simp, from succ_eq_binary_union} @[reducible]def pair (x y : bSet 𝔹) : bSet 𝔹 := {{x}, {x,y}} @[simp]lemma subst_congr_pair_left {x z y : bSet 𝔹} : x =ᴮ z ≤ pair x y =ᴮ pair z y := begin unfold pair, have this₁ : x =ᴮ z ≤ {{x},{x,y}} =ᴮ {{z},{x,y}} := by simp*, have this₂ : x =ᴮ z ≤ {{z},{x,y}} =ᴮ {{z},{z,y}} := by simp*, apply bv_trans; from ‹_› end @[simp]lemma subst_congr_pair_left' {x z y : bSet 𝔹} {Γ : 𝔹} : Γ ≤ x=ᴮ z → Γ ≤ pair x y =ᴮ pair z y := poset_yoneda_inv Γ (subst_congr_pair_left) lemma subst_congr_pair_right {x y z : bSet 𝔹} : y =ᴮ z ≤ pair x y =ᴮ pair x z := by unfold pair; simp* lemma subst_congr_pair_right' {Γ} {x y z : bSet 𝔹} (H : Γ ≤ y =ᴮ z) : Γ ≤ pair x y =ᴮ pair x z := poset_yoneda_inv Γ (subst_congr_pair_right) ‹_› lemma pair_congr {x₁ x₂ y₁ y₂ : bSet 𝔹} {Γ : 𝔹} (H₁ : Γ ≤ x₁ =ᴮ y₁) (H₂ : Γ ≤ x₂ =ᴮ y₂) : Γ ≤ pair x₁ x₂ =ᴮ pair y₁ y₂ := begin apply bv_rw' H₁, {intros v₁ v₂, tidy_context, have : Γ_1 ≤ pair v₂ x₂ =ᴮ pair v₁ x₂, by {apply subst_congr_pair_left', rwa[bv_eq_symm]}, from bv_trans this a_right,}, apply bv_rw' H₂, {intros v₁ v₂, tidy_context, have : Γ_1 ≤ pair y₁ v₂ =ᴮ pair y₁ v₁, by {apply subst_congr_pair_right', rwa[bv_eq_symm]}, from bv_trans this a_right}, from bv_refl end @[simp]lemma B_congr_insert1_left {y : bSet 𝔹} : B_congr (λ x, bSet.insert1 x y) := λ _ _ _, poset_yoneda_inv _ subst_congr_insert1_left @[simp]lemma B_congr_insert1_right {y : bSet 𝔹} : B_congr (λ x, bSet.insert1 y x) := λ _ _ _, poset_yoneda_inv _ subst_congr_insert1_right @[simp]lemma B_congr_succ : B_congr (succ : bSet 𝔹 → bSet 𝔹) := λ x y, begin unfold succ, intros, have : Γ ≤ bSet.insert1 x x =ᴮ bSet.insert1 x y, by {simp*}, have : Γ ≤ bSet.insert1 x y =ᴮ bSet.insert1 y y, by {simp*}, bv_cc end @[simp]lemma B_congr_pair_left {y : bSet 𝔹} : B_congr (λ x, pair x y) := λ _ _ _, poset_yoneda_inv _ subst_congr_pair_left @[simp]lemma B_congr_pair_right {y : bSet 𝔹} : B_congr (λ x, pair y x) := λ _ _ _, poset_yoneda_inv _ subst_congr_pair_right @[simp]lemma B_ext_pair_left {ϕ : bSet 𝔹 → 𝔹} {H : B_ext ϕ} {x} : B_ext (λ z, ϕ ((λ w, pair w x) z)) := by simp[H] @[simp]lemma B_ext_pair_right {ϕ : bSet 𝔹 → 𝔹} {H : B_ext ϕ} {x} : B_ext (λ z, ϕ ((λ w, pair x w) z)) := by simp[H] example {y z : bSet 𝔹} : ⊤ ≤ ({y,z} : bSet 𝔹) =ᴮ ({z,y}) := insert1_symm _ _ @[simp]lemma B_ext_pair_mem_left {x y : bSet 𝔹} : B_ext (λ z, pair z x ∈ᴮ y) := B_ext_term (λ w, w ∈ᴮ y) (λ z, pair z x) @[simp]lemma B_ext_pair_mem_right {x y : bSet 𝔹} : B_ext (λ z, pair x z ∈ᴮ y) := B_ext_term (λ w, w ∈ᴮ y) (λ z, pair x z) lemma eq_of_eq_pair'_left {x z y : bSet 𝔹} : pair x y =ᴮ pair z y ≤ x =ᴮ z := begin unfold pair, unfold has_insert.insert, rw[bv_eq_unfold], fapply bv_specialize_left, exact some none, fapply bv_specialize_right, exact some none, simp, rw[inf_sup_right_left_eq], repeat{apply bv_or_elim}, {apply le_trans, apply inf_le_inf; apply eq_inserted_of_eq_singleton, {[smt] eblast_using[bv_eq_symm, bv_eq_trans]}}, {apply inf_le_right_of_le, apply le_trans, apply eq_of_mem_singleton', apply eq_of_eq_singleton, refl}, {apply inf_le_left_of_le, apply le_trans, apply eq_of_mem_singleton', apply eq_of_eq_singleton, rw[bv_eq_symm]}, {apply inf_le_left_of_le, apply le_trans, apply eq_of_mem_singleton', apply eq_of_eq_singleton, rw[bv_eq_symm]} end lemma inserted_eq_of_insert_eq {y v w : bSet 𝔹} : {v,y} =ᴮ {v,w} ≤ y =ᴮ w := begin unfold has_insert.insert, rw[bv_eq_unfold], apply bv_specialize_left none, apply bv_specialize_right none, change (⊤ ⟹ _) ⊓ (⊤ ⟹ _ : 𝔹) ≤ _, simp, rw[inf_sup_right_left_eq], repeat{apply bv_or_elim}, apply inf_le_left, apply inf_le_left, apply inf_le_right_of_le, rw[bv_eq_symm], apply le_trans, apply inf_le_inf; apply eq_of_mem_singleton', {[smt] eblast_using[bv_eq_symm, bv_eq_trans]} end lemma eq_of_eq_pair'_right {x z y : bSet 𝔹} : pair y x =ᴮ pair y z ≤ x =ᴮ z := begin unfold pair has_insert.insert, rw[bv_eq_unfold], apply bv_specialize_left none, apply bv_specialize_right none, unfold singleton, simp, rw[inf_sup_right_left_eq], repeat{apply bv_or_elim}, {apply inf_le_left_of_le, apply inserted_eq_of_insert_eq}, {apply inf_le_left_of_le, apply inserted_eq_of_insert_eq}, {apply inf_le_right_of_le, rw[bv_eq_symm], apply inserted_eq_of_insert_eq}, {apply le_trans, apply inf_le_inf; apply eq_of_mem_singleton', apply le_trans, apply inf_le_inf; apply eq_inserted_of_eq_singleton, rw[bv_eq_symm], apply bv_eq_trans} end run_cmd do mk_simp_attr `dnf, mk_simp_attr `cnf attribute [dnf] inf_sup_left inf_sup_right attribute [cnf] sup_inf_left sup_inf_right /- Taken together, eq_of_eq_pair_left and eq_of_eq_pair_right say that x = v and y = w if and only if pair x y = pair v w -/ theorem eq_of_eq_pair_left {x y v w: bSet 𝔹} : pair x y =ᴮ pair v w ≤ x =ᴮ v := begin unfold pair has_insert.insert, rw[bv_eq_unfold], apply bv_specialize_left none, apply bv_specialize_right (some none), unfold singleton, simp, simp only with dnf, repeat{apply bv_or_elim}, {apply inf_le_right_of_le, apply le_trans, apply eq_inserted_of_eq_singleton', rw[bv_eq_symm]}, {apply inf_le_left_of_le, rw[mem_unfold], apply bv_Or_elim, intro i, cases i, apply inf_le_right_of_le, simp, rw[bv_eq_symm], apply le_trans, apply eq_inserted_of_eq_singleton', rw[bv_eq_symm], repeat{cases i}}, {apply inf_le_right_of_le, apply le_trans, fapply eq_of_mem_singleton, from {x}, from {v}, refl, apply eq_of_eq_singleton, refl}, {apply inf_le_right_of_le, apply le_trans, fapply eq_of_mem_singleton, from {x}, from {v}, refl, apply eq_of_eq_singleton, refl} end lemma eq_of_eq_pair_left' {x y v w : bSet 𝔹} {Γ} : Γ ≤ pair x y =ᴮ pair v w → Γ ≤ x =ᴮ v := poset_yoneda_inv Γ eq_of_eq_pair_left theorem eq_of_eq_pair_right {x y v w: bSet 𝔹} : pair x y =ᴮ pair v w ≤ y =ᴮ w := begin apply bv_have, apply eq_of_eq_pair_left, apply le_trans, show 𝔹, from pair v y =ᴮ pair v w, rw[inf_comm], apply le_trans, apply inf_le_inf, swap, refl, apply subst_congr_pair_left, exact y, rw[bv_eq_symm], apply bv_eq_trans, apply eq_of_eq_pair'_right end lemma eq_of_eq_pair_right' {x y v w : bSet 𝔹} {Γ} : Γ ≤ pair x y =ᴮ pair v w → Γ ≤ y =ᴮ w := poset_yoneda_inv Γ eq_of_eq_pair_right lemma eq_of_eq_pair {x y z w : bSet 𝔹} {Γ : 𝔹} (H_eq : Γ ≤ pair x y =ᴮ pair z w) : Γ ≤ x =ᴮ z ∧ Γ ≤ y =ᴮ w := ⟨eq_of_eq_pair_left' ‹_›, eq_of_eq_pair_right' ‹_›⟩ lemma pair_eq_pair_iff {x y x' y' : bSet 𝔹} {Γ : 𝔹} : Γ ≤ pair x y =ᴮ pair x' y' ↔ Γ ≤ x =ᴮ x' ∧ Γ ≤ y =ᴮ y' := iff.intro (λ _, eq_of_eq_pair ‹_›) (λ ⟨_,_⟩, pair_congr ‹_› ‹_›) @[reducible]def prod (v w : bSet 𝔹) : bSet 𝔹 := ⟨v.type × w.type, λ a, pair (v.func a.1) (w.func a.2), λ a, (v.bval a.1) ⊓ (w.bval a.2)⟩ @[simp, cleanup]lemma prod_type {v w : bSet 𝔹} : (prod v w).type = (v.type × w.type) := by refl @[simp, cleanup]lemma prod_func {v w : bSet 𝔹} {pr} : (prod v w).func pr = pair (v.func (pr.1)) (w.func (pr.2)) := by refl @[simp, cleanup]lemma prod_bval {v w : bSet 𝔹} {a b} : (prod v w).bval (a,b) = v.bval a ⊓ w.bval b := by refl @[simp, cleanup]lemma prod_type_forall {v w : bSet 𝔹} {ϕ : (prod v w).type → 𝔹} : (⨅(z:(prod v w).type), ϕ z) = ⨅(z : v.type × w.type), ϕ z := by refl @[simp]lemma prod_check_bval {x y : pSet.{u}} {pr} : (prod x̌ y̌ : bSet 𝔹).bval pr = ⊤ := begin dsimp only with cleanup, simp end lemma prod_mem_old {v w x y : bSet 𝔹} : x ∈ᴮ v ⊓ y ∈ᴮ w ≤ pair x y ∈ᴮ prod v w := begin simp[pair, prod], simp only[mem_unfold], apply bv_cases_left, intro i, apply bv_cases_right, intro j, apply bv_use (i,j), tidy, {rw[inf_assoc], apply inf_le_left}, {rw[inf_comm], simp [inf_assoc]}, {let a := _, let b := _, change (bval v i ⊓ a) ⊓ (bval w j ⊓ b) ≤ _, have : a ⊓ b ≤ {{x}, {x, y}} =ᴮ {{func v i}, {x,y}}, by simp*, have : a ⊓ b ≤ {{func v i}, {x,y}} =ᴮ {{func v i}, {func v i, func w j}}, by {apply subst_congr_insert1_left'', have this₁ : a ⊓ b ≤ {x,y} =ᴮ {func v i, y}, by simp*, have this₂ : a ⊓ b ≤ {func v i, y} =ᴮ {func v i, func w j}, by simp*, from bv_trans ‹_› ‹_›}, apply le_trans, show 𝔹, from a ⊓ b, by {ac_change (bval v i ⊓ bval w j) ⊓ (a ⊓ b) ≤ a ⊓ b, from inf_le_right}, from bv_trans ‹_› ‹_›} end lemma prod_mem {v w x y : bSet 𝔹} {Γ} : Γ ≤ x ∈ᴮ v → Γ ≤ y ∈ᴮ w → Γ ≤ pair x y ∈ᴮ prod v w := λ H₁ H₂, by {transitivity x ∈ᴮ v ⊓ y ∈ᴮ w, bv_split_goal, from prod_mem_old} lemma mem_left_of_prod_mem {v w x y : bSet 𝔹} {Γ : 𝔹} : Γ ≤ pair x y ∈ᴮ prod v w → Γ ≤ x ∈ᴮ v := begin intro H_pair_mem, rw[mem_unfold] at H_pair_mem, bv_cases_at H_pair_mem p, cases p with i j, dsimp at *, bv_split, rw[mem_unfold], apply bv_use i, replace H_pair_mem_1_right := eq_of_eq_pair_left' H_pair_mem_1_right, simp only [le_inf_iff] at *, simp* end lemma mem_right_of_prod_mem {v w x y : bSet 𝔹} {Γ : 𝔹} : Γ ≤ pair x y ∈ᴮ prod v w → Γ ≤ y ∈ᴮ w := begin intro H_pair_mem, rw[mem_unfold] at H_pair_mem, bv_cases_at H_pair_mem p, cases p with i j, dsimp at *, bv_split, rw[mem_unfold], apply bv_use j, replace H_pair_mem_1_right := eq_of_eq_pair_right' H_pair_mem_1_right, simp only [le_inf_iff] at *, simp* end @[simp]lemma mem_prod_iff {v w x y : bSet 𝔹} {Γ} : Γ ≤ pair x y ∈ᴮ prod v w ↔ (Γ ≤ x ∈ᴮ v ∧ Γ ≤ y ∈ᴮ w) := ⟨λ _, ⟨mem_left_of_prod_mem ‹_›, mem_right_of_prod_mem ‹_›⟩, λ ⟨_,_⟩, prod_mem ‹_› ‹_›⟩ @[simp]lemma mem_prod {v w x y : bSet 𝔹} {Γ} (H_mem₁ : Γ ≤ x ∈ᴮ v) (H_mem₂ : Γ ≤ y ∈ᴮ w) : Γ ≤ pair x y ∈ᴮ prod v w := mem_prod_iff.mpr (by simp*) @[simp]lemma B_congr_prod_left {y : bSet 𝔹} : B_congr (λ x, prod x y) := begin intros a b Γ H_eq, dsimp, rw bv_eq_unfold, refine le_inf _ _, { bv_intro pr, bv_imp_intro Hpr, erw mem_prod_iff, refine ⟨_,_⟩, { apply bv_rw' (bv_symm H_eq), simp, simp at Hpr, from mem.mk'' (Hpr.left) }, { simp at Hpr, from mem.mk'' (Hpr.right) }}, { bv_intro pr, bv_imp_intro Hpr, erw mem_prod_iff, refine ⟨_,_⟩, { apply bv_rw' (H_eq), simp, simp at Hpr, from mem.mk'' (Hpr.left) }, { simp at Hpr, from mem.mk'' (Hpr.right) } } end @[simp]lemma B_congr_prod_right {x : bSet 𝔹} : B_congr (λ y, prod x y) := begin intros a b Γ H_eq, dsimp, rw bv_eq_unfold, refine le_inf _ _, { bv_intro pr, bv_imp_intro Hpr, erw mem_prod_iff, refine ⟨_,_⟩, { apply bv_rw' (bv_symm H_eq), simp, simp at Hpr, from mem.mk'' (Hpr.left) }, { simp at Hpr, apply bv_rw' (bv_symm H_eq), simp, exact mem.mk'' Hpr.right }}, { bv_intro pr, bv_imp_intro Hpr, erw mem_prod_iff, refine ⟨_,_⟩, { apply bv_rw' (H_eq), simp, simp at Hpr, from mem.mk'' (Hpr.left) }, { simp at Hpr, apply bv_rw' (H_eq), simp, exact mem.mk'' Hpr.right } } end lemma prod_congr {x₁ x₂ y₁ y₂ : bSet 𝔹} {Γ} (H₁ : Γ ≤ x₁ =ᴮ x₂) (H₂ : Γ ≤ y₁ =ᴮ y₂) : Γ ≤ prod x₁ y₁ =ᴮ prod x₂ y₂ := begin have := B_congr_prod_left H₁, show bSet 𝔹, from y₁, dsimp at this, refine bv_trans this _, from B_congr_prod_right H₂ end lemma mem_prod_iff₂ {x y z : bSet 𝔹} {Γ} : Γ ≤ z ∈ᴮ prod x y ↔ ∃ (v) (Hv : Γ ≤ v ∈ᴮ x) (w) (Hw : Γ ≤ w ∈ᴮ y), Γ ≤ z =ᴮ pair v w := begin refine ⟨_,_⟩; intro H, swap, { rcases H with ⟨v,Hv,w,Hw,H_eq⟩, apply bv_rw' H_eq, simp, rw mem_prod_iff, simp* }, { suffices : Γ ≤ ⨆ v, v ∈ᴮ x ⊓ ⨆ w, w ∈ᴮ y ⊓ z =ᴮ pair v w, by {rcases (exists_convert this) with ⟨v, H'v⟩, use v, bv_split_at H'v, use ‹_›, rcases (exists_convert H'v_right) with ⟨w, H'w⟩, use w, bv_split_at H'w, from ⟨‹_›,‹_›⟩}, rw mem_unfold at H, bv_cases_at H pr Hpr, bv_split_at Hpr, apply bv_use (x.func pr.1), simp at Hpr_left, cases Hpr_left, refine le_inf _ _, { from mem.mk'' ‹_› }, { apply bv_use (y.func pr.2), refine le_inf _ _, { from mem.mk'' ‹_› }, { from Hpr_right } } } end lemma prod_ext {S₁ S₂ x y : bSet 𝔹} {Γ : 𝔹} (H₁ : Γ ≤ S₁ ⊆ᴮ prod x y) (H₂ : Γ ≤ S₂ ⊆ᴮ prod x y) (H_prod_ext : Γ ≤ ⨅ v, v ∈ᴮ x ⟹ ⨅ w, w∈ᴮ y ⟹ (pair v w ∈ᴮ S₁ ⇔ pair v w ∈ᴮ S₂)) : Γ ≤ S₁ =ᴮ S₂ := begin apply mem_ext, {bv_intro z, bv_imp_intro Hz_mem, have Hz_mem' : Γ_1 ≤ z ∈ᴮ prod x y := mem_of_mem_subset ‹_› ‹_›, rw mem_prod_iff₂ at Hz_mem', rcases Hz_mem' with ⟨v,Hv,w,Hw,H_eq⟩, replace H_prod_ext := H_prod_ext v, replace H_prod_ext := H_prod_ext ‹_›, replace H_prod_ext := H_prod_ext w, replace H_prod_ext := H_prod_ext ‹_›, bv_split_at H_prod_ext, apply bv_rw' H_eq, simp, have := bv_rw'' H_eq Hz_mem, exact H_prod_ext_left ‹_›}, {bv_intro z, bv_imp_intro Hz_mem, have Hz_mem' : Γ_1 ≤ z ∈ᴮ prod x y := mem_of_mem_subset H₂ ‹_›, rw mem_prod_iff₂ at Hz_mem', rcases Hz_mem' with ⟨v,Hv,w,Hw,H_eq⟩, replace H_prod_ext := H_prod_ext v, replace H_prod_ext := H_prod_ext ‹_›, replace H_prod_ext := H_prod_ext w, replace H_prod_ext := H_prod_ext ‹_›, bv_split_at H_prod_ext, apply bv_rw' H_eq, simp, have := bv_rw'' H_eq Hz_mem, exact H_prod_ext_right ‹_›} end @[simp]lemma check_singleton {x : pSet.{u}} {Γ : 𝔹} : Γ ≤ {x}̌ =ᴮ {x̌} := begin unfold singleton, unfold has_insert.insert, simp end @[simp]lemma check_unordered_pair {x y : pSet.{u}} {Γ} : Γ ≤ ({x,y})̌ =ᴮ ({x̌, y̌} : bSet 𝔹) := begin unfold has_insert.insert, simp end @[simp]lemma eq_unordered_pair_of_eq {a b c d : bSet 𝔹} {Γ} (H₁ : Γ ≤ a =ᴮ c) (H₂ : Γ ≤ b =ᴮ d) : Γ ≤ {a,b} =ᴮ {c,d} := begin have : _ ≤ {_, b} =ᴮ {_,b} := @subst_congr_insert1_right'' _ _ _ _ _ _ H₁, refine bv_trans this _, apply subst_congr_insert1_left', from ‹_› end lemma check_pair {x y : pSet.{u}} {Γ} : Γ ≤ (pSet.pair x y)̌ =ᴮ bSet.pair (x̌) (y̌ : bSet 𝔹) := begin unfold pSet.pair, unfold bSet.pair, have : Γ ≤ {{x}, {x, y}}̌ =ᴮ {{x}̌ , {x,y}̌ } := check_unordered_pair, refine bv_trans this _, refine eq_unordered_pair_of_eq _ _, simp, simp end lemma check_prod {x y : pSet.{u}} {Γ : 𝔹} : Γ ≤ (pSet.prod x y)̌ =ᴮ bSet.prod x̌ y̌ := begin rw bv_eq_unfold, refine le_inf _ _; bv_intro pr; bv_imp_intro Hbvpr, { cases pr with i j, rw mem_unfold, apply bv_use (check_cast.symm i, check_cast.symm j), refine le_inf (by simp) _, change Γ_1 ≤ (pSet.pair (x.func i) (y.func j))̌ =ᴮ pair _ _, refine bv_trans check_pair _, rw pair_eq_pair_iff, refine ⟨_,_⟩, { cases x, from bv_refl }, { cases y, from bv_refl }}, { cases pr with i j, change _ ≤ pair _ _ ∈ᴮ _, dsimp only, rw check_func, rw check_func, change _ ≤ (λ w, w ∈ᴮ (pSet.prod x y)̌ ) _, apply bv_rw' (bv_symm check_pair), simp, apply check_mem, simp [pSet.mem_prod_iff] } end -- /-- f is =ᴮ-extensional on x if for every w₁ and w₂ ∈ x, if w₁ =ᴮ w₂, then for every v₁ and v₂, if (w₁,v₁) ∈ f and (w₂,v₂) ∈ f, then v₁ =ᴮ v₂ -/ -- @[reducible]def is_extensional (x f : bSet 𝔹) : 𝔹 := -- ⨅w₁, w₁ ∈ᴮ x ⟹ (⨅w₂, w₂ ∈ᴮ x ⟹ (w₁ =ᴮ w₂ ⟹ ⨅v₁ v₂, (pair w₁ v₁ ∈ᴮ f ⊓ pair w₂ v₂ ∈ᴮ f) ⟹ v₁ =ᴮ v₂)) /-- f is =ᴮ-extensional if for every w₁ w₂ v₁ v₂, if pair (w₁ v₁) and pair (w₂ v₂) ∈ f and w₁ =ᴮ w₂, then v₁ =ᴮ v₂ -/ @[reducible]def is_func (f : bSet 𝔹) : 𝔹 := ⨅ w₁, ⨅w₂, ⨅v₁, ⨅ v₂, pair w₁ v₁ ∈ᴮ f ⊓ pair w₂ v₂ ∈ᴮ f ⟹ (w₁ =ᴮ w₂ ⟹ v₁ =ᴮ v₂) @[simp] lemma is_func_subset_of_is_func {f g : bSet 𝔹} {Γ} (H : Γ ≤ is_func f) (H_sub : Γ ≤ g ⊆ᴮ f) : Γ ≤ is_func g := begin bv_intro w₁, bv_intro w₂, bv_intro v₁, bv_intro v₂, bv_imp_intro H', replace H := H w₁ w₂ v₁ v₂, suffices this : Γ_1 ≤ pair w₁ v₁ ∈ᴮ f ⊓ pair w₂ v₂ ∈ᴮ f, by {exact H ‹_›}, bv_split, refine le_inf _ _; rw[subset_unfold'] at H_sub, exact H_sub (pair w₁ v₁) ‹_›, exact H_sub (pair w₂ v₂) ‹_› end @[reducible]def is_functional (f : bSet 𝔹) : 𝔹 := ⨅z, (⨆w, pair z w ∈ᴮ f) ⟹ (⨆w', ⨅w'', pair z w'' ∈ᴮ f ⟹ w' =ᴮ w'') lemma is_functional_of_is_func (f : bSet 𝔹) {Γ} (H : Γ ≤ is_func f) : Γ ≤ is_functional f := begin unfold is_functional, unfold is_func at H, bv_intro z, bv_imp_intro w_spec, bv_cases_at w_spec w, clear w_spec, replace H := H z z, apply bv_use w, bv_intro w', bv_imp_intro Hw', from H w w' (le_inf ‹_› ‹_›) (bv_refl) end @[reducible]def is_total (x y f : bSet 𝔹) : 𝔹 := (⨅w₁, w₁ ∈ᴮ x ⟹ ⨆w₂, w₂ ∈ᴮ y ⊓ pair w₁ w₂ ∈ᴮ f) -- bounded version of is_total @[reducible]def is_total' (x y f : bSet 𝔹) : 𝔹 := (⨅ i, x.bval i ⟹ ⨆j, y.bval j ⊓ pair (x.func i) (y.func j) ∈ᴮ f) lemma is_total_iff_is_total' {Γ : 𝔹} {x y f} : Γ ≤ is_total x y f ↔ Γ ≤ is_total' x y f := begin unfold is_total, rw ←bounded_forall, swap, {change B_ext _, apply B_ext_supr, intro i, apply B_ext_inf, simp, from B_ext_pair_mem_left}, refine ⟨_,_⟩; intro H, { bv_intro i, bv_imp_intro Hi, replace H := H i Hi, rw ←bounded_exists at H, swap, {change B_ext _, from B_ext_pair_mem_right }, from ‹_› }, { bv_intro i, bv_imp_intro Hi, replace H := H i Hi, rw ←bounded_exists, swap, { change B_ext _, from B_ext_pair_mem_right }, from ‹_› } end @[simp]lemma is_total_subset_of_is_total {S x y f : bSet 𝔹} {Γ} (H_is_total : Γ ≤ is_total x y f) (H_subset : Γ ≤ S ⊆ᴮ x) : Γ ≤ is_total S y f := by {simp*, intro z, bv_imp_intro Hz, from H_is_total z (mem_of_mem_subset ‹_› ‹_›)} /-- f is (more precisely, contains) a function from x to y if for every element of x, there exists an element of y such that the pair is in f, and f is a function -/ @[reducible]def is_func' (x y f : bSet 𝔹) : 𝔹 := is_func f ⊓ is_total x y f @[simp]lemma is_func_of_is_func' {x y f : bSet 𝔹} {Γ} (H : Γ ≤ is_func' x y f) : Γ ≤ is_func f := bv_and.left ‹_› lemma is_total_of_is_func' {x y f : bSet 𝔹} {Γ : 𝔹} (H_is_func' : Γ ≤ is_func' x y f) : Γ ≤ is_total x y f := bv_and.right ‹_› lemma is_func'_empty {Γ : 𝔹} {x} : Γ ≤ is_func' (∅ : bSet 𝔹) x ∅ := begin refine le_inf _ _, bv_intro x, bv_intro y, bv_intro z, bv_intro w, bv_imp_intro H, bv_exfalso, exact bot_of_mem_empty (bv_and.left H), apply forall_empty end -- aka function extensionality @[simp]lemma eq_of_is_func_of_eq {x y f x' y' : bSet 𝔹} {Γ : 𝔹} (H_is_func : Γ ≤ is_func f) (H_eq₁ : Γ ≤ x =ᴮ y) (H_mem₁ : Γ ≤ pair x x' ∈ᴮ f) (H_mem₂ : Γ ≤ pair y y' ∈ᴮ f) : Γ ≤ x' =ᴮ y' := H_is_func x y x' y' (le_inf ‹_› ‹_›) ‹_› -- aka function extensionality @[simp]lemma eq_of_is_func'_of_eq {a b x y f x' y' : bSet 𝔹} {Γ : 𝔹} (H_is_func' : Γ ≤ is_func' a b f) (H_eq₁ : Γ ≤ x =ᴮ y) (H_mem₁ : Γ ≤ pair x x' ∈ᴮ f) (H_mem₂ : Γ ≤ pair y y' ∈ᴮ f) : Γ ≤ x' =ᴮ y' := by {[smt] eblast_using [eq_of_is_func_of_eq, is_func_of_is_func']} @[simp]lemma is_func'_subset_of_is_func' {S x y f : bSet 𝔹} {Γ : 𝔹} (H_is_func : Γ ≤ is_func' x y f) (H_subset : Γ ≤ S ⊆ᴮ x) : Γ ≤ is_func' S y f := begin refine le_inf _ _, {[smt] eblast_using is_func_of_is_func'}, from is_total_subset_of_is_total (is_total_of_is_func' ‹_›) ‹_› end -- bounded image def image (x y f : bSet 𝔹) : bSet 𝔹 := subset.mk (λ j : y.type, ⨆ z, z ∈ᴮ x ⊓ pair z (y.func j) ∈ᴮ f) @[simp]lemma image_subset {x y f : bSet 𝔹} {Γ} : Γ ≤ (image x y f) ⊆ᴮ y := subset.mk_subset @[simp]lemma mem_image {x y a b f : bSet 𝔹} {Γ} (H_mem : Γ ≤ pair a b ∈ᴮ f) (H_mem'' : Γ ≤ a ∈ᴮ x) (H_mem' : Γ ≤ b ∈ᴮ y) : Γ ≤ b ∈ᴮ image x y f := begin rw[image, mem_subset.mk_iff], rw[mem_unfold] at H_mem', bv_cases_at H_mem' i Hi, apply bv_use i, bv_split_at Hi, refine le_inf ‹_› (le_inf _ ‹_›), apply bv_use a, refine le_inf ‹_› _, apply @bv_rw' _ _ _ _ _ (bv_symm Hi_right) (λ z, pair a z ∈ᴮ f), exact B_ext_pair_mem_right, from ‹_› end lemma mem_image_iff {x y b f : bSet 𝔹} {Γ} : Γ ≤ b ∈ᴮ image x y f ↔ (Γ ≤ b ∈ᴮ y ) ∧ Γ ≤ ⨆ z, z ∈ᴮ x ⊓ pair z b ∈ᴮ f := begin refine ⟨_,_⟩; intro H, refine ⟨_,_⟩, { from mem_of_mem_subset (image_subset) ‹_› }, { unfold image at H, rw mem_subset.mk_iff at H, bv_cases_at H i Hi, bv_split_at Hi, bv_split_at Hi_right, bv_cases_at Hi_right_left z Hz, apply bv_use z, refine le_inf (bv_and.left ‹_›) _, change _ ≤ (λ w, w ∈ᴮ f) _, apply bv_rw' Hi_left, simp, from bv_and.right Hz }, { cases H with _ H, bv_cases_at H z Hz, apply mem_image, from bv_and.right ‹_›, from bv_and.left ‹_›, from ‹_› }, end @[simp]lemma B_congr_image_left {y f : bSet 𝔹} : B_congr (λ x, image x y f) := begin intros x y Γ H_eq, refine mem_ext _ _, { bv_intro z, bv_imp_intro Hz, rw mem_image_iff at ⊢ Hz, rcases Hz with ⟨Hz_mem_y, H⟩, refine ⟨‹_›,_⟩, apply bv_rw' (bv_symm H_eq), simp, repeat { from ‹_› } }, { bv_intro z, bv_imp_intro Hz, rw mem_image_iff at ⊢ Hz, rcases Hz with ⟨Hz_mem_y, H⟩, refine ⟨‹_›,_⟩, apply bv_rw' H_eq, simp, repeat { from ‹_› } } end @[simp]lemma B_congr_image_right {x y : bSet 𝔹} : B_congr (λ f, image x y f) := begin intros x y Γ H_eq, refine mem_ext _ _, { bv_intro z, bv_imp_intro Hz, rw mem_image_iff at ⊢ Hz, rcases Hz with ⟨Hz_mem_y, H⟩, refine ⟨‹_›,_⟩, apply bv_rw' (bv_symm H_eq), simp, repeat { from ‹_› } }, { bv_intro z, bv_imp_intro Hz, rw mem_image_iff at ⊢ Hz, rcases Hz with ⟨Hz_mem_y, H⟩, refine ⟨‹_›,_⟩, apply bv_rw' H_eq, simp, repeat { from ‹_› } } end -- bounded preimage def preimage (x y f : bSet 𝔹) : bSet 𝔹 := subset.mk (λ i : x.type, ⨆ b, b ∈ᴮ y ⊓ pair (x.func i) b ∈ᴮ f) @[simp]lemma preimage_subset {x y f} {Γ : 𝔹} : Γ ≤ (preimage x y f) ⊆ᴮ x := subset.mk_subset @[simp]lemma mem_preimage {x y a b f : bSet 𝔹} {Γ} (H_mem : Γ ≤ pair a b ∈ᴮ f) (H_mem'' : Γ ≤ a ∈ᴮ x) (H_mem' : Γ ≤ b ∈ᴮ y) : Γ ≤ a ∈ᴮ preimage x y f := begin rw[preimage, mem_subset.mk_iff], rw[mem_unfold] at H_mem'', bv_cases_at H_mem'' i Hi, apply bv_use i, bv_split_at Hi, refine le_inf ‹_› (le_inf _ ‹_›), apply bv_use b, refine le_inf ‹_› _, apply @bv_rw' _ _ _ _ _ (bv_symm Hi_right) (λ z, pair z b ∈ᴮ f), exact B_ext_pair_mem_left, from ‹_› end /-- f is a function x → y if it is extensional, total, and is a subset of the product of x and y -/ @[reducible]def is_function (x y f : bSet 𝔹) : 𝔹 := is_func' x y f ⊓ (f ⊆ᴮ prod x y) @[simp]lemma B_ext_is_function_left {y f : bSet 𝔹} : B_ext (λ x, is_function x y f) := by simp[is_function] @[simp]lemma B_ext_is_function_right {x y: bSet 𝔹} : B_ext (λ f, is_function x y f) := by simp lemma is_func'_of_is_function {Γ : 𝔹} {x y f} (H_func : Γ ≤ is_function x y f) : Γ ≤ is_func' x y f := bv_and.left H_func lemma eq_of_is_function_of_eq {a b x y f x' y' : bSet 𝔹} {Γ : 𝔹} (H_is_function : Γ ≤ is_function a b f) (H_eq₁ : Γ ≤ x =ᴮ y) (H_mem₁ : Γ ≤ pair x x' ∈ᴮ f) (H_mem₂ : Γ ≤ pair y y' ∈ᴮ f) : Γ ≤ x' =ᴮ y' := by {apply eq_of_is_func'_of_eq, from is_func'_of_is_function ‹_›, repeat {assumption}} lemma subset_prod_of_is_function {Γ : 𝔹} {x y f} (H_func : Γ ≤ is_function x y f) : Γ ≤ f ⊆ᴮ prod x y := bv_and.right H_func lemma is_total_of_is_function {x y f : bSet 𝔹} {Γ} (H_func : Γ ≤ is_function x y f) : Γ ≤ is_total x y f := is_total_of_is_func' (is_func'_of_is_function H_func) lemma mem_domain_of_is_function {x y f : bSet 𝔹} {Γ} {z w : bSet 𝔹} (H_mem : Γ ≤ pair z w ∈ᴮ f) (H_func : Γ ≤ is_function x y f) : Γ ≤ z ∈ᴮ x := begin have : Γ ≤ pair z w ∈ᴮ prod x y, by { exact mem_of_mem_subset (bv_and.right H_func) ‹_› }, rw mem_prod_iff at this, from this.left end lemma mem_codomain_of_is_function {x y f : bSet 𝔹} {Γ} {z w : bSet 𝔹} (H_mem : Γ ≤ pair z w ∈ᴮ f) (H_func : Γ ≤ is_function x y f) : Γ ≤ w ∈ᴮ y := begin have : Γ ≤ pair z w ∈ᴮ prod x y, by { exact mem_of_mem_subset (bv_and.right H_func) ‹_› }, rw mem_prod_iff at this, from this.right end lemma factor_image_is_func' { x y f : bSet 𝔹 } { Γ } (H_is_func' : Γ ≤ is_func' x y f) : Γ ≤ is_func' x (image x y f) f := begin refine le_inf (bv_and.left ‹_›) _, bv_intro w₁, bv_imp_intro Hw₁, have := is_total_of_is_func' H_is_func', replace this := this w₁ Hw₁, bv_cases_at this w₂ Hw₂, apply bv_use w₂, refine le_inf _ (bv_and.right ‹_›), rw mem_image_iff, refine ⟨bv_and.left ‹_›, _⟩, apply bv_use w₁, from le_inf ‹_› (bv_and.right ‹_›) end lemma factor_image_is_function { x y f : bSet 𝔹 } { Γ } (H_is_function : Γ ≤ is_function x y f) : Γ ≤ is_function x (image x y f) f := begin refine le_inf _ _, { exact factor_image_is_func' (is_func'_of_is_function ‹_›) }, { rw subset_unfold', bv_intro w, bv_imp_intro Hw, have Hw_mem_prod : Γ_1 ≤ w ∈ᴮ prod x y, by { apply mem_of_mem_subset (subset_prod_of_is_function ‹_›) ‹_› }, rw mem_prod_iff₂ at Hw_mem_prod, rcases Hw_mem_prod with ⟨v,Hv,w',Hw', H_eq⟩, rw mem_prod_iff₂, use v, use ‹_›, use w', refine ⟨_,‹_›⟩, { rw mem_image_iff, refine ⟨‹_›, _⟩, apply bv_use v, refine le_inf ‹_› _, bv_cc }} end lemma check_is_total {x y f : pSet.{u}} (H_total : pSet.is_total x y f) {Γ : 𝔹} : Γ ≤ is_total x̌ y̌ f̌ := begin bv_intro z, bv_imp_intro Hz, apply bv_by_contra, bv_imp_intro H, classical, by_contra H_nonzero, rw ←bot_lt_iff_not_le_bot at H_nonzero, rcases eq_check_of_mem_check ‹_› Hz with ⟨i, Γ', H₁, H₂, H₃⟩, simp only with bv_push_neg at H, rcases (H_total (x.func i) (by simp)) with ⟨b, Hb_mem, Hb_pair_mem⟩, replace H := le_trans H₂ (H (b̌)), suffices this : Γ' ≤ ⊥, by {exact false_of_bot_lt_and_le_bot H₁ ‹_› }, bv_or_elim_at H, { refine bv_absurd _ _ H.left, from check_mem ‹_› }, { have this : Γ_3 ≤ _ := check_mem Hb_pair_mem, refine bv_absurd _ _ H.right, apply bv_rw' H₃, from B_ext_pair_mem_left, change _ ≤ (λ w, w ∈ᴮ f̌) _, apply bv_rw' (bv_symm check_pair), simp, from ‹_› } end lemma check_is_func {x y f : pSet.{u}} (H_func : pSet.is_func x y f) {Γ : 𝔹} : Γ ≤ is_function x̌ y̌ f̌ := begin refine le_inf (le_inf _ _) _, { have : Γ ≤ f̌ ⊆ᴮ _ := check_subset (pSet.subset_prod_of_is_func ‹_›), bv_intro w₁, bv_intro w₂, bv_intro v₁, bv_intro v₂, bv_imp_intro H, bv_split_at H, bv_imp_intro H_eq, have H_left' := H_left, have H_right' := H_right, replace H_left := mem_of_mem_subset this H_left, replace H_right := mem_of_mem_subset this H_right, change _ ≤ (λ w, (pair w₁ v₁) ∈ᴮ w) (pSet.prod x y)̌ at H_left, change _ ≤ (λ w, (pair w₂ v₂) ∈ᴮ w) (pSet.prod x y)̌ at H_right, replace H_left := bv_rw'' (check_prod) H_left, replace H_right := bv_rw'' (check_prod) H_right, rw mem_prod_iff at H_left H_right, rcases H_left with ⟨H₁, H₂⟩, rcases H_right with ⟨H₃, H₄⟩, rw mem_unfold at H₁ H₂ H₃ H₄, bv_cases_at H₁ i₁ Hi₁, bv_cases_at H₂ j₁ Hj₁, bv_cases_at H₃ i₂ Hi₂, bv_cases_at H₄ j₂ Hj₂, simp at Hi₁ Hj₁ Hi₂ Hj₂, rw check_func at *, suffices : Γ_6 ≤ (pSet.func y (check_cast j₁))̌ =ᴮ (pSet.func y (check_cast j₂))̌ , by bv_cc, classical, by_cases H_bot : (⊥ < Γ_6), swap, {rw le_bot_iff_not_bot_lt at H_bot, from le_trans H_bot bot_le}, apply check_eq, refine pSet.eq_of_is_func_of_eq H_func _ _ (_ : pSet.equiv (pSet.func x (check_cast i₁)) (pSet.func x (check_cast i₂))), { apply check_mem_reflect ‹_›, let A := _, change _ ≤ A ∈ᴮ _, suffices this : Γ_6 ≤ A =ᴮ pair w₁ v₁, by {change _ ≤ (λ w, w ∈ᴮ f̌) _, apply bv_rw' this, simp, from ‹_› }, refine bv_trans check_pair _, rw pair_eq_pair_iff, refine ⟨_,_⟩; apply bv_symm; assumption }, { apply check_mem_reflect ‹_›, let A := _, change _ ≤ A ∈ᴮ _, suffices this : Γ_6 ≤ A =ᴮ pair w₂ v₂, by {change _ ≤ (λ w, w ∈ᴮ f̌) _, apply bv_rw' this, simp, from ‹_› }, refine bv_trans check_pair _, rw pair_eq_pair_iff, refine ⟨_,_⟩; apply bv_symm; assumption }, { apply check_eq_reflect ‹_›, bv_cc }}, { from check_is_total (pSet.is_total_of_is_func ‹_›) }, { apply bv_rw' (bv_symm check_prod), { simp }, from check_subset (pSet.subset_prod_of_is_func ‹_›) } end def function_of_func' {x y f : bSet 𝔹} {Γ} (H_is_func' : Γ ≤ is_func' x y f) : bSet 𝔹 := f ∩ᴮ (prod x y) lemma function_of_func'_subset {x y f : bSet 𝔹} {Γ} {H_is_func' : Γ ≤ is_func' x y f} : Γ ≤ function_of_func' H_is_func' ⊆ᴮ f := binary_inter_subset_left lemma mem_function_of_func'_iff {x y f : bSet 𝔹} {Γ} {H_is_func' : Γ ≤ is_func' x y f} {z} : Γ ≤ z ∈ᴮ (function_of_func' H_is_func') ↔ Γ ≤ z ∈ᴮ f ∧ Γ ≤ z ∈ᴮ (prod x y) := mem_binary_inter_iff @[reducible]def is_inj (f : bSet 𝔹) : 𝔹 := ⨅w₁, ⨅ w₂, ⨅v₁, ⨅ v₂, (pair w₁ v₁ ∈ᴮ f ⊓ pair w₂ v₂ ∈ᴮ f ⊓ v₁ =ᴮ v₂) ⟹ w₁ =ᴮ w₂ @[reducible]def is_injective_function (x y f : bSet 𝔹) : 𝔹 := is_function x y f ⊓ is_inj f lemma is_inj_of_is_injective_function { x y f : bSet 𝔹 } { Γ : 𝔹 } : Γ ≤ is_injective_function x y f → Γ ≤ is_inj f := λ _, bv_and.right ‹_› lemma factor_image_is_injective_function { x y f : bSet 𝔹 } { Γ : 𝔹 } (H_is_function : Γ ≤ is_injective_function x y f) : Γ ≤ is_injective_function x (image x y f) f := begin refine le_inf _ _, { apply factor_image_is_function, from bv_and.left ‹_› }, from bv_and.right ‹_› end @[simp]lemma B_ext_is_injective_function_left {y f : bSet 𝔹} : B_ext (λ x, is_injective_function x y f) := by simp lemma is_func'_of_is_injective_function {x y f : bSet 𝔹} {Γ} (H : Γ ≤ is_injective_function x y f) : Γ ≤ is_func' x y f := is_func'_of_is_function $ bv_and.left H lemma check_is_injective_function {x y f : pSet.{u}} (H_inj : pSet.is_injective_function x y f) {Γ : 𝔹} : Γ ≤ bSet.is_injective_function x̌ y̌ f̌ := begin have : Γ ≤ _ := check_is_func H_inj.left, refine le_inf this _, bv_split_at this, bv_intro w₁, bv_intro w₂, bv_intro v₁, bv_intro v₂, bv_imp_intro H, bv_split_at H, bv_split_at H_left, cases H_inj with _ H_inj, unfold pSet.is_inj at H_inj, have H₁ := mem_of_mem_subset this_right H_left_left, have H₂ := mem_of_mem_subset this_right H_left_right, rw [mem_prod_iff] at H₁ H₂, cases H₁ with Hw₁ Hv₁, cases H₂ with Hw₂ Hv₂, rw mem_unfold at Hw₁ Hv₁ Hw₂ Hv₂, bv_cases_at Hw₁ iw₁ Hiw₁, bv_cases_at Hw₂ iw₂ Hiw₂, bv_cases_at Hv₁ iv₁ Hiv₁, bv_cases_at Hv₂ iv₂ Hiv₂, rw [check_bval_top, top_inf_eq] at Hiw₁ Hiw₂ Hiv₁ Hiv₂, suffices : Γ_5 ≤ (func x̌ iw₁) =ᴮ (func x̌ iw₂), by bv_cc, simp only [check_func] at ⊢ Hiv₁ Hiv₂ Hiw₁ Hiw₂, classical, by_cases H_lt : ⊥ < Γ_5, swap, {rw le_bot_iff_not_bot_lt at H_lt, from le_trans H_lt bot_le}, refine (check_eq $ H_inj _ _ (pSet.func y (check_cast iv₁)) (pSet.func y (check_cast iv₂)) _), refine ⟨_,_,_⟩, { by_contra, suffices : Γ_5 ≤ ⊥, from false_of_bot_lt_and_le_bot ‹_› ‹_›, apply check_not_mem a, suffices : Γ_5 ≤ pair w₁ v₁ =ᴮ (pSet.pair (pSet.func x (check_cast iw₁)) (pSet.func y (check_cast iv₁)))̌ , by {change _ ≤ (λ w, w ∈ᴮ f̌) _, apply bv_rw' (bv_symm $ this), simp, from ‹_›}, change _ ≤ (λ w, pair w₁ v₁ =ᴮ w) _, apply bv_rw' check_pair, simp, rw pair_eq_pair_iff, from ⟨‹_›,‹_›⟩ }, { by_contra, suffices : Γ_5 ≤ ⊥, from false_of_bot_lt_and_le_bot ‹_› ‹_›, apply check_not_mem a, suffices : Γ_5 ≤ pair w₂ v₂ =ᴮ (pSet.pair (pSet.func x (check_cast iw₂)) (pSet.func y (check_cast iv₂)))̌ , by {change _ ≤ (λ w, w ∈ᴮ f̌) _, apply bv_rw' (bv_symm $ this), simp, from ‹_›}, change _ ≤ (λ w, pair w₂ v₂ =ᴮ w) _, apply bv_rw' check_pair, simp, rw pair_eq_pair_iff, from ⟨‹_›,‹_›⟩ }, { apply check_bv_eq_iff.mpr, tactic.rotate 1, from 𝔹, apply_instance, rw ←check_bv_eq_nonzero_iff_eq_top, from lt_of_lt_of_le H_lt (by bv_cc) }, end @[simp]lemma eq_of_is_inj_of_eq {x y x' y' f : bSet 𝔹} {Γ : 𝔹} (H_is_inj : Γ ≤ is_inj f) (H_eq : Γ ≤ x' =ᴮ y') (H_mem₁ : Γ ≤ pair x x' ∈ᴮ f) (H_mem₂ : Γ ≤ pair y y' ∈ᴮ f) : Γ ≤ x =ᴮ y := H_is_inj x y x' y' (le_inf (le_inf ‹_› ‹_›) ‹_›) -- lemma funext (f x y z : bSet 𝔹) {Γ : 𝔹} (H_func : Γ ≤ is_func f) (H : Γ ≤ (pair x y) ∈ᴮ f) -- (H' : Γ ≤ (pair x z) ∈ᴮ f) : Γ ≤ y =ᴮ z := -- H_func x x y z (le_inf ‹_› ‹_›) (bv_refl) -- ∀ z ∈ x, ∀ w ∈ y, (z,w) ∈ f ↔ (z,w) ∈ g -- not really funext since it doesn't use extensionality in an essential way lemma funext {x y f g : bSet 𝔹} {Γ : 𝔹} (H₁ : Γ ≤ is_function x y f) (H₂ : Γ ≤ is_function x y g) (H_peq : Γ ≤ ⨅ p, p ∈ᴮ prod x y ⟹ (p ∈ᴮ f ⇔ p ∈ᴮ g)) : Γ ≤ f =ᴮ g := begin have H_sub₁ := subset_prod_of_is_function H₁, have H_sub₂ := subset_prod_of_is_function H₂, apply mem_ext, all_goals {bv_intro z, bv_imp_intro Hz_mem}, { have := mem_of_mem_subset H_sub₁ Hz_mem, replace H_peq := H_peq z ‹_›, rw le_inf_iff at H_peq, cases H_peq with H_peq₁ H_peq₂, exact H_peq₁ Hz_mem }, { have := mem_of_mem_subset H_sub₂ Hz_mem, replace H_peq := H_peq z ‹_›, rw le_inf_iff at H_peq, cases H_peq with H_peq₁ H_peq₂, exact H_peq₂ Hz_mem } end /-- A relation f is surjective if for every w ∈ y there is a v ∈ x such that (v,w) ∈ f. -/ @[reducible]def is_surj (x y : bSet 𝔹) (f : bSet 𝔹) : 𝔹 := ⨅v, v ∈ᴮ y ⟹ (⨆w, w ∈ᴮ x ⊓ pair w v ∈ᴮ f) /-- x is larger than y if there is a subset S ⊆ X which surjects onto y. -/ def larger_than (x y : bSet 𝔹) : 𝔹 := ⨆ S, ⨆f, S ⊆ᴮ x ⊓ (is_func' S y f) ⊓ (is_surj S y f) lemma is_surj_empty {Γ : 𝔹} : Γ ≤ is_surj (∅ : bSet 𝔹) ∅ ∅ := forall_empty lemma function_of_func'_is_function {x y f : bSet 𝔹} {Γ} (H_is_func' : Γ ≤ is_func' x y f) : Γ ≤ is_function x y (function_of_func' H_is_func') := begin refine le_inf (le_inf _ _) _, { exact is_func_subset_of_is_func (is_func_of_is_func' ‹_›) function_of_func'_subset }, { bv_intro w₁, rw[<-deduction, inf_comm], let Γ_1 := w₁ ∈ᴮ x ⊓ Γ, change Γ_1 ≤ _, have H : Γ_1 ≤ w₁ ∈ᴮ x := by simp[Γ_1, inf_le_right], have : Γ_1 ≤ is_func' x y f := le_trans inf_le_right H_is_func', have H_total := bv_and.right this w₁ H, bv_cases_at H_total w₂ H_w₂, apply bv_use w₂, bv_split, refine le_inf ‹_› _, erw[mem_binary_inter_iff], simp* }, { exact binary_inter_subset_right } end lemma function_of_func'_surj_of_surj {x y f : bSet 𝔹} {Γ} (H_is_func' : Γ ≤ is_func' x y f) (H_is_surj : Γ ≤ is_surj x y f) : Γ ≤ is_surj x y (function_of_func' H_is_func') := begin bv_intro z, bv_imp_intro' Hz, have := H_is_surj z Hz, bv_cases_at' this w Hw, apply bv_use w, bv_split, refine le_inf ‹_› _, erw[mem_binary_inter_iff], simp* end lemma function_of_func'_inj_of_inj {x y f : bSet 𝔹} {Γ} {H : Γ ≤ is_func' x y f} (H_is_surj : Γ ≤ is_inj f) : Γ ≤ is_inj (function_of_func' H) := begin bv_intro w₁, bv_intro w₂, bv_intro v₁, bv_intro v₂, bv_imp_intro' H', bv_split_at H', bv_split_at H'_left, suffices : Γ_1 ≤ pair w₁ v₁ ∈ᴮ f ∧ Γ_1 ≤ pair w₂ v₂ ∈ᴮ f, by {refine H_is_surj w₁ w₂ v₁ v₂ _, simp*}, refine ⟨_,_⟩; from mem_of_mem_subset (by {apply function_of_func'_subset, from ‹_›}) ‹_› end lemma surj_image { x y f : bSet 𝔹 } { Γ } (H_func : Γ ≤ is_func' x y f) : Γ ≤ is_surj x (image x y f) f := begin bv_intro w, bv_imp_intro H_mem, rw mem_image_iff at H_mem, cases H_mem with H_mem₁ H_mem₂, exact H_mem₂ end lemma image_eq_codomain_of_surj {x y f : bSet 𝔹} {Γ} (H_surj : Γ ≤ is_surj x y f) : Γ ≤ image x y f =ᴮ y := begin refine subset_ext (by apply image_subset) _, rw subset_unfold', bv_intro z, bv_imp_intro Hz, rw mem_image_iff, exact ⟨‹_›,H_surj z ‹_›⟩ end -- TODO: maybe move the S ⊆ᴮ x outside of the inner ⨆? @[simp]lemma larger_than_domain_subset {Γ : 𝔹} {x y S : bSet 𝔹} (HS : Γ ≤ ⨆ f, S ⊆ᴮ x ⊓ (is_func' S y f) ⊓ (is_surj S y f)) : Γ ≤ S ⊆ᴮ x := by {bv_cases_at HS f Hf, exact bv_and.left (bv_and.left ‹_›)} def injects_into (x y : bSet 𝔹) : 𝔹 := ⨆f, (is_func' x y f) ⊓ is_inj f def injection_into (x y : bSet 𝔹) : 𝔹 := ⨆f, is_injective_function x y f lemma injection_into_of_injects_into {x y : bSet 𝔹} {Γ} (H : Γ ≤ injects_into x y) : Γ ≤ injection_into x y := begin bv_cases_at H f Hf, bv_split_at Hf, apply bv_use (function_of_func' Hf_left), refine le_inf _ _, { from function_of_func'_is_function _ }, { from function_of_func'_inj_of_inj ‹_› } end lemma injects_into_of_injection_into {x y : bSet 𝔹} {Γ} (H_inj : Γ ≤ injection_into x y) : Γ ≤ injects_into x y := begin bv_cases_at H_inj f Hf, apply bv_use f, bv_split_at Hf, from le_inf (is_func'_of_is_function ‹_›) ‹_› end lemma injects_into_iff_injection_into {x y : bSet 𝔹} {Γ} : Γ ≤ injects_into x y ↔ Γ ≤ injection_into x y := ⟨λ _, injection_into_of_injects_into ‹_›, λ _, injects_into_of_injection_into ‹_›⟩ lemma check_injects_into {x y : pSet.{u}} (H_inj : pSet.injects_into x y) {Γ : 𝔹} : Γ ≤ bSet.injects_into x̌ y̌ := begin cases H_inj with f H_f_inj, apply bv_use f̌, have : Γ ≤ _ := check_is_injective_function H_f_inj, change _ ≤ _ ⊓ _ at this, refine le_inf _ (bv_and.right ‹_›), from is_func'_of_is_function (bv_and.left ‹_›) end @[reducible]def is_surj_onto (x y f : bSet 𝔹) : 𝔹 := (is_func' x y f) ⊓ (is_surj x y f) def surjects_onto (x y : bSet 𝔹) : 𝔹 := ⨆f, is_surj_onto x y f @[simp]lemma B_ext_larger_than_right {y : bSet 𝔹} : B_ext (λ z, larger_than y z) := by simp[larger_than] @[simp]lemma B_ext_larger_than_left {y : bSet 𝔹} : B_ext (λ z, larger_than z y) := by simp[larger_than] @[simp]lemma B_ext_injects_into_left {y : bSet 𝔹} : B_ext (λ z, injects_into z y) := by simp[injects_into] @[simp]lemma B_ext_injects_into_right {y : bSet 𝔹} : B_ext (λ z, injects_into y z) := by simp[injects_into] local infix `≺`:75 := (λ x y, -(larger_than x y)) local infix `≼`:75 := (λ x y, injects_into x y) -- aka AC -- TODO -- lemma injects_into_of_surjects_onto {x y : bSet 𝔹} {Γ} (H_inj : Γ ≤ surjects_onto x y) : Γ ≤ injects_into y x := sorry section surjects_onto_of_larger_than variables {x y : bSet 𝔹} {Γ : 𝔹} (H_larger_than : Γ ≤ larger_than x y) (H_nonempty : Γ ≤ exists_mem y ) section pointed_extension variables {S f : bSet 𝔹} (b : bSet 𝔹) (H_b : Γ ≤ b ∈ᴮ y) (H_S : Γ ≤ S ⊆ᴮ x) (H_surj : Γ ≤ is_func' S y f ⊓ is_surj S y f) include b H_S H_surj def pointed_extension : bSet 𝔹 := subset.mk $ λ pr : (prod x y).type, (x.func pr.1 ∈ᴮ S ⟹ pair (x.func pr.1) (y.func pr.2) ∈ᴮ f) ⊓ ((- (x.func pr.1 ∈ᴮ S)) ⟹ (y.func pr.2) =ᴮ b) @[simp,cleanup]lemma pointed_extension_func {pr} : (pointed_extension b H_S H_surj).func pr = pair (x.func pr.1) (y.func pr.2) := by refl lemma pointed_extension_bval {pr} : (pointed_extension b H_S H_surj).bval pr = ((x.func pr.1 ∈ᴮ S ⟹ pair (x.func pr.1) (y.func pr.2) ∈ᴮ f) ⊓ ((- (x.func pr.1 ∈ᴮ S)) ⟹ (y.func pr.2) =ᴮ b)) ⊓ (prod x y).bval pr := by refl @[simp]lemma pointed_extension_bval_of_mem {pr : (prod x y).type} (H_mem : Γ ≤ (x.func pr.1) ∈ᴮ S) (H_bval : Γ ≤ (pointed_extension b H_S H_surj).bval pr) : Γ ≤ x.bval pr.1 ∧ Γ ≤ y.bval pr.2 ∧ Γ ≤ pair (x.func pr.1) (y.func pr.2) ∈ᴮ f := begin simp [pointed_extension_bval] at H_bval, rcases H_bval with ⟨⟨H_bval₁, H_bval₂⟩, ⟨_,_⟩⟩, from ⟨‹_›,‹_›,H_bval₁ ‹_›⟩ end @[simp]lemma pointed_extension_pair_mem_of_mem {i : x.type} {j : y.type} (H_mem : Γ ≤ (x.func i) ∈ᴮ S) (H_bval : Γ ≤ (pointed_extension b H_S H_surj).bval (i,j)) : Γ ≤ pair (x.func i) (y.func j) ∈ᴮ f := (pointed_extension_bval_of_mem b H_S H_surj (by {change _ ≤ func x (i,j).fst ∈ᴮ _ at H_mem, from ‹_›}) ‹_›).right.right @[simp]lemma pointed_extension_pair_mem_of_mem' {w v : bSet 𝔹} {pr : (prod x y).type} (H_mem : Γ ≤ (x.func pr.1) ∈ᴮ S) (H_bval : Γ ≤ (pointed_extension b H_S H_surj).bval pr) (H_eq : Γ ≤ pair w v =ᴮ func (pointed_extension b H_S H_surj) pr) : Γ ≤ pair w v ∈ᴮ f := begin simp at H_eq, apply @bv_rw' _ _ _ _ _ (H_eq) (λ z, z ∈ᴮ f), simp, cases pr with i j, apply pointed_extension_pair_mem_of_mem, repeat {assumption} end -- (pointed_extension_bval_of_mem b H_S H_surj (by {change _ ≤ func x (i,j).fst ∈ᴮ _ at H_mem, from ‹_›}) ‹_›).right.right @[simp]lemma pointed_extension_bval_of_not_mem {pr : (prod x y).type} (H_mem : Γ ≤ - ((x.func pr.1) ∈ᴮ S)) (H_bval : Γ ≤ (pointed_extension b H_S H_surj).bval pr) : Γ ≤ x.bval pr.1 ∧ Γ ≤ y.bval pr.2 ∧ Γ ≤ (y.func pr.2) =ᴮ b := begin simp [pointed_extension_bval] at H_bval, rcases H_bval with ⟨⟨H_bval₁, H_bval₂⟩, ⟨_,_⟩⟩, from ⟨‹_›,‹_›,H_bval₂ ‹_›⟩ end @[simp]lemma pointed_extension_y_eq_of_not_mem {i : x.type} {j : y.type} (H_mem : Γ ≤ - ((x.func i) ∈ᴮ S)) (H_bval : Γ ≤ (pointed_extension b H_S H_surj).bval (i,j)) : Γ ≤ y.func j =ᴮ b := (pointed_extension_bval_of_not_mem b H_S H_surj (by {change _ ≤ - (func x (i,j).fst ∈ᴮ _) at H_mem, from ‹_›}) ‹_›).right.right @[simp]lemma pointed_extension_y_eq_of_not_mem' {w v : bSet 𝔹} {pr : (prod x y).type} (H_mem : Γ ≤ - ((x.func pr.1) ∈ᴮ S)) (H_bval : Γ ≤ (pointed_extension b H_S H_surj).bval pr) (H_eq : Γ ≤ pair w v =ᴮ func (pointed_extension b H_S H_surj) pr) : Γ ≤ v =ᴮ b := begin simp at H_eq, replace H_eq := eq_of_eq_pair_right' H_eq, apply @bv_rw' _ _ _ _ _ (H_eq) (λ z, z =ᴮ b), simp, cases pr with i j, apply pointed_extension_y_eq_of_not_mem, repeat {assumption} end include H_b variable {b} lemma mem_pointed_extension_iff {w v : bSet 𝔹} (H_x_mem : Γ ≤ w ∈ᴮ x) : Γ ≤ pair w v ∈ᴮ pointed_extension b H_S H_surj ↔ (Γ ≤ ((w ∈ᴮ S ⊓ pair w v ∈ᴮ f) ⊔ (- (w ∈ᴮ S) ⊓ v =ᴮ b))) := begin refine ⟨_,_⟩; intro H, { bv_cases_on' (w ∈ᴮ S), { apply bv_or_left, refine le_inf ‹_› _, bv_split_at H_surj, have := is_total_of_is_func' H_surj_left w ‹_›, bv_cases_at this w₂ Hw₂, rw[mem_unfold'], apply bv_use (pair w w₂), rename H H', bv_split, refine le_inf ‹_› _, suffices this : Γ_2 ≤ v =ᴮ w₂, by {exact pair_congr (bv_refl) ‹_› }, suffices this : Γ_2 ≤ pair w v ∈ᴮ f, by { apply eq_of_is_func_of_eq, repeat {assumption}, from bv_refl }, rw[mem_unfold] at H', bv_cases_at H' pr Hpr, bv_split_at Hpr, apply pointed_extension_pair_mem_of_mem', repeat {assumption}, {simp at Hpr_right, rw[pair_eq_pair_iff] at Hpr_right, cases Hpr_right, bv_cc}, exact le_inf (le_inf ‹_› ‹_›) ‹_› }, { apply bv_or_right, refine (le_inf ‹_› _) , rw[mem_unfold] at H, bv_cases_at H pr Hpr, bv_split_at Hpr, apply pointed_extension_y_eq_of_not_mem', repeat {assumption}, {simp at Hpr_right, rw[pair_eq_pair_iff] at Hpr_right, cases Hpr_right, rw[<-imp_bot], apply @bv_rw' _ _ _ _ _ (bv_symm Hpr_right_left) (λ z, z ∈ᴮ S ⟹ ⊥), {simp}, dsimp, rwa[imp_bot] }, }, }, { bv_or_elim_at' H, { bv_split_at H.left, bv_split_at H_surj, have := is_total_of_is_func' (H_surj_left) w H.left_left, bv_cases_at this v' Hv', have H_S' := H_S, rw[subset_unfold'] at H_S', replace H_S' := H_S' w ‹_›, rw[mem_unfold] at H_S', bv_cases_at H_S' i Hi, bv_split_at Hv', rw[mem_unfold] at Hv'_left, bv_cases_at Hv'_left j Hj, apply bv_use (i,j), refine le_inf _ _, { simp, refine ⟨⟨_,_⟩,_,_⟩, { bv_imp_intro H_good, suffices this : Γ_5 ≤ pair w v' =ᴮ pair (func x i) (func y j) , by {apply @bv_rw' _ _ _ _ _ (bv_symm this) (λ z, z ∈ᴮ f), simp, from ‹_› }, refine pair_congr (bv_and.right ‹_›) (bv_and.right ‹_›) }, { bv_imp_intro H_bad, refine bv_exfalso (bv_absurd _ H.left_left _), apply bv_rw' (bv_and.right Hi), simp, from ‹_› }, { from bv_and.left Hi }, { from bv_and.left Hj } }, { refine pair_congr (bv_and.right ‹_›) _, suffices this : Γ_4 ≤ v =ᴮ v', by {bv_split_at Hj, bv_cc}, apply eq_of_is_func'_of_eq, from ‹_›, from (bv_refl : _ ≤ w =ᴮ w), from ‹_›, from ‹_› }, }, { bv_split_at H.right, rw[mem_unfold] at H_x_mem H_b, bv_cases_at H_x_mem i Hi, bv_split_at Hi, bv_cases_at H_b j Hj, bv_split_at Hj, apply bv_use (i,j), refine le_inf (le_inf _ (le_inf ‹_› ‹_›)) (pair_congr ‹_› (by bv_cc)), dsimp, refine le_inf _ _, { bv_imp_intro H_mem, refine bv_exfalso (bv_absurd _ H_mem _), apply @bv_rw' _ _ _ _ _ (bv_symm Hi_right) (λ z, - (z ∈ᴮ S)), simp, from ‹_› }, { bv_imp_intro H_not_mem, from bv_symm ‹_› } } } end lemma pointed_extension_is_func : Γ ≤ is_func (pointed_extension b H_S H_surj) := begin bv_intro w₁, bv_intro w₂, bv_intro v₁, bv_intro v₂, bv_imp_intro' H, bv_imp_intro H_eq, bv_split_at H, rw[mem_unfold] at H_left H_right, bv_cases_at H_left pr₁ Hpr₁, bv_cases_at H_right pr₂ Hpr₂, cases pr₁ with i j, cases pr₂ with i' j', simp only with cleanup at Hpr₁ Hpr₂, bv_split_at Hpr₁, bv_split_at Hpr₂, rw[pair_eq_pair_iff] at Hpr₁_right Hpr₂_right, auto_cases, bv_cases_on ((x.func i) ∈ᴮ S) with H_mem, { suffices this : Γ_5 ≤ pair w₁ v₁ ∈ᴮ f ∧ Γ_5 ≤ pair w₂ v₂ ∈ᴮ f, by { exact eq_of_is_func'_of_eq (bv_and.left ‹_›) ‹_› this.left this.right }, refine ⟨_,_⟩, { suffices : Γ_5 ≤ pair (x.func i) (y.func j) ∈ᴮ f, by { suffices H_eq : Γ_5 ≤ pair w₁ v₁ =ᴮ pair (x.func i) (y.func j) , by {apply @bv_rw' _ _ _ _ _ H_eq (λ z, z ∈ᴮ f), simp, from ‹_›}, from pair_congr ‹_› ‹_›, }, apply pointed_extension_pair_mem_of_mem, repeat {assumption} }, { suffices : Γ_5 ≤ pair (x.func i') (y.func j') ∈ᴮ f, by { suffices H_eq : Γ_5 ≤ pair w₂ v₂ =ᴮ pair (x.func i') (y.func j') , by {apply @bv_rw' _ _ _ _ _ H_eq (λ z, z ∈ᴮ f), simp, from ‹_›}, from pair_congr ‹_› ‹_›, }, apply pointed_extension_pair_mem_of_mem, repeat {assumption}, suffices h_eq : Γ_5 ≤ func x i' =ᴮ func x i, by {apply @bv_rw' _ _ _ _ _ h_eq (λ z, z ∈ᴮ S), simp, from ‹_›}, by bv_cc } }, { suffices this : Γ_5 ≤ v₁ =ᴮ b ∧ Γ_5 ≤ v₂ =ᴮ b, by { cases this with this₁ this₂, bv_cc }, refine ⟨_,_⟩, { suffices : Γ_5 ≤ (y.func j) =ᴮ b, by { bv_cc }, apply pointed_extension_y_eq_of_not_mem, repeat {assumption} }, { suffices : Γ_5 ≤ (y.func j') =ᴮ b, by { bv_cc }, suffices this : Γ_5 ≤ -(func x i' ∈ᴮ S), by {replace H_mem.right := this, apply pointed_extension_y_eq_of_not_mem, repeat{assumption}}, suffices h_eq : Γ_5 ≤ func x i' =ᴮ func x i, by {apply @bv_rw' _ _ _ _ _ h_eq (λ z, - (z ∈ᴮ S)), simp, from ‹_›}, bv_cc } }, end lemma pointed_extension_is_total : Γ ≤ is_total x y (pointed_extension b H_S H_surj) := begin bv_intro a, bv_imp_intro' Ha, bv_cases_on (a ∈ᴮ S) with H_mem, { have := is_total_of_is_func' (bv_and.left (‹_› : Γ_2 ≤ _)), replace this := this a ‹_›, bv_cases_at this w₂ Hw₂, apply bv_use w₂, refine le_inf (bv_and.left ‹_›) _, have H_mem_x : Γ_3 ≤ a ∈ᴮ x := mem_of_mem_subset ‹_› ‹_›, apply (mem_pointed_extension_iff H_b ‹_› ‹_› ‹_›).mpr, apply bv_or_left, from le_inf ‹_› (bv_and.right ‹_›) }, { apply bv_use b, refine le_inf ‹_› _, apply (mem_pointed_extension_iff H_b ‹_› ‹_› ‹_›).mpr, apply bv_or_right, from le_inf ‹_› (bv_refl) } end lemma pointed_extension_is_func' : Γ ≤ is_func' x y (pointed_extension b H_S H_surj) := begin refine le_inf _ _, { apply pointed_extension_is_func, from ‹_› }, { apply pointed_extension_is_total, from ‹_› }, end lemma pointed_extension_is_surj : Γ ≤ is_surj x y (pointed_extension b H_S H_surj) := begin bv_intro v, bv_imp_intro' Hv, bv_split_at H_surj, have H_surj' := H_surj_right, replace H_surj_right := H_surj_right v Hv, bv_cases_at H_surj_right w Hw, bv_split_at Hw, have H_mem_x := (mem_of_mem_subset H_S ‹_›), apply bv_use w, refine le_inf ‹_› _, apply (mem_pointed_extension_iff H_b ‹_› (le_inf ‹_› ‹_›) ‹_›).mpr, from bv_or_left (le_inf ‹_› ‹_›) end lemma pointed_extension_spec : Γ ≤ surjects_onto x y := begin apply bv_use (pointed_extension b H_S H_surj), from le_inf (by {apply pointed_extension_is_func', from ‹_›}) (by {apply pointed_extension_is_surj, from ‹_›}) end end pointed_extension include H_larger_than H_nonempty lemma surjects_onto_of_larger_than_and_exists_mem : Γ ≤ surjects_onto x y := begin bv_cases_at H_larger_than S HS, bv_cases_at HS f Hf, bv_split_at Hf, bv_split_at Hf_left, bv_cases_at H_nonempty b Hb, from pointed_extension_spec ‹_› ‹_› (le_inf ‹_› ‹_›) end end surjects_onto_of_larger_than lemma larger_than_of_surjects_onto {x y : bSet 𝔹} {Γ} (H_surj : Γ ≤ surjects_onto x y) : Γ ≤ larger_than x y := begin apply bv_use x, unfold surjects_onto at H_surj, bv_cases_at H_surj f Hf, apply bv_use f, from le_inf (le_inf (by simp) (bv_and.left ‹_›)) (bv_and.right ‹_›) end -- lemma check_is_func {x y f : pSet.{u}} : pSet.is_func x y f ↔ ∀{Γ : 𝔹}, Γ ≤ is_function x̌ y̌ f̌ := sorry lemma check_not_is_func {x y f : pSet.{u}} (H : ¬ pSet.is_func x y f) : ∀ {Γ : 𝔹}, ( Γ ≤ (is_function x̌ y̌ f̌) → Γ ≤ (⊥ : 𝔹)) := begin rw pSet.is_func_iff at H, intros Γ H', push_neg at H, bv_split_at H', cases H, { replace H := (check_not_subset H : Γ ≤ _), have := @bv_rw'' 𝔹 _ _ _ _ (check_prod) (λ z, - (f̌ ⊆ᴮ z)) H (by simp), dsimp only at this, bv_contradiction }, { rcases H with ⟨z, ⟨Hz_mem, Hz⟩⟩, have H'_total := is_total_of_is_func' H'_left, replace H'_total := H'_total (ž) (by simp*), bv_cases_at H'_total w Hw, bv_split_at Hw, classical, by_contra H_nonzero, rw ←bot_lt_iff_not_le_bot at H_nonzero, rcases eq_check_of_mem_check ‹_› Hw_left with ⟨i, Γ', HΓ'_nonzero, HΓ'_le, Hi⟩, have Hz₁ := Hz (y.func i), cases Hz₁ with H_not_total H_not_func, { suffices this : Γ' ≤ ⊥, by exact false_of_bot_lt_and_le_bot HΓ'_nonzero ‹_›, refine check_not_mem H_not_total _, apply @bv_rw' _ _ _ _ _ check_pair (λ z, z ∈ᴮ f̌), simp, dsimp, apply @bv_rw' _ _ _ _ _ (bv_symm Hi) (λ w, pair ž w ∈ᴮ f̌), from B_ext_pair_mem_right, from le_trans HΓ'_le ‹_› }, { rcases H_not_func with ⟨b, Hb_pair_mem, Hb_neq⟩, have H_not_eq : Γ' ≤ _ := check_not_eq Hb_neq, have H_is_func := is_func_of_is_func' H'_left ž ž w b̌ (le_inf ‹_› _) bv_refl, replace H_is_func := (le_trans HΓ'_le H_is_func : Γ' ≤ w =ᴮ b̌), refine false_of_bot_lt_and_le_bot HΓ'_nonzero (bv_absurd _ (bv_symm H_is_func) _), apply bv_rw' Hi, simp, from ‹_›, apply @bv_rw' _ _ _ _ _ (bv_symm check_pair) (λ w, w ∈ᴮ f̌), simp, exact check_mem Hb_pair_mem } }, end -- lemma check_is_surj {x y f : pSet.{u}} : pSet.is_surj x y f ↔ ∀{Γ : 𝔹}, Γ ≤ is_surj x̌ y̌ f̌ := -- begin -- sorry -- end lemma check_not_is_surj {x y f : pSet.{u}} (H : ¬ pSet.is_surj x y f) : ∀ {Γ : 𝔹}, Γ ≤ is_surj x̌ y̌ f̌ → Γ ≤ (⊥ : 𝔹) := begin unfold pSet.is_surj at H, push_neg at H, intros Γ H_surj, unfold is_surj at H_surj, rcases H with ⟨b, ⟨Hb₁, Hb₂⟩⟩ , have := (check_mem Hb₁ : Γ ≤ _), replace H_surj := H_surj (b̌) this, rw[<-bounded_exists] at H_surj, swap, {change B_ext _, from B_ext_pair_mem_left }, bv_cases_at H_surj i_a Hi_a, bv_split_at Hi_a, specialize Hb₂ (x.func (check_cast i_a)), cases Hb₂, { apply check_not_mem ‹_›, simp }, { rw ←pSet.pair_sound at Hb₂, change _ ∉ f at Hb₂, apply check_not_mem ‹_›, have this : Γ_1 ≤ (pSet.pair (pSet.func x (check_cast i_a)) b)̌ =ᴮ bSet.pair _ _, by {apply check_pair}, apply @bv_rw' _ _ _ _ _ this (λ z, z ∈ᴮ f̌), simp, rwa[←check_func] } end lemma bot_lt_of_true {b : 𝔹} (H : ∀ {Γ}, Γ ≤ b) : ⊥ < b := by {specialize @H ⊤, rw top_le_iff at H, simp*} section variable {Γ : 𝔹} /-- Given a surjection f : x ↠ z and an injection g : y ↪ z, lift f along g to a surjection f' : x ↠ y. -/ def lift_surj_inj {x z f g : bSet 𝔹} (y : bSet 𝔹) (H_surj : Γ ≤ is_surj x z f) (H_inj : Γ ≤ is_inj g) : bSet 𝔹 := @subset.mk _ _ (prod x y) (λ p, (⨆w, w ∈ᴮ z ⊓ (pair (x.func p.fst) w) ∈ᴮ f ⊓ (pair (y.func p.snd) w ∈ᴮ g))) lemma ex_witness_of_mem_lift_surj_inj {x y z f g : bSet 𝔹} {w₁ w₂ : bSet 𝔹} {H_surj : Γ ≤ is_surj x z f} {H_inj : Γ ≤ is_inj g} (H_is_func'_f : Γ ≤ is_func' x z f) (H : Γ ≤ pair w₁ w₂ ∈ᴮ (lift_surj_inj y H_surj H_inj)) : Γ ≤ ⨆ w, (w ∈ᴮ z ⊓ (pair w₁ w ∈ᴮ f) ⊓ (pair w₂ w ∈ᴮ g)) := begin bv_cases_at' H pr Hi, bv_split_at Hi, bv_split_at Hi_left, bv_cases_at' Hi_left_left w Hw, apply bv_use w, bv_split_at Hw, bv_split_at Hw_left, simp[pair_eq_pair_iff] at Hi_right, cases Hi_right with H₁ H₂, refine le_inf (le_inf ‹_› _) _, apply bv_rw' H₁, exact B_ext_pair_mem_left, from ‹_›, apply bv_rw' H₂, exact B_ext_pair_mem_left, from ‹_› end lemma mem_lift_surj_inj_iff {x y z f g : bSet 𝔹} {w₁ w₂ : bSet 𝔹} {H_surj : Γ ≤ is_surj x z f} {H_inj : Γ ≤ is_inj g} (H_is_func'_f : Γ ≤ is_func' x z f) {H_mem₁ : Γ ≤ w₁ ∈ᴮ x} {H_mem₂ : Γ ≤ w₂ ∈ᴮ y} : Γ ≤ pair w₁ w₂ ∈ᴮ (lift_surj_inj y H_surj H_inj) ↔ Γ ≤ ⨆ w, (w ∈ᴮ z ⊓ (pair w₁ w ∈ᴮ f) ⊓ (pair w₂ w ∈ᴮ g)) := begin refine ⟨_,_⟩; intro H, { apply ex_witness_of_mem_lift_surj_inj _ _, from x, from y, repeat {assumption} }, { unfold lift_surj_inj, rw[mem_subset.mk_iff], bv_cases_at H w Hw, bv_split_at Hw, bv_split_at Hw_left, rw[mem_unfold] at H_mem₁, bv_cases_at H_mem₁ i Hi, rw[mem_unfold] at H_mem₂, bv_cases_at H_mem₂ j Hj, apply bv_use (i,j), refine le_inf _ _, { bv_split, simp[pair_congr, *] }, { refine le_inf _ _, { apply bv_use w, refine le_inf (le_inf ‹_› _) _, bv_split_at Hi, apply @bv_rw' _ _ _ _ _ (bv_symm $ Hi_right) (λ x, pair x w ∈ᴮ f), exact B_ext_pair_mem_left, from ‹_›, bv_split_at Hj, apply @bv_rw' _ _ _ _ _ (bv_symm $ Hj_right) (λ x, pair x w ∈ᴮ g), exact B_ext_pair_mem_left, from ‹_› }, { bv_split, simp* }}} end -- refine ⟨_,_⟩; intro H, -- { unfold lift_surj_inj at H, rw[mem_unfold] at H, bv_cases_at H i Hi, dsimp at *, -- have Hi' := (bv_and.left $ bv_and.left Hi), bv_cases_at Hi' k Hk, apply bv_use (z.func k), -- refine le_inf (le_inf _ _) _, -- { sorry }, -- { sorry }, -- { sorry }}, -- { sorry }, lemma lift_surj_inj_is_func {x y z f g : bSet 𝔹} {w₁ w₂ : bSet 𝔹} {H_surj : Γ ≤ is_surj x z f} {H_inj : Γ ≤ is_inj g} (H_is_func_f : Γ ≤ is_func' x z f) : Γ ≤ is_func (lift_surj_inj y H_surj H_inj) := begin bv_intro w₁, bv_intro w₂, bv_intro v₁, bv_intro v₂, bv_imp_intro' H_graph, rw[le_inf_iff] at H_graph, cases H_graph with H_gr₁ H_gr₂, bv_imp_intro H_eq, have H_inj₂ := H_inj, rw[is_inj] at H_inj₂, apply_at H_gr₁ (ex_witness_of_mem_lift_surj_inj H_is_func_f), apply_at H_gr₂ (ex_witness_of_mem_lift_surj_inj H_is_func_f), bv_cases_at H_gr₁ c₁ Hc₁, bv_cases_at H_gr₂ c₂ Hc₂, suffices c₁_eq_c₂ : _ ≤ c₁ =ᴮ c₂, by {clear_except H_inj Hc₁ Hc₂ c₁_eq_c₂, refine H_inj v₁ v₂ c₁ c₂ _, bv_split, bv_split, from le_inf (le_inf ‹_› ‹_›) ‹_› }, refine (bv_and.left H_is_func_f) w₁ w₂ c₁ c₂ _ ‹_›, bv_split, bv_split, from le_inf ‹_› ‹_›, repeat {assumption}, end lemma lift_surj_inj_is_total {y z f g S : bSet 𝔹} (H_surj : Γ ≤ is_surj S z f) (H_inj : Γ ≤ is_inj g) (H_is_func_f : Γ ≤ is_func' S z f) : Γ ≤ is_total (subset.mk (λ i : S.type, ⨆ b, b ∈ᴮ y ⊓ ⨆ c, c ∈ᴮ z ⊓ pair (S.func i) c ∈ᴮ f ⊓ pair b c ∈ᴮ g)) y (lift_surj_inj y H_surj H_inj) := begin bv_intro w₁, bv_imp_intro' Hw₁, rw[mem_subset.mk_iff] at Hw₁, bv_cases_at Hw₁ i Hi, have Hi' := (bv_and.left $ bv_and.right Hi), bv_cases_at Hi' b Hb, apply bv_use b, refine le_inf (bv_and.left Hb) _, apply (mem_lift_surj_inj_iff H_is_func_f).mpr, apply bv_rw' (bv_and.left Hi), {apply B_ext_supr, intro i, apply B_ext_inf, swap, simp, apply B_ext_inf, simp, exact B_ext_term (λ z, z ∈ᴮ f) (λ x, pair x i) }, exact (bv_and.right Hb), from ‹_›, from ‹_›, rw[mem_unfold], apply bv_use i, exact le_inf (bv_and.right $ bv_and.right Hi) (bv_and.left Hi), exact bv_and.left Hb end lemma lift_surj_inj_is_surj {y z f g S : bSet 𝔹} (H_surj : Γ ≤ is_surj S z f) (H_inj : Γ ≤ is_inj g) (H_is_func_f : Γ ≤ is_func' S z f) (H_is_func_g : Γ ≤ is_func' y z g) : Γ ≤ is_surj (subset.mk (λ i : S.type, ⨆ b, b ∈ᴮ y ⊓ ⨆ c, c ∈ᴮ z ⊓ pair (S.func i) c ∈ᴮ f ⊓ pair b c ∈ᴮ g)) y (lift_surj_inj y H_surj H_inj) := begin bv_intro b, bv_imp_intro' Hb_mem, have := is_total_of_is_func' H_is_func_g b ‹_›, bv_cases_at this w₂ Hw₂, have := H_surj w₂ (bv_and.left Hw₂), bv_cases_at' this v Hv, bv_split_at Hv, rw[mem_unfold] at Hv_left, apply bv_use v, refine le_inf _ _, { rw[mem_subset.mk_iff], bv_cases_at' Hv_left i Hi, apply bv_use i, refine le_inf (bv_and.right Hi) (le_inf _ (bv_and.left Hi)), { apply bv_use b, refine le_inf ‹_› _, apply bv_use w₂, refine le_inf (le_inf (bv_and.left ‹_›) _) (bv_and.right ‹_›), have := (bv_symm $ bv_and.right Hi), apply @bv_rw' _ _ (func S i) v _ this (λ z, pair z w₂ ∈ᴮ f), swap, from ‹_›, apply B_ext_pair_mem_left }}, { apply (mem_lift_surj_inj_iff H_is_func_f).mpr, apply bv_use w₂, exact le_inf (le_inf (bv_and.left Hw₂) ‹_›) (bv_and.right ‹_›), repeat {assumption}, dsimp [Γ_3], exact inf_le_left_of_le inf_le_left } end end section variable {Γ : 𝔹} variables {x z f g : bSet 𝔹} (y : bSet 𝔹) (H_surj : Γ ≤ is_surj x z f) (H_inj : Γ ≤ is_inj g) -- extends a surjection f : x ↠ z along an injection g : x ↪ y to a surjection -- f' : y ↠ z include H_surj H_inj def extend_surj_inj : bSet 𝔹 := @subset.mk _ _ (prod y z) (λ p, (⨆w, w ∈ᴮ x ⊓ (pair w (z.func p.snd)) ∈ᴮ f ⊓ (pair w (y.func p.fst) ∈ᴮ g ))) variables {y} {H_surj} {H_inj} lemma ex_witness_of_mem_extend_surj_inj {w₁ w₂ : bSet 𝔹} (H_is_func'_f : Γ ≤ is_func' x z f) (H : Γ ≤ pair w₁ w₂ ∈ᴮ (extend_surj_inj y H_surj H_inj)) : Γ ≤ ⨆ w, (w ∈ᴮ x ⊓ (pair w w₁ ∈ᴮ g) ⊓ (pair w w₂ ∈ᴮ f)) := begin bv_cases_at' H pr Hi, bv_split_at Hi, bv_split_at Hi_left, bv_cases_at' Hi_left_left w Hw, apply bv_use w, bv_split_at Hw, bv_split_at Hw_left, simp[pair_eq_pair_iff] at Hi_right, cases Hi_right with H₁ H₂, refine le_inf (le_inf ‹_› _) _, apply bv_rw' H₁, exact B_ext_pair_mem_right, from ‹_›, apply bv_rw' H₂, exact B_ext_pair_mem_right, from ‹_› end lemma mem_extend_surj_inj_iff {w₁ w₂ : bSet 𝔹} {H_mem₁ : Γ ≤ w₁ ∈ᴮ y} {H_mem₂ : Γ ≤ w₂ ∈ᴮ z} (H_is_func'_f : Γ ≤ is_func' x z f) : Γ ≤ pair w₁ w₂ ∈ᴮ (extend_surj_inj y H_surj H_inj) ↔ Γ ≤ ⨆ w, (w ∈ᴮ x ⊓ (pair w w₁ ∈ᴮ g) ⊓ (pair w w₂ ∈ᴮ f)) := begin refine ⟨_,_⟩; intro H, { exact ex_witness_of_mem_extend_surj_inj H_is_func'_f ‹_› }, { unfold extend_surj_inj, rw[mem_subset.mk_iff], bv_cases_at H w Hw, bv_split_at Hw, bv_split_at Hw_left, rw[mem_unfold] at H_mem₁, bv_cases_at H_mem₁ i Hi, rw[mem_unfold] at H_mem₂, bv_cases_at H_mem₂ j Hj, apply bv_use (i,j), refine le_inf _ _, { bv_split, simp[pair_congr, *] }, { refine le_inf _ _, { apply bv_use w, refine le_inf (le_inf ‹_› _) _, bv_split_at Hj, apply @bv_rw' _ _ _ _ _ (bv_symm $ Hj_right) (λ x, pair w x ∈ᴮ f), exact B_ext_pair_mem_right, from ‹_›, bv_split_at Hi, apply @bv_rw' _ _ _ _ _ (bv_symm $ Hi_right) (λ x, pair w x ∈ᴮ g), exact B_ext_pair_mem_right, from ‹_› }, { bv_split, simp* }}} end variables (H_f_is_func' : Γ ≤ is_func' x z f) (H_g_is_func' : Γ ≤ is_func' x y g) include H_f_is_func' H_g_is_func' lemma extend_surj_inj_is_func : Γ ≤ is_func (extend_surj_inj y H_surj H_inj) := begin bv_intro w₁, bv_intro w₂, bv_intro v₁, bv_intro v₂, bv_imp_intro' H_mems, bv_split_at H_mems, bv_imp_intro H_eq, apply_at H_mems_left ex_witness_of_mem_extend_surj_inj ‹_›, tactic.rotate 1, repeat{assumption}, apply_at H_mems_right ex_witness_of_mem_extend_surj_inj ‹_›, tactic.rotate 1, repeat{assumption}, bv_cases_at H_mems_left w₁' Hw₁', bv_cases_at H_mems_right w₂' Hw₂', suffices H_eq' : Γ_4 ≤ w₁' =ᴮ w₂', by {apply eq_of_is_func'_of_eq, from ‹_›, from H_eq', all_goals {bv_split, from ‹_›} }, apply eq_of_is_inj_of_eq ‹_› H_eq, all_goals {bv_split, bv_split, from ‹_›} end lemma extend_surj_inj_is_total : Γ ≤ is_total (image x y g) z (extend_surj_inj y H_surj H_inj) := begin bv_intro w₁, bv_imp_intro' Hw₁, have Hw₁_mem : _ ≤ w₁ ∈ᴮ y := mem_of_mem_subset image_subset Hw₁, rw image at Hw₁, rw[mem_subset.mk_iff] at Hw₁, bv_cases_at Hw₁ i Hi, have Hi' := (bv_and.left $ bv_and.right Hi), bv_cases_at Hi' b' Hb', bv_split_at Hb', have := is_total_of_is_func' H_f_is_func' b' Hb'_left, bv_cases_at this b Hb, apply bv_use b, refine le_inf (bv_and.left Hb) _, apply (mem_extend_surj_inj_iff H_f_is_func').mpr, apply bv_use b', refine le_inf (le_inf ‹_› _) (bv_and.right Hb), apply bv_rw' (bv_and.left Hi), exact B_ext_pair_mem_right, repeat {assumption}, exact bv_and.left ‹_› end lemma extend_surj_inj_is_surj : Γ ≤ is_surj (image x y g) z (extend_surj_inj y H_surj H_inj) := begin bv_intro b', bv_imp_intro' Hb'_mem, have := H_surj b' ‹_›, bv_cases_at this b Hb, bv_split_at Hb, have := is_total_of_is_func' H_g_is_func' b ‹_›, bv_cases_at' this w₂ Hw₂, bv_split_at Hw₂, apply bv_use w₂, refine le_inf _ _, { exact mem_image ‹_› ‹_› ‹_› }, { apply (mem_extend_surj_inj_iff H_f_is_func').mpr, apply bv_use b, exact le_inf (le_inf ‹_› ‹_›) ‹_›, repeat{assumption} } end end lemma bSet_lt_of_lt_of_le {x y z : bSet 𝔹} {Γ} (H₁ : Γ ≤ x ≺ y) (H₂ : Γ ≤ y ≼ z) : Γ ≤ x ≺ z := begin dsimp only [larger_than, injects_into] at ⊢ H₁ H₂, rw[<-imp_bot] at ⊢ H₁, bv_imp_intro H, refine H₁ _, bv_cases_at H S H_S, bv_cases_at H₂ g H_g, bv_cases_at H_S f Hf, bv_split, bv_split, apply bv_use (subset.mk (λ i : S.type, ⨆ b, b ∈ᴮ y ⊓ ⨆ c, c ∈ᴮ z ⊓ pair (S.func i) c ∈ᴮ f ⊓ pair b c ∈ᴮ g)), apply bv_use (lift_surj_inj y ‹_› ‹_›), refine le_inf (le_inf (subset_trans' subset.mk_subset ‹_›) (le_inf _ _)) _, { apply lift_surj_inj_is_func, repeat {assumption} }, { exact lift_surj_inj_is_total Hf_right ‹_› ‹_› }, { exact lift_surj_inj_is_surj Hf_right ‹_› ‹_› (le_inf ‹_› ‹_›) } end lemma bSet_lt_of_le_of_lt {x y z : bSet 𝔹} {Γ} (H₁ : Γ ≤ x ≼ y) (H₂ : Γ ≤ y ≺ z) : Γ ≤ x ≺ z := begin unfold larger_than at ⊢ H₂, rw[<-imp_bot], bv_imp_intro H, unfold injects_into at H₁, rw[<-imp_bot] at H₂, refine H₂ _, bv_cases_at H S HS, bv_cases_at HS f Hf, bv_cases_at H₁ g H_g, apply bv_use (image S y g), bv_split, bv_split_at Hf_left, apply bv_use (extend_surj_inj y ‹_› ‹_›), refine le_inf (le_inf (subset.mk_subset) (le_inf _ _)) _, { apply extend_surj_inj_is_func, from ‹_›, exact is_func'_subset_of_is_func' H_g_left ‹_› }, { apply extend_surj_inj_is_total, from ‹_›, exact is_func'_subset_of_is_func' H_g_left ‹_›}, { apply extend_surj_inj_is_surj, from ‹_›, exact is_func'_subset_of_is_func' H_g_left ‹_› } end section is_func'_comp variables {x y z f g: bSet 𝔹} {Γ : 𝔹} (Hf_func : Γ ≤ is_func' x y f) (Hg_func : Γ ≤ is_func' y z g) include Hf_func Hg_func def is_func'_comp : bSet 𝔹 := subset.mk (λ pr : (prod x z).type, ⨆ b, b ∈ᴮ y ⊓ pair (x.func pr.1) b ∈ᴮ f ⊓ pair b (z.func pr.2) ∈ᴮ g) lemma mem_is_func'_comp_iff {Γ'} {a c : bSet 𝔹} : Γ' ≤ pair a c ∈ᴮ is_func'_comp Hf_func Hg_func ↔ Γ' ≤ a ∈ᴮ x ∧ Γ' ≤ c ∈ᴮ z ∧ Γ' ≤ ⨆ b, b ∈ᴮ y ⊓ (pair a b ∈ᴮ f ⊓ pair b c ∈ᴮ g) := begin refine ⟨_,_⟩; intro H, { refine ⟨_,_,_⟩, { suffices : Γ' ≤ pair a c ∈ᴮ prod x z, by {rw mem_prod_iff at this, from this.left }, refine mem_of_mem_subset (subset.mk_subset) H }, { suffices : Γ' ≤ pair a c ∈ᴮ prod x z, by {rw mem_prod_iff at this, from this.right }, refine mem_of_mem_subset (subset.mk_subset) H }, { erw mem_subset.mk_iff₂ at H, bv_cases_at H pr Hpr, cases pr with i k, bv_split_at Hpr, bv_split_at Hpr_right, bv_cases_at Hpr_right_right b Hb, bv_split_at Hb, apply bv_use b, refine le_inf (bv_and.left ‹_›) _, erw pair_eq_pair_iff at Hpr_right_left, cases Hpr_right_left with H₁ H₂, refine le_inf _ _, apply bv_rw' H₁, from B_ext_pair_mem_left, from bv_and.right ‹_›, apply bv_rw' H₂, from B_ext_pair_mem_right, from ‹_› }}, { erw mem_subset.mk_iff₂, rcases H with ⟨H_mem₁, H_mem₂, H⟩, rw mem_unfold at H_mem₁ H_mem₂, bv_cases_at H_mem₁ i Hi, bv_cases_at H_mem₂ k Hk, apply bv_use (i,k), refine le_inf (le_inf (bv_and.left ‹_›) (bv_and.left ‹_›)) (le_inf _ _), erw pair_eq_pair_iff, from ⟨bv_and.right ‹_›, bv_and.right ‹_›⟩, bv_cases_at H b Hb, bv_split_at Hb, apply bv_use b, bv_split_at Hi, bv_split_at Hk, refine le_inf (le_inf _ _) _, { from ‹_› }, { apply @bv_rw' _ _ _ _ _ (bv_symm Hi_right) (λ w, pair w b ∈ᴮ f), from B_ext_pair_mem_left, from bv_and.left ‹_› }, { apply @bv_rw' _ _ _ _ _ (bv_symm Hk_right) (λ w, pair b w ∈ᴮ g), from B_ext_pair_mem_right, from bv_and.right ‹_› }} end lemma is_func'_comp_is_func : Γ ≤ is_func (is_func'_comp Hf_func Hg_func) := begin bv_intro w₁, bv_intro w₂, bv_intro v₁, bv_intro v₂, bv_imp_intro' H, bv_imp_intro H_eq, bv_split_at H, rw mem_is_func'_comp_iff at H_left H_right, rcases H_right with ⟨Hw₂_mem, Hv₂_mem, Hb₂⟩, rcases H_left with ⟨Hw₁_mem, Hv₁_mem, Hb₁⟩, bv_cases_at Hb₁ b₁ Hb₁', bv_split_at Hb₁', bv_cases_at Hb₂ b₂ Hb₂', bv_split_at Hb₂', bv_split_at Hb₁'_right, bv_split_at Hb₂'_right, refine (is_func_of_is_func' Hg_func b₁ b₂ v₁ v₂ (le_inf ‹_› ‹_›) _), from (is_func_of_is_func' Hf_func w₁ w₂ b₁ b₂ (le_inf ‹_› ‹_›) ‹_›) end lemma is_func'_comp_is_total : Γ ≤ is_total x z (is_func'_comp Hf_func Hg_func) := begin bv_intro a, bv_imp_intro' Ha, have := (is_total_of_is_func' Hf_func) a Ha, bv_cases_at this b Hb, bv_split_at Hb, have := (is_total_of_is_func' Hg_func) b Hb_left, bv_cases_at' this c Hc, bv_split_at Hc, apply bv_use c, refine le_inf ‹_› _, rw mem_is_func'_comp_iff, refine ⟨‹_›,‹_›,_⟩, apply bv_use b, from le_inf ‹_› (le_inf ‹_› ‹_›) end lemma is_func'_comp_is_func' : Γ ≤ is_func' x z (is_func'_comp Hf_func Hg_func) := le_inf (is_func'_comp_is_func _ _) (is_func'_comp_is_total _ _) variables (Hf_inj : Γ ≤ is_inj f) (Hg_inj : Γ ≤ is_inj g) include Hf_inj Hg_inj lemma is_func'_comp_inj : Γ ≤ is_inj (is_func'_comp Hf_func Hg_func) := begin bv_intro w₁, bv_intro w₂, bv_intro v₁, bv_intro v₂, bv_imp_intro' H, bv_split_at H, bv_split_at H_left, rw mem_is_func'_comp_iff at H_left_left H_left_right, rcases H_left_left with ⟨Hw₁, Hv₁, Hb₁⟩, rcases H_left_right with ⟨Hw₂, Hv₂, Hb₂⟩, bv_cases_at Hb₁ b₁ Hb₁', bv_cases_at Hb₂ b₂ Hb₂', bv_split_at Hb₁', bv_split_at Hb₂', bv_split, refine Hf_inj w₁ w₂ b₁ b₂ _, refine le_inf (le_inf ‹_› ‹_›) _, from Hg_inj b₁ b₂ v₁ v₂ (le_inf (le_inf ‹_› ‹_›) ‹_›) end lemma is_func'_comp_surj (H₁ : Γ ≤ is_surj x y f) (H₂ : Γ ≤ is_surj y z g ) : Γ ≤ is_surj x z (is_func'_comp Hf_func Hg_func) := begin bv_intro wz, bv_imp_intro' Hwz_mem, replace H₂ := H₂ wz ‹_›, bv_cases_at H₂ wy Hwy, bv_split_at Hwy, replace H₁ := H₁ wy ‹_›, bv_cases_at H₁ wx Hwz, apply bv_use wx, refine le_inf (bv_and.left ‹_›) _, rw mem_is_func'_comp_iff, bv_split_at Hwz, refine ⟨‹_›,‹_›,_⟩, apply bv_use wy, bv_split_goal end end is_func'_comp def function_comp {x y z f g : bSet 𝔹} {Γ : 𝔹} (H₁ : Γ ≤ is_function x y f) (H₂ : Γ ≤ is_function y z g) : bSet 𝔹 := is_func'_comp (is_func'_of_is_function H₁) (is_func'_of_is_function H₂) lemma function_comp_is_function {x y z f g : bSet 𝔹} {Γ : 𝔹} {H₁ : Γ ≤ is_function x y f} {H₂ : Γ ≤ is_function y z g} : Γ ≤ is_function x z (function_comp H₁ H₂) := begin refine le_inf _ _, { apply is_func'_comp_is_func' }, { apply subset.mk_subset } end def injective_function_comp {x y z f g : bSet 𝔹} {Γ : 𝔹} (H₁ : Γ ≤ is_injective_function x y f) (H₂ : Γ ≤ is_injective_function y z g) : bSet 𝔹 := is_func'_comp (is_func'_of_is_injective_function H₁) (is_func'_of_is_injective_function H₂) lemma injective_function_comp_is_injective_function {x y z f g : bSet 𝔹} {Γ : 𝔹} {H₁ : Γ ≤ is_injective_function x y f} {H₂ : Γ ≤ is_injective_function y z g} : Γ ≤ is_injective_function x z (injective_function_comp H₁ H₂) := begin refine le_inf (by {apply function_comp_is_function; from bv_and.left ‹_›}) _, apply is_func'_comp_inj; from bv_and.right ‹_› end lemma injective_function_comp_is_function {x y z f g : bSet 𝔹} {Γ : 𝔹} {H₁ : Γ ≤ is_injective_function x y f} {H₂ : Γ ≤ is_injective_function y z g} : Γ ≤ is_function x z (injective_function_comp H₁ H₂) := bv_and.left (by apply injective_function_comp_is_injective_function) lemma injects_into_trans {x y z} {Γ : 𝔹} (H₁ : Γ ≤ injects_into x y) (H₂ : Γ ≤ injects_into y z): Γ ≤ injects_into x z := begin bv_cases_at H₁ f Hf, bv_cases_at H₂ g Hg, bv_split_at Hf, bv_split_at Hg, apply bv_use (is_func'_comp Hf_left Hg_left), from le_inf (is_func'_comp_is_func' _ _) (is_func'_comp_inj _ _ Hf_right Hg_right) end lemma injection_into_trans {x y z} {Γ : 𝔹} (H₁ : Γ ≤ injection_into x y) (H₂ : Γ ≤ injection_into y z): Γ ≤ injection_into x z := by {rw ←injects_into_iff_injection_into at H₁ H₂ ⊢, from injects_into_trans H₁ H₂} lemma AE_of_check_func_check₀ (x y : pSet.{u}) {f : bSet 𝔹} {Γ : 𝔹} (H : Γ ≤ is_func' (x̌) (y̌) f) (H_nonzero : ⊥ < Γ) : ∀ (i : x.type), ∃ (j : y.type), ⊥ < (is_func' (x̌) (y̌) f) ⊓ (pair ((x.func i)̌ ) ((y.func j)̌ )) ∈ᴮ f := begin intro i, have := is_total_of_is_func' H ((x.func i)̌ ) (by simp), have H' : Γ ≤ (is_func' (x̌) (y̌) f) ⊓ ⨆ w, w ∈ᴮ (y̌) ⊓ pair (x.func i)̌ w ∈ᴮ f , by exact le_inf ‹_› ‹_›, rw[<-bounded_exists] at H', swap, {change B_ext _, exact B_ext_pair_mem_right}, replace H' := lt_of_lt_of_le H_nonzero H', rw[inf_supr_eq] at H', cases y, dsimp at H', simp only [top_inf_eq] at H', exact (nonzero_wit H') end lemma AE_of_check_func_check (x y : pSet.{u}) {f : bSet 𝔹} {Γ : 𝔹} (H : Γ ≤ is_func' (x̌) (y̌) f) (H_nonzero : ⊥ < Γ) : Π (i : x.type), ∃ (j : y.type ) (Γ' : 𝔹) (H_nonzero' : ⊥ < Γ') (H_le : Γ' ≤ Γ), Γ' ≤ (is_func' (x̌) (y̌) f) ∧ Γ' ≤ (pair ((x.func i)̌ ) ((y.func j)̌ )) ∈ᴮ f := begin intro i, have := is_total_of_is_func' H ((x.func i)̌ ) (by simp), have H' : Γ ≤ (is_func' (x̌) (y̌) f) ⊓ ⨆ w, w ∈ᴮ (y̌) ⊓ pair (x.func i)̌ w ∈ᴮ f , by exact le_inf ‹_› ‹_›, rw[<-bounded_exists] at H', swap, {change B_ext _, exact B_ext_pair_mem_right}, rw[inf_supr_eq] at H', cases y, dsimp at H', simp only [top_inf_eq] at H', have := nonzero_wit' H_nonzero H', cases this with j Hj, use j, use is_func' x̌ (mk y_α (λ (a : y_α), (y_A a)̌ ) (λ (a : y_α), ⊤)) f ⊓ pair (pSet.func x i)̌ (y_A j)̌ ∈ᴮ f ⊓ Γ, use ‹_›, refine ⟨inf_le_right,⟨_,_⟩⟩; tidy_context end -- lemma AE_of_check_func_check' -- (x : pSet.{u}) -- {y f : bSet 𝔹} -- {Γ : 𝔹} -- (H : Γ ≤ is_func' x̌ y f) -- (H_nonezero : ⊥ < Γ) -- : Π (i : x.type), ∃ (b : pSet.{u}) (Γ' : 𝔹) (H_nonzero' : ⊥ < Γ') (H_le : Γ' ≤ Γ), -- Γ' ≤ is_func' x̌ y f ∧ Γ' ≤ pair (x.func i)̌ b̌ ∈ᴮ f := -- begin -- intro i, have := is_total_of_is_func' H ((x.func i)̌ ) (by simp), -- have H' : Γ ≤ (is_func' (x̌) y f) ⊓ ⨆ w, w ∈ᴮ y ⊓ pair (x.func i)̌ w ∈ᴮ f , -- by { exact le_inf ‹_› ‹_› }, -- rw[<-bounded_exists] at H', swap, {change B_ext _, exact B_ext_pair_mem_right}, -- rw[inf_supr_eq] at H', -- this is probably not true -- cases y, dsimp at H', simp only [top_inf_eq] at H', -- -- have := nonzero_wit' H_nonzero H', cases this with j Hj, -- end -- note: primed version of 𝔹-valued casing tactics will only note instead of replacing hypotheses -- this circumvents dependency issues that occasionally pop up lemma exists_surjection_of_surjects_onto {x y : bSet 𝔹} {Γ : 𝔹} (H_surj : Γ ≤ surjects_onto x y) : Γ ≤ ⨆ f, is_function x y f ⊓ is_surj x y f := begin bv_cases_at H_surj f' Hf', apply bv_use (function_of_func' $ bv_and.left Hf'), from le_inf (function_of_func'_is_function _) ( function_of_func'_surj_of_surj _ $ bv_and.right ‹_›), end def functions (x y : bSet 𝔹) : bSet 𝔹 := set_of_indicator (λ s : (bv_powerset (prod x y) : bSet 𝔹).type, is_function x y ((bv_powerset (prod x y)).func s)) @[simp, cleanup] lemma functions_func {x y : bSet 𝔹} {i} : (functions x y).func i = (bv_powerset $ prod x y).func i := rfl @[simp, cleanup] lemma functions_bval {x y : bSet 𝔹} {i} : (functions x y).bval i = is_function x y ((bv_powerset (prod x y)).func i) := rfl @[simp, cleanup] lemma functions_type {x y : bSet 𝔹} : (functions x y).type = (bv_powerset (prod x y)).type := rfl lemma mem_functions_iff {g x y : bSet 𝔹} {Γ : 𝔹} : (Γ ≤ g ∈ᴮ functions x y) ↔ (Γ ≤ is_function x y g) := begin refine ⟨_,_⟩; intro H, { rw[mem_unfold] at H, bv_cases_at H s, bv_split, apply bv_rw' H_1_right, simp, dsimp[functions] at H_1_left, from ‹_›}, { rw[mem_unfold], unfold is_function at H, bv_split, bv_split, have H_right' := bv_powerset_spec.mp H_right, rw[mem_unfold] at H_right', bv_cases_at H_right' s, apply bv_use s, bv_split, refine le_inf _ ‹_›, refine le_inf (le_inf _ _) ‹_›, {apply bv_rw' (bv_symm ‹_ ≤ g =ᴮ func (𝒫 prod x y) s›), simp, from ‹_›}, -- TODO(jesse) why does apply fail to generate a motive for bv_rw'? bv_intro w₁, bv_imp_intro Hw₁, replace H_left_right := H_left_right w₁ ‹_›, bv_cases_at H_left_right w₂, apply bv_use w₂, bv_split, refine le_inf ‹_› _, apply bv_rw' (bv_symm ‹_ ≤ g =ᴮ func (𝒫 prod x y) s›), simp, from ‹_› } end -- /-- f is an injective function on x if it is a function and for every w₁ and w₂ ∈ x, if there exist v₁ and v₂ such that (w₁, v₁) ∈ f and (w₂, v₂) ∈ f, -- then v₁ = v₂ implies w₁ = w₂ -/ -- def is_inj_func (x y) (f : bSet 𝔹) : 𝔹 := -- is_func x y f ⊓ (⨅w₁ w₂, w₁ ∈ᴮ x ⊓ w₂ ∈ᴮ x ⟹ -- (⨆v₁ v₂, (pair w₁ v₁ ∈ᴮ f ⊓ pair w₂ v₂ ∈ᴮ f ⊓ v₁ =ᴮ v₂ ⟹ w₁ =ᴮ w₂))) section function_mk' variables {x y : bSet 𝔹} (F : x.type → y.type) (χ : x.type → 𝔹) (H_ext : ∀ i j {Γ}, Γ ≤ x.func i =ᴮ x.func j → Γ ≤ y.func (F i) =ᴮ y.func (F j)) (H_mem : ∀ i {Γ}, Γ ≤ x.bval i → Γ ≤ y.bval (F i) ∧ Γ ≤ χ i) include H_ext H_mem def function.mk' : bSet 𝔹 := subset.mk (λ pr : (prod x y).type, χ pr.1 ⊓ y.func pr.2 =ᴮ y.func (F pr.1)) @[simp, cleanup]lemma function.mk'_type : (function.mk' F χ H_ext H_mem).type = (prod x y).type := by refl @[simp, cleanup]lemma function.mk'_func {pr} : (function.mk' F χ H_ext H_mem).func pr = (prod x y).func pr := by refl @[simp, cleanup]lemma function.mk'_bval {pr} : (function.mk' F χ H_ext H_mem).bval pr = χ pr.1 ⊓ y.func pr.2 =ᴮ y.func (F pr.1) ⊓ (prod x y).bval pr := by refl @[simp, cleanup]lemma function.mk'_type_forall {ϕ : (function.mk' F χ H_ext H_mem).type → 𝔹} : (⨅(z: (function.mk' F χ H_ext H_mem).type), ϕ z) = ⨅(z : (prod x y).type), ϕ z := by refl lemma function.mk'_is_func {Γ} : Γ ≤ is_func (function.mk' F χ H_ext H_mem) := begin bv_intro w₁, bv_intro w₂, bv_intro v₁, bv_intro v₂, bv_imp_intro H, bv_imp_intro H_eq, bv_split_at H, rw[mem_unfold] at H_left H_right, bv_cases_at H_left pr₁ Hpr₁, bv_cases_at H_right pr₂ Hpr₂, cases pr₁ with i j, cases pr₂ with i' j', simp at *, repeat{auto_cases}, rw[pair_eq_pair_iff] at Hpr₁_right Hpr₂_right, auto_cases, -- floris, don't look at the tactic state have := @H_ext i i' Γ_4 (by bv_cc), bv_cc -- TODO(jesse): 𝔹-valued eblast? end lemma function.mk'_is_total {Γ} : Γ ≤ is_total x y (function.mk' F χ H_ext H_mem) := begin rw is_total_iff_is_total', bv_intro i, bv_imp_intro Hi, apply bv_use (F i), rw[mem_unfold,inf_supr_eq], apply bv_use (i, (F i)), simp* end lemma function.mk'_is_subset {Γ} : Γ ≤ (function.mk' F χ H_ext H_mem) ⊆ᴮ prod x y := begin rw[subset_unfold], simp only with cleanup, bv_intro pr, cases pr with i j, dsimp, bv_imp_intro H_bval, apply bv_use (i,j), simp [le_inf_iff] at *, tidy end lemma function.mk'_is_function {Γ} : Γ ≤ is_function x y (function.mk' F χ H_ext H_mem) := begin refine le_inf (le_inf _ _) _, { apply function.mk'_is_func }, { apply function.mk'_is_total }, { apply function.mk'_is_subset }, end lemma function.mk'_is_inj {Γ} (H_inj : ∀ i j {Γ' : 𝔹}, Γ' ≤ y.func (F i ) =ᴮ y.func (F j) → Γ' ≤ x.func i =ᴮ x.func j) : Γ ≤ is_inj (function.mk' F χ H_ext H_mem) := begin bv_intro w₁, bv_intro w₂, bv_intro v₁, bv_intro v₂, bv_imp_intro H, bv_split_at H, bv_split_at H_left, bv_cases_at H_left_left pr₁ Hpr₁, bv_cases_at H_left_right pr₂ Hpr₂, dsimp at Hpr₁ Hpr₂, bv_split_at Hpr₁, bv_split_at Hpr₂, rw pair_eq_pair_iff at Hpr₁_right Hpr₂_right, cases Hpr₁_right, cases Hpr₂_right, cases pr₁ with i j, cases pr₂ with i' j', specialize @H_inj i i' Γ_3, bv_split, bv_split, dsimp at *, have := H_inj (by bv_cc), bv_cc end end function_mk' section inj_inverse variables {x y f : bSet 𝔹} {Γ : 𝔹} (H_func : Γ ≤ is_func' x y f) (H_inj : Γ ≤ is_inj f) include H_func H_inj def inj_inverse : bSet 𝔹 := subset.mk (λ pr : (prod (image x y f) x).type, pair (x.func pr.2) ((image x y f).func pr.1) ∈ᴮ f) lemma mem_inj_inverse_iff {Γ'} {b a : bSet 𝔹} : Γ' ≤ pair b a ∈ᴮ inj_inverse H_func H_inj ↔ Γ' ≤ a ∈ᴮ x ∧ Γ' ≤ b ∈ᴮ y ∧ Γ' ≤ pair a b ∈ᴮ f := begin refine ⟨_,_⟩; intro H, { unfold inj_inverse at H, rw mem_subset.mk_iff at H, refine ⟨_,_,_⟩, { bv_cases_at H pr Hpr, cases pr with i j, bv_split_at Hpr, erw pair_eq_pair_iff at Hpr_left, cases Hpr_left, simp at Hpr_right, change _ ≤ (λ w, w ∈ᴮ x) _, apply bv_rw' Hpr_left_right, simp, apply mem.mk'', from Hpr_right.right.right }, { bv_cases_at H pr Hpr, cases pr with i j, bv_split_at Hpr, erw pair_eq_pair_iff at Hpr_left, cases Hpr_left, simp at Hpr_right, change _ ≤ (λ w, w ∈ᴮ y) _, apply bv_rw' Hpr_left_left, simp, apply mem_of_mem_subset (image_subset) _, tactic.rotate 2, apply mem.mk'', from Hpr_right.right.left }, { bv_cases_at H pr Hpr, cases pr with i j, bv_split_at Hpr, erw pair_eq_pair_iff at Hpr_left, cases Hpr_left, simp at Hpr_right, apply bv_rw' Hpr_left_right, from B_ext_pair_mem_left, apply bv_rw' Hpr_left_left, from B_ext_pair_mem_right, from Hpr_right.left } }, { erw mem_subset.mk_iff, rcases H with ⟨H₁, H₂, H₃⟩, rw mem_unfold at H₁ H₂, bv_cases_at H₁ i Hi, bv_cases_at H₂ j Hj, apply bv_use (j,i), refine le_inf _ _, { erw pair_eq_pair_iff, refine ⟨_,_⟩, { change _ ≤ _ =ᴮ y.func _, bv_split, bv_cc }, { change _ ≤ _ =ᴮ x.func _, bv_split, bv_cc } }, { refine le_inf _ _, { bv_split_at Hi, bv_split_at Hj, simp, apply @bv_rw' _ _ _ _ _ (bv_symm Hi_right) (λ w, pair w ((y).func j) ∈ᴮ f), from B_ext_pair_mem_left, apply @bv_rw' _ _ _ _ _ (bv_symm Hj_right) (λ w, pair a w ∈ᴮ f), from B_ext_pair_mem_right, from ‹_› }, { bv_split, dsimp, refine le_inf (le_inf _ ‹_›) Hi_left, apply bv_use (func x i), refine le_inf (mem.mk'' ‹_›) _, apply @bv_rw' _ _ _ _ _ (bv_symm Hi_right) (λ w, pair w ((y).func j) ∈ᴮ f), from B_ext_pair_mem_left, apply @bv_rw' _ _ _ _ _ (bv_symm Hj_right) (λ w, pair a w ∈ᴮ f), from B_ext_pair_mem_right, from ‹_› }} } end lemma inj_inverse.is_func : Γ ≤ is_func (inj_inverse H_func H_inj) := begin bv_intro w₁, bv_intro w₂, bv_intro v₁, bv_intro v₂, bv_imp_intro' H, bv_split_at H, bv_imp_intro H_eq, rw mem_inj_inverse_iff at H_left H_right, repeat {auto_cases}, refine H_inj v₁ v₂ w₁ w₂ _, bv_split_goal end lemma inj_inverse.is_total : Γ ≤ is_total (image x y f) x (inj_inverse H_func H_inj) := begin bv_intro z, bv_imp_intro' Hz, rw mem_image_iff at Hz, cases Hz with Hz₁ Hz₂, bv_cases_at Hz₂ z' Hz', apply bv_use z', refine le_inf _ _, { from bv_and.left ‹_› }, { rw mem_inj_inverse_iff, from ⟨bv_and.left ‹_›, ‹_›, bv_and.right ‹_›⟩ } end lemma inj_inverse.is_func' : Γ ≤ is_func' (image x y f) x (inj_inverse H_func H_inj) := begin refine le_inf _ _, { apply inj_inverse.is_func }, { apply inj_inverse.is_total }, end lemma inj_inverse.is_surj : Γ ≤ is_surj (image x y f) x (inj_inverse H_func H_inj) := begin bv_intro z, bv_imp_intro' Hz_mem, have := is_total_of_is_func' H_func, replace this := this z Hz_mem, bv_cases_at this w₂ Hw₂, bv_split_at Hw₂, apply bv_use w₂, refine le_inf _ _, { rw mem_image_iff, refine ⟨‹_›, _⟩, apply bv_use z, from le_inf ‹_› ‹_› }, { rw mem_inj_inverse_iff, from ⟨‹_›,‹_›,‹_›⟩ } end lemma inj_inverse.subset_prod : Γ ≤ inj_inverse H_func H_inj ⊆ᴮ prod (image x y f) x := by { apply subset.mk_subset } lemma inj_inverse.is_function : Γ ≤ is_function (image x y f) x (inj_inverse H_func H_inj) := le_inf (by apply inj_inverse.is_func') (by apply inj_inverse.subset_prod) lemma inj_inverse.is_inj : Γ ≤ is_inj (inj_inverse H_func H_inj) := begin bv_intro w₁, bv_intro w₂, bv_intro v₁, bv_intro v₂, bv_imp_intro' H, bv_split_at H, bv_split_at H_left, rw mem_inj_inverse_iff at H_left_left H_left_right, apply eq_of_is_func'_of_eq H_func H_right, tidy end end inj_inverse section injective_function_inverse def injective_function_inverse {x y f : bSet 𝔹} { Γ : 𝔹 } (H_inj : Γ ≤ is_injective_function x y f) : bSet 𝔹 := inj_inverse (is_func'_of_is_injective_function H_inj) (is_inj_of_is_injective_function H_inj) lemma injective_function_inverse_is_injective_function { x y f : bSet 𝔹 } { Γ : 𝔹 } { H_inj : Γ ≤ is_injective_function x y f } : Γ ≤ is_injective_function (image x y f) x (injective_function_inverse H_inj) := le_inf (by apply inj_inverse.is_function) (by apply inj_inverse.is_inj) lemma injective_function_inverse_is_inj { x y f : bSet 𝔹 } { Γ : 𝔹 } { H_inj : Γ ≤ is_injective_function x y f } : Γ ≤ is_inj (injective_function_inverse H_inj) := bv_and.right (by apply injective_function_inverse_is_injective_function) end injective_function_inverse section function_eval variables { x y f : bSet 𝔹 } { Γ : 𝔹 } (H_func : Γ ≤ is_function x y f) include H_func noncomputable def function_eval (z : bSet 𝔹) (H_mem : Γ ≤ z ∈ᴮ x) : bSet 𝔹 := begin have H_total := (is_total_of_is_function H_func z ‹_›), exact classical.some (exists_convert H_total) end variable { H_func } lemma function_eval_spec { z : bSet 𝔹 } { H_mem : Γ ≤ z ∈ᴮ x } : Γ ≤ (function_eval H_func z H_mem) ∈ᴮ y ⊓ pair z (function_eval H_func z H_mem) ∈ᴮ f := begin let p := _, change _ ≤ _ ⊓ pair z (classical.some p) ∈ᴮ _, exact classical.some_spec p end lemma function_eval_mem_codomain { z : bSet 𝔹 } { H_mem : Γ ≤ z ∈ᴮ x } : Γ ≤ (function_eval H_func z H_mem) ∈ᴮ y := bv_and.left (by apply function_eval_spec) lemma function_eval_pair_mem { z : bSet 𝔹 } { H_mem : Γ ≤ z ∈ᴮ x } : Γ ≤ pair z (function_eval H_func z H_mem) ∈ᴮ f := bv_and.right (by apply function_eval_spec) end function_eval lemma surjects_onto_of_injects_into {x y : bSet 𝔹} {Γ} (H_inj : Γ ≤ injects_into x y) (H_exists_mem : Γ ≤ exists_mem x) : Γ ≤ surjects_onto y x := begin refine surjects_onto_of_larger_than_and_exists_mem _ ‹_›, bv_cases_at H_inj f Hf, bv_split_at Hf, apply bv_use (image x y f), apply bv_use (inj_inverse ‹_› ‹_›), refine le_inf (le_inf image_subset _) _, by apply inj_inverse.is_func', by apply inj_inverse.is_surj end -- section dom_cover -- def dom_section : Π (x : bSet 𝔹), bSet 𝔹 -- | x@⟨α,A,B⟩ := function.mk' (check_shadow_cast_symm : x.type → (check_shadow x).type) (x.bval) -- (by {intros i j Γ, apply B_congr_check_shadow}) (by {intros, simpa[*, check_shadow]}) -- def dom_cover : bSet 𝔹 := sorry -- use surjects_onto_of_injects_into -- def dom_cover (x : bSet 𝔹) : bSet 𝔹 := -- function.mk' (check_shadow_cast : _ → x.type) (λ i, ⊤) _ _ /- by following lemma 1.52 in Bell, should be able to well-order any set via well-ordering principle in pSet -/ -- lemma dom_cover_surjection : is_surj (check_shadow ) := -- end dom_cover def function.mk {u : bSet 𝔹} (F : u.type → bSet 𝔹) (h_congr : ∀ i j, u.func i =ᴮ u.func j ≤ F i =ᴮ F j) : bSet 𝔹 := ⟨u.type, λ a, pair (u.func a) (F a), u.bval⟩ @[simp, cleanup]lemma function.mk_type {u : bSet 𝔹} {F : u.type → bSet 𝔹} {h_congr : ∀ i j, u.func i =ᴮ u.func j ≤ F i =ᴮ F j} : (function.mk F h_congr).type = u.type := by refl @[simp, cleanup]lemma function.mk_func {u : bSet 𝔹} {F : u.type → bSet 𝔹} {h_congr : ∀ i j, u.func i =ᴮ u.func j ≤ F i =ᴮ F j} {i} : (function.mk F h_congr).func i = pair(u.func i) (F i) := by refl @[simp, cleanup]lemma function.mk_bval {u : bSet 𝔹} {F : u.type → bSet 𝔹} {h_congr : ∀ i j, u.func i =ᴮ u.func j ≤ F i =ᴮ F j} {i} : (function.mk F h_congr).bval i = u.bval i := by refl @[simp]lemma function.mk_self {u : bSet 𝔹} {F : u.type → bSet 𝔹} {h_congr : ∀ i j, u.func i =ᴮ u.func j ≤ F i =ᴮ F j} {i : u.type} : u.bval i ≤ pair (u.func i) (F i) ∈ᴮ function.mk F h_congr := by {rw[mem_unfold], apply bv_use i, simp} @[simp]lemma function.mk_self' {u : bSet 𝔹} {F : u.type → bSet 𝔹} {h_congr : ∀ i j, u.func i =ᴮ u.func j ≤ F i =ᴮ F j} {i : u.type} : ⊤ ≤ u.bval i ⟹ pair (u.func i) (F i) ∈ᴮ function.mk F h_congr := by simp /-- This is analogous to the check operation: we collect a type-indexed collection of bSets into a definite bSet -/ def check' {α : Type u} (A : α → bSet 𝔹) : bSet 𝔹 := ⟨α, A, λ x, ⊤⟩ @[simp, cleanup]def check'_type {α : Type u} {A : α → bSet 𝔹} : (check' A).type = α := by refl @[simp, cleanup]def check'_bval {α : Type u} {A : α → bSet 𝔹} {i} : (check' A).bval i = ⊤ := by refl @[simp, cleanup]def check'_func {α : Type u} {A : α → bSet 𝔹} {i} : (check' A).func i = A i := by refl lemma mk_is_func {u : bSet 𝔹} (F : u.type → bSet 𝔹) (h_congr : ∀ i j, u.func i =ᴮ u.func j ≤ F i =ᴮ F j) : ⊤ ≤ is_func (function.mk F h_congr) := begin bv_intro w₁, bv_intro w₂, bv_intro v₁, bv_intro v₂, bv_imp_intro H, bv_imp_intro H_eq, unfold function.mk at H, bv_split_at H, rw[mem_unfold] at H_left H_right, bv_cases_at H_left i Hi, bv_cases_at H_right j Hj, clear_except H_eq Hi Hj, simp[pair_eq_pair_iff] at Hi Hj, repeat{auto_cases}, suffices : Γ_3 ≤ F i =ᴮ F j, by bv_cc, refine le_trans _ (h_congr i j), bv_cc end -- lemma mk_is_func' {u : bSet 𝔹} (F : u.type → bSet 𝔹) (h_congr : ∀ i j, u.func i =ᴮ u.func j ≤ F i =ᴮ F j) {Γ} : Γ ≤ is_func' u (check' F) (function.mk F h_congr) := sorry -- lemma mk_is_func {u : bSet 𝔹} (F : u.type → bSet 𝔹) (h_congr : ∀ i j, u.func i =ᴮ u.func j ≤ F i =ᴮ F j) : ⊤ ≤ is_func u (check' F) (function.mk F h_congr) := -- begin -- repeat{apply le_inf}, -- {bv_intro i, apply bv_imp_intro, have := @prod_mem 𝔹 _ u (check' F) (func u i) (F i), -- apply le_trans _ this, apply le_inf, simp[mem.mk'], apply bv_use i, simp}, -- {bv_intro x, apply bv_imp_intro, bv_intro y, repeat{apply bv_imp_intro}, -- bv_intro v₁, bv_intro v₂, apply bv_imp_intro, -- /- `tidy_context` says -/ apply poset_yoneda, intros Γ a, simp only [le_inf_iff] at a, cases a, cases a_right, cases a_left, cases a_left_left, cases a_left_left_left, -- rw[mem_unfold] at a_right_left a_right_right, -- bv_cases_at a_right_right i, specialize_context Γ, -- bv_cases_at a_right_left j, specialize_context Γ_1, -- clear a_right_right a_right_left, -- bv_split_at a_right_left_1, bv_split_at a_right_right_1, -- simp only with cleanup at a_right_left_1_1_1 a_right_right_1_1_1, -- bv_mp a_right_right_1_1_1 (eq_of_eq_pair_left), -- bv_mp a_right_right_1_1_1 (eq_of_eq_pair_right), -- TODO(jesse) generate sane variable names -- bv_mp a_right_left_1_1_1 (eq_of_eq_pair_left), -- bv_mp a_right_left_1_1_1 (eq_of_eq_pair_right), -- have : Γ_2 ≤ func u i =ᴮ func u j, apply bv_trans, rw[bv_eq_symm], -- assumption, rw[bv_eq_symm], apply bv_trans, rw[bv_eq_symm], -- assumption, assumption, -- TODO(jesse) write a cc-like tactic to automate this -- suffices : Γ_2 ≤ F i =ᴮ F j, -- by {apply bv_trans, assumption, rw[bv_eq_symm], apply bv_trans, -- assumption, from this}, -- apply le_trans this, apply h_congr}, -- the tactics are a success! -- {bv_intro z, rw[<-deduction], rw[top_inf_eq], rw[mem_unfold], apply bv_Or_elim, -- intro i_z, apply bv_use (F i_z), repeat{apply le_inf}, -- {tidy_context, rw[mem_unfold], apply bv_use i_z, apply le_inf, apply le_top, simp}, -- tidy_context, bv_mp a_right (subst_congr_pair_left), show bSet 𝔹, from (F i_z), -- change Γ ≤ (λ w, w ∈ᴮ function.mk F h_congr) (pair z (F i_z)), -- apply bv_rw' a_right_1, apply B_ext_mem_left, apply bv_use i_z, apply le_inf ‹_›, -- simp[bv_eq_refl], -- bv_intro w', repeat{apply bv_imp_intro}, tidy_context, -- rw[mem_unfold] at a_left_right, bv_cases_at a_left_right i_w', -- specialize_context Γ, bv_split_at a_left_right_1, -- change _ ≤ (λv, (F i_z) =ᴮ v) w', apply bv_rw' a_left_right_1_1_1, -- {simp[B_ext], intros x y, rw[inf_comm], apply bv_eq_trans}, -- change Γ_1 ≤ F i_z =ᴮ F i_w', simp only with cleanup at *, -- bv_cases_at a_right i_pair, specialize_context Γ_1, bv_split_at a_right_1, -- bv_mp a_right_1_1_1 (eq_of_eq_pair_left), bv_mp a_right_1_1_1 (eq_of_eq_pair_right), -- bv_split_at a_left_right_1, clear a_right_1_1 a_right_1 a_left_right_1_1 a_left_right_1_2 a_right_1_1_1, -- clear a_left_right_1 a_left_right a_left_left_left a_right, -- have : Γ_2 ≤ F i_z =ᴮ F i_pair, -- by {apply le_trans _ (h_congr _ _), apply bv_trans, rw[bv_eq_symm], from ‹_›, from ‹_›}, -- apply bv_trans, exact this, apply bv_trans, rw[bv_eq_symm], from ‹_›, from ‹_›} -- end lemma mk_inj_of_inj {u : bSet 𝔹} {F : u.type → bSet 𝔹} (h_inj : ∀ i j, i ≠ j → F i =ᴮ F j ≤ ⊥) (h_congr : ∀ i j, u.func i =ᴮ u.func j ≤ F i =ᴮ F j) : ⊤ ≤ is_inj (function.mk F h_congr) := begin bv_intro w₁, bv_intro w₂, bv_intro v₁, bv_intro v₂, apply bv_imp_intro, rw[top_inf_eq], rw[mem_unfold, mem_unfold], rw[deduction], apply bv_cases_left, intro i, apply bv_cases_right, intro j, apply bv_imp_intro, simp, tidy_context, haveI : decidable (i = j) := classical.prop_decidable _, by_cases i = j, {subst h, have : Γ ≤ pair w₁ v₁ =ᴮ pair w₂ v₂, by apply bv_trans; {tidy}, bv_mp this eq_of_eq_pair_left, from ‹_›}, have := h_inj i j h, by_cases Γ = ⊥, rw[h], apply bot_le, suffices : Γ = ⊥, by contradiction, apply bot_unique, suffices : Γ ≤ F i =ᴮ F j, by {apply le_trans this ‹_›}, bv_mp a_left_left_right eq_of_eq_pair_right, bv_mp a_left_right_right eq_of_eq_pair_right, from bv_trans (bv_symm ‹_›) (bv_trans a_right ‹_›) end -- lemma mk_inj_of_inj {u : bSet 𝔹} {F : u.type → bSet 𝔹} (h_inj : ∀ i j, i ≠ j → F i =ᴮ F j ≤ ⊥) (h_congr : ∀ i j, u.func i =ᴮ u.func j ≤ F i =ᴮ F j) : -- ⊤ ≤ is_inj_func u (check' F) (function.mk F h_congr) := -- begin -- apply le_inf, apply mk_is_func, -- bv_intro w₁, bv_intro w₂, apply bv_imp_intro, rw[top_inf_eq], -- rw[mem_unfold, mem_unfold], apply bv_cases_left, intro i, -- apply bv_cases_right, intro j, apply le_supr_of_le (F i), -- apply le_supr_of_le (F j), apply bv_imp_intro, -- tidy_context, -- haveI : decidable (i = j) := by apply classical.prop_decidable, -- by_cases i = j, -- { subst h, apply bv_trans, tidy}, -- have := h_inj i j h, -- by_cases Γ = ⊥, rw[h], apply bot_le, -- suffices : Γ = ⊥, by contradiction, -- apply bot_unique, from le_trans ‹_› this -- end lemma bot_of_mem_self {x : bSet 𝔹} : ⊤ ≤ (x ∈ᴮ x ⟹ ⊥) := begin induction x, simp[-imp_bot, bv_eq,mem], intro i, specialize x_ih i, apply bot_unique, apply bv_have_true x_ih, tidy_context, bv_mp a_left_left (show x_B i ≤ x_A i ∈ᴮ mk x_α x_A x_B, by apply mem.mk), change Γ ≤ (x_A i ∈ᴮ mk x_α x_A x_B) at a_left_left_1, have : Γ ≤ x_A i ∈ᴮ x_A i, rw[show Γ = Γ ⊓ Γ, by simp], apply le_trans, apply inf_le_inf, exact a_left_right, exact a_left_left_1, apply subst_congr_mem_right, have x_ih2 : Γ ≤ _ := le_trans (le_top) x_ih, exact context_imp_elim x_ih2 ‹_› end lemma bot_of_mem_self' {x : bSet 𝔹} {Γ} (H : Γ ≤ (x ∈ᴮ x)) : Γ ≤ ⊥ := begin have := @bot_of_mem_self 𝔹 _ x, rw[<-deduction, top_inf_eq] at this, from le_trans H this end lemma bot_of_zero_eq_one {Γ : 𝔹} (H : Γ ≤ 0 =ᴮ 1) : Γ ≤ ⊥ := bot_of_mem_self' $ by {apply bv_rw' H, simp, from zero_mem_one} -- lemma bot_of_mem_mem_aux {x : bSet 𝔹} {i : x.type} : ⊤ ≤ ( x ∈ᴮ x.func i ⟹ ⊥) := -- begin -- induction x, apply bv_imp_intro, rw[top_inf_eq], rw[mem_unfold], -- apply bv_Or_elim, intro j, -- specialize x_ih i, swap, exact j, tidy_context, -- bv_mp a_left (show bval (func (mk x_α x_A x_B) i) j ≤ (func (func (mk _ _ _) i) j) ∈ᴮ func (mk _ _ _) i, by apply mem.mk'), -- end lemma bot_of_mem_mem (x y : bSet 𝔹) : ⊤ ≤ ((x ∈ᴮ y ⊓ y ∈ᴮ x) ⟹ ⊥) := begin induction x generalizing y, induction y, simp[-imp_bot, -top_le_iff, mem], apply bv_imp_intro, rw[top_inf_eq], apply bv_cases_right, intro a', apply bv_cases_left, intro a'', specialize x_ih a', tidy_context, specialize y_ih a'', bv_mp a_right_left (show x_B a' ≤ _ ∈ᴮ (mk x_α x_A x_B), by apply mem.mk), change Γ ≤ _ ∈ᴮ (mk x_α x_A x_B) at a_right_left_1, bv_mp a_left_left (show y_B a'' ≤ _ ∈ᴮ (mk y_α y_A y_B), by apply mem.mk), change Γ ≤ _ ∈ᴮ (mk y_α y_A y_B) at a_left_left_1, have this₁ : Γ ≤ x_A a' ∈ᴮ y_A a'', apply le_trans' a_right_left_1, apply le_trans, apply inf_le_inf, from a_left_right, refl, apply subst_congr_mem_right, have this₂ : Γ ≤ y_A a'' ∈ᴮ x_A a', apply le_trans' a_left_left_1, apply le_trans, apply inf_le_inf, from a_right_right, refl, apply subst_congr_mem_right, specialize x_ih (y_A a''), specialize_context_at x_ih Γ, bv_to_pi x_ih, apply x_ih, bv_split_goal end lemma bot_of_mem_mem' (x y : bSet 𝔹) {Γ} (H : Γ ≤ x ∈ᴮ y) (H' : Γ ≤ y ∈ᴮ x) : Γ ≤ ⊥ := begin have : Γ ≤ ((x ∈ᴮ y ⊓ y ∈ᴮ x) ⟹ ⊥), by {refine le_trans le_top (bot_of_mem_mem _ _) }, exact this (le_inf ‹_› ‹_›) end end extras section check variables {𝔹 : Type u} [nontrivial_complete_boolean_algebra 𝔹] -- lemma mem_check_mem_powerset_nonzero_iff {x : pSet} {S : (pSet.powerset x).type} {i : x.type} : -- (⊥ : 𝔹) < (x.func i)̌ ∈ᴮ ((pSet.powerset x).func S)̌ ↔ (cast pSet.powerset_type S) i := -- begin -- refine ⟨_,_⟩; intro H, -- { sorry }, -- { sorry } -- end example {x : bSet 𝔹} {i : x.type} {χ : x.type → 𝔹} : χ i ≤ (x.func i) ∈ᴮ (set_of_indicator χ) := by {rw[mem_unfold], tidy_context, apply bv_use i, bv_split_goal} lemma check_powerset_subset_powerset (x : pSet) {Γ : 𝔹} : Γ ≤ (pSet.powerset x)̌ ⊆ᴮ (bv_powerset (x̌)) := begin rw[subset_unfold], bv_intro s, simp only [mem, bval, top_imp, func, check, check_bval_top], suffices : ∃ χ : (x̌).type → 𝔹, Γ ≤ ((pSet.powerset x)̌ .func s) =ᴮ (set_of_indicator χ), by {cases this with χ Hχ, rw[mem_unfold], apply bv_use χ, refine le_inf _ ‹_›, { change _ ≤ _ ⊆ᴮ _, have := bv_rw' (bv_symm Hχ), show bSet 𝔹 → 𝔹, from λ z, z ⊆ᴮ x̌, from this, by simp, have eq_check_type : type ((p𝒫 x)̌ ) = pSet.type (p𝒫 x) := by {simp, recover, all_goals{from ‹_›} }, suffices this : (p𝒫 x).func (cast eq_check_type s) ⊆ x, by {convert check_subset this, cases x, refl}, from pSet.mem_powerset.mp (by convert pSet.mem.mk (p𝒫 x).func _; from pSet.mk_eq)}}, cases x with α A, use (λ i, Prop_to_bot_top (s i)), refine subset_ext _ _, { rw[subset_unfold], bv_intro j, bv_imp_intro Hj, simp, apply bv_use j.val, refine le_inf _ _, { have := j.property, unfold Prop_to_bot_top, simp* }, { exact bv_refl }}, { rw[subset_unfold], bv_intro j, bv_imp_intro Hj, simp, let Q := bval (set_of_indicator (λ (i : type $ (pSet.mk α A)̌ ), Prop_to_bot_top (s i))) j, haveI := classical.prop_decidable, by_cases H: ⊥ < Q, { suffices : s j, by { refine bv_use ⟨j, this⟩, swap, simp*, transitivity ⊤, { exact le_top }, { exact bv_refl }}, by_contra, suffices this : Q = ⊥, by {rw[this] at H, simpa using H}, dsimp[Q, Prop_to_bot_top], simp* }, { rw[bot_lt_iff_not_le_bot] at H, push_neg at H, transitivity ⊥, { exact le_trans Hj H }, { exact bot_le }}} end lemma check_functions_subset_functions {x y : pSet.{u}} {Γ : 𝔹} : Γ ≤ (pSet.functions x y)̌ ⊆ᴮ functions x̌ y̌ := begin rw subset_unfold', bv_intro w, bv_imp_intro Hw, rw mem_unfold at Hw, bv_cases_at Hw f Hf, bv_split_at Hf, rw check_func at Hf_right, let g := _, change _ ≤ w =ᴮ ǧ at Hf_right, suffices : pSet.is_func x y g, by {rw mem_functions_iff, apply bv_rw' Hf_right, simp, from check_is_func this }, apply (pSet.mem_functions_iff _).mp, dsimp[g], apply pSet.mem.mk end @[simp]lemma check_mem' {y : pSet} {i : y.type} : ((y.func i)̌ ) ∈ᴮ y̌ = (⊤ : 𝔹) := by {apply top_unique, simp} lemma of_nat_inj {n k : ℕ} (H_neq : n ≠ k) : ((of_nat n : bSet 𝔹) =ᴮ of_nat k) = ⊥ := check_bv_eq_bot_of_not_equiv (pSet.of_nat_inj ‹_›) lemma of_nat_mem_of_lt {k₁ k₂ : ℕ} (H_lt : k₁ < k₂) {Γ} : Γ ≤ (bSet.of_nat k₁ : bSet 𝔹) ∈ᴮ (bSet.of_nat k₂) := check_mem $ pSet.of_nat_mem_of_lt H_lt lemma check_succ_eq_succ_check {n : ℕ} : (of_nat (n.succ) : bSet 𝔹) = bSet.succ (of_nat n) := by simp[of_nat, succ, pSet.of_nat] @[simp]lemma zero_eq_some_none {Γ : 𝔹} : Γ ≤ 0 =ᴮ two.func (some none) := bv_refl end check section powerset parameters {𝔹 : Type u} [nontrivial_complete_boolean_algebra 𝔹] parameter (x : bSet 𝔹) local notation `fx2` := functions x 𝟚 def powerset_injects.F : (bv_powerset x).type → (functions x 𝟚).type := λ χ, λ pr, ((x.func pr.1 ∈ᴮ set_of_indicator χ ⊓ (𝟚.func (pr.2) =ᴮ 0)) ⊔ ((x.func pr.1) ∈ᴮ (subset.mk (λ i, - ((x.func i) ∈ᴮ set_of_indicator χ))) ⊓ (𝟚.func (pr.2) =ᴮ 1))) lemma mem_powerset_injects.F_iff {Γ : 𝔹} {χ : x.type → 𝔹} {z : bSet 𝔹} : Γ ≤ pair z 0 ∈ᴮ func (functions x 𝟚) (powerset_injects.F χ) ↔ Γ ≤ z ∈ᴮ set_of_indicator χ := begin refine ⟨_,_⟩; intro H, { rw mem_unfold at H, bv_cases_at H pr Hpr, bv_split_at Hpr, cases pr with i j, erw pair_eq_pair_iff at Hpr_right, cases Hpr_right with Hpr_right.left Hpr_right.right, bv_or_elim_at Hpr_left, change _ ≤ (λ w, w ∈ᴮ set_of_indicator χ) _, apply bv_rw' Hpr_right.left, simp, from bv_and.left ‹_›, apply bv_exfalso, apply bot_of_zero_eq_one, have := bv_and.right Hpr_left.right, bv_cc}, { bv_cases_at H i Hi, bv_split_at Hi, rw mem_unfold, apply bv_use (i, some none), refine le_inf _ _, { apply bv_or_left, refine le_inf _ _, { change _ ≤ (λ w, w ∈ᴮ (set_of_indicator χ)) _, apply bv_rw' (bv_symm Hi_right), simp, from ‹_› }, { exact bv_refl }}, { change _ ≤ pair _ _ =ᴮ pair _ _, simp [pair_eq_pair_iff, *] }} end lemma powerset_injects.F_ext : ∀ (i j : type (𝒫 x)) {Γ : 𝔹}, Γ ≤ func (𝒫 x) i =ᴮ func (𝒫 x) j → Γ ≤ func (functions x 𝟚) (powerset_injects.F i) =ᴮ func (functions x 𝟚) (powerset_injects.F j) := begin intros χ₁ χ₂ Γ H, apply mem_ext; bv_intro z; bv_imp_intro Hz, { rw mem_unfold at Hz, bv_cases_at Hz ρ Hρ, rw[eq_iff_subset_subset, le_inf_iff] at H, cases ρ with i j, bv_split_at Hρ, cases H with H₁ H₂, bv_or_elim_at Hρ_left, { rename Hρ_left.left Hρ_left, bv_split_at Hρ_left, apply bv_use (i,j), refine le_inf (bv_or_left $ le_inf _ _) _, tactic.rotate 1, from ‹_›, from Hρ_right, refine mem_of_mem_subset H₁ ‹_› }, { rename Hρ_left.right Hρ_left, bv_split_at Hρ_left, apply bv_use (i,j), refine le_inf (bv_or_right $ le_inf _ _) _, tactic.rotate 1, from ‹_›, from Hρ_right, rw mem_subset.mk_iff at Hρ_left_left ⊢, bv_cases_at Hρ_left_left i' Hi', bv_split_at Hi', apply bv_use i', refine le_inf ‹_› _, rw ←imp_bot, refine le_inf _ (bv_and.right ‹_›), bv_imp_intro H', exact bv_absurd _ (mem_of_mem_subset H₂ ‹_›) (bv_and.left Hi'_right)}, }, {rw mem_unfold at Hz, bv_cases_at Hz ρ Hρ, rw[eq_iff_subset_subset, le_inf_iff] at H, cases ρ with i j, bv_split_at Hρ, cases H with H₁ H₂, bv_or_elim_at Hρ_left, { rename Hρ_left.left Hρ_left, bv_split_at Hρ_left, apply bv_use (i,j), refine le_inf (bv_or_left $ le_inf _ _) _, tactic.rotate 1, from ‹_›, from Hρ_right, refine mem_of_mem_subset H₂ ‹_› }, { rename Hρ_left.right Hρ_left, bv_split_at Hρ_left, apply bv_use (i,j), refine le_inf (bv_or_right $ le_inf _ _) _, tactic.rotate 1, from ‹_›, from Hρ_right, rw mem_subset.mk_iff at Hρ_left_left ⊢, bv_cases_at Hρ_left_left i' Hi', bv_split_at Hi', apply bv_use i', refine le_inf ‹_› _, rw ←imp_bot, refine le_inf _ (bv_and.right ‹_›), bv_imp_intro H', exact bv_absurd _ (mem_of_mem_subset H₁ ‹_›) (bv_and.left ‹_›)}, } end lemma powerset_injects.F_subset_prod {χ : x.type → 𝔹} {Γ : 𝔹} {H_le : Γ ≤ set_of_indicator χ ⊆ᴮ x} : Γ ≤ func (𝒫 prod x 𝟚) (powerset_injects.F χ) ⊆ᴮ prod x 𝟚 := begin change _ ≤ set_of_indicator _ ⊆ᴮ _, rw subset_unfold, bv_intro pr, bv_imp_intro H_pr, cases pr with i j, bv_or_elim_at H_pr, { rename H_pr.left H_pr, bv_split_at H_pr, have := mem_of_mem_subset H_le H_pr_left, rw mem_unfold at this, bv_cases_at this i' Hi, apply bv_use (i',j), simp, bv_split_at Hi, rw pair_eq_pair_iff, refine ⟨‹_›,_,bv_refl⟩, bv_cc }, { rename H_pr.right H_pr, bv_split_at H_pr, rw mem_subset.mk_iff at H_pr_left, bv_cases_at H_pr_left i' Hi', bv_split_at Hi', rw mem_unfold, apply bv_use (i', j), refine le_inf _ _, { simp, from bv_and.right ‹_› }, { erw pair_eq_pair_iff, refine ⟨‹_›, bv_refl⟩ }}, end lemma powerset_injects.F_mem : ∀ (i : type (𝒫 x)) {Γ : 𝔹}, Γ ≤ bval (𝒫 x) i → Γ ≤ bval (functions x 𝟚) (powerset_injects.F i) ∧ Γ ≤ ⊤ := begin intros χ Γ H_le, change _ ≤ (set_of_indicator χ) ⊆ᴮ x at H_le, refine ⟨_,le_top⟩, simp only with cleanup, refine le_inf (le_inf _ _) _, { bv_intro v₁, bv_intro v₂, bv_intro w₁, bv_intro w₂, bv_imp_intro H, bv_split_at H, bv_imp_intro H_eq, have := @powerset_injects.F_subset_prod _ _ x χ Γ_2 ‹_›, have H_pm_left := mem_of_mem_subset this H_left, have H_pm_right := mem_of_mem_subset this H_right, rw mem_prod_iff at H_pm_left H_pm_right, cases H_pm_left with Hv₁ Hw₁, cases H_pm_right with Hv₂ Hw₂, bv_cases_at H_left pr₁ Hpr₁, bv_cases_at H_right pr₂ Hpr₂, cases pr₁ with i₁ j₁, cases pr₂ with i₂ j₂, bv_split_at Hpr₁, bv_split_at Hpr₂, bv_or_elim_at Hpr₁_left; bv_or_elim_at Hpr₂_left, { erw pair_eq_pair_iff at Hpr₁_right Hpr₂_right, auto_cases, bv_split_at Hpr₁_left.left, bv_split_at Hpr₂_left.left, bv_cc }, {bv_exfalso, refine bv_absurd _ (bv_and.left Hpr₁_left.left) _, bv_split_at Hpr₂_left.right, rw mem_subset.mk_iff at Hpr₂_left.right_left, bv_cases_at Hpr₂_left.right_left i Hi, bv_split_at Hi, suffices : Γ_7 ≤ x.func i₁ =ᴮ x.func i, by {apply @bv_rw' _ _ _ _ _ this (λ w, -(w ∈ᴮ set_of_indicator χ)), simp, from bv_and.left ‹_› }, erw pair_eq_pair_iff at Hpr₁_right Hpr₂_right, auto_cases, bv_cc }, {bv_exfalso, refine bv_absurd _ (bv_and.left Hpr₂_left.left) _, bv_split_at Hpr₁_left.right, rw mem_subset.mk_iff at Hpr₁_left.right_left, bv_cases_at Hpr₁_left.right_left i Hi, bv_split_at Hi, suffices : Γ_7 ≤ x.func i₂ =ᴮ x.func i, by {apply @bv_rw' _ _ _ _ _ this (λ w, -(w ∈ᴮ set_of_indicator χ)), simp, from bv_and.left ‹_› }, erw pair_eq_pair_iff at Hpr₁_right Hpr₂_right, auto_cases, bv_cc }, { erw pair_eq_pair_iff at Hpr₁_right Hpr₂_right, auto_cases, bv_split_at Hpr₁_left.right, bv_split_at Hpr₂_left.right, bv_cc } }, { bv_intro z, bv_imp_intro Hz, bv_cases_on z ∈ᴮ (set_of_indicator χ), {apply bv_use (0 : bSet 𝔹), rw le_inf_iff, refine ⟨_,_⟩, { from of_nat_mem_of_lt dec_trivial }, { rw mem_unfold at Hz, bv_cases_at Hz i Hi, bv_split_at Hi, apply bv_rw' Hi_right, from B_ext_pair_mem_left, rw mem_unfold, apply bv_use (i, some none), refine le_inf _ _, { apply bv_or_left, refine le_inf _ _, { change _ ≤ (λ w, w ∈ᴮ set_of_indicator χ) _, apply bv_rw' (bv_symm Hi_right), simpa }, { from bv_refl } }, { erw pair_eq_pair_iff, simp* }}}, {apply bv_use (1 : bSet 𝔹), rw le_inf_iff, refine ⟨_,_⟩, { from of_nat_mem_of_lt dec_trivial }, { rw mem_unfold at Hz, bv_cases_at Hz i Hi, bv_split_at Hi, apply bv_rw' Hi_right, from B_ext_pair_mem_left, rw mem_unfold, apply bv_use (i, none), refine le_inf _ _, { apply bv_or_right, refine le_inf _ _, { dsimp only, let p := _, change _ ≤ _ ∈ᴮ p, change _ ≤ (λ w, w ∈ᴮ p) _, apply bv_rw' (bv_symm Hi_right), simp, dsimp only [p], rw mem_subset.mk_iff, apply bv_use i, refine le_inf ‹_› (le_inf _ ‹_›), apply @bv_rw' _ _ _ _ _ (bv_symm Hi_right) (λ w, - (w ∈ᴮ set_of_indicator χ)), simp, from ‹_› }, { from bv_refl },}, { erw pair_eq_pair_iff, from ⟨by simp*, bv_refl⟩ }}}}, apply powerset_injects.F_subset_prod, from ‹_› end lemma powerset_injects.F_inj : ∀ (i j : (𝒫 x).type) {Γ}, Γ ≤ (fx2).func (powerset_injects.F i ) =ᴮ (fx2).func (powerset_injects.F j) → Γ ≤ (𝒫 x).func i =ᴮ (𝒫 x).func j := begin intros χ₁ χ₂ Γ H, apply mem_ext, { bv_intro z, bv_imp_intro Hz, erw ←mem_powerset_injects.F_iff at Hz, have := bv_rw'' H Hz, erw mem_powerset_injects.F_iff at this, exact this }, { bv_intro z, bv_imp_intro Hz, erw ←mem_powerset_injects.F_iff at Hz, have := bv_rw'' (bv_symm H) Hz, erw mem_powerset_injects.F_iff at this, exact this }, end def powerset_injects.f : bSet 𝔹 := function.mk' powerset_injects.F (λ _, ⊤) powerset_injects.F_ext powerset_injects.F_mem lemma powerset_injects_into_functions {x : bSet 𝔹} {Γ : 𝔹} : Γ ≤ injects_into (bv_powerset x) (functions x 𝟚) := begin apply bv_use (powerset_injects.f x), refine le_inf _ _, { exact is_func'_of_is_function (function.mk'_is_function _ _ _ _) }, { exact function.mk'_is_inj _ _ _ _ (powerset_injects.F_inj _) } end end powerset section ordinals variables {𝔹 : Type u} [nontrivial_complete_boolean_algebra 𝔹] @[reducible]def epsilon_trichotomy (x : bSet 𝔹) : 𝔹 := (⨅y, y∈ᴮ x ⟹ (⨅z, z ∈ᴮ x ⟹ (y =ᴮ z ⊔ y ∈ᴮ z ⊔ z ∈ᴮ y))) @[reducible]def epsilon_well_founded (x : bSet 𝔹) : 𝔹 := (⨅u, u ⊆ᴮ x ⟹ (- (u =ᴮ ∅) ⟹ ⨆y, y∈ᴮ u ⊓ (⨅z', z' ∈ᴮ u ⟹ (- (z' ∈ᴮ y))))) def epsilon_well_orders (x : bSet 𝔹) : 𝔹 := epsilon_trichotomy x ⊓ epsilon_well_founded x @[reducible]def ewo (x : bSet 𝔹) : 𝔹 := epsilon_well_orders x @[simp]lemma B_ext_ewo : B_ext (λ w : bSet 𝔹, epsilon_well_orders w) := by simp[epsilon_well_orders] lemma epsilon_dichotomy (x y z : bSet 𝔹) : epsilon_well_orders x ≤ y ∈ᴮ x ⟹ (z ∈ᴮ x ⟹ (y =ᴮ z ⊔ y ∈ᴮ z ⊔ z ∈ᴮ y)) := begin unfold epsilon_well_orders, apply bv_imp_intro, tidy_context, bv_to_pi', specialize a_left_left y, dsimp at a_left_left, bv_to_pi', specialize a_left_left ‹_›, bv_to_pi', exact a_left_left z end def is_transitive (x : bSet 𝔹) : 𝔹 := ⨅y, y∈ᴮ x ⟹ y ⊆ᴮ x lemma subset_of_mem_transitive {x w : bSet 𝔹} {Γ : 𝔹} (H₁ : Γ ≤ is_transitive x) (H₂ : Γ ≤ w ∈ᴮ x) : Γ ≤ w ⊆ᴮ x := by {bv_specialize_at H₁ w, bv_to_pi H₁_1, solve_by_elim} @[simp] lemma B_ext_is_transitive : B_ext (is_transitive : bSet 𝔹 → 𝔹) := by {intros x y, unfold is_transitive, revert x y, change B_ext _, simp} def Ord (x : bSet 𝔹) : 𝔹 := epsilon_well_orders x ⊓ is_transitive x lemma epsilon_trichotomy_of_Ord {x a b : bSet 𝔹} {Γ} (Ha_mem : Γ ≤ a ∈ᴮ x) (Hb_mem : Γ ≤ b ∈ᴮ x) (H_Ord : Γ ≤ Ord x) : Γ ≤ a =ᴮ b ⊔ a ∈ᴮ b ⊔ b ∈ᴮ a := bv_and.left (bv_and.left H_Ord) a Ha_mem b Hb_mem local infix `≺`:75 := (λ x y, -(larger_than x y)) local infix `≼`:75 := (λ x y, injects_into x y) lemma injects_into_of_subset {x y : bSet 𝔹} {Γ} (H : Γ ≤ x ⊆ᴮ y) : Γ ≤ x ≼ y := begin refine bv_use _, {refine set_of_indicator _, show bSet 𝔹, exact prod x y, rintro ⟨a,b⟩, exact (x.func a) =ᴮ (y.func b) ⊓ x.bval a ⊓ y.bval b }, { refine le_inf _ _, { rw[is_func', is_func], refine le_inf _ _, { bv_intro w₁, bv_intro w₂, bv_intro v₁, bv_intro v₂, bv_imp_intro H', bv_imp_intro H_eq, bv_split, bv_cases_at H'_left p₁, bv_cases_at H'_right p₂, cases p₁ with i₁ i₂, cases p₂ with j₁ j₂, rename H'_left_1 H₁, rename H'_right_1 H₂, clear_except H₁ H₂ H_eq, simp only [le_inf_iff] at H₁ H₂, repeat{auto_cases}, have := eq_of_eq_pair H₁_right, have := eq_of_eq_pair H₂_right, repeat{auto_cases}, bv_cc }, {bv_intro w₁, bv_imp_intro w₁_mem_x, apply bv_use w₁, rw[subset_unfold'] at H, replace H := H w₁ ‹_›, refine le_inf ‹_› _, dsimp, rw[mem_unfold] at w₁_mem_x, rw[mem_unfold] at H, bv_cases_at w₁_mem_x i, bv_cases_at H j, apply bv_use (i,j), simp only [le_inf_iff], refine ⟨⟨⟨_,_⟩,_⟩,_⟩, refine bv_trans _ (bv_and.right H_1), apply bv_symm, exact bv_trans (bv_and.right w₁_mem_x_1) (bv_refl), exact bv_and.left w₁_mem_x_1, exact bv_and.left H_1, refine pair_congr _ _, exact bv_and.right w₁_mem_x_1, exact bv_and.right H_1}}, { bv_intro w₁, bv_intro w₂, bv_intro v₁, bv_intro v₂, simp, bv_imp_intro, bv_split, bv_split, bv_cases_at H_1_left_left i, bv_cases_at H_1_left_right j, rcases i with ⟨i₁,i₂⟩, rcases j with ⟨j₁,j₂⟩, clear H_1_left_left H_1_left_right, bv_split, simp only [le_inf_iff] at H_1_left_right_1_left H_1_left_left_1_left, apply_all eq_of_eq_pair, repeat{auto_cases}, bv_cc }} end lemma injects_into_refl {Γ} {x : bSet 𝔹} : Γ ≤ x ≼ x := injects_into_of_subset subset_self lemma bSet_le_of_subset {x y : bSet 𝔹} {Γ} (H : Γ ≤ x ⊆ᴮ y) : Γ ≤ x ≼ y := injects_into_of_subset H lemma injection_into_of_subset {x y : bSet 𝔹} {Γ} (H : Γ ≤ x ⊆ᴮ y) : Γ ≤ injection_into x y := injects_into_iff_injection_into.mp $ injects_into_of_subset ‹_› def Card (y : bSet 𝔹) : 𝔹 := Ord(y) ⊓ ⨅x, x ∈ᴮ y ⟹ (- larger_than y x) lemma is_transitive_of_mem_Ord (y x : bSet 𝔹) : Ord x ⊓ y ∈ᴮ x ≤ (is_transitive y) := begin apply bSet.rec_on' y, clear y, intros y y_ih, bv_intro w, apply bv_imp_intro, rw[subset_unfold'], bv_intro z, apply bv_imp_intro, unfold Ord, tidy_context, bv_specialize_at a_left_left_left_right y, bv_imp_elim_at a_left_left_left_right_1 ‹_›, rw[subset_unfold'] at H, bv_specialize_at H w, bv_imp_elim_at H_1 ‹_›, bv_specialize_at a_left_left_left_right w, bv_imp_elim_at a_left_left_left_right_2 ‹_›, rw[subset_unfold'] at H_3, bv_specialize_at H_3 z, bv_imp_elim_at H_3_1 ‹_›, bv_mp a_left_left_left_left (epsilon_dichotomy x y z), bv_imp_elim_at a_left_left_left_left_1 ‹_›, bv_imp_elim_at H_5 ‹_›, bv_or_elim_at H_6, swap, assumption, bv_or_elim_at H_6.left, bv_exfalso, suffices : Γ_2 ≤ y ∈ᴮ w ⊓ w ∈ᴮ y, have : Γ_2 ≤ _ := le_trans (le_top) (bot_of_mem_mem y w), bv_imp_elim_at this ‹_›, assumption, apply le_inf, swap, assumption, apply bv_rw' H_6.left.left, simp, assumption, bv_exfalso, have a_left_right_old := a_left_right, rw[mem_unfold] at a_left_right, bv_cases_at a_left_right i_w, bv_split_at a_left_right_1, specialize y_ih i_w, rw[deduction] at y_ih, have := le_trans (le_inf ‹_› ‹_› : Γ_3 ≤ Ord x) ‹_›, have this' : Γ_3 ≤ func y i_w ∈ᴮ x, rw[bv_eq_symm] at a_left_right_1_right, change Γ_3 ≤ (λ z, z ∈ᴮ x) (func y i_w), apply bv_rw' a_left_right_1_right, simp, from H_2, bv_imp_elim_at this ‹_›, have : Γ_3 ≤ is_transitive w, apply bv_rw' ‹_›, simp, from ‹_›, unfold is_transitive at this, have H_8 := this z ‹_›, rw[subset_unfold'] at H_8, bv_specialize_at H_8 y, bv_imp_elim_at H_8_1 ‹_›, suffices : Γ_3 ≤ y ∈ᴮ w ⊓ w ∈ᴮ y, have this3 := le_trans (@le_top _ _ Γ_3) (bot_of_mem_mem y w), bv_to_pi this3, apply this3, bv_split_goal end lemma is_ewo_of_mem_Ord (y x : bSet 𝔹) : Ord x ⊓ y ∈ᴮ x ≤ (epsilon_well_orders y) := begin bv_split_goal, rename i z, apply bv_imp_intro, bv_split_goal; rename i w, apply bv_imp_intro, all_goals{unfold Ord}, {unfold epsilon_well_orders, tidy_context, bv_to_pi', specialize a_left_left_left_left_left w, dsimp at a_left_left_left_left_left, specialize a_left_left_left_right y, bv_to_pi a_left_left_left_right, specialize a_left_left_left_right ‹_›, rw[subset_unfold'] at a_left_left_left_right, bv_to_pi a_left_left_left_right, have H₁ := a_left_left_left_right w, bv_to_pi', have H₂ : Γ ≤ w ∈ᴮ x, from H₁ ‹_›, have H₃ : Γ ≤ z ∈ᴮ x, by {specialize a_left_left_left_right z, bv_to_pi', from a_left_left_left_right ‹_›}, rename a_left_left_left_left_left H, replace H := H ‹_› z ‹_›, bv_or_elim_at H, bv_or_elim_at H.left, apply le_sup_left_of_le, apply le_sup_left_of_le, bv_split_goal, apply le_sup_right_of_le, assumption, apply le_sup_left_of_le, apply le_sup_right_of_le, assumption}, {repeat{apply bv_imp_intro}, tidy_context, rename a_left_left_left_left H, rename i w, bv_split, have : Γ ≤ w ⊆ᴮ x, by {rw[subset_unfold'], bv_intro w', bv_imp_intro, have := mem_of_mem_subset a_left_right H, from mem_of_mem_subset (subset_of_mem_transitive ‹_› ‹_›) ‹_›}, from H_right w ‹_› ‹_›} end theorem Ord_of_mem_Ord {x y : bSet 𝔹} {Γ : 𝔹} (H_mem : Γ ≤ x ∈ᴮ y) (H_Ord : Γ ≤ Ord y) : Γ ≤ Ord x := begin refine le_inf _ _, { have := is_ewo_of_mem_Ord x y, exact le_trans (le_inf H_Ord H_mem) ‹_› }, { have := is_transitive_of_mem_Ord x y, exact le_trans (le_inf H_Ord H_mem) ‹_› } end open ordinal open cardinal noncomputable def ordinal.mk : ordinal.{u} → bSet 𝔹 := λ η, limit_rec_on η ∅ (λ ξ mk_ξ, succ mk_ξ) begin intros ξ is_limit_ξ ih, have this' : ξ = @ordinal.type (ξ.out).α (ξ.out).r (ξ.out).wo, by {rw[<-quotient.out_eq ξ], convert type_def _, rw[quotient.out_eq], cases quotient.out ξ, refl}, refine ⟨ξ.out.α, _, λ x, ⊤⟩, intro x, apply ih, rw this', apply typein_lt_type _ x end @[simp]lemma ordinal.mk_zero : ordinal.mk 0 = (∅ : bSet 𝔹) := by simp[ordinal.mk] @[simp]lemma ordinal.mk_succ (ξ ξ_pred : ordinal) (h : ξ = ordinal.succ ξ_pred) : (ordinal.mk ξ : bSet 𝔹) = succ (ordinal.mk ξ_pred) := by {simp[h, ordinal.mk]} @[simp]lemma ordinal.mk_limit (ξ : ordinal) (h : is_limit ξ) : (ordinal.mk ξ : bSet 𝔹) = ⟨ξ.out.α, λ x, ordinal.mk (@typein _ (ξ.out.r) (ξ.out.wo) x), (λ x, ⊤)⟩ := by simp[*, ordinal.mk] def lift_nat_Well_order : Well_order.{u} := { α := ulift ℕ, r := (λ x y, x.down < y.down), wo := by {haveI this : (is_well_order ℕ (λ x y, x < y)) := by apply_instance, from { trichotomous := by {change ∀ a b : ulift ℕ, a.down < b.down ∨ a = b ∨ b.down < a.down, intros a b, have := this.trichotomous, specialize this a.down b.down, tidy, left, from ‹_›, right, right, from ‹_›}, irrefl := by {intro a, apply this.irrefl}, trans := by {intros a b c, apply this.trans}, wf := by {have := this.wf, split, cases this with H, intro a, specialize H a.down, induction a, induction a, split, intros y H', cases H', cases H, specialize H_h a_n (by {change a_n < a_n + 1, simp}), specialize a_ih H_h, split, intros y H', by_cases y.down = a_n, subst h, split, intros y' H'', cases a_ih, exact a_ih_h y' H'', have h' : y.down < a_n, by {have := this.trichotomous, specialize this y.down a_n, simp[*, -this] at this, suffices this' : ¬ a_n < y.down, by {simp[*,-this] at this; assumption}, intro H, from nat.lt_irrefl _ (lt_of_lt_of_le H (nat.le_of_lt_succ H'))}, cases a_ih, from a_ih_h y h'}}}} lemma lift_nat_Well_order_iso_nat : lift_nat_Well_order.r ≃o (λ x y : ℕ, x < y) := {to_fun := ulift.down, inv_fun := ulift.up, left_inv := by tidy, right_inv := by tidy, ord := by tidy} noncomputable lemma order_isomorphism_of_equiv {X Y : Well_order.{u}} (H : X ≈ Y) : X.r ≃o Y.r := begin apply classical.choice, cases X, cases Y, apply type_eq.mp, from (quotient.sound H) end lemma order_iso_trans {α β γ} {X : α → α → Prop} {Y : β → β → Prop} {Z : γ → γ → Prop} (H₁ : X ≃o Y) (H₂ : Y ≃o Z) : X ≃o Z := H₁.trans H₂ lemma order_iso_symm {α β} {X : α → α → Prop} {Y : β → β → Prop} (H : X ≃o Y) : Y ≃o X := H.symm -- noncomputable lemma omega_out_iso_nat : ordinal.omega.out.r ≃o ((λ x y : ℕ, x < y)) := -- begin -- have this₁ := order_isomorphism_of_equiv (@quotient.mk_out (Well_order) _ lift_nat_Well_order), -- have this₂ := (lift_nat_Well_order_iso_nat), -- apply order_iso_trans _ this₂, apply order_iso_trans _ this₁, -- sorry -- end -- lemma mk_omega_eq_omega : ⊤ ≤ ordinal.mk ordinal.omega =ᴮ (bSet.omega : bSet 𝔹) := -- begin -- rw[ordinal.mk_limit ordinal.omega omega_is_limit], apply le_inf, swap, -- {simp[-top_le_iff], intro k, induction k, induction k, simp, -- repeat{sorry}}, -- {sorry} -- end lemma check_is_transitive {x : pSet} (H : pSet.is_transitive x) {Γ} : Γ ≤ is_transitive (x̌ : bSet 𝔹) := begin bv_intro y, bv_imp_intro, unfold pSet.is_transitive at H, rw[mem_unfold] at H_1, cases x, dsimp at H_1, bv_cases_at H_1 i_y, bv_split, apply bv_rw' H_1_1_right, simp, specialize H (x_A i_y) (by apply pSet.mem.mk), apply check_subset ‹_› end lemma check_ewo_left {x : pSet} (H : pSet.epsilon_well_orders x) {Γ : 𝔹} : Γ ≤ (⨅y, y∈ᴮ x̌ ⟹ (⨅z, z ∈ᴮ x̌ ⟹ (y =ᴮ z ⊔ y ∈ᴮ z ⊔ z ∈ᴮ y))) := begin bv_intro y, bv_imp_intro, bv_intro z, bv_imp_intro, rw[mem_unfold] at H_1 H_2, cases x, dsimp at H_1 H_2, bv_cases_at H_2 i_z, bv_cases_at H_1 i_y, bv_split, specialize H_left (x_A i_y) (by apply pSet.mem.mk) (x_A i_z) (by apply pSet.mem.mk), rename H_left this, repeat{cases this}, apply le_sup_left_of_le, apply le_sup_left_of_le, apply bv_rw' H_2_1_right, simp, apply bv_rw' H_1_1_right, simp, from check_bv_eq ‹_›, apply le_sup_left_of_le, apply le_sup_right_of_le, apply bv_rw' H_2_1_right, simp, apply bv_rw' H_1_1_right, simp, from check_mem ‹_›, apply le_sup_right_of_le, apply bv_rw' H_2_1_right, simp, apply bv_rw' H_1_1_right, simp, from check_mem ‹_› end lemma check_ewo_right {x : pSet} (H : pSet.epsilon_well_orders x) {Γ : 𝔹} : Γ ≤ (⨅u, u ⊆ᴮ x̌ ⟹ (- (u =ᴮ ∅) ⟹ ⨆y, y∈ᴮ u ⊓ (⨅z', z' ∈ᴮ u ⟹ (- (z' ∈ᴮ y))))) := begin bv_intro u, bv_imp_intro, bv_imp_intro, cases H, rw[subset_unfold'] at H_1, apply bSet_axiom_of_regularity, from ‹_› end lemma check_ewo {x : pSet} (H : pSet.epsilon_well_orders x) {Γ} : Γ ≤ epsilon_well_orders (x̌ : bSet 𝔹) := le_inf (check_ewo_left ‹_›) (check_ewo_right ‹_›) @[simp]lemma check_Ord {x : pSet} (H : pSet.Ord x) {Γ} : Γ ≤ Ord (x̌ : bSet 𝔹) := le_inf (check_ewo H.left) (check_is_transitive H.right) @[simp]lemma Ord_card_ex (κ : cardinal) {Γ : 𝔹} : Γ ≤ Ord ((pSet.card_ex κ)̌ ) := by simp[pSet.card_ex] def closed_under_successor (Γ) (x : bSet 𝔹) := Γ ≤ ⨅y, y ∈ᴮ x ⟹ succ y ∈ᴮ x def omega_spec (ω : bSet 𝔹) := (∀ {Γ : 𝔹}, Γ ≤ not_empty ω ∧ closed_under_successor Γ ω) ∧ ∀ (x : bSet 𝔹) {Γ} (H₁ : Γ ≤ ∅ ∈ᴮ x) (H₂ : closed_under_successor Γ x), Γ ≤ ω ⊆ᴮ x lemma omega_closed_under_succ {Γ : 𝔹} : closed_under_successor Γ (bSet.omega) := begin unfold closed_under_successor, bv_intro y, bv_imp_intro H_mem, bv_cases_at H_mem k, cases k with k, simp at H_mem_1, refine bv_use _, exact (ulift.up $ k + 1), simp, apply bv_rw' H_mem_1, { exact @B_ext_term 𝔹 _ (λ z, z =ᴮ ((k+1)̃ ̌)) succ (by simp) (by simp) }, -- TODO(jesse): automate calculation of the motive { simp[pSet.of_nat, succ] }, end def omega_nonempty {Γ : 𝔹} : Γ ≤ not_empty bSet.omega := begin rw nonempty_iff_exists_mem, apply bv_use (∅ : bSet 𝔹), change _ ≤ (λ z, z ∈ᴮ omega) _, apply bv_rw' (bv_symm zero_eq_empty), simp, apply of_nat_mem_omega end lemma omega_is_omega : omega_spec (bSet.omega : bSet 𝔹) := begin refine ⟨_,_⟩, { intro Γ, refine ⟨_,_⟩, { exact omega_nonempty }, { apply omega_closed_under_succ }}, { intros x Γ H₁ H₂, unfold closed_under_successor at H₂, rw[subset_unfold], simp, intro k, cases k, induction k, convert H₁, {change (∅̌) = _, simp}, {let A := _, change Γ ≤ A ∈ᴮ x at k_ih, convert H₂ A ‹_›, from check_succ_eq_succ_check}}, end lemma Ord_omega {Γ : 𝔹} : Γ ≤ Ord (omega) := le_inf (check_ewo pSet.is_ewo_omega) (check_is_transitive pSet.is_transitive_omega) lemma Ord_of_nat {Γ : 𝔹} {n : ℕ} : Γ ≤ Ord (of_nat n) := Ord_of_mem_Ord of_nat_mem_omega Ord_omega lemma Ord_one { Γ : 𝔹 } : Γ ≤ Ord 1 := Ord_of_nat lemma Ord_zero { Γ : 𝔹 } : Γ ≤ Ord 0 := Ord_of_nat lemma of_nat_subset_omega {n : ℕ} {Γ : 𝔹} : Γ ≤ of_nat n ⊆ᴮ omega := subset_of_mem_transitive (bv_and.right Ord_omega) of_nat_mem_omega /-- ℵ₁ is defined as: the least ordinal which does not inject into ω -/ @[reducible]def aleph_one_Ord_spec (x : bSet 𝔹) : 𝔹 := (-(x ≼ omega)) ⊓ ((Ord x) ⊓ (⨅ y, (Ord y) ⟹ ((- injects_into y bSet.omega) ⟹ x ⊆ᴮ y))) @[simp]lemma aleph_one_check_exists_mem {𝔹 : Type u} [nontrivial_complete_boolean_algebra 𝔹] {Γ : 𝔹} : Γ ≤ exists_mem (pSet.card_ex $ aleph 1)̌ := begin simp only [show _ = pSet.card_ex (aleph ↑1), by simp], from check_exists_mem pSet.card_ex_aleph_exists_mem end @[simp]lemma B_ext_Ord : B_ext (Ord : bSet 𝔹 → 𝔹) := B_ext_inf (by simp) (by simp) /-- The universal property of ℵ₁ is that it injects into any set which is larger than ω -/ @[reducible]def le_of_omega_lt (x : bSet 𝔹) : 𝔹 := ⨅ z, Ord z ⟹ ((bSet.omega ≺ z) ⟹ (x ≼ z)) @[simp] lemma B_ext_le_of_omega_lt : B_ext (le_of_omega_lt : bSet 𝔹 → 𝔹) := by { delta le_of_omega_lt, simp } end ordinals section zorns_lemma variables {𝔹 : Type u} [nontrivial_complete_boolean_algebra 𝔹] theorem bSet_zorns_lemma' {Γ : 𝔹} : Γ ≤ ⨅(X : bSet 𝔹), -(X =ᴮ ∅) ⟹ ((⨅y, (y ⊆ᴮ X ⊓ (⨅(w₁ : bSet 𝔹), ⨅(w₂ : bSet 𝔹), w₁ ∈ᴮ y ⊓ w₂ ∈ᴮ y ⟹ (w₁ ⊆ᴮ w₂ ⊔ w₂ ⊆ᴮ w₁))) ⟹ (bv_union y ∈ᴮ X)) ⟹ (⨆c, c ∈ᴮ X ⊓ (⨅z, z ∈ᴮ X ⟹ (c ⊆ᴮ z ⟹ c =ᴮ z)))) := begin bv_intro X, rw[<-curry_uncurry], have := core_aux_lemma2 (λ x, (-(x =ᴮ ∅) ⊓ ⨅ (y : bSet 𝔹), (y ⊆ᴮ x ⊓ ⨅ (w₁ w₂ : bSet 𝔹), w₁ ∈ᴮ y ⊓ w₂ ∈ᴮ y ⟹ (w₁ ⊆ᴮ w₂ ⊔ w₂ ⊆ᴮ w₁)) ⟹ bv_union y ∈ᴮ x)) (λ x, ⨆ (c : bSet 𝔹), c ∈ᴮ x ⊓ ⨅ (z : bSet 𝔹), z ∈ᴮ x ⟹ (c ⊆ᴮ z ⟹ c =ᴮ z)) (by change B_ext _; simp) (by change B_ext _; simp) _ _, rw[eq_top_iff] at this, replace this := (le_trans le_top this : Γ ≤ _), from this X, dsimp, intros u Hu, rw[eq_top_iff] at Hu ⊢, bv_split, apply bSet_zorns_lemma, from (top_unique ‹_›), from ‹_›, apply top_unique, dsimp, apply bv_use ({∅} : bSet 𝔹), simp, split, {apply top_unique, rw[<-imp_bot], bv_imp_intro, rw[bv_eq_unfold] at H, bv_split, replace H_left := H_left none, dsimp at H_left, replace H_left := H_left (le_top), from bot_of_mem_self' ‹_›}, intros x, refine poset_yoneda _, intros Γ a, simp only [le_inf_iff] at *, cases a, apply mem_singleton_of_eq, refine subset_ext (by simp) _, rw[subset_unfold'], bv_intro w, bv_imp_intro, have := bv_union_spec' x, show 𝔹, from Γ_1, replace this := this w, bv_split, replace this_left := this_left ‹_›, bv_cases_at this_left w', rw[subset_unfold'] at a_left, bv_split, replace a_left := a_left w' ‹_›, have : Γ_2 ≤ ∅ =ᴮ w', by {apply eq_of_mem_singleton, from ‹_›}, apply bv_exfalso, apply bot_of_mem_empty, show bSet 𝔹, from w, bv_cc end end zorns_lemma section CH variables {𝔹 : Type u} [nontrivial_complete_boolean_algebra 𝔹] local infix `≺`:75 := (λ x y, -(larger_than x y)) local infix `≼`:75 := (λ x y, injects_into x y) def CH : 𝔹 := - ⨆ x, Ord x ⊓ ⨆y, omega ≺ x ⊓ x ≺ y ⊓ y ≼ 𝒫 omega def CH₂ : 𝔹 := - ⨆x, Ord x ⊓ omega ≺ x ⊓ x ≺ 𝒫 omega lemma CH_iff_CH₂ : ∀{Γ : 𝔹}, Γ ≤ CH ↔ Γ ≤ CH₂ := begin apply bv_iff.neg, intro Γ, split; intro H, { bv_cases_at H x Hx, bv_split_at Hx, bv_cases_at Hx_right y Hy, clear H Hx_right, bv_split_at Hy, bv_split_at Hy_left, apply bv_use x, refine le_inf (le_inf Hx_left Hy_left_left) (bSet_lt_of_lt_of_le Hy_left_right Hy_right) }, { bv_cases_at H x Hx, bv_split_at Hx, bv_split_at Hx_left, clear H, apply bv_use x, refine le_inf Hx_left_left _, apply bv_use (𝒫 omega), apply le_inf (le_inf Hx_left_right Hx_right) injects_into_refl } end end CH end bSet
{-# LANGUAGE ViewPatterns #-} module Statistics.Covariance.Shrinkage.MMSE ( mmseCov , shrinkCov , sampleCov , naiveCov , pinCoef , lwShrinkageCoef , rblwShrinkCovCoef , rblwShrinkageCoef , oracleShrinkCovCoef , oracleShrinkageCoef ) where import Numeric.LinearAlgebra hiding ((<>)) import Numeric.Sum (kbn, sumVector) import Statistics.Sample (mean) import qualified Data.Vector.Unboxed as VU mmseCov :: (Matrix Double -> Double) -> Matrix Double -> Herm Double mmseCov shrink x = shrinkCov s p f where s = sampleCov x f = naiveCov x p = shrink x shrinkCov :: Herm Double -> Double -> Herm Double -> Herm Double shrinkCov sample coef target = scale (1 - coef) sample `add` scale coef target sampleCov :: Matrix Double -> Herm Double sampleCov = snd . meanCov avgVarCov :: Herm Double -> Herm Double avgVarCov (unSym -> s) = trustSym $ scale s' (ident p) where p = cols s s' = mean $ takeDiag s naiveCov :: Matrix Double -> Herm Double naiveCov = avgVarCov . sampleCov pinCoef :: Double -> Double pinCoef = max 0 . min 1 lwShrinkageCoef :: Matrix Double -> Double lwShrinkageCoef x = numer / denom where n = rows x p = cols x s = unSym $ sampleCov x trs2 = trace $ s <> s tr2s = sq $ trace s frob ix = let c = x ? [ix] in sq . norm_Frob $ unSym (mTm c) - s numer = sumVector kbn (VU.generate n frob) / fromIntegral (sq n) denom = trs2 - tr2s / fromIntegral p rblwShrinkCovCoef :: Int -> Herm Double -> Double rblwShrinkCovCoef (fromIntegral -> n) (unSym -> s) = numer / denom where p = cols s trs2 = trace $ s <> s tr2s = sq $ trace s numer = (n - 2) / n * trs2 + tr2s denom = (n + 2) * (trs2 - tr2s / fromIntegral p) rblwShrinkageCoef :: Matrix Double -> Double rblwShrinkageCoef x = rblwShrinkCovCoef n (sampleCov x) where n = rows x data OASIter = OASIter Double (Herm Double) data OAS = OAS Int Int (Herm Double) (Herm Double) oracleStep :: OAS -> Herm Double -> OASIter oracleStep (OAS n p s f) sj = OASIter pj' sj' where n' = fromIntegral n p' = fromIntegral p trss = trace $ unSym sj <> unSym s tr2s = sq . trace $ unSym sj numer = (1 - 2 / p') * trss + tr2s denom = (n' + 1 - 2 / p') * trss + (1 - n' / p') * tr2s pj' = numer / denom sj' = scale (1 - pj') s `add` scale pj' f oracleIter :: Double -> OAS -> Herm Double -> Double oracleIter tol oas = go 1 . oracleStep oas where go p (OASIter p' sj') | abs (p - p') < tol = p' | otherwise = go p' $ oracleStep oas sj' oracleShrinkCovCoef :: Int -> Herm Double -> Double oracleShrinkCovCoef n s = oracleIter 1e-6 (OAS n p s f) s where p = cols $ unSym s f = avgVarCov s oracleShrinkageCoef :: Matrix Double -> Double oracleShrinkageCoef x = oracleShrinkCovCoef n (sampleCov x) where n = rows x sq :: Num a => a -> a sq a = a * a trace :: Matrix Double -> Double trace = sumVector kbn . takeDiag
[GOAL] α : Type u_1 inst✝¹ : MeasurableSpace α μ : Measure α f g : α → ℝ s : Set α inst✝ : SigmaFinite μ f_int : IntegrableOn f s g_int : IntegrableOn g s hs : MeasurableSet s hfg : f ≤ᶠ[ae (Measure.restrict μ s)] g ⊢ ↑↑(Measure.prod μ volume) (regionBetween f g s) = ENNReal.ofReal (∫ (y : α) in s, (g - f) y ∂μ) [PROOFSTEP] have h : g - f =ᵐ[μ.restrict s] fun x => Real.toNNReal (g x - f x) := hfg.mono fun x hx => (Real.coe_toNNReal _ <| sub_nonneg.2 hx).symm [GOAL] α : Type u_1 inst✝¹ : MeasurableSpace α μ : Measure α f g : α → ℝ s : Set α inst✝ : SigmaFinite μ f_int : IntegrableOn f s g_int : IntegrableOn g s hs : MeasurableSet s hfg : f ≤ᶠ[ae (Measure.restrict μ s)] g h : g - f =ᶠ[ae (Measure.restrict μ s)] fun x => ↑(Real.toNNReal (g x - f x)) ⊢ ↑↑(Measure.prod μ volume) (regionBetween f g s) = ENNReal.ofReal (∫ (y : α) in s, (g - f) y ∂μ) [PROOFSTEP] rw [volume_regionBetween_eq_lintegral f_int.aemeasurable g_int.aemeasurable hs, integral_congr_ae h, lintegral_congr_ae, lintegral_coe_eq_integral _ ((integrable_congr h).mp (g_int.sub f_int))] [GOAL] α : Type u_1 inst✝¹ : MeasurableSpace α μ : Measure α f g : α → ℝ s : Set α inst✝ : SigmaFinite μ f_int : IntegrableOn f s g_int : IntegrableOn g s hs : MeasurableSet s hfg : f ≤ᶠ[ae (Measure.restrict μ s)] g h : g - f =ᶠ[ae (Measure.restrict μ s)] fun x => ↑(Real.toNNReal (g x - f x)) ⊢ (fun y => ENNReal.ofReal ((g - f) y)) =ᶠ[ae (Measure.restrict μ s)] fun a => ↑(Real.toNNReal (g a - f a)) [PROOFSTEP] dsimp only [GOAL] α : Type u_1 inst✝¹ : MeasurableSpace α μ : Measure α f g : α → ℝ s : Set α inst✝ : SigmaFinite μ f_int : IntegrableOn f s g_int : IntegrableOn g s hs : MeasurableSet s hfg : f ≤ᶠ[ae (Measure.restrict μ s)] g h : g - f =ᶠ[ae (Measure.restrict μ s)] fun x => ↑(Real.toNNReal (g x - f x)) ⊢ (fun y => ENNReal.ofReal ((g - f) y)) =ᶠ[ae (Measure.restrict μ s)] fun a => ↑(Real.toNNReal (g a - f a)) [PROOFSTEP] rfl [GOAL] E : Type u_1 inst✝ : NormedAddCommGroup E f : C(ℝ, E) hf : Summable fun n => ‖ContinuousMap.restrict (Icc 0 1) (comp f (ContinuousMap.addRight ↑n))‖ ⊢ Integrable ↑f [PROOFSTEP] refine' @integrable_of_summable_norm_restrict ℝ ℤ E _ volume _ _ _ _ _ _ _ _ (summable_of_nonneg_of_le (fun n : ℤ => mul_nonneg (norm_nonneg (f.restrict (⟨Icc (n : ℝ) ((n : ℝ) + 1), isCompact_Icc⟩ : Compacts ℝ))) ENNReal.toReal_nonneg) (fun n => _) hf) _ -- porting note: `refine` was able to find that on its own before [GOAL] case refine'_1 E : Type u_1 inst✝ : NormedAddCommGroup E f : C(ℝ, E) hf : Summable fun n => ‖ContinuousMap.restrict (Icc 0 1) (comp f (ContinuousMap.addRight ↑n))‖ ⊢ ℤ → Compacts ℝ [PROOFSTEP] intro n [GOAL] case refine'_1 E : Type u_1 inst✝ : NormedAddCommGroup E f : C(ℝ, E) hf : Summable fun n => ‖ContinuousMap.restrict (Icc 0 1) (comp f (ContinuousMap.addRight ↑n))‖ n : ℤ ⊢ Compacts ℝ [PROOFSTEP] exact ⟨Icc (n : ℝ) ((n : ℝ) + 1), isCompact_Icc⟩ [GOAL] case refine'_2 E : Type u_1 inst✝ : NormedAddCommGroup E f : C(ℝ, E) hf : Summable fun n => ‖ContinuousMap.restrict (Icc 0 1) (comp f (ContinuousMap.addRight ↑n))‖ n : ℤ ⊢ ‖ContinuousMap.restrict (↑{ carrier := Icc (↑n) (↑n + 1), isCompact' := (_ : IsCompact (Icc (↑n) (↑n + 1))) }) f‖ * ENNReal.toReal (↑↑volume ↑{ carrier := Icc (↑n) (↑n + 1), isCompact' := (_ : IsCompact (Icc (↑n) (↑n + 1))) }) ≤ ‖ContinuousMap.restrict (Icc 0 1) (comp f (ContinuousMap.addRight ↑n))‖ [PROOFSTEP] simp only [Compacts.coe_mk, Real.volume_Icc, add_sub_cancel', ENNReal.toReal_ofReal zero_le_one, mul_one, norm_le _ (norm_nonneg _)] [GOAL] case refine'_2 E : Type u_1 inst✝ : NormedAddCommGroup E f : C(ℝ, E) hf : Summable fun n => ‖ContinuousMap.restrict (Icc 0 1) (comp f (ContinuousMap.addRight ↑n))‖ n : ℤ ⊢ ∀ (x : ↑(Icc (↑n) (↑n + 1))), ‖↑(ContinuousMap.restrict (Icc (↑n) (↑n + 1)) f) x‖ ≤ ‖ContinuousMap.restrict (Icc 0 1) (comp f (ContinuousMap.addRight ↑n))‖ [PROOFSTEP] intro x [GOAL] case refine'_2 E : Type u_1 inst✝ : NormedAddCommGroup E f : C(ℝ, E) hf : Summable fun n => ‖ContinuousMap.restrict (Icc 0 1) (comp f (ContinuousMap.addRight ↑n))‖ n : ℤ x : ↑(Icc (↑n) (↑n + 1)) ⊢ ‖↑(ContinuousMap.restrict (Icc (↑n) (↑n + 1)) f) x‖ ≤ ‖ContinuousMap.restrict (Icc 0 1) (comp f (ContinuousMap.addRight ↑n))‖ [PROOFSTEP] have := ((f.comp <| ContinuousMap.addRight n).restrict (Icc 0 1)).norm_coe_le_norm ⟨x - n, ⟨sub_nonneg.mpr x.2.1, sub_le_iff_le_add'.mpr x.2.2⟩⟩ [GOAL] case refine'_2 E : Type u_1 inst✝ : NormedAddCommGroup E f : C(ℝ, E) hf : Summable fun n => ‖ContinuousMap.restrict (Icc 0 1) (comp f (ContinuousMap.addRight ↑n))‖ n : ℤ x : ↑(Icc (↑n) (↑n + 1)) this : ‖↑(ContinuousMap.restrict (Icc 0 1) (comp f (ContinuousMap.addRight ↑n))) { val := ↑x - ↑n, property := (_ : 0 ≤ ↑x - ↑n ∧ ↑x - ↑n ≤ 1) }‖ ≤ ‖ContinuousMap.restrict (Icc 0 1) (comp f (ContinuousMap.addRight ↑n))‖ ⊢ ‖↑(ContinuousMap.restrict (Icc (↑n) (↑n + 1)) f) x‖ ≤ ‖ContinuousMap.restrict (Icc 0 1) (comp f (ContinuousMap.addRight ↑n))‖ [PROOFSTEP] simpa only [ContinuousMap.restrict_apply, comp_apply, coe_addRight, Subtype.coe_mk, sub_add_cancel] using this [GOAL] case refine'_3 E : Type u_1 inst✝ : NormedAddCommGroup E f : C(ℝ, E) hf : Summable fun n => ‖ContinuousMap.restrict (Icc 0 1) (comp f (ContinuousMap.addRight ↑n))‖ ⊢ ⋃ (i : ℤ), ↑{ carrier := Icc (↑i) (↑i + 1), isCompact' := (_ : IsCompact (Icc (↑i) (↑i + 1))) } = univ [PROOFSTEP] exact iUnion_Icc_int_cast ℝ [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℝ E c : ℝ f : ℝ → E ⊢ ∫ (x : ℝ) in Iic c, f (-x) = ∫ (x : ℝ) in Ioi (-c), f x [PROOFSTEP] have A : MeasurableEmbedding fun x : ℝ => -x := (Homeomorph.neg ℝ).closedEmbedding.measurableEmbedding [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℝ E c : ℝ f : ℝ → E A : MeasurableEmbedding fun x => -x ⊢ ∫ (x : ℝ) in Iic c, f (-x) = ∫ (x : ℝ) in Ioi (-c), f x [PROOFSTEP] have := MeasurableEmbedding.set_integral_map (μ := volume) A f (Ici (-c)) [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℝ E c : ℝ f : ℝ → E A : MeasurableEmbedding fun x => -x this : ∫ (y : ℝ) in Ici (-c), f y ∂Measure.map (fun x => -x) volume = ∫ (x : ℝ) in (fun x => -x) ⁻¹' Ici (-c), f (-x) ⊢ ∫ (x : ℝ) in Iic c, f (-x) = ∫ (x : ℝ) in Ioi (-c), f x [PROOFSTEP] rw [Measure.map_neg_eq_self (volume : Measure ℝ)] at this [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℝ E c : ℝ f : ℝ → E A : MeasurableEmbedding fun x => -x this : ∫ (y : ℝ) in Ici (-c), f y = ∫ (x : ℝ) in (fun x => -x) ⁻¹' Ici (-c), f (-x) ⊢ ∫ (x : ℝ) in Iic c, f (-x) = ∫ (x : ℝ) in Ioi (-c), f x [PROOFSTEP] simp_rw [← integral_Ici_eq_integral_Ioi, this, neg_preimage, preimage_neg_Ici, neg_neg] [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℝ E c : ℝ f : ℝ → E ⊢ ∫ (x : ℝ) in Ioi c, f (-x) = ∫ (x : ℝ) in Iic (-c), f x [PROOFSTEP] rw [← neg_neg c, ← integral_comp_neg_Iic] [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℝ E c : ℝ f : ℝ → E ⊢ ∫ (x : ℝ) in Iic (-c), f (- -x) = ∫ (x : ℝ) in Iic (- - -c), f x [PROOFSTEP] simp only [neg_neg]
(* Title: HOL/Computational_Algebra/Fundamental_Theorem_Algebra.thy Author: Amine Chaieb, TU Muenchen *) section \<open>Fundamental Theorem of Algebra\<close> theory Fundamental_Theorem_Algebra imports Polynomial Complex_Main begin subsection \<open>More lemmas about module of complex numbers\<close> text \<open>The triangle inequality for cmod\<close> lemma complex_mod_triangle_sub: "cmod w \<le> cmod (w + z) + norm z" using complex_mod_triangle_ineq2[of "w + z" "-z"] by auto subsection \<open>Basic lemmas about polynomials\<close> lemma poly_bound_exists: fixes p :: "'a::{comm_semiring_0,real_normed_div_algebra} poly" shows "\<exists>m. m > 0 \<and> (\<forall>z. norm z \<le> r \<longrightarrow> norm (poly p z) \<le> m)" proof (induct p) case 0 then show ?case by (rule exI[where x=1]) simp next case (pCons c cs) from pCons.hyps obtain m where m: "\<forall>z. norm z \<le> r \<longrightarrow> norm (poly cs z) \<le> m" by blast let ?k = " 1 + norm c + \<bar>r * m\<bar>" have kp: "?k > 0" using abs_ge_zero[of "r*m"] norm_ge_zero[of c] by arith have "norm (poly (pCons c cs) z) \<le> ?k" if H: "norm z \<le> r" for z proof - from m H have th: "norm (poly cs z) \<le> m" by blast from H have rp: "r \<ge> 0" using norm_ge_zero[of z] by arith have "norm (poly (pCons c cs) z) \<le> norm c + norm (z * poly cs z)" using norm_triangle_ineq[of c "z* poly cs z"] by simp also have "\<dots> \<le> norm c + r * m" using mult_mono[OF H th rp norm_ge_zero[of "poly cs z"]] by (simp add: norm_mult) also have "\<dots> \<le> ?k" by simp finally show ?thesis . qed with kp show ?case by blast qed text \<open>Offsetting the variable in a polynomial gives another of same degree\<close> definition offset_poly :: "'a::comm_semiring_0 poly \<Rightarrow> 'a \<Rightarrow> 'a poly" where "offset_poly p h = fold_coeffs (\<lambda>a q. smult h q + pCons a q) p 0" lemma offset_poly_0: "offset_poly 0 h = 0" by (simp add: offset_poly_def) lemma offset_poly_pCons: "offset_poly (pCons a p) h = smult h (offset_poly p h) + pCons a (offset_poly p h)" by (cases "p = 0 \<and> a = 0") (auto simp add: offset_poly_def) lemma offset_poly_single: "offset_poly [:a:] h = [:a:]" by (simp add: offset_poly_pCons offset_poly_0) lemma poly_offset_poly: "poly (offset_poly p h) x = poly p (h + x)" apply (induct p) apply (simp add: offset_poly_0) apply (simp add: offset_poly_pCons algebra_simps) done lemma offset_poly_eq_0_lemma: "smult c p + pCons a p = 0 \<Longrightarrow> p = 0" by (induct p arbitrary: a) (simp, force) lemma offset_poly_eq_0_iff: "offset_poly p h = 0 \<longleftrightarrow> p = 0" apply (safe intro!: offset_poly_0) apply (induct p) apply simp apply (simp add: offset_poly_pCons) apply (frule offset_poly_eq_0_lemma, simp) done lemma degree_offset_poly: "degree (offset_poly p h) = degree p" apply (induct p) apply (simp add: offset_poly_0) apply (case_tac "p = 0") apply (simp add: offset_poly_0 offset_poly_pCons) apply (simp add: offset_poly_pCons) apply (subst degree_add_eq_right) apply (rule le_less_trans [OF degree_smult_le]) apply (simp add: offset_poly_eq_0_iff) apply (simp add: offset_poly_eq_0_iff) done definition "psize p = (if p = 0 then 0 else Suc (degree p))" lemma psize_eq_0_iff [simp]: "psize p = 0 \<longleftrightarrow> p = 0" unfolding psize_def by simp lemma poly_offset: fixes p :: "'a::comm_ring_1 poly" shows "\<exists>q. psize q = psize p \<and> (\<forall>x. poly q x = poly p (a + x))" proof (intro exI conjI) show "psize (offset_poly p a) = psize p" unfolding psize_def by (simp add: offset_poly_eq_0_iff degree_offset_poly) show "\<forall>x. poly (offset_poly p a) x = poly p (a + x)" by (simp add: poly_offset_poly) qed text \<open>An alternative useful formulation of completeness of the reals\<close> lemma real_sup_exists: assumes ex: "\<exists>x. P x" and bz: "\<exists>z. \<forall>x. P x \<longrightarrow> x < z" shows "\<exists>s::real. \<forall>y. (\<exists>x. P x \<and> y < x) \<longleftrightarrow> y < s" proof from bz have "bdd_above (Collect P)" by (force intro: less_imp_le) then show "\<forall>y. (\<exists>x. P x \<and> y < x) \<longleftrightarrow> y < Sup (Collect P)" using ex bz by (subst less_cSup_iff) auto qed subsection \<open>Fundamental theorem of algebra\<close> lemma unimodular_reduce_norm: assumes md: "cmod z = 1" shows "cmod (z + 1) < 1 \<or> cmod (z - 1) < 1 \<or> cmod (z + \<i>) < 1 \<or> cmod (z - \<i>) < 1" proof - obtain x y where z: "z = Complex x y " by (cases z) auto from md z have xy: "x\<^sup>2 + y\<^sup>2 = 1" by (simp add: cmod_def) have False if "cmod (z + 1) \<ge> 1" "cmod (z - 1) \<ge> 1" "cmod (z + \<i>) \<ge> 1" "cmod (z - \<i>) \<ge> 1" proof - from that z xy have "2 * x \<le> 1" "2 * x \<ge> -1" "2 * y \<le> 1" "2 * y \<ge> -1" by (simp_all add: cmod_def power2_eq_square algebra_simps) then have "\<bar>2 * x\<bar> \<le> 1" "\<bar>2 * y\<bar> \<le> 1" by simp_all then have "\<bar>2 * x\<bar>\<^sup>2 \<le> 1\<^sup>2" "\<bar>2 * y\<bar>\<^sup>2 \<le> 1\<^sup>2" by - (rule power_mono, simp, simp)+ then have th0: "4 * x\<^sup>2 \<le> 1" "4 * y\<^sup>2 \<le> 1" by (simp_all add: power_mult_distrib) from add_mono[OF th0] xy show ?thesis by simp qed then show ?thesis unfolding linorder_not_le[symmetric] by blast qed text \<open>Hence we can always reduce modulus of \<open>1 + b z^n\<close> if nonzero\<close> lemma reduce_poly_simple: assumes b: "b \<noteq> 0" and n: "n \<noteq> 0" shows "\<exists>z. cmod (1 + b * z^n) < 1" using n proof (induct n rule: nat_less_induct) fix n assume IH: "\<forall>m<n. m \<noteq> 0 \<longrightarrow> (\<exists>z. cmod (1 + b * z ^ m) < 1)" assume n: "n \<noteq> 0" let ?P = "\<lambda>z n. cmod (1 + b * z ^ n) < 1" show "\<exists>z. ?P z n" proof cases assume "even n" then have "\<exists>m. n = 2 * m" by presburger then obtain m where m: "n = 2 * m" by blast from n m have "m \<noteq> 0" "m < n" by presburger+ with IH[rule_format, of m] obtain z where z: "?P z m" by blast from z have "?P (csqrt z) n" by (simp add: m power_mult) then show ?thesis .. next assume "odd n" then have "\<exists>m. n = Suc (2 * m)" by presburger+ then obtain m where m: "n = Suc (2 * m)" by blast have th0: "cmod (complex_of_real (cmod b) / b) = 1" using b by (simp add: norm_divide) from unimodular_reduce_norm[OF th0] \<open>odd n\<close> have "\<exists>v. cmod (complex_of_real (cmod b) / b + v^n) < 1" apply (cases "cmod (complex_of_real (cmod b) / b + 1) < 1") apply (rule_tac x="1" in exI) apply simp apply (cases "cmod (complex_of_real (cmod b) / b - 1) < 1") apply (rule_tac x="-1" in exI) apply simp apply (cases "cmod (complex_of_real (cmod b) / b + \<i>) < 1") apply (cases "even m") apply (rule_tac x="\<i>" in exI) apply (simp add: m power_mult) apply (rule_tac x="- \<i>" in exI) apply (simp add: m power_mult) apply (cases "even m") apply (rule_tac x="- \<i>" in exI) apply (simp add: m power_mult) apply (auto simp add: m power_mult) apply (rule_tac x="\<i>" in exI) apply (auto simp add: m power_mult) done then obtain v where v: "cmod (complex_of_real (cmod b) / b + v^n) < 1" by blast let ?w = "v / complex_of_real (root n (cmod b))" from odd_real_root_pow[OF \<open>odd n\<close>, of "cmod b"] have th1: "?w ^ n = v^n / complex_of_real (cmod b)" by (simp add: power_divide of_real_power[symmetric]) have th2:"cmod (complex_of_real (cmod b) / b) = 1" using b by (simp add: norm_divide) then have th3: "cmod (complex_of_real (cmod b) / b) \<ge> 0" by simp have th4: "cmod (complex_of_real (cmod b) / b) * cmod (1 + b * (v ^ n / complex_of_real (cmod b))) < cmod (complex_of_real (cmod b) / b) * 1" apply (simp only: norm_mult[symmetric] distrib_left) using b v apply (simp add: th2) done from mult_left_less_imp_less[OF th4 th3] have "?P ?w n" unfolding th1 . then show ?thesis .. qed qed text \<open>Bolzano-Weierstrass type property for closed disc in complex plane.\<close> lemma metric_bound_lemma: "cmod (x - y) \<le> \<bar>Re x - Re y\<bar> + \<bar>Im x - Im y\<bar>" using real_sqrt_sum_squares_triangle_ineq[of "Re x - Re y" 0 0 "Im x - Im y"] unfolding cmod_def by simp lemma Bolzano_Weierstrass_complex_disc: assumes r: "\<forall>n. cmod (s n) \<le> r" shows "\<exists>f z. strict_mono (f :: nat \<Rightarrow> nat) \<and> (\<forall>e >0. \<exists>N. \<forall>n \<ge> N. cmod (s (f n) - z) < e)" proof - from seq_monosub[of "Re \<circ> s"] obtain f where f: "strict_mono f" "monoseq (\<lambda>n. Re (s (f n)))" unfolding o_def by blast from seq_monosub[of "Im \<circ> s \<circ> f"] obtain g where g: "strict_mono g" "monoseq (\<lambda>n. Im (s (f (g n))))" unfolding o_def by blast let ?h = "f \<circ> g" from r[rule_format, of 0] have rp: "r \<ge> 0" using norm_ge_zero[of "s 0"] by arith have th: "\<forall>n. r + 1 \<ge> \<bar>Re (s n)\<bar>" proof fix n from abs_Re_le_cmod[of "s n"] r[rule_format, of n] show "\<bar>Re (s n)\<bar> \<le> r + 1" by arith qed have conv1: "convergent (\<lambda>n. Re (s (f n)))" apply (rule Bseq_monoseq_convergent) apply (simp add: Bseq_def) apply (metis gt_ex le_less_linear less_trans order.trans th) apply (rule f(2)) done have th: "\<forall>n. r + 1 \<ge> \<bar>Im (s n)\<bar>" proof fix n from abs_Im_le_cmod[of "s n"] r[rule_format, of n] show "\<bar>Im (s n)\<bar> \<le> r + 1" by arith qed have conv2: "convergent (\<lambda>n. Im (s (f (g n))))" apply (rule Bseq_monoseq_convergent) apply (simp add: Bseq_def) apply (metis gt_ex le_less_linear less_trans order.trans th) apply (rule g(2)) done from conv1[unfolded convergent_def] obtain x where "LIMSEQ (\<lambda>n. Re (s (f n))) x" by blast then have x: "\<forall>r>0. \<exists>n0. \<forall>n\<ge>n0. \<bar>Re (s (f n)) - x\<bar> < r" unfolding LIMSEQ_iff real_norm_def . from conv2[unfolded convergent_def] obtain y where "LIMSEQ (\<lambda>n. Im (s (f (g n)))) y" by blast then have y: "\<forall>r>0. \<exists>n0. \<forall>n\<ge>n0. \<bar>Im (s (f (g n))) - y\<bar> < r" unfolding LIMSEQ_iff real_norm_def . let ?w = "Complex x y" from f(1) g(1) have hs: "strict_mono ?h" unfolding strict_mono_def by auto have "\<exists>N. \<forall>n\<ge>N. cmod (s (?h n) - ?w) < e" if "e > 0" for e proof - from that have e2: "e/2 > 0" by simp from x[rule_format, OF e2] y[rule_format, OF e2] obtain N1 N2 where N1: "\<forall>n\<ge>N1. \<bar>Re (s (f n)) - x\<bar> < e / 2" and N2: "\<forall>n\<ge>N2. \<bar>Im (s (f (g n))) - y\<bar> < e / 2" by blast have "cmod (s (?h n) - ?w) < e" if "n \<ge> N1 + N2" for n proof - from that have nN1: "g n \<ge> N1" and nN2: "n \<ge> N2" using seq_suble[OF g(1), of n] by arith+ from add_strict_mono[OF N1[rule_format, OF nN1] N2[rule_format, OF nN2]] show ?thesis using metric_bound_lemma[of "s (f (g n))" ?w] by simp qed then show ?thesis by blast qed with hs show ?thesis by blast qed text \<open>Polynomial is continuous.\<close> lemma poly_cont: fixes p :: "'a::{comm_semiring_0,real_normed_div_algebra} poly" assumes ep: "e > 0" shows "\<exists>d >0. \<forall>w. 0 < norm (w - z) \<and> norm (w - z) < d \<longrightarrow> norm (poly p w - poly p z) < e" proof - obtain q where q: "degree q = degree p" "poly q x = poly p (z + x)" for x proof show "degree (offset_poly p z) = degree p" by (rule degree_offset_poly) show "\<And>x. poly (offset_poly p z) x = poly p (z + x)" by (rule poly_offset_poly) qed have th: "\<And>w. poly q (w - z) = poly p w" using q(2)[of "w - z" for w] by simp show ?thesis unfolding th[symmetric] proof (induct q) case 0 then show ?case using ep by auto next case (pCons c cs) from poly_bound_exists[of 1 "cs"] obtain m where m: "m > 0" "norm z \<le> 1 \<Longrightarrow> norm (poly cs z) \<le> m" for z by blast from ep m(1) have em0: "e/m > 0" by (simp add: field_simps) have one0: "1 > (0::real)" by arith from field_lbound_gt_zero[OF one0 em0] obtain d where d: "d > 0" "d < 1" "d < e / m" by blast from d(1,3) m(1) have dm: "d * m > 0" "d * m < e" by (simp_all add: field_simps) show ?case proof (rule ex_forward[OF field_lbound_gt_zero[OF one0 em0]], clarsimp simp add: norm_mult) fix d w assume H: "d > 0" "d < 1" "d < e/m" "w \<noteq> z" "norm (w - z) < d" then have d1: "norm (w-z) \<le> 1" "d \<ge> 0" by simp_all from H(3) m(1) have dme: "d*m < e" by (simp add: field_simps) from H have th: "norm (w - z) \<le> d" by simp from mult_mono[OF th m(2)[OF d1(1)] d1(2) norm_ge_zero] dme show "norm (w - z) * norm (poly cs (w - z)) < e" by simp qed qed qed text \<open>Hence a polynomial attains minimum on a closed disc in the complex plane.\<close> lemma poly_minimum_modulus_disc: "\<exists>z. \<forall>w. cmod w \<le> r \<longrightarrow> cmod (poly p z) \<le> cmod (poly p w)" proof - show ?thesis proof (cases "r \<ge> 0") case False then show ?thesis by (metis norm_ge_zero order.trans) next case True then have "cmod 0 \<le> r \<and> cmod (poly p 0) = - (- cmod (poly p 0))" by simp then have mth1: "\<exists>x z. cmod z \<le> r \<and> cmod (poly p z) = - x" by blast have False if "cmod z \<le> r" "cmod (poly p z) = - x" "\<not> x < 1" for x z proof - from that have "- x < 0 " by arith with that(2) norm_ge_zero[of "poly p z"] show ?thesis by simp qed then have mth2: "\<exists>z. \<forall>x. (\<exists>z. cmod z \<le> r \<and> cmod (poly p z) = - x) \<longrightarrow> x < z" by blast from real_sup_exists[OF mth1 mth2] obtain s where s: "\<forall>y. (\<exists>x. (\<exists>z. cmod z \<le> r \<and> cmod (poly p z) = - x) \<and> y < x) \<longleftrightarrow> y < s" by blast let ?m = "- s" have s1[unfolded minus_minus]: "(\<exists>z x. cmod z \<le> r \<and> - (- cmod (poly p z)) < y) \<longleftrightarrow> ?m < y" for y using s[rule_format, of "-y"] unfolding minus_less_iff[of y] equation_minus_iff by blast from s1[of ?m] have s1m: "\<And>z x. cmod z \<le> r \<Longrightarrow> cmod (poly p z) \<ge> ?m" by auto have "\<exists>z. cmod z \<le> r \<and> cmod (poly p z) < - s + 1 / real (Suc n)" for n using s1[rule_format, of "?m + 1/real (Suc n)"] by simp then have th: "\<forall>n. \<exists>z. cmod z \<le> r \<and> cmod (poly p z) < - s + 1 / real (Suc n)" .. from choice[OF th] obtain g where g: "\<forall>n. cmod (g n) \<le> r" "\<forall>n. cmod (poly p (g n)) <?m + 1 /real(Suc n)" by blast from Bolzano_Weierstrass_complex_disc[OF g(1)] obtain f z where fz: "strict_mono (f :: nat \<Rightarrow> nat)" "\<forall>e>0. \<exists>N. \<forall>n\<ge>N. cmod (g (f n) - z) < e" by blast { fix w assume wr: "cmod w \<le> r" let ?e = "\<bar>cmod (poly p z) - ?m\<bar>" { assume e: "?e > 0" then have e2: "?e/2 > 0" by simp from poly_cont[OF e2, of z p] obtain d where d: "d > 0" "\<forall>w. 0<cmod (w - z)\<and> cmod(w - z) < d \<longrightarrow> cmod(poly p w - poly p z) < ?e/2" by blast have th1: "cmod(poly p w - poly p z) < ?e / 2" if w: "cmod (w - z) < d" for w using d(2)[rule_format, of w] w e by (cases "w = z") simp_all from fz(2) d(1) obtain N1 where N1: "\<forall>n\<ge>N1. cmod (g (f n) - z) < d" by blast from reals_Archimedean2[of "2/?e"] obtain N2 :: nat where N2: "2/?e < real N2" by blast have th2: "cmod (poly p (g (f (N1 + N2))) - poly p z) < ?e/2" using N1[rule_format, of "N1 + N2"] th1 by simp have th0: "a < e2 \<Longrightarrow> \<bar>b - m\<bar> < e2 \<Longrightarrow> 2 * e2 \<le> \<bar>b - m\<bar> + a \<Longrightarrow> False" for a b e2 m :: real by arith have ath: "m \<le> x \<Longrightarrow> x < m + e \<Longrightarrow> \<bar>x - m\<bar> < e" for m x e :: real by arith from s1m[OF g(1)[rule_format]] have th31: "?m \<le> cmod(poly p (g (f (N1 + N2))))" . from seq_suble[OF fz(1), of "N1 + N2"] have th00: "real (Suc (N1 + N2)) \<le> real (Suc (f (N1 + N2)))" by simp have th000: "0 \<le> (1::real)" "(1::real) \<le> 1" "real (Suc (N1 + N2)) > 0" using N2 by auto from frac_le[OF th000 th00] have th00: "?m + 1 / real (Suc (f (N1 + N2))) \<le> ?m + 1 / real (Suc (N1 + N2))" by simp from g(2)[rule_format, of "f (N1 + N2)"] have th01:"cmod (poly p (g (f (N1 + N2)))) < - s + 1 / real (Suc (f (N1 + N2)))" . from order_less_le_trans[OF th01 th00] have th32: "cmod (poly p (g (f (N1 + N2)))) < ?m + (1/ real(Suc (N1 + N2)))" . from N2 have "2/?e < real (Suc (N1 + N2))" by arith with e2 less_imp_inverse_less[of "2/?e" "real (Suc (N1 + N2))"] have "?e/2 > 1/ real (Suc (N1 + N2))" by (simp add: inverse_eq_divide) with ath[OF th31 th32] have thc1: "\<bar>cmod (poly p (g (f (N1 + N2)))) - ?m\<bar> < ?e/2" by arith have ath2: "\<bar>a - b\<bar> \<le> c \<Longrightarrow> \<bar>b - m\<bar> \<le> \<bar>a - m\<bar> + c" for a b c m :: real by arith have th22: "\<bar>cmod (poly p (g (f (N1 + N2)))) - cmod (poly p z)\<bar> \<le> cmod (poly p (g (f (N1 + N2))) - poly p z)" by (simp add: norm_triangle_ineq3) from ath2[OF th22, of ?m] have thc2: "2 * (?e/2) \<le> \<bar>cmod(poly p (g (f (N1 + N2)))) - ?m\<bar> + cmod (poly p (g (f (N1 + N2))) - poly p z)" by simp from th0[OF th2 thc1 thc2] have False . } then have "?e = 0" by auto then have "cmod (poly p z) = ?m" by simp with s1m[OF wr] have "cmod (poly p z) \<le> cmod (poly p w)" by simp } then show ?thesis by blast qed qed text \<open>Nonzero polynomial in z goes to infinity as z does.\<close> lemma poly_infinity: fixes p:: "'a::{comm_semiring_0,real_normed_div_algebra} poly" assumes ex: "p \<noteq> 0" shows "\<exists>r. \<forall>z. r \<le> norm z \<longrightarrow> d \<le> norm (poly (pCons a p) z)" using ex proof (induct p arbitrary: a d) case 0 then show ?case by simp next case (pCons c cs a d) show ?case proof (cases "cs = 0") case False with pCons.hyps obtain r where r: "\<forall>z. r \<le> norm z \<longrightarrow> d + norm a \<le> norm (poly (pCons c cs) z)" by blast let ?r = "1 + \<bar>r\<bar>" have "d \<le> norm (poly (pCons a (pCons c cs)) z)" if "1 + \<bar>r\<bar> \<le> norm z" for z proof - have r0: "r \<le> norm z" using that by arith from r[rule_format, OF r0] have th0: "d + norm a \<le> 1 * norm(poly (pCons c cs) z)" by arith from that have z1: "norm z \<ge> 1" by arith from order_trans[OF th0 mult_right_mono[OF z1 norm_ge_zero[of "poly (pCons c cs) z"]]] have th1: "d \<le> norm(z * poly (pCons c cs) z) - norm a" unfolding norm_mult by (simp add: algebra_simps) from norm_diff_ineq[of "z * poly (pCons c cs) z" a] have th2: "norm (z * poly (pCons c cs) z) - norm a \<le> norm (poly (pCons a (pCons c cs)) z)" by (simp add: algebra_simps) from th1 th2 show ?thesis by arith qed then show ?thesis by blast next case True with pCons.prems have c0: "c \<noteq> 0" by simp have "d \<le> norm (poly (pCons a (pCons c cs)) z)" if h: "(\<bar>d\<bar> + norm a) / norm c \<le> norm z" for z :: 'a proof - from c0 have "norm c > 0" by simp from h c0 have th0: "\<bar>d\<bar> + norm a \<le> norm (z * c)" by (simp add: field_simps norm_mult) have ath: "\<And>mzh mazh ma. mzh \<le> mazh + ma \<Longrightarrow> \<bar>d\<bar> + ma \<le> mzh \<Longrightarrow> d \<le> mazh" by arith from norm_diff_ineq[of "z * c" a] have th1: "norm (z * c) \<le> norm (a + z * c) + norm a" by (simp add: algebra_simps) from ath[OF th1 th0] show ?thesis using True by simp qed then show ?thesis by blast qed qed text \<open>Hence polynomial's modulus attains its minimum somewhere.\<close> lemma poly_minimum_modulus: "\<exists>z.\<forall>w. cmod (poly p z) \<le> cmod (poly p w)" proof (induct p) case 0 then show ?case by simp next case (pCons c cs) show ?case proof (cases "cs = 0") case False from poly_infinity[OF False, of "cmod (poly (pCons c cs) 0)" c] obtain r where r: "cmod (poly (pCons c cs) 0) \<le> cmod (poly (pCons c cs) z)" if "r \<le> cmod z" for z by blast have ath: "\<And>z r. r \<le> cmod z \<or> cmod z \<le> \<bar>r\<bar>" by arith from poly_minimum_modulus_disc[of "\<bar>r\<bar>" "pCons c cs"] obtain v where v: "cmod (poly (pCons c cs) v) \<le> cmod (poly (pCons c cs) w)" if "cmod w \<le> \<bar>r\<bar>" for w by blast have "cmod (poly (pCons c cs) v) \<le> cmod (poly (pCons c cs) z)" if z: "r \<le> cmod z" for z using v[of 0] r[OF z] by simp with v ath[of r] show ?thesis by blast next case True with pCons.hyps show ?thesis by simp qed qed text \<open>Constant function (non-syntactic characterization).\<close> definition "constant f \<longleftrightarrow> (\<forall>x y. f x = f y)" lemma nonconstant_length: "\<not> constant (poly p) \<Longrightarrow> psize p \<ge> 2" by (induct p) (auto simp: constant_def psize_def) lemma poly_replicate_append: "poly (monom 1 n * p) (x::'a::comm_ring_1) = x^n * poly p x" by (simp add: poly_monom) text \<open>Decomposition of polynomial, skipping zero coefficients after the first.\<close> lemma poly_decompose_lemma: assumes nz: "\<not> (\<forall>z. z \<noteq> 0 \<longrightarrow> poly p z = (0::'a::idom))" shows "\<exists>k a q. a \<noteq> 0 \<and> Suc (psize q + k) = psize p \<and> (\<forall>z. poly p z = z^k * poly (pCons a q) z)" unfolding psize_def using nz proof (induct p) case 0 then show ?case by simp next case (pCons c cs) show ?case proof (cases "c = 0") case True from pCons.hyps pCons.prems True show ?thesis apply auto apply (rule_tac x="k+1" in exI) apply (rule_tac x="a" in exI) apply clarsimp apply (rule_tac x="q" in exI) apply auto done next case False show ?thesis apply (rule exI[where x=0]) apply (rule exI[where x=c]) apply (auto simp: False) done qed qed lemma poly_decompose: assumes nc: "\<not> constant (poly p)" shows "\<exists>k a q. a \<noteq> (0::'a::idom) \<and> k \<noteq> 0 \<and> psize q + k + 1 = psize p \<and> (\<forall>z. poly p z = poly p 0 + z^k * poly (pCons a q) z)" using nc proof (induct p) case 0 then show ?case by (simp add: constant_def) next case (pCons c cs) have "\<not> (\<forall>z. z \<noteq> 0 \<longrightarrow> poly cs z = 0)" proof assume "\<forall>z. z \<noteq> 0 \<longrightarrow> poly cs z = 0" then have "poly (pCons c cs) x = poly (pCons c cs) y" for x y by (cases "x = 0") auto with pCons.prems show False by (auto simp add: constant_def) qed from poly_decompose_lemma[OF this] show ?case apply clarsimp apply (rule_tac x="k+1" in exI) apply (rule_tac x="a" in exI) apply simp apply (rule_tac x="q" in exI) apply (auto simp add: psize_def split: if_splits) done qed text \<open>Fundamental theorem of algebra\<close> lemma fundamental_theorem_of_algebra: assumes nc: "\<not> constant (poly p)" shows "\<exists>z::complex. poly p z = 0" using nc proof (induct "psize p" arbitrary: p rule: less_induct) case less let ?p = "poly p" let ?ths = "\<exists>z. ?p z = 0" from nonconstant_length[OF less(2)] have n2: "psize p \<ge> 2" . from poly_minimum_modulus obtain c where c: "\<forall>w. cmod (?p c) \<le> cmod (?p w)" by blast show ?ths proof (cases "?p c = 0") case True then show ?thesis by blast next case False from poly_offset[of p c] obtain q where q: "psize q = psize p" "\<forall>x. poly q x = ?p (c + x)" by blast have False if h: "constant (poly q)" proof - from q(2) have th: "\<forall>x. poly q (x - c) = ?p x" by auto have "?p x = ?p y" for x y proof - from th have "?p x = poly q (x - c)" by auto also have "\<dots> = poly q (y - c)" using h unfolding constant_def by blast also have "\<dots> = ?p y" using th by auto finally show ?thesis . qed with less(2) show ?thesis unfolding constant_def by blast qed then have qnc: "\<not> constant (poly q)" by blast from q(2) have pqc0: "?p c = poly q 0" by simp from c pqc0 have cq0: "\<forall>w. cmod (poly q 0) \<le> cmod (?p w)" by simp let ?a0 = "poly q 0" from False pqc0 have a00: "?a0 \<noteq> 0" by simp from a00 have qr: "\<forall>z. poly q z = poly (smult (inverse ?a0) q) z * ?a0" by simp let ?r = "smult (inverse ?a0) q" have lgqr: "psize q = psize ?r" using a00 unfolding psize_def degree_def by (simp add: poly_eq_iff) have False if h: "\<And>x y. poly ?r x = poly ?r y" proof - have "poly q x = poly q y" for x y proof - from qr[rule_format, of x] have "poly q x = poly ?r x * ?a0" by auto also have "\<dots> = poly ?r y * ?a0" using h by simp also have "\<dots> = poly q y" using qr[rule_format, of y] by simp finally show ?thesis . qed with qnc show ?thesis unfolding constant_def by blast qed then have rnc: "\<not> constant (poly ?r)" unfolding constant_def by blast from qr[rule_format, of 0] a00 have r01: "poly ?r 0 = 1" by auto have mrmq_eq: "cmod (poly ?r w) < 1 \<longleftrightarrow> cmod (poly q w) < cmod ?a0" for w proof - have "cmod (poly ?r w) < 1 \<longleftrightarrow> cmod (poly q w / ?a0) < 1" using qr[rule_format, of w] a00 by (simp add: divide_inverse ac_simps) also have "\<dots> \<longleftrightarrow> cmod (poly q w) < cmod ?a0" using a00 unfolding norm_divide by (simp add: field_simps) finally show ?thesis . qed from poly_decompose[OF rnc] obtain k a s where kas: "a \<noteq> 0" "k \<noteq> 0" "psize s + k + 1 = psize ?r" "\<forall>z. poly ?r z = poly ?r 0 + z^k* poly (pCons a s) z" by blast have "\<exists>w. cmod (poly ?r w) < 1" proof (cases "psize p = k + 1") case True with kas(3) lgqr[symmetric] q(1) have s0: "s = 0" by auto have hth[symmetric]: "cmod (poly ?r w) = cmod (1 + a * w ^ k)" for w using kas(4)[rule_format, of w] s0 r01 by (simp add: algebra_simps) from reduce_poly_simple[OF kas(1,2)] show ?thesis unfolding hth by blast next case False note kn = this from kn kas(3) q(1) lgqr have k1n: "k + 1 < psize p" by simp have th01: "\<not> constant (poly (pCons 1 (monom a (k - 1))))" unfolding constant_def poly_pCons poly_monom using kas(1) apply simp apply (rule exI[where x=0]) apply (rule exI[where x=1]) apply simp done from kas(1) kas(2) have th02: "k + 1 = psize (pCons 1 (monom a (k - 1)))" by (simp add: psize_def degree_monom_eq) from less(1) [OF k1n [simplified th02] th01] obtain w where w: "1 + w^k * a = 0" unfolding poly_pCons poly_monom using kas(2) by (cases k) (auto simp add: algebra_simps) from poly_bound_exists[of "cmod w" s] obtain m where m: "m > 0" "\<forall>z. cmod z \<le> cmod w \<longrightarrow> cmod (poly s z) \<le> m" by blast have w0: "w \<noteq> 0" using kas(2) w by (auto simp add: power_0_left) from w have "(1 + w ^ k * a) - 1 = 0 - 1" by simp then have wm1: "w^k * a = - 1" by simp have inv0: "0 < inverse (cmod w ^ (k + 1) * m)" using norm_ge_zero[of w] w0 m(1) by (simp add: inverse_eq_divide zero_less_mult_iff) with field_lbound_gt_zero[OF zero_less_one] obtain t where t: "t > 0" "t < 1" "t < inverse (cmod w ^ (k + 1) * m)" by blast let ?ct = "complex_of_real t" let ?w = "?ct * w" have "1 + ?w^k * (a + ?w * poly s ?w) = 1 + ?ct^k * (w^k * a) + ?w^k * ?w * poly s ?w" using kas(1) by (simp add: algebra_simps power_mult_distrib) also have "\<dots> = complex_of_real (1 - t^k) + ?w^k * ?w * poly s ?w" unfolding wm1 by simp finally have "cmod (1 + ?w^k * (a + ?w * poly s ?w)) = cmod (complex_of_real (1 - t^k) + ?w^k * ?w * poly s ?w)" by metis with norm_triangle_ineq[of "complex_of_real (1 - t^k)" "?w^k * ?w * poly s ?w"] have th11: "cmod (1 + ?w^k * (a + ?w * poly s ?w)) \<le> \<bar>1 - t^k\<bar> + cmod (?w^k * ?w * poly s ?w)" unfolding norm_of_real by simp have ath: "\<And>x t::real. 0 \<le> x \<Longrightarrow> x < t \<Longrightarrow> t \<le> 1 \<Longrightarrow> \<bar>1 - t\<bar> + x < 1" by arith have "t * cmod w \<le> 1 * cmod w" apply (rule mult_mono) using t(1,2) apply auto done then have tw: "cmod ?w \<le> cmod w" using t(1) by (simp add: norm_mult) from t inv0 have "t * (cmod w ^ (k + 1) * m) < 1" by (simp add: field_simps) with zero_less_power[OF t(1), of k] have th30: "t^k * (t* (cmod w ^ (k + 1) * m)) < t^k * 1" by simp have "cmod (?w^k * ?w * poly s ?w) = t^k * (t* (cmod w ^ (k + 1) * cmod (poly s ?w)))" using w0 t(1) by (simp add: algebra_simps power_mult_distrib norm_power norm_mult) then have "cmod (?w^k * ?w * poly s ?w) \<le> t^k * (t* (cmod w ^ (k + 1) * m))" using t(1,2) m(2)[rule_format, OF tw] w0 by auto with th30 have th120: "cmod (?w^k * ?w * poly s ?w) < t^k" by simp from power_strict_mono[OF t(2), of k] t(1) kas(2) have th121: "t^k \<le> 1" by auto from ath[OF norm_ge_zero[of "?w^k * ?w * poly s ?w"] th120 th121] have th12: "\<bar>1 - t^k\<bar> + cmod (?w^k * ?w * poly s ?w) < 1" . from th11 th12 have "cmod (1 + ?w^k * (a + ?w * poly s ?w)) < 1" by arith then have "cmod (poly ?r ?w) < 1" unfolding kas(4)[rule_format, of ?w] r01 by simp then show ?thesis by blast qed with cq0 q(2) show ?thesis unfolding mrmq_eq not_less[symmetric] by auto qed qed text \<open>Alternative version with a syntactic notion of constant polynomial.\<close> lemma fundamental_theorem_of_algebra_alt: assumes nc: "\<not> (\<exists>a l. a \<noteq> 0 \<and> l = 0 \<and> p = pCons a l)" shows "\<exists>z. poly p z = (0::complex)" using nc proof (induct p) case 0 then show ?case by simp next case (pCons c cs) show ?case proof (cases "c = 0") case True then show ?thesis by auto next case False have "\<not> constant (poly (pCons c cs))" proof assume nc: "constant (poly (pCons c cs))" from nc[unfolded constant_def, rule_format, of 0] have "\<forall>w. w \<noteq> 0 \<longrightarrow> poly cs w = 0" by auto then have "cs = 0" proof (induct cs) case 0 then show ?case by simp next case (pCons d ds) show ?case proof (cases "d = 0") case True then show ?thesis using pCons.prems pCons.hyps by simp next case False from poly_bound_exists[of 1 ds] obtain m where m: "m > 0" "\<forall>z. \<forall>z. cmod z \<le> 1 \<longrightarrow> cmod (poly ds z) \<le> m" by blast have dm: "cmod d / m > 0" using False m(1) by (simp add: field_simps) from field_lbound_gt_zero[OF dm zero_less_one] obtain x where x: "x > 0" "x < cmod d / m" "x < 1" by blast let ?x = "complex_of_real x" from x have cx: "?x \<noteq> 0" "cmod ?x \<le> 1" by simp_all from pCons.prems[rule_format, OF cx(1)] have cth: "cmod (?x*poly ds ?x) = cmod d" by (simp add: eq_diff_eq[symmetric]) from m(2)[rule_format, OF cx(2)] x(1) have th0: "cmod (?x*poly ds ?x) \<le> x*m" by (simp add: norm_mult) from x(2) m(1) have "x * m < cmod d" by (simp add: field_simps) with th0 have "cmod (?x*poly ds ?x) \<noteq> cmod d" by auto with cth show ?thesis by blast qed qed then show False using pCons.prems False by blast qed then show ?thesis by (rule fundamental_theorem_of_algebra) qed qed subsection \<open>Nullstellensatz, degrees and divisibility of polynomials\<close> lemma nullstellensatz_lemma: fixes p :: "complex poly" assumes "\<forall>x. poly p x = 0 \<longrightarrow> poly q x = 0" and "degree p = n" and "n \<noteq> 0" shows "p dvd (q ^ n)" using assms proof (induct n arbitrary: p q rule: nat_less_induct) fix n :: nat fix p q :: "complex poly" assume IH: "\<forall>m<n. \<forall>p q. (\<forall>x. poly p x = (0::complex) \<longrightarrow> poly q x = 0) \<longrightarrow> degree p = m \<longrightarrow> m \<noteq> 0 \<longrightarrow> p dvd (q ^ m)" and pq0: "\<forall>x. poly p x = 0 \<longrightarrow> poly q x = 0" and dpn: "degree p = n" and n0: "n \<noteq> 0" from dpn n0 have pne: "p \<noteq> 0" by auto show "p dvd (q ^ n)" proof (cases "\<exists>a. poly p a = 0") case True then obtain a where a: "poly p a = 0" .. have ?thesis if oa: "order a p \<noteq> 0" proof - let ?op = "order a p" from pne have ap: "([:- a, 1:] ^ ?op) dvd p" "\<not> [:- a, 1:] ^ (Suc ?op) dvd p" using order by blast+ note oop = order_degree[OF pne, unfolded dpn] show ?thesis proof (cases "q = 0") case True with n0 show ?thesis by (simp add: power_0_left) next case False from pq0[rule_format, OF a, unfolded poly_eq_0_iff_dvd] obtain r where r: "q = [:- a, 1:] * r" by (rule dvdE) from ap(1) obtain s where s: "p = [:- a, 1:] ^ ?op * s" by (rule dvdE) have sne: "s \<noteq> 0" using s pne by auto show ?thesis proof (cases "degree s = 0") case True then obtain k where kpn: "s = [:k:]" by (cases s) (auto split: if_splits) from sne kpn have k: "k \<noteq> 0" by simp let ?w = "([:1/k:] * ([:-a,1:] ^ (n - ?op))) * (r ^ n)" have "q ^ n = p * ?w" apply (subst r) apply (subst s) apply (subst kpn) using k oop [of a] apply (subst power_mult_distrib) apply simp apply (subst power_add [symmetric]) apply simp done then show ?thesis unfolding dvd_def by blast next case False with sne dpn s oa have dsn: "degree s < n" apply auto apply (erule ssubst) apply (simp add: degree_mult_eq degree_linear_power) done have "poly r x = 0" if h: "poly s x = 0" for x proof - have xa: "x \<noteq> a" proof assume "x = a" from h[unfolded this poly_eq_0_iff_dvd] obtain u where u: "s = [:- a, 1:] * u" by (rule dvdE) have "p = [:- a, 1:] ^ (Suc ?op) * u" apply (subst s) apply (subst u) apply (simp only: power_Suc ac_simps) done with ap(2)[unfolded dvd_def] show False by blast qed from h have "poly p x = 0" by (subst s) simp with pq0 have "poly q x = 0" by blast with r xa show ?thesis by auto qed with IH[rule_format, OF dsn, of s r] False have "s dvd (r ^ (degree s))" by blast then obtain u where u: "r ^ (degree s) = s * u" .. then have u': "\<And>x. poly s x * poly u x = poly r x ^ degree s" by (simp only: poly_mult[symmetric] poly_power[symmetric]) let ?w = "(u * ([:-a,1:] ^ (n - ?op))) * (r ^ (n - degree s))" from oop[of a] dsn have "q ^ n = p * ?w" apply - apply (subst s) apply (subst r) apply (simp only: power_mult_distrib) apply (subst mult.assoc [where b=s]) apply (subst mult.assoc [where a=u]) apply (subst mult.assoc [where b=u, symmetric]) apply (subst u [symmetric]) apply (simp add: ac_simps power_add [symmetric]) done then show ?thesis unfolding dvd_def by blast qed qed qed then show ?thesis using a order_root pne by blast next case False with fundamental_theorem_of_algebra_alt[of p] obtain c where ccs: "c \<noteq> 0" "p = pCons c 0" by blast then have pp: "poly p x = c" for x by simp let ?w = "[:1/c:] * (q ^ n)" from ccs have "(q ^ n) = (p * ?w)" by simp then show ?thesis unfolding dvd_def by blast qed qed lemma nullstellensatz_univariate: "(\<forall>x. poly p x = (0::complex) \<longrightarrow> poly q x = 0) \<longleftrightarrow> p dvd (q ^ (degree p)) \<or> (p = 0 \<and> q = 0)" proof - consider "p = 0" | "p \<noteq> 0" "degree p = 0" | n where "p \<noteq> 0" "degree p = Suc n" by (cases "degree p") auto then show ?thesis proof cases case p: 1 then have eq: "(\<forall>x. poly p x = (0::complex) \<longrightarrow> poly q x = 0) \<longleftrightarrow> q = 0" by (auto simp add: poly_all_0_iff_0) { assume "p dvd (q ^ (degree p))" then obtain r where r: "q ^ (degree p) = p * r" .. from r p have False by simp } with eq p show ?thesis by blast next case dp: 2 then obtain k where k: "p = [:k:]" "k \<noteq> 0" by (cases p) (simp split: if_splits) then have th1: "\<forall>x. poly p x \<noteq> 0" by simp from k dp(2) have "q ^ (degree p) = p * [:1/k:]" by simp then have th2: "p dvd (q ^ (degree p))" .. from dp(1) th1 th2 show ?thesis by blast next case dp: 3 have False if dvd: "p dvd (q ^ (Suc n))" and h: "poly p x = 0" "poly q x \<noteq> 0" for x proof - from dvd obtain u where u: "q ^ (Suc n) = p * u" .. from h have "poly (q ^ (Suc n)) x \<noteq> 0" by simp with u h(1) show ?thesis by (simp only: poly_mult) simp qed with dp nullstellensatz_lemma[of p q "degree p"] show ?thesis by auto qed qed text \<open>Useful lemma\<close> lemma constant_degree: fixes p :: "'a::{idom,ring_char_0} poly" shows "constant (poly p) \<longleftrightarrow> degree p = 0" (is "?lhs = ?rhs") proof show ?rhs if ?lhs proof - from that[unfolded constant_def, rule_format, of _ "0"] have th: "poly p = poly [:poly p 0:]" by auto then have "p = [:poly p 0:]" by (simp add: poly_eq_poly_eq_iff) then have "degree p = degree [:poly p 0:]" by simp then show ?thesis by simp qed show ?lhs if ?rhs proof - from that obtain k where "p = [:k:]" by (cases p) (simp split: if_splits) then show ?thesis unfolding constant_def by auto qed qed text \<open>Arithmetic operations on multivariate polynomials.\<close> lemma mpoly_base_conv: fixes x :: "'a::comm_ring_1" shows "0 = poly 0 x" "c = poly [:c:] x" "x = poly [:0,1:] x" by simp_all lemma mpoly_norm_conv: fixes x :: "'a::comm_ring_1" shows "poly [:0:] x = poly 0 x" "poly [:poly 0 y:] x = poly 0 x" by simp_all lemma mpoly_sub_conv: fixes x :: "'a::comm_ring_1" shows "poly p x - poly q x = poly p x + -1 * poly q x" by simp lemma poly_pad_rule: "poly p x = 0 \<Longrightarrow> poly (pCons 0 p) x = 0" by simp lemma poly_cancel_eq_conv: fixes x :: "'a::field" shows "x = 0 \<Longrightarrow> a \<noteq> 0 \<Longrightarrow> y = 0 \<longleftrightarrow> a * y - b * x = 0" by auto lemma poly_divides_pad_rule: fixes p:: "('a::comm_ring_1) poly" assumes pq: "p dvd q" shows "p dvd (pCons 0 q)" proof - have "pCons 0 q = q * [:0,1:]" by simp then have "q dvd (pCons 0 q)" .. with pq show ?thesis by (rule dvd_trans) qed lemma poly_divides_conv0: fixes p:: "'a::field poly" assumes lgpq: "degree q < degree p" and lq: "p \<noteq> 0" shows "p dvd q \<longleftrightarrow> q = 0" (is "?lhs \<longleftrightarrow> ?rhs") proof assume ?rhs then have "q = p * 0" by simp then show ?lhs .. next assume l: ?lhs show ?rhs proof (cases "q = 0") case True then show ?thesis by simp next assume q0: "q \<noteq> 0" from l q0 have "degree p \<le> degree q" by (rule dvd_imp_degree_le) with lgpq show ?thesis by simp qed qed lemma poly_divides_conv1: fixes p :: "'a::field poly" assumes a0: "a \<noteq> 0" and pp': "p dvd p'" and qrp': "smult a q - p' = r" shows "p dvd q \<longleftrightarrow> p dvd r" (is "?lhs \<longleftrightarrow> ?rhs") proof from pp' obtain t where t: "p' = p * t" .. show ?rhs if ?lhs proof - from that obtain u where u: "q = p * u" .. have "r = p * (smult a u - t)" using u qrp' [symmetric] t by (simp add: algebra_simps) then show ?thesis .. qed show ?lhs if ?rhs proof - from that obtain u where u: "r = p * u" .. from u [symmetric] t qrp' [symmetric] a0 have "q = p * smult (1/a) (u + t)" by (simp add: algebra_simps) then show ?thesis .. qed qed lemma basic_cqe_conv1: "(\<exists>x. poly p x = 0 \<and> poly 0 x \<noteq> 0) \<longleftrightarrow> False" "(\<exists>x. poly 0 x \<noteq> 0) \<longleftrightarrow> False" "(\<exists>x. poly [:c:] x \<noteq> 0) \<longleftrightarrow> c \<noteq> 0" "(\<exists>x. poly 0 x = 0) \<longleftrightarrow> True" "(\<exists>x. poly [:c:] x = 0) \<longleftrightarrow> c = 0" by simp_all lemma basic_cqe_conv2: assumes l: "p \<noteq> 0" shows "\<exists>x. poly (pCons a (pCons b p)) x = (0::complex)" proof - have False if "h \<noteq> 0" "t = 0" and "pCons a (pCons b p) = pCons h t" for h t using l that by simp then have th: "\<not> (\<exists> h t. h \<noteq> 0 \<and> t = 0 \<and> pCons a (pCons b p) = pCons h t)" by blast from fundamental_theorem_of_algebra_alt[OF th] show ?thesis by auto qed lemma basic_cqe_conv_2b: "(\<exists>x. poly p x \<noteq> (0::complex)) \<longleftrightarrow> p \<noteq> 0" by (metis poly_all_0_iff_0) lemma basic_cqe_conv3: fixes p q :: "complex poly" assumes l: "p \<noteq> 0" shows "(\<exists>x. poly (pCons a p) x = 0 \<and> poly q x \<noteq> 0) \<longleftrightarrow> \<not> (pCons a p) dvd (q ^ psize p)" proof - from l have dp: "degree (pCons a p) = psize p" by (simp add: psize_def) from nullstellensatz_univariate[of "pCons a p" q] l show ?thesis by (metis dp pCons_eq_0_iff) qed lemma basic_cqe_conv4: fixes p q :: "complex poly" assumes h: "\<And>x. poly (q ^ n) x = poly r x" shows "p dvd (q ^ n) \<longleftrightarrow> p dvd r" proof - from h have "poly (q ^ n) = poly r" by auto then have "(q ^ n) = r" by (simp add: poly_eq_poly_eq_iff) then show "p dvd (q ^ n) \<longleftrightarrow> p dvd r" by simp qed lemma poly_const_conv: fixes x :: "'a::comm_ring_1" shows "poly [:c:] x = y \<longleftrightarrow> c = y" by simp end
module Data.List.Predicates.Interleaving import Data.List %access public export %default total data Interleaving : (xs, ys, zs : List type) -> Type where Empty : Interleaving Nil Nil Nil LeftAdd : (x : type) -> (rest : Interleaving xs ys zs) -> Interleaving (x::xs) ys (x::zs) RightAdd : (y : type) -> (rest : Interleaving xs ys zs) -> Interleaving xs (y::ys) (y::zs) leftEmpty : (ys : List type) -> Interleaving Nil ys ys leftEmpty [] = Empty leftEmpty (x :: xs) = RightAdd x (leftEmpty xs) leftEmptyCons : (x : type) -> (xs : List type) -> Interleaving Nil (x::xs) (x::xs) leftEmptyCons x [] = RightAdd x Empty leftEmptyCons x (y :: xs) with (leftEmptyCons y xs) leftEmptyCons x (y :: xs) | (RightAdd y rest) = RightAdd x (RightAdd y rest) rightEmpty : (xs : List type) -> Interleaving xs Nil xs rightEmpty [] = Empty rightEmpty (x :: xs) = LeftAdd x (rightEmpty xs)
As of 21 June 2016 .
As of 21 June 2016 .
(* Title: The pi-calculus Author/Maintainer: Jesper Bengtson (jebe.dk), 2012 *) theory Weak_Late_Bisim_Subst_Pres imports Weak_Late_Bisim_Subst Weak_Late_Bisim_Pres begin lemma tauPres: fixes P :: pi and Q :: pi assumes "P \<approx>\<^sup>s Q" shows "\<tau>.(P) \<approx>\<^sup>s \<tau>.(Q)" using assms by(force simp add: substClosed_def intro: Weak_Late_Bisim_Pres.tauPres) lemma inputPres: fixes P :: pi and Q :: pi and a :: name and x :: name assumes PeqQ: "P \<approx>\<^sup>s Q" shows "a<x>.P \<approx>\<^sup>s a<x>.Q" proof(auto simp add: substClosed_def) fix \<sigma> :: "(name \<times> name) list" { fix P Q a x \<sigma> assume "P \<approx>\<^sup>s Q" then have "P[<\<sigma>>] \<approx>\<^sup>s Q[<\<sigma>>]" by(rule partUnfold) then have "\<forall>y. (P[<\<sigma>>])[x::=y] \<approx> (Q[<\<sigma>>])[x::=y]" apply(auto simp add: substClosed_def) by(erule_tac x="[(x, y)]" in allE) auto moreover assume "x \<sharp> \<sigma>" ultimately have "(a<x>.P)[<\<sigma>>] \<approx> (a<x>.Q)[<\<sigma>>]" using weakBisimEqvt by(force intro: Weak_Late_Bisim_Pres.inputPres) } note Goal = this obtain y::name where "y \<sharp> P" and "y \<sharp> Q" and "y \<sharp> \<sigma>" by(generate_fresh "name") auto from \<open>P \<approx>\<^sup>s Q\<close> have "([(x, y)] \<bullet> P) \<approx>\<^sup>s ([(x, y)] \<bullet> Q)" by(rule eqvtI) hence "(a<y>.([(x, y)] \<bullet> P))[<\<sigma>>] \<approx> (a<y>.([(x, y)] \<bullet> Q))[<\<sigma>>]" using \<open>y \<sharp> \<sigma>\<close> by(rule Goal) moreover from \<open>y \<sharp> P\<close> \<open>y \<sharp> Q\<close> have "a<x>.P = a<y>.([(x, y)] \<bullet> P)" and "a<x>.Q = a<y>.([(x, y)] \<bullet> Q)" by(simp add: pi.alphaInput)+ ultimately show "(a<x>.P)[<\<sigma>>] \<approx> (a<x>.Q)[<\<sigma>>]" by simp qed lemma outputPres: fixes P :: pi and Q :: pi assumes "P \<approx>\<^sup>s Q" shows "a{b}.P \<approx>\<^sup>s a{b}.Q" using assms by(force simp add: substClosed_def intro: Weak_Late_Bisim_Pres.outputPres) assumes "P \<approx>\<^sup>s Q" shows "[a\<frown>b]P \<approx>\<^sup>s [a\<frown>b]Q" using assms by(force simp add: substClosed_def intro: Weak_Late_Bisim_Pres.matchPres) lemma mismatchPres: fixes P :: pi and Q :: pi and a :: name and b :: name assumes "P \<approx>\<^sup>s Q" shows "[a\<noteq>b]P \<approx>\<^sup>s [a\<noteq>b]Q" using assms by(force simp add: substClosed_def intro: Weak_Late_Bisim_Pres.mismatchPres) lemma parPres: fixes P :: pi and Q :: pi and R :: pi assumes "P \<approx>\<^sup>s Q" shows "P \<parallel> R \<approx>\<^sup>s Q \<parallel> R" using assms by(force simp add: substClosed_def intro: Weak_Late_Bisim_Pres.parPres) assumes PeqQ: "P \<approx>\<^sup>s Q" shows "<\<nu>x>P \<approx>\<^sup>s <\<nu>x>Q" proof(auto simp add: substClosed_def) fix s::"(name \<times> name) list" have Res: "\<And>P Q x s. \<lbrakk>P[<s>] \<approx> Q[<s>]; x \<sharp> s\<rbrakk> \<Longrightarrow> (<\<nu>x>P)[<s>] \<approx> (<\<nu>x>Q)[<s>]" by(force intro: Weak_Late_Bisim_Pres.resPres) have "\<exists>c::name. c \<sharp> (P, Q, s)" by(blast intro: name_exists_fresh) then obtain c::name where cFreshP: "c \<sharp> P" and cFreshQ: "c \<sharp> Q" and cFreshs: "c \<sharp> s" by(force simp add: fresh_prod) from PeqQ have "P[<([(x, c)] \<bullet> s)>] \<approx> Q[<([(x, c)] \<bullet> s)>]" by(simp add: substClosed_def) hence "([(x, c)] \<bullet> P[<([(x, c)] \<bullet> s)>]) \<approx> ([(x, c)] \<bullet> Q[<([(x, c)] \<bullet> s)>])" by(rule Weak_Late_Bisim.eqvtI) hence "([(x, c)] \<bullet> P)[<s>] \<approx> ([(x, c)] \<bullet> Q)[<s>]" by simp hence "(<\<nu>c>([(x, c)] \<bullet> P))[<s>] \<approx> (<\<nu>c>([(x, c)] \<bullet> Q))[<s>]" using cFreshs by(rule Res) moreover from cFreshP cFreshQ have "<\<nu>x>P = <\<nu>c>([(x, c)] \<bullet> P)" and "<\<nu>x>Q = <\<nu>c>([(x, c)] \<bullet> Q)" by(simp add: alphaRes)+ ultimately show "(<\<nu>x>P)[<s>] \<approx> (<\<nu>x>Q)[<s>]" by simp qed shows "!P \<approx>\<^sup>s !Q" using assms by(force simp add: substClosed_def intro: Weak_Late_Bisim_Pres.bangPres) end
Require Import VST.floyd.base2. Require Import VST.floyd.client_lemmas. Require Import VST.floyd.closed_lemmas. Require Import VST.floyd.local2ptree_denote. Import LiftNotation. Import compcert.lib.Maps. Local Open Scope logic. Definition eval_vardesc (id: ident) (ty: type) (Delta: tycontext) (T2: PTree.t (type * val)) (GV: option globals) : option val := match (var_types Delta) ! id with | Some _ => match T2 ! id with | Some (ty', v) => if eqb_type ty ty' then Some v else None | None => None end | None => match GV with | Some gv => Some (gv id) | None => None end end. Definition eval_lvardesc (id: ident) (ty: type) (Delta: tycontext) (T2: PTree.t (type * val)) : option val := match (var_types Delta) ! id with | Some _ => match T2 ! id with | Some (ty', v) => if eqb_type ty ty' then Some v else None | None => None end | None => None end. Fixpoint msubst_eval_expr {cs: compspecs} (Delta: tycontext) (T1: PTree.t val) (T2: PTree.t (type * val)) (GV: option globals) (e: Clight.expr) : option val := match e with | Econst_int i ty => Some (Vint i) | Econst_long i ty => Some (Vlong i) | Econst_float f ty => Some (Vfloat f) | Econst_single f ty => Some (Vsingle f) | Etempvar id ty => PTree.get id T1 | Eaddrof a ty => msubst_eval_lvalue Delta T1 T2 GV a | Eunop op a ty => option_map (eval_unop op (typeof a)) (msubst_eval_expr Delta T1 T2 GV a) | Ebinop op a1 a2 ty => match (msubst_eval_expr Delta T1 T2 GV a1), (msubst_eval_expr Delta T1 T2 GV a2) with | Some v1, Some v2 => Some (eval_binop op (typeof a1) (typeof a2) v1 v2) | _, _ => None end | Ecast a ty => option_map (eval_cast (typeof a) ty) (msubst_eval_expr Delta T1 T2 GV a) | Evar id ty => eval_vardesc id ty Delta T2 GV | Ederef a ty => msubst_eval_expr Delta T1 T2 GV a | Efield a i ty => option_map (eval_field (typeof a) i) (msubst_eval_lvalue Delta T1 T2 GV a) | Esizeof t _ => Some (if complete_type cenv_cs t then Vptrofs (Ptrofs.repr (sizeof t)) else Vundef) | Ealignof t _ => Some (if complete_type cenv_cs t then Vptrofs (Ptrofs.repr (alignof t)) else Vundef) end with msubst_eval_lvalue {cs: compspecs} (Delta: tycontext) (T1: PTree.t val) (T2: PTree.t (type * val)) (GV: option globals) (e: Clight.expr) : option val := match e with | Evar id ty => eval_vardesc id ty Delta T2 GV | Ederef a ty => msubst_eval_expr Delta T1 T2 GV a | Efield a i ty => option_map (eval_field (typeof a) i) (msubst_eval_lvalue Delta T1 T2 GV a) | _ => Some Vundef end. Definition msubst_eval_LR {cs: compspecs} Delta T1 T2 GV e (lr: LLRR) := match lr with | LLLL => msubst_eval_lvalue Delta T1 T2 GV e | RRRR => msubst_eval_expr Delta T1 T2 GV e end. Definition msubst_eval_lvar {cs: compspecs} Delta T2 i t := eval_lvardesc i t Delta T2. Lemma msubst_eval_expr_eq_aux: forall {cs: compspecs} (Delta: tycontext) (T1: PTree.t val) (T2: PTree.t (type * val)) (GV: option globals) e rho v, (forall i v, T1 ! i = Some v -> eval_id i rho = v) -> (forall i t v, eval_vardesc i t Delta T2 GV = Some v -> eval_var i t rho = v) -> msubst_eval_expr Delta T1 T2 GV e = Some v -> eval_expr e rho = v with msubst_eval_lvalue_eq_aux: forall {cs: compspecs} (Delta: tycontext) (T1: PTree.t val) (T2: PTree.t (type * val)) (GV: option globals) e rho v, (forall i v, T1 ! i = Some v -> eval_id i rho = v) -> (forall i t v, eval_vardesc i t Delta T2 GV = Some v -> eval_var i t rho = v) -> msubst_eval_lvalue Delta T1 T2 GV e = Some v -> eval_lvalue e rho = v. Proof. + clear msubst_eval_expr_eq_aux. induction e; intros; simpl in H1 |- *; try solve [inversion H1; auto]. - erewrite msubst_eval_lvalue_eq_aux; eauto. - unfold_lift; simpl. destruct (msubst_eval_expr Delta T1 T2 GV e) eqn:?; [| inversion H1]. inversion H1. rewrite IHe with (v := v0) by auto. reflexivity. - unfold_lift; simpl. destruct (msubst_eval_expr Delta T1 T2 GV e1) eqn:?; [| inversion H1]. destruct (msubst_eval_expr Delta T1 T2 GV e2) eqn:?; [| inversion H1]. inversion H1. rewrite IHe1 with (v := v0) by auto. rewrite IHe2 with (v := v1) by auto. reflexivity. - unfold_lift; simpl. destruct (msubst_eval_expr Delta T1 T2 GV e) eqn:?; [| inversion H1]. inversion H1. rewrite IHe with (v := v0) by auto. reflexivity. - unfold_lift; simpl. destruct (msubst_eval_lvalue Delta T1 T2 GV e) eqn:?; [| inversion H1]. inversion H1. erewrite msubst_eval_lvalue_eq_aux by eauto. reflexivity. + clear msubst_eval_lvalue_eq_aux. induction e; intros; simpl in H1 |- *; try solve [inversion H1; auto]. - unfold_lift; simpl. destruct (msubst_eval_expr Delta T1 T2 GV e) eqn:?; [| inversion H1]. inversion H1. erewrite msubst_eval_expr_eq_aux by eauto; auto. - unfold_lift; simpl. destruct (msubst_eval_lvalue Delta T1 T2 GV e) eqn:?; [| inversion H1]. inversion H1. rewrite IHe with (v := v0) by auto. reflexivity. Qed. Require Import VST.veric.expr_lemmas2. Lemma msubst_eval_eq_aux {cs: compspecs}: forall Delta T1 T2 GV rho, tc_environ Delta rho -> fold_right `(and) `(True) (map locald_denote (LocalD T1 T2 GV)) rho -> (forall i v, T1 ! i = Some v -> eval_id i rho = v) /\ (forall i t v, eval_vardesc i t Delta T2 GV = Some v -> eval_var i t rho = v). Proof. intros; split; intros. + intros. assert (In (locald_denote (temp i v)) (map locald_denote (LocalD T1 T2 GV))). { apply in_map. apply LocalD_sound. left. eauto. } pose proof local_ext _ _ _ H2 H0. destruct H3; auto. + intros. unfold eval_vardesc in H1. unfold eval_var. red in H. destruct_var_types i; rewrite ?Heqo, ?Heqo0 in *. - destruct (T2 ! i) as [[? ?]|] eqn:?; [| inv H1]. destruct (eqb_type t t1) eqn:?; inv H1. apply eqb_type_true in Heqb0. subst t1. assert (In (locald_denote (lvar i t v)) (map locald_denote (LocalD T1 T2 GV))) by (apply in_map; apply LocalD_sound; eauto 50). assert (H3 := local_ext _ _ _ H1 H0). clear - H3 Heqo Heqo0. hnf in H3. rewrite Heqo0 in H3. destruct H3; subst. rewrite eqb_type_refl. auto. - destruct GV as [?gv |]; inv H1. assert (In (locald_denote (gvars gv)) (map locald_denote (LocalD T1 T2 (Some gv)))) by (apply in_map; apply LocalD_sound; eauto 50). assert (H3 := local_ext _ _ _ H1 H0). clear - H3. unfold eval_var in *. hnf in H3. subst. auto. Qed. Lemma msubst_eval_lvar_eq_aux {cs: compspecs}: forall Delta T1 T2 GV rho, tc_environ Delta rho -> fold_right `(and) `(True) (map locald_denote (LocalD T1 T2 GV)) rho -> (forall i t v, eval_lvardesc i t Delta T2 = Some v -> eval_lvar i t rho = v). Proof. intros. unfold eval_lvar. unfold eval_lvardesc in H1. red in H. destruct_var_types i; rewrite ?Heqo, ?Heqo0 in *; [| inv H1]. destruct (T2 ! i) as [[? ?]|] eqn:?; [| inv H1]. destruct (eqb_type t t1) eqn:?; inv H1. apply eqb_type_true in Heqb0; subst t1. assert (In (locald_denote (lvar i t v)) (map locald_denote (LocalD T1 T2 GV))) by ( apply in_map; apply LocalD_sound; eauto 50). assert (H3 := local_ext _ _ _ H1 H0). clear - H3 Heqo Heqo0. hnf in H3. rewrite Heqo0 in H3. destruct H3; subst. rewrite eqb_type_refl. auto. Qed. Lemma msubst_eval_expr_eq: forall {cs: compspecs} Delta P T1 T2 GV R e v, msubst_eval_expr Delta T1 T2 GV e = Some v -> ENTAIL Delta, PROPx P (LOCALx (LocalD T1 T2 GV) (SEPx R)) |-- local (`(eq v) (eval_expr e)). Proof. intros. unfold PROPx, LOCALx. apply derives_trans with (local (tc_environ Delta) && local (fold_right (` and) (` True) (map locald_denote (LocalD T1 T2 GV)))); [solve_andp |]. unfold local, lift, lift1. simpl; intro rho. normalize; intros. autorewrite with subst norm1 norm2; normalize. destruct (msubst_eval_eq_aux _ _ _ _ _ H0 H1). apply eq_sym, (msubst_eval_expr_eq_aux Delta T1 T2 GV); auto. Qed. Lemma msubst_eval_lvalue_eq: forall {cs: compspecs} Delta P T1 T2 GV R e v, msubst_eval_lvalue Delta T1 T2 GV e = Some v -> ENTAIL Delta, PROPx P (LOCALx (LocalD T1 T2 GV) (SEPx R)) |-- local (`(eq v) (eval_lvalue e)). Proof. intros. unfold PROPx, LOCALx. apply derives_trans with (local (tc_environ Delta) && local (fold_right (` and) (` True) (map locald_denote (LocalD T1 T2 GV)))); [solve_andp |]. unfold local, lift, lift1. simpl; intro rho. normalize; intros. autorewrite with subst norm1 norm2; normalize. destruct (msubst_eval_eq_aux _ _ _ _ _ H0 H1). apply eq_sym, (msubst_eval_lvalue_eq_aux Delta T1 T2 GV); auto. Qed. Lemma msubst_eval_LR_eq: forall {cs: compspecs} Delta P T1 T2 GV R e v lr, msubst_eval_LR Delta T1 T2 GV e lr = Some v -> ENTAIL Delta, PROPx P (LOCALx (LocalD T1 T2 GV) (SEPx R)) |-- local (`(eq v) (eval_LR e lr)). Proof. intros. destruct lr. + apply msubst_eval_lvalue_eq; auto. + apply msubst_eval_expr_eq; auto. Qed. Lemma msubst_eval_exprlist_eq: forall {cs: compspecs} Delta P T1 T2 GV R tys el vl, force_list (map (msubst_eval_expr Delta T1 T2 GV) (explicit_cast_exprlist tys el)) = Some vl -> ENTAIL Delta, PROPx P (LOCALx (LocalD T1 T2 GV) (SEPx R)) |-- local (`(eq vl) (eval_exprlist tys el)). Proof. intros. revert tys vl H; induction el; destruct tys, vl; intros; try solve [inv H]; try solve [go_lowerx; apply prop_right; reflexivity]. simpl map in H. unfold force_list in H; fold (@force_list val) in H. destruct (msubst_eval_expr Delta T1 T2 GV a) eqn:?. simpl in H. destruct (force_list (map (msubst_eval_expr Delta T1 T2 GV) (explicit_cast_exprlist tys el))); inv H. simpl in H. inv H. simpl in H. destruct (option_map (force_val1 (sem_cast (typeof a) t)) (msubst_eval_expr Delta T1 T2 GV a)) eqn:?; inv H. destruct ( force_list (map (msubst_eval_expr Delta T1 T2 GV) (explicit_cast_exprlist tys el))) eqn:?; inv H1. specialize (IHel _ _ Heqo0). simpl eval_exprlist. destruct (msubst_eval_expr Delta T1 T2 GV a) eqn:?; inv Heqo. apply @msubst_eval_expr_eq with (P:=P) (GV:=GV) (R:=R) in Heqo1. apply derives_trans with (local (`(eq v0) (eval_expr a)) && local (`(eq vl) (eval_exprlist tys el))). apply andp_right; auto. go_lowerx. unfold_lift. intros. apply prop_right. rewrite <- H. rewrite <- H0. auto. Qed. Lemma msubst_eval_lvar_eq: forall {cs: compspecs} Delta P T1 T2 GV R i t v, msubst_eval_lvar Delta T2 i t = Some v -> ENTAIL Delta, PROPx P (LOCALx (LocalD T1 T2 GV) (SEPx R)) |-- local (`(eq v) (eval_lvar i t)). Proof. intros. unfold PROPx, LOCALx. apply derives_trans with (local (tc_environ Delta) && local (fold_right (` and) (` True) (map locald_denote (LocalD T1 T2 GV)))); [solve_andp |]. unfold local, lift, lift1. simpl; intro rho. normalize; intros. autorewrite with subst norm1 norm2; normalize. pose proof (msubst_eval_lvar_eq_aux _ _ _ _ _ H0 H1). apply eq_sym. apply H2; auto. Qed. Ltac prove_eqb_type := match goal with |- context [eqb_type ?A ?B] => try change (eqb_type A B) with true; rewrite (proj2 (eqb_type_spec A B)) by (repeat f_equal; rep_lia) end; cbv beta iota. Ltac solve_msubst_eval_lvalue := (simpl; cbv beta iota zeta delta [force_val2 force_val1]; rewrite ?isptr_force_ptr, <- ?offset_val_force_ptr by auto; unfold eval_vardesc; repeat match goal with |- match match PTree.get ?A ?B with _ => _ end with _ => _ end = _ => let x := fresh "x" in set (x := PTree.get A B); hnf in x; subst x; cbv beta iota end; try prove_eqb_type; reflexivity) || match goal with |- msubst_eval_lvalue _ _ _ _ ?e = _ => fail "Cannot symbolically evaluate expression" e "given the information in your LOCAL clause; did you forget a 'temp' declaration?" end. Ltac solve_msubst_eval_expr := (simpl; cbv beta iota zeta delta [force_val2 force_val1]; rewrite ?isptr_force_ptr, <- ?offset_val_force_ptr by auto; reflexivity) || match goal with |- msubst_eval_expr _ _ _ _ ?e = _ => fail "Cannot symbolically evaluate expression" e "given the information in your LOCAL clause; did you forget a 'temp' declaration?" end. Ltac solve_msubst_eval_LR := (unfold msubst_eval_LR; simpl; cbv beta iota zeta delta [force_val2 force_val1]; rewrite ?isptr_force_ptr, <- ?offset_val_force_ptr by auto; unfold eval_vardesc; repeat match goal with |- match PTree.get ?A ?B with _ => _ end = _ => let x := fresh "x" in set (x := PTree.get A B); hnf in x; subst x; cbv beta iota end; try prove_eqb_type; reflexivity) || match goal with |- msubst_eval_LR _ _ _ _ ?e _ = _ => fail "Cannot symbolically evaluate expression" e "given the information in your LOCAL clause; did you forget a 'temp' declaration?" end. Ltac solve_msubst_eval_lvar := (unfold msubst_eval_lvar; unfold eval_vardesc, eval_lvardesc; repeat match goal with |- match PTree.get ?A ?B with _ => _ end = _ => let x := fresh "x" in set (x := PTree.get A B); hnf in x; subst x; cbv beta iota end; try prove_eqb_type; reflexivity) || match goal with |- msubst_eval_lvar _ _ ?id _ = _ => fail "Cannot symbolically evaluate lvar" id "given the information in your LOCAL clause; did you forget an 'lvar' declaration?" end. (**********************************************************) (* Continuation *) (* Require Import VST.veric.xexpr_rel. Inductive l_cont : Type := | LC_deref : r_cont -> l_cont | LC_field : l_cont -> type -> ident -> l_cont with r_cont : Type := | RC_addrof : l_cont -> r_cont | RC_unop : unary_operation -> r_cont -> type -> r_cont | RC_binop_l : binary_operation -> r_cont -> type -> r_value -> type -> r_cont | RC_binop_r : binary_operation -> val -> type -> r_cont -> type -> r_cont | RC_cast : r_cont -> type -> type -> r_cont | RC_byref: l_cont -> r_cont | RC_load: r_cont. Definition sum_map {A B C D : Type} (f : A -> B) (g: C -> D) (x : A + C) := match x with | inl y => inl (f y) | inr z => inr (g z) end. Definition prod_left_map {A B C} (f: A -> B) (x: A * C) : B * C := match x with | (x1, x2) => (f x1, x2) end. Definition compute_cont_map {A B} (f: val -> val) (g: A -> B) : option (val + (A * (l_value * type))) -> option (val + (B * (l_value * type))) := option_map (sum_map f (prod_left_map g)). Fixpoint compute_r_cont {cs: compspecs} (T1: PTree.t val) (T2: PTree.t vardesc) (e: r_value) : option (val + (r_cont * (l_value * type))) := match e with | R_const v => Some (inl v) | R_tempvar id => option_map inl (PTree.get id T1) | R_addrof a => compute_cont_map id RC_addrof (compute_l_cont T1 T2 a) | R_unop op a ta => compute_cont_map (eval_unop op ta) (fun c => RC_unop op c ta) (compute_r_cont T1 T2 a) | R_binop op a1 ta1 a2 ta2 => match compute_r_cont T1 T2 a1 with | Some (inl v1) => compute_cont_map (eval_binop op ta1 ta2 v1) (fun c => RC_binop_r op v1 ta1 c ta2) (compute_r_cont T1 T2 a2) | Some (inr (c, e_cont)) => Some (inr (RC_binop_l op c ta1 a2 ta2, e_cont)) | None => None end | R_cast a ta ty => compute_cont_map (eval_cast ta ty) (fun c => RC_cast c ta ty) (compute_r_cont T1 T2 a) | R_byref a => compute_cont_map id RC_byref (compute_l_cont T1 T2 a) | R_load a ty => Some (inr (RC_load, (a, ty))) | R_ilegal _ => None end with compute_l_cont {cs: compspecs} (T1: PTree.t val) (T2: PTree.t vardesc) (e: l_value) : option (val + (l_cont * (l_value * type))) := match e with | L_var id ty => option_map inl (eval_vardesc ty (PTree.get id T2)) | L_deref a => compute_cont_map force_ptr LC_deref (compute_r_cont T1 T2 a) | L_field a ta i => compute_cont_map (eval_field ta i) (fun c => LC_field c ta i) (compute_l_cont T1 T2 a) | L_ilegal _ => None end. Fixpoint fill_r_cont (e: r_cont) (v: val): r_value := match e with | RC_addrof a => R_addrof (fill_l_cont a v) | RC_unop op a ta => R_unop op (fill_r_cont a v) ta | RC_binop_l op a1 ta1 a2 ta2 => R_binop op (fill_r_cont a1 v) ta1 a2 ta2 | RC_binop_r op v1 ta1 a2 ta2 => R_binop op (R_const v1) ta1 (fill_r_cont a2 v) ta2 | RC_cast a ta ty => R_cast (fill_r_cont a v) ta ty | RC_byref a => R_byref (fill_l_cont a v) | RC_load => R_const v end with fill_l_cont (e: l_cont) (v: val): l_value := match e with | LC_deref a => L_deref (fill_r_cont a v) | LC_field a ta i => L_field (fill_l_cont a v) ta i end. Lemma compute_LR_cont_sound: forall (cs: compspecs) (T1: PTree.t val) (T2: PTree.t vardesc) P Q R, (forall e v, compute_r_cont T1 T2 e = Some (inl v) -> PROPx P (LOCALx (LocalD T1 T2 Q) (SEPx R)) |-- rel_r_value e v) /\ (forall e v c e0 sh t p v0, compute_r_cont T1 T2 e = Some (inr (c, (e0, t))) -> PROPx P (LOCALx (LocalD T1 T2 Q) (SEPx R)) |-- rel_l_value e0 p -> PROPx P (LOCALx (LocalD T1 T2 Q) (SEPx R)) |-- `(mapsto sh t p v0) -> PROPx P (LOCALx (LocalD T1 T2 Q) (SEPx R)) |-- rel_r_value (fill_r_cont c v0) v -> PROPx P (LOCALx (LocalD T1 T2 Q) (SEPx R)) |-- rel_r_value e v). /\ *)
-- {-# OPTIONS -v tc.meta:30 #-} {-# OPTIONS --sized-types #-} module GiveSize where postulate Size : Set postulate ∞ : Size {-# BUILTIN SIZE Size #-} -- {-# BUILTIN SIZEINF ∞ #-} id : Size → Size id i = {!i!}
/- Copyright (c) 2021 Vladimir Goryachev. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Vladimir Goryachev, Kyle Miller, Scott Morrison, Eric Rodriguez ! This file was ported from Lean 3 source module data.nat.count ! leanprover-community/mathlib commit 1ead22342e1a078bd44744ace999f85756555d35 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.SetTheory.Cardinal.Basic import Mathbin.Tactic.Ring /-! # Counting on ℕ > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the `count` function, which gives, for any predicate on the natural numbers, "how many numbers under `k` satisfy this predicate?". We then prove several expected lemmas about `count`, relating it to the cardinality of other objects, and helping to evaluate it for specific `k`. -/ open Finset namespace Nat variable (p : ℕ → Prop) section Count variable [DecidablePred p] #print Nat.count /- /-- Count the number of naturals `k < n` satisfying `p k`. -/ def count (n : ℕ) : ℕ := (List.range n).countp p #align nat.count Nat.count -/ #print Nat.count_zero /- @[simp] theorem count_zero : count p 0 = 0 := by rw [count, List.range_zero, List.countp] #align nat.count_zero Nat.count_zero -/ #print Nat.CountSet.fintype /- /-- A fintype instance for the set relevant to `nat.count`. Locally an instance in locale `count` -/ def CountSet.fintype (n : ℕ) : Fintype { i // i < n ∧ p i } := by apply Fintype.ofFinset ((Finset.range n).filterₓ p) intro x rw [mem_filter, mem_range] rfl #align nat.count_set.fintype Nat.CountSet.fintype -/ scoped[Count] attribute [instance] Nat.CountSet.fintype #print Nat.count_eq_card_filter_range /- theorem count_eq_card_filter_range (n : ℕ) : count p n = ((range n).filterₓ p).card := by rw [count, List.countp_eq_length_filter] rfl #align nat.count_eq_card_filter_range Nat.count_eq_card_filter_range -/ #print Nat.count_eq_card_fintype /- /-- `count p n` can be expressed as the cardinality of `{k // k < n ∧ p k}`. -/ theorem count_eq_card_fintype (n : ℕ) : count p n = Fintype.card { k : ℕ // k < n ∧ p k } := by rw [count_eq_card_filter_range, ← Fintype.card_ofFinset, ← count_set.fintype] rfl #align nat.count_eq_card_fintype Nat.count_eq_card_fintype -/ #print Nat.count_succ /- theorem count_succ (n : ℕ) : count p (n + 1) = count p n + if p n then 1 else 0 := by split_ifs <;> simp [count, List.range_succ, h] #align nat.count_succ Nat.count_succ -/ #print Nat.count_monotone /- @[mono] theorem count_monotone : Monotone (count p) := monotone_nat_of_le_succ fun n => by by_cases h : p n <;> simp [count_succ, h] #align nat.count_monotone Nat.count_monotone -/ #print Nat.count_add /- theorem count_add (a b : ℕ) : count p (a + b) = count p a + count (fun k => p (a + k)) b := by have : Disjoint ((range a).filterₓ p) (((range b).map <| addLeftEmbedding a).filterₓ p) := by apply disjoint_filter_filter rw [Finset.disjoint_left] simp_rw [mem_map, mem_range, addLeftEmbedding_apply] rintro x hx ⟨c, _, rfl⟩ exact (self_le_add_right _ _).not_lt hx simp_rw [count_eq_card_filter_range, range_add, filter_union, card_disjoint_union this, filter_map, addLeftEmbedding, card_map] rfl #align nat.count_add Nat.count_add -/ #print Nat.count_add' /- theorem count_add' (a b : ℕ) : count p (a + b) = count (fun k => p (k + b)) a + count p b := by rw [add_comm, count_add, add_comm] simp_rw [add_comm b] #align nat.count_add' Nat.count_add' -/ #print Nat.count_one /- theorem count_one : count p 1 = if p 0 then 1 else 0 := by simp [count_succ] #align nat.count_one Nat.count_one -/ #print Nat.count_succ' /- theorem count_succ' (n : ℕ) : count p (n + 1) = count (fun k => p (k + 1)) n + if p 0 then 1 else 0 := by rw [count_add', count_one] #align nat.count_succ' Nat.count_succ' -/ variable {p} #print Nat.count_lt_count_succ_iff /- @[simp] theorem count_lt_count_succ_iff {n : ℕ} : count p n < count p (n + 1) ↔ p n := by by_cases h : p n <;> simp [count_succ, h] #align nat.count_lt_count_succ_iff Nat.count_lt_count_succ_iff -/ #print Nat.count_succ_eq_succ_count_iff /- theorem count_succ_eq_succ_count_iff {n : ℕ} : count p (n + 1) = count p n + 1 ↔ p n := by by_cases h : p n <;> simp [h, count_succ] #align nat.count_succ_eq_succ_count_iff Nat.count_succ_eq_succ_count_iff -/ #print Nat.count_succ_eq_count_iff /- theorem count_succ_eq_count_iff {n : ℕ} : count p (n + 1) = count p n ↔ ¬p n := by by_cases h : p n <;> simp [h, count_succ] #align nat.count_succ_eq_count_iff Nat.count_succ_eq_count_iff -/ alias count_succ_eq_succ_count_iff ↔ _ count_succ_eq_succ_count #align nat.count_succ_eq_succ_count Nat.count_succ_eq_succ_count alias count_succ_eq_count_iff ↔ _ count_succ_eq_count #align nat.count_succ_eq_count Nat.count_succ_eq_count /- warning: nat.count_le_cardinal -> Nat.count_le_cardinal is a dubious translation: lean 3 declaration is forall {p : Nat -> Prop} [_inst_1 : DecidablePred.{1} Nat p] (n : Nat), LE.le.{1} Cardinal.{0} Cardinal.hasLe.{0} ((fun (a : Type) (b : Type.{1}) [self : HasLiftT.{1, 2} a b] => self.0) Nat Cardinal.{0} (HasLiftT.mk.{1, 2} Nat Cardinal.{0} (CoeTCₓ.coe.{1, 2} Nat Cardinal.{0} (Nat.castCoe.{1} Cardinal.{0} Cardinal.hasNatCast.{0}))) (Nat.count p (fun (a : Nat) => _inst_1 a) n)) (Cardinal.mk.{0} (coeSort.{1, 2} (Set.{0} Nat) Type (Set.hasCoeToSort.{0} Nat) (setOf.{0} Nat (fun (k : Nat) => p k)))) but is expected to have type forall {p : Nat -> Prop} [_inst_1 : DecidablePred.{1} Nat p] (n : Nat), LE.le.{1} Cardinal.{0} Cardinal.instLECardinal.{0} (Nat.cast.{1} Cardinal.{0} Cardinal.instNatCastCardinal.{0} (Nat.count p (fun (a : Nat) => _inst_1 a) n)) (Cardinal.mk.{0} (Set.Elem.{0} Nat (setOf.{0} Nat (fun (k : Nat) => p k)))) Case conversion may be inaccurate. Consider using '#align nat.count_le_cardinal Nat.count_le_cardinalₓ'. -/ theorem count_le_cardinal (n : ℕ) : (count p n : Cardinal) ≤ Cardinal.mk { k | p k } := by rw [count_eq_card_fintype, ← Cardinal.mk_fintype] exact Cardinal.mk_subtype_mono fun x hx => hx.2 #align nat.count_le_cardinal Nat.count_le_cardinal #print Nat.lt_of_count_lt_count /- theorem lt_of_count_lt_count {a b : ℕ} (h : count p a < count p b) : a < b := (count_monotone p).reflect_lt h #align nat.lt_of_count_lt_count Nat.lt_of_count_lt_count -/ #print Nat.count_strict_mono /- theorem count_strict_mono {m n : ℕ} (hm : p m) (hmn : m < n) : count p m < count p n := (count_lt_count_succ_iff.2 hm).trans_le <| count_monotone _ (Nat.succ_le_iff.2 hmn) #align nat.count_strict_mono Nat.count_strict_mono -/ #print Nat.count_injective /- theorem count_injective {m n : ℕ} (hm : p m) (hn : p n) (heq : count p m = count p n) : m = n := by by_contra' h : m ≠ n wlog hmn : m < n · exact this hn hm HEq.symm h.symm (h.lt_or_lt.resolve_left hmn) · simpa [HEq] using count_strict_mono hm hmn #align nat.count_injective Nat.count_injective -/ #print Nat.count_le_card /- theorem count_le_card (hp : (setOf p).Finite) (n : ℕ) : count p n ≤ hp.toFinset.card := by rw [count_eq_card_filter_range] exact Finset.card_mono fun x hx => hp.mem_to_finset.2 (mem_filter.1 hx).2 #align nat.count_le_card Nat.count_le_card -/ #print Nat.count_lt_card /- theorem count_lt_card {n : ℕ} (hp : (setOf p).Finite) (hpn : p n) : count p n < hp.toFinset.card := (count_lt_count_succ_iff.2 hpn).trans_le (count_le_card hp _) #align nat.count_lt_card Nat.count_lt_card -/ variable {q : ℕ → Prop} variable [DecidablePred q] #print Nat.count_mono_left /- theorem count_mono_left {n : ℕ} (hpq : ∀ k, p k → q k) : count p n ≤ count q n := by simp only [count_eq_card_filter_range] exact card_le_of_subset ((range n).monotone_filter_right hpq) #align nat.count_mono_left Nat.count_mono_left -/ end Count end Nat
(* Copyright (C) 2020 Susi Lehtola This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *) (* type: mgga_exc *) (* prefix: mgga_k_csk_loc_params *params; assert(p->params != NULL); params = (mgga_k_csk_loc_params * )(p->params); *) $include "mgga_k_csk.mpl" (* Equation (21) *) csk_z := (p, q) -> 1 + params_a_csk_cp*p + params_a_csk_cq*q - (1 + 5*p/3):
Require Import Nat Arith. Inductive Nat : Type := succ : Nat -> Nat | zero : Nat. Inductive Lst : Type := cons : Nat -> Lst -> Lst | nil : Lst. Inductive Tree : Type := node : Nat -> Tree -> Tree -> Tree | leaf : Tree. Inductive Pair : Type := mkpair : Nat -> Nat -> Pair with ZLst : Type := zcons : Pair -> ZLst -> ZLst | znil : ZLst. Fixpoint plus (plus_arg0 : Nat) (plus_arg1 : Nat) : Nat := match plus_arg0, plus_arg1 with | zero, n => n | succ n, m => succ (plus n m) end. Fixpoint even (even_arg0 : Nat) : bool := match even_arg0 with | zero => true | succ n => negb (even n) end. Fixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst := match append_arg0, append_arg1 with | nil, x => x | cons x y, z => cons x (append y z) end. Fixpoint len (len_arg0 : Lst) : Nat := match len_arg0 with | nil => zero | cons x y => succ (len y) end. (* No helper lemma needed. *) Theorem theorem0 : forall (x : Lst) (y : Lst), eq (even (len (append x y))) (even (plus (len x) (len y))). Proof. induction x. - intros. simpl. rewrite IHx. reflexivity. - intros. reflexivity. Qed.
Georgetown — Sally Long, a long-time resident of the Georgetown area, died Wednesday the 18th of June at Sun Bridge Healthcare Center. Born in 1928 in Madison, S.D., Sally received a Bachelor of Science in Nursing Education from South Dakota State College in 1951. She continued her education at the University of Minnesota, from which she received her M.Ed. in Nursing in 1955. Sally taught Nursing at the University of Massachusetts at Amherst in the mid-1960s and worked at various psychiatric nursing facilities throughout western Massachusetts in the 1970s. In a career shift, she took a position as a librarian assistant at Franklin County Technical School, Turners Falls, where she worked until her retirement. Sally loved good food and socializing, enjoyed going to movies and plays with friends, and had a wonderful smile that could light up a room. She is survived by her niece, Tabitha Winslow and several grandnieces, all of whom live in southern California, and brought great joy to her later years. Memorial gifts may be made to the Dakin Pioneer Valley Humane Society, PO Box 319, South Deerfield, MA 01373. The Douglass Funeral Service, Amherst, has been entrusted with arrangements.
[STATEMENT] lemma mtp_gt_0_iff_in_FV: shows "mtp x t > 0 \<longleftrightarrow> x \<in> FV t" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (0 < mtp x t) = (x \<in> FV t) [PROOF STEP] proof (induct t arbitrary: x) [PROOF STATE] proof (state) goal (5 subgoals): 1. \<And>x. (0 < mtp x \<^bold>\<sharp>) = (x \<in> FV \<^bold>\<sharp>) 2. \<And>x xa. (0 < mtp xa \<^bold>\<guillemotleft>x\<^bold>\<guillemotright>) = (xa \<in> FV \<^bold>\<guillemotleft>x\<^bold>\<guillemotright>) 3. \<And>t x. (\<And>x. (0 < mtp x t) = (x \<in> FV t)) \<Longrightarrow> (0 < mtp x \<^bold>\<lambda>\<^bold>[t\<^bold>]) = (x \<in> FV \<^bold>\<lambda>\<^bold>[t\<^bold>]) 4. \<And>t1 t2 x. \<lbrakk>\<And>x. (0 < mtp x t1) = (x \<in> FV t1); \<And>x. (0 < mtp x t2) = (x \<in> FV t2)\<rbrakk> \<Longrightarrow> (0 < mtp x (t1 \<^bold>\<circ> t2)) = (x \<in> FV (t1 \<^bold>\<circ> t2)) 5. \<And>t1 t2 x. \<lbrakk>\<And>x. (0 < mtp x t1) = (x \<in> FV t1); \<And>x. (0 < mtp x t2) = (x \<in> FV t2)\<rbrakk> \<Longrightarrow> (0 < mtp x (\<^bold>\<lambda>\<^bold>[t1\<^bold>] \<^bold>\<Zspot> t2)) = (x \<in> FV (\<^bold>\<lambda>\<^bold>[t1\<^bold>] \<^bold>\<Zspot> t2)) [PROOF STEP] show "\<And>x. 0 < mtp x \<^bold>\<sharp> \<longleftrightarrow> x \<in> FV \<^bold>\<sharp>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>x. (0 < mtp x \<^bold>\<sharp>) = (x \<in> FV \<^bold>\<sharp>) [PROOF STEP] by simp [PROOF STATE] proof (state) this: (0 < mtp ?x \<^bold>\<sharp>) = (?x \<in> FV \<^bold>\<sharp>) goal (4 subgoals): 1. \<And>x xa. (0 < mtp xa \<^bold>\<guillemotleft>x\<^bold>\<guillemotright>) = (xa \<in> FV \<^bold>\<guillemotleft>x\<^bold>\<guillemotright>) 2. \<And>t x. (\<And>x. (0 < mtp x t) = (x \<in> FV t)) \<Longrightarrow> (0 < mtp x \<^bold>\<lambda>\<^bold>[t\<^bold>]) = (x \<in> FV \<^bold>\<lambda>\<^bold>[t\<^bold>]) 3. \<And>t1 t2 x. \<lbrakk>\<And>x. (0 < mtp x t1) = (x \<in> FV t1); \<And>x. (0 < mtp x t2) = (x \<in> FV t2)\<rbrakk> \<Longrightarrow> (0 < mtp x (t1 \<^bold>\<circ> t2)) = (x \<in> FV (t1 \<^bold>\<circ> t2)) 4. \<And>t1 t2 x. \<lbrakk>\<And>x. (0 < mtp x t1) = (x \<in> FV t1); \<And>x. (0 < mtp x t2) = (x \<in> FV t2)\<rbrakk> \<Longrightarrow> (0 < mtp x (\<^bold>\<lambda>\<^bold>[t1\<^bold>] \<^bold>\<Zspot> t2)) = (x \<in> FV (\<^bold>\<lambda>\<^bold>[t1\<^bold>] \<^bold>\<Zspot> t2)) [PROOF STEP] show "\<And>x z. 0 < mtp x \<^bold>\<guillemotleft>z\<^bold>\<guillemotright> \<longleftrightarrow> x \<in> FV \<^bold>\<guillemotleft>z\<^bold>\<guillemotright>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>x z. (0 < mtp x \<^bold>\<guillemotleft>z\<^bold>\<guillemotright>) = (x \<in> FV \<^bold>\<guillemotleft>z\<^bold>\<guillemotright>) [PROOF STEP] by auto [PROOF STATE] proof (state) this: (0 < mtp ?x \<^bold>\<guillemotleft>?z\<^bold>\<guillemotright>) = (?x \<in> FV \<^bold>\<guillemotleft>?z\<^bold>\<guillemotright>) goal (3 subgoals): 1. \<And>t x. (\<And>x. (0 < mtp x t) = (x \<in> FV t)) \<Longrightarrow> (0 < mtp x \<^bold>\<lambda>\<^bold>[t\<^bold>]) = (x \<in> FV \<^bold>\<lambda>\<^bold>[t\<^bold>]) 2. \<And>t1 t2 x. \<lbrakk>\<And>x. (0 < mtp x t1) = (x \<in> FV t1); \<And>x. (0 < mtp x t2) = (x \<in> FV t2)\<rbrakk> \<Longrightarrow> (0 < mtp x (t1 \<^bold>\<circ> t2)) = (x \<in> FV (t1 \<^bold>\<circ> t2)) 3. \<And>t1 t2 x. \<lbrakk>\<And>x. (0 < mtp x t1) = (x \<in> FV t1); \<And>x. (0 < mtp x t2) = (x \<in> FV t2)\<rbrakk> \<Longrightarrow> (0 < mtp x (\<^bold>\<lambda>\<^bold>[t1\<^bold>] \<^bold>\<Zspot> t2)) = (x \<in> FV (\<^bold>\<lambda>\<^bold>[t1\<^bold>] \<^bold>\<Zspot> t2)) [PROOF STEP] show Lam: "\<And>t x. (\<And>x. 0 < mtp x t \<longleftrightarrow> x \<in> FV t) \<Longrightarrow> 0 < mtp x \<^bold>\<lambda>\<^bold>[t\<^bold>] \<longleftrightarrow> x \<in> FV \<^bold>\<lambda>\<^bold>[t\<^bold>]" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>t x. (\<And>x. (0 < mtp x t) = (x \<in> FV t)) \<Longrightarrow> (0 < mtp x \<^bold>\<lambda>\<^bold>[t\<^bold>]) = (x \<in> FV \<^bold>\<lambda>\<^bold>[t\<^bold>]) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>t x. (\<And>x. (0 < mtp x t) = (x \<in> FV t)) \<Longrightarrow> (0 < mtp x \<^bold>\<lambda>\<^bold>[t\<^bold>]) = (x \<in> FV \<^bold>\<lambda>\<^bold>[t\<^bold>]) [PROOF STEP] fix t and x :: nat [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>t x. (\<And>x. (0 < mtp x t) = (x \<in> FV t)) \<Longrightarrow> (0 < mtp x \<^bold>\<lambda>\<^bold>[t\<^bold>]) = (x \<in> FV \<^bold>\<lambda>\<^bold>[t\<^bold>]) [PROOF STEP] assume ind: "\<And>x. 0 < mtp x t \<longleftrightarrow> x \<in> FV t" [PROOF STATE] proof (state) this: (0 < mtp ?x t) = (?x \<in> FV t) goal (1 subgoal): 1. \<And>t x. (\<And>x. (0 < mtp x t) = (x \<in> FV t)) \<Longrightarrow> (0 < mtp x \<^bold>\<lambda>\<^bold>[t\<^bold>]) = (x \<in> FV \<^bold>\<lambda>\<^bold>[t\<^bold>]) [PROOF STEP] show "0 < mtp x \<^bold>\<lambda>\<^bold>[t\<^bold>] \<longleftrightarrow> x \<in> FV \<^bold>\<lambda>\<^bold>[t\<^bold>]" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (0 < mtp x \<^bold>\<lambda>\<^bold>[t\<^bold>]) = (x \<in> FV \<^bold>\<lambda>\<^bold>[t\<^bold>]) [PROOF STEP] using ind [PROOF STATE] proof (prove) using this: (0 < mtp ?x t) = (?x \<in> FV t) goal (1 subgoal): 1. (0 < mtp x \<^bold>\<lambda>\<^bold>[t\<^bold>]) = (x \<in> FV \<^bold>\<lambda>\<^bold>[t\<^bold>]) [PROOF STEP] apply auto [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<lbrakk>\<And>x. (0 < mtp x t) = (x \<in> FV t); Suc x \<in> FV t\<rbrakk> \<Longrightarrow> x \<in> (\<lambda>x. x - Suc 0) ` (FV t - {0}) 2. \<And>x. \<lbrakk>\<And>x. (0 < mtp x t) = (x \<in> FV t); x = x - Suc 0; x \<in> FV t; Suc (x - Suc 0) \<notin> FV t\<rbrakk> \<Longrightarrow> x = 0 [PROOF STEP] apply (metis Diff_iff One_nat_def diff_Suc_1 empty_iff imageI insert_iff nat.distinct(1)) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>x. \<lbrakk>\<And>x. (0 < mtp x t) = (x \<in> FV t); x = x - Suc 0; x \<in> FV t; Suc (x - Suc 0) \<notin> FV t\<rbrakk> \<Longrightarrow> x = 0 [PROOF STEP] by (metis Suc_pred neq0_conv) [PROOF STATE] proof (state) this: (0 < mtp x \<^bold>\<lambda>\<^bold>[t\<^bold>]) = (x \<in> FV \<^bold>\<lambda>\<^bold>[t\<^bold>]) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: (\<And>x. (0 < mtp x ?t) = (x \<in> FV ?t)) \<Longrightarrow> (0 < mtp ?x \<^bold>\<lambda>\<^bold>[?t\<^bold>]) = (?x \<in> FV \<^bold>\<lambda>\<^bold>[?t\<^bold>]) goal (2 subgoals): 1. \<And>t1 t2 x. \<lbrakk>\<And>x. (0 < mtp x t1) = (x \<in> FV t1); \<And>x. (0 < mtp x t2) = (x \<in> FV t2)\<rbrakk> \<Longrightarrow> (0 < mtp x (t1 \<^bold>\<circ> t2)) = (x \<in> FV (t1 \<^bold>\<circ> t2)) 2. \<And>t1 t2 x. \<lbrakk>\<And>x. (0 < mtp x t1) = (x \<in> FV t1); \<And>x. (0 < mtp x t2) = (x \<in> FV t2)\<rbrakk> \<Longrightarrow> (0 < mtp x (\<^bold>\<lambda>\<^bold>[t1\<^bold>] \<^bold>\<Zspot> t2)) = (x \<in> FV (\<^bold>\<lambda>\<^bold>[t1\<^bold>] \<^bold>\<Zspot> t2)) [PROOF STEP] show "\<And>t u x. \<lbrakk>\<And>x. 0 < mtp x t \<longleftrightarrow> x \<in> FV t; \<And>x. 0 < mtp x u \<longleftrightarrow> x \<in> FV u\<rbrakk> \<Longrightarrow> 0 < mtp x (t \<^bold>\<circ> u) \<longleftrightarrow> x \<in> FV (t \<^bold>\<circ> u)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>t u x. \<lbrakk>\<And>x. (0 < mtp x t) = (x \<in> FV t); \<And>x. (0 < mtp x u) = (x \<in> FV u)\<rbrakk> \<Longrightarrow> (0 < mtp x (t \<^bold>\<circ> u)) = (x \<in> FV (t \<^bold>\<circ> u)) [PROOF STEP] by simp [PROOF STATE] proof (state) this: \<lbrakk>\<And>x. (0 < mtp x ?t) = (x \<in> FV ?t); \<And>x. (0 < mtp x ?u) = (x \<in> FV ?u)\<rbrakk> \<Longrightarrow> (0 < mtp ?x (?t \<^bold>\<circ> ?u)) = (?x \<in> FV (?t \<^bold>\<circ> ?u)) goal (1 subgoal): 1. \<And>t1 t2 x. \<lbrakk>\<And>x. (0 < mtp x t1) = (x \<in> FV t1); \<And>x. (0 < mtp x t2) = (x \<in> FV t2)\<rbrakk> \<Longrightarrow> (0 < mtp x (\<^bold>\<lambda>\<^bold>[t1\<^bold>] \<^bold>\<Zspot> t2)) = (x \<in> FV (\<^bold>\<lambda>\<^bold>[t1\<^bold>] \<^bold>\<Zspot> t2)) [PROOF STEP] show "\<And>t u x. \<lbrakk>\<And>x. 0 < mtp x t \<longleftrightarrow> x \<in> FV t; \<And>x. 0 < mtp x u \<longleftrightarrow> x \<in> FV u\<rbrakk> \<Longrightarrow> 0 < mtp x (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u) \<longleftrightarrow> x \<in> FV (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>t u x. \<lbrakk>\<And>x. (0 < mtp x t) = (x \<in> FV t); \<And>x. (0 < mtp x u) = (x \<in> FV u)\<rbrakk> \<Longrightarrow> (0 < mtp x (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u)) = (x \<in> FV (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u)) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>t u x. \<lbrakk>\<And>x. (0 < mtp x t) = (x \<in> FV t); \<And>x. (0 < mtp x u) = (x \<in> FV u)\<rbrakk> \<Longrightarrow> (0 < mtp x (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u)) = (x \<in> FV (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u)) [PROOF STEP] fix t u and x :: nat [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>t u x. \<lbrakk>\<And>x. (0 < mtp x t) = (x \<in> FV t); \<And>x. (0 < mtp x u) = (x \<in> FV u)\<rbrakk> \<Longrightarrow> (0 < mtp x (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u)) = (x \<in> FV (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u)) [PROOF STEP] assume ind1: "\<And>x. 0 < mtp x t \<longleftrightarrow> x \<in> FV t" [PROOF STATE] proof (state) this: (0 < mtp ?x t) = (?x \<in> FV t) goal (1 subgoal): 1. \<And>t u x. \<lbrakk>\<And>x. (0 < mtp x t) = (x \<in> FV t); \<And>x. (0 < mtp x u) = (x \<in> FV u)\<rbrakk> \<Longrightarrow> (0 < mtp x (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u)) = (x \<in> FV (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u)) [PROOF STEP] assume ind2: "\<And>x. 0 < mtp x u \<longleftrightarrow> x \<in> FV u" [PROOF STATE] proof (state) this: (0 < mtp ?x u) = (?x \<in> FV u) goal (1 subgoal): 1. \<And>t u x. \<lbrakk>\<And>x. (0 < mtp x t) = (x \<in> FV t); \<And>x. (0 < mtp x u) = (x \<in> FV u)\<rbrakk> \<Longrightarrow> (0 < mtp x (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u)) = (x \<in> FV (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u)) [PROOF STEP] show "0 < mtp x (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u) \<longleftrightarrow> x \<in> FV (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (0 < mtp x (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u)) = (x \<in> FV (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u)) [PROOF STEP] using ind1 ind2 [PROOF STATE] proof (prove) using this: (0 < mtp ?x t) = (?x \<in> FV t) (0 < mtp ?x u) = (?x \<in> FV u) goal (1 subgoal): 1. (0 < mtp x (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u)) = (x \<in> FV (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u)) [PROOF STEP] apply simp [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>\<And>x. (0 < mtp x t) = (x \<in> FV t); \<And>x. (0 < mtp x u) = (x \<in> FV u)\<rbrakk> \<Longrightarrow> (Suc x \<in> FV t \<or> x \<in> FV u \<and> 0 < max (Suc 0) (mtp 0 t)) = (x \<in> (\<lambda>x. x - Suc 0) ` (FV t - {0}) \<or> x \<in> FV u) [PROOF STEP] by force [PROOF STATE] proof (state) this: (0 < mtp x (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u)) = (x \<in> FV (\<^bold>\<lambda>\<^bold>[t\<^bold>] \<^bold>\<Zspot> u)) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: \<lbrakk>\<And>x. (0 < mtp x ?t) = (x \<in> FV ?t); \<And>x. (0 < mtp x ?u) = (x \<in> FV ?u)\<rbrakk> \<Longrightarrow> (0 < mtp ?x (\<^bold>\<lambda>\<^bold>[?t\<^bold>] \<^bold>\<Zspot> ?u)) = (?x \<in> FV (\<^bold>\<lambda>\<^bold>[?t\<^bold>] \<^bold>\<Zspot> ?u)) goal: No subgoals! [PROOF STEP] qed
Today officially started treatment. 5 days of chemo, then 3 weeks off. This was the first day and there was a lot of information to digest. Met with doctor, nurse coordinator, they even did a personal Power Point presentation! The actual chemo drug is Decitabine and it is administered via IV. It only takes an hour. However, two out of the 5 days I have lab work first so they can check my blood counts and determine if I need blood or platelet infusion. Today, only a platelet infusion. It was about the same level as last week, which is good. It means my counts had stabilized and even gone up a bit. How about those Cardinals? I was able to watch game during treatment. Interesting watching what other people do during treatment. Some type away on their laptops, others chit-chat, a lot just lay back and take a nap. With doctor and nurse visits, I didn’t really have much time to do anything else this day. Missing you but you’re in good hands. Your blog is definitely one of high social substance. It will make a great digest for others who are also in this battle and to those who need their awareness raised. You are a diamond in the rough, to say the least. What was the last thing I said to you…remember?? “Take care”. Ok, you’ve been properly chastised, now the treatment begins. The medicos will be doing their thing, and I’ll be doing a little healing treatment too! I’ve got plenty of prayer time available for you, and I know a real good one JUST for you. Laughter is the best medicine! I’m not the short-sheet-the-bed or bed-pan-in-the-freezer type…but I have been known to do surprise underwear checks, so beware! Love is a universal healing agent, and should be applied liberally to the effected areas. I’ll be sending you waves of love, deep from my heart, as you go through this. If you need anything, your neighborhood buddies here will be happy to pitch in! You are such a positive guy, it will go a long way in getting you through this very quickly. Thanks…my neighbors have been very helpful already. One is cutting my grass for me now. Wonderful to hear the first round went great. Stay positive which I’m sure you will. I wouldn’t expect differently. Keeping you in my thoughts and prayers! We’ll definitely need a wing celebration when your done with all this!
theory L_Transform imports Validity Bisimilarity_Implies_Equivalence FL_Equivalence_Implies_Bisimilarity begin section \<open>\texorpdfstring{$L$}{L}-Transform\<close> subsection \<open>States\<close> text \<open>The intuition is that states of kind~\<open>AC\<close> can perform ordinary actions, and states of kind~\<open>EF\<close> can commit effects.\<close> datatype ('state,'effect) L_state = AC "'effect \<times> 'effect fs_set \<times> 'state" | EF "'effect fs_set \<times> 'state" instantiation L_state :: (pt,pt) pt begin fun permute_L_state :: "perm \<Rightarrow> ('a,'b) L_state \<Rightarrow> ('a,'b) L_state" where "p \<bullet> (AC x) = AC (p \<bullet> x)" | "p \<bullet> (EF x) = EF (p \<bullet> x)" instance proof fix x :: "('a,'b) L_state" show "0 \<bullet> x = x" by (cases x, simp_all) next fix p q and x :: "('a,'b) L_state" show "(p + q) \<bullet> x = p \<bullet> q \<bullet> x" by (cases x, simp_all) qed end declare permute_L_state.simps [eqvt] lemma supp_AC [simp]: "supp (AC x) = supp x" unfolding supp_def by simp lemma supp_EF [simp]: "supp (EF x) = supp x" unfolding supp_def by simp instantiation L_state :: (fs,fs) fs begin instance proof fix x :: "('a,'b) L_state" show "finite (supp x)" by (cases x) (simp add: finite_supp)+ qed end subsection \<open>Actions and binding names\<close> datatype ('act,'effect) L_action = Act 'act | Eff 'effect instantiation L_action :: (pt,pt) pt begin fun permute_L_action :: "perm \<Rightarrow> ('a,'b) L_action \<Rightarrow> ('a,'b) L_action" where "p \<bullet> (Act \<alpha>) = Act (p \<bullet> \<alpha>)" | "p \<bullet> (Eff f) = Eff (p \<bullet> f)" instance proof fix x :: "('a,'b) L_action" show "0 \<bullet> x = x" by (cases x, simp_all) next fix p q and x :: "('a,'b) L_action" show "(p + q) \<bullet> x = p \<bullet> q \<bullet> x" by (cases x, simp_all) qed end declare permute_L_action.simps [eqvt] lemma supp_Act [simp]: "supp (Act \<alpha>) = supp \<alpha>" unfolding supp_def by simp lemma supp_Eff [simp]: "supp (Eff f) = supp f" unfolding supp_def by simp instantiation L_action :: (fs,fs) fs begin instance proof fix x :: "('a,'b) L_action" show "finite (supp x)" by (cases x) (simp add: finite_supp)+ qed end instantiation L_action :: (bn,fs) bn begin fun bn_L_action :: "('a,'b) L_action \<Rightarrow> atom set" where "bn_L_action (Act \<alpha>) = bn \<alpha>" | "bn_L_action (Eff _) = {}" instance proof fix p and \<alpha> :: "('a,'b) L_action" show "p \<bullet> bn \<alpha> = bn (p \<bullet> \<alpha>)" by (cases \<alpha>) (simp add: bn_eqvt, simp) next fix \<alpha> :: "('a,'b) L_action" show "finite (bn \<alpha>)" by (cases \<alpha>) (simp add: bn_finite, simp) qed end subsection \<open>Satisfaction\<close> context effect_nominal_ts begin fun L_satisfies :: "('state,'effect) L_state \<Rightarrow> 'pred \<Rightarrow> bool" (infix "\<turnstile>\<^sub>L" 70) where "AC (_,_,P) \<turnstile>\<^sub>L \<phi> \<longleftrightarrow> P \<turnstile> \<phi>" | "EF _ \<turnstile>\<^sub>L \<phi> \<longleftrightarrow> False" lemma L_satisfies_eqvt: assumes "P\<^sub>L \<turnstile>\<^sub>L \<phi>" shows "(p \<bullet> P\<^sub>L) \<turnstile>\<^sub>L (p \<bullet> \<phi>)" proof (cases P\<^sub>L) case (AC fFP) with assms have "snd (snd fFP) \<turnstile> \<phi>" by (metis L_satisfies.simps(1) prod.collapse) then have "snd (snd (p \<bullet> fFP)) \<turnstile> p \<bullet> \<phi>" by (metis satisfies_eqvt snd_eqvt) then show ?thesis using AC by (metis L_satisfies.simps(1) permute_L_state.simps(1) prod.collapse) next case EF with assms have "False" by simp then show ?thesis .. qed end subsection \<open>Transitions\<close> context effect_nominal_ts begin fun L_transition :: "('state,'effect) L_state \<Rightarrow> (('act,'effect) L_action, ('state,'effect) L_state) residual \<Rightarrow> bool" (infix "\<rightarrow>\<^sub>L" 70) where "AC (f,F,P) \<rightarrow>\<^sub>L \<alpha>P' \<longleftrightarrow> (\<exists>\<alpha> P'. P \<rightarrow> \<langle>\<alpha>,P'\<rangle> \<and> \<alpha>P' = \<langle>Act \<alpha>, EF (L (\<alpha>,F,f), P')\<rangle> \<and> bn \<alpha> \<sharp>* (F,f))" \<comment> \<open>note the freshness condition\<close> | "EF (F,P) \<rightarrow>\<^sub>L \<alpha>P' \<longleftrightarrow> (\<exists>f. f \<in>\<^sub>f\<^sub>s F \<and> \<alpha>P' = \<langle>Eff f, AC (f, F, \<langle>f\<rangle>P)\<rangle>)" lemma L_transition_eqvt: assumes "P\<^sub>L \<rightarrow>\<^sub>L \<alpha>\<^sub>LP\<^sub>L'" shows "(p \<bullet> P\<^sub>L) \<rightarrow>\<^sub>L (p \<bullet> \<alpha>\<^sub>LP\<^sub>L')" proof (cases P\<^sub>L) case AC { fix f F P assume *: "P\<^sub>L = AC (f,F,P)" with assms obtain \<alpha> P' where trans: "P \<rightarrow> \<langle>\<alpha>,P'\<rangle>" and \<alpha>P': "\<alpha>\<^sub>LP\<^sub>L' = \<langle>Act \<alpha>, EF (L (\<alpha>,F,f), P')\<rangle>" and fresh: "bn \<alpha> \<sharp>* (F,f)" by auto from trans have "p \<bullet> P \<rightarrow> \<langle>p \<bullet> \<alpha>, p \<bullet> P'\<rangle>" by (simp add: transition_eqvt') moreover from \<alpha>P' have "p \<bullet> \<alpha>\<^sub>LP\<^sub>L' = \<langle>Act (p \<bullet> \<alpha>), EF (L (p \<bullet> \<alpha>, p \<bullet> F, p \<bullet> f), p \<bullet> P')\<rangle>" by (simp add: L_eqvt') moreover from fresh have "bn (p \<bullet> \<alpha>) \<sharp>* (p \<bullet> F, p \<bullet> f)" by (metis bn_eqvt fresh_star_Pair fresh_star_permute_iff) ultimately have "p \<bullet> P\<^sub>L \<rightarrow>\<^sub>L p \<bullet> \<alpha>\<^sub>LP\<^sub>L'" using "*" by auto } with AC show ?thesis by (metis prod.collapse) next case EF { fix F P assume *: "P\<^sub>L = EF (F,P)" with assms obtain f where "f \<in>\<^sub>f\<^sub>s F" and "\<alpha>\<^sub>LP\<^sub>L' = \<langle>Eff f, AC (f, F, \<langle>f\<rangle>P)\<rangle>" by auto then have "(p \<bullet> f) \<in>\<^sub>f\<^sub>s (p \<bullet> F)" and "p \<bullet> \<alpha>\<^sub>LP\<^sub>L' = \<langle>Eff (p \<bullet> f), AC (p \<bullet> f, p \<bullet> F, \<langle>p \<bullet> f\<rangle>(p \<bullet> P))\<rangle>" by simp+ then have "p \<bullet> P\<^sub>L \<rightarrow>\<^sub>L p \<bullet> \<alpha>\<^sub>LP\<^sub>L'" using "*" L_transition.simps(2) Pair_eqvt permute_L_state.simps(2) by force } with EF show ?thesis by (metis prod.collapse) qed text \<open>The binding names in the alpha-variant that witnesses the $L$-transition may be chosen fresh for any finitely supported context.\<close> lemma L_transition_AC_strong: assumes "finite (supp X)" and "AC (f,F,P) \<rightarrow>\<^sub>L \<langle>\<alpha>\<^sub>L,P\<^sub>L'\<rangle>" shows "\<exists>\<alpha> P'. P \<rightarrow> \<langle>\<alpha>,P'\<rangle> \<and> \<langle>\<alpha>\<^sub>L,P\<^sub>L'\<rangle> = \<langle>Act \<alpha>, EF (L (\<alpha>,F,f), P')\<rangle> \<and> bn \<alpha> \<sharp>* X" using assms proof - from \<open>AC (f,F,P) \<rightarrow>\<^sub>L \<langle>\<alpha>\<^sub>L,P\<^sub>L'\<rangle>\<close> obtain \<alpha> P' where transition: "P \<rightarrow> \<langle>\<alpha>,P'\<rangle>" and alpha: "\<langle>\<alpha>\<^sub>L,P\<^sub>L'\<rangle> = \<langle>Act \<alpha>, EF (L (\<alpha>,F,f), P')\<rangle>" and fresh: "bn \<alpha> \<sharp>* (F,f)" by (metis L_transition.simps(1)) let ?Act = "Act \<alpha> :: ('act,'effect) L_action" \<comment> \<open>the type annotation prevents a type that is too polymorphic and doesn't fix~@{typ 'effect}\<close> have "finite (bn \<alpha>)" by (fact bn_finite) moreover note \<open>finite (supp X)\<close> moreover have "finite (supp (\<langle>?Act, EF (L (\<alpha>,F,f), P')\<rangle>, \<langle>\<alpha>,P'\<rangle>, F, f))" by (metis finite_Diff finite_UnI finite_supp supp_Pair supp_abs_residual_pair) moreover from fresh have "bn \<alpha> \<sharp>* (\<langle>?Act, EF (L (\<alpha>,F,f), P')\<rangle>, \<langle>\<alpha>,P'\<rangle>, F, f)" by (auto simp add: fresh_star_def fresh_def supp_Pair supp_abs_residual_pair) ultimately obtain p where fresh_X: "(p \<bullet> bn \<alpha>) \<sharp>* X" and "supp (\<langle>?Act, EF (L (\<alpha>,F,f), P')\<rangle>, \<langle>\<alpha>,P'\<rangle>, F, f) \<sharp>* p" by (metis at_set_avoiding2) then have "supp \<langle>?Act, EF (L (\<alpha>,F,f), P')\<rangle> \<sharp>* p" and "supp \<langle>\<alpha>,P'\<rangle> \<sharp>* p" and "supp (F,f) \<sharp>* p" by (metis fresh_star_Un supp_Pair)+ then have "p \<bullet> \<langle>?Act, EF (L (\<alpha>,F,f), P')\<rangle> = \<langle>?Act, EF (L (\<alpha>,F,f), P')\<rangle>" and "p \<bullet> \<langle>\<alpha>,P'\<rangle> = \<langle>\<alpha>,P'\<rangle>" and "p \<bullet> (F,f) = (F,f)" by (metis supp_perm_eq)+ then have "\<langle>Act (p \<bullet> \<alpha>), EF (L (p \<bullet> \<alpha>, F, f), p \<bullet> P')\<rangle> = \<langle>?Act, EF (L (\<alpha>,F,f), P')\<rangle>" and "\<langle>p \<bullet> \<alpha>, p \<bullet> P'\<rangle> = \<langle>\<alpha>,P'\<rangle>" using permute_L_action.simps(1) permute_L_state.simps(2) abs_residual_pair_eqvt L_eqvt' Pair_eqvt by auto then show "\<exists>\<alpha> P'. P \<rightarrow> \<langle>\<alpha>,P'\<rangle> \<and> \<langle>\<alpha>\<^sub>L,P\<^sub>L'\<rangle> = \<langle>Act \<alpha>, EF (L (\<alpha>,F,f), P')\<rangle> \<and> bn \<alpha> \<sharp>* X" using transition and alpha and fresh_X by (metis bn_eqvt) qed (* bn \<alpha> \<sharp>* (F,f) is required for the \<longleftarrow> implication as well as for the \<longrightarrow> implication; additionally bn \<alpha> \<sharp>* P is required for the \<longrightarrow> implication. *) lemma L_transition_AC_fresh: assumes "bn \<alpha> \<sharp>* (F,f,P)" shows "AC (f,F,P) \<rightarrow>\<^sub>L \<langle>Act \<alpha>, P\<^sub>L'\<rangle> \<longleftrightarrow> (\<exists>P'. P\<^sub>L' = EF (L (\<alpha>,F,f), P') \<and> P \<rightarrow> \<langle>\<alpha>,P'\<rangle>)" proof assume "AC (f,F,P) \<rightarrow>\<^sub>L \<langle>Act \<alpha>, P\<^sub>L'\<rangle>" moreover have "finite (supp (F,f,P))" by (fact finite_supp) ultimately obtain \<alpha>' P' where trans: "P \<rightarrow> \<langle>\<alpha>',P'\<rangle>" and eq: "\<langle>Act \<alpha> :: ('act,'effect) L_action, P\<^sub>L'\<rangle> = \<langle>Act \<alpha>', EF (L (\<alpha>',F,f), P')\<rangle>" and fresh: "bn \<alpha>' \<sharp>* (F,f,P)" using L_transition_AC_strong by blast from eq obtain p where p: "p \<bullet> (Act \<alpha> :: ('act,'effect) L_action, P\<^sub>L') = (Act \<alpha>', EF (L (\<alpha>',F,f), P'))" and supp_p: "supp p \<subseteq> bn (Act \<alpha> :: ('act,'effect) L_action) \<union> p \<bullet> bn (Act \<alpha> :: ('act,'effect) L_action)" using residual_eq_iff_perm_renaming by metis from p have p_\<alpha>: "p \<bullet> \<alpha> = \<alpha>'" and p_P\<^sub>L': "p \<bullet> P\<^sub>L' = EF (L (\<alpha>',F,f), P')" by simp_all from supp_p and p_\<alpha> and assms and fresh have "supp p \<sharp>* (F, f, P)" by (simp add: bn_eqvt fresh_star_def) blast then have p_F: "p \<bullet> F = F" and p_f: "p \<bullet> f = f" and p_P: "p \<bullet> P = P" by (simp_all add: fresh_star_Pair perm_supp_eq) from p_P\<^sub>L' have "P\<^sub>L' = -p \<bullet> EF (L (\<alpha>',F,f), P')" by (metis permute_minus_cancel(2)) then have "P\<^sub>L' = EF (L (\<alpha>,F,f), -p \<bullet> P')" using p_\<alpha> p_F p_f by simp (metis (full_types) permute_minus_cancel(2)) moreover from trans have "P \<rightarrow> \<langle>\<alpha>, -p \<bullet> P'\<rangle>" using p_P and p_\<alpha> by (metis permute_minus_cancel(2) transition_eqvt') ultimately show "\<exists>P'. P\<^sub>L' = EF (L (\<alpha>,F,f), P') \<and> P \<rightarrow> \<langle>\<alpha>,P'\<rangle>" by blast next assume "\<exists>P'. P\<^sub>L' = EF (L (\<alpha>,F,f), P') \<and> P \<rightarrow> \<langle>\<alpha>,P'\<rangle>" moreover from assms have "bn \<alpha> \<sharp>* (F,f)" by (simp add: fresh_star_Pair) ultimately show "AC (f, F, P) \<rightarrow>\<^sub>L \<langle>Act \<alpha>, P\<^sub>L'\<rangle>" using L_transition.simps(1) by blast qed end subsection \<open>Translation of \texorpdfstring{$F/L$}{F/L}-formulas into formulas without effects\<close> text \<open>Since we defined formulas via a manual quotient construction, we also need to define the $L$-transform via lifting from the underlying type of infinitely branching trees. As before, we cannot use {\bf nominal\_function} because that generates proof obligations where, for formulas of the form~@{term "Conj xset"}, the assumption that~@{term xset} has finite support is missing.\<close> text \<open>The following auxiliary function returns trees (modulo $\alpha$-equivalence) rather than formulas. This allows us to prove equivariance for \emph{all} argument trees, without an assumption that they are (hereditarily) finitely supported. Further below--after this auxiliary function has been lifted to $F/L$-formulas as arguments--we derive a version that returns formulas.\<close> primrec L_transform_Tree :: "('idx,'pred::fs,'act::bn,'eff::fs) Tree \<Rightarrow> ('idx, 'pred, ('act,'eff) L_action) Formula.Tree\<^sub>\<alpha>" where "L_transform_Tree (tConj tset) = Formula.Conj\<^sub>\<alpha> (map_bset L_transform_Tree tset)" | "L_transform_Tree (tNot t) = Formula.Not\<^sub>\<alpha> (L_transform_Tree t)" | "L_transform_Tree (tPred f \<phi>) = Formula.Act\<^sub>\<alpha> (Eff f) (Formula.Pred\<^sub>\<alpha> \<phi>)" | "L_transform_Tree (tAct f \<alpha> t) = Formula.Act\<^sub>\<alpha> (Eff f) (Formula.Act\<^sub>\<alpha> (Act \<alpha>) (L_transform_Tree t))" lemma L_transform_Tree_eqvt [eqvt]: "p \<bullet> L_transform_Tree t = L_transform_Tree (p \<bullet> t)" proof (induct t) case (tConj tset) then show ?case by simp (metis (no_types, hide_lams) bset.map_cong0 map_bset_eqvt permute_fun_def permute_minus_cancel(1)) qed simp_all text \<open>@{const L_transform_Tree} respects $\alpha$-equivalence.\<close> lemma alpha_Tree_L_transform_Tree: assumes "alpha_Tree t1 t2" shows "L_transform_Tree t1 = L_transform_Tree t2" using assms proof (induction t1 t2 rule: alpha_Tree_induct') case (alpha_tConj tset1 tset2) then have "rel_bset (=) (map_bset L_transform_Tree tset1) (map_bset L_transform_Tree tset2)" by (simp add: bset.rel_map(1) bset.rel_map(2) bset.rel_mono_strong) then show ?case by (simp add: bset.rel_eq) next case (alpha_tAct f1 \<alpha>1 t1 f2 \<alpha>2 t2) from \<open>alpha_Tree (FL_Formula.Tree.tAct f1 \<alpha>1 t1) (FL_Formula.Tree.tAct f2 \<alpha>2 t2)\<close> obtain p where *: "(bn \<alpha>1, t1) \<approx>set alpha_Tree (supp_rel alpha_Tree) p (bn \<alpha>2, t2)" and **: "(bn \<alpha>1, \<alpha>1) \<approx>set (=) supp p (bn \<alpha>2, \<alpha>2)" and "f1 = f2" by auto from * have fresh: "(supp_rel alpha_Tree t1 - bn \<alpha>1) \<sharp>* p" and alpha: "alpha_Tree (p \<bullet> t1) t2" and eq: "p \<bullet> bn \<alpha>1 = bn \<alpha>2" by (auto simp add: alpha_set) from alpha_tAct.IH(2) have "supp_rel Formula.alpha_Tree (Formula.rep_Tree\<^sub>\<alpha> (L_transform_Tree t1)) \<subseteq> supp_rel alpha_Tree t1" by (metis (no_types, lifting) infinite_mono Formula.alpha_Tree_permute_rep_commute L_transform_Tree_eqvt mem_Collect_eq subsetI supp_rel_def) with fresh have fresh': "(supp_rel Formula.alpha_Tree (Formula.rep_Tree\<^sub>\<alpha> (L_transform_Tree t1)) - bn \<alpha>1) \<sharp>* p" by (meson DiffD1 DiffD2 DiffI fresh_star_def subsetCE) moreover from alpha have alpha': "Formula.alpha_Tree (p \<bullet> Formula.rep_Tree\<^sub>\<alpha> (L_transform_Tree t1)) (Formula.rep_Tree\<^sub>\<alpha> (L_transform_Tree t2))" using alpha_tAct.IH(1) by (metis Formula.alpha_Tree_permute_rep_commute L_transform_Tree_eqvt) moreover from fresh' alpha' eq have "supp_rel Formula.alpha_Tree (Formula.rep_Tree\<^sub>\<alpha> (L_transform_Tree t1)) - bn \<alpha>1 = supp_rel Formula.alpha_Tree (Formula.rep_Tree\<^sub>\<alpha> (L_transform_Tree t2)) - bn \<alpha>2" by (metis (mono_tags) Diff_eqvt Formula.alpha_Tree_eqvt' Formula.alpha_Tree_eqvt_aux Formula.alpha_Tree_supp_rel atom_set_perm_eq) ultimately have "(bn \<alpha>1, Formula.rep_Tree\<^sub>\<alpha> (L_transform_Tree t1)) \<approx>set Formula.alpha_Tree (supp_rel Formula.alpha_Tree) p (bn \<alpha>2, Formula.rep_Tree\<^sub>\<alpha> (L_transform_Tree t2))" using eq by (simp add: alpha_set) moreover from ** have "(bn \<alpha>1, Act \<alpha>1) \<approx>set (=) supp p (bn \<alpha>2, Act \<alpha>2)" by (metis (mono_tags, lifting) L_Transform.supp_Act alpha_set permute_L_action.simps(1)) ultimately have "Formula.Act\<^sub>\<alpha> (Act \<alpha>1) (L_transform_Tree t1) = Formula.Act\<^sub>\<alpha> (Act \<alpha>2) (L_transform_Tree t2)" by (auto simp add: Formula.Act\<^sub>\<alpha>_eq_iff) with \<open>f1 = f2\<close> show ?case by simp qed simp_all text \<open>$L$-transform for trees modulo $\alpha$-equivalence.\<close> lift_definition L_transform_Tree\<^sub>\<alpha> :: "('idx,'pred::fs,'act::bn,'eff::fs) Tree\<^sub>\<alpha> \<Rightarrow> ('idx, 'pred, ('act,'eff) L_action) Formula.Tree\<^sub>\<alpha>" is L_transform_Tree by (fact alpha_Tree_L_transform_Tree) lemma L_transform_Tree\<^sub>\<alpha>_eqvt [eqvt]: "p \<bullet> L_transform_Tree\<^sub>\<alpha> t\<^sub>\<alpha> = L_transform_Tree\<^sub>\<alpha> (p \<bullet> t\<^sub>\<alpha>)" by transfer (simp) lemma L_transform_Tree\<^sub>\<alpha>_Conj\<^sub>\<alpha> [simp]: "L_transform_Tree\<^sub>\<alpha> (Conj\<^sub>\<alpha> tset\<^sub>\<alpha>) = Formula.Conj\<^sub>\<alpha> (map_bset L_transform_Tree\<^sub>\<alpha> tset\<^sub>\<alpha>)" by (simp add: Conj\<^sub>\<alpha>_def' L_transform_Tree\<^sub>\<alpha>.abs_eq) (metis (no_types, lifting) L_transform_Tree\<^sub>\<alpha>.rep_eq bset.map_comp bset.map_cong0 comp_apply) lemma L_transform_Tree\<^sub>\<alpha>_Not\<^sub>\<alpha> [simp]: "L_transform_Tree\<^sub>\<alpha> (Not\<^sub>\<alpha> t\<^sub>\<alpha>) = Formula.Not\<^sub>\<alpha> (L_transform_Tree\<^sub>\<alpha> t\<^sub>\<alpha>)" by transfer simp lemma L_transform_Tree\<^sub>\<alpha>_Pred\<^sub>\<alpha> [simp]: "L_transform_Tree\<^sub>\<alpha> (Pred\<^sub>\<alpha> f \<phi>) = Formula.Act\<^sub>\<alpha> (Eff f) (Formula.Pred\<^sub>\<alpha> \<phi>)" by transfer simp lemma L_transform_Tree\<^sub>\<alpha>_Act\<^sub>\<alpha> [simp]: "L_transform_Tree\<^sub>\<alpha> (Act\<^sub>\<alpha> f \<alpha> t\<^sub>\<alpha>) = Formula.Act\<^sub>\<alpha> (Eff f) (Formula.Act\<^sub>\<alpha> (Act \<alpha>) (L_transform_Tree\<^sub>\<alpha> t\<^sub>\<alpha>))" by transfer simp lemma finite_supp_map_bset_L_transform_Tree\<^sub>\<alpha> [simp]: assumes "finite (supp tset\<^sub>\<alpha>)" shows "finite (supp (map_bset L_transform_Tree\<^sub>\<alpha> tset\<^sub>\<alpha>))" proof - have "eqvt map_bset" and "eqvt L_transform_Tree\<^sub>\<alpha>" by (simp add: eqvtI)+ then have "supp (map_bset L_transform_Tree\<^sub>\<alpha>) = {}" using supp_fun_eqvt supp_fun_app_eqvt by blast then have "supp (map_bset L_transform_Tree\<^sub>\<alpha> tset\<^sub>\<alpha>) \<subseteq> supp tset\<^sub>\<alpha>" using supp_fun_app by blast with assms show "finite (supp (map_bset L_transform_Tree\<^sub>\<alpha> tset\<^sub>\<alpha>))" by (metis finite_subset) qed lemma L_transform_Tree\<^sub>\<alpha>_preserves_hereditarily_fs: assumes "hereditarily_fs t\<^sub>\<alpha>" shows "Formula.hereditarily_fs (L_transform_Tree\<^sub>\<alpha> t\<^sub>\<alpha>)" using assms proof (induct rule: hereditarily_fs.induct) case (Conj\<^sub>\<alpha> tset\<^sub>\<alpha>) then show ?case by (auto intro!: Formula.hereditarily_fs.Conj\<^sub>\<alpha>) (metis imageE map_bset.rep_eq) next case (Not\<^sub>\<alpha> t\<^sub>\<alpha>) then show ?case by (simp add: Formula.hereditarily_fs.Not\<^sub>\<alpha>) next case (Pred\<^sub>\<alpha> f \<phi>) then show ?case by (simp add: Formula.hereditarily_fs.Act\<^sub>\<alpha> Formula.hereditarily_fs.Pred\<^sub>\<alpha>) next case (Act\<^sub>\<alpha> t\<^sub>\<alpha> f \<alpha>) then show ?case by (simp add: Formula.hereditarily_fs.Act\<^sub>\<alpha>) qed text \<open>$L$-transform for $F/L$-formulas.\<close> lift_definition L_transform_formula :: "('idx,'pred::fs,'act::bn,'eff::fs) formula \<Rightarrow> ('idx, 'pred, ('act,'eff) L_action) Formula.Tree\<^sub>\<alpha>" is L_transform_Tree\<^sub>\<alpha> . lemma L_transform_formula_eqvt [eqvt]: "p \<bullet> L_transform_formula x = L_transform_formula (p \<bullet> x)" by transfer (simp) lemma L_transform_formula_Conj [simp]: assumes "finite (supp xset)" shows "L_transform_formula (Conj xset) = Formula.Conj\<^sub>\<alpha> (map_bset L_transform_formula xset)" using assms by (simp add: Conj_def L_transform_formula_def bset.map_comp map_fun_def) lemma L_transform_formula_Not [simp]: "L_transform_formula (Not x) = Formula.Not\<^sub>\<alpha> (L_transform_formula x)" by transfer simp lemma L_transform_formula_Pred [simp]: "L_transform_formula (Pred f \<phi>) = Formula.Act\<^sub>\<alpha> (Eff f) (Formula.Pred\<^sub>\<alpha> \<phi>)" by transfer simp lemma L_transform_formula_Act [simp]: "L_transform_formula (FL_Formula.Act f \<alpha> x) = Formula.Act\<^sub>\<alpha> (Eff f) (Formula.Act\<^sub>\<alpha> (Act \<alpha>) (L_transform_formula x))" by transfer simp lemma L_transform_formula_hereditarily_fs [simp]: "Formula.hereditarily_fs (L_transform_formula x)" by transfer (fact L_transform_Tree\<^sub>\<alpha>_preserves_hereditarily_fs) text \<open>Finally, we define the proper $L$-transform, which returns formulas instead of trees.\<close> definition L_transform :: "('idx,'pred::fs,'act::bn,'eff::fs) formula \<Rightarrow> ('idx, 'pred, ('act,'eff) L_action) Formula.formula" where "L_transform x = Formula.Abs_formula (L_transform_formula x)" lemma L_transform_eqvt [eqvt]: "p \<bullet> L_transform x = L_transform (p \<bullet> x)" unfolding L_transform_def by simp lemma finite_supp_map_bset_L_transform [simp]: assumes "finite (supp xset)" shows "finite (supp (map_bset L_transform xset))" proof - have "eqvt map_bset" and "eqvt L_transform" by (simp add: eqvtI)+ then have "supp (map_bset L_transform) = {}" using supp_fun_eqvt supp_fun_app_eqvt by blast then have "supp (map_bset L_transform xset) \<subseteq> supp xset" using supp_fun_app by blast with assms show "finite (supp (map_bset L_transform xset))" by (metis finite_subset) qed lemma L_transform_Conj [simp]: assumes "finite (supp xset)" shows "L_transform (Conj xset) = Formula.Conj (map_bset L_transform xset)" using assms unfolding L_transform_def by (simp add: Formula.Conj_def bset.map_comp o_def) lemma L_transform_Not [simp]: "L_transform (Not x) = Formula.Not (L_transform x)" unfolding L_transform_def by (simp add: Formula.Not_def) lemma L_transform_Pred [simp]: "L_transform (Pred f \<phi>) = Formula.Act (Eff f) (Formula.Pred \<phi>)" unfolding L_transform_def by (simp add: Formula.Act_def Formula.Pred_def Formula.hereditarily_fs.Pred\<^sub>\<alpha>) lemma L_transform_Act [simp]: "L_transform (FL_Formula.Act f \<alpha> x) = Formula.Act (Eff f) (Formula.Act (Act \<alpha>) (L_transform x))" unfolding L_transform_def by (simp add: Formula.Act_def Formula.hereditarily_fs.Act\<^sub>\<alpha>) context effect_nominal_ts begin interpretation L_transform: nominal_ts "(\<turnstile>\<^sub>L)" "(\<rightarrow>\<^sub>L)" by unfold_locales (fact L_satisfies_eqvt, fact L_transition_eqvt) text \<open>The $L$-transform preserves satisfaction of formulas in the following sense:\<close> theorem FL_valid_iff_valid_L_transform: assumes "(x::('idx,'pred,'act,'effect) formula) \<in> \<A>[F]" shows "FL_valid P x \<longleftrightarrow> L_transform.valid (EF (F, P)) (L_transform x)" using assms proof (induct x arbitrary: P) case (Conj xset F) then show ?case by auto (metis imageE map_bset.rep_eq, simp add: map_bset.rep_eq) next case (Not F x) then show ?case by simp next case (Pred f F \<phi>) let ?\<phi> = "Formula.Pred \<phi> :: ('idx, 'pred, ('act,'effect) L_action) Formula.formula" show ?case proof assume "FL_valid P (Pred f \<phi>)" then have "L_transform.valid (AC (f, F, \<langle>f\<rangle>P)) ?\<phi>" by (simp add: L_transform.valid_Act) moreover from \<open>f \<in>\<^sub>f\<^sub>s F\<close> have "EF (F, P) \<rightarrow>\<^sub>L \<langle>Eff f, AC (f, F, \<langle>f\<rangle>P)\<rangle>" by (metis L_transition.simps(2)) ultimately show "L_transform.valid (EF (F, P)) (L_transform (Pred f \<phi>))" using L_transform.valid_Act by fastforce next assume "L_transform.valid (EF (F, P)) (L_transform (Pred f \<phi>))" then obtain P' where trans: "EF (F, P) \<rightarrow>\<^sub>L \<langle>Eff f, P'\<rangle>" and valid: "L_transform.valid P' ?\<phi>" by simp (metis bn_L_action.simps(2) empty_iff fresh_star_def L_transform.valid_Act_fresh L_transform.valid_Pred L_transition.simps(2)) from trans have "P' = AC (f, F, \<langle>f\<rangle>P)" by (simp add: residual_empty_bn_eq_iff) with valid show "FL_valid P (Pred f \<phi>)" by simp qed next case (Act f F \<alpha> x) show ?case proof assume "FL_valid P (FL_Formula.Act f \<alpha> x)" then obtain \<alpha>' x' P' where eq: "FL_Formula.Act f \<alpha> x = FL_Formula.Act f \<alpha>' x'" and trans: "\<langle>f\<rangle>P \<rightarrow> \<langle>\<alpha>',P'\<rangle>" and valid: "FL_valid P' x'" and fresh: "bn \<alpha>' \<sharp>* (F, f)" by (metis FL_valid_Act_strong finite_supp) from eq obtain p where p_x: "p \<bullet> x = x'" and p_\<alpha>: "p \<bullet> \<alpha> = \<alpha>'" and supp_p: "supp p \<subseteq> bn \<alpha> \<union> bn \<alpha>'" by (metis bn_eqvt FL_Formula.Act_eq_iff_perm_renaming) from \<open>bn \<alpha> \<sharp>* (F, f)\<close> and fresh have "supp (F, f) \<sharp>* p" using supp_p by (auto simp add: fresh_star_Pair fresh_star_def supp_Pair fresh_def) then have "p \<bullet> F = F" and "p \<bullet> f = f" using supp_perm_eq by fastforce+ from valid have "FL_valid (-p \<bullet> P') x" using p_x by (metis FL_valid_eqvt permute_minus_cancel(2)) then have "L_transform.valid (EF (L (\<alpha>, F, f), -p \<bullet> P')) (L_transform x)" using Act.hyps(4) by metis then have "L_transform.valid (p \<bullet> EF (L (\<alpha>, F, f), -p \<bullet> P')) (p \<bullet> L_transform x)" by (fact L_transform.valid_eqvt) then have "L_transform.valid (EF (L (\<alpha>', F, f), P')) (L_transform x')" using p_x and p_\<alpha> and \<open>p \<bullet> F = F\<close> and \<open>p \<bullet> f = f\<close> by simp then have "L_transform.valid (AC (f, F, \<langle>f\<rangle>P)) (Formula.Act (Act \<alpha>') (L_transform x'))" using trans fresh L_transform.valid_Act by fastforce with \<open>f \<in>\<^sub>f\<^sub>s F\<close> and eq show "L_transform.valid (EF (F, P)) (L_transform (FL_Formula.Act f \<alpha> x))" using L_transform.valid_Act by fastforce next assume *: "L_transform.valid (EF (F, P)) (L_transform (FL_Formula.Act f \<alpha> x))" \<comment> \<open>rename~@{term "bn \<alpha>"} to avoid~@{term "(F, f, P)"}, without touching~@{term F} or~@{term "FL_Formula.Act f \<alpha> x"}\<close> obtain p where 1: "(p \<bullet> bn \<alpha>) \<sharp>* (F, f, P)" and 2: "supp (F, FL_Formula.Act f \<alpha> x) \<sharp>* p" proof (rule at_set_avoiding2[of "bn \<alpha>" "(F, f, P)" "(F, FL_Formula.Act f \<alpha> x)", THEN exE]) show "finite (bn \<alpha>)" by (fact bn_finite) next show "finite (supp (F, f, P))" by (fact finite_supp) next show "finite (supp (F, FL_Formula.Act f \<alpha> x))" by (simp add: finite_supp) next from \<open>bn \<alpha> \<sharp>* (F, f)\<close> show "bn \<alpha> \<sharp>* (F, FL_Formula.Act f \<alpha> x)" by (simp add: fresh_star_Pair fresh_star_def fresh_def supp_Pair) qed metis from 2 have "supp F \<sharp>* p" and Act_fresh: "supp (FL_Formula.Act f \<alpha> x) \<sharp>* p" by (simp add: fresh_star_Pair fresh_star_def supp_Pair)+ from \<open>supp F \<sharp>* p\<close> have "p \<bullet> F = F" by (metis supp_perm_eq) from Act_fresh have "p \<bullet> f = f" using fresh_star_Un supp_perm_eq by fastforce from Act_fresh have eq: "FL_Formula.Act f \<alpha> x = FL_Formula.Act f (p \<bullet> \<alpha>) (p \<bullet> x)" by (metis FL_Formula.Act_eq_iff_perm FL_Formula.Act_eqvt supp_perm_eq) with * obtain P' where trans: "EF (F, P) \<rightarrow>\<^sub>L \<langle>Eff f,P'\<rangle>" and valid: "L_transform.valid P' (Formula.Act (Act (p \<bullet> \<alpha>)) (L_transform (p \<bullet> x)))" using L_transform_Act by (metis L_transform.valid_Act_fresh bn_L_action.simps(2) empty_iff fresh_star_def) from trans have P': "P' = AC (f, F, \<langle>f\<rangle>P)" by (simp add: residual_empty_bn_eq_iff) have supp_f_P: "supp (\<langle>f\<rangle>P) \<subseteq> supp f \<union> supp P" using effect_apply_eqvt supp_fun_app supp_fun_app_eqvt by fastforce with 1 have "bn (Act (p \<bullet> \<alpha>)) \<sharp>* AC (f, F, \<langle>f\<rangle>P)" by (auto simp add: bn_eqvt fresh_star_def fresh_def supp_Pair) with valid obtain P'' where trans': "AC (f, F, \<langle>f\<rangle>P) \<rightarrow>\<^sub>L \<langle>Act (p \<bullet> \<alpha>),P''\<rangle>" and valid': "L_transform.valid P'' (L_transform (p \<bullet> x))" using P' by (metis L_transform.valid_Act_fresh) from supp_f_P and 1 have "bn (p \<bullet> \<alpha>) \<sharp>* (F, f, \<langle>f\<rangle>P)" by (auto simp add: bn_eqvt fresh_star_def fresh_def supp_Pair) with trans' obtain P' where P'': "P'' = EF (L (p \<bullet> \<alpha>, F, f), P')" and trans'': "\<langle>f\<rangle>P \<rightarrow> \<langle>p \<bullet> \<alpha>,P'\<rangle>" by (metis L_transition_AC_fresh) from valid' have "L_transform.valid (-p \<bullet> P'') (L_transform x)" by (metis (mono_tags) L_transform.valid_eqvt L_transform_eqvt permute_minus_cancel(2)) with P'' \<open>p \<bullet> F = F\<close> \<open>p \<bullet> f = f\<close> have "L_transform.valid (EF (L (\<alpha>, F, f), - p \<bullet> P')) (L_transform x)" by simp (metis pemute_minus_self permute_minus_cancel(1)) then have "FL_valid P' (p \<bullet> x)" using Act.hyps(4) by (metis FL_valid_eqvt permute_minus_cancel(1)) with trans'' and eq show "FL_valid P (FL_Formula.Act f \<alpha> x)" by (metis FL_valid_Act) qed qed end subsection \<open>Bisimilarity in the \texorpdfstring{$L$}{L}-transform\<close> context effect_nominal_ts begin (* Not quite sure why this is needed again? *) interpretation L_transform: nominal_ts "(\<turnstile>\<^sub>L)" "(\<rightarrow>\<^sub>L)" by unfold_locales (fact L_satisfies_eqvt, fact L_transition_eqvt) notation L_transform.bisimilar (infix "\<sim>\<cdot>\<^sub>L" 100) text \<open>$F/L$-bisimilarity is equivalent to bisimilarity in the $L$-transform.\<close> inductive L_bisimilar :: "('state,'effect) L_state \<Rightarrow> ('state,'effect) L_state \<Rightarrow> bool" where "P \<sim>\<cdot>[F] Q \<Longrightarrow> L_bisimilar (EF (F,P)) (EF (F,Q))" | "P \<sim>\<cdot>[F] Q \<Longrightarrow> f \<in>\<^sub>f\<^sub>s F \<Longrightarrow> L_bisimilar (AC (f, F, \<langle>f\<rangle>P)) (AC (f, F, \<langle>f\<rangle>Q))" lemma L_bisimilar_is_L_transform_bisimulation: "L_transform.is_bisimulation L_bisimilar" unfolding L_transform.is_bisimulation_def proof show "symp L_bisimilar" by (metis FL_bisimilar_symp L_bisimilar.cases L_bisimilar.intros symp_def) next have "\<forall>P\<^sub>L Q\<^sub>L. L_bisimilar P\<^sub>L Q\<^sub>L \<longrightarrow> (\<forall>\<phi>. P\<^sub>L \<turnstile>\<^sub>L \<phi> \<longrightarrow> Q\<^sub>L \<turnstile>\<^sub>L \<phi>)" (is ?S) using FL_bisimilar_is_L_bisimulation L_bisimilar.simps is_L_bisimulation_def by auto moreover have "\<forall>P\<^sub>L Q\<^sub>L. L_bisimilar P\<^sub>L Q\<^sub>L \<longrightarrow> (\<forall>\<alpha>\<^sub>L P\<^sub>L'. bn \<alpha>\<^sub>L \<sharp>* Q\<^sub>L \<longrightarrow> P\<^sub>L \<rightarrow>\<^sub>L \<langle>\<alpha>\<^sub>L,P\<^sub>L'\<rangle> \<longrightarrow> (\<exists>Q\<^sub>L'. Q\<^sub>L \<rightarrow>\<^sub>L \<langle>\<alpha>\<^sub>L,Q\<^sub>L'\<rangle> \<and> L_bisimilar P\<^sub>L' Q\<^sub>L'))" (is ?T) proof (clarify) fix P\<^sub>L Q\<^sub>L \<alpha>\<^sub>L P\<^sub>L' assume L_bisim: "L_bisimilar P\<^sub>L Q\<^sub>L" and fresh\<^sub>L: "bn \<alpha>\<^sub>L \<sharp>* Q\<^sub>L" and trans\<^sub>L: "P\<^sub>L \<rightarrow>\<^sub>L \<langle>\<alpha>\<^sub>L,P\<^sub>L'\<rangle>" obtain Q\<^sub>L' where "Q\<^sub>L \<rightarrow>\<^sub>L \<langle>\<alpha>\<^sub>L,Q\<^sub>L'\<rangle>" and "L_bisimilar P\<^sub>L' Q\<^sub>L'" using L_bisim proof (rule L_bisimilar.cases) fix P F Q assume P\<^sub>L: "P\<^sub>L = EF (F, P)" and Q\<^sub>L: "Q\<^sub>L = EF (F, Q)" and bisim: "P \<sim>\<cdot>[F] Q" from P\<^sub>L and trans\<^sub>L obtain f where effect: "f \<in>\<^sub>f\<^sub>s F" and \<alpha>\<^sub>LP\<^sub>L': "\<langle>\<alpha>\<^sub>L,P\<^sub>L'\<rangle> = \<langle>Eff f, AC (f, F, \<langle>f\<rangle>P)\<rangle>" using L_transition.simps(2) by blast from Q\<^sub>L and effect have "Q\<^sub>L \<rightarrow>\<^sub>L \<langle>Eff f, AC (f, F, \<langle>f\<rangle>Q)\<rangle>" using L_transition.simps(2) by blast moreover from bisim and effect have "L_bisimilar (AC (f, F, \<langle>f\<rangle>P)) (AC (f, F, \<langle>f\<rangle>Q))" using L_bisimilar.intros(2) by blast moreover from \<alpha>\<^sub>LP\<^sub>L' have "\<alpha>\<^sub>L = Eff f" and "P\<^sub>L' = AC (f, F, \<langle>f\<rangle>P)" by (metis bn_L_action.simps(2) residual_empty_bn_eq_iff)+ ultimately show "thesis" using \<open>\<And>Q\<^sub>L'. Q\<^sub>L \<rightarrow>\<^sub>L \<langle>\<alpha>\<^sub>L,Q\<^sub>L'\<rangle> \<Longrightarrow> L_bisimilar P\<^sub>L' Q\<^sub>L' \<Longrightarrow> thesis\<close> by blast next fix P F Q f assume P\<^sub>L: "P\<^sub>L = AC (f, F, \<langle>f\<rangle>P)" and Q\<^sub>L: "Q\<^sub>L = AC (f, F, \<langle>f\<rangle>Q)" and bisim: "P \<sim>\<cdot>[F] Q" and effect: "f \<in>\<^sub>f\<^sub>s F" have "finite (supp (\<langle>f\<rangle>Q, F, f))" by (fact finite_supp) with P\<^sub>L and trans\<^sub>L obtain \<alpha> P' where trans_P: "\<langle>f\<rangle>P \<rightarrow> \<langle>\<alpha>,P'\<rangle>" and \<alpha>\<^sub>LP\<^sub>L': "\<langle>\<alpha>\<^sub>L,P\<^sub>L'\<rangle> = \<langle>Act \<alpha>, EF (L (\<alpha>,F,f), P')\<rangle>" and fresh: "bn \<alpha> \<sharp>* (\<langle>f\<rangle>Q, F, f)" by (metis L_transition_AC_strong) from bisim and effect and fresh and trans_P obtain Q' where trans_Q: "\<langle>f\<rangle>Q \<rightarrow> \<langle>\<alpha>,Q'\<rangle>" and bisim': "P' \<sim>\<cdot>[L (\<alpha>,F,f)] Q'" by (metis FL_bisimilar_simulation_step) from fresh have "bn \<alpha> \<sharp>* (F, f)" by (meson fresh_PairD(2) fresh_star_def) with Q\<^sub>L and trans_Q have trans_Q\<^sub>L: "Q\<^sub>L \<rightarrow>\<^sub>L \<langle>Act \<alpha>, EF (L (\<alpha>,F,f), Q')\<rangle>" by (metis L_transition.simps(1)) from \<alpha>\<^sub>LP\<^sub>L' obtain p where p: "(\<alpha>\<^sub>L,P\<^sub>L') = p \<bullet> (Act \<alpha>, EF (L (\<alpha>,F,f), P'))" and supp_p: "supp p \<subseteq> bn \<alpha> \<union> bn \<alpha>\<^sub>L" by (metis (no_types, lifting) bn_L_action.simps(1) residual_eq_iff_perm_renaming) from supp_p and fresh and fresh\<^sub>L and Q\<^sub>L have "supp p \<sharp>* (\<langle>f\<rangle>Q, F, f)" unfolding fresh_star_def by (metis (no_types, hide_lams) Un_iff fresh_Pair fresh_def subsetCE supp_AC) then have p_fQ: "p \<bullet> \<langle>f\<rangle>Q = \<langle>f\<rangle>Q" and p_Ff: "p \<bullet> (F,f) = (F,f)" by (simp add: fresh_star_def perm_supp_eq)+ from p and p_Ff have "\<alpha>\<^sub>L = Act (p \<bullet> \<alpha>)" and "P\<^sub>L' = EF (L (p \<bullet> \<alpha>, F, f), p \<bullet> P')" by auto moreover from Q\<^sub>L and p_fQ and p_Ff have "p \<bullet> Q\<^sub>L = Q\<^sub>L" by simp with trans_Q\<^sub>L have "Q\<^sub>L \<rightarrow>\<^sub>L p \<bullet> \<langle>Act \<alpha>, EF (L (\<alpha>,F,f), Q')\<rangle>" by (metis L_transform.transition_eqvt) then have "Q\<^sub>L \<rightarrow>\<^sub>L \<langle>Act (p \<bullet> \<alpha>), EF (L (p \<bullet> \<alpha>, F, f), p \<bullet> Q')\<rangle>" using p_Ff by simp moreover from p_Ff have "p \<bullet> F = F" and "p \<bullet> f = f" by simp+ with bisim' have "(p \<bullet> P') \<sim>\<cdot>[L (p \<bullet> \<alpha>, F, f)] (p \<bullet> Q')" by (metis FL_bisimilar_eqvt L_eqvt') then have "L_bisimilar (EF (L (p \<bullet> \<alpha>, F, f), p \<bullet> P')) (EF (L (p \<bullet> \<alpha>, F, f), p \<bullet> Q'))" by (metis L_bisimilar.intros(1)) ultimately show thesis using \<open>\<And>Q\<^sub>L'. Q\<^sub>L \<rightarrow>\<^sub>L \<langle>\<alpha>\<^sub>L,Q\<^sub>L'\<rangle> \<Longrightarrow> L_bisimilar P\<^sub>L' Q\<^sub>L' \<Longrightarrow> thesis\<close> by blast qed then show "\<exists>Q\<^sub>L'. Q\<^sub>L \<rightarrow>\<^sub>L \<langle>\<alpha>\<^sub>L,Q\<^sub>L'\<rangle> \<and> L_bisimilar P\<^sub>L' Q\<^sub>L'" by auto qed ultimately show "?S \<and> ?T" by metis qed definition invL_FL_bisimilar :: "'effect first \<Rightarrow> 'state \<Rightarrow> 'state \<Rightarrow> bool" where "invL_FL_bisimilar F P Q \<equiv> EF (F,P) \<sim>\<cdot>\<^sub>L EF(F,Q)" lemma invL_FL_bisimilar_is_L_bisimulation: "is_L_bisimulation invL_FL_bisimilar" unfolding is_L_bisimulation_def proof fix F have "symp (invL_FL_bisimilar F)" (is ?R) by (metis L_transform.bisimilar_symp invL_FL_bisimilar_def symp_def) moreover have "\<forall>P Q. invL_FL_bisimilar F P Q \<longrightarrow> (\<forall>f. f \<in>\<^sub>f\<^sub>s F \<longrightarrow> (\<forall>\<phi>. \<langle>f\<rangle>P \<turnstile> \<phi> \<longrightarrow> \<langle>f\<rangle>Q \<turnstile> \<phi>))" (is ?S) proof (clarify) fix P Q f \<phi> assume bisim: "invL_FL_bisimilar F P Q" and effect: "f \<in>\<^sub>f\<^sub>s F" and satisfies: "\<langle>f\<rangle>P \<turnstile> \<phi>" from bisim have "EF (F,P) \<sim>\<cdot>\<^sub>L EF (F,Q)" by (metis invL_FL_bisimilar_def) moreover have "bn (Eff f) \<sharp>* EF (F,Q)" by (simp add: fresh_star_def) moreover from effect have "EF (F,P) \<rightarrow>\<^sub>L \<langle>Eff f, AC (f, F, \<langle>f\<rangle>P)\<rangle>" by (metis L_transition.simps(2)) ultimately obtain Q\<^sub>L' where trans: "EF (F,Q) \<rightarrow>\<^sub>L \<langle>Eff f, Q\<^sub>L'\<rangle>" and L_bisim: "AC (f, F, \<langle>f\<rangle>P) \<sim>\<cdot>\<^sub>L Q\<^sub>L'" by (metis L_transform.bisimilar_simulation_step) from trans obtain f' where "\<langle>Eff f :: ('act,'effect) L_action, Q\<^sub>L'\<rangle> = \<langle>Eff f', AC (f', F, \<langle>f'\<rangle>Q)\<rangle>" by (metis L_transition.simps(2)) then have Q\<^sub>L': "Q\<^sub>L' = AC (f, F, \<langle>f\<rangle>Q)" by (metis L_action.inject(2) bn_L_action.simps(2) residual_empty_bn_eq_iff) from satisfies have "AC (f, F, \<langle>f\<rangle>P) \<turnstile>\<^sub>L \<phi>" by (metis L_satisfies.simps(1)) with L_bisim and Q\<^sub>L' have "AC (f, F, \<langle>f\<rangle>Q) \<turnstile>\<^sub>L \<phi>" by (metis L_transform.bisimilar_is_bisimulation L_transform.is_bisimulation_def) then show "\<langle>f\<rangle>Q \<turnstile> \<phi>" by (metis L_satisfies.simps(1)) qed moreover have "\<forall>P Q. invL_FL_bisimilar F P Q \<longrightarrow> (\<forall>f. f \<in>\<^sub>f\<^sub>s F \<longrightarrow> (\<forall>\<alpha> P'. bn \<alpha> \<sharp>* (\<langle>f\<rangle>Q, F, f) \<longrightarrow> \<langle>f\<rangle>P \<rightarrow> \<langle>\<alpha>,P'\<rangle> \<longrightarrow> (\<exists>Q'. \<langle>f\<rangle>Q \<rightarrow> \<langle>\<alpha>,Q'\<rangle> \<and> invL_FL_bisimilar (L (\<alpha>, F, f)) P' Q')))" (is ?T) proof (clarify) fix P Q f \<alpha> P' assume bisim: "invL_FL_bisimilar F P Q" and effect: "f \<in>\<^sub>f\<^sub>s F" and fresh: "bn \<alpha> \<sharp>* (\<langle>f\<rangle>Q, F, f)" and trans: "\<langle>f\<rangle>P \<rightarrow> \<langle>\<alpha>,P'\<rangle>" from bisim have "EF (F,P) \<sim>\<cdot>\<^sub>L EF (F,Q)" by (metis invL_FL_bisimilar_def) moreover have "bn (Eff f) \<sharp>* EF (F,Q)" by (simp add: fresh_star_def) moreover from effect have "EF (F,P) \<rightarrow>\<^sub>L \<langle>Eff f, AC (f, F, \<langle>f\<rangle>P)\<rangle>" by (metis L_transition.simps(2)) ultimately obtain Q\<^sub>L' where trans\<^sub>L: "EF (F,Q) \<rightarrow>\<^sub>L \<langle>Eff f, Q\<^sub>L'\<rangle>" and L_bisim: "AC (f, F, \<langle>f\<rangle>P) \<sim>\<cdot>\<^sub>L Q\<^sub>L'" by (metis L_transform.bisimilar_simulation_step) from trans\<^sub>L obtain f' where "\<langle>Eff f :: ('act,'effect) L_action, Q\<^sub>L'\<rangle> = \<langle>Eff f', AC (f', F, \<langle>f'\<rangle>Q)\<rangle>" by (metis L_transition.simps(2)) then have Q\<^sub>L': "Q\<^sub>L' = AC (f, F, \<langle>f\<rangle>Q)" by (metis L_action.inject(2) bn_L_action.simps(2) residual_empty_bn_eq_iff) from L_bisim and Q\<^sub>L' have "AC (f, F, \<langle>f\<rangle>P) \<sim>\<cdot>\<^sub>L AC (f, F, \<langle>f\<rangle>Q)" by metis moreover from fresh have "bn (Act \<alpha>) \<sharp>* AC (f, F, \<langle>f\<rangle>Q)" by (simp add: fresh_def fresh_star_def supp_Pair) moreover from fresh have "bn \<alpha> \<sharp>* (F, f)" by (simp add: fresh_star_Pair) with trans have "AC (f, F, \<langle>f\<rangle>P) \<rightarrow>\<^sub>L \<langle>Act \<alpha>, EF (L (\<alpha>,F,f), P')\<rangle>" by (metis L_transition.simps(1)) ultimately obtain Q\<^sub>L'' where trans\<^sub>L': "AC (f, F, \<langle>f\<rangle>Q) \<rightarrow>\<^sub>L \<langle>Act \<alpha>, Q\<^sub>L''\<rangle>" and L_bisim': "EF (L (\<alpha>,F,f), P') \<sim>\<cdot>\<^sub>L Q\<^sub>L''" by (metis L_transform.bisimilar_simulation_step) have "finite (supp (\<langle>f\<rangle>Q, F, f))" by (fact finite_supp) with trans\<^sub>L' obtain \<alpha>' Q' where trans': "\<langle>f\<rangle>Q \<rightarrow> \<langle>\<alpha>',Q'\<rangle>" and alpha: "\<langle>Act \<alpha> :: ('act,'effect) L_action, Q\<^sub>L''\<rangle> = \<langle>Act \<alpha>', EF (L (\<alpha>',F,f), Q')\<rangle>" and fresh': "bn \<alpha>' \<sharp>* (\<langle>f\<rangle>Q, F,f)" by (metis L_transition_AC_strong) from alpha obtain p where p: "(Act \<alpha> :: ('act,'effect) L_action, Q\<^sub>L'') = p \<bullet> (Act \<alpha>', EF (L (\<alpha>',F,f), Q'))" and supp_p: "supp p \<subseteq> bn \<alpha> \<union> bn \<alpha>'" by (metis Un_commute bn_L_action.simps(1) residual_eq_iff_perm_renaming) from supp_p and fresh and fresh' have "supp p \<sharp>* (\<langle>f\<rangle>Q, F,f)" unfolding fresh_star_def by (metis (no_types, hide_lams) Un_iff subsetCE) then have p_fQ: "p \<bullet> \<langle>f\<rangle>Q = \<langle>f\<rangle>Q" and p_F: "p \<bullet> F = F" and p_f: "p \<bullet> f = f" by (simp add: fresh_star_def perm_supp_eq)+ from p and p_F and p_f have p_\<alpha>': "p \<bullet> \<alpha>' = \<alpha>" and Q\<^sub>L'': "Q\<^sub>L'' = EF (L (p \<bullet> \<alpha>', F, f), p \<bullet> Q')" by auto from trans' and p_fQ and p_\<alpha>' have "\<langle>f\<rangle>Q \<rightarrow> \<langle>\<alpha>, p \<bullet> Q'\<rangle>" by (metis transition_eqvt') moreover from L_bisim' and Q\<^sub>L'' and p_\<alpha>' have "invL_FL_bisimilar (L (\<alpha>,F,f)) P' (p \<bullet> Q')" by (metis invL_FL_bisimilar_def) ultimately show "\<exists>Q'. \<langle>f\<rangle>Q \<rightarrow> \<langle>\<alpha>,Q'\<rangle> \<and> invL_FL_bisimilar (L (\<alpha>,F,f)) P' Q'" by metis qed ultimately show "?R \<and> ?S \<and> ?T" by metis qed theorem "P \<sim>\<cdot>[F] Q \<longleftrightarrow> EF (F,P) \<sim>\<cdot>\<^sub>L EF(F,Q)" proof assume "P \<sim>\<cdot>[F] Q" then have "L_bisimilar (EF (F,P)) (EF (F,Q))" by (metis L_bisimilar.intros(1)) then show "EF (F,P) \<sim>\<cdot>\<^sub>L EF(F,Q)" by (metis L_bisimilar_is_L_transform_bisimulation L_transform.bisimilar_def) next assume "EF (F, P) \<sim>\<cdot>\<^sub>L EF (F, Q)" then have "invL_FL_bisimilar F P Q" by (metis invL_FL_bisimilar_def) then show "P \<sim>\<cdot>[F] Q" by (metis invL_FL_bisimilar_is_L_bisimulation FL_bisimilar_def) qed end text \<open>The following (alternative) proof of the ``$\leftarrow$'' direction of this equivalence, namely that bisimilarity in the $L$-transform implies $F/L$-bisimilarity, uses the fact that the $L$-transform preserves satisfaction of formulas, together with the fact that bisimilarity (in the $L$-transform) implies logical equivalence. However, since we proved the latter in the context of indexed nominal transition systems, this proof requires an indexed nominal transition system with effects where, additionally, the cardinality of the state set of the $L$-transform is bounded. We could re-organize our formalization to remove this assumption: the proof of @{thm indexed_nominal_ts.bisimilarity_implies_equivalence} does not actually make use of the cardinality assumptions provided by indexed nominal transition systems.\<close> locale L_transform_indexed_effect_nominal_ts = indexed_effect_nominal_ts L satisfies transition effect_apply for L :: "('act::bn) \<times> ('effect::fs) fs_set \<times> 'effect \<Rightarrow> 'effect fs_set" and satisfies :: "'state::fs \<Rightarrow> 'pred::fs \<Rightarrow> bool" (infix "\<turnstile>" 70) and transition :: "'state \<Rightarrow> ('act,'state) residual \<Rightarrow> bool" (infix "\<rightarrow>" 70) and effect_apply :: "'effect \<Rightarrow> 'state \<Rightarrow> 'state" ("\<langle>_\<rangle>_" [0,101] 100) + assumes card_idx_L_transform_state: "|UNIV::('state, 'effect) L_state set| <o |UNIV::'idx set|" begin interpretation L_transform: indexed_nominal_ts "(\<turnstile>\<^sub>L)" "(\<rightarrow>\<^sub>L)" by unfold_locales (fact L_satisfies_eqvt, fact L_transition_eqvt, fact card_idx_perm, fact card_idx_L_transform_state) notation L_transform.bisimilar (infix "\<sim>\<cdot>\<^sub>L" 100) theorem "EF (F,P) \<sim>\<cdot>\<^sub>L EF(F,Q) \<longrightarrow> P \<sim>\<cdot>[F] Q" proof assume "EF (F, P) \<sim>\<cdot>\<^sub>L EF (F, Q)" then have "L_transform.logically_equivalent (EF (F, P)) (EF (F, Q))" by (fact L_transform.bisimilarity_implies_equivalence) with FL_valid_iff_valid_L_transform have "FL_logically_equivalent F P Q" using FL_logically_equivalent_def L_transform.logically_equivalent_def by blast then show "P \<sim>\<cdot>[F] Q" by (fact FL_equivalence_implies_bisimilarity) qed end end
module Control.Comonad.Store.Representable import Control.Comonad import public Control.Comonad.Store.Interface import Data.Functor.Representable %default total public export data Store : (f : Type -> Type) -> {rep : Representable f r} -> Type -> Type where MkStore : {0 rep : Representable f r} -> f a -> r -> Store {rep} f a public export (rep : Representable f r) => Functor (Store f {rep}) where map f (MkStore s i) = MkStore (map f s) i public export (rep : Representable f r) => Comonad (Store f {rep}) where extract (MkStore s i) = s `index` i duplicate (MkStore s i) = MkStore (tabulate (MkStore s)) i public export (rep : Representable f r) => ComonadStore r (Store {rep} f) where pos (MkStore _ i) = i peek i (MkStore s _) = s `index` i public export store : (rep : Representable f r) => (r -> a) -> r -> Store {rep} f a store g i = MkStore (tabulate g) i
module Prelude where infixr 90 _∘_ infixr 0 _$_ id : {A : Set} -> A -> A id x = x _∘_ : {A B C : Set} -> (B -> C) -> (A -> B) -> A -> C (f ∘ g) x = f (g x) _$_ : {A B : Set} -> (A -> B) -> A -> B f $ x = f x flip : {A B C : Set} -> (A -> B -> C) -> B -> A -> C flip f x y = f y x const : {A B : Set} -> A -> B -> A const x _ = x typeOf : {A : Set} -> A -> Set typeOf {A} _ = A typeOf1 : {A : Set1} -> A -> Set1 typeOf1 {A} _ = A
If $f$ converges to $l < 0$, then there exists $r > 0$ such that for all $x$ with $|x - c| < r$, we have $f(x) < 0$.
def filterMedian (Filter): ### Imports import numpy as np import matplotlib.pyplot as plt import math as m import navFunc as nf import time # Load image into numpy matrix A = Filter.img size = nf.structtype() size.A = nf.structtype() size.A.lin, size.A.col = A.shape #################### Mean filter ## Pre-set steps: Filter.kernel = np.ones((Filter.kernelSize, Filter.kernelSize)) ################# central = m.floor((Filter.kernelSize / 2)) C = np.zeros((size.A.lin + central * 2, size.A.col + central * 2)) C[(0 + central):(size.A.lin + central), (0 + central):(size.A.col + central)] = A ################# ## Run the kernel over the matrix (similar to convolution): ################# buffer = np.zeros((Filter.kernelSize * Filter.kernelSize)) D = np.zeros(A.shape) # for each line: for j in range((0), size.A.lin): # for each collumn: for k in range((0), size.A.col): # Run kernel in one matrix's elements ## for each line: for kl in range(0, Filter.kernelSize): ## for each collumn: for kk in range(0, Filter.kernelSize): buffer[(Filter.kernelSize * kl + kk)] = (C[j + kl, k + kk]) buffer = np.sort(buffer) value = buffer[int(np.floor((Filter.kernelSize**2)/2))] D[j, k] = value # print('LINE has finished') D = np.uint8(D) print('################################') print('Process finished') print('Filter have been applied') print('################################') return D
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark, Kyle Miller, Lu-Ming Zhang -/ import combinatorics.simple_graph.basic import combinatorics.simple_graph.connectivity import linear_algebra.matrix.trace import linear_algebra.matrix.symmetric /-! # Adjacency Matrices This module defines the adjacency matrix of a graph, and provides theorems connecting graph properties to computational properties of the matrix. ## Main definitions * `matrix.is_adj_matrix`: `A : matrix V V α` is qualified as an "adjacency matrix" if (1) every entry of `A` is `0` or `1`, (2) `A` is symmetric, (3) every diagonal entry of `A` is `0`. * `matrix.is_adj_matrix.to_graph`: for `A : matrix V V α` and `h : A.is_adj_matrix`, `h.to_graph` is the simple graph induced by `A`. * `matrix.compl`: for `A : matrix V V α`, `A.compl` is supposed to be the adjacency matrix of the complement graph of the graph induced by `A`. * `simple_graph.adj_matrix`: the adjacency matrix of a `simple_graph`. * `simple_graph.adj_matrix_pow_apply_eq_card_walk`: each entry of the `n`th power of a graph's adjacency matrix counts the number of length-`n` walks between the corresponding pair of vertices. -/ open_locale big_operators matrix open finset matrix simple_graph variables {V α β : Type*} namespace matrix /-- `A : matrix V V α` is qualified as an "adjacency matrix" if (1) every entry of `A` is `0` or `1`, (2) `A` is symmetric, (3) every diagonal entry of `A` is `0`. -/ structure is_adj_matrix [has_zero α] [has_one α] (A : matrix V V α) : Prop := (zero_or_one : ∀ i j, (A i j) = 0 ∨ (A i j) = 1 . obviously) (symm : A.is_symm . obviously) (apply_diag : ∀ i, A i i = 0 . obviously) namespace is_adj_matrix variables {A : matrix V V α} @[simp] lemma apply_diag_ne [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) (i : V) : ¬ A i i = 1 := by simp [h.apply_diag i] @[simp] lemma apply_ne_one_iff [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) (i j : V) : ¬ A i j = 1 ↔ A i j = 0 := by { obtain (h|h) := h.zero_or_one i j; simp [h] } @[simp] lemma apply_ne_zero_iff [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) (i j : V) : ¬ A i j = 0 ↔ A i j = 1 := by rw [←apply_ne_one_iff h, not_not] /-- For `A : matrix V V α` and `h : is_adj_matrix A`, `h.to_graph` is the simple graph whose adjacency matrix is `A`. -/ @[simps] def to_graph [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) : simple_graph V := { adj := λ i j, A i j = 1, symm := λ i j hij, by rwa h.symm.apply i j, loopless := λ i, by simp [h] } instance [mul_zero_one_class α] [nontrivial α] [decidable_eq α] (h : is_adj_matrix A) : decidable_rel h.to_graph.adj := by { simp only [to_graph], apply_instance } end is_adj_matrix /-- For `A : matrix V V α`, `A.compl` is supposed to be the adjacency matrix of the complement graph of the graph induced by `A.adj_matrix`. -/ def compl [has_zero α] [has_one α] [decidable_eq α] [decidable_eq V] (A : matrix V V α) : matrix V V α := λ i j, ite (i = j) 0 (ite (A i j = 0) 1 0) section compl variables [decidable_eq α] [decidable_eq V] (A : matrix V V α) @[simp] lemma compl_apply_diag [has_zero α] [has_one α] (i : V) : A.compl i i = 0 := by simp [compl] @[simp] lemma compl_apply [has_zero α] [has_one α] (i j : V) : A.compl i j = 0 ∨ A.compl i j = 1 := by { unfold compl, split_ifs; simp, } @[simp] lemma is_symm_compl [has_zero α] [has_one α] (h : A.is_symm) : A.compl.is_symm := by { ext, simp [compl, h.apply, eq_comm], } @[simp] lemma is_adj_matrix_compl [has_zero α] [has_one α] (h : A.is_symm) : is_adj_matrix A.compl := { symm := by simp [h] } namespace is_adj_matrix variable {A} @[simp] lemma compl [has_zero α] [has_one α] (h : is_adj_matrix A) : is_adj_matrix A.compl := is_adj_matrix_compl A h.symm lemma to_graph_compl_eq [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) : h.compl.to_graph = (h.to_graph)ᶜ := begin ext v w, cases h.zero_or_one v w with h h; by_cases hvw : v = w; simp [matrix.compl, h, hvw] end end is_adj_matrix end compl end matrix open matrix namespace simple_graph variables (G : simple_graph V) [decidable_rel G.adj] variables (α) /-- `adj_matrix G α` is the matrix `A` such that `A i j = (1 : α)` if `i` and `j` are adjacent in the simple graph `G`, and otherwise `A i j = 0`. -/ def adj_matrix [has_zero α] [has_one α] : matrix V V α := of $ λ i j, if (G.adj i j) then (1 : α) else 0 variable {α} -- TODO: set as an equation lemma for `adj_matrix`, see mathlib4#3024 @[simp] lemma adj_matrix_apply (v w : V) [has_zero α] [has_one α] : G.adj_matrix α v w = if (G.adj v w) then 1 else 0 := rfl @[simp] theorem transpose_adj_matrix [has_zero α] [has_one α] : (G.adj_matrix α)ᵀ = G.adj_matrix α := by { ext, simp [adj_comm] } @[simp] lemma is_symm_adj_matrix [has_zero α] [has_one α] : (G.adj_matrix α).is_symm := transpose_adj_matrix G variable (α) /-- The adjacency matrix of `G` is an adjacency matrix. -/ @[simp] lemma is_adj_matrix_adj_matrix [has_zero α] [has_one α] : (G.adj_matrix α).is_adj_matrix := { zero_or_one := λ i j, by by_cases G.adj i j; simp [h] } /-- The graph induced by the adjacency matrix of `G` is `G` itself. -/ lemma to_graph_adj_matrix_eq [mul_zero_one_class α] [nontrivial α] : (G.is_adj_matrix_adj_matrix α).to_graph = G := begin ext, simp only [is_adj_matrix.to_graph_adj, adj_matrix_apply, ite_eq_left_iff, zero_ne_one], apply not_not, end variables {α} [fintype V] @[simp] lemma adj_matrix_dot_product [non_assoc_semiring α] (v : V) (vec : V → α) : dot_product (G.adj_matrix α v) vec = ∑ u in G.neighbor_finset v, vec u := by simp [neighbor_finset_eq_filter, dot_product, sum_filter] @[simp] lemma dot_product_adj_matrix [non_assoc_semiring α] (v : V) (vec : V → α) : dot_product vec (G.adj_matrix α v) = ∑ u in G.neighbor_finset v, vec u := by simp [neighbor_finset_eq_filter, dot_product, sum_filter, finset.sum_apply] @[simp] lemma adj_matrix_mul_vec_apply [non_assoc_semiring α] (v : V) (vec : V → α) : ((G.adj_matrix α).mul_vec vec) v = ∑ u in G.neighbor_finset v, vec u := by rw [mul_vec, adj_matrix_dot_product] @[simp] lemma adj_matrix_vec_mul_apply [non_assoc_semiring α] (v : V) (vec : V → α) : ((G.adj_matrix α).vec_mul vec) v = ∑ u in G.neighbor_finset v, vec u := begin rw [← dot_product_adj_matrix, vec_mul], refine congr rfl _, ext, rw [← transpose_apply (adj_matrix α G) x v, transpose_adj_matrix], end @[simp] lemma adj_matrix_mul_apply [non_assoc_semiring α] (M : matrix V V α) (v w : V) : (G.adj_matrix α ⬝ M) v w = ∑ u in G.neighbor_finset v, M u w := by simp [mul_apply, neighbor_finset_eq_filter, sum_filter] @[simp] variable (α) @[simp] theorem trace_adj_matrix [add_comm_monoid α] [has_one α] : matrix.trace (G.adj_matrix α) = 0 := by simp [matrix.trace] variable {α} theorem adj_matrix_mul_self_apply_self [non_assoc_semiring α] (i : V) : ((G.adj_matrix α) ⬝ (G.adj_matrix α)) i i = degree G i := by simp [degree] variable {G} @[simp] lemma adj_matrix_mul_vec_const_apply [semiring α] {a : α} {v : V} : (G.adj_matrix α).mul_vec (function.const _ a) v = G.degree v * a := by simp [degree] lemma adj_matrix_mul_vec_const_apply_of_regular [semiring α] {d : ℕ} {a : α} (hd : G.is_regular_of_degree d) {v : V} : (G.adj_matrix α).mul_vec (function.const _ a) v = (d * a) := by simp [hd v] theorem adj_matrix_pow_apply_eq_card_walk [decidable_eq V] [semiring α] (n : ℕ) (u v : V) : (G.adj_matrix α ^ n) u v = fintype.card {p : G.walk u v | p.length = n} := begin rw card_set_walk_length_eq, induction n with n ih generalizing u v, { obtain rfl | h := eq_or_ne u v; simp [finset_walk_length, *] }, { nth_rewrite 0 [nat.succ_eq_one_add], simp only [pow_add, pow_one, finset_walk_length, ih, mul_eq_mul, adj_matrix_mul_apply], rw finset.card_bUnion, { norm_cast, simp only [nat.cast_sum, card_map, neighbor_finset_def], apply finset.sum_to_finset_eq_subtype, }, /- Disjointness for card_bUnion -/ { rintros ⟨x, hx⟩ - ⟨y, hy⟩ - hxy, rw disjoint_iff_inf_le, intros p hp, simp only [inf_eq_inter, mem_inter, mem_map, function.embedding.coe_fn_mk, exists_prop] at hp; obtain ⟨⟨px, hpx, rfl⟩, ⟨py, hpy, hp⟩⟩ := hp, cases hp, simpa using hxy, } }, end end simple_graph namespace matrix.is_adj_matrix variables [mul_zero_one_class α] [nontrivial α] variables {A : matrix V V α} (h : is_adj_matrix A) /-- If `A` is qualified as an adjacency matrix, then the adjacency matrix of the graph induced by `A` is itself. -/ lemma adj_matrix_to_graph_eq [decidable_eq α] : h.to_graph.adj_matrix α = A := begin ext i j, obtain (h'|h') := h.zero_or_one i j; simp [h'], end end matrix.is_adj_matrix
function create_subgraph(vertex_set::AbstractArray,edge_list::AbstractArray,directed::Bool) new_graph = graph(Int64[],ExEdge{Int64}[],is_directed = directed) vertex_set_d = Dict() for vertex in vertex_set add_vertex!(new_graph,vertex) vertex_set_d[vertex] = 1 end for edge in edge_list if (haskey(vertex_set_d,edge.source)) && (haskey(vertex_set_d,edge.target)) new_edge = ExEdge(edge.index,edge.source,edge.target) for (k,v) in edge.attributes new_edge.attributes[k] = v end add_edge!(new_graph,new_edge) end end return new_graph end function all_neighbors(v::Int64,g::GenericGraph) if is_directed(g) neighbr = out_neighbors(v,g) for n in in_neighbors(v,g) append!(neighbr,n) end return neighbr else return out_neighbors(v,g) end end function all_degree(v::Int64,g::GenericGraph) if is_directed(g) return out_degree(v,g) + in_degree(v,g) else return out_degree(v,g) end end function occurrence_of_degree(g::GenericGraph) g_vertices = vertices(g) degrees = zeros(Int64,0) max = 0 d = 0 for i = 1:length(g_vertices) d = all_degree(g_vertices[i],g)+1 if max < d for j=1:(d-max) push!(degrees,0) end degrees[d] +=1 max = d else degrees[d] +=1 end end return degrees end
% book : Signals and Systems Laboratory with MATLAB % authors : Alex Palamides & Anastasia Veloni % % % z-Transform properties %linearity syms n z x1=n^2; x2=2^n; a1=3; a2=4; Le=a1*x1+a2*x2; Left=ztrans(Le,z) X1=ztrans(x1); X2=ztrans(x2); Right=a1*X1+a2*X2
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta ! This file was ported from Lean 3 source module category_theory.limits.shapes.split_coequalizer ! leanprover-community/mathlib commit f47581155c818e6361af4e4fda60d27d020c226b ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.CategoryTheory.Limits.Shapes.Equalizers /-! # Split coequalizers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define what it means for a triple of morphisms `f g : X ⟶ Y`, `π : Y ⟶ Z` to be a split coequalizer: there is a section `s` of `π` and a section `t` of `g`, which additionally satisfy `t ≫ f = π ≫ s`. In addition, we show that every split coequalizer is a coequalizer (`category_theory.is_split_coequalizer.is_coequalizer`) and absolute (`category_theory.is_split_coequalizer.map`) A pair `f g : X ⟶ Y` has a split coequalizer if there is a `Z` and `π : Y ⟶ Z` making `f,g,π` a split coequalizer. A pair `f g : X ⟶ Y` has a `G`-split coequalizer if `G f, G g` has a split coequalizer. These definitions and constructions are useful in particular for the monadicity theorems. ## TODO Dualise to split equalizers. -/ namespace CategoryTheory universe v v₂ u u₂ variable {C : Type u} [Category.{v} C] variable {D : Type u₂} [Category.{v₂} D] variable (G : C ⥤ D) variable {X Y : C} (f g : X ⟶ Y) #print CategoryTheory.IsSplitCoequalizer /- /-- A split coequalizer diagram consists of morphisms f π X ⇉ Y → Z g satisfying `f ≫ π = g ≫ π` together with morphisms t s X ← Y ← Z satisfying `s ≫ π = 𝟙 Z`, `t ≫ g = 𝟙 Y` and `t ≫ f = π ≫ s`. The name "coequalizer" is appropriate, since any split coequalizer is a coequalizer, see `category_theory.is_split_coequalizer.is_coequalizer`. Split coequalizers are also absolute, since a functor preserves all the structure above. -/ structure IsSplitCoequalizer {Z : C} (π : Y ⟶ Z) where rightSection : Z ⟶ Y leftSection : Y ⟶ X condition : f ≫ π = g ≫ π rightSection_π : right_section ≫ π = 𝟙 Z leftSection_bottom : left_section ≫ g = 𝟙 Y leftSection_top : left_section ≫ f = π ≫ right_section #align category_theory.is_split_coequalizer CategoryTheory.IsSplitCoequalizer -/ instance {X : C} : Inhabited (IsSplitCoequalizer (𝟙 X) (𝟙 X) (𝟙 X)) := ⟨⟨𝟙 _, 𝟙 _, rfl, Category.id_comp _, Category.id_comp _, rfl⟩⟩ open IsSplitCoequalizer attribute [reassoc.1] condition attribute [simp, reassoc.1] right_section_π left_section_bottom left_section_top variable {f g} /- warning: category_theory.is_split_coequalizer.map -> CategoryTheory.IsSplitCoequalizer.map is a dubious translation: lean 3 declaration is forall {C : Type.{u3}} [_inst_1 : CategoryTheory.Category.{u1, u3} C] {D : Type.{u4}} [_inst_2 : CategoryTheory.Category.{u2, u4} D] {X : C} {Y : C} {f : Quiver.Hom.{succ u1, u3} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) X Y} {g : Quiver.Hom.{succ u1, u3} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) X Y} {Z : C} {π : Quiver.Hom.{succ u1, u3} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) Y Z}, (CategoryTheory.IsSplitCoequalizer.{u1, u3} C _inst_1 X Y f g Z π) -> (forall (F : CategoryTheory.Functor.{u1, u2, u3, u4} C _inst_1 D _inst_2), CategoryTheory.IsSplitCoequalizer.{u2, u4} D _inst_2 (CategoryTheory.Functor.obj.{u1, u2, u3, u4} C _inst_1 D _inst_2 F X) (CategoryTheory.Functor.obj.{u1, u2, u3, u4} C _inst_1 D _inst_2 F Y) (CategoryTheory.Functor.map.{u1, u2, u3, u4} C _inst_1 D _inst_2 F X Y f) (CategoryTheory.Functor.map.{u1, u2, u3, u4} C _inst_1 D _inst_2 F X Y g) (CategoryTheory.Functor.obj.{u1, u2, u3, u4} C _inst_1 D _inst_2 F Z) (CategoryTheory.Functor.map.{u1, u2, u3, u4} C _inst_1 D _inst_2 F Y Z π)) but is expected to have type forall {C : Type.{u3}} [_inst_1 : CategoryTheory.Category.{u1, u3} C] {D : Type.{u4}} [_inst_2 : CategoryTheory.Category.{u2, u4} D] {X : C} {Y : C} {f : Quiver.Hom.{succ u1, u3} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) X Y} {g : Quiver.Hom.{succ u1, u3} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) X Y} {Z : C} {π : Quiver.Hom.{succ u1, u3} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) Y Z}, (CategoryTheory.IsSplitCoequalizer.{u1, u3} C _inst_1 X Y f g Z π) -> (forall (F : CategoryTheory.Functor.{u1, u2, u3, u4} C _inst_1 D _inst_2), CategoryTheory.IsSplitCoequalizer.{u2, u4} D _inst_2 (Prefunctor.obj.{succ u1, succ u2, u3, u4} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) D (CategoryTheory.CategoryStruct.toQuiver.{u2, u4} D (CategoryTheory.Category.toCategoryStruct.{u2, u4} D _inst_2)) (CategoryTheory.Functor.toPrefunctor.{u1, u2, u3, u4} C _inst_1 D _inst_2 F) X) (Prefunctor.obj.{succ u1, succ u2, u3, u4} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) D (CategoryTheory.CategoryStruct.toQuiver.{u2, u4} D (CategoryTheory.Category.toCategoryStruct.{u2, u4} D _inst_2)) (CategoryTheory.Functor.toPrefunctor.{u1, u2, u3, u4} C _inst_1 D _inst_2 F) Y) (Prefunctor.map.{succ u1, succ u2, u3, u4} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) D (CategoryTheory.CategoryStruct.toQuiver.{u2, u4} D (CategoryTheory.Category.toCategoryStruct.{u2, u4} D _inst_2)) (CategoryTheory.Functor.toPrefunctor.{u1, u2, u3, u4} C _inst_1 D _inst_2 F) X Y f) (Prefunctor.map.{succ u1, succ u2, u3, u4} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) D (CategoryTheory.CategoryStruct.toQuiver.{u2, u4} D (CategoryTheory.Category.toCategoryStruct.{u2, u4} D _inst_2)) (CategoryTheory.Functor.toPrefunctor.{u1, u2, u3, u4} C _inst_1 D _inst_2 F) X Y g) (Prefunctor.obj.{succ u1, succ u2, u3, u4} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) D (CategoryTheory.CategoryStruct.toQuiver.{u2, u4} D (CategoryTheory.Category.toCategoryStruct.{u2, u4} D _inst_2)) (CategoryTheory.Functor.toPrefunctor.{u1, u2, u3, u4} C _inst_1 D _inst_2 F) Z) (Prefunctor.map.{succ u1, succ u2, u3, u4} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) D (CategoryTheory.CategoryStruct.toQuiver.{u2, u4} D (CategoryTheory.Category.toCategoryStruct.{u2, u4} D _inst_2)) (CategoryTheory.Functor.toPrefunctor.{u1, u2, u3, u4} C _inst_1 D _inst_2 F) Y Z π)) Case conversion may be inaccurate. Consider using '#align category_theory.is_split_coequalizer.map CategoryTheory.IsSplitCoequalizer.mapₓ'. -/ /-- Split coequalizers are absolute: they are preserved by any functor. -/ @[simps] def IsSplitCoequalizer.map {Z : C} {π : Y ⟶ Z} (q : IsSplitCoequalizer f g π) (F : C ⥤ D) : IsSplitCoequalizer (F.map f) (F.map g) (F.map π) where rightSection := F.map q.rightSection leftSection := F.map q.leftSection condition := by rw [← F.map_comp, q.condition, F.map_comp] rightSection_π := by rw [← F.map_comp, q.right_section_π, F.map_id] leftSection_bottom := by rw [← F.map_comp, q.left_section_bottom, F.map_id] leftSection_top := by rw [← F.map_comp, q.left_section_top, F.map_comp] #align category_theory.is_split_coequalizer.map CategoryTheory.IsSplitCoequalizer.map section open Limits #print CategoryTheory.IsSplitCoequalizer.asCofork /- /-- A split coequalizer clearly induces a cofork. -/ @[simps pt] def IsSplitCoequalizer.asCofork {Z : C} {h : Y ⟶ Z} (t : IsSplitCoequalizer f g h) : Cofork f g := Cofork.ofπ h t.condition #align category_theory.is_split_coequalizer.as_cofork CategoryTheory.IsSplitCoequalizer.asCofork -/ /- warning: category_theory.is_split_coequalizer.as_cofork_π -> CategoryTheory.IsSplitCoequalizer.asCofork_π is a dubious translation: lean 3 declaration is forall {C : Type.{u2}} [_inst_1 : CategoryTheory.Category.{u1, u2} C] {X : C} {Y : C} {f : Quiver.Hom.{succ u1, u2} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u2} C (CategoryTheory.Category.toCategoryStruct.{u1, u2} C _inst_1)) X Y} {g : Quiver.Hom.{succ u1, u2} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u2} C (CategoryTheory.Category.toCategoryStruct.{u1, u2} C _inst_1)) X Y} {Z : C} {h : Quiver.Hom.{succ u1, u2} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u2} C (CategoryTheory.Category.toCategoryStruct.{u1, u2} C _inst_1)) Y Z} (t : CategoryTheory.IsSplitCoequalizer.{u1, u2} C _inst_1 X Y f g Z h), Eq.{succ u1} (Quiver.Hom.{succ u1, u2} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u2} C (CategoryTheory.Category.toCategoryStruct.{u1, u2} C _inst_1)) (CategoryTheory.Functor.obj.{0, u1, 0, u2} CategoryTheory.Limits.WalkingParallelPair CategoryTheory.Limits.walkingParallelPairHomCategory C _inst_1 (CategoryTheory.Limits.parallelPair.{u1, u2} C _inst_1 X Y f g) CategoryTheory.Limits.WalkingParallelPair.one) (CategoryTheory.Functor.obj.{0, u1, 0, u2} CategoryTheory.Limits.WalkingParallelPair CategoryTheory.Limits.walkingParallelPairHomCategory C _inst_1 (CategoryTheory.Functor.obj.{u1, u1, u2, max u1 u2} C _inst_1 (CategoryTheory.Functor.{0, u1, 0, u2} CategoryTheory.Limits.WalkingParallelPair CategoryTheory.Limits.walkingParallelPairHomCategory C _inst_1) (CategoryTheory.Functor.category.{0, u1, 0, u2} CategoryTheory.Limits.WalkingParallelPair CategoryTheory.Limits.walkingParallelPairHomCategory C _inst_1) (CategoryTheory.Functor.const.{0, u1, 0, u2} CategoryTheory.Limits.WalkingParallelPair CategoryTheory.Limits.walkingParallelPairHomCategory C _inst_1) (CategoryTheory.Limits.Cocone.pt.{0, u1, 0, u2} CategoryTheory.Limits.WalkingParallelPair CategoryTheory.Limits.walkingParallelPairHomCategory C _inst_1 (CategoryTheory.Limits.parallelPair.{u1, u2} C _inst_1 X Y f g) (CategoryTheory.IsSplitCoequalizer.asCofork.{u1, u2} C _inst_1 X Y f g Z h t))) CategoryTheory.Limits.WalkingParallelPair.one)) (CategoryTheory.Limits.Cofork.π.{u1, u2} C _inst_1 X Y f g (CategoryTheory.IsSplitCoequalizer.asCofork.{u1, u2} C _inst_1 X Y f g Z h t)) h but is expected to have type forall {C : Type.{u2}} [_inst_1 : CategoryTheory.Category.{u1, u2} C] {X : C} {Y : C} {f : Quiver.Hom.{succ u1, u2} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u2} C (CategoryTheory.Category.toCategoryStruct.{u1, u2} C _inst_1)) X Y} {g : Quiver.Hom.{succ u1, u2} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u2} C (CategoryTheory.Category.toCategoryStruct.{u1, u2} C _inst_1)) X Y} {Z : C} {h : Quiver.Hom.{succ u1, u2} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u2} C (CategoryTheory.Category.toCategoryStruct.{u1, u2} C _inst_1)) Y Z} (t : CategoryTheory.IsSplitCoequalizer.{u1, u2} C _inst_1 X Y f g Z h), Eq.{succ u1} (Quiver.Hom.{succ u1, u2} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u2} C (CategoryTheory.Category.toCategoryStruct.{u1, u2} C _inst_1)) (Prefunctor.obj.{1, succ u1, 0, u2} CategoryTheory.Limits.WalkingParallelPair (CategoryTheory.CategoryStruct.toQuiver.{0, 0} CategoryTheory.Limits.WalkingParallelPair (CategoryTheory.Category.toCategoryStruct.{0, 0} CategoryTheory.Limits.WalkingParallelPair CategoryTheory.Limits.walkingParallelPairHomCategory)) C (CategoryTheory.CategoryStruct.toQuiver.{u1, u2} C (CategoryTheory.Category.toCategoryStruct.{u1, u2} C _inst_1)) (CategoryTheory.Functor.toPrefunctor.{0, u1, 0, u2} CategoryTheory.Limits.WalkingParallelPair CategoryTheory.Limits.walkingParallelPairHomCategory C _inst_1 (CategoryTheory.Limits.parallelPair.{u1, u2} C _inst_1 X Y f g)) CategoryTheory.Limits.WalkingParallelPair.one) (Prefunctor.obj.{1, succ u1, 0, u2} CategoryTheory.Limits.WalkingParallelPair (CategoryTheory.CategoryStruct.toQuiver.{0, 0} CategoryTheory.Limits.WalkingParallelPair (CategoryTheory.Category.toCategoryStruct.{0, 0} CategoryTheory.Limits.WalkingParallelPair CategoryTheory.Limits.walkingParallelPairHomCategory)) C (CategoryTheory.CategoryStruct.toQuiver.{u1, u2} C (CategoryTheory.Category.toCategoryStruct.{u1, u2} C _inst_1)) (CategoryTheory.Functor.toPrefunctor.{0, u1, 0, u2} CategoryTheory.Limits.WalkingParallelPair CategoryTheory.Limits.walkingParallelPairHomCategory C _inst_1 (Prefunctor.obj.{succ u1, succ u1, u2, max u1 u2} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u2} C (CategoryTheory.Category.toCategoryStruct.{u1, u2} C _inst_1)) (CategoryTheory.Functor.{0, u1, 0, u2} CategoryTheory.Limits.WalkingParallelPair CategoryTheory.Limits.walkingParallelPairHomCategory C _inst_1) (CategoryTheory.CategoryStruct.toQuiver.{u1, max u2 u1} (CategoryTheory.Functor.{0, u1, 0, u2} CategoryTheory.Limits.WalkingParallelPair CategoryTheory.Limits.walkingParallelPairHomCategory C _inst_1) (CategoryTheory.Category.toCategoryStruct.{u1, max u2 u1} (CategoryTheory.Functor.{0, u1, 0, u2} CategoryTheory.Limits.WalkingParallelPair CategoryTheory.Limits.walkingParallelPairHomCategory C _inst_1) (CategoryTheory.Functor.category.{0, u1, 0, u2} CategoryTheory.Limits.WalkingParallelPair CategoryTheory.Limits.walkingParallelPairHomCategory C _inst_1))) (CategoryTheory.Functor.toPrefunctor.{u1, u1, u2, max u2 u1} C _inst_1 (CategoryTheory.Functor.{0, u1, 0, u2} CategoryTheory.Limits.WalkingParallelPair CategoryTheory.Limits.walkingParallelPairHomCategory C _inst_1) (CategoryTheory.Functor.category.{0, u1, 0, u2} CategoryTheory.Limits.WalkingParallelPair CategoryTheory.Limits.walkingParallelPairHomCategory C _inst_1) (CategoryTheory.Functor.const.{0, u1, 0, u2} CategoryTheory.Limits.WalkingParallelPair CategoryTheory.Limits.walkingParallelPairHomCategory C _inst_1)) (CategoryTheory.Limits.Cocone.pt.{0, u1, 0, u2} CategoryTheory.Limits.WalkingParallelPair CategoryTheory.Limits.walkingParallelPairHomCategory C _inst_1 (CategoryTheory.Limits.parallelPair.{u1, u2} C _inst_1 X Y f g) (CategoryTheory.IsSplitCoequalizer.asCofork.{u1, u2} C _inst_1 X Y f g Z h t)))) CategoryTheory.Limits.WalkingParallelPair.one)) (CategoryTheory.Limits.Cofork.π.{u1, u2} C _inst_1 X Y f g (CategoryTheory.IsSplitCoequalizer.asCofork.{u1, u2} C _inst_1 X Y f g Z h t)) h Case conversion may be inaccurate. Consider using '#align category_theory.is_split_coequalizer.as_cofork_π CategoryTheory.IsSplitCoequalizer.asCofork_πₓ'. -/ @[simp] theorem IsSplitCoequalizer.asCofork_π {Z : C} {h : Y ⟶ Z} (t : IsSplitCoequalizer f g h) : t.asCofork.π = h := rfl #align category_theory.is_split_coequalizer.as_cofork_π CategoryTheory.IsSplitCoequalizer.asCofork_π #print CategoryTheory.IsSplitCoequalizer.isCoequalizer /- /-- The cofork induced by a split coequalizer is a coequalizer, justifying the name. In some cases it is more convenient to show a given cofork is a coequalizer by showing it is split. -/ def IsSplitCoequalizer.isCoequalizer {Z : C} {h : Y ⟶ Z} (t : IsSplitCoequalizer f g h) : IsColimit t.asCofork := Cofork.IsColimit.mk' _ fun s => ⟨t.rightSection ≫ s.π, by dsimp rw [← t.left_section_top_assoc, s.condition, t.left_section_bottom_assoc], fun m hm => by simp [← hm]⟩ #align category_theory.is_split_coequalizer.is_coequalizer CategoryTheory.IsSplitCoequalizer.isCoequalizer -/ end variable (f g) #print CategoryTheory.HasSplitCoequalizer /- /- ./././Mathport/Syntax/Translate/Command.lean:388:30: infer kinds are unsupported in Lean 4: #[`splittable] [] -/ /-- The pair `f,g` is a split pair if there is a `h : Y ⟶ Z` so that `f, g, h` forms a split coequalizer in `C`. -/ class HasSplitCoequalizer : Prop where splittable : ∃ (Z : C)(h : Y ⟶ Z), Nonempty (IsSplitCoequalizer f g h) #align category_theory.has_split_coequalizer CategoryTheory.HasSplitCoequalizer -/ #print CategoryTheory.Functor.IsSplitPair /- /-- The pair `f,g` is a `G`-split pair if there is a `h : G Y ⟶ Z` so that `G f, G g, h` forms a split coequalizer in `D`. -/ abbrev Functor.IsSplitPair : Prop := HasSplitCoequalizer (G.map f) (G.map g) #align category_theory.functor.is_split_pair CategoryTheory.Functor.IsSplitPair -/ #print CategoryTheory.HasSplitCoequalizer.coequalizerOfSplit /- /-- Get the coequalizer object from the typeclass `is_split_pair`. -/ noncomputable def HasSplitCoequalizer.coequalizerOfSplit [HasSplitCoequalizer f g] : C := (HasSplitCoequalizer.splittable f g).some #align category_theory.has_split_coequalizer.coequalizer_of_split CategoryTheory.HasSplitCoequalizer.coequalizerOfSplit -/ #print CategoryTheory.HasSplitCoequalizer.coequalizerπ /- /-- Get the coequalizer morphism from the typeclass `is_split_pair`. -/ noncomputable def HasSplitCoequalizer.coequalizerπ [HasSplitCoequalizer f g] : Y ⟶ HasSplitCoequalizer.coequalizerOfSplit f g := (HasSplitCoequalizer.splittable f g).choose_spec.some #align category_theory.has_split_coequalizer.coequalizer_π CategoryTheory.HasSplitCoequalizer.coequalizerπ -/ #print CategoryTheory.HasSplitCoequalizer.isSplitCoequalizer /- /-- The coequalizer morphism `coequalizer_ι` gives a split coequalizer on `f,g`. -/ noncomputable def HasSplitCoequalizer.isSplitCoequalizer [HasSplitCoequalizer f g] : IsSplitCoequalizer f g (HasSplitCoequalizer.coequalizerπ f g) := Classical.choice (HasSplitCoequalizer.splittable f g).choose_spec.choose_spec #align category_theory.has_split_coequalizer.is_split_coequalizer CategoryTheory.HasSplitCoequalizer.isSplitCoequalizer -/ /- warning: category_theory.map_is_split_pair -> CategoryTheory.map_is_split_pair is a dubious translation: lean 3 declaration is forall {C : Type.{u3}} [_inst_1 : CategoryTheory.Category.{u1, u3} C] {D : Type.{u4}} [_inst_2 : CategoryTheory.Category.{u2, u4} D] (G : CategoryTheory.Functor.{u1, u2, u3, u4} C _inst_1 D _inst_2) {X : C} {Y : C} (f : Quiver.Hom.{succ u1, u3} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) X Y) (g : Quiver.Hom.{succ u1, u3} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) X Y) [_inst_3 : CategoryTheory.HasSplitCoequalizer.{u1, u3} C _inst_1 X Y f g], CategoryTheory.HasSplitCoequalizer.{u2, u4} D _inst_2 (CategoryTheory.Functor.obj.{u1, u2, u3, u4} C _inst_1 D _inst_2 G X) (CategoryTheory.Functor.obj.{u1, u2, u3, u4} C _inst_1 D _inst_2 G Y) (CategoryTheory.Functor.map.{u1, u2, u3, u4} C _inst_1 D _inst_2 G X Y f) (CategoryTheory.Functor.map.{u1, u2, u3, u4} C _inst_1 D _inst_2 G X Y g) but is expected to have type forall {C : Type.{u3}} [_inst_1 : CategoryTheory.Category.{u1, u3} C] {D : Type.{u4}} [_inst_2 : CategoryTheory.Category.{u2, u4} D] (G : CategoryTheory.Functor.{u1, u2, u3, u4} C _inst_1 D _inst_2) {X : C} {Y : C} (f : Quiver.Hom.{succ u1, u3} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) X Y) (g : Quiver.Hom.{succ u1, u3} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) X Y) [_inst_3 : CategoryTheory.HasSplitCoequalizer.{u1, u3} C _inst_1 X Y f g], CategoryTheory.HasSplitCoequalizer.{u2, u4} D _inst_2 (Prefunctor.obj.{succ u1, succ u2, u3, u4} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) D (CategoryTheory.CategoryStruct.toQuiver.{u2, u4} D (CategoryTheory.Category.toCategoryStruct.{u2, u4} D _inst_2)) (CategoryTheory.Functor.toPrefunctor.{u1, u2, u3, u4} C _inst_1 D _inst_2 G) X) (Prefunctor.obj.{succ u1, succ u2, u3, u4} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) D (CategoryTheory.CategoryStruct.toQuiver.{u2, u4} D (CategoryTheory.Category.toCategoryStruct.{u2, u4} D _inst_2)) (CategoryTheory.Functor.toPrefunctor.{u1, u2, u3, u4} C _inst_1 D _inst_2 G) Y) (Prefunctor.map.{succ u1, succ u2, u3, u4} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) D (CategoryTheory.CategoryStruct.toQuiver.{u2, u4} D (CategoryTheory.Category.toCategoryStruct.{u2, u4} D _inst_2)) (CategoryTheory.Functor.toPrefunctor.{u1, u2, u3, u4} C _inst_1 D _inst_2 G) X Y f) (Prefunctor.map.{succ u1, succ u2, u3, u4} C (CategoryTheory.CategoryStruct.toQuiver.{u1, u3} C (CategoryTheory.Category.toCategoryStruct.{u1, u3} C _inst_1)) D (CategoryTheory.CategoryStruct.toQuiver.{u2, u4} D (CategoryTheory.Category.toCategoryStruct.{u2, u4} D _inst_2)) (CategoryTheory.Functor.toPrefunctor.{u1, u2, u3, u4} C _inst_1 D _inst_2 G) X Y g) Case conversion may be inaccurate. Consider using '#align category_theory.map_is_split_pair CategoryTheory.map_is_split_pairₓ'. -/ /-- If `f, g` is split, then `G f, G g` is split. -/ instance map_is_split_pair [HasSplitCoequalizer f g] : HasSplitCoequalizer (G.map f) (G.map g) where splittable := ⟨_, _, ⟨IsSplitCoequalizer.map (HasSplitCoequalizer.isSplitCoequalizer f g) _⟩⟩ #align category_theory.map_is_split_pair CategoryTheory.map_is_split_pair namespace Limits #print CategoryTheory.Limits.hasCoequalizer_of_hasSplitCoequalizer /- /-- If a pair has a split coequalizer, it has a coequalizer. -/ instance (priority := 1) hasCoequalizer_of_hasSplitCoequalizer [HasSplitCoequalizer f g] : HasCoequalizer f g := HasColimit.mk ⟨_, (HasSplitCoequalizer.isSplitCoequalizer f g).isCoequalizer⟩ #align category_theory.limits.has_coequalizer_of_has_split_coequalizer CategoryTheory.Limits.hasCoequalizer_of_hasSplitCoequalizer -/ end Limits end CategoryTheory