Datasets:
AI4M
/

text
stringlengths
0
3.34M
(** * positives: basic facts about binary positive numbers *) Require Export BinNums. Require Import comparisons. (** positives as a [cmpType] *) Fixpoint eqb_pos i j := match i,j with | xH,xH => true | xI i,xI j | xO i, xO j => eqb_pos i j | _,_ => false end. Lemma eqb_pos_spec: forall i j, reflect (i=j) (eqb_pos i j). Proof. induction i; intros [j|j|]; simpl; (try case IHi); constructor; congruence. Qed. Fixpoint pos_compare i j := match i,j with | xH, xH => Eq | xO i, xO j | xI i, xI j => pos_compare i j | xH, _ => Lt | _, xH => Gt | xO _, _ => Lt | _,_ => Gt end. Lemma pos_compare_spec: forall i j, compare_spec (i=j) (pos_compare i j). Proof. induction i; destruct j; simpl; try case IHi; try constructor; congruence. Qed. Canonical Structure cmp_pos := mk_cmp _ eqb_pos_spec _ pos_compare_spec. (** positive maps (for making environments) *) (** we redefine such trees here rather than importing them from the standard library: since we do not need any proof about them, this avoids us a heavy Require Import *) Section e. Variable A: Type. Inductive sigma := sigma_empty | N(l: sigma)(o: option A)(r: sigma). Fixpoint sigma_get default m i := match m with | N l o r => match i with | xH => match o with None => default | Some a => a end | xO i => sigma_get default l i | xI i => sigma_get default r i end | _ => default end. Fixpoint sigma_add i v m := match m with | sigma_empty => match i with | xH => N sigma_empty (Some v) sigma_empty | xO i => N (sigma_add i v sigma_empty) None sigma_empty | xI i => N sigma_empty None (sigma_add i v sigma_empty) end | N l o r => match i with | xH => N l (Some v) r | xO i => N (sigma_add i v l) o r | xI i => N l o (sigma_add i v r) end end. End e.
module FIRRemez using FFTW using Distributed using SharedArrays import Random import LinearAlgebra #import PyPlot import Printf import FiniteDiff import DelimitedFiles include("../src/misc/declarations.jl") include("./minimax/Chebyshev.jl") include("./minimax/interpolators.jl") include("./minimax/eval.jl") include("./minimax/filter.jl") include("./minimax/exchange.jl") include("./minimax/exchange_strategy.jl") include("./minimax/engine.jl") include("./minimax/extrema_search.jl") include("../src/misc/utilities.jl") include("../src/misc/template_signals.jl") include("../src/misc/bounds.jl") include("../src/misc/IO.jl") include("../src/misc/frontend.jl") include("./FIR/design.jl") include("./FIR/type_conversion.jl") include("../src/misc/visualize.jl") export frontendoptimization, visualizeoptimzationsolution, naiveimpulsersp, getdefaultoptparameters, MiniMaxConfigType, Barycentric2nditp, frontendfilterdesign, getp, # visualization. plotmagnitudersp, visualizefiltersolution end
State Before: R : Type u S₁ : Type v S₂ : Type w S₃ : Type x σ : Type u_1 a a' a₁ a₂ : R e : ℕ n m✝ : σ s✝ : σ →₀ ℕ inst✝² : CommSemiring R inst✝¹ : CommSemiring S₁ p✝ q : MvPolynomial σ R inst✝ : DecidableEq σ m : σ →₀ ℕ s : σ p : MvPolynomial σ R ⊢ coeff m (p * X s) = if s ∈ m.support then coeff (m - Finsupp.single s 1) p else 0 State After: R : Type u S₁ : Type v S₂ : Type w S₃ : Type x σ : Type u_1 a a' a₁ a₂ : R e : ℕ n m✝ : σ s✝ : σ →₀ ℕ inst✝² : CommSemiring R inst✝¹ : CommSemiring S₁ p✝ q : MvPolynomial σ R inst✝ : DecidableEq σ m : σ →₀ ℕ s : σ p : MvPolynomial σ R ⊢ (if Finsupp.single s 1 ≤ m then coeff (m - Finsupp.single s 1) p * 1 else 0) = if s ∈ m.support then coeff (m - Finsupp.single s 1) p else 0 Tactic: refine' (coeff_mul_monomial' _ _ _ _).trans _ State Before: R : Type u S₁ : Type v S₂ : Type w S₃ : Type x σ : Type u_1 a a' a₁ a₂ : R e : ℕ n m✝ : σ s✝ : σ →₀ ℕ inst✝² : CommSemiring R inst✝¹ : CommSemiring S₁ p✝ q : MvPolynomial σ R inst✝ : DecidableEq σ m : σ →₀ ℕ s : σ p : MvPolynomial σ R ⊢ (if Finsupp.single s 1 ≤ m then coeff (m - Finsupp.single s 1) p * 1 else 0) = if s ∈ m.support then coeff (m - Finsupp.single s 1) p else 0 State After: no goals Tactic: simp_rw [Finsupp.single_le_iff, Finsupp.mem_support_iff, Nat.succ_le_iff, pos_iff_ne_zero, mul_one]
Formal statement is: lemma mem_cone: assumes "cone S" "x \<in> S" "c \<ge> 0" shows "c *\<^sub>R x \<in> S" Informal statement is: If $S$ is a cone and $x \in S$, then $cx \in S$ for all $c \geq 0$.
theory 2 imports Main begin datatype nat = zero | s nat datatype lst = nil | cons nat lst fun add :: "nat \<Rightarrow> nat \<Rightarrow> nat" where "add zero y = y" | "add (s x) y = s (add x y)" fun app :: "lst \<Rightarrow> lst \<Rightarrow> lst" where "app nil r = r" | "app (cons a l) r = cons a (app l r)" fun len :: "lst \<Rightarrow> nat" where "len nil = zero" | "len (cons e l) = s (len l)" fun leq :: "nat \<Rightarrow> nat \<Rightarrow> bool" where "leq zero x = True" | "leq (s x) zero = False" | "leq (s x) (s y) = leq x y" fun less :: "nat \<Rightarrow> nat \<Rightarrow> bool" where "less x y = leq (s x) y" fun cnt :: "lst \<Rightarrow> nat \<Rightarrow> nat" where "cnt nil x = zero" | "cnt (cons x tail) e = (if (\<not>(x=e)) then (cnt tail e) else (s (cnt tail e)))" fun outOfBounds :: "nat \<Rightarrow> nat" where "outOfBounds i = i" fun get :: "lst \<Rightarrow> nat \<Rightarrow> nat" where "get nil i = outOfBounds i" | "get (cons x tail) zero = x" | "get (cons x tail) (s i) = get tail i" lemma "less i (len x) \<and> get x i = e \<Longrightarrow> less zero (cnt l e)"
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-} -- | -- Module : Statistics.Distribution.Normal -- Copyright : (c) 2009 Bryan O'Sullivan -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- The normal distribution. This is a continuous probability -- distribution that describes data that cluster around a mean. module Statistics.Distribution.Normal ( NormalDistribution -- * Constructors , normalDistr , normalDistrE , normalDistrErr , standard ) where import Control.Applicative import Data.Aeson (FromJSON(..), ToJSON, Value(..), (.:)) import Data.Binary (Binary(..)) import Data.Data (Data, Typeable) import GHC.Generics (Generic) import Numeric.MathFunctions.Constants (m_sqrt_2, m_sqrt_2_pi) import Numeric.SpecFunctions (erfc, invErfc) import qualified System.Random.MWC.Distributions as MWC import qualified Data.Vector.Generic as G import qualified Statistics.Distribution as D import qualified Statistics.Sample as S import Statistics.Internal -- | The normal distribution. data NormalDistribution = ND { mean :: {-# UNPACK #-} !Double , stdDev :: {-# UNPACK #-} !Double , ndPdfDenom :: {-# UNPACK #-} !Double , ndCdfDenom :: {-# UNPACK #-} !Double } deriving (Eq, Typeable, Data, Generic) instance Show NormalDistribution where showsPrec i (ND m s _ _) = defaultShow2 "normalDistr" m s i instance Read NormalDistribution where readPrec = defaultReadPrecM2 "normalDistr" normalDistrE instance ToJSON NormalDistribution instance FromJSON NormalDistribution where parseJSON (Object v) = do m <- v .: "mean" sd <- v .: "stdDev" either fail return $ normalDistrErr m sd parseJSON _ = empty instance Binary NormalDistribution where put (ND m sd _ _) = put m >> put sd get = do m <- get sd <- get either fail return $ normalDistrErr m sd instance D.Distribution NormalDistribution where cumulative = cumulative complCumulative = complCumulative instance D.ContDistr NormalDistribution where logDensity = logDensity quantile = quantile complQuantile = complQuantile instance D.MaybeMean NormalDistribution where maybeMean = Just . D.mean instance D.Mean NormalDistribution where mean = mean instance D.MaybeVariance NormalDistribution where maybeStdDev = Just . D.stdDev maybeVariance = Just . D.variance instance D.Variance NormalDistribution where stdDev = stdDev instance D.Entropy NormalDistribution where entropy d = 0.5 * log (2 * pi * exp 1 * D.variance d) instance D.MaybeEntropy NormalDistribution where maybeEntropy = Just . D.entropy instance D.ContGen NormalDistribution where genContVar d = MWC.normal (mean d) (stdDev d) -- | Standard normal distribution with mean equal to 0 and variance equal to 1 standard :: NormalDistribution standard = ND { mean = 0.0 , stdDev = 1.0 , ndPdfDenom = log m_sqrt_2_pi , ndCdfDenom = m_sqrt_2 } -- | Create normal distribution from parameters. -- -- IMPORTANT: prior to 0.10 release second parameter was variance not -- standard deviation. normalDistr :: Double -- ^ Mean of distribution -> Double -- ^ Standard deviation of distribution -> NormalDistribution normalDistr m sd = either error id $ normalDistrErr m sd -- | Create normal distribution from parameters. -- -- IMPORTANT: prior to 0.10 release second parameter was variance not -- standard deviation. normalDistrE :: Double -- ^ Mean of distribution -> Double -- ^ Standard deviation of distribution -> Maybe NormalDistribution normalDistrE m sd = either (const Nothing) Just $ normalDistrErr m sd -- | Create normal distribution from parameters. -- normalDistrErr :: Double -- ^ Mean of distribution -> Double -- ^ Standard deviation of distribution -> Either String NormalDistribution normalDistrErr m sd | sd > 0 = Right $ ND { mean = m , stdDev = sd , ndPdfDenom = log $ m_sqrt_2_pi * sd , ndCdfDenom = m_sqrt_2 * sd } | otherwise = Left $ errMsg m sd errMsg :: Double -> Double -> String errMsg _ sd = "Statistics.Distribution.Normal.normalDistr: standard deviation must be positive. Got " ++ show sd -- | Variance is estimated using maximum likelihood method -- (biased estimation). -- -- Returns @Nothing@ if sample contains less than one element or -- variance is zero (all elements are equal) instance D.FromSample NormalDistribution Double where fromSample xs | G.length xs <= 1 = Nothing | v == 0 = Nothing | otherwise = Just $! normalDistr m (sqrt v) where (m,v) = S.meanVariance xs logDensity :: NormalDistribution -> Double -> Double logDensity d x = (-xm * xm / (2 * sd * sd)) - ndPdfDenom d where xm = x - mean d sd = stdDev d cumulative :: NormalDistribution -> Double -> Double cumulative d x = erfc ((mean d - x) / ndCdfDenom d) / 2 complCumulative :: NormalDistribution -> Double -> Double complCumulative d x = erfc ((x - mean d) / ndCdfDenom d) / 2 quantile :: NormalDistribution -> Double -> Double quantile d p | p == 0 = -inf | p == 1 = inf | p == 0.5 = mean d | p > 0 && p < 1 = x * ndCdfDenom d + mean d | otherwise = error $ "Statistics.Distribution.Normal.quantile: p must be in [0,1] range. Got: "++show p where x = - invErfc (2 * p) inf = 1/0 complQuantile :: NormalDistribution -> Double -> Double complQuantile d p | p == 0 = inf | p == 1 = -inf | p == 0.5 = mean d | p > 0 && p < 1 = x * ndCdfDenom d + mean d | otherwise = error $ "Statistics.Distribution.Normal.complQuantile: p must be in [0,1] range. Got: "++show p where x = invErfc (2 * p) inf = 1/0
-- @@stderr -- dtrace: failed to compile script test/unittest/printa/err.D_PRINTF_ARG_TYPE.jstack.d: [D_PRINTF_ARG_TYPE] line 12: printa( ) argument #2 is incompatible with conversion #1 prototype: conversion: %p prototype: pointer or integer argument: stack
[STATEMENT] lemma norm_le_l1_cart: "norm x \<le> sum(\<lambda>i. \<bar>x$i\<bar>) UNIV" [PROOF STATE] proof (prove) goal (1 subgoal): 1. norm x \<le> (\<Sum>i\<in>UNIV. \<bar>x $ i\<bar>) [PROOF STEP] by (simp add: norm_vec_def L2_set_le_sum)
= De <unk> a <unk> : interviews with persons affected by the 2010 Haiti earthquake =
State Before: ι : Type u γ : Type w β : ι → Type v β₁ : ι → Type v₁ β₂ : ι → Type v₂ dec : DecidableEq ι inst✝¹ : (i : ι) → Zero (β i) s : Finset ι x✝ : (i : ↑↑s) → β ↑i i✝ : ι p : ι → Prop inst✝ : DecidablePred p i : ι x : β i h : ¬p i ⊢ filter p (single i x) = 0 State After: no goals Tactic: rw [filter_single, if_neg h]
[STATEMENT] lemma continuous_on_avoid: fixes f :: "'a::metric_space \<Rightarrow> 'b::t1_space" assumes "continuous_on s f" and "x \<in> s" and "f x \<noteq> a" shows "\<exists>e>0. \<forall>y \<in> s. dist x y < e \<longrightarrow> f y \<noteq> a" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>e>0. \<forall>y\<in>s. dist x y < e \<longrightarrow> f y \<noteq> a [PROOF STEP] using assms(1)[unfolded continuous_on_eq_continuous_within, THEN bspec[where x=x], OF assms(2)] continuous_within_avoid[of x s f a] [PROOF STATE] proof (prove) using this: continuous (at x within s) f \<lbrakk>continuous (at x within s) f; f x \<noteq> a\<rbrakk> \<Longrightarrow> \<exists>e>0. \<forall>y\<in>s. dist x y < e \<longrightarrow> f y \<noteq> a goal (1 subgoal): 1. \<exists>e>0. \<forall>y\<in>s. dist x y < e \<longrightarrow> f y \<noteq> a [PROOF STEP] using assms(3) [PROOF STATE] proof (prove) using this: continuous (at x within s) f \<lbrakk>continuous (at x within s) f; f x \<noteq> a\<rbrakk> \<Longrightarrow> \<exists>e>0. \<forall>y\<in>s. dist x y < e \<longrightarrow> f y \<noteq> a f x \<noteq> a goal (1 subgoal): 1. \<exists>e>0. \<forall>y\<in>s. dist x y < e \<longrightarrow> f y \<noteq> a [PROOF STEP] by auto
[STATEMENT] lemma ht_loaded_locs_subseteq_hs_pending_loaded_locs: "ht_loaded_locs \<subseteq> hs_pending_loaded_locs" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ht_loaded_locs \<subseteq> hs_pending_loaded_locs [PROOF STEP] unfolding ht_loaded_locs_def hs_pending_loaded_locs_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. prefixed ''hs_'' - {hs_load_pending, local.hs_pending, hs_mfence, hs_load_ht} \<subseteq> prefixed ''hs_'' - {hs_load_pending} [PROOF STEP] by (fastforce intro: append_prefixD)
@testset "test_utils.jl" begin estimates = (PointEstimate, DistributionEstimate) outputs = (SingleOutput, MultiOutput) @testset "$est, $out, PointPredictInput" for (est, out) in Iterators.product(estimates, outputs) temp = FakeTemplate{est, out}() test_interface(temp) end @testset "Vector inputs case" begin temp = FakeTemplate{PointEstimate, SingleOutput}() test_interface(temp; inputs=[rand(5), rand(5)], outputs=rand(1, 2)) end @testset "$est, $out, PointOrDistributionPredictInput" for (est, out) in Iterators.product(estimates, outputs) Models.predict_input_type(m::Type{<:FakeTemplate}) = PointOrDistributionPredictInput Models.predict_input_type(m::Type{<:FakeModel}) = PointOrDistributionPredictInput temp = FakeTemplate{est, out}() test_interface(temp) end @testset "Vector inputs case" begin temp = FakeTemplate{PointEstimate, SingleOutput}() test_interface( temp; inputs=[rand(5), rand(5)], outputs=rand(1, 2), distribution_inputs=[MvNormal(5, m) for m in 1:2] ) end end
(** To put in a chapter about inductive types *) (** Multiplication Schemes (CPS) *) Require Import bin_nums tutorial_type_classes.SRC.Monoid Omega List. Generalizable Variables op one. Inductive Computation {A:Type} : Type := | Return (a : A) | Mult (x y : A) (k : A -> Computation). Notation "z '<---' x 'times' y ';' e2 " := (Mult x y (fun z => e2)) (right associativity, at level 60). Definition chain := forall (A:Type), A -> @Computation A. (* Axiom suggestion so as to get a hand on complexity properties. Inductive similar {A B:Type}: @Computation A -> @Computation B -> Prop := | S_return: forall (a:A) (b:B), similar (Return a) (Return b) | Mult_return: forall kA kB a1 a2 b1 b2, (forall a b, similar (kA a) (kB b)) -> similar (Mult a1 a2 kA) (Mult b1 b2 kB). Axiom free_chain: forall (c:chain) A B a b, similar (c A a) (c B b). *) Inductive equiv {A B:Type}: list (A*B) -> @Computation A -> @Computation B -> Prop := | Ereturn: forall (x:A) (y:B) (l:list (A*B)), In (x,y) l -> equiv l (Return x) (Return y) | Emult: forall (x1 y1:A) (x2 y2:B) (l:list (A*B)) (kA:A-> @Computation A) (kB:B -> @Computation B), In (x1,x2) l -> In (y1,y2) l -> (forall (x':A) (y':B),equiv ((x',y')::l) (kA x') (kB y')) -> equiv l (Mult x1 y1 kA) (Mult x2 y2 kB). (*Inductive well_formed {A:Type}: @Computation A -> @Computation A -> Prop:= | Wf_return: forall (x:A), equiv (Return x) (Return x) | Wf_mult: forall (x1 y1:A)(kA kA': A->@Computation A), (forall a:A, well_formed (kA a) (kA' a)) well_formed (Mult x1 y1 kA) (Mult x1 y1 kA').*) Axiom parametric_equiv: forall c:chain, forall A B (a:A) (b:B), equiv ((a,b)::nil) (c A a) (c B b). Fixpoint execute {A:Type} `{M:Monoid A op one} (c : @Computation A) : A := match c with Return x => x | Mult x y k => execute (k (op x y)) end. Definition apply_chain (c: chain){A}`{M:Monoid A op one} (a:A) := execute (c A a). (** number of mutiplications *) Fixpoint comp_complexity (c : @Computation unit) : nat := match c with | Mult _ _ k => S (comp_complexity (k tt)) | _ => 0%nat end. Definition complexity (c: chain) := comp_complexity (c _ tt). Require Import ArithRing. Instance NatPlus : Monoid plus 0%nat. split; intros; ring. Qed. Definition the_exponent (c:chain) := apply_chain c (M:= NatPlus) 1%nat. (** the exponent associated to a chain *) (** computation of x ^ 3 *) Example C3 : chain := fun {A:Type} (a : A) => a2 <--- a times a ; a3 <--- a2 times a ; Return a3. Compute complexity C3. (** computation of x ^ 7 *) Example C7 : chain := fun {A} (x:A) => x2 <--- x times x ; x3 <--- x2 times x ; x6 <--- x3 times x3 ; x7 <--- x6 times x ; Return x7. Remark C7_correct : forall A `{M: Monoid A op one} (x:A), apply_chain C7 x = op x (op x (op x (op x (op x (op x x))))). Proof. intros ; cbn. now repeat rewrite <- dot_assoc. Qed. (** Scheme for computing a x ^ p (p positive) *) Fixpoint axp_scheme p {A:Type} : A -> A -> @Computation A := match p with | xH => (fun a x => y <--- a times x ; Return y) | xO q => (fun a x => x2 <--- x times x ; axp_scheme q a x2) | xI q => (fun a x => ax <--- a times x ; x2 <--- x times x ; axp_scheme q ax x2) end. Definition Pos_pow_chain (p:positive) := match p with xH => fun (A:Type) (x:A) => Return x | _ => fun (A:Type) (x:A) => axp_scheme (Pos.pred p) x x end. Definition C11 := Pos_pow_chain 11%positive. Compute apply_chain (M:=ZMult) C11 2%Z. (* = fun (A : Type) (x0 : A) => x1 <--- x0 times x0; (* x^2 *) x2 <--- x0 times x1; (* x^3 *) x3 <--- x1 times x1; (* x ^ 4 *) x4 <--- x3 times x3; (* x ^8 *) x5 <--- x2 times x4; Return x5 *) Definition C87 : chain := fun A (x:A) => x2 <--- x times x ; x3 <--- x2 times x ; x6 <--- x3 times x3 ; x7 <--- x6 times x ; x10 <--- x7 times x3 ; x20 <--- x10 times x10 ; x40 <--- x20 times x20 ; x80 <--- x40 times x40 ; x87 <--- x80 times x7 ; Return x87. Compute the_exponent C87. Compute the_exponent C11. Definition chain_correct (c : chain) (p:positive) := forall A `(M:Monoid A op one) (a:A), apply_chain c a = power a (Pos.to_nat p). Definition correct_chain_generator (f : positive ->chain ) := forall p, chain_correct (f p) p. (** JUSQU'ICI TOUT VA BIEN *) (** Correctness of the binary method *) Lemma L : forall p A `(M:Monoid A op one) (a:A) x, execute (axp_scheme p a x) = op a (power x (Pos.to_nat p)). Proof. induction p. - intros a x; simpl axp_scheme. replace (Pos.to_nat p~1) with (S (Pos.to_nat p + Pos.to_nat p)%nat). cbn. intros;rewrite IHp; rewrite power_of_square, <- power_x_plus. now rewrite dot_assoc. rewrite Pnat.Pos2Nat.inj_xI;omega. - intros a x; simpl axp_scheme. replace (Pos.to_nat p~0 ) with (Pos.to_nat p + Pos.to_nat p)%nat. intros; simpl; rewrite IHp, power_of_square, <- power_x_plus; auto. rewrite Pnat.Pos2Nat.inj_xO;omega. - simpl; intros; now rewrite (one_right x). Qed. Lemma binary_correct : correct_chain_generator Pos_pow_chain. Proof. intros n x. intros; unfold apply_chain. destruct n. simpl. rewrite L. f_equal. rewrite <- (sqr (A:=x) M). rewrite power_of_power. f_equal. rewrite (mult_comm (Pos.to_nat n) 2)%nat. replace (2* Pos.to_nat n)%nat with (Pos.to_nat n + Pos.to_nat n)%nat. SearchAbout Pos.iter_op. now rewrite ZL6. ring. - simpl. rewrite L. rewrite Pos2Nat.inj_xO. SearchAbout Pos.pred_double. SearchAbout power. replace (op a (power a (Pos.to_nat (Pos.pred_double n)))) with (power a (S (Pos.to_nat (Pos.pred_double n)))). SearchRewrite (S (Pos.to_nat _)). f_equal. rewrite <- Pos2Nat.inj_succ. SearchRewrite (Pos.succ (Pos.pred_double _)). rewrite Pos.succ_pred_double. SearchRewrite (Pos.to_nat (xO _)). now rewrite Pos2Nat.inj_xO. now simpl. - simpl. now rewrite one_right. Qed. (** We can define "optimal" algorithms for generating computation schemes *) Definition optimal (f : positive -> chain) := forall (g : positive -> chain), correct_chain_generator g -> forall p, (complexity (f p) <= complexity (g p))%nat. (** In the following section, we show that the binary method is not optimal *) Section bin_pow_scheme_not_optimal. Hypothesis binary_opt : optimal Pos_pow_chain. (** First, let's have a look at the computation scheme generated for, let's say, 87 *) Compute Pos_pow_chain 87. (* The variables output by Coq have been renamed by hand (x_i associated with x ^ i) = fun (A : Type) (x : x) => x_2 <--- x times x; x_3 <--- x times x_2; x_4 <--- x_2 times x_2; x_7 <--- x_3 times x_4; x_8 <--- x_4 times x_4; x_16 <--- x_8 times x_8; x_23 <--- x_7 times x_16; x_32 <--- x_16 times x_16; x_64 <--- x_32 times x_32; x_87 <--- x_23 times x_64; Return x_87 : forall A : Type, A -> Computation *) Compute complexity (Pos_pow_chain 87 ). Compute complexity C87. (** Notice that C87 has been automatically generated with the "euclidean addition chains" method http://www-igm.univ-mlv.fr/~berstel/Articles/1994AdditionChains.pdf https://eudml.org/doc/92517 *) Lemma L87 : chain_correct C87 87. Proof. red. intros. compute. now repeat (rewrite dot_assoc || rewrite (one_right (Monoid :=M))). Qed. (** we slightly modify the binary scheme *) Definition h (p:positive) := if Pos.eqb p 87%positive then C87 else Pos_pow_chain p. Lemma h_correct : correct_chain_generator h. Proof. intro p; case_eq (Pos.eqb p 87). - intros H a; unfold h; rewrite H. rewrite Pos.eqb_eq in H; subst p; apply L87. - intros ; unfold h; rewrite H; apply binary_correct. Qed. Lemma absurd : False. Proof. generalize (binary_opt h h_correct 87%positive). compute; intros. omega. Qed. End bin_pow_scheme_not_optimal. (*** The computation scheme associated to naive power *) (** In fact, the computation scheme for the naive algorithm is just the iteration of the following function *) (* Definition transform (f : (A -> Computation) -> (A -> Computation)) (k: A -> Computation) (x: A) := f (fun y:A => z <--- y times x ; k z) x. Definition naive_power_scheme (i:N) := match i with 0 => fun x => Return one | Npos q => Pos.iter transform (fun k => k) (Pos.pred q) Return end. *) Definition transform{A:Type} (f: (A -> @Computation A) -> (A -> @Computation A)) (c : (A -> @Computation A)) : A -> @Computation A := fun (x:A) => f (fun (y:A) => z <--- y times x ; c z) x. Definition naive_power_scheme (i:positive) : chain := fun (A: Type) => Pos.iter (transform (A:=A)) (fun k => k) (Pos.pred i) Return . Compute naive_power_scheme 6. Compute the_exponent (naive_power_scheme 6).
Require Import Tactics. Require Import Sigma. Require Export Coq.Logic.EqdepFacts. Require Import Axioms. (* Equality *) Definition transport {A : Type} {x x'} (e : @eq A x x') (P : A -> Type) (y : P x) : P x' := eq_rect x P y x' e. Definition eqsymm {A : Type} {x x'} (e : @eq A x x') : eq x' x := eq_rect _ (fun y => eq y x) (eq_refl x) _ e. Definition eqtrans {A : Type} {x y z : A} (e : x = y) (e' : y = z) : x = z := eq_rect _ (fun w => w = z) e' _ (eqsymm e). Definition eqcompat {A B : Type} {x y : A} (f : A -> B) (e : x = y) : f x = f y := eq_rect _ (fun z => f x = f z) (eq_refl (f x)) _ e. Lemma transport_left_inv : forall (A : Type) (B : A -> Type) (a a' : A) (x : B a) (e : a = a'), transport (eqsymm e) B (transport e B x) = x. Proof. intros A B a a' x e. subst a'. reflexivity. Qed. Lemma transport_right_inv : forall (A : Type) (B : A -> Type) (a a' : A) (x : B a') (e : a = a'), transport e B (transport (eqsymm e) B x) = x. Proof. intros A B a a' x e. subst a'. reflexivity. Qed. Lemma transport_compose : forall (A : Type) (B : A -> Type) (a1 a2 a3 : A) (x : B a1) (e1 : a1 = a2) (e2 : a2 = a3), transport e2 B (transport e1 B x) = transport (eqtrans e1 e2) B x. Proof. intros A B a1 a2 a3 x e1 e2. subst a2 a3. cbn. reflexivity. Qed. Lemma transport_compat : forall A B (f : A -> B) (C : B -> Type) (a a' : A) (x : C (f a)) (h : a = a'), transport (eqcompat f h) C x = transport h (fun z => C (f z)) x. Proof. intros A B f C a a' x h. subst a'. cbn. reflexivity. Qed. Lemma transport_back : forall A (B : A -> Type) a a' (h : a = a') (h' : a' = a) (x : B a), transport h' B (transport h B x) = x. Proof. intros A B a a' h h' x. subst a'. substrefl h'. cbn. reflexivity. Qed. Lemma transport_self : forall (A : Type) (B : A -> Type) (a : A) (h : a = a) x, transport h B x = x. Proof. intros A a a' h. substrefl h. auto. Qed. Lemma transport_symm : forall A (B : A -> Type) (a a' : A) (h : a = a') (x : B a) (y : B a'), transport h B x = y -> x = transport (eqsymm h) B y. Proof. intros A B a a' h x y Heq. subst a'. exact Heq. Qed. Lemma transport_symm' : forall A (B : A -> Type) (a a' : A) (h : a' = a) (x : B a) (y : B a'), transport (eqsymm h) B x = y -> x = transport h B y. Proof. intros A B a a' h x y Heq. subst a'. exact Heq. Qed. Lemma transport_const : forall A B (a a' : A) (h : a = a') (b : B), transport h (fun _ => B) b = b. Proof. intros A B a a' h b. subst a'. reflexivity. Qed. (* Usually need to fill in C and h. *) Lemma pi1_transport_lift : forall (A : Type) (B : Type) (C : A -> B -> Type) (a a' : A) (h : a = a') (x : exT B (C a)), pi1 (transport h (fun a'' => exT B (C a'')) x) = pi1 x. Proof. intros A B C a a' h x. subst a'. reflexivity. Qed. Lemma pi1_transport_dep_lift : forall (A : Type) (B : A -> Type) (C : forall (a:A), B a -> Type) (a a' : A) (h : a = a') (x : exT (B a) (C a)), pi1 (transport h (fun z => exT (B z) (C z)) x) = transport h B (pi1 x). Proof. intros A B C a a' h x. subst a'. cbn. reflexivity. Qed. Lemma app_transport_dom : forall (A : Type) (B : A -> Type) (C : Type) (a a' : A) (h : a = a') (f : B a -> C) (x : B a'), transport h (fun z => B z -> C) f x = f (transport (eqsymm h) B x). Proof. intros A B C a a' h f x. subst a'. cbn. reflexivity. Qed. Lemma app_transport_cod_dep : forall (A : Type) (B : Type) (C : A -> B -> Type) (a a' : A) (h : a = a') (f : forall (b:B), C a b) (x : B), transport h (fun z => forall (b:B), C z b) f x = transport h (fun z => C z x) (f x). Proof. intros A B C a a' h f x. subst a'. reflexivity. Qed. Lemma transport_commute : forall A B (f : A -> B) (C : B -> Type) a a' (h : a = a') (x : C (f a)), transport h (fun z => C (f z)) x = transport (f_equal f h) C x. Proof. intros A B f C a a' h x. subst a'. reflexivity. Qed. Lemma transport_f_equal : forall A B (C : B -> Type) (f : A -> B) (a a' : A) (h : a = a') (x : C (f a)), transport (f_equal f h) C x = transport h (fun z => C (f z)) x. Proof. intros A B C f a a' h x. subst a'. cbn. reflexivity. Qed. Lemma prod_extensionality : forall A B (p q : A * B), fst p = fst q -> snd p = snd q -> p = q. Proof. intros A B p q Hfst Hsnd. destruct p as (a, b). destruct q as (c, d). f_equal; auto. Qed. (* Dependent equality *) Definition transportdep {A:Type} {B : A -> Type} {a a' : A} {b : B a} {b' : B a'} (e : eq_dep A B a b a' b') (P : forall a, B a -> Type) (x : P a b) : P a' b' := eq_dep_rect A B a b P x a' b' e. Lemma eq_impl_eq_dep_snd : forall A (B : A -> Type) a (b b' : B a), b = b' -> eq_dep _ _ a b a b'. Proof. intros A B a b b' H. subst b'. apply eq_dep_refl. Qed. Lemma eq_impl_eq_dep_fst : forall A (B : A -> Type) (a a' : A) (b : forall a, B a), a = a' -> eq_dep _ _ a (b a) a' (b a'). Proof. intros A B a a' b H. subst a'. apply eq_dep_refl. Qed. Lemma eq_impl_eq_dep : forall A (B : A -> Type) (a a' : A) (b : B a) (b' : B a') (h : a = a'), transport h B b = b' -> eq_dep A B a b a' b'. Proof. intros A B a a' b b' h H. subst a'. subst b'. cbn. apply eq_dep_refl. Qed. Lemma eq_impl_eq_dep_free : forall A B (a a' : A) (b b' : B), a = a' -> b = b' -> eq_dep _ (fun _ => B) a b a' b'. Proof. intros A B a a' b b' Heq Heq'. subst a' b'. reflexivity. Qed. Lemma transport_eq_transportdep_snd : forall A (B : A -> Type) (C : forall a, B a -> Type) a (b b' : B a) (h : b = b') (x : C a b), transport h (C a) x = transportdep (eq_impl_eq_dep_snd A B a b b' h) C x. Proof. intros A B C a b b' h x. subst b'. replace (eq_impl_eq_dep_snd A B a b b eq_refl) with (eq_dep_intro A B a b) by (apply proof_irrelevance). cbn. reflexivity. Qed. Lemma transport_eq_transportdep_fst : forall A (B : A -> Type) (C : forall a, B a -> Type) (a a' : A) (b : forall a, B a) (h : a = a') (x : C a (b a)), transport h (fun z => C z (b z)) x = transportdep (eq_impl_eq_dep_fst A B a a' b h) C x. Proof. intros A B C a a' b h x. subst a'. replace (eq_impl_eq_dep_fst A B a a b eq_refl) with (eq_dep_intro A B a (b a)) by (apply proof_irrelevance). cbn. reflexivity. Qed. Lemma transportdep_compose : forall (A : Type) (B : A -> Type) (C : forall a, B a -> Type) (a1 a2 a3 : A) (b1 : B a1) (b2 : B a2) (b3 : B a3) (x : C a1 b1) (e1 : eq_dep _ _ a1 b1 a2 b2) (e2 : eq_dep _ _ a2 b2 a3 b3), transportdep e2 C (transportdep e1 C x) = transportdep (eq_dep_trans _#8 e1 e2) C x. Proof. intros A B C a1 a2 a3 b1 b2 b3 x e1 e2. case e2. case e1. cbn. (* This next step shouldn't be necessary, but since eq_dep_trans is opaque, it doesn't reduce. *) replace (eq_dep_trans A B a1 a1 a1 b1 b1 b1 (eq_dep_intro A B a1 b1) (eq_dep_intro A B a1 b1)) with (eq_dep_intro A B a1 b1) by (apply proof_irrelevance). cbn. reflexivity. Qed. Lemma eq_dep_impl_eq : forall A (B : A -> Type) (a a' : A) (b : B a) (b' : B a'), eq_dep _ _ a b a' b' -> exists (h : a = a'), transport h B b = b'. Proof. intros A B a a' b b' H. induct H. exists (eq_refl _). cbn. reflexivity. Qed. Lemma eq_dep_impl_eq_fst : forall A (B : A -> Type) (a a' : A) (b : B a) (b' : B a'), eq_dep _ _ a b a' b' -> a = a'. Proof. intros A B a a' b b' H. so (eq_dep_impl_eq _#6 H) as (h & _). exact h. Qed. Lemma eq_dep_impl_eq_snd : forall A (B : A -> Type) (a : A) (b : B a) (b' : B a), eq_dep _ _ a b a b' -> b = b'. Proof. intros A B a b b' H. so (eq_dep_impl_eq _#6 H) as (h & H'). substrefl h. exact H'. Qed. Lemma eq_dep_impl_eq_snd_free : forall A (B : Type) (a a' : A) (b b' : B), eq_dep _ _ a b a' b' -> b = b'. Proof. intros A B a a' b b' Heq. so (eq_dep_impl_eq_fst _#6 Heq); subst a'. exact (eq_dep_impl_eq_snd _#5 Heq). Qed. Lemma eq_dep_pi1 : forall (A : Type) (B : A -> Type) (C : forall a, B a -> Type) (a a' : A) (x : exT (B a) (C a)) (y : exT (B a') (C a')), eq_dep _ (fun a => exT (B a) (C a)) a x a' y -> eq_dep _ B a (pi1 x) a' (pi1 y). Proof. intros A B C a a' x y Heq. so (eq_dep_impl_eq_fst _#6 Heq); subst a'. so (eq_dep_impl_eq_snd _#5 Heq); subst y. reflexivity. Qed. Lemma eq_dep_prod_fst : forall A B (C : A -> Type) (x x' : A * B) (y : C (fst x)) (y' : C (fst x')), snd x = snd x' -> eq_dep A C (fst x) y (fst x') y' -> eq_dep (A * B) (fun z => C (fst z)) x y x' y'. Proof. intros A B C x x' y y' Hsnd Heq. destruct x as (a, b). destruct x' as (a', b'). cbn in y, y', Hsnd, Heq. subst b'. so (eq_dep_impl_eq_fst _#6 Heq). subst a'. so (eq_dep_impl_eq_snd _#5 Heq). subst y'. apply eq_dep_refl. Qed. Lemma functional_extensionality_eq_dep_dom : forall A (B : A -> Type) C (a a' : A) (f : B a -> C) (f' : B a' -> C), a = a' -> (forall (x : B a) (x' : B a'), eq_dep A B a x a' x' -> f x = f' x') -> eq_dep A (fun z => B z -> C) a f a' f'. Proof. intros A B C a a' f f' Heqa H. subst a'. apply eq_impl_eq_dep_snd. fextensionality 1. intro x. apply H. apply eq_dep_refl. Qed. Lemma functional_extensionality_eq_dep_cod : forall A B (C : A -> Type) (a a' : A) (f : B -> C a) (f' : B -> C a'), a = a' -> (forall (x : B), eq_dep A C a (f x) a' (f' x)) -> eq_dep A (fun z => B -> C z) a f a' f'. Proof. intros A B C a a' f f' Heqa H. subst a'. apply eq_impl_eq_dep_snd. fextensionality 1. intro y. apply eq_dep_impl_eq_snd; auto. Qed. Lemma functional_extensionality_eq_dep_cod' : forall A B (C : A -> Type) (a a' : A) (f : B -> C a) (f' : B -> C a'), B -> (forall (x : B), eq_dep A C a (f x) a' (f' x)) -> eq_dep A (fun z => B -> C z) a f a' f'. Proof. intros A B C a a' f f' x H. so (eq_dep_impl_eq_fst _#6 (H x)); subst a'. apply eq_impl_eq_dep_snd. fextensionality 1. intro y. apply eq_dep_impl_eq_snd; auto. Qed. (* Heterogeneous (so-called "John Major") equality. Exists in the standard library as JMeq. Redefine it here because the Coq tactic library silently uses axioms when you use JMeq. *) Inductive heq {A : Type} (x : A) : forall {B : Type}, B -> Prop := | heq_refl : heq x x. Hint Resolve heq_refl. Lemma heq_trans : forall A B C (a : A) (b : B) (c : C), heq a b -> heq b c -> heq a c. Proof. intros A B C a b c Hab Hbc. revert Hbc. induct Hab. auto. Qed. Lemma heq_symm : forall A B (a : A) (b : B), heq a b -> heq b a. Proof. intros A B a b H. induct H. apply heq_refl. Qed. Lemma heq_transport : forall A (B : A -> Type) a a' (h : a = a') (x : B a), heq (transport h B x) x. Proof. intros A B a a' h x. subst a'. cbn. apply heq_refl. Qed. Lemma eq_impl_heq : forall A (x y : A), x = y -> heq x y. Proof. intros A x y H. subst y. apply heq_refl. Qed. Lemma heq_impl_eq : forall (A : Type) (x y : A), heq x y -> x = y. Proof. cut (forall (A B : Type) (x : A) (y : B) (e : A = B), heq x y -> eq_rect _ (fun z => z) x _ e = y). { intros H A x y Heq. exact (H A A x y (eq_refl _) Heq). } intros A B x y e H. revert e. destruct H. intro e. pose proof (proof_irrelevance _ e (eq_refl _)). subst e. simpl. reflexivity. Qed. Lemma eq_heq_impl_eq_dep : forall A (B : A -> Type) (a a' : A) (b : B a) (b' : B a'), a = a' -> heq b b' -> eq_dep A B a b a' b'. Proof. intros A B a a' b b' Heqa Heqb. subst a'. apply eq_impl_eq_dep_snd. apply heq_impl_eq; auto. Qed. Lemma heq_pair : forall A A' B B' (a : A) (a' : A') (b : B) (b' : B'), heq a a' -> heq b b' -> heq (a, b) (a', b'). Proof. intros A A' B B' a a' b b' Ha. cases Ha. intro Hb. cases Hb. apply heq_refl. Qed. Lemma heq_prop : forall (A B : Prop) (a : A) (b : B), heq a b. Proof. intros A B a b. assert (A = B). { pextensionality; auto. } subst B. apply eq_impl_heq. apply proof_irrelevance. Qed. (* SigT *) (* For use with the built-in injection tactic. *) Lemma existT_injection_2 : forall (T : Type) (P : T -> Type) (x : T) (y y' : P x), existT _ x y = existT _ x y' -> y = y'. Proof. intros T P x y y' Heq. assert (heq (projT2 (existT _ x y)) (projT2 (existT _ x y'))) as Heq'. { rewrite -> Heq; []. apply heq_refl. } simpl in Heq'. apply heq_impl_eq; auto. Qed. (* Sigma *) Lemma exT_extensionality : forall (A : Type) (P : A -> Type) (x y : exT A P), forall (h : pi1 x = pi1 y), transport h P (pi2 x) = pi2 y -> x = y. Proof. intros A P x y Heq1 Heq2. destruct x as [x1 x2]. destruct y as [y1 y2]. simpl in Heq1. subst y1. simpl in Heq2. subst y2. reflexivity. Qed. Lemma existsT_unique_equal : forall (A : Type) (P : A -> Type), (existsT! (x : A), P x) -> forall x y, P x -> P y -> x = y. Proof. intros A P H x y Hx Hy. destruct H as (z & _ & Hunique). transitivity z. - symmetry; apply Hunique; auto. - apply Hunique; auto. Qed. Lemma expair_injection_1 : forall (T : Type) (P : T -> Type) (x x' : T) (y : P x) (y' : P x'), expair x y = expair x' y' -> x = x'. Proof. intros T P x x' y y' Heq. assert (pi1 (expair x y) = pi1 (expair x' y')) as Heq'. { rewrite -> Heq. reflexivity. } simpl in Heq'. exact Heq'. Qed. Lemma expair_eta : forall S (T : S -> Type) (x : exT S T), expair (pi1 x) (pi2 x) = x. Proof. intros S T x. destruct x. simpl; reflexivity. Qed. Lemma exT_extensionality_prop : forall (A : Type) (P : A -> Prop) (x y : exT A P), pi1 x = pi1 y -> x = y. Proof. intros A P x y Heq. apply (exT_extensionality _ _ _ _ Heq); []. apply proof_irrelevance. Qed. Lemma exT_extensionality_prop_eq_dep : forall A (B : A -> Type) (P : forall a, B a -> Prop) (a a' : A) (x : exT (B a) (P a)) (x' : exT (B a') (P a')), eq_dep A B a (pi1 x) a' (pi1 x') -> eq_dep A (fun z => exT (B z) (P z)) a x a' x'. Proof. intros A B P a a' x x' H. so (eq_dep_impl_eq_fst _#6 H); subst a'. apply eq_impl_eq_dep_snd. apply exT_extensionality_prop. apply eq_dep_impl_eq_snd; auto. Qed. Lemma expair_injection_2 : forall (T : Type) (P : T -> Type) (x : T) (y y' : P x), expair x y = expair x y' -> y = y'. Proof. intros T P x y y' Heq. assert (heq (pi2 (expair x y)) (pi2 (expair x y'))) as Heq'. { rewrite -> Heq; []. apply heq_refl. } simpl in Heq'. apply heq_impl_eq; auto. Qed. Lemma expair_injection_transport : forall (T : Type) (P : T -> Type) (x x' : T) (y : P x) (y' : P x'), expair x y = expair x' y' -> exists (h : x = x'), transport h P y = y'. Proof. intros T P x x' y y' Heq. so (expair_injection_1 _#6 Heq). subst x'. exists (eq_refl _). cbn. exact (expair_injection_2 _#5 Heq). Qed. Lemma expair_injection_dep : forall A (B : A -> Type) a a' (b : B a) (b' : B a'), expair a b = expair a' b' -> eq_dep A B a b a' b'. Proof. intros A B a a' b b' H. so (expair_injection_1 _#6 H); subst a'. so (expair_injection_2 _#5 H); subst b'. reflexivity. Qed. Lemma expair_compat_dep : forall A (B : A -> Type) a a' (b : B a) (b' : B a'), eq_dep A B a b a' b' -> expair a b = expair a' b'. Proof. intros A B a a' b b' H. so (eq_dep_impl_eq_fst _#6 H); subst a'. so (eq_dep_impl_eq_snd _#5 H); subst b'. reflexivity. Qed. Lemma expair_compat_heq : forall A (B : A -> Type) a a' (b : B a) (b' : B a'), a = a' -> heq b b' -> expair a b = expair a' b'. Proof. intros A B a a' b b' ? Heq. subst a'. so (heq_impl_eq _#3 Heq). subst b'. reflexivity. Qed. Lemma expair_compat_transport : forall A (B : A -> Type) a a' (b : B a) (b' : B a') (h : a = a'), transport h B b = b' -> expair a b = expair a' b'. Proof. intros A B a a' b b' h H. subst a'. cbn in H. subst b'. reflexivity. Qed. Lemma exT_equal : forall (A : Type) (B : A -> Type) (C C' : forall a, B a -> Type) (a a' : A), eq_dep A (fun a => B a -> Type) a (C a) a' (C' a') -> exT (B a) (C a) = exT (B a') (C' a'). Proof. intros A B C C' a a' Heq. so (eq_dep_impl_eq_fst _#6 Heq). subst a'. f_equal. exact (eq_dep_impl_eq_snd _#5 Heq). Qed. Ltac injectionT H := let H' := fresh H in match type of H with | existT _ ?x _ = existT _ ?x _ => so (existT_injection_2 _#5 H) as H'; clear H; revert H' | expair ?x _ = expair ?x _ => so (expair_injection_2 _#5 H) as H'; clear H; revert H' | eq_dep _ _ ?x _ ?x _ => so (eq_dep_impl_eq_snd _#5 H) as H'; clear H; revert H' | eq_dep _ _ ?x _ ?y _ => so (eq_dep_impl_eq_fst _#6 H) as H'; revert H' end. Lemma f_equal_dep : forall A (B : A -> Type) (C : Type) (a a' : A) (b : B a) (b' : B a') (f : forall a, B a -> C), eq_dep A B a b a' b' -> f a b = f a' b'. Proof. intros A B C a a' b b' f Heq. injectionT Heq. intros <-. injectionT Heq. intros <-. reflexivity. Qed.
[STATEMENT] lemma is_sig_red_mono: "is_sig_red sing_reg top_tail F p \<Longrightarrow> F \<subseteq> F' \<Longrightarrow> is_sig_red sing_reg top_tail F' p" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>is_sig_red sing_reg top_tail F p; F \<subseteq> F'\<rbrakk> \<Longrightarrow> is_sig_red sing_reg top_tail F' p [PROOF STEP] by (auto simp: is_sig_red_def dest: sig_red_mono)
module GenericAdder %default total AdderType : (numargs : Nat) -> (elemType : Type) -> Type AdderType Z ty = ty AdderType (S k) ty = (next : ty) -> AdderType k ty adder : Num elemType => (numargs : Nat) -> (acc : elemType) -> AdderType numargs elemType adder Z acc = acc adder (S k) acc = \next => adder k (acc + next)
module HEff -- Based on https://github.com/effectfully/Eff/blob/master/Resources/Core.agda import Data.HVect Effect : Type -> Type Effect r = r -> (a : Type) -> (a -> r) -> Type Effects : (Type -> Type) -> Vect n Type -> Vect n Type Effects f [] = [] Effects f (x :: xs) = f x :: Effects f xs data Exists' : {t : Type} -> {rs : Vect n Type} -> HVect rs -> t -> HVect (Effects Effect rs) -> Effect t -> Type where Here : Exists' (x :: xs) x (y :: ys) y There : Exists' xs x ys y -> Exists' (_ :: xs) x (_ :: ys) y update' : {t : Type} -> (r : HVect rs) -> (e : Exists' {t = t} r s effs eff) -> t -> HVect rs update' [] Here _ impossible update' [] (There _) _ impossible update' (x :: xs) Here v = v :: xs update' (x :: xs) (There e) v = x :: update' xs e v HEffect : Type HEffect = {n : Nat} -> (rs : Vect n Type) -> HVect (Effects Effect rs) -> Effect (HVect rs) data HEff : HEffect where Pure : (x : a) -> HEff rs effs (r' x) a r' Bind : (e : Exists' r s effs eff) -> eff s a s' -> ((x : a) -> HEff rs effs (update' r e (s' x)) b r'') -> HEff rs effs r b r'' (>>=) : HEff rs effs r a r' -> ((x : a) -> HEff rs effs (r' x) b r'') -> HEff rs effs r b r'' (>>=) (Pure x) f = f x (>>=) (Bind e x f) g = Bind e x (\y => f y >>= g) data Access = LoggedOut | LoggedIn data Store : Access -> (ty : Type) -> (ty -> Access) -> Type where Login : Store LoggedOut () (const LoggedIn) Logout : Store LoggedIn () (const LoggedOut) login : {auto e : Exists' r LoggedOut effs Store} -> HEff rs effs r () (\_ => update' r e LoggedIn) login {e} = Bind e Login Pure logout : {auto e : Exists' r LoggedIn effs Store} -> HEff rs effs r () (\_ => update' r e LoggedOut) logout {e} = Bind e Logout Pure data State : Type -> (a : Type) -> (a -> Type) -> Type where Get : State s s (const s) Put : s' -> State s () (const s') get : {auto e : Exists' r s effs State} -> HEff rs effs r s (\_ => update' r e s) get {e} = Bind e Get Pure put : {auto e : Exists' r s effs State} -> s' -> HEff rs effs r () (\_ => update' r e s') put {e} s' = Bind e (Put s') Pure run : HEff [] [] r a r' -> a run (Pure x) = x run (Bind Here _ _) impossible run (Bind (There _) _ _) impossible head' : HVect xs -> head xs head' (x :: _) = x tail' : HVect xs -> HVect (tail xs) tail' (x :: xs) = xs runStore : HEff (Access :: rs) (Store :: effs) r a r' -> HEff rs effs (tail' r) a (\x => tail' $ r' x) runStore (Pure x) = Pure x runStore (Bind Here Login f) = runStore $ f () runStore (Bind Here Logout f) = runStore $ f () runStore (Bind (There e) eff f) = Bind e eff (\x => runStore $ f x) runState : (head' r) -> HEff (Type :: rs) (State :: effs) r a r' -> HEff rs effs (tail' r) (DPair a (\x => head' $ r' x)) (\x => tail' $ r' (fst x)) runState s (Pure x) = Pure (x ** s) runState s (Bind Here Get f) = runState s $ f s runState s (Bind Here (Put s') f) = runState s' $ f () runState s (Bind (There e) eff f) = Bind e eff (\x => runState s $ f x) example : HEff [Access, Type] [Store, State] [LoggedOut, Nat] Nat (\n => [LoggedOut, Vect n Bool]) example = do login n <- get put (replicate n True) logout Pure n test : DPair Nat (\n => Vect n Bool) test = run . runState 3 . runStore $ example
In addition to this de facto loss of facilities , the number of aerodromes in the UK has been in decline over the last 50 years , as a result of increasing urbanisation and the closure of airfields built during WWII . Alternative and more profitable uses for land can also lead to existing aerodromes being threatened with closure , for example North Weald , or actually being closed , as happened to Ipswich <unk> and Bristol Filton Airport . Referring to the importance of a " functioning national network of GA airfields " , especially where GA performs an air transport role , the CAA states that " there could be cause for concern if a significant further loss of airfields were to continue , especially if crucial nodes on the transport network were to be lost . "
Tony is a lecturer in the English department at UCD, andfor better or worsehe has had many of the current DavisWiki users as students at one time or another. Hes been around Davis for a while, and hes a big fan of the place, so he enjoys learning new things about the area, and contributing new facts himself. He was once a proud member of the Voorhies Hall Voorhies FBombs Ultimate Frisbee team. Hes also not so sure about writing about himself in the third person... 20050707 21:45:08 nbsp I think you were my TA last summer for Intro to Drama! Users/SummerSong 20050708 02:18:27 nbsp My brother bought an iBook from this guy, and I used it while driving back from Philly since mine was in for recall work. Thanks! Users/TarZxf 20060409 21:35:57 nbsp Hi Tony! I had no idea you were on the wiki! Trust me folks, this guy is good. Users/JillWeinstein 20090123 18:22:44 nbsp Hey, youre my instructor for ENL40! Users/strawberry 20090210 23:29:21 nbsp Guess who... ) See you in class! Users/MichVan
\section{Attribute Grammars} \subsection{Left-Right attributes} Given a rule of type $A_0 \rarr A_1A_2\ldots$ \begin{description} \item[Left attribute] $\sigma_0 = f(\ldots)$ associated to $A_0$ \item[Right attribute] $\delta_i = f(\ldots), i \ge 1$, associated to $A_i$ \end{description} An attribute cannot be both left and right. \subsection{Dependence Graph} Given a rule $p$, its dependence graph $dep_p$ is a directed graph: \begin{itemize} \item Nodes are the attributes \item There is an arc from every argument to the result \item Left attributes are on the left, right to the right \end{itemize} If the dependence graph is acyclic there exists a set of attribute values. A grammar is \textbf{loop-free} if the dependence graph is always acyclic. \subsection{Depth-First visit} \begin{itemize} \item Start from the root \item Visit the child nodes in some specified order \item Foreach subtree $t_N$ rooted at node $N$ : \begin{itemize} \item Before visiting $t_N$ compute the right attributes of $N$ and pass them down to the visit \item After visiting $t_N$ compute the left attributes using the return value of the visit \end{itemize} \end{itemize} \subsection{Depth-First Visit Conditions (one-sweep)} \begin{itemize} \item The graph $dep_p$ has no circuit \item In $dep_p$ there exists no path from a left attribute to a right attribute of the same node \item In $dep_p$ there exists no arc from a left attribute of the father to a right attribute of any child \item There are no circuits in $sibl_p$ graph \end{itemize} There is an arc $D_i \rarr D_j$ in $sibl_p$ iff in $dep_p$ there is an arc $\alpha_i \rarr \beta_j$ with $\alpha_i \in \text{attr}(D_i)$ and $\beta_j \in \text{attr}(D_j)$. \subsection{One-Sweep Evaluator} There is a procedure for each nonterminal, its parameters are the subtree rooted at the nonterminal and the right attributes of the root; it visits the subtree and returns the left attributes of the root. For the rule $p: D_0 \rarr D_1D_2\ldots D_r$ \begin{itemize} \item Choose a Topological Order of Siblings $TOS$ compatible with $sibl_p$ \item For each symbol $D_i, i>0$ choose a topological order of the right attributes $TOR$ \item Choose a topological order of the left attributes of $D_0$ \end{itemize} \subsection{Condition L} Used to embed semantic evaluator inside recursive descent syntax parser. \begin{itemize} \item Support syntax is of type LL(k) \item Depth-First Visit Conditions \item The natural order ($D_1, D_2, \ldots$) is a valid TOS is $sibl_p$ (i.e. no arc $D_j\rarr D_i$ with $j>i$) \end{itemize}
import analysis.special_functions.exp import data.real.basic import tactic open real variables a b : ℝ #check pow_two_nonneg #check pow_two_nonneg b #check @exp_le_exp #check exp_le_exp.mpr -- BEGIN example (a : ℝ) : 0 ≤ a^2 := begin exact pow_two_nonneg a, end example (a b : ℝ) (h : a ≤ b) : exp a ≤ exp b := begin rw exp_le_exp, exact h, end -- END
module EqNat public export data EqNat : (num1 : Nat) -> (num2 : Nat) -> Type where Same : (num : Nat) -> EqNat num num -- sameS : (eq : EqNat k j) -> EqNat (S k) (S j) -- sameS (Same j) = Same (S j) public export checkEqNat : (num1 : Nat) -> (num2 : Nat) -> Maybe (EqNat num1 num2) checkEqNat Z Z = Just $ Same Z checkEqNat Z (S k) = Nothing checkEqNat (S k) Z = Nothing checkEqNat (S k) (S j) = case checkEqNat k j of Nothing => Nothing Just (Same j) => Just $ Same (S j)
module mod_pt_array implicit none ! the type of element can contain coordinates of vertexes, coordinate of centroid cell ... type :: element integer :: ident = 0 real :: value_elem = 0.0 end type type :: element_pt type(element), pointer :: p => null() end type type(element_pt), dimension(:), allocatable :: elements integer :: nbelements end module
(* *********************************************************************) (* *) (* The Compcert verified compiler *) (* *) (* Xavier Leroy, INRIA Paris-Rocquencourt *) (* *) (* Copyright Institut National de Recherche en Informatique et en *) (* Automatique. All rights reserved. This file is distributed *) (* under the terms of the GNU General Public License as published by *) (* the Free Software Foundation, either version 2 of the License, or *) (* (at your option) any later version. This file is also distributed *) (* under the terms of the INRIA Non-Commercial License Agreement. *) (* *) (* *********************************************************************) (** This file collects a number of definitions and theorems that are used throughout the development. It complements the Coq standard library. *) Require Export ZArith. Require Export Znumtheory. Require Export List. Require Export Bool. Require Import Wf_nat. (** * Useful tactics *) Ltac inv H := inversion H; clear H; subst. Ltac predSpec pred predspec x y := generalize (predspec x y); case (pred x y); intro. Ltac caseEq name := generalize (refl_equal name); pattern name at -1 in |- *; case name. Ltac destructEq name := destruct name as []_eqn. Ltac decEq := match goal with | [ |- _ = _ ] => f_equal | [ |- (?X ?A <> ?X ?B) ] => cut (A <> B); [intro; congruence | try discriminate] end. Ltac byContradiction := cut False; [contradiction|idtac]. Ltac omegaContradiction := cut False; [contradiction|omega]. Lemma modusponens: forall (P Q: Prop), P -> (P -> Q) -> Q. Proof. auto. Qed. Ltac exploit x := refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _ _) _) || refine (modusponens _ _ (x _ _ _ _) _) || refine (modusponens _ _ (x _ _ _) _) || refine (modusponens _ _ (x _ _) _) || refine (modusponens _ _ (x _) _). (** * Definitions and theorems over the type [positive] *) Definition peq (x y: positive): {x = y} + {x <> y}. Proof. intros. caseEq (Pcompare x y Eq). intro. left. apply Pcompare_Eq_eq; auto. intro. right. red. intro. subst y. rewrite (Pcompare_refl x) in H. discriminate. intro. right. red. intro. subst y. rewrite (Pcompare_refl x) in H. discriminate. Qed. Lemma peq_true: forall (A: Type) (x: positive) (a b: A), (if peq x x then a else b) = a. Proof. intros. case (peq x x); intros. auto. elim n; auto. Qed. Lemma peq_false: forall (A: Type) (x y: positive) (a b: A), x <> y -> (if peq x y then a else b) = b. Proof. intros. case (peq x y); intros. elim H; auto. auto. Qed. Definition Plt (x y: positive): Prop := Zlt (Zpos x) (Zpos y). Lemma Plt_ne: forall (x y: positive), Plt x y -> x <> y. Proof. unfold Plt; intros. red; intro. subst y. omega. Qed. Hint Resolve Plt_ne: coqlib. Lemma Plt_trans: forall (x y z: positive), Plt x y -> Plt y z -> Plt x z. Proof. unfold Plt; intros; omega. Qed. Remark Psucc_Zsucc: forall (x: positive), Zpos (Psucc x) = Zsucc (Zpos x). Proof. intros. rewrite Pplus_one_succ_r. reflexivity. Qed. Lemma Plt_succ: forall (x: positive), Plt x (Psucc x). Proof. intro. unfold Plt. rewrite Psucc_Zsucc. omega. Qed. Hint Resolve Plt_succ: coqlib. Lemma Plt_trans_succ: forall (x y: positive), Plt x y -> Plt x (Psucc y). Proof. intros. apply Plt_trans with y. assumption. apply Plt_succ. Qed. Hint Resolve Plt_succ: coqlib. Lemma Plt_succ_inv: forall (x y: positive), Plt x (Psucc y) -> Plt x y \/ x = y. Proof. intros x y. unfold Plt. rewrite Psucc_Zsucc. intro. assert (A: (Zpos x < Zpos y)%Z \/ Zpos x = Zpos y). omega. elim A; intro. left; auto. right; injection H0; auto. Qed. Definition plt (x y: positive) : {Plt x y} + {~ Plt x y}. Proof. intros. unfold Plt. apply Z_lt_dec. Qed. Definition Ple (p q: positive) := Zle (Zpos p) (Zpos q). Lemma Ple_refl: forall (p: positive), Ple p p. Proof. unfold Ple; intros; omega. Qed. Lemma Ple_trans: forall (p q r: positive), Ple p q -> Ple q r -> Ple p r. Proof. unfold Ple; intros; omega. Qed. Lemma Plt_Ple: forall (p q: positive), Plt p q -> Ple p q. Proof. unfold Plt, Ple; intros; omega. Qed. Lemma Ple_succ: forall (p: positive), Ple p (Psucc p). Proof. intros. apply Plt_Ple. apply Plt_succ. Qed. Lemma Plt_Ple_trans: forall (p q r: positive), Plt p q -> Ple q r -> Plt p r. Proof. unfold Plt, Ple; intros; omega. Qed. Lemma Plt_strict: forall p, ~ Plt p p. Proof. unfold Plt; intros. omega. Qed. Hint Resolve Ple_refl Plt_Ple Ple_succ Plt_strict: coqlib. (** Peano recursion over positive numbers. *) Section POSITIVE_ITERATION. Lemma Plt_wf: well_founded Plt. Proof. apply well_founded_lt_compat with nat_of_P. intros. apply nat_of_P_lt_Lt_compare_morphism. exact H. Qed. Variable A: Type. Variable v1: A. Variable f: positive -> A -> A. Lemma Ppred_Plt: forall x, x <> xH -> Plt (Ppred x) x. Proof. intros. elim (Psucc_pred x); intro. contradiction. set (y := Ppred x) in *. rewrite <- H0. apply Plt_succ. Qed. Let iter (x: positive) (P: forall y, Plt y x -> A) : A := match peq x xH with | left EQ => v1 | right NOTEQ => f (Ppred x) (P (Ppred x) (Ppred_Plt x NOTEQ)) end. Definition positive_rec : positive -> A := Fix Plt_wf (fun _ => A) iter. Lemma unroll_positive_rec: forall x, positive_rec x = iter x (fun y _ => positive_rec y). Proof. unfold positive_rec. apply (Fix_eq Plt_wf (fun _ => A) iter). intros. unfold iter. case (peq x 1); intro. auto. decEq. apply H. Qed. Lemma positive_rec_base: positive_rec 1%positive = v1. Proof. rewrite unroll_positive_rec. unfold iter. case (peq 1 1); intro. auto. elim n; auto. Qed. Lemma positive_rec_succ: forall x, positive_rec (Psucc x) = f x (positive_rec x). Proof. intro. rewrite unroll_positive_rec. unfold iter. case (peq (Psucc x) 1); intro. destruct x; simpl in e; discriminate. rewrite Ppred_succ. auto. Qed. Lemma positive_Peano_ind: forall (P: positive -> Prop), P xH -> (forall x, P x -> P (Psucc x)) -> forall x, P x. Proof. intros. apply (well_founded_ind Plt_wf P). intros. case (peq x0 xH); intro. subst x0; auto. elim (Psucc_pred x0); intro. contradiction. rewrite <- H2. apply H0. apply H1. apply Ppred_Plt. auto. Qed. End POSITIVE_ITERATION. (** * Definitions and theorems over the type [Z] *) Definition zeq: forall (x y: Z), {x = y} + {x <> y} := Z_eq_dec. Lemma zeq_true: forall (A: Type) (x: Z) (a b: A), (if zeq x x then a else b) = a. Proof. intros. case (zeq x x); intros. auto. elim n; auto. Qed. Lemma zeq_false: forall (A: Type) (x y: Z) (a b: A), x <> y -> (if zeq x y then a else b) = b. Proof. intros. case (zeq x y); intros. elim H; auto. auto. Qed. Open Scope Z_scope. Definition zlt: forall (x y: Z), {x < y} + {x >= y} := Z_lt_ge_dec. Lemma zlt_true: forall (A: Type) (x y: Z) (a b: A), x < y -> (if zlt x y then a else b) = a. Proof. intros. case (zlt x y); intros. auto. omegaContradiction. Qed. Lemma zlt_false: forall (A: Type) (x y: Z) (a b: A), x >= y -> (if zlt x y then a else b) = b. Proof. intros. case (zlt x y); intros. omegaContradiction. auto. Qed. Definition zle: forall (x y: Z), {x <= y} + {x > y} := Z_le_gt_dec. Lemma zle_true: forall (A: Type) (x y: Z) (a b: A), x <= y -> (if zle x y then a else b) = a. Proof. intros. case (zle x y); intros. auto. omegaContradiction. Qed. Lemma zle_false: forall (A: Type) (x y: Z) (a b: A), x > y -> (if zle x y then a else b) = b. Proof. intros. case (zle x y); intros. omegaContradiction. auto. Qed. (** Properties of powers of two. *) Lemma two_power_nat_O : two_power_nat O = 1. Proof. reflexivity. Qed. Lemma two_power_nat_pos : forall n : nat, two_power_nat n > 0. Proof. induction n. rewrite two_power_nat_O. omega. rewrite two_power_nat_S. omega. Qed. Lemma two_power_nat_two_p: forall x, two_power_nat x = two_p (Z_of_nat x). Proof. induction x. auto. rewrite two_power_nat_S. rewrite inj_S. rewrite two_p_S. omega. omega. Qed. Lemma two_p_monotone: forall x y, 0 <= x <= y -> two_p x <= two_p y. Proof. intros. replace (two_p x) with (two_p x * 1) by omega. replace y with (x + (y - x)) by omega. rewrite two_p_is_exp; try omega. apply Zmult_le_compat_l. assert (two_p (y - x) > 0). apply two_p_gt_ZERO. omega. omega. assert (two_p x > 0). apply two_p_gt_ZERO. omega. omega. Qed. Lemma two_p_monotone_strict: forall x y, 0 <= x < y -> two_p x < two_p y. Proof. intros. assert (two_p x <= two_p (y - 1)). apply two_p_monotone; omega. assert (two_p (y - 1) > 0). apply two_p_gt_ZERO. omega. replace y with (Zsucc (y - 1)) by omega. rewrite two_p_S. omega. omega. Qed. Lemma two_p_strict: forall x, x >= 0 -> x < two_p x. Proof. intros x0 GT. pattern x0. apply natlike_ind. simpl. omega. intros. rewrite two_p_S; auto. generalize (two_p_gt_ZERO x H). omega. omega. Qed. Lemma two_p_strict_2: forall x, x >= 0 -> 2 * x - 1 < two_p x. Proof. intros. assert (x = 0 \/ x - 1 >= 0) by omega. destruct H0. subst. vm_compute. auto. replace (two_p x) with (2 * two_p (x - 1)). generalize (two_p_strict _ H0). omega. rewrite <- two_p_S. decEq. omega. omega. Qed. (** Properties of [Zmin] and [Zmax] *) Lemma Zmin_spec: forall x y, Zmin x y = if zlt x y then x else y. Proof. intros. case (zlt x y); unfold Zlt, Zge; intros. unfold Zmin. rewrite z. auto. unfold Zmin. caseEq (x ?= y); intro. apply Zcompare_Eq_eq. auto. contradiction. reflexivity. Qed. Lemma Zmax_spec: forall x y, Zmax x y = if zlt y x then x else y. Proof. intros. case (zlt y x); unfold Zlt, Zge; intros. unfold Zmax. rewrite <- (Zcompare_antisym y x). rewrite z. simpl. auto. unfold Zmax. rewrite <- (Zcompare_antisym y x). caseEq (y ?= x); intro; simpl. symmetry. apply Zcompare_Eq_eq. auto. contradiction. reflexivity. Qed. Lemma Zmax_bound_l: forall x y z, x <= y -> x <= Zmax y z. Proof. intros. generalize (Zmax1 y z). omega. Qed. Lemma Zmax_bound_r: forall x y z, x <= z -> x <= Zmax y z. Proof. intros. generalize (Zmax2 y z). omega. Qed. (** Properties of Euclidean division and modulus. *) Lemma Zdiv_small: forall x y, 0 <= x < y -> x / y = 0. Proof. intros. assert (y > 0). omega. assert (forall a b, 0 <= a < y -> 0 <= y * b + a < y -> b = 0). intros. assert (b = 0 \/ b > 0 \/ (-b) > 0). omega. elim H3; intro. auto. elim H4; intro. assert (y * b >= y * 1). apply Zmult_ge_compat_l. omega. omega. omegaContradiction. assert (y * (-b) >= y * 1). apply Zmult_ge_compat_l. omega. omega. rewrite <- Zopp_mult_distr_r in H6. omegaContradiction. apply H1 with (x mod y). apply Z_mod_lt. auto. rewrite <- Z_div_mod_eq. auto. auto. Qed. Lemma Zmod_small: forall x y, 0 <= x < y -> x mod y = x. Proof. intros. assert (y > 0). omega. generalize (Z_div_mod_eq x y H0). rewrite (Zdiv_small x y H). omega. Qed. Lemma Zmod_unique: forall x y a b, x = a * y + b -> 0 <= b < y -> x mod y = b. Proof. intros. subst x. rewrite Zplus_comm. rewrite Z_mod_plus. apply Zmod_small. auto. omega. Qed. Lemma Zdiv_unique: forall x y a b, x = a * y + b -> 0 <= b < y -> x / y = a. Proof. intros. subst x. rewrite Zplus_comm. rewrite Z_div_plus. rewrite (Zdiv_small b y H0). omega. omega. Qed. Lemma Zdiv_Zdiv: forall a b c, b > 0 -> c > 0 -> (a / b) / c = a / (b * c). Proof. intros. generalize (Z_div_mod_eq a b H). generalize (Z_mod_lt a b H). intros. generalize (Z_div_mod_eq (a/b) c H0). generalize (Z_mod_lt (a/b) c H0). intros. set (q1 := a / b) in *. set (r1 := a mod b) in *. set (q2 := q1 / c) in *. set (r2 := q1 mod c) in *. symmetry. apply Zdiv_unique with (r2 * b + r1). rewrite H2. rewrite H4. ring. split. assert (0 <= r2 * b). apply Zmult_le_0_compat. omega. omega. omega. assert ((r2 + 1) * b <= c * b). apply Zmult_le_compat_r. omega. omega. replace ((r2 + 1) * b) with (r2 * b + b) in H5 by ring. replace (c * b) with (b * c) in H5 by ring. omega. Qed. Lemma Zmult_le_compat_l_neg : forall n m p:Z, n >= m -> p <= 0 -> p * n <= p * m. Proof. intros. assert ((-p) * n >= (-p) * m). apply Zmult_ge_compat_l. auto. omega. replace (p * n) with (- ((-p) * n)) by ring. replace (p * m) with (- ((-p) * m)) by ring. omega. Qed. Lemma Zdiv_interval_1: forall lo hi a b, lo <= 0 -> hi > 0 -> b > 0 -> lo * b <= a < hi * b -> lo <= a/b < hi. Proof. intros. generalize (Z_div_mod_eq a b H1). generalize (Z_mod_lt a b H1). intros. set (q := a/b) in *. set (r := a mod b) in *. split. assert (lo < (q + 1)). apply Zmult_lt_reg_r with b. omega. apply Zle_lt_trans with a. omega. replace ((q + 1) * b) with (b * q + b) by ring. omega. omega. apply Zmult_lt_reg_r with b. omega. replace (q * b) with (b * q) by ring. omega. Qed. Lemma Zdiv_interval_2: forall lo hi a b, lo <= a <= hi -> lo <= 0 -> hi >= 0 -> b > 0 -> lo <= a/b <= hi. Proof. intros. assert (lo <= a / b < hi+1). apply Zdiv_interval_1. omega. omega. auto. assert (lo * b <= lo * 1). apply Zmult_le_compat_l_neg. omega. omega. replace (lo * 1) with lo in H3 by ring. assert ((hi + 1) * 1 <= (hi + 1) * b). apply Zmult_le_compat_l. omega. omega. replace ((hi + 1) * 1) with (hi + 1) in H4 by ring. omega. omega. Qed. Lemma Zmod_recombine: forall x a b, a > 0 -> b > 0 -> x mod (a * b) = ((x/b) mod a) * b + (x mod b). Proof. intros. set (xb := x/b). apply Zmod_unique with (xb/a). generalize (Z_div_mod_eq x b H0); fold xb; intro EQ1. generalize (Z_div_mod_eq xb a H); intro EQ2. rewrite EQ2 in EQ1. eapply trans_eq. eexact EQ1. ring. generalize (Z_mod_lt x b H0). intro. generalize (Z_mod_lt xb a H). intro. assert (0 <= xb mod a * b <= a * b - b). split. apply Zmult_le_0_compat; omega. replace (a * b - b) with ((a - 1) * b) by ring. apply Zmult_le_compat; omega. omega. Qed. (** Properties of divisibility. *) Lemma Zdivides_trans: forall x y z, (x | y) -> (y | z) -> (x | z). Proof. intros. inv H. inv H0. exists (q0 * q). ring. Qed. Definition Zdivide_dec: forall (p q: Z), p > 0 -> { (p|q) } + { ~(p|q) }. Proof. intros. destruct (zeq (Zmod q p) 0). left. exists (q / p). transitivity (p * (q / p) + (q mod p)). apply Z_div_mod_eq; auto. transitivity (p * (q / p)). omega. ring. right; red; intros. elim n. apply Z_div_exact_1; auto. inv H0. rewrite Z_div_mult; auto. ring. Qed. (** Conversion from [Z] to [nat]. *) Definition nat_of_Z (z: Z) : nat := match z with | Z0 => O | Zpos p => nat_of_P p | Zneg p => O end. Lemma nat_of_Z_of_nat: forall n, nat_of_Z (Z_of_nat n) = n. Proof. intros. unfold Z_of_nat. destruct n. auto. simpl. rewrite nat_of_P_o_P_of_succ_nat_eq_succ. auto. Qed. Lemma nat_of_Z_max: forall z, Z_of_nat (nat_of_Z z) = Zmax z 0. Proof. intros. unfold Zmax. destruct z; simpl; auto. symmetry. apply Zpos_eq_Z_of_nat_o_nat_of_P. Qed. Lemma nat_of_Z_eq: forall z, z >= 0 -> Z_of_nat (nat_of_Z z) = z. Proof. intros. rewrite nat_of_Z_max. apply Zmax_left. auto. Qed. Lemma nat_of_Z_neg: forall n, n <= 0 -> nat_of_Z n = O. Proof. destruct n; unfold Zle; simpl; auto. congruence. Qed. Lemma nat_of_Z_plus: forall p q, p >= 0 -> q >= 0 -> nat_of_Z (p + q) = (nat_of_Z p + nat_of_Z q)%nat. Proof. intros. apply inj_eq_rev. rewrite inj_plus. repeat rewrite nat_of_Z_eq; auto. omega. Qed. (** Alignment: [align n amount] returns the smallest multiple of [amount] greater than or equal to [n]. *) Definition align (n: Z) (amount: Z) := ((n + amount - 1) / amount) * amount. Lemma align_le: forall x y, y > 0 -> x <= align x y. Proof. intros. unfold align. generalize (Z_div_mod_eq (x + y - 1) y H). intro. replace ((x + y - 1) / y * y) with ((x + y - 1) - (x + y - 1) mod y). generalize (Z_mod_lt (x + y - 1) y H). omega. rewrite Zmult_comm. omega. Qed. Lemma align_divides: forall x y, y > 0 -> (y | align x y). Proof. intros. unfold align. apply Zdivide_factor_l. Qed. (** * Definitions and theorems on the data types [option], [sum] and [list] *) Set Implicit Arguments. (** Mapping a function over an option type. *) Definition option_map (A B: Type) (f: A -> B) (x: option A) : option B := match x with | None => None | Some y => Some (f y) end. (** Mapping a function over a sum type. *) Definition sum_left_map (A B C: Type) (f: A -> B) (x: A + C) : B + C := match x with | inl y => inl C (f y) | inr z => inr B z end. (** Properties of [List.nth] (n-th element of a list). *) Hint Resolve in_eq in_cons: coqlib. Lemma nth_error_in: forall (A: Type) (n: nat) (l: list A) (x: A), List.nth_error l n = Some x -> In x l. Proof. induction n; simpl. destruct l; intros. discriminate. injection H; intro; subst a. apply in_eq. destruct l; intros. discriminate. apply in_cons. auto. Qed. Hint Resolve nth_error_in: coqlib. Lemma nth_error_nil: forall (A: Type) (idx: nat), nth_error (@nil A) idx = None. Proof. induction idx; simpl; intros; reflexivity. Qed. Hint Resolve nth_error_nil: coqlib. (** Compute the length of a list, with result in [Z]. *) Fixpoint list_length_z_aux (A: Type) (l: list A) (acc: Z) {struct l}: Z := match l with | nil => acc | hd :: tl => list_length_z_aux tl (Zsucc acc) end. Remark list_length_z_aux_shift: forall (A: Type) (l: list A) n m, list_length_z_aux l n = list_length_z_aux l m + (n - m). Proof. induction l; intros; simpl. omega. replace (n - m) with (Zsucc n - Zsucc m) by omega. auto. Qed. Definition list_length_z (A: Type) (l: list A) : Z := list_length_z_aux l 0. Lemma list_length_z_cons: forall (A: Type) (hd: A) (tl: list A), list_length_z (hd :: tl) = list_length_z tl + 1. Proof. intros. unfold list_length_z. simpl. rewrite (list_length_z_aux_shift tl 1 0). omega. Qed. Lemma list_length_z_pos: forall (A: Type) (l: list A), list_length_z l >= 0. Proof. induction l; simpl. unfold list_length_z; simpl. omega. rewrite list_length_z_cons. omega. Qed. Lemma list_length_z_map: forall (A B: Type) (f: A -> B) (l: list A), list_length_z (map f l) = list_length_z l. Proof. induction l. reflexivity. simpl. repeat rewrite list_length_z_cons. congruence. Qed. (** Extract the n-th element of a list, as [List.nth_error] does, but the index [n] is of type [Z]. *) Fixpoint list_nth_z (A: Type) (l: list A) (n: Z) {struct l}: option A := match l with | nil => None | hd :: tl => if zeq n 0 then Some hd else list_nth_z tl (Zpred n) end. Lemma list_nth_z_in: forall (A: Type) (l: list A) n x, list_nth_z l n = Some x -> In x l. Proof. induction l; simpl; intros. congruence. destruct (zeq n 0). left; congruence. right; eauto. Qed. Lemma list_nth_z_map: forall (A B: Type) (f: A -> B) (l: list A) n, list_nth_z (List.map f l) n = option_map f (list_nth_z l n). Proof. induction l; simpl; intros. auto. destruct (zeq n 0). auto. eauto. Qed. Lemma list_nth_z_range: forall (A: Type) (l: list A) n x, list_nth_z l n = Some x -> 0 <= n < list_length_z l. Proof. induction l; simpl; intros. discriminate. rewrite list_length_z_cons. destruct (zeq n 0). generalize (list_length_z_pos l); omega. exploit IHl; eauto. unfold Zpred. omega. Qed. (** Properties of [List.incl] (list inclusion). *) Lemma incl_cons_inv: forall (A: Type) (a: A) (b c: list A), incl (a :: b) c -> incl b c. Proof. unfold incl; intros. apply H. apply in_cons. auto. Qed. Hint Resolve incl_cons_inv: coqlib. Lemma incl_app_inv_l: forall (A: Type) (l1 l2 m: list A), incl (l1 ++ l2) m -> incl l1 m. Proof. unfold incl; intros. apply H. apply in_or_app. left; assumption. Qed. Lemma incl_app_inv_r: forall (A: Type) (l1 l2 m: list A), incl (l1 ++ l2) m -> incl l2 m. Proof. unfold incl; intros. apply H. apply in_or_app. right; assumption. Qed. Hint Resolve incl_tl incl_refl incl_app_inv_l incl_app_inv_r: coqlib. Lemma incl_same_head: forall (A: Type) (x: A) (l1 l2: list A), incl l1 l2 -> incl (x::l1) (x::l2). Proof. intros; red; simpl; intros. intuition. Qed. (** Properties of [List.map] (mapping a function over a list). *) Lemma list_map_exten: forall (A B: Type) (f f': A -> B) (l: list A), (forall x, In x l -> f x = f' x) -> List.map f' l = List.map f l. Proof. induction l; simpl; intros. reflexivity. rewrite <- H. rewrite IHl. reflexivity. intros. apply H. tauto. tauto. Qed. Lemma list_map_compose: forall (A B C: Type) (f: A -> B) (g: B -> C) (l: list A), List.map g (List.map f l) = List.map (fun x => g(f x)) l. Proof. induction l; simpl. reflexivity. rewrite IHl; reflexivity. Qed. Lemma list_map_identity: forall (A: Type) (l: list A), List.map (fun (x:A) => x) l = l. Proof. induction l; simpl; congruence. Qed. Lemma list_map_nth: forall (A B: Type) (f: A -> B) (l: list A) (n: nat), nth_error (List.map f l) n = option_map f (nth_error l n). Proof. induction l; simpl; intros. repeat rewrite nth_error_nil. reflexivity. destruct n; simpl. reflexivity. auto. Qed. Lemma list_length_map: forall (A B: Type) (f: A -> B) (l: list A), List.length (List.map f l) = List.length l. Proof. induction l; simpl; congruence. Qed. Lemma list_in_map_inv: forall (A B: Type) (f: A -> B) (l: list A) (y: B), In y (List.map f l) -> exists x:A, y = f x /\ In x l. Proof. induction l; simpl; intros. contradiction. elim H; intro. exists a; intuition auto. generalize (IHl y H0). intros [x [EQ IN]]. exists x; tauto. Qed. Lemma list_append_map: forall (A B: Type) (f: A -> B) (l1 l2: list A), List.map f (l1 ++ l2) = List.map f l1 ++ List.map f l2. Proof. induction l1; simpl; intros. auto. rewrite IHl1. auto. Qed. Lemma list_append_map_inv: forall (A B: Type) (f: A -> B) (m1 m2: list B) (l: list A), List.map f l = m1 ++ m2 -> exists l1, exists l2, List.map f l1 = m1 /\ List.map f l2 = m2 /\ l = l1 ++ l2. Proof. induction m1; simpl; intros. exists (@nil A); exists l; auto. destruct l; simpl in H; inv H. exploit IHm1; eauto. intros [l1 [l2 [P [Q R]]]]. subst l. exists (a0 :: l1); exists l2; intuition. simpl; congruence. Qed. (** Properties of list membership. *) Lemma in_cns: forall (A: Type) (x y: A) (l: list A), In x (y :: l) <-> y = x \/ In x l. Proof. intros. simpl. tauto. Qed. Lemma in_app: forall (A: Type) (x: A) (l1 l2: list A), In x (l1 ++ l2) <-> In x l1 \/ In x l2. Proof. intros. split; intro. apply in_app_or. auto. apply in_or_app. auto. Qed. Lemma list_in_insert: forall (A: Type) (x: A) (l1 l2: list A) (y: A), In x (l1 ++ l2) -> In x (l1 ++ y :: l2). Proof. intros. apply in_or_app; simpl. elim (in_app_or _ _ _ H); intro; auto. Qed. (** [list_disjoint l1 l2] holds iff [l1] and [l2] have no elements in common. *) Definition list_disjoint (A: Type) (l1 l2: list A) : Prop := forall (x y: A), In x l1 -> In y l2 -> x <> y. Lemma list_disjoint_cons_left: forall (A: Type) (a: A) (l1 l2: list A), list_disjoint (a :: l1) l2 -> list_disjoint l1 l2. Proof. unfold list_disjoint; simpl; intros. apply H; tauto. Qed. Lemma list_disjoint_cons_right: forall (A: Type) (a: A) (l1 l2: list A), list_disjoint l1 (a :: l2) -> list_disjoint l1 l2. Proof. unfold list_disjoint; simpl; intros. apply H; tauto. Qed. Lemma list_disjoint_notin: forall (A: Type) (l1 l2: list A) (a: A), list_disjoint l1 l2 -> In a l1 -> ~(In a l2). Proof. unfold list_disjoint; intros; red; intros. apply H with a a; auto. Qed. Lemma list_disjoint_sym: forall (A: Type) (l1 l2: list A), list_disjoint l1 l2 -> list_disjoint l2 l1. Proof. unfold list_disjoint; intros. apply sym_not_equal. apply H; auto. Qed. Lemma list_disjoint_dec: forall (A: Type) (eqA_dec: forall (x y: A), {x=y} + {x<>y}) (l1 l2: list A), {list_disjoint l1 l2} + {~list_disjoint l1 l2}. Proof. induction l1; intros. left; red; intros. elim H. case (In_dec eqA_dec a l2); intro. right; red; intro. apply (H a a); auto with coqlib. case (IHl1 l2); intro. left; red; intros. elim H; intro. red; intro; subst a y. contradiction. apply l; auto. right; red; intros. elim n0. eapply list_disjoint_cons_left; eauto. Defined. (** [list_equiv l1 l2] holds iff the lists [l1] and [l2] contain the same elements. *) Definition list_equiv (A : Type) (l1 l2: list A) : Prop := forall x, In x l1 <-> In x l2. (** [list_norepet l] holds iff the list [l] contains no repetitions, i.e. no element occurs twice. *) Inductive list_norepet (A: Type) : list A -> Prop := | list_norepet_nil: list_norepet nil | list_norepet_cons: forall hd tl, ~(In hd tl) -> list_norepet tl -> list_norepet (hd :: tl). Lemma list_norepet_dec: forall (A: Type) (eqA_dec: forall (x y: A), {x=y} + {x<>y}) (l: list A), {list_norepet l} + {~list_norepet l}. Proof. induction l. left; constructor. destruct IHl. case (In_dec eqA_dec a l); intro. right. red; intro. inversion H. contradiction. left. constructor; auto. right. red; intro. inversion H. contradiction. Defined. Lemma list_map_norepet: forall (A B: Type) (f: A -> B) (l: list A), list_norepet l -> (forall x y, In x l -> In y l -> x <> y -> f x <> f y) -> list_norepet (List.map f l). Proof. induction 1; simpl; intros. constructor. constructor. red; intro. generalize (list_in_map_inv f _ _ H2). intros [x [EQ IN]]. generalize EQ. change (f hd <> f x). apply H1. tauto. tauto. red; intro; subst x. contradiction. apply IHlist_norepet. intros. apply H1. tauto. tauto. auto. Qed. Remark list_norepet_append_commut: forall (A: Type) (a b: list A), list_norepet (a ++ b) -> list_norepet (b ++ a). Proof. intro A. assert (forall (x: A) (b: list A) (a: list A), list_norepet (a ++ b) -> ~(In x a) -> ~(In x b) -> list_norepet (a ++ x :: b)). induction a; simpl; intros. constructor; auto. inversion H. constructor. red; intro. elim (in_app_or _ _ _ H6); intro. elim H4. apply in_or_app. tauto. elim H7; intro. subst a. elim H0. left. auto. elim H4. apply in_or_app. tauto. auto. induction a; simpl; intros. rewrite <- app_nil_end. auto. inversion H0. apply H. auto. red; intro; elim H3. apply in_or_app. tauto. red; intro; elim H3. apply in_or_app. tauto. Qed. Lemma list_norepet_app: forall (A: Type) (l1 l2: list A), list_norepet (l1 ++ l2) <-> list_norepet l1 /\ list_norepet l2 /\ list_disjoint l1 l2. Proof. induction l1; simpl; intros; split; intros. intuition. constructor. red;simpl;auto. tauto. inversion H; subst. rewrite IHl1 in H3. rewrite in_app in H2. intuition. constructor; auto. red; intros. elim H2; intro. congruence. auto. destruct H as [B [C D]]. inversion B; subst. constructor. rewrite in_app. intuition. elim (D a a); auto. apply in_eq. rewrite IHl1. intuition. red; intros. apply D; auto. apply in_cons; auto. Qed. Lemma list_norepet_append: forall (A: Type) (l1 l2: list A), list_norepet l1 -> list_norepet l2 -> list_disjoint l1 l2 -> list_norepet (l1 ++ l2). Proof. generalize list_norepet_app; firstorder. Qed. Lemma list_norepet_append_right: forall (A: Type) (l1 l2: list A), list_norepet (l1 ++ l2) -> list_norepet l2. Proof. generalize list_norepet_app; firstorder. Qed. Lemma list_norepet_append_left: forall (A: Type) (l1 l2: list A), list_norepet (l1 ++ l2) -> list_norepet l1. Proof. generalize list_norepet_app; firstorder. Qed. (** [is_tail l1 l2] holds iff [l2] is of the form [l ++ l1] for some [l]. *) Inductive is_tail (A: Type): list A -> list A -> Prop := | is_tail_refl: forall c, is_tail c c | is_tail_cons: forall i c1 c2, is_tail c1 c2 -> is_tail c1 (i :: c2). Lemma is_tail_in: forall (A: Type) (i: A) c1 c2, is_tail (i :: c1) c2 -> In i c2. Proof. induction c2; simpl; intros. inversion H. inversion H. tauto. right; auto. Qed. Lemma is_tail_cons_left: forall (A: Type) (i: A) c1 c2, is_tail (i :: c1) c2 -> is_tail c1 c2. Proof. induction c2; intros; inversion H. constructor. constructor. constructor. auto. Qed. Hint Resolve is_tail_refl is_tail_cons is_tail_in is_tail_cons_left: coqlib. Lemma is_tail_incl: forall (A: Type) (l1 l2: list A), is_tail l1 l2 -> incl l1 l2. Proof. induction 1; eauto with coqlib. Qed. Lemma is_tail_trans: forall (A: Type) (l1 l2: list A), is_tail l1 l2 -> forall (l3: list A), is_tail l2 l3 -> is_tail l1 l3. Proof. induction 1; intros. auto. apply IHis_tail. eapply is_tail_cons_left; eauto. Qed. (** [list_forall2 P [x1 ... xN] [y1 ... yM]] holds iff [N = M] and [P xi yi] holds for all [i]. *) Section FORALL2. Variable A: Type. Variable B: Type. Variable P: A -> B -> Prop. Inductive list_forall2: list A -> list B -> Prop := | list_forall2_nil: list_forall2 nil nil | list_forall2_cons: forall a1 al b1 bl, P a1 b1 -> list_forall2 al bl -> list_forall2 (a1 :: al) (b1 :: bl). Lemma list_forall2_app: forall a2 b2 a1 b1, list_forall2 a1 b1 -> list_forall2 a2 b2 -> list_forall2 (a1 ++ a2) (b1 ++ b2). Proof. induction 1; intros; simpl. auto. constructor; auto. Qed. Lemma list_forall2_length: forall l1 l2, list_forall2 l1 l2 -> length l1 = length l2. Proof. induction 1; simpl; congruence. Qed. End FORALL2. Lemma list_forall2_imply: forall (A B: Type) (P1: A -> B -> Prop) (l1: list A) (l2: list B), list_forall2 P1 l1 l2 -> forall (P2: A -> B -> Prop), (forall v1 v2, In v1 l1 -> In v2 l2 -> P1 v1 v2 -> P2 v1 v2) -> list_forall2 P2 l1 l2. Proof. induction 1; intros. constructor. constructor. auto with coqlib. apply IHlist_forall2; auto. intros. auto with coqlib. Qed. (** Dropping the first N elements of a list. *) Fixpoint list_drop (A: Type) (n: nat) (x: list A) {struct n} : list A := match n with | O => x | S n' => match x with nil => nil | hd :: tl => list_drop n' tl end end. Lemma list_drop_incl: forall (A: Type) (x: A) n (l: list A), In x (list_drop n l) -> In x l. Proof. induction n; simpl; intros. auto. destruct l; auto with coqlib. Qed. Lemma list_drop_norepet: forall (A: Type) n (l: list A), list_norepet l -> list_norepet (list_drop n l). Proof. induction n; simpl; intros. auto. inv H. constructor. auto. Qed. Lemma list_map_drop: forall (A B: Type) (f: A -> B) n (l: list A), list_drop n (map f l) = map f (list_drop n l). Proof. induction n; simpl; intros. auto. destruct l; simpl; auto. Qed. (** A list of [n] elements, all equal to [x]. *) Fixpoint list_repeat {A: Type} (n: nat) (x: A) {struct n} := match n with | O => nil | S m => x :: list_repeat m x end. Lemma length_list_repeat: forall (A: Type) n (x: A), length (list_repeat n x) = n. Proof. induction n; simpl; intros. auto. decEq; auto. Qed. Lemma in_list_repeat: forall (A: Type) n (x: A) y, In y (list_repeat n x) -> y = x. Proof. induction n; simpl; intros. elim H. destruct H; auto. Qed. (** * Definitions and theorems over boolean types *) Definition proj_sumbool (P Q: Prop) (a: {P} + {Q}) : bool := if a then true else false. Implicit Arguments proj_sumbool [P Q]. Coercion proj_sumbool: sumbool >-> bool. Lemma proj_sumbool_true: forall (P Q: Prop) (a: {P}+{Q}), proj_sumbool a = true -> P. Proof. intros P Q a. destruct a; simpl. auto. congruence. Qed. Lemma proj_sumbool_is_true: forall (P: Prop) (a: {P}+{~P}), P -> proj_sumbool a = true. Proof. intros. unfold proj_sumbool. destruct a. auto. contradiction. Qed. Section DECIDABLE_EQUALITY. Variable A: Type. Variable dec_eq: forall (x y: A), {x=y} + {x<>y}. Variable B: Type. Lemma dec_eq_true: forall (x: A) (ifso ifnot: B), (if dec_eq x x then ifso else ifnot) = ifso. Proof. intros. destruct (dec_eq x x). auto. congruence. Qed. Lemma dec_eq_false: forall (x y: A) (ifso ifnot: B), x <> y -> (if dec_eq x y then ifso else ifnot) = ifnot. Proof. intros. destruct (dec_eq x y). congruence. auto. Qed. Lemma dec_eq_sym: forall (x y: A) (ifso ifnot: B), (if dec_eq x y then ifso else ifnot) = (if dec_eq y x then ifso else ifnot). Proof. intros. destruct (dec_eq x y). subst y. rewrite dec_eq_true. auto. rewrite dec_eq_false; auto. Qed. End DECIDABLE_EQUALITY. Section DECIDABLE_PREDICATE. Variable P: Prop. Variable dec: {P} + {~P}. Variable A: Type. Lemma pred_dec_true: forall (a b: A), P -> (if dec then a else b) = a. Proof. intros. destruct dec. auto. contradiction. Qed. Lemma pred_dec_false: forall (a b: A), ~P -> (if dec then a else b) = b. Proof. intros. destruct dec. contradiction. auto. Qed. End DECIDABLE_PREDICATE. (** * Well-founded orderings *) Require Import Relations. (** A non-dependent version of lexicographic ordering. *) Section LEX_ORDER. Variable A: Type. Variable B: Type. Variable ordA: A -> A -> Prop. Variable ordB: B -> B -> Prop. Inductive lex_ord: A*B -> A*B -> Prop := | lex_ord_left: forall a1 b1 a2 b2, ordA a1 a2 -> lex_ord (a1,b1) (a2,b2) | lex_ord_right: forall a b1 b2, ordB b1 b2 -> lex_ord (a,b1) (a,b2). Lemma wf_lex_ord: well_founded ordA -> well_founded ordB -> well_founded lex_ord. Proof. intros Awf Bwf. assert (forall a, Acc ordA a -> forall b, Acc ordB b -> Acc lex_ord (a, b)). induction 1. induction 1. constructor; intros. inv H3. apply H0. auto. apply Bwf. apply H2; auto. red; intros. destruct a as [a b]. apply H; auto. Qed. Lemma transitive_lex_ord: transitive _ ordA -> transitive _ ordB -> transitive _ lex_ord. Proof. intros trA trB; red; intros. inv H; inv H0. left; eapply trA; eauto. left; auto. left; auto. right; eapply trB; eauto. Qed. End LEX_ORDER.
\section{Results} \subsection{Minimal model of transcriptional regulation}\label{sec_model} As a tractable circuit for which we have control over the parameters both theoretically and experimentally, we chose the so-called simple repression motif, a common regulatory scheme among prokaryotes \cite{Rydenfelt2014}. This circuit consists of a single promoter with an RNA-polymerase (RNAP) binding site and a single binding site for a transcriptional repressor \cite{Garcia2011c}. The regulation due to the repressor occurs via exclusion of the RNAP from its binding site when the repressor is bound, decreasing the likelihood of having a transcription event. As with many important macromolecules, we consider the repressor to be allosteric, meaning that it can exist in two conformations, one in which the repressor is able to bind to the specific binding site (active state) and one in which it cannot bind the specific binding site (inactive state). The environmental signaling occurs via passive import of an extracellular inducer that binds the repressor, shifting the equilibrium between the two conformations of the repressor \cite{Razo-Mejia2018}. In previous work we have extensively characterized the mean response of this circuit under different conditions using equilibrium based models \cite{Phillips2019}. Here we build upon these models to characterize the full distribution of gene expression with parameters such as repressor copy number and its affinity for the DNA being systematically varied. As the copy number of molecular species is a discrete quantity, chemical master equations have emerged as a useful tool to model their inherent probability distribution \cite{Sanchez2013}. In \fref{fig2_minimal_model}(A) we show the minimal model and the necessary set of parameters needed to compute the full distribution of mRNA and its protein gene product. Specifically, we assume a three-state model where the promoter can be found in a 1) transcriptionally active state ($A$ state), 2) a transcriptionally inactive state without the repressor bound ($I$ state) and 3) a transcriptionally inactive state with the repressor bound ($R$ state). We do not assume that the transition between the active state $A$ and the inactive state $I$ occurs due to RNAP binding to the promoter as the transcription initiation kinetics involve several more steps than simple binding \cite{Browning2004}. We coarse-grain all these steps into effective ``on" and ``off" states for the promoter, consistent with experiments demonstrating the bursty nature of gene expression in {\it E. coli} \cite{Golding2005}. These three states generate a system of coupled differential equations for each of the three state distributions $P_A(m, p; t)$, $P_I(m, p; t)$ and $P_R(m, p; t)$, where $m$ and $p$ are the mRNA and protein count per cell, respectively and $t$ is time. Given the rates depicted in \fref{fig2_minimal_model}(A) we define the system of ODEs for a specific $m$ and $p$. For the transcriptionally active state, we have \begin{equation} \begin{aligned} \dt{P_A(m, p)} &= - \overbrace{\kpoff P_A(m, p)}^{A \rightarrow I} % A -> I + \overbrace{\kpon P_I(m, p)}^{I \rightarrow A}\\ % I -> A &+ \overbrace{r_m P_A(m-1, p)}^{m-1 \rightarrow m} % m-1 -> m - \overbrace{r_m P_A(m, p)}^{m \rightarrow m+1}% m -> m+1 + \overbrace{\gm (m + 1) P_A(m+1 , p)}^{m+1 \rightarrow m} % m+1 -> m - \overbrace{\gm m P_A(m , p)}^{m \rightarrow m-1}\\ % m -> m-1 &+ \overbrace{r_p m P_A(m, p - 1)}^{p-1 \rightarrow p} % p-1 -> p - \overbrace{r_p m P_A(m, p)}^{p \rightarrow p+1} % p -> p+1 + \overbrace{\gp (p + 1) P_A(m, p + 1)}^{p + 1 \rightarrow p} % p+1 -> p - \overbrace{\gp p P_A(m, p)}^{p \rightarrow p-1}, % p -> p-1 \end{aligned} \end{equation} where the state transitions for each term are labeled by overbraces. For the transcriptionally inactive state $I$, we have \begin{equation} \begin{aligned} \dt{P_I(m, p)} &= \overbrace{\kpoff P_A(m, p)}^{A \rightarrow I} % A -> I - \overbrace{\kpon P_I(m, p)}^{I \rightarrow A} % I -> A + \overbrace{\kroff P_R(m, p)}^{R \rightarrow I} % R -> I - \overbrace{\kron P_I(m, p)}^{I \rightarrow R}\\ % I -> R &+ \overbrace{\gm (m + 1) P_I(m+1 , p)}^{m+1 \rightarrow m} % m+1 -> m - \overbrace{\gm m P_I(m , p)}^{m \rightarrow m-1}\\ % m -> m-1 &+ \overbrace{r_p m P_I(m, p - 1)}^{p-1 \rightarrow p} % p-1 -> p - \overbrace{r_p m P_I(m, p)}^{p \rightarrow p+1} % p -> p+1 + \overbrace{\gp (p + 1) P_I(m, p + 1)}^{p + 1 \rightarrow p} % p+1 -> p - \overbrace{\gp p P_I(m, p)}^{p \rightarrow p-1}. % p -> p-1 \end{aligned} \end{equation} And finally, for the repressor bound state $R$, \begin{equation} \begin{aligned} \dt{P_R(m, p)} &= - \overbrace{\kroff P_R(m, p)}^{R \rightarrow I} % R -> I + \overbrace{\kron P_I(m, p)}^{I \rightarrow R}\\ % I -> R &+ \overbrace{\gm (m + 1) P_R(m+1 , p)}^{m+1 \rightarrow m} % m+1 -> m - \overbrace{\gm m P_R(m , p)}^{m \rightarrow m-1}\\ % m -> m-1 &+ \overbrace{r_p m P_R(m, p - 1)}^{p-1 \rightarrow p} % p-1 -> p - \overbrace{r_p m P_R(m, p)}^{p \rightarrow p+1} % p -> p+1 + \overbrace{\gp (p + 1) P_R(m, p + 1)}^{p + 1 \rightarrow p} % p+1 -> p - \overbrace{\gp p P_R(m, p)}^{p \rightarrow p-1}. % p -> p-1 \end{aligned} \end{equation} As we will discuss later in \secref{sec_cell_cycle} the protein degradation term $\gp$ is set to zero since active protein degradation is slow compared to the cell cycle of exponentially growing bacteria, but rather we explicitly implement binomial partitioning of the proteins into daughter cells upon division \cite{Maurizi1992}. It is convenient to rewrite these equations in a compact matrix notation \cite{Sanchez2013}. For this we define the vector $\PP(m, p)$ as \begin{equation} \PP(m, p) = (P_A(m, p), P_I(m, p), P_R(m, p))^T, \end{equation} where $^T$ is the transpose. By defining the matrices $\Km$ to contain the promoter state transitions, $\Rm$ and $\Gm$ to contain the mRNA production and degradation terms, respectively, and $\Rp$ and $\Gp$ to contain the protein production and degradation terms, respectively, the system of ODEs can then be written as (See \siref{supp_model} for full definition of these matrices) \begin{equation} \begin{aligned} \dt{\PP(m, p)} &= \left( \Km -\Rm -m\Gm -m\Rp -p\Gp \right) \PP(m, p)\\ &+ \Rm \PP(m-1, p) + (m + 1) \Gm \PP(m + 1, p)\\ &+ m \Rp \PP(m, p - 1) + (p + 1) \Gp \PP(m, p + 1). \end{aligned} \label{eq_cme_matrix} \end{equation} Having defined the gene expression dynamics we now proceed to determine all rate parameters in \eref{eq_cme_matrix}. \subsection{Inferring parameters from published data sets} \label{sec_param} A decade of research in our group has characterized the simple repression motif with an ever expanding array of predictions and corresponding experiments to uncover the physics of this genetic circuit \cite{Phillips2019}. In doing so we have come to understand the mean response of a single promoter in the presence of varying levels of repressor copy numbers and repressor-DNA affinities \cite{Garcia2011c}, due to the effect that competing binding sites and multiple promoter copies impose \cite{Brewster2014}, and in recent work, assisted by the Monod-Wyman-Changeux (MWC) model, we expanded the scope to the allosteric nature of the repressor \cite{Razo-Mejia2018}. All of these studies have exploited the simplicity and predictive power of equilibrium approximations to these non-equilibrium systems \cite{Buchler2003}. We have also used a similar kinetic model to that depicted in \fref{fig2_minimal_model}(A) to study the noise in mRNA copy number \cite{Jones2014a}. Although these studies focus on the same experimental system described by different theoretical frameworks, in earlier work in our laboratory an attempt to unite parametric knowledge across studies based on equilibrium and non-equilibrium models has not been performed previously. As a test case of the depth of our theoretical understanding of this simple transcriptional regulation system we combine all of the studies mentioned above to inform the parameter values of the model presented in \fref{fig2_minimal_model}(A). \fref{fig2_minimal_model}(B) schematizes the data sets and experimental techniques used to measure gene expression along with the parameters that can be inferred from them. \siref{supp_param_inference} expands on the details of how the inference was performed for each of the parameters. Briefly, the promoter activation and inactivation rates $\kpon$ and $\kpoff$, as well as the transcription rate $r_m$ were obtained in units of the mRNA degradation rate $\gm$ by fitting a two-state promoter model (no state $R$ from \fref{fig2_minimal_model}(A)) \cite{Peccoud1995} to mRNA FISH data of an unregulated promoter (no repressor present in the cell) \cite{Jones2014a}. The repressor on rate is assumed to be of the form $\kron = k_o [R]$ where $k_o$ is a diffusion-limited on rate and $[R]$ is the concentration of active repressor in the cell \cite{Jones2014a}. This concentration of active repressor is at the same time determined by the repressor copy number in the cell, and the fraction of these repressors that are in the active state, i.e. able to bind DNA. Existing estimates of the transition rates between conformations of allosteric molecules set them at the microsecond scale \cite{Cui2008}. By considering this to be representative for our repressor of interest, the separation of time-scales between the rapid conformational changes of the repressor and the slower downstream processes such as the open-complex formation processes allow us to model the probability of the repressor being in the active state as an equilibrium MWC process. The parameters of the MWC model $K_A$, $K_I$ and $\eAI$ were previously characterized from video-microscopy and flow-cytometry data \cite{Razo-Mejia2018}. For the repressor off rate, $\kroff$, we take advantage of the fact that the mean mRNA copy number as derived from the model in \fref{fig2_minimal_model}(A) cast in the language of rates is of the same functional form as the equilibrium model cast in the language of binding energies \cite{Phillips2015}. Therefore the value of the repressor-DNA binding energy $\eR$ constrains the value of the repressor off rate $\kroff$. These constraints on the rates allow us to make self-consistent predictions under both the equilibrium and the kinetic framework. Having all parameters in hand, we can now proceed to solve the gene expression dynamics. \begin{figure}[h!] \centering \includegraphics {./fig/main/fig2_parameter_inference.pdf} \caption{\textbf{Minimal kinetic model of transcriptional regulation for a simple repression architecture.} (A) Three-state promoter stochastic model of transcriptional regulation by a repressor. The regulation by the repressor occurs via exclusion of the transcription initiation machinery, not allowing the promoter to transition to the transcriptionally active state. All parameters highlighted with colored boxes were determined from published datasets based on the same genetic circuit. Parameters in dashed boxes were taken directly from values reported in the literature or adjusted to satisfy known biological restrictions. (B) Data sets used to infer the parameter values. From left to right Garcia \& Phillips \cite{Garcia2011c} is used to determine $\kroff$ and $\kron$, Brewster et al. \cite{Brewster2014} is used to determine $\eAI$ and $\kron$, Razo-Mejia et al. \cite{Razo-Mejia2018} is used to determine $K_A$, $K_I$, and $\kron$ and Jones et al. \cite{Jones2014a} is used to determine $r_m$, $\kpon$, and $\kpoff$.} \label{fig2_minimal_model} \end{figure}
import tactic -- tactic mode import data.real.basic -- the real numbers example (a b : ℝ) : (a+b)^3=a^3+3*a^2*b+3*a*b^2+b^3 := begin ring, end
{-# OPTIONS --allow-unsolved-metas #-} module lambda.system-d where open import Data.Nat open import Data.Fin hiding (lift) open import lambda.vec open import lambda.untyped infixr 21 _∧_ infixr 22 _⇒_ data type : Set where base : ℕ → type _⇒_ _∧_ : type → type → type context : ℕ → Set context = vec type infix 10 _⊢_∶_ data _⊢_∶_ {n : ℕ} (Γ : context n) : term n → type → Set where ax : ∀ {i} → Γ ⊢ var i ∶ lookup i Γ lam : ∀ {A B x} → Γ ▸ A ⊢ x ∶ B → Γ ⊢ lam x ∶ A ⇒ B app : ∀ {A B x y} → Γ ⊢ x ∶ (A ⇒ B) → Γ ⊢ y ∶ A → Γ ⊢ app x y ∶ B ∧ⁱ : ∀ {A B x} → Γ ⊢ x ∶ A → Γ ⊢ x ∶ B → Γ ⊢ x ∶ A ∧ B ∧ᵉˡ : ∀ {A B x} → Γ ⊢ x ∶ A ∧ B → Γ ⊢ x ∶ A ∧ᵉʳ : ∀ {A B x} → Γ ⊢ x ∶ A ∧ B → Γ ⊢ x ∶ B ⊢_∶_ : term 0 → type → Set ⊢ x ∶ t = ε ⊢ x ∶ t -- This lemma is actually false, because i did not setup the context -- inclusions properly. It's not really complicated to fix: just -- transpose the whole machinery from lambda.stack to lambda.vec. The -- only thing is that it's a bit long and boring to get the same job -- done on an indexed datatype. Substitution is hard to get right... lift-p : ∀ {n A X Γ} {x : term n} → Γ ⊢ x ∶ A → Γ ▸ X ⊢ lift x ∶ A lift-p ax = ax lift-p (lam x) = {!!} lift-p (app x y) = app (lift-p x) (lift-p y) lift-p (∧ⁱ x₁ x₂) = ∧ⁱ (lift-p x₁) (lift-p x₂) lift-p (∧ᵉˡ x) = ∧ᵉˡ (lift-p x) lift-p (∧ᵉʳ x) = ∧ᵉʳ (lift-p x) ↑-p : ∀ {n m X Γ Δ} {ρ : Fin n → term m} → ((i : Fin n) → Δ ⊢ ρ i ∶ lookup i Γ) → (i : Fin (suc n)) → (Δ ▸ X) ⊢ ↑ ρ i ∶ lookup i (Γ ▸ X) ↑-p ρT zero = ax ↑-p ρT (suc i) = lift-p (ρT i) subst-p : ∀ {n m A} {x : term n} {Γ : context n} {Δ : context m} {ρ : Fin n → term m} → Γ ⊢ x ∶ A → ((i : Fin n) → Δ ⊢ ρ i ∶ lookup i Γ) → Δ ⊢ subst x ρ ∶ A subst-p (ax {i}) ρT = ρT i subst-p (lam x) ρT = lam (subst-p x (↑-p ρT)) subst-p (app x y) ρT = app (subst-p x ρT) (subst-p y ρT) subst-p (∧ⁱ x₁ x₂) ρT = ∧ⁱ (subst-p x₁ ρT) (subst-p x₂ ρT) subst-p (∧ᵉˡ x) ρT = ∧ᵉˡ (subst-p x ρT) subst-p (∧ᵉʳ x) ρT = ∧ᵉʳ (subst-p x ρT)
-- Andreas, 2017-01-13, issue #2402 -- Error message: incomplete pattern matching open import Common.Bool module _ (A B C D E F G H I J K L M O P Q R S T U V W X Y Z : Set) where test2 : Bool → Bool test2 x with true test2 true | x = ? -- WAS: Reports: -- Incomplete pattern matching for .IncompletePattern.with-56. -- Missing cases: -- .IncompletePattern.with-56 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ false -- when checking the definition of with-56 -- That's total bogus! -- Expected: -- Incomplete pattern matching for .Issue2402-2.with-56. -- Missing cases: -- test2 false | w -- when checking the definition of with-56
(* Copyright (C) 2017 M.A.L. Marques 2019 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: gga_exc *) (* prefix: gga_x_cap_params *params; assert(p->params != NULL); params = (gga_x_cap_params * )(p->params); *) cap_f0 := s -> 1 - params_a_alphaoAx*s*log(1 + s)/(1 + params_a_c*log(1 + s)): cap_f := x -> cap_f0(X2S*x): f := (rs, z, xt, xs0, xs1) -> gga_exchange(cap_f, rs, z, xs0, xs1):
from sklearn.cluster import MiniBatchKMeans import numpy as np from tqdm import tqdm import joblib import matplotlib.pyplot as plt import os from argparse import ArgumentParser from load_audio import load_audio import torch import torchaudio def label_spk(spk_emb_path, km_path, split, output_dir, n_PCA=None): # load pretrained model km_model = joblib.load(km_path) spk_emb = np.load(spk_emb_path) preds = km_model.predict(spk_emb) with open(os.path.join(output_dir, f"{split}_spk.km"), 'w') as f: for pred in preds: f.write(str(pred)) f.write("\n") if __name__ == "__main__": PARSER = ArgumentParser() PARSER.add_argument("-k", "--km_path", help="pretrained kmean model path", required=True) PARSER.add_argument("-s", "--spk_emb_path", help="pretrained kmean model path", required=True) PARSER.add_argument("-s", "--split", help="dataset split name", required=True) PARSER.add_argument("-o", "--output_dir", help="save label as .km file", required=True) label_spk(**vars(PARSER.parse_args()))
/- Copyright (c) 2022 Mantas Bakšys. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mantas Bakšys -/ import algebra.big_operators.basic import algebra.order.module import data.prod.lex import group_theory.perm.support import order.monotone.monovary import tactic.abel /-! # Rearrangement inequality This file proves the rearrangement inequality and deduces the conditions for equality and strict inequality. The rearrangement inequality tells you that for two functions `f g : ι → α`, the sum `∑ i, f i * g (σ i)` is maximized over all `σ : perm ι` when `g ∘ σ` monovaries with `f` and minimized when `g ∘ σ` antivaries with `f`. The inequality also tells you that `∑ i, f i * g (σ i) = ∑ i, f i * g i` if and only if `g ∘ σ` monovaries with `f` when `g` monovaries with `f`. The above equality also holds if and only if `g ∘ σ` antivaries with `f` when `g` antivaries with `f`. From the above two statements, we deduce that the inequality is strict if and only if `g ∘ σ` does not monovary with `f` when `g` monovaries with `f`. Analogously, the inequality is strict if and only if `g ∘ σ` does not antivary with `f` when `g` antivaries with `f`. ## Implementation notes In fact, we don't need much compatibility between the addition and multiplication of `α`, so we can actually decouple them by replacing multiplication with scalar multiplication and making `f` and `g` land in different types. As a bonus, this makes the dual statement trivial. The multiplication versions are provided for convenience. The case for `monotone`/`antitone` pairs of functions over a `linear_order` is not deduced in this file because it is easily deducible from the `monovary` API. -/ open equiv equiv.perm finset function order_dual open_locale big_operators variables {ι α β : Type*} /-! ### Scalar multiplication versions -/ section smul variables [linear_ordered_ring α] [linear_ordered_add_comm_group β] [module α β] [ordered_smul α β] {s : finset ι} {σ : perm ι} {f : ι → α} {g : ι → β} /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_smul_comp_perm_le_sum_smul (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) ≤ ∑ i in s, f i • g i := begin classical, revert hσ σ hfg, apply finset.induction_on_max_value (λ i, to_lex (g i, f i)) s, { simp only [le_rfl, finset.sum_empty, implies_true_iff] }, intros a s has hamax hind σ hfg hσ, set τ : perm ι := σ.trans (swap a (σ a)) with hτ, have hτs : {x | τ x ≠ x} ⊆ s, { intros x hx, simp only [ne.def, set.mem_set_of_eq, equiv.coe_trans, equiv.swap_comp_apply] at hx, split_ifs at hx with h₁ h₂ h₃, { obtain rfl | hax := eq_or_ne x a, { contradiction }, { exact mem_of_mem_insert_of_ne (hσ $ λ h, hax $ h.symm.trans h₁) hax } }, { exact (hx $ σ.injective h₂.symm).elim }, { exact mem_of_mem_insert_of_ne (hσ hx) (ne_of_apply_ne _ h₂) } }, specialize hind (hfg.subset $ subset_insert _ _) hτs, simp_rw sum_insert has, refine le_trans _ (add_le_add_left hind _), obtain hσa | hσa := eq_or_ne a (σ a), { rw [hτ, ←hσa, swap_self, trans_refl] }, have h1s : σ⁻¹ a ∈ s, { rw [ne.def, ←inv_eq_iff_eq] at hσa, refine mem_of_mem_insert_of_ne (hσ $ λ h, hσa _) hσa, rwa [apply_inv_self, eq_comm] at h }, simp only [← s.sum_erase_add _ h1s, add_comm], rw [← add_assoc, ← add_assoc], simp only [hτ, swap_apply_left, function.comp_app, equiv.coe_trans, apply_inv_self], refine add_le_add (smul_add_smul_le_smul_add_smul' _ _) (sum_congr rfl $ λ x hx, _).le, { specialize hamax (σ⁻¹ a) h1s, rw prod.lex.le_iff at hamax, cases hamax, { exact hfg (mem_insert_of_mem h1s) (mem_insert_self _ _) hamax }, { exact hamax.2 } }, { specialize hamax (σ a) (mem_of_mem_insert_of_ne (hσ $ σ.injective.ne hσa.symm) hσa.symm), rw prod.lex.le_iff at hamax, cases hamax, { exact hamax.le }, { exact hamax.1.le } }, { rw [mem_erase, ne.def, eq_inv_iff_eq] at hx, rw swap_apply_of_ne_of_ne hx.1 (σ.injective.ne _), rintro rfl, exact has hx.2 } end /-- **Equality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_smul_comp_perm_eq_sum_smul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) = ∑ i in s, f i • g i ↔ monovary_on f (g ∘ σ) s := begin classical, refine ⟨not_imp_not.1 $ λ h, _, λ h, (hfg.sum_smul_comp_perm_le_sum_smul hσ).antisymm _⟩, { rw monovary_on at h, push_neg at h, obtain ⟨x, hx, y, hy, hgxy, hfxy⟩ := h, set τ : perm ι := (swap x y).trans σ, have hτs : {x | τ x ≠ x} ⊆ s, { refine (set_support_mul_subset σ $ swap x y).trans (set.union_subset hσ $ λ z hz, _), obtain ⟨_, rfl | rfl⟩ := swap_apply_ne_self_iff.1 hz; assumption }, refine ((hfg.sum_smul_comp_perm_le_sum_smul hτs).trans_lt' _).ne, obtain rfl | hxy := eq_or_ne x y, { cases lt_irrefl _ hfxy }, simp only [←s.sum_erase_add _ hx, ←(s.erase x).sum_erase_add _ (mem_erase.2 ⟨hxy.symm, hy⟩), add_assoc, equiv.coe_trans, function.comp_app, swap_apply_right, swap_apply_left], refine add_lt_add_of_le_of_lt (finset.sum_congr rfl $ λ z hz, _).le (smul_add_smul_lt_smul_add_smul hfxy hgxy), simp_rw mem_erase at hz, rw swap_apply_of_ne_of_ne hz.2.1 hz.1 }, { convert h.sum_smul_comp_perm_le_sum_smul ((set_support_inv_eq _).subset.trans hσ) using 1, simp_rw [function.comp_app, apply_inv_self] } end /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_smul_comp_perm_lt_sum_smul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) < ∑ i in s, f i • g i ↔ ¬ monovary_on f (g ∘ σ) s := by simp [←hfg.sum_smul_comp_perm_eq_sum_smul_iff hσ, lt_iff_le_and_ne, hfg.sum_smul_comp_perm_le_sum_smul hσ] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_smul_le_sum_smul (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) • g i ≤ ∑ i in s, f i • g i := begin convert hfg.sum_smul_comp_perm_le_sum_smul (show {x | σ⁻¹ x ≠ x} ⊆ s, by simp only [set_support_inv_eq, hσ]) using 1, exact σ.sum_comp' s (λ i j, f i • g j) hσ, end /-- **Equality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_smul_eq_sum_smul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) • g i = ∑ i in s, f i • g i ↔ monovary_on (f ∘ σ) g s := begin have hσinv : {x | σ⁻¹ x ≠ x} ⊆ s := (set_support_inv_eq _).subset.trans hσ, refine (iff.trans _ $ hfg.sum_smul_comp_perm_eq_sum_smul_iff hσinv).trans ⟨λ h, _, λ h, _⟩, { simpa only [σ.sum_comp' s (λ i j, f i • g j) hσ] }, { convert h.comp_right σ, { rw [comp.assoc, inv_def, symm_comp_self, comp.right_id] }, { rw [σ.eq_preimage_iff_image_eq, set.image_perm hσ] } }, { convert h.comp_right σ.symm, { rw [comp.assoc, self_comp_symm, comp.right_id] }, { rw σ.symm.eq_preimage_iff_image_eq, exact set.image_perm hσinv } } end /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_smul_lt_sum_smul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) • g i < ∑ i in s, f i • g i ↔ ¬ monovary_on (f ∘ σ) g s := by simp [←hfg.sum_comp_perm_smul_eq_sum_smul_iff hσ, lt_iff_le_and_ne, hfg.sum_comp_perm_smul_le_sum_smul hσ] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_smul_le_sum_smul_comp_perm (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g i ≤ ∑ i in s, f i • g (σ i) := hfg.dual_right.sum_smul_comp_perm_le_sum_smul hσ /-- **Equality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_smul_eq_sum_smul_comp_perm_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) = ∑ i in s, f i • g i ↔ antivary_on f (g ∘ σ) s := (hfg.dual_right.sum_smul_comp_perm_eq_sum_smul_iff hσ).trans monovary_on_to_dual_right /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_smul_lt_sum_smul_comp_perm_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g i < ∑ i in s, f i • g (σ i) ↔ ¬ antivary_on f (g ∘ σ) s := by simp [←hfg.sum_smul_eq_sum_smul_comp_perm_iff hσ, lt_iff_le_and_ne, eq_comm, hfg.sum_smul_le_sum_smul_comp_perm hσ] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_smul_le_sum_comp_perm_smul (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g i ≤ ∑ i in s, f (σ i) • g i := hfg.dual_right.sum_comp_perm_smul_le_sum_smul hσ /-- **Equality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_smul_eq_sum_comp_perm_smul_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) • g i = ∑ i in s, f i • g i ↔ antivary_on (f ∘ σ) g s := (hfg.dual_right.sum_comp_perm_smul_eq_sum_smul_iff hσ).trans monovary_on_to_dual_right /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_smul_lt_sum_comp_perm_smul_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g i < ∑ i in s, f (σ i) • g i ↔ ¬ antivary_on (f ∘ σ) g s := by simp [←hfg.sum_smul_eq_sum_comp_perm_smul_iff hσ, eq_comm, lt_iff_le_and_ne, hfg.sum_smul_le_sum_comp_perm_smul hσ] variables [fintype ι] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_smul_comp_perm_le_sum_smul (hfg : monovary f g) : ∑ i, f i • g (σ i) ≤ ∑ i, f i • g i := (hfg.monovary_on _).sum_smul_comp_perm_le_sum_smul $ λ i _, mem_univ _ /-- **Equality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_smul_comp_perm_eq_sum_smul_iff (hfg : monovary f g) : ∑ i, f i • g (σ i) = ∑ i, f i • g i ↔ monovary f (g ∘ σ) := by simp [(hfg.monovary_on _).sum_smul_comp_perm_eq_sum_smul_iff (λ i _, mem_univ _)] /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_smul_comp_perm_lt_sum_smul_iff (hfg : monovary f g) : ∑ i, f i • g (σ i) < ∑ i, f i • g i ↔ ¬ monovary f (g ∘ σ) := by simp [(hfg.monovary_on _).sum_smul_comp_perm_lt_sum_smul_iff (λ i _, mem_univ _)] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary.sum_comp_perm_smul_le_sum_smul (hfg : monovary f g) : ∑ i, f (σ i) • g i ≤ ∑ i, f i • g i := (hfg.monovary_on _).sum_comp_perm_smul_le_sum_smul $ λ i _, mem_univ _ /-- **Equality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_comp_perm_smul_eq_sum_smul_iff (hfg : monovary f g) : ∑ i, f (σ i) • g i = ∑ i, f i • g i ↔ monovary (f ∘ σ) g := by simp [(hfg.monovary_on _).sum_comp_perm_smul_eq_sum_smul_iff (λ i _, mem_univ _)] /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_comp_perm_smul_lt_sum_smul_iff (hfg : monovary f g) : ∑ i, f (σ i) • g i < ∑ i, f i • g i ↔ ¬ monovary (f ∘ σ) g := by simp [(hfg.monovary_on _).sum_comp_perm_smul_lt_sum_smul_iff (λ i _, mem_univ _)] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_smul_le_sum_smul_comp_perm (hfg : antivary f g) : ∑ i, f i • g i ≤ ∑ i, f i • g (σ i) := (hfg.antivary_on _).sum_smul_le_sum_smul_comp_perm $ λ i _, mem_univ _ /-- **Equality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_smul_eq_sum_smul_comp_perm_iff (hfg : antivary f g) : ∑ i, f i • g (σ i) = ∑ i, f i • g i ↔ antivary f (g ∘ σ) := by simp [(hfg.antivary_on _).sum_smul_eq_sum_smul_comp_perm_iff (λ i _, mem_univ _)] /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_smul_lt_sum_smul_comp_perm_iff (hfg : antivary f g) : ∑ i, f i • g i < ∑ i, f i • g (σ i) ↔ ¬ antivary f (g ∘ σ) := by simp [(hfg.antivary_on _).sum_smul_lt_sum_smul_comp_perm_iff (λ i _, mem_univ _)] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_smul_le_sum_comp_perm_smul (hfg : antivary f g) : ∑ i, f i • g i ≤ ∑ i, f (σ i) • g i := (hfg.antivary_on _).sum_smul_le_sum_comp_perm_smul $ λ i _, mem_univ _ /-- **Equality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_smul_eq_sum_comp_perm_smul_iff (hfg : antivary f g) : ∑ i, f (σ i) • g i = ∑ i, f i • g i ↔ antivary (f ∘ σ) g := by simp [(hfg.antivary_on _).sum_smul_eq_sum_comp_perm_smul_iff (λ i _, mem_univ _)] /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_smul_lt_sum_comp_perm_smul_iff (hfg : antivary f g) : ∑ i, f i • g i < ∑ i, f (σ i) • g i ↔ ¬ antivary (f ∘ σ) g := by simp [(hfg.antivary_on _).sum_smul_lt_sum_comp_perm_smul_iff (λ i _, mem_univ _)] end smul /-! ### Multiplication versions Special cases of the above when scalar multiplication is actually multiplication. -/ section mul variables [linear_ordered_ring α] {s : finset ι} {σ : perm ι} {f g : ι → α} /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_mul_comp_perm_le_sum_mul (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g (σ i) ≤ ∑ i in s, f i * g i := hfg.sum_smul_comp_perm_le_sum_smul hσ /-- **Equality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_mul_comp_perm_eq_sum_mul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g (σ i) = ∑ i in s, f i * g i ↔ monovary_on f (g ∘ σ) s := hfg.sum_smul_comp_perm_eq_sum_smul_iff hσ /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_mul_comp_perm_lt_sum_mul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) < ∑ i in s, f i • g i ↔ ¬ monovary_on f (g ∘ σ) s := hfg.sum_smul_comp_perm_lt_sum_smul_iff hσ /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_mul_le_sum_mul (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) * g i ≤ ∑ i in s, f i * g i := hfg.sum_comp_perm_smul_le_sum_smul hσ /-- **Equality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_mul_eq_sum_mul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) * g i = ∑ i in s, f i * g i ↔ monovary_on (f ∘ σ) g s := hfg.sum_comp_perm_smul_eq_sum_smul_iff hσ /-- **Strict inequality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_mul_lt_sum_mul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) * g i < ∑ i in s, f i * g i ↔ ¬ monovary_on (f ∘ σ) g s := hfg.sum_comp_perm_smul_lt_sum_smul_iff hσ /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_mul_le_sum_mul_comp_perm (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g i ≤ ∑ i in s, f i * g (σ i) := hfg.sum_smul_le_sum_smul_comp_perm hσ /-- **Equality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_mul_eq_sum_mul_comp_perm_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g (σ i) = ∑ i in s, f i * g i ↔ antivary_on f (g ∘ σ) s := hfg.sum_smul_eq_sum_smul_comp_perm_iff hσ /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_mul_lt_sum_mul_comp_perm_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g i < ∑ i in s, f i * g (σ i) ↔ ¬ antivary_on f (g ∘ σ) s := hfg.sum_smul_lt_sum_smul_comp_perm_iff hσ /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_mul_le_sum_comp_perm_mul (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g i ≤ ∑ i in s, f (σ i) * g i := hfg.sum_smul_le_sum_comp_perm_smul hσ /-- **Equality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_mul_eq_sum_comp_perm_mul_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) * g i = ∑ i in s, f i * g i ↔ antivary_on (f ∘ σ) g s := hfg.sum_smul_eq_sum_comp_perm_smul_iff hσ /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_mul_lt_sum_comp_perm_mul_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g i < ∑ i in s, f (σ i) * g i ↔ ¬ antivary_on (f ∘ σ) g s := hfg.sum_smul_lt_sum_comp_perm_smul_iff hσ variables [fintype ι] /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_mul_comp_perm_le_sum_mul (hfg : monovary f g) : ∑ i, f i * g (σ i) ≤ ∑ i, f i * g i := hfg.sum_smul_comp_perm_le_sum_smul /-- **Equality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_mul_comp_perm_eq_sum_mul_iff (hfg : monovary f g) : ∑ i, f i * g (σ i) = ∑ i, f i * g i ↔ monovary f (g ∘ σ) := hfg.sum_smul_comp_perm_eq_sum_smul_iff /-- **Strict inequality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_mul_comp_perm_lt_sum_mul_iff (hfg : monovary f g) : ∑ i, f i * g (σ i) < ∑ i, f i * g i ↔ ¬ monovary f (g ∘ σ) := hfg.sum_smul_comp_perm_lt_sum_smul_iff /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary.sum_comp_perm_mul_le_sum_mul (hfg : monovary f g) : ∑ i, f (σ i) * g i ≤ ∑ i, f i * g i := hfg.sum_comp_perm_smul_le_sum_smul /-- **Equality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_comp_perm_mul_eq_sum_mul_iff (hfg : monovary f g) : ∑ i, f (σ i) * g i = ∑ i, f i * g i ↔ monovary (f ∘ σ) g := hfg.sum_comp_perm_smul_eq_sum_smul_iff /-- **Strict inequality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_comp_perm_mul_lt_sum_mul_iff (hfg : monovary f g) : ∑ i, f (σ i) * g i < ∑ i, f i * g i ↔ ¬ monovary (f ∘ σ) g := hfg.sum_comp_perm_smul_lt_sum_smul_iff /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_mul_le_sum_mul_comp_perm (hfg : antivary f g) : ∑ i, f i * g i ≤ ∑ i, f i * g (σ i) := hfg.sum_smul_le_sum_smul_comp_perm /-- **Equality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_mul_eq_sum_mul_comp_perm_iff (hfg : antivary f g) : ∑ i, f i * g (σ i) = ∑ i, f i * g i ↔ antivary f (g ∘ σ) := hfg.sum_smul_eq_sum_smul_comp_perm_iff /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_mul_lt_sum_mul_comp_perm_iff (hfg : antivary f g) : ∑ i, f i • g i < ∑ i, f i • g (σ i) ↔ ¬ antivary f (g ∘ σ) := hfg.sum_smul_lt_sum_smul_comp_perm_iff /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_mul_le_sum_comp_perm_mul (hfg : antivary f g) : ∑ i, f i * g i ≤ ∑ i, f (σ i) * g i := hfg.sum_smul_le_sum_comp_perm_smul /-- **Equality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_mul_eq_sum_comp_perm_mul_iff (hfg : antivary f g) : ∑ i, f (σ i) * g i = ∑ i, f i * g i ↔ antivary (f ∘ σ) g := hfg.sum_smul_eq_sum_comp_perm_smul_iff /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_mul_lt_sum_comp_perm_mul_iff (hfg : antivary f g) : ∑ i, f i * g i < ∑ i, f (σ i) * g i ↔ ¬ antivary (f ∘ σ) g := hfg.sum_smul_lt_sum_comp_perm_smul_iff end mul
\subsection{Classification of Riemann Surfaces} We roughly classified all Riemann surfaces in the preceding section by viewing them as quotients of their universal covers, which can only be one of $\mathbb C_\infty,\mathbb C,\mathbb D$. We say the surface is uniformised by its universal cover. For some of these cases, we can do something better. \begin{proposition} If a Riemann surface $R$ is uniformised by $\mathbb C_\infty$, then $R$ is conformally equivalent to $\mathbb C_\infty$. \end{proposition} \begin{proof} Suppose $R=G\backslash\mathbb C_\infty$, then we know that $G$ acts by conformal equivalences $\mathbb C_\infty\to\mathbb C_\infty$. But this is just M\"obius transformations (from Example Sheet). However, any M\"obius transformation has at least one fixed point, but $G$ should act freely, hence necessarily $G$ is trivial and hence $R\cong\mathbb C_\infty$. \end{proof} What about $\mathbb C$? \begin{proposition} If a Riemann surface $R$ is uniformised by $\mathbb C$, i.e. $R\cong G\backslash\mathbb C$, then one of the following holds:\\ (i) $G$ is trivial and $R\cong\mathbb C$.\\ (ii) $G\cong\mathbb Z$ and $R\cong\mathbb C_\star$.\\ (iii) $G\cong\mathbb Z^2$ and $R\cong\mathbb C/\Lambda$ for a lattice $\Lambda$. \end{proposition} \begin{proof} The conformal automorphisms of $\mathbb C$ are simply the (nonconstant) linear maps $\{z\mapsto az+b:a\in\mathbb C_\star,b\in\mathbb C\}$ (again from Example Sheet). Which of them can $G$ act by? Note that if $a\neq 1$, then $z\mapsto az+b$ has a fixed point, therefore $G$ can only consist of translations. But then (Example Sheet again!) $G$ (identified by the values of $b$) can only be one of:\\ (i) Trivial.\\ (ii) $\langle\omega\rangle\cong\mathbb Z$ for some $\omega\neq 0$.\\ (iii) a lattice $\Lambda\cong\mathbb Z^2$.\\ And these corresponds to the three situations as stated. \end{proof} Oh, by the way, a surface cannot be uniformised by more than one of $\mathbb C_\infty,\mathbb C,\mathbb D$. \begin{lemma}[Lifting Lemma] Let $f:R\to S$ be an analytic map of Riemann surfaces. Suppose $R$ is simply connected, and let $\pi:\tilde{S}\to S$ be the uniformising map of $S$, then there is an analytic map $F:R\to\tilde{S}$ such that $f=\pi\circ F$. \end{lemma} So we have the commutative diagram \[ \begin{tikzcd} &\tilde{S}\arrow{d}{\pi}\\ R\arrow[dashed]{ur}{F}\arrow[swap]{r}{f}&S \end{tikzcd} \] \begin{proof} Example Sheet. \end{proof} \begin{proposition} A Riemann surface $R$ is uniformised by at most one of $\mathbb C_\infty,\mathbb C,\mathbb D$. \end{proposition} \begin{proof} By the previous discussion, we already know everything that is uniformised by $\mathbb C$ or $\mathbb C_\infty$ and they are distinct. Now suppose $R$ is uniformised by $\mathbb D$ and $\tilde{R}$ which is either $\mathbb C$ or $\mathbb C_\infty$. Let $\pi,f$ be the respective uniformisation maps, then by the preceding lemma, there is $F:\tilde{R}\to\mathbb D$ such that \[ \begin{tikzcd} &\mathbb D\arrow{d}{\pi}\\ \tilde{R}\arrow[swap]{r}{f}\arrow{ur}{F}&R \end{tikzcd} \] commutes. But then $F$ has to be constant by Liouville's Theorem, hence $f$ is also constant, contradiction. \end{proof} So any other Riemann surface must be uniformised by $\mathbb D$. \begin{proposition} Any conformal automorphisms of $\mathbb D$ is in the form $$z\mapsto e^{i\theta}\frac{z-a}{1-\bar{a}z},a\in\mathbb C,\theta\in\mathbb R$$ \end{proposition} \begin{proof} Complex Analysis. \end{proof} This is perhaps easier to picture if we send $\mathbb D$ to the open upper half plane $\mathbb H$ (by the M\"obius transformation $z\mapsto (1+iz)/(1-iz)$), which has automorphisms in the form $z\mapsto (az+b)/(cz+d)$ for $a,b,c,d\in\mathbb R,ad-bc=1$. \begin{definition} A subgroup of $\operatorname{PSL}(\mathbb R)$ that acts properly discontinuously on $\mathbb H$ is called a Fuchsian group. \end{definition}
Formal statement is: lemma has_contour_integral_div: "(f has_contour_integral i) g \<Longrightarrow> ((\<lambda>x. f x/c) has_contour_integral (i/c)) g" Informal statement is: If $f$ has a contour integral $i$ along $g$, then $f/c$ has a contour integral $i/c$ along $g$.
module Tuples where open import Data.Product _² : ∀ {a} (A : Set a) → Set a A ² = A × A _³ : ∀ {a} (A : Set a) → Set a A ³ = A × A ² _⁴ : ∀ {a} (A : Set a) → Set a A ⁴ = A × A ³ _⁵ : ∀ {a} (A : Set a) → Set a A ⁵ = A × A ⁴ _⁶ : ∀ {a} (A : Set a) → Set a A ⁶ = A × A ⁵ _⁷ : ∀ {a} (A : Set a) → Set a A ⁷ = A × A ⁶
Director Tim Damon recently went Rogue, as in Nissan Rogue Sport, in five short films highlighting the SUV’s tech/lifestyle amenities for agency Designory. Pictures in a Row (PICROW) Studios just completed the first spot introducing Amazon’s new Prime Wardrobe service. Directed by Peter Dietrich, Clumsy Junior tells the story of a father’s growing exasperation with his awkward son. Director Jessica Sanders's new short film features Ethan Peck & Aqualillies set to Bebe Rexha's “I Got You."
Standing in front of the group, begin by pointing up in the air towards the right or left. Follow up with verbal prompts so that athletes follow steps appropriately. When you point your finger in a certain direction, outfielders should dropstep in that direction. When you yell "crossover," athletes should take their crossover steps... and on "go," athletes are to take two or three running steps. Move athletes into one line with the first outfielder stepping out in front of you. Begin by pointing a baseball in one direction (right or left). The athlete is then to dropstep and crossover in appropriate direction as you reach back and throw an easy pop fly. Involve fly balls off of the bat only after fundamentals are solid.
If $f$ and $g$ are two functions that are eventually nonzero, then $f$ is eventually less than $g$ if and only if $1/f$ is eventually greater than $1/g$.
Load LFindLoad. From lfind Require Import LFind. From QuickChick Require Import QuickChick. From adtind Require Import goal33. Derive Show for natural. Derive Arbitrary for natural. Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed. Lemma conj28synthconj4_hyp: forall (lv0 : natural) (lv1 : natural) (lv2 : natural), (@eq natural (plus (mult lv0 lv1) lv0) lv2) -> (@eq natural (Succ (plus (mult lv0 lv1) (plus lv1 lv0))) (plus lv2 (plus (Succ Zero) lv1))). Admitted. QuickChick conj28synthconj4_hyp.
If $f$ tends to $l$ and $l$ is not an integer, then $f$ tends to the floor of $l$.
(* Title: HOL/Auth/n_germanSymIndex_lemma_inv__41_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_germanSymIndex Protocol Case Study*} theory n_germanSymIndex_lemma_inv__41_on_rules imports n_germanSymIndex_lemma_on_inv__41 begin section{*All lemmas on causal relation between inv__41*} lemma lemma_inv__41_on_rules: assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__41 p__Inv2)" shows "invHoldForRule s f r (invariants N)" proof - have c1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)\<or> (\<exists> i. i\<le>N\<and>r=n_SendReqS i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" apply (cut_tac b1, auto) done moreover { assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_StoreVsinv__41) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendReqSVsinv__41) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendReqE__part__0Vsinv__41) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendReqE__part__1Vsinv__41) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqSVsinv__41) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqEVsinv__41) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInv__part__0Vsinv__41) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInv__part__1Vsinv__41) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInvAckVsinv__41) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__41) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendGntSVsinv__41) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendGntEVsinv__41) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvGntSVsinv__41) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvGntEVsinv__41) done } ultimately show "invHoldForRule s f r (invariants N)" by satx qed end
Formal statement is: lemma has_contour_integral_reverse_linepath: "(f has_contour_integral i) (linepath a b) \<Longrightarrow> (f has_contour_integral (-i)) (linepath b a)" Informal statement is: If $f$ has a contour integral along the line segment from $a$ to $b$, then $f$ has a contour integral along the line segment from $b$ to $a$, and the value of the contour integral is the negative of the value of the contour integral along the line segment from $a$ to $b$.
Formal statement is: lemma monom_eq_iff': "monom c n = monom d m \<longleftrightarrow> c = d \<and> (c = 0 \<or> n = m)" Informal statement is: Two monomials are equal if and only if they have the same coefficient and either both are zero or both have the same degree.
module Vsurfcurdiag use Vmeshes real(rprec) :: curvra, curvri, cudema, cudemi, avcude end module Vsurfcurdiag
\section{Food Waste} Every year danish households throws away nearly 237,000 tons of food\cite{maSpild_iTal}, that could have been eaten by people. This is estimated to be nearly 16 mio. DKK. About 20 \% of a danish households food budget is wasted on throwing away food that could have been eaten, this means that if no food were wasted at all, 1 mio. people could be fed, nearly corresponding to 20 \% of the danish population. The people who throws away most food, are the people living alone. The average person living alone throws away 98.8 kg of food per year, whereas a household with 5 people throws away 46.8 kg of food per person per year. It is mostly dairy products, vegetables and bread that gets thrown away, though in December a lot of meat is also thrown away, due to the fact that it is Christmas and at this time people eat more food. Since 2007 the danish people have been purchasing 10 \% less food, a lot of this food used to end up as food waste. 54 \% of the danish people rarely or never uses the food from the night before as leftovers, and 69 \% does not use leftovers for lunch the day after. 20 \% of danish people does not make a shopping list before shopping for groceries. 52 \% of people does not make a meal plan, 31 \% does it sometimes and 17 \% does it often. 81 \% of danish people would use leftovers to avoid food waste, 50 \% would make a meal plan and make a grocery shopping list. 59 \% of the consumers believe that the danish food waste is their own fault.\cite{maSpild_iTal}
Population justification: The global population size has not been quantified, but the species is reported to be common to very common through much of its range (del Hoyo et al. 1997). BirdLife International (2019) Species factsheet: Phaenicophaeus tristis. Downloaded from http://www.birdlife.org on 20/04/2019. Recommended citation for factsheets for more than one species: BirdLife International (2019) IUCN Red List for birds. Downloaded from http://www.birdlife.org on 20/04/2019.
(* Title: ZF/AC/AC_Equiv.thy Author: Krzysztof Grabczewski Axioms AC1 -- AC19 come from "Equivalents of the Axiom of Choice, II" by H. Rubin and J.E. Rubin, 1985. Axiom AC0 comes from "Axiomatic Set Theory" by P. Suppes, 1972. Some Isabelle proofs of equivalences of these axioms are formalizations of proofs presented by the Rubins. The others are based on the Rubins' proofs, but slightly changed. *) theory AC_Equiv imports Main begin (*obviously not Main_ZFC*) (* Well Ordering Theorems *) definition "WO1 == \<forall>A. \<exists>R. well_ord(A,R)" definition "WO2 == \<forall>A. \<exists>a. Ord(a) & A\<approx>a" definition "WO3 == \<forall>A. \<exists>a. Ord(a) & (\<exists>b. b \<subseteq> a & A\<approx>b)" definition "WO4(m) == \<forall>A. \<exists>a f. Ord(a) & domain(f)=a & (\<Union>b<a. f`b) = A & (\<forall>b<a. f`b \<lesssim> m)" definition "WO5 == \<exists>m \<in> nat. 1\<le>m & WO4(m)" definition "WO6 == \<forall>A. \<exists>m \<in> nat. 1\<le>m & (\<exists>a f. Ord(a) & domain(f)=a & (\<Union>b<a. f`b) = A & (\<forall>b<a. f`b \<lesssim> m))" definition "WO7 == \<forall>A. Finite(A) \<longleftrightarrow> (\<forall>R. well_ord(A,R) \<longrightarrow> well_ord(A,converse(R)))" definition "WO8 == \<forall>A. (\<exists>f. f \<in> (\<Prod>X \<in> A. X)) \<longrightarrow> (\<exists>R. well_ord(A,R))" definition (* Auxiliary concepts needed below *) pairwise_disjoint :: "i => o" where "pairwise_disjoint(A) == \<forall>A1 \<in> A. \<forall>A2 \<in> A. A1 \<inter> A2 \<noteq> 0 \<longrightarrow> A1=A2" definition sets_of_size_between :: "[i, i, i] => o" where "sets_of_size_between(A,m,n) == \<forall>B \<in> A. m \<lesssim> B & B \<lesssim> n" (* Axioms of Choice *) definition "AC0 == \<forall>A. \<exists>f. f \<in> (\<Prod>X \<in> Pow(A)-{0}. X)" definition "AC1 == \<forall>A. 0\<notin>A \<longrightarrow> (\<exists>f. f \<in> (\<Prod>X \<in> A. X))" definition "AC2 == \<forall>A. 0\<notin>A & pairwise_disjoint(A) \<longrightarrow> (\<exists>C. \<forall>B \<in> A. \<exists>y. B \<inter> C = {y})" definition "AC3 == \<forall>A B. \<forall>f \<in> A->B. \<exists>g. g \<in> (\<Prod>x \<in> {a \<in> A. f`a\<noteq>0}. f`x)" definition "AC4 == \<forall>R A B. (R \<subseteq> A*B \<longrightarrow> (\<exists>f. f \<in> (\<Prod>x \<in> domain(R). R``{x})))" definition "AC5 == \<forall>A B. \<forall>f \<in> A->B. \<exists>g \<in> range(f)->A. \<forall>x \<in> domain(g). f`(g`x) = x" definition "AC6 == \<forall>A. 0\<notin>A \<longrightarrow> (\<Prod>B \<in> A. B)\<noteq>0" definition "AC7 == \<forall>A. 0\<notin>A & (\<forall>B1 \<in> A. \<forall>B2 \<in> A. B1\<approx>B2) \<longrightarrow> (\<Prod>B \<in> A. B) \<noteq> 0" definition "AC8 == \<forall>A. (\<forall>B \<in> A. \<exists>B1 B2. B=<B1,B2> & B1\<approx>B2) \<longrightarrow> (\<exists>f. \<forall>B \<in> A. f`B \<in> bij(fst(B),snd(B)))" definition "AC9 == \<forall>A. (\<forall>B1 \<in> A. \<forall>B2 \<in> A. B1\<approx>B2) \<longrightarrow> (\<exists>f. \<forall>B1 \<in> A. \<forall>B2 \<in> A. f`<B1,B2> \<in> bij(B1,B2))" definition "AC10(n) == \<forall>A. (\<forall>B \<in> A. ~Finite(B)) \<longrightarrow> (\<exists>f. \<forall>B \<in> A. (pairwise_disjoint(f`B) & sets_of_size_between(f`B, 2, succ(n)) & \<Union>(f`B)=B))" definition "AC11 == \<exists>n \<in> nat. 1\<le>n & AC10(n)" definition "AC12 == \<forall>A. (\<forall>B \<in> A. ~Finite(B)) \<longrightarrow> (\<exists>n \<in> nat. 1\<le>n & (\<exists>f. \<forall>B \<in> A. (pairwise_disjoint(f`B) & sets_of_size_between(f`B, 2, succ(n)) & \<Union>(f`B)=B)))" definition "AC13(m) == \<forall>A. 0\<notin>A \<longrightarrow> (\<exists>f. \<forall>B \<in> A. f`B\<noteq>0 & f`B \<subseteq> B & f`B \<lesssim> m)" definition "AC14 == \<exists>m \<in> nat. 1\<le>m & AC13(m)" definition "AC15 == \<forall>A. 0\<notin>A \<longrightarrow> (\<exists>m \<in> nat. 1\<le>m & (\<exists>f. \<forall>B \<in> A. f`B\<noteq>0 & f`B \<subseteq> B & f`B \<lesssim> m))" definition "AC16(n, k) == \<forall>A. ~Finite(A) \<longrightarrow> (\<exists>T. T \<subseteq> {X \<in> Pow(A). X\<approx>succ(n)} & (\<forall>X \<in> {X \<in> Pow(A). X\<approx>succ(k)}. \<exists>! Y. Y \<in> T & X \<subseteq> Y))" definition "AC17 == \<forall>A. \<forall>g \<in> (Pow(A)-{0} -> A) -> Pow(A)-{0}. \<exists>f \<in> Pow(A)-{0} -> A. f`(g`f) \<in> g`f" locale AC18 = assumes AC18: "A\<noteq>0 & (\<forall>a \<in> A. B(a) \<noteq> 0) \<longrightarrow> ((\<Inter>a \<in> A. \<Union>b \<in> B(a). X(a,b)) = (\<Union>f \<in> \<Prod>a \<in> A. B(a). \<Inter>a \<in> A. X(a, f`a)))" \<comment>"AC18 cannot be expressed within the object-logic" definition "AC19 == \<forall>A. A\<noteq>0 & 0\<notin>A \<longrightarrow> ((\<Inter>a \<in> A. \<Union>b \<in> a. b) = (\<Union>f \<in> (\<Prod>B \<in> A. B). \<Inter>a \<in> A. f`a))" (* ********************************************************************** *) (* Theorems concerning ordinals *) (* ********************************************************************** *) (* lemma for ordertype_Int *) lemma rvimage_id: "rvimage(A,id(A),r) = r \<inter> A*A" apply (unfold rvimage_def) apply (rule equalityI, safe) apply (drule_tac P = "%a. <id (A) `xb,a>:r" in id_conv [THEN subst], assumption) apply (drule_tac P = "%a. <a,ya>:r" in id_conv [THEN subst], (assumption+)) apply (fast intro: id_conv [THEN ssubst]) done (* used only in Hartog.ML *) lemma ordertype_Int: "well_ord(A,r) ==> ordertype(A, r \<inter> A*A) = ordertype(A,r)" apply (rule_tac P = "%a. ordertype (A,a) =ordertype (A,r) " in rvimage_id [THEN subst]) apply (erule id_bij [THEN bij_ordertype_vimage]) done lemma lam_sing_bij: "(\<lambda>x \<in> A. {x}) \<in> bij(A, {{x}. x \<in> A})" apply (rule_tac d = "%z. THE x. z={x}" in lam_bijective) apply (auto simp add: the_equality) done lemma inj_strengthen_type: "[| f \<in> inj(A, B); !!a. a \<in> A ==> f`a \<in> C |] ==> f \<in> inj(A,C)" by (unfold inj_def, blast intro: Pi_type) (* ********************************************************************** *) (* Another elimination rule for \<exists>! *) (* ********************************************************************** *) lemma ex1_two_eq: "[| \<exists>! x. P(x); P(x); P(y) |] ==> x=y" by blast (* ********************************************************************** *) (* Lemmas used in the proofs like WO? ==> AC? *) (* ********************************************************************** *) lemma first_in_B: "[| well_ord(\<Union>(A),r); 0 \<notin> A; B \<in> A |] ==> (THE b. first(b,B,r)) \<in> B" by (blast dest!: well_ord_imp_ex1_first [THEN theI, THEN first_def [THEN def_imp_iff, THEN iffD1]]) lemma ex_choice_fun: "[| well_ord(\<Union>(A), R); 0 \<notin> A |] ==> \<exists>f. f \<in> (\<Prod>X \<in> A. X)" by (fast elim!: first_in_B intro!: lam_type) lemma ex_choice_fun_Pow: "well_ord(A, R) ==> \<exists>f. f \<in> (\<Prod>X \<in> Pow(A)-{0}. X)" by (fast elim!: well_ord_subset [THEN ex_choice_fun]) (* ********************************************************************** *) (* Lemmas needed to state when a finite relation is a function. *) (* The criteria are cardinalities of the relation and its domain. *) (* Used in WO6WO1.ML *) (* ********************************************************************** *) (*Using AC we could trivially prove, for all u, domain(u) \<lesssim> u*) lemma lepoll_m_imp_domain_lepoll_m: "[| m \<in> nat; u \<lesssim> m |] ==> domain(u) \<lesssim> m" apply (unfold lepoll_def) apply (erule exE) apply (rule_tac x = "\<lambda>x \<in> domain(u). \<mu> i. \<exists>y. <x,y> \<in> u & f`<x,y> = i" in exI) apply (rule_tac d = "%y. fst (converse(f) ` y) " in lam_injective) apply (fast intro: LeastI2 nat_into_Ord [THEN Ord_in_Ord] inj_is_fun [THEN apply_type]) apply (erule domainE) apply (frule inj_is_fun [THEN apply_type], assumption) apply (rule LeastI2) apply (auto elim!: nat_into_Ord [THEN Ord_in_Ord]) done lemma rel_domain_ex1: "[| succ(m) \<lesssim> domain(r); r \<lesssim> succ(m); m \<in> nat |] ==> function(r)" apply (unfold function_def, safe) apply (rule ccontr) apply (fast elim!: lepoll_trans [THEN succ_lepoll_natE] lepoll_m_imp_domain_lepoll_m [OF _ Diff_sing_lepoll] elim: domain_Diff_eq [OF _ not_sym, THEN subst]) done lemma rel_is_fun: "[| succ(m) \<lesssim> domain(r); r \<lesssim> succ(m); m \<in> nat; r \<subseteq> A*B; A=domain(r) |] ==> r \<in> A->B" by (simp add: Pi_iff rel_domain_ex1) end
(* * Copyright 2014, General Dynamics C4 Systems * * SPDX-License-Identifier: GPL-2.0-only *) (* CSpace invariants *) theory ArchCSpaceInv_AI imports "../CSpaceInv_AI" begin context Arch begin global_naming ARM_HYP definition safe_ioport_insert :: "cap \<Rightarrow> cap \<Rightarrow> 'a::state_ext state \<Rightarrow> bool" where "safe_ioport_insert newcap oldcap s \<equiv> True" declare safe_ioport_insert_def[simp] lemma safe_ioport_insert_triv: "\<not>is_arch_cap newcap \<Longrightarrow> safe_ioport_insert newcap oldcap s" by (clarsimp simp: safe_ioport_insert_def) lemma set_cap_ioports': "\<lbrace>\<lambda>s. valid_ioports s \<and> cte_wp_at (\<lambda>cap'. safe_ioport_insert cap cap' s) ptr s\<rbrace> set_cap cap ptr \<lbrace>\<lambda>rv. valid_ioports\<rbrace>" by wpsimp lemma unique_table_refs_no_cap_asidE: "\<lbrakk>caps_of_state s p = Some cap; unique_table_refs (caps_of_state s)\<rbrakk> \<Longrightarrow> no_cap_to_obj_with_diff_ref cap S s" apply (clarsimp simp: no_cap_to_obj_with_diff_ref_def cte_wp_at_caps_of_state) apply (unfold unique_table_refs_def) apply (drule_tac x=p in spec, drule_tac x="(a,b)" in spec) apply (drule spec)+ apply (erule impE, assumption)+ apply (clarsimp simp: is_cap_simps) done lemmas unique_table_refs_no_cap_asidD = unique_table_refs_no_cap_asidE[where S="{}"] lemma replace_cap_invs: "\<lbrace>\<lambda>s. invs s \<and> cte_wp_at (replaceable s p cap) p s \<and> cap \<noteq> cap.NullCap \<and> ex_cte_cap_wp_to (appropriate_cte_cap cap) p s \<and> s \<turnstile> cap\<rbrace> set_cap cap p \<lbrace>\<lambda>rv s. invs s\<rbrace>" apply (simp add: invs_def valid_state_def valid_mdb_def2) apply (rule hoare_pre) apply (wp replace_cap_valid_pspace set_cap_caps_of_state2 set_cap_idle replace_cap_ifunsafe valid_irq_node_typ set_cap_typ_at set_cap_irq_handlers set_cap_valid_arch_caps set_cap_cap_refs_respects_device_region_replaceable) apply (clarsimp simp: valid_pspace_def cte_wp_at_caps_of_state replaceable_def) apply (rule conjI) apply (fastforce simp: tcb_cap_valid_def dest!: cte_wp_tcb_cap_valid [OF caps_of_state_cteD]) apply (rule conjI) apply (erule_tac P="\<lambda>cps. mdb_cte_at cps (cdt s)" in rsubst) apply (rule ext) apply (safe del: disjE)[1] apply (simp add: gen_obj_refs_empty final_NullCap)+ apply (rule conjI) apply (simp add: untyped_mdb_def is_cap_simps) apply (erule disjE) apply (clarsimp, rule conjI, clarsimp+)[1] apply (erule allEI, erule allEI) apply (drule_tac x="fst p" in spec, drule_tac x="snd p" in spec) apply (clarsimp simp: gen_obj_refs_subset) apply (drule(1) disjoint_subset, simp) apply (rule conjI) apply (erule descendants_inc_minor) apply simp apply (elim disjE) apply clarsimp apply clarsimp apply (rule conjI) apply (erule disjE) apply (simp add: fun_upd_def[symmetric] fun_upd_idem) apply (simp add: untyped_inc_def not_is_untyped_no_range) apply (rule conjI) apply (erule disjE) apply (simp add: fun_upd_def[symmetric] fun_upd_idem) apply (simp add: ut_revocable_def) apply (rule conjI) apply (erule disjE) apply (clarsimp simp: irq_revocable_def) apply clarsimp apply (clarsimp simp: irq_revocable_def) apply (rule conjI) apply (erule disjE) apply (simp add: fun_upd_def[symmetric] fun_upd_idem) apply (simp add: reply_master_revocable_def) apply (rule conjI) apply (erule disjE) apply (simp add: fun_upd_def[symmetric] fun_upd_idem) apply (clarsimp simp add: reply_mdb_def) apply (thin_tac "\<forall>a b. (a, b) \<in> cte_refs cp nd \<and> Q a b\<longrightarrow> R a b" for cp nd Q R) apply (thin_tac "is_pt_cap cap \<longrightarrow> P" for cap P)+ apply (thin_tac "is_pd_cap cap \<longrightarrow> P" for cap P)+ apply (rule conjI) apply (unfold reply_caps_mdb_def)[1] apply (erule allEI, erule allEI) apply (clarsimp split: if_split simp add: is_cap_simps simp del: split_paired_Ex split_paired_All) apply (rename_tac ptra ptrb rights') apply (rule_tac x="(ptra,ptrb)" in exI) apply fastforce apply (unfold reply_masters_mdb_def)[1] apply (erule allEI, erule allEI) apply (fastforce split: if_split_asm simp: is_cap_simps) apply (rule conjI) apply (erule disjE) apply (clarsimp simp add: is_reply_cap_to_def) apply (drule caps_of_state_cteD) apply (subgoal_tac "cte_wp_at (is_reply_cap_to t) p s") apply (erule(1) valid_reply_capsD [OF has_reply_cap_cte_wpD]) apply (erule cte_wp_at_lift) apply(fastforce simp add:is_reply_cap_to_def) apply (simp add: is_cap_simps) apply (frule(1) valid_global_refsD2) apply (frule(1) cap_refs_in_kernel_windowD) apply (rule conjI) apply (erule disjE) apply (clarsimp simp: valid_reply_masters_def cte_wp_at_caps_of_state) apply (cases p,fastforce simp:is_master_reply_cap_to_def) apply (simp add: is_cap_simps) apply (elim disjE) apply simp apply (clarsimp simp: valid_table_capsD[OF caps_of_state_cteD] valid_arch_caps_def unique_table_refs_no_cap_asidE) apply simp apply (rule Ball_emptyI) apply (simp add: gen_obj_refs_subset) done definition "is_simple_cap_arch cap \<equiv> \<not>is_pt_cap cap \<and> \<not> is_pd_cap cap" declare is_simple_cap_arch_def[simp] lemma is_simple_cap_arch: "\<not>is_arch_cap cap \<Longrightarrow> is_simple_cap_arch cap" by (simp add: is_cap_simps) lemmas cap_master_cap_def = cap_master_cap_def[simplified cap_master_arch_cap_def] definition "cap_vptr_arch acap \<equiv> case acap of (PageCap _ _ _ _ (Some (_, vptr))) \<Rightarrow> Some vptr | (PageTableCap _ (Some (_, vptr))) \<Rightarrow> Some vptr | _ \<Rightarrow> None" definition "cap_vptr cap \<equiv> arch_cap_fun_lift cap_vptr_arch None cap" declare cap_vptr_arch_def[abs_def, simp] lemmas cap_vptr_simps [simp] = cap_vptr_def [simplified, split_simps cap.split arch_cap.split option.split prod.split] definition "is_derived_arch cap cap' \<equiv> ((is_pt_cap cap \<or> is_pd_cap cap) \<longrightarrow> cap_asid cap = cap_asid cap' \<and> cap_asid cap \<noteq> None) \<and> (vs_cap_ref cap = vs_cap_ref cap' \<or> is_pg_cap cap')" lemma is_derived_arch_non_arch: "\<not>is_arch_cap cap \<Longrightarrow> \<not> is_arch_cap cap' \<Longrightarrow> is_derived_arch cap cap'" unfolding is_derived_arch_def is_pg_cap_def is_pt_cap_def is_pd_cap_def vs_cap_ref_def is_arch_cap_def by (auto split: cap.splits) lemma is_derived_cap_arch_asid: "is_derived_arch cap cap' \<Longrightarrow> cap_master_cap cap = cap_master_cap cap' \<Longrightarrow> is_pt_cap cap' \<or> is_pd_cap cap' \<Longrightarrow> cap_asid cap = cap_asid cap'" unfolding is_derived_arch_def apply (cases cap; cases cap'; simp) by (auto simp: is_cap_simps cap_master_cap_def split: arch_cap.splits) lemma cap_master_cap_arch_simps: "cap_master_arch_cap ((arch_cap.PageCap dev ref rghts sz mapdata)) = (arch_cap.PageCap dev ref UNIV sz None)" "cap_master_arch_cap ( (arch_cap.ASIDPoolCap pool asid)) = (arch_cap.ASIDPoolCap pool 0)" "cap_master_arch_cap ( (arch_cap.PageTableCap ptr x)) = (arch_cap.PageTableCap ptr None)" "cap_master_arch_cap ( (arch_cap.PageDirectoryCap ptr y)) = (arch_cap.PageDirectoryCap ptr None)" "cap_master_arch_cap ( arch_cap.ASIDControlCap) = arch_cap.ASIDControlCap" by (simp add: cap_master_arch_cap_def)+ definition "cap_asid_base_arch cap \<equiv> case cap of (arch_cap.ASIDPoolCap _ asid) \<Rightarrow> Some asid | _ \<Rightarrow> None" declare cap_asid_base_arch_def[abs_def, simp] definition "cap_asid_base cap \<equiv> arch_cap_fun_lift cap_asid_base_arch None cap" lemmas cap_asid_base_simps [simp] = cap_asid_base_def [simplified, split_simps cap.split arch_cap.split] lemma same_master_cap_same_types: "cap_master_cap cap = cap_master_cap cap' \<Longrightarrow> (is_pt_cap cap = is_pt_cap cap') \<and> (is_pd_cap cap = is_pd_cap cap')" by (clarsimp simp: cap_master_cap_def is_cap_simps split: cap.splits arch_cap.splits) lemma is_derived_cap_arch_asid_issues: "is_derived_arch cap cap' \<Longrightarrow> cap_master_cap cap = cap_master_cap cap' \<Longrightarrow> ((is_pt_cap cap \<or> is_pd_cap cap) \<longrightarrow> cap_asid cap \<noteq> None) \<and> (is_pg_cap cap \<or> (vs_cap_ref cap = vs_cap_ref cap'))" apply (simp add: is_derived_arch_def) by (auto simp: cap_master_cap_def is_cap_simps cap_asid_def split: cap.splits arch_cap.splits option.splits) definition safe_parent_for_arch :: "cap \<Rightarrow> cap \<Rightarrow> bool" where "safe_parent_for_arch cap parent \<equiv> False" declare safe_parent_for_arch_def[simp] lemma safe_parent_for_arch_not_arch: "\<not>is_arch_cap cap \<Longrightarrow> \<not>safe_parent_for_arch cap p" by (clarsimp simp: safe_parent_for_arch_def is_cap_simps) lemma safe_parent_cap_range_arch: "\<And>cap pcap. safe_parent_for_arch cap pcap \<Longrightarrow> cap_range cap \<subseteq> cap_range pcap" by (clarsimp simp: safe_parent_for_arch_def cap_range_def) end context begin interpretation Arch . requalify_facts replace_cap_invs end end
-- Let's play with agda. -- Am i having fun doing this? @KMx404 module intro where --load the file with C-c - like that data Bool: Set where true : Bool false : Bool data Empty: Set Empty Empty : Empty -- I'm gonna leave this here. Moving to tests
weightConstructionIncubacionInfeccion=function(lags=7, par1_inf=24.206087, par2_inf=2.984198, distribucion_inf ){ texto=paste0("p",distribucion_inf,"(1:lags, par1_inf, par2_inf, lower.tail = FALSE)") omegaLag=rev(eval(parse(text = texto))) omegaLag <- omegaLag / (sum(omegaLag) * par2_inf) return(omegaLag) } R_caso=function(betas, omegas){ lags=length(omegas)-1 initialCases=as.matrix(rep(betas[1], lags)) cases=betas initialVector=initialCases #Generate expectation Matrix longCases=c(initialVector,cases) casesMatrix_T=matrix(0,length(longCases)-lags,lags+1) for(i in 1:dim(casesMatrix_T)[1]){ casesMatrix_T[i,]=longCases[i:(i+lags)] } t=as.vector(casesMatrix_T%*%omegas) return(t) }
(* Title: HOL/Auth/n_german_lemma_inv__13_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_german Protocol Case Study*} theory n_german_lemma_inv__13_on_rules imports n_german_lemma_on_inv__13 begin section{*All lemmas on causal relation between inv__13*} lemma lemma_inv__13_on_rules: assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__13 p__Inv1 p__Inv2)" shows "invHoldForRule s f r (invariants N)" proof - have c1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)\<or> (\<exists> i. i\<le>N\<and>r=n_SendReqS i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" apply (cut_tac b1, auto) done moreover { assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_StoreVsinv__13) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendReqSVsinv__13) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendReqE__part__0Vsinv__13) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendReqE__part__1Vsinv__13) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqSVsinv__13) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqEVsinv__13) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInv__part__0Vsinv__13) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInv__part__1Vsinv__13) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInvAckVsinv__13) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__13) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendGntSVsinv__13) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendGntEVsinv__13) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvGntSVsinv__13) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvGntEVsinv__13) done } ultimately show "invHoldForRule s f r (invariants N)" by satx qed end
## Integration over Polytopes #### Extra dependencies : matplotlib (if using methods : plot_polytope and plot_polynomial) ```python from sympy import sqrt from sympy.abc import x, y, z from sympy.geometry import * from sympy.integrals.intpoly import * ``` ## Methods : ### polytope_integrate(poly, expr, **kwargs) : Pre-processes the input data for integrating univariate/bivariate polynomials over 2-Polytopes. poly(Polygon) : 2-Polytope expr(SymPy expression) : uni/bi-variate polynomial Optional Parameters clockwise(Boolean) : If user is not sure about orientation of vertices and wants to clockwise sort the points. max_degree(Integer) : Maximum degree of any monomial of the input polynomial. #### Examples : ```python triangle = Polygon(Point(0,0), Point(1,1), Point(1,0)) plot_polytope(triangle) print("Area of Triangle with vertices : (0,0), (1,1), (1,0) : ", polytope_integrate(triangle, 1)) print("x*y integrated over Triangle with vertices : (0,0), (1,1), (1,0) : ", polytope_integrate(triangle, x*y),"\n") hexagon = Polygon(Point(0, 0), Point(-sqrt(3) / 2, 0.5), Point(-sqrt(3) / 2, 3 / 2), Point(0, 2), Point(sqrt(3) / 2, 3 / 2), Point(sqrt(3) / 2, 0.5)) plot_polytope(hexagon) print("Area of regular hexagon with unit side length : ", polytope_integrate(hexagon, 1)) print("x + y**2 integrated over regular hexagon with unit side length : ", polytope_integrate(hexagon, x + y**2)) polys = [1, x, y, x*y] print("1, x, y, x*y integrated over hexagon : ", polytope_integrate(hexagon, polys, max_degree=2)) ``` ### integration_reduction(facets, index, a, b, expr, dims, degree) : facets : List of facets that decide the region enclose by 2-Polytope. index : The index of the facet with respect to which the integral is supposed to be found. a, b : Hyperplane parameters corresponding to facets. expr : Uni/Bi-variate Polynomial dims : List of symbols denoting axes degree : Degree of the homogeneous polynoimal(expr) This is a helper function for polytope_integrate. It relates the result of the integral of a polynomial over a d-dimensional entity to the result of the same integral of that polynomial over the (d - 1)-dimensional facet[index]. For the 2D case, surface integral --> line integrals --> evaluation of polynomial at vertices of line segments For the 3D case, volume integral --> 2D use case The only minor limitation is that some lines of code are 2D specific, but that can be easily changed. Note that this function is a helper one and works for a facet which bounds the polytope(i.e. the intersection point with the other facets is required), not for an independent line. #### Examples: ```python facets = [Segment2D(Point(0, 0), Point(1, 1)), Segment2D(Point(1, 1), Point(1, 0)), Segment2D(Point(0, 0), Point(1, 0))] print(integration_reduction(facets, 0, (0, 1), 0, 1, [x, y], 0)) print(integration_reduction(facets, 1, (0, 1), 0, 1, [x, y], 0)) print(integration_reduction(facets, 2, (0, 1), 0, 1, [x, y], 0)) ``` ### hyperplane_parameters(poly) : poly : 2-Polytope Returns the list of hyperplane parameters for facets of the polygon. Limitation : 2D specific. #### Examples: ```python triangle = Polygon(Point(0,0), Point(1,1), Point(1,0)) hyperplane_parameters(triangle) ``` ### best_origin(a, b, lineseg, expr) : a, b : Line parameters of the line-segment expr : Uni/Bi-variate polynomial Returns a point on the lineseg whose vector inner product with the divergence of expr yields an expression with the least maximum total power. This is for reducing the number of computations in the integration reduction call. Limitation : 2D specific. #### Examples: ```python print("Best origin for x**3*y on x + y = 3 : ", best_origin((1,1), 3, Segment2D(Point(0, 3), Point(3, 0)), x**3*y)) print("Best origin for x*y**3 on x + y = 3 : ",best_origin((1,1), 3, Segment2D(Point(0, 3), Point(3, 0)), x*y**3)) ``` ### decompose(expr, separate=False) : expr : Uni/Bi-variate polynomial. separate(default : False) : If separate is True then return list of constituting monomials. Returns a dictionary of the terms having same total power. This is done to get homogeneous polynomials of different degrees from the expression. #### Examples: ```python print(decompose(1 + x + x**2 + x*y)) print(decompose(x**2 + x + y + 1 + x**3 + x**2*y + y**4 + x**3*y + y**2*x**2)) print(decompose(x**2 + x + y + 1 + x**3 + x**2*y + y**4 + x**3*y + y**2*x**2, 1)) ``` ### norm(expr) : point : Tuple/SymPy Point object/Dictionary Returns Euclidean norm of the point object. #### Examples: ```python print(norm((1, 2))) print(norm(Point(1, 2))) print(norm({x: 3, y: 3, z: 1})) ``` ### intersection(lineseg_1, lineseg_2) : lineseg_1, lineseg_2 : The input line segements whose intersection is to be found. Returns intersection point of two lines of which lineseg_1, lineseg_2 are part of. This function is called for adjacent line segments so the intersection point is always present with line segment boundaries. #### Examples: ```python print(intersection(Segment2D(Point(0, 0), Point(2, 2)), Segment2D(Point(1, 0), Point(0, 1)))) print(intersection(Segment2D(Point(2, 0), Point(2, 2)), Segment2D(Point(0, 0), Point(4, 4)))) ``` ### is_vertex(ent) : ent : Geometrical entity to denote a vertex. Returns True if ent is a vertex. Currently tuples of length 2 or 3 and SymPy Point object are supported. #### Examples: ```python print(is_vertex(Point(2, 8))) print(is_vertex(Point(2, 8, 1))) print(is_vertex((1, 1))) print(is_vertex([2, 9])) print(is_vertex(Polygon(Point(0, 0), Point(1, 1), Point(1, 0)))) ``` ### plot_polytope(poly) : poly : 2-Polytope Plots the 2-Polytope. Currently just defers it to plotting module in SymPy which in turn uses matplotlib. #### Examples: ```python hexagon = Polygon(Point(0, 0), Point(-sqrt(3) / 2, 0.5), Point(-sqrt(3) / 2, 3 / 2), Point(0, 2), Point(sqrt(3) / 2, 3 / 2), Point(sqrt(3) / 2, 0.5)) plot_polytope(hexagon) twist = Polygon(Point(-1, 1), Point(0, 0), Point(1, 1), Point(1, -1), Point(0, 0), Point(-1, -1)) plot_polytope(twist) ``` ### plot_polynomial(expr) : expr : The uni/bi-variate polynomial to plot Plots the polynomial. Currently just defers it to plotting module in SymPy which in turn uses matplotlib. #### Examples: ```python expr = x**2 plot_polynomial(expr) expr = x*y plot_polynomial(expr) ``` ```python ```
(* Title: HOL/Auth/n_germanSimp_lemma_on_inv__51.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_germanSimp Protocol Case Study*} theory n_germanSimp_lemma_on_inv__51 imports n_germanSimp_base begin section{*All lemmas on causal relation between inv__51 and some rule r*} lemma n_RecvReqSVsinv__51: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__51 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvReqS N i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__51 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Ident ''Chan3'') p__Inv4) ''Cmd'')) (Const InvAck)) (eqn (IVar (Ident ''CurCmd'')) (Const Empty))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Ident ''Chan3'') p__Inv4) ''Cmd'')) (Const InvAck)) (eqn (IVar (Ident ''CurCmd'')) (Const Empty))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Ident ''Chan3'') p__Inv4) ''Cmd'')) (Const InvAck)) (eqn (IVar (Ident ''CurCmd'')) (Const Empty))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvReqE__part__0Vsinv__51: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__0 N i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__51 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvReqE__part__0 N i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__51 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvReqE__part__1Vsinv__51: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__1 N i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__51 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvReqE__part__1 N i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__51 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInvAckVsinv__51: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__51 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInvAck i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__51 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Para (Ident ''ShrSet'') p__Inv3)) (Const true)) (eqn (IVar (Ident ''CurCmd'')) (Const ReqS))) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv4) ''Cmd'')) (Const Inv))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvInvAckVsinv__51: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__51 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvInvAck i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__51 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendGntSVsinv__51: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__51 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntS i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__51 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendGntEVsinv__51: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__51 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntE N i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__51 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_StoreVsinv__51: assumes a1: "\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__51 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvGntSVsinv__51: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvGntS i" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__51 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvGntEVsinv__51: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvGntE i" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__51 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendInv__part__0Vsinv__51: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__51 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendInv__part__1Vsinv__51: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__51 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
Require Import TestSuite.admit. Set Implicit Arguments. Generalizable All Variables. Set Asymmetric Patterns. Set Universe Polymorphism. Delimit Scope object_scope with object. Delimit Scope morphism_scope with morphism. Delimit Scope category_scope with category. Delimit Scope functor_scope with functor. Local Open Scope category_scope. Record SpecializedCategory (obj : Type) := { Object :> _ := obj; Morphism : obj -> obj -> Type; Compose : forall s d d', Morphism d d' -> Morphism s d -> Morphism s d' }. Bind Scope category_scope with SpecializedCategory. Bind Scope object_scope with Object. Bind Scope morphism_scope with Morphism. Arguments Object {obj%type} C%category / : rename. Arguments Morphism {obj%type} !C%category s d : rename. (* , simpl nomatch. *) Arguments Compose {obj%type} [!C%category s%object d%object d'%object] m1%morphism m2%morphism : rename. Record Category := { CObject : Type; UnderlyingCategory :> @SpecializedCategory CObject }. Definition GeneralizeCategory `(C : @SpecializedCategory obj) : Category. refine {| CObject := C.(Object) |}; auto. (* Changing this [auto] to [assumption] removes the universe inconsistency. *) Defined. Coercion GeneralizeCategory : SpecializedCategory >-> Category. Record SpecializedFunctor `(C : @SpecializedCategory objC) `(D : @SpecializedCategory objD) := { ObjectOf :> objC -> objD; MorphismOf : forall s d, C.(Morphism) s d -> D.(Morphism) (ObjectOf s) (ObjectOf d) }. Section Functor. Context (C D : Category). Definition Functor := SpecializedFunctor C D. End Functor. Bind Scope functor_scope with SpecializedFunctor. Bind Scope functor_scope with Functor. Arguments SpecializedFunctor {objC} C {objD} D. Arguments Functor C D. Arguments ObjectOf {objC%type C%category objD%type D%category} F%functor c%object : rename, simpl nomatch. Arguments MorphismOf {objC%type} [C%category] {objD%type} [D%category] F%functor [s%object d%object] m%morphism : rename, simpl nomatch. Section FunctorComposition. Context `(B : @SpecializedCategory objB). Context `(C : @SpecializedCategory objC). Context `(D : @SpecializedCategory objD). Context `(E : @SpecializedCategory objE). Definition ComposeFunctors (G : SpecializedFunctor D E) (F : SpecializedFunctor C D) : SpecializedFunctor C E := Build_SpecializedFunctor C E (fun c => G (F c)) (fun _ _ m => G.(MorphismOf) (F.(MorphismOf) m)). End FunctorComposition. Record SpecializedNaturalTransformation `{C : @SpecializedCategory objC} `{D : @SpecializedCategory objD} (F G : SpecializedFunctor C D) := { ComponentsOf :> forall c, D.(Morphism) (F c) (G c) }. Definition ProductCategory `(C : @SpecializedCategory objC) `(D : @SpecializedCategory objD) : @SpecializedCategory (objC * objD)%type := @Build_SpecializedCategory _ (fun s d => (C.(Morphism) (fst s) (fst d) * D.(Morphism) (snd s) (snd d))%type) (fun s d d' m2 m1 => (Compose (fst m2) (fst m1), Compose (snd m2) (snd m1))). Infix "*" := ProductCategory : category_scope. Section ProductCategoryFunctors. Context `{C : @SpecializedCategory objC}. Context `{D : @SpecializedCategory objD}. Definition fst_Functor : SpecializedFunctor (C * D) C := Build_SpecializedFunctor (C * D) C (@fst _ _) (fun _ _ => @fst _ _). Definition snd_Functor : SpecializedFunctor (C * D) D := Build_SpecializedFunctor (C * D) D (@snd _ _) (fun _ _ => @snd _ _). End ProductCategoryFunctors. Definition OppositeCategory `(C : @SpecializedCategory objC) : @SpecializedCategory objC := @Build_SpecializedCategory objC (fun s d => Morphism C d s) (fun _ _ _ m1 m2 => Compose m2 m1). Section OppositeFunctor. Context `(C : @SpecializedCategory objC). Context `(D : @SpecializedCategory objD). Variable F : SpecializedFunctor C D. Let COp := OppositeCategory C. Let DOp := OppositeCategory D. Definition OppositeFunctor : SpecializedFunctor COp DOp := Build_SpecializedFunctor COp DOp (fun c : COp => F c : DOp) (fun (s d : COp) (m : C.(Morphism) d s) => MorphismOf F (s := d) (d := s) m). End OppositeFunctor. Section FunctorProduct. Context `(C : @SpecializedCategory objC). Context `(D : @SpecializedCategory objD). Context `(D' : @SpecializedCategory objD'). Definition FunctorProduct (F : Functor C D) (F' : Functor C D') : SpecializedFunctor C (D * D'). match goal with | [ |- SpecializedFunctor ?C0 ?D0 ] => refine (Build_SpecializedFunctor C0 D0 (fun c => (F c, F' c)) (fun s d m => (MorphismOf F m, MorphismOf F' m))) end. Defined. End FunctorProduct. Section FunctorProduct'. Context `(C : @SpecializedCategory objC). Context `(D : @SpecializedCategory objD). Context `(C' : @SpecializedCategory objC'). Context `(D' : @SpecializedCategory objD'). Variable F : Functor C D. Variable F' : Functor C' D'. Definition FunctorProduct' : SpecializedFunctor (C * C') (D * D') := FunctorProduct (ComposeFunctors F fst_Functor) (ComposeFunctors F' snd_Functor). End FunctorProduct'. (** XXX TODO(jgross): Change this to [FunctorProduct]. *) Infix "*" := FunctorProduct' : functor_scope. Definition TypeCat : @SpecializedCategory Type := (@Build_SpecializedCategory Type (fun s d => s -> d) (fun _ _ _ f g => (fun x => f (g x)))). Section HomFunctor. Context `(C : @SpecializedCategory objC). Let COp := OppositeCategory C. Definition CovariantHomFunctor (A : COp) : SpecializedFunctor C TypeCat := Build_SpecializedFunctor C TypeCat (fun X : C => C.(Morphism) A X : TypeCat) (fun X Y f => (fun g : C.(Morphism) A X => Compose f g)). Definition hom_functor_object_of (c'c : COp * C) := C.(Morphism) (fst c'c) (snd c'c) : TypeCat. Definition hom_functor_morphism_of (s's : (COp * C)%type) (d'd : (COp * C)%type) (hf : (COp * C).(Morphism) s's d'd) : TypeCat.(Morphism) (hom_functor_object_of s's) (hom_functor_object_of d'd). unfold hom_functor_object_of in *. destruct s's as [ s' s ], d'd as [ d' d ]. destruct hf as [ h f ]. intro g. exact (Compose f (Compose g h)). Defined. Definition HomFunctor : SpecializedFunctor (COp * C) TypeCat := Build_SpecializedFunctor (COp * C) TypeCat (fun c'c : COp * C => C.(Morphism) (fst c'c) (snd c'c) : TypeCat) (fun X Y (hf : (COp * C).(Morphism) X Y) => hom_functor_morphism_of hf). End HomFunctor. Section FullFaithful. Context `(C : @SpecializedCategory objC). Context `(D : @SpecializedCategory objD). Variable F : SpecializedFunctor C D. Let COp := OppositeCategory C. Let DOp := OppositeCategory D. Let FOp := OppositeFunctor F. Definition InducedHomNaturalTransformation : SpecializedNaturalTransformation (HomFunctor C) (ComposeFunctors (HomFunctor D) (FOp * F)) := (Build_SpecializedNaturalTransformation (HomFunctor C) (ComposeFunctors (HomFunctor D) (FOp * F)) (fun sd : (COp * C) => MorphismOf F (s := _) (d := _))). End FullFaithful. Definition FunctorCategory `(C : @SpecializedCategory objC) `(D : @SpecializedCategory objD) : @SpecializedCategory (SpecializedFunctor C D). refine (@Build_SpecializedCategory _ (SpecializedNaturalTransformation (C := C) (D := D)) _); admit. Defined. Notation "C ^ D" := (FunctorCategory D C) : category_scope. Section Yoneda. Context `(C : @SpecializedCategory objC). Let COp := OppositeCategory C. Section Yoneda. Let Yoneda_NT s d (f : COp.(Morphism) s d) : SpecializedNaturalTransformation (CovariantHomFunctor C s) (CovariantHomFunctor C d) := Build_SpecializedNaturalTransformation (CovariantHomFunctor C s) (CovariantHomFunctor C d) (fun c : C => (fun m : C.(Morphism) _ _ => Compose m f)). Definition Yoneda : SpecializedFunctor COp (TypeCat ^ C) := Build_SpecializedFunctor COp (TypeCat ^ C) (fun c : COp => CovariantHomFunctor C c : TypeCat ^ C) (fun s d (f : Morphism COp s d) => Yoneda_NT s d f). End Yoneda. End Yoneda. Section FullyFaithful. Context `(C : @SpecializedCategory objC). Set Printing Universes. Check InducedHomNaturalTransformation (Yoneda C). (* Error: Universe inconsistency (cannot enforce Top.865 = Top.851 because Top.851 < Top.869 <= Top.864 <= Top.865). *) End FullyFaithful.
(** * Hoare: Hoare Logic, Part I *) Set Warnings "-notation-overridden,-parsing". Require Import Maps. From Coq Require Import Bool.Bool. From Coq Require Import Arith.Arith. From Coq Require Import Arith.EqNat. From Coq Require Import Arith.PeanoNat. Import Nat. From Coq Require Import Lia. Require Export Imp. (** In the final chaper of _Logical Foundations_ (_Software Foundations_, volume 1), we began applying the mathematical tools developed in the first part of the course to studying the theory of a small programming language, Imp. - We defined a type of _abstract syntax trees_ for Imp, together with an _evaluation relation_ (a partial function on states) that specifies the _operational semantics_ of programs. The language we defined, though small, captures some of the key features of full-blown languages like C, C++, and Java, including the fundamental notion of mutable state and some common control structures. - We proved a number of _metatheoretic properties_ -- "meta" in the sense that they are properties of the language as a whole, rather than of particular programs in the language. These included: - determinism of evaluation - equivalence of some different ways of writing down the definitions (e.g., functional and relational definitions of arithmetic expression evaluation) - guaranteed termination of certain classes of programs - correctness (in the sense of preserving meaning) of a number of useful program transformations - behavioral equivalence of programs (in the [Equiv] chapter). *) (** If we stopped here, we would already have something useful: a set of tools for defining and discussing programming languages and language features that are mathematically precise, flexible, and easy to work with, applied to a set of key properties. All of these properties are things that language designers, compiler writers, and users might care about knowing. Indeed, many of them are so fundamental to our understanding of the programming languages we deal with that we might not consciously recognize them as "theorems." But properties that seem intuitively obvious can sometimes be quite subtle (sometimes also subtly wrong!). We'll return to the theme of metatheoretic properties of whole languages later in this volume when we discuss _types_ and _type soundness_. In this chapter, though, we turn to a different set of issues. *) (** Our goal is to carry out some simple examples of _program verification_ -- i.e., to use the precise definition of Imp to prove formally that particular programs satisfy particular specifications of their behavior. We'll develop a reasoning system called _Floyd-Hoare Logic_ -- often shortened to just _Hoare Logic_ -- in which each of the syntactic constructs of Imp is equipped with a generic "proof rule" that can be used to reason compositionally about the correctness of programs involving this construct. Hoare Logic originated in the 1960s, and it continues to be the subject of intensive research right up to the present day. It lies at the core of a multitude of tools that are being used in academia and industry to specify and verify real software systems. Hoare Logic combines two beautiful ideas: a natural way of writing down _specifications_ of programs, and a _compositional proof technique_ for proving that programs are correct with respect to such specifications -- where by "compositional" we mean that the structure of proofs directly mirrors the structure of the programs that they are about. *) (* ################################################################# *) (** * Assertions *) (** An _assertion_ is a claim about the current state of memory. We will use assertions to write program specifications. *) Definition Assertion := state -> Prop. (** For example, - [fun st => st X = 3] holds if the value of [X] according to [st] is [3], - [fun st => True] always holds, and - [fun st => False] never holds. *) (** **** Exercise: 1 star, standard, optional (assertions) Paraphrase the following assertions in English (or your favorite natural language). *) Module ExAssertions. Definition assn1 : Assertion := fun st => st X <= st Y. Definition assn2 : Assertion := fun st => st X = 3 \/ st X <= st Y. Definition assn3 : Assertion := fun st => st Z * st Z <= st X /\ ~ (((S (st Z)) * (S (st Z))) <= st X). Definition assn4 : Assertion := fun st => st Z = max (st X) (st Y). (* FILL IN HERE *) End ExAssertions. (** [] *) (** This way of writing assertions can be a little bit heavy, for two reasons: (1) every single assertion that we ever write is going to begin with [fun st => ]; and (2) this state [st] is the only one that we ever use to look up variables in assertions (we will never need to talk about two different memory states at the same time). For discussing examples informally, we'll adopt some simplifying conventions: we'll drop the initial [fun st =>], and we'll write just [X] to mean [st X]. Thus, instead of writing fun st => st X = m we'll write just X = m *) (** This example also illustrates a convention that we'll use throughout the Hoare Logic chapters: in informal assertions, capital letters like [X], [Y], and [Z] are Imp variables, while lowercase letters like [x], [y], [m], and [n] are ordinary Coq variables (of type [nat]). This is why, when translating from informal to formal, we replace [X] with [st X] but leave [m] alone. *) (** Given two assertions [P] and [Q], we say that [P] _implies_ [Q], written [P ->> Q], if, whenever [P] holds in some state [st], [Q] also holds. *) Definition assert_implies (P Q : Assertion) : Prop := forall st, P st -> Q st. Declare Scope hoare_spec_scope. Notation "P ->> Q" := (assert_implies P Q) (at level 80) : hoare_spec_scope. Open Scope hoare_spec_scope. (** (The [hoare_spec_scope] annotation here tells Coq that this notation is not global but is intended to be used in particular contexts. The [Open Scope] tells Coq that this file is one such context.) *) (** We'll also want the "iff" variant of implication between assertions: *) Notation "P <<->> Q" := (P ->> Q /\ Q ->> P) (at level 80) : hoare_spec_scope. (** Our convention can be implemented uses Coq coercions and anotation scopes (much as we did with [%imp] in [Imp]) to automatically lift [aexp]s, numbers, and [Prop]s into [Assertion]s when they appear in the [%assertion] scope or when Coq knows the type of an expression is [Assertion]. *) Definition Aexp : Type := state -> nat. Definition assert_of_Prop (P : Prop) : Assertion := fun _ => P. Definition Aexp_of_nat (n : nat) : Aexp := fun _ => n. Definition Aexp_of_aexp (a : aexp) : Aexp := fun st => aeval st a. Coercion assert_of_Prop : Sortclass >-> Assertion. Coercion Aexp_of_nat : nat >-> Aexp. Coercion Aexp_of_aexp : aexp >-> Aexp. Arguments assert_of_Prop /. Arguments Aexp_of_nat /. Arguments Aexp_of_aexp /. Declare Scope assertion_scope. Bind Scope assertion_scope with Assertion. Bind Scope assertion_scope with Aexp. Delimit Scope assertion_scope with assertion. Notation assert P := (P%assertion : Assertion). Notation mkAexp a := (a%assertion : Aexp). Notation "~ P" := (fun st => ~ assert P st) : assertion_scope. Notation "P /\ Q" := (fun st => assert P st /\ assert Q st) : assertion_scope. Notation "P \/ Q" := (fun st => assert P st \/ assert Q st) : assertion_scope. Notation "P -> Q" := (fun st => assert P st -> assert Q st) : assertion_scope. Notation "P <-> Q" := (fun st => assert P st <-> assert Q st) : assertion_scope. Notation "a = b" := (fun st => mkAexp a st = mkAexp b st) : assertion_scope. Notation "a <> b" := (fun st => mkAexp a st <> mkAexp b st) : assertion_scope. Notation "a <= b" := (fun st => mkAexp a st <= mkAexp b st) : assertion_scope. Notation "a < b" := (fun st => mkAexp a st < mkAexp b st) : assertion_scope. Notation "a >= b" := (fun st => mkAexp a st >= mkAexp b st) : assertion_scope. Notation "a > b" := (fun st => mkAexp a st > mkAexp b st) : assertion_scope. Notation "a + b" := (fun st => mkAexp a st + mkAexp b st) : assertion_scope. Notation "a - b" := (fun st => mkAexp a st - mkAexp b st) : assertion_scope. Notation "a * b" := (fun st => mkAexp a st * mkAexp b st) : assertion_scope. (** One small limitation of this approach is that we don't have an automatic way to coerce function applications that appear within an assertion to make appropriate use of the state. Instead, we use an explicit [ap] operator to lift the function. *) Definition ap {X} (f : nat -> X) (x : Aexp) := fun st => f (x st). Definition ap2 {X} (f : nat -> nat -> X) (x : Aexp) (y : Aexp) (st : state) := f (x st) (y st). Module ExPrettyAssertions. Definition ex1 : Assertion := X = 3. Definition ex2 : Assertion := True. Definition ex3 : Assertion := False. Definition assn1 : Assertion := X <= Y. Definition assn2 : Assertion := X = 3 \/ X <= Y. Definition assn3 : Assertion := Z * Z <= X /\ ~ (((ap S Z) * (ap S Z)) <= X). Definition assn4 : Assertion := Z = ap2 max X Y. End ExPrettyAssertions. (* ################################################################# *) (** * Hoare Triples, Informally *) (** A _Hoare triple_ is a claim about the state before and after executing a command. A standard notation is {P} c {Q} meaning: - If command [c] begins execution in a state satisfying assertion [P], - and if [c] eventually terminates in some final state, - then that final state will satisfy the assertion [Q]. Assertion [P] is called the _precondition_ of the triple, and [Q] is the _postcondition_. Because single braces are already used in other ways in Coq, we'll write Hoare triples with double braces: {{P}} c {{Q}} *) (** For example, - [{{X = 0}} X := X + 1 {{X = 1}}] is a valid Hoare triple, stating that command [X := X + 1] would transform a state in which [X = 0] to a state in which [X = 1]. - [{{X = m}} X := X + 1 {{X = m + 1}}], is also a valid Hoare triple. It's even more descriptive of the exact behavior of that command than the previous example. *) (** **** Exercise: 1 star, standard, optional (triples) Paraphrase the following Hoare triples in English. 1) {{True}} c {{X = 5}} 2) forall m, {{X = m}} c {{X = m + 5)}} 3) {{X <= Y}} c {{Y <= X}} 4) {{True}} c {{False}} 5) forall m, {{X = m}} c {{Y = real_fact m}} 6) forall m, {{X = m}} c {{(Z * Z) <= m /\ ~ (((S Z) * (S Z)) <= m)}} *) (* FILL IN HERE [] *) (** **** Exercise: 1 star, standard, optional (valid_triples) Which of the following Hoare triples are _valid_ -- i.e., the claimed relation between [P], [c], and [Q] is true? 1) {{True}} X := 5 {{X = 5}} 2) {{X = 2}} X := X + 1 {{X = 3}} 3) {{True}} X := 5; Y := 0 {{X = 5}} 4) {{X = 2 /\ X = 3}} X := 5 {{X = 0}} 5) {{True}} skip {{False}} 6) {{False}} skip {{True}} 7) {{True}} while true do skip end {{False}} 8) {{X = 0}} while X = 0 do X := X + 1 end {{X = 1}} 9) {{X = 1}} while ~(X = 0) do X := X + 1 end {{X = 100}} *) (* FILL IN HERE [] *) (* ################################################################# *) (** * Hoare Triples, Formally *) (** We can formalize Hoare triples and their notation in Coq as follows: *) Definition hoare_triple (P : Assertion) (c : com) (Q : Assertion) : Prop := forall st st', st =[ c ]=> st' -> P st -> Q st'. Notation "{{ P }} c {{ Q }}" := (hoare_triple P c Q) (at level 90, c custom com at level 99) : hoare_spec_scope. Check ({{True}} X := 0 {{True}}). (** **** Exercise: 1 star, standard (hoare_post_true) *) (** Prove that if [Q] holds in every state, then any triple with [Q] as its postcondition is valid. *) Theorem hoare_post_true : forall (P Q : Assertion) c, (forall st, Q st) -> {{P}} c {{Q}}. Proof. (* FILL IN HERE *) Admitted. (** [] *) (** **** Exercise: 1 star, standard (hoare_pre_false) *) (** Prove that if [P] holds in no state, then any triple with [P] as its precondition is valid. *) Theorem hoare_pre_false : forall (P Q : Assertion) c, (forall st, ~ (P st)) -> {{P}} c {{Q}}. Proof. (* FILL IN HERE *) Admitted. (** [] *) (* ################################################################# *) (** * Proof Rules *) (** The goal of Hoare logic is to provide a _compositional_ method for proving the validity of specific Hoare triples. That is, we want the structure of a program's correctness proof to mirror the structure of the program itself. To this end, in the sections below, we'll introduce a rule for reasoning about each of the different syntactic forms of commands in Imp -- one for assignment, one for sequencing, one for conditionals, etc. -- plus a couple of "structural" rules for gluing things together. We will then be able to prove programs correct using these proof rules, without ever unfolding the definition of [hoare_triple]. *) (* ================================================================= *) (** ** Assignment *) (** The rule for assignment is the most fundamental of the Hoare logic proof rules. Here's how it works. Consider this incomplete Hoare triple: {{ ??? }} X := Y {{ X = 1 }} We want to assign [Y] to [X] and finish in a state where [X] is [1]. What could the precondition be? One possibility is [Y = 1], because if [Y] is already [1] then assigning it to [X] causes [X] to be [1]. That leads to a valid Hoare triple: {{ Y = 1 }} X := Y {{ X = 1 }} It may seem as though coming up with that precondition must have taken some clever thought. But there is a mechanical way we could have done it: if we take the postcondition [X = 1] and in it replace [X] with [Y]---that is, replace the left-hand side of the assignment statement with the right-hand side---we get the precondition, [Y = 1]. *) (** That same technique works in more complicated cases. For example, {{ ??? }} X := X + Y {{ X = 1 }} If we replace the [X] in [X = 1] with [X + Y], we get [X + Y = 1]. That again leads to a valid Hoare triple: {{ X + Y = 1 }} X := X + Y {{ X = 1 }} Why does this technique work? The postcondition identifies some property [P] that we want to hold of the variable [X] being assigned. In this case, [P] is "equals [1]". To complete the triple and make it valid, we need to identify a precondition that guarantees that property will hold of [X]. Such a precondition must ensure that the same property holds of _whatever is being assigned to_ [X]. So, in the example, we need "equals [1]" to hold of [X + Y]. That's exactly what the technique guarantees. *) (** In general, the postcondition could be some arbitrary assertion [Q], and the right-hand side of the assignment could be some arithmetic expression [a]: {{ ??? }} X := a {{ Q }} The precondition would then be [Q], but with any occurrences of [X] in it replaced by [a]. Let's introduce a notation for this idea of replacing occurrences: Define [Q [X |-> a]] to mean "[Q] where [a] is substituted in place of [X]". That yields the Hoare logic rule for assignment: {{ Q [X |-> a] }} X := a {{ Q }} One way of reading that rule is: If you want statement [X := a] to terminate in a state that satisfies assertion [Q], then it suffices to start in a state that also satisfies [Q], except where [a] is substituted for every occurrence of [X]. To many people, this rule seems "backwards" at first, because it proceeds from the postcondition to the precondition. Actually it makes good sense to go in this direction: the postcondition is often what is more important, because it characterizes what we can assume afer running the code. Nonetheless, it's also possible to formulate a "forward" assignment rule. We'll do that later in some exercises. *) (** Here are some valid instances of the assignment rule: {{ (X <= 5) [X |-> X + 1] }} (that is, X + 1 <= 5) X := X + 1 {{ X <= 5 }} {{ (X = 3) [X |-> 3] }} (that is, 3 = 3) X := 3 {{ X = 3 }} {{ (0 <= X /\ X <= 5) [X |-> 3] (that is, 0 <= 3 /\ 3 <= 5) X := 3 {{ 0 <= X /\ X <= 5 }} *) (** To formalize the rule, we must first formalize the idea of "substituting an expression for an Imp variable in an assertion", which we refer to as assertion substitution, or [assn_sub]. That is, given a proposition [P], a variable [X], and an arithmetic expression [a], we want to derive another proposition [P'] that is just the same as [P] except that [P'] should mention [a] wherever [P] mentions [X]. *) (** Since [P] is an arbitrary Coq assertion, we can't directly "edit" its text. However, we can achieve the same effect by evaluating [P] in an updated state: *) Definition assn_sub X a (P:Assertion) : Assertion := fun (st : state) => P (X !-> aeval st a ; st). Notation "P [ X |-> a ]" := (assn_sub X a P) (at level 10, X at next level, a custom com). (** That is, [P [X |-> a]] stands for an assertion -- let's call it [P'] -- that is just like [P] except that, wherever [P] looks up the variable [X] in the current state, [P'] instead uses the value of the expression [a]. *) (** To see how this works, let's calculate what happens with a couple of examples. First, suppose [P'] is [(X <= 5) [X |-> 3]] -- that is, more formally, [P'] is the Coq expression fun st => (fun st' => st' X <= 5) (X !-> aeval st 3 ; st), which simplifies to fun st => (fun st' => st' X <= 5) (X !-> 3 ; st) and further simplifies to fun st => ((X !-> 3 ; st) X) <= 5 and finally to fun st => 3 <= 5. That is, [P'] is the assertion that [3] is less than or equal to [5] (as expected). *) (** For a more interesting example, suppose [P'] is [(X <= 5) [X |-> X + 1]]. Formally, [P'] is the Coq expression fun st => (fun st' => st' X <= 5) (X !-> aeval st (X + 1) ; st), which simplifies to fun st => (X !-> aeval st (X + 1) ; st) X <= 5 and further simplifies to fun st => (aeval st (X + 1)) <= 5. That is, [P'] is the assertion that [X + 1] is at most [5]. *) (** Now, using the concept of substitution, we can give the precise proof rule for assignment: ------------------------------ (hoare_asgn) {{Q [X |-> a]}} X := a {{Q}} *) (** We can prove formally that this rule is indeed valid. *) Theorem hoare_asgn : forall Q X a, {{Q [X |-> a]}} X := a {{Q}}. Proof. unfold hoare_triple. intros Q X a st st' HE HQ. inversion HE. subst. unfold assn_sub in HQ. assumption. Qed. (** Here's a first formal proof using this rule. *) Example assn_sub_example : {{(X < 5) [X |-> X + 1]}} X := X + 1 {{X < 5}}. Proof. (* WORKED IN CLASS *) apply hoare_asgn. Qed. (** (Of course, what would be even more helpful is to prove this simpler triple: {{X < 4}} X := X + 1 {{X < 5}} We will see how to do so in the next section. *) (** **** Exercise: 2 stars, standard, optional (hoare_asgn_examples) Complete these Hoare triples... 1) {{ ??? }} X ::= 2 * X {{ X <= 10 }} 2) {{ ??? }} X := 3 {{ 0 <= X /\ X <= 5 }} ...using the names [assn_sub_ex1] and [assn_sub_ex2], and prove both with just [apply hoare_asgn]. If you find that tactic doesn't suffice, double check that you have completed the triple properly. *) (* FILL IN HERE *) (* Do not modify the following line: *) Definition manual_grade_for_hoare_asgn_examples : option (nat*string) := None. (** [] *) (** **** Exercise: 2 stars, standard, especially useful (hoare_asgn_wrong) The assignment rule looks backward to almost everyone the first time they see it. If it still seems puzzling, it may help to think a little about alternative "forward" rules. Here is a seemingly natural one: ------------------------------ (hoare_asgn_wrong) {{ True }} X := a {{ X = a }} Give a counterexample showing that this rule is incorrect and argue informally that it is really a counterexample. (Hint: The rule universally quantifies over the arithmetic expression [a], and your counterexample needs to exhibit an [a] for which the rule doesn't work.) *) (* FILL IN HERE *) (* Do not modify the following line: *) Definition manual_grade_for_hoare_asgn_wrong : option (nat*string) := None. (** [] *) (** **** Exercise: 3 stars, advanced (hoare_asgn_fwd) However, by using a _parameter_ [m] (a Coq number) to remember the original value of [X] we can define a Hoare rule for assignment that does, intuitively, "work forwards" rather than backwards. ------------------------------------------ (hoare_asgn_fwd) {{fun st => P st /\ st X = m}} X := a {{fun st => P st' /\ st X = aeval st' a }} (where st' = (X !-> m ; st)) Note that we use the original value of [X] to reconstruct the state [st'] before the assignment took place. Prove that this rule is correct. (Also note that this rule is more complicated than [hoare_asgn].) *) Theorem hoare_asgn_fwd : forall m a P, {{fun st => P st /\ st X = m}} X := a {{fun st => P (X !-> m ; st) /\ st X = aeval (X !-> m ; st) a }}. Proof. (* FILL IN HERE *) Admitted. (** [] *) (** **** Exercise: 2 stars, advanced, optional (hoare_asgn_fwd_exists) Another way to define a forward rule for assignment is to existentially quantify over the previous value of the assigned variable. Prove that it is correct. ------------------------------------ (hoare_asgn_fwd_exists) {{fun st => P st}} X := a {{fun st => exists m, P (X !-> m ; st) /\ st X = aeval (X !-> m ; st) a }} *) Theorem hoare_asgn_fwd_exists : forall a P, {{fun st => P st}} X := a {{fun st => exists m, P (X !-> m ; st) /\ st X = aeval (X !-> m ; st) a }}. Proof. (* FILL IN HERE *) Admitted. (** [] *) (* ================================================================= *) (** ** Consequence *) (** Sometimes the preconditions and postconditions we get from the Hoare rules won't quite be the ones we want in the particular situation at hand -- they may be logically equivalent but have a different syntactic form that fails to unify with the goal we are trying to prove, or they actually may be logically weaker (for preconditions) or stronger (for postconditions) than what we need. *) (** For instance, while {{(X = 3) [X |-> 3]}} X := 3 {{X = 3}}, follows directly from the assignment rule, {{True}} X := 3 {{X = 3}} does not. This triple is valid, but it is not an instance of [hoare_asgn] because [True] and [(X = 3) [X |-> 3]] are not syntactically equal assertions. However, they are logically _equivalent_, so if one triple is valid, then the other must certainly be as well. We can capture this observation with the following rule: {{P'}} c {{Q}} P <<->> P' ----------------------------- (hoare_consequence_pre_equiv) {{P}} c {{Q}} *) (** Taking this line of thought a bit further, we can see that strengthening the precondition or weakening the postcondition of a valid triple always produces another valid triple. This observation is captured by two _Rules of Consequence_. {{P'}} c {{Q}} P ->> P' ----------------------------- (hoare_consequence_pre) {{P}} c {{Q}} {{P}} c {{Q'}} Q' ->> Q ----------------------------- (hoare_consequence_post) {{P}} c {{Q}} *) (** Here are the formal versions: *) Theorem hoare_consequence_pre : forall (P P' Q : Assertion) c, {{P'}} c {{Q}} -> P ->> P' -> {{P}} c {{Q}}. Proof. unfold hoare_triple, "->>". intros P P' Q c Hhoare Himp st st' Heval Hpre. apply Hhoare with (st := st). - assumption. - apply Himp. assumption. Qed. Theorem hoare_consequence_post : forall (P Q Q' : Assertion) c, {{P}} c {{Q'}} -> Q' ->> Q -> {{P}} c {{Q}}. Proof. unfold hoare_triple, "->>". intros P Q Q' c Hhoare Himp st st' Heval Hpre. apply Himp. apply Hhoare with (st := st). - assumption. - assumption. Qed. (** For example, we can use the first consequence rule like this: {{ True }} ->> {{ (X = 1) [X |-> 1] }} X := 1 {{ X = 1 }} Or, formally... *) Example hoare_asgn_example1 : {{True}} X := 1 {{X = 1}}. Proof. (* WORKED IN CLASS *) apply hoare_consequence_pre with (P' := (X = 1) [X |-> 1]). - apply hoare_asgn. - unfold "->>", assn_sub, t_update. intros st _. simpl. reflexivity. Qed. (** We can also use it to prove the example mentioned earlier. {{ X < 4 }} ->> {{ (X < 5)[X |-> X + 1] }} X := X + 1 {{ X < 5 }} Or, formally ... *) Example assn_sub_example2 : {{X < 4}} X := X + 1 {{X < 5}}. Proof. (* WORKED IN CLASS *) apply hoare_consequence_pre with (P' := (X < 5) [X |-> X + 1]). - apply hoare_asgn. - unfold "->>", assn_sub, t_update. intros st H. simpl in *. lia. Qed. (** Finally, here is a combined rule of consequence that allows us to vary both the precondition and the postcondition. {{P'}} c {{Q'}} P ->> P' Q' ->> Q ----------------------------- (hoare_consequence) {{P}} c {{Q}} *) Theorem hoare_consequence : forall (P P' Q Q' : Assertion) c, {{P'}} c {{Q'}} -> P ->> P' -> Q' ->> Q -> {{P}} c {{Q}}. Proof. intros P P' Q Q' c Htriple Hpre Hpost. apply hoare_consequence_pre with (P' := P'). - apply hoare_consequence_post with (Q' := Q'). + assumption. + assumption. - assumption. Qed. (* ================================================================= *) (** ** Automation *) (** Many of the proofs we have done so far with Hoare triples can be streamlined using the automation techniques that we introduced in the [Auto] chapter of _Logical Foundations_. Recall that the [auto] tactic can be told to [unfold] definitions as part of its proof search. Let's give that hint for the definitions and coercions we're using: *) Hint Unfold assert_implies hoare_triple assn_sub t_update : core. Hint Unfold assert_of_Prop Aexp_of_nat Aexp_of_aexp : core. (** Also recall that [auto] will search for a proof involving [intros] and [apply]. By default, the theorems that it will apply include any of the local hypotheses, as well as theorems in a core database. *) (** The proof of [hoare_consequence_pre], repeated below, looks like an opportune place for such automation, because all it does is [unfold], [intros], and [apply]. It uses [assumption], too, but that's just application of a hypothesis. *) Theorem hoare_consequence_pre' : forall (P P' Q : Assertion) c, {{P'}} c {{Q}} -> P ->> P' -> {{P}} c {{Q}}. Proof. unfold hoare_triple, "->>". intros P P' Q c Hhoare Himp st st' Heval Hpre. apply Hhoare with (st := st). - assumption. - apply Himp. assumption. Qed. (** Merely using [auto], though, doesn't complete the proof. *) Theorem hoare_consequence_pre'' : forall (P P' Q : Assertion) c, {{P'}} c {{Q}} -> P ->> P' -> {{P}} c {{Q}}. Proof. auto. (* no progress *) Abort. (** The problem is the [apply Hhoare with...] part of the proof. Coq isn't able to figure out how to instantiate [st] without some help from us. Recall, though, that there are versions of many tactics that will use _existential variables_ to make progress even when the regular versions of those tactics would get stuck. Here, the [eapply] tactic will introduce an existential variable [?st] as a placeholder for [st], and [eassumption] will instantiate [?st] with [st] when it discovers [st] in assumption [Heval]. By using [eapply] we are essentially telling Coq, "Be patient: The missing part is going to be filled in later in the proof." *) Theorem hoare_consequence_pre''' : forall (P P' Q : Assertion) c, {{P'}} c {{Q}} -> P ->> P' -> {{P}} c {{Q}}. Proof. unfold hoare_triple, "->>". intros P P' Q c Hhoare Himp st st' Heval Hpre. eapply Hhoare. - eassumption. - apply Himp. assumption. Qed. (** Tactic [eauto] will use [eapply] as part of its proof search. So, the entire proof can be done in just one line. *) Theorem hoare_consequence_pre'''' : forall (P P' Q : Assertion) c, {{P'}} c {{Q}} -> P ->> P' -> {{P}} c {{Q}}. Proof. eauto. Qed. (** Of course, it's hard to predict that [eauto] suffices here without having gone through the original proof of [hoare_consequence_pre] to see the tactics it used. But now that we know [eauto] works, it's a good bet that it will also work for [hoare_consequence_post]. *) Theorem hoare_consequence_post' : forall (P Q Q' : Assertion) c, {{P}} c {{Q'}} -> Q' ->> Q -> {{P}} c {{Q}}. Proof. eauto. Qed. (** We can also use [eapply] to streamline a proof, [hoare_asgn_example1], that we did earlier as an example of using the consequence rule: *) Example hoare_asgn_example1' : {{True}} X := 1 {{X = 1}}. Proof. eapply hoare_consequence_pre. (* no need to state an assertion *) - apply hoare_asgn. - unfold "->>", assn_sub, t_update. intros st _. simpl. reflexivity. Qed. (** The final bullet of that proof also looks like a candidate for automation. *) Example hoare_asgn_example1'' : {{True}} X := 1 {{X = 1}}. Proof. eapply hoare_consequence_pre. - apply hoare_asgn. - auto. Qed. (** Now we have quite a nice proof script: it simply identifies the Hoare rules that need to be used and leaves the remaining low-level details up to Coq to figure out. *) (** By now it might be apparent that the _entire_ proof could be automated if we added [hoare_consequence_pre] and [hoare_asgn] to the hint database. We won't do that in this chapter, so that we can get a better understanding of when and how the Hoare rules are used. In the next chapter, [Hoare2], we'll dive deeper into automating entire proofs of Hoare triples. *) (** The other example of using consequence that we did earlier, [hoare_asgn_example2], requires a little more work to automate. We can streamline the first line with [eapply], but we can't just use [auto] for the final bullet, since it needs [omega]. *) Example assn_sub_example2' : {{X < 4}} X := X + 1 {{X < 5}}. Proof. eapply hoare_consequence_pre. - apply hoare_asgn. - auto. (* no progress *) unfold "->>", assn_sub, t_update. intros st H. simpl in *. lia. Qed. (** Let's introduce our own tactic to handle both that bullet and the bullet from example 1: *) Ltac assn_auto := try auto; (* as in example 1, above *) try (unfold "->>", assn_sub, t_update; intros; simpl in *; lia). (* as in example 2 *) Example assn_sub_example2'' : {{X < 4}} X := X + 1 {{X < 5}}. Proof. eapply hoare_consequence_pre. - apply hoare_asgn. - assn_auto. Qed. Example hoare_asgn_example1''': {{True}} X := 1 {{X = 1}}. Proof. eapply hoare_consequence_pre. - apply hoare_asgn. - assn_auto. Qed. (** Again, we have quite a nice proof script. All the low-level details of proof about assertions have been taken care of automatically. Of course, [assn_auto] isn't able to prove everything we could possibly want to know about assertions -- there's no magic here! But it's good enough so far. *) (** **** Exercise: 2 stars, standard (hoare_asgn_examples_2) Prove these triples. Try to make your proof scripts as nicely automated as those above. *) Example assn_sub_ex1' : {{ X <= 5 }} X := 2 * X {{ X <= 10 }}. Proof. (* FILL IN HERE *) Admitted. Example assn_sub_ex2' : {{ 0 <= 3 /\ 3 <= 5 }} X := 3 {{ 0 <= X /\ X <= 5 }}. Proof. (* FILL IN HERE *) Admitted. (** [] *) (* ================================================================= *) (** ** Skip *) (** Since [skip] doesn't change the state, it preserves any assertion [P]: -------------------- (hoare_skip) {{ P }} skip {{ P }} *) Theorem hoare_skip : forall P, {{P}} skip {{P}}. Proof. intros P st st' H HP. inversion H; subst. assumption. Qed. (* ================================================================= *) (** ** Sequencing *) (** If command [c1] takes any state where [P] holds to a state where [Q] holds, and if [c2] takes any state where [Q] holds to one where [R] holds, then doing [c1] followed by [c2] will take any state where [P] holds to one where [R] holds: {{ P }} c1 {{ Q }} {{ Q }} c2 {{ R }} ---------------------- (hoare_seq) {{ P }} c1;c2 {{ R }} *) Theorem hoare_seq : forall P Q R c1 c2, {{Q}} c2 {{R}} -> {{P}} c1 {{Q}} -> {{P}} c1; c2 {{R}}. Proof. unfold hoare_triple. intros P Q R c1 c2 H1 H2 st st' H12 Pre. inversion H12; subst. eauto. Qed. (** Note that, in the formal rule [hoare_seq], the premises are given in backwards order ([c2] before [c1]). This matches the natural flow of information in many of the situations where we'll use the rule, since the natural way to construct a Hoare-logic proof is to begin at the end of the program (with the final postcondition) and push postconditions backwards through commands until we reach the beginning. *) (** Here's an example of a program involving sequencing. Note the use of [hoare_seq] in conjunction with [hoare_consequence_pre] and the [eapply] tactic. *) Example hoare_asgn_example3 : forall (a:aexp) (n:nat), {{a = n}} X := a; skip {{X = n}}. Proof. intros a n. eapply hoare_seq. - (* right part of seq *) apply hoare_skip. - (* left part of seq *) eapply hoare_consequence_pre. + apply hoare_asgn. + assn_auto. Qed. (** Informally, a nice way of displaying a proof using the sequencing rule is as a "decorated program" where the intermediate assertion [Q] is written between [c1] and [c2]: {{ a = n }} X := a; {{ X = n }} <--- decoration for Q skip {{ X = n }} *) (** **** Exercise: 2 stars, standard, especially useful (hoare_asgn_example4) Translate this "decorated program" into a formal proof: {{ True }} ->> {{ 1 = 1 }} X := 1; {{ X = 1 }} ->> {{ X = 1 /\ 2 = 2 }} Y := 2 {{ X = 1 /\ Y = 2 }} Note the use of "[->>]" decorations, each marking a use of [hoare_consequence_pre]. We've started you off by providing a use of [hoare_seq] that explicitly identifies [X = 1] as the intermediate assertion. *) Example hoare_asgn_example4 : {{ True }} X := 1; Y := 2 {{ X = 1 /\ Y = 2 }}. Proof. apply hoare_seq with (Q := (X = 1)%assertion). (* The annotation [%assertion] is needed here to help Coq parse correctly. *) (* FILL IN HERE *) Admitted. (** [] *) (** **** Exercise: 3 stars, standard (swap_exercise) Write an Imp program [c] that swaps the values of [X] and [Y] and show that it satisfies the following specification: {{X <= Y}} c {{Y <= X}} Your proof should not need to use [unfold hoare_triple]. (Hint: Remember that the assignment rule works best when it's applied "back to front," from the postcondition to the precondition. So your proof will want to start at the end and work back to the beginning of your program.) *) Definition swap_program : com (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted. Theorem swap_exercise : {{X <= Y}} swap_program {{Y <= X}}. Proof. (* FILL IN HERE *) Admitted. (** [] *) (** **** Exercise: 4 stars, standard (invalid_triple) Show that {{ a = n }} X := 3;; Y := a {{ Y = n }} is not a valid Hoare triple for some choices of [a] and [n]. Conceptual hint: invent a particular [a] and [n] for which the triple in invalid, then use those to complete the proof. Technical hint: hypothesis [H], below, begins [forall a n, ...]. You'll want to instantiate that for the particular [a] and [n] you've invented. You can do that with [assert] and [apply], but Coq offers an even easier tactic: [specialize]. If you write specialize H with (a := your_a) (n := your_n) the hypothesis will be instantiated on [your_a] and [your_n]. *) Theorem invalid_triple : ~ forall (a : aexp) (n : nat), {{ a = n }} X := 3; Y := a {{ Y = n }}. Proof. unfold hoare_triple. intros H. (* FILL IN HERE *) Admitted. (** [] *) (* ================================================================= *) (** ** Conditionals *) (** What sort of rule do we want for reasoning about conditional commands? Certainly, if the same assertion [Q] holds after executing either of the branches, then it holds after the whole conditional. So we might be tempted to write: {{P}} c1 {{Q}} {{P}} c2 {{Q}} --------------------------------- {{P}} if b then c1 else c2 {{Q}} *) (** However, this is rather weak. For example, using this rule, we cannot show {{ True }} if X = 0 then Y := 2 else Y := X + 1 end {{ X <= Y }} since the rule tells us nothing about the state in which the assignments take place in the "then" and "else" branches. *) (** Fortunately, we can say something more precise. In the "then" branch, we know that the boolean expression [b] evaluates to [true], and in the "else" branch, we know it evaluates to [false]. Making this information available in the premises of the rule gives us more information to work with when reasoning about the behavior of [c1] and [c2] (i.e., the reasons why they establish the postcondition [Q]). {{P /\ b}} c1 {{Q}} {{P /\ ~ b}} c2 {{Q}} ------------------------------------ (hoare_if) {{P}} if b then c1 else c2 end {{Q}} *) (** To interpret this rule formally, we need to do a little work. Strictly speaking, the assertion we've written, [P /\ b], is the conjunction of an assertion and a boolean expression -- i.e., it doesn't typecheck. To fix this, we need a way of formally "lifting" any bexp [b] to an assertion. We'll write [bassn b] for the assertion "the boolean expression [b] evaluates to [true] (in the given state)." *) Definition bassn b : Assertion := fun st => (beval st b = true). Coercion bassn : bexp >-> Assertion. Arguments bassn /. Hint Unfold bassn : core. (** A couple of useful facts about [bassn]: *) Lemma bexp_eval_true : forall b st, beval st b = true -> (bassn b) st. Proof. auto. Qed. Lemma bexp_eval_false : forall b st, beval st b = false -> ~ ((bassn b) st). Proof. congruence. Qed. Hint Resolve bexp_eval_false : core. (** We mentioned the [congruence] tactic in passing in [Auto] when building the [find_rwd] tactic. Like [find_rwd], [congruence] is able to automatically find that both [beval st b = false] and [beval st b = true] are being assumed, notice the contradiction, and [discriminate] to complete the proof. *) (** Now we can formalize the Hoare proof rule for conditionals and prove it correct. *) Theorem hoare_if : forall P Q (b:bexp) c1 c2, {{ P /\ b }} c1 {{Q}} -> {{ P /\ ~ b}} c2 {{Q}} -> {{P}} if b then c1 else c2 end {{Q}}. (** That is (unwrapping the notations): Theorem hoare_if : forall P Q b c1 c2, {{fun st => P st /\ bassn b st}} c1 {{Q}} -> {{fun st => P st /\ ~ (bassn b st)}} c2 {{Q}} -> {{P}} if b then c1 else c2 end {{Q}}. *) Proof. intros P Q b c1 c2 HTrue HFalse st st' HE HP. inversion HE; subst; eauto. Qed. (* ----------------------------------------------------------------- *) (** *** Example *) (** Here is a formal proof that the program we used to motivate the rule satisfies the specification we gave. *) Example if_example : {{True}} if (X = 0) then Y := 2 else Y := X + 1 end {{X <= Y}}. Proof. apply hoare_if. - (* Then *) eapply hoare_consequence_pre. + apply hoare_asgn. + assn_auto. (* no progress *) unfold "->>", assn_sub, t_update, bassn. simpl. intros st [_ H]. apply eqb_eq in H. rewrite H. lia. - (* Else *) eapply hoare_consequence_pre. + apply hoare_asgn. + assn_auto. Qed. (** As we did earlier, it would be nice to eliminate all the low-level proof script that isn't about the Hoare rules. Unfortunately, the [assn_auto] tactic we wrote wasn't quite up to the job. Looking at the proof of [if_example], we can see why. We had to unfold a definition ([bassn]) and use a theorem ([eqb_eq]) that we didn't need in earlier proofs. So, let's add those into our tactic, and clean it up a little in the process. *) Ltac assn_auto' := unfold "->>", assn_sub, t_update, bassn; intros; simpl in *; try rewrite -> eqb_eq in *; (* for equalities *) auto; try lia. (** Now the proof is quite streamlined. *) Example if_example'' : {{True}} if X = 0 then Y := 2 else Y := X + 1 end {{X <= Y}}. Proof. apply hoare_if. - eapply hoare_consequence_pre. + apply hoare_asgn. + assn_auto'. - eapply hoare_consequence_pre. + apply hoare_asgn. + assn_auto'. Qed. (** We can even shorten it a little bit more. *) Example if_example''' : {{True}} if X = 0 then Y := 2 else Y := X + 1 end {{X <= Y}}. Proof. apply hoare_if; eapply hoare_consequence_pre; try apply hoare_asgn; try assn_auto'. Qed. (** For later proofs, it will help to extend [assn_auto'] to handle inequalities, too. *) Ltac assn_auto'' := unfold "->>", assn_sub, t_update, bassn; intros; simpl in *; try rewrite -> eqb_eq in *; try rewrite -> leb_le in *; (* for inequalities *) auto; try lia. (** **** Exercise: 2 stars, standard (if_minus_plus) Prove the theorem below using [hoare_if]. Do not use [unfold hoare_triple]. *) Theorem if_minus_plus : {{True}} if (X <= Y) then Z := Y - X else Y := X + Z end {{Y = X + Z}}. Proof. (* FILL IN HERE *) Admitted. (** [] *) (* ----------------------------------------------------------------- *) (** *** Exercise: One-sided conditionals *) (** In this exercise we consider extending Imp with "one-sided conditionals" of the form [if1 b then c end]. Here [b] is a boolean expression, and [c] is a command. If [b] evaluates to [true], then command [c] is evaluated. If [b] evaluates to [false], then [if1 b then c end] does nothing. We recommend that you complete this exercise before attempting the ones that follow, as it should help solidify your understanding of the material. *) (** The first step is to extend the syntax of commands and introduce the usual notations. (We've done this for you. We use a separate module to prevent polluting the global name space.) *) Module If1. Inductive com : Type := | CSkip : com | CAss : string -> aexp -> com | CSeq : com -> com -> com | CIf : bexp -> com -> com -> com | CWhile : bexp -> com -> com | CIf1 : bexp -> com -> com. Notation "'if1' x 'then' y 'end'" := (CIf1 x y) (in custom com at level 0, x custom com at level 99). Notation "'skip'" := CSkip (in custom com at level 0). Notation "x := y" := (CAss x y) (in custom com at level 0, x constr at level 0, y at level 85, no associativity). Notation "x ; y" := (CSeq x y) (in custom com at level 90, right associativity). Notation "'if' x 'then' y 'else' z 'end'" := (CIf x y z) (in custom com at level 89, x at level 99, y at level 99, z at level 99). Notation "'while' x 'do' y 'end'" := (CWhile x y) (in custom com at level 89, x at level 99, y at level 99). (** **** Exercise: 2 stars, standard (if1_ceval) *) (** Add two new evaluation rules to relation [ceval], below, for [if1]. Let the rules for [if] guide you.*) Reserved Notation "st '=[' c ']=>'' st'" (at level 40, c custom com at level 99, st constr, st' constr at next level). Inductive ceval : com -> state -> state -> Prop := | E_Skip : forall st, st =[ skip ]=> st | E_Ass : forall st a1 n x, aeval st a1 = n -> st =[ x := a1 ]=> (x !-> n ; st) | E_Seq : forall c1 c2 st st' st'', st =[ c1 ]=> st' -> st' =[ c2 ]=> st'' -> st =[ c1 ; c2 ]=> st'' | E_IfTrue : forall st st' b c1 c2, beval st b = true -> st =[ c1 ]=> st' -> st =[ if b then c1 else c2 end ]=> st' | E_IfFalse : forall st st' b c1 c2, beval st b = false -> st =[ c2 ]=> st' -> st =[ if b then c1 else c2 end ]=> st' | E_WhileFalse : forall b st c, beval st b = false -> st =[ while b do c end ]=> st | E_WhileTrue : forall st st' st'' b c, beval st b = true -> st =[ c ]=> st' -> st' =[ while b do c end ]=> st'' -> st =[ while b do c end ]=> st'' (* FILL IN HERE *) where "st '=[' c ']=>' st'" := (ceval c st st'). Hint Constructors ceval : core. (** The following unit tests should be provable simply by [eauto] if you have defined the rules for [if1] correctly. *) Example if1true_test : empty_st =[ if1 X = 0 then X := 1 end ]=> (X !-> 1). Proof. (* FILL IN HERE *) Admitted. Example if1false_test : (X !-> 2) =[ if1 X = 0 then X := 1 end ]=> (X !-> 2). Proof. (* FILL IN HERE *) Admitted. (** [] *) (** Now we have to repeat the definition and notation of Hoare triples, so that they will use the updated [com] type. *) Definition hoare_triple (P : Assertion) (c : com) (Q : Assertion) : Prop := forall st st', st =[ c ]=> st' -> P st -> Q st'. Hint Unfold hoare_triple : core. Notation "{{ P }} c {{ Q }}" := (hoare_triple P c Q) (at level 90, c custom com at level 99) : hoare_spec_scope. (** **** Exercise: 2 stars, standard (hoare_if1) *) (** Invent a Hoare logic proof rule for [if1]. State and prove a theorem named [hoare_if1] that shows the validity of your rule. Use [hoare_if] as a guide. Try to invent a rule that is _complete_, meaning it can be used to prove the correctness of as many one-sided conditionals as possible. Also try to keep your rule _compositional_, meaning that any Imp command that appears in a premise should syntactically be a part of the command in the conclusion. Hint: if you encounter difficulty getting Coq to parse part of your rule as an assertion, try manually indicating that it should be in the assertion scope. For example, if you want [e] to be parsed as an assertion, write it as [(e)%assertion]. *) (* FILL IN HERE *) (** For full credit, prove formally [hoare_if1_good] that your rule is precise enough to show the following valid Hoare triple: {{ X + Y = Z }} if1 ~(Y = 0) then X := X + Y end {{ X = Z }} *) (* Do not modify the following line: *) Definition manual_grade_for_hoare_if1 : option (nat*string) := None. (** [] *) (** Before the next exercise, we need to restate the Hoare rules of consequence (for preconditions) and assignment for the new [com] type. *) Theorem hoare_consequence_pre : forall (P P' Q : Assertion) c, {{P'}} c {{Q}} -> P ->> P' -> {{P}} c {{Q}}. Proof. eauto. Qed. Theorem hoare_asgn : forall Q X a, {{Q [X |-> a]}} (X := a) {{Q}}. Proof. intros Q X a st st' Heval HQ. inversion Heval; subst. auto. Qed. (** **** Exercise: 2 stars, standard (hoare_if1_good) *) (** Prove that your [if1] rule is complete enough for the following valid Hoare triple. Hint: [assn_auto''] once more will get you most but not all the way to a completely automated proof. You can finish manually, or tweak the tactic further. *) Lemma hoare_if1_good : {{ X + Y = Z }} if1 ~(Y = 0) then X := X + Y end {{ X = Z }}. Proof. (* FILL IN HERE *) Admitted. (** [] *) End If1. (* ================================================================= *) (** ** While Loops *) (** The Hoare rule for [while] loops is based on the idea of an _invariant_: an assertion whose truth is guaranteed before and after executing a command. An assertion [P] is an invariant of [c] if {{P}} c {{P}} holds. Note that in the middle of executing [c], the invariant might temporarily become false, but by the end of [c], it must be restored. *) (** As a first attempt at a [while] rule, we could try: {{P}} c {{P}} --------------------------- {{P} while b do c end {{P}} That rule is valid: if [P] is an invariant of [c], as the premise requires, then no matter how many times the loop body executes, [P] is going to be true when the loop finally finishes. But the rule also omits two crucial pieces of information. First, the loop terminates when [b] becomes false. So we can strengthen the postcondition in the conclusion: {{P}} c {{P}} --------------------------------- {{P} while b do c end {{P /\ ~b}} Second, the loop body will be executed only if [b] is true. So we can also strengthen the precondition in the premise: {{P /\ b}} c {{P}} --------------------------------- (hoare_while) {{P} while b do c end {{P /\ ~b}} *) (** That is the Hoare [while] rule. Note how it combines aspects of [skip] and conditionals: - If the loop body executes zero times, the rule is like [skip] in that the precondition survives to become (part of) the postcondition. - Like a conditional, we can assume guard [b] holds on entry to the subcommand. *) Theorem hoare_while : forall P (b:bexp) c, {{P /\ b}} c {{P}} -> {{P}} while b do c end {{P /\ ~ b}}. Proof. intros P b c Hhoare st st' Heval HP. (* We proceed by induction on [Heval], because, in the "keep looping" case, its hypotheses talk about the whole loop instead of just [c]. The [remember] is used to keep the original command in the hypotheses; otherwise, it would be lost in the [induction]. By using [inversion] we clear away all the cases except those involving [while]. *) remember <{while b do c end}> as original_command eqn:Horig. induction Heval; try (inversion Horig; subst; clear Horig); eauto. Qed. (** We say that [P] is a _loop invariant_ of [while b do c end] if [P] suffices to prove [hoare_while] for that loop. Being a loop invariant is different from being an invariant of the body, because it means being able to prove correctness of the loop. For example, [X = 0] is a loop invariant of while X = 2 do X := 1 end even though [X = 0] is not an invariant of [X := 1]. *) (** This is a slightly (but crucially) weaker requirement. For example, if [P] is the assertion [X = 0], then [P] _is_ an invariant of the loop while X = 2 do X := 1 end although it is clearly _not_ preserved by the body of the loop. *) Example while_example : {{X <= 3}} while (X <= 2) do X := X + 1 end {{X = 3}}. Proof. eapply hoare_consequence_post. - apply hoare_while. eapply hoare_consequence_pre. + apply hoare_asgn. + assn_auto''. - assn_auto''. Qed. (** If the loop never terminates, any postcondition will work. *) Theorem always_loop_hoare : forall Q, {{True}} while true do skip end {{Q}}. Proof. intros Q. eapply hoare_consequence_post. - apply hoare_while. apply hoare_post_true. auto. - simpl. intros st [Hinv Hguard]. congruence. Qed. (** Of course, this result is not surprising if we remember that the definition of [hoare_triple] asserts that the postcondition must hold _only_ when the command terminates. If the command doesn't terminate, we can prove anything we like about the post-condition. Hoare rules that specify what happens _if_ commands terminate, without proving that they do, are said to describe a logic of _partial_ correctness. It is also possible to give Hoare rules for _total_ correctness, which additionally specifies that commands must terminate. Total correctness is out of the scope of this textbook. *) (* ----------------------------------------------------------------- *) (** *** Exercise: [REPEAT] *) (** **** Exercise: 4 stars, advanced (hoare_repeat) In this exercise, we'll add a new command to our language of commands: [REPEAT] c [until] b [end]. You will write the evaluation rule for [REPEAT] and add a new Hoare rule to the language for programs involving it. (You may recall that the evaluation rule is given in an example in the [Auto] chapter. Try to figure it out yourself here rather than peeking.) *) Module RepeatExercise. Inductive com : Type := | CSkip : com | CAss : string -> aexp -> com | CSeq : com -> com -> com | CIf : bexp -> com -> com -> com | CWhile : bexp -> com -> com | CRepeat : com -> bexp -> com. (** [REPEAT] behaves like [while], except that the loop guard is checked _after_ each execution of the body, with the loop repeating as long as the guard stays _false_. Because of this, the body will always execute at least once. *) Notation "'repeat' e1 'until' b2 'end'" := (CRepeat e1 b2) (in custom com at level 0, e1 custom com at level 99, b2 custom com at level 99). Notation "'skip'" := CSkip (in custom com at level 0). Notation "x := y" := (CAss x y) (in custom com at level 0, x constr at level 0, y at level 85, no associativity). Notation "x ; y" := (CSeq x y) (in custom com at level 90, right associativity). Notation "'if' x 'then' y 'else' z 'end'" := (CIf x y z) (in custom com at level 89, x at level 99, y at level 99, z at level 99). Notation "'while' x 'do' y 'end'" := (CWhile x y) (in custom com at level 89, x at level 99, y at level 99). (** Add new rules for [REPEAT] to [ceval] below. You can use the rules for [while] as a guide, but remember that the body of a [REPEAT] should always execute at least once, and that the loop ends when the guard becomes true. *) Inductive ceval : state -> com -> state -> Prop := | E_Skip : forall st, st =[ skip ]=> st | E_Ass : forall st a1 n x, aeval st a1 = n -> st =[ x := a1 ]=> (x !-> n ; st) | E_Seq : forall c1 c2 st st' st'', st =[ c1 ]=> st' -> st' =[ c2 ]=> st'' -> st =[ c1 ; c2 ]=> st'' | E_IfTrue : forall st st' b c1 c2, beval st b = true -> st =[ c1 ]=> st' -> st =[ if b then c1 else c2 end ]=> st' | E_IfFalse : forall st st' b c1 c2, beval st b = false -> st =[ c2 ]=> st' -> st =[ if b then c1 else c2 end ]=> st' | E_WhileFalse : forall b st c, beval st b = false -> st =[ while b do c end ]=> st | E_WhileTrue : forall st st' st'' b c, beval st b = true -> st =[ c ]=> st' -> st' =[ while b do c end ]=> st'' -> st =[ while b do c end ]=> st'' (* FILL IN HERE *) where "st '=[' c ']=>' st'" := (ceval st c st'). (** A couple of definitions from above, copied here so they use the new [ceval]. *) Definition hoare_triple (P : Assertion) (c : com) (Q : Assertion) : Prop := forall st st', st =[ c ]=> st' -> P st -> Q st'. Notation "{{ P }} c {{ Q }}" := (hoare_triple P c Q) (at level 90, c custom com at level 99). (** To make sure you've got the evaluation rules for [repeat] right, prove that [ex1_repeat] evaluates correctly. *) Definition ex1_repeat := <{ repeat X := 1; Y := Y + 1 until (X = 1) end }>. Theorem ex1_repeat_works : empty_st =[ ex1_repeat ]=> (Y !-> 1 ; X !-> 1). Proof. (* FILL IN HERE *) Admitted. (** Now state and prove a theorem, [hoare_repeat], that expresses an appropriate proof rule for [repeat] commands. Use [hoare_while] as a model, and try to make your rule as precise as possible. *) (* FILL IN HERE *) (** For full credit, make sure (informally) that your rule can be used to prove the following valid Hoare triple: {{ X > 0 }} repeat Y := X; X := X - 1 until X = 0 end {{ X = 0 /\ Y > 0 }} *) End RepeatExercise. (* Do not modify the following line: *) Definition manual_grade_for_hoare_repeat : option (nat*string) := None. (** [] *) (* ################################################################# *) (** * Summary *) (** So far, we've introduced Hoare Logic as a tool for reasoning about Imp programs. The rules of Hoare Logic are: --------------------------- (hoare_asgn) {{Q [X |-> a]}} X:=a {{Q}} -------------------- (hoare_skip) {{ P }} skip {{ P }} {{ P }} c1 {{ Q }} {{ Q }} c2 {{ R }} ---------------------- (hoare_seq) {{ P }} c1;c2 {{ R }} {{P /\ b}} c1 {{Q}} {{P /\ ~ b}} c2 {{Q}} ------------------------------------ (hoare_if) {{P}} if b then c1 else c2 end {{Q}} {{P /\ b}} c {{P}} ----------------------------------- (hoare_while) {{P}} while b do c end {{P /\ ~ b}} {{P'}} c {{Q'}} P ->> P' Q' ->> Q ----------------------------- (hoare_consequence) {{P}} c {{Q}} In the next chapter, we'll see how these rules are used to prove that programs satisfy specifications of their behavior. *) (* ################################################################# *) (** * Additional Exercises *) (* ================================================================= *) (** ** Havoc *) (** In this exercise, we will derive proof rules for a [HAVOC] command, which is similar to the nondeterministic [any] expression from the the [Imp] chapter. First, we enclose this work in a separate module, and recall the syntax and big-step semantics of Himp commands. *) Module Himp. Inductive com : Type := | CSkip : com | CAss : string -> aexp -> com | CSeq : com -> com -> com | CIf : bexp -> com -> com -> com | CWhile : bexp -> com -> com | CHavoc : string -> com. Notation "'havoc' l" := (CHavoc l) (in custom com at level 60, l constr at level 0). Notation "'skip'" := CSkip (in custom com at level 0). Notation "x := y" := (CAss x y) (in custom com at level 0, x constr at level 0, y at level 85, no associativity). Notation "x ; y" := (CSeq x y) (in custom com at level 90, right associativity). Notation "'if' x 'then' y 'else' z 'end'" := (CIf x y z) (in custom com at level 89, x at level 99, y at level 99, z at level 99). Notation "'while' x 'do' y 'end'" := (CWhile x y) (in custom com at level 89, x at level 99, y at level 99). Inductive ceval : com -> state -> state -> Prop := | E_Skip : forall st, st =[ skip ]=> st | E_Ass : forall st a1 n x, aeval st a1 = n -> st =[ x := a1 ]=> (x !-> n ; st) | E_Seq : forall c1 c2 st st' st'', st =[ c1 ]=> st' -> st' =[ c2 ]=> st'' -> st =[ c1 ; c2 ]=> st'' | E_IfTrue : forall st st' b c1 c2, beval st b = true -> st =[ c1 ]=> st' -> st =[ if b then c1 else c2 end ]=> st' | E_IfFalse : forall st st' b c1 c2, beval st b = false -> st =[ c2 ]=> st' -> st =[ if b then c1 else c2 end ]=> st' | E_WhileFalse : forall b st c, beval st b = false -> st =[ while b do c end ]=> st | E_WhileTrue : forall st st' st'' b c, beval st b = true -> st =[ c ]=> st' -> st' =[ while b do c end ]=> st'' -> st =[ while b do c end ]=> st'' | E_Havoc : forall st X n, st =[ havoc X ]=> (X !-> n ; st) where "st '=[' c ']=>' st'" := (ceval c st st'). Hint Constructors ceval : core. (** The definition of Hoare triples is exactly as before. *) Definition hoare_triple (P:Assertion) (c:com) (Q:Assertion) : Prop := forall st st', st =[ c ]=> st' -> P st -> Q st'. Hint Unfold hoare_triple : core. Notation "{{ P }} c {{ Q }}" := (hoare_triple P c Q) (at level 90, c custom com at level 99) : hoare_spec_scope. (** And the precondition consequence rule is exactly as before. *) Theorem hoare_consequence_pre : forall (P P' Q : Assertion) c, {{P'}} c {{Q}} -> P ->> P' -> {{P}} c {{Q}}. Proof. eauto. Qed. (** **** Exercise: 3 stars, standard (hoare_havoc) *) (** Complete the Hoare rule for [HAVOC] commands below by defining [havoc_pre], and prove that the resulting rule is correct. *) Definition havoc_pre (X : string) (Q : Assertion) (st : total_map nat) : Prop (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted. Theorem hoare_havoc : forall (Q : Assertion) (X : string), {{ havoc_pre X Q }} havoc X {{ Q }}. Proof. (* FILL IN HERE *) Admitted. (** [] *) (** **** Exercise: 3 stars, standard (havoc_post) *) (** Complete the following proof without changing any of the provided commands. If you find that it can't be completed, your definition of [havoc_pre] is probably too strong. Find a way to relax it so that [havoc_post] can be proved. Hint: the [assn_auto] tactics we've built won't help you here. You need to proceed manually. *) Theorem havoc_post : forall (P : Assertion) (X : string), {{ P }} havoc X {{ fun st => exists (n:nat), P [X |-> n] st }}. Proof. intros P X. eapply hoare_consequence_pre. - apply hoare_havoc. - (* FILL IN HERE *) Admitted. (** [] *) End Himp. (* ================================================================= *) (** ** Assert and Assume *) (** **** Exercise: 4 stars, standard, optional (assert_vs_assume) *) Module HoareAssertAssume. (** In this exercise, we will extend IMP with two commands, [assert] and [ASSUME]. Both commands are ways to indicate that a certain statement should hold any time this part of the program is reached. However they differ as follows: - If an [assert] statement fails, it causes the program to go into an error state and exit. - If an [ASSUME] statement fails, the program fails to evaluate at all. In other words, the program gets stuck and has no final state. The new set of commands is: *) Inductive com : Type := | CSkip : com | CAss : string -> aexp -> com | CSeq : com -> com -> com | CIf : bexp -> com -> com -> com | CWhile : bexp -> com -> com | CAssert : bexp -> com | CAssume : bexp -> com. Notation "'assert' l" := (CAssert l) (in custom com at level 8, l custom com at level 0). Notation "'assume' l" := (CAssume l) (in custom com at level 8, l custom com at level 0). Notation "'skip'" := CSkip (in custom com at level 0). Notation "x := y" := (CAss x y) (in custom com at level 0, x constr at level 0, y at level 85, no associativity). Notation "x ; y" := (CSeq x y) (in custom com at level 90, right associativity). Notation "'if' x 'then' y 'else' z 'end'" := (CIf x y z) (in custom com at level 89, x at level 99, y at level 99, z at level 99). Notation "'while' x 'do' y 'end'" := (CWhile x y) (in custom com at level 89, x at level 99, y at level 99). (** To define the behavior of [assert] and [ASSUME], we need to add notation for an error, which indicates that an assertion has failed. We modify the [ceval] relation, therefore, so that it relates a start state to either an end state or to [error]. The [result] type indicates the end value of a program, either a state or an error: *) Inductive result : Type := | RNormal : state -> result | RError : result. (** Now we are ready to give you the ceval relation for the new language. *) Inductive ceval : com -> state -> result -> Prop := (* Old rules, several modified *) | E_Skip : forall st, st =[ skip ]=> RNormal st | E_Ass : forall st a1 n x, aeval st a1 = n -> st =[ x := a1 ]=> RNormal (x !-> n ; st) | E_SeqNormal : forall c1 c2 st st' r, st =[ c1 ]=> RNormal st' -> st' =[ c2 ]=> r -> st =[ c1 ; c2 ]=> r | E_SeqError : forall c1 c2 st, st =[ c1 ]=> RError -> st =[ c1 ; c2 ]=> RError | E_IfTrue : forall st r b c1 c2, beval st b = true -> st =[ c1 ]=> r -> st =[ if b then c1 else c2 end ]=> r | E_IfFalse : forall st r b c1 c2, beval st b = false -> st =[ c2 ]=> r -> st =[ if b then c1 else c2 end ]=> r | E_WhileFalse : forall b st c, beval st b = false -> st =[ while b do c end ]=> RNormal st | E_WhileTrueNormal : forall st st' r b c, beval st b = true -> st =[ c ]=> RNormal st' -> st' =[ while b do c end ]=> r -> st =[ while b do c end ]=> r | E_WhileTrueError : forall st b c, beval st b = true -> st =[ c ]=> RError -> st =[ while b do c end ]=> RError (* Rules for Assert and Assume *) | E_AssertTrue : forall st b, beval st b = true -> st =[ assert b ]=> RNormal st | E_AssertFalse : forall st b, beval st b = false -> st =[ assert b ]=> RError | E_Assume : forall st b, beval st b = true -> st =[ assume b ]=> RNormal st where "st '=[' c ']=>' r" := (ceval c st r). (** We redefine hoare triples: Now, [{{P}} c {{Q}}] means that, whenever [c] is started in a state satisfying [P], and terminates with result [r], then [r] is not an error and the state of [r] satisfies [Q]. *) Definition hoare_triple (P : Assertion) (c : com) (Q : Assertion) : Prop := forall st r, st =[ c ]=> r -> P st -> (exists st', r = RNormal st' /\ Q st'). Notation "{{ P }} c {{ Q }}" := (hoare_triple P c Q) (at level 90, c custom com at level 99) : hoare_spec_scope. (** To test your understanding of this modification, give an example precondition and postcondition that are satisfied by the [ASSUME] statement but not by the [assert] statement. Then prove that any triple for [assert] also works for [ASSUME]. *) Theorem assert_assume_differ : exists (P:Assertion) b (Q:Assertion), ({{P}} assume b {{Q}}) /\ ~ ({{P}} assert b {{Q}}). (* FILL IN HERE *) Admitted. Theorem assert_implies_assume : forall P b Q, ({{P}} assert b {{Q}}) -> ({{P}} assume b {{Q}}). Proof. (* FILL IN HERE *) Admitted. (** Your task is now to state Hoare rules for [assert] and [assume], and use them to prove a simple program correct. Name your hoare rule theorems [hoare_assert] and [hoare_assume]. For your benefit, we provide proofs for the old hoare rules adapted to the new semantics. *) Theorem hoare_asgn : forall Q X a, {{Q [X |-> a]}} X := a {{Q}}. Proof. unfold hoare_triple. intros Q X a st st' HE HQ. inversion HE. subst. exists (X !-> aeval st a ; st). split; try reflexivity. assumption. Qed. Theorem hoare_consequence_pre : forall (P P' Q : Assertion) c, {{P'}} c {{Q}} -> P ->> P' -> {{P}} c {{Q}}. Proof. intros P P' Q c Hhoare Himp. intros st st' Hc HP. apply (Hhoare st st'). assumption. apply Himp. assumption. Qed. Theorem hoare_consequence_post : forall (P Q Q' : Assertion) c, {{P}} c {{Q'}} -> Q' ->> Q -> {{P}} c {{Q}}. Proof. intros P Q Q' c Hhoare Himp. intros st r Hc HP. unfold hoare_triple in Hhoare. assert (exists st', r = RNormal st' /\ Q' st'). { apply (Hhoare st); assumption. } destruct H as [st' [Hr HQ'] ]. exists st'. split; try assumption. apply Himp. assumption. Qed. Theorem hoare_seq : forall P Q R c1 c2, {{Q}} c2 {{R}} -> {{P}} c1 {{Q}} -> {{P}} c1;c2 {{R}}. Proof. intros P Q R c1 c2 H1 H2 st r H12 Pre. inversion H12; subst. - eapply H1. + apply H6. + apply H2 in H3. apply H3 in Pre. destruct Pre as [st'0 [Heq HQ] ]. inversion Heq; subst. assumption. - (* Find contradictory assumption *) apply H2 in H5. apply H5 in Pre. destruct Pre as [st' [C _] ]. inversion C. Qed. (** State and prove your hoare rules, [hoare_assert] and [hoare_assume], below. *) (* FILL IN HERE *) (** Here are the other proof rules (sanity check) *) (* NOTATION : IY -- Do we want <{ }> to be printing in here? *) Theorem hoare_skip : forall P, {{P}} skip {{P}}. Proof. intros P st st' H HP. inversion H. subst. eexists. split. reflexivity. assumption. Qed. Theorem hoare_if : forall P Q (b:bexp) c1 c2, {{ P /\ b}} c1 {{Q}} -> {{ P /\ ~ b}} c2 {{Q}} -> {{P}} if b then c1 else c2 end {{Q}}. Proof. intros P Q b c1 c2 HTrue HFalse st st' HE HP. inversion HE; subst. - (* b is true *) apply (HTrue st st'). assumption. split. assumption. apply bexp_eval_true. assumption. - (* b is false *) apply (HFalse st st'). assumption. split. assumption. apply bexp_eval_false. assumption. Qed. Theorem hoare_while : forall P (b:bexp) c, {{P /\ b}} c {{P}} -> {{P}} while b do c end {{ P /\ ~b}}. Proof. intros P b c Hhoare st st' He HP. remember <{while b do c end}> as wcom eqn:Heqwcom. induction He; try (inversion Heqwcom); subst; clear Heqwcom. - (* E_WhileFalse *) eexists. split. reflexivity. split. assumption. apply bexp_eval_false. assumption. - (* E_WhileTrueNormal *) clear IHHe1. apply IHHe2. reflexivity. clear IHHe2 He2 r. unfold hoare_triple in Hhoare. apply Hhoare in He1. + destruct He1 as [st1 [Heq Hst1] ]. inversion Heq; subst. assumption. + split; assumption. - (* E_WhileTrueError *) exfalso. clear IHHe. unfold hoare_triple in Hhoare. apply Hhoare in He. + destruct He as [st' [C _] ]. inversion C. + split; assumption. Qed. Example assert_assume_example: {{True}} assume (X = 1); X := X + 1; assert (X = 2) {{True}}. Proof. (* FILL IN HERE *) Admitted. End HoareAssertAssume. (** [] *) (* 2020-09-09 21:08 *)
The minimum age of applicant should be 17 years and maximum age should not exceed 25 years. Applicants applying for B.Tech (Naval Architecture & Ocean Engineering) degree course have to submit a physical Fitness Certificate from a Registered Medical Practitioner. Applicant should have passed Class 12 /equivalent (PCM 60%). Applicant should have passed B.Sc (PCM)/ B.Sc (Electronics with Physics as individual subject in one of the years) with 60% marks. Applicant should have a B.E./B.Tech degree from IIT or college recognised by AICTE with marks not less than 50%. Note: Marks of English are to be 50% or more in any one of the above given examination. Applicant should have passed 12th Standard or equivalent with PCM-60% and English- 50% marks. Applicant should have passed 12th or equivalent examination with PCM-50% and English- 50% marks. Applicant should have passed 12th Standard or equivalent examination with PCM-60% and English- 50% marks. Applicant should have passed Class 12 or equivalent examination (PCM-60% & English- 50%). Applicant should have passed a BE/B.Tech in Marine Engineering/Mechanical Engineering/ Naval Architecture with at least 60% marks from a recognised University. Associate Member of Institution of Engineers Part A and B in Mechanical Engineering with at least 60% marks. Note: Applicants with prescribed GATE/GRE Scores are exempted from IMU’s CET. Applicant should have Graduate Engg, in Mechanical/ Civil/ Aeronautical/ Marine/ Naval Architecture or equivalent with 60% aggregate. Applicant should have a bachelor's degree in any subject with 50% marks from recognised university (45% marks in case of SC/ST). Applicant should have a bachelor's degree in any subject with 50% marks from a recognised university (45% marks in case of SC/ST). Note: In case of SC/ST candidates, there will be a 5% relaxation in eligibility marks.
(* Title: Scan.thy Author: Akama Hitoshi *) theory Scan imports HOL.List "../Util/Sum_Util" begin lemma pair_induct [case_names Nil PairCons]: assumes head: "P []" assumes pair: "\<And>x as xas. P xas \<Longrightarrow> P ((x, as)#xas)" shows "P xas" proof (induct xas) case Nil then show ?case by (simp add: head) next case (Cons ax xas) then show ?case proof (cases ax) case (Pair x as) then show ?thesis by (simp add: pair Cons) qed qed lemma pair_rev_induct [case_names Nil PairSnoc]: assumes head: "P []" assumes pair: "\<And>x as xas. P xas \<Longrightarrow> P (xas @ [(x, as)])" shows "P xas" proof (induct xas rule: rev_induct) case Nil then show ?case by (simp add: head) next case (snoc ax xas) then show ?case proof (cases ax) case (Pair x as) then show ?thesis by (simp add: pair snoc) qed qed subsubsection \<open>Scanned string\<close> text \<open>Scanned string\<close> type_synonym ('y, 'b) scanned_tail = "('y \<times> 'b list) list" type_synonym ('y, 'b) scanned = "'b list \<times> ('y, 'b) scanned_tail" fun length_scanned :: "('y, 'b) scanned \<Rightarrow> nat" where "length_scanned (w, xas) = Suc (length xas)" definition append_scanned :: "('y, 'b) scanned \<Rightarrow> ('y, 'b) scanned_tail \<Rightarrow> ('y, 'b) scanned" (infixl "@@@" 80) where "append_scanned = (\<lambda>(w, xas) yas. (w, xas @ yas))" lemma append_scanned_assoc: "(xas @@@ yas) @@@ zas = xas @@@ (yas @ zas)" by (cases xas, simp add: append_scanned_def) lemma append_scanned_simp: "(w, xas) @@@ yas = (w, xas @ yas)" unfolding append_scanned_def by simp lemma append_scanned_Nil[simp]: "xas @@@ [] = xas" by (cases xas, simp add: append_scanned_def) lemma fst_append_scanned[simp]: "fst (a @@@ b) = fst a" by (cases a, simp add: append_scanned_simp) lemma length_scanned_gt: "length_scanned xas > 0" by (cases xas, simp) lemma length_append_scanned_1: "length_scanned (xas @@@ [p]) = Suc (length_scanned xas)" proof (cases xas) case (Pair w xs) then show ?thesis by (induct xs, simp_all add: append_scanned_simp) qed lemma length_Cons_scanned_1: "length_scanned (w, x # xas) = Suc (length_scanned (w, xas))" by (induct xas, simp_all add: append_scanned_simp) lemma length_append_scanned[simp]: "length_scanned (xas @@@ ys) = length_scanned xas + length ys" proof (induct ys arbitrary: xas rule: rev_induct) case Nil then show ?case by simp next case (snoc x xs) then show ?case by (simp add: append_scanned_assoc[symmetric] length_append_scanned_1) qed lemma scanned_induct_aux: assumes head: "\<And>w. P (w, [])" assumes pair: "\<And>w x as xas. (\<And>u. P (u, xas)) \<Longrightarrow> P ((w, [(x, as)]) @@@ xas)" shows "P (w, xs)" proof (induct xs arbitrary: w rule: pair_induct) case Nil then show ?case using head by simp next case (PairCons x as xas) then show ?case proof - have "P ((w, [(x, as)]) @@@ xas)" by (simp add: PairCons pair) then show ?thesis by (simp add: append_scanned_simp) qed qed lemma scanned_induct[case_names Nil PairCons]: assumes head: "\<And>w. P (w, [])" assumes pair: "\<And>w x as xas. (\<And>u. P (u, xas)) \<Longrightarrow> P ((w, [(x, as)]) @@@ xas)" shows "P sc" apply (cases sc) apply simp apply (rule scanned_induct_aux) apply (simp add: head) apply (simp add: pair) done lemma scanned_rev_induct_aux: assumes head: "\<And>w. P (w, [])" assumes pair: "\<And>x as sc. P sc \<Longrightarrow> P (sc @@@ [(x, as)])" shows "P (w, xs)" proof (induct xs rule: pair_rev_induct) case Nil then show ?case using head by simp next case (PairSnoc x as xas) then show ?case proof - have "P ((w, xas) @@@ [(x, as)])" by (simp add: PairSnoc pair) then show ?thesis by (simp add: append_scanned_simp) qed qed lemma scanned_rev_induct[case_names Nil PairSnoc]: assumes head: "\<And>w. P (w, [])" assumes pair: "\<And>x as sc. P sc \<Longrightarrow> P (sc @@@ [(x, as)])" shows "P sc" using assms by (cases sc, simp add: scanned_rev_induct_aux) subsubsection \<open>Scan\<close> text \<open>scan var-alphabet list, and split it into a scanned string\<close> fun scan_pair_rec :: "'y \<Rightarrow> 'b list \<Rightarrow> ('y + 'b) list \<Rightarrow> ('y, 'b) scanned_tail" where "scan_pair_rec x as [] = [(x, as)]" | "scan_pair_rec x as (Inl y#u) = (x, as) # scan_pair_rec y [] u" | "scan_pair_rec x as (Inr a#u) = scan_pair_rec x (as @ [a]) u" fun scan_head :: "'b list \<Rightarrow> ('y + 'b) list \<Rightarrow> ('y, 'b) scanned" where "scan_head as [] = (as, [])" | "scan_head as (Inl x#u) = (as, scan_pair_rec x [] u)" | "scan_head as (Inr a#u) = scan_head (as @ [a]) u" definition scan :: "('y + 'b) list \<Rightarrow> ('y, 'b) scanned" where "scan u = scan_head [] u" definition scan_pair :: "('y + 'b) list \<Rightarrow> ('y \<times> 'b list) list" where "scan_pair u = snd (scan u)" definition keys_pair :: "('y \<times> 'b list) list \<Rightarrow> 'y list" where "keys_pair ps = map fst ps" fun map_value_pair :: "('b \<Rightarrow> 'c list) \<Rightarrow> ('y \<times> 'b list) list \<Rightarrow> ('y \<times> 'c list) list" where "map_value_pair f Nil = []" | "map_value_pair f ((y, bs)#ybs) = (y, concat (map f bs)) # map_value_pair f ybs" definition map_value_scanned where "map_value_scanned f scanned = (map f (fst scanned), map_value_pair f (snd scanned))" fun concat_value_pair where "concat_value_pair Nil = []" | "concat_value_pair ((x, as)#xas) = as @ concat_value_pair xas" lemma concat_value_pair_last_simp[simp]: "concat_value_pair (xas @ [(x, as)]) = concat_value_pair xas @ as" by (induct xas rule: pair_induct, simp_all) definition concat_value_scanned where "concat_value_scanned scanned = fst scanned @ concat_value_pair (snd scanned)" lemma concat_value_scanned_Nil[simp]: "concat_value_scanned (as, []) = as" unfolding concat_value_scanned_def by simp lemma concat_value_scanned_last_simp[simp]: "concat_value_scanned (sc @@@ [(x, as)]) = concat_value_scanned sc @ as" proof (induct sc rule: scanned_induct) case (Nil w) then show ?case by (simp add: concat_value_scanned_def append_scanned_def) next case (PairCons w x as xas) then show ?case by (simp add: concat_value_scanned_def append_scanned_def) qed lemma map_value_pair_last_simp[simp]: "map_value_pair f (ybs @ [(y, bs)]) = map_value_pair f ybs @ [(y, concat (map f bs))]" by (induct ybs rule: pair_induct, simp_all) lemma keys_pair_map_value_pair: "keys_pair (map_value_pair f xas) = keys_pair xas" by (induct xas rule: pair_induct, simp_all add: keys_pair_def) lemma keys_pair_Nil[simp]: "keys_pair [] = []" unfolding keys_pair_def by simp lemma keys_pair_Cons[simp]: "keys_pair ((x, as)#xas) = x # keys_pair xas" unfolding keys_pair_def by simp lemma keys_pair_snoc[simp]: "keys_pair (xas @ [(x, as)]) = keys_pair xas @ [x]" unfolding keys_pair_def by simp lemma scan_word_simp[simp]: "scan (map Inr w) = (w, [])" proof - { fix as have "scan_head as (map Inr w) = (as @ w, [])" by (induct w arbitrary: as, simp_all) } note that = this then show ?thesis by (simp add: that scan_def) qed lemma scan_last_simp[simp]: "scan (u @ Inl x # map Inr w) = scan u @@@ [(x :: 'x, w)]" proof - { fix y :: 'x and bs have "scan_pair_rec y bs (map Inr w) = [(y, bs @ w)]" by (induct w arbitrary: bs, simp_all) } note pair_alphabet = this { fix x y :: 'x and as u have "scan_pair_rec x as (u @ Inl y # map Inr w) = scan_pair_rec x as u @ [(y, w)]" by (induct u arbitrary: x y as rule: xa_induct, simp_all add: pair_alphabet) } note pair = this { fix as have "scan_head as (u @ Inl x # map Inr w) = scan_head as u @@@ [(x, w)]" by (induct u arbitrary: as rule: xa_induct, simp_all add: pair_alphabet pair append_scanned_simp) } thus ?thesis by (simp add: scan_def) qed corollary scan_nil_simp[simp]: "scan [] = ([], [])" by (simp add: scan_word_simp[of "[]", simplified]) corollary scan_last_var_simp[simp]: "scan (u @ [Inl x]) = scan u @@@ [(x, [])]" by (simp add: scan_last_simp[of "u" "x" "[]", simplified]) corollary scan_last_single_simp[simp]: "scan (Inl x # map Inr w) = ([], [(x, w)])" by (simp add: scan_last_simp[of "[]", simplified] append_scanned_simp) corollary scan_var_simp[simp]: "scan [Inl x] = ([], [(x, [])])" by (simp add: scan_last_var_simp[of "[]" "x", simplified] append_scanned_simp) lemma scan_pair_nil_simp[simp]: "scan_pair [] = []" unfolding scan_pair_def by simp lemma scan_pair_var_simp[simp]: "scan_pair [Inl x] = [(x, [])]" unfolding scan_pair_def by simp lemma scan_pair_alpha_simp[simp]: "scan_pair (Inr a#u) = scan_pair u" unfolding scan_pair_def scan_def proof (simp) fix as bs show "snd (scan_head as u) = snd (scan_head bs u)" by (induct u arbitrary: as bs rule: xa_induct, simp_all) qed lemma scan_pair_word_simp[simp]: "scan_pair (map Inr as) = []" unfolding scan_pair_def by simp lemma scan_pair_last_simp[simp]: "scan_pair (u @ Inl x # map Inr w) = scan_pair u @ [(x :: 'x, w)]" unfolding scan_pair_def by (cases "scan u", simp add: append_scanned_simp) lemma snd_scan: "snd (scan u) = scan_pair u" unfolding scan_pair_def by simp subsubsection \<open>Flat\<close> text \<open>flatten pairs\<close> fun flat_rec :: "('y, 'b) scanned_tail \<Rightarrow> ('y + 'b) list" where "flat_rec [] = []" | "flat_rec ((x, as)#xas) = Inl x # map Inr as @ flat_rec xas" definition flat :: "('y, 'b) scanned \<Rightarrow> ('y + 'b) list" where "flat = (\<lambda>(b0, xas). map Inr b0 @ flat_rec xas)" lemma flat_simp: "flat (b0, xas) = map Inr b0 @ flat_rec xas" unfolding flat_def by simp lemma flat_rec_append[simp]: "flat_rec (xs @ ys) = flat_rec xs @ flat_rec ys" by (induct xs arbitrary: ys rule: pair_rev_induct, simp_all) lemma flat_word_simp[simp]: "flat (w, []) = map Inr w" by (induct w, simp_all add: flat_def) lemma flat_append[simp]: "flat (xas @@@ xs) = flat xas @ flat_rec xs" proof (induct xas arbitrary: xs rule: scanned_rev_induct) case (Nil w) then show ?case by (simp add: append_scanned_simp flat_def) next case (PairSnoc y bs sc) then show ?case by (simp add: append_scanned_simp append_scanned_assoc) qed theorem scan_inverse: "flat (scan u) = u" by (induct u rule: xw_induct, simp_all) end
REBOL [ Title: "remaining-inventory-for-this-item" Date: 21-Oct-2017 Name: "remaining-inventory-for-this-item.r" Author: "Mike Yaunish" File: %remaining-inventory-for-this-item.r Version: 1.0 Purpose: {DB-Rider select script. For database:billing_complete and table:inventory} ] num-of-records-selected: do-to-selected/how-many [ item-id: get-field "item" ] either ( num-of-records-selected > 1 )[ my-request "Inventory for only 1 item can be displayed at a time.^/The first item selected will been displayed." do/args join query-db/overlay-path rejoin [ query-db/database "/lineitem/report/inventory-remaining.r"] item-id ][ do/args join query-db/overlay-path rejoin [ query-db/database "/lineitem/report/inventory-remaining.r"] item-id ] user-msg/query rejoin[ "Select script has worked with:" num-of-records-selected "records" ]
# Using the Breast Cancer Wisconsin (Diagnostic) Database to create a classifier that can help diagnose patients. # Author: Rishu Shrivastava ([email protected]) # Date : June 4, 2017 # last updated : June 12, 2017 import numpy as np import pandas as pd from sklearn.datasets import load_breast_cancer cancer = load_breast_cancer() print("Data set type: ",type(cancer)) #print(cancer.items()) #print(cancer.data) #print(type(cancer['feature_names'])) #print(cancer['feature_names'][1]) #print("adding element to numpy ndarray", np.append(cancer['feature_names'],[['target']])) def print_keys(): # return keys return cancer.keys() def len_dataset(): # return length of dataset return len(cancer['feature_names']) def create_dataframe(): # create a dataframe using the dataset dframe = pd.DataFrame(cancer.data, columns=[cancer.feature_names]) dframe['target'] = pd.Series(data=cancer.target, index=dframe.index) print("shape of dataframe :",dframe.shape) return dframe def cancer_instances(): #return a series with the total number of malignant and benign instances cancerdf = create_dataframe() cancer_count = cancerdf['target'].value_counts() #print("Malignant : Benign count = ", cancer_count[0],":", cancer_count[1]) dict= {'malignant': cancer_count[0], 'benign':cancer_count[1]} s = pd.Series(dict, index=['malignant', 'benign']) return s def split_data(): # split the data into tuples X and y cancerdf = create_dataframe() X = cancerdf.ix[:,:30] y = cancerdf['target'] return X, y from sklearn.model_selection import train_test_split def generate_test_train(): # generate test train data set using the data frame X, y = split_data() X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) return X_train, X_test, y_train, y_test from sklearn.neighbors import KNeighborsClassifier def fit_knn_classifier(): X_train, X_test, y_train, y_test = generate_test_train() # for KNN neighbors = 1 knn = KNeighborsClassifier(n_neighbors = 1) knn.fit(X_train, y_train) return knn def accuracy_score(): # calculate prediction score X_train, X_test, y_train, y_test = generate_test_train() knn = fit_knn_classifier() s = knn.score(X_test,y_test) return s def calculate_mean_feature(): cancerdf = create_dataframe() means = cancerdf.mean()[:-1].values.reshape(1, -1) knn = fit_knn_classifier() pr = knn.predict(means) return pr print(print_keys()) print(len_dataset()) #print(create_dataframe()) print(cancer_instances()) #print(split_data()) #print(generate_test_train()) print(fit_knn_classifier()) print(accuracy_score()) print(calculate_mean_feature())
(* *********************************************************************) (* *) (* The Compcert verified compiler *) (* *) (* Xavier Leroy, INRIA Paris-Rocquencourt *) (* *) (* Copyright Institut National de Recherche en Informatique et en *) (* Automatique. All rights reserved. This file is distributed *) (* under the terms of the INRIA Non-Commercial License Agreement. *) (* *) (* *********************************************************************) (** Corollaries of the main semantic preservation theorem. *) Require Import Classical. Require Import Coqlib. Require Import AST. Require Import Integers. Require Import Values. Require Import Events. Require Import Globalenvs. Require Import Smallstep. Require Import Behaviors. Require Import Csyntax. Require Import Csem. Require Import Cstrategy. Require Import Clight. Require Import Cminor. Require Import RTL. Require Import Asm. Require Import Compiler. Require Import Errors. (** * Preservation of whole-program behaviors *) (** From the simulation diagrams proved in file [Compiler]. it follows that whole-program observable behaviors are preserved in the following sense. First, every behavior of the generated assembly code is matched by a behavior of the source C code. *) Theorem transf_c_program_preservation: forall p tp beh, transf_c_program p = OK tp -> program_behaves (AsmBits.semantics_bits tp) beh -> exists beh', program_behaves (Csem.semantics p) beh' /\ behavior_improves beh' beh. Proof. intros. eapply backward_simulation_behavior_improves; eauto. apply transf_c_program_correct; auto. Qed. (** As a corollary, if the source C code cannot go wrong, the behavior of the generated assembly code is one of the possible behaviors of the source C code. *) Theorem transf_c_program_is_refinement: forall p tp, transf_c_program p = OK tp -> (forall beh, program_behaves (Csem.semantics p) beh -> not_wrong beh) -> (forall beh, program_behaves (AsmBits.semantics_bits tp) beh -> program_behaves (Csem.semantics p) beh). Proof. intros. eapply backward_simulation_same_safe_behavior; eauto. apply transf_c_program_correct; auto. Qed. (** If we consider the C evaluation strategy implemented by the compiler, we get stronger preservation results. *) Theorem transf_cstrategy_program_preservation: forall p tp, transf_c_program p = OK tp -> (forall beh, program_behaves (Cstrategy.semantics p) beh -> exists beh', program_behaves (AsmBits.semantics_bits tp) beh' /\ behavior_improves beh beh') /\(forall beh, program_behaves (AsmBits.semantics_bits tp) beh -> exists beh', program_behaves (Cstrategy.semantics p) beh' /\ behavior_improves beh' beh) /\(forall beh, not_wrong beh -> program_behaves (Cstrategy.semantics p) beh -> program_behaves (AsmBits.semantics_bits tp) beh) /\(forall beh, (forall beh', program_behaves (Cstrategy.semantics p) beh' -> not_wrong beh') -> program_behaves (AsmBits.semantics_bits tp) beh -> program_behaves (Cstrategy.semantics p) beh). Proof. assert (WBT: forall p, well_behaved_traces (Cstrategy.semantics p)). intros. eapply ssr_well_behaved. apply Cstrategy.semantics_strongly_receptive. intros. intuition. eapply forward_simulation_behavior_improves; eauto. apply (fst (transf_cstrategy_program_correct _ _ H)). exploit backward_simulation_behavior_improves. apply (snd (transf_cstrategy_program_correct _ _ H)). eauto. intros [beh1 [A B]]. exists beh1; split; auto. rewrite atomic_behaviors; auto. eapply forward_simulation_same_safe_behavior; eauto. apply (fst (transf_cstrategy_program_correct _ _ H)). exploit backward_simulation_same_safe_behavior. apply (snd (transf_cstrategy_program_correct _ _ H)). intros. rewrite <- atomic_behaviors in H2; eauto. eauto. intros. rewrite atomic_behaviors; auto. Qed. (** We can also use the alternate big-step semantics for [Cstrategy] to establish behaviors of the generated assembly code. *) Theorem bigstep_cstrategy_preservation: forall p tp, transf_c_program p = OK tp -> (forall t r, Cstrategy.bigstep_program_terminates p t r -> program_behaves (AsmBits.semantics_bits tp) (Terminates t r)) /\(forall T, Cstrategy.bigstep_program_diverges p T -> program_behaves (AsmBits.semantics_bits tp) (Reacts T) \/ exists t, program_behaves (AsmBits.semantics_bits tp) (Diverges t) /\ traceinf_prefix t T). Proof. intuition. apply transf_cstrategy_program_preservation with p; auto. red; auto. apply behavior_bigstep_terminates with (Cstrategy.bigstep_semantics p); auto. apply Cstrategy.bigstep_semantics_sound. exploit (behavior_bigstep_diverges (Cstrategy.bigstep_semantics_sound p)). eassumption. intros [A | [t [A B]]]. left. apply transf_cstrategy_program_preservation with p; auto. red; auto. right; exists t; split; auto. apply transf_cstrategy_program_preservation with p; auto. red; auto. Qed. (** * Satisfaction of specifications *) (** The second additional results shows that if all executions of the source C program satisfies a given specification (a predicate on the observable behavior of the program), then all executions of the produced Asm program satisfy this specification as well. We first show this result for specifications that are stable under the [behavior_improves] relation. *) Section SPECS_PRESERVED. Variable spec: program_behavior -> Prop. Hypothesis spec_stable: forall beh1 beh2, behavior_improves beh1 beh2 -> spec beh1 -> spec beh2. Theorem transf_c_program_preserves_spec: forall p tp, transf_c_program p = OK tp -> (forall beh, program_behaves (Csem.semantics p) beh -> spec beh) -> (forall beh, program_behaves (AsmBits.semantics_bits tp) beh -> spec beh). Proof. intros. exploit transf_c_program_preservation; eauto. intros [beh' [A B]]. apply spec_stable with beh'; auto. Qed. End SPECS_PRESERVED. (** As a corollary, we obtain preservation of safety specifications: specifications that exclude "going wrong" behaviors. *) Section SAFETY_PRESERVED. Variable spec: program_behavior -> Prop. Hypothesis spec_safety: forall beh, spec beh -> not_wrong beh. Theorem transf_c_program_preserves_safety_spec: forall p tp, transf_c_program p = OK tp -> (forall beh, program_behaves (Csem.semantics p) beh -> spec beh) -> (forall beh, program_behaves (AsmBits.semantics_bits tp) beh -> spec beh). Proof. intros. eapply transf_c_program_preserves_spec; eauto. intros. destruct H2. congruence. destruct H2 as [t [EQ1 EQ2]]. subst beh1. elim (spec_safety _ H3). Qed. End SAFETY_PRESERVED. (** We also have preservation of liveness specifications: specifications that assert the existence of a prefix of the observable trace satisfying some conditions. *) Section LIVENESS_PRESERVED. Variable spec: trace -> Prop. Definition liveness_spec_satisfied (b: program_behavior) : Prop := exists t, behavior_prefix t b /\ spec t. Theorem transf_c_program_preserves_liveness_spec: forall p tp, transf_c_program p = OK tp -> (forall beh, program_behaves (Csem.semantics p) beh -> liveness_spec_satisfied beh) -> (forall beh, program_behaves (AsmBits.semantics_bits tp) beh -> liveness_spec_satisfied beh). Proof. intros. eapply transf_c_program_preserves_spec; eauto. intros. destruct H3 as [t1 [A B]]. destruct H2. subst. exists t1; auto. destruct H2 as [t [C D]]. subst. destruct A as [b1 E]. destruct D as [b2 F]. destruct b1; simpl in E; inv E. exists t1; split; auto. exists (behavior_app t0 b2); apply behavior_app_assoc. Qed. End LIVENESS_PRESERVED.
lemma connected_closedD: "\<lbrakk>connected s; A \<inter> B \<inter> s = {}; s \<subseteq> A \<union> B; closed A; closed B\<rbrakk> \<Longrightarrow> A \<inter> s = {} \<or> B \<inter> s = {}"
Formal statement is: lemma compact_sequence_with_limit: fixes f :: "nat \<Rightarrow> 'a::heine_borel" shows "(f \<longlongrightarrow> l) sequentially \<Longrightarrow> compact (insert l (range f))" Informal statement is: If a sequence converges to a limit, then the set of all terms of the sequence and the limit is compact.
[GOAL] β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{?u.1349, u_2} V inst✝ : HasZeroMorphisms V X : DifferentialObject ℤ (GradedObjectWithShift b V) x y : β h : x = y ⊢ (fun b_1 => b_1 + { as := 1 }.as • b) x = (fun b_1 => b_1 + { as := 1 }.as • b) y [PROOFSTEP] cases h [GOAL] case refl β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{?u.1349, u_2} V inst✝ : HasZeroMorphisms V X : DifferentialObject ℤ (GradedObjectWithShift b V) x : β ⊢ (fun b_1 => b_1 + { as := 1 }.as • b) x = (fun b_1 => b_1 + { as := 1 }.as • b) x [PROOFSTEP] rfl [GOAL] β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{u_3, u_2} V inst✝ : HasZeroMorphisms V X : DifferentialObject ℤ (GradedObjectWithShift b V) x y : β h : x = y ⊢ objEqToHom X h ≫ d X y = d X x ≫ objEqToHom X (_ : (fun b_1 => b_1 + { as := 1 }.as • b) x = (fun b_1 => b_1 + { as := 1 }.as • b) y) [PROOFSTEP] cases h [GOAL] case refl β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{u_3, u_2} V inst✝ : HasZeroMorphisms V X : DifferentialObject ℤ (GradedObjectWithShift b V) x : β ⊢ objEqToHom X (_ : x = x) ≫ d X x = d X x ≫ objEqToHom X (_ : (fun b_1 => b_1 + { as := 1 }.as • b) x = (fun b_1 => b_1 + { as := 1 }.as • b) x) [PROOFSTEP] dsimp [GOAL] case refl β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{u_3, u_2} V inst✝ : HasZeroMorphisms V X : DifferentialObject ℤ (GradedObjectWithShift b V) x : β ⊢ 𝟙 (obj X x) ≫ d X x = d X x ≫ 𝟙 (obj X (x + 1 • b)) [PROOFSTEP] simp [GOAL] β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{u_3, u_2} V inst✝ : HasZeroMorphisms V X✝ X Y : DifferentialObject ℤ (GradedObjectWithShift b V) f : X ⟶ Y x y : β h : x = y ⊢ objEqToHom X h ≫ Hom.f f y = Hom.f f x ≫ objEqToHom Y h [PROOFSTEP] cases h [GOAL] case refl β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{u_3, u_2} V inst✝ : HasZeroMorphisms V X✝ X Y : DifferentialObject ℤ (GradedObjectWithShift b V) f : X ⟶ Y x : β ⊢ objEqToHom X (_ : x = x) ≫ Hom.f f x = Hom.f f x ≫ objEqToHom Y (_ : x = x) [PROOFSTEP] simp [GOAL] β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{u_3, u_2} V inst✝ : HasZeroMorphisms V X : HomologicalComplex V (ComplexShape.up' b) x y z : β h : y = z ⊢ d X x y ≫ eqToHom (_ : HomologicalComplex.X X y = HomologicalComplex.X X z) = d X x z [PROOFSTEP] cases h [GOAL] case refl β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{u_3, u_2} V inst✝ : HasZeroMorphisms V X : HomologicalComplex V (ComplexShape.up' b) x y : β ⊢ d X x y ≫ eqToHom (_ : HomologicalComplex.X X y = HomologicalComplex.X X y) = d X x y [PROOFSTEP] simp [GOAL] β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{?u.42080, u_2} V inst✝ : HasZeroMorphisms V X : DifferentialObject ℤ (GradedObjectWithShift b V) i j : β h : i + b = j ⊢ i + 1 • b = j [PROOFSTEP] simp [h] [GOAL] β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{?u.42080, u_2} V inst✝ : HasZeroMorphisms V X : DifferentialObject ℤ (GradedObjectWithShift b V) i j : β w : ¬ComplexShape.Rel (ComplexShape.up' b) i j ⊢ (fun i j => if h : i + b = j then DifferentialObject.d X i ≫ objEqToHom X (_ : i + 1 • b = j) else 0) i j = 0 [PROOFSTEP] dsimp at w [GOAL] β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{?u.42080, u_2} V inst✝ : HasZeroMorphisms V X : DifferentialObject ℤ (GradedObjectWithShift b V) i j : β w : ¬i + b = j ⊢ (fun i j => if h : i + b = j then DifferentialObject.d X i ≫ objEqToHom X (_ : i + 1 • b = j) else 0) i j = 0 [PROOFSTEP] convert dif_neg w [GOAL] β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{?u.42080, u_2} V inst✝ : HasZeroMorphisms V X : DifferentialObject ℤ (GradedObjectWithShift b V) i j k : β hij : ComplexShape.Rel (ComplexShape.up' b) i j hjk : ComplexShape.Rel (ComplexShape.up' b) j k ⊢ (fun i j => if h : i + b = j then DifferentialObject.d X i ≫ objEqToHom X (_ : i + 1 • b = j) else 0) i j ≫ (fun i j => if h : i + b = j then DifferentialObject.d X i ≫ objEqToHom X (_ : i + 1 • b = j) else 0) j k = 0 [PROOFSTEP] dsimp at hij hjk [GOAL] β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{?u.42080, u_2} V inst✝ : HasZeroMorphisms V X : DifferentialObject ℤ (GradedObjectWithShift b V) i j k : β hij : i + b = j hjk : j + b = k ⊢ (fun i j => if h : i + b = j then DifferentialObject.d X i ≫ objEqToHom X (_ : i + 1 • b = j) else 0) i j ≫ (fun i j => if h : i + b = j then DifferentialObject.d X i ≫ objEqToHom X (_ : i + 1 • b = j) else 0) j k = 0 [PROOFSTEP] substs hij hjk [GOAL] β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{?u.42080, u_2} V inst✝ : HasZeroMorphisms V X : DifferentialObject ℤ (GradedObjectWithShift b V) i : β ⊢ (fun i j => if h : i + b = j then DifferentialObject.d X i ≫ objEqToHom X (_ : i + 1 • b = j) else 0) i (i + b) ≫ (fun i j => if h : i + b = j then DifferentialObject.d X i ≫ objEqToHom X (_ : i + 1 • b = j) else 0) (i + b) (i + b + b) = 0 [PROOFSTEP] simp [GOAL] β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{?u.42080, u_2} V inst✝ : HasZeroMorphisms V X Y : DifferentialObject ℤ (GradedObjectWithShift b V) f : X ⟶ Y i j : β h : ComplexShape.Rel (ComplexShape.up' b) i j ⊢ DifferentialObject.Hom.f f i ≫ d ((fun X => mk (fun i => obj X i) fun i j => if h : i + b = j then DifferentialObject.d X i ≫ objEqToHom X (_ : i + 1 • b = j) else 0) Y) i j = d ((fun X => mk (fun i => obj X i) fun i j => if h : i + b = j then DifferentialObject.d X i ≫ objEqToHom X (_ : i + 1 • b = j) else 0) X) i j ≫ DifferentialObject.Hom.f f j [PROOFSTEP] dsimp at h ⊢ [GOAL] β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{?u.42080, u_2} V inst✝ : HasZeroMorphisms V X Y : DifferentialObject ℤ (GradedObjectWithShift b V) f : X ⟶ Y i j : β h : i + b = j ⊢ (DifferentialObject.Hom.f f i ≫ if h : i + b = j then DifferentialObject.d Y i ≫ objEqToHom Y (_ : i + 1 • b = j) else 0) = (if h : i + b = j then DifferentialObject.d X i ≫ objEqToHom X (_ : i + 1 • b = j) else 0) ≫ DifferentialObject.Hom.f f j [PROOFSTEP] subst h [GOAL] β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{?u.42080, u_2} V inst✝ : HasZeroMorphisms V X Y : DifferentialObject ℤ (GradedObjectWithShift b V) f : X ⟶ Y i : β ⊢ (DifferentialObject.Hom.f f i ≫ if h : i + b = i + b then DifferentialObject.d Y i ≫ objEqToHom Y (_ : i + 1 • b = i + b) else 0) = (if h : i + b = i + b then DifferentialObject.d X i ≫ objEqToHom X (_ : i + 1 • b = i + b) else 0) ≫ DifferentialObject.Hom.f f (i + b) [PROOFSTEP] simp only [dite_true, Category.assoc, eqToHom_f'] -- Porting note: this `rw` used to be part of the `simp`. [GOAL] β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{?u.42080, u_2} V inst✝ : HasZeroMorphisms V X Y : DifferentialObject ℤ (GradedObjectWithShift b V) f : X ⟶ Y i : β ⊢ DifferentialObject.Hom.f f i ≫ DifferentialObject.d Y i ≫ objEqToHom Y (_ : i + 1 • b = i + b) = DifferentialObject.d X i ≫ DifferentialObject.Hom.f f (i + 1 • b) ≫ objEqToHom Y (_ : i + 1 • b = i + b) [PROOFSTEP] have : f.f i ≫ Y.d i = X.d i ≫ f.f _ := (congr_fun f.comm i).symm [GOAL] β : Type u_1 inst✝² : AddCommGroup β b : β V : Type u_2 inst✝¹ : Category.{?u.42080, u_2} V inst✝ : HasZeroMorphisms V X Y : DifferentialObject ℤ (GradedObjectWithShift b V) f : X ⟶ Y i : β this : DifferentialObject.Hom.f f i ≫ DifferentialObject.d Y i = DifferentialObject.d X i ≫ DifferentialObject.Hom.f f ((fun b_1 => b_1 + { as := 1 }.as • b) i) ⊢ DifferentialObject.Hom.f f i ≫ DifferentialObject.d Y i ≫ objEqToHom Y (_ : i + 1 • b = i + b) = DifferentialObject.d X i ≫ DifferentialObject.Hom.f f (i + 1 • b) ≫ objEqToHom Y (_ : i + 1 • b = i + b) [PROOFSTEP] rw [reassoc_of% this]
[STATEMENT] lemma hbase_tl: "C ns \<in> hbase b \<Longrightarrow> ns \<noteq> [] \<Longrightarrow> C (tl ns) \<in> hbase b" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>C ns \<in> hbase b; ns \<noteq> []\<rbrakk> \<Longrightarrow> C (tl ns) \<in> hbase b [PROOF STEP] by (cases "C ns" b rule: hbase.cases) (auto intro: hbaseI2)
module Main import System import Data.Vect printLenght: IO () printLenght = do putStr "Input a string: " input <- getLine let len = length input putStrLn(show len) printLonger: IO () printLonger = do putStr "Input the first string: " first <- getLine putStr "Input the second string: " second <- getLine let firstLen = length first let secondLen = length second let longest = max firstLen secondLen putStrLn ("The longest: " ++ (show longest)) readNumber: IO (Maybe Nat) readNumber = do input <- getLine if all isDigit (unpack input) then pure (Just(cast input)) else pure Nothing total readNumbers: IO (Maybe (Nat, Nat)) readNumbers = do Just num1_ok <- readNumber | Nothing => pure Nothing Just num2_ok <- readNumber | Nothing => pure Nothing pure (Just (num1_ok, num2_ok)) total stringToNat: String -> Maybe Integer stringToNat input = if all isDigit (unpack input) then Just(cast input) else Nothing guess: Integer -> Nat -> IO() guess target guesses = do userInput <- getLine let parsed = stringToNat userInput case parsed of Nothing => putStrLn ("Invalid input: " ++ userInput) (Just number) => case compare number target of LT => putStrLn ("too low. Guess #" ++ (show guesses)) >>= \_ => guess target (guesses + 1) EQ => putStrLn "Correct!!!" GT => putStrLn ("too high. Guess #" ++ (show guesses)) >>= \_ => guess target (guesses + 1) randomGuess: IO() randomGuess = do rndNum <- time putStrLn ("Guess me: " ++ (show rndNum)) guess rndNum 1 readVectLen: (len: Nat) -> IO (Vect len String) readVectLen Z = pure [] readVectLen (S k) = do x <- getLine xs <- readVectLen k pure (x :: xs) readVect: IO(len ** Vect len String) readVect = do x <- getLine if (x == "") then pure(_ ** []) else do (_ ** xs) <- readVect pure (_ ** (x :: xs)) maybeZipVects: Vect n a -> Vect m b -> Maybe(Vect n (a, b)) maybeZipVects {n} left right = case exactLength n right of Just right' => Just(zip left right') Nothing => Nothing zipInputs: IO() zipInputs = do putStrLn "Enter the first vector:" (_ ** firstVect) <- readVect putStrLn "Enter the second vector:" (_ ** secondVect) <- readVect case maybeZipVects firstVect secondVect of Nothing => putStrLn "Vectors are different" Just zipped => printLn zipped readToBlank: IO(List String) readToBlank = do line <- getLine if line == "" then pure [] else do lines <- readToBlank pure (line :: lines) readAndSave: IO() readAndSave = do putStrLn "Enter lines:" lines <- readToBlank let oneString = unlines lines putStrLn "Enter filename:" fileName <- getLine result <- writeFile fileName oneString case result of (Left _) => pure () (Right err) => printLn err readLinesFrom : (file : File) -> IO (n: Nat ** Vect n String) readLinesFrom file = do isEOF <- fEOF file case isEOF of True => pure (_ ** []) False => do Right line <- fGetLine file | Left err => pure (_ ** []) (_ ** nextLines) <- readLinesFrom file pure (_ ** trim line :: nextLines) readVectFile: (filename: String) -> IO (n ** Vect n String) readVectFile filename = do Right file <- openFile filename Read | Left err => pure (_ ** []) readLinesFrom file main : IO () main = do _ <- putStr "Enter your name: " x <- getLine putStrLn ("Hi there, " ++ x)
#readelf: -Wr #target: i?86-*-* Relocation section '.rel.dyn' at offset 0x[0-9a-f]+ contains [0-9]+ entries: +Offset +Info +Type +Sym. Value +Symbol's Name #... [0-9a-f ]+R_386_GLOB_DAT +0+ +(abort|puts).* #... [0-9a-f ]+R_386_GLOB_DAT +0+ +(abort|puts).* #pass
[STATEMENT] lemma seq_lemma: assumes "prov_triple (p1, c1, q1)" and "prov_triple (p2, c2, q2)" and "q1 = p2" shows "prov_triple (p1, c1 ;; c2, q2)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. prov_triple (p1, c1 ;; c2, q2) [PROOF STEP] using assms prov_triple.seq [PROOF STATE] proof (prove) using this: prov_triple (p1, c1, q1) prov_triple (p2, c2, q2) q1 = p2 \<lbrakk>prov_triple (?p, ?c1.0, ?q); prov_triple (?q, ?c2.0, ?r)\<rbrakk> \<Longrightarrow> prov_triple (?p, ?c1.0 ;; ?c2.0, ?r) goal (1 subgoal): 1. prov_triple (p1, c1 ;; c2, q2) [PROOF STEP] by auto
-- The SIP applied to groups {-# OPTIONS --safe #-} module Cubical.Algebra.Group.GroupPath where open import Cubical.Foundations.Prelude open import Cubical.Foundations.Function using (_∘_) open import Cubical.Foundations.Isomorphism open import Cubical.Foundations.Equiv open import Cubical.Foundations.HLevels open import Cubical.Foundations.GroupoidLaws hiding (assoc) open import Cubical.Foundations.Transport open import Cubical.Foundations.Univalence open import Cubical.Foundations.SIP open import Cubical.Data.Sigma open import Cubical.Displayed.Base open import Cubical.Displayed.Auto open import Cubical.Displayed.Record open import Cubical.Displayed.Universe open import Cubical.Algebra.Group.Base open import Cubical.Algebra.Group.Properties open import Cubical.Algebra.Group.Morphisms open import Cubical.Algebra.Group.MorphismProperties private variable ℓ ℓ' ℓ'' : Level open Iso open GroupStr open IsGroupHom 𝒮ᴰ-Group : DUARel (𝒮-Univ ℓ) GroupStr ℓ 𝒮ᴰ-Group = 𝒮ᴰ-Record (𝒮-Univ _) IsGroupEquiv (fields: data[ _·_ ∣ autoDUARel _ _ ∣ pres· ] data[ 1g ∣ autoDUARel _ _ ∣ pres1 ] data[ inv ∣ autoDUARel _ _ ∣ presinv ] prop[ isGroup ∣ (λ _ _ → isPropIsGroup _ _ _) ]) where open GroupStr open IsGroupHom GroupPath : (M N : Group ℓ) → GroupEquiv M N ≃ (M ≡ N) GroupPath = ∫ 𝒮ᴰ-Group .UARel.ua -- The module below defines a group induced from an equivalence -- between a group G and a type A which preserves the full raw group -- structure from G to A. This version is useful when proving that -- some type equivalent to a group is a group while also specifying -- the binary operation, unit and inverse. module _ (G : Group ℓ) {A : Type ℓ} (m : A → A → A) (u : A) (inverse : A → A) (e : ⟨ G ⟩ ≃ A) (p· : ∀ x y → e .fst (G .snd ._·_ x y) ≡ m (e .fst x) (e .fst y)) (pu : e .fst (G .snd .1g) ≡ u) (pinv : ∀ x → e .fst (G .snd .inv x) ≡ inverse (e .fst x)) where private module G = GroupStr (G .snd) BaseΣ : Type (ℓ-suc ℓ) BaseΣ = Σ[ B ∈ Type ℓ ] (B → B → B) × B × (B → B) FamilyΣ : BaseΣ → Type ℓ FamilyΣ (B , m , u , i) = IsGroup u m i inducedΣ : FamilyΣ (A , m , u , inverse) inducedΣ = subst FamilyΣ (UARel.≅→≡ (autoUARel BaseΣ) (e , p· , pu , pinv)) G.isGroup InducedGroup : Group ℓ InducedGroup .fst = A InducedGroup .snd ._·_ = m InducedGroup .snd .1g = u InducedGroup .snd .inv = inverse InducedGroup .snd .isGroup = inducedΣ InducedGroupEquiv : GroupEquiv G InducedGroup fst InducedGroupEquiv = e snd InducedGroupEquiv = makeIsGroupHom p· InducedGroupPath : G ≡ InducedGroup InducedGroupPath = GroupPath _ _ .fst InducedGroupEquiv -- The module below defines a group induced from an equivalence which -- preserves the binary operation (i.e. a group isomorphism). This -- version is useful when proving that some type equivalent to a group -- G is a group when one doesn't care about what the unit and inverse -- are. When using this version the unit and inverse will both be -- defined by transporting over the unit and inverse from G to A. module _ (G : Group ℓ) {A : Type ℓ} (m : A → A → A) (e : ⟨ G ⟩ ≃ A) (p· : ∀ x y → e .fst (G .snd ._·_ x y) ≡ m (e .fst x) (e .fst y)) where private module G = GroupStr (G .snd) FamilyΣ : Σ[ B ∈ Type ℓ ] (B → B → B) → Type ℓ FamilyΣ (B , n) = Σ[ e ∈ B ] Σ[ i ∈ (B → B) ] IsGroup e n i inducedΣ : FamilyΣ (A , m) inducedΣ = subst FamilyΣ (UARel.≅→≡ (autoUARel (Σ[ B ∈ Type ℓ ] (B → B → B))) (e , p·)) (G.1g , G.inv , G.isGroup) InducedGroupFromPres· : Group ℓ InducedGroupFromPres· .fst = A InducedGroupFromPres· .snd ._·_ = m InducedGroupFromPres· .snd .1g = inducedΣ .fst InducedGroupFromPres· .snd .inv = inducedΣ .snd .fst InducedGroupFromPres· .snd .isGroup = inducedΣ .snd .snd InducedGroupEquivFromPres· : GroupEquiv G InducedGroupFromPres· fst InducedGroupEquivFromPres· = e snd InducedGroupEquivFromPres· = makeIsGroupHom p· InducedGroupPathFromPres· : G ≡ InducedGroupFromPres· InducedGroupPathFromPres· = GroupPath _ _ .fst InducedGroupEquivFromPres· uaGroup : {G H : Group ℓ} → GroupEquiv G H → G ≡ H uaGroup {G = G} {H = H} = equivFun (GroupPath G H) -- Group-ua functoriality Group≡ : (G H : Group ℓ) → ( Σ[ p ∈ ⟨ G ⟩ ≡ ⟨ H ⟩ ] Σ[ q ∈ PathP (λ i → p i) (1g (snd G)) (1g (snd H)) ] Σ[ r ∈ PathP (λ i → p i → p i → p i) (_·_ (snd G)) (_·_ (snd H)) ] Σ[ s ∈ PathP (λ i → p i → p i) (inv (snd G)) (inv (snd H)) ] PathP (λ i → IsGroup (q i) (r i) (s i)) (isGroup (snd G)) (isGroup (snd H))) ≃ (G ≡ H) Group≡ G H = isoToEquiv theIso where theIso : Iso _ _ fun theIso (p , q , r , s , t) i = p i , groupstr (q i) (r i) (s i) (t i) inv theIso x = cong ⟨_⟩ x , cong (1g ∘ snd) x , cong (_·_ ∘ snd) x , cong (inv ∘ snd) x , cong (isGroup ∘ snd) x rightInv theIso _ = refl leftInv theIso _ = refl caracGroup≡ : {G H : Group ℓ} (p q : G ≡ H) → cong ⟨_⟩ p ≡ cong ⟨_⟩ q → p ≡ q caracGroup≡ {G = G} {H = H} p q P = sym (transportTransport⁻ (ua (Group≡ G H)) p) ∙∙ cong (transport (ua (Group≡ G H))) helper ∙∙ transportTransport⁻ (ua (Group≡ G H)) q where helper : transport (sym (ua (Group≡ G H))) p ≡ transport (sym (ua (Group≡ G H))) q helper = Σ≡Prop (λ _ → isPropΣ (isOfHLevelPathP' 1 (is-set (snd H)) _ _) λ _ → isPropΣ (isOfHLevelPathP' 1 (isSetΠ2 λ _ _ → is-set (snd H)) _ _) λ _ → isPropΣ (isOfHLevelPathP' 1 (isSetΠ λ _ → is-set (snd H)) _ _) λ _ → isOfHLevelPathP 1 (isPropIsGroup _ _ _) _ _) (transportRefl (cong ⟨_⟩ p) ∙ P ∙ sym (transportRefl (cong ⟨_⟩ q))) uaGroupId : (G : Group ℓ) → uaGroup (idGroupEquiv {G = G}) ≡ refl uaGroupId G = caracGroup≡ _ _ uaIdEquiv uaCompGroupEquiv : {F G H : Group ℓ} (f : GroupEquiv F G) (g : GroupEquiv G H) → uaGroup (compGroupEquiv f g) ≡ uaGroup f ∙ uaGroup g uaCompGroupEquiv f g = caracGroup≡ _ _ ( cong ⟨_⟩ (uaGroup (compGroupEquiv f g)) ≡⟨ uaCompEquiv _ _ ⟩ cong ⟨_⟩ (uaGroup f) ∙ cong ⟨_⟩ (uaGroup g) ≡⟨ sym (cong-∙ ⟨_⟩ (uaGroup f) (uaGroup g)) ⟩ cong ⟨_⟩ (uaGroup f ∙ uaGroup g) ∎) -- J-rule for GroupEquivs GroupEquivJ : {G : Group ℓ} (P : (H : Group ℓ) → GroupEquiv G H → Type ℓ') → P G idGroupEquiv → ∀ {H} e → P H e GroupEquivJ {G = G} P p {H} e = transport (λ i → P (GroupPath G H .fst e i) (transp (λ j → GroupEquiv G (GroupPath G H .fst e (i ∨ ~ j))) i e)) (subst (P G) (sym lem) p) where lem : transport (λ j → GroupEquiv G (GroupPath G H .fst e (~ j))) e ≡ idGroupEquiv lem = Σ≡Prop (λ _ → isPropIsGroupHom _ _) (Σ≡Prop (λ _ → isPropIsEquiv _) (funExt λ x → (λ i → fst (fst (fst e .snd .equiv-proof (transportRefl (fst (fst e) (transportRefl x i)) i)))) ∙ retEq (fst e) x))
// MIT License Copyright (c) 2020 Jarrett Wendt #pragma once #include <gsl/gsl> #include "Macros.h" #include "SharedPtr.h" #include "Entity.h" namespace Library { class Engine final { friend Entity; /** the parentmost Entity */ static inline SharedPtr<Entity> world{ nullptr }; static inline std::string programName{}; static inline std::string pythonSourceDirectory{}; static inline const std::string initFileName{ "init.py" }; static inline const std::string shutdownFileName{ "del.py" }; static inline FILE* initFilePtr{ nullptr }; public: STATIC_CLASS(Engine) using Args = gsl::span<const char*>; /** * O(1) * * @returns the parentmost Entity */ static Entity& World() noexcept; /** * to be called by WinMain() */ static void Main(const Args& args); /** * setting this to false will terminate the simulation * * @returns whether or not the simulation is active */ static bool& IsActive() noexcept; /** * runs before the first Update() */ static void Init(); /** * the main engine loop */ static void Update(); /** * runs after the last Update() */ static void Terminate(); private: /** * wraps all of the logic for parsing the command line args. */ static void ParseArgs(const Args& args); /** * Invoked by WinMain's WndProc. * * @param hWnd HWND * @param uMsg UINT * @param wParam WPARAM * @param lParam LPARAM */ #ifdef _WIN64 static long long __stdcall WndProc(void* hWnd, unsigned int uMsg, unsigned long long wParam, long long lParam); #else static long __stdcall WndProc(void* hWnd, unsigned int uMsg, unsigned wParam, long lParam); #endif }; }
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import group_theory.perm group_theory.order_of_element group_theory.quotient_group universes u v open finset is_subgroup equiv equiv.perm quotient_group instance {α β : Type*} [group α] [group β] [decidable_eq β] (f : α → β) [is_group_hom f] : decidable_pred (is_group_hom.ker f) := λ _, decidable_of_iff _ (is_group_hom.mem_ker f).symm def alternating (α : Type*) [decidable_eq α] [fintype α] : Type* := is_group_hom.ker (sign : perm α → units ℤ) def perm.of_list_swap (α : Type*) [decidable_eq α] [fintype α] : list {x : α × α // x.1 ≠ x.2} → perm α | [] := 1 | (⟨(a, b), _⟩ :: l) := swap a b * perm.of_list_swap l /- not definitionally equal to `subtype.decidable_eq`, since `subtype.decidable_eq` does not reduce in the kernel -/ instance (α : Type*) [decidable_eq α] [fintype α] : decidable_eq (alternating α) := λ a b, decidable_of_iff (a.1 = b.1) (by cases a; cases b; simp [subtype.mk.inj_eq]) instance (α : Type*) [decidable_eq α] [fintype α] : fintype (alternating α) := set_fintype _ instance (α : Type*) [decidable_eq α] [fintype α] : group (alternating α) := by unfold alternating; apply_instance section classical local attribute [instance, priority 0] classical.prop_decidable lemma card_alternating {α : Type*} [decidable_eq α] [fintype α] (h : 2 ≤ fintype.card α): fintype.card (alternating α) = (fintype.card α).fact / 2 := have (quotient_group.quotient (is_group_hom.ker (sign : perm α → units ℤ))) ≃ units ℤ, from quotient_ker_equiv_of_surjective _ (sign_surjective h), (nat.mul_right_inj (show 0 < 2, from dec_trivial)).1 $ calc fintype.card (alternating α) * 2 = fintype.card (units ℤ × alternating α) : by rw [mul_comm, fintype.card_prod, fintype.card_units_int] ... = fintype.card (perm α) : fintype.card_congr (calc (units ℤ × alternating α) ≃ (quotient_group.quotient (is_group_hom.ker (sign : perm α → units ℤ)) × alternating α) : equiv.prod_congr this.symm (by refl) ... ≃ perm α : (group_equiv_quotient_times_subgroup _).symm) ... = (fintype.card α).fact : fintype.card_perm ... = (fintype.card α).fact / 2 * 2 : eq.symm $ nat.div_mul_cancel (nat.dvd_fact dec_trivial h) end classical local notation `A5` := alternating (fin 5) variables {α : Type*} [fintype α] [decidable_eq α] section meta_ local attribute [semireducible] reflected meta instance fin_reflect (n : ℕ) : has_reflect (fin n) := λ a, `(@fin.mk %%`(n) %%(nat.reflect a.1) (of_as_true %%`(_root_.trivial))) meta instance fin_fun.has_reflect : has_reflect (fin 5 → fin 5) := list.rec_on (quot.unquot (@univ (fin 5) _).1) (λ f, `(λ y : fin 5, y)) (λ x l ih f, let e := ih f in if f x = x then e else let ex := fin_reflect 5 x in let efx := fin_reflect 5 (f x) in if e = `(λ y : fin 5, y) then `(λ y : fin 5, ite (y = %%ex) (%%efx) y) else `(λ y : fin 5, ite (y = %%ex) (%%efx) ((%%e : fin 5 → fin 5) y))) meta instance : has_reflect (perm (fin 5)) := λ f, `(@equiv.mk.{1 1} (fin 5) (fin 5) %%(fin_fun.has_reflect f.to_fun) %%(fin_fun.has_reflect f.inv_fun) (of_as_true %%`(_root_.trivial)) (of_as_true %%`(_root_.trivial))) meta instance I1 : has_reflect A5 := λ f, `(@subtype.mk (perm (fin 5)) (is_group_hom.ker (sign : perm (fin 5) → units ℤ)) %%(@reflect (perm (fin 5)) f.1 (equiv.perm.has_reflect f.1)) ((is_group_hom.mem_ker sign).2 %%`(@eq.refl (units ℤ) 1))) meta instance multiset.has_reflect {α : Type} [reflected α] [has_reflect α] : has_reflect (multiset α) := λ s, let l : list α := quot.unquot s in `(@quotient.mk.{1} (list %%`(α)) _ %%`(l)) meta instance I2 (a : A5) : has_reflect {b : A5 × A5 // b.2 * a * b.2⁻¹ = b.1} := λ b, `(@subtype.mk (A5 × A5) (λ b, b.2 * %%`(a) * b.2⁻¹ = b.1) %%(prod.has_reflect _ _ b.1) (of_as_true %%`(_root_.trivial))) meta instance I3 : reflected (A5 × A5) := `(A5 × A5) meta instance I4 : has_reflect (A5 × multiset (A5 × A5)) := λ s, let ra : reflected s.1 := (I1 s.1) in `(let a : A5 := %%ra in @prod.mk A5 (multiset (A5 × A5)) a %%(multiset.has_reflect s.2)) meta instance I5 : has_reflect (A5 × list (A5 × A5)) := λ s, let ra : reflected s.1 := (I1 s.1) in `(let a : A5 := %%ra in @prod.mk A5 (list (A5 × A5)) a %%`(s.2)) meta def conjugacy_classes_A5_meta_aux : list A5 → list (A5 × list (A5 × A5)) | [] := [] | (a :: l) := let m : A5 × list (A5 × A5) := ⟨a, ((quot.unquot (@univ A5 _).1).map (λ x, show A5 × A5, from (x * a * x⁻¹, x))).pw_filter (λ x y, x.1 ≠ y.1)⟩ in m :: conjugacy_classes_A5_meta_aux (l.diff (m.2.map prod.fst)) meta def conjugacy_classes_A5_meta : multiset (A5 × multiset (A5 × A5)) := (quotient.mk ((conjugacy_classes_A5_meta_aux (quot.unquot univ.1)).map (λ a, ⟨a.1, (quotient.mk a.2)⟩))) meta def exact_reflect {α : Sort*} [has_reflect α] (a : α) : tactic unit := tactic.exact `(a) end meta_ @[irreducible] def conjugacy_classes_A5_aux : multiset (A5 × multiset (A5 × A5)) := by exact_reflect (conjugacy_classes_A5_meta) def conjugacy_classes_A5_aux_list : list (A5 × list (A5 × A5)) := by exact_reflect (conjugacy_classes_A5_meta_aux (quot.unquot finset.univ.1)) #print conjugacy_classes_A5_aux def conjugacy_classes_A5_aux2 : multiset (multiset A5) := conjugacy_classes_A5_aux.map (λ s, s.2.map prod.fst) lemma nodup_conjugacy_classes_A5_aux2_bind : (conjugacy_classes_A5_aux2.bind id).nodup := dec_trivial --#reduce nodup_conjugacy_classes_A5_aux2_bind lemma nodup_conjugacy_classes_A5_aux2 : ∀ s : multiset A5, s ∈ conjugacy_classes_A5_aux2 → s.nodup := (multiset.nodup_bind.1 nodup_conjugacy_classes_A5_aux2_bind).1 def conjugacy_classes_A5 : finset (finset A5) := ⟨conjugacy_classes_A5_aux2.pmap finset.mk nodup_conjugacy_classes_A5_aux2, dec_trivial⟩ lemma nodup_conjugacy_classes_A5_bind : (conjugacy_classes_A5.1.bind finset.val).nodup := have conjugacy_classes_A5.1.bind finset.val = conjugacy_classes_A5_aux2.bind id, from multiset.ext.2 $ λ a, by rw [conjugacy_classes_A5, @multiset.count_bind A5, @multiset.count_bind A5, multiset.map_pmap, multiset.pmap_eq_map]; refl, by rw this; exact nodup_conjugacy_classes_A5_aux2_bind lemma g : ∀ x ∈ [0,0,0,0,0,0,0], x = 0 := dec_trivial lemma ajfh : [0,1,2,3,4,5,6].nodup := dec_trivial local attribute [instance, priority 1000] finset.decidable_dforall_finset #print of_as_true lemma is_conj_conjugacy_classes_A5 : ∀ x : A5 × A5 × A5, x ∈ conjugacy_classes_A5_aux_list.bind (λ s, s.2.map (λ y : A5 × A5, (s.1, y))) → x.2.2 * x.1 * x.2.2⁻¹ = x.2.1 := @of_as_true _ (list.decidable_forall_mem _) (by trivial) -- #print list.mem -- lemma is_conj_conjugacy_classes_A5 : ∀ x : A5 × A5 × A5, -- x ∈ conjugacy_classes_A5_aux_list.bind (λ s, s.2.map (λ y : A5 × A5, (s.1, y))) → -- x.2.2 * x.1 * x.2.2⁻¹ = x.2.1 := -- begin -- assume x hx, -- repeat { refine or.rec_on hx (λ h, by rw h; exact dec_trivial) -- (λ hx, _) <|> assumption }, -- end lemma is_conj_conjugacy_classes_A5 (s : finset A5) (h : s ∈ conjugacy_classes_A5) : ∀ x y ∈ s, is_conj x y := assume x y hx hy, begin simp only [conjugacy_classes_A5, finset.mem_def, multiset.mem_pmap, conjugacy_classes_A5_aux2] at h, rcases h with ⟨t, ht₁, ht₂⟩, rw [multiset.mem_map] at ht₁, rcases ht₁ with ⟨u, hu₁, hu₂⟩, have hx' : x ∈ multiset.map (λ (b : {b : A5 × A5 // b.2 * u.1 * b.2⁻¹ = b.1}), b.1.1) u.2, { simpa [ht₂.symm, hu₂] using hx }, have hy' : y ∈ multiset.map (λ (b : {b : A5 × A5 // b.2 * u.1 * b.2⁻¹ = b.1}), b.1.1) u.2, { simpa [ht₂.symm, hu₂] using hy }, cases multiset.mem_map.1 hx' with xc hxc, cases multiset.mem_map.1 hy' with yc hyc, exact is_conj_trans (is_conj_symm (show is_conj u.1 x, from hxc.2 ▸ ⟨_, xc.2⟩)) (hyc.2 ▸ ⟨_, yc.2⟩) end variables {G : Type u} [group G] [decidable_eq G] lemma normal_subgroup_eq_bind_conjugacy_classes (s : finset (finset G)) (h₁ : ∀ x, ∃ t ∈ s, x ∈ t) (h₂ : ∀ t ∈ s, ∀ x y ∈ t, is_conj x y) (I : finset G) [nI : normal_subgroup (↑I : set G)] : ∃ u ⊆ s, I = u.bind id := ⟨(s.powerset.filter (λ u : finset (finset G), u.bind id ⊆ I)).bind id, (λ x, by simp only [finset.subset_iff, mem_bind, mem_filter, exists_imp_distrib, mem_powerset, and_imp, id.def] {contextual := tt}; tauto), le_antisymm (λ x hxI, let ⟨t, ht₁, ht₂⟩ := h₁ x in mem_bind.2 ⟨t, mem_bind.2 ⟨(s.powerset.filter (λ u : finset (finset G), u.bind id ⊆ I)).bind id, mem_filter.2 ⟨mem_powerset.2 (λ u hu, let ⟨v, hv₁, hv₂⟩ := mem_bind.1 hu in mem_powerset.1 (mem_filter.1 hv₁).1 hv₂), λ y hy, let ⟨u, hu₁, hu₂⟩ := mem_bind.1 hy in let ⟨v, hv₁, hv₂⟩ := mem_bind.1 hu₁ in (mem_filter.1 hv₁).2 (mem_bind.2 ⟨u, hv₂, hu₂⟩)⟩, mem_bind.2 ⟨{t}, mem_filter.2 ⟨by simp [ht₁, finset.subset_iff], λ y hy, let ⟨u, hu₁, hu₂⟩ := mem_bind.1 hy in let ⟨z, hz⟩ := h₂ t ht₁ x y ht₂ (by simp * at *) in hz ▸ @normal_subgroup.normal G _ I.to_set nI _ hxI _⟩, by simp⟩⟩, ht₂⟩) (λ x, by simp only [finset.subset_iff, mem_bind, exists_imp_distrib, mem_filter, mem_powerset]; tauto)⟩ lemma simple_of_card_conjugacy_classes [fintype G] (s : finset (finset G)) (h₁ : ∀ x, ∃ t ∈ s, x ∈ t) (h₂ : ∀ t ∈ s, ∀ x y ∈ t, is_conj x y) (hs : (s.1.bind finset.val).nodup) (h₃ : ∀ t ≤ s.1.map finset.card, 1 ∈ t → t.sum ∣ fintype.card G → t.sum = 1 ∨ t.sum = fintype.card G) : simple_group G := by haveI := classical.dec; exact ⟨λ H iH, let I := (set.to_finset H) in have Ii : normal_subgroup (↑I : set G), by simpa using iH, let ⟨u, hu₁, hu₂⟩ := @normal_subgroup_eq_bind_conjugacy_classes G _ _ s h₁ h₂ I Ii in have hInd : ∀ (x : finset G), x ∈ u → ∀ (y : finset G), y ∈ u → x ≠ y → id x ∩ id y = ∅, from λ x hxu y hyu hxy, begin rw multiset.nodup_bind at hs, rw [← finset.disjoint_iff_inter_eq_empty, finset.disjoint_left], exact multiset.forall_of_pairwise (λ (a b : finset G) (h : multiset.disjoint a.1 b.1), multiset.disjoint.symm h) hs.2 x (hu₁ hxu) y (hu₁ hyu) hxy end, have hci : card I = u.sum finset.card, by rw [hu₂, card_bind hInd]; refl, have hu1 : (1 : G) ∈ u.bind id, by exactI hu₂ ▸ is_submonoid.one_mem (↑I : set G), let ⟨v, hv₁, hv₂⟩ := mem_bind.1 hu1 in have hv : v = finset.singleton (1 : G), from finset.ext.2 $ λ a, ⟨λ hav, mem_singleton.2 $ is_conj_one_right.1 (h₂ v (hu₁ hv₁) _ _ hv₂ hav), by simp [show (1 : G) ∈ v, from hv₂] {contextual := tt}⟩, have hci' : card I = 1 ∨ card I = fintype.card G, begin rw [hci], exact h₃ _ (multiset.map_le_map (show u.1 ≤ s.1, from (multiset.le_iff_subset u.2).2 hu₁)) (multiset.mem_map.2 ⟨finset.singleton 1, hv ▸ hv₁, rfl⟩) (calc u.sum finset.card = card I : hci.symm ... = fintype.card (↑I : set G) : (set.card_fintype_of_finset' I (by simp)).symm ... ∣ fintype.card G : by exactI card_subgroup_dvd_card _) end, hci'.elim (λ hci', or.inl (set.ext (λ x, let ⟨y, hy⟩ := finset.card_eq_one.1 hci' in by resetI; simp only [I, finset.ext, set.mem_to_finset, finset.mem_singleton] at hy; simp [is_subgroup.mem_trivial, hy, (hy 1).1 (is_submonoid.one_mem H)]))) (λ hci', or.inr $ suffices I = finset.univ, by simpa [I, set.ext_iff, finset.ext] using this, finset.eq_of_subset_of_card_le (λ _, by simp) (by rw hci'; refl))⟩ lemma card_A5 : fintype.card A5 = 60 := card_alternating dec_trivial lemma conjugacy_classes_A5_bind_eq_univ : conjugacy_classes_A5.bind (λ t, t) = univ := eq_of_subset_of_card_le (λ _ _, finset.mem_univ _) (calc card univ = 60 : card_A5 ... ≤ (conjugacy_classes_A5.1.bind finset.val).card : dec_trivial ... = (conjugacy_classes_A5.bind id).card : begin rw [finset.card_bind, multiset.card_bind], refl, { exact multiset.forall_of_pairwise (λ a b, by simp [finset.inter_comm]) (by simp only [finset.disjoint_iff_inter_eq_empty.symm, finset.disjoint_left]; exact (multiset.nodup_bind.1 nodup_conjugacy_classes_A5_bind).2) } end) lemma simple_group_A5 : simple_group A5 := simple_of_card_conjugacy_classes conjugacy_classes_A5 (λ x, mem_bind.1 $ by rw [conjugacy_classes_A5_bind_eq_univ]; simp) is_conj_conjugacy_classes_A5 nodup_conjugacy_classes_A5_bind (by simp only [multiset.mem_powerset.symm, card_A5]; exact dec_trivial)
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import tactic.doc_commands open lean.parser tactic interactive /-- `restate_axiom` takes a structure field, and makes a new, definitionally simplified copy of it. If the existing field name ends with a `'`, the new field just has the prime removed. Otherwise, we append `_lemma`. The main application is to provide clean versions of structure fields that have been tagged with an auto_param. -/ meta def restate_axiom (d : declaration) (new_name : name) : tactic unit := do (levels, type, value, reducibility, trusted) ← pure (match d.to_definition with | declaration.defn name levels type value reducibility trusted := (levels, type, value, reducibility, trusted) | _ := undefined end), (s, u) ← mk_simp_set ff [] [], new_type ← (s.dsimplify [] type) <|> pure (type), prop ← is_prop new_type, let new_decl := if prop then declaration.thm new_name levels new_type (task.pure value) else declaration.defn new_name levels new_type value reducibility trusted, updateex_env $ λ env, env.add new_decl private meta def name_lemma (old : name) (new : option name := none) : tactic name := match new with | none := match old.components.reverse with | last :: most := (do let last := last.to_string, let last := if last.to_list.ilast = ''' then (last.to_list.reverse.drop 1).reverse.as_string else last ++ "_lemma", return (mk_str_name old.get_prefix last)) <|> failed | nil := undefined end | (some new) := return (mk_str_name old.get_prefix new.to_string) end /-- `restate_axiom` makes a new copy of a structure field, first definitionally simplifying the type. This is useful to remove `auto_param` or `opt_param` from the statement. As an example, we have: ```lean structure A := (x : ℕ) (a' : x = 1 . skip) example (z : A) : z.x = 1 := by rw A.a' -- rewrite tactic failed, lemma is not an equality nor a iff restate_axiom A.a' example (z : A) : z.x = 1 := by rw A.a ``` By default, `restate_axiom` names the new lemma by removing a trailing `'`, or otherwise appending `_lemma` if there is no trailing `'`. You can also give `restate_axiom` a second argument to specify the new name, as in ```lean restate_axiom A.a f example (z : A) : z.x = 1 := by rw A.f ``` -/ @[user_command] meta def restate_axiom_cmd (_ : parse $ tk "restate_axiom") : lean.parser unit := do from_lemma ← ident, new_name ← optional ident, from_lemma_fully_qualified ← resolve_constant from_lemma, d ← get_decl from_lemma_fully_qualified <|> fail ("declaration " ++ to_string from_lemma ++ " not found"), do { new_name ← name_lemma from_lemma_fully_qualified new_name, restate_axiom d new_name } add_tactic_doc { name := "restate_axiom", category := doc_category.cmd, decl_names := [`restate_axiom_cmd], tags := ["renaming", "environment"] }
lemma eventually_at_right_less: "\<forall>\<^sub>F y in at_right (x::'a::{linorder_topology, no_top}). x < y"
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov ! This file was ported from Lean 3 source module analysis.normed_space.complemented ! leanprover-community/mathlib commit 3397560e65278e5f31acefcdea63138bd53d1cd4 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Analysis.NormedSpace.Banach import Mathbin.Analysis.NormedSpace.FiniteDimension /-! # Complemented subspaces of normed vector spaces A submodule `p` of a topological module `E` over `R` is called *complemented* if there exists a continuous linear projection `f : E →ₗ[R] p`, `∀ x : p, f x = x`. We prove that for a closed subspace of a normed space this condition is equivalent to existence of a closed subspace `q` such that `p ⊓ q = ⊥`, `p ⊔ q = ⊤`. We also prove that a subspace of finite codimension is always a complemented subspace. ## Tags complemented subspace, normed vector space -/ variable {𝕜 E F G : Type _} [NontriviallyNormedField 𝕜] [NormedAddCommGroup E] [NormedSpace 𝕜 E] [NormedAddCommGroup F] [NormedSpace 𝕜 F] [NormedAddCommGroup G] [NormedSpace 𝕜 G] noncomputable section open LinearMap (ker range) namespace ContinuousLinearMap section variable [CompleteSpace 𝕜] theorem ker_closedComplemented_of_finiteDimensional_range (f : E →L[𝕜] F) [FiniteDimensional 𝕜 (range f)] : (ker f).ClosedComplemented := by set f' : E →L[𝕜] range f := f.cod_restrict _ (f : E →ₗ[𝕜] F).mem_range_self rcases f'.exists_right_inverse_of_surjective (f : E →ₗ[𝕜] F).range_rangeRestrict with ⟨g, hg⟩ simpa only [ker_cod_restrict] using f'.closed_complemented_ker_of_right_inverse g (ext_iff.1 hg) #align continuous_linear_map.ker_closed_complemented_of_finite_dimensional_range ContinuousLinearMap.ker_closedComplemented_of_finiteDimensional_range end variable [CompleteSpace E] [CompleteSpace (F × G)] /-- If `f : E →L[R] F` and `g : E →L[R] G` are two surjective linear maps and their kernels are complement of each other, then `x ↦ (f x, g x)` defines a linear equivalence `E ≃L[R] F × G`. -/ def equivProdOfSurjectiveOfIsCompl (f : E →L[𝕜] F) (g : E →L[𝕜] G) (hf : range f = ⊤) (hg : range g = ⊤) (hfg : IsCompl (ker f) (ker g)) : E ≃L[𝕜] F × G := ((f : E →ₗ[𝕜] F).equivProdOfSurjectiveOfIsCompl (↑g) hf hg hfg).toContinuousLinearEquivOfContinuous (f.Continuous.prod_mk g.Continuous) #align continuous_linear_map.equiv_prod_of_surjective_of_is_compl ContinuousLinearMap.equivProdOfSurjectiveOfIsCompl @[simp] theorem coe_equivProdOfSurjectiveOfIsCompl {f : E →L[𝕜] F} {g : E →L[𝕜] G} (hf : range f = ⊤) (hg : range g = ⊤) (hfg : IsCompl (ker f) (ker g)) : (equivProdOfSurjectiveOfIsCompl f g hf hg hfg : E →ₗ[𝕜] F × G) = f.Prod g := rfl #align continuous_linear_map.coe_equiv_prod_of_surjective_of_is_compl ContinuousLinearMap.coe_equivProdOfSurjectiveOfIsCompl @[simp] theorem equivProdOfSurjectiveOfIsCompl_toLinearEquiv {f : E →L[𝕜] F} {g : E →L[𝕜] G} (hf : range f = ⊤) (hg : range g = ⊤) (hfg : IsCompl (ker f) (ker g)) : (equivProdOfSurjectiveOfIsCompl f g hf hg hfg).toLinearEquiv = LinearMap.equivProdOfSurjectiveOfIsCompl f g hf hg hfg := rfl #align continuous_linear_map.equiv_prod_of_surjective_of_is_compl_to_linear_equiv ContinuousLinearMap.equivProdOfSurjectiveOfIsCompl_toLinearEquiv @[simp] theorem equivProdOfSurjectiveOfIsCompl_apply {f : E →L[𝕜] F} {g : E →L[𝕜] G} (hf : range f = ⊤) (hg : range g = ⊤) (hfg : IsCompl (ker f) (ker g)) (x : E) : equivProdOfSurjectiveOfIsCompl f g hf hg hfg x = (f x, g x) := rfl #align continuous_linear_map.equiv_prod_of_surjective_of_is_compl_apply ContinuousLinearMap.equivProdOfSurjectiveOfIsCompl_apply end ContinuousLinearMap namespace Subspace variable [CompleteSpace E] (p q : Subspace 𝕜 E) /-- If `q` is a closed complement of a closed subspace `p`, then `p × q` is continuously isomorphic to `E`. -/ def prodEquivOfClosedCompl (h : IsCompl p q) (hp : IsClosed (p : Set E)) (hq : IsClosed (q : Set E)) : (p × q) ≃L[𝕜] E := by haveI := hp.complete_space_coe; haveI := hq.complete_space_coe refine' (p.prod_equiv_of_is_compl q h).toContinuousLinearEquivOfContinuous _ exact (p.subtypeL.coprod q.subtypeL).Continuous #align subspace.prod_equiv_of_closed_compl Subspace.prodEquivOfClosedCompl /-- Projection to a closed submodule along a closed complement. -/ def linearProjOfClosedCompl (h : IsCompl p q) (hp : IsClosed (p : Set E)) (hq : IsClosed (q : Set E)) : E →L[𝕜] p := ContinuousLinearMap.fst 𝕜 p q ∘L ↑(prodEquivOfClosedCompl p q h hp hq).symm #align subspace.linear_proj_of_closed_compl Subspace.linearProjOfClosedCompl variable {p q} @[simp] theorem coe_prodEquivOfClosedCompl (h : IsCompl p q) (hp : IsClosed (p : Set E)) (hq : IsClosed (q : Set E)) : ⇑(p.prodEquivOfClosedCompl q h hp hq) = p.prodEquivOfIsCompl q h := rfl #align subspace.coe_prod_equiv_of_closed_compl Subspace.coe_prodEquivOfClosedCompl @[simp] theorem coe_prodEquivOfClosedCompl_symm (h : IsCompl p q) (hp : IsClosed (p : Set E)) (hq : IsClosed (q : Set E)) : ⇑(p.prodEquivOfClosedCompl q h hp hq).symm = (p.prodEquivOfIsCompl q h).symm := rfl #align subspace.coe_prod_equiv_of_closed_compl_symm Subspace.coe_prodEquivOfClosedCompl_symm @[simp] theorem coe_continuous_linearProjOfClosedCompl (h : IsCompl p q) (hp : IsClosed (p : Set E)) (hq : IsClosed (q : Set E)) : (p.linearProjOfClosedCompl q h hp hq : E →ₗ[𝕜] p) = p.linearProjOfIsCompl q h := rfl #align subspace.coe_continuous_linear_proj_of_closed_compl Subspace.coe_continuous_linearProjOfClosedCompl @[simp] theorem coe_continuous_linear_proj_of_closed_compl' (h : IsCompl p q) (hp : IsClosed (p : Set E)) (hq : IsClosed (q : Set E)) : ⇑(p.linearProjOfClosedCompl q h hp hq) = p.linearProjOfIsCompl q h := rfl #align subspace.coe_continuous_linear_proj_of_closed_compl' Subspace.coe_continuous_linear_proj_of_closed_compl' theorem closedComplemented_of_closed_compl (h : IsCompl p q) (hp : IsClosed (p : Set E)) (hq : IsClosed (q : Set E)) : p.ClosedComplemented := ⟨p.linearProjOfClosedCompl q h hp hq, Submodule.linearProjOfIsCompl_apply_left h⟩ #align subspace.closed_complemented_of_closed_compl Subspace.closedComplemented_of_closed_compl theorem closedComplemented_iff_has_closed_compl : p.ClosedComplemented ↔ IsClosed (p : Set E) ∧ ∃ (q : Subspace 𝕜 E)(hq : IsClosed (q : Set E)), IsCompl p q := ⟨fun h => ⟨h.IsClosed, h.has_closed_complement⟩, fun ⟨hp, ⟨q, hq, hpq⟩⟩ => closedComplemented_of_closed_compl hpq hp hq⟩ #align subspace.closed_complemented_iff_has_closed_compl Subspace.closedComplemented_iff_has_closed_compl theorem closedComplemented_of_quotient_finiteDimensional [CompleteSpace 𝕜] [FiniteDimensional 𝕜 (E ⧸ p)] (hp : IsClosed (p : Set E)) : p.ClosedComplemented := by obtain ⟨q, hq⟩ : ∃ q, IsCompl p q := p.exists_is_compl haveI : FiniteDimensional 𝕜 q := (p.quotient_equiv_of_is_compl q hq).FiniteDimensional exact closed_complemented_of_closed_compl hq hp q.closed_of_finite_dimensional #align subspace.closed_complemented_of_quotient_finite_dimensional Subspace.closedComplemented_of_quotient_finiteDimensional end Subspace
Require Import SpecDeps. Require Import RData. Require Import EventReplay. Require Import MoverTypes. Require Import Constants. Require Import CommonLib. Require Import AbsAccessor.Spec. Require Import RunComplete.Spec. Require Import RunAux.Spec. Require Import RunLoop.Spec. Local Open Scope Z_scope. Section Spec. Definition smc_rec_run_spec (rec_addr: Z64) (rec_run_addr: Z64) (adt: RData) : option (RData * Z64) := match rec_addr, rec_run_addr with | VZ64 _rec_addr, VZ64 _rec_run_addr => rely is_int64 _rec_run_addr; when'' _g_rec_run_base, _g_rec_run_ofst == find_granule_spec (VZ64 _rec_run_addr) adt; rely is_int _g_rec_run_ofst; when _t'8 == is_null_spec (_g_rec_run_base, _g_rec_run_ofst) adt; rely is_int _t'8; if (_t'8 =? 1) then Some (adt, (VZ64 1)) else rely is_int64 _rec_addr; when'' _g_rec_base, _g_rec_ofst, adt == find_lock_unused_granule_spec (VZ64 _rec_addr) (VZ64 3) adt; rely is_int _g_rec_ofst; when _t'7 == is_null_spec (_g_rec_base, _g_rec_ofst) adt; rely is_int _t'7; if (_t'7 =? 1) then Some (adt, (VZ64 1)) else when adt == atomic_granule_get_spec (_g_rec_base, _g_rec_ofst) adt; when adt == granule_unlock_spec (_g_rec_base, _g_rec_ofst) adt; when adt == ns_granule_map_spec 0 (_g_rec_run_base, _g_rec_run_ofst) adt; when _t'6, adt == ns_buffer_read_rec_run_spec 0 adt; rely is_int _t'6; if (_t'6 =? 0) then when adt == ns_buffer_unmap_spec 0 adt; when adt == atomic_granule_put_release_spec (_g_rec_base, _g_rec_ofst) adt; Some (adt, (VZ64 1)) else when'' _rec_base, _rec_ofst, adt == granule_map_spec (_g_rec_base, _g_rec_ofst) 3 adt; rely is_int _rec_ofst; when adt == granule_lock_spec (_g_rec_base, _g_rec_ofst) adt; when _t'5 == get_rec_runnable_spec (_rec_base, _rec_ofst) adt; rely is_int _t'5; if (_t'5 =? 0) then when adt == granule_unlock_spec (_g_rec_base, _g_rec_ofst) adt; when adt == buffer_unmap_spec (_rec_base, _rec_ofst) adt; when adt == ns_buffer_unmap_spec 0 adt; when adt == atomic_granule_put_release_spec (_g_rec_base, _g_rec_ofst) adt; Some (adt, (VZ64 1)) else when _t'4, adt == complete_mmio_emulation_spec (_rec_base, _rec_ofst) adt; rely is_int _t'4; if (_t'4 =? 0) then when adt == granule_unlock_spec (_g_rec_base, _g_rec_ofst) adt; when adt == buffer_unmap_spec (_rec_base, _rec_ofst) adt; when adt == ns_buffer_unmap_spec 0 adt; when adt == atomic_granule_put_release_spec (_g_rec_base, _g_rec_ofst) adt; Some (adt, (VZ64 1)) else when adt == complete_hvc_exit_spec (_rec_base, _rec_ofst) adt; when adt == reset_last_run_info_spec (_rec_base, _rec_ofst) adt; when adt == reset_disposed_info_spec (_rec_base, _rec_ofst) adt; when adt == granule_unlock_spec (_g_rec_base, _g_rec_ofst) adt; when adt == rec_run_loop_spec (_rec_base, _rec_ofst) adt; Some (adt, (VZ64 2)) end. End Spec.
State Before: ι : Type ?u.32704 α : Type u_1 β : Type ?u.32710 π : ι → Type ?u.32715 inst✝ : GeneralizedCoheytingAlgebra α a b c d : α ⊢ (a \ b) ∆ b = a ⊔ b State After: no goals Tactic: rw [symmDiff_comm, symmDiff_sdiff_eq_sup, sup_comm]
[GOAL] 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B C : Set E x : E hAB : IsExtreme 𝕜 A B hBC : IsExtreme 𝕜 B C ⊢ IsExtreme 𝕜 A C [PROOFSTEP] refine' ⟨Subset.trans hBC.1 hAB.1, fun x₁ hx₁A x₂ hx₂A x hxC hx ↦ _⟩ [GOAL] 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B C : Set E x✝ : E hAB : IsExtreme 𝕜 A B hBC : IsExtreme 𝕜 B C x₁ : E hx₁A : x₁ ∈ A x₂ : E hx₂A : x₂ ∈ A x : E hxC : x ∈ C hx : x ∈ openSegment 𝕜 x₁ x₂ ⊢ x₁ ∈ C ∧ x₂ ∈ C [PROOFSTEP] obtain ⟨hx₁B, hx₂B⟩ := hAB.2 hx₁A hx₂A (hBC.1 hxC) hx [GOAL] case intro 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B C : Set E x✝ : E hAB : IsExtreme 𝕜 A B hBC : IsExtreme 𝕜 B C x₁ : E hx₁A : x₁ ∈ A x₂ : E hx₂A : x₂ ∈ A x : E hxC : x ∈ C hx : x ∈ openSegment 𝕜 x₁ x₂ hx₁B : x₁ ∈ B hx₂B : x₂ ∈ B ⊢ x₁ ∈ C ∧ x₂ ∈ C [PROOFSTEP] exact hBC.2 hx₁B hx₂B hxC hx [GOAL] 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B C : Set E x : E hAB : IsExtreme 𝕜 A B hAC : IsExtreme 𝕜 A C ⊢ IsExtreme 𝕜 A (B ∩ C) [PROOFSTEP] use Subset.trans (inter_subset_left _ _) hAB.1 [GOAL] case right 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B C : Set E x : E hAB : IsExtreme 𝕜 A B hAC : IsExtreme 𝕜 A C ⊢ ∀ ⦃x₁ : E⦄, x₁ ∈ A → ∀ ⦃x₂ : E⦄, x₂ ∈ A → ∀ ⦃x : E⦄, x ∈ B ∩ C → x ∈ openSegment 𝕜 x₁ x₂ → x₁ ∈ B ∩ C ∧ x₂ ∈ B ∩ C [PROOFSTEP] rintro x₁ hx₁A x₂ hx₂A x ⟨hxB, hxC⟩ hx [GOAL] case right.intro 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B C : Set E x✝ : E hAB : IsExtreme 𝕜 A B hAC : IsExtreme 𝕜 A C x₁ : E hx₁A : x₁ ∈ A x₂ : E hx₂A : x₂ ∈ A x : E hxB : x ∈ B hxC : x ∈ C hx : x ∈ openSegment 𝕜 x₁ x₂ ⊢ x₁ ∈ B ∩ C ∧ x₂ ∈ B ∩ C [PROOFSTEP] obtain ⟨hx₁B, hx₂B⟩ := hAB.2 hx₁A hx₂A hxB hx [GOAL] case right.intro.intro 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B C : Set E x✝ : E hAB : IsExtreme 𝕜 A B hAC : IsExtreme 𝕜 A C x₁ : E hx₁A : x₁ ∈ A x₂ : E hx₂A : x₂ ∈ A x : E hxB : x ∈ B hxC : x ∈ C hx : x ∈ openSegment 𝕜 x₁ x₂ hx₁B : x₁ ∈ B hx₂B : x₂ ∈ B ⊢ x₁ ∈ B ∩ C ∧ x₂ ∈ B ∩ C [PROOFSTEP] obtain ⟨hx₁C, hx₂C⟩ := hAC.2 hx₁A hx₂A hxC hx [GOAL] case right.intro.intro.intro 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B C : Set E x✝ : E hAB : IsExtreme 𝕜 A B hAC : IsExtreme 𝕜 A C x₁ : E hx₁A : x₁ ∈ A x₂ : E hx₂A : x₂ ∈ A x : E hxB : x ∈ B hxC : x ∈ C hx : x ∈ openSegment 𝕜 x₁ x₂ hx₁B : x₁ ∈ B hx₂B : x₂ ∈ B hx₁C : x₁ ∈ C hx₂C : x₂ ∈ C ⊢ x₁ ∈ B ∩ C ∧ x₂ ∈ B ∩ C [PROOFSTEP] exact ⟨⟨hx₁B, hx₁C⟩, hx₂B, hx₂C⟩ [GOAL] 𝕜 : Type u_1 E : Type u_2 F✝ : Type u_3 ι✝ : Type u_4 π : ι✝ → Type u_5 inst✝³ : OrderedSemiring 𝕜 inst✝² : AddCommMonoid E inst✝¹ : SMul 𝕜 E A B C : Set E x : E ι : Sort u_6 inst✝ : Nonempty ι F : ι → Set E hAF : ∀ (i : ι), IsExtreme 𝕜 A (F i) ⊢ IsExtreme 𝕜 A (⋂ (i : ι), F i) [PROOFSTEP] obtain i := Classical.arbitrary ι [GOAL] 𝕜 : Type u_1 E : Type u_2 F✝ : Type u_3 ι✝ : Type u_4 π : ι✝ → Type u_5 inst✝³ : OrderedSemiring 𝕜 inst✝² : AddCommMonoid E inst✝¹ : SMul 𝕜 E A B C : Set E x : E ι : Sort u_6 inst✝ : Nonempty ι F : ι → Set E hAF : ∀ (i : ι), IsExtreme 𝕜 A (F i) i : ι ⊢ IsExtreme 𝕜 A (⋂ (i : ι), F i) [PROOFSTEP] refine' ⟨iInter_subset_of_subset i (hAF i).1, fun x₁ hx₁A x₂ hx₂A x hxF hx ↦ _⟩ [GOAL] 𝕜 : Type u_1 E : Type u_2 F✝ : Type u_3 ι✝ : Type u_4 π : ι✝ → Type u_5 inst✝³ : OrderedSemiring 𝕜 inst✝² : AddCommMonoid E inst✝¹ : SMul 𝕜 E A B C : Set E x✝ : E ι : Sort u_6 inst✝ : Nonempty ι F : ι → Set E hAF : ∀ (i : ι), IsExtreme 𝕜 A (F i) i : ι x₁ : E hx₁A : x₁ ∈ A x₂ : E hx₂A : x₂ ∈ A x : E hxF : x ∈ ⋂ (i : ι), F i hx : x ∈ openSegment 𝕜 x₁ x₂ ⊢ x₁ ∈ ⋂ (i : ι), F i ∧ x₂ ∈ ⋂ (i : ι), F i [PROOFSTEP] simp_rw [mem_iInter] at hxF ⊢ [GOAL] 𝕜 : Type u_1 E : Type u_2 F✝ : Type u_3 ι✝ : Type u_4 π : ι✝ → Type u_5 inst✝³ : OrderedSemiring 𝕜 inst✝² : AddCommMonoid E inst✝¹ : SMul 𝕜 E A B C : Set E x✝ : E ι : Sort u_6 inst✝ : Nonempty ι F : ι → Set E hAF : ∀ (i : ι), IsExtreme 𝕜 A (F i) i : ι x₁ : E hx₁A : x₁ ∈ A x₂ : E hx₂A : x₂ ∈ A x : E hx : x ∈ openSegment 𝕜 x₁ x₂ hxF : ∀ (i : ι), x ∈ F i ⊢ (∀ (i : ι), x₁ ∈ F i) ∧ ∀ (i : ι), x₂ ∈ F i [PROOFSTEP] have h := fun i ↦ (hAF i).2 hx₁A hx₂A (hxF i) hx [GOAL] 𝕜 : Type u_1 E : Type u_2 F✝ : Type u_3 ι✝ : Type u_4 π : ι✝ → Type u_5 inst✝³ : OrderedSemiring 𝕜 inst✝² : AddCommMonoid E inst✝¹ : SMul 𝕜 E A B C : Set E x✝ : E ι : Sort u_6 inst✝ : Nonempty ι F : ι → Set E hAF : ∀ (i : ι), IsExtreme 𝕜 A (F i) i : ι x₁ : E hx₁A : x₁ ∈ A x₂ : E hx₂A : x₂ ∈ A x : E hx : x ∈ openSegment 𝕜 x₁ x₂ hxF : ∀ (i : ι), x ∈ F i h : ∀ (i : ι), x₁ ∈ F i ∧ x₂ ∈ F i ⊢ (∀ (i : ι), x₁ ∈ F i) ∧ ∀ (i : ι), x₂ ∈ F i [PROOFSTEP] exact ⟨fun i ↦ (h i).1, fun i ↦ (h i).2⟩ [GOAL] 𝕜 : Type u_1 E : Type u_2 F✝ : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B C : Set E x : E F : Set (Set E) hF : Set.Nonempty F hA : ∀ (B : Set E), B ∈ F → IsExtreme 𝕜 A B ⊢ IsExtreme 𝕜 A (⋂ (B : Set E) (_ : B ∈ F), B) [PROOFSTEP] haveI := hF.to_subtype [GOAL] 𝕜 : Type u_1 E : Type u_2 F✝ : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B C : Set E x : E F : Set (Set E) hF : Set.Nonempty F hA : ∀ (B : Set E), B ∈ F → IsExtreme 𝕜 A B this : Nonempty ↑F ⊢ IsExtreme 𝕜 A (⋂ (B : Set E) (_ : B ∈ F), B) [PROOFSTEP] simpa only [iInter_subtype] using isExtreme_iInter fun i : F ↦ hA _ i.2 [GOAL] 𝕜 : Type u_1 E : Type u_2 F✝ : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B C : Set E x : E F : Set (Set E) hF : Set.Nonempty F hAF : ∀ (B : Set E), B ∈ F → IsExtreme 𝕜 A B ⊢ IsExtreme 𝕜 A (⋂₀ F) [PROOFSTEP] obtain ⟨B, hB⟩ := hF [GOAL] case intro 𝕜 : Type u_1 E : Type u_2 F✝ : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B✝ C : Set E x : E F : Set (Set E) hAF : ∀ (B : Set E), B ∈ F → IsExtreme 𝕜 A B B : Set E hB : B ∈ F ⊢ IsExtreme 𝕜 A (⋂₀ F) [PROOFSTEP] refine' ⟨(sInter_subset_of_mem hB).trans (hAF B hB).1, fun x₁ hx₁A x₂ hx₂A x hxF hx ↦ _⟩ [GOAL] case intro 𝕜 : Type u_1 E : Type u_2 F✝ : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B✝ C : Set E x✝ : E F : Set (Set E) hAF : ∀ (B : Set E), B ∈ F → IsExtreme 𝕜 A B B : Set E hB : B ∈ F x₁ : E hx₁A : x₁ ∈ A x₂ : E hx₂A : x₂ ∈ A x : E hxF : x ∈ ⋂₀ F hx : x ∈ openSegment 𝕜 x₁ x₂ ⊢ x₁ ∈ ⋂₀ F ∧ x₂ ∈ ⋂₀ F [PROOFSTEP] simp_rw [mem_sInter] at hxF ⊢ [GOAL] case intro 𝕜 : Type u_1 E : Type u_2 F✝ : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B✝ C : Set E x✝ : E F : Set (Set E) hAF : ∀ (B : Set E), B ∈ F → IsExtreme 𝕜 A B B : Set E hB : B ∈ F x₁ : E hx₁A : x₁ ∈ A x₂ : E hx₂A : x₂ ∈ A x : E hx : x ∈ openSegment 𝕜 x₁ x₂ hxF : ∀ (t : Set E), t ∈ F → x ∈ t ⊢ (∀ (t : Set E), t ∈ F → x₁ ∈ t) ∧ ∀ (t : Set E), t ∈ F → x₂ ∈ t [PROOFSTEP] have h := fun B hB ↦ (hAF B hB).2 hx₁A hx₂A (hxF B hB) hx [GOAL] case intro 𝕜 : Type u_1 E : Type u_2 F✝ : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B✝ C : Set E x✝ : E F : Set (Set E) hAF : ∀ (B : Set E), B ∈ F → IsExtreme 𝕜 A B B : Set E hB : B ∈ F x₁ : E hx₁A : x₁ ∈ A x₂ : E hx₂A : x₂ ∈ A x : E hx : x ∈ openSegment 𝕜 x₁ x₂ hxF : ∀ (t : Set E), t ∈ F → x ∈ t h : ∀ (B : Set E), B ∈ F → x₁ ∈ B ∧ x₂ ∈ B ⊢ (∀ (t : Set E), t ∈ F → x₁ ∈ t) ∧ ∀ (t : Set E), t ∈ F → x₂ ∈ t [PROOFSTEP] exact ⟨fun B hB ↦ (h B hB).1, fun B hB ↦ (h B hB).2⟩ [GOAL] 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B C : Set E x : E ⊢ x ∈ extremePoints 𝕜 A ↔ IsExtreme 𝕜 A {x} [PROOFSTEP] refine' ⟨_, fun hx ↦ ⟨singleton_subset_iff.1 hx.1, fun x₁ hx₁ x₂ hx₂ ↦ hx.2 hx₁ hx₂ rfl⟩⟩ [GOAL] 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B C : Set E x : E ⊢ x ∈ extremePoints 𝕜 A → IsExtreme 𝕜 A {x} [PROOFSTEP] rintro ⟨hxA, hAx⟩ [GOAL] case intro 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B C : Set E x : E hxA : x ∈ A hAx : ∀ ⦃x₁ : E⦄, x₁ ∈ A → ∀ ⦃x₂ : E⦄, x₂ ∈ A → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x ⊢ IsExtreme 𝕜 A {x} [PROOFSTEP] use singleton_subset_iff.2 hxA [GOAL] case right 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B C : Set E x : E hxA : x ∈ A hAx : ∀ ⦃x₁ : E⦄, x₁ ∈ A → ∀ ⦃x₂ : E⦄, x₂ ∈ A → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x ⊢ ∀ ⦃x₁ : E⦄, x₁ ∈ A → ∀ ⦃x₂ : E⦄, x₂ ∈ A → ∀ ⦃x_1 : E⦄, x_1 ∈ {x} → x_1 ∈ openSegment 𝕜 x₁ x₂ → x₁ ∈ {x} ∧ x₂ ∈ {x} [PROOFSTEP] rintro x₁ hx₁A x₂ hx₂A y (rfl : y = x) [GOAL] case right 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝² : OrderedSemiring 𝕜 inst✝¹ : AddCommMonoid E inst✝ : SMul 𝕜 E A B C : Set E x₁ : E hx₁A : x₁ ∈ A x₂ : E hx₂A : x₂ ∈ A y : E hxA : y ∈ A hAx : ∀ ⦃x₁ : E⦄, x₁ ∈ A → ∀ ⦃x₂ : E⦄, x₂ ∈ A → y ∈ openSegment 𝕜 x₁ x₂ → x₁ = y ∧ x₂ = y ⊢ y ∈ openSegment 𝕜 x₁ x₂ → x₁ ∈ {y} ∧ x₂ ∈ {y} [PROOFSTEP] exact hAx hx₁A hx₂A [GOAL] 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x : E s : Set E t : Set F ⊢ extremePoints 𝕜 (s ×ˢ t) = extremePoints 𝕜 s ×ˢ extremePoints 𝕜 t [PROOFSTEP] ext [GOAL] case h 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x : E s : Set E t : Set F x✝ : E × F ⊢ x✝ ∈ extremePoints 𝕜 (s ×ˢ t) ↔ x✝ ∈ extremePoints 𝕜 s ×ˢ extremePoints 𝕜 t [PROOFSTEP] refine' (and_congr_right fun hx ↦ ⟨fun h ↦ _, fun h ↦ _⟩).trans and_and_and_comm [GOAL] case h.refine'_1 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x : E s : Set E t : Set F x✝ : E × F hx : x✝ ∈ s ×ˢ t h : ∀ ⦃x₁ : E × F⦄, x₁ ∈ s ×ˢ t → ∀ ⦃x₂ : E × F⦄, x₂ ∈ s ×ˢ t → x✝ ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝ ∧ x₂ = x✝ ⊢ (∀ ⦃x₁ : E⦄, x₁ ∈ s → ∀ ⦃x₂ : E⦄, x₂ ∈ s → x✝.fst ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝.fst ∧ x₂ = x✝.fst) ∧ ∀ ⦃x₁ : F⦄, x₁ ∈ t → ∀ ⦃x₂ : F⦄, x₂ ∈ t → x✝.snd ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝.snd ∧ x₂ = x✝.snd case h.refine'_2 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x : E s : Set E t : Set F x✝ : E × F hx : x✝ ∈ s ×ˢ t h : (∀ ⦃x₁ : E⦄, x₁ ∈ s → ∀ ⦃x₂ : E⦄, x₂ ∈ s → x✝.fst ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝.fst ∧ x₂ = x✝.fst) ∧ ∀ ⦃x₁ : F⦄, x₁ ∈ t → ∀ ⦃x₂ : F⦄, x₂ ∈ t → x✝.snd ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝.snd ∧ x₂ = x✝.snd ⊢ ∀ ⦃x₁ : E × F⦄, x₁ ∈ s ×ˢ t → ∀ ⦃x₂ : E × F⦄, x₂ ∈ s ×ˢ t → x✝ ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝ ∧ x₂ = x✝ [PROOFSTEP] constructor [GOAL] case h.refine'_1.left 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x : E s : Set E t : Set F x✝ : E × F hx : x✝ ∈ s ×ˢ t h : ∀ ⦃x₁ : E × F⦄, x₁ ∈ s ×ˢ t → ∀ ⦃x₂ : E × F⦄, x₂ ∈ s ×ˢ t → x✝ ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝ ∧ x₂ = x✝ ⊢ ∀ ⦃x₁ : E⦄, x₁ ∈ s → ∀ ⦃x₂ : E⦄, x₂ ∈ s → x✝.fst ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝.fst ∧ x₂ = x✝.fst [PROOFSTEP] rintro x₁ hx₁ x₂ hx₂ hx_fst [GOAL] case h.refine'_1.left 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x : E s : Set E t : Set F x✝ : E × F hx : x✝ ∈ s ×ˢ t h : ∀ ⦃x₁ : E × F⦄, x₁ ∈ s ×ˢ t → ∀ ⦃x₂ : E × F⦄, x₂ ∈ s ×ˢ t → x✝ ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝ ∧ x₂ = x✝ x₁ : E hx₁ : x₁ ∈ s x₂ : E hx₂ : x₂ ∈ s hx_fst : x✝.fst ∈ openSegment 𝕜 x₁ x₂ ⊢ x₁ = x✝.fst ∧ x₂ = x✝.fst [PROOFSTEP] refine' (h (mk_mem_prod hx₁ hx.2) (mk_mem_prod hx₂ hx.2) _).imp (congr_arg Prod.fst) (congr_arg Prod.fst) [GOAL] case h.refine'_1.left 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x : E s : Set E t : Set F x✝ : E × F hx : x✝ ∈ s ×ˢ t h : ∀ ⦃x₁ : E × F⦄, x₁ ∈ s ×ˢ t → ∀ ⦃x₂ : E × F⦄, x₂ ∈ s ×ˢ t → x✝ ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝ ∧ x₂ = x✝ x₁ : E hx₁ : x₁ ∈ s x₂ : E hx₂ : x₂ ∈ s hx_fst : x✝.fst ∈ openSegment 𝕜 x₁ x₂ ⊢ x✝ ∈ openSegment 𝕜 (x₁, x✝.snd) (x₂, x✝.snd) [PROOFSTEP] rw [← Prod.image_mk_openSegment_left] [GOAL] case h.refine'_1.left 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x : E s : Set E t : Set F x✝ : E × F hx : x✝ ∈ s ×ˢ t h : ∀ ⦃x₁ : E × F⦄, x₁ ∈ s ×ˢ t → ∀ ⦃x₂ : E × F⦄, x₂ ∈ s ×ˢ t → x✝ ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝ ∧ x₂ = x✝ x₁ : E hx₁ : x₁ ∈ s x₂ : E hx₂ : x₂ ∈ s hx_fst : x✝.fst ∈ openSegment 𝕜 x₁ x₂ ⊢ x✝ ∈ (fun x => (x, x✝.snd)) '' openSegment 𝕜 x₁ x₂ [PROOFSTEP] exact ⟨_, hx_fst, Prod.mk.eta⟩ [GOAL] case h.refine'_1.right 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x : E s : Set E t : Set F x✝ : E × F hx : x✝ ∈ s ×ˢ t h : ∀ ⦃x₁ : E × F⦄, x₁ ∈ s ×ˢ t → ∀ ⦃x₂ : E × F⦄, x₂ ∈ s ×ˢ t → x✝ ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝ ∧ x₂ = x✝ ⊢ ∀ ⦃x₁ : F⦄, x₁ ∈ t → ∀ ⦃x₂ : F⦄, x₂ ∈ t → x✝.snd ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝.snd ∧ x₂ = x✝.snd [PROOFSTEP] rintro x₁ hx₁ x₂ hx₂ hx_snd [GOAL] case h.refine'_1.right 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x : E s : Set E t : Set F x✝ : E × F hx : x✝ ∈ s ×ˢ t h : ∀ ⦃x₁ : E × F⦄, x₁ ∈ s ×ˢ t → ∀ ⦃x₂ : E × F⦄, x₂ ∈ s ×ˢ t → x✝ ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝ ∧ x₂ = x✝ x₁ : F hx₁ : x₁ ∈ t x₂ : F hx₂ : x₂ ∈ t hx_snd : x✝.snd ∈ openSegment 𝕜 x₁ x₂ ⊢ x₁ = x✝.snd ∧ x₂ = x✝.snd [PROOFSTEP] refine' (h (mk_mem_prod hx.1 hx₁) (mk_mem_prod hx.1 hx₂) _).imp (congr_arg Prod.snd) (congr_arg Prod.snd) [GOAL] case h.refine'_1.right 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x : E s : Set E t : Set F x✝ : E × F hx : x✝ ∈ s ×ˢ t h : ∀ ⦃x₁ : E × F⦄, x₁ ∈ s ×ˢ t → ∀ ⦃x₂ : E × F⦄, x₂ ∈ s ×ˢ t → x✝ ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝ ∧ x₂ = x✝ x₁ : F hx₁ : x₁ ∈ t x₂ : F hx₂ : x₂ ∈ t hx_snd : x✝.snd ∈ openSegment 𝕜 x₁ x₂ ⊢ x✝ ∈ openSegment 𝕜 (x✝.fst, x₁) (x✝.fst, x₂) [PROOFSTEP] rw [← Prod.image_mk_openSegment_right] [GOAL] case h.refine'_1.right 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x : E s : Set E t : Set F x✝ : E × F hx : x✝ ∈ s ×ˢ t h : ∀ ⦃x₁ : E × F⦄, x₁ ∈ s ×ˢ t → ∀ ⦃x₂ : E × F⦄, x₂ ∈ s ×ˢ t → x✝ ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝ ∧ x₂ = x✝ x₁ : F hx₁ : x₁ ∈ t x₂ : F hx₂ : x₂ ∈ t hx_snd : x✝.snd ∈ openSegment 𝕜 x₁ x₂ ⊢ x✝ ∈ (fun y => (x✝.fst, y)) '' openSegment 𝕜 x₁ x₂ [PROOFSTEP] exact ⟨_, hx_snd, Prod.mk.eta⟩ [GOAL] case h.refine'_2 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x : E s : Set E t : Set F x✝ : E × F hx : x✝ ∈ s ×ˢ t h : (∀ ⦃x₁ : E⦄, x₁ ∈ s → ∀ ⦃x₂ : E⦄, x₂ ∈ s → x✝.fst ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝.fst ∧ x₂ = x✝.fst) ∧ ∀ ⦃x₁ : F⦄, x₁ ∈ t → ∀ ⦃x₂ : F⦄, x₂ ∈ t → x✝.snd ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝.snd ∧ x₂ = x✝.snd ⊢ ∀ ⦃x₁ : E × F⦄, x₁ ∈ s ×ˢ t → ∀ ⦃x₂ : E × F⦄, x₂ ∈ s ×ˢ t → x✝ ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝ ∧ x₂ = x✝ [PROOFSTEP] rintro x₁ hx₁ x₂ hx₂ ⟨a, b, ha, hb, hab, hx'⟩ [GOAL] case h.refine'_2.intro.intro.intro.intro.intro 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x : E s : Set E t : Set F x✝ : E × F hx : x✝ ∈ s ×ˢ t h : (∀ ⦃x₁ : E⦄, x₁ ∈ s → ∀ ⦃x₂ : E⦄, x₂ ∈ s → x✝.fst ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝.fst ∧ x₂ = x✝.fst) ∧ ∀ ⦃x₁ : F⦄, x₁ ∈ t → ∀ ⦃x₂ : F⦄, x₂ ∈ t → x✝.snd ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝.snd ∧ x₂ = x✝.snd x₁ : E × F hx₁ : x₁ ∈ s ×ˢ t x₂ : E × F hx₂ : x₂ ∈ s ×ˢ t a b : 𝕜 ha : 0 < a hb : 0 < b hab : a + b = 1 hx' : a • x₁ + b • x₂ = x✝ ⊢ x₁ = x✝ ∧ x₂ = x✝ [PROOFSTEP] simp_rw [Prod.ext_iff] [GOAL] case h.refine'_2.intro.intro.intro.intro.intro 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x : E s : Set E t : Set F x✝ : E × F hx : x✝ ∈ s ×ˢ t h : (∀ ⦃x₁ : E⦄, x₁ ∈ s → ∀ ⦃x₂ : E⦄, x₂ ∈ s → x✝.fst ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝.fst ∧ x₂ = x✝.fst) ∧ ∀ ⦃x₁ : F⦄, x₁ ∈ t → ∀ ⦃x₂ : F⦄, x₂ ∈ t → x✝.snd ∈ openSegment 𝕜 x₁ x₂ → x₁ = x✝.snd ∧ x₂ = x✝.snd x₁ : E × F hx₁ : x₁ ∈ s ×ˢ t x₂ : E × F hx₂ : x₂ ∈ s ×ˢ t a b : 𝕜 ha : 0 < a hb : 0 < b hab : a + b = 1 hx' : a • x₁ + b • x₂ = x✝ ⊢ (x₁.fst = x✝.fst ∧ x₁.snd = x✝.snd) ∧ x₂.fst = x✝.fst ∧ x₂.snd = x✝.snd [PROOFSTEP] exact and_and_and_comm.1 ⟨h.1 hx₁.1 hx₂.1 ⟨a, b, ha, hb, hab, congr_arg Prod.fst hx'⟩, h.2 hx₁.2 hx₂.2 ⟨a, b, ha, hb, hab, congr_arg Prod.snd hx'⟩⟩ [GOAL] 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x : E s : (i : ι) → Set (π i) ⊢ extremePoints 𝕜 (pi univ s) = pi univ fun i => extremePoints 𝕜 (s i) [PROOFSTEP] ext x [GOAL] case h 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i ⊢ x ∈ extremePoints 𝕜 (pi univ s) ↔ x ∈ pi univ fun i => extremePoints 𝕜 (s i) [PROOFSTEP] simp only [mem_extremePoints, mem_pi, mem_univ, true_imp_iff, @forall_and ι] [GOAL] case h 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i ⊢ ((∀ (i : ι), x i ∈ s i) ∧ ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x) ↔ (∀ (i : ι), x i ∈ s i) ∧ ∀ (x_1 : ι) (x₁ : π x_1), x₁ ∈ s x_1 → ∀ (x₂ : π x_1), x₂ ∈ s x_1 → x x_1 ∈ openSegment 𝕜 x₁ x₂ → x₁ = x x_1 ∧ x₂ = x x_1 [PROOFSTEP] refine' and_congr_right fun hx ↦ ⟨fun h i ↦ _, fun h ↦ _⟩ [GOAL] case h.refine'_1 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι ⊢ ∀ (x₁ : π i), x₁ ∈ s i → ∀ (x₂ : π i), x₂ ∈ s i → x i ∈ openSegment 𝕜 x₁ x₂ → x₁ = x i ∧ x₂ = x i [PROOFSTEP] rintro x₁ hx₁ x₂ hx₂ hi [GOAL] case h.refine'_1 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ ⊢ x₁ = x i ∧ x₂ = x i [PROOFSTEP] refine' (h (update x i x₁) _ (update x i x₂) _ _).imp (fun h₁ ↦ by rw [← h₁, update_same]) fun h₂ ↦ by rw [← h₂, update_same] [GOAL] 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ h₁ : update x i x₁ = x ⊢ x₁ = x i [PROOFSTEP] rw [← h₁, update_same] [GOAL] 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ h₂ : update x i x₂ = x ⊢ x₂ = x i [PROOFSTEP] rw [← h₂, update_same] [GOAL] case h.refine'_1.refine'_1 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ ⊢ ∀ (i_1 : ι), update x i x₁ i_1 ∈ s i_1 case h.refine'_1.refine'_2 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ ⊢ ∀ (i_1 : ι), update x i x₂ i_1 ∈ s i_1 case h.refine'_1.refine'_3 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ ⊢ x ∈ openSegment 𝕜 (update x i x₁) (update x i x₂) [PROOFSTEP] iterate 2 rintro j obtain rfl | hji := eq_or_ne j i · rwa [update_same] · rw [update_noteq hji] exact hx _ [GOAL] case h.refine'_1.refine'_1 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ ⊢ ∀ (i_1 : ι), update x i x₁ i_1 ∈ s i_1 case h.refine'_1.refine'_2 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ ⊢ ∀ (i_1 : ι), update x i x₂ i_1 ∈ s i_1 case h.refine'_1.refine'_3 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ ⊢ x ∈ openSegment 𝕜 (update x i x₁) (update x i x₂) [PROOFSTEP] rintro j [GOAL] case h.refine'_1.refine'_1 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ j : ι ⊢ update x i x₁ j ∈ s j case h.refine'_1.refine'_2 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ ⊢ ∀ (i_1 : ι), update x i x₂ i_1 ∈ s i_1 case h.refine'_1.refine'_3 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ ⊢ x ∈ openSegment 𝕜 (update x i x₁) (update x i x₂) [PROOFSTEP] obtain rfl | hji := eq_or_ne j i [GOAL] case h.refine'_1.refine'_1.inl 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x j : ι x₁ : π j hx₁ : x₁ ∈ s j x₂ : π j hx₂ : x₂ ∈ s j hi : x j ∈ openSegment 𝕜 x₁ x₂ ⊢ update x j x₁ j ∈ s j [PROOFSTEP] rwa [update_same] [GOAL] case h.refine'_1.refine'_1.inr 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ j : ι hji : j ≠ i ⊢ update x i x₁ j ∈ s j [PROOFSTEP] rw [update_noteq hji] [GOAL] case h.refine'_1.refine'_1.inr 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ j : ι hji : j ≠ i ⊢ x j ∈ s j [PROOFSTEP] exact hx _ [GOAL] case h.refine'_1.refine'_2 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ ⊢ ∀ (i_1 : ι), update x i x₂ i_1 ∈ s i_1 case h.refine'_1.refine'_3 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ ⊢ x ∈ openSegment 𝕜 (update x i x₁) (update x i x₂) [PROOFSTEP] rintro j [GOAL] case h.refine'_1.refine'_2 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ j : ι ⊢ update x i x₂ j ∈ s j case h.refine'_1.refine'_3 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ ⊢ x ∈ openSegment 𝕜 (update x i x₁) (update x i x₂) [PROOFSTEP] obtain rfl | hji := eq_or_ne j i [GOAL] case h.refine'_1.refine'_2.inl 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x j : ι x₁ : π j hx₁ : x₁ ∈ s j x₂ : π j hx₂ : x₂ ∈ s j hi : x j ∈ openSegment 𝕜 x₁ x₂ ⊢ update x j x₂ j ∈ s j [PROOFSTEP] rwa [update_same] [GOAL] case h.refine'_1.refine'_2.inr 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ j : ι hji : j ≠ i ⊢ update x i x₂ j ∈ s j [PROOFSTEP] rw [update_noteq hji] [GOAL] case h.refine'_1.refine'_2.inr 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ j : ι hji : j ≠ i ⊢ x j ∈ s j [PROOFSTEP] exact hx _ [GOAL] case h.refine'_1.refine'_3 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ ⊢ x ∈ openSegment 𝕜 (update x i x₁) (update x i x₂) [PROOFSTEP] rw [← Pi.image_update_openSegment] [GOAL] case h.refine'_1.refine'_3 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x i : ι x₁ : π i hx₁ : x₁ ∈ s i x₂ : π i hx₂ : x₂ ∈ s i hi : x i ∈ openSegment 𝕜 x₁ x₂ ⊢ x ∈ update x i '' openSegment 𝕜 x₁ x₂ [PROOFSTEP] exact ⟨_, hi, update_eq_self _ _⟩ [GOAL] case h.refine'_2 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x_1 : ι) (x₁ : π x_1), x₁ ∈ s x_1 → ∀ (x₂ : π x_1), x₂ ∈ s x_1 → x x_1 ∈ openSegment 𝕜 x₁ x₂ → x₁ = x x_1 ∧ x₂ = x x_1 ⊢ ∀ (x₁ : (i : ι) → π i), (∀ (i : ι), x₁ i ∈ s i) → ∀ (x₂ : (i : ι) → π i), (∀ (i : ι), x₂ i ∈ s i) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x [PROOFSTEP] rintro x₁ hx₁ x₂ hx₂ ⟨a, b, ha, hb, hab, hx'⟩ [GOAL] case h.refine'_2.intro.intro.intro.intro.intro 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x_1 : ι) (x₁ : π x_1), x₁ ∈ s x_1 → ∀ (x₂ : π x_1), x₂ ∈ s x_1 → x x_1 ∈ openSegment 𝕜 x₁ x₂ → x₁ = x x_1 ∧ x₂ = x x_1 x₁ : (i : ι) → π i hx₁ : ∀ (i : ι), x₁ i ∈ s i x₂ : (i : ι) → π i hx₂ : ∀ (i : ι), x₂ i ∈ s i a b : 𝕜 ha : 0 < a hb : 0 < b hab : a + b = 1 hx' : a • x₁ + b • x₂ = x ⊢ x₁ = x ∧ x₂ = x [PROOFSTEP] simp_rw [funext_iff, ← forall_and] [GOAL] case h.refine'_2.intro.intro.intro.intro.intro 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁶ : OrderedSemiring 𝕜 inst✝⁵ : AddCommGroup E inst✝⁴ : AddCommGroup F inst✝³ : (i : ι) → AddCommGroup (π i) inst✝² : Module 𝕜 E inst✝¹ : Module 𝕜 F inst✝ : (i : ι) → Module 𝕜 (π i) A B : Set E x✝ : E s : (i : ι) → Set (π i) x : (i : ι) → π i hx : ∀ (i : ι), x i ∈ s i h : ∀ (x_1 : ι) (x₁ : π x_1), x₁ ∈ s x_1 → ∀ (x₂ : π x_1), x₂ ∈ s x_1 → x x_1 ∈ openSegment 𝕜 x₁ x₂ → x₁ = x x_1 ∧ x₂ = x x_1 x₁ : (i : ι) → π i hx₁ : ∀ (i : ι), x₁ i ∈ s i x₂ : (i : ι) → π i hx₂ : ∀ (i : ι), x₂ i ∈ s i a b : 𝕜 ha : 0 < a hb : 0 < b hab : a + b = 1 hx' : a • x₁ + b • x₂ = x ⊢ ∀ (x_1 : ι), x₁ x_1 = x x_1 ∧ x₂ x_1 = x x_1 [PROOFSTEP] exact fun i ↦ h _ _ (hx₁ _) _ (hx₂ _) ⟨a, b, ha, hb, hab, congr_fun hx' _⟩ [GOAL] 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x : E ⊢ x ∈ extremePoints 𝕜 A ↔ x ∈ A ∧ ∀ (x₁ : E), x₁ ∈ A → ∀ (x₂ : E), x₂ ∈ A → x ∈ segment 𝕜 x₁ x₂ → x₁ = x ∨ x₂ = x [PROOFSTEP] refine' and_congr_right fun hxA ↦ forall₄_congr fun x₁ h₁ x₂ h₂ ↦ _ [GOAL] 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x : E hxA : x ∈ A x₁ : E h₁ : x₁ ∈ A x₂ : E h₂ : x₂ ∈ A ⊢ x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x ↔ x ∈ segment 𝕜 x₁ x₂ → x₁ = x ∨ x₂ = x [PROOFSTEP] constructor [GOAL] case mp 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x : E hxA : x ∈ A x₁ : E h₁ : x₁ ∈ A x₂ : E h₂ : x₂ ∈ A ⊢ (x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x) → x ∈ segment 𝕜 x₁ x₂ → x₁ = x ∨ x₂ = x [PROOFSTEP] rw [← insert_endpoints_openSegment] [GOAL] case mp 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x : E hxA : x ∈ A x₁ : E h₁ : x₁ ∈ A x₂ : E h₂ : x₂ ∈ A ⊢ (x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x) → x ∈ insert x₁ (insert x₂ (openSegment 𝕜 x₁ x₂)) → x₁ = x ∨ x₂ = x [PROOFSTEP] rintro H (rfl | rfl | hx) [GOAL] case mp.inl 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x : E hxA : x ∈ A x₂ : E h₂ : x₂ ∈ A h₁ : x ∈ A H : x ∈ openSegment 𝕜 x x₂ → x = x ∧ x₂ = x ⊢ x = x ∨ x₂ = x case mp.inr.inl 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x : E hxA : x ∈ A x₁ : E h₁ : x₁ ∈ A h₂ : x ∈ A H : x ∈ openSegment 𝕜 x₁ x → x₁ = x ∧ x = x ⊢ x₁ = x ∨ x = x case mp.inr.inr 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x : E hxA : x ∈ A x₁ : E h₁ : x₁ ∈ A x₂ : E h₂ : x₂ ∈ A H : x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x hx : x ∈ openSegment 𝕜 x₁ x₂ ⊢ x₁ = x ∨ x₂ = x [PROOFSTEP] exacts [Or.inl rfl, Or.inr rfl, Or.inl <| (H hx).1] [GOAL] case mpr 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x : E hxA : x ∈ A x₁ : E h₁ : x₁ ∈ A x₂ : E h₂ : x₂ ∈ A ⊢ (x ∈ segment 𝕜 x₁ x₂ → x₁ = x ∨ x₂ = x) → x ∈ openSegment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x [PROOFSTEP] intro H hx [GOAL] case mpr 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x : E hxA : x ∈ A x₁ : E h₁ : x₁ ∈ A x₂ : E h₂ : x₂ ∈ A H : x ∈ segment 𝕜 x₁ x₂ → x₁ = x ∨ x₂ = x hx : x ∈ openSegment 𝕜 x₁ x₂ ⊢ x₁ = x ∧ x₂ = x [PROOFSTEP] rcases H (openSegment_subset_segment _ _ _ hx) with (rfl | rfl) [GOAL] case mpr.inl 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x₁ : E h₁ : x₁ ∈ A x₂ : E h₂ : x₂ ∈ A hxA : x₁ ∈ A H : x₁ ∈ segment 𝕜 x₁ x₂ → x₁ = x₁ ∨ x₂ = x₁ hx : x₁ ∈ openSegment 𝕜 x₁ x₂ ⊢ x₁ = x₁ ∧ x₂ = x₁ case mpr.inr 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x₁ : E h₁ : x₁ ∈ A x₂ : E h₂ hxA : x₂ ∈ A H : x₂ ∈ segment 𝕜 x₁ x₂ → x₁ = x₂ ∨ x₂ = x₂ hx : x₂ ∈ openSegment 𝕜 x₁ x₂ ⊢ x₁ = x₂ ∧ x₂ = x₂ [PROOFSTEP] exacts [⟨rfl, (left_mem_openSegment_iff.1 hx).symm⟩, ⟨right_mem_openSegment_iff.1 hx, rfl⟩] [GOAL] 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x : E hA : Convex 𝕜 A ⊢ x ∈ extremePoints 𝕜 A ↔ x ∈ A ∧ Convex 𝕜 (A \ {x}) [PROOFSTEP] use fun hx ↦ ⟨hx.1, (mem_extremePoints_iff_extreme_singleton.1 hx).convex_diff hA⟩ [GOAL] case mpr 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x : E hA : Convex 𝕜 A ⊢ x ∈ A ∧ Convex 𝕜 (A \ {x}) → x ∈ extremePoints 𝕜 A [PROOFSTEP] rintro ⟨hxA, hAx⟩ [GOAL] case mpr.intro 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x : E hA : Convex 𝕜 A hxA : x ∈ A hAx : Convex 𝕜 (A \ {x}) ⊢ x ∈ extremePoints 𝕜 A [PROOFSTEP] refine' mem_extremePoints_iff_forall_segment.2 ⟨hxA, fun x₁ hx₁ x₂ hx₂ hx ↦ _⟩ [GOAL] case mpr.intro 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x : E hA : Convex 𝕜 A hxA : x ∈ A hAx : Convex 𝕜 (A \ {x}) x₁ : E hx₁ : x₁ ∈ A x₂ : E hx₂ : x₂ ∈ A hx : x ∈ [x₁-[𝕜]x₂] ⊢ x₁ = x ∨ x₂ = x [PROOFSTEP] rw [convex_iff_segment_subset] at hAx [GOAL] case mpr.intro 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x : E hA : Convex 𝕜 A hxA : x ∈ A hAx : ∀ ⦃x_1 : E⦄, x_1 ∈ A \ {x} → ∀ ⦃y : E⦄, y ∈ A \ {x} → [x_1-[𝕜]y] ⊆ A \ {x} x₁ : E hx₁ : x₁ ∈ A x₂ : E hx₂ : x₂ ∈ A hx : x ∈ [x₁-[𝕜]x₂] ⊢ x₁ = x ∨ x₂ = x [PROOFSTEP] by_contra' h [GOAL] case mpr.intro 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x : E hA : Convex 𝕜 A hxA : x ∈ A hAx : ∀ ⦃x_1 : E⦄, x_1 ∈ A \ {x} → ∀ ⦃y : E⦄, y ∈ A \ {x} → [x_1-[𝕜]y] ⊆ A \ {x} x₁ : E hx₁ : x₁ ∈ A x₂ : E hx₂ : x₂ ∈ A hx : x ∈ [x₁-[𝕜]x₂] h : x₁ ≠ x ∧ x₂ ≠ x ⊢ False [PROOFSTEP] exact (hAx ⟨hx₁, fun hx₁ ↦ h.1 (mem_singleton_iff.2 hx₁)⟩ ⟨hx₂, fun hx₂ ↦ h.2 (mem_singleton_iff.2 hx₂)⟩ hx).2 rfl [GOAL] 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x : E hA : Convex 𝕜 A ⊢ x ∈ extremePoints 𝕜 A ↔ x ∈ A \ ↑(convexHull 𝕜) (A \ {x}) [PROOFSTEP] rw [hA.mem_extremePoints_iff_convex_diff, hA.convex_remove_iff_not_mem_convexHull_remove, mem_diff] [GOAL] 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x : E ⊢ extremePoints 𝕜 (↑(convexHull 𝕜) A) ⊆ A [PROOFSTEP] rintro x hx [GOAL] 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x✝ x : E hx : x ∈ extremePoints 𝕜 (↑(convexHull 𝕜) A) ⊢ x ∈ A [PROOFSTEP] rw [(convex_convexHull 𝕜 _).mem_extremePoints_iff_convex_diff] at hx [GOAL] 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x✝ x : E hx : x ∈ ↑(convexHull 𝕜) A ∧ Convex 𝕜 (↑(convexHull 𝕜) A \ {x}) ⊢ x ∈ A [PROOFSTEP] by_contra h [GOAL] 𝕜 : Type u_1 E : Type u_2 F : Type u_3 ι : Type u_4 π : ι → Type u_5 inst✝⁴ : LinearOrderedRing 𝕜 inst✝³ : AddCommGroup E inst✝² : Module 𝕜 E inst✝¹ : DenselyOrdered 𝕜 inst✝ : NoZeroSMulDivisors 𝕜 E A B : Set E x✝ x : E hx : x ∈ ↑(convexHull 𝕜) A ∧ Convex 𝕜 (↑(convexHull 𝕜) A \ {x}) h : ¬x ∈ A ⊢ False [PROOFSTEP] exact (convexHull_min (subset_diff.2 ⟨subset_convexHull 𝕜 _, disjoint_singleton_right.2 h⟩) hx.2 hx.1).2 rfl
State Before: α : Type u_1 β : Type ?u.7261 E : Type u_2 F : Type ?u.7267 inst✝³ : MeasurableSpace α inst✝² : NormedAddCommGroup E f g : α → E s t : Set α μ ν : Measure α l l' : Filter α inst✝¹ : CompleteSpace E inst✝ : NormedSpace ℝ E ht : MeasurableSet t hfs : IntegrableOn f s hts : t ⊆ s ⊢ (∫ (x : α) in s \ t, f x ∂μ) = (∫ (x : α) in s, f x ∂μ) - ∫ (x : α) in t, f x ∂μ State After: case hst α : Type u_1 β : Type ?u.7261 E : Type u_2 F : Type ?u.7267 inst✝³ : MeasurableSpace α inst✝² : NormedAddCommGroup E f g : α → E s t : Set α μ ν : Measure α l l' : Filter α inst✝¹ : CompleteSpace E inst✝ : NormedSpace ℝ E ht : MeasurableSet t hfs : IntegrableOn f s hts : t ⊆ s ⊢ Disjoint (s \ t) t case ht α : Type u_1 β : Type ?u.7261 E : Type u_2 F : Type ?u.7267 inst✝³ : MeasurableSpace α inst✝² : NormedAddCommGroup E f g : α → E s t : Set α μ ν : Measure α l l' : Filter α inst✝¹ : CompleteSpace E inst✝ : NormedSpace ℝ E ht : MeasurableSet t hfs : IntegrableOn f s hts : t ⊆ s ⊢ MeasurableSet t case hfs α : Type u_1 β : Type ?u.7261 E : Type u_2 F : Type ?u.7267 inst✝³ : MeasurableSpace α inst✝² : NormedAddCommGroup E f g : α → E s t : Set α μ ν : Measure α l l' : Filter α inst✝¹ : CompleteSpace E inst✝ : NormedSpace ℝ E ht : MeasurableSet t hfs : IntegrableOn f s hts : t ⊆ s ⊢ IntegrableOn (fun x => f x) (s \ t) case hft α : Type u_1 β : Type ?u.7261 E : Type u_2 F : Type ?u.7267 inst✝³ : MeasurableSpace α inst✝² : NormedAddCommGroup E f g : α → E s t : Set α μ ν : Measure α l l' : Filter α inst✝¹ : CompleteSpace E inst✝ : NormedSpace ℝ E ht : MeasurableSet t hfs : IntegrableOn f s hts : t ⊆ s ⊢ IntegrableOn (fun x => f x) t Tactic: rw [eq_sub_iff_add_eq, ← integral_union, diff_union_of_subset hts] State Before: case hst α : Type u_1 β : Type ?u.7261 E : Type u_2 F : Type ?u.7267 inst✝³ : MeasurableSpace α inst✝² : NormedAddCommGroup E f g : α → E s t : Set α μ ν : Measure α l l' : Filter α inst✝¹ : CompleteSpace E inst✝ : NormedSpace ℝ E ht : MeasurableSet t hfs : IntegrableOn f s hts : t ⊆ s ⊢ Disjoint (s \ t) t case ht α : Type u_1 β : Type ?u.7261 E : Type u_2 F : Type ?u.7267 inst✝³ : MeasurableSpace α inst✝² : NormedAddCommGroup E f g : α → E s t : Set α μ ν : Measure α l l' : Filter α inst✝¹ : CompleteSpace E inst✝ : NormedSpace ℝ E ht : MeasurableSet t hfs : IntegrableOn f s hts : t ⊆ s ⊢ MeasurableSet t case hfs α : Type u_1 β : Type ?u.7261 E : Type u_2 F : Type ?u.7267 inst✝³ : MeasurableSpace α inst✝² : NormedAddCommGroup E f g : α → E s t : Set α μ ν : Measure α l l' : Filter α inst✝¹ : CompleteSpace E inst✝ : NormedSpace ℝ E ht : MeasurableSet t hfs : IntegrableOn f s hts : t ⊆ s ⊢ IntegrableOn (fun x => f x) (s \ t) case hft α : Type u_1 β : Type ?u.7261 E : Type u_2 F : Type ?u.7267 inst✝³ : MeasurableSpace α inst✝² : NormedAddCommGroup E f g : α → E s t : Set α μ ν : Measure α l l' : Filter α inst✝¹ : CompleteSpace E inst✝ : NormedSpace ℝ E ht : MeasurableSet t hfs : IntegrableOn f s hts : t ⊆ s ⊢ IntegrableOn (fun x => f x) t State After: no goals Tactic: exacts [disjoint_sdiff_self_left, ht, hfs.mono_set (diff_subset _ _), hfs.mono_set hts]
\documentclass{article} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{geometry} \geometry{ a4paper, total={170mm,257mm}, left=20mm, top=20mm, } \setlength{\parskip}{7pt} \setlength{\parindent}{0pt} \title{Using the Diligent JTAG-HS2 Programming Cable with OpenOCD} \date{2019-10-11} \author{Armand Bouvier-Neveu -- Thales Research and technology France} \PassOptionsToPackage{hyphens}{url}\usepackage{hyperref} \usepackage{listings} \usepackage{amssymb} \usepackage{graphicx} \graphicspath{ {./images/} } \usepackage{float} \lstset{ basicstyle=\ttfamily, breaklines=true, columns=fullflexible, tabsize=4, showstringspaces=false, frame=single } \begin{document} \maketitle \section{About} The JTAG-HS2 Programming Cable is an USB JTAG probe. It is available here: \url{https://store.digilentinc.com/jtag-hs2-programming-cable/} \begin{figure}[H] \centering \includegraphics[width=0.6\textwidth]{hs2.png} \end{figure} The cable is fully compatible with all Xilinx tools, but it can also be used with OpenOCD. \section{Software configuration} \subsection{Libusb} You need libusb to use the cable. On Ubuntu, you can use apt: \begin{lstlisting}[language=bash] $ sudo apt install libusb-1.0-0-dev \end{lstlisting} You can also build it yourself using the sources available on \url{https://libusb.info} \subsection{Libftdi} The cable contains an FTDI chip, so you need libftdi. Ubuntu: \begin{lstlisting}[language=bash] $ sudo apt install libftdi1-dev \end{lstlisting} Or from sources: \url{https://www.intra2net.com/en/developer/libftdi/download.php} \subsection{OpenOCD Compilation} The OpenOCD interface driver used with the cable is \textit{ftdi}. To enable this interface, use the \textit{-{}-enable-ftdi} option when compiling OpenOCD. \begin{lstlisting}[language=bash] $ ./configure --enable-ftdi <other options> \end{lstlisting} To check if your existing instance of OpenOCD supports the ftdi interface, you can list the supported debug adapter drivers: \begin{lstlisting}[language=bash] $ openocd -c interface_list \end{lstlisting} \subsection{udev rules} It is necessary to add a udev rule to use the cable. OpenOCD provides a file containing the rule we need. Copy it into /etc/udev/rules.d/ \begin{lstlisting}[language=bash] $ sudo cp <openocd>/contrib/60-openocd.rules /etc/udev/rules.d \end{lstlisting} The file is also available here: \url{https://github.com/riscv/riscv-openocd/blob/riscv/contrib/60-openocd.rules} The particular entry about the HS2 cable is : \begin{lstlisting} ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6014", MODE="660", GROUP="plugdev", TAG+="uaccess" \end{lstlisting} Then either reboot your system or reload the udev configuration with : \begin{lstlisting}[language=bash] $ sudo udevadm control --reload \end{lstlisting} \subsection{Checking} To check if the cable is recognized, run lsusb. There should be a line like this: \begin{lstlisting}[language=bash] $ lsusb [...] Bus 005 Device 003: ID 0403:6014 Future Technology Devices International, Ltd FT232H Single HS USB-UART/FIFO IC [...] \end{lstlisting} For more details about the device, use more options: \begin{lstlisting}[language=bash] $ lsusb -v -d 0403:6014 \end{lstlisting} \newpage \section{OpenOCD Config File} Examples of config files using the HS2 cable can be found on the Internet: \vspace{-\topsep} \begin{itemize} \item \url{https://github.com/pulp-platform/pulpissimo/blob/master/fpga/pulpissimo-zedboard/openocd-zedboard-hs2.cfg} \item \url{https://github.com/arduino/OpenOCD/blob/master/tcl/interface/ftdi/digilent-hs2.cfg} \end{itemize} Generally, for the interface part of the config file, you can use: \begin{lstlisting} interface ftdi ftdi_device_desc "Digilent USB Device" ftdi_vid_pid 0x0403 0x6014 ftdi_serial 210249A85F9B ftdi_channel 0 ftdi_layout_init 0x00e8 0x60eb reset_config none \end{lstlisting} Use \textbf{lsusb -v -d 0403:6014} to find the necessary values : \vspace{-\topsep} \begin{itemize} \item \textbf{ftdi\_device\_desc}: this command should use the same value as the \textbf{iProduct} field \item \textbf{ftdi\_vid\_pid}: \textbf{idVendor} and \textbf{idProduct} \item \textbf{ftdi\_serial}: this command is useful if there are more than one adapter connected to the host and can be omitted otherwise. The needed value is in the \textbf{iSerial} field. \item \textbf{ftdi\_channel}: the default (channel 0) is fine \item \textbf{ftdi\_layout\_init}: initial values of the FTDI GPIO data and direction registers. Refer to the adapter schematics to find them. 0x00e8 and 0x60eb work for the HS2 cable \end{itemize} For more information about the OpenOCD commands, see \url{http://www.openocd.org/doc/html/Debug-Adapter-Configuration.html} \newpage \section{Verification} To check if the set up is successful, you can use the following procedure: \vspace{-\topsep} \begin{itemize} \item Plug the cable in an USB port of your workstation \item Do not plug the JTAG end of the cable; leave it floating \item Run openocd with this config file (change the serial number): \begin{lstlisting}[language=bash] $ openocd -f test.cfg \end{lstlisting} \begin{lstlisting} # Digilent JTAG-HS2 interface ftdi ftdi_device_desc "Digilent USB Device" ftdi_vid_pid 0x0403 0x6014 ftdi_serial 210249A85F9B ftdi_channel 0 ftdi_layout_init 0x00e8 0x60eb reset_config none adapter_khz 1000 set _CHIPNAME riscv jtag newtap $_CHIPNAME cpu -irlen 5 set _TARGETNAME $_CHIPNAME.cpu target create $_TARGETNAME riscv -chain-position $_TARGETNAME init halt echo "Ready for Remote Connections" \end{lstlisting} \item If the set up is succesful, you should see something like this: \begin{lstlisting}[language=bash] Open On-Chip Debugger 0.10.0+dev-00630-g30b93b8-dirty (2019-10-02-14:34) Licensed under GNU GPL v2 For bug reports, read http://openocd.org/doc/doxygen/bugs.html none separate adapter speed: 1000 kHz Info : auto-selecting first available session transport "jtag". To override use 'transport select <transport>'. Info : clock speed 1000 kHz Error: JTAG scan chain interrogation failed: all zeroes Error: Check JTAG interface, timings, target power, etc. Error: Trying to use configured scan chain anyway... Error: riscv.cpu: IR capture error; saw 0x00 not 0x01 Warn : Bypassing JTAG setup events due to errors Error: dtmcontrol is 0. Check JTAG connectivity/board power. Info : Listening on port 3333 for gdb connections Error: Target not examined yet \end{lstlisting} \end{itemize} \newpage \section{Hardware configuration} The HS2 cable does not use the TRST signal. Do not leave the pin floating and tie it to 1 if the target TAP reset is active low, or 0 if it is active high. \section{Vivado Hardware Manager} The Digilent JTAG-HS2 cable is supported by the Xilinx Hardware Server. For some reason, it is impossible to use the cable with OpenOCD while the Hardware Server is active. This makes using Vivado and OpenOCD at the same time a problem. A possible fix is the following protocol: \vspace{-\topsep} \begin{itemize} \item Open the hardware server in Vivado and connect to your FPGA board \item Upload the bitstream and program the device \item \textbf{Close} the hardware server \item Launch OpenOCD \end{itemize} Of course, This closes the hardware server and removes access to Vivado features. To properly fix the issue, you would need to find a way of preventing the Vivado Hardware Server from occupying the USB device of the cable. \end{document}
(* Title: HOL/Auth/n_germanSimp_lemma_inv__3_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_germanSimp Protocol Case Study*} theory n_germanSimp_lemma_inv__3_on_rules imports n_germanSimp_lemma_on_inv__3 begin section{*All lemmas on causal relation between inv__3*} lemma lemma_inv__3_on_rules: assumes b1: "r \<in> rules N" and b2: "(f=inv__3 )" shows "invHoldForRule s f r (invariants N)" proof - have c1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__0 N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__1 N i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" apply (cut_tac b1, auto) done moreover { assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_StoreVsinv__3) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqSVsinv__3) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__0 N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqE__part__0Vsinv__3) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__1 N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqE__part__1Vsinv__3) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInv__part__0Vsinv__3) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInv__part__1Vsinv__3) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInvAckVsinv__3) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__3) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendGntSVsinv__3) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendGntEVsinv__3) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvGntSVsinv__3) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvGntEVsinv__3) done } ultimately show "invHoldForRule s f r (invariants N)" by satx qed end
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2013, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include <moveit/robot_model/robot_model.h> #include <moveit/robot_state/robot_state.h> #include <moveit/robot_state/conversions.h> #include <urdf_parser/urdf_parser.h> #include <fstream> #include <gtest/gtest.h> #include <boost/filesystem/path.hpp> #include <moveit/profiler/profiler.h> #include <moveit_resources/config.h> class LoadPlanningModelsPr2 : public testing::Test { protected: virtual void SetUp() { boost::filesystem::path res_path(MOVEIT_TEST_RESOURCES_DIR); srdf_model.reset(new srdf::Model()); std::string xml_string; std::fstream xml_file((res_path / "pr2_description/urdf/robot.xml").string().c_str(), std::fstream::in); if (xml_file.is_open()) { while (xml_file.good()) { std::string line; std::getline(xml_file, line); xml_string += (line + "\n"); } xml_file.close(); urdf_model = urdf::parseURDF(xml_string); } srdf_model->initFile(*urdf_model, (res_path / "pr2_description/srdf/robot.xml").string()); robot_model.reset(new moveit::core::RobotModel(urdf_model, srdf_model)); }; virtual void TearDown() { } protected: boost::shared_ptr<urdf::ModelInterface> urdf_model; boost::shared_ptr<srdf::Model> srdf_model; moveit::core::RobotModelConstPtr robot_model; }; TEST_F(LoadPlanningModelsPr2, InitOK) { ASSERT_EQ(urdf_model->getName(), "pr2"); ASSERT_EQ(srdf_model->getName(), "pr2"); } TEST_F(LoadPlanningModelsPr2, ModelInit) { boost::shared_ptr<srdf::Model> srdfModel(new srdf::Model()); // with no world multidof we should get a fixed joint moveit::core::RobotModel robot_model0(urdf_model, srdfModel); EXPECT_TRUE(robot_model0.getRootJoint()->getVariableCount() == 0); static const std::string SMODEL1 = "<?xml version=\"1.0\" ?>" "<robot name=\"pr2\">" "<virtual_joint name=\"base_joint\" child_link=\"base_footprint\" " "parent_frame=\"base_footprint\" type=\"planar\"/>" "</robot>"; srdfModel->initString(*urdf_model, SMODEL1); moveit::core::RobotModel robot_model1(urdf_model, srdfModel); ASSERT_TRUE(robot_model1.getRootJoint() != NULL); EXPECT_EQ(robot_model1.getModelFrame(), "/base_footprint"); static const std::string SMODEL2 = "<?xml version=\"1.0\" ?>" "<robot name=\"pr2\">" "<virtual_joint name=\"world_joint\" child_link=\"base_footprint\" " "parent_frame=\"odom_combined\" type=\"floating\"/>" "</robot>"; srdfModel->initString(*urdf_model, SMODEL2); moveit::core::RobotModel robot_model2(urdf_model, srdfModel); ASSERT_TRUE(robot_model2.getRootJoint() != NULL); EXPECT_EQ(robot_model2.getModelFrame(), "/odom_combined"); } TEST_F(LoadPlanningModelsPr2, GroupInit) { static const std::string SMODEL1 = "<?xml version=\"1.0\" ?>" "<robot name=\"pr2\">" "<virtual_joint name=\"base_joint\" child_link=\"base_footprint\" " "parent_frame=\"base_footprint\" type=\"planar\"/>" "<group name=\"left_arm_base_tip\">" "<chain base_link=\"monkey_base\" tip_link=\"monkey_tip\"/>" "</group>" "<group name=\"left_arm_joints\">" "<joint name=\"l_monkey_pan_joint\"/>" "<joint name=\"l_monkey_fles_joint\"/>" "</group>" "</robot>"; boost::shared_ptr<srdf::Model> srdfModel(new srdf::Model()); srdfModel->initString(*urdf_model, SMODEL1); moveit::core::RobotModel robot_model1(urdf_model, srdfModel); const moveit::core::JointModelGroup* left_arm_base_tip_group = robot_model1.getJointModelGroup("left_arm_base_tip"); ASSERT_TRUE(left_arm_base_tip_group == NULL); const moveit::core::JointModelGroup* left_arm_joints_group = robot_model1.getJointModelGroup("left_arm_joints"); ASSERT_TRUE(left_arm_joints_group == NULL); static const std::string SMODEL2 = "<?xml version=\"1.0\" ?>" "<robot name=\"pr2\">" "<virtual_joint name=\"base_joint\" child_link=\"base_footprint\" " "parent_frame=\"base_footprint\" type=\"planar\"/>" "<group name=\"left_arm_base_tip\">" "<chain base_link=\"torso_lift_link\" tip_link=\"l_wrist_roll_link\"/>" "</group>" "<group name=\"left_arm_joints\">" "<joint name=\"l_shoulder_pan_joint\"/>" "<joint name=\"l_shoulder_lift_joint\"/>" "<joint name=\"l_upper_arm_roll_joint\"/>" "<joint name=\"l_elbow_flex_joint\"/>" "<joint name=\"l_forearm_roll_joint\"/>" "<joint name=\"l_wrist_flex_joint\"/>" "<joint name=\"l_wrist_roll_joint\"/>" "</group>" "</robot>"; srdfModel->initString(*urdf_model, SMODEL2); moveit::core::RobotModelPtr robot_model2(new moveit::core::RobotModel(urdf_model, srdfModel)); left_arm_base_tip_group = robot_model2->getJointModelGroup("left_arm_base_tip"); ASSERT_TRUE(left_arm_base_tip_group != NULL); left_arm_joints_group = robot_model2->getJointModelGroup("left_arm_joints"); ASSERT_TRUE(left_arm_joints_group != NULL); EXPECT_EQ(left_arm_base_tip_group->getJointModels().size(), 9); EXPECT_EQ(left_arm_joints_group->getJointModels().size(), 7); EXPECT_EQ(left_arm_joints_group->getVariableNames().size(), left_arm_joints_group->getVariableCount()); EXPECT_EQ(left_arm_joints_group->getVariableCount(), 7); EXPECT_EQ(robot_model2->getVariableNames().size(), robot_model2->getVariableCount()); bool found_shoulder_pan_link = false; bool found_wrist_roll_link = false; for (unsigned int i = 0; i < left_arm_base_tip_group->getLinkModels().size(); i++) { if (left_arm_base_tip_group->getLinkModels()[i]->getName() == "l_shoulder_pan_link") { EXPECT_TRUE(found_shoulder_pan_link == false); found_shoulder_pan_link = true; } if (left_arm_base_tip_group->getLinkModels()[i]->getName() == "l_wrist_roll_link") { EXPECT_TRUE(found_wrist_roll_link == false); found_wrist_roll_link = true; } EXPECT_TRUE(left_arm_base_tip_group->getLinkModels()[i]->getName() != "torso_lift_link"); } EXPECT_TRUE(found_shoulder_pan_link); EXPECT_TRUE(found_wrist_roll_link); moveit::core::RobotState ks(robot_model2); ks.setToDefaultValues(); std::map<std::string, double> jv; jv["base_joint/x"] = 0.433; jv["base_joint/theta"] = -0.5; ks.setVariablePositions(jv); moveit_msgs::RobotState robot_state; moveit::core::robotStateToRobotStateMsg(ks, robot_state); moveit::core::RobotState ks2(robot_model2); moveit::core::robotStateMsgToRobotState(robot_state, ks2); const double* v1 = ks.getVariablePositions(); const double* v2 = ks2.getVariablePositions(); for (std::size_t i = 0; i < ks.getVariableCount(); ++i) EXPECT_NEAR(v1[i], v2[i], 1e-5); } TEST_F(LoadPlanningModelsPr2, SubgroupInit) { moveit::core::RobotModel robot_model(urdf_model, srdf_model); const moveit::core::JointModelGroup* jmg = robot_model.getJointModelGroup("arms"); ASSERT_TRUE(jmg); EXPECT_EQ(jmg->getSubgroupNames().size(), 2); EXPECT_TRUE(jmg->isSubgroup("right_arm")); const moveit::core::JointModelGroup* jmg2 = robot_model.getJointModelGroup("whole_body"); EXPECT_EQ(jmg2->getSubgroupNames().size(), 5); EXPECT_TRUE(jmg2->isSubgroup("arms")); EXPECT_TRUE(jmg2->isSubgroup("right_arm")); } TEST_F(LoadPlanningModelsPr2, AssociatedFixedLinks) { moveit::core::RobotModelPtr model(new moveit::core::RobotModel(urdf_model, srdf_model)); EXPECT_TRUE(model->getLinkModel("r_gripper_palm_link")->getAssociatedFixedTransforms().size() > 1); } TEST_F(LoadPlanningModelsPr2, FullTest) { moveit::core::RobotModelPtr robot_model(new moveit::core::RobotModel(urdf_model, srdf_model)); moveit::core::RobotState ks(robot_model); ks.setToDefaultValues(); moveit::core::RobotState ks2(robot_model); ks2.setToDefaultValues(); std::vector<shapes::ShapeConstPtr> shapes; EigenSTL::vector_Affine3d poses; shapes::Shape* shape = new shapes::Box(.1, .1, .1); shapes.push_back(shapes::ShapeConstPtr(shape)); poses.push_back(Eigen::Affine3d::Identity()); std::set<std::string> touch_links; trajectory_msgs::JointTrajectory empty_state; moveit::core::AttachedBody* attached_body = new moveit::core::AttachedBody( robot_model->getLinkModel("r_gripper_palm_link"), "box", shapes, poses, touch_links, empty_state); ks.attachBody(attached_body); std::vector<const moveit::core::AttachedBody*> attached_bodies_1; ks.getAttachedBodies(attached_bodies_1); ASSERT_EQ(attached_bodies_1.size(), 1); std::vector<const moveit::core::AttachedBody*> attached_bodies_2; ks2 = ks; ks2.getAttachedBodies(attached_bodies_2); ASSERT_EQ(attached_bodies_2.size(), 1); ks.clearAttachedBody("box"); attached_bodies_1.clear(); ks.getAttachedBodies(attached_bodies_1); ASSERT_EQ(attached_bodies_1.size(), 0); ks2 = ks; attached_bodies_2.clear(); ks2.getAttachedBodies(attached_bodies_2); ASSERT_EQ(attached_bodies_2.size(), 0); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
`depends/Bucket` := proc(mr, r::(name=range), x, $) depends(rhs(r), x) or depends(mr, x minus {lhs(r)}) end proc: `depends/Index` := proc(n, o::name, e, mr, x, $) depends({n,e}, x) or depends(mr, x minus {o}) end proc: # note that v _can_ occur in m1. `depends/Let` := proc(m1, v::name, m2, x, $) depends(m1, x) or depends(m2, x minus {v}) end proc: `eval/Bucket` := proc(e::anyfunc(anything,name=range), eqs, $) local bvar, body; bvar, body := BindingTools:-generic_evalat(op([2,1],e), op(1,e), eqs); eval(op(0,e), eqs)(body, bvar = eval(op([2,2],e), eqs)) end proc: `eval/Index` := proc(e::anyfunc(anything,name,anything,anything), eqs, $) local o, mr; o, mr := BindingTools:-generic_evalat(op(2,e), op(4,e), eqs); eval(op(0,e), eqs)(eval(op(1,e), eqs), o, eval(op(3,e), eqs), mr) end proc: `eval/Let` := proc(e, eqs, $) local m1, v, m2; m1, v, m2 := op(e); eval(op(0,e), eqs)(eval(m1, eqs), BindingTools:-generic_evalat(v, m2, eqs)) end proc: Summary := module () option package; export RoundTrip, Summarize, SummarizeKB, bucket, summarize; global Bucket, Fanout, Index, Split, Nop, Add, Let, SumIE, ProductIE, BucketIE; uses Hakaru, KB; RoundTrip := proc(e) local result; interface(screenwidth=9999, prettyprint=0, warnlevel=0, showassumed=0,quiet=true); kernelopts(assertlevel=0); result := eval(ToInert(Summarize(_passed)), _Inert_ATTRIBUTE=NULL); lprint(result) end proc; Summarize := proc(e, {ctx :: list := []}, $) local ie; ie := table('[sum =SumIE , Sum =SumIE , product=ProductIE, Product=ProductIE, bucket =BucketIE , Bucket =BucketIE ]'); subsindets(SummarizeKB(e, foldr(assert, empty, op(ctx))), And(specfunc({indices(ie, 'nolist')}), anyfunc(anything, anything=range)), e -> subsop(0 = ie[op(0,e)], applyop(`+`, [2,2,2], e, 1))) end proc; SummarizeKB := proc(e, kb :: t_kb, $) local patterns, x, kb1, e1, rng, summary, mr, f; if not hasfun(e, '{Sum,sum}', 'piecewise') then e; elif e :: '{known_continuous, known_discrete, specfunc({Msum, Weight, Fanout, Split, Nop, Add, exp, log, GAMMA, Beta, idx, And, Or, Not}), `+`, `*`, `^`, `..`, boolean, indexed, list}' then map(procname, _passed); elif e :: 'Context(anything, anything)' then kb1 := assert(op(1,e), kb); applyop(procname, 2, e, kb1); elif e :: 'specfunc(piecewise)' then kb_piecewise(e, kb, ((lhs, kb) -> lhs), SummarizeKB); elif e :: 'lam(name, anything, anything)' then patterns := htype_patterns(op(2,e)); if patterns :: Branches(Branch(PVar(name),anything)) then # Eta-expand the function type x := op(1,e); x, kb1 := genType(x, op(2,e), kb); e1 := eval(op(3,e), op(1,e)=x); lam(x, op(2,e), SummarizeKB(e1, kb1)) else # Eta-expand the function type and the sum-of-product argument-type x := op(1,e); if depends([e,kb], x) then x := gensym(x) end if; e1 := eval(op(3,e), op(1,e)=x); lam(x, op(2,e), 'case'(x, map(proc(branch) local eSubst, pSubst, p1, binds, y, kb1, i, pSubst1; eSubst, pSubst := pattern_match([x,e], x, op(1,branch)); p1 := subs(pSubst, op(1,branch)); binds := [pattern_binds(p1)]; kb1 := kb; pSubst1 := table(); for i from 1 to nops(binds) do y, kb1 := genType(op(i,binds), op([2,i],branch), kb1); pSubst1[op(i,binds)] := y; end do; pSubst1 := op(op(pSubst1)); Branch(subs(pSubst1, p1), SummarizeKB(eval(eval(e1,eSubst),pSubst1), kb1)) end proc, patterns))) end if elif e :: 'ary(anything, name, anything)' then x, kb1 := genType(op(2,e), HInt(closed_bounds(0..op(1,e)-1)), kb); e1 := SummarizeKB(eval(op(3,e), op(2,e)=x), kb1); subsop(2=x, 3=e1, e); elif e :: 'And(specfunc({sum, Sum, product, Product}), anyfunc(anything, name=range))' then rng := op([2,2],e); x, kb1 := genType(op([2,1],e), HInt(closed_bounds(rng)), kb); rng := map(SummarizeKB, rng, kb); e1 := eval(op(1,e), op([2,1],e)=x); if op(0, e) in '{sum, Sum}' and has(e1, 'piecewise') then mr, f := summarize(e1, kb, x, summary); if hasfun(mr, '{Fanout, Index}') then mr := SummarizeKB(mr, kb1); return Let(Bucket(mr, x=rng), summary, NewSLO:-simplify_factor_assuming(f, kb)); end if; end if; e1 := SummarizeKB(e1, kb1); subsop(2=(x=rng), 1=e1, e); else error "SummarizeKB doesn't know how to handle %1", e; end if; end proc; bucket := proc(mr, r::(name=range), cond::list:=[], $) if mr :: 'Fanout(anything,anything)' then Pair(op(map(procname, _passed))) elif mr :: 'Split(anything,anything,anything)' then Pair(bucket(op(2,mr), r, [ op(1,mr) ,op(cond)]), bucket(op(3,mr), r, [Not(op(1,mr)),op(cond)])) elif mr :: 'Index(anything,name,anything,anything)' then ary(op(1,mr), op(2,mr), bucket(op(4,mr), r, [op(2,mr)=op(3,mr),op(cond)])); elif mr :: 'Nop()' then _Unit elif mr :: 'Add(anything)' then sum(piecewise_And(cond, op(1,mr), 0), r) else 'procname(_passed)' end if; end proc; summarize := proc(ee, kb :: t_kb, i :: {name,list(name),set(name)}, summary, $) local e, r, s, e1, mr1, f1, e2, mr2, f2, variables, var_outerness, outermost, thunk, consider, o, t, lo, hi, b, a; # Try to ensure termination e := simplify_assuming(ee, kb); if length(e) >= length(ee) then e := ee end if; # Nop rule if Testzero(e) then return Nop(), 0 end if; r := indets(e, '{relation, logical, specfunc({And,Or})}'); s, r := selectremove(depends, r, i); # Fanout rule r := sort(convert(r, 'list'), 'length'); while nops(r) > 0 do e1 := eval(e, r[-1]=true); if e = e1 then r := r[1..-2]; next end if; e2 := eval(e, r[-1]=false); if e = e2 then r := r[1..-2]; next end if; mr1, f1 := summarize(e1, kb, i, 'fst(summary)'); mr2, f2 := summarize(e2, kb, i, 'snd(summary)'); return Fanout(mr1, mr2), 'piecewise'(r[-1], f1, f2); end do; variables := kb_to_variables(kb); var_outerness := table(variables =~ [seq(1..nops(variables))]); outermost := -infinity; consider := proc(expr, th, $) local outerness; outerness := map((n -> var_outerness[n]), indets(expr, 'name')); outerness := min(select(type, outerness, 'integer')); if outermost < outerness then outermost := outerness; thunk := th; end if; end proc; if has(variables, i) then error "The loop to be summarized shadows the variable %1", i; end if; for r in s do e1 := eval(e, r=true); if e = e1 then next end if; e2 := eval(e, r=false); if e = e2 then next end if; # Index rule if r :: `=` and Testzero(e2) then for o in indets(r, 'name') minus convert(i, 'set') do if not (var_outerness[o] :: integer) then next end if; t := getType(kb, o); if not (t :: specfunc(HInt)) then next end if; lo := op(select(type, t, 'Bound(identical(`>=`), anything)')); if lo = NULL then next else lo := op(2,lo) end if; hi := op(select(type, t, 'Bound(identical(`<=`), anything)')); if hi = NULL then next else hi := op(2,hi) end if; if not ispoly(`-`(op(r)), 'linear', o, 'b', 'a') then next end if; b := Normalizer(-b/a); consider(b, ((e1, o, lo, hi, b) -> proc($) local mr, f; mr, f := summarize(e1, kb, i, 'idx'(summary, o-lo)); Index(hi-lo+1, o, b, mr), 'piecewise'(And(o::integer, lo<=o, o<=hi), f, 0); end proc)(e1, o, lo, hi, b)); end do; end if; # Split rule consider(r, ((e1, e2, r) -> proc($) local mr1, f1, mr2, f2; mr1, f1 := summarize(e1, kb, i, 'fst(summary)'); mr2, f2 := summarize(e2, kb, i, 'snd(summary)'); Split(r, mr1, mr2), f1 + f2; end proc)(e1, e2, r)); end do; if thunk :: procedure then return thunk(); else # Add rule return Add(e), summary; end if; end proc; end module; # Summary
#Series temporais e analises preditivas - Fernando Amaral library(ggplot2) library(forecast) library(seasonal) library(seasonalview) #sazonalidade e tendencia plot(co2) abline(reg=lm(co2~time(co2))) #decomposicao classica classicdecco2 = decompose(co2) autoplot(classicdecco2) #decomposicao classica autoplot(fdeaths) x = decompose(fdeaths) autoplot(x) #X-13ARIMA-SEATS x13ap = seas(AirPassengers) autoplot(x13ap) #mstl msap = mstl(AirPassengers) autoplot(msap) #vizao grafica view(x13ap) ggseasonplot(AirPassengers) ggseasonplot(AirPassengers, polar = T) ggmonthplot(AirPassengers)
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.norm_num import tactic.linarith import tactic.omega import control.lawful_fix import order.category.omega_complete_partial_order import data.nat.basic universes u_1 u_2 namespace part.examples open function has_fix omega_complete_partial_order /-! `easy` is a trivial, non-recursive example -/ def easy.intl (easy : ℕ → ℕ → part ℕ) : ℕ → ℕ → part ℕ | x y := pure x def easy := fix easy.intl -- automation coming soon theorem easy.cont : continuous' easy.intl := pi.omega_complete_partial_order.flip₂_continuous' easy.intl (λ x, pi.omega_complete_partial_order.flip₂_continuous' _ (λ x_1, const_continuous' (pure x))) -- automation coming soon theorem easy.equations.eqn_1 (x y : ℕ) : easy x y = pure x := by rw [easy, lawful_fix.fix_eq' easy.cont]; refl /-! division on natural numbers -/ def div.intl (div : ℕ → ℕ → part ℕ) : ℕ → ℕ → part ℕ | x y := if y ≤ x ∧ y > 0 then div (x - y) y else pure x def div : ℕ → ℕ → part ℕ := fix div.intl -- automation coming soon theorem div.cont : continuous' div.intl := pi.omega_complete_partial_order.flip₂_continuous' div.intl (λ (x : ℕ), pi.omega_complete_partial_order.flip₂_continuous' (λ (g : ℕ → ℕ → part ℕ), div.intl g x) (λ (x_1 : ℕ), (continuous_hom.ite_continuous' (λ (x_2 : ℕ → ℕ → part ℕ), x_2 (x - x_1) x_1) (λ (x_1 : ℕ → ℕ → part ℕ), pure x) (pi.omega_complete_partial_order.flip₁_continuous' (λ (v_1 : ℕ) (x_2 : ℕ → ℕ → part ℕ), x_2 (x - x_1) v_1) _ $ pi.omega_complete_partial_order.flip₁_continuous' (λ (v : ℕ) (g : ℕ → ℕ → part ℕ) (x : ℕ), g v x) _ id_continuous') (const_continuous' (pure x))))) -- automation coming soon theorem div.equations.eqn_1 (x y : ℕ) : div x y = if y ≤ x ∧ y > 0 then div (x - y) y else pure x := by conv_lhs { rw [div, lawful_fix.fix_eq' div.cont] }; refl inductive tree (α : Type*) | nil {} : tree | node (x : α) : tree → tree → tree open part.examples.tree /-! `map` on a `tree` using monadic notation -/ def tree_map.intl {α β : Type*} (f : α → β) (tree_map : tree α → part (tree β)) : tree α → part (tree β) | nil := pure nil | (node x t₀ t₁) := do tt₀ ← tree_map t₀, tt₁ ← tree_map t₁, pure $ node (f x) tt₀ tt₁ -- automation coming soon def tree_map {α : Type u_1} {β : Type u_2} (f : α → β) : tree α → part (tree β) := fix (tree_map.intl f) -- automation coming soon theorem tree_map.cont : ∀ {α : Type u_1} {β : Type u_2} (f : α → β), continuous' (tree_map.intl f) := λ {α : Type u_1} {β : Type u_2} (f : α → β), pi.omega_complete_partial_order.flip₂_continuous' (tree_map.intl f) (λ (x : tree α), tree.cases_on x (id (const_continuous' (pure nil))) (λ (x_x : α) (x_a x_a_1 : tree α), (continuous_hom.bind_continuous' (λ (x : tree α → part (tree β)), x x_a) (λ (x : tree α → part (tree β)) (tt₀ : tree β), x x_a_1 >>= λ (tt₁ : tree β), pure (node (f x_x) tt₀ tt₁)) (pi.omega_complete_partial_order.flip₁_continuous' (λ (v : tree α) (x : tree α → part (tree β)), x v) x_a id_continuous') (pi.omega_complete_partial_order.flip₂_continuous' (λ (x : tree α → part (tree β)) (tt₀ : tree β), x x_a_1 >>= λ (tt₁ : tree β), pure (node (f x_x) tt₀ tt₁)) (λ (x : tree β), continuous_hom.bind_continuous' (λ (x : tree α → part (tree β)), x x_a_1) (λ (x_1 : tree α → part (tree β)) (tt₁ : tree β), pure (node (f x_x) x tt₁)) (pi.omega_complete_partial_order.flip₁_continuous' (λ (v : tree α) (x : tree α → part (tree β)), x v) x_a_1 id_continuous') (pi.omega_complete_partial_order.flip₂_continuous' (λ (x_1 : tree α → part (tree β)) (tt₁ : tree β), pure (node (f x_x) x tt₁)) (λ (x_1 : tree β), const_continuous' (pure (node (f x_x) x x_1))))))))) -- automation coming soon theorem tree_map.equations.eqn_1 {α : Type u_1} {β : Type u_2} (f : α → β) : tree_map f nil = pure nil := by rw [tree_map,lawful_fix.fix_eq' (tree_map.cont f)]; refl -- automation coming soon theorem tree_map.equations.eqn_2 {α : Type u_1} {β : Type u_2} (f : α → β) (x : α) (t₀ t₁ : tree α) : tree_map f (node x t₀ t₁) = tree_map f t₀ >>= λ (tt₀ : tree β), tree_map f t₁ >>= λ (tt₁ : tree β), pure (node (f x) tt₀ tt₁) := by conv_lhs { rw [tree_map,lawful_fix.fix_eq' (tree_map.cont f)] }; refl /-! `map` on a `tree` using applicative notation -/ def tree_map'.intl {α β} (f : α → β) (tree_map : tree α → part (tree β)) : tree α → part (tree β) | nil := pure nil | (node x t₀ t₁) := node (f x) <$> tree_map t₀ <*> tree_map t₁ -- automation coming soon def tree_map' {α : Type u_1} {β : Type u_2} (f : α → β) : tree α → part (tree β) := fix (tree_map'.intl f) -- automation coming soon theorem tree_map'.cont : ∀ {α : Type u_1} {β : Type u_2} (f : α → β), continuous' (tree_map'.intl f) := λ {α : Type u_1} {β : Type u_2} (f : α → β), pi.omega_complete_partial_order.flip₂_continuous' (tree_map'.intl f) (λ (x : tree α), tree.cases_on x (id (const_continuous' (pure nil))) (λ (x_x : α) (x_a x_a_1 : tree α), (continuous_hom.seq_continuous' (λ (x : tree α → part (tree β)), node (f x_x) <$> x x_a) (λ (x : tree α → part (tree β)), x x_a_1) (continuous_hom.map_continuous' (node (f x_x)) (λ (x : tree α → part (tree β)), x x_a) (pi.omega_complete_partial_order.flip₁_continuous' (λ (v : tree α) (x : tree α → part (tree β)), x v) x_a id_continuous')) (pi.omega_complete_partial_order.flip₁_continuous' (λ (v : tree α) (x : tree α → part (tree β)), x v) x_a_1 id_continuous')))) -- automation coming soon theorem tree_map'.equations.eqn_1 {α : Type u_1} {β : Type u_2} (f : α → β) : tree_map' f nil = pure nil := by rw [tree_map',lawful_fix.fix_eq' (tree_map'.cont f)]; refl -- automation coming soon theorem tree_map'.equations.eqn_2 {α : Type u_1} {β : Type u_2} (f : α → β) (x : α) (t₀ t₁ : tree α) : tree_map' f (node x t₀ t₁) = node (f x) <$> tree_map' f t₀ <*> tree_map' f t₁ := by conv_lhs { rw [tree_map',lawful_fix.fix_eq' (tree_map'.cont f)] }; refl /-! f91 is a function whose proof of termination cannot rely on the structural ordering of its arguments and does not use the usual well-founded order on natural numbers. It is an interesting candidate to show that `fix` lets us disentangle the issue of termination from the definition of the function. -/ def f91.intl (f91 : ℕ → part ℕ) (n : ℕ) : part ℕ := if n > 100 then pure $ n - 10 else f91 (n + 11) >>= f91 -- automation coming soon def f91 : ℕ → part ℕ := fix f91.intl -- automation coming soon lemma f91.cont : continuous' f91.intl := pi.omega_complete_partial_order.flip₂_continuous' f91.intl (λ (x : ℕ), id (continuous_hom.ite_continuous' (λ (x_1 : ℕ → part ℕ), pure (x - 10)) (λ (x_1 : ℕ → part ℕ), x_1 (x + 11) >>= x_1) (const_continuous' (pure (x - 10))) (continuous_hom.bind_continuous' (λ (x_1 : ℕ → part ℕ), x_1 (x + 11)) (λ (x : ℕ → part ℕ), x) (pi.omega_complete_partial_order.flip₁_continuous' (λ (v : ℕ) (x : ℕ → part ℕ), x v) (x + 11) id_continuous') (pi.omega_complete_partial_order.flip₂_continuous' (λ (x : ℕ → part ℕ), x) (λ (x_1 : ℕ), pi.omega_complete_partial_order.flip₁_continuous' (λ (v : ℕ) (g : ℕ → part ℕ), g v) x_1 id_continuous'))))) . -- automation coming soon theorem f91.equations.eqn_1 (n : ℕ) : f91 n = ite (n > 100) (pure (n - 10)) (f91 (n + 11) >>= f91) := by conv_lhs { rw [f91, lawful_fix.fix_eq' f91.cont] }; refl lemma f91_spec (n : ℕ) : (∃ n', n < n' + 11 ∧ n' ∈ f91 n) := begin apply well_founded.induction (measure_wf $ λ n, 101 - n) n, clear n, dsimp [measure,inv_image], intros n ih, by_cases h' : n > 100, { rw [part.examples.f91.equations.eqn_1,if_pos h'], existsi n - 10, rw tsub_add_eq_add_tsub, norm_num [pure], apply le_of_lt, transitivity 100, norm_num, exact h' }, { rw [part.examples.f91.equations.eqn_1,if_neg h'], simp, rcases ih (n + 11) _ with ⟨n',hn₀,hn₁⟩, rcases ih (n') _ with ⟨n'',hn'₀,hn'₁⟩, refine ⟨n'',_,_,hn₁,hn'₁⟩, { clear ih hn₁ hn'₁, omega }, { clear ih hn₁, omega }, { clear ih, omega } }, end lemma f91_dom (n : ℕ) : (f91 n).dom := by rw part.dom_iff_mem; apply exists_imp_exists _ (f91_spec n); simp def f91' (n : ℕ) : ℕ := (f91 n).get (f91_dom n) run_cmd guard (f91' 109 = 99) lemma f91_spec' (n : ℕ) : f91' n = if n > 100 then n - 10 else 91 := begin suffices : (∃ n', n' ∈ f91 n ∧ n' = if n > 100 then n - 10 else 91), { dsimp [f91'], rw part.get_eq_of_mem, rcases this with ⟨n,_,_⟩, subst n, assumption }, apply well_founded.induction (measure_wf $ λ n, 101 - n) n, clear n, dsimp [measure,inv_image], intros n ih, by_cases h' : n > 100, { rw [part.examples.f91.equations.eqn_1,if_pos h',if_pos h'], simp [pure] }, { rw [part.examples.f91.equations.eqn_1,if_neg h',if_neg h'], simp, rcases ih (n + 11) _ with ⟨n',hn'₀,hn'₁⟩, split_ifs at hn'₁, { subst hn'₁, norm_num at hn'₀, refine ⟨_,hn'₀,_⟩, rcases ih (n+1) _ with ⟨n',hn'₀,hn'₁⟩, split_ifs at hn'₁, { subst n', convert hn'₀, clear hn'₀ hn'₀ ih, omega }, { subst n', exact hn'₀ }, { clear ih hn'₀, omega } }, { refine ⟨_,hn'₀,_⟩, subst n', rcases ih 91 _ with ⟨n',hn'₀,hn'₁⟩, rw if_neg at hn'₁, subst n', exact hn'₀, { clear ih hn'₀ hn'₀, omega, }, { clear ih hn'₀, omega, } }, { clear ih, omega } } end end part.examples
# reference: https://github.com/microsoft/LightGBM/blob/master/examples/python-guide/simple_example.py import lightgbm as lgb from sklearn.model_selection import GridSearchCV import pandas as pd import numpy as np from hyperopt import hp, Trials, fmin, tpe from sklearn.metrics import roc_auc_score, mean_squared_error from sklearn.model_selection import train_test_split from sklearn.feature_extraction import FeatureHasher import logging import time import warnings warnings.filterwarnings('ignore') class lgbm_demo: def __init__(self, objective, file_path): logging.basicConfig(level=logging.INFO, filename='info.log', filemode='w', format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s') self.objective = objective self.fixed_params = {'metric': 'l1', 'feature_fraction': 0.9, 'bagging_fraction': 0.8, 'bagging_freq': 5, 'verbose': 0} # train train_path = file_path + '/train_final.csv' train_df = pd.read_csv(train_path, header=0, delimiter=',') # train_df = train_df.drop('continuous_dti_joint', axis=1) for i in range(train_df.shape[0]): train_df.iloc[i, 1] = max(train_df.iloc[i, 0], train_df.iloc[i, 1]) train_df.iloc[i, 4] = max(train_df.iloc[i, 3], train_df.iloc[i, 4]) train_df = train_df.fillna(0) # add feature # ratio = installment / (annual_inc / 12) train_df['payment_ratio'] = train_df['continuous_installment'] * 12\ / train_df['continuous_annual_inc'] features = train_df.iloc[:, 21:70] train_df = train_df.drop(labels=['discrete_addr_state_' + str(i) + '_one_hot' for i in range(1, 50)], axis=1) features = np.array(features) recover_features = [] for feature in features: for i in range(len(feature)): if feature[i] == 1: recover_features.append(i) break recover_features = list(map(str, recover_features)) hashing = FeatureHasher(input_type='string', n_features=49) matrix = hashing.transform(recover_features) matrix = matrix.toarray() cols = ['addr_state_feature_' + str(i) for i in range(1, 50)] matrix = pd.DataFrame(matrix, columns=cols) train_df = pd.concat([train_df, matrix], axis=1) train_set, validate_set = train_test_split(train_df, test_size=0.2) # test test_path = file_path + '/test_final.csv' test_df = pd.read_csv(test_path, header=0, delimiter=',') # test_df = test_df.drop('continuous_dti_joint', axis=1) for i in range(test_df.shape[0]): test_df.iloc[i, 1] = max(test_df.iloc[i, 0], test_df.iloc[i, 1]) test_df.iloc[i, 4] = max(test_df.iloc[i, 3], test_df.iloc[i, 4]) test_df = test_df.fillna(0) test_df['payment_ratio'] = test_df['continuous_installment']\ / test_df['continuous_annual_inc'] * 12 features = test_df.iloc[:, 21:70] test_df = test_df.drop(labels=['discrete_addr_state_' + str(i) + '_one_hot' for i in range(1, 50)], axis=1) features = np.array(features) recover_features = [] for feature in features: for i in range(len(feature)): if feature[i] == 1: recover_features.append(i) break recover_features = list(map(str, recover_features)) hashing = FeatureHasher(input_type='string', n_features=49) matrix = hashing.transform(recover_features) matrix = matrix.toarray() cols = ['addr_state_feature_' + str(i) for i in range(1, 50)] matrix = pd.DataFrame(matrix, columns=cols) test_df = pd.concat([test_df, matrix], axis=1) # create train dataset target_col = 15 train_set = np.array(train_set) self.train_label = train_set[:, target_col] # This should be modified self.train_data = np.delete(train_set, target_col, axis=1) self.train_dataset = lgb.Dataset(self.train_data, self.train_label) # create validation dataset validate_set = np.array(validate_set) self.v_label = validate_set[:, target_col] # This should be modified self.v_data = np.delete(validate_set, target_col, axis=1) self.v_dataset = lgb.Dataset(self.v_data, self.v_label, reference=self.train_dataset) # create test dataset self.test_label = test_df.loc[:, 'loan_status'] # This should be modified self.test_data = test_df.drop('loan_status', axis=1) def build(self): print("Starting building......") def fn(params): gbm = lgb.LGBMClassifier(boosting_type=params['boosting_type'], objective=self.objective, learning_rate=params['learning_rate'], num_leaves=params['num_leaves'], max_depth=params['max_depth'], n_estimators=params['n_estimators']) model = self.fit(gbm) pred = model.predict(self.v_data, num_iteration=model.best_iteration_).astype(int) return 1 - roc_auc_score(self.v_label, pred) # # initial print('Starting initialization......') learning_rate = 0.05 num_leaves = 31 max_depth = 5 n_estimators = 20 gbm = lgb.LGBMClassifier(boosting_type='gbdt', objective=self.objective, learning_rate=learning_rate, num_leaves=num_leaves, max_depth=max_depth, n_estimators=n_estimators) # first print('Starting searching for best max depth & leave number......') candidate = {'max_depth': range(3, 10, 1), 'num_leaves': range(10, 100, 5)} gsearch = GridSearchCV(gbm, param_grid=candidate, scoring='f1', cv=5, n_jobs=-1) gsearch.fit(self.train_data, self.train_label) max_depth = gsearch.best_params_['max_depth'] num_leaves = min(2 ** max_depth - 1, gsearch.best_params_['num_leaves']) logging.info('Best max depth is ' + str(max_depth)) # sophisticated modification # space_dtree = { # 'boosting_type': 'gbdt', # 'objective': self.objective, # 'learning_rate': learning_rate, # 'max_depth': max_depth, # 'num_leaves': hp.choice('num_leaves', # range(max(num_leaves - 10, max_depth), # min(num_leaves + 10, 2 ** max_depth - 1), 1)), # 'n_estimators': n_estimators # } # best1 = fmin(fn=fn, space=space_dtree, algo=tpe.suggest, max_evals=100, trials=Trials(), verbose=True) # num_leaves = best1['num_leaves'] logging.info('Best num of leaves ' + str(num_leaves)) # update model gbm = lgb.LGBMClassifier(boosting_type='gbdt', objective=self.objective, learning_rate=learning_rate, num_leaves=num_leaves, max_depth=max_depth, n_estimators=n_estimators) # second print('Starting searching for best number of estimators......') candidate = {'n_estimators': range(10, 120, 10)} gsearch = GridSearchCV(gbm, param_grid=candidate, scoring='f1', cv=5, n_jobs=-1) gsearch.fit(self.train_data, self.train_label) n_estimators = gsearch.best_params_['n_estimators'] logging.info('Best num of estimator ' + str(n_estimators)) # update model gbm = lgb.LGBMClassifier(boosting_type='gbdt', objective=self.objective, learning_rate=learning_rate, num_leaves=num_leaves, max_depth=max_depth, n_estimators=n_estimators) # third print('Starting searching for best learning rate......') step_for_learning_rate = 2 while step_for_learning_rate > 0.05: candidate = {'learning_rate': [learning_rate * (2 ** i) for i in range(-2, 3, 1)]} gsearch = GridSearchCV(gbm, param_grid=candidate, scoring='f1', cv=5, n_jobs=-1) gsearch.fit(self.train_data, self.train_label) step_for_learning_rate = step_for_learning_rate / 2 learning_rate = gsearch.best_params_['learning_rate'] logging.info('Best learning rate ' + str(learning_rate)) gbm = lgb.LGBMClassifier(boosting_type='gbdt', objective=self.objective, learning_rate=learning_rate, num_leaves=num_leaves, max_depth=max_depth, n_estimators=n_estimators) print('Building completed!') return gbm def fit(self, gbm): print('Starting training...') # train gbm.fit(self.train_data, self.train_label, eval_set=[(self.v_data, self.v_label)], eval_metric='l1', early_stopping_rounds=5 ) return gbm def predict(self, gbm): print('Starting predicting...') # predict pred = gbm.predict(self.test_data, num_iteration=gbm.best_iteration_).astype(int) print('Predicting completed!') return mean_squared_error(self.test_label, pred) if __name__ == '__main__': start = time.time() file_path = "./final" lgb_ = lgbm_demo('binary', file_path) gbm = lgb_.build() lgb_.fit(gbm) logging.info('Mean squared error is ' + str(lgb_.predict(gbm))) end = time.time() logging.info('Running time is ' + str(end - start) + ' seconds.') # gbm = lgb.LGBMClassifier(objective=lgb_.objective, num_leaves=31, # learning_rate=0.05, n_estimators=20) # gbm.fit(lgb_.train_data, lgb_.train_label, # eval_set=[(lgb_.v_data, lgb_.v_label)], # eval_metric='l1', early_stopping_rounds=5) # y_pred = gbm.predict(lgb_.test_data, num_iteration=gbm.best_iteration_) # print(mean_squared_error(lgb_.test_label, y_pred))
(** Standard definitions of a simple typed lambda calculus with booleans **) Require Import Utils Context. (** syntax definition **) Inductive stlc_ty : Type := | stlc_bool : stlc_ty | stlc_arrow : stlc_ty -> stlc_ty -> stlc_ty. Inductive stlc_term : Type := | stlc_true : stlc_term | stlc_false : stlc_term | stlc_var : id -> stlc_term | stlc_app : stlc_term -> stlc_term -> stlc_term | stlc_abs : id -> stlc_ty -> stlc_term -> stlc_term. (** Semantics **) Fixpoint subst (x : id) (t : stlc_term) (t' : stlc_term) {struct t'} : stlc_term := match t' with | stlc_var i => if beq_id x i then t else t' | stlc_app l r => stlc_app (subst x t l) (subst x t r) | stlc_abs i T t1 => stlc_abs i T (if beq_id x i then t1 else (subst x t t1)) | stlc_true => stlc_true | stlc_false => stlc_false end. Inductive stlc_bvalue : stlc_term -> Prop := | sv_true : stlc_bvalue stlc_true | sv_false : stlc_bvalue stlc_false. Inductive stlc_absvalue : stlc_term -> Prop := | sv_abs : forall x T t12, stlc_absvalue (stlc_abs x T t12). Definition stlc_value (t : stlc_term) : Prop := stlc_bvalue t \/ stlc_absvalue t. Hint Constructors stlc_bvalue stlc_absvalue. Hint Unfold stlc_value. Reserved Notation "t '==>s' t'" (at level 40). Inductive stlc_step : stlc_term -> stlc_term -> Prop := | se_appabs : forall x T t12 v2, stlc_value v2 -> (stlc_app (stlc_abs x T t12) v2) ==>s subst x v2 t12 | se_app1 : forall t1 t1' t2, t1 ==>s t1' -> stlc_app t1 t2 ==>s stlc_app t1' t2 | se_app2 : forall v1 t2 t2', stlc_value v1 -> t2 ==>s t2' -> stlc_app v1 t2 ==>s stlc_app v1 t2' where "t '==>s' t'" := (stlc_step t t'). Hint Constructors stlc_step. Definition stlc_multi_step := refl_step_closure stlc_step. Notation "t '==>s*' t'" := (stlc_multi_step t t') (at level 40). (** typing **) Definition stlc_context := finite_map stlc_ty. Inductive stlc_has_type : stlc_context -> stlc_term -> stlc_ty -> Prop := | ST_Var : forall Gamma x T, lookup x Gamma = Some T -> stlc_has_type Gamma (stlc_var x) T | ST_Abs : forall Gamma x T11 T12 t12, stlc_has_type (extend x T11 Gamma) t12 T12 -> stlc_has_type Gamma (stlc_abs x T11 t12) (stlc_arrow T11 T12) | ST_App : forall T11 T12 Gamma t1 t2, stlc_has_type Gamma t1 (stlc_arrow T11 T12) -> stlc_has_type Gamma t2 T11 -> stlc_has_type Gamma (stlc_app t1 t2) T12 | ST_True : forall Gamma, stlc_has_type Gamma stlc_true stlc_bool | ST_False : forall Gamma, stlc_has_type Gamma stlc_false stlc_bool. Hint Constructors stlc_has_type.
# Problem set 1 ##Strassen Algorithm Let $C = AB$, where $A$ and $B$ are squared matrices of the same size. Direct computation of $C$ requires $\mathcal{O}(n^3)$ arithmetic operations. Fortunately, this complexity can be reduced even for arbitrary matrices $A$ and $B$. The following approach which has $\mathcal{O}(n^{\log_2 7})$ is called Strassen algorithm. Its idea is based on the fact that elements of $2\times 2$ matrix $$ \begin{bmatrix} c_{11} & c_{12} \\ c_{21} & c_{22} \end{bmatrix} = \begin{bmatrix} a_{11} & a_{12} \\ a_{21} & a_{22} \end{bmatrix} \begin{bmatrix} b_{11} & b_{12} \\ b_{21} & b_{22} \end{bmatrix} $$ can be computed using only 7 multiplications: \begin{equation}\begin{split} c_{11} &= f_1 + f_4 - f_5 + f_7, \\ c_{12} &= f_3 + f_5, \\ c_{21} &= f_2 + f_4, \\ c_{22} &= f_1 - f_2 + f_3 + f_6, \end{split}\end{equation} where \begin{equation}\begin{split} f_1 &= (a_{11} + a_{22}) (b_{11} + b_{22}),\\ f_2 &= (a_{21} + a_{22}) b_{11},\\ f_3 &= a_{11} (b_{12} - b_{22}),\\ f_4 &= a_{22} (b_{21} - b_{11}),\\ f_5 &= (a_{11} + a_{12}) b_{22},\\ f_6 &= (a_{21} - a_{11}) (b_{11} + b_{12}),\\ f_7 &= (a_{12} - a_{22}) (b_{21} + b_{22}). \end{split}\end{equation} Formulas above hold for the case when $a_{ij}, b_{ij}, c_{ij}$ ($i$ and $j=1,2$) are blocks. Therefore, spliting matrices $A$ and $B$ of abitrary sizes into 4 blocks and applying described procedure recursively for blocks one will get $\mathcal{O}(n^{\log_2 7})$ complexity. **Tasks** - (4 pts) Prove that Strassen alogorithm has $\mathcal{O}(n^{\log_2 7})$ complexity - (4 pts) Implement Strassen algorithm in Python. **Note**: for simplicity consider that $n$ is a power of 2 - (3 pts) Compare the result with direct matrix-by-matrix multiplication and $\verb|numpy.dot|$ procedure by ploting timings as a function of $n$. **Note**: use logarithmic scale ``` ``` ##Fast Fourier Transform Let $y = Ax$ (matvec operation), where $A \in \mathbb{C}^{m\times n}$ and $x \in \mathbb{C}^{n\times 1}$. Direct computation of $y$ requires $\mathcal{O}(n^2)$. Since $A$ contains $n^2$ elements, this complexity can not be reduced for an arbitrary matrix $A$. There are certain classes of matrices for which matvec requires less operations. For instance, sparse, Toeplitz, lowrank, etc. Another important example of structured matrix which arises in a huge amount of applications (signal and image processing, fast PDE solvers) is Fourier matrix $$ F_n = \{ \omega^{kl} \}_{k,l=0}^{n-1}, \quad \text{where} \quad \omega = e^{-\frac{2\pi i}{n}}. $$ Matvec operation with Fourier matrix is called discrete Fourier transform (DFT) and has $\mathcal{O}(n \log n)$ complexity. The simplest way to get this complexity is to spilt odd and even rows in Fourier matrix: \begin{equation} P_n F_n = \begin{bmatrix} F_{n/2} & F_{n/2} \\ F_{n/2} W_{n/2} & -F_{n/2} W_{n/2} \end{bmatrix}, \quad (1) \end{equation} where $P_n$ is a permutaion matrix which permutes odd and even rows, and $W_{n/2}=\text{diag}(1,\omega,\omega^2,\dots,\omega^{n/2-1})$. Thus, multiplication by $F_n$ is reduced to several multiplications by $F_{n/2}$ and linear operations such as multiplication by the diagonal matrix $W_{n/2}$. Continuing this procedure recursively for $F_{n/2}$ we will get $\mathcal{O}(n \log n)$ operations. **Tasks** - (4 pts) Prove expression (1) - (4 pts) Implement the described fft algorithm in Python. **Note**: for simplicity consider that $n$ is a power of 2 - (3 pts) Compare the result with $\verb|numpy.dot|$ and $\verb|numpy.fft.fft|$ procedures by ploting timings as a function of $n$. **Note**: use logarithmic scale ``` ```
[STATEMENT] lemma eval_evals_exec_xcpt: "(G \<turnstile> xs -ex\<succ>val-> xs' \<longrightarrow> gx xs' = None \<longrightarrow> gx xs = None) \<and> (G \<turnstile> xs -exs[\<succ>]vals-> xs' \<longrightarrow> gx xs' = None \<longrightarrow> gx xs = None) \<and> (G \<turnstile> xs -st-> xs' \<longrightarrow> gx xs' = None \<longrightarrow> gx xs = None)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (G \<turnstile> xs -ex\<succ>val-> xs' \<longrightarrow> gx xs' = None \<longrightarrow> gx xs = None) \<and> (G \<turnstile> xs -exs[\<succ>]vals-> xs' \<longrightarrow> gx xs' = None \<longrightarrow> gx xs = None) \<and> (G \<turnstile> xs -st-> xs' \<longrightarrow> gx xs' = None \<longrightarrow> gx xs = None) [PROOF STEP] by (induct rule: eval_evals_exec.induct) auto
module IID-Proof-Test where open import LF open import Identity open import IID open import IIDr open import DefinitionalEquality open import IID-Proof-Setup η : {I : Set}(γ : OPg I)(U : I -> Set) -> Args γ U -> Args γ U η (ι i) U _ = ★ η (σ A γ) U a = < a₀ | η (γ a₀) U a₁ > where a₀ = π₀ a a₁ = π₁ a η (δ A i γ) U a = < a₀ | η γ U a₁ > where a₀ = π₀ a a₁ = π₁ a r←→gArgs-equal : {I : Set}(γ : OPg I)(U : I -> Set) (i : I)(a : Args (ε γ i) U) -> _==_ {I × \i -> Args (ε γ i) U} < index γ U (r→gArgs γ U i a) | g→rArgs γ U (r→gArgs γ U i a) > < i | a > r←→gArgs-equal {I} (ι i) U j < p | ★ > = elim== i (\k q -> _==_ {I × \k -> Args (ε (ι i) k) U} < i | < refl | ★ > > < k | < q | ★ > > ) refl j p r←→gArgs-equal {I} (σ A γ) U j < a | b > = cong f ih where ih = r←→gArgs-equal (γ a) U j b f : (I × \i -> Args (ε (γ a) i) U) -> (I × \i -> Args (ε (σ A γ) i) U) f < k | q > = < k | < a | q > > r←→gArgs-equal {I} (δ H i γ) U j < g | b > = cong f ih where ih = r←→gArgs-equal γ U j b f : (I × \k -> Args (ε γ k) U) -> (I × \k -> Args (ε (δ H i γ) k) U) f < k | q > = < k | < g | q > > {- r←→gArgs-subst-identity' : {I : Set}(γ : OPg I) -> (\(U : I -> Set)(C : (i : I) -> rArgs (ε γ) U i -> Set) (a : Args γ U)(h : C (index γ U (r→gArgs γ U (index γ U (η γ U a)) (g→rArgs γ U (η γ U a)))) (g→rArgs γ U (r→gArgs γ U (index γ U (η γ U a)) (g→rArgs γ U (η γ U a)))) ) -> r←→gArgs-subst γ U C (index γ U (η γ U a)) (g→rArgs γ U (η γ U a)) h ) ==¹ (\(U : I -> Set)(C : (i : I) -> rArgs (ε γ) U i -> Set) (a : Args γ U)(h : C (index γ U (r→gArgs γ U (index γ U (η γ U a)) (g→rArgs γ U (η γ U a)))) (g→rArgs γ U (r→gArgs γ U (index γ U (η γ U a)) (g→rArgs γ U (η γ U a)))) ) -> h ) r←→gArgs-subst-identity' (ι i) = refl¹ r←→gArgs-subst-identity' (σ A γ) = ? r←→gArgs-subst-identity' (δ A i γ) = subst¹ (\ ∙ -> f ∙ ==¹ f (\U C a h -> h)) (r←→gArgs-subst-identity' γ) ? where ih = r←→gArgs-subst-identity' γ f = \g U C a h -> g U (\i c -> C i < π₀ a | c >) (π₁ a) h -}
DDU-GKY is mindful that it must engage the support of multiple partners to ensure success and maximize on the investment made in time and resources. In order to energize and build mass support as well as create awareness amongst the rural youth, The DDU-GKY projects are market linked and implemented in PPP mode. The involvement and partnership between civil society organizations, Educational institutions, apex skill partners and regulating organizations, the Government and Private organizations, ensures that DDU-GKY can leverage on the strengths of all and achieve transformative change. Curriculum framing and assessment support is through NCVT (National Council on Vocational Training) or SSCs (Sector Skills Councils). Industry partnerships allow access to new technology and on the job training. There are dedicated training hours for soft skills, spoken English and basic computers, in residential as well as non-residential well equipped campuses, with adequate technology as per industry standards. Our team makes unrelenting efforts to make sure that we can achieve a minimum placement of 70% of the project target of all trainees, through the support of our training partners and employer engagement. With a minimum recommended monthly salary of INR 6,000/- (varying based on training acquired). Industry interactions have emphasised the need for training in soft skills, team working etc., as more important than domain skills, which they learn on the job. To ensure that candidates can perform in their work areas as well as assimilate into the organization and society, DDU-GKY has mandated a minimum of 160 hours of training in soft skills, function English and computer literacy. Additionally, a finishing module called Work Readiness training is suggested to ensure that trained candidates hit the ground running wherever they join. A retention strategy is just as important to us and we have put in place mechanisms to track performance post placement, salary top-ups to candidates through DBT, incentives to training partners for achievement of outcomes in retention & progression and a framework for the establishment and operations of a migration support centre. ​Over 180 million or 69% of the country’s youth population between the ages of 18 and 34 years, live in its rural areas. Of these, the bottom of the pyramid youth from poor families with no or marginal employment number about 55 million. Vision: "Transform rural poor youth into an economically independent and globally relevant workforceType your paragraph here." In reference to the Minutes of the meeting of Pre-bids query for TSA. The Tentative dates for RFP bids (Download). Advertisement for TSA under DDU-GKY.
State Before: α : Type u_2 β : Type u_1 γ : Type ?u.11661 δ : Type ?u.11664 a : α s t : Multiset α f g : α → Multiset β ⊢ (bind s fun x => 0) = 0 State After: no goals Tactic: simp [bind, join, nsmul_zero]
#ifndef basis_dcab07d2_8e6a_4150_b6fb_1eb09f015f76_h #define basis_dcab07d2_8e6a_4150_b6fb_1eb09f015f76_h #include <gslib\error.h> //#include <gslib\string.h> #include <gslib\std.h> #include <rathen\config.h> #include <rathen\buildin.h> __rathen_begin__ class __gs_novtable type abstract { public: virtual ~type() {} virtual const gchar* get_name() const = 0; virtual int get_size() const = 0; virtual type* get_oprret(const oprinfo& opr) = 0; /* * Commutative attribute, if an operator was commutative, then a series of transformation could be done * in the expression optimization, for example, * it would always prefer to put the variables to the left side of the operator, and the constants to the * right side, so that we could generate the code try to put the constants within the instructions. */ virtual bool is_comutative(const oprinfo& opr) const { if (opr.opr == _t("=")) return false; return true; } /* Complex attribute, a complex type always has a construction/destruction operation. */ virtual bool is_complex() const { return false; } }; class __gs_novtable com_type abstract: public type { public: virtual bool is_complex() const { return true; } }; class type_manager { public: typedef std::pair<string, type*> type_pair; typedef unordered_map<string, type*> type_map; typedef type_map::iterator iterator; typedef type_map::const_iterator const_iterator; public: static type_manager* get_singleton_ptr() { static type_manager inst; return &inst; } ~type_manager() { std::for_each(_tpmap.begin(), _tpmap.end(), [](const type_pair& tp) { delete tp.second; }); _tpmap.clear(); } type* find_type(const gchar* name) { return find_type(string(name)); } type* find_type(const gchar* name, int len) { return find_type(string(name, len)); } type* find_type(const string& name) { auto i = _tpmap.find(name); return i == _tpmap.end() ? 0 : i->second; } private: type_map _tpmap; public: template<class _cst> bool regtype() { type* t = gs_new(_cst); if(!_reginner(t)) { gs_del(type, t); return false; } return true; } private: type_manager(); bool _reginner(type* t) { assert(t); if(find_type(t->get_name())) return false; _tpmap.insert(std::make_pair(string(t->get_name()), t)); return true; } }; #define _type_manager type_manager::get_singleton_ptr() class int_type: public type { public: virtual const gchar* get_name() const { return _t("int"); } virtual int get_size() const { return 4; } virtual type* get_oprret(const oprinfo& opr) { return this; } // TODO }; class bool_type: public type { public: virtual const gchar* get_name() const { return _t("bool"); } virtual int get_size() const { return 4; } virtual type* get_oprret(const oprinfo& opr) { return this; } // TODO }; class void_type: public type { public: virtual const gchar* get_name() const { return _t("void"); } virtual int get_size() const { return 0; } virtual type* get_oprret(const oprinfo& opr) { return 0; } }; class string_type: public com_type { public: virtual const gchar* get_name() const { return _t("string"); } virtual int get_size() const { return (int)sizeof(gs::string); } virtual type* get_oprret(const oprinfo& opr) { return this; } // TODO }; class __gs_novtable object abstract { public: enum { tag_data, tag_const, tag_block, tag_node, tag_scope, //tag_ //... }; protected: string _name; public: object() {} virtual ~object() {} virtual void set_name(const gchar* name) { _name = name; } virtual uint get_tag() const = 0; virtual bool is_holder() const = 0; virtual const string& get_name() const { return _name; } }; struct unikey { public: typedef gchar* vckey; typedef const gchar* cckey; protected: cckey _key; public: unikey(): _key(0) {} unikey(const gchar* k): _key(k) {} unikey(const string& k): _key(k.c_str()) {} unikey(const object* obj): _key(obj->get_name().c_str()) {} const gchar* get_key() const { return _key; } }; struct indexing { public: struct hash { size_t operator()(const unikey& k) const { return string_hash(k.get_key()); } }; struct equal { bool operator()(const unikey& k1, const unikey& k2) const { return string_hash(k1.get_key()) == string_hash(k2.get_key()); } }; typedef unordered_map<unikey, object*, hash, equal> unimap; typedef unimap::iterator iterator; typedef unimap::const_iterator const_iterator; protected: unimap _pairs; public: indexing() {} ~indexing() {} bool add_value(object* ptr) { assert(ptr); if(_pairs.insert(std::make_pair(unikey(ptr), ptr)).second) { set_error(_t("udt insert dp failed, maybe an error in name mangling.")); return false; } return true; } object* find_value(const gchar* name) { assert(name); iterator i = _pairs.find(unikey(name)); return i == _pairs.end() ? 0 :i->second; } const object* find_value(const gchar* name) const { assert(name); const_iterator i = _pairs.find(unikey(name)); return i == _pairs.end() ? 0 : i->second; } }; // class __gnvt pass_object: // virtual public object // { // public: // virtual bool is_holder() const { return false; } // }; // // class __gnvt hold_object: // virtual public object // { // public: // virtual bool is_holder() const { return true; } // virtual void add_indexing(object* obj) { _indexing.add_value(obj); } // virtual indexing& get_indexing() { return _indexing; } // // protected: // indexing _indexing; // // public: // object* find_object(const gchar* name) { return _indexing.find_value(name); } // const object* find_object(const gchar* name) const { return _indexing.find_value(name); } // }; // class block: // public object // { // protected: // indexing _indexing; // // public: // virtual void add_indexing(object* obj) { _indexing.add_value(obj); } // virtual indexing& get_indexing() { return _indexing; } // // public: // object* find_object(const gchar* name) { return _indexing.find_value(name); } // const object* find_object(const gchar* name) const { return _indexing.find_value(name); } // }; // // class data: // public object // { // protected: // type* _type; // // public: // virtual tag get_tag() const { return tag_data; } // virtual void set_type(type* t) { _type = t; } // virtual type* get_type() const { return _type; } // }; // // class reference: // public object // { // protected: // string _origin; // // public: // virtual tag get_tag() const { return tag_const; } // virtual void set_origin(const gchar* str, int len) { _origin.assign(str, len); } // virtual const gchar* get_origin() const { return _origin.c_str(); } // // public: // void set_origin(const gchar* str) { set_origin(str, strtool::length(str)); } // }; __rathen_end__ #endif
[STATEMENT] lemma rt_strictly_fresher_eqI [intro]: assumes "i\<in>kD(rt1)" and "i\<in>kD(rt2)" and "nsqn rt1 i = nsqn rt2 i" and "\<pi>\<^sub>5(the (rt2 i)) < \<pi>\<^sub>5(the (rt1 i))" shows "rt1 \<sqsubset>\<^bsub>i\<^esub> rt2" [PROOF STATE] proof (prove) goal (1 subgoal): 1. rt1 \<sqsubset>\<^bsub>i\<^esub> rt2 [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: i \<in> kD rt1 i \<in> kD rt2 nsqn rt1 i = nsqn rt2 i \<pi>\<^sub>5 (the (rt2 i)) < \<pi>\<^sub>5 (the (rt1 i)) goal (1 subgoal): 1. rt1 \<sqsubset>\<^bsub>i\<^esub> rt2 [PROOF STEP] unfolding rt_strictly_fresher_def' [PROOF STATE] proof (prove) using this: i \<in> kD rt1 i \<in> kD rt2 nsqn rt1 i = nsqn rt2 i \<pi>\<^sub>5 (the (rt2 i)) < \<pi>\<^sub>5 (the (rt1 i)) goal (1 subgoal): 1. nsqn\<^sub>r (the (rt1 i)) < nsqn\<^sub>r (the (rt2 i)) \<or> nsqn\<^sub>r (the (rt1 i)) = nsqn\<^sub>r (the (rt2 i)) \<and> \<pi>\<^sub>5 (the (rt2 i)) < \<pi>\<^sub>5 (the (rt1 i)) [PROOF STEP] by (auto simp add: kD_nsqn)
{-# OPTIONS --universe-polymorphism #-} module Issue293a where open import Agda.Primitive using (Level; _⊔_) renaming (lzero to zero; lsuc to suc) ------------------------------------------------------------------------ record RawMonoid c ℓ : Set (suc (c ⊔ ℓ)) where infixl 7 _∙_ infix 4 _≈_ field Carrier : Set c _≈_ : Carrier → Carrier → Set ℓ _∙_ : Carrier → Carrier → Carrier ε : Carrier module M (rm : RawMonoid zero zero) where open RawMonoid rm thm : ∀ x → x ∙ ε ≈ x thm = {!!} -- Previous agda2-goal-and-context: -- rm : RawMonoid zero zero -- ------------------------ -- Goal: (x : RawMonoid.Carrier rm) → -- RawMonoid._≈_ rm (RawMonoid._∙_ rm x (RawMonoid.ε rm)) x -- Current agda2-goal-and-context: -- rm : RawMonoid zero zero -- ------------------------ -- Goal: (x : Carrier) → x ∙ ε ≈ x ------------------------------------------------------------------------ record RawMonoid′ : Set₁ where infixl 7 _∙_ infix 4 _≈_ field Carrier : Set _≈_ : Carrier → Carrier → Set _∙_ : Carrier → Carrier → Carrier ε : Carrier module M′ (rm : RawMonoid′) where open RawMonoid′ rm thm′ : ∀ x → x ∙ ε ≈ x thm′ = {!!} -- Previous and current agda2-goal-and-context: -- rm : RawMonoid′ -- --------------- -- Goal: (x : Carrier) → x ∙ ε ≈ x ------------------------------------------------------------------------ -- UP isn't relevant. record RawMonoid″ (Carrier : Set) : Set₁ where infixl 7 _∙_ infix 4 _≈_ field _≈_ : Carrier → Carrier → Set _∙_ : Carrier → Carrier → Carrier ε : Carrier data Bool : Set where true false : Bool data List (A : Set) : Set where [] : List A _∷_ : (x : A)(xs : List A) → List A module M″ (rm : RawMonoid″ (List Bool)) where open RawMonoid″ rm thm″ : ∀ x → x ∙ ε ≈ x thm″ = {!!} -- Previous agda2-goal-and-context: -- rm : RawMonoid″ (List Bool) -- --------------------------- -- Goal: (x : List Bool) → -- RawMonoid″._≈_ rm (RawMonoid″._∙_ rm x (RawMonoid″.ε rm)) x -- Current agda2-goal-and-context: -- rm : RawMonoid″ (List Bool) -- --------------------------- -- Goal: (x : List Bool) → x ∙ ε ≈ x
corollary\<^marker>\<open>tag unimportant\<close> Jordan_disconnected: fixes c :: "real \<Rightarrow> complex" assumes "simple_path c" "pathfinish c = pathstart c" shows "\<not> connected(- path_image c)"
(* Title: HOL/Auth/n_germanSymIndex_lemma_inv__37_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_germanSymIndex Protocol Case Study*} theory n_germanSymIndex_lemma_inv__37_on_rules imports n_germanSymIndex_lemma_on_inv__37 begin section{*All lemmas on causal relation between inv__37*} lemma lemma_inv__37_on_rules: assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__37 p__Inv2)" shows "invHoldForRule s f r (invariants N)" proof - have c1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)\<or> (\<exists> i. i\<le>N\<and>r=n_SendReqS i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" apply (cut_tac b1, auto) done moreover { assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_StoreVsinv__37) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendReqSVsinv__37) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendReqE__part__0Vsinv__37) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendReqE__part__1Vsinv__37) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqSVsinv__37) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqEVsinv__37) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInv__part__0Vsinv__37) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInv__part__1Vsinv__37) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInvAckVsinv__37) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__37) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendGntSVsinv__37) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendGntEVsinv__37) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvGntSVsinv__37) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvGntEVsinv__37) done } ultimately show "invHoldForRule s f r (invariants N)" by satx qed end
import tactic /-! # Tactic cheat sheet. -- natnumgame tactics apply, exact (and assumption) split use (use `use` to make progress with `nonempty X`) -/ /-! ## 1) Extracting information from hypotheses -/ /-! ### 1a) cases and rcases Many objects in Lean are pairs of data. For example, a proof of `P ∧ Q` is stored as a pair consisting of a proof of `P` and a proof of `Q`. The hypothesis `∃ n : ℕ, f n = 37` is stored internally as a pair, namely a natural `n` and a proof that `f n = 37`. Note that "hypothesis" and "proof" mean the same thing. If `h : X` is something which is stored as a pair in Lean, then `cases h with a b` will destroy `h` and replace it with the two pieces of data which made up `h`, calling them `a` and `b`. -/ example (h : ∃ n : ℕ, n ^ 2 = 2) : false := begin -- h: ∃ (n : ℕ), n ^ 2 = 2 cases h with n hn, -- n: ℕ -- hn: n ^ 2 = 2 sorry end example (P Q : Prop) (h : P ∧ Q) : P := begin -- h: P ∧ Q cases h with hP hQ, -- hP: P -- hQ: Q exact hP, end -- Some things are more than two pieces of data! You can do much more -- elaborate deconstructions with the `rcases` command. example (R : ℕ → ℕ → Prop) (hR : equivalence R) : symmetric R := begin -- hR: equivalence R rcases hR with ⟨hrefl, hsymm, htrans⟩, -- hrefl: reflexive R -- hsymm: symmetric R -- htrans: transitive R exact hsymm, end /-! ## 1b) specialize Say you have a long hypothesis `h : ∀ n : ℕ, f n > 37 → n = 23`. This hypothesis is a *function*. It takes as inputs a natural number n and a proof that `f n > 37`, and then it gives as output a proof that `n = 23`. You can feed in some inputs and specialize the function. Say for example you you manage to prove the hypothesis `ht : f t > 37` for some natural number `t`. Then `specialize h t ft` would change `h` to `t = 23`. -/ example (X Y : set ℕ) (a : ℕ) (h : ∀ n : ℕ, n ∈ X → n ∈ Y) (haX : a ∈ X) : a ∈ Y := begin -- a: ℕ -- haX: a ∈ X -- h: ∀ (n : ℕ), n ∈ X → n ∈ Y specialize h a haX, -- h: a ∈ Y assumption, end /-! # 2) Making new hypothesis -/ /-! ## have The `have` tactic makes a new hypothesis. The proof of the current goal is paused and a new goal is created. Generally one should now put braces `{ }` because if there is more than one goal then understanding what the code is doing can get very difficult. -/ example (a b c n : ℕ) (hn : n > 2) : a^n + b^n = c^n → a * b = 0 := begin -- ⊢ a ^ n + b ^ n = c ^ n → a * b = 0 -- looks a bit tricky -- why not prove something easier first have ha : (a + 1) + 1 = a + 2, { -- ⊢ a + 1 + 1 = a + 2 apply add_assoc, }, -- ha: a + 1 + 1 = a + 2 -- ⊢ a ^ n + b ^ n = c ^ n → a * b = 0 sorry end /-! # 3) Using hypotheses to change the goal. -/ /-! ## 2a) rw The generic `sub in` tactic. If `h : X = Y` then `rw h` will change all `X`'s in the goal to `Y`'s. Also works with `h : P ↔ Q` if `P` and `Q` are true-false statements. -/ example (X Y : set ℕ) (hXY : X = Y) (a : ℕ) (haX : a ∈ Y) : a ∈ X := begin -- hXY: X = Y -- ⊢ a ∈ X rw hXY, -- hXY: X = Y -- ⊢ a ∈ Y assumption end -- Variants -- `rw h1 at h2`, `rw h1 at h2 ⊢`, `rw h at *` /-! ## 2b) convert `convert` is in some sense the opposite way of thinking to `rw`. Instead of continually rewriting the goal until it becomes one of your assumptions, why not just tell Lean that the assumption is basically the right answer modulo a few loose ends, which Lean will then leave for you as new goals. -/ example (X Y : set ℕ) (hX : 37 ∈ X) : 37 ∈ Y := begin -- hX: 37 ∈ X -- ⊢ 37 ∈ Y convert hX, -- ⊢ Y = X sorry end /- # 4) Changing the goal without using hypotheses -/ /-! ### 4a) intro and rintro -/ -- `intro` is a basic tactic for introducing hypotheses example (P Q : Prop) : P → Q := begin -- ⊢ P → Q intro hP, -- hP: P -- ⊢ Q sorry end -- `rintro` is to `intro` what `rcases` is to `cases`. It enables -- you to assume something and simultaneously take it apart. example (f : ℕ → ℚ) : (∃ n : ℕ, f n > 37) → (∃ n : ℕ, f n > 36) := begin -- ⊢ (∃ (n : ℕ), f n > 37) → P rintro ⟨n, hn⟩, -- n: ℕ -- hn: f n > 37 -- ⊢ P sorry, end /-! ## 4b) ext -/ -- `ext` is Lean's extensionality tactic. If your goal is to prove that -- two extensional things are equal (e.g. sets, functions, binary relations) -- then `ext a` or `ext a b` or whatever is appropriate, will turn the -- question into the assertion that they behave in the same way. Let's look -- at some examples example (A B : set ℕ) : A = B := begin -- ⊢ A = B ext x, -- x : ℕ -- ⊢ x ∈ A ↔ x ∈ B sorry end example (X Y : Type) (f g : X → Y) : f = g := begin -- ⊢ f = g ext x, -- x : X -- ⊢ f x = g x sorry end example (α : Type) (R S : α → α → Prop) : R = S := begin -- ⊢ R = S ext a b, -- a b : α -- ⊢ R a b ↔ S a b sorry end
import Data.Vect maryInVector : Elem "Mary" ["Peter", "Paul", "Mary"] maryInVector = There (There Here)
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Natural homomorphism from the natural numbers into a monoid with one. -/ import tactic.interactive algebra.order algebra.ordered_group algebra.ring namespace nat variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] /-- Canonical homomorphism from `ℕ` to a type `α` with `0`, `1` and `+`. -/ protected def cast : ℕ → α | 0 := 0 | (n+1) := cast n + 1 @[priority 0] instance cast_coe : has_coe ℕ α := ⟨nat.cast⟩ @[simp] theorem cast_zero : ((0 : ℕ) : α) = 0 := rfl theorem cast_add_one (n : ℕ) : ((n + 1 : ℕ) : α) = n + 1 := rfl @[simp] theorem cast_succ (n : ℕ) : ((succ n : ℕ) : α) = n + 1 := rfl end @[simp] theorem cast_one [add_monoid α] [has_one α] : ((1 : ℕ) : α) = 1 := zero_add _ @[simp] theorem cast_add [add_monoid α] [has_one α] (m) : ∀ n, ((m + n : ℕ) : α) = m + n | 0 := (add_zero _).symm | (n+1) := show ((m + n : ℕ) : α) + 1 = m + (n + 1), by rw [cast_add n, add_assoc] instance [add_monoid α] [has_one α] : is_add_monoid_hom (coe : ℕ → α) := by refine_struct {..}; simp @[simp] theorem cast_bit0 [add_monoid α] [has_one α] (n : ℕ) : ((bit0 n : ℕ) : α) = bit0 n := cast_add _ _ @[simp] theorem cast_bit1 [add_monoid α] [has_one α] (n : ℕ) : ((bit1 n : ℕ) : α) = bit1 n := by rw [bit1, cast_add_one, cast_bit0]; refl lemma cast_two {α : Type*} [semiring α] : ((2 : ℕ) : α) = 2 := by simp @[simp] theorem cast_pred [add_group α] [has_one α] : ∀ {n}, n > 0 → ((n - 1 : ℕ) : α) = n - 1 | (n+1) h := (add_sub_cancel (n:α) 1).symm @[simp] theorem cast_sub [add_group α] [has_one α] {m n} (h : m ≤ n) : ((n - m : ℕ) : α) = n - m := eq_sub_of_add_eq $ by rw [← cast_add, nat.sub_add_cancel h] @[simp] theorem cast_mul [semiring α] (m) : ∀ n, ((m * n : ℕ) : α) = m * n | 0 := (mul_zero _).symm | (n+1) := (cast_add _ _).trans $ show ((m * n : ℕ) : α) + m = m * (n + 1), by rw [cast_mul n, left_distrib, mul_one] instance [semiring α] : is_semiring_hom (coe : ℕ → α) := by refine_struct {..}; simp theorem mul_cast_comm [semiring α] (a : α) (n : ℕ) : a * n = n * a := by induction n; simp [left_distrib, right_distrib, *] @[simp] theorem cast_nonneg [linear_ordered_semiring α] : ∀ n : ℕ, 0 ≤ (n : α) | 0 := le_refl _ | (n+1) := add_nonneg (cast_nonneg n) zero_le_one @[simp] theorem cast_le [linear_ordered_semiring α] : ∀ {m n : ℕ}, (m : α) ≤ n ↔ m ≤ n | 0 n := by simp [zero_le] | (m+1) 0 := by simpa [not_succ_le_zero] using lt_add_of_lt_of_nonneg zero_lt_one (@cast_nonneg α _ m) | (m+1) (n+1) := (add_le_add_iff_right 1).trans $ (@cast_le m n).trans $ (add_le_add_iff_right 1).symm @[simp] theorem cast_lt [linear_ordered_semiring α] {m n : ℕ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_pos [linear_ordered_semiring α] {n : ℕ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] theorem eq_cast [add_monoid α] [has_one α] (f : ℕ → α) (H0 : f 0 = 0) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) : ∀ n : ℕ, f n = n | 0 := H0 | (n+1) := by rw [Hadd, H1, eq_cast]; refl theorem eq_cast' [add_group α] [has_one α] (f : ℕ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) : ∀ n : ℕ, f n = n := eq_cast _ (by rw [← add_left_inj (f 0), add_zero, ← Hadd]) H1 Hadd @[simp] theorem cast_id (n : ℕ) : ↑n = n := (eq_cast id rfl rfl (λ _ _, rfl) n).symm @[simp] theorem cast_min [decidable_linear_ordered_semiring α] {a b : ℕ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp] theorem cast_max [decidable_linear_ordered_semiring α] {a b : ℕ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp] theorem abs_cast [decidable_linear_ordered_comm_ring α] (a : ℕ) : abs (a : α) = a := abs_of_nonneg (cast_nonneg a) end nat
-- {-# OPTIONS -v tc.lhs:10 -v tc.lhs.split:50 #-} postulate A : Set record R : Set where field f : A test : _ → A test record{f = a} = a -- This could succeed, but Agda currently does not try to guess -- the type type of the record pattern from its field names.
/- Provides simplification lemmas for applicative laws. -/ universe variables u @[simp] lemma fmap_pure {m : Type u → Type u} [hm : applicative m] {α β : Type u} (f : α → β) (v : α) : f <$> (pure v : m α) = pure (f v) := applicative.map_pure m f v